<commit_before>#include "Fraction.h"
#include <cmath>
#include <iostream>

long long Fraction::gcd(long long numerator, long long denominator) {  // method of successive division
	long long temp;
	if (numerator < denominator) {
		temp = denominator;
		denominator = numerator;
		numerator = temp;
	}
	while (denominator != 0) {
		temp = numerator % denominator;
		numerator = denominator;
		denominator = temp;
	}
	return numerator;
}

void Fraction::rof() {
	if (numerator) {
		long long g = gcd(abs(numerator), denominator);                                 // The g is greatest common divisor of two numbers.
		numerator /= g;
		denominator /= g;
	}
	else {
		denominator = 1;
	}
}

// Operator overloading.
Fraction operator + (const Fraction &frac1, const Fraction &frac2) {
	return Fraction(frac1.numerator * frac2.denominator + frac2.numerator * frac1.denominator, frac2.denominator * frac1.denominator);
}

Fraction operator += (Fraction &frac1, const Fraction &frac2) {
	frac1 = Fraction(frac1.numerator * frac2.denominator + frac2.numerator * frac1.denominator, frac2.denominator * frac1.denominator);
	return frac1;
}

Fraction operator - (const Fraction &frac1, const Fraction &frac2) {
	return Fraction(frac1.numerator * frac2.denominator - frac2.numerator * frac1.denominator, frac2.denominator * frac1.denominator);
}

Fraction operator -= (Fraction &frac1, const Fraction &frac2) {
	frac1 = Fraction(frac1.numerator * frac2.denominator - frac2.numerator * frac1.denominator, frac2.denominator * frac1.denominator);
	return frac1;
}

Fraction operator * (const Fraction &frac1, const Fraction &frac2) {
	return Fraction(frac1.numerator * frac2.numerator, frac2.denominator * frac1.denominator);
}

Fraction operator *= (Fraction &frac1, const Fraction &frac2) {
	frac1 = Fraction(frac1.numerator * frac2.numerator, frac2.denominator * frac1.denominator);
	return frac1;
}

Fraction operator / (const Fraction &frac1, const Fraction &frac2) {
	return Fraction(frac1.numerator * frac2.denominator, frac2.numerator * frac1.denominator);
}

Fraction operator /= (Fraction &frac1, const Fraction &frac2) {
	frac1 = Fraction(frac1.numerator * frac2.denominator, frac2.numerator * frac1.denominator);
	return frac1;
}

std::ostream& operator<< (std::ostream &os, const Fraction &frac) {
	Fraction frac_temp(frac.numerator, frac.denominator);
	os << frac_temp.numerator;						// When denominator is 1, do not output it.
	if (frac_temp.denominator != 1)
		os << "/" << frac_temp.denominator;
	return os;
}

std::istream& operator>> (std::istream &is, Fraction &frac) {
	is >> frac.numerator;
	if (is.get() != '/') {							// read denominator if and only if next char is '/'
		return is;
	}
	else {
		is >> frac.denominator;
	}
	is.get();								// use get() to clear the break
	return is;
}

bool operator == (const Fraction &frac1, const Fraction &frac2) {
	return (frac1.numerator * frac2.denominator) == (frac2.numerator * frac1.denominator);
}

bool operator != (const Fraction &frac1, const Fraction &frac2) {
	return !(frac1 == frac2);
}

bool operator < (const Fraction &frac1, const Fraction &frac2) {
	return (frac1.numerator * frac2.denominator) < (frac2.numerator * frac1.denominator);
}

bool operator <= (const Fraction &frac1, const Fraction &frac2) {
	return (frac1 < frac2) || (frac1 == frac2);
}

bool operator > (const Fraction &frac1, const Fraction &frac2) {
	return !(frac1 <= frac2);
}

bool operator >= (const Fraction &frac1, const Fraction &frac2) {
	return !(frac1 < frac2);
}

Fraction Fraction::Frac_abs(Fraction &temp_frac) {                                       // Absolute value of a fraction.
	return (temp_frac >= 0) ? temp_frac : (0 - temp_frac);
}

void Fraction::cin_num(long long temp_a) {
	this->numerator = temp_a;
}

void Fraction::cin_den(long long temp_a) {
	this->denominator = temp_a;
}
<commit_msg>Update Fraction.cpp<commit_after>#include "Fraction.h"
#include <cmath>
#include <iostream>
#include <sstream>

long long Fraction::gcd(long long numerator, long long denominator) {                  // Greatest common factor
	long long temp;
	if (numerator < denominator) {
		temp = denominator;
		denominator = numerator;
		numerator = temp;
	}
	while (denominator != 0) {
		temp = numerator % denominator;
		numerator = denominator;
		denominator = temp;
	}
	return numerator;
}

void Fraction::rof() {
	if (numerator) {
		long long g = gcd(abs(numerator), denominator);                                 // The g is greatest common divisor of two numbers.
		numerator /= g;
		denominator /= g;
	}
	else {
		denominator = 1;
	}
}

// Operator overloading.
Fraction operator + (const Fraction &frac1, const Fraction &frac2) {
	return Fraction(frac1.numerator * frac2.denominator + frac2.numerator * frac1.denominator, frac2.denominator * frac1.denominator);
}

Fraction operator += (Fraction &frac1, const Fraction &frac2) {
	frac1 = Fraction(frac1.numerator * frac2.denominator + frac2.numerator * frac1.denominator, frac2.denominator * frac1.denominator);
	return frac1;
}

Fraction operator - (const Fraction &frac1, const Fraction &frac2) {
	return Fraction(frac1.numerator * frac2.denominator - frac2.numerator * frac1.denominator, frac2.denominator * frac1.denominator);
}

Fraction operator -= (Fraction &frac1, const Fraction &frac2) {
	frac1 = Fraction(frac1.numerator * frac2.denominator - frac2.numerator * frac1.denominator, frac2.denominator * frac1.denominator);
	return frac1;
}

Fraction operator * (const Fraction &frac1, const Fraction &frac2) {
	return Fraction(frac1.numerator * frac2.numerator, frac2.denominator * frac1.denominator);
}

Fraction operator *= (Fraction &frac1, const Fraction &frac2) {
	frac1 = Fraction(frac1.numerator * frac2.numerator, frac2.denominator * frac1.denominator);
	return frac1;
}

Fraction operator / (const Fraction &frac1, const Fraction &frac2) {
	return Fraction(frac1.numerator * frac2.denominator, frac2.numerator * frac1.denominator);
}

Fraction operator /= (Fraction &frac1, const Fraction &frac2) {
	frac1 = Fraction(frac1.numerator * frac2.denominator, frac2.numerator * frac1.denominator);
	return frac1;
}

std::ostream& operator<< (std::ostream &os, const Fraction &frac) {
	Fraction frac_temp(frac.numerator, frac.denominator);
	os << frac_temp.numerator;						// When denominator is 1, do not output it.
	if (frac_temp.denominator != 1)
		os << "/" << frac_temp.denominator;
	return os;
}

std::istream& operator >> (std::istream &is, Fraction &frac) {
	is >> frac.numerator;
	if (is.get() != '/') {							// read denominator if and only if next char is '/'
		return is;
	}
	else {
		is >> frac.denominator;
	}
	is.get();								        // use get() to clear the break
	return is;
}

bool operator == (const Fraction &frac1, const Fraction &frac2) {
	return (frac1.numerator * frac2.denominator) == (frac2.numerator * frac1.denominator);
}

bool operator != (const Fraction &frac1, const Fraction &frac2) {
	return !(frac1 == frac2);
}

bool operator < (const Fraction &frac1, const Fraction &frac2) {
	return (frac1.numerator * frac2.denominator) < (frac2.numerator * frac1.denominator);
}

bool operator <= (const Fraction &frac1, const Fraction &frac2) {
	return (frac1 < frac2) || (frac1 == frac2);
}

bool operator > (const Fraction &frac1, const Fraction &frac2) {
	return !(frac1 <= frac2);
}

bool operator >= (const Fraction &frac1, const Fraction &frac2) {
	return !(frac1 < frac2);
}

Fraction Fraction::Frac_abs(Fraction &temp_frac) {                                       // Absolute value of a fraction.
	return (temp_frac >= 0) ? temp_frac : (0 - temp_frac);
}

void Fraction::cin_num(long long temp_a) {                                               // Input a Fraction's numerator.
	this->numerator = temp_a;
}

void Fraction::cin_den(long long temp_a) {                                               // Input a Fraction's denminator.
	this->denominator = temp_a;
}

string Fraction::cout_temp_addition_for_transmission() const {                           // Temporary output.
	std::ostringstream out;
	out << *this;

	return out.str();
}
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

//-----------------------------------------------------------------
//           Implementation of the TPC PID class
// Very naive one... Should be made better by the detector experts...
//      Origin: Iouri Belikov, CERN, Jouri.Belikov@cern.ch
//-----------------------------------------------------------------

#include "AliTPCpidESD.h"
#include "AliESDEvent.h"
#include "AliESDtrack.h"

ClassImp(AliTPCpidESD)

//_________________________________________________________________________
  AliTPCpidESD::AliTPCpidESD(Double_t *param):
    fMIP(0.),
    fRes(0.),
    fRange(0.)
{
  //
  //  The main constructor
  //
  fMIP=param[0];
  fRes=param[1];
  fRange=param[2];
}

Double_t AliTPCpidESD::Bethe(Double_t bg) {
  //
  // This is the Bethe-Bloch function normalised to 1 at the minimum
  //
  Double_t bg2=bg*bg;
  Double_t bethe;
  if (bg<3.5e1)
      bethe=(1.+ bg2)/bg2*(log(5940*bg2) - bg2/(1.+ bg2));
  else // Density effect ( approximately :)
      bethe=1.15*(1.+ bg2)/bg2*(log(3.5*5940*bg) - bg2/(1.+ bg2));
  return bethe/11.091;
}

//_________________________________________________________________________
Int_t AliTPCpidESD::MakePID(AliESDEvent *event)
{
  //
  //  This function calculates the "detector response" PID probabilities
  //
  Int_t ntrk=event->GetNumberOfTracks();
  for (Int_t i=0; i<ntrk; i++) {
    AliESDtrack *t=event->GetTrack(i);
    if ((t->GetStatus()&AliESDtrack::kTPCin )==0)
      if ((t->GetStatus()&AliESDtrack::kTPCout)==0) continue;
    Double_t p[10];
    Double_t mom=t->GetP();
    const AliExternalTrackParam *in=t->GetInnerParam();
    if (in) mom=in->GetP();
    Double_t dedx=t->GetTPCsignal()/fMIP;
    Bool_t mismatch=kTRUE, heavy=kTRUE;
    for (Int_t j=0; j<AliPID::kSPECIES; j++) {
      Double_t mass=AliPID::ParticleMass(j);
      Double_t bethe=Bethe(mom/mass);
      Double_t sigma=fRes*bethe;
      if (TMath::Abs(dedx-bethe) > fRange*sigma) {
	p[j]=TMath::Exp(-0.5*fRange*fRange)/sigma;
      } else {
        p[j]=TMath::Exp(-0.5*(dedx-bethe)*(dedx-bethe)/(sigma*sigma))/sigma;
        mismatch=kFALSE;
      }

      // Check for particles heavier than (AliPID::kSPECIES - 1)
      if (dedx < (bethe + fRange*sigma)) heavy=kFALSE;

    }

    if (mismatch)
       for (Int_t j=0; j<AliPID::kSPECIES; j++) p[j]=1/AliPID::kSPECIES;

    t->SetTPCpid(p);

    if (heavy) t->ResetStatus(AliESDtrack::kTPCpid);

  }
  return 0;
}
<commit_msg>Improved Bethe-Bloch formula (Yuri)<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

//-----------------------------------------------------------------
//           Implementation of the TPC PID class
// Very naive one... Should be made better by the detector experts...
//      Origin: Iouri Belikov, CERN, Jouri.Belikov@cern.ch
//-----------------------------------------------------------------

#include "AliTPCpidESD.h"
#include "AliESDEvent.h"
#include "AliESDtrack.h"

ClassImp(AliTPCpidESD)

//_________________________________________________________________________
  AliTPCpidESD::AliTPCpidESD(Double_t *param):
    fMIP(0.),
    fRes(0.),
    fRange(0.)
{
  //
  //  The main constructor
  //
  fMIP=param[0];
  fRes=param[1];
  fRange=param[2];
}

Double_t AliTPCpidESD::Bethe(Double_t bg) {
  //
  // This is the Bethe-Bloch function normalised to 1 at the minimum
  //
  Double_t bg2=bg*bg;
  Double_t beta2 = bg2/(1.+ bg2);

  return 8.62702e-2*(9.14550 - beta2 - TMath::Log(3.51000e-5 + 1./bg2))/beta2;
}

