<commit_before>// @(#)root/treeplayer:$Id$
// Author: Axel Naumann, 2011-09-28

/*************************************************************************
 * Copyright (C) 1995-2011, Rene Brun and Fons Rademakers and al.        *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "TTreeReaderValue.h"

#include "TTreeReader.h"
#include "TBranchClones.h"
#include "TBranchElement.h"
#include "TBranchRef.h"
#include "TBranchSTL.h"
#include "TBranchProxyDirector.h"
#include "TLeaf.h"
#include "TTreeProxyGenerator.h"
#include "TTreeReaderValue.h"
#include "TRegexp.h"
#include "TStreamerInfo.h"
#include "TStreamerElement.h"
#include "TNtuple.h"

////////////////////////////////////////////////////////////////////////////////
//                                                                            //
// TTreeReaderValue                                                        //
//                                                                            //
// Extracts data from a TTree.                                                //
//                                                                            //
//                                                                            //
//                                                                            //
//                                                                            //
//                                                                            //
//                                                                            //
//                                                                            //
//                                                                            //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////

ClassImp(TTreeReaderValueBase)

//______________________________________________________________________________
ROOT::TTreeReaderValueBase::TTreeReaderValueBase(TTreeReader* reader /*= 0*/,
                                                       const char* branchname /*= 0*/,
                                                       TDictionary* dict /*= 0*/):
   fTreeReader(reader),
   fBranchName(branchname),
   fDict(dict),
   fProxy(0),
   fSetupStatus(kSetupNotSetup),
   fReadStatus(kReadNothingYet),
   fLeaf(NULL),
   fTreeLastOffset(-1)
{
   // Construct a tree value reader and register it with the reader object.
   if (fTreeReader) fTreeReader->RegisterValueReader(this);
}

//______________________________________________________________________________
ROOT::TTreeReaderValueBase::~TTreeReaderValueBase()
{
   // Unregister from tree reader, cleanup.
   if (fTreeReader) fTreeReader->DeregisterValueReader(this);
}

//______________________________________________________________________________
ROOT::TTreeReaderValueBase::EReadStatus
ROOT::TTreeReaderValueBase::ProxyRead() {
   if (!fProxy) return kReadNothingYet;
   if (fProxy->Read()) {
      fReadStatus = kReadSuccess;
   } else {
      fReadStatus = kReadError;
   }
   return fReadStatus;
}

//______________________________________________________________________________
TLeaf* ROOT::TTreeReaderValueBase::GetLeaf() {
   if (fLeafName.Length() > 0){

      Long64_t newChainOffset = fTreeReader->GetTree()->GetChainOffset();

      if (newChainOffset != fTreeLastOffset){
         fTreeLastOffset = newChainOffset;
         fLeaf = fTreeReader->GetTree()->GetBranch(fBranchName)->GetLeaf(fLeafName);
      }
      return fLeaf;
   }
   else {
      Error("GetLeaf()", "We are not reading a leaf");
      return 0;
   }
}

//______________________________________________________________________________
void* ROOT::TTreeReaderValueBase::GetAddress() {
   if (ProxyRead() != kReadSuccess) return 0;

   if (fLeafName.Length() > 0){
      Long64_t newChainOffset = fTreeReader->GetTree()->GetChainOffset();

      if (newChainOffset != fTreeLastOffset){
         fTreeLastOffset = newChainOffset;
         fLeaf = fTreeReader->GetTree()->GetBranch(fBranchName)->GetLeaf(fLeafName);
      }
      return fLeaf->GetValuePointer();
   }
   return fProxy ? (Byte_t*)fProxy->GetWhere() : 0;
}

//______________________________________________________________________________
void ROOT::TTreeReaderValueBase::CreateProxy() {
   // Create the proxy object for our branch.
   if (fProxy) {
      return;
   }
   if (!fTreeReader) {
      Error("CreateProxy()", "TTreeReader object not set / available for branch %s!",
            fBranchName.Data());
      return;
   }
   if (!fDict) {
      TBranch* br = fTreeReader->GetTree()->GetBranch(fBranchName);
      const char* brDataType = "{UNDETERMINED}";
      if (br) {
         TDictionary* brDictUnused = 0;
         brDataType = GetBranchDataType(br, brDictUnused);
      }
      Error("CreateProxy()", "The template argument type T of %s accessing branch %s (which contains data of type %s) is not known to ROOT. You will need to create a dictionary for it.",
            IsA()->GetName() ? IsA()->GetName() : "?", fBranchName.Data(), brDataType);
      return;
   }

   // Search for the branchname, determine what it contains, and wire the
   // TBranchProxy representing it to us so we can access its data.

   ROOT::TNamedBranchProxy* namedProxy
      = (ROOT::TNamedBranchProxy*)fTreeReader->FindObject(fBranchName);
   if (namedProxy && namedProxy->GetDict() == fDict) {
      fProxy = namedProxy->GetProxy();
      return;
   }

   TBranch* branch = fTreeReader->GetTree()->GetBranch(fBranchName);
   TLeaf *myLeaf = NULL;
   TDictionary* branchActualType = 0;

   if (!branch) {
      if (fBranchName.Contains(".")){
         TRegexp leafNameExpression ("\\.[a-zA-Z0-9]+$");
         TString leafName (fBranchName(leafNameExpression));
         TString branchName = fBranchName(0, fBranchName.Length() - leafName.Length());
         branch = fTreeReader->GetTree()->GetBranch(branchName);
         if (!branch){
            Error("CreateProxy()", "The tree does not have a branch called %s. You could check with TTree::Print() for available branches.", fBranchName.Data());
            fProxy = 0;
            return;
         }
         else {
            myLeaf = branch->GetLeaf(TString(leafName(1, leafName.Length())));
            if (!myLeaf){
               Error("CreateProxy()", "The tree does not have a branch, nor a sub-branch called %s. You could check with TTree::Print() for available branches.", fBranchName.Data());
            }
            else {
               TDictionary *tempDict = TDictionary::GetDictionary(myLeaf->GetTypeName());
               if (tempDict && tempDict->IsA() == TDataType::Class() && TDictionary::GetDictionary(((TDataType*)tempDict)->GetTypeName()) == fDict){
                  //fLeafOffset = myLeaf->GetOffset() / 4;
                  branchActualType = fDict;
                  fLeaf = myLeaf;
                  fBranchName = branchName;
                  fLeafName = leafName(1, leafName.Length());
               }
               else {
                  Error("CreateProxy()", "Leaf of type %s cannot be read by TTreeReaderValue<%s>.", myLeaf->GetTypeName(), fDict->GetName());
               }
            }
         }
      }
      else {
         Error("CreateProxy()", "The tree does not have a branch called %s. You could check with TTree::Print() for available branches.", fBranchName.Data());
         fProxy = 0;
         return;
      }
   }

   if (!myLeaf){
      const char* branchActualTypeName = GetBranchDataType(branch, branchActualType);

      if (!branchActualType) {
         Error("CreateProxy()", "The branch %s contains data of type %s, which does not have a dictionary.",
               fBranchName.Data(), branchActualTypeName ? branchActualTypeName : "{UNDETERMINED TYPE}");
         fProxy = 0;
         return;
      }

      if (fDict != branchActualType) {
         Error("CreateProxy()", "The branch %s contains data of type %s. It cannot be accessed by a TTreeReaderValue<%s>",
               fBranchName.Data(), branchActualType->GetName(), fDict->GetName());
         return;
      }
   }

   // Update named proxy's dictionary
   if (namedProxy && !namedProxy->GetDict()) {
      namedProxy->SetDict(fDict);
      fProxy = namedProxy->GetProxy();
      return;
   }

   // Search for the branchname, determine what it contains, and wire the
   // TBranchProxy representing it to us so we can access its data.
   // A proxy for branch must not have been created before (i.e. check
   // fProxies before calling this function!)

   TString membername;

   bool isTopLevel = branch->GetMother() == branch;
   if (!isTopLevel) {
      membername = strrchr(branch->GetName(), '.');
      if (membername.IsNull()) {
         membername = branch->GetName();
      }
   }
   namedProxy = new ROOT::TNamedBranchProxy(fTreeReader->fDirector, branch, membername);
   fTreeReader->GetProxies()->Add(namedProxy);
   fProxy = namedProxy->GetProxy();
}

//______________________________________________________________________________
const char* ROOT::TTreeReaderValueBase::GetBranchDataType(TBranch* branch,
                                           TDictionary* &dict) const
{
   // Retrieve the type of data stored by branch; put its dictionary into
   // dict, return its type name. If no dictionary is available, at least
   // its type name should be returned.

   dict = 0;
   if (branch->IsA() == TBranchElement::Class()) {
      TBranchElement* brElement = (TBranchElement*)branch;
      if (brElement->GetType() == TBranchElement::kSTLNode ||
            brElement->GetType() == TBranchElement::kLeafNode ||
            brElement->GetType() == TBranchElement::kObjectNode) {

         TStreamerInfo *streamerInfo = brElement->GetInfo();
         Int_t id = brElement->GetID();

         if (id >= 0){
            TStreamerElement *element = (TStreamerElement*)streamerInfo->GetElements()->At(id);
            if (element->IsA() == TStreamerSTL::Class()){
               TStreamerSTL *myStl = (TStreamerSTL*)element;
               dict = myStl->GetClass();
               return 0;
            }
         }

         if (brElement->GetTypeName()) dict = TDictionary::GetDictionary(brElement->GetTypeName());
         if (dict && dict->IsA() == TDataType::Class()){
            dict = TDictionary::GetDictionary(((TDataType*)dict)->GetTypeName());
            if (dict != fDict){
               dict = TClass::GetClass(brElement->GetTypeName());
            }
            if (dict != fDict){
               dict = brElement->GetCurrentClass();
            }
         }
         else if (!dict) {
            dict = brElement->GetCurrentClass();
         }

         return brElement->GetTypeName();
      } else if (brElement->GetType() == TBranchElement::kClonesNode) {
         dict = TClonesArray::Class();
         return "TClonesArray";
      } else if (brElement->GetType() == 31
                 || brElement->GetType() == 41) {
         // it's a member, extract from GetClass()'s streamer info
         Error("GetBranchDataType()", "Must use TTreeReaderValueArray to access a member of an object that is stored in a collection.");
      }
      else {
         Error("GetBranchDataType()", "Unknown type and class combination: %i, %s", brElement->GetType(), brElement->GetClassName());
      }
      return 0;
   } else if (branch->IsA() == TBranch::Class()
              || branch->IsA() == TBranchObject::Class()
              || branch->IsA() == TBranchSTL::Class()) {
      if (branch->GetTree()->IsA() == TNtuple::Class()){
         dict = TDataType::GetDataType(kFloat_t);
         return dict->GetName();
      }
      const char* dataTypeName = branch->GetClassName();
      if ((!dataTypeName || !dataTypeName[0])
          && branch->IsA() == TBranch::Class()) {
         // leaflist. Can't represent.
         Error("GetBranchDataType()", "The branch %s was created using a leaf list and cannot be represented as a C++ type. Please access one of its siblings using a TTreeReaderValueArray:", branch->GetName());
         TIter iLeaves(branch->GetListOfLeaves());
         TLeaf* leaf = 0;
         while ((leaf = (TLeaf*) iLeaves())) {
            Error("GetBranchDataType()", "   %s.%s", branch->GetName(), leaf->GetName());
         }
         return 0;
      }
      if (dataTypeName) dict = TDictionary::GetDictionary(dataTypeName);
      return dataTypeName;
   } else if (branch->IsA() == TBranchClones::Class()) {
      dict = TClonesArray::Class();
      return "TClonesArray";
   } else if (branch->IsA() == TBranchRef::Class()) {
      // Can't represent.
      Error("GetBranchDataType()", "The branch %s is a TBranchRef and cannot be represented as a C++ type.", branch->GetName());
      return 0;
   } else {
      Error("GetBranchDataType()", "The branch %s is of type %s - something that is not handled yet.", branch->GetName(), branch->IsA()->GetName());
      return 0;
   }

   return 0;
}

