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

#include <folly/Foreach.h>

#include <folly/Benchmark.h>
#include <gtest/gtest.h>
#include <map>
#include <string>
#include <vector>
#include <list>

using namespace folly;
using namespace folly::detail;

TEST(Foreach, ForEachRvalue) {
  const char* const hello = "hello";
  int n = 0;
  FOR_EACH(it, std::string(hello)) {
    ++n;
  }
  EXPECT_EQ(strlen(hello), n);
  FOR_EACH_R(it, std::string(hello)) {
    --n;
    EXPECT_EQ(hello[n], *it);
  }
  EXPECT_EQ(0, n);
}

TEST(Foreach, ForEachKV) {
  std::map<std::string, int> testMap;
  testMap["abc"] = 1;
  testMap["def"] = 2;
  std::string keys = "";
  int values = 0;
  int numEntries = 0;
  FOR_EACH_KV (key, value, testMap) {
    keys += key;
    values += value;
    ++numEntries;
  }
  EXPECT_EQ("abcdef", keys);
  EXPECT_EQ(3, values);
  EXPECT_EQ(2, numEntries);
}

TEST(Foreach, ForEachKVBreak) {
  std::map<std::string, int> testMap;
  testMap["abc"] = 1;
  testMap["def"] = 2;
  std::string keys = "";
  int values = 0;
  int numEntries = 0;
  FOR_EACH_KV (key, value, testMap) {
    keys += key;
    values += value;
    ++numEntries;
    break;
  }
  EXPECT_EQ("abc", keys);
  EXPECT_EQ(1, values);
  EXPECT_EQ(1, numEntries);
}

TEST(Foreach, ForEachKvWithMultiMap) {
  std::multimap<std::string, int> testMap;
  testMap.insert(std::make_pair("abc", 1));
  testMap.insert(std::make_pair("abc", 2));
  testMap.insert(std::make_pair("def", 3));
  std::string keys = "";
  int values = 0;
  int numEntries = 0;
  FOR_EACH_KV (key, value, testMap) {
    keys += key;
    values += value;
    ++numEntries;
  }
  EXPECT_EQ("abcabcdef", keys);
  EXPECT_EQ(6, values);
  EXPECT_EQ(3, numEntries);
}

TEST(Foreach, ForEachEnumerate) {
  std::vector<int> vv;
  int sumAA = 0;
  int sumIter = 0;
  int numIterations = 0;
  FOR_EACH_ENUMERATE(aa, iter, vv) {
    sumAA += aa;
    sumIter += *iter;
    ++numIterations;
  }
  EXPECT_EQ(sumAA, 0);
  EXPECT_EQ(sumIter, 0);
  EXPECT_EQ(numIterations, 0);

  vv.push_back(1);
  vv.push_back(3);
  vv.push_back(5);
  FOR_EACH_ENUMERATE(aa, iter, vv) {
    sumAA += aa;
    sumIter += *iter;
    ++numIterations;
  }
  EXPECT_EQ(sumAA, 3);   // 0 + 1 + 2
  EXPECT_EQ(sumIter, 9); // 1 + 3 + 5
  EXPECT_EQ(numIterations, 3);
}

TEST(Foreach, ForEachEnumerateBreak) {
  std::vector<int> vv;
  int sumAA = 0;
  int sumIter = 0;
  int numIterations = 0;
  vv.push_back(1);
  vv.push_back(2);
  vv.push_back(4);
  vv.push_back(8);
  FOR_EACH_ENUMERATE(aa, iter, vv) {
    sumAA += aa;
    sumIter += *iter;
    ++numIterations;
    if (aa == 1) break;
  }
  EXPECT_EQ(sumAA, 1);   // 0 + 1
  EXPECT_EQ(sumIter, 3); // 1 + 2
  EXPECT_EQ(numIterations, 2);
}

TEST(Foreach, ForEachRangeR) {
  int sum = 0;

  FOR_EACH_RANGE_R (i, 0, 0) {
    sum += i;
  }
  EXPECT_EQ(0, sum);

  FOR_EACH_RANGE_R (i, 0, -1) {
    sum += i;
  }
  EXPECT_EQ(0, sum);

  FOR_EACH_RANGE_R (i, 0, 5) {
    sum += i;
  }
  EXPECT_EQ(10, sum);

  std::list<int> lst = { 0, 1, 2, 3, 4 };
  sum = 0;
  FOR_EACH_RANGE_R (i, lst.begin(), lst.end()) {
    sum += *i;
  }
  EXPECT_EQ(10, sum);
}

// Benchmarks:
// 1. Benchmark iterating through the man with FOR_EACH, and also assign
//    iter->first and iter->second to local vars inside the FOR_EACH loop.
// 2. Benchmark iterating through the man with FOR_EACH, but use iter->first and
//    iter->second as is, without assigning to local variables.
// 3. Use FOR_EACH_KV loop to iterate through the map.

std::map<int, std::string> bmMap;  // For use in benchmarks below.

void setupBenchmark(size_t iters) {
  bmMap.clear();
  for (size_t i = 0; i < iters; ++i) {
    bmMap[i] = "teststring";
  }
}

BENCHMARK(ForEachKVNoMacroAssign, iters) {
  int sumKeys = 0;
  std::string sumValues;

  BENCHMARK_SUSPEND {
    setupBenchmark(iters);
    int sumKeys = 0;
    std::string sumValues = "";
  }

  FOR_EACH (iter, bmMap) {
    const int k = iter->first;
    const std::string v = iter->second;
    sumKeys += k;
    sumValues += v;
  }
}

BENCHMARK(ForEachKVNoMacroNoAssign, iters) {
  int sumKeys = 0;
  std::string sumValues;

  BENCHMARK_SUSPEND {
    setupBenchmark(iters);
  }

  FOR_EACH (iter, bmMap) {
    sumKeys += iter->first;
    sumValues += iter->second;
  }
}

BENCHMARK(ManualLoopNoAssign, iters) {
  BENCHMARK_SUSPEND {
    setupBenchmark(iters);
  }
  int sumKeys = 0;
  std::string sumValues;

  for (auto iter = bmMap.begin(); iter != bmMap.end(); ++iter) {
    sumKeys += iter->first;
    sumValues += iter->second;
  }
}

BENCHMARK(ForEachKVMacro, iters) {
  BENCHMARK_SUSPEND {
    setupBenchmark(iters);
  }
  int sumKeys = 0;
  std::string sumValues;

  FOR_EACH_KV (k, v, bmMap) {
    sumKeys += k;
    sumValues += v;
  }
}

BENCHMARK(ForEachManual, iters) {
  int sum = 1;
  for (size_t i = 1; i < iters; ++i) {
    sum *= i;
  }
  doNotOptimizeAway(sum);
}

BENCHMARK(ForEachRange, iters) {
  int sum = 1;
  FOR_EACH_RANGE (i, 1, iters) {
    sum *= i;
  }
  doNotOptimizeAway(sum);
}

BENCHMARK(ForEachDescendingManual, iters) {
  int sum = 1;
  for (size_t i = iters; i-- > 1; ) {
    sum *= i;
  }
  doNotOptimizeAway(sum);
}

BENCHMARK(ForEachRangeR, iters) {
  int sum = 1;
  FOR_EACH_RANGE_R (i, 1, iters) {
    sum *= i;
  }
  doNotOptimizeAway(sum);
}