//_________________________________________________________________________
Int_t AliTPCpidESD::MakePID(AliESDEvent *event)
{
  //
  //  This function calculates the "detector response" PID probabilities
  //
  Int_t ntrk=event->GetNumberOfTracks();
  for (Int_t i=0; i<ntrk; i++) {
    AliESDtrack *t=event->GetTrack(i);
    if ((t->GetStatus()&AliESDtrack::kTPCin )==0)
      if ((t->GetStatus()&AliESDtrack::kTPCout)==0) continue;
    Double_t p[10];
    Double_t mom=t->GetP();
    const AliExternalTrackParam *in=t->GetInnerParam();
    if (in) mom=in->GetP();
    Double_t dedx=t->GetTPCsignal()/fMIP;
    Bool_t mismatch=kTRUE, heavy=kTRUE;
    for (Int_t j=0; j<AliPID::kSPECIES; j++) {
      Double_t mass=AliPID::ParticleMass(j);
      Double_t bethe=Bethe(mom/mass);
      Double_t sigma=fRes*bethe;
      if (TMath::Abs(dedx-bethe) > fRange*sigma) {
	p[j]=TMath::Exp(-0.5*fRange*fRange)/sigma;
      } else {
        p[j]=TMath::Exp(-0.5*(dedx-bethe)*(dedx-bethe)/(sigma*sigma))/sigma;
        mismatch=kFALSE;
      }

      // Check for particles heavier than (AliPID::kSPECIES - 1)
      if (dedx < (bethe + fRange*sigma)) heavy=kFALSE;

    }

    if (mismatch)
       for (Int_t j=0; j<AliPID::kSPECIES; j++) p[j]=1/AliPID::kSPECIES;

    t->SetTPCpid(p);

    if (heavy) t->ResetStatus(AliESDtrack::kTPCpid);

  }
  return 0;
}
<|endoftext|>


<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/extensions/file_manager/url_util.h"

#include "base/files/file_path.h"
#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/strings/utf_string_conversions.h"
#include "net/base/escape.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace file_manager {
namespace util {
namespace {

// Pretty print the JSON escaped in the query string.
std::string PrettyPrintEscapedJson(const std::string& query) {
  const std::string json = net::UnescapeURLComponent(
      query, net::UnescapeRule::SPACES | net::UnescapeRule::URL_SPECIAL_CHARS);
  const base::Value* value = base::JSONReader::Read(json);
  std::string pretty_json;
  base::JSONWriter::WriteWithOptions(value,
                                     base::JSONWriter::OPTIONS_PRETTY_PRINT,
                                     &pretty_json);
  return pretty_json;
}

TEST(FileManagerUrlUtilTest, GetFileManagerBaseUrl) {
  EXPECT_EQ("chrome-extension://hhaomjibdihmijegdhdafkllkbggdgoj/",
            GetFileManagerBaseUrl().spec());
}

TEST(FileManagerUrlUtilTest, GetFileManagerMainPageUrl) {
  EXPECT_EQ("chrome-extension://hhaomjibdihmijegdhdafkllkbggdgoj/main.html",
            GetFileManagerMainPageUrl().spec());
}

TEST(FileManagerUrlUtilTest, GetFileManagerMainPageUrlWithParams_NoFileTypes) {
  const GURL url = GetFileManagerMainPageUrlWithParams(
      ui::SelectFileDialog::SELECT_OPEN_FILE,
      base::UTF8ToUTF16("some title"),
      base::FilePath::FromUTF8Unsafe("foo.txt"),
      NULL,  // No file types
      0,  // Hence no file type index.
      FILE_PATH_LITERAL("txt"));
  EXPECT_EQ("chrome-extension", url.scheme());
  EXPECT_EQ("hhaomjibdihmijegdhdafkllkbggdgoj", url.host());
  EXPECT_EQ("/main.html", url.path());
  // Confirm that "%20" is used instead of "+" in the query.
  EXPECT_TRUE(url.query().find("+") == std::string::npos);
  EXPECT_TRUE(url.query().find("%20") != std::string::npos);
  // The escaped query is hard to read. Pretty print the escaped JSON.
  EXPECT_EQ("{\n"
            "   \"defaultExtension\": \"txt\",\n"
            "   \"defaultPath\": \"foo.txt\",\n"
            "   \"shouldReturnLocalPath\": true,\n"
            "   \"title\": \"some title\",\n"
            "   \"type\": \"open-file\"\n"
            "}\n",
            PrettyPrintEscapedJson(url.query()));
}

TEST(FileManagerUrlUtilTest,
     GetFileManagerMainPageUrlWithParams_WithFileTypes) {
  // Create a FileTypeInfo which looks like:
  // extensions: [["htm", "html"], ["txt"]]
  // descriptions: ["HTML", "TEXT"]
  ui::SelectFileDialog::FileTypeInfo file_types;
  file_types.extensions.push_back(std::vector<base::FilePath::StringType>());
  file_types.extensions[0].push_back(FILE_PATH_LITERAL("htm"));
  file_types.extensions[0].push_back(FILE_PATH_LITERAL("html"));
  file_types.extensions.push_back(std::vector<base::FilePath::StringType>());
  file_types.extensions[1].push_back(FILE_PATH_LITERAL("txt"));
  file_types.extension_description_overrides.push_back(
      base::UTF8ToUTF16("HTML"));
  file_types.extension_description_overrides.push_back(
      base::UTF8ToUTF16("TEXT"));
  // "shouldReturnLocalPath" will be false if drive is supported.
  file_types.support_drive = true;

  const GURL url = GetFileManagerMainPageUrlWithParams(
      ui::SelectFileDialog::SELECT_OPEN_FILE,
      base::UTF8ToUTF16("some title"),
      base::FilePath::FromUTF8Unsafe("foo.txt"),
      &file_types,
      1,  // The file type index is 1-based.
      FILE_PATH_LITERAL("txt"));
  EXPECT_EQ("chrome-extension", url.scheme());
  EXPECT_EQ("hhaomjibdihmijegdhdafkllkbggdgoj", url.host());
  EXPECT_EQ("/main.html", url.path());
  // Confirm that "%20" is used instead of "+" in the query.
  EXPECT_TRUE(url.query().find("+") == std::string::npos);
  EXPECT_TRUE(url.query().find("%20") != std::string::npos);
  // The escaped query is hard to read. Pretty print the escaped JSON.
  EXPECT_EQ("{\n"
            "   \"defaultExtension\": \"txt\",\n"
            "   \"defaultPath\": \"foo.txt\",\n"
            "   \"includeAllFiles\": false,\n"
            "   \"shouldReturnLocalPath\": false,\n"
            "   \"title\": \"some title\",\n"
            "   \"type\": \"open-file\",\n"
            "   \"typeList\": [ {\n"
            "      \"description\": \"HTML\",\n"
            "      \"extensions\": [ \"htm\", \"html\" ],\n"
            "      \"selected\": true\n"
            "   }, {\n"
            "      \"description\": \"TEXT\",\n"
            "      \"extensions\": [ \"txt\" ],\n"
            "      \"selected\": false\n"
            "   } ]\n"
            "}\n",
            PrettyPrintEscapedJson(url.query()));
}

TEST(FileManagerUrlUtilTest, GetMediaPlayerUrl) {
  EXPECT_EQ("chrome-extension://hhaomjibdihmijegdhdafkllkbggdgoj/"
            "mediaplayer.html",
            GetMediaPlayerUrl().spec());
}

TEST(FileManagerUrlUtilTest, GetActionChoiceUrl_RegularMode) {
  EXPECT_EQ("chrome-extension://hhaomjibdihmijegdhdafkllkbggdgoj/"
            "action_choice.html#/foo.txt",
            GetActionChoiceUrl(base::FilePath::FromUTF8Unsafe("foo.txt"),
                               false).spec());
}

TEST(FileManagerUrlUtilTest, GetActionChoiceUrl_AdvancedMode) {
  EXPECT_EQ("chrome-extension://hhaomjibdihmijegdhdafkllkbggdgoj/"
            "action_choice.html?advanced-mode#/foo.txt",
            GetActionChoiceUrl(base::FilePath::FromUTF8Unsafe("foo.txt"),
                               true).spec());
}

}  // namespace
}  // namespace util
}  // namespace file_manager
<commit_msg>file_manager: Fix memory leak in FileManagerUrlUtilTest<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/extensions/file_manager/url_util.h"

#include "base/files/file_path.h"
#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/memory/scoped_ptr.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "net/base/escape.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace file_manager {
namespace util {
namespace {

// Pretty print the JSON escaped in the query string.
std::string PrettyPrintEscapedJson(const std::string& query) {
  const std::string json = net::UnescapeURLComponent(
      query, net::UnescapeRule::SPACES | net::UnescapeRule::URL_SPECIAL_CHARS);
  scoped_ptr<base::Value> value(base::JSONReader::Read(json));
  std::string pretty_json;
  base::JSONWriter::WriteWithOptions(value.get(),
                                     base::JSONWriter::OPTIONS_PRETTY_PRINT,
                                     &pretty_json);
  return pretty_json;
}

TEST(FileManagerUrlUtilTest, GetFileManagerBaseUrl) {
  EXPECT_EQ("chrome-extension://hhaomjibdihmijegdhdafkllkbggdgoj/",
            GetFileManagerBaseUrl().spec());
}

TEST(FileManagerUrlUtilTest, GetFileManagerMainPageUrl) {
  EXPECT_EQ("chrome-extension://hhaomjibdihmijegdhdafkllkbggdgoj/main.html",
            GetFileManagerMainPageUrl().spec());
}

TEST(FileManagerUrlUtilTest, GetFileManagerMainPageUrlWithParams_NoFileTypes) {
  const GURL url = GetFileManagerMainPageUrlWithParams(
      ui::SelectFileDialog::SELECT_OPEN_FILE,
      base::UTF8ToUTF16("some title"),
      base::FilePath::FromUTF8Unsafe("foo.txt"),
      NULL,  // No file types
      0,  // Hence no file type index.
      FILE_PATH_LITERAL("txt"));
  EXPECT_EQ("chrome-extension", url.scheme());
  EXPECT_EQ("hhaomjibdihmijegdhdafkllkbggdgoj", url.host());
  EXPECT_EQ("/main.html", url.path());
  // Confirm that "%20" is used instead of "+" in the query.
  EXPECT_TRUE(url.query().find("+") == std::string::npos);
  EXPECT_TRUE(url.query().find("%20") != std::string::npos);
  // The escaped query is hard to read. Pretty print the escaped JSON.
  EXPECT_EQ("{\n"
            "   \"defaultExtension\": \"txt\",\n"
            "   \"defaultPath\": \"foo.txt\",\n"
            "   \"shouldReturnLocalPath\": true,\n"
            "   \"title\": \"some title\",\n"
            "   \"type\": \"open-file\"\n"
            "}\n",
            PrettyPrintEscapedJson(url.query()));
}

TEST(FileManagerUrlUtilTest,
     GetFileManagerMainPageUrlWithParams_WithFileTypes) {
  // Create a FileTypeInfo which looks like:
  // extensions: [["htm", "html"], ["txt"]]
  // descriptions: ["HTML", "TEXT"]
  ui::SelectFileDialog::FileTypeInfo file_types;
  file_types.extensions.push_back(std::vector<base::FilePath::StringType>());
  file_types.extensions[0].push_back(FILE_PATH_LITERAL("htm"));
  file_types.extensions[0].push_back(FILE_PATH_LITERAL("html"));
  file_types.extensions.push_back(std::vector<base::FilePath::StringType>());
  file_types.extensions[1].push_back(FILE_PATH_LITERAL("txt"));
  file_types.extension_description_overrides.push_back(
      base::UTF8ToUTF16("HTML"));
  file_types.extension_description_overrides.push_back(
      base::UTF8ToUTF16("TEXT"));
  // "shouldReturnLocalPath" will be false if drive is supported.
  file_types.support_drive = true;

  const GURL url = GetFileManagerMainPageUrlWithParams(
      ui::SelectFileDialog::SELECT_OPEN_FILE,
      base::UTF8ToUTF16("some title"),
      base::FilePath::FromUTF8Unsafe("foo.txt"),
      &file_types,
      1,  // The file type index is 1-based.
      FILE_PATH_LITERAL("txt"));
  EXPECT_EQ("chrome-extension", url.scheme());
  EXPECT_EQ("hhaomjibdihmijegdhdafkllkbggdgoj", url.host());
  EXPECT_EQ("/main.html", url.path());
  // Confirm that "%20" is used instead of "+" in the query.
  EXPECT_TRUE(url.query().find("+") == std::string::npos);
  EXPECT_TRUE(url.query().find("%20") != std::string::npos);
  // The escaped query is hard to read. Pretty print the escaped JSON.
  EXPECT_EQ("{\n"
            "   \"defaultExtension\": \"txt\",\n"
            "   \"defaultPath\": \"foo.txt\",\n"
            "   \"includeAllFiles\": false,\n"
            "   \"shouldReturnLocalPath\": false,\n"
            "   \"title\": \"some title\",\n"
            "   \"type\": \"open-file\",\n"
            "   \"typeList\": [ {\n"
            "      \"description\": \"HTML\",\n"
            "      \"extensions\": [ \"htm\", \"html\" ],\n"
            "      \"selected\": true\n"
            "   }, {\n"
            "      \"description\": \"TEXT\",\n"
            "      \"extensions\": [ \"txt\" ],\n"
            "      \"selected\": false\n"
            "   } ]\n"
            "}\n",
            PrettyPrintEscapedJson(url.query()));
}

TEST(FileManagerUrlUtilTest, GetMediaPlayerUrl) {
  EXPECT_EQ("chrome-extension://hhaomjibdihmijegdhdafkllkbggdgoj/"
            "mediaplayer.html",
            GetMediaPlayerUrl().spec());
}

TEST(FileManagerUrlUtilTest, GetActionChoiceUrl_RegularMode) {
  EXPECT_EQ("chrome-extension://hhaomjibdihmijegdhdafkllkbggdgoj/"
            "action_choice.html#/foo.txt",
            GetActionChoiceUrl(base::FilePath::FromUTF8Unsafe("foo.txt"),
                               false).spec());
}

TEST(FileManagerUrlUtilTest, GetActionChoiceUrl_AdvancedMode) {
  EXPECT_EQ("chrome-extension://hhaomjibdihmijegdhdafkllkbggdgoj/"
            "action_choice.html?advanced-mode#/foo.txt",
            GetActionChoiceUrl(base::FilePath::FromUTF8Unsafe("foo.txt"),
                               true).spec());
}

}  // namespace
}  // namespace util
}  // namespace file_manager
<|endoftext|>