<commit_msg>Fixes for coverity issues 51895, 51894 and 51893<commit_after>// @(#)root/treeplayer:$Id$
// Author: Axel Naumann, 2011-09-28

/*************************************************************************
 * Copyright (C) 1995-2011, Rene Brun and Fons Rademakers and al.        *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "TTreeReaderValue.h"

#include "TTreeReader.h"
#include "TBranchClones.h"
#include "TBranchElement.h"
#include "TBranchRef.h"
#include "TBranchSTL.h"
#include "TBranchProxyDirector.h"
#include "TLeaf.h"
#include "TTreeProxyGenerator.h"
#include "TTreeReaderValue.h"
#include "TRegexp.h"
#include "TStreamerInfo.h"
#include "TStreamerElement.h"
#include "TNtuple.h"

////////////////////////////////////////////////////////////////////////////////
//                                                                            //
// TTreeReaderValue                                                        //
//                                                                            //
// Extracts data from a TTree.                                                //
//                                                                            //
//                                                                            //
//                                                                            //
//                                                                            //
//                                                                            //
//                                                                            //
//                                                                            //
//                                                                            //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////

ClassImp(TTreeReaderValueBase)

//______________________________________________________________________________
ROOT::TTreeReaderValueBase::TTreeReaderValueBase(TTreeReader* reader /*= 0*/,
                                                       const char* branchname /*= 0*/,
                                                       TDictionary* dict /*= 0*/):
   fTreeReader(reader),
   fBranchName(branchname),
   fDict(dict),
   fProxy(0),
   fSetupStatus(kSetupNotSetup),
   fReadStatus(kReadNothingYet),
   fLeaf(NULL),
   fTreeLastOffset(-1)
{
   // Construct a tree value reader and register it with the reader object.
   if (fTreeReader) fTreeReader->RegisterValueReader(this);
}

//______________________________________________________________________________
ROOT::TTreeReaderValueBase::~TTreeReaderValueBase()
{
   // Unregister from tree reader, cleanup.
   if (fTreeReader) fTreeReader->DeregisterValueReader(this);
}

//______________________________________________________________________________
ROOT::TTreeReaderValueBase::EReadStatus
ROOT::TTreeReaderValueBase::ProxyRead() {
   if (!fProxy) return kReadNothingYet;
   if (fProxy->Read()) {
      fReadStatus = kReadSuccess;
   } else {
      fReadStatus = kReadError;
   }
   return fReadStatus;
}

//______________________________________________________________________________
TLeaf* ROOT::TTreeReaderValueBase::GetLeaf() {
   if (fLeafName.Length() > 0){

      Long64_t newChainOffset = fTreeReader->GetTree()->GetChainOffset();

      if (newChainOffset != fTreeLastOffset){
         fTreeLastOffset = newChainOffset;

         TTree *myTree = fTreeReader->GetTree();

         if (!myTree) {
            fReadStatus = kReadError;
            Error("GetLeaf()", "Unable to get the tree from the TTreeReader");
            return 0;
         }

         TBranch *myBranch = myTree->GetBranch(fBranchName);

         if (!myBranch) {
            fReadStatus = kReadError;
            Error("GetLeaf()", "Unable to get the branch from the tree");
            return 0;
         }

         fLeaf = myBranch->GetLeaf(fLeafName);
      }
      return fLeaf;
   }
   else {
      Error("GetLeaf()", "We are not reading a leaf");
      return 0;
   }
}

//______________________________________________________________________________
void* ROOT::TTreeReaderValueBase::GetAddress() {
   if (ProxyRead() != kReadSuccess) return 0;

   if (fLeafName.Length() > 0){
      if (GetLeaf()){
         return fLeaf->GetValuePointer();
      }
      else {
         fReadStatus = kReadError;
         Error("GetAddress()", "Unable to get the leaf");
         return 0;
      }
   }
   return fProxy ? (Byte_t*)fProxy->GetWhere() : 0;
}

//______________________________________________________________________________
void ROOT::TTreeReaderValueBase::CreateProxy() {
   // Create the proxy object for our branch.
   if (fProxy) {
      return;
   }
   if (!fTreeReader) {
      Error("CreateProxy()", "TTreeReader object not set / available for branch %s!",
            fBranchName.Data());
      return;
   }
   if (!fDict) {
      TBranch* br = fTreeReader->GetTree()->GetBranch(fBranchName);
      const char* brDataType = "{UNDETERMINED}";
      if (br) {
         TDictionary* brDictUnused = 0;
         brDataType = GetBranchDataType(br, brDictUnused);
      }
      Error("CreateProxy()", "The template argument type T of %s accessing branch %s (which contains data of type %s) is not known to ROOT. You will need to create a dictionary for it.",
            IsA()->GetName() ? IsA()->GetName() : "?", fBranchName.Data(), brDataType);
      return;
   }

   // Search for the branchname, determine what it contains, and wire the
   // TBranchProxy representing it to us so we can access its data.

   ROOT::TNamedBranchProxy* namedProxy
      = (ROOT::TNamedBranchProxy*)fTreeReader->FindObject(fBranchName);
   if (namedProxy && namedProxy->GetDict() == fDict) {
      fProxy = namedProxy->GetProxy();
      return;
   }

   TBranch* branch = fTreeReader->GetTree()->GetBranch(fBranchName);
   TLeaf *myLeaf = NULL;
   TDictionary* branchActualType = 0;

   if (!branch) {
      if (fBranchName.Contains(".")){
         TRegexp leafNameExpression ("\\.[a-zA-Z0-9]+$");
         TString leafName (fBranchName(leafNameExpression));
         TString branchName = fBranchName(0, fBranchName.Length() - leafName.Length());
         branch = fTreeReader->GetTree()->GetBranch(branchName);
         if (!branch){
            Error("CreateProxy()", "The tree does not have a branch called %s. You could check with TTree::Print() for available branches.", fBranchName.Data());
            fProxy = 0;
            return;
         }
         else {
            myLeaf = branch->GetLeaf(TString(leafName(1, leafName.Length())));
            if (!myLeaf){
               Error("CreateProxy()", "The tree does not have a branch, nor a sub-branch called %s. You could check with TTree::Print() for available branches.", fBranchName.Data());
            }
            else {
               TDictionary *tempDict = TDictionary::GetDictionary(myLeaf->GetTypeName());
               if (tempDict && tempDict->IsA() == TDataType::Class() && TDictionary::GetDictionary(((TDataType*)tempDict)->GetTypeName()) == fDict){
                  //fLeafOffset = myLeaf->GetOffset() / 4;
                  branchActualType = fDict;
                  fLeaf = myLeaf;
                  fBranchName = branchName;
                  fLeafName = leafName(1, leafName.Length());
               }
               else {
                  Error("CreateProxy()", "Leaf of type %s cannot be read by TTreeReaderValue<%s>.", myLeaf->GetTypeName(), fDict->GetName());
               }
            }
         }
      }
      else {
         Error("CreateProxy()", "The tree does not have a branch called %s. You could check with TTree::Print() for available branches.", fBranchName.Data());
         fProxy = 0;
         return;
      }
   }

   if (!myLeaf){
      const char* branchActualTypeName = GetBranchDataType(branch, branchActualType);

      if (!branchActualType) {
         Error("CreateProxy()", "The branch %s contains data of type %s, which does not have a dictionary.",
               fBranchName.Data(), branchActualTypeName ? branchActualTypeName : "{UNDETERMINED TYPE}");
         fProxy = 0;
         return;
      }

      if (fDict != branchActualType) {
         Error("CreateProxy()", "The branch %s contains data of type %s. It cannot be accessed by a TTreeReaderValue<%s>",
               fBranchName.Data(), branchActualType->GetName(), fDict->GetName());
         return;
      }
   }

   // Update named proxy's dictionary
   if (namedProxy && !namedProxy->GetDict()) {
      namedProxy->SetDict(fDict);
      fProxy = namedProxy->GetProxy();
      return;
   }

   // Search for the branchname, determine what it contains, and wire the
   // TBranchProxy representing it to us so we can access its data.
   // A proxy for branch must not have been created before (i.e. check
   // fProxies before calling this function!)

   TString membername;

   bool isTopLevel = branch->GetMother() == branch;
   if (!isTopLevel) {
      membername = strrchr(branch->GetName(), '.');
      if (membername.IsNull()) {
         membername = branch->GetName();
      }
   }
   namedProxy = new ROOT::TNamedBranchProxy(fTreeReader->fDirector, branch, membername);
   fTreeReader->GetProxies()->Add(namedProxy);
   fProxy = namedProxy->GetProxy();
}

//______________________________________________________________________________
const char* ROOT::TTreeReaderValueBase::GetBranchDataType(TBranch* branch,
                                           TDictionary* &dict) const
{
   // Retrieve the type of data stored by branch; put its dictionary into
   // dict, return its type name. If no dictionary is available, at least
   // its type name should be returned.

   dict = 0;
   if (branch->IsA() == TBranchElement::Class()) {
      TBranchElement* brElement = (TBranchElement*)branch;
      if (brElement->GetType() == TBranchElement::kSTLNode ||
            brElement->GetType() == TBranchElement::kLeafNode ||
            brElement->GetType() == TBranchElement::kObjectNode) {

         TStreamerInfo *streamerInfo = brElement->GetInfo();
         Int_t id = brElement->GetID();

         if (id >= 0){
            TStreamerElement *element = (TStreamerElement*)streamerInfo->GetElements()->At(id);
            if (element->IsA() == TStreamerSTL::Class()){
               TStreamerSTL *myStl = (TStreamerSTL*)element;
               dict = myStl->GetClass();
               return 0;
            }
         }

         if (brElement->GetTypeName()) dict = TDictionary::GetDictionary(brElement->GetTypeName());
         if (dict && dict->IsA() == TDataType::Class()){
            dict = TDictionary::GetDictionary(((TDataType*)dict)->GetTypeName());
            if (dict != fDict){
               dict = TClass::GetClass(brElement->GetTypeName());
            }
            if (dict != fDict){
               dict = brElement->GetCurrentClass();
            }
         }
         else if (!dict) {
            dict = brElement->GetCurrentClass();
         }

         return brElement->GetTypeName();
      } else if (brElement->GetType() == TBranchElement::kClonesNode) {
         dict = TClonesArray::Class();
         return "TClonesArray";
      } else if (brElement->GetType() == 31
                 || brElement->GetType() == 41) {
         // it's a member, extract from GetClass()'s streamer info
         Error("GetBranchDataType()", "Must use TTreeReaderValueArray to access a member of an object that is stored in a collection.");
      }
      else {
         Error("GetBranchDataType()", "Unknown type and class combination: %i, %s", brElement->GetType(), brElement->GetClassName());
      }
      return 0;
   } else if (branch->IsA() == TBranch::Class()
              || branch->IsA() == TBranchObject::Class()
              || branch->IsA() == TBranchSTL::Class()) {
      if (branch->GetTree()->IsA() == TNtuple::Class()){
         dict = TDataType::GetDataType(kFloat_t);
         return dict->GetName();
      }
      const char* dataTypeName = branch->GetClassName();
      if ((!dataTypeName || !dataTypeName[0])
          && branch->IsA() == TBranch::Class()) {
         // leaflist. Can't represent.
         Error("GetBranchDataType()", "The branch %s was created using a leaf list and cannot be represented as a C++ type. Please access one of its siblings using a TTreeReaderValueArray:", branch->GetName());
         TIter iLeaves(branch->GetListOfLeaves());
         TLeaf* leaf = 0;
         while ((leaf = (TLeaf*) iLeaves())) {
            Error("GetBranchDataType()", "   %s.%s", branch->GetName(), leaf->GetName());
         }
         return 0;
      }
      if (dataTypeName) dict = TDictionary::GetDictionary(dataTypeName);
      return dataTypeName;
   } else if (branch->IsA() == TBranchClones::Class()) {
      dict = TClonesArray::Class();
      return "TClonesArray";
   } else if (branch->IsA() == TBranchRef::Class()) {
      // Can't represent.
      Error("GetBranchDataType()", "The branch %s is a TBranchRef and cannot be represented as a C++ type.", branch->GetName());
      return 0;
   } else {
      Error("GetBranchDataType()", "The branch %s is of type %s - something that is not handled yet.", branch->GetName(), branch->IsA()->GetName());
      return 0;
   }

   return 0;
}

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012 The Backplane Incorporated,
 *     Vinay Hiremath,
 *     Zach Tratar
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify,
 * merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished
 * to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include <iostream>
