<commit_before>/* bzflag
 * Copyright (c) 1993 - 2003 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#include <math.h>
#include "common.h"
#include "BaseBuilding.h"
#include "global.h"
#include "Intersect.h"
#include "QuadWallSceneNode.h"
#include "BZDBCache.h"

std::string		BaseBuilding::typeName("BaseBuilding");

BaseBuilding::BaseBuilding(const float *p, float rotation,
	const float *size, int _team) :
		Obstacle(p, rotation, size[0], size[1], size[2]),
		team(_team)
{
}

BaseBuilding::~BaseBuilding()
{
  // do nothing
}

std::string		BaseBuilding::getType() const
{
  return typeName;
}

std::string		BaseBuilding::getClassName()
{
  return typeName;
}

float			BaseBuilding::intersect(const Ray &r) const
{
  return timeRayHitsBlock(r, getPosition(), getRotation(),
			  getWidth(), getBreadth(), getHeight());
}

void			BaseBuilding::getNormal(const float *p, float *n) const
{
  getNormalRect(p, getPosition(), getRotation(), getWidth(), getBreadth(), n);
}

void			BaseBuilding::get3DNormal(const float* p, float* n) const
{
  // This bit of cruft causes bullets to bounce of buildings in the z direction
  if (fabs(p[2] - getPosition()[2]) < Epsilon) {
    n[0] = 0.0f;
    n[1] = 0.0f;
    n[2] = -1.0f;
  }
  else if (fabs(p[2] - (getPosition()[2] + getHeight())) < Epsilon) {
    n[0] = 0.0f;
    n[1] = 0.0f;
    n[2] = 1.0f;
  } // end cruftiness
  else
    getNormal(p, n);
}

bool			BaseBuilding::isInside(const float *p, float radius) const
{
  return (p[2] < (getPosition()[2] + getHeight()))
  &&     ((p[2]+BZDBCache::tankHeight) > getPosition()[2])
  &&     testRectCircle(getPosition(), getRotation(), getWidth(), getBreadth(), p, radius);
}

bool			BaseBuilding::isInside(const float *p, float angle,
			float dx, float dy) const
{
  return (p[2] < (getPosition()[2] + getHeight()))
  &&     ((p[2]+BZDBCache::tankHeight) >= getPosition()[2])
  &&     testRectRect(getPosition(), getRotation(), getWidth(), getBreadth(), p, angle, dx, dy);
}

bool			BaseBuilding::isInside(const float* oldP, float,
					       const float *p, float angle,
			float dx, float dy) const
{
  float topBaseHeight = getPosition()[2] + getHeight();
  float higherZ;
  float lowerZ;
  // if a base is just the ground (z == 0 && height == 0) no collision
  // ground is already handled
  if (topBaseHeight <= 0.0)
    return false;
  if (oldP[2] > p[2]) {
    higherZ = oldP[2];
    lowerZ  = p[2];
  } else {
    higherZ = p[2];
    lowerZ  = oldP[2];
  }
  if (lowerZ >= topBaseHeight)
    return false;
  if ((higherZ + BZDBCache::tankHeight) < getPosition()[2])
    return false;
  return testRectRect(getPosition(), getRotation(), getWidth(), getBreadth(),
		      p, angle, dx, dy);
}

bool			BaseBuilding::isCrossing(const float *p, float angle,
			float dx, float dy,
			float *plane) const
{
  // if not inside or contained, then not crossing
  if (!isInside(p, angle, dx, dy) ||
      testRectInRect(getPosition(), getRotation(),
	getWidth(), getBreadth(), p, angle, dx, dy))
    return false;
  if(!plane) return true;

  // it's crossing -- choose which wall is being crossed (this
  // is a guestimate, should really do a careful test). Just
  // see which wall the point is closest to
  const float *p2 = getPosition();
  const float a2  = getRotation();
  const float c   = cosf(-a2), s = sinf(-a2);
  const float x   = c * (p[0] - p2[0]) - s * (p[1] - p2[1]);
  const float y   = c * (p[1] - p2[1]) - s * (p[0] - p2[0]);
  float pw[2];
  if(fabsf(fabsf(x) - getWidth()) < fabsf(fabsf(y) - getBreadth())) {
    plane[0] = ((x < 0.0) ? -cosf(a2) : cosf(a2));
    plane[1] = ((x < 0.0) ? -sinf(a2) : sinf(a2));
    pw[0] = p2[0] + getWidth() * plane[0];
    pw[1] = p2[1] + getWidth() * plane[1];
  } else {
    plane[0] = ((y < 0.0) ? sinf(a2) : -sinf(a2));
    plane[1] = ((y < 0.0) ? cosf(a2) : -cosf(a2));
    pw[0] = p2[0] + getBreadth() * plane[0];
    pw[1] = p2[1] + getBreadth() * plane[1];
  }

  // now finish off plane equation
  plane[2] = 0.0;
  plane[3] = -(plane[0] * pw[0] + plane[1] * pw[1]);
  return true;
}

bool			BaseBuilding::getHitNormal(const float *pos1, float azimuth1,
			const float *pos2, float azimuth2,
			float halfWidth, float halfBreadth,
			float *normal) const
{
  return Obstacle::getHitNormal(pos1, azimuth1, pos2, azimuth2, halfWidth, halfBreadth,
			getPosition(), getRotation(), getWidth(), getBreadth(),
			getHeight(), normal) >= 0.0f;
}

ObstacleSceneNodeGenerator* BaseBuilding::newSceneNodeGenerator() const
{
  return new BaseSceneNodeGenerator(this);
}

void			BaseBuilding::getCorner(int index, float *pos) const
{
  const float *base = getPosition();
  const float c = cosf(getRotation());
  const float s = sinf(getRotation());
  const float w = getWidth();
  const float b = getBreadth();
  switch(index & 3) {
    case 0:
      pos[0] = base[0] + c * w - s * b;
      pos[1] = base[1] + s * w + c * b;
      break;
    case 1:
      pos[0] = base[0] - c * w - s * b;
      pos[1] = base[1] - s * w + c * b;
      break;
    case 2:
      pos[0] = base[0] - c * w + s * b;
      pos[1] = base[1] - s * w - c * b;
      break;
    case 3:
      pos[0] = base[0] + c * w + s * b;
      pos[1] = base[1] + s * w - c * b;
      break;
  }
  pos[2] = base[2];
  if(index >= 4) pos[2] += getHeight();
}

const int	BaseBuilding::getTeam() const {
  return team;
}

BaseSceneNodeGenerator::BaseSceneNodeGenerator(const BaseBuilding* _base) : base(_base)
{
  // do nothing
}

BaseSceneNodeGenerator::~BaseSceneNodeGenerator()
{
  // do nothing
}

WallSceneNode*	BaseSceneNodeGenerator::getNextNode(float uRepeats, float vRepeats, bool lod)
{
  const GLfloat *pos = base->getPosition();
  if(getNodeNumber() >= 1 && pos[2] == 0) return NULL;
  if(getNodeNumber() >= 6) return NULL;
  GLfloat bPoint[3], sCorner[3], tCorner[3];
  if(base->getPosition()[2] == 0) {
    incNodeNumber();
    base->getCorner(0, bPoint);
    base->getCorner(3, tCorner);
    base->getCorner(1, sCorner);
  } else {
    switch(incNodeNumber()) {
      case 1:
	base->getCorner(4, bPoint);
	base->getCorner(5, sCorner);
	base->getCorner(7, tCorner);
	break;
      case 2:
	base->getCorner(0, bPoint);
	base->getCorner(3, sCorner);
	base->getCorner(1, tCorner);
	break;
      case 3:
	base->getCorner(0, bPoint);
	base->getCorner(1, sCorner);
	base->getCorner(4, tCorner);
	break;
      case 4:
	base->getCorner(1, bPoint);
	base->getCorner(2, sCorner);
	base->getCorner(5, tCorner);
	break;
      case 5:
	base->getCorner(2, bPoint);
	base->getCorner(3, sCorner);
	base->getCorner(6, tCorner);
	break;
      case 6:
	base->getCorner(3, bPoint);
	base->getCorner(0, sCorner);
	base->getCorner(7, tCorner);
	break;
    }
  }
  GLfloat color[4];
  switch(base->getTeam()) {
    case 1:
      color[0] = 0.7f; color[1] = 0.0f; color[2] = 0.0f;
      break;
    case 2:
      color[0] = 0.0f; color[1] = 0.7f; color[2] = 0.0f;
      break;
    case 3:
      color[0] = 0.0f; color[1] = 0.0f; color[2] = 0.7f;
      break;
    case 4:
      color[0] = 0.7f; color[1] = 0.0f; color[2] = 0.7f;
      break;
  }
  color[3] = 1.0;

  GLfloat sEdge[3];
  GLfloat tEdge[3];
  sEdge[0] = sCorner[0] - bPoint[0];
  sEdge[1] = sCorner[1] - bPoint[1];
  sEdge[2] = sCorner[2] - bPoint[2];
  tEdge[0] = tCorner[0] - bPoint[0];
  tEdge[1] = tCorner[1] - bPoint[1];
  tEdge[2] = tCorner[2] - bPoint[2];

  WallSceneNode *retval = new QuadWallSceneNode(bPoint, sEdge, tEdge, uRepeats, vRepeats, lod);
  retval->setColor(color);
  return retval;
}

// Local variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8

<commit_msg>rendering of thick bases at 0 height fixed<commit_after>/* bzflag
 * Copyright (c) 1993 - 2003 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#include <math.h>
#include "common.h"
#include "BaseBuilding.h"
#include "global.h"
#include "Intersect.h"
#include "QuadWallSceneNode.h"
#include "BZDBCache.h"

std::string		BaseBuilding::typeName("BaseBuilding");

BaseBuilding::BaseBuilding(const float *p, float rotation,
	const float *size, int _team) :
		Obstacle(p, rotation, size[0], size[1], size[2]),
		team(_team)
{
}

BaseBuilding::~BaseBuilding()
{
  // do nothing
}

std::string		BaseBuilding::getType() const
{
  return typeName;
}

std::string		BaseBuilding::getClassName()
{
  return typeName;
}

float			BaseBuilding::intersect(const Ray &r) const
{
  return timeRayHitsBlock(r, getPosition(), getRotation(),
			  getWidth(), getBreadth(), getHeight());
}

void			BaseBuilding::getNormal(const float *p, float *n) const
{
  getNormalRect(p, getPosition(), getRotation(), getWidth(), getBreadth(), n);
}

void			BaseBuilding::get3DNormal(const float* p, float* n) const
{
  // This bit of cruft causes bullets to bounce of buildings in the z direction
  if (fabs(p[2] - getPosition()[2]) < Epsilon) {
    n[0] = 0.0f;
    n[1] = 0.0f;
    n[2] = -1.0f;
  }
  else if (fabs(p[2] - (getPosition()[2] + getHeight())) < Epsilon) {
    n[0] = 0.0f;
    n[1] = 0.0f;
    n[2] = 1.0f;
  } // end cruftiness
  else
    getNormal(p, n);
}

bool			BaseBuilding::isInside(const float *p, float radius) const
{
  return (p[2] < (getPosition()[2] + getHeight()))
  &&     ((p[2]+BZDBCache::tankHeight) > getPosition()[2])
  &&     testRectCircle(getPosition(), getRotation(), getWidth(), getBreadth(), p, radius);
}

bool			BaseBuilding::isInside(const float *p, float angle,
			float dx, float dy) const
{
  return (p[2] < (getPosition()[2] + getHeight()))
  &&     ((p[2]+BZDBCache::tankHeight) >= getPosition()[2])
  &&     testRectRect(getPosition(), getRotation(), getWidth(), getBreadth(), p, angle, dx, dy);
}

bool			BaseBuilding::isInside(const float* oldP, float,
					       const float *p, float angle,
			float dx, float dy) const
{
  float topBaseHeight = getPosition()[2] + getHeight();
  float higherZ;
  float lowerZ;
  // if a base is just the ground (z == 0 && height == 0) no collision
  // ground is already handled
  if (topBaseHeight <= 0.0)
    return false;
  if (oldP[2] > p[2]) {
    higherZ = oldP[2];
    lowerZ  = p[2];
  } else {
    higherZ = p[2];
    lowerZ  = oldP[2];
  }
  if (lowerZ >= topBaseHeight)
    return false;
  if ((higherZ + BZDBCache::tankHeight) < getPosition()[2])
    return false;
  return testRectRect(getPosition(), getRotation(), getWidth(), getBreadth(),
		      p, angle, dx, dy);
}

bool			BaseBuilding::isCrossing(const float *p, float angle,
			float dx, float dy,
			float *plane) const
{
  // if not inside or contained, then not crossing
  if (!isInside(p, angle, dx, dy) ||
      testRectInRect(getPosition(), getRotation(),
	getWidth(), getBreadth(), p, angle, dx, dy))
    return false;
  if(!plane) return true;

  // it's crossing -- choose which wall is being crossed (this
  // is a guestimate, should really do a careful test). Just
  // see which wall the point is closest to
  const float *p2 = getPosition();
  const float a2  = getRotation();
  const float c   = cosf(-a2), s = sinf(-a2);
  const float x   = c * (p[0] - p2[0]) - s * (p[1] - p2[1]);
  const float y   = c * (p[1] - p2[1]) - s * (p[0] - p2[0]);
  float pw[2];
  if(fabsf(fabsf(x) - getWidth()) < fabsf(fabsf(y) - getBreadth())) {
    plane[0] = ((x < 0.0) ? -cosf(a2) : cosf(a2));
    plane[1] = ((x < 0.0) ? -sinf(a2) : sinf(a2));
    pw[0] = p2[0] + getWidth() * plane[0];
    pw[1] = p2[1] + getWidth() * plane[1];
  } else {
    plane[0] = ((y < 0.0) ? sinf(a2) : -sinf(a2));
    plane[1] = ((y < 0.0) ? cosf(a2) : -cosf(a2));
    pw[0] = p2[0] + getBreadth() * plane[0];
    pw[1] = p2[1] + getBreadth() * plane[1];
  }

  // now finish off plane equation
  plane[2] = 0.0;
  plane[3] = -(plane[0] * pw[0] + plane[1] * pw[1]);
  return true;
}

bool			BaseBuilding::getHitNormal(const float *pos1, float azimuth1,
			const float *pos2, float azimuth2,
			float halfWidth, float halfBreadth,
			float *normal) const
{
  return Obstacle::getHitNormal(pos1, azimuth1, pos2, azimuth2, halfWidth, halfBreadth,
			getPosition(), getRotation(), getWidth(), getBreadth(),
			getHeight(), normal) >= 0.0f;
}

ObstacleSceneNodeGenerator* BaseBuilding::newSceneNodeGenerator() const
{
  return new BaseSceneNodeGenerator(this);
}

void			BaseBuilding::getCorner(int index, float *pos) const
{
  const float *base = getPosition();
  const float c = cosf(getRotation());
  const float s = sinf(getRotation());
  const float w = getWidth();
  const float b = getBreadth();
  switch(index & 3) {
    case 0:
      pos[0] = base[0] + c * w - s * b;
      pos[1] = base[1] + s * w + c * b;
      break;
    case 1:
      pos[0] = base[0] - c * w - s * b;
      pos[1] = base[1] - s * w + c * b;
      break;
    case 2:
      pos[0] = base[0] - c * w + s * b;
      pos[1] = base[1] - s * w - c * b;
      break;
    case 3:
      pos[0] = base[0] + c * w + s * b;
      pos[1] = base[1] + s * w - c * b;
      break;
  }
  pos[2] = base[2];
  if(index >= 4) pos[2] += getHeight();
}

const int	BaseBuilding::getTeam() const {
  return team;
}

BaseSceneNodeGenerator::BaseSceneNodeGenerator(const BaseBuilding* _base) : base(_base)
{
  // do nothing
}

BaseSceneNodeGenerator::~BaseSceneNodeGenerator()
{
  // do nothing
}

WallSceneNode*	BaseSceneNodeGenerator::getNextNode(float uRepeats, float vRepeats, bool lod)
{
  const GLfloat *pos = base->getPosition();
  const float height = base->getHeight();
  if(getNodeNumber() >= 1 && height == 0) return NULL;
  if(getNodeNumber() >= 6) return NULL;
  GLfloat bPoint[3], sCorner[3], tCorner[3];
  if (height == 0) {
    incNodeNumber();
    base->getCorner(0, bPoint);
    base->getCorner(3, tCorner);
    base->getCorner(1, sCorner);
  } else {
    switch(incNodeNumber()) {
      case 1:
	base->getCorner(4, bPoint);
	base->getCorner(5, sCorner);
	base->getCorner(7, tCorner);
	break;
      case 2:
	base->getCorner(0, bPoint);
	base->getCorner(3, sCorner);
	base->getCorner(1, tCorner);
	break;
      case 3:
	base->getCorner(0, bPoint);
	base->getCorner(1, sCorner);
	base->getCorner(4, tCorner);
	break;
      case 4:
	base->getCorner(1, bPoint);
	base->getCorner(2, sCorner);
	base->getCorner(5, tCorner);
	break;
      case 5:
	base->getCorner(2, bPoint);
	base->getCorner(3, sCorner);
	base->getCorner(6, tCorner);
	break;
      case 6:
	base->getCorner(3, bPoint);
	base->getCorner(0, sCorner);
	base->getCorner(7, tCorner);
	break;
    }
  }
  GLfloat color[4];
  switch(base->getTeam()) {
    case 1:
      color[0] = 0.7f; color[1] = 0.0f; color[2] = 0.0f;
      break;
    case 2:
      color[0] = 0.0f; color[1] = 0.7f; color[2] = 0.0f;
      break;
    case 3:
      color[0] = 0.0f; color[1] = 0.0f; color[2] = 0.7f;
      break;
    case 4:
      color[0] = 0.7f; color[1] = 0.0f; color[2] = 0.7f;
      break;
  }
  color[3] = 1.0;

  GLfloat sEdge[3];
  GLfloat tEdge[3];
  sEdge[0] = sCorner[0] - bPoint[0];
  sEdge[1] = sCorner[1] - bPoint[1];
  sEdge[2] = sCorner[2] - bPoint[2];
  tEdge[0] = tCorner[0] - bPoint[0];
  tEdge[1] = tCorner[1] - bPoint[1];
  tEdge[2] = tCorner[2] - bPoint[2];

  WallSceneNode *retval = new QuadWallSceneNode(bPoint, sEdge, tEdge, uRepeats, vRepeats, lod);
  retval->setColor(color);
  return retval;
}

// Local variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8

<|endoftext|>


<commit_before>#ifndef CONTAINERS_ARCHIVE_VERSIONED_HPP_
#define CONTAINERS_ARCHIVE_VERSIONED_HPP_

#include "containers/archive/archive.hpp"
#include "version.hpp"

namespace archive_internal {

// This is just used to implement serialize_cluster_version and
// deserialize_cluster_version.

// This defines how to serialize cluster_version_t (which conveniently has a
// contiguous set of valid representation, from v1_13 to v1_13_is_latest).
ARCHIVE_PRIM_MAKE_RANGED_SERIALIZABLE(cluster_version_t, int8_t,
                                      cluster_version_t::v1_13,
                                      cluster_version_t::v1_13_is_latest);

}  // namespace archive_details

// These are generally universal.  They must not have their behavior change -- except
// if we remove some cluster_version_t value, in which case... maybe would fail on a
// range error with the specific removed values.  Or maybe, we would do something
// differently.
inline void serialize_cluster_version(write_message_t *wm, cluster_version_t v) {
    archive_internal::serialize<cluster_version_t::LATEST>(wm, v);
}

inline archive_result_t deserialize_cluster_version(read_stream_t *s,
                                                    cluster_version_t *thing) {
    return archive_internal::deserialize<cluster_version_t::LATEST>(s, thing);
}

// Serializes a value for a given version.  DOES NOT SERIALIZE THE VERSION NUMBER!
template <class T>
void serialize_for_version(cluster_version_t version, write_message_t *wm,
                           const T &value) {
    rassert(version == cluster_version_t::ONLY_VERSION);
    switch (version) {
    case cluster_version_t::v1_13:
        serialize<cluster_version_t::v1_13>(wm, value);
    }
}

// Deserializes a value, assuming it's serialized for a given version.  (This doesn't
// deserialize any version numbers.)
template <class T>
archive_result_t deserialize_for_version(cluster_version_t version,
                                         read_stream_t *s,
                                         T *thing) {
    rassert(version == cluster_version_t::ONLY_VERSION);
    switch (version) {
    case cluster_version_t::v1_13:
        return deserialize<cluster_version_t::v1_13>(s, thing);
    }
}

// RSI: Remove this, or something.
struct bogus_made_up_struct_t;
template <cluster_version_t W>
size_t serialized_size(const bogus_made_up_struct_t &);

// RSI: This is completely unused right now.  (Should it be?)
template <class T>
size_t serialized_size_for_version(cluster_version_t version,
                                   const T &thing) {
    rassert(version == cluster_version_t::ONLY_VERSION);
    switch (version) {
    case cluster_version_t::v1_13:
        return serialized_size<cluster_version_t::v1_13>(thing);
    }
}

#define INSTANTIATE_SERIALIZE_SINCE_v1_13(typ)                 \
    template void serialize<cluster_version_t::v1_13_is_latest>(  \
            write_message_t *, const typ &)

#define INSTANTIATE_DESERIALIZE_SINCE_v1_13(typ)                        \
    template archive_result_t deserialize<cluster_version_t::v1_13_is_latest>( \
            read_stream_t *, typ *)

#define INSTANTIATE_SERIALIZED_SIZE_SINCE_v1_13(typ) \
    template size_t serialized_size<cluster_version_t::v1_13_is_latest>(const typ &)

// RSI: Probably rename this?
#define INSTANTIATE_SINCE_v1_13(typ)            \
    INSTANTIATE_SERIALIZE_SINCE_v1_13(typ);     \
    INSTANTIATE_DESERIALIZE_SINCE_v1_13(typ)

#define INSTANTIATE_SELF_SINCE_v1_13(typ)                               \
    template void typ::rdb_serialize<cluster_version_t::v1_13_is_latest>( \
            write_message_t *) const;                                   \
    template archive_result_t typ::rdb_deserialize<cluster_version_t::v1_13_is_latest>( \
            read_stream_t *s)

#endif  // CONTAINERS_ARCHIVE_VERSIONED_HPP_
<commit_msg>Removed RSI about removing something.<commit_after>#ifndef CONTAINERS_ARCHIVE_VERSIONED_HPP_
#define CONTAINERS_ARCHIVE_VERSIONED_HPP_

#include "containers/archive/archive.hpp"
#include "version.hpp"

namespace archive_internal {

// This is just used to implement serialize_cluster_version and
// deserialize_cluster_version.  (cluster_version_t conveniently has a contiguous set
// of valid representation, from v1_13 to v1_13_is_latest).
ARCHIVE_PRIM_MAKE_RANGED_SERIALIZABLE(cluster_version_t, int8_t,
                                      cluster_version_t::v1_13,
                                      cluster_version_t::v1_13_is_latest);

class bogus_made_up_type_t;

}  // namespace archive_details

// These are generally universal.  They must not have their behavior change -- except
// if we remove some cluster_version_t value, in which case... maybe would fail on a
// range error with the specific removed values.  Or maybe, we would do something
// differently.
inline void serialize_cluster_version(write_message_t *wm, cluster_version_t v) {
    archive_internal::serialize<cluster_version_t::LATEST>(wm, v);
}

inline archive_result_t deserialize_cluster_version(read_stream_t *s,
                                                    cluster_version_t *thing) {
    return archive_internal::deserialize<cluster_version_t::LATEST>(s, thing);
}

// Serializes a value for a given version.  DOES NOT SERIALIZE THE VERSION NUMBER!
template <class T>
void serialize_for_version(cluster_version_t version, write_message_t *wm,
                           const T &value) {
    rassert(version == cluster_version_t::ONLY_VERSION);
    switch (version) {
    case cluster_version_t::v1_13:
        serialize<cluster_version_t::v1_13>(wm, value);
    }
}

// Deserializes a value, assuming it's serialized for a given version.  (This doesn't
// deserialize any version numbers.)
template <class T>
archive_result_t deserialize_for_version(cluster_version_t version,
                                         read_stream_t *s,
                                         T *thing) {
    rassert(version == cluster_version_t::ONLY_VERSION);
    switch (version) {
    case cluster_version_t::v1_13:
        return deserialize<cluster_version_t::v1_13>(s, thing);
    }
}

// Some serialized_size needs to be visible, apparently, so that
// serialized_size_for_version will actually parse.
template <cluster_version_t W>
size_t serialized_size(const archive_internal::bogus_made_up_type_t &);

// RSI: This is completely unused right now.  (Should it be?)
template <class T>
size_t serialized_size_for_version(cluster_version_t version,
                                   const T &thing) {
    rassert(version == cluster_version_t::ONLY_VERSION);
    switch (version) {
    case cluster_version_t::v1_13:
        return serialized_size<cluster_version_t::v1_13>(thing);
    }
}

#define INSTANTIATE_SERIALIZE_SINCE_v1_13(typ)                 \
    template void serialize<cluster_version_t::v1_13_is_latest>(  \
            write_message_t *, const typ &)

#define INSTANTIATE_DESERIALIZE_SINCE_v1_13(typ)                        \
    template archive_result_t deserialize<cluster_version_t::v1_13_is_latest>( \
            read_stream_t *, typ *)

#define INSTANTIATE_SERIALIZED_SIZE_SINCE_v1_13(typ) \
    template size_t serialized_size<cluster_version_t::v1_13_is_latest>(const typ &)

// RSI: Probably rename this?
#define INSTANTIATE_SINCE_v1_13(typ)            \
    INSTANTIATE_SERIALIZE_SINCE_v1_13(typ);     \
    INSTANTIATE_DESERIALIZE_SINCE_v1_13(typ)

#define INSTANTIATE_SELF_SINCE_v1_13(typ)                               \
    template void typ::rdb_serialize<cluster_version_t::v1_13_is_latest>( \
            write_message_t *) const;                                   \
    template archive_result_t typ::rdb_deserialize<cluster_version_t::v1_13_is_latest>( \
            read_stream_t *s)

#endif  // CONTAINERS_ARCHIVE_VERSIONED_HPP_
<|endoftext|>


<commit_before>//
//  interpreter.cpp
//  SimpleInformationRetrievalTools
//
//  Created by ryecao on 6/9/15.
//  Copyright (c) 2015 Zhendong Cao. All rights reserved.
//

#include "interpreter.h"
#include <iostream>
#include <sstream>
#include <string>
#include <cctype>

using namespace std;

vector<pair<string,string> > Interpreter::ProcessQuery(const string query){
	istringstream query_stream(query);
	string word;
	vector<int> bool_op_pos;
	vector<string> query_vector;
	vector<string> parameters;
	vector<pair<string,string> > result;

	bool search_type_set = false;
	bool synonym_set = false;
	bool top_k_set = false;

	int pos = 0;
	while(query_stream >> word){
		if (word == "AND" || word == "OR" || word == "NOT" ){
			_search_type = BOOL;
			search_type_set = true;
			bool_op_pos.push_back(pos);
		}
		if (word[0] == '-') {
			parameters.push_back(word);
		}
		else{
			query_vector.push_back(word);
		}
		pos++;
	}

	for (auto &para:parameters){
		if(search_type_set == false){
			if (para == "-PHRASE_SEARCH"){
				_search_type = PHRASE_SEARCH;
				search_type_set = true;
			}
		}

		if (synonym_set == false){
			if (para == "-SYNONYM_ON"){
				_synonym_mode = SYNONYM_ON;
				synonym_set = true;
			}
			else if (para == "-SYNONYM_OFF"){
				_synonym_mode = SYNONYM_OFF;
				synonym_set = true;
			}
		}

		if (top_k_set == false){
			if ( para == "-TOP_K_OFF"){
				_top_k_mode = TOP_K_OFF;
				top_k_set = true;
			}
			if ( para == "-TOP_K_HEAP"){
				_top_k_mode = TOP_K_HEAP;
				top_k_set = true;
			}
			if ( para == "-TOP_K_CHAMPION_LIST"){
				_top_k_mode = TOP_K_CHAMPION_LIST;
				top_k_set = true;
			}
			if ( para == "-TOP_K_STATIC_QUALITY_SCORE"){
				_top_k_mode = TOP_K_STATIC_QUALITY_SCORE;
				top_k_set = true;
			}
			if ( para == "-TOP_K_CLUSTER_PRUNING"){
				_top_k_mode = TOP_K_CLUSTER_PRUNING;
				top_k_set = true;
			}
		}
	}

	if (_search_type == BOOL){
		string segment = "";
		int bool_pos = 0;
		for (int i = 0; i < query_vector.size(); ++i){
			if(i == bool_op_pos[bool_pos]){

				if (segment != ""){
					if (bool_pos == 0){
						result.push_back(make_pair("AND",segment));
					}
					else{
						result.push_back(make_pair(query_vector[bool_op_pos[bool_pos-1]],segment.substr(0, segment.size()-1)));
					}
				}
				bool_pos++;
				segment = "";
				continue;
			}
			segment += query_vector[i] + " ";
		}

		result.push_back(make_pair(query_vector[bool_op_pos[bool_pos-1]],segment));

	}
	else{
		for (auto &q:query_vector){
			result.push_back(make_pair("AND", q));
		}
	}

	return result;
}
<commit_msg>fix filename capitalization problem<commit_after>//
//  interpreter.cpp
//  SimpleInformationRetrievalTools
//
//  Created by ryecao on 6/9/15.
//  Copyright (c) 2015 Zhendong Cao. All rights reserved.
//

#include "Interpreter.h"
#include <iostream>
#include <sstream>
#include <string>
#include <cctype>

using namespace std;

vector<pair<string,string> > Interpreter::ProcessQuery(const string query){
	istringstream query_stream(query);
	string word;
	vector<int> bool_op_pos;
	vector<string> query_vector;
	vector<string> parameters;
	vector<pair<string,string> > result;

	bool search_type_set = false;
	bool synonym_set = false;
	bool top_k_set = false;

	int pos = 0;
	while(query_stream >> word){
		if (word == "AND" || word == "OR" || word == "NOT" ){
			_search_type = BOOL;
			search_type_set = true;
			bool_op_pos.push_back(pos);
		}
		if (word[0] == '-') {
			parameters.push_back(word);
		}
		else{
			query_vector.push_back(word);
		}
		pos++;
	}

	for (auto &para:parameters){
		if(search_type_set == false){
			if (para == "-PHRASE_SEARCH"){
				_search_type = PHRASE_SEARCH;
				search_type_set = true;
			}
		}

		if (synonym_set == false){
			if (para == "-SYNONYM_ON"){
				_synonym_mode = SYNONYM_ON;
				synonym_set = true;
			}
			else if (para == "-SYNONYM_OFF"){
				_synonym_mode = SYNONYM_OFF;
				synonym_set = true;
			}
		}

		if (top_k_set == false){
			if ( para == "-TOP_K_OFF"){
				_top_k_mode = TOP_K_OFF;
				top_k_set = true;
			}
			if ( para == "-TOP_K_HEAP"){
				_top_k_mode = TOP_K_HEAP;
				top_k_set = true;
			}
			if ( para == "-TOP_K_CHAMPION_LIST"){
				_top_k_mode = TOP_K_CHAMPION_LIST;
				top_k_set = true;
			}
			if ( para == "-TOP_K_STATIC_QUALITY_SCORE"){
				_top_k_mode = TOP_K_STATIC_QUALITY_SCORE;
				top_k_set = true;
			}
			if ( para == "-TOP_K_CLUSTER_PRUNING"){
				_top_k_mode = TOP_K_CLUSTER_PRUNING;
				top_k_set = true;
			}
		}
	}

	if (_search_type == BOOL){
		string segment = "";
		int bool_pos = 0;
		for (int i = 0; i < query_vector.size(); ++i){
			if(i == bool_op_pos[bool_pos]){

				if (segment != ""){
					if (bool_pos == 0){
						result.push_back(make_pair("AND",segment));
					}
					else{
						result.push_back(make_pair(query_vector[bool_op_pos[bool_pos-1]],segment.substr(0, segment.size()-1)));
					}
				}
				bool_pos++;
				segment = "";
				continue;
			}
			segment += query_vector[i] + " ";
		}

		result.push_back(make_pair(query_vector[bool_op_pos[bool_pos-1]],segment));

	}
	else{
		for (auto &q:query_vector){
			result.push_back(make_pair("AND", q));
		}
	}

	return result;
}
<|endoftext|>


<commit_before>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2010 Scientific Computing and Imaging Institute,
   University of Utah.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/
/**
  \file    AnalyzeConverter.cpp
  \author  Tom Fogal
           SCI Institute
           University of Utah
*/
#include "AnalyzeConverter.h"