<commit_before>/***************************************************************************
 *   Copyright (c) 2008 Werner Mayer <werner.wm.mayer@gmx.de>              *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   This library  is distributed in the hope that it will be useful,      *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"

#ifndef _PreComp_
# include <qobject.h>
#endif

#include "Workbench.h"
#include <Gui/ToolBarManager.h>
#include <Gui/MenuManager.h>

using namespace FemGui;

#if 0 // needed for Qt's lupdate utility
    qApp->translate("Workbench", "FEM");
    qApp->translate("Workbench", "&FEM");
#endif

/// @namespace FemGui @class Workbench
TYPESYSTEM_SOURCE(FemGui::Workbench, Gui::StdWorkbench)

Workbench::Workbench()
{
}

Workbench::~Workbench()
{
}

void Workbench::setupContextMenu(const char* recipient, Gui::MenuItem* item) const
{
     StdWorkbench::setupContextMenu( recipient, item );
     *item << "Separator"
           << "FEM_MeshClear"
           << "FEM_MeshPrintInfo";
}

Gui::ToolBarItem* Workbench::setupToolBars() const
{
    Gui::ToolBarItem* root = StdWorkbench::setupToolBars();
    Gui::ToolBarItem* model = new Gui::ToolBarItem(root);
    model->setCommand("Model");
    *model << "FEM_Analysis"
           << "Separator"
           << "FEM_MaterialSolid"
           << "FEM_MaterialFluid"
           << "FEM_MaterialMechanicalNonlinear"
           << "FEM_ElementGeometry1D"
           << "FEM_ElementRotation1D"
           << "FEM_ElementGeometry2D"
           << "FEM_ElementFluid1D";

    Gui::ToolBarItem* mech = new Gui::ToolBarItem(root);
    mech->setCommand("Mechanical Constraints");
    *mech << "FEM_ConstraintFixed"
          << "FEM_ConstraintDisplacement"
          << "FEM_ConstraintPlaneRotation"
          << "FEM_ConstraintContact"
          << "FEM_ConstraintTransform"
          << "Separator"
          << "FEM_ConstraintForce"
          << "FEM_ConstraintPressure"
          << "FEM_ConstraintSelfWeight";

    Gui::ToolBarItem* thermal = new Gui::ToolBarItem(root);
    thermal->setCommand("Thermal Constraints");
    *thermal << "FEM_ConstraintInitialTemperature"
             << "Separator"
             << "FEM_ConstraintTemperature"
             << "FEM_ConstraintHeatflux";

     Gui::ToolBarItem* mesh = new Gui::ToolBarItem(root);
     mesh->setCommand("Mesh");
#ifdef FCWithNetgen
     *mesh << "FEM_MeshNetgenFromShape";
#endif
     *mesh << "FEM_MeshGmshFromShape"
           << "Separator"
           << "FEM_MeshBoundaryLayer"
           << "FEM_MeshRegion"
           << "FEM_MeshGroup"
           << "Separator"
           << "FEM_FEMMesh2Mesh";

    Gui::ToolBarItem* fluid = new Gui::ToolBarItem(root);
    fluid->setCommand("Fluid Constraints");
    *fluid << "FEM_ConstraintInitialFlowVelocity"
           << "Separator"
           << "FEM_ConstraintFluidBoundary"
           << "FEM_ConstraintFlowVelocity";

    Gui::ToolBarItem* electrostat = new Gui::ToolBarItem(root);
    electrostat->setCommand("Electrostatic Constraints");
    *electrostat << "FEM_ConstraintElectrostaticPotential";

     Gui::ToolBarItem* solve = new Gui::ToolBarItem(root);
     solve->setCommand("Solve");
     *solve << "FEM_SolverCalculixCxxtools"
           << "FEM_SolverCalculiX"
           << "FEM_SolverElmer"
           << "Separator"
           << "FEM_EquationHeat"
           << "FEM_EquationElasticity"
           << "FEM_EquationFluxsolver"
           << "FEM_EquationElectrostatic"
           << "FEM_EquationFlow"
           << "Separator"
           << "FEM_SolverControl"
           << "FEM_SolverRun";

     Gui::ToolBarItem* results = new Gui::ToolBarItem(root);
     results->setCommand("Results");
     *results << "FEM_ResultsPurge"
              << "FEM_ResultShow";

#ifdef FC_USE_VTK
     *results << "Separator"
              << "FEM_PostApplyChanges"
              << "FEM_PostPipelineFromResult"
              << "Separator"
              << "FEM_PostCreateClipFilter"
              << "FEM_PostCreateScalarClipFilter"
              << "FEM_PostCreateCutFilter"
              << "FEM_PostCreateWarpVectorFilter"
              << "FEM_PostCreateDataAlongLineFilter"
              << "FEM_PostCreateLinearizedStressesFilter"
              << "FEM_PostCreateDataAtPointFilter"
              << "Separator"
              << "FEM_PostCreateFunctions";
#endif

    return root;
}

Gui::MenuItem* Workbench::setupMenuBar() const
{
    Gui::MenuItem* root = StdWorkbench::setupMenuBar();
    Gui::MenuItem* item = root->findItem("&Windows");

    Gui::MenuItem* elec = new Gui::MenuItem;
    elec->setCommand("&Electrostatic Constraints");
    *elec << "FEM_ConstraintElectrostaticPotential";

    Gui::MenuItem* mech = new Gui::MenuItem;
    mech->setCommand("&Mechanical Constraints");
    *mech << "FEM_ConstraintFixed"
          << "FEM_ConstraintDisplacement"
          << "FEM_ConstraintPlaneRotation"
          << "FEM_ConstraintContact"
          << "FEM_ConstraintTransform"
          << "Separator"
          << "FEM_ConstraintForce"
          << "FEM_ConstraintPressure"
          << "FEM_ConstraintSelfWeight"
          << "Separator"
          << "FEM_ConstraintBearing"
          << "FEM_ConstraintGear"
          << "FEM_ConstraintPulley";

    Gui::MenuItem* thermal = new Gui::MenuItem;
    thermal->setCommand("&Thermal Constraints");
    *thermal << "FEM_ConstraintInitialTemperature"
             << "Separator"
             << "FEM_ConstraintHeatflux"
             << "FEM_ConstraintTemperature"
             << "FEM_ConstraintBodyHeatSource";

    Gui::MenuItem* fluid = new Gui::MenuItem;
    fluid->setCommand("&Fluid Constraints");
    *fluid << "FEM_ConstraintInitialFlowVelocity"
           << "Separator"
           << "FEM_ConstraintFluidBoundary"
           << "FEM_ConstraintFlowVelocity";

    Gui::MenuItem* model = new Gui::MenuItem;
    root->insertItem(item, model);
    model->setCommand("M&odel");
    *model << "FEM_Analysis"
           << "Separator"
           << "FEM_MaterialSolid"
           << "FEM_MaterialFluid"
           << "FEM_MaterialMechanicalNonlinear"
           << "FEM_ElementGeometry1D"
           << "FEM_ElementRotation1D"
           << "FEM_ElementGeometry2D"
           << "FEM_ElementFluid1D"
           << "Separator"
           << elec
           << fluid
           << mech
           << thermal;

    Gui::MenuItem* mesh = new Gui::MenuItem;
    root->insertItem(item, mesh);
    mesh->setCommand("M&esh");
#ifdef FCWithNetgen
     *mesh << "FEM_MeshNetgenFromShape";
#endif
     *mesh << "FEM_MeshGmshFromShape"
           << "Separator"
           << "FEM_MeshBoundaryLayer"
           << "FEM_MeshRegion"
           << "FEM_MeshGroup"
           << "Separator"
           << "FEM_CreateNodesSet"
           << "FEM_FEMMesh2Mesh";

    Gui::MenuItem* solve = new Gui::MenuItem;
    root->insertItem(item, solve);
    solve->setCommand("&Solve");
    *solve << "FEM_SolverCalculixCxxtools"
           << "FEM_SolverCalculiX"
           << "FEM_SolverElmer"
           << "FEM_SolverZ88"
           << "Separator"
           << "FEM_EquationHeat"
           << "FEM_EquationElasticity"
           << "FEM_EquationElectrostatic"
           << "FEM_EquationFluxsolver"
           << "FEM_EquationFlow"
           << "Separator"
           << "FEM_SolverControl"
           << "FEM_SolverRun";

    Gui::MenuItem* results = new Gui::MenuItem;
    root->insertItem(item, results);
    results->setCommand("&Results");
    *results << "FEM_ResultsPurge"
             << "FEM_ResultShow";

#ifdef FC_USE_VTK
    *results << "Separator"
             << "FEM_PostApplyChanges"
             << "FEM_PostPipelineFromResult"
             << "Separator"
             << "FEM_PostCreateClipFilter"
             << "FEM_PostCreateScalarClipFilter"
             << "FEM_PostCreateCutFilter"
             << "FEM_PostCreateWarpVectorFilter"
             << "FEM_PostCreateDataAlongLineFilter"
             << "FEM_PostCreateLinearizedStressesFilter"
             << "FEM_PostCreateDataAtPointFilter"
             << "Separator"
             << "FEM_PostCreateFunctions";
#endif

    return root;
}
<commit_msg>FEM: menue entries, add submenue for materials<commit_after>/***************************************************************************
 *   Copyright (c) 2008 Werner Mayer <werner.wm.mayer@gmx.de>              *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   This library  is distributed in the hope that it will be useful,      *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"

#ifndef _PreComp_
# include <qobject.h>
#endif

#include "Workbench.h"
#include <Gui/ToolBarManager.h>
#include <Gui/MenuManager.h>

using namespace FemGui;

#if 0 // needed for Qt's lupdate utility
    qApp->translate("Workbench", "FEM");
    qApp->translate("Workbench", "&FEM");
#endif

/// @namespace FemGui @class Workbench
TYPESYSTEM_SOURCE(FemGui::Workbench, Gui::StdWorkbench)

Workbench::Workbench()
{
}

Workbench::~Workbench()
{
}

void Workbench::setupContextMenu(const char* recipient, Gui::MenuItem* item) const
{
     StdWorkbench::setupContextMenu( recipient, item );
     *item << "Separator"
           << "FEM_MeshClear"
           << "FEM_MeshPrintInfo";
}

Gui::ToolBarItem* Workbench::setupToolBars() const
{
    Gui::ToolBarItem* root = StdWorkbench::setupToolBars();
    Gui::ToolBarItem* model = new Gui::ToolBarItem(root);
    model->setCommand("Model");
    *model << "FEM_Analysis"
           << "Separator"
           << "FEM_MaterialSolid"
           << "FEM_MaterialFluid"
           << "FEM_MaterialMechanicalNonlinear"
           << "FEM_ElementGeometry1D"
           << "FEM_ElementRotation1D"
           << "FEM_ElementGeometry2D"
           << "FEM_ElementFluid1D";

    Gui::ToolBarItem* mech = new Gui::ToolBarItem(root);
    mech->setCommand("Mechanical Constraints");
    *mech << "FEM_ConstraintFixed"
          << "FEM_ConstraintDisplacement"
          << "FEM_ConstraintPlaneRotation"
          << "FEM_ConstraintContact"
          << "FEM_ConstraintTransform"
          << "Separator"
          << "FEM_ConstraintForce"
          << "FEM_ConstraintPressure"
          << "FEM_ConstraintSelfWeight";

    Gui::ToolBarItem* thermal = new Gui::ToolBarItem(root);
    thermal->setCommand("Thermal Constraints");
    *thermal << "FEM_ConstraintInitialTemperature"
             << "Separator"
             << "FEM_ConstraintTemperature"
             << "FEM_ConstraintHeatflux";

     Gui::ToolBarItem* mesh = new Gui::ToolBarItem(root);
     mesh->setCommand("Mesh");
#ifdef FCWithNetgen
     *mesh << "FEM_MeshNetgenFromShape";
#endif
     *mesh << "FEM_MeshGmshFromShape"
           << "Separator"
           << "FEM_MeshBoundaryLayer"
           << "FEM_MeshRegion"
           << "FEM_MeshGroup"
           << "Separator"
           << "FEM_FEMMesh2Mesh";

    Gui::ToolBarItem* fluid = new Gui::ToolBarItem(root);
    fluid->setCommand("Fluid Constraints");
    *fluid << "FEM_ConstraintInitialFlowVelocity"
           << "Separator"
           << "FEM_ConstraintFluidBoundary"
           << "FEM_ConstraintFlowVelocity";

    Gui::ToolBarItem* electrostat = new Gui::ToolBarItem(root);
    electrostat->setCommand("Electrostatic Constraints");
    *electrostat << "FEM_ConstraintElectrostaticPotential";

     Gui::ToolBarItem* solve = new Gui::ToolBarItem(root);
     solve->setCommand("Solve");
     *solve << "FEM_SolverCalculixCxxtools"
           << "FEM_SolverCalculiX"
           << "FEM_SolverElmer"
           << "Separator"
           << "FEM_EquationHeat"
           << "FEM_EquationElasticity"
           << "FEM_EquationFluxsolver"
           << "FEM_EquationElectrostatic"
           << "FEM_EquationFlow"
           << "Separator"
           << "FEM_SolverControl"
           << "FEM_SolverRun";

     Gui::ToolBarItem* results = new Gui::ToolBarItem(root);
     results->setCommand("Results");
     *results << "FEM_ResultsPurge"
              << "FEM_ResultShow";

#ifdef FC_USE_VTK
     *results << "Separator"
              << "FEM_PostApplyChanges"
              << "FEM_PostPipelineFromResult"
              << "Separator"
              << "FEM_PostCreateClipFilter"
              << "FEM_PostCreateScalarClipFilter"
              << "FEM_PostCreateCutFilter"
              << "FEM_PostCreateWarpVectorFilter"
              << "FEM_PostCreateDataAlongLineFilter"
              << "FEM_PostCreateLinearizedStressesFilter"
              << "FEM_PostCreateDataAtPointFilter"
              << "Separator"
              << "FEM_PostCreateFunctions";
#endif

    return root;
}

Gui::MenuItem* Workbench::setupMenuBar() const
{
    Gui::MenuItem* root = StdWorkbench::setupMenuBar();
    Gui::MenuItem* item = root->findItem("&Windows");

    Gui::MenuItem* material = new Gui::MenuItem;
    material->setCommand("Materials");
    *material << "FEM_MaterialSolid"
              << "FEM_MaterialFluid"
              << "FEM_MaterialMechanicalNonlinear";

    Gui::MenuItem* elec = new Gui::MenuItem;
    elec->setCommand("&Electrostatic Constraints");
    *elec << "FEM_ConstraintElectrostaticPotential";

    Gui::MenuItem* mech = new Gui::MenuItem;
    mech->setCommand("&Mechanical Constraints");
    *mech << "FEM_ConstraintFixed"
          << "FEM_ConstraintDisplacement"
          << "FEM_ConstraintPlaneRotation"
          << "FEM_ConstraintContact"
          << "FEM_ConstraintTransform"
          << "Separator"
          << "FEM_ConstraintForce"
          << "FEM_ConstraintPressure"
          << "FEM_ConstraintSelfWeight"
          << "Separator"
          << "FEM_ConstraintBearing"
          << "FEM_ConstraintGear"
          << "FEM_ConstraintPulley";

    Gui::MenuItem* thermal = new Gui::MenuItem;
    thermal->setCommand("&Thermal Constraints");
    *thermal << "FEM_ConstraintInitialTemperature"
             << "Separator"
             << "FEM_ConstraintHeatflux"
             << "FEM_ConstraintTemperature"
             << "FEM_ConstraintBodyHeatSource";

    Gui::MenuItem* fluid = new Gui::MenuItem;
    fluid->setCommand("&Fluid Constraints");
    *fluid << "FEM_ConstraintInitialFlowVelocity"
           << "Separator"
           << "FEM_ConstraintFluidBoundary"
           << "FEM_ConstraintFlowVelocity";

    Gui::MenuItem* model = new Gui::MenuItem;
    root->insertItem(item, model);
    model->setCommand("M&odel");
    *model << "FEM_Analysis"
           << "Separator"
           << material
           << "Separator"
           << "FEM_ElementGeometry1D"
           << "FEM_ElementRotation1D"
           << "FEM_ElementGeometry2D"
           << "FEM_ElementFluid1D"
           << "Separator"
           << elec
           << fluid
           << mech
           << thermal;

    Gui::MenuItem* mesh = new Gui::MenuItem;
    root->insertItem(item, mesh);
    mesh->setCommand("M&esh");
#ifdef FCWithNetgen
     *mesh << "FEM_MeshNetgenFromShape";
#endif
     *mesh << "FEM_MeshGmshFromShape"
           << "Separator"
           << "FEM_MeshBoundaryLayer"
           << "FEM_MeshRegion"
           << "FEM_MeshGroup"
           << "Separator"
           << "FEM_CreateNodesSet"
           << "FEM_FEMMesh2Mesh";

    Gui::MenuItem* solve = new Gui::MenuItem;
    root->insertItem(item, solve);
    solve->setCommand("&Solve");
    *solve << "FEM_SolverCalculixCxxtools"
           << "FEM_SolverCalculiX"
           << "FEM_SolverElmer"
           << "FEM_SolverZ88"
           << "Separator"
           << "FEM_EquationHeat"
           << "FEM_EquationElasticity"
           << "FEM_EquationElectrostatic"
           << "FEM_EquationFluxsolver"
           << "FEM_EquationFlow"
           << "Separator"
           << "FEM_SolverControl"
           << "FEM_SolverRun";

    Gui::MenuItem* results = new Gui::MenuItem;
    root->insertItem(item, results);
    results->setCommand("&Results");
    *results << "FEM_ResultsPurge"
             << "FEM_ResultShow";

#ifdef FC_USE_VTK
    *results << "Separator"
             << "FEM_PostApplyChanges"
             << "FEM_PostPipelineFromResult"
             << "Separator"
             << "FEM_PostCreateClipFilter"
             << "FEM_PostCreateScalarClipFilter"
             << "FEM_PostCreateCutFilter"
             << "FEM_PostCreateWarpVectorFilter"
             << "FEM_PostCreateDataAlongLineFilter"
             << "FEM_PostCreateLinearizedStressesFilter"
             << "FEM_PostCreateDataAtPointFilter"
             << "Separator"
             << "FEM_PostCreateFunctions";
#endif

    return root;
}
<|endoftext|>


<commit_before>#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include "snarkfront.hpp"

using namespace snarkfront;
using namespace std;

void printUsage(const char* exeName) {
    cout << "usage: " << exeName
         << " -p BN128|Edwards"
            " -b 256|512"
            " -d tree_depth"
            " -i leaf_number"
         << endl;

    exit(EXIT_FAILURE);
}

template <typename PAIRING, typename BUNDLE, typename ZK_PATH>
void runTest(const size_t treeDepth,
             const size_t leafNumber)
{
    BUNDLE bundle(treeDepth);

    while (! bundle.isFull()) {
        const typename BUNDLE::DigType leaf{bundle.treeSize()};

        bundle.addLeaf(
            leaf,
            leafNumber == bundle.treeSize());
    }

    if (leafNumber >= bundle.treeSize()) {
        cout << "leaf number " << leafNumber
             << " is larger than " << bundle.treeSize()
             << endl;

        exit(EXIT_FAILURE);
    }

    const auto& leaf = bundle.authLeaf().front();
    const auto& authPath = bundle.authPath().front();

    cout << "leaf " << leafNumber << " child bits ";
    for (int i = authPath.childBits().size() - 1; i >= 0; --i) {
        cout << authPath.childBits()[i];
    }
    cout << endl;

    cout << "root path" << endl;
    for (int i = authPath.rootPath().size() - 1; i >= 0; --i) {
        cout << "[" << i << "] "
             << asciiHex(authPath.rootPath()[i], true) << endl;
    }

    cout << "siblings" << endl;
    for (int i = authPath.siblings().size() - 1; i >= 0; --i) {
        cout << "[" << i << "] "
             << asciiHex(authPath.siblings()[i], true) << endl;
    }

    typename ZK_PATH::DigType rt;
    bless(rt, authPath.rootHash());

    end_input<PAIRING>();

    typename ZK_PATH::DigType zkLeaf;
    bless(zkLeaf, leaf);

    ZK_PATH zkAuthPath(authPath);
    zkAuthPath.updatePath(zkLeaf);

    assert_true(rt == zkAuthPath.rootHash());

    cout << "variable count " << variable_count<PAIRING>() << endl;
}

template <typename PAIRING>
bool runTest(const string& shaBits,
             const size_t treeDepth,
             const size_t leafNumber)
{
    typedef typename PAIRING::Fr FR;

    if (nameSHA256(shaBits)) {
        runTest<PAIRING,
                MerkleBundle_SHA256<uint32_t>, // count could be size_t
                zk::MerkleAuthPath_SHA256<FR>>(
            treeDepth,
            leafNumber);

    } else if (nameSHA512(shaBits)) {
        runTest<PAIRING,
                MerkleBundle_SHA512<uint64_t>, // count could be size_t
                zk::MerkleAuthPath_SHA512<FR>>(
            treeDepth,
            leafNumber);
    }

    GenericProgressBar progress1(cerr), progress2(cerr, 50);

    cerr << "generate key pair";
    const auto key = keypair<PAIRING>(progress2);
    cerr << endl;

    const auto in = input<PAIRING>();

    cerr << "generate proof";
    const auto p = proof(key, progress2);
    cerr << endl;

    cerr << "verify proof ";
    const bool proofOK = verify(key, in, p, progress1);
    cerr << endl;

    return proofOK;
}

int main(int argc, char *argv[])
{
    Getopt cmdLine(argc, argv, "pb", "di", "");
    if (!cmdLine || cmdLine.empty()) printUsage(argv[0]);

    const auto
        pairing = cmdLine.getString('p'),
        shaBits = cmdLine.getString('b');

    const auto
        treeDepth = cmdLine.getNumber('d'),
        leafNumber = cmdLine.getNumber('i');

    if (!validPairingName(pairing) ||
        !(nameSHA256(shaBits) || nameSHA512(shaBits)) ||
        -1 == treeDepth ||
        -1 == leafNumber)
        printUsage(argv[0]);

    bool result;

    if (pairingBN128(pairing)) {
        // Barreto-Naehrig 128 bits
        init_BN128();
        result = runTest<BN128_PAIRING>(shaBits, treeDepth, leafNumber);

    } else if (pairingEdwards(pairing)) {
        // Edwards 80 bits
        init_Edwards();
        result = runTest<EDWARDS_PAIRING>(shaBits, treeDepth, leafNumber);
    }

    cout << "proof verification " << (result ? "OK" : "FAIL") << endl;

    exit(EXIT_SUCCESS);
}
<commit_msg>return EXIT_SUCCESS in main()<commit_after>#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include "snarkfront.hpp"

using namespace snarkfront;
using namespace std;

void printUsage(const char* exeName) {
    cout << "usage: " << exeName
         << " -p BN128|Edwards"
            " -b 256|512"
            " -d tree_depth"
            " -i leaf_number"
         << endl;

    exit(EXIT_FAILURE);
}

template <typename PAIRING, typename BUNDLE, typename ZK_PATH>
void runTest(const size_t treeDepth,
             const size_t leafNumber)
{
    BUNDLE bundle(treeDepth);

    while (! bundle.isFull()) {
        const typename BUNDLE::DigType leaf{bundle.treeSize()};

        bundle.addLeaf(
            leaf,
            leafNumber == bundle.treeSize());
    }

    if (leafNumber >= bundle.treeSize()) {
        cout << "leaf number " << leafNumber
             << " is larger than " << bundle.treeSize()
             << endl;

        exit(EXIT_FAILURE);
    }

    const auto& leaf = bundle.authLeaf().front();
    const auto& authPath = bundle.authPath().front();

    cout << "leaf " << leafNumber << " child bits ";
    for (int i = authPath.childBits().size() - 1; i >= 0; --i) {
        cout << authPath.childBits()[i];
    }
    cout << endl;

    cout << "root path" << endl;
    for (int i = authPath.rootPath().size() - 1; i >= 0; --i) {
        cout << "[" << i << "] "
             << asciiHex(authPath.rootPath()[i], true) << endl;
    }

    cout << "siblings" << endl;
    for (int i = authPath.siblings().size() - 1; i >= 0; --i) {
        cout << "[" << i << "] "
             << asciiHex(authPath.siblings()[i], true) << endl;
    }

    typename ZK_PATH::DigType rt;
    bless(rt, authPath.rootHash());

    end_input<PAIRING>();

    typename ZK_PATH::DigType zkLeaf;
    bless(zkLeaf, leaf);

    ZK_PATH zkAuthPath(authPath);
    zkAuthPath.updatePath(zkLeaf);

    assert_true(rt == zkAuthPath.rootHash());

    cout << "variable count " << variable_count<PAIRING>() << endl;
}

template <typename PAIRING>
bool runTest(const string& shaBits,
             const size_t treeDepth,
             const size_t leafNumber)
{
    typedef typename PAIRING::Fr FR;

    if (nameSHA256(shaBits)) {
        runTest<PAIRING,
                MerkleBundle_SHA256<uint32_t>, // count could be size_t
                zk::MerkleAuthPath_SHA256<FR>>(
            treeDepth,
            leafNumber);

    } else if (nameSHA512(shaBits)) {
        runTest<PAIRING,
                MerkleBundle_SHA512<uint64_t>, // count could be size_t
                zk::MerkleAuthPath_SHA512<FR>>(
            treeDepth,
            leafNumber);
    }

    GenericProgressBar progress1(cerr), progress2(cerr, 50);

    cerr << "generate key pair";
    const auto key = keypair<PAIRING>(progress2);
    cerr << endl;

    const auto in = input<PAIRING>();

    cerr << "generate proof";
    const auto p = proof(key, progress2);
    cerr << endl;

    cerr << "verify proof ";
    const bool proofOK = verify(key, in, p, progress1);
    cerr << endl;

    return proofOK;
}

int main(int argc, char *argv[])
{
    Getopt cmdLine(argc, argv, "pb", "di", "");
    if (!cmdLine || cmdLine.empty()) printUsage(argv[0]);

    const auto
        pairing = cmdLine.getString('p'),
        shaBits = cmdLine.getString('b');

    const auto
        treeDepth = cmdLine.getNumber('d'),
        leafNumber = cmdLine.getNumber('i');

    if (!validPairingName(pairing) ||
        !(nameSHA256(shaBits) || nameSHA512(shaBits)) ||
        -1 == treeDepth ||
        -1 == leafNumber)
        printUsage(argv[0]);

    bool result;

    if (pairingBN128(pairing)) {
        // Barreto-Naehrig 128 bits
        init_BN128();
        result = runTest<BN128_PAIRING>(shaBits, treeDepth, leafNumber);

    } else if (pairingEdwards(pairing)) {
        // Edwards 80 bits
        init_Edwards();
        result = runTest<EDWARDS_PAIRING>(shaBits, treeDepth, leafNumber);
    }

    cout << "proof verification " << (result ? "OK" : "FAIL") << endl;

    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>// Copyright (C) 2013 Jérôme Leclercq
// This file is part of the "Nazara Engine - Graphics module"
// For conditions of distribution and use, see copyright notice in Config.hpp

#include <Nazara/Graphics/Light.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/Graphics/AbstractRenderQueue.hpp>
#include <Nazara/Graphics/Camera.hpp>
#include <Nazara/Math/Basic.hpp>
#include <Nazara/Math/Sphere.hpp>
#include <Nazara/Renderer/Renderer.hpp>
#include <Nazara/Renderer/ShaderProgram.hpp>
#include <cstring>
#include <Nazara/Graphics/Debug.hpp>

///TODO: Utilisation des UBOs

NzLight::NzLight(nzLightType type) :
m_type(type),
m_color(NzColor::White),
m_boundingVolumeUpdated(false),
m_ambientFactor((type == nzLightType_Directional) ? 0.2f : 0.f),
m_attenuation(0.9f),
m_diffuseFactor(1.f),
m_innerAngle(15.f),
m_outerAngle(45.f),
m_radius(5.f)
{
}

NzLight::NzLight(const NzLight& light) :
NzSceneNode(light),
m_type(light.m_type),
m_boundingVolume(light.m_boundingVolume),
m_color(light.m_color),
m_boundingVolumeUpdated(light.m_boundingVolumeUpdated),
m_ambientFactor(light.m_ambientFactor),
m_attenuation(light.m_attenuation),
m_diffuseFactor(light.m_diffuseFactor),
m_innerAngle(light.m_innerAngle),
m_outerAngle(light.m_outerAngle),
m_radius(light.m_radius)
{
}

void NzLight::AddToRenderQueue(NzAbstractRenderQueue* renderQueue) const
{
	renderQueue->AddLight(this);
}

void NzLight::Enable(const NzShaderProgram* program, unsigned int lightUnit) const
{
	/*
	struct Light
	{
		int type;
		vec4 color;
		vec2 factors;

		vec4 parameters1;
		vec4 parameters2;
		vec2 parameters3;
	};

	Directional
	-P1: vec3 direction

	Point
	-P1: vec3 position + float attenuation
	-P2: float invRadius

	Spot
	-P1: vec3 position + float attenuation
	-P2: vec3 direction + float invRadius
	-P3: float cosInnerAngle + float cosOuterAngle
	*/

	///TODO: Optimiser
	int typeLocation = program->GetUniformLocation("Lights[0].type");
	int colorLocation = program->GetUniformLocation("Lights[0].color");
	int factorsLocation = program->GetUniformLocation("Lights[0].factors");
	int parameters1Location = program->GetUniformLocation("Lights[0].parameters1");
	int parameters2Location = program->GetUniformLocation("Lights[0].parameters2");
	int parameters3Location = program->GetUniformLocation("Lights[0].parameters3");

	if (lightUnit > 0)
	{
		int type2Location = program->GetUniformLocation("Lights[1].type");
		int offset = lightUnit * (type2Location - typeLocation); // type2Location - typeLocation donne la taille de la structure

		// On applique cet offset
		typeLocation += offset;
		colorLocation += offset;
		factorsLocation += offset;
		parameters1Location += offset;
		parameters2Location += offset;
		parameters3Location += offset;
	}

	program->SendInteger(typeLocation, m_type);
	program->SendColor(colorLocation, m_color);
	program->SendVector(factorsLocation, NzVector2f(m_ambientFactor, m_diffuseFactor));

	if (!m_derivedUpdated)
		UpdateDerived();

	switch (m_type)
	{
		case nzLightType_Directional:
			program->SendVector(parameters1Location, NzVector4f(m_derivedRotation * NzVector3f::Forward()));
			break;

		case nzLightType_Point:
			program->SendVector(parameters1Location, NzVector4f(m_derivedPosition, m_attenuation));
			program->SendVector(parameters2Location, NzVector4f(1.f/m_radius, 0.f, 0.f, 0.f));
			break;

		case nzLightType_Spot:
			program->SendVector(parameters1Location, NzVector4f(m_derivedPosition, m_attenuation));
			program->SendVector(parameters2Location, NzVector4f(m_derivedRotation * NzVector3f::Forward(), 1.f/m_radius));
			program->SendVector(parameters3Location, NzVector2f(std::cos(NzDegreeToRadian(m_innerAngle)), std::cos(NzDegreeToRadian(m_outerAngle))));
			break;
	}
}