int main(int argc, char** argv) {
  testing::InitGoogleTest(&argc, argv);
  auto r = RUN_ALL_TESTS();
  if (r) {
    return r;
  }
  runBenchmarks();
  return 0;
}
<commit_msg>folly/test/ForeachTest.cpp: avoid -Wsign-compare error<commit_after>/*
 * Copyright 2014 Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <folly/Foreach.h>

#include <folly/Benchmark.h>
#include <gtest/gtest.h>
#include <map>
#include <string>
#include <vector>
#include <list>

using namespace folly;
using namespace folly::detail;

TEST(Foreach, ForEachRvalue) {
  const char* const hello = "hello";
  int n = 0;
  FOR_EACH(it, std::string(hello)) {
    ++n;
  }
  EXPECT_EQ(strlen(hello), n);
  FOR_EACH_R(it, std::string(hello)) {
    --n;
    EXPECT_EQ(hello[n], *it);
  }
  EXPECT_EQ(0, n);
}

TEST(Foreach, ForEachKV) {
  std::map<std::string, int> testMap;
  testMap["abc"] = 1;
  testMap["def"] = 2;
  std::string keys = "";
  int values = 0;
  int numEntries = 0;
  FOR_EACH_KV (key, value, testMap) {
    keys += key;
    values += value;
    ++numEntries;
  }
  EXPECT_EQ("abcdef", keys);
  EXPECT_EQ(3, values);
  EXPECT_EQ(2, numEntries);
}

TEST(Foreach, ForEachKVBreak) {
  std::map<std::string, int> testMap;
  testMap["abc"] = 1;
  testMap["def"] = 2;
  std::string keys = "";
  int values = 0;
  int numEntries = 0;
  FOR_EACH_KV (key, value, testMap) {
    keys += key;
    values += value;
    ++numEntries;
    break;
  }
  EXPECT_EQ("abc", keys);
  EXPECT_EQ(1, values);
  EXPECT_EQ(1, numEntries);
}

TEST(Foreach, ForEachKvWithMultiMap) {
  std::multimap<std::string, int> testMap;
  testMap.insert(std::make_pair("abc", 1));
  testMap.insert(std::make_pair("abc", 2));
  testMap.insert(std::make_pair("def", 3));
  std::string keys = "";
  int values = 0;
  int numEntries = 0;
  FOR_EACH_KV (key, value, testMap) {
    keys += key;
    values += value;
    ++numEntries;
  }
  EXPECT_EQ("abcabcdef", keys);
  EXPECT_EQ(6, values);
  EXPECT_EQ(3, numEntries);
}

TEST(Foreach, ForEachEnumerate) {
  std::vector<int> vv;
  int sumAA = 0;
  int sumIter = 0;
  int numIterations = 0;
  FOR_EACH_ENUMERATE(aa, iter, vv) {
    sumAA += aa;
    sumIter += *iter;
    ++numIterations;
  }
  EXPECT_EQ(sumAA, 0);
  EXPECT_EQ(sumIter, 0);
  EXPECT_EQ(numIterations, 0);

  vv.push_back(1);
  vv.push_back(3);
  vv.push_back(5);
  FOR_EACH_ENUMERATE(aa, iter, vv) {
    sumAA += aa;
    sumIter += *iter;
    ++numIterations;
  }
  EXPECT_EQ(sumAA, 3);   // 0 + 1 + 2
  EXPECT_EQ(sumIter, 9); // 1 + 3 + 5
  EXPECT_EQ(numIterations, 3);
}

TEST(Foreach, ForEachEnumerateBreak) {
  std::vector<int> vv;
  int sumAA = 0;
  int sumIter = 0;
  int numIterations = 0;
  vv.push_back(1);
  vv.push_back(2);
  vv.push_back(4);
  vv.push_back(8);
  FOR_EACH_ENUMERATE(aa, iter, vv) {
    sumAA += aa;
    sumIter += *iter;
    ++numIterations;
    if (aa == 1) break;
  }
  EXPECT_EQ(sumAA, 1);   // 0 + 1
  EXPECT_EQ(sumIter, 3); // 1 + 2
  EXPECT_EQ(numIterations, 2);
}

TEST(Foreach, ForEachRangeR) {
  int sum = 0;

  FOR_EACH_RANGE_R (i, 0, 0) {
    sum += i;
  }
  EXPECT_EQ(0, sum);

  FOR_EACH_RANGE_R (i, 0, -1) {
    sum += i;
  }
  EXPECT_EQ(0, sum);

  FOR_EACH_RANGE_R (i, 0, 5) {
    sum += i;
  }
  EXPECT_EQ(10, sum);

  std::list<int> lst = { 0, 1, 2, 3, 4 };
  sum = 0;
  FOR_EACH_RANGE_R (i, lst.begin(), lst.end()) {
    sum += *i;
  }
  EXPECT_EQ(10, sum);
}

// Benchmarks:
// 1. Benchmark iterating through the man with FOR_EACH, and also assign
//    iter->first and iter->second to local vars inside the FOR_EACH loop.
// 2. Benchmark iterating through the man with FOR_EACH, but use iter->first and
//    iter->second as is, without assigning to local variables.
// 3. Use FOR_EACH_KV loop to iterate through the map.

std::map<int, std::string> bmMap;  // For use in benchmarks below.

void setupBenchmark(size_t iters) {
  bmMap.clear();
  for (size_t i = 0; i < iters; ++i) {
    bmMap[i] = "teststring";
  }
}

BENCHMARK(ForEachKVNoMacroAssign, iters) {
  int sumKeys = 0;
  std::string sumValues;

  BENCHMARK_SUSPEND {
    setupBenchmark(iters);
    int sumKeys = 0;
    std::string sumValues = "";
  }

  FOR_EACH (iter, bmMap) {
    const int k = iter->first;
    const std::string v = iter->second;
    sumKeys += k;
    sumValues += v;
  }
}

BENCHMARK(ForEachKVNoMacroNoAssign, iters) {
  int sumKeys = 0;
  std::string sumValues;

  BENCHMARK_SUSPEND {
    setupBenchmark(iters);
  }

  FOR_EACH (iter, bmMap) {
    sumKeys += iter->first;
    sumValues += iter->second;
  }
}

BENCHMARK(ManualLoopNoAssign, iters) {
  BENCHMARK_SUSPEND {
    setupBenchmark(iters);
  }
  int sumKeys = 0;
  std::string sumValues;

  for (auto iter = bmMap.begin(); iter != bmMap.end(); ++iter) {
    sumKeys += iter->first;
    sumValues += iter->second;
  }
}

BENCHMARK(ForEachKVMacro, iters) {
  BENCHMARK_SUSPEND {
    setupBenchmark(iters);
  }
  int sumKeys = 0;
  std::string sumValues;

  FOR_EACH_KV (k, v, bmMap) {
    sumKeys += k;
    sumValues += v;
  }
}

BENCHMARK(ForEachManual, iters) {
  int sum = 1;
  for (size_t i = 1; i < iters; ++i) {
    sum *= i;
  }
  doNotOptimizeAway(sum);
}

BENCHMARK(ForEachRange, iters) {
  int sum = 1;
  FOR_EACH_RANGE (i, 1, iters) {
    sum *= i;
  }
  doNotOptimizeAway(sum);
}

BENCHMARK(ForEachDescendingManual, iters) {
  int sum = 1;
  for (size_t i = iters; i-- > 1; ) {
    sum *= i;
  }
  doNotOptimizeAway(sum);
}

BENCHMARK(ForEachRangeR, iters) {
  int sum = 1;
  FOR_EACH_RANGE_R (i, 1U, iters) {
    sum *= i;
  }
  doNotOptimizeAway(sum);
}

int main(int argc, char** argv) {
  testing::InitGoogleTest(&argc, argv);
  auto r = RUN_ALL_TESTS();
  if (r) {
    return r;
  }
  runBenchmarks();
  return 0;
}
<|endoftext|>


<commit_before>#include "Camera.h"
#include "Render.h"
#include "base/basedef.h"
#include "math/mathdef.h"
#include <GL/glew.h>

using fei::Camera;

Camera::Camera()
: width(1.0f),
  height(1.0f),
  cameraType(Type::ORTHOGRAPHIC),
  cameraScale(1.0f),
  needDataUpdate(true)
{
}

void Camera::update()
{
	updateCameraData();
	glMatrixMode(GL_PROJECTION);
	if (cameraType == Type::ORTHOGRAPHIC) {
		glLoadIdentity();
		glOrtho(left, right, bottom, top, near, far);
	} else if (cameraType == Type::PERSPECTIVE) {
		//TODO: write it when you want to test it
	}
	glTranslatef(-pos.x, -pos.y, 0);
	glMatrixMode(GL_MODELVIEW);
}

void Camera::setCameraType(Type type)
{
	if (cameraType != type) {
		cameraType = type;
		needDataUpdate = true;
	}
}

Camera::Type Camera::getCameraType()
{
	return cameraType;
}

void Camera::setCameraScale(float scale)
{
	if (cameraScale != scale && std::abs(scale) > fei::eps) {
		cameraScale = scale;
		needDataUpdate = true;
	}
}

float Camera::getCameraScale()
{
	return cameraScale;
}

void Camera::cameraScaleZoom(float zoom)
{
	setCameraScale(cameraScale * zoom);
}

void Camera::cameraScaleCenterZoom(const Vec2& center, float zoom)
{
	move((center - pos) * (1.0f - 1.0f / zoom));
	setCameraScale(cameraScale * zoom);
}

void Camera::setCameraSize(const fei::Vec2& v)
{
	width = v.x;
	height = v.y;
	needDataUpdate = true;
}

const fei::Vec2 Camera::screenToWorld(const fei::Vec2& scrPos)
{
	updateCameraData();
	auto camSize = fei::Vec2(right - left, top - bottom);
	auto vpSize = fei::Render::getInstance()->getViewport().getSize();
	auto ans = camSize.zoomed(scrPos.zoomed(vpSize.reciprocal()) - fei::Vec2(0.5f)) + pos;
	return ans;
}

const fei::Vec2 Camera::worldToScreen(const fei::Vec2& wrdPos)
{
	updateCameraData();
	auto camSize = fei::Vec2(right - left, top - bottom);
	auto vpSize = fei::Render::getInstance()->getViewport().getSize();
	auto ans = ((wrdPos - pos).zoomed(camSize.reciprocal()) + fei::Vec2(0.5f)).zoomed(vpSize);
	return ans;
}

void Camera::updateCameraData()
{
	if (needDataUpdate) {
		if (cameraType == Type::ORTHOGRAPHIC) {
			float ratio = 2.0f * cameraScale;
			left = -width / ratio;
			right = width / ratio;
			bottom = -height / ratio;
			top = height / ratio;
			near = -99999.0f;
			far = 99999.0f;
		} else if (cameraType == Type::PERSPECTIVE) {
			//TODO: write it when you want to test it
		}
		needDataUpdate = false;
	}
}
<commit_msg>fix namespace<commit_after>#include "Camera.h"
#include "Render.h"
#include "base/basedef.h"
#include "math/mathdef.h"
#include <GL/glew.h>

using fei::Camera;

Camera::Camera()
: width(1.0f),
  height(1.0f),
  cameraType(Type::ORTHOGRAPHIC),
  cameraScale(1.0f),
  needDataUpdate(true)
{
}

void Camera::update()
{
	updateCameraData();
	glMatrixMode(GL_PROJECTION);
	if (cameraType == Type::ORTHOGRAPHIC) {
		glLoadIdentity();
		glOrtho(left, right, bottom, top, near, far);
	} else if (cameraType == Type::PERSPECTIVE) {
		//TODO: write it when you want to test it
	}
	glTranslatef(-pos.x, -pos.y, 0);
	glMatrixMode(GL_MODELVIEW);
}

void Camera::setCameraType(Type type)
{
	if (cameraType != type) {
		cameraType = type;
		needDataUpdate = true;
	}
}

Camera::Type Camera::getCameraType()
{
	return cameraType;
}

void Camera::setCameraScale(float scale)
{
	if (cameraScale != scale && std::abs(scale) > fei::eps) {
		cameraScale = scale;
		needDataUpdate = true;
	}
}

float Camera::getCameraScale()
{
	return cameraScale;
}

void Camera::cameraScaleZoom(float zoom)
{
	setCameraScale(cameraScale * zoom);
}

void Camera::cameraScaleCenterZoom(const fei::Vec2& center, float zoom)
{
	move((center - pos) * (1.0f - 1.0f / zoom));
	setCameraScale(cameraScale * zoom);
}

void Camera::setCameraSize(const fei::Vec2& v)
{
	width = v.x;
	height = v.y;
	needDataUpdate = true;
}

const fei::Vec2 Camera::screenToWorld(const fei::Vec2& scrPos)
{
	updateCameraData();
	auto camSize = fei::Vec2(right - left, top - bottom);
	auto vpSize = fei::Render::getInstance()->getViewport().getSize();
	auto ans = camSize.zoomed(scrPos.zoomed(vpSize.reciprocal()) - fei::Vec2(0.5f)) + pos;
	return ans;
}

const fei::Vec2 Camera::worldToScreen(const fei::Vec2& wrdPos)
{
	updateCameraData();
	auto camSize = fei::Vec2(right - left, top - bottom);
	auto vpSize = fei::Render::getInstance()->getViewport().getSize();
	auto ans = ((wrdPos - pos).zoomed(camSize.reciprocal()) + fei::Vec2(0.5f)).zoomed(vpSize);
	return ans;
}

void Camera::updateCameraData()
{
	if (needDataUpdate) {
		if (cameraType == Type::ORTHOGRAPHIC) {
			float ratio = 2.0f * cameraScale;
			left = -width / ratio;
			right = width / ratio;
			bottom = -height / ratio;
			top = height / ratio;
			near = -99999.0f;
			far = 99999.0f;
		} else if (cameraType == Type::PERSPECTIVE) {
			//TODO: write it when you want to test it
		}
		needDataUpdate = false;
	}
}
<|endoftext|>


<commit_before>//=================================================================================================
//                    Copyright (C) 2017 Olivier Mallet - All Rights Reserved
//=================================================================================================

#ifndef CHROMOSOME_HPP
#define CHROMOSOME_HPP

namespace galgo {

//=================================================================================================

template <typename T, int...N>
class Chromosome
{
   static_assert(std::is_same<float,T>::value || std::is_same<double,T>::value, "variable type can only be float or double, please amend.");

public:
   // constructor
   Chromosome(const GeneticAlgorithm<T,N...>& ga);
   // copy constructor
   Chromosome(const Chromosome<T,N...>& rhs);
   // end of recursion for creating new chromosome
   template <int I = 0>
   typename std::enable_if<I == sizeof...(N), void>::type create();
   // recursion for creating new chromosome
   template <int I = 0>
   typename std::enable_if<I < sizeof...(N), void>::type create();
   // end of recursion for initializing new chromosome
   template <int I = 0>
   typename std::enable_if<I == sizeof...(N), void>::type initialize();
   // recursion for initializing new chromosome
   template <int I = 0>
   typename std::enable_if<I < sizeof...(N), void>::type initialize();
   // end of recursion for converting gene to real value
   template <int I = 0>
   typename std::enable_if<I == sizeof...(N), void>::type convert();
   // recursion for converting gene to real value
   template <int I = 0>
   typename std::enable_if<I < sizeof...(N), void>::type convert();
   // evaluate chromosome
   void evaluate();
   // reset chromosome
   void reset();
   // end of recursion for setting or replace kth gene by a new one
   template <int I = 0>
   inline typename std::enable_if<I == sizeof...(N), void>::type setGene(int k);
   // recursion for setting or replace kth gene by a new one
   template <int I = 0>
   inline typename std::enable_if<I < sizeof...(N), void>::type setGene(int k);
   // end of recursion for initializing or replacing kth gene by a know value
   template <int I = 0>
   typename std::enable_if<I == sizeof...(N), void>::type initGene(int k, T x);
   // recursion for initializing or replacing kth gene by a know value
   template <int I = 0>
   typename std::enable_if<I < sizeof...(N), void>::type initGene(int k, T x);
   // add bit to chromosome
   void addBit(char bit);
   // initialize or replace an existing chromosome bit
   void setBit(char bit, int pos);
   // flip an existing chromosome bit
   void flipBit(int pos);
   // get chromosome bit
   char getBit(int pos) const;
   // initialize or replace a portion of bits with a portion of another chromosome
   void setPortion(const Chromosome<T,N...>& x, int start, int end);
   // initialize or replace a portion of bits with a portion of another chromosome
   void setPortion(const Chromosome<T,N...>& x, int start);
   // get parameter value(s) from chromosome
   const std::vector<T>& getParam() const;
   // get objective function result
   const std::vector<T>& getResult() const;
   // get the total sum of all objective function(s) result
   T getTotal() const;
   // get constraint value(s)
   const std::vector<T> getConstraint() const;
   // return chromosome size in number of bits
   int size() const;
   // return number of chromosome bits to mutate
   T mutrate() const;
   // return number of genes in chromosome
   int nbgene() const;
   // return numero of generation this chromosome belongs to
   int nogen() const;
   // return lower bound(s)
   const std::vector<T>& lowerBound() const;
   // return upper bound(s)
   const std::vector<T>& upperBound() const;

private:
   std::vector<T> param;                          // estimated parameters parameters
   std::vector<T> result;                         // chromosome objective function(s) result
   std::string chr;                               // string of bits representing chromosome
   const GeneticAlgorithm<T,N...>* ptr = nullptr; // pointer to genetic algorithm
public:
   T fitness;                                     // chromosome fitness, objective function(s) result that can be modified (adapted to constraint(s), set to positive values, etc...)
private:
   T total;                                       // total sum of objective function(s) result
   int chrsize;                                   // chromosome size (in number of bits)
   int numgen;                                    // numero of generation
   int idx;                                       // index for chromosome breakdown
};

/*-------------------------------------------------------------------------------------------------*/