#include <string.h>

using namespace std;

int main(int argc, char *argv[]) {
	// the options:
	// 1.) search string
	// 2.) editor
	// 3.) root search path
	// 4.) role/extension array
	// 5.) maximum results
	const unsigned int MAX_OPTIONS = 5;
	string options[MAX_OPTIONS];

	for (int i = 0; i < MAX_OPTIONS; i++) {
		options[i] = "";
	}

	for (int i = 1; i < argc; i++) {
		if (!strcmp(argv[i], "--editor")) {
			if (i != (argc - 1)) {
				options[1] = argv[i + 1];
				i++;
			}
		} else if (!strcmp(argv[i], "--path")) {
			if (i != (argc - 1)) {
				options[2] = argv[i + 1];
				i++;
			}
		} else if (!strcmp(argv[i], "--role")) {
			if (i != (argc - 1)) {
				options[3] = argv[i + 1];
				i++;
			}
		} else if (!strcmp(argv[i], "--max")) {
			if (i != (argc - 1)) {
				options[4] = argv[i + 1];
				i++;
			}
		} else if (i == 1) {
			options[0] = argv[i];
		}
	}

	// 2.) default any options not set or invalid (empty strings)

	// 3.) grab the options from external files

	// 4.) execv

	// 5.) while (1) { TAKE_IN_FILE_TO_OPEN }

	return 0;
}
<commit_msg>Parsing Options from Command Line is Finished<commit_after>/*
 * Copyright (c) 2012 The Backplane Incorporated,
 *     Vinay Hiremath,
 *     Zach Tratar
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify,
 * merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished
 * to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include <iostream>
#include <string.h>

using namespace std;

int main(int argc, char *argv[]) {
	// the default options
	string query = "";
	string editor = "vim";
	string path = "./";
	string role = "";
	string extensions[] = {"*"};
	unsigned int results_cap = 25;

	// get the options from the command line
	for (int i = 1; i < argc; i++) {
		if (!strcmp(argv[i], "--editor")) {
			if (i != (argc - 1)) {
				editor = argv[i + 1];
				i++;
			}
		} else if (!strcmp(argv[i], "--path")) {
			if (i != (argc - 1)) {
				path = argv[i + 1];
				i++;
			}
		} else if (!strcmp(argv[i], "--role")) {
			if (i != (argc - 1)) {
				role = argv[i + 1];
				i++;
			}
		} else if (!strcmp(argv[i], "--max")) {
			if (i != (argc - 1)) {
				results_cap = atoi(argv[i + 1]);
				i++;
			}
		} else if (i == 1) {
			query = argv[i];
		}
	}

	if (!query.compare("")) {
		cout << "You must provide a search string as the first argument to pill." << endl;
		return 0;
	}

	// 3.) grab the options from external files

	// 4.) execv

	// 5.) while (1) { TAKE_IN_FILE_TO_OPEN }

	return 0;
}
<|endoftext|>


<commit_before>// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2015 Intel Corporation. All Rights Reserved.

#include "image.h"
#include "r200.h"

using namespace rsimpl;
using namespace rsimpl::ds;

namespace rsimpl
{
    r200_camera::r200_camera(std::shared_ptr<uvc::device> device, const static_device_info & info)
        : ds_device(device, info,
        calibration_validator([](rs_stream, rs_stream){return true; }, [](rs_stream){return true; }))
    {
    }

    void r200_camera::start_fw_logger(char fw_log_op_code, int grab_rate_in_ms, std::timed_mutex& mutex)
    {
        throw std::logic_error("Not implemented");
    }

    void r200_camera::stop_fw_logger()
    {
        throw std::logic_error("Not implemented");
    }

    std::shared_ptr<rs_device> make_r200_device(std::shared_ptr<uvc::device> device)
    {
        LOG_INFO("Connecting to Intel RealSense R200");

        static_device_info info;
        info.name = { "Intel RealSense R200" };
        auto c = ds::read_camera_info(*device);

        ds_device::set_common_ds_config(device, info, c);

        // R200 provides Full HD raw 10 format, its descriptors is defined as follows
        info.subdevice_modes.push_back({ 2, {2400, 1081},  pf_rw10, 30, c.intrinsicsThird[0], {c.modesThird[0][0]}, {0}});

        return std::make_shared<r200_camera>(device, info);
    }

    std::shared_ptr<rs_device> make_lr200_device(std::shared_ptr<uvc::device> device)
    {
        LOG_INFO("Connecting to Intel RealSense LR200");

        static_device_info info;
        info.name = { "Intel RealSense LR200" };
        auto c = ds::read_camera_info(*device);

        ds_device::set_common_ds_config(device, info, c);

        // LR200 provides Full HD raw 16 format as well for the color stream
        info.subdevice_modes.push_back({ 2,{ 1920, 1080 }, pf_rw16, 30, c.intrinsicsThird[0],{ c.modesThird[0][0] },{ 0 } });

        return std::make_shared<r200_camera>(device, info);
    }
}
<commit_msg>removing redundant initialization of calibration validator<commit_after>// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2015 Intel Corporation. All Rights Reserved.

#include "image.h"
#include "r200.h"

using namespace rsimpl;
using namespace rsimpl::ds;

namespace rsimpl
{
    r200_camera::r200_camera(std::shared_ptr<uvc::device> device, const static_device_info & info)
        : ds_device(device, info, calibration_validator())
    {
    }

    void r200_camera::start_fw_logger(char fw_log_op_code, int grab_rate_in_ms, std::timed_mutex& mutex)
    {
        throw std::logic_error("Not implemented");
    }

    void r200_camera::stop_fw_logger()
    {
        throw std::logic_error("Not implemented");
    }

    std::shared_ptr<rs_device> make_r200_device(std::shared_ptr<uvc::device> device)
    {
        LOG_INFO("Connecting to Intel RealSense R200");

        static_device_info info;
        info.name = { "Intel RealSense R200" };
        auto c = ds::read_camera_info(*device);

        ds_device::set_common_ds_config(device, info, c);

        // R200 provides Full HD raw 10 format, its descriptors is defined as follows
        info.subdevice_modes.push_back({ 2, {2400, 1081},  pf_rw10, 30, c.intrinsicsThird[0], {c.modesThird[0][0]}, {0}});

        return std::make_shared<r200_camera>(device, info);
    }

    std::shared_ptr<rs_device> make_lr200_device(std::shared_ptr<uvc::device> device)
    {
        LOG_INFO("Connecting to Intel RealSense LR200");

        static_device_info info;
        info.name = { "Intel RealSense LR200" };
        auto c = ds::read_camera_info(*device);

        ds_device::set_common_ds_config(device, info, c);

        // LR200 provides Full HD raw 16 format as well for the color stream
        info.subdevice_modes.push_back({ 2,{ 1920, 1080 }, pf_rw16, 30, c.intrinsicsThird[0],{ c.modesThird[0][0] },{ 0 } });

        return std::make_shared<r200_camera>(device, info);
    }
}
<|endoftext|>


<commit_before>/** Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License */
#include "skin.h"
#include "utils/polygonUtils.h"

#define MIN_AREA_SIZE (0.4 * 0.4)