AnalyzeConverter::AnalyzeConverter()
{
  m_vConverterDesc = "Analyze 7.5";
  m_vSupportedExt.push_back("HDR");
}

struct analyze_hdr {
  int hdr_size;
  char data_type[10];
  char db_name[18];
  int extents;
  short session_err;
  char regular;
  char hkey_un0;
  short dim[8]; // yes, really.
  short datatype;
  short bpp;
  float aspect[3];
  float voxel_offset;
};

enum AnalyzeDataTypes {
  DT_NONE=0,
  DT_BINARY,          // 1 bit/voxel
  DT_UNSIGNED_CHAR,   // 8 bit
  DT_SIGNED_SHORT=4,
  DT_SIGNED_INT=8,
  DT_FLOAT=16,
  DT_COMPLEX=32,
  DT_DOUBLE=64,
  DT_RGB=128,
  DT_ALL=255
};

bool AnalyzeConverter::ConvertToRAW(const std::string& strSourceFilename,
                                    const std::string&,
                                    bool,
                                    UINT64& iHeaderSkip,
                                    UINT64& iComponentSize,
                                    UINT64& iComponentCount,
                                    bool& bConvertEndianness,
                                    bool& bSigned, bool& bIsFloat,
                                    UINT64VECTOR3& vVolumeSize,
                                    FLOATVECTOR3& vVolumeAspect,
                                    std::string& strTitle,
                                    UVFTables::ElementSemanticTable& eType,
                                    std::string& strIntermediateFile,
                                    bool& bDeleteIntermediateFile)
{
  strTitle = "from analyze converter";
  eType = UVFTables::ES_UNDEFINED;

  std::ifstream analyze(strSourceFilename.c_str(), std::ios::binary);
  if(!analyze) {
    T_ERROR("Could not open %s!", strSourceFilename.c_str());
    return false;
  }
  struct analyze_hdr hdr;

  analyze.read(reinterpret_cast<char*>(&hdr.hdr_size), 4);
  analyze.read(hdr.data_type, 10);
  analyze.read(hdr.db_name, 18);
  analyze.read(reinterpret_cast<char*>(&hdr.extents), 4);
  analyze.read(reinterpret_cast<char*>(&hdr.session_err), 2);
  analyze.read(&hdr.regular, 1);
  analyze.read(&hdr.hkey_un0, 1);
  for(size_t i=0; i < 8; ++i) {
    analyze.read(reinterpret_cast<char*>(&hdr.dim[i]), 2);
  }
  // 14 bytes of unused garbage.
  analyze.seekg(14, std::ios_base::cur);
  analyze.read(reinterpret_cast<char*>(&hdr.datatype), 2); // DT_xxx ..
  analyze.read(reinterpret_cast<char*>(&hdr.bpp), 2);
  analyze.seekg(2, std::ios_base::cur); // "dim_un0", unused.
  analyze.read(reinterpret_cast<char*>(&hdr.aspect[0]), 4);
  analyze.read(reinterpret_cast<char*>(&hdr.aspect[1]), 4);
  analyze.read(reinterpret_cast<char*>(&hdr.aspect[2]), 4);
  analyze.seekg(16, std::ios_base::cur); // 4 unused aspect values
  // 'voxel_offset' really is a float that stores a byte offset.  Seriously.
  // Maybe some of the same people that wrote DICOM made Analyze as well.
  analyze.read(reinterpret_cast<char*>(&hdr.voxel_offset), 4);

  // The header size was meant to be used in case the analyze format
  // was extended.  It never was.  Thus the headers are always 348
  // bytes.  This provides a convenient check for endianness; if the
  // size isn't 348, then we need to endian convert everything.
  bConvertEndianness = false;
  if(hdr.hdr_size != 348) {
    MESSAGE("Endianness is wrong, swapping...");
    bConvertEndianness = true;
    hdr.bpp = EndianConvert::Swap<short>(hdr.bpp);
    hdr.dim[0] = EndianConvert::Swap<short>(hdr.dim[0]);
    hdr.dim[1] = EndianConvert::Swap<short>(hdr.dim[1]);
    hdr.dim[2] = EndianConvert::Swap<short>(hdr.dim[2]);
    hdr.aspect[0] = EndianConvert::Swap<float>(hdr.aspect[0]);
    hdr.aspect[1] = EndianConvert::Swap<float>(hdr.aspect[1]);
    hdr.aspect[2] = EndianConvert::Swap<float>(hdr.aspect[2]);
    hdr.voxel_offset = EndianConvert::Swap<float>(hdr.voxel_offset);
    hdr.datatype = EndianConvert::Swap<short>(hdr.datatype);
  }

  iComponentCount = 1; // always, I guess?
  iComponentSize = hdr.bpp;
  vVolumeSize = UINT64VECTOR3(hdr.dim[0], hdr.dim[1], hdr.dim[2]);
  vVolumeAspect = FLOATVECTOR3(hdr.aspect[0], hdr.aspect[1], hdr.aspect[2]);
  {
    // Check to make sure the aspect ratios make sense.  Sometimes analyze
    // seems to fill them with zeroes...
    for(size_t i=0; i < 3; ++i) {
      if(vVolumeAspect[i] == 0.0) {
        WARNING("Aspect ratio is 0 for dimension %u, resetting to 1...", i);
        vVolumeAspect[i] = 1.0f;
      }
    }
  }
  MESSAGE("%gx%gx%g aspect ratio", vVolumeAspect[0], vVolumeAspect[1],
          vVolumeAspect[2]);
  MESSAGE("%llu-bit %llux%llux%llu data.", iComponentSize,
          vVolumeSize[0], vVolumeSize[1], vVolumeSize[2]);
  {
    UINT64 bits=0;
    switch(hdr.datatype) {
      case DT_BINARY:        bits =  1;
                             bSigned = false;
                             bIsFloat = false;
                             break;
      case DT_UNSIGNED_CHAR: bits =  8;
                             bSigned = false;
                             bIsFloat = false;
                             break;
      case DT_SIGNED_SHORT:  bits = 16;
                             bSigned = true;
                             bIsFloat = false;
                             break;
      case DT_SIGNED_INT:    bits = 32;
                             bSigned = true;
                             bIsFloat = false;
                             break;
      case DT_FLOAT:         bits = 32;
                             bSigned = true;
                             bIsFloat = true;
                             break;
      case DT_COMPLEX:
        T_ERROR("Don't know how to handle complex data.");
        return false;
        break;
      case DT_DOUBLE:        bits = 64;
                             bSigned = true;
                             bIsFloat = true;
                             break;
      default:
        WARNING("Unknown data type.");
        bits = 0;
        break;
    }
    if(iComponentSize != bits) {
      T_ERROR("Bits per pixel and data type disagree!  Broken file?");
      analyze.close();
      return false;
    }
  }

  // If the voxel offset is negative, then there is padding between every slice
  // in the data set.  We would need to write an intermediate file to handle
  // that; instead, we just don't handle it.
  if(hdr.voxel_offset < 0.0) {
    analyze.close();
    T_ERROR("Analyze voxel offset is negative (%g).  Intermediate file "
            "required; this converter is broken.");
    return false;
  }
  iHeaderSkip = static_cast<UINT64>(hdr.voxel_offset);
  MESSAGE("Skipping %llu bytes.", iHeaderSkip);

  strIntermediateFile = SysTools::RemoveExt(strSourceFilename) + ".img";
  MESSAGE("Using intermediate file %s", strIntermediateFile.c_str());
  bDeleteIntermediateFile = false;

  return true;
}