// constructor
template <typename T, int...N>
Chromosome<T,N...>::Chromosome(const GeneticAlgorithm<T,N...>& ga)
{
   param.resize(sizeof...(N));
   ptr = &ga;
   chrsize = ga.nbbit;
   numgen = ga.nogen;
}

/*-------------------------------------------------------------------------------------------------*/

// copy constructor
template <typename T, int...N>
Chromosome<T,N...>::Chromosome(const Chromosome<T,N...>& rhs)
{
   param = rhs.param;
   result = rhs.result;
   chr = rhs.chr;
   ptr = rhs.ptr;
   // re-initializing fitness to its original value
   fitness = rhs.total;
   total = rhs.total;
   chrsize = rhs.chrsize;
   numgen = rhs.numgen;
}

/*-------------------------------------------------------------------------------------------------*/

// end of recursion for creating new chromosome
template <typename T, int...N> template <int I>
inline typename std::enable_if<I == sizeof...(N), void>::type
Chromosome<T,N...>::create() {}

// recursion for creating new chromosome
template <typename T, int...N> template <int I>
inline typename std::enable_if<I < sizeof...(N), void>::type
Chromosome<T,N...>::create()
{
   std::string str = std::get<I>(ptr->tp).encode();
   chr.append(str);
   create<I + 1>();
}

/*-------------------------------------------------------------------------------------------------*/

// intialize chromosome from a known value
template <typename T, int...N> template <int I>
inline typename std::enable_if<I == sizeof...(N), void>::type
Chromosome<T,N...>::initialize() {}

// recursion for initializing chromosome from a known value
template <typename T, int...N> template <int I>
inline typename std::enable_if<I < sizeof...(N), void>::type
Chromosome<T,N...>::initialize()
{
   std::string str = std::get<I>(ptr->tp).encode(ptr->initialSet[I]);
   chr.append(str);
   initialize<I + 1>();
}

/*-------------------------------------------------------------------------------------------------*/

// end of recursion for converting gene to real value
template <typename T, int...N> template <int I>
inline typename std::enable_if<I == sizeof...(N), void>::type
Chromosome<T,N...>::convert() {}

// recursion for converting gene to real value
template <typename T, int...N> template <int I>
inline typename std::enable_if<I < sizeof...(N), void>::type
Chromosome<T,N...>::convert()
{
   const auto& par = std::get<I>(ptr->tp);
   param[I] = par.decode(chr.substr(idx, par.size()));
   idx += par.size();
   convert<I + 1>();
}

/*-------------------------------------------------------------------------------------------------*/

// evaluate chromosome fitness
template <typename T, int...N>
inline void Chromosome<T,N...>::evaluate() {
   // setting index for chromosome breakdown to 0
   idx = 0;
   // converting chromosome to value(s)
   convert();
   // computing objective result(s)
   result = ptr->Objective(param);
   // computing sum of all results (in case there is not only one objective functions)
   total = std::accumulate(result.begin(), result.end(), 0.0);
   // initializing fitness to this total
   fitness = total;
}

/*-------------------------------------------------------------------------------------------------*/

// reset chromosome
template <typename T, int...N>
inline void Chromosome<T,N...>::reset()
{
   chr.clear();
   result = 0.0;
   total = 0.0;
   fitness = 0.0;
}

/*-------------------------------------------------------------------------------------------------*/

// end of recursion for setting or replace kth gene by a new one
template <typename T, int...N> template <int I>
inline typename std::enable_if<I == sizeof...(N), void>::type
Chromosome<T,N...>::setGene(int k) {}

// recursion for setting or replace kth gene by a new one
template <typename T, int...N> template <int I>
inline typename std::enable_if<I < sizeof...(N), void>::type
Chromosome<T,N...>::setGene(int k)
{
   #ifndef NDEBUG
   if (k < 0 || k >= ptr->nbparam) {
      throw std::invalid_argument("Error: in galgo::Chromosome<T>::setGene(int), argument cannot be outside interval [0,nbparam-1], please amend.");
   }
   #endif

   // setting index for chromosome breakdown to 0
   if (I == 0) idx = 0;

   // getting Ith parameter in tuple
   const auto& par = std::get<I>(ptr->tp);

   // if gene found
   if (I == k) {
      // generating a new gene
      std::string s = par.encode();
      // adding or replacing gene in chromosome
      chr.replace(idx, par.size(), s, 0, par.size());
      // ending recursion
      setGene<sizeof...(N)>(k);
   } else {
      idx += par.size();
      setGene<I + 1>(k);
   }
}

/*-------------------------------------------------------------------------------------------------*/

// end of recursion for initializing or replacing kth gene by a know value
template <typename T, int...N> template <int I>
inline typename std::enable_if<I == sizeof...(N), void>::type
Chromosome<T,N...>::initGene(int k, T x) {}

// recursion for initializing or replacing kth gene by a know value
template <typename T, int...N> template <int I>
inline typename std::enable_if<I < sizeof...(N), void>::type
Chromosome<T,N...>::initGene(int k, T x)
{
   #ifndef NDEBUG
   if (k < 0 || k >= ptr->nbparam) {
      throw std::invalid_argument("Error: in galgo::Chromosome<T>::initGene(int), first argument cannot be outside interval [0,nbparam-1], please amend.");
   }
   #endif

   // setting index for chromosome breakdown to 0
   if (I == 0) idx = 0;

   // getting Ith parameter in tuple
   const auto& par = std::get<I>(ptr->tp);

   // if gene found
   if (I == k) {
      // generating a new gene
      std::string s = par.encode(x);
      // adding or replacing gene in chromosome
      chr.replace(idx, par.size(), s, 0, par.size());
      // ending recursion
      initGene<sizeof...(N)>(k, x);
   } else {
      idx += par.size();
      initGene<I + 1>(k, x);
   }
}

/*-------------------------------------------------------------------------------------------------*/

// add chromosome bit to chromosome (when constructing a new one)
template <typename T, int...N>
inline void Chromosome<T,N...>::addBit(char bit)
{
   chr.push_back(bit);

   #ifndef NDEBUG
   if (chr.size() > chrsize) {
      throw std::invalid_argument("Error: in galgo::Chromosome<T>::setBit(char), exceeding chromosome size.");
   }
   #endif
}

/*-------------------------------------------------------------------------------------------------*/

// initialize or replace an existing chromosome bit
template <typename T, int...N>
inline void Chromosome<T,N...>::setBit(char bit, int pos)
{
   #ifndef NDEBUG
   if (pos >= chrsize) {
      throw std::invalid_argument("Error: in galgo::Chromosome<T>::replaceBit(char, int), second argument cannot be equal or greater than chromosome size.");
   }
   #endif

   std::stringstream ss;
   std::string str;
   ss << bit;
   ss >> str;
   chr.replace(pos, 1, str);
   std::cout << chr << "\n";
}

/*-------------------------------------------------------------------------------------------------*/

// flip an existing chromosome bit
template <typename T, int...N>
inline void Chromosome<T,N...>::flipBit(int pos)
{
   #ifndef NDEBUG
   if (pos >= chrsize) {
      throw std::invalid_argument("Error: in galgo::Chromosome<T>::flipBit(int), argument cannot be equal or greater than chromosome size.");
   }
   #endif

   if (chr[pos] == '0') {
      chr.replace(pos, 1, "1");
   } else {
      chr.replace(pos, 1, "0");
   }
}

/*-------------------------------------------------------------------------------------------------*/

// get a chromosome bit
template <typename T, int...N>
inline char Chromosome<T,N...>::getBit(int pos) const
{
   #ifndef NDEBUG
   if (pos >= chrsize) {
      throw std::invalid_argument("Error: in galgo::Chromosome<T>::getBit(int), argument cannot be equal or greater than chromosome size.");
   }
   #endif

   return chr[pos];
}

/*-------------------------------------------------------------------------------------------------*/

// initialize or replace a portion of bits with a portion of another chromosome (from position start to position end included)
template <typename T, int...N>
inline void Chromosome<T,N...>::setPortion(const Chromosome<T,N...>& x, int start, int end)
{
   #ifndef NDEBUG
   if (start > chrsize) {
      throw std::invalid_argument("Error: in galgo::Chromosome<T>::setPortion(const Chromosome<T>&, int, int), second argument cannot be greater than chromosome size.");
   }
   #endif

   chr.replace(start, end - start + 1, x.chr, start, end - start + 1);
}

/*-------------------------------------------------------------------------------------------------*/

// initialize or replace a portion of bits with a portion of another chromosome (from position start to the end of he chromosome)
template <typename T, int...N>
inline void Chromosome<T,N...>::setPortion(const Chromosome<T,N...>& x, int start)
{
   #ifndef NDEBUG
   if (start > chrsize) {
      throw std::invalid_argument("Error: in galgo::Chromosome<T>::setPortion(const Chromosome<T>&, int), second argument cannot be greater than chromosome size.");
   }
   #endif

   chr.replace(start, chrsize, x.chr, start, x.chrsize);
}

/*-------------------------------------------------------------------------------------------------*/

// get parameter value(s) from chromosome
template <typename T, int...N>
inline const std::vector<T>& Chromosome<T,N...>::getParam() const
{
   return param;
}

/*-------------------------------------------------------------------------------------------------*/

// get objective function result
template <typename T, int...N>
inline const std::vector<T>& Chromosome<T,N...>::getResult() const
{
   return result;
}

/*-------------------------------------------------------------------------------------------------*/

// get the total sum of all objective function(s) result
template <typename T, int...N>
inline T Chromosome<T,N...>::getTotal() const
{
   return total;
}

/*-------------------------------------------------------------------------------------------------*/

// get constraint value(s) for this chromosome
template <typename T, int...N>
inline const std::vector<T> Chromosome<T,N...>::getConstraint() const
{
   return ptr->Constraint(param);
}

/*-------------------------------------------------------------------------------------------------*/

// return chromosome size in number of bits
template <typename T, int...N>
inline int Chromosome<T,N...>::size() const
{
   return chrsize;
}

/*-------------------------------------------------------------------------------------------------*/