float NzLight::GetAmbientFactor() const
{
	return m_ambientFactor;
}

float NzLight::GetAttenuation() const
{
	return m_attenuation;
}

const NzBoundingVolumef& NzLight::GetBoundingVolume() const
{
	if (!m_boundingVolumeUpdated)
		UpdateBoundingVolume();

	return m_boundingVolume;
}

NzColor NzLight::GetColor() const
{
	return m_color;
}

float NzLight::GetDiffuseFactor() const
{
	return m_diffuseFactor;
}

float NzLight::GetInnerAngle() const
{
	return m_innerAngle;
}

nzLightType NzLight::GetLightType() const
{
	return m_type;
}

float NzLight::GetOuterAngle() const
{
	return m_outerAngle;
}

float NzLight::GetRadius() const
{
	return m_radius;
}

nzSceneNodeType NzLight::GetSceneNodeType() const
{
	return nzSceneNodeType_Light;
}

bool NzLight::IsDrawable() const
{
	return true;
}

void NzLight::SetAmbientFactor(float factor)
{
	m_ambientFactor = factor;
}

void NzLight::SetAttenuation(float attenuation)
{
	m_attenuation = attenuation;
}

void NzLight::SetColor(const NzColor& color)
{
	m_color = color;
}

void NzLight::SetDiffuseFactor(float factor)
{
	m_diffuseFactor = factor;
}