bool AnalyzeConverter::ConvertToNative(const std::string&,
                                       const std::string&,
                                       UINT64,
                                       UINT64,
                                       UINT64, bool,
                                       bool,
                                       UINT64VECTOR3,
                                       FLOATVECTOR3,
                                       bool,
                                       const bool)
{
  return false;
}
<commit_msg>analyze: Fix dimension && aspect detection.<commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2010 Scientific Computing and Imaging Institute,
   University of Utah.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/
/**
  \file    AnalyzeConverter.cpp
  \author  Tom Fogal
           SCI Institute
           University of Utah
*/
#include "AnalyzeConverter.h"

AnalyzeConverter::AnalyzeConverter()
{
  m_vConverterDesc = "Analyze 7.5";
  m_vSupportedExt.push_back("HDR");
}

struct analyze_hdr {
  int hdr_size;
  char data_type[10];
  char db_name[18];
  int extents;
  short session_err;
  char regular;
  char hkey_un0;
  short dim[8]; // yes, really.
  short datatype;
  short bpp;
  float aspect[3];
  float voxel_offset;
};

enum AnalyzeDataTypes {
  DT_NONE=0,
  DT_BINARY,          // 1 bit/voxel
  DT_UNSIGNED_CHAR,   // 8 bit
  DT_SIGNED_SHORT=4,
  DT_SIGNED_INT=8,
  DT_FLOAT=16,
  DT_COMPLEX=32,
  DT_DOUBLE=64,
  DT_RGB=128,
  DT_ALL=255
};