// return mutation rate
template <typename T, int...N>
inline T Chromosome<T,N...>::mutrate() const
{
   return ptr->mutrate;
}

/*-------------------------------------------------------------------------------------------------*/

// return number of genes in chromosome
template <typename T, int...N>
inline int Chromosome<T,N...>::nbgene() const
{
   return ptr->nbparam;
}

/*-------------------------------------------------------------------------------------------------*/

// return numero of generation this chromosome belongs to
template <typename T, int...N>
inline int Chromosome<T,N...>::nogen() const
{
   return numgen;
}

/*-------------------------------------------------------------------------------------------------*/

// return lower bound(s)
template <typename T, int...N>
inline const std::vector<T>& Chromosome<T,N...>::lowerBound() const
{
   return ptr->lowerBound;
}

/*-------------------------------------------------------------------------------------------------*/

// return upper bound(s)
template <typename T, int...N>
inline const std::vector<T>& Chromosome<T,N...>::upperBound() const
{
   return ptr->upperBound;
}

//=================================================================================================

}

#endif
<commit_msg>Delete Chromosome.hpp<commit_after><|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.                  *
 **************************************************************************/

#include <TGeoBBox.h>

#include "AliEMCALGeometry.h"
#include "AliEveEMCALSModuleData.h"

class TClonesArray;
class TGeoNode;
class TGeoMatrix;
class TVector2;
class AliEveEventManager;

ClassImp(AliEveEMCALSModuleData)

Float_t AliEveEMCALSModuleData::fgSModuleBigBox0 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleBigBox1 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleBigBox2 = 0.;

Float_t AliEveEMCALSModuleData::fgSModuleSmallBox0 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleSmallBox1 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleSmallBox2 = 0.;

Float_t AliEveEMCALSModuleData::fgSModuleDCalBox0 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleDCalBox1 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleDCalBox2 = 0.;

Float_t AliEveEMCALSModuleData::fgSModuleSmallDBox0 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleSmallDBox1 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleSmallDBox2 = 0.;

//Float_t AliEveEMCALSModuleData::fgSModuleCenter0 = 0.;
//Float_t AliEveEMCALSModuleData::fgSModuleCenter1 = 0.;
//Float_t AliEveEMCALSModuleData::fgSModuleCenter2 = 0.;

//
// Constructor
//
//______________________________________________________________________________
AliEveEMCALSModuleData::AliEveEMCALSModuleData(Int_t sm,AliEMCALGeometry* geom, TGeoNode* node, TGeoHMatrix* m) :
  TObject(),
  fGeom(geom),
  fNode(node),
  fSmId(sm),
  fNsm(0),
  fNDigits(0),
  fNClusters(0),
  fNHits(0),
  fPhiTileSize(0), fEtaTileSize(0),
  fHitArray(0),
  fDigitArray(0),
  fClusterArray(0),
  fMatrix(0),
  fHMatrix(m)
{
  Init(sm);
}

///
/// Copy constructor
///
//______________________________________________________________________________
  AliEveEMCALSModuleData::AliEveEMCALSModuleData(const AliEveEMCALSModuleData &esmdata) :
  TObject(),
  fGeom(esmdata.fGeom),
  fNode(esmdata.fNode),
  fSmId(esmdata.fSmId),
  fNsm(esmdata.fNsm),
  fNDigits(esmdata.fNDigits),
  fNClusters(esmdata.fNClusters),
  fNHits(esmdata.fNHits),
  fPhiTileSize(esmdata.fPhiTileSize), fEtaTileSize(esmdata.fEtaTileSize),
  fHitArray(esmdata.fHitArray),
  fDigitArray(esmdata.fDigitArray),
  fClusterArray(esmdata.fClusterArray),
  fMatrix(esmdata.fMatrix),
  fHMatrix(esmdata.fHMatrix)
{
  Init(esmdata.fNsm);
}

///
/// Destructor
///
//______________________________________________________________________________
AliEveEMCALSModuleData::~AliEveEMCALSModuleData()
{
  if(!fHitArray.empty())
    fHitArray.clear();

  if(!fDigitArray.empty())
    fDigitArray.clear();

  if(!fClusterArray.empty())
    fClusterArray.clear();
}

///
/// Release the SM data
///
//______________________________________________________________________________
void AliEveEMCALSModuleData::DropData()
{
  fNDigits   = 0;
  fNClusters = 0;
  fNHits     = 0;

  if(!fHitArray.empty())
    fHitArray.clear();

  if(!fDigitArray.empty())
    fDigitArray.clear();

  if(!fClusterArray.empty())
    fClusterArray.clear();

  return;
}

///
/// Initialize parameters
///
// ______________________________________________________________________________
void AliEveEMCALSModuleData::Init(Int_t sm)
{
  fNsm         = fGeom->GetNumberOfSuperModules();
  fPhiTileSize = fGeom->GetPhiTileSize();
  fEtaTileSize = fGeom->GetPhiTileSize();

  TGeoBBox* bbbox  = (TGeoBBox*) fNode->GetDaughter(0) ->GetVolume()->GetShape();
  TGeoBBox* sbbox  = (TGeoBBox*) fNode->GetDaughter(10)->GetVolume()->GetShape();
  TGeoBBox* dbbox  = (TGeoBBox*) fNode->GetDaughter(12)->GetVolume()->GetShape();
  TGeoBBox* dsbbox = (TGeoBBox*) fNode->GetDaughter(18)->GetVolume()->GetShape();

  fMatrix = (TGeoMatrix*) fNode->GetDaughter(sm)->GetMatrix();

  if(sm < 10)
  {
    fgSModuleBigBox0 = bbbox->GetDX();
    fgSModuleBigBox1 = bbbox->GetDY();
    fgSModuleBigBox2 = bbbox->GetDZ();
  }
  else if(sm < 12)
  {
    fgSModuleSmallBox0 = sbbox->GetDX();
    fgSModuleSmallBox1 = sbbox->GetDY();
    fgSModuleSmallBox2 = sbbox->GetDZ();
  }
  else if(sm < 18)
  {
    fgSModuleDCalBox0 = dbbox->GetDX();
    fgSModuleDCalBox1 = dbbox->GetDY();
    fgSModuleDCalBox2 = dbbox->GetDZ();
  }
  else if(sm < 20)
  {
    fgSModuleSmallDBox0 = dsbbox->GetDX();
    fgSModuleSmallDBox1 = dsbbox->GetDY();
    fgSModuleSmallDBox2 = dsbbox->GetDZ();
  }
}

///
/// Add a digit to this SM
///
// ______________________________________________________________________________
void AliEveEMCALSModuleData::RegisterDigit(Int_t AbsId, Int_t isupMod, Double_t iamp, Double_t ix, Double_t iy, Double_t iz)
{
  std::vector<Double_t> bufDig(6);
  bufDig[0] = AbsId;
  bufDig[1] = isupMod;
  bufDig[2] = iamp;
  bufDig[3] = ix;
  bufDig[4] = iy;
  bufDig[5] = iz;

  fDigitArray.push_back(bufDig);

  fNDigits++;
}

///
/// Add a hit to this SM
///
// ______________________________________________________________________________
void AliEveEMCALSModuleData::RegisterHit(Int_t AbsId, Int_t isupMod, Double_t iamp, Double_t ix, Double_t iy, Double_t iz)
{
  std::vector<Float_t> bufHit(6);
  bufHit[0] = AbsId;
  bufHit[1] = isupMod;
  bufHit[2] = iamp;
  bufHit[3] = ix;
  bufHit[4] = iy;
  bufHit[5] = iz;

  fHitArray.push_back(bufHit);

  fNHits++;
}

///
/// Add a cluster to this SM
///
// ______________________________________________________________________________
void AliEveEMCALSModuleData::RegisterCluster(Int_t isupMod, Double_t iamp, Double_t ix, Double_t iy, Double_t iz)
{
  std::vector<Double_t> bufClu(5);
  bufClu[0] = isupMod;
  bufClu[1] = iamp;
  bufClu[2] = ix;
  bufClu[3] = iy;
  bufClu[4] = iz;

  fClusterArray.push_back(bufClu);

  fNClusters++;
}
<commit_msg>forgot ClassImp doxy condition<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.                  *
 **************************************************************************/

#include <TGeoBBox.h>

#include "AliEMCALGeometry.h"
#include "AliEveEMCALSModuleData.h"

class TClonesArray;
class TGeoNode;
class TGeoMatrix;
class TVector2;
class AliEveEventManager;

/// \cond CLASSIMP
ClassImp(AliEveEMCALSModuleData) ;
/// \endcond

Float_t AliEveEMCALSModuleData::fgSModuleBigBox0 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleBigBox1 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleBigBox2 = 0.;

Float_t AliEveEMCALSModuleData::fgSModuleSmallBox0 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleSmallBox1 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleSmallBox2 = 0.;

Float_t AliEveEMCALSModuleData::fgSModuleDCalBox0 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleDCalBox1 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleDCalBox2 = 0.;

Float_t AliEveEMCALSModuleData::fgSModuleSmallDBox0 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleSmallDBox1 = 0.;
Float_t AliEveEMCALSModuleData::fgSModuleSmallDBox2 = 0.;

//Float_t AliEveEMCALSModuleData::fgSModuleCenter0 = 0.;
//Float_t AliEveEMCALSModuleData::fgSModuleCenter1 = 0.;
//Float_t AliEveEMCALSModuleData::fgSModuleCenter2 = 0.;

//
// Constructor
//
//______________________________________________________________________________
AliEveEMCALSModuleData::AliEveEMCALSModuleData(Int_t sm,AliEMCALGeometry* geom, TGeoNode* node, TGeoHMatrix* m) :
  TObject(),
  fGeom(geom),
  fNode(node),
  fSmId(sm),
  fNsm(0),
  fNDigits(0),
  fNClusters(0),
  fNHits(0),
  fPhiTileSize(0), fEtaTileSize(0),
  fHitArray(0),
  fDigitArray(0),
  fClusterArray(0),
  fMatrix(0),
  fHMatrix(m)
{
  Init(sm);
}

///
/// Copy constructor
///
//______________________________________________________________________________
  AliEveEMCALSModuleData::AliEveEMCALSModuleData(const AliEveEMCALSModuleData &esmdata) :
  TObject(),
  fGeom(esmdata.fGeom),
  fNode(esmdata.fNode),
  fSmId(esmdata.fSmId),
  fNsm(esmdata.fNsm),
  fNDigits(esmdata.fNDigits),
  fNClusters(esmdata.fNClusters),
  fNHits(esmdata.fNHits),
  fPhiTileSize(esmdata.fPhiTileSize), fEtaTileSize(esmdata.fEtaTileSize),
  fHitArray(esmdata.fHitArray),
  fDigitArray(esmdata.fDigitArray),
  fClusterArray(esmdata.fClusterArray),
  fMatrix(esmdata.fMatrix),
  fHMatrix(esmdata.fHMatrix)
{
  Init(esmdata.fNsm);
}

///
/// Destructor
///
//______________________________________________________________________________
AliEveEMCALSModuleData::~AliEveEMCALSModuleData()
{
  if(!fHitArray.empty())
    fHitArray.clear();

  if(!fDigitArray.empty())
    fDigitArray.clear();

  if(!fClusterArray.empty())
    fClusterArray.clear();
}

///
/// Release the SM data
///
//______________________________________________________________________________
void AliEveEMCALSModuleData::DropData()
{
  fNDigits   = 0;
  fNClusters = 0;
  fNHits     = 0;

  if(!fHitArray.empty())
    fHitArray.clear();

  if(!fDigitArray.empty())
    fDigitArray.clear();

  if(!fClusterArray.empty())
    fClusterArray.clear();

  return;
}