namespace cura
{

void generateSkins(int layerNr, SliceMeshStorage& storage, int extrusionWidth, int downSkinCount, int upSkinCount, int wall_line_count, int innermost_wall_extrusion_width, int insetCount, bool no_small_gaps_heuristic, bool avoidOverlappingPerimeters_0, bool avoidOverlappingPerimeters)
{
    generateSkinAreas(layerNr, storage, innermost_wall_extrusion_width, downSkinCount, upSkinCount, wall_line_count, no_small_gaps_heuristic);

    SliceLayer* layer = &storage.layers[layerNr];
    for(unsigned int partNr=0; partNr<layer->parts.size(); partNr++)
    {
        SliceLayerPart* part = &layer->parts[partNr];
        generateSkinInsets(part, extrusionWidth, insetCount, avoidOverlappingPerimeters_0, avoidOverlappingPerimeters);
    }
}

void generateSkinAreas(int layer_nr, SliceMeshStorage& storage, int innermost_wall_extrusion_width, int downSkinCount, int upSkinCount, int wall_line_count, bool no_small_gaps_heuristic)
{
    SliceLayer& layer = storage.layers[layer_nr];

    if (downSkinCount == 0 && upSkinCount == 0)
    {
        return;
    }

    for(unsigned int partNr = 0; partNr < layer.parts.size(); partNr++)
    {
        SliceLayerPart& part = layer.parts[partNr];

        if (int(part.insets.size()) < wall_line_count)
        {
            continue; // the last wall is not present, the part should only get inter preimeter gaps, but no skin.
        }

        Polygons upskin = part.insets.back().offset(-innermost_wall_extrusion_width/2);
        Polygons downskin = (downSkinCount == 0)? Polygons() : upskin;
        if (upSkinCount == 0) upskin = Polygons();

        auto getInsidePolygons = [&part](SliceLayer& layer2)
            {
                Polygons result;
                for(SliceLayerPart& part2 : layer2.parts)
                {
                    if (part.boundaryBox.hit(part2.boundaryBox))
                        result.add(part2.insets.back());
                }
                return result;
            };

        if (no_small_gaps_heuristic)
        {
            if (static_cast<int>(layer_nr - downSkinCount) >= 0)
            {
                downskin = downskin.difference(getInsidePolygons(storage.layers[layer_nr - downSkinCount])); // skin overlaps with the walls
            }

            if (static_cast<int>(layer_nr + upSkinCount) < static_cast<int>(storage.layers.size()))
            {
                upskin = upskin.difference(getInsidePolygons(storage.layers[layer_nr + upSkinCount])); // skin overlaps with the walls
            }
        }
        else
        {
            if (layer_nr >= downSkinCount && downSkinCount > 0)
            {
                Polygons not_air = getInsidePolygons(storage.layers[layer_nr - 1]);
                for (int downskin_layer_nr = layer_nr - downSkinCount; downskin_layer_nr < layer_nr - 1; downskin_layer_nr++)
                {
                    not_air = not_air.intersection(getInsidePolygons(storage.layers[downskin_layer_nr]));
                }
                downskin = downskin.difference(not_air); // skin overlaps with the walls
            }

            if (layer_nr < static_cast<int>(storage.layers.size()) - downSkinCount && upSkinCount > 0)
            {
                Polygons not_air = getInsidePolygons(storage.layers[layer_nr + 1]);
                for (int upskin_layer_nr = layer_nr + 2; upskin_layer_nr < layer_nr + upSkinCount + 1; upskin_layer_nr++)
                {
                    not_air = not_air.intersection(getInsidePolygons(storage.layers[upskin_layer_nr]));
                }
                upskin = upskin.difference(not_air); // skin overlaps with the walls
            }
        }

        Polygons skin = upskin.unionPolygons(downskin);

        skin.removeSmallAreas(MIN_AREA_SIZE);

        for (PolygonsPart& skin_area_part : skin.splitIntoParts())
        {
            part.skin_parts.emplace_back();
            part.skin_parts.back().outline = skin_area_part;
        }
    }
}

void generateSkinInsets(SliceLayerPart* part, int extrusionWidth, int insetCount, bool avoidOverlappingPerimeters_0, bool avoidOverlappingPerimeters)
{
    if (insetCount == 0)
    {
        return;
    }

    for (SkinPart& skin_part : part->skin_parts)
    {
        for(int i=0; i<insetCount; i++)
        {
            skin_part.insets.push_back(Polygons());
            if (i == 0)
            {
                PolygonUtils::offsetSafe(skin_part.outline, - extrusionWidth/2, extrusionWidth, skin_part.insets[0], avoidOverlappingPerimeters_0);
                Polygons in_between = skin_part.outline.difference(skin_part.insets[0].offset(extrusionWidth/2));
                skin_part.perimeterGaps.add(in_between);
            } else
            {
                PolygonUtils::offsetExtrusionWidth(skin_part.insets[i-1], true, extrusionWidth, skin_part.insets[i], &skin_part.perimeterGaps, avoidOverlappingPerimeters);
            }

            // optimize polygons: remove unnnecesary verts
            skin_part.insets[i].simplify();
            if (skin_part.insets[i].size() < 1)
            {
                skin_part.insets.pop_back();
                break;
            }
        }
    }
}

void generateInfill(int layerNr, SliceMeshStorage& storage, int innermost_wall_extrusion_width, int infill_skin_overlap, int wall_line_count)
{
    SliceLayer& layer = storage.layers[layerNr];

    for(SliceLayerPart& part : layer.parts)
    {
        if (int(part.insets.size()) < wall_line_count)
        {
            part.infill_area.emplace_back(); // put empty polygon as (uncombined) infill
            continue; // the last wall is not present, the part should only get inter preimeter gaps, but no infill.
        }
        Polygons infill = part.insets.back().offset(-innermost_wall_extrusion_width / 2 - infill_skin_overlap);

        for(SliceLayerPart& part2 : layer.parts)
        {
            if (part.boundaryBox.hit(part2.boundaryBox))
            {
                for(SkinPart& skin_part : part2.skin_parts)
                {
                    infill = infill.difference(skin_part.outline);
                }
            }
        }
        infill.removeSmallAreas(MIN_AREA_SIZE);

        part.infill_area.push_back(infill.offset(infill_skin_overlap));
    }
}

void combineInfillLayers(SliceMeshStorage& storage,unsigned int amount)
{
    if(amount <= 1) //If we must combine 1 layer, nothing needs to be combined. Combining 0 layers is invalid.
    {
        return;
    }
    if(storage.layers.empty() || storage.layers.size() - 1 < static_cast<size_t>(storage.getSettingAsCount("top_layers")) || storage.getSettingAsCount("infill_line_distance") <= 0) //No infill is even generated.
    {
        return;
    }
    /* We need to round down the layer index we start at to the nearest
    divisible index. Otherwise we get some parts that have infill at divisible
    layers and some at non-divisible layers. Those layers would then miss each
    other. */
    size_t min_layer = storage.getSettingAsCount("bottom_layers") + amount - 1;
    min_layer -= min_layer % amount; //Round upwards to the nearest layer divisible by infill_sparse_combine.
    size_t max_layer = storage.layers.size() - 1 - storage.getSettingAsCount("top_layers");
    max_layer -= max_layer % amount; //Round downwards to the nearest layer divisible by infill_sparse_combine.
    for(size_t layer_idx = min_layer;layer_idx <= max_layer;layer_idx += amount) //Skip every few layers, but extrude more.
    {
        SliceLayer* layer = &storage.layers[layer_idx];

        for(unsigned int n = 1;n < amount;n++)
        {
            if(layer_idx < n)
            {
                break;
            }

            SliceLayer* layer2 = &storage.layers[layer_idx - n];
            for(SliceLayerPart& part : layer->parts)
            {
                Polygons result;
                for(SliceLayerPart& part2 : layer2->parts)
                {
                    if(part.boundaryBox.hit(part2.boundaryBox))
                    {
                        Polygons intersection = part.infill_area[n - 1].intersection(part2.infill_area[0]).offset(-200).offset(200);
                        result.add(intersection);
                        part.infill_area[n - 1] = part.infill_area[n - 1].difference(intersection);
                        part2.infill_area[0] = part2.infill_area[0].difference(intersection);
                    }
                }

                part.infill_area.push_back(result);
            }
        }
    }
}

void generatePerimeterGaps(int layer_nr, SliceMeshStorage& storage, int extrusionWidth, int downSkinCount, int upSkinCount)
{
    SliceLayer& layer = storage.layers[layer_nr];

    for (SliceLayerPart& part : layer.parts)
    { // handle gaps between perimeters etc.
        if (downSkinCount > 0 && upSkinCount > 0 && // note: if both are zero or less, then all gaps will be used
            layer_nr >= downSkinCount && layer_nr < static_cast<int>(storage.layers.size() - upSkinCount)) // remove gaps which appear within print, i.e. not on the bottom most or top most skin
        {
            Polygons outlines_above;
            for (SliceLayerPart& part_above : storage.layers[layer_nr + upSkinCount].parts)
            {
                if (part.boundaryBox.hit(part_above.boundaryBox))
                {
                    outlines_above.add(part_above.outline);
                }
            }
            Polygons outlines_below;
            for (SliceLayerPart& part_below : storage.layers[layer_nr - downSkinCount].parts)
            {
                if (part.boundaryBox.hit(part_below.boundaryBox))
                {
                    outlines_below.add(part_below.outline);
                }
            }
            part.perimeterGaps = part.perimeterGaps.intersection(outlines_above.xorPolygons(outlines_below));
        }
        part.perimeterGaps.removeSmallAreas(MIN_AREA_SIZE);
    }
}

}//namespace cura
<commit_msg>Fix typo. downSkinCount -> upSkinCount<commit_after>/** Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License */
#include "skin.h"
#include "utils/polygonUtils.h"

#define MIN_AREA_SIZE (0.4 * 0.4)

namespace cura
{

void generateSkins(int layerNr, SliceMeshStorage& storage, int extrusionWidth, int downSkinCount, int upSkinCount, int wall_line_count, int innermost_wall_extrusion_width, int insetCount, bool no_small_gaps_heuristic, bool avoidOverlappingPerimeters_0, bool avoidOverlappingPerimeters)
{
    generateSkinAreas(layerNr, storage, innermost_wall_extrusion_width, downSkinCount, upSkinCount, wall_line_count, no_small_gaps_heuristic);

    SliceLayer* layer = &storage.layers[layerNr];
    for(unsigned int partNr=0; partNr<layer->parts.size(); partNr++)
    {
        SliceLayerPart* part = &layer->parts[partNr];
        generateSkinInsets(part, extrusionWidth, insetCount, avoidOverlappingPerimeters_0, avoidOverlappingPerimeters);
    }
}

void generateSkinAreas(int layer_nr, SliceMeshStorage& storage, int innermost_wall_extrusion_width, int downSkinCount, int upSkinCount, int wall_line_count, bool no_small_gaps_heuristic)
{
    SliceLayer& layer = storage.layers[layer_nr];

    if (downSkinCount == 0 && upSkinCount == 0)
    {
        return;
    }

    for(unsigned int partNr = 0; partNr < layer.parts.size(); partNr++)
    {
        SliceLayerPart& part = layer.parts[partNr];

        if (int(part.insets.size()) < wall_line_count)
        {
            continue; // the last wall is not present, the part should only get inter preimeter gaps, but no skin.
        }

        Polygons upskin = part.insets.back().offset(-innermost_wall_extrusion_width/2);
        Polygons downskin = (downSkinCount == 0)? Polygons() : upskin;
        if (upSkinCount == 0) upskin = Polygons();

        auto getInsidePolygons = [&part](SliceLayer& layer2)
            {
                Polygons result;
                for(SliceLayerPart& part2 : layer2.parts)
                {
                    if (part.boundaryBox.hit(part2.boundaryBox))
                        result.add(part2.insets.back());
                }
                return result;
            };

        if (no_small_gaps_heuristic)
        {
            if (static_cast<int>(layer_nr - downSkinCount) >= 0)
            {
                downskin = downskin.difference(getInsidePolygons(storage.layers[layer_nr - downSkinCount])); // skin overlaps with the walls
            }

            if (static_cast<int>(layer_nr + upSkinCount) < static_cast<int>(storage.layers.size()))
            {
                upskin = upskin.difference(getInsidePolygons(storage.layers[layer_nr + upSkinCount])); // skin overlaps with the walls
            }
        }
        else
        {
            if (layer_nr >= downSkinCount && downSkinCount > 0)
            {
                Polygons not_air = getInsidePolygons(storage.layers[layer_nr - 1]);
                for (int downskin_layer_nr = layer_nr - downSkinCount; downskin_layer_nr < layer_nr - 1; downskin_layer_nr++)
                {
                    not_air = not_air.intersection(getInsidePolygons(storage.layers[downskin_layer_nr]));
                }
                downskin = downskin.difference(not_air); // skin overlaps with the walls
            }

            if (layer_nr < static_cast<int>(storage.layers.size()) - upSkinCount && upSkinCount > 0)
            {
                Polygons not_air = getInsidePolygons(storage.layers[layer_nr + 1]);
                for (int upskin_layer_nr = layer_nr + 2; upskin_layer_nr < layer_nr + upSkinCount + 1; upskin_layer_nr++)
                {
                    not_air = not_air.intersection(getInsidePolygons(storage.layers[upskin_layer_nr]));
                }
                upskin = upskin.difference(not_air); // skin overlaps with the walls
            }
        }

        Polygons skin = upskin.unionPolygons(downskin);

        skin.removeSmallAreas(MIN_AREA_SIZE);

        for (PolygonsPart& skin_area_part : skin.splitIntoParts())
        {
            part.skin_parts.emplace_back();
            part.skin_parts.back().outline = skin_area_part;
        }
    }
}

void generateSkinInsets(SliceLayerPart* part, int extrusionWidth, int insetCount, bool avoidOverlappingPerimeters_0, bool avoidOverlappingPerimeters)
{
    if (insetCount == 0)
    {
        return;
    }

    for (SkinPart& skin_part : part->skin_parts)
    {
        for(int i=0; i<insetCount; i++)
        {
            skin_part.insets.push_back(Polygons());
            if (i == 0)
            {
                PolygonUtils::offsetSafe(skin_part.outline, - extrusionWidth/2, extrusionWidth, skin_part.insets[0], avoidOverlappingPerimeters_0);
                Polygons in_between = skin_part.outline.difference(skin_part.insets[0].offset(extrusionWidth/2));
                skin_part.perimeterGaps.add(in_between);
            } else
            {
                PolygonUtils::offsetExtrusionWidth(skin_part.insets[i-1], true, extrusionWidth, skin_part.insets[i], &skin_part.perimeterGaps, avoidOverlappingPerimeters);
            }

            // optimize polygons: remove unnnecesary verts
            skin_part.insets[i].simplify();
            if (skin_part.insets[i].size() < 1)
            {
                skin_part.insets.pop_back();
                break;
            }
        }
    }
}

void generateInfill(int layerNr, SliceMeshStorage& storage, int innermost_wall_extrusion_width, int infill_skin_overlap, int wall_line_count)
{
    SliceLayer& layer = storage.layers[layerNr];

    for(SliceLayerPart& part : layer.parts)
    {
        if (int(part.insets.size()) < wall_line_count)
        {
            part.infill_area.emplace_back(); // put empty polygon as (uncombined) infill
            continue; // the last wall is not present, the part should only get inter preimeter gaps, but no infill.
        }
        Polygons infill = part.insets.back().offset(-innermost_wall_extrusion_width / 2 - infill_skin_overlap);

        for(SliceLayerPart& part2 : layer.parts)
        {
            if (part.boundaryBox.hit(part2.boundaryBox))
            {
                for(SkinPart& skin_part : part2.skin_parts)
                {
                    infill = infill.difference(skin_part.outline);
                }
            }
        }
        infill.removeSmallAreas(MIN_AREA_SIZE);

        part.infill_area.push_back(infill.offset(infill_skin_overlap));
    }
}

void combineInfillLayers(SliceMeshStorage& storage,unsigned int amount)
{
    if(amount <= 1) //If we must combine 1 layer, nothing needs to be combined. Combining 0 layers is invalid.
    {
        return;
    }
    if(storage.layers.empty() || storage.layers.size() - 1 < static_cast<size_t>(storage.getSettingAsCount("top_layers")) || storage.getSettingAsCount("infill_line_distance") <= 0) //No infill is even generated.
    {
        return;
    }
    /* We need to round down the layer index we start at to the nearest
    divisible index. Otherwise we get some parts that have infill at divisible
    layers and some at non-divisible layers. Those layers would then miss each
    other. */
    size_t min_layer = storage.getSettingAsCount("bottom_layers") + amount - 1;
    min_layer -= min_layer % amount; //Round upwards to the nearest layer divisible by infill_sparse_combine.
    size_t max_layer = storage.layers.size() - 1 - storage.getSettingAsCount("top_layers");
    max_layer -= max_layer % amount; //Round downwards to the nearest layer divisible by infill_sparse_combine.
    for(size_t layer_idx = min_layer;layer_idx <= max_layer;layer_idx += amount) //Skip every few layers, but extrude more.
    {
        SliceLayer* layer = &storage.layers[layer_idx];

        for(unsigned int n = 1;n < amount;n++)
        {
            if(layer_idx < n)
            {
                break;
            }

            SliceLayer* layer2 = &storage.layers[layer_idx - n];
            for(SliceLayerPart& part : layer->parts)
            {
                Polygons result;
                for(SliceLayerPart& part2 : layer2->parts)
                {
                    if(part.boundaryBox.hit(part2.boundaryBox))
                    {
                        Polygons intersection = part.infill_area[n - 1].intersection(part2.infill_area[0]).offset(-200).offset(200);
                        result.add(intersection);
                        part.infill_area[n - 1] = part.infill_area[n - 1].difference(intersection);
                        part2.infill_area[0] = part2.infill_area[0].difference(intersection);
                    }
                }

                part.infill_area.push_back(result);
            }
        }
    }
}

void generatePerimeterGaps(int layer_nr, SliceMeshStorage& storage, int extrusionWidth, int downSkinCount, int upSkinCount)
{
    SliceLayer& layer = storage.layers[layer_nr];

    for (SliceLayerPart& part : layer.parts)
    { // handle gaps between perimeters etc.
        if (downSkinCount > 0 && upSkinCount > 0 && // note: if both are zero or less, then all gaps will be used
            layer_nr >= downSkinCount && layer_nr < static_cast<int>(storage.layers.size() - upSkinCount)) // remove gaps which appear within print, i.e. not on the bottom most or top most skin
        {
            Polygons outlines_above;
            for (SliceLayerPart& part_above : storage.layers[layer_nr + upSkinCount].parts)
            {
                if (part.boundaryBox.hit(part_above.boundaryBox))
                {
                    outlines_above.add(part_above.outline);
                }
            }
            Polygons outlines_below;
            for (SliceLayerPart& part_below : storage.layers[layer_nr - downSkinCount].parts)
            {
                if (part.boundaryBox.hit(part_below.boundaryBox))
                {
                    outlines_below.add(part_below.outline);
                }
            }
            part.perimeterGaps = part.perimeterGaps.intersection(outlines_above.xorPolygons(outlines_below));
        }
        part.perimeterGaps.removeSmallAreas(MIN_AREA_SIZE);
    }
}

}//namespace cura
<|endoftext|>