bool AnalyzeConverter::ConvertToRAW(const std::string& strSourceFilename,
                                    const std::string&,
                                    bool,
                                    UINT64& iHeaderSkip,
                                    UINT64& iComponentSize,
                                    UINT64& iComponentCount,
                                    bool& bConvertEndianness,
                                    bool& bSigned, bool& bIsFloat,
                                    UINT64VECTOR3& vVolumeSize,
                                    FLOATVECTOR3& vVolumeAspect,
                                    std::string& strTitle,
                                    UVFTables::ElementSemanticTable& eType,
                                    std::string& strIntermediateFile,
                                    bool& bDeleteIntermediateFile)
{
  strTitle = "from analyze converter";
  eType = UVFTables::ES_UNDEFINED;

  std::ifstream analyze(strSourceFilename.c_str(), std::ios::binary);
  if(!analyze) {
    T_ERROR("Could not open %s!", strSourceFilename.c_str());
    return false;
  }
  struct analyze_hdr hdr;

  analyze.read(reinterpret_cast<char*>(&hdr.hdr_size), 4);
  analyze.read(hdr.data_type, 10);
  analyze.read(hdr.db_name, 18);
  analyze.read(reinterpret_cast<char*>(&hdr.extents), 4);
  analyze.read(reinterpret_cast<char*>(&hdr.session_err), 2);
  analyze.read(&hdr.regular, 1);
  analyze.read(&hdr.hkey_un0, 1);
  short num_dimensions;
  analyze.read(reinterpret_cast<char*>(&num_dimensions), 2);
  if(num_dimensions <= 2) {
    T_ERROR("%dd data; must have at least 3 dimensions!");
    return false;
  }
  for(size_t i=0; i < 7; ++i) {
    analyze.read(reinterpret_cast<char*>(&hdr.dim[i]), 2);
  }
  // 14 bytes of unused garbage.
  analyze.seekg(14, std::ios_base::cur);
  analyze.read(reinterpret_cast<char*>(&hdr.datatype), 2); // DT_xxx ..
  analyze.read(reinterpret_cast<char*>(&hdr.bpp), 2);
  analyze.seekg(2, std::ios_base::cur); // "dim_un0", unused.
  float num_aspect;
  analyze.read(reinterpret_cast<char*>(&num_aspect), 4);
  analyze.read(reinterpret_cast<char*>(&hdr.aspect[0]), 4);
  analyze.read(reinterpret_cast<char*>(&hdr.aspect[1]), 4);
  analyze.read(reinterpret_cast<char*>(&hdr.aspect[2]), 4);
  analyze.seekg(12, std::ios_base::cur); // 4 unused aspect values
  // 'voxel_offset' really is a float that stores a byte offset.  Seriously.
  // Maybe some of the same people that wrote DICOM made Analyze as well.
  analyze.read(reinterpret_cast<char*>(&hdr.voxel_offset), 4);

  // The header size was meant to be used in case the analyze format
  // was extended.  It never was.  Thus the headers are always 348
  // bytes.  This provides a convenient check for endianness; if the
  // size isn't 348, then we need to endian convert everything.
  bConvertEndianness = false;
  if(hdr.hdr_size != 348) {
    MESSAGE("Endianness is wrong, swapping...");
    bConvertEndianness = true;
    hdr.bpp = EndianConvert::Swap<short>(hdr.bpp);
    hdr.dim[0] = EndianConvert::Swap<short>(hdr.dim[0]);
    hdr.dim[1] = EndianConvert::Swap<short>(hdr.dim[1]);
    hdr.dim[2] = EndianConvert::Swap<short>(hdr.dim[2]);
    hdr.aspect[0] = EndianConvert::Swap<float>(hdr.aspect[0]);
    hdr.aspect[1] = EndianConvert::Swap<float>(hdr.aspect[1]);
    hdr.aspect[2] = EndianConvert::Swap<float>(hdr.aspect[2]);
    hdr.voxel_offset = EndianConvert::Swap<float>(hdr.voxel_offset);
    hdr.datatype = EndianConvert::Swap<short>(hdr.datatype);
  }

  iComponentCount = 1; // always, I guess?
  iComponentSize = hdr.bpp;
  vVolumeSize = UINT64VECTOR3(hdr.dim[0], hdr.dim[1], hdr.dim[2]);
  vVolumeAspect = FLOATVECTOR3(hdr.aspect[0], hdr.aspect[1], hdr.aspect[2]);
  MESSAGE("%gx%gx%g aspect ratio", vVolumeAspect[0], vVolumeAspect[1],
          vVolumeAspect[2]);
  MESSAGE("%llu-bit %llux%llux%llu data.", iComponentSize,
          vVolumeSize[0], vVolumeSize[1], vVolumeSize[2]);
  {
    UINT64 bits=0;
    switch(hdr.datatype) {
      case DT_BINARY:        bits =  1;
                             bSigned = false;
                             bIsFloat = false;
                             MESSAGE("binary");
                             break;
      case DT_UNSIGNED_CHAR: bits =  8;
                             bSigned = false;
                             bIsFloat = false;
                             MESSAGE("uchar");
                             break;
      case DT_SIGNED_SHORT:  bits = 16;
                             bSigned = true;
                             bIsFloat = false;
                             MESSAGE("signed short");
                             break;
      case DT_SIGNED_INT:    bits = 32;
                             bSigned = true;
                             bIsFloat = false;
                             MESSAGE("int");
                             break;
      case DT_FLOAT:         bits = 32;
                             bSigned = true;
                             bIsFloat = true;
                             MESSAGE("float");
                             break;
      case DT_COMPLEX:
        T_ERROR("Don't know how to handle complex data.");
        return false;
        break;
      case DT_DOUBLE:        bits = 64;
                             bSigned = true;
                             bIsFloat = true;
                             MESSAGE("double");
                             break;
      default:
        WARNING("Unknown data type.");
        bits = 0;
        break;
    }
    if(iComponentSize != bits) {
      T_ERROR("Bits per pixel and data type disagree!  Broken file?");
      analyze.close();
      return false;
    }
  }

  // If the voxel offset is negative, then there is padding between every slice
  // in the data set.  We would need to write an intermediate file to handle
  // that; instead, we just don't handle it.
  if(hdr.voxel_offset < 0.0) {
    analyze.close();
    T_ERROR("Analyze voxel offset is negative (%g).  Intermediate file "
            "required; this converter is broken.");
    return false;
  }
  iHeaderSkip = static_cast<UINT64>(hdr.voxel_offset);
  MESSAGE("Skipping %llu bytes.", iHeaderSkip);

  strIntermediateFile = SysTools::RemoveExt(strSourceFilename) + ".img";
  MESSAGE("Using intermediate file %s", strIntermediateFile.c_str());
  bDeleteIntermediateFile = false;

  return true;
}