void NzLight::SetInnerAngle(float innerAngle)
{
	m_innerAngle = innerAngle;
}

void NzLight::SetLightType(nzLightType type)
{
	m_type = type;
}

void NzLight::SetOuterAngle(float outerAngle)
{
	m_outerAngle = outerAngle;

	m_boundingVolume.MakeNull();
	m_boundingVolumeUpdated = false;
}

void NzLight::SetRadius(float radius)
{
	m_radius = radius;

	m_boundingVolume.MakeNull();
	m_boundingVolumeUpdated = false;
}

NzLight& NzLight::operator=(const NzLight& light)
{
	NzSceneNode::operator=(light);

	m_ambientFactor = light.m_ambientFactor;
	m_attenuation = light.m_attenuation;
	m_boundingVolume = light.m_boundingVolume;
	m_boundingVolumeUpdated = light.m_boundingVolumeUpdated;
	m_color = light.m_color;
	m_diffuseFactor = light.m_diffuseFactor;
	m_innerAngle = light.m_innerAngle;
	m_outerAngle = light.m_outerAngle;
	m_radius = light.m_radius;
	m_type = light.m_type;

	return *this;
}

void NzLight::Disable(const NzShaderProgram* program, unsigned int lightUnit)
{
	///TODO: Optimiser
	program->SendInteger(program->GetUniformLocation("Lights[" + NzString::Number(lightUnit) + "].type"), -1);
}

bool NzLight::FrustumCull(const NzFrustumf& frustum)
{
	switch (m_type)
	{
		case nzLightType_Directional:
			return true; // Toujours visible

		case nzLightType_Point:
			if (!m_derivedUpdated)
				UpdateDerived();

			// Un test sphérique est bien plus rapide et précis que celui de la bounding box
			return frustum.Contains(NzSpheref(m_derivedPosition, m_radius));

		case nzLightType_Spot:
			if (!m_boundingVolumeUpdated)
				UpdateBoundingVolume();

			return frustum.Contains(m_boundingVolume);
	}

	NazaraError("Invalid light type (0x" + NzString::Number(m_type, 16) + ')');
	return false;
}

void NzLight::Invalidate()
{
	NzSceneNode::Invalidate();

	m_boundingVolumeUpdated = false;
}

void NzLight::Register()
{
}

void NzLight::Unregister()
{
}