///
/// Initialize parameters
///
// ______________________________________________________________________________
void AliEveEMCALSModuleData::Init(Int_t sm)
{
  fNsm         = fGeom->GetNumberOfSuperModules();
  fPhiTileSize = fGeom->GetPhiTileSize();
  fEtaTileSize = fGeom->GetPhiTileSize();

  TGeoBBox* bbbox  = (TGeoBBox*) fNode->GetDaughter(0) ->GetVolume()->GetShape();
  TGeoBBox* sbbox  = (TGeoBBox*) fNode->GetDaughter(10)->GetVolume()->GetShape();
  TGeoBBox* dbbox  = (TGeoBBox*) fNode->GetDaughter(12)->GetVolume()->GetShape();
  TGeoBBox* dsbbox = (TGeoBBox*) fNode->GetDaughter(18)->GetVolume()->GetShape();

  fMatrix = (TGeoMatrix*) fNode->GetDaughter(sm)->GetMatrix();

  if(sm < 10)
  {
    fgSModuleBigBox0 = bbbox->GetDX();
    fgSModuleBigBox1 = bbbox->GetDY();
    fgSModuleBigBox2 = bbbox->GetDZ();
  }
  else if(sm < 12)
  {
    fgSModuleSmallBox0 = sbbox->GetDX();
    fgSModuleSmallBox1 = sbbox->GetDY();
    fgSModuleSmallBox2 = sbbox->GetDZ();
  }
  else if(sm < 18)
  {
    fgSModuleDCalBox0 = dbbox->GetDX();
    fgSModuleDCalBox1 = dbbox->GetDY();
    fgSModuleDCalBox2 = dbbox->GetDZ();
  }
  else if(sm < 20)
  {
    fgSModuleSmallDBox0 = dsbbox->GetDX();
    fgSModuleSmallDBox1 = dsbbox->GetDY();
    fgSModuleSmallDBox2 = dsbbox->GetDZ();
  }
}

///
/// Add a digit to this SM
///
// ______________________________________________________________________________
void AliEveEMCALSModuleData::RegisterDigit(Int_t AbsId, Int_t isupMod, Double_t iamp, Double_t ix, Double_t iy, Double_t iz)
{
  std::vector<Double_t> bufDig(6);
  bufDig[0] = AbsId;
  bufDig[1] = isupMod;
  bufDig[2] = iamp;
  bufDig[3] = ix;
  bufDig[4] = iy;
  bufDig[5] = iz;

  fDigitArray.push_back(bufDig);

  fNDigits++;
}

///
/// Add a hit to this SM
///
// ______________________________________________________________________________
void AliEveEMCALSModuleData::RegisterHit(Int_t AbsId, Int_t isupMod, Double_t iamp, Double_t ix, Double_t iy, Double_t iz)
{
  std::vector<Float_t> bufHit(6);
  bufHit[0] = AbsId;
  bufHit[1] = isupMod;
  bufHit[2] = iamp;
  bufHit[3] = ix;
  bufHit[4] = iy;
  bufHit[5] = iz;

  fHitArray.push_back(bufHit);

  fNHits++;
}

///
/// Add a cluster to this SM
///
// ______________________________________________________________________________
void AliEveEMCALSModuleData::RegisterCluster(Int_t isupMod, Double_t iamp, Double_t ix, Double_t iy, Double_t iz)
{
  std::vector<Double_t> bufClu(5);
  bufClu[0] = isupMod;
  bufClu[1] = iamp;
  bufClu[2] = ix;
  bufClu[3] = iy;
  bufClu[4] = iz;

  fClusterArray.push_back(bufClu);

  fNClusters++;
}
<|endoftext|>


<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "docsumconfig.h"
#include "docsumwriter.h"
#include "idocsumenvironment.h"
#include "rankfeaturesdfw.h"
#include "textextractordfw.h"
#include "geoposdfw.h"
#include "positionsdfw.h"
#include "juniperdfw.h"
#include <vespa/vespalib/util/stringfmt.h>
#include <vespa/vespalib/util/exceptions.h>

namespace search::docsummary {

using vespalib::IllegalArgumentException;
using vespalib::make_string;

const ResultConfig &
DynamicDocsumConfig::getResultConfig() const {
    return *_writer->GetResultConfig();
}

IDocsumFieldWriter::UP
DynamicDocsumConfig::createFieldWriter(const string & fieldName, const string & overrideName, const string & argument, bool & rc)
{
    const ResultConfig & resultConfig = getResultConfig();
    rc = false;
    IDocsumFieldWriter::UP fieldWriter;
    if (overrideName == "dynamicteaser") {
        if ( ! argument.empty() ) {
            const char *langFieldName = "something unused";
            DynamicTeaserDFW *fw = new DynamicTeaserDFW(getEnvironment()->getJuniper());
            fieldWriter.reset(fw);
            rc = fw->Init(fieldName.c_str(), langFieldName, resultConfig, argument.c_str());
        } else {
            throw IllegalArgumentException("Missing argument");
        }
    } else if (overrideName == "textextractor") {
        if ( ! argument.empty() ) {
            TextExtractorDFW * fw = new TextExtractorDFW();
            fieldWriter.reset(fw);
            rc = fw->init(fieldName, argument, resultConfig);
        } else {
            throw IllegalArgumentException("Missing argument");
        }
    } else if (overrideName == "summaryfeatures") {
        SummaryFeaturesDFW *fw = new SummaryFeaturesDFW();
        fieldWriter.reset(fw);
        fw->init(getEnvironment());
        rc = true;
    } else if (overrideName == "rankfeatures") {
        RankFeaturesDFW * fw = new RankFeaturesDFW();
        fw->init(getEnvironment());
        fieldWriter.reset(fw);
        rc = true;
    } else if (overrideName == "empty") {
        EmptyDFW *fw = new EmptyDFW();
        fieldWriter.reset(fw);
        rc = true;
    } else if (overrideName == "copy") {
        if ( ! argument.empty() ) {
            CopyDFW *fw = new CopyDFW();
            fieldWriter.reset(fw);
            rc = fw->Init(resultConfig, argument.c_str());
        } else {
            throw IllegalArgumentException("Missing argument");
        }
    } else if (overrideName == "absdist") {
        if (getEnvironment()) {
            IAttributeManager *am = getEnvironment()->getAttributeManager();
            fieldWriter = createAbsDistanceDFW(argument.c_str(), am);
            rc = fieldWriter.get();
        }
    } else if (overrideName == "positions") {
        if (getEnvironment()) {
            IAttributeManager *am = getEnvironment()->getAttributeManager();
            fieldWriter = createPositionsDFW(argument.c_str(), am);
            rc = fieldWriter.get();
        }
    } else if (overrideName == "geopos") {
        if (getEnvironment()) {
            IAttributeManager *am = getEnvironment()->getAttributeManager();
            fieldWriter = GeoPositionDFW::create(argument.c_str(), am);
            rc = fieldWriter.get();
        }
    } else if (overrideName == "attribute") {
        const char *vectorName = argument.c_str();
        if (getEnvironment() && getEnvironment()->getAttributeManager()) {
            IDocsumFieldWriter *fw = AttributeDFWFactory::create(*getEnvironment()->getAttributeManager(), vectorName);
            fieldWriter.reset(fw);
            rc = fw != NULL;
        }
    } else {
        throw IllegalArgumentException("unknown override operation '" + overrideName + "' for field '" + fieldName + "'.");
    }
    return fieldWriter;
}

void
DynamicDocsumConfig::configure(const vespa::config::search::SummarymapConfig &cfg)
{
    std::vector<string> strCfg;
    if ((cfg.defaultoutputclass != -1) && !_writer->SetDefaultOutputClass(cfg.defaultoutputclass)) {
        throw IllegalArgumentException(make_string("could not set default output class to %d", cfg.defaultoutputclass));
    }
    for (size_t i = 0; i < cfg.override.size(); ++i) {
        const vespa::config::search::SummarymapConfig::Override & o = cfg.override[i];
        if (o.command == "attributecombiner") {
            // TODO: Remove this when support has been added
            continue;
        }
        bool rc(false);
        IDocsumFieldWriter::UP fieldWriter = createFieldWriter(o.field, o.command, o.arguments, rc);
        if (rc && fieldWriter.get() != NULL) {
            rc = _writer->Override(o.field.c_str(), fieldWriter.release()); // OBJECT HAND-OVER
        }
        if (!rc) {
            throw IllegalArgumentException(o.command + " override operation failed during initialization");
        }
    }
}

}
<commit_msg>Wire in AttributeCombinerDFW.<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "docsumconfig.h"
#include "docsumwriter.h"
#include "idocsumenvironment.h"
#include "rankfeaturesdfw.h"
#include "textextractordfw.h"
#include "geoposdfw.h"
#include "positionsdfw.h"
#include "juniperdfw.h"
#include "attribute_combiner_dfw.h"
#include <vespa/vespalib/util/stringfmt.h>
#include <vespa/vespalib/util/exceptions.h>

namespace search::docsummary {

using vespalib::IllegalArgumentException;
using vespalib::make_string;

const ResultConfig &
DynamicDocsumConfig::getResultConfig() const {
    return *_writer->GetResultConfig();
}

IDocsumFieldWriter::UP
DynamicDocsumConfig::createFieldWriter(const string & fieldName, const string & overrideName, const string & argument, bool & rc)
{
    const ResultConfig & resultConfig = getResultConfig();
    rc = false;
    IDocsumFieldWriter::UP fieldWriter;
    if (overrideName == "dynamicteaser") {
        if ( ! argument.empty() ) {
            const char *langFieldName = "something unused";
            DynamicTeaserDFW *fw = new DynamicTeaserDFW(getEnvironment()->getJuniper());
            fieldWriter.reset(fw);
            rc = fw->Init(fieldName.c_str(), langFieldName, resultConfig, argument.c_str());
        } else {
            throw IllegalArgumentException("Missing argument");
        }
    } else if (overrideName == "textextractor") {
        if ( ! argument.empty() ) {
            TextExtractorDFW * fw = new TextExtractorDFW();
            fieldWriter.reset(fw);
            rc = fw->init(fieldName, argument, resultConfig);
        } else {
            throw IllegalArgumentException("Missing argument");
        }
    } else if (overrideName == "summaryfeatures") {
        SummaryFeaturesDFW *fw = new SummaryFeaturesDFW();
        fieldWriter.reset(fw);
        fw->init(getEnvironment());
        rc = true;
    } else if (overrideName == "rankfeatures") {
        RankFeaturesDFW * fw = new RankFeaturesDFW();
        fw->init(getEnvironment());
        fieldWriter.reset(fw);
        rc = true;
    } else if (overrideName == "empty") {
        EmptyDFW *fw = new EmptyDFW();
        fieldWriter.reset(fw);
        rc = true;
    } else if (overrideName == "copy") {
        if ( ! argument.empty() ) {
            CopyDFW *fw = new CopyDFW();
            fieldWriter.reset(fw);
            rc = fw->Init(resultConfig, argument.c_str());
        } else {
            throw IllegalArgumentException("Missing argument");
        }
    } else if (overrideName == "absdist") {
        if (getEnvironment()) {
            IAttributeManager *am = getEnvironment()->getAttributeManager();
            fieldWriter = createAbsDistanceDFW(argument.c_str(), am);
            rc = fieldWriter.get();
        }
    } else if (overrideName == "positions") {
        if (getEnvironment()) {
            IAttributeManager *am = getEnvironment()->getAttributeManager();
            fieldWriter = createPositionsDFW(argument.c_str(), am);
            rc = fieldWriter.get();
        }
    } else if (overrideName == "geopos") {
        if (getEnvironment()) {
            IAttributeManager *am = getEnvironment()->getAttributeManager();
            fieldWriter = GeoPositionDFW::create(argument.c_str(), am);
            rc = fieldWriter.get();
        }
    } else if (overrideName == "attribute") {
        const char *vectorName = argument.c_str();
        if (getEnvironment() && getEnvironment()->getAttributeManager()) {
            IDocsumFieldWriter *fw = AttributeDFWFactory::create(*getEnvironment()->getAttributeManager(), vectorName);
            fieldWriter.reset(fw);
            rc = fw != NULL;
        }
    } else if (overrideName == "attributecombiner") {
        if (getEnvironment() && getEnvironment()->getAttributeManager()) {
            fieldWriter = AttributeCombinerDFW::create(fieldName, *getEnvironment()->getAttributeManager());
            rc = static_cast<bool>(fieldWriter);
        }
    } else {
        throw IllegalArgumentException("unknown override operation '" + overrideName + "' for field '" + fieldName + "'.");
    }
    return fieldWriter;
}

void
DynamicDocsumConfig::configure(const vespa::config::search::SummarymapConfig &cfg)
{
    std::vector<string> strCfg;
    if ((cfg.defaultoutputclass != -1) && !_writer->SetDefaultOutputClass(cfg.defaultoutputclass)) {
        throw IllegalArgumentException(make_string("could not set default output class to %d", cfg.defaultoutputclass));
    }
    for (size_t i = 0; i < cfg.override.size(); ++i) {
        const vespa::config::search::SummarymapConfig::Override & o = cfg.override[i];
        bool rc(false);
        IDocsumFieldWriter::UP fieldWriter = createFieldWriter(o.field, o.command, o.arguments, rc);
        if (rc && fieldWriter.get() != NULL) {
            rc = _writer->Override(o.field.c_str(), fieldWriter.release()); // OBJECT HAND-OVER
        }
        if (!rc) {
            throw IllegalArgumentException(o.command + " override operation failed during initialization");
        }
    }
}

}
<|endoftext|>