<commit_before>#include <stdlib.h>

#ifdef _WIN32
#define _UNICODE 1
#define UNICODE 1
#endif

#include "../include/sliprock.h"
#include "sliprock_internals.h"
#include "stringbuf.h"
#include <csignal>
#include <exception>
#include <mutex>
#define BOOST_TEST_MODULE SlipRock module
#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
//#include <boost/thread.hpp>
#include <stdexcept>
#include <thread>

#ifdef _WIN32
#define address pipename
#include <windows.h>
#endif
#ifndef BOOST_TEST
#define BOOST_TEST BOOST_CHECK
#endif

#ifndef _WIN32
typedef int HANDLE;
#include <pthread.h>
#define INVALID_HANDLE_VALUE (-1)
#endif
struct set_on_close {
  set_on_close(std::mutex &m, bool &b) : boolean(b), mut(m) {}
  ~set_on_close() {
    std::unique_lock<std::mutex> locker{mut};
    boolean = true;
  }

private:
  bool &boolean;
  std::mutex &mut;
};
template <size_t size>
bool client(char (&buf)[size], SliprockConnection *con, bool &finished,
            std::mutex &mutex) {
  set_on_close closer(mutex, finished);
  char buf2[size + 1] = {0};
  bool read_succeeded = false;
  HANDLE fd = INVALID_HANDLE_VALUE;
  (void)system("ls -a ~/.sliprock");
  SliprockReceiver *receiver =
      sliprock_open("dummy_valr", sizeof("dummy_val") - 1, (uint32_t)getpid());
  if (receiver == nullptr) {
    perror("sliprock_open");
    goto fail;
  }
  MADE_IT;
  fd = (HANDLE)sliprock_connect(receiver);
  if (fd == INVALID_HANDLE_VALUE) {
    perror("sliprock_connect");
    goto fail;
  }
  MADE_IT;
#ifdef _WIN32
  DWORD read;
  BOOST_TEST(0 != ReadFile(fd, buf2, sizeof buf, &read, nullptr));
  BOOST_TEST(read == sizeof buf);
  BOOST_TEST(0 != WriteFile(fd, buf2, sizeof buf, &read, nullptr));
  BOOST_TEST(read == sizeof buf);
#else
  if (fd >= 0) {
    BOOST_TEST(sizeof buf == read(fd, buf2, sizeof buf));
    BOOST_TEST(sizeof buf == write(fd, buf2, sizeof buf));
  }
#endif
  // static_assert(sizeof buf2 == sizeof buf, "Buffer size mismatch");
  static_assert(sizeof con->address == sizeof receiver->sock,
                "Connection size mismatch");
  BOOST_TEST(memcmp(&buf2[0], &buf[0], sizeof buf) == 0);
  puts(buf);
  puts(buf2);
#ifndef _WIN32
  BOOST_TEST(fd > -1);
#endif
  read_succeeded = true;
fail:
  BOOST_REQUIRE(nullptr != receiver);
  BOOST_TEST(0 == memcmp(reinterpret_cast<void *>(&receiver->sock),
                         reinterpret_cast<void *>(&con->address),
                         sizeof con->address));
  BOOST_TEST(read_succeeded == true);
  BOOST_TEST(receiver != static_cast<SliprockReceiver *>(nullptr));
#ifndef _WIN32
  BOOST_TEST(close(fd) == 0);
#else
  BOOST_TEST(CloseHandle(fd) != 0);
#endif
  sliprock_close_receiver(receiver);
  return read_succeeded;
}

template <size_t n>
bool server(char (&buf)[n], SliprockConnection *con, bool &finished,
            std::mutex &mutex) {
  set_on_close closer(mutex, finished);
  MADE_IT;
  auto handle = (HANDLE)sliprock_accept(con);
  MADE_IT;
  if (handle == INVALID_HANDLE_VALUE)
    return false;
  MADE_IT;
  char buf3[sizeof buf];
#ifndef _WIN32
  if (write(handle, buf, sizeof buf) != sizeof buf)
    return false;
  MADE_IT;
  if (read(handle, buf3, sizeof buf) != sizeof buf)
    return false;
  MADE_IT;
  if (close(handle))
    return false;
  MADE_IT;
#else
  DWORD written;
  MADE_IT;
  if (WriteFile(handle, buf, sizeof buf, &written, NULL) == 0)
    return false;
  MADE_IT;
  if (written != sizeof buf3)
    return false;
  MADE_IT;
  if (ReadFile(handle, buf3, sizeof buf3, &written, NULL) == 0)
    return false;
  if (!CloseHandle(handle))
    return false;
  MADE_IT;
#endif
  bool x = !memcmp(buf3, buf, sizeof buf);
  finished = true;
  return x;
}
#ifndef _WIN32
static void donothing(int _) {
  (void)_;
  return;
}
static_assert(std::is_same<std::thread::native_handle_type, pthread_t>(),
              "Mismatched native handle type!");
#elif 0
static_assert(std::is_same<std::thread::native_handle_type, HANDLE>(),
              "Mismatched native handle type!");
#endif
// Interrupt a thread IF read_done is true, ensuring that lock is held
// when reading its value.
static void interrupt_thread(std::mutex &lock, const bool &read_done,
                             std::thread &thread) {
  std::unique_lock<std::mutex> locker(lock);
  if (!read_done) {
#ifndef _WIN32
    pthread_kill(thread.native_handle(), SIGPIPE);
#else
    (void)thread;
    //CancelSynchronousIo(thread.native_handle());
#endif
  }
}
BOOST_AUTO_TEST_CASE(can_create_connection) {
#ifndef _WIN32
  struct sigaction sigact;
  memset(&sigact, 0, sizeof sigact);
  sigact.sa_handler = donothing;
  sigemptyset(&sigact.sa_mask);
  sigaddset(&sigact.sa_mask, SIGPIPE);
  sigaction(SIGPIPE, &sigact, nullptr);
#endif
  (void)system("rm -rf -- \"$HOME/.sliprock\" /tmp/sliprock.*");
  SliprockConnection *con =
      sliprock_socket("dummy_valq", sizeof("dummy_val") - 1);
  BOOST_REQUIRE(con != nullptr);

  std::mutex lock, lock2;
  bool read_done = false, write_done = false;
  char buf[] = "Test message!";
  bool write_succeeded = false, read_succeeded = false;
  std::thread thread([&]() {
    if (!(read_succeeded = server(buf, con, read_done, lock2)))
      perror("sliprock_server");
  });
  std::thread thread2(
      [&]() { write_succeeded = client(buf, con, write_done, lock); });
  auto interrupter = std::thread{[&]() {
    struct timespec q = {1, 0};
    nanosleep(&q, nullptr);
    interrupt_thread(lock2, read_done, thread);
    interrupt_thread(lock, write_done, thread2);
  }};
  thread.join();
  thread2.join();
  interrupter.join();
  BOOST_TEST(write_succeeded);
  BOOST_TEST(read_succeeded);

  sliprock_close(con);
}
// BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Use CancelSynchronousIo on Windows<commit_after>#include <stdlib.h>

#ifdef _WIN32
#define _UNICODE 1
#define UNICODE 1
#endif

#include "../include/sliprock.h"
#include "sliprock_internals.h"
#include "stringbuf.h"
#include <csignal>
#include <exception>
#include <mutex>
#define BOOST_TEST_MODULE SlipRock module
#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
//#include <boost/thread.hpp>
#include <stdexcept>
#include <thread>

#ifdef _WIN32
#define address pipename
#include <windows.h>
#endif
#ifndef BOOST_TEST
#define BOOST_TEST BOOST_CHECK
#endif