void NzLight::UpdateBoundingVolume() const
{
	if (m_boundingVolume.IsNull())
	{
		switch (m_type)
		{
			case nzLightType_Directional:
				m_boundingVolume.MakeInfinite();
				m_boundingVolumeUpdated = true;
				return; // Rien d'autre à faire

			case nzLightType_Point:
			{
				NzVector3f radius(m_radius);
				m_boundingVolume.Set(-radius, radius);
				break;
			}

			case nzLightType_Spot:
			{
				// On forme une boite sur l'origine
				NzBoxf box(NzVector3f::Zero());

				// On calcule le reste des points
				float height = m_radius;
				NzVector3f base(NzVector3f::Forward()*height);

				// Il nous faut maintenant le rayon du cercle projeté à cette distance
				// Tangente = Opposé/Adjaçent <=> Opposé = Adjaçent*Tangente
				float radius = height*std::tan(NzDegreeToRadian(m_outerAngle));
				NzVector3f lExtend = NzVector3f::Left()*radius;
				NzVector3f uExtend = NzVector3f::Up()*radius;

				// Et on ajoute ensuite les quatres extrémités de la pyramide
				box.ExtendTo(base + lExtend + uExtend);
				box.ExtendTo(base + lExtend - uExtend);
				box.ExtendTo(base - lExtend + uExtend);
				box.ExtendTo(base - lExtend - uExtend);

				m_boundingVolume.Set(box);
				break;
			}
		}
	}

	switch (m_type)
	{
		case nzLightType_Directional:
			break;

		case nzLightType_Point:
			if (!m_derivedUpdated)
				UpdateDerived();

			m_boundingVolume.Update(NzMatrix4f::Translate(m_derivedPosition)); // Notre BoundingBox ne changera que selon la position
			break;

		case nzLightType_Spot:
			if (!m_transformMatrixUpdated)
				UpdateTransformMatrix();

			m_boundingVolume.Update(m_transformMatrix);
			break;
	}

	m_boundingVolumeUpdated = true;
}
<commit_msg>Fixed SpotLight bounding volume computation<commit_after>// Copyright (C) 2013 Jérôme Leclercq
// This file is part of the "Nazara Engine - Graphics module"
// For conditions of distribution and use, see copyright notice in Config.hpp

#include <Nazara/Graphics/Light.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/Graphics/AbstractRenderQueue.hpp>
#include <Nazara/Graphics/Camera.hpp>
#include <Nazara/Math/Basic.hpp>
#include <Nazara/Math/Sphere.hpp>
#include <Nazara/Renderer/Renderer.hpp>
#include <Nazara/Renderer/ShaderProgram.hpp>
#include <cstring>
#include <Nazara/Graphics/Debug.hpp>

///TODO: Utilisation des UBOs

NzLight::NzLight(nzLightType type) :
m_type(type),
m_color(NzColor::White),
m_boundingVolumeUpdated(false),
m_ambientFactor((type == nzLightType_Directional) ? 0.2f : 0.f),
m_attenuation(0.9f),
m_diffuseFactor(1.f),
m_innerAngle(15.f),
m_outerAngle(45.f),
m_radius(5.f)
{
}

NzLight::NzLight(const NzLight& light) :
NzSceneNode(light),
m_type(light.m_type),
m_boundingVolume(light.m_boundingVolume),
m_color(light.m_color),
m_boundingVolumeUpdated(light.m_boundingVolumeUpdated),
m_ambientFactor(light.m_ambientFactor),
m_attenuation(light.m_attenuation),
m_diffuseFactor(light.m_diffuseFactor),
m_innerAngle(light.m_innerAngle),
m_outerAngle(light.m_outerAngle),
m_radius(light.m_radius)
{
}

void NzLight::AddToRenderQueue(NzAbstractRenderQueue* renderQueue) const
{
	renderQueue->AddLight(this);
}

void NzLight::Enable(const NzShaderProgram* program, unsigned int lightUnit) const
{
	/*
	struct Light
	{
		int type;
		vec4 color;
		vec2 factors;

		vec4 parameters1;
		vec4 parameters2;
		vec2 parameters3;
	};

	Directional
	-P1: vec3 direction

	Point
	-P1: vec3 position + float attenuation
	-P2: float invRadius

	Spot
	-P1: vec3 position + float attenuation
	-P2: vec3 direction + float invRadius
	-P3: float cosInnerAngle + float cosOuterAngle
	*/

	///TODO: Optimiser
	int typeLocation = program->GetUniformLocation("Lights[0].type");
	int colorLocation = program->GetUniformLocation("Lights[0].color");
	int factorsLocation = program->GetUniformLocation("Lights[0].factors");
	int parameters1Location = program->GetUniformLocation("Lights[0].parameters1");
	int parameters2Location = program->GetUniformLocation("Lights[0].parameters2");
	int parameters3Location = program->GetUniformLocation("Lights[0].parameters3");

	if (lightUnit > 0)
	{
		int type2Location = program->GetUniformLocation("Lights[1].type");
		int offset = lightUnit * (type2Location - typeLocation); // type2Location - typeLocation donne la taille de la structure

		// On applique cet offset
		typeLocation += offset;
		colorLocation += offset;
		factorsLocation += offset;
		parameters1Location += offset;
		parameters2Location += offset;
		parameters3Location += offset;
	}

	program->SendInteger(typeLocation, m_type);
	program->SendColor(colorLocation, m_color);
	program->SendVector(factorsLocation, NzVector2f(m_ambientFactor, m_diffuseFactor));

	if (!m_derivedUpdated)
		UpdateDerived();

	switch (m_type)
	{
		case nzLightType_Directional:
			program->SendVector(parameters1Location, NzVector4f(m_derivedRotation * NzVector3f::Forward()));
			break;

		case nzLightType_Point:
			program->SendVector(parameters1Location, NzVector4f(m_derivedPosition, m_attenuation));
			program->SendVector(parameters2Location, NzVector4f(1.f/m_radius, 0.f, 0.f, 0.f));
			break;

		case nzLightType_Spot:
			program->SendVector(parameters1Location, NzVector4f(m_derivedPosition, m_attenuation));
			program->SendVector(parameters2Location, NzVector4f(m_derivedRotation * NzVector3f::Forward(), 1.f/m_radius));
			program->SendVector(parameters3Location, NzVector2f(std::cos(NzDegreeToRadian(m_innerAngle)), std::cos(NzDegreeToRadian(m_outerAngle))));
			break;
	}
}

float NzLight::GetAmbientFactor() const
{
	return m_ambientFactor;
}

float NzLight::GetAttenuation() const
{
	return m_attenuation;
}

const NzBoundingVolumef& NzLight::GetBoundingVolume() const
{
	if (!m_boundingVolumeUpdated)
		UpdateBoundingVolume();

	return m_boundingVolume;
}

NzColor NzLight::GetColor() const
{
	return m_color;
}

float NzLight::GetDiffuseFactor() const
{
	return m_diffuseFactor;
}

float NzLight::GetInnerAngle() const
{
	return m_innerAngle;
}

nzLightType NzLight::GetLightType() const
{
	return m_type;
}

float NzLight::GetOuterAngle() const
{
	return m_outerAngle;
}

float NzLight::GetRadius() const
{
	return m_radius;
}

nzSceneNodeType NzLight::GetSceneNodeType() const
{
	return nzSceneNodeType_Light;
}

bool NzLight::IsDrawable() const
{
	return true;
}

void NzLight::SetAmbientFactor(float factor)
{
	m_ambientFactor = factor;
}

void NzLight::SetAttenuation(float attenuation)
{
	m_attenuation = attenuation;
}

void NzLight::SetColor(const NzColor& color)
{
	m_color = color;
}

void NzLight::SetDiffuseFactor(float factor)
{
	m_diffuseFactor = factor;
}

void NzLight::SetInnerAngle(float innerAngle)
{
	m_innerAngle = innerAngle;
}

void NzLight::SetLightType(nzLightType type)
{
	m_type = type;
}

void NzLight::SetOuterAngle(float outerAngle)
{
	m_outerAngle = outerAngle;

	m_boundingVolume.MakeNull();
	m_boundingVolumeUpdated = false;
}

void NzLight::SetRadius(float radius)
{
	m_radius = radius;

	m_boundingVolume.MakeNull();
	m_boundingVolumeUpdated = false;
}

NzLight& NzLight::operator=(const NzLight& light)
{
	NzSceneNode::operator=(light);

	m_ambientFactor = light.m_ambientFactor;
	m_attenuation = light.m_attenuation;
	m_boundingVolume = light.m_boundingVolume;
	m_boundingVolumeUpdated = light.m_boundingVolumeUpdated;
	m_color = light.m_color;
	m_diffuseFactor = light.m_diffuseFactor;
	m_innerAngle = light.m_innerAngle;
	m_outerAngle = light.m_outerAngle;
	m_radius = light.m_radius;
	m_type = light.m_type;

	return *this;
}

void NzLight::Disable(const NzShaderProgram* program, unsigned int lightUnit)
{
	///TODO: Optimiser
	program->SendInteger(program->GetUniformLocation("Lights[" + NzString::Number(lightUnit) + "].type"), -1);
}

bool NzLight::FrustumCull(const NzFrustumf& frustum)
{
	switch (m_type)
	{
		case nzLightType_Directional:
			return true; // Toujours visible

		case nzLightType_Point:
			if (!m_derivedUpdated)
				UpdateDerived();

			// Un test sphérique est bien plus rapide et précis que celui de la bounding box
			return frustum.Contains(NzSpheref(m_derivedPosition, m_radius));

		case nzLightType_Spot:
			if (!m_boundingVolumeUpdated)
				UpdateBoundingVolume();

			return frustum.Contains(m_boundingVolume);
	}

	NazaraError("Invalid light type (0x" + NzString::Number(m_type, 16) + ')');
	return false;
}

void NzLight::Invalidate()
{
	NzSceneNode::Invalidate();

	m_boundingVolumeUpdated = false;
}

void NzLight::Register()
{
}

void NzLight::Unregister()
{
}

void NzLight::UpdateBoundingVolume() const
{
	if (m_boundingVolume.IsNull())
	{
		switch (m_type)
		{
			case nzLightType_Directional:
				m_boundingVolume.MakeInfinite();
				m_boundingVolumeUpdated = true;
				return; // Rien d'autre à faire

			case nzLightType_Point:
			{
				NzVector3f radius(m_radius);
				m_boundingVolume.Set(-radius, radius);
				break;
			}

			case nzLightType_Spot:
			{
				// On forme une boite sur l'origine
				NzBoxf box(NzVector3f::Zero());

				// On calcule le reste des points
				NzVector3f base(NzVector3f::Forward()*m_radius);

				// Il nous faut maintenant le rayon du cercle projeté à cette distance
				// Tangente = Opposé/Adjaçent <=> Opposé = Adjaçent*Tangente
				float radius = m_radius*std::tan(NzDegreeToRadian(m_outerAngle));
				NzVector3f lExtend = NzVector3f::Left()*radius;
				NzVector3f uExtend = NzVector3f::Up()*radius;

				// Et on ajoute ensuite les quatres extrémités de la pyramide
				box.ExtendTo(base + lExtend + uExtend);
				box.ExtendTo(base + lExtend - uExtend);
				box.ExtendTo(base - lExtend + uExtend);
				box.ExtendTo(base - lExtend - uExtend);

				m_boundingVolume.Set(box);
				break;
			}
		}
	}

	switch (m_type)
	{
		case nzLightType_Directional:
			break;

		case nzLightType_Point:
			if (!m_derivedUpdated)
				UpdateDerived();

			m_boundingVolume.Update(NzMatrix4f::Translate(m_derivedPosition)); // Notre BoundingBox ne changera que selon la position
			break;

		case nzLightType_Spot:
			if (!m_derivedUpdated)
				UpdateDerived();

			m_boundingVolume.Update(NzMatrix4f::Transform(m_derivedPosition, m_derivedRotation));
			break;
	}

	m_boundingVolumeUpdated = true;
}
<|endoftext|>


<commit_before>// Copyright (C) 2014 Jérôme Leclercq
// This file is part of the "Nazara Engine - Graphics module"
// For conditions of distribution and use, see copyright notice in Config.hpp

#include <Nazara/Graphics/Scene.hpp>
#include <Nazara/Core/Clock.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/Core/ErrorFlags.hpp>
#include <Nazara/Graphics/Camera.hpp>
#include <Nazara/Graphics/ColorBackground.hpp>
#include <Nazara/Graphics/RenderTechniques.hpp>
#include <Nazara/Graphics/SceneRoot.hpp>
#include <Nazara/Renderer/Config.hpp>
#include <functional>
#include <memory>
#include <set>
#include <vector>
#include <Nazara/Graphics/Debug.hpp>

struct NzSceneImpl
{
	NzSceneImpl(NzScene* scene) :
	root(scene)
	{
	}

	std::unique_ptr<NzAbstractBackground> background;
	std::unique_ptr<NzAbstractRenderTechnique> renderTechnique;
	std::vector<NzUpdatable*> updateList;
	std::vector<NzUpdatable*> visibleUpdateList;
	NzClock updateClock;
	NzColor ambientColor = NzColor(25,25,25);
	NzSceneRoot root;
	NzAbstractViewer* viewer;
	bool update;
	float frameTime;
	float updateTime;
	int renderTechniqueRanking;
	unsigned int updatePerSecond = 60;
};