<commit_before>//
//  ModifiedRenderingExample.cpp
//  ExampleApp
//
//  Created by eeGeo on 03/05/2013.
//  Copyright (c) 2013 eeGeo. All rights reserved.
//

#include "ModifiedRenderingExample.h"
#include "PooledMesh.h"
#include "IStreamingVolume.h"
#include "DiffuseTexturedVertex.h"
#include "MathsHelpers.h"
#include "IInterestPointProvider.h"
#include "CameraHelpers.h"

using namespace Eegeo;
using namespace Eegeo::Rendering;

namespace Examples
{
    ModifiedRenderingExample::ModifiedRenderingExample(RenderContext& renderContext,
                                                       Eegeo::Camera::ICameraProvider& cameraProvider,
                                                       Eegeo::Location::IInterestPointProvider& interestPointProvider,
                                                       Eegeo::Streaming::IStreamingVolume& visibleVolume,
                                                       Eegeo::Lighting::GlobalLighting& lighting,
                                                       Eegeo::Resources::MeshPool<Eegeo::Rendering::RenderableItem*>& buildingPool,
                                                       Eegeo::Resources::MeshPool<Eegeo::Rendering::RenderableItem*>& shadowPool)
    :renderContext(renderContext)
    ,cameraProvider(cameraProvider)
    ,interestPointProvider(interestPointProvider)
    ,visibleVolume(visibleVolume)
    ,buildingPool(buildingPool)
    ,shadowPool(shadowPool)
    ,lighting(lighting)
    ,pCriteria(NULL)
    {
    }

    void ModifiedRenderingExample::Start()
    {
        //MyPoolFilterCriteria implemented below... uses camera interest point as selection criteria
        pCriteria = new ModifiedRenderingExample::MyPoolFilterCriteria(this);

        //apply to pools, but lifetime responsibility is ours
        buildingPool.SetFilterCriteria(pCriteria);
        shadowPool.SetFilterCriteria(pCriteria);
    }

    void ModifiedRenderingExample::Suspend()
    {
        //remove it from the pools, and destroy the criteria
        buildingPool.SetFilterCriteria(NULL);
        shadowPool.SetFilterCriteria(NULL);

        delete pCriteria;
        pCriteria = NULL;
    }

    void ModifiedRenderingExample::Update()
    {

    }

    void ModifiedRenderingExample::Draw()
    {
        //i want to draw the buildings matching the criteria a flat color and transparent...
        //if shadows match the filter criteria, just don't draw them
        //
        //if the buildings match, DrawItems uses my shader and sets state to draw transparently

        typedef Eegeo::Resources::PooledMesh<RenderableItem*>* TPooledMeshPtr;
        typedef Eegeo::DataStructures::PoolEntry<TPooledMeshPtr> TPoolEntry;
        typedef std::vector<TPoolEntry> TResVec;

        TResVec filtered;
        buildingPool.GetEntriesMeetingFilterCriteria(filtered);

        std::vector<RenderableItem*> toRender;

        for(TResVec::const_iterator it = filtered.begin(); it != filtered.end(); ++ it)
        {
            const TPoolEntry& item = *it;
            RenderableItem* resource = item.instance->GetResource();

            if(item.allocated && resource != NULL && item.instance->ShouldDraw())
            {
                toRender.push_back(resource);
            }
        }

        //ok, the toRender items were not drawn by the platform, so I should draw them now
        DrawItems(toRender);
    }

    void ModifiedRenderingExample::DrawItems(const std::vector<Eegeo::Rendering::RenderableItem*>& items)
    {
        GLState& glState = renderContext.GetGLState();

        std::vector<Eegeo::Culling::IndexBufferRange> rangesToDraw;

        if (glState.UseProgram.TrySet(shader.ProgramHandle))
        {
            const Eegeo::m44 &colors = lighting.GetColors();
            Eegeo_GL(glUniformMatrix4fv(shader.LightColorsUniform, 1, 0, (const GLfloat*)&colors));
        }

        for(std::vector<RenderableItem*>::const_iterator it = items.begin(); it != items.end(); ++ it)
        {
            RenderableItem* item = *it;

            if(item->IndexCount() == 0) {
                continue;
            }

            //semt-transparent, so we're gonna be blending
            glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
            glEnable(GL_BLEND);

            Eegeo::v3 cameraLocalPos = Eegeo::Camera::CameraHelpers::CameraRelativePoint(item->GetEcefPosition(), renderContext.GetCameraOriginEcef());

            Eegeo::m44 model, mvp;
            Helpers::MathsHelpers::ComputeScaleAndOffset(model, 1.0f, item->GetEcefPosition().Norm().ToSingle(), cameraLocalPos);
            Eegeo::m44::Mul(mvp, renderContext.GetViewProjectionMatrix(), model);

            Eegeo_GL(glUniformMatrix4fv(shader.ModelViewProjectionUniform, 1, 0, (const GLfloat*)&mvp))

            Eegeo_GL(glUniform3f(shader.MinVertRangeUniform,
                                 item->GetMinVertexRange().GetX(),
                                 item->GetMinVertexRange().GetY(),
                                 item->GetMinVertexRange().GetZ()));

            Eegeo_GL(glUniform3f(shader.MaxVertRangeUniform,
                                 item->GetMaxVertexRange().GetX(),
                                 item->GetMaxVertexRange().GetY(),
                                 item->GetMaxVertexRange().GetZ()));

            Eegeo_GL(glUniform4f(shader.DiffuseColorUniform, 0.0f, 0.0f, 1.0f, 0.1f)); //alpha 10%

            Eegeo_GL(glEnableVertexAttribArray(shader.PositionAttribute));
            Eegeo_GL(glEnableVertexAttribArray(shader.LightDotAttribute));

            glState.BindArrayBuffer(item->GetVertexBuffer());
            glState.BindElementArrayBuffer(item->GetIndexBuffer());

            //i don't need the UV channel as not texturing them, but it is part of the buulding vertex so must be considered
            Eegeo_GL(glVertexAttribPointer(shader.PositionAttribute, 3, GL_UNSIGNED_SHORT, GL_TRUE, sizeof(ShortDiffuseTexturedVertex), 0));
            Eegeo_GL(glVertexAttribPointer(shader.LightDotAttribute, 1, GL_FLOAT, GL_FALSE, sizeof(ShortDiffuseTexturedVertex), (GLvoid*) (sizeof(short)*6)));

            Eegeo_GL(glDrawElements(GL_TRIANGLES, item->IndexCount(), GL_UNSIGNED_SHORT, (void*)0 ));

        }

        glDisable(GL_BLEND);
        glState.BindArrayBuffer(0);
        glState.BindElementArrayBuffer(0);
    }

    bool ModifiedRenderingExample::MyPoolFilterCriteria::operator()(Eegeo::Rendering::RenderableItem* item)
    {
        const double filterRadius = 400.0f;
        const double filterRadiusSq = filterRadius*filterRadius;

        Eegeo::v3 cameraRelativePos = Eegeo::Camera::CameraHelpers::CameraRelativePoint(item->GetEcefPosition(), owner->interestPointProvider.GetEcefInterestPoint());

        double delta = cameraRelativePos.LengthSq();
        bool closeToInterest = delta < filterRadiusSq;

        if (closeToInterest)
        {
            return true; //i want to draw with custom semi-transparent rendering method
        }

        return false; //let the platform do the default rendering
    }
}<commit_msg>Fix for move of vertex types in platform. Buddy:Jonty<commit_after>//
//  ModifiedRenderingExample.cpp
//  ExampleApp
//
//  Created by eeGeo on 03/05/2013.
//  Copyright (c) 2013 eeGeo. All rights reserved.
//

#include "ModifiedRenderingExample.h"
#include "PooledMesh.h"
#include "IStreamingVolume.h"
#include "DiffuseTexturedVertex.h"
#include "MathsHelpers.h"
#include "IInterestPointProvider.h"
#include "CameraHelpers.h"

using namespace Eegeo;
using namespace Eegeo::Rendering;

namespace Examples
{
    ModifiedRenderingExample::ModifiedRenderingExample(RenderContext& renderContext,
                                                       Eegeo::Camera::ICameraProvider& cameraProvider,
                                                       Eegeo::Location::IInterestPointProvider& interestPointProvider,
                                                       Eegeo::Streaming::IStreamingVolume& visibleVolume,
                                                       Eegeo::Lighting::GlobalLighting& lighting,
                                                       Eegeo::Resources::MeshPool<Eegeo::Rendering::RenderableItem*>& buildingPool,
                                                       Eegeo::Resources::MeshPool<Eegeo::Rendering::RenderableItem*>& shadowPool)
    :renderContext(renderContext)
    ,cameraProvider(cameraProvider)
    ,interestPointProvider(interestPointProvider)
    ,visibleVolume(visibleVolume)
    ,buildingPool(buildingPool)
    ,shadowPool(shadowPool)
    ,lighting(lighting)
    ,pCriteria(NULL)
    {
    }

    void ModifiedRenderingExample::Start()
    {
        //MyPoolFilterCriteria implemented below... uses camera interest point as selection criteria
        pCriteria = new ModifiedRenderingExample::MyPoolFilterCriteria(this);

        //apply to pools, but lifetime responsibility is ours
        buildingPool.SetFilterCriteria(pCriteria);
        shadowPool.SetFilterCriteria(pCriteria);
    }

    void ModifiedRenderingExample::Suspend()
    {
        //remove it from the pools, and destroy the criteria
        buildingPool.SetFilterCriteria(NULL);
        shadowPool.SetFilterCriteria(NULL);

        delete pCriteria;
        pCriteria = NULL;
    }

    void ModifiedRenderingExample::Update()
    {

    }