#ifndef _WIN32
typedef int HANDLE;
#include <pthread.h>
#define INVALID_HANDLE_VALUE (-1)
#endif
struct set_on_close {
  set_on_close(std::mutex &m, bool &b) : boolean(b), mut(m) {}
  ~set_on_close() {
    std::unique_lock<std::mutex> locker{mut};
    boolean = true;
  }

private:
  bool &boolean;
  std::mutex &mut;
};
template <size_t size>
bool client(char (&buf)[size], SliprockConnection *con, bool &finished,
            std::mutex &mutex) {
  set_on_close closer(mutex, finished);
  char buf2[size + 1] = {0};
  bool read_succeeded = false;
  HANDLE fd = INVALID_HANDLE_VALUE;
  (void)system("ls -a ~/.sliprock");
  SliprockReceiver *receiver =
      sliprock_open("dummy_valr", sizeof("dummy_val") - 1, (uint32_t)getpid());
  if (receiver == nullptr) {
    perror("sliprock_open");
    goto fail;
  }
  MADE_IT;
  fd = (HANDLE)sliprock_connect(receiver);
  if (fd == INVALID_HANDLE_VALUE) {
    perror("sliprock_connect");
    goto fail;
  }
  MADE_IT;
#ifdef _WIN32
  DWORD read;
  BOOST_TEST(0 != ReadFile(fd, buf2, sizeof buf, &read, nullptr));
  BOOST_TEST(read == sizeof buf);
  BOOST_TEST(0 != WriteFile(fd, buf2, sizeof buf, &read, nullptr));
  BOOST_TEST(read == sizeof buf);
#else
  if (fd >= 0) {
    BOOST_TEST(sizeof buf == read(fd, buf2, sizeof buf));
    BOOST_TEST(sizeof buf == write(fd, buf2, sizeof buf));
  }
#endif
  // static_assert(sizeof buf2 == sizeof buf, "Buffer size mismatch");
  static_assert(sizeof con->address == sizeof receiver->sock,
                "Connection size mismatch");
  BOOST_TEST(memcmp(&buf2[0], &buf[0], sizeof buf) == 0);
  puts(buf);
  puts(buf2);
#ifndef _WIN32
  BOOST_TEST(fd > -1);
#endif
  read_succeeded = true;
fail:
  BOOST_REQUIRE(nullptr != receiver);
  BOOST_TEST(0 == memcmp(reinterpret_cast<void *>(&receiver->sock),
                         reinterpret_cast<void *>(&con->address),
                         sizeof con->address));
  BOOST_TEST(read_succeeded == true);
  BOOST_TEST(receiver != static_cast<SliprockReceiver *>(nullptr));
#ifndef _WIN32
  BOOST_TEST(close(fd) == 0);
#else
  BOOST_TEST(CloseHandle(fd) != 0);
#endif
  sliprock_close_receiver(receiver);
  return read_succeeded;
}

template <size_t n>
bool server(char (&buf)[n], SliprockConnection *con, bool &finished,
            std::mutex &mutex) {
  set_on_close closer(mutex, finished);
  MADE_IT;
  auto handle = (HANDLE)sliprock_accept(con);
  MADE_IT;
  if (handle == INVALID_HANDLE_VALUE)
    return false;
  MADE_IT;
  char buf3[sizeof buf];
#ifndef _WIN32
  if (write(handle, buf, sizeof buf) != sizeof buf)
    return false;
  MADE_IT;
  if (read(handle, buf3, sizeof buf) != sizeof buf)
    return false;
  MADE_IT;
  if (close(handle))
    return false;
  MADE_IT;
#else
  DWORD written;
  MADE_IT;
  if (WriteFile(handle, buf, sizeof buf, &written, NULL) == 0)
    return false;
  MADE_IT;
  if (written != sizeof buf3)
    return false;
  MADE_IT;
  if (ReadFile(handle, buf3, sizeof buf3, &written, NULL) == 0)
    return false;
  if (!CloseHandle(handle))
    return false;
  MADE_IT;
#endif
  bool x = !memcmp(buf3, buf, sizeof buf);
  finished = true;
  return x;
}
#ifndef _WIN32
static void donothing(int _) {
  (void)_;
  return;
}
static_assert(std::is_same<std::thread::native_handle_type, pthread_t>(),
              "Mismatched native handle type!");
#elif 0
static_assert(std::is_same<std::thread::native_handle_type, HANDLE>(),
              "Mismatched native handle type!");
#endif
// Interrupt a thread IF read_done is true, ensuring that lock is held
// when reading its value.
static void interrupt_thread(std::mutex &lock, const bool &read_done,
                             std::thread &thread) {
  std::unique_lock<std::mutex> locker(lock);
  if (!read_done) {
#ifndef _WIN32
    pthread_kill(thread.native_handle(), SIGPIPE);
#elif _MSC_VER
    CancelSynchronousIo(thread.native_handle());
#else
    (void)thread;
#endif
  }
}
BOOST_AUTO_TEST_CASE(can_create_connection) {
#ifndef _WIN32
  struct sigaction sigact;
  memset(&sigact, 0, sizeof sigact);
  sigact.sa_handler = donothing;
  sigemptyset(&sigact.sa_mask);
  sigaddset(&sigact.sa_mask, SIGPIPE);
  sigaction(SIGPIPE, &sigact, nullptr);
#endif
  (void)system("rm -rf -- \"$HOME/.sliprock\" /tmp/sliprock.*");
  SliprockConnection *con =
      sliprock_socket("dummy_valq", sizeof("dummy_val") - 1);
  BOOST_REQUIRE(con != nullptr);

  std::mutex lock, lock2;
  bool read_done = false, write_done = false;
  char buf[] = "Test message!";
  bool write_succeeded = false, read_succeeded = false;
  std::thread thread([&]() {
    if (!(read_succeeded = server(buf, con, read_done, lock2)))
      perror("sliprock_server");
  });
  std::thread thread2(
      [&]() { write_succeeded = client(buf, con, write_done, lock); });
  auto interrupter = std::thread{[&]() {
#ifndef _WIN32
    struct timespec q = {1, 0};
    nanosleep(&q, nullptr);
#else
    Sleep(1000);
#endif
    interrupt_thread(lock2, read_done, thread);
    interrupt_thread(lock, write_done, thread2);
  }};
  thread.join();
  thread2.join();
  interrupter.join();
  BOOST_TEST(write_succeeded);
  BOOST_TEST(read_succeeded);

  sliprock_close(con);
}
// BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>// Lesson 13.cpp : Defines the entry point for the console application.

#include <render_framework\render_framework.h>
#include <chrono>
#pragma comment (lib , "Render Framework" )

using namespace std;
using namespace glm;
using namespace render_framework;
using namespace chrono;

// Global scop box
shared_ptr<mesh> box;
// Keep track of current mode
int MODE = 0;

/*
 * key_callback
 *
 * used for identifying key presses
 * and switching the current mode
 */
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) {
  if (key == GLFW_KEY_SPACE && action == GLFW_PRESS) {

    switch (MODE) {
      case 0:
        MODE = 1;
        break;
      case 1:
        MODE = 0;
        break;
//      case 2:
//        MODE = 0;
//        break;
      default:
        MODE = 0;
        break;
    }
  }

} // key_callback

/*
 * userTranslation
 *
 * Moves the object around inside the window using the keyboard arrow keys.
 */
void userTranslation(float deltaTime)
{
	// Move the quad when arrow keys are pressed
	if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_RIGHT)) {
		box->trans.translate(vec3(10.0, 0.0, 0.0) * deltaTime);
	}
	if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_LEFT)) {
		box->trans.translate(vec3(-10.0, 0.0, 0.0) * deltaTime);
	}
	if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_UP)) {
		box->trans.translate(vec3(0.0, 0.0, -10.0) * deltaTime);
	}
	if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_DOWN)) {
		box->trans.translate(vec3(0.0, 0.0, 10.0) * deltaTime);
	}
	if (glfwGetKey(renderer::get_instance().get_window(), 'W')) {
		box->trans.translate(vec3(0.0, 10.0, 0.0) * deltaTime);
	}
	if (glfwGetKey(renderer::get_instance().get_window(), 'S')) {
		box->trans.translate(vec3(0.0, -10.0, 0.0) * deltaTime);
	}
} // userTranslation()

/*
 * userRotation
 *
 * rotates the object
 */
void userRotation(float deltaTime) {

  if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_UP)) {
	  box->trans.rotate(vec3(-pi<float>(), 0.0, 0.0f) * deltaTime);
  }
  if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_DOWN)) {
	  box->trans.rotate(vec3(pi<float>(), 0.0, 0.0f) * deltaTime);
  }
  if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_RIGHT)) {
	  box->trans.rotate(vec3(0.0, -pi<float>(), 0.0f) * deltaTime);
  }
  if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_LEFT)) {
	  box->trans.rotate(vec3(0.0, pi<float>(), 0.0f) * deltaTime);
  }
  if (glfwGetKey(renderer::get_instance().get_window(), 'W')) {
	  box->trans.rotate(vec3(0.0, 0.0, pi<float>()) * deltaTime);
  }
  if (glfwGetKey(renderer::get_instance().get_window(), 'S')) {
	  box->trans.rotate(vec3(0.0, 0.0, -pi<float>()) * deltaTime);
  }

} // userRotation

/*
 * Update routine
 *
 * Updates the application state
 */
void update(float deltaTime)
{
	switch (MODE) {
	case 0:
		userTranslation(deltaTime);
		break;
    case 1:
		userRotation(deltaTime);
		break;
//	case 2:
//      userScale(deltaTime);
//      break;
	default:
		break;
	}
} // update()

int main()
{
	// Initialize the renderer
	if (!renderer::get_instance().initialise()) return -1;

	// Set the clear colour to cyan
	glClearColor(0.0f, 1.0f, 1.0f, 1.0f);

	/* Set the projection matrix */
	// First get the aspect ratio (width/height)
	float aspect = (float)renderer::get_instance().get_screen_width() /
					(float)renderer::get_instance().get_screen_width();
	// Use this to create projection matrix
	auto projection = perspective(
						degrees(quarter_pi<float>()),	// FOV
						aspect,							// Aspect ratio
						2.414f,							// Near plane
						10000.0f);						// Far plane
	// Set the projection matrix
	renderer::get_instance().set_projection(projection);

	// Set the view matrix
	auto view = lookAt(
					vec3(20.0f, 20.0f, 20.0f),	// Camera position
					vec3(0.0f, 0.0f, 0.0f),		// Target
					vec3(0.0f, 1.0f, 0.0f));	// Up vector
	renderer::get_instance().set_view(view);

	/* Set the function for the key callback */
	glfwSetKeyCallback(renderer::get_instance().get_window(), key_callback);

	// Create box
	box = make_shared<mesh>();
	box->geom = geometry_builder::create_box();

	// Load in effect.  Start with shaders
	auto eff = make_shared<effect>();
	eff->add_shader("shader.vert", GL_VERTEX_SHADER);
	eff->add_shader("shader.frag", GL_FRAGMENT_SHADER);
	if (!effect_loader::build_effect(eff)) {
		return -1;
	}

	// Create material for box
	box->mat = make_shared<material>();
	box->mat->effect = eff;
	box->mat->set_uniform_value("colour", vec4(0.0, 1.0, 0.0, 1.0));
	box->mat->set_uniform_value("hue", vec4(1.0, 0.0, 0.0, 1.0));

	// Monitor the elapsed time per frame
	auto currentTimeStamp = system_clock::now();
	auto prevTimeStamp = system_clock::now();

	// Main render loop
	while (renderer::get_instance().is_running())
	{
		// Get current time
		currentTimeStamp = system_clock::now();
		// Calculate elapsed time
		auto elapsed = duration_cast<milliseconds>(currentTimeStamp - prevTimeStamp);
		// Convert to fractions of a second
		auto seconds = float(elapsed.count()) / 1000.0;

		// Update Scene
		update(seconds);

		// Check if running
		if (renderer::get_instance().begin_render())
		{
			// Render Cube
			renderer::get_instance().render(box);

			// End the render
			renderer::get_instance().end_render();
		}

		prevTimeStamp = currentTimeStamp;

	} // Main render loop
}
<commit_msg>Changed box to object<commit_after>// Lesson 13.cpp : Defines the entry point for the console application.

#include <render_framework\render_framework.h>
#include <chrono>
#pragma comment (lib , "Render Framework" )

using namespace std;
using namespace glm;
using namespace render_framework;
using namespace chrono;

// Global scop box
shared_ptr<mesh> object;
// Keep track of current mode
int MODE = 0;

/*
 * key_callback
 *
 * used for identifying key presses
 * and switching the current mode
 */
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) {
  if (key == GLFW_KEY_SPACE && action == GLFW_PRESS) {

    switch (MODE) {
      case 0:
        MODE = 1;
        break;
      case 1:
        MODE = 0;
        break;
//      case 2:
//        MODE = 0;
//        break;
      default:
        MODE = 0;
        break;
    }
  }

} // key_callback

/*
 * userTranslation
 *
 * Moves the object around inside the window using the keyboard arrow keys.
 */