NzScene::NzScene()
{
	m_impl = new NzSceneImpl(this);
	m_impl->background.reset(new NzColorBackground);
	m_impl->renderTechnique.reset(NzRenderTechniques::GetByRanking(-1, &m_impl->renderTechniqueRanking));
}

NzScene::~NzScene()
{
	delete m_impl;
}

void NzScene::AddToVisibilityList(NzUpdatable* object)
{
	m_impl->visibleUpdateList.push_back(object);
}

void NzScene::Cull()
{
	#if NAZARA_GRAPHICS_SAFE
	if (!m_impl->viewer)
	{
		NazaraError("No viewer");
		return;
	}
	#endif

	NzAbstractRenderQueue* renderQueue = m_impl->renderTechnique->GetRenderQueue();
	renderQueue->Clear(false);

	m_impl->visibleUpdateList.clear();

	// Frustum culling
	RecursiveFrustumCull(m_impl->renderTechnique->GetRenderQueue(), m_impl->viewer->GetFrustum(), &m_impl->root);

	///TODO: Occlusion culling

	///TODO: Light culling
}

void NzScene::Draw()
{
	#if NAZARA_GRAPHICS_SAFE
	if (!m_impl->viewer)
	{
		NazaraError("No viewer");
		return;
	}
	#endif

	m_impl->viewer->ApplyView();

	try
	{
		NzErrorFlags errFlags(nzErrorFlag_ThrowException);
		m_impl->renderTechnique->Clear(this);
		m_impl->renderTechnique->Draw(this);
	}
	catch (const std::exception& e)
	{
		NzString oldName = m_impl->renderTechnique->GetName();
		m_impl->renderTechnique.reset(NzRenderTechniques::GetByRanking(m_impl->renderTechniqueRanking-1, &m_impl->renderTechniqueRanking));
		NazaraError("Render technique \"" + oldName + "\" failed, switched to \"" + m_impl->renderTechnique->GetName() + '"');
		return;
	}
}

NzColor NzScene::GetAmbientColor() const
{
	return m_impl->ambientColor;
}

NzAbstractBackground* NzScene::GetBackground() const
{
	return m_impl->background.get();
}

NzAbstractRenderTechnique* NzScene::GetRenderTechnique() const
{
	return m_impl->renderTechnique.get();
}

NzSceneNode& NzScene::GetRoot() const
{
	return m_impl->root;
}

NzAbstractViewer* NzScene::GetViewer() const
{
	return m_impl->viewer;
}

float NzScene::GetUpdateTime() const
{
	return m_impl->updateTime;
}

unsigned int NzScene::GetUpdatePerSecond() const
{
	return m_impl->updatePerSecond;
}

void NzScene::RegisterForUpdate(NzUpdatable* object)
{
	#if NAZARA_GRAPHICS_SAFE
	if (!object)
	{
		NazaraError("Invalid object");
		return;
	}
	#endif

	m_impl->updateList.push_back(object);
}

void NzScene::SetAmbientColor(const NzColor& color)
{
	m_impl->ambientColor = color;
}

void NzScene::SetBackground(NzAbstractBackground* background)
{
	m_impl->background.reset(background);
}

void NzScene::SetRenderTechnique(NzAbstractRenderTechnique* renderTechnique)
{
	m_impl->renderTechnique.reset(renderTechnique);
}

void NzScene::SetViewer(NzAbstractViewer* viewer)
{
	m_impl->viewer = viewer;
}

void NzScene::SetViewer(NzAbstractViewer& viewer)
{
	SetViewer(&viewer);
}

void NzScene::SetUpdatePerSecond(unsigned int updatePerSecond)
{
	m_impl->updatePerSecond = updatePerSecond;
}

void NzScene::UnregisterForUpdate(NzUpdatable* object)
{
	#if NAZARA_GRAPHICS_SAFE
	if (!object)
	{
		NazaraError("Invalid object");
		return;
	}
	#endif

	auto it = std::find(m_impl->updateList.begin(), m_impl->updateList.end(), object);
	if (it != m_impl->updateList.end())
		m_impl->updateList.erase(it);
}

void NzScene::Update()
{
	m_impl->update = (m_impl->updatePerSecond == 0 || m_impl->updateClock.GetMilliseconds() > 1000/m_impl->updatePerSecond);
	if (m_impl->update)
	{
		m_impl->updateTime = m_impl->updateClock.GetSeconds();
		m_impl->updateClock.Restart();

		for (NzUpdatable* updatable : m_impl->updateList)
			///TODO: Multihreading
			updatable->Update();
	}
}

void NzScene::UpdateVisible()
{
	if (m_impl->update)
	{
		for (NzUpdatable* node : m_impl->visibleUpdateList)
			node->Update();
	}
}

NzScene::operator const NzSceneNode&() const
{
	return m_impl->root;
}

void NzScene::RecursiveFrustumCull(NzAbstractRenderQueue* renderQueue, const NzFrustumf& frustum, NzNode* node)
{
	for (NzNode* child : node->GetChilds())
	{
		if (child->GetNodeType() == nzNodeType_Scene)
		{
			NzSceneNode* sceneNode = static_cast<NzSceneNode*>(child);

			///TODO: Empêcher le rendu des enfants si le parent est cullé selon un flag
			sceneNode->UpdateVisibility(frustum);
			if (sceneNode->IsVisible())
				sceneNode->AddToRenderQueue(renderQueue);
		}

		if (child->HasChilds())
			RecursiveFrustumCull(renderQueue, frustum, child);
	}
}
<commit_msg>Optimized Scenes configuration<commit_after>// Copyright (C) 2014 Jérôme Leclercq
// This file is part of the "Nazara Engine - Graphics module"
// For conditions of distribution and use, see copyright notice in Config.hpp

#include <Nazara/Graphics/Scene.hpp>
#include <Nazara/Core/Clock.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/Core/ErrorFlags.hpp>
#include <Nazara/Graphics/Camera.hpp>
#include <Nazara/Graphics/ColorBackground.hpp>
#include <Nazara/Graphics/RenderTechniques.hpp>
#include <Nazara/Graphics/SceneRoot.hpp>
#include <Nazara/Renderer/Config.hpp>
#include <functional>
#include <memory>
#include <set>
#include <vector>
#include <Nazara/Graphics/Debug.hpp>

struct NzSceneImpl
{
	NzSceneImpl(NzScene* scene) :
	root(scene)
	{
	}

	std::unique_ptr<NzAbstractBackground> background;
	std::unique_ptr<NzAbstractRenderTechnique> renderTechnique;
	std::vector<NzUpdatable*> updateList;
	std::vector<NzUpdatable*> visibleUpdateList;
	NzClock updateClock;
	NzColor ambientColor = NzColor(25,25,25);
	NzSceneRoot root;
	NzAbstractViewer* viewer = nullptr;
	bool update;
	float frameTime;
	float updateTime;
	int renderTechniqueRanking;
	unsigned int updatePerSecond = 60;
};

NzScene::NzScene()
{
	m_impl = new NzSceneImpl(this);
}

NzScene::~NzScene()
{
	delete m_impl;
}

void NzScene::AddToVisibilityList(NzUpdatable* object)
{
	m_impl->visibleUpdateList.push_back(object);
}

void NzScene::Cull()
{
	#if NAZARA_GRAPHICS_SAFE
	if (!m_impl->viewer)
	{
		NazaraError("No viewer");
		return;
	}
	#endif

	if (!m_impl->renderTechnique)
		m_impl->renderTechnique.reset(NzRenderTechniques::GetByRanking(-1, &m_impl->renderTechniqueRanking));

	NzAbstractRenderQueue* renderQueue = m_impl->renderTechnique->GetRenderQueue();
	renderQueue->Clear(false);

	m_impl->visibleUpdateList.clear();

	// Frustum culling
	RecursiveFrustumCull(renderQueue, m_impl->viewer->GetFrustum(), &m_impl->root);

	///TODO: Occlusion culling

	///TODO: Light culling
}

void NzScene::Draw()
{
	#if NAZARA_GRAPHICS_SAFE
	if (!m_impl->viewer)
	{
		NazaraError("No viewer");
		return;
	}
	#endif

	m_impl->viewer->ApplyView();

	if (!m_impl->background)
		m_impl->background.reset(new NzColorBackground);

	try
	{
		NzErrorFlags errFlags(nzErrorFlag_ThrowException);
		m_impl->renderTechnique->Clear(this);
		m_impl->renderTechnique->Draw(this);
	}
	catch (const std::exception& e)
	{
		NzString oldName = m_impl->renderTechnique->GetName();
		m_impl->renderTechnique.reset(NzRenderTechniques::GetByRanking(m_impl->renderTechniqueRanking-1, &m_impl->renderTechniqueRanking));
		NazaraError("Render technique \"" + oldName + "\" failed, switched to \"" + m_impl->renderTechnique->GetName() + '"');
		return;
	}
}

NzColor NzScene::GetAmbientColor() const
{
	return m_impl->ambientColor;
}

NzAbstractBackground* NzScene::GetBackground() const
{
	return m_impl->background.get();
}

NzAbstractRenderTechnique* NzScene::GetRenderTechnique() const
{
	return m_impl->renderTechnique.get();
}

NzSceneNode& NzScene::GetRoot() const
{
	return m_impl->root;
}

NzAbstractViewer* NzScene::GetViewer() const
{
	return m_impl->viewer;
}

float NzScene::GetUpdateTime() const
{
	return m_impl->updateTime;
}

unsigned int NzScene::GetUpdatePerSecond() const
{
	return m_impl->updatePerSecond;
}

void NzScene::RegisterForUpdate(NzUpdatable* object)
{
	#if NAZARA_GRAPHICS_SAFE
	if (!object)
	{
		NazaraError("Invalid object");
		return;
	}
	#endif

	m_impl->updateList.push_back(object);
}

void NzScene::SetAmbientColor(const NzColor& color)
{
	m_impl->ambientColor = color;
}

void NzScene::SetBackground(NzAbstractBackground* background)
{
	m_impl->background.reset(background);
}

void NzScene::SetRenderTechnique(NzAbstractRenderTechnique* renderTechnique)
{
	m_impl->renderTechnique.reset(renderTechnique);
}

void NzScene::SetViewer(NzAbstractViewer* viewer)
{
	m_impl->viewer = viewer;
}

void NzScene::SetViewer(NzAbstractViewer& viewer)
{
	SetViewer(&viewer);
}

void NzScene::SetUpdatePerSecond(unsigned int updatePerSecond)
{
	m_impl->updatePerSecond = updatePerSecond;
}

void NzScene::UnregisterForUpdate(NzUpdatable* object)
{
	#if NAZARA_GRAPHICS_SAFE
	if (!object)
	{
		NazaraError("Invalid object");
		return;
	}
	#endif

	auto it = std::find(m_impl->updateList.begin(), m_impl->updateList.end(), object);
	if (it != m_impl->updateList.end())
		m_impl->updateList.erase(it);
}

void NzScene::Update()
{
	m_impl->update = (m_impl->updatePerSecond == 0 || m_impl->updateClock.GetMilliseconds() > 1000/m_impl->updatePerSecond);
	if (m_impl->update)
	{
		m_impl->updateTime = m_impl->updateClock.GetSeconds();
		m_impl->updateClock.Restart();

		for (NzUpdatable* updatable : m_impl->updateList)
			///TODO: Multihreading
			updatable->Update();
	}
}

void NzScene::UpdateVisible()
{
	if (m_impl->update)
	{
		for (NzUpdatable* node : m_impl->visibleUpdateList)
			node->Update();
	}
}

NzScene::operator const NzSceneNode&() const
{
	return m_impl->root;
}

void NzScene::RecursiveFrustumCull(NzAbstractRenderQueue* renderQueue, const NzFrustumf& frustum, NzNode* node)
{
	for (NzNode* child : node->GetChilds())
	{
		if (child->GetNodeType() == nzNodeType_Scene)
		{
			NzSceneNode* sceneNode = static_cast<NzSceneNode*>(child);

			///TODO: Empêcher le rendu des enfants si le parent est cullé selon un flag
			sceneNode->UpdateVisibility(frustum);
			if (sceneNode->IsVisible())
				sceneNode->AddToRenderQueue(renderQueue);
		}

		if (child->HasChilds())
			RecursiveFrustumCull(renderQueue, frustum, child);
	}
}
<|endoftext|>


<commit_before>//#define DEBUG
#include <iostream>

#include <cstring>
#include <iomanip>
#include "tests.h"
#include "core/function_obj.h"
#include "core/type.h"
#include "core/type_helper.h"
/* TODO
	Add function inpterpeting and execution DONE
	Add varible interpeting and memmory system. DONE
	Add syntax checking and error reporting PARTERLY
	Add polyargument functions
    Verify that exception system does not intoduce memmory leaks

*/