    void ModifiedRenderingExample::Draw()
    {
        //i want to draw the buildings matching the criteria a flat color and transparent...
        //if shadows match the filter criteria, just don't draw them
        //
        //if the buildings match, DrawItems uses my shader and sets state to draw transparently

        typedef Eegeo::Resources::PooledMesh<RenderableItem*>* TPooledMeshPtr;
        typedef Eegeo::DataStructures::PoolEntry<TPooledMeshPtr> TPoolEntry;
        typedef std::vector<TPoolEntry> TResVec;

        TResVec filtered;
        buildingPool.GetEntriesMeetingFilterCriteria(filtered);

        std::vector<RenderableItem*> toRender;

        for(TResVec::const_iterator it = filtered.begin(); it != filtered.end(); ++ it)
        {
            const TPoolEntry& item = *it;
            RenderableItem* resource = item.instance->GetResource();

            if(item.allocated && resource != NULL && item.instance->ShouldDraw())
            {
                toRender.push_back(resource);
            }
        }

        //ok, the toRender items were not drawn by the platform, so I should draw them now
        DrawItems(toRender);
    }

    void ModifiedRenderingExample::DrawItems(const std::vector<Eegeo::Rendering::RenderableItem*>& items)
    {
        GLState& glState = renderContext.GetGLState();

        std::vector<Eegeo::Culling::IndexBufferRange> rangesToDraw;

        if (glState.UseProgram.TrySet(shader.ProgramHandle))
        {
            const Eegeo::m44 &colors = lighting.GetColors();
            Eegeo_GL(glUniformMatrix4fv(shader.LightColorsUniform, 1, 0, (const GLfloat*)&colors));
        }

        for(std::vector<RenderableItem*>::const_iterator it = items.begin(); it != items.end(); ++ it)
        {
            RenderableItem* item = *it;

            if(item->IndexCount() == 0) {
                continue;
            }

            //semt-transparent, so we're gonna be blending
            glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
            glEnable(GL_BLEND);

            Eegeo::v3 cameraLocalPos = Eegeo::Camera::CameraHelpers::CameraRelativePoint(item->GetEcefPosition(), renderContext.GetCameraOriginEcef());

            Eegeo::m44 model, mvp;
            Helpers::MathsHelpers::ComputeScaleAndOffset(model, 1.0f, item->GetEcefPosition().Norm().ToSingle(), cameraLocalPos);
            Eegeo::m44::Mul(mvp, renderContext.GetViewProjectionMatrix(), model);

            Eegeo_GL(glUniformMatrix4fv(shader.ModelViewProjectionUniform, 1, 0, (const GLfloat*)&mvp))

            Eegeo_GL(glUniform3f(shader.MinVertRangeUniform,
                                 item->GetMinVertexRange().GetX(),
                                 item->GetMinVertexRange().GetY(),
                                 item->GetMinVertexRange().GetZ()));

            Eegeo_GL(glUniform3f(shader.MaxVertRangeUniform,
                                 item->GetMaxVertexRange().GetX(),
                                 item->GetMaxVertexRange().GetY(),
                                 item->GetMaxVertexRange().GetZ()));

            Eegeo_GL(glUniform4f(shader.DiffuseColorUniform, 0.0f, 0.0f, 1.0f, 0.1f)); //alpha 10%

            Eegeo_GL(glEnableVertexAttribArray(shader.PositionAttribute));
            Eegeo_GL(glEnableVertexAttribArray(shader.LightDotAttribute));

            glState.BindArrayBuffer(item->GetVertexBuffer());
            glState.BindElementArrayBuffer(item->GetIndexBuffer());

            //i don't need the UV channel as not texturing them, but it is part of the buulding vertex so must be considered
            Eegeo_GL(glVertexAttribPointer(shader.PositionAttribute, 3, GL_UNSIGNED_SHORT, GL_TRUE, sizeof(VertexTypes::ShortDiffuseTexturedVertex), 0));
            Eegeo_GL(glVertexAttribPointer(shader.LightDotAttribute, 1, GL_FLOAT, GL_FALSE, sizeof(VertexTypes::ShortDiffuseTexturedVertex), (GLvoid*) (sizeof(short)*6)));

            Eegeo_GL(glDrawElements(GL_TRIANGLES, item->IndexCount(), GL_UNSIGNED_SHORT, (void*)0 ));

        }

        glDisable(GL_BLEND);
        glState.BindArrayBuffer(0);
        glState.BindElementArrayBuffer(0);
    }

    bool ModifiedRenderingExample::MyPoolFilterCriteria::operator()(Eegeo::Rendering::RenderableItem* item)
    {
        const double filterRadius = 400.0f;
        const double filterRadiusSq = filterRadius*filterRadius;

        Eegeo::v3 cameraRelativePos = Eegeo::Camera::CameraHelpers::CameraRelativePoint(item->GetEcefPosition(), owner->interestPointProvider.GetEcefInterestPoint());

        double delta = cameraRelativePos.LengthSq();
        bool closeToInterest = delta < filterRadiusSq;

        if (closeToInterest)
        {
            return true; //i want to draw with custom semi-transparent rendering method
        }

        return false; //let the platform do the default rendering
    }
}<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_BASE_HH
#define DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_BASE_HH

#include <type_traits>

#include <dune/common/typetraits.hh>
#include <dune/common/dynvector.hh>

#include <dune/geometry/genericreferenceelements.hh>

#include <dune/stuff/common/exceptions.hh>

#include "../interface.hh"