void userTranslation(float deltaTime)
{
	// Move the quad when arrow keys are pressed
	if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_RIGHT)) {
		object->trans.translate(vec3(10.0, 0.0, 0.0) * deltaTime);
	}
	if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_LEFT)) {
		object->trans.translate(vec3(-10.0, 0.0, 0.0) * deltaTime);
	}
	if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_UP)) {
		object->trans.translate(vec3(0.0, 0.0, -10.0) * deltaTime);
	}
	if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_DOWN)) {
		object->trans.translate(vec3(0.0, 0.0, 10.0) * deltaTime);
	}
	if (glfwGetKey(renderer::get_instance().get_window(), 'W')) {
		object->trans.translate(vec3(0.0, 10.0, 0.0) * deltaTime);
	}
	if (glfwGetKey(renderer::get_instance().get_window(), 'S')) {
		object->trans.translate(vec3(0.0, -10.0, 0.0) * deltaTime);
	}
} // userTranslation()

/*
 * userRotation
 *
 * rotates the object
 */
void userRotation(float deltaTime) {

  if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_UP)) {
	  object->trans.rotate(vec3(-pi<float>(), 0.0, 0.0f) * deltaTime);
  }
  if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_DOWN)) {
	  object->trans.rotate(vec3(pi<float>(), 0.0, 0.0f) * deltaTime);
  }
  if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_RIGHT)) {
	  object->trans.rotate(vec3(0.0, -pi<float>(), 0.0f) * deltaTime);
  }
  if (glfwGetKey(renderer::get_instance().get_window(), GLFW_KEY_LEFT)) {
	  object->trans.rotate(vec3(0.0, pi<float>(), 0.0f) * deltaTime);
  }
  if (glfwGetKey(renderer::get_instance().get_window(), 'W')) {
	  object->trans.rotate(vec3(0.0, 0.0, pi<float>()) * deltaTime);
  }
  if (glfwGetKey(renderer::get_instance().get_window(), 'S')) {
	  object->trans.rotate(vec3(0.0, 0.0, -pi<float>()) * deltaTime);
  }

} // userRotation

/*
 * Update routine
 *
 * Updates the application state
 */
void update(float deltaTime)
{
	switch (MODE) {
	case 0:
		userTranslation(deltaTime);
		break;
    case 1:
		userRotation(deltaTime);
		break;
//	case 2:
//      userScale(deltaTime);
//      break;
	default:
		break;
	}
} // update()

int main()
{
	// Initialize the renderer
	if (!renderer::get_instance().initialise()) return -1;

	// Set the clear colour to cyan
	glClearColor(0.0f, 1.0f, 1.0f, 1.0f);

	/* Set the projection matrix */
	// First get the aspect ratio (width/height)
	float aspect = (float)renderer::get_instance().get_screen_width() /
					(float)renderer::get_instance().get_screen_width();
	// Use this to create projection matrix
	auto projection = perspective(
						degrees(quarter_pi<float>()),	// FOV
						aspect,							// Aspect ratio
						2.414f,							// Near plane
						10000.0f);						// Far plane
	// Set the projection matrix
	renderer::get_instance().set_projection(projection);

	// Set the view matrix
	auto view = lookAt(
					vec3(20.0f, 20.0f, 20.0f),	// Camera position
					vec3(0.0f, 0.0f, 0.0f),		// Target
					vec3(0.0f, 1.0f, 0.0f));	// Up vector
	renderer::get_instance().set_view(view);

	/* Set the function for the key callback */
	glfwSetKeyCallback(renderer::get_instance().get_window(), key_callback);

	// Create box
	object = make_shared<mesh>();
	object->geom = geometry_builder::create_box();

	// Load in effect.  Start with shaders
	auto eff = make_shared<effect>();
	eff->add_shader("shader.vert", GL_VERTEX_SHADER);
	eff->add_shader("shader.frag", GL_FRAGMENT_SHADER);
	if (!effect_loader::build_effect(eff)) {
		return -1;
	}

	// Create material for box
	object->mat = make_shared<material>();
	object->mat->effect = eff;
	object->mat->set_uniform_value("colour", vec4(0.0, 1.0, 0.0, 1.0));
	object->mat->set_uniform_value("hue", vec4(1.0, 0.0, 0.0, 1.0));

	// Monitor the elapsed time per frame
	auto currentTimeStamp = system_clock::now();
	auto prevTimeStamp = system_clock::now();

	// Main render loop
	while (renderer::get_instance().is_running())
	{
		// Get current time
		currentTimeStamp = system_clock::now();
		// Calculate elapsed time
		auto elapsed = duration_cast<milliseconds>(currentTimeStamp - prevTimeStamp);
		// Convert to fractions of a second
		auto seconds = float(elapsed.count()) / 1000.0;

		// Update Scene
		update(seconds);

		// Check if running
		if (renderer::get_instance().begin_render())
		{
			// Render Cube
			renderer::get_instance().render(object);

			// End the render
			renderer::get_instance().end_render();
		}

		prevTimeStamp = currentTimeStamp;

	} // Main render loop
}
<|endoftext|>


<commit_before>// Test.cpp
// Sean Jones

#define GLFW_INCLUDE_GLU
#include <GLFW/glfw3.h>
#include <chrono>
#include <glm/glm.hpp>
#include <glm/gtx/constants.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/core/type_vec3.hpp>

using namespace std::chrono;

GLFWwindow* window;

bool running = true;

// Value to keep track of current orientation on axis
glm::vec3 position(0.0f, 0.0f, 0.0f);

bool initialise()
{
  // Set Color to cyan
  glClearColor(0.0f, 1.0f, 1.0f, 1.0f);

  return true;
} // initialise

//updates the application
void update(double deltaTime)
{
  // Check if escape pressed or window is closed
  running = !glfwGetKey(window, GLFW_KEY_ESCAPE) &&
    !glfwWindowShouldClose(window);

  // Move the quad when arrow keys are pressed
  if (glfwGetKey(window, GLFW_KEY_RIGHT)){
    position += glm::vec3(1.0f, 0.0f, 0.0f) * float(deltaTime);
  }
  if (glfwGetKey(window, GLFW_KEY_LEFT)){
    position -= glm::vec3(1.0f, 0.0f, 0.0f) * float(deltaTime);
  }
  if (glfwGetKey(window, GLFW_KEY_UP)){
    position += glm::vec3(0.0f, 1.0f, 0.0f) * float(deltaTime);
  }
  if (glfwGetKey(window, GLFW_KEY_DOWN)){
    position -= glm::vec3(0.0f, 1.0f, 0.0f) * float(deltaTime);
  }
} // update

//renders the application
void render()
{

  // Create model matrix
  auto model = glm::translate(glm::mat4(1.0f), position);

  // Set matrix mode
  glMatrixMode(GL_MODELVIEW);

  // Load model matrix
  glLoadMatrixf(glm::value_ptr(model));

  // Clear the screen
  glClear(GL_COLOR_BUFFER_BIT);

  //Set the colour
  glColor4f(1.0f, 0.0f, 0.0f, 1.0f);

  //Render a Triangel
  glBegin(GL_QUADS);

    glVertex3f(0.5f, 0.5f, 0.0f);
    glVertex3f(-0.5f, 0.5f, 0.0f);
    glVertex3f(-0.5f, -0.5f, 0.0f);
    glVertex3f(0.5f, -0.5f, 0.0f);

  glEnd();

  // Swap front and back buffers
  glfwSwapBuffers(window);

  // Set transform matrix to identity (no transform)
  glLoadIdentity();

} // render

int main(void)
{
    /* Initialize the library */
    if (!glfwInit())
    {
        return -1;
    }

    /* Create a windowed mode window and its OpenGL context */
    window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        return -1;
    }

    /* Make the window's context current */
    glfwMakeContextCurrent(window);

    //initialise the window
    if (!initialise())
    {
      glfwTerminate();
      return -1;
    }

    // Monitor the elapsed time per frame
    auto currentTimeStamp = system_clock::now();
    auto prevTimeStamp = system_clock::now();

    /* Loop until the user closes the window */
    while (!glfwWindowShouldClose(window))
    {
        // Get current time
        currentTimeStamp = system_clock::now();
        // Calculate elapsed time
        auto elapsed = duration_cast<milliseconds>(currentTimeStamp
            - prevTimeStamp);
        //Convert to fractions of a second
        auto seconds = double(elapsed.count()) / 1000.0;

        // Update Application
        update(seconds);
        //Render scene
        render();

        /* Swap front and back buffers */
        glfwSwapBuffers(window);

        /* Poll for and process events */
        glfwPollEvents();

        // set the previous time stamp to current time stamp
        prevTimeStamp = currentTimeStamp;
    } // Main Loop

    glfwTerminate();
    return 0;
} // main
<commit_msg>Added basic edge detection<commit_after>// Test.cpp
// Sean Jones

#define GLFW_INCLUDE_GLU
#include <GLFW/glfw3.h>
#include <chrono>
#include <glm/glm.hpp>
#include <glm/gtx/constants.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/core/type_vec3.hpp>

using namespace std::chrono;

GLFWwindow* window;

bool running = true;

// Value to keep track of current orientation on axis
glm::vec3 position(0.0f, 0.0f, 0.0f);

bool initialise()
{
  // Set Color to cyan
  glClearColor(0.0f, 1.0f, 1.0f, 1.0f);

  return true;
} // initialise

//updates the application
void update(double deltaTime)
{
  // Check if escape pressed or window is closed
  running = !glfwGetKey(window, GLFW_KEY_ESCAPE) &&
    !glfwWindowShouldClose(window);

  // Move the quad when arrow keys are pressed
  if (glfwGetKey(window, GLFW_KEY_RIGHT)){
    if (position.x < 0.5) {
      position += glm::vec3(1.0f, 0.0f, 0.0f) * float(deltaTime);
    }
  }
  if (glfwGetKey(window, GLFW_KEY_LEFT)){
    if (position.x > -0.5) {
      position -= glm::vec3(1.0f, 0.0f, 0.0f) * float(deltaTime);
    }
  }
  if (glfwGetKey(window, GLFW_KEY_UP)){
    if (position.y < 0.5) {
      position += glm::vec3(0.0f, 1.0f, 0.0f) * float(deltaTime);
    }
  }
  if (glfwGetKey(window, GLFW_KEY_DOWN)){
    if (position.y > -0.5) {
      position -= glm::vec3(0.0f, 1.0f, 0.0f) * float(deltaTime);
    }
  }

} // update

//renders the application
void render()
{

  // Create model matrix
  auto model = glm::translate(glm::mat4(1.0f), position);

  // Set matrix mode
  glMatrixMode(GL_MODELVIEW);

  // Load model matrix
  glLoadMatrixf(glm::value_ptr(model));

  // Clear the screen
  glClear(GL_COLOR_BUFFER_BIT);

  //Set the colour
  glColor4f(1.0f, 0.0f, 0.0f, 1.0f);

  //Render a Triangel
  glBegin(GL_QUADS);

    glVertex3f(0.5f, 0.5f, 0.0f);
    glVertex3f(-0.5f, 0.5f, 0.0f);
    glVertex3f(-0.5f, -0.5f, 0.0f);
    glVertex3f(0.5f, -0.5f, 0.0f);

  glEnd();

  // Swap front and back buffers
  glfwSwapBuffers(window);

  // Set transform matrix to identity (no transform)
  glLoadIdentity();

} // render

int main(void)
{
    /* Initialize the library */
    if (!glfwInit())
    {
        return -1;
    }

    /* Create a windowed mode window and its OpenGL context */
    window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        return -1;
    }

    /* Make the window's context current */
    glfwMakeContextCurrent(window);

    //initialise the window
    if (!initialise())
    {
      glfwTerminate();
      return -1;
    }

    // Monitor the elapsed time per frame
    auto currentTimeStamp = system_clock::now();
    auto prevTimeStamp = system_clock::now();

    /* Loop until the user closes the window */
    while (!glfwWindowShouldClose(window))
    {
        // Get current time
        currentTimeStamp = system_clock::now();
        // Calculate elapsed time
        auto elapsed = duration_cast<milliseconds>(currentTimeStamp
            - prevTimeStamp);
        //Convert to fractions of a second
        auto seconds = double(elapsed.count()) / 1000.0;

        // Update Application
        update(seconds);
        //Render scene
        render();

        /* Swap front and back buffers */
        glfwSwapBuffers(window);

        /* Poll for and process events */
        glfwPollEvents();

        // set the previous time stamp to current time stamp
        prevTimeStamp = currentTimeStamp;
    } // Main Loop

    glfwTerminate();
    return 0;
} // main
<|endoftext|>