bool AnalyzeConverter::ConvertToNative(const std::string&,
                                       const std::string&,
                                       UINT64,
                                       UINT64,
                                       UINT64, bool,
                                       bool,
                                       UINT64VECTOR3,
                                       FLOATVECTOR3,
                                       bool,
                                       const bool)
{
  return false;
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#include <comphelper/random.hxx>
#include <svx/sdrpaintwindow.hxx>
#include <sdr/overlay/overlaymanagerbuffered.hxx>
#include <svx/svdpntv.hxx>
#include <vcl/gdimtf.hxx>
#include <vcl/svapp.hxx>
#include <vcl/settings.hxx>
#include <set>
#include <vector>

//rhbz#1007697 do this in two loops, one to collect the candidates
//and another to update them because updating a candidate can
//trigger the candidate to be deleted, so asking for its
//sibling after that is going to fail hard
class CandidateMgr
{
    std::vector<VclPtr<vcl::Window> > m_aCandidates;
    std::set<VclPtr<vcl::Window> > m_aDeletedCandidates;
    DECL_LINK(WindowEventListener, VclSimpleEvent*);
public:
    void PaintTransparentChildren(vcl::Window & rWindow, Rectangle const& rPixelRect);
    ~CandidateMgr();
};

IMPL_LINK(CandidateMgr, WindowEventListener, VclSimpleEvent*, pEvent)
{
    VclWindowEvent* pWinEvent = dynamic_cast< VclWindowEvent* >( pEvent );
    if (pWinEvent)
    {
        vcl::Window* pWindow = pWinEvent->GetWindow();
        if (pWinEvent->GetId() == VCLEVENT_OBJECT_DYING)
        {
            m_aDeletedCandidates.insert(pWindow);
        }
    }

    return 0;
}

CandidateMgr::~CandidateMgr()
{
    for (auto aI = m_aCandidates.begin(); aI != m_aCandidates.end(); ++aI)
    {
        VclPtr<vcl::Window> pCandidate = *aI;
        if (m_aDeletedCandidates.find(pCandidate) != m_aDeletedCandidates.end())
            continue;
        pCandidate->RemoveEventListener(LINK(this, CandidateMgr, WindowEventListener));
    }
}

void PaintTransparentChildren(vcl::Window & rWindow, Rectangle const& rPixelRect)
{
    if (!rWindow.IsChildTransparentModeEnabled())
        return;

    CandidateMgr aManager;
    aManager.PaintTransparentChildren(rWindow, rPixelRect);
}

void CandidateMgr::PaintTransparentChildren(vcl::Window & rWindow, Rectangle const& rPixelRect)
{
    vcl::Window * pCandidate = rWindow.GetWindow( GetWindowType::FirstChild );
    while (pCandidate)
    {
        if (pCandidate->IsPaintTransparent())
        {
            const Rectangle aCandidatePosSizePixel(
                            pCandidate->GetPosPixel(),
                            pCandidate->GetSizePixel());

            if (aCandidatePosSizePixel.IsOver(rPixelRect))
            {
                m_aCandidates.push_back(pCandidate);
                pCandidate->AddEventListener(LINK(this, CandidateMgr, WindowEventListener));
            }
        }
        pCandidate = pCandidate->GetWindow( GetWindowType::Next );
    }

    for (auto aI = m_aCandidates.begin(); aI != m_aCandidates.end(); ++aI)
    {
        pCandidate = *aI;
        if (m_aDeletedCandidates.find(pCandidate) != m_aDeletedCandidates.end())
            continue;
        //rhbz#1007697 this can cause the window itself to be
        //deleted. So we are listening to see if that happens
        //and if so, then skip the update
        pCandidate->Invalidate(InvalidateFlags::NoTransparent|InvalidateFlags::Children);
        // important: actually paint the child here!
        if (m_aDeletedCandidates.find(pCandidate) != m_aDeletedCandidates.end())
            continue;
        pCandidate->Update();
    }
}

SdrPreRenderDevice::SdrPreRenderDevice(OutputDevice& rOriginal)
:   mrOutputDevice(rOriginal),
    mpPreRenderDevice(VclPtr<VirtualDevice>::Create())
{
}

SdrPreRenderDevice::~SdrPreRenderDevice()
{
    mpPreRenderDevice.disposeAndClear();
}

void SdrPreRenderDevice::PreparePreRenderDevice()
{
    // compare size of mpPreRenderDevice with size of visible area
    if(mpPreRenderDevice->GetOutputSizePixel() != mrOutputDevice.GetOutputSizePixel())
    {
        mpPreRenderDevice->SetOutputSizePixel(mrOutputDevice.GetOutputSizePixel());
    }

    // Also compare the MapModes for zoom/scroll changes
    if(mpPreRenderDevice->GetMapMode() != mrOutputDevice.GetMapMode())
    {
        mpPreRenderDevice->SetMapMode(mrOutputDevice.GetMapMode());
    }

    // #i29186#
    mpPreRenderDevice->SetDrawMode(mrOutputDevice.GetDrawMode());
    mpPreRenderDevice->SetSettings(mrOutputDevice.GetSettings());
}

void SdrPreRenderDevice::OutputPreRenderDevice(const vcl::Region& rExpandedRegion)
{
    // region to pixels
    const vcl::Region aRegionPixel(mrOutputDevice.LogicToPixel(rExpandedRegion));
    //RegionHandle aRegionHandle(aRegionPixel.BeginEnumRects());
    //Rectangle aRegionRectanglePixel;

    // MapModes off
    bool bMapModeWasEnabledDest(mrOutputDevice.IsMapModeEnabled());
    bool bMapModeWasEnabledSource(mpPreRenderDevice->IsMapModeEnabled());
    mrOutputDevice.EnableMapMode(false);
    mpPreRenderDevice->EnableMapMode(false);

    RectangleVector aRectangles;
    aRegionPixel.GetRegionRectangles(aRectangles);

    for(RectangleVector::const_iterator aRectIter(aRectangles.begin()); aRectIter != aRectangles.end(); ++aRectIter)
    {
        // for each rectangle, copy the area
        const Point aTopLeft(aRectIter->TopLeft());
        const Size aSize(aRectIter->GetSize());

        mrOutputDevice.DrawOutDev(
            aTopLeft, aSize,
            aTopLeft, aSize,
            *mpPreRenderDevice.get());

#ifdef DBG_UTIL
        // #i74769#
        static bool bDoPaintForVisualControlRegion(false);

        if(bDoPaintForVisualControlRegion)
        {
            int nR = comphelper::rng::uniform_int_distribution(0, 0x7F-1);
            int nG = comphelper::rng::uniform_int_distribution(0, 0x7F-1);
            int nB = comphelper::rng::uniform_int_distribution(0, 0x7F-1);
            const Color aColor(((((nR|0x80)<<8L)|(nG|0x80))<<8L)|(nB|0x80));

            mrOutputDevice.SetLineColor(aColor);
            mrOutputDevice.SetFillColor();
            mrOutputDevice.DrawRect(*aRectIter);
        }
#endif
    }

    mrOutputDevice.EnableMapMode(bMapModeWasEnabledDest);
    mpPreRenderDevice->EnableMapMode(bMapModeWasEnabledSource);
}

void SdrPaintWindow::impCreateOverlayManager()
{
    // not yet one created?
    if(!mxOverlayManager.is())
    {
        // is it a window?
        if(OUTDEV_WINDOW == GetOutputDevice().GetOutDevType())
        {
            vcl::Window* pWindow = dynamic_cast<vcl::Window*>(&GetOutputDevice());
            // decide which OverlayManager to use
            if(GetPaintView().IsBufferedOverlayAllowed() && mbUseBuffer && !pWindow->SupportsDoubleBuffering())
            {
                // buffered OverlayManager, buffers its background and refreshes from there
                // for pure overlay changes (no system redraw). The 3rd parameter specifies
                // whether that refresh itself will use a 2nd vdev to avoid flickering.
                // Also hand over the old OverlayManager if existent; this means to take over
                // the registered OverlayObjects from it
                mxOverlayManager = sdr::overlay::OverlayManagerBuffered::create(GetOutputDevice(), GetPaintView().GetModel(), true);
            }
            else
            {
                // unbuffered OverlayManager, just invalidates places where changes
                // take place
                // Also hand over the old OverlayManager if existent; this means to take over
                // the registered OverlayObjects from it
                mxOverlayManager = sdr::overlay::OverlayManager::create(GetOutputDevice(), GetPaintView().GetModel());
            }

            OSL_ENSURE(mxOverlayManager.is(), "SdrPaintWindow::SdrPaintWindow: Could not allocate an overlayManager (!)");

            // Request a repaint so that the buffered overlay manager fills
            // its buffer properly.  This is a workaround for missing buffer
            // updates.
            if (pWindow != NULL)
                pWindow->Invalidate();

            Color aColA(GetPaintView().getOptionsDrawinglayer().GetStripeColorA());
            Color aColB(GetPaintView().getOptionsDrawinglayer().GetStripeColorB());

            if(Application::GetSettings().GetStyleSettings().GetHighContrastMode())
            {
                aColA = aColB = Application::GetSettings().GetStyleSettings().GetHighlightColor();
                aColB.Invert();
            }

            mxOverlayManager->setStripeColorA(aColA);
            mxOverlayManager->setStripeColorB(aColB);
            mxOverlayManager->setStripeLengthPixel(GetPaintView().getOptionsDrawinglayer().GetStripeLength());
        }
    }
}

SdrPaintWindow::SdrPaintWindow(SdrPaintView& rNewPaintView, OutputDevice& rOut)
:   mrOutputDevice(rOut),
    mrPaintView(rNewPaintView),
    mpPreRenderDevice(0L),
    mbTemporaryTarget(false), // #i72889#
    mbUseBuffer(true)
{
}

SdrPaintWindow::~SdrPaintWindow()
{
    mxOverlayManager.clear();

    DestroyPreRenderDevice();
}

rtl::Reference< sdr::overlay::OverlayManager > SdrPaintWindow::GetOverlayManager() const
{
    if(!mxOverlayManager.is())
    {
        // Create buffered overlay manager by default.
        const_cast< SdrPaintWindow* >(this)->impCreateOverlayManager();
    }

    return mxOverlayManager;
}

Rectangle SdrPaintWindow::GetVisibleArea() const
{
    Size aVisSizePixel(GetOutputDevice().GetOutputSizePixel());
    return Rectangle(GetOutputDevice().PixelToLogic(Rectangle(Point(0,0), aVisSizePixel)));
}

bool SdrPaintWindow::OutputToRecordingMetaFile() const
{
    GDIMetaFile* pMetaFile = mrOutputDevice.GetConnectMetaFile();
    return (pMetaFile && pMetaFile->IsRecord() && !pMetaFile->IsPause());
}

void SdrPaintWindow::PreparePreRenderDevice()
{
    const bool bPrepareBufferedOutput(
        mrPaintView.IsBufferedOutputAllowed()
        && !OutputToPrinter()
        && !OutputToVirtualDevice()
        && !OutputToRecordingMetaFile());

    if(bPrepareBufferedOutput)
    {
        if(!mpPreRenderDevice)
        {
            mpPreRenderDevice = new SdrPreRenderDevice(mrOutputDevice);
        }
    }
    else
    {
        DestroyPreRenderDevice();
    }

    if(mpPreRenderDevice)
    {
        mpPreRenderDevice->PreparePreRenderDevice();
    }
}

void SdrPaintWindow::DestroyPreRenderDevice()
{
    if(mpPreRenderDevice)
    {
        delete mpPreRenderDevice;
        mpPreRenderDevice = 0L;
    }
}

void SdrPaintWindow::OutputPreRenderDevice(const vcl::Region& rExpandedRegion)
{
    if(mpPreRenderDevice)
    {
        mpPreRenderDevice->OutputPreRenderDevice(rExpandedRegion);
    }
}

// #i73602# add flag if buffer shall be used
void SdrPaintWindow::DrawOverlay(const vcl::Region& rRegion)
{
    // ## force creation of OverlayManager since the first repaint needs to
    // save the background to get a controlled start into overlay mechanism
    impCreateOverlayManager();

    if(mxOverlayManager.is() && !OutputToPrinter())
    {
        if(mpPreRenderDevice)
        {
            mxOverlayManager->completeRedraw(rRegion, &mpPreRenderDevice->GetPreRenderDevice());
        }
        else
        {
            mxOverlayManager->completeRedraw(rRegion);
        }
    }
}

void SdrPaintWindow::SetRedrawRegion(const vcl::Region& rNew)
{
    maRedrawRegion = rNew;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>coverity#1309261 Unchecked dynamic_cast<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#include <comphelper/random.hxx>
#include <svx/sdrpaintwindow.hxx>
#include <sdr/overlay/overlaymanagerbuffered.hxx>
#include <svx/svdpntv.hxx>
#include <vcl/gdimtf.hxx>
#include <vcl/svapp.hxx>
#include <vcl/settings.hxx>
#include <set>
#include <vector>

//rhbz#1007697 do this in two loops, one to collect the candidates
//and another to update them because updating a candidate can
//trigger the candidate to be deleted, so asking for its
//sibling after that is going to fail hard
class CandidateMgr
{
    std::vector<VclPtr<vcl::Window> > m_aCandidates;
    std::set<VclPtr<vcl::Window> > m_aDeletedCandidates;
    DECL_LINK(WindowEventListener, VclSimpleEvent*);
public:
    void PaintTransparentChildren(vcl::Window & rWindow, Rectangle const& rPixelRect);
    ~CandidateMgr();
};

IMPL_LINK(CandidateMgr, WindowEventListener, VclSimpleEvent*, pEvent)
{
    VclWindowEvent* pWinEvent = dynamic_cast< VclWindowEvent* >( pEvent );
    if (pWinEvent)
    {
        vcl::Window* pWindow = pWinEvent->GetWindow();
        if (pWinEvent->GetId() == VCLEVENT_OBJECT_DYING)
        {
            m_aDeletedCandidates.insert(pWindow);
        }
    }

    return 0;
}

CandidateMgr::~CandidateMgr()
{
    for (auto aI = m_aCandidates.begin(); aI != m_aCandidates.end(); ++aI)
    {
        VclPtr<vcl::Window> pCandidate = *aI;
        if (m_aDeletedCandidates.find(pCandidate) != m_aDeletedCandidates.end())
            continue;
        pCandidate->RemoveEventListener(LINK(this, CandidateMgr, WindowEventListener));
    }
}

void PaintTransparentChildren(vcl::Window & rWindow, Rectangle const& rPixelRect)
{
    if (!rWindow.IsChildTransparentModeEnabled())
        return;

    CandidateMgr aManager;
    aManager.PaintTransparentChildren(rWindow, rPixelRect);
}

void CandidateMgr::PaintTransparentChildren(vcl::Window & rWindow, Rectangle const& rPixelRect)
{
    vcl::Window * pCandidate = rWindow.GetWindow( GetWindowType::FirstChild );
    while (pCandidate)
    {
        if (pCandidate->IsPaintTransparent())
        {
            const Rectangle aCandidatePosSizePixel(
                            pCandidate->GetPosPixel(),
                            pCandidate->GetSizePixel());

            if (aCandidatePosSizePixel.IsOver(rPixelRect))
            {
                m_aCandidates.push_back(pCandidate);
                pCandidate->AddEventListener(LINK(this, CandidateMgr, WindowEventListener));
            }
        }
        pCandidate = pCandidate->GetWindow( GetWindowType::Next );
    }

    for (auto aI = m_aCandidates.begin(); aI != m_aCandidates.end(); ++aI)
    {
        pCandidate = *aI;
        if (m_aDeletedCandidates.find(pCandidate) != m_aDeletedCandidates.end())
            continue;
        //rhbz#1007697 this can cause the window itself to be
        //deleted. So we are listening to see if that happens
        //and if so, then skip the update
        pCandidate->Invalidate(InvalidateFlags::NoTransparent|InvalidateFlags::Children);
        // important: actually paint the child here!
        if (m_aDeletedCandidates.find(pCandidate) != m_aDeletedCandidates.end())
            continue;
        pCandidate->Update();
    }
}

SdrPreRenderDevice::SdrPreRenderDevice(OutputDevice& rOriginal)
:   mrOutputDevice(rOriginal),
    mpPreRenderDevice(VclPtr<VirtualDevice>::Create())
{
}

SdrPreRenderDevice::~SdrPreRenderDevice()
{
    mpPreRenderDevice.disposeAndClear();
}

void SdrPreRenderDevice::PreparePreRenderDevice()
{
    // compare size of mpPreRenderDevice with size of visible area
    if(mpPreRenderDevice->GetOutputSizePixel() != mrOutputDevice.GetOutputSizePixel())
    {
        mpPreRenderDevice->SetOutputSizePixel(mrOutputDevice.GetOutputSizePixel());
    }

    // Also compare the MapModes for zoom/scroll changes
    if(mpPreRenderDevice->GetMapMode() != mrOutputDevice.GetMapMode())
    {
        mpPreRenderDevice->SetMapMode(mrOutputDevice.GetMapMode());
    }

    // #i29186#
    mpPreRenderDevice->SetDrawMode(mrOutputDevice.GetDrawMode());
    mpPreRenderDevice->SetSettings(mrOutputDevice.GetSettings());
}

void SdrPreRenderDevice::OutputPreRenderDevice(const vcl::Region& rExpandedRegion)
{
    // region to pixels
    const vcl::Region aRegionPixel(mrOutputDevice.LogicToPixel(rExpandedRegion));
    //RegionHandle aRegionHandle(aRegionPixel.BeginEnumRects());
    //Rectangle aRegionRectanglePixel;

    // MapModes off
    bool bMapModeWasEnabledDest(mrOutputDevice.IsMapModeEnabled());
    bool bMapModeWasEnabledSource(mpPreRenderDevice->IsMapModeEnabled());
    mrOutputDevice.EnableMapMode(false);
    mpPreRenderDevice->EnableMapMode(false);

    RectangleVector aRectangles;
    aRegionPixel.GetRegionRectangles(aRectangles);

    for(RectangleVector::const_iterator aRectIter(aRectangles.begin()); aRectIter != aRectangles.end(); ++aRectIter)
    {
        // for each rectangle, copy the area
        const Point aTopLeft(aRectIter->TopLeft());
        const Size aSize(aRectIter->GetSize());

        mrOutputDevice.DrawOutDev(
            aTopLeft, aSize,
            aTopLeft, aSize,
            *mpPreRenderDevice.get());

#ifdef DBG_UTIL
        // #i74769#
        static bool bDoPaintForVisualControlRegion(false);

        if(bDoPaintForVisualControlRegion)
        {
            int nR = comphelper::rng::uniform_int_distribution(0, 0x7F-1);
            int nG = comphelper::rng::uniform_int_distribution(0, 0x7F-1);
            int nB = comphelper::rng::uniform_int_distribution(0, 0x7F-1);
            const Color aColor(((((nR|0x80)<<8L)|(nG|0x80))<<8L)|(nB|0x80));

            mrOutputDevice.SetLineColor(aColor);
            mrOutputDevice.SetFillColor();
            mrOutputDevice.DrawRect(*aRectIter);
        }
#endif
    }

    mrOutputDevice.EnableMapMode(bMapModeWasEnabledDest);
    mpPreRenderDevice->EnableMapMode(bMapModeWasEnabledSource);
}

void SdrPaintWindow::impCreateOverlayManager()
{
    // not yet one created?
    if(!mxOverlayManager.is())
    {
        // is it a window?
        if(OUTDEV_WINDOW == GetOutputDevice().GetOutDevType())
        {
            vcl::Window& rWindow = dynamic_cast<vcl::Window&>(GetOutputDevice());
            // decide which OverlayManager to use
            if(GetPaintView().IsBufferedOverlayAllowed() && mbUseBuffer && !rWindow.SupportsDoubleBuffering())
            {
                // buffered OverlayManager, buffers its background and refreshes from there
                // for pure overlay changes (no system redraw). The 3rd parameter specifies
                // whether that refresh itself will use a 2nd vdev to avoid flickering.
                // Also hand over the old OverlayManager if existent; this means to take over
                // the registered OverlayObjects from it
                mxOverlayManager = sdr::overlay::OverlayManagerBuffered::create(GetOutputDevice(), GetPaintView().GetModel(), true);
            }
            else
            {
                // unbuffered OverlayManager, just invalidates places where changes
                // take place
                // Also hand over the old OverlayManager if existent; this means to take over
                // the registered OverlayObjects from it
                mxOverlayManager = sdr::overlay::OverlayManager::create(GetOutputDevice(), GetPaintView().GetModel());
            }

            OSL_ENSURE(mxOverlayManager.is(), "SdrPaintWindow::SdrPaintWindow: Could not allocate an overlayManager (!)");

            // Request a repaint so that the buffered overlay manager fills
            // its buffer properly.  This is a workaround for missing buffer
            // updates.
            rWindow.Invalidate();

            Color aColA(GetPaintView().getOptionsDrawinglayer().GetStripeColorA());
            Color aColB(GetPaintView().getOptionsDrawinglayer().GetStripeColorB());

            if(Application::GetSettings().GetStyleSettings().GetHighContrastMode())
            {
                aColA = aColB = Application::GetSettings().GetStyleSettings().GetHighlightColor();
                aColB.Invert();
            }

            mxOverlayManager->setStripeColorA(aColA);
            mxOverlayManager->setStripeColorB(aColB);
            mxOverlayManager->setStripeLengthPixel(GetPaintView().getOptionsDrawinglayer().GetStripeLength());
        }
    }
}

SdrPaintWindow::SdrPaintWindow(SdrPaintView& rNewPaintView, OutputDevice& rOut)
:   mrOutputDevice(rOut),
    mrPaintView(rNewPaintView),
    mpPreRenderDevice(0L),
    mbTemporaryTarget(false), // #i72889#
    mbUseBuffer(true)
{
}

SdrPaintWindow::~SdrPaintWindow()
{
    mxOverlayManager.clear();

    DestroyPreRenderDevice();
}

rtl::Reference< sdr::overlay::OverlayManager > SdrPaintWindow::GetOverlayManager() const
{
    if(!mxOverlayManager.is())
    {
        // Create buffered overlay manager by default.
        const_cast< SdrPaintWindow* >(this)->impCreateOverlayManager();
    }

    return mxOverlayManager;
}

Rectangle SdrPaintWindow::GetVisibleArea() const
{
    Size aVisSizePixel(GetOutputDevice().GetOutputSizePixel());
    return Rectangle(GetOutputDevice().PixelToLogic(Rectangle(Point(0,0), aVisSizePixel)));
}

bool SdrPaintWindow::OutputToRecordingMetaFile() const
{
    GDIMetaFile* pMetaFile = mrOutputDevice.GetConnectMetaFile();
    return (pMetaFile && pMetaFile->IsRecord() && !pMetaFile->IsPause());
}

void SdrPaintWindow::PreparePreRenderDevice()
{
    const bool bPrepareBufferedOutput(
        mrPaintView.IsBufferedOutputAllowed()
        && !OutputToPrinter()
        && !OutputToVirtualDevice()
        && !OutputToRecordingMetaFile());

    if(bPrepareBufferedOutput)
    {
        if(!mpPreRenderDevice)
        {
            mpPreRenderDevice = new SdrPreRenderDevice(mrOutputDevice);
        }
    }
    else
    {
        DestroyPreRenderDevice();
    }

    if(mpPreRenderDevice)
    {
        mpPreRenderDevice->PreparePreRenderDevice();
    }
}

void SdrPaintWindow::DestroyPreRenderDevice()
{
    if(mpPreRenderDevice)
    {
        delete mpPreRenderDevice;
        mpPreRenderDevice = 0L;
    }
}

void SdrPaintWindow::OutputPreRenderDevice(const vcl::Region& rExpandedRegion)
{
    if(mpPreRenderDevice)
    {
        mpPreRenderDevice->OutputPreRenderDevice(rExpandedRegion);
    }
}

// #i73602# add flag if buffer shall be used
void SdrPaintWindow::DrawOverlay(const vcl::Region& rRegion)
{
    // ## force creation of OverlayManager since the first repaint needs to
    // save the background to get a controlled start into overlay mechanism
    impCreateOverlayManager();

    if(mxOverlayManager.is() && !OutputToPrinter())
    {
        if(mpPreRenderDevice)
        {
            mxOverlayManager->completeRedraw(rRegion, &mpPreRenderDevice->GetPreRenderDevice());
        }
        else
        {
            mxOverlayManager->completeRedraw(rRegion);
        }
    }
}

void SdrPaintWindow::SetRedrawRegion(const vcl::Region& rNew)
{
    maRedrawRegion = rNew;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>#include <iostream>
#include <random>
#include <fstream>
#include <cstdlib>
#include <cmath>
#include <algorithm>

int main(int argc, char *argv[]){

  int SEED = atoi(argv[1]);  // Seed
  int N = atoi(argv[2]);     // Number of nodes
  int M = atoi(argv[3]);     // Number of nodes

  int m0 = 5;                // Initial number of nodes
  double alpha = 1.;         // Switching probability

  // Random generators
  std::default_random_engine generator;
  std::uniform_real_distribution<double> ureal(0., 1.);

  // Connections
  std::vector<std::vector<int>> edge_list(N);

  // Index variables
  int i, j, k;

  // Connecting the initial core
  for ( j = 0; j < m0; j++ )
  {
    for ( i = j+1; i < m0; i++ )
    {
      edge_list[i].push_back(j);
      edge_list[j].push_back(i);
    }
  }

  // Growing the network
  for ( j = m0; j < N; j++)
  {

    if ( ureal(generator) <= alpha)
    {

      // Erdos-Renyi branch

      for ( k = 0; k < M; k++ )
      {
	// Choosing a pair
	i = (j-1)*ureal(generator);
	edge_list[i].push_back(j);
	edge_list[j].push_back(i);
      }

    }
    else {

      // Barabasi-Albert branch

    }
  }

  std::ofstream outFile;

  outFile.open(argv[4]);

  for(int k = 0; k < N; k++)
    for(std::vector<int>::iterator it = edge_list[k].begin(); it != edge_list[k].end(); ++it)
      outFile << k << " " << *it << std::endl;

  outFile.close();

  return 0;
}
<commit_msg>Added malloc<commit_after>#include <iostream>
#include <random>
#include <fstream>
#include <cstdlib>
#include <cmath>
#include <algorithm>

int main(int argc, char *argv[]){

  int SEED = atoi(argv[1]);  // Seed
  int N = atoi(argv[2]);     // Number of nodes
  int M = atoi(argv[3]);     // Number of nodes
  double *V;
  V = (double *) malloc(N*sizeof(double));

  int m0 = 5;                // Initial number of nodes
  double alpha = 1.;         // Switching probability

  // Random generators
  std::default_random_engine generator;
  std::uniform_real_distribution<double> ureal(0., 1.);

  // Connections
  std::vector<std::vector<int>> edge_list(N);

  // Index variables
  int i, j, k;

  // Connecting the initial core
  for ( j = 0; j < m0; j++ )
  {
    for ( i = j+1; i < m0; i++ )
    {
      edge_list[i].push_back(j);
      edge_list[j].push_back(i);
    }
  }

  // Growing the network
  for ( j = m0; j < N; j++)
  {

    if ( ureal(generator) <= alpha)
    {

      // Erdos-Renyi branch

      for ( k = 0; k < M; k++ )
      {
	// Choosing a pair
	i = (j-1)*ureal(generator);
	edge_list[i].push_back(j);
	edge_list[j].push_back(i);
      }

    }
    else {

      // Barabasi-Albert branch

    }
  }

  std::ofstream outFile;

  outFile.open(argv[4]);

  for(int k = 0; k < N; k++)
    for(std::vector<int>::iterator it = edge_list[k].begin(); it != edge_list[k].end(); ++it)
      outFile << k << " " << *it << std::endl;

  outFile.close();

  return 0;
}
<|endoftext|>


<commit_before>// Time:  O(n)
// Space: O(n)

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
class Solution {
 public:
    /**
     * @param A: Given an integer array with no duplicates.
     * @return: The root of max tree.
     */
    TreeNode* maxTree(vector<int> A) {
        if (A.empty()) {
            return NULL;
        }

        stack<TreeNode *> nodeStack;
        nodeStack.push(new TreeNode(A[0]));
        for (int i = 1; i < A.size(); ++i) {
            // The stack stores nodes in descending order.
            if (A[i] <= nodeStack.top()->val) {
                TreeNode *node = new TreeNode(A[i]);
                nodeStack.push(node);
            } else {
                // Pop every node which value is less than A[i],
                // and let them as right children of
                // the last node less than A[i]
                TreeNode *smaller_node = nodeStack.top();
                nodeStack.pop();
                while (!nodeStack.empty() && nodeStack.top()->val < A[i]) {
                    nodeStack.top()->right = smaller_node;
                    smaller_node = nodeStack.top();
                    nodeStack.pop();
                }

                // Pop the last node which value is less
                // than A[i], and let it as right child,
                // and push A[i] to the stack.
                TreeNode *node = new TreeNode(A[i]);
                node->left = smaller_node;
                nodeStack.push(node);
            }
        }

        // Pop every node in the stack,
        // and let them as right children of the root
        TreeNode *root = nodeStack.top();
        nodeStack.pop();
        while (!nodeStack.empty()) {
            nodeStack.top()->right = root;
            root = nodeStack.top();
            nodeStack.pop();
        }

        return root;
    }
};
<commit_msg>update<commit_after>// Time:  O(n)
// Space: O(n)

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
class Solution {
 public:
    /**
     * @param A: Given an integer array with no duplicates.
     * @return: The root of max tree.
     */
    TreeNode* maxTree(vector<int> A) {
        if (A.empty()) {
            return nullptr;
        }

        stack<TreeNode *> nodeStack;
        nodeStack.emplace(new TreeNode(A[0]));
        for (int i = 1; i < A.size(); ++i) {
            // The stack stores nodes in descending order.
            if (A[i] <= nodeStack.top()->val) {
                TreeNode *node = new TreeNode(A[i]);
                nodeStack.emplace(node);
            } else {
                // Pop every node which value is less than A[i],
                // and let them as right children of
                // the last node less than A[i]
                TreeNode *smaller_node = nodeStack.top();
                nodeStack.pop();
                while (!nodeStack.empty() && nodeStack.top()->val < A[i]) {
                    nodeStack.top()->right = smaller_node;
                    smaller_node = nodeStack.top();
                    nodeStack.pop();
                }

                // Pop the last node which value is less
                // than A[i], and let it as right child,
                // and push A[i] to the stack.
                TreeNode *node = new TreeNode(A[i]);
                node->left = smaller_node;
                nodeStack.emplace(node);
            }
        }

        // Pop every node in the stack,
        // and let them as right children of the root
        TreeNode *root = nodeStack.top();
        nodeStack.pop();
        while (!nodeStack.empty()) {
            nodeStack.top()->right = root;
            root = nodeStack.top();
            nodeStack.pop();
        }

        return root;
    }
};
<|endoftext|>


<commit_before>// Copyright (c) 2017 The e-Gulden Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "oerushield/oerushield.h"

#include "base58.h"
#include "chainparams.h"
#include "oerushield/oerudb.h"
#include "oerushield/oerutx.h"
#include "oerushield/signaturechecker.h"
#include "primitives/block.h"
#include "primitives/transaction.h"
#include "util.h"
#include "utilstrencodings.h"

#include <string>
#include <vector>

const std::vector<unsigned char> COeruShield::OERU_BYTES = { 0x4f, 0x45, 0x52, 0x55 }; // "OERU"
const uint64_t COeruShield::MAX_HEIGHT_DIFFERENCE = 720;

const std::vector<std::vector<unsigned char>> COeruShield::MASTER_KEYS =
{
    ParseHex("1e58eb7273d4ce30e9a961600aaa49871beec551aba5b6f5a5712d6ccd1a8e3a"),
    ParseHex("b752e70e9b8343719491edfb524db6599e21d98269c1e720509636a6bb5db7ba"),
    ParseHex("f6b2c579d2bc9c86603d0689546ca989c543049d5bdd8486c9b72eee4ccca5b1")
};

COeruShield::COeruShield(COeruDB *oeruDB)
{
    this->oeruDB = oeruDB;
}

bool COeruShield::CheckMasterTx(CTransaction tx, int nHeight) const
{
    if (tx.IsCoinBase())
        return false;

    if (tx.vout.size() != 3)
        return false;

    CTxOut masterOut = tx.vout[0];
    CTxOut minerOut = tx.vout[1];
    CTxOut signatureOut = tx.vout[2];

    CBitcoinAddress master;
    if (!GetDestinationAddress(masterOut, master))
        return false;

    if (!IsMasterKey(master))
        return false;

    CBitcoinAddress miner;
    if (!GetDestinationAddress(minerOut, miner))
        return false;

    COeruTxOut masterOeruOut(&signatureOut);
    COeruMasterData masterData;
    if (!masterOeruOut.GetOeruMasterData(masterData))
        return false;

    if (!masterData.IsValid())
        return false;

    uint64_t masterHeight;
    if (!masterData.GetHeight(masterHeight))
        return false;

    if (masterHeight < nHeight - COeruShield::MAX_HEIGHT_DIFFERENCE)
        return false;

    if (!masterData.HasValidSignature(master))
        return false;

    bool enable;
    if (!masterData.GetEnable(enable))
        return false;

    if (enable)
        oeruDB->AddCertifiedAddress(miner);
    else
        oeruDB->RemoveCertifiedAddress(miner);

    return true;
}

bool COeruShield::FindOeruVOut(const CTransaction& coinbaseTx, COeruTxOut& oeruTxOut) const
{
    if (!coinbaseTx.IsCoinBase())
        return false;

    for (auto &vout : coinbaseTx.vout)
    {
        oeruTxOut = COeruTxOut(&vout);

        if (oeruTxOut.HasOeruBytes())
        {
            return true;
        }
    }
    return false;
}

bool COeruShield::GetCoinbaseAddress(const CTransaction& coinbaseTx, CBitcoinAddress& coinbaseAddress) const
{
    if (coinbaseTx.vout.size() < 1)
        return false;

    return GetDestinationAddress(coinbaseTx.vout[0], coinbaseAddress);
}

bool COeruShield::GetCoinbaseTx(const CBlock& block, CTransaction& coinbaseTx) const
{
    if (block.vtx.size() < 1)
        return false;

    coinbaseTx = block.vtx[0];

    if (!coinbaseTx.IsCoinBase())
        return false;

    return true;
}

bool COeruShield::GetDestinationAddress(const CTxOut txOut, CBitcoinAddress &destination) const
{
    CTxDestination txDestination;
    if (!ExtractDestination(txOut.scriptPubKey, txDestination))
        return false;

    destination = CBitcoinAddress(txDestination);
    if (!destination.IsValid())
        return false;

    return true;
}

bool COeruShield::IsActive() const
{
    int minAddresses = Params().OeruShieldMinCertifiedAddresses();
    return oeruDB->NumCertifiedAddresses() >= minAddresses;
}

bool COeruShield::IsBlockIdentified(const CBlock& block, const int nHeight) const
{
    CTransaction coinbaseTx;
    if ( ! GetCoinbaseTx(block, coinbaseTx))
        return false;

    CBitcoinAddress coinbaseAddress;
    if ( ! GetCoinbaseAddress(coinbaseTx, coinbaseAddress))
        return false;

    COeruTxOut oeruTxOut;
    if ( ! FindOeruVOut(coinbaseTx, oeruTxOut)) {
       LogPrint("OeruShield", "%s: No valid oeru vout found\n", __FUNCTION__);
       return false;
    }

    std::vector<unsigned char> vchData;
    if (!oeruTxOut.GetOpReturnData(vchData)) {
       LogPrint("OeruShield", "%s: No OP_RETURN data found\n", __FUNCTION__);
       return false;
    }

    std::vector<unsigned char> vchSig(vchData.begin() + COeruShield::OERU_BYTES.size(), vchData.end());
    std::string strMessage = std::to_string(nHeight);

    CSignatureChecker signatureChecker;
    if (signatureChecker.VerifySignature(strMessage, vchSig, coinbaseAddress)) {
        LogPrint("OeruShield", "%s: Valid OERU signature\n", __FUNCTION__);
        return true;
    } else {
        LogPrint("OeruShield", "%s: No valid OERU signature\n", __FUNCTION__);
        return false;
    }
}

bool COeruShield::IsBlockCertified(const CBlock& block, const int nHeight) const
{
    if ( ! IsBlockIdentified(block, nHeight))
        return false;

    CTransaction coinbaseTx;
    if ( ! GetCoinbaseTx(block, coinbaseTx) || coinbaseTx.vout.size() < 2)
        return false;

    CBitcoinAddress coinbaseAddress;
    if ( ! GetCoinbaseAddress(coinbaseTx, coinbaseAddress))
        return false;

    return oeruDB->IsAddressCertified(coinbaseAddress);
}

bool COeruShield::IsMasterKey(std::vector<unsigned char> addrHash) const
{
    for (auto it = COeruShield::MASTER_KEYS.begin(); it != COeruShield::MASTER_KEYS.end(); ++it)
    {
        if (*it == addrHash)
        {
            return true;
        }
    }

    return false;
}

bool COeruShield::IsMasterKey(CBitcoinAddress addr) const
{
    std::string strAddr = addr.ToString();
    std::vector<unsigned char> hash;
    hash.resize(CSHA256::OUTPUT_SIZE);

    CSHA256().Write((unsigned char*) &strAddr[0], strAddr.size())
        .Finalize(&hash[0]);

    return IsMasterKey(hash);
}
<commit_msg>Switched miner and master out in oeru TX<commit_after>// Copyright (c) 2017 The e-Gulden Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "oerushield/oerushield.h"

#include "base58.h"
#include "chainparams.h"
#include "oerushield/oerudb.h"
#include "oerushield/oerutx.h"
#include "oerushield/signaturechecker.h"
#include "primitives/block.h"
#include "primitives/transaction.h"
#include "util.h"
#include "utilstrencodings.h"

#include <string>
#include <vector>

const std::vector<unsigned char> COeruShield::OERU_BYTES = { 0x4f, 0x45, 0x52, 0x55 }; // "OERU"
const uint64_t COeruShield::MAX_HEIGHT_DIFFERENCE = 720;

const std::vector<std::vector<unsigned char>> COeruShield::MASTER_KEYS =
{
    ParseHex("1e58eb7273d4ce30e9a961600aaa49871beec551aba5b6f5a5712d6ccd1a8e3a"),
    ParseHex("b752e70e9b8343719491edfb524db6599e21d98269c1e720509636a6bb5db7ba"),
    ParseHex("f6b2c579d2bc9c86603d0689546ca989c543049d5bdd8486c9b72eee4ccca5b1")
};

COeruShield::COeruShield(COeruDB *oeruDB)
{
    this->oeruDB = oeruDB;
}

bool COeruShield::CheckMasterTx(CTransaction tx, int nHeight) const
{
    if (tx.IsCoinBase())
        return false;

    if (tx.vout.size() != 3)
        return false;

    CTxOut minerOut = tx.vout[0];
    CTxOut masterOut = tx.vout[1];
    CTxOut signatureOut = tx.vout[2];

    CBitcoinAddress master;
    if (!GetDestinationAddress(masterOut, master))
        return false;

    if (!IsMasterKey(master))
        return false;

    CBitcoinAddress miner;
    if (!GetDestinationAddress(minerOut, miner))
        return false;

    COeruTxOut masterOeruOut(&signatureOut);
    COeruMasterData masterData;
    if (!masterOeruOut.GetOeruMasterData(masterData))
        return false;

    if (!masterData.IsValid())
        return false;

    uint64_t masterHeight;
    if (!masterData.GetHeight(masterHeight))
        return false;

    if (masterHeight < nHeight - COeruShield::MAX_HEIGHT_DIFFERENCE)
        return false;

    if (!masterData.HasValidSignature(master))
        return false;

    bool enable;
    if (!masterData.GetEnable(enable))
        return false;

    if (enable)
        oeruDB->AddCertifiedAddress(miner);
    else
        oeruDB->RemoveCertifiedAddress(miner);

    return true;
}

bool COeruShield::FindOeruVOut(const CTransaction& coinbaseTx, COeruTxOut& oeruTxOut) const
{
    if (!coinbaseTx.IsCoinBase())
        return false;

    for (auto &vout : coinbaseTx.vout)
    {
        oeruTxOut = COeruTxOut(&vout);

        if (oeruTxOut.HasOeruBytes())
        {
            return true;
        }
    }
    return false;
}

bool COeruShield::GetCoinbaseAddress(const CTransaction& coinbaseTx, CBitcoinAddress& coinbaseAddress) const
{
    if (coinbaseTx.vout.size() < 1)
        return false;

    return GetDestinationAddress(coinbaseTx.vout[0], coinbaseAddress);
}

bool COeruShield::GetCoinbaseTx(const CBlock& block, CTransaction& coinbaseTx) const
{
    if (block.vtx.size() < 1)
        return false;

    coinbaseTx = block.vtx[0];

    if (!coinbaseTx.IsCoinBase())
        return false;

    return true;
}

bool COeruShield::GetDestinationAddress(const CTxOut txOut, CBitcoinAddress &destination) const
{
    CTxDestination txDestination;
    if (!ExtractDestination(txOut.scriptPubKey, txDestination))
        return false;

    destination = CBitcoinAddress(txDestination);
    if (!destination.IsValid())
        return false;

    return true;
}

bool COeruShield::IsActive() const
{
    int minAddresses = Params().OeruShieldMinCertifiedAddresses();
    return oeruDB->NumCertifiedAddresses() >= minAddresses;
}

bool COeruShield::IsBlockIdentified(const CBlock& block, const int nHeight) const
{
    CTransaction coinbaseTx;
    if ( ! GetCoinbaseTx(block, coinbaseTx))
        return false;

    CBitcoinAddress coinbaseAddress;
    if ( ! GetCoinbaseAddress(coinbaseTx, coinbaseAddress))
        return false;

    COeruTxOut oeruTxOut;
    if ( ! FindOeruVOut(coinbaseTx, oeruTxOut)) {
       LogPrint("OeruShield", "%s: No valid oeru vout found\n", __FUNCTION__);
       return false;
    }

    std::vector<unsigned char> vchData;
    if (!oeruTxOut.GetOpReturnData(vchData)) {
       LogPrint("OeruShield", "%s: No OP_RETURN data found\n", __FUNCTION__);
       return false;
    }

    std::vector<unsigned char> vchSig(vchData.begin() + COeruShield::OERU_BYTES.size(), vchData.end());
    std::string strMessage = std::to_string(nHeight);

    CSignatureChecker signatureChecker;
    if (signatureChecker.VerifySignature(strMessage, vchSig, coinbaseAddress)) {
        LogPrint("OeruShield", "%s: Valid OERU signature\n", __FUNCTION__);
        return true;
    } else {
        LogPrint("OeruShield", "%s: No valid OERU signature\n", __FUNCTION__);
        return false;
    }
}

bool COeruShield::IsBlockCertified(const CBlock& block, const int nHeight) const
{
    if ( ! IsBlockIdentified(block, nHeight))
        return false;

    CTransaction coinbaseTx;
    if ( ! GetCoinbaseTx(block, coinbaseTx) || coinbaseTx.vout.size() < 2)
        return false;

    CBitcoinAddress coinbaseAddress;
    if ( ! GetCoinbaseAddress(coinbaseTx, coinbaseAddress))
        return false;

    return oeruDB->IsAddressCertified(coinbaseAddress);
}

bool COeruShield::IsMasterKey(std::vector<unsigned char> addrHash) const
{
    for (auto it = COeruShield::MASTER_KEYS.begin(); it != COeruShield::MASTER_KEYS.end(); ++it)
    {
        if (*it == addrHash)
        {
            return true;
        }
    }

    return false;
}

bool COeruShield::IsMasterKey(CBitcoinAddress addr) const
{
    std::string strAddr = addr.ToString();
    std::vector<unsigned char> hash;
    hash.resize(CSHA256::OUTPUT_SIZE);

    CSHA256().Write((unsigned char*) &strAddr[0], strAddr.size())
        .Finalize(&hash[0]);

    return IsMasterKey(hash);
}
<|endoftext|>