namespace Dune {
namespace GDT {
namespace Spaces {

// forward, to allow for specialization
template< class ImpTraits, int domainDim, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 >
class ContinuousLagrangeBase
{
  static_assert(AlwaysFalse< ImpTraits >::value, "Untested for these dimensions!");
};

template< class ImpTraits, int domainDim, class RangeFieldImp, int rangeDim >
class ContinuousLagrangeBase< ImpTraits, domainDim, RangeFieldImp, rangeDim, 1 >
  : public SpaceInterface< ImpTraits >
{
  typedef SpaceInterface< ImpTraits > BaseType;
  typedef ContinuousLagrangeBase< ImpTraits, domainDim, RangeFieldImp, rangeDim, 1 > ThisType;

  static const RangeFieldImp compare_tolerance_ = 1e-13;
public:
  typedef ImpTraits Traits;

  using BaseType::polOrder;

  using typename BaseType::DomainFieldType;
  using BaseType::dimDomain;
  using typename BaseType::DomainType;

  typedef typename Traits::RangeFieldType RangeFieldType;
  using BaseType::dimRange;
  using BaseType::dimRangeCols;

  using typename BaseType::EntityType;
  using typename BaseType::IntersectionType;
  using typename BaseType::BoundaryInfoType;
  using typename BaseType::PatternType;

  virtual ~ContinuousLagrangeBase() {}

  using BaseType::compute_pattern;

  template< class G, class S >
  PatternType compute_pattern(const GridView< G >& local_grid_view, const SpaceInterface< S >& ansatz_space) const
  {
    return BaseType::compute_volume_pattern(local_grid_view, ansatz_space);
  }

  virtual std::vector< DomainType > lagrange_points(const EntityType& entity) const
  {
    // check
    static_assert(polOrder == 1, "Not tested for higher polynomial orders!");
    if (dimRange != 1) DUNE_THROW_COLORFULLY(NotImplemented, "Does not work for higher dimensions");
    assert(this->grid_view()->indexSet().contains(entity));
    // get the basis and reference element
    const auto basis = this->base_function_set(entity);
    const auto& reference_element = ReferenceElements< DomainFieldType, dimDomain >::general(entity.type());
    const int num_vertices = reference_element.size(dimDomain);
    assert(num_vertices >= 0);
    assert(size_t(num_vertices) == basis.size() && "This should not happen with polOrder 1!");
    // prepare return vector
    std::vector< DomainType > local_vertices(num_vertices, DomainType(0));
    if (this->tmp_basis_values_.size() < basis.size())
      this->tmp_basis_values_.resize(basis.size());
    // loop over all vertices
    for (int ii = 0; ii < num_vertices; ++ii) {
      // get the local coordinate of the iith vertex
      const auto local_vertex = reference_element.position(ii, dimDomain);
      // evaluate the basefunctionset
      basis.evaluate(local_vertex, this->tmp_basis_values_);
      // find the basis function that evaluates to one here (has to be only one!)
      size_t ones = 0;
      size_t zeros = 0;
      size_t failures = 0;
      for (size_t jj = 0; jj < basis.size(); ++jj) {
        if (std::abs(this->tmp_basis_values_[jj][0] - RangeFieldType(1)) < compare_tolerance_) {
          local_vertices[jj] = local_vertex;
          ++ones;
        } else if (std::abs(this->tmp_basis_values_[jj][0]) < compare_tolerance_)
          ++zeros;
        else
          ++failures;
      }
      assert(ones == 1 && zeros == (basis.size() - 1) && failures == 0 && "This must not happen for polOrder 1!");
    }
    return local_vertices;
  } // ... lagrange_points(...)

  virtual std::set< size_t > local_dirichlet_DoFs(const EntityType& entity,
                                                  const BoundaryInfoType& boundaryInfo) const
  {
    static_assert(polOrder == 1, "Not tested for higher polynomial orders!");
    if (dimRange != 1) DUNE_THROW_COLORFULLY(NotImplemented, "Does not work for higher dimensions");
    // check
    assert(this->grid_view()->indexSet().contains(entity));
    // prepare
    std::set< size_t > localDirichletDofs;
    std::vector< DomainType > dirichlet_vertices;
    // get all dirichlet vertices of this entity, therefore
    // * loop over all intersections
    const auto intersection_it_end = this->grid_view()->iend(entity);
    for (auto intersection_it = this->grid_view()->ibegin(entity);
         intersection_it != intersection_it_end;
         ++intersection_it) {
      // only work on dirichlet ones
      const auto& intersection = *intersection_it;
      if (boundaryInfo.dirichlet(intersection)) {
        // and get the vertices of the intersection
        const auto geometry = intersection.geometry();
        for (int cc = 0; cc < geometry.corners(); ++cc)
          dirichlet_vertices.emplace_back(entity.geometry().local(geometry.corner(cc)));
      } // only work on dirichlet ones
    } // loop over all intersections
    // find the corresponding basis functions
    const auto basis = this->base_function_set(entity);
    if (this->tmp_basis_values_.size() < basis.size())
      this->tmp_basis_values_.resize(basis.size());
    for (size_t cc = 0; cc < dirichlet_vertices.size(); ++cc) {
      // find the basis function that evaluates to one here (has to be only one!)
      basis.evaluate(dirichlet_vertices[cc], this->tmp_basis_values_);
      size_t ones = 0;
      size_t zeros = 0;
      size_t failures = 0;
      for (size_t jj = 0; jj < basis.size(); ++jj) {
        if (std::abs(this->tmp_basis_values_[jj][0] - RangeFieldType(1)) < compare_tolerance_) {
          localDirichletDofs.insert(jj);
          ++ones;
        } else if (std::abs(this->tmp_basis_values_[jj][0]) < compare_tolerance_)
          ++zeros;
        else
          ++failures;
      }
      assert(ones == 1 && zeros == (basis.size() - 1) && failures == 0 && "This must not happen for polOrder 1!");
    }
    return localDirichletDofs;
  } // ... local_dirichlet_DoFs(...)

private:
  template< class C, bool set_row >
  struct DirichletConstraints;
  template< class C >
  struct DirichletConstraints< C, true >  { static RangeFieldType value() { return RangeFieldType(1); } };
  template< class C >
  struct DirichletConstraints< C, false > { static RangeFieldType value() { return RangeFieldType(0); } };

  template< class T, bool set_row >
  void compute_local_constraints(const SpaceInterface< T >& other,
                                 const EntityType& entity,
                                 Constraints::Dirichlet< IntersectionType, RangeFieldType, set_row >& ret) const
  {
    // check
    static_assert(polOrder == 1, "Not tested for higher polynomial orders!");
    if (dimRange != 1) DUNE_THROW_COLORFULLY(NotImplemented, "Does not work for higher dimensions");
    assert(this->grid_view()->indexSet().contains(entity));
    typedef DirichletConstraints
        < Constraints::Dirichlet< IntersectionType, RangeFieldType, set_row >, set_row > SetRow;
    const std::set< size_t > localDirichletDofs = this->local_dirichlet_DoFs(entity, ret.gridBoundary());
    const size_t numRows = localDirichletDofs.size();
    if (numRows > 0) {
      const size_t numCols = this->mapper().numDofs(entity);
      ret.setSize(numRows, numCols);
      this->mapper().globalIndices(entity, tmpMappedRows_);
      other.mapper().globalIndices(entity, tmpMappedCols_);
      size_t localRow = 0;
      const RangeFieldType zero(0);
      for (auto localDirichletDofIt = localDirichletDofs.begin();
           localDirichletDofIt != localDirichletDofs.end();
           ++localDirichletDofIt) {
        const size_t& localDirichletDofIndex = * localDirichletDofIt;
        ret.globalRow(localRow) = tmpMappedRows_[localDirichletDofIndex];
        for (size_t jj = 0; jj < ret.cols(); ++jj) {
          ret.globalCol(jj) = tmpMappedCols_[jj];
          if (tmpMappedCols_[jj] == tmpMappedRows_[localDirichletDofIndex])
            ret.value(localRow, jj) = SetRow::value();
          else
            ret.value(localRow, jj) = zero;
        }
        ++localRow;
      }
    } else {
      ret.setSize(0, 0);
    }
  } // ... compute_local_constraints(..., Dirichlet< ..., true >)

public:
  template< bool set >
  void local_constraints(const EntityType& entity,
                         Constraints::Dirichlet< IntersectionType, RangeFieldType, set >& ret) const
  {
    local_constraints(*this, entity, ret);
  }

  virtual void local_constraints(const ThisType& other,
                                 const EntityType& entity,
                                 Constraints::Dirichlet< IntersectionType, RangeFieldType, true >& ret) const
  {
    compute_local_constraints(other, entity, ret);
  }

  virtual void local_constraints(const ThisType& other,
                                 const EntityType& entity,
                                 Constraints::Dirichlet< IntersectionType, RangeFieldType, false >& ret) const
  {
    compute_local_constraints(other, entity, ret);
  }

protected:
  mutable Dune::DynamicVector< size_t > tmpMappedRows_;
  mutable Dune::DynamicVector< size_t > tmpMappedCols_;
}; // class ContinuousLagrangeBase

} // namespace Spaces
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_BASE_HH
<commit_msg>[spaces.cg.base] make gcc-4.8 happy<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_BASE_HH
#define DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_BASE_HH

#include <type_traits>

#include <dune/common/typetraits.hh>
#include <dune/common/dynvector.hh>

#include <dune/geometry/genericreferenceelements.hh>

#include <dune/stuff/common/exceptions.hh>

#include "../interface.hh"

namespace Dune {
namespace GDT {
namespace Spaces {

// forward, to allow for specialization
template< class ImpTraits, int domainDim, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 >
class ContinuousLagrangeBase
{
  static_assert(AlwaysFalse< ImpTraits >::value, "Untested for these dimensions!");
};

template< class ImpTraits, int domainDim, class RangeFieldImp, int rangeDim >
class ContinuousLagrangeBase< ImpTraits, domainDim, RangeFieldImp, rangeDim, 1 >
  : public SpaceInterface< ImpTraits >
{
  typedef SpaceInterface< ImpTraits > BaseType;
  typedef ContinuousLagrangeBase< ImpTraits, domainDim, RangeFieldImp, rangeDim, 1 > ThisType;

  static const constexpr RangeFieldImp compare_tolerance_ = 1e-13;
public:
  typedef ImpTraits Traits;

  using BaseType::polOrder;

  using typename BaseType::DomainFieldType;
  using BaseType::dimDomain;
  using typename BaseType::DomainType;

  typedef typename Traits::RangeFieldType RangeFieldType;
  using BaseType::dimRange;
  using BaseType::dimRangeCols;

  using typename BaseType::EntityType;
  using typename BaseType::IntersectionType;
  using typename BaseType::BoundaryInfoType;
  using typename BaseType::PatternType;

  virtual ~ContinuousLagrangeBase() {}

  using BaseType::compute_pattern;

  template< class G, class S >
  PatternType compute_pattern(const GridView< G >& local_grid_view, const SpaceInterface< S >& ansatz_space) const
  {
    return BaseType::compute_volume_pattern(local_grid_view, ansatz_space);
  }

  virtual std::vector< DomainType > lagrange_points(const EntityType& entity) const
  {
    // check
    static_assert(polOrder == 1, "Not tested for higher polynomial orders!");
    if (dimRange != 1) DUNE_THROW_COLORFULLY(NotImplemented, "Does not work for higher dimensions");
    assert(this->grid_view()->indexSet().contains(entity));
    // get the basis and reference element
    const auto basis = this->base_function_set(entity);
    const auto& reference_element = ReferenceElements< DomainFieldType, dimDomain >::general(entity.type());
    const int num_vertices = reference_element.size(dimDomain);
    assert(num_vertices >= 0);
    assert(size_t(num_vertices) == basis.size() && "This should not happen with polOrder 1!");
    // prepare return vector
    std::vector< DomainType > local_vertices(num_vertices, DomainType(0));
    if (this->tmp_basis_values_.size() < basis.size())
      this->tmp_basis_values_.resize(basis.size());
    // loop over all vertices
    for (int ii = 0; ii < num_vertices; ++ii) {
      // get the local coordinate of the iith vertex
      const auto local_vertex = reference_element.position(ii, dimDomain);
      // evaluate the basefunctionset
      basis.evaluate(local_vertex, this->tmp_basis_values_);
      // find the basis function that evaluates to one here (has to be only one!)
      size_t ones = 0;
      size_t zeros = 0;
      size_t failures = 0;
      for (size_t jj = 0; jj < basis.size(); ++jj) {
        if (std::abs(this->tmp_basis_values_[jj][0] - RangeFieldType(1)) < compare_tolerance_) {
          local_vertices[jj] = local_vertex;
          ++ones;
        } else if (std::abs(this->tmp_basis_values_[jj][0]) < compare_tolerance_)
          ++zeros;
        else
          ++failures;
      }
      assert(ones == 1 && zeros == (basis.size() - 1) && failures == 0 && "This must not happen for polOrder 1!");
    }
    return local_vertices;
  } // ... lagrange_points(...)

  virtual std::set< size_t > local_dirichlet_DoFs(const EntityType& entity,
                                                  const BoundaryInfoType& boundaryInfo) const
  {
    static_assert(polOrder == 1, "Not tested for higher polynomial orders!");
    if (dimRange != 1) DUNE_THROW_COLORFULLY(NotImplemented, "Does not work for higher dimensions");
    // check
    assert(this->grid_view()->indexSet().contains(entity));
    // prepare
    std::set< size_t > localDirichletDofs;
    std::vector< DomainType > dirichlet_vertices;
    // get all dirichlet vertices of this entity, therefore
    // * loop over all intersections
    const auto intersection_it_end = this->grid_view()->iend(entity);
    for (auto intersection_it = this->grid_view()->ibegin(entity);
         intersection_it != intersection_it_end;
         ++intersection_it) {
      // only work on dirichlet ones
      const auto& intersection = *intersection_it;
      if (boundaryInfo.dirichlet(intersection)) {
        // and get the vertices of the intersection
        const auto geometry = intersection.geometry();
        for (int cc = 0; cc < geometry.corners(); ++cc)
          dirichlet_vertices.emplace_back(entity.geometry().local(geometry.corner(cc)));
      } // only work on dirichlet ones
    } // loop over all intersections
    // find the corresponding basis functions
    const auto basis = this->base_function_set(entity);
    if (this->tmp_basis_values_.size() < basis.size())
      this->tmp_basis_values_.resize(basis.size());
    for (size_t cc = 0; cc < dirichlet_vertices.size(); ++cc) {
      // find the basis function that evaluates to one here (has to be only one!)
      basis.evaluate(dirichlet_vertices[cc], this->tmp_basis_values_);
      size_t ones = 0;
      size_t zeros = 0;
      size_t failures = 0;
      for (size_t jj = 0; jj < basis.size(); ++jj) {
        if (std::abs(this->tmp_basis_values_[jj][0] - RangeFieldType(1)) < compare_tolerance_) {
          localDirichletDofs.insert(jj);
          ++ones;
        } else if (std::abs(this->tmp_basis_values_[jj][0]) < compare_tolerance_)
          ++zeros;
        else
          ++failures;
      }
      assert(ones == 1 && zeros == (basis.size() - 1) && failures == 0 && "This must not happen for polOrder 1!");
    }
    return localDirichletDofs;
  } // ... local_dirichlet_DoFs(...)

private:
  template< class C, bool set_row >
  struct DirichletConstraints;
  template< class C >
  struct DirichletConstraints< C, true >  { static RangeFieldType value() { return RangeFieldType(1); } };
  template< class C >
  struct DirichletConstraints< C, false > { static RangeFieldType value() { return RangeFieldType(0); } };

  template< class T, bool set_row >
  void compute_local_constraints(const SpaceInterface< T >& other,
                                 const EntityType& entity,
                                 Constraints::Dirichlet< IntersectionType, RangeFieldType, set_row >& ret) const
  {
    // check
    static_assert(polOrder == 1, "Not tested for higher polynomial orders!");
    if (dimRange != 1) DUNE_THROW_COLORFULLY(NotImplemented, "Does not work for higher dimensions");
    assert(this->grid_view()->indexSet().contains(entity));
    typedef DirichletConstraints
        < Constraints::Dirichlet< IntersectionType, RangeFieldType, set_row >, set_row > SetRow;
    const std::set< size_t > localDirichletDofs = this->local_dirichlet_DoFs(entity, ret.gridBoundary());
    const size_t numRows = localDirichletDofs.size();
    if (numRows > 0) {
      const size_t numCols = this->mapper().numDofs(entity);
      ret.setSize(numRows, numCols);
      this->mapper().globalIndices(entity, tmpMappedRows_);
      other.mapper().globalIndices(entity, tmpMappedCols_);
      size_t localRow = 0;
      const RangeFieldType zero(0);
      for (auto localDirichletDofIt = localDirichletDofs.begin();
           localDirichletDofIt != localDirichletDofs.end();
           ++localDirichletDofIt) {
        const size_t& localDirichletDofIndex = * localDirichletDofIt;
        ret.globalRow(localRow) = tmpMappedRows_[localDirichletDofIndex];
        for (size_t jj = 0; jj < ret.cols(); ++jj) {
          ret.globalCol(jj) = tmpMappedCols_[jj];
          if (tmpMappedCols_[jj] == tmpMappedRows_[localDirichletDofIndex])
            ret.value(localRow, jj) = SetRow::value();
          else
            ret.value(localRow, jj) = zero;
        }
        ++localRow;
      }
    } else {
      ret.setSize(0, 0);
    }
  } // ... compute_local_constraints(..., Dirichlet< ..., true >)

public:
  template< bool set >
  void local_constraints(const EntityType& entity,
                         Constraints::Dirichlet< IntersectionType, RangeFieldType, set >& ret) const
  {
    local_constraints(*this, entity, ret);
  }

  virtual void local_constraints(const ThisType& other,
                                 const EntityType& entity,
                                 Constraints::Dirichlet< IntersectionType, RangeFieldType, true >& ret) const
  {
    compute_local_constraints(other, entity, ret);
  }

  virtual void local_constraints(const ThisType& other,
                                 const EntityType& entity,
                                 Constraints::Dirichlet< IntersectionType, RangeFieldType, false >& ret) const
  {
    compute_local_constraints(other, entity, ret);
  }

protected:
  mutable Dune::DynamicVector< size_t > tmpMappedRows_;
  mutable Dune::DynamicVector< size_t > tmpMappedCols_;
}; // class ContinuousLagrangeBase

} // namespace Spaces
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_BASE_HH
<|endoftext|>