bool menu(memory::memory& mem,math_func::function_interface& func)
{
	std::cout << "PRINT VARIABLES [1]\nEMPTY VARIABLE TABLE[2]\nPRINT FUNCS[3]\nPRINT BUILD INFO[4]\nPRINT HELP[5]\nRUN TESTS [6]\nEXIT [7]\nMenu> ";
	std::string input;
	std::getline(std::cin, input);
	if (input == "1")
	{
		std::vector<std::string> vars = mem.allVars();
		for (unsigned int i = 0; i < vars.size(); i++)
		{
			std::cout <<"Variable "<<i+1 << ": " << vars[i] << " = " << mem.get(vars[i])->toString() << "\n";
		}
		if (vars.size() == 0)
		{
			std::cout << "TABLE EMPTY\n";
		}

		return false;
	}
	else if (input == "2")
	{
		mem.empty();
		return false;
	}
	else if (input == "3")
	{
		func.display();

	}
	else if (input == "4")
	{
		util::buildInfo();
		return false;
	}
	else if (input == "5")
	{
		util::help();
		return false;
	}
	else if (input == "6")
	{
		std::string exr = "x=(sqrt(sqrt(5*5)^2)*100)/5*(sin(PI)^2+cos(PI)^2)";
		test::profileInterpreter(exr);
//		test::profileInterpreterVM(exr);
		return false;
	}
	else if (input == "7")
	{

		return true;
	}
	else
	{
		std::cout << "Unkown input, try again\n";
		return menu(mem,func);
	}
	return false;
}
int main(int argc, char* argv[])
{

	{

#ifndef DEBUG
		err_redirect err; //remove cerr stream
#endif
		std::cout << std::setprecision(20);

		interpreter inter;
		std::string expression = "";

	memory::memory mem; //Create memory unit
	operators::operators_interface oper;
	math_func::function_interface functions; //Create function unit

	//init and load operators
	oper.load(operators::std_operators);
	inter.setOperator(&oper);

	//Init and load memory unit
	mem.set("PI", 3.14159f, true, true);  //Add constat variable PI with value 3.14
	inter.setMemory(&mem); //Assign memory unit to interpreter

	//init and load func unit
	functions.load(math_func::std_math_trig_func); // Load std_math_trig_funct into function unit
	functions.load(math_func::std_math_func);
	functions.load(math_func::std_math_num_func);
	functions.load(math_func::mathlibra_data_constructors);
	inter.setFunction(&functions);
	auto my_manager = plugin::get_platform_specific_manager();
	if(my_manager != nullptr)
	{
	try
	{	my_manager->loadPlugins(&functions);

	}
	catch (exception& e)
	{

		std::cout << "[\n Exception: " << e.what() << "\n";
		std::cout << " Description: " << e.desc() << "\n]\n";
	}
	}
#if defined(CORAX_VM_EXEC)
	CoraxVM::corax_program prgm;
	CoraxVM::Corax_program_builder_module prgm_builder(&inter);
	CoraxVM::corax_runtime runtime;
#endif

	bool exit = false;
     std::cout << "Calculator backend test\nLukas Rahmn 2016\n\nEnter an expression or write menu to open the menu\n\n";
	do
	{

		std::cout << "> ";
		std::getline(std::cin, expression);
		if (expression == "menu")
		{
			exit = menu(mem,functions);
		}
		else
		{

			try
			{
				inter.set(expression.c_str(), expression.size());
				inter.interpret();
#if  defined(SYNTAX_TREE_EXEC)

					mem.set("ans",inter.exec());

#elif defined(CORAX_VM_EXEC)
					prgm_builder.create_program(&prgm);
					mem.set("ans", runtime.run(&prgm));
#else
#error "WARNING, no execution enviroment selected"
#endif
					std::cout << expression << " = " << mem.get("ans")->toString() << std::endl;

			}

			catch (exception& e)
			{

				std::cout << "[\n Exception: " << e.what() << "\n";
				std::cout << " Description: " << e.desc() << "\n]\n";
			}
			/*catch (...)
			{
			std::cout << "Catched unknown exception\n";
			}*/
		}
	} while (!exit);
		}
	debug::check_tree_mem_leak();
	return 0;

}
<commit_msg>Updated tester to support sytanx 'menu #number' instead of just menu<commit_after>//#define DEBUG
#include <iostream>

#include <cstring>
#include <iomanip>
#include "tests.h"
#include "core/function_obj.h"
#include "core/type.h"
#include "core/type_helper.h"
/* TODO
	Add function inpterpeting and execution DONE
	Add varible interpeting and memmory system. DONE
	Add syntax checking and error reporting PARTERLY
	Add polyargument functions
    Verify that exception system does not intoduce memmory leaks

*/
std::vector<std::string> split(std::string str,char delim)
{
    std::vector<std::string> strs;
    strs.push_back(std::string());
    for(auto s = str.begin(); s < str.end(); s++)
    {
        if(*s==delim)
        {
            strs.push_back(std::string());
        }
        else
        {
            strs.back().push_back(*s);
        }
    }
    if(strs.back().size() == 0)
    {
        strs.pop_back();
    }
    return strs;
}

bool menu(memory::memory& mem,math_func::function_interface& func,std::string input)
{
        if(input.size() == 0)
        {
	    std::cout << "PRINT VARIABLES [1]\nEMPTY VARIABLE TABLE[2]\nPRINT FUNCS[3]\nPRINT BUILD INFO[4]\nPRINT HELP[5]\nRUN TESTS [6]\nEXIT [7]\nMenu> ";
	    std::getline(std::cin, input);
        }
	if (input == "1")
	{
		std::vector<std::string> vars = mem.allVars();
		for (unsigned int i = 0; i < vars.size(); i++)
		{
			std::cout <<"Variable "<<i+1 << ": " << vars[i] << " = " << mem.get(vars[i])->toString() << "\n";
		}
		if (vars.size() == 0)
		{
			std::cout << "TABLE EMPTY\n";
		}

		return false;
	}
	else if (input == "2")
	{
		mem.empty();
		return false;
	}
	else if (input == "3")
	{
		func.display();

	}
	else if (input == "4")
	{
		util::buildInfo();
		return false;
	}
	else if (input == "5")
	{
		util::help();
		return false;
	}
	else if (input == "6")
	{
		std::string exr = "x=(sqrt(sqrt(5*5)^2)*100)/5*(sin(PI)^2+cos(PI)^2)";
		test::profileInterpreter(exr);
//		test::profileInterpreterVM(exr);
		return false;
	}
	else if (input == "7")
	{

		return true;
	}
	else
	{
		std::cout << "Unkown input, try again\n";
		return menu(mem,func,"");
	}
	return false;
}
int main(int argc, char* argv[])
{

	{

#ifndef DEBUG
		err_redirect err; //remove cerr stream
#endif
		std::cout << std::setprecision(20);

		interpreter inter;
		std::string expression = "";

	memory::memory mem; //Create memory unit
	operators::operators_interface oper;
	math_func::function_interface functions; //Create function unit

	//init and load operators
	oper.load(operators::std_operators);
	inter.setOperator(&oper);

	//Init and load memory unit
	mem.set("PI", 3.14159f, true, true);  //Add constat variable PI with value 3.14
	inter.setMemory(&mem); //Assign memory unit to interpreter

	//init and load func unit
	functions.load(math_func::std_math_trig_func); // Load std_math_trig_funct into function unit
	functions.load(math_func::std_math_func);
	functions.load(math_func::std_math_num_func);
	functions.load(math_func::mathlibra_data_constructors);
	inter.setFunction(&functions);
	auto my_manager = plugin::get_platform_specific_manager();
	if(my_manager != nullptr)
	{
	try
	{	my_manager->loadPlugins(&functions);

	}
	catch (exception& e)
	{

		std::cout << "[\n Exception: " << e.what() << "\n";
		std::cout << " Description: " << e.desc() << "\n]\n";
	}
	}
#if defined(CORAX_VM_EXEC)
	CoraxVM::corax_program prgm;
	CoraxVM::Corax_program_builder_module prgm_builder(&inter);
	CoraxVM::corax_runtime runtime;
#endif

	bool exit = false;
     std::cout << "Calculator backend test\nLukas Rahmn 2016\n\nEnter an expression or write menu to open the menu\n\n";
	do
	{

		std::cout << "> ";
		std::getline(std::cin, expression);
                std::vector<std::string> arg=split(expression,' ');
                if(arg.size() == 1 && arg[0] == "menu")
		{
			exit = menu(mem,functions,"");
		}
                else if(arg.size() == 2 && arg[0] == "menu")
                {
                    exit = menu(mem,functions,arg[1]);
                }
		else
		{

			try
			{
				inter.set(expression.c_str(), expression.size());
				inter.interpret();
#if  defined(SYNTAX_TREE_EXEC)

					mem.set("ans",inter.exec());

#elif defined(CORAX_VM_EXEC)
					prgm_builder.create_program(&prgm);
					mem.set("ans", runtime.run(&prgm));
#else
#error "WARNING, no execution enviroment selected"
#endif
					std::cout << expression << " = " << mem.get("ans")->toString() << std::endl;

			}

			catch (exception& e)
			{

				std::cout << "[\n Exception: " << e.what() << "\n";
				std::cout << " Description: " << e.desc() << "\n]\n";
			}
			/*catch (...)
			{
			std::cout << "Catched unknown exception\n";
			}*/
		}
	} while (!exit);
		}
	debug::check_tree_mem_leak();
	return 0;

}
<|endoftext|>


<commit_before>#include "OpenGLRenderer.hpp"
#include <gl/glew.h>

OpenGLRenderer::OpenGLRenderer(Window window) {
    // Setup glfw window.
    window.setWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    window.setWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    window.setWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    window.setWindowHint(GLFW_RESIZABLE, GL_FALSE);
    std::string windowTitle = "OpenGL";
    window.createWindow(windowTitle);
}

OpenGLRenderer::~OpenGLRenderer() {

}
<commit_msg>Setup GLEW.<commit_after>#include <GL/glew.h>
#include "OpenGLRenderer.hpp"

OpenGLRenderer::OpenGLRenderer(Window window) {
    // Setup glfw window.
    window.setWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    window.setWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    window.setWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    window.setWindowHint(GLFW_RESIZABLE, GL_FALSE);
    std::string windowTitle = "OpenGL";
    window.createWindow(windowTitle);

    // Setup GLEW
    glewExperimental = true;
    if(glewInit() != GLEW_OK){

    }
}

OpenGLRenderer::~OpenGLRenderer() {

}
<|endoftext|>


<commit_before>#include "CbcConfig.h"

// CBC_VERSION_MAJOR defined for Cbc > 2.5
#ifndef CBC_VERSION_MAJOR
#include "OsiCbcSolverInterface_2_5.cpp"
#elif CBC_VERSION_MAJOR == 2 && CBC_VERSION_MINOR <= 8
#include "OsiCbcSolverInterface_2_8.cpp"
#elif CBC_VERSION_MAJOR == 2 && CBC_VERSION_MINOR == 9
#include "OsiCbcSolverInterface_2_9.cpp"
#else
#error "Cyclus cannot yet handle your version of CoinCBC. Please open an issue with your CoinCBC version."
#endif

#ifdef __APPLE__
// for some reason these symbol doesn't exist in the mac binaries
void _OsiSolverInterface::addCol(CoinPackedVectorBase const& vec, double collb,
                                double colub, double obj, std::string name) {
  // just ignore the name
  addCol(vec, collb, colub, obj);
}
#endif<commit_msg>annoyed<commit_after>#include "CbcConfig.h"

// CBC_VERSION_MAJOR defined for Cbc > 2.5
#ifndef CBC_VERSION_MAJOR
#include "OsiCbcSolverInterface_2_5.cpp"
#elif CBC_VERSION_MAJOR == 2 && CBC_VERSION_MINOR <= 8
#include "OsiCbcSolverInterface_2_8.cpp"
#elif CBC_VERSION_MAJOR == 2 && CBC_VERSION_MINOR == 9
#include "OsiCbcSolverInterface_2_9.cpp"
#else
#error "Cyclus cannot yet handle your version of CoinCBC. Please open an issue with your CoinCBC version."
#endif

#ifdef __APPLE__
// for some reason these symbol doesn't exist in the mac binaries
void OsiCbcSolverInterface::addCol(CoinPackedVectorBase const& vec, double collb,
                                   double colub, double obj, std::string name) {
  // just ignore the name
  addCol(vec, collb, colub, obj);
}
#endif<|endoftext|>