<commit_before>///
/// @file   test.cpp
/// @brief  primecount integration tests.
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <primecount.hpp>
#include <primecount-internal.hpp>
#include <primesieve.hpp>
#include <ptypes.hpp>

#include <stdint.h>
#include <iostream>
#include <cstdlib>
#include <string>
#include <stdexcept>
#include <sstream>
#include <ctime>

#ifdef _OPENMP
  #include <omp.h>
#endif

/// For types: f1(x) , f2(x)
#define CHECK_11(f1, f2) check_equal(#f1, x, f1 (x), f2 (x))

/// For types: f1(x) , f2(x, threads)
#define CHECK_12(f1, f2) check_equal(#f1, x, f1 (x), f2 (x, get_num_threads()))

/// For types: f1(x, threads) , f2(x, threads)
#define CHECK_22(f1, f2) check_equal(#f1, x, f1 (x, get_num_threads()), f2 (x, get_num_threads()))

#define CHECK_EQUAL(f1, f2, check, iters) \
{ \
  cout << "Testing " << #f1 << "(x)" << flush; \
 \
  /* test for 0 <= x < 10000 */ \
  for (int64_t x = 0; x < 10000; x++) \
    check(f1, f2); \
 \
  int64_t x = 0; \
  /* test using random increment */ \
  for (int64_t i = 0; i < iters; i++, x += get_rand()) \
  { \
    check(f1, f2); \
    double percent = 100.0 * (i + 1.0) / iters; \
    cout << "\rTesting " << #f1 "(x) " << (int) percent << "%" << flush; \
  } \
 \
  cout << endl; \
}

using namespace std;
using namespace primecount;
using primesieve::parallel_nth_prime;

namespace {

int get_rand()
{
  // 0 <= get_rand() < 10^7
  return (rand() % 10000) * 1000 + 1;
}

void check_equal(const string& f1, int64_t x, int64_t res1, int64_t res2)
{
  if (res1 != res2)
  {
    ostringstream oss;
    oss << f1 << "(" << x << ") = " << res1
        << " is an error, the correct result is " << res2;
    throw runtime_error(oss.str());
  }
}

void test_phi_thread_safety(int64_t iters)
{
#ifdef _OPENMP
  cout << "Testing phi(x, a)" << flush;

  int nested_threads = 2;
  int64_t single_thread_sum = 0;
  int64_t multi_thread_sum = 0;
  int64_t base = 1000000;

  omp_set_nested(true);

  #pragma omp parallel for reduction(+: multi_thread_sum)
  for (int64_t i = 0; i < iters; i++)
    multi_thread_sum += pi_legendre(base + i, nested_threads);

  omp_set_nested(false);

  for (int64_t i = 0; i < iters; i++)
    single_thread_sum += pi_legendre(base + i, 1);

  if (multi_thread_sum != single_thread_sum)
    throw runtime_error("Error: multi-threaded phi(x, a) is broken.");

  std::cout << "\rTesting phi(x, a) 100%" << endl;
#endif
}

} // namespace

namespace primecount {

bool test()
{
  srand((unsigned) time(0));
  try
  {
    test_phi_thread_safety(100);

    CHECK_EQUAL(pi_legendre,                  pi_primesieve,      CHECK_22, 100);
    CHECK_EQUAL(pi_meissel,                   pi_legendre,        CHECK_22, 400);
    CHECK_EQUAL(pi_lehmer,                    pi_meissel,         CHECK_22, 400);
    CHECK_EQUAL(pi_lehmer2,                   pi_lehmer,          CHECK_22, 200);
    CHECK_EQUAL(pi_lmo1,                      pi_meissel,         CHECK_12, 200);
    CHECK_EQUAL(pi_lmo2,                      pi_meissel,         CHECK_12, 200);
    CHECK_EQUAL(pi_lmo3,                      pi_meissel,         CHECK_12, 300);
    CHECK_EQUAL(pi_lmo4,                      pi_meissel,         CHECK_12, 300);
    CHECK_EQUAL(pi_lmo5,                      pi_meissel,         CHECK_12, 400);
    CHECK_EQUAL(pi_lmo_parallel1,             pi_meissel,         CHECK_22, 400);
    CHECK_EQUAL(pi_lmo_parallel2,             pi_meissel,         CHECK_22, 400);
    CHECK_EQUAL(pi_lmo_parallel3,             pi_meissel,         CHECK_22, 400);
    CHECK_EQUAL(pi_deleglise_rivat1,          pi_lmo_parallel3,   CHECK_12, 600);
    CHECK_EQUAL(pi_deleglise_rivat2,          pi_lmo_parallel3,   CHECK_12, 600);
    CHECK_EQUAL(pi_deleglise_rivat3,          pi_lmo_parallel3,   CHECK_12, 600);
#ifdef HAVE_INT128_T
    CHECK_EQUAL(pi_deleglise_rivat4,          pi_lmo_parallel3,   CHECK_12, 600);
#endif
    CHECK_EQUAL(pi_deleglise_rivat_parallel1, pi_lmo_parallel3,   CHECK_22, 900);
    CHECK_EQUAL(pi_deleglise_rivat_parallel2, pi_lmo_parallel3,   CHECK_22, 900);
    CHECK_EQUAL(pi_deleglise_rivat_parallel3, pi_lmo_parallel3,   CHECK_22, 900);
#ifdef HAVE_INT128_T
    CHECK_EQUAL(pi_deleglise_rivat_parallel4, pi_lmo_parallel3,   CHECK_22, 900);
#endif
    CHECK_EQUAL(nth_prime,                    parallel_nth_prime, CHECK_11,  70);
  }
  catch (runtime_error& e)
  {
    cerr << endl << e.what() << endl;
    return false;
  }

  cout << "All tests passed successfully!" << endl;
  return true;
}

} // namespace primecount
<commit_msg>Do not print status information<commit_after>///
/// @file   test.cpp
/// @brief  primecount integration tests.
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <primecount.hpp>
#include <primecount-internal.hpp>
#include <primesieve.hpp>
#include <ptypes.hpp>

#include <stdint.h>
#include <iostream>
#include <cstdlib>
#include <string>
#include <stdexcept>
#include <sstream>
#include <ctime>

#ifdef _OPENMP
  #include <omp.h>
#endif

/// For types: f1(x) , f2(x)
#define CHECK_11(f1, f2) check_equal(#f1, x, f1 (x), f2 (x))

/// For types: f1(x) , f2(x, threads)
#define CHECK_12(f1, f2) check_equal(#f1, x, f1 (x), f2 (x, get_num_threads()))

/// For types: f1(x, threads) , f2(x, threads)
#define CHECK_22(f1, f2) check_equal(#f1, x, f1 (x, get_num_threads()), f2 (x, get_num_threads()))

#define CHECK_EQUAL(f1, f2, check, iters) \
{ \
  cout << "Testing " << #f1 << "(x)" << flush; \
 \
  /* test for 0 <= x < 10000 */ \
  for (int64_t x = 0; x < 10000; x++) \
    check(f1, f2); \
 \
  int64_t x = 0; \
  /* test using random increment */ \
  for (int64_t i = 0; i < iters; i++, x += get_rand()) \
  { \
    check(f1, f2); \
    double percent = 100.0 * (i + 1.0) / iters; \
    cout << "\rTesting " << #f1 "(x) " << (int) percent << "%" << flush; \
  } \
 \
  cout << endl; \
}

using namespace std;
using namespace primecount;
using primesieve::parallel_nth_prime;

namespace {

int get_rand()
{
  // 0 <= get_rand() < 10^7
  return (rand() % 10000) * 1000 + 1;
}

void check_equal(const string& f1, int64_t x, int64_t res1, int64_t res2)
{
  if (res1 != res2)
  {
    ostringstream oss;
    oss << f1 << "(" << x << ") = " << res1
        << " is an error, the correct result is " << res2;
    throw runtime_error(oss.str());
  }
}

void test_phi_thread_safety(int64_t iters)
{
#ifdef _OPENMP
  cout << "Testing phi(x, a)" << flush;

  int nested_threads = 2;
  int64_t single_thread_sum = 0;
  int64_t multi_thread_sum = 0;
  int64_t base = 1000000;

  omp_set_nested(true);

  #pragma omp parallel for reduction(+: multi_thread_sum)
  for (int64_t i = 0; i < iters; i++)
    multi_thread_sum += pi_legendre(base + i, nested_threads);

  omp_set_nested(false);

  for (int64_t i = 0; i < iters; i++)
    single_thread_sum += pi_legendre(base + i, 1);

  if (multi_thread_sum != single_thread_sum)
    throw runtime_error("Error: multi-threaded phi(x, a) is broken.");

  std::cout << "\rTesting phi(x, a) 100%" << endl;
#endif
}

} // namespace

namespace primecount {

bool test()
{
  set_print_status(false);
  srand(static_cast<unsigned>(time(0)));
  try
  {
    test_phi_thread_safety(100);

    CHECK_EQUAL(pi_legendre,                  pi_primesieve,      CHECK_22, 100);
    CHECK_EQUAL(pi_meissel,                   pi_legendre,        CHECK_22, 400);
    CHECK_EQUAL(pi_lehmer,                    pi_meissel,         CHECK_22, 400);
    CHECK_EQUAL(pi_lehmer2,                   pi_lehmer,          CHECK_22, 200);
    CHECK_EQUAL(pi_lmo1,                      pi_meissel,         CHECK_12, 200);
    CHECK_EQUAL(pi_lmo2,                      pi_meissel,         CHECK_12, 200);
    CHECK_EQUAL(pi_lmo3,                      pi_meissel,         CHECK_12, 300);
    CHECK_EQUAL(pi_lmo4,                      pi_meissel,         CHECK_12, 300);
    CHECK_EQUAL(pi_lmo5,                      pi_meissel,         CHECK_12, 400);
    CHECK_EQUAL(pi_lmo_parallel1,             pi_meissel,         CHECK_22, 400);
    CHECK_EQUAL(pi_lmo_parallel2,             pi_meissel,         CHECK_22, 400);
    CHECK_EQUAL(pi_lmo_parallel3,             pi_meissel,         CHECK_22, 400);
    CHECK_EQUAL(pi_deleglise_rivat1,          pi_lmo_parallel3,   CHECK_12, 600);
    CHECK_EQUAL(pi_deleglise_rivat2,          pi_lmo_parallel3,   CHECK_12, 600);
    CHECK_EQUAL(pi_deleglise_rivat3,          pi_lmo_parallel3,   CHECK_12, 600);
#ifdef HAVE_INT128_T
    CHECK_EQUAL(pi_deleglise_rivat4,          pi_lmo_parallel3,   CHECK_12, 600);
#endif
    CHECK_EQUAL(pi_deleglise_rivat_parallel1, pi_lmo_parallel3,   CHECK_22, 900);
    CHECK_EQUAL(pi_deleglise_rivat_parallel2, pi_lmo_parallel3,   CHECK_22, 900);
    CHECK_EQUAL(pi_deleglise_rivat_parallel3, pi_lmo_parallel3,   CHECK_22, 900);
#ifdef HAVE_INT128_T
    CHECK_EQUAL(pi_deleglise_rivat_parallel4, pi_lmo_parallel3,   CHECK_22, 900);
#endif
    CHECK_EQUAL(nth_prime,                    parallel_nth_prime, CHECK_11,  70);
  }
  catch (runtime_error& e)
  {
    cerr << endl << e.what() << endl;
    return false;
  }

  cout << "All tests passed successfully!" << endl;
  return true;
}

} // namespace primecount
<|endoftext|>