<commit_before>#include <gtest/gtest.h>

#include <boost/variant.hpp>
#include <expression.hpp>

using namespace std;
using namespace dcpu;
using namespace dcpu::lexer;
using namespace dcpu::ast;

static logging::log logger;
static location_ptr _location = make_shared<location>("<Test>", 1, 1);

TEST(ExpressionEval, Add) {
	auto expr = expression(binary_operation(_location, binary_operator::PLUS,
		literal_operand(_location, 4),
		literal_operand(_location, 9)));

	EXPECT_EQ(evaluated_expression(_location, 13), evaluate(logger, expr));
}

TEST(ExpressionEval, Subtract) {
	auto expr = expression(binary_operation(_location, binary_operator::MINUS,
		literal_operand(_location, 4),
		literal_operand(_location, 9)));

	EXPECT_EQ(evaluated_expression(_location, -5), evaluate(logger, expr));
}

TEST(ExpressionEval, Multiply) {
	auto expr = expression(binary_operation(_location, binary_operator::MULTIPLY,
		literal_operand(_location, 2),
		literal_operand(_location, 4)));

	EXPECT_EQ(evaluated_expression(_location, 8), evaluate(logger, expr));
}

TEST(ExpressionEval, Divide) {
	auto expr = expression(binary_operation(_location, binary_operator::DIVIDE,
		literal_operand(_location, 8),
		literal_operand(_location, 2)));

	EXPECT_EQ(evaluated_expression(_location, 4), evaluate(logger, expr));

	auto expr2 = expression(binary_operation(_location, binary_operator::DIVIDE,
		literal_operand(_location, 15),
		literal_operand(_location, 4)));

	EXPECT_EQ(evaluated_expression(_location, 3), evaluate(logger, expr2));
}

TEST(ExpressionEval, DivideByZero) {
	stringstream out;
	logging::log capture_log(out);

	auto expr = expression(binary_operation(_location, binary_operator::DIVIDE,
		literal_operand(_location, 8),
		literal_operand(_location, 0)));

	EXPECT_EQ(evaluated_expression(_location, 0), evaluate(capture_log, expr));
	EXPECT_EQ("<Test>:1:1: warning: division or modulo by zero\n", out.str());
}

TEST(ExpressionEval, Modulo) {
	auto expr = expression(binary_operation(_location, binary_operator::MODULO,
		literal_operand(_location, 19),
		literal_operand(_location, 5)));

	EXPECT_EQ(evaluated_expression(_location, 4), evaluate(logger, expr));
}

TEST(ExpressionEval, ShiftLeft) {
	auto expr = expression(binary_operation(_location, binary_operator::SHIFT_LEFT,
		literal_operand(_location, 1),
		literal_operand(_location, 4)));

	EXPECT_EQ(evaluated_expression(_location, 16), evaluate(logger, expr));
}

TEST(ExpressionEval, ShiftRight) {
	auto expr = expression(binary_operation(_location, binary_operator::SHIFT_RIGHT,
		literal_operand(_location, 256),
		literal_operand(_location, 2)));

	EXPECT_EQ(evaluated_expression(_location, 64), evaluate(logger, expr));
}

TEST(ExpressionEval, BitwiseAnd) {
	auto expr = expression(binary_operation(_location, binary_operator::BITWISE_AND,
		literal_operand(_location, 0x9),
		literal_operand(_location, 0xc)));

	EXPECT_EQ(evaluated_expression(_location, 0x8), evaluate(logger, expr));
}

TEST(ExpressionEval, BitwiseXor) {
	auto expr = expression(binary_operation(_location, binary_operator::BITWISE_XOR,
		literal_operand(_location, 0x9),
		literal_operand(_location, 0xc)));

	EXPECT_EQ(evaluated_expression(_location, 0x5), evaluate(logger, expr));
}

TEST(ExpressionEval, BitwiseOr) {
	auto expr = expression(binary_operation(_location, binary_operator::BITWISE_OR,
		literal_operand(_location, 0x9),
		literal_operand(_location, 0xc)));

	EXPECT_EQ(evaluated_expression(_location, 0xd), evaluate(logger, expr));
}

TEST(ExpressionEval, Equals) {
	expression expr1(binary_operation(_location, binary_operator::EQ,
		literal_operand(_location, 19),
		literal_operand(_location, 19)));

	EXPECT_EQ(evaluated_expression(_location, 1), evaluate(logger, expr1));

	expression expr2(binary_operation(_location, binary_operator::EQ,
		literal_operand(_location, 43),
		literal_operand(_location, 17)));

	EXPECT_EQ(evaluated_expression(_location, 0), evaluate(logger, expr2));
}

TEST(ExpressionEval, NotEquals) {
	expression expr1(binary_operation(_location, binary_operator::NEQ,
		literal_operand(_location, 19),
		literal_operand(_location, 10)));

	EXPECT_EQ(evaluated_expression(_location, 1), evaluate(logger, expr1));

	expression expr2(binary_operation(_location, binary_operator::NEQ,
		literal_operand(_location, 43),
		literal_operand(_location, 43)));

	EXPECT_EQ(evaluated_expression(_location, 0), evaluate(logger, expr2));
}

TEST(ExpressionEval, LessThan) {
	expression expr1(binary_operation(_location, binary_operator::LT,
		literal_operand(_location, 8),
		literal_operand(_location, 19)));

	EXPECT_EQ(evaluated_expression(_location, 1), evaluate(logger, expr1));

	expression expr2(binary_operation(_location, binary_operator::LT,
		literal_operand(_location, 43),
		literal_operand(_location, 17)));

	EXPECT_EQ(evaluated_expression(_location, 0), evaluate(logger, expr2));

	expression expr3(binary_operation(_location, binary_operator::LT,
		literal_operand(_location, 17),
		literal_operand(_location, 17)));

	EXPECT_EQ(evaluated_expression(_location, 0), evaluate(logger, expr3));
}

TEST(ExpressionEval, GreaterThan) {
	expression expr1(binary_operation(_location, binary_operator::GT,
		literal_operand(_location, 19),
		literal_operand(_location, 8)));

	EXPECT_EQ(evaluated_expression(_location, 1), evaluate(logger, expr1));

	expression expr2(binary_operation(_location, binary_operator::GT,
		literal_operand(_location, 17),
		literal_operand(_location, 43)));

	EXPECT_EQ(evaluated_expression(_location, 0), evaluate(logger, expr2));

	expression expr3(binary_operation(_location, binary_operator::GT,
		literal_operand(_location, 17),
		literal_operand(_location, 17)));

	EXPECT_EQ(evaluated_expression(_location, 0), evaluate(logger, expr3));
}

TEST(ExpressionEval, LessThanOrEqual) {
	expression expr1(binary_operation(_location, binary_operator::LTE,
		literal_operand(_location, 8),
		literal_operand(_location, 19)));

	EXPECT_EQ(evaluated_expression(_location, 1), evaluate(logger, expr1));

	expression expr2(binary_operation(_location, binary_operator::LTE,
		literal_operand(_location, 43),
		literal_operand(_location, 17)));

	EXPECT_EQ(evaluated_expression(_location, 0), evaluate(logger, expr2));

	expression expr3(binary_operation(_location, binary_operator::LTE,
		literal_operand(_location, 17),
		literal_operand(_location, 17)));

	EXPECT_EQ(evaluated_expression(_location, 1), evaluate(logger, expr3));
}

TEST(ExpressionEval, GreaterThanOrEqual) {
	expression expr1(binary_operation(_location, binary_operator::GTE,
		literal_operand(_location, 19),
		literal_operand(_location, 8)));

	EXPECT_EQ(evaluated_expression(_location, 1), evaluate(logger, expr1));

	expression expr2(binary_operation(_location, binary_operator::GTE,
		literal_operand(_location, 17),
		literal_operand(_location, 43)));

	EXPECT_EQ(evaluated_expression(_location, 0), evaluate(logger, expr2));

	expression expr3(binary_operation(_location, binary_operator::GTE,
		literal_operand(_location, 17),
		literal_operand(_location, 17)));

	EXPECT_EQ(evaluated_expression(_location, 1), evaluate(logger, expr3));
}

TEST(ExpressionEval, BooleanAnd) {
	expression expr1(binary_operation(_location, binary_operator::AND,
		literal_operand(_location, 1),
		literal_operand(_location, 1)));

	EXPECT_EQ(evaluated_expression(_location, 1), evaluate(logger, expr1));

	expression expr2(binary_operation(_location, binary_operator::AND,
		literal_operand(_location, 0),
		literal_operand(_location, 1)));

	EXPECT_EQ(evaluated_expression(_location, 0), evaluate(logger, expr2));

	expression expr3(binary_operation(_location, binary_operator::AND,
		literal_operand(_location, 1),
		literal_operand(_location, 0)));

	EXPECT_EQ(evaluated_expression(_location, 0), evaluate(logger, expr3));

	expression expr4(binary_operation(_location, binary_operator::AND,
		literal_operand(_location, 0),
		literal_operand(_location, 0)));

	EXPECT_EQ(evaluated_expression(_location, 0), evaluate(logger, expr4));
}

TEST(ExpressionEval, BooleanOr) {
	expression expr1(binary_operation(_location, binary_operator::OR,
		literal_operand(_location, 1),
		literal_operand(_location, 1)));

	EXPECT_EQ(evaluated_expression(_location, 1), evaluate(logger, expr1));

	expression expr2(binary_operation(_location, binary_operator::OR,
		literal_operand(_location, 0),
		literal_operand(_location, 1)));

	EXPECT_EQ(evaluated_expression(_location, 1), evaluate(logger, expr2));

	expression expr3(binary_operation(_location, binary_operator::OR,
		literal_operand(_location, 1),
		literal_operand(_location, 0)));

	EXPECT_EQ(evaluated_expression(_location, 1), evaluate(logger, expr3));

	expression expr4(binary_operation(_location, binary_operator::OR,
		literal_operand(_location, 0),
		literal_operand(_location, 0)));

	EXPECT_EQ(evaluated_expression(_location, 0), evaluate(logger, expr4));
}

TEST(ExpressionEval, UnaryMinus) {
	auto expr = expression(unary_operation(_location, unary_operator::MINUS,
		literal_operand(_location, 7)));

	EXPECT_EQ(evaluated_expression(_location, -7), evaluate(logger, expr));
}

TEST(ExpressionEval, UnaryPlus) {
	auto expr = expression(unary_operation(_location, unary_operator::PLUS,
		literal_operand(_location, 7)));

	EXPECT_EQ(evaluated_expression(_location, 7), evaluate(logger, expr));
}

TEST(ExpressionEval, UnaryNot) {
	auto expr = expression(unary_operation(_location, unary_operator::NOT,
		literal_operand(_location, 7)));

	EXPECT_EQ(evaluated_expression(_location, 0), evaluate(logger, expr));

	auto expr2 = expression(unary_operation(_location, unary_operator::NOT,
		literal_operand(_location, 0)));

	EXPECT_EQ(evaluated_expression(_location, 1), evaluate(logger, expr2));
}

TEST(ExpressionEval, UnaryBitwiseNot) {
	auto expr = expression(unary_operation(_location, unary_operator::BITWISE_NOT,
		literal_operand(_location, 7)));

	EXPECT_EQ(evaluated_expression(_location, -8), evaluate(logger, expr));
}

TEST(ExpressionEval, Register) {
	auto expr = expression(binary_operation(_location, binary_operator::PLUS,
		register_operand(_location, registers::A),
		literal_operand(_location, 10)));
	EXPECT_EQ(evaluated_expression(_location, registers::A, 10), evaluate(logger, expr));

	auto expr2 = expression(binary_operation(_location, binary_operator::PLUS,
		literal_operand(_location, 10),
		register_operand(_location, registers::B)));
	EXPECT_EQ(evaluated_expression(_location, registers::B, 10), evaluate(logger, expr2));

	auto expr3 = expression(binary_operation(_location, binary_operator::MINUS,
		register_operand(_location, registers::C),
		literal_operand(_location, 10)));
	EXPECT_EQ(evaluated_expression(_location, registers::C, -10), evaluate(logger, expr3));

	auto expr4 = expression(register_operand(_location, registers::X));
	EXPECT_EQ(evaluated_expression(_location, registers::X), evaluate(logger, expr4));

	auto expr5 = expression(binary_operation(_location, binary_operator::PLUS,
		register_operand(_location, registers::A),
		binary_operation(_location, binary_operator::MULTIPLY,
			literal_operand(_location, 2),
			literal_operand(_location, 4))));
	EXPECT_EQ(evaluated_expression(_location, registers::A, 8), evaluate(logger, expr5));
}
<commit_msg>Updated test to verify divide by zero warning is only printed once<commit_after>#include <gtest/gtest.h>

#include <boost/variant.hpp>
#include <expression.hpp>

using namespace std;
using namespace dcpu;
using namespace dcpu::lexer;
using namespace dcpu::ast;

static logging::log logger;
static location_ptr _location = make_shared<location>("<Test>", 1, 1);

TEST(ExpressionEval, Add) {
	auto expr = expression(binary_operation(_location, binary_operator::PLUS,
		literal_operand(_location, 4),
		literal_operand(_location, 9)));

	EXPECT_EQ(evaluated_expression(_location, 13), evaluate(logger, expr));
}

TEST(ExpressionEval, Subtract) {
	auto expr = expression(binary_operation(_location, binary_operator::MINUS,
		literal_operand(_location, 4),
		literal_operand(_location, 9)));

	EXPECT_EQ(evaluated_expression(_location, -5), evaluate(logger, expr));
}

TEST(ExpressionEval, Multiply) {
	auto expr = expression(binary_operation(_location, binary_operator::MULTIPLY,
		literal_operand(_location, 2),
		literal_operand(_location, 4)));

	EXPECT_EQ(evaluated_expression(_location, 8), evaluate(logger, expr));
}

TEST(ExpressionEval, Divide) {
	auto expr = expression(binary_operation(_location, binary_operator::DIVIDE,
		literal_operand(_location, 8),
		literal_operand(_location, 2)));

	EXPECT_EQ(evaluated_expression(_location, 4), evaluate(logger, expr));

	auto expr2 = expression(binary_operation(_location, binary_operator::DIVIDE,
		literal_operand(_location, 15),
		literal_operand(_location, 4)));

	EXPECT_EQ(evaluated_expression(_location, 3), evaluate(logger, expr2));
}

TEST(ExpressionEval, DivideByZero) {
	stringstream out;
	logging::log capture_log(out);

	auto expr = expression(binary_operation(_location, binary_operator::DIVIDE,
		literal_operand(_location, 8),
		literal_operand(_location, 0)));

	EXPECT_EQ(evaluated_expression(_location, 0), evaluate(capture_log, expr));
	EXPECT_EQ(evaluated_expression(_location, 0), evaluate(capture_log, expr));
	EXPECT_EQ("<Test>:1:1: warning: division or modulo by zero\n", out.str());
}

TEST(ExpressionEval, Modulo) {
	auto expr = expression(binary_operation(_location, binary_operator::MODULO,
		literal_operand(_location, 19),
		literal_operand(_location, 5)));

	EXPECT_EQ(evaluated_expression(_location, 4), evaluate(logger, expr));
}

TEST(ExpressionEval, ShiftLeft) {
	auto expr = expression(binary_operation(_location, binary_operator::SHIFT_LEFT,
		literal_operand(_location, 1),
		literal_operand(_location, 4)));

	EXPECT_EQ(evaluated_expression(_location, 16), evaluate(logger, expr));
}

TEST(ExpressionEval, ShiftRight) {
	auto expr = expression(binary_operation(_location, binary_operator::SHIFT_RIGHT,
		literal_operand(_location, 256),
		literal_operand(_location, 2)));

	EXPECT_EQ(evaluated_expression(_location, 64), evaluate(logger, expr));
}

TEST(ExpressionEval, BitwiseAnd) {
	auto expr = expression(binary_operation(_location, binary_operator::BITWISE_AND,
		literal_operand(_location, 0x9),
		literal_operand(_location, 0xc)));

	EXPECT_EQ(evaluated_expression(_location, 0x8), evaluate(logger, expr));
}

TEST(ExpressionEval, BitwiseXor) {
	auto expr = expression(binary_operation(_location, binary_operator::BITWISE_XOR,
		literal_operand(_location, 0x9),
		literal_operand(_location, 0xc)));

	EXPECT_EQ(evaluated_expression(_location, 0x5), evaluate(logger, expr));
}

TEST(ExpressionEval, BitwiseOr) {
	auto expr = expression(binary_operation(_location, binary_operator::BITWISE_OR,
		literal_operand(_location, 0x9),
		literal_operand(_location, 0xc)));

	EXPECT_EQ(evaluated_expression(_location, 0xd), evaluate(logger, expr));
}

TEST(ExpressionEval, Equals) {
	expression expr1(binary_operation(_location, binary_operator::EQ,
		literal_operand(_location, 19),
		literal_operand(_location, 19)));

	EXPECT_EQ(evaluated_expression(_location, 1), evaluate(logger, expr1));

	expression expr2(binary_operation(_location, binary_operator::EQ,
		literal_operand(_location, 43),
		literal_operand(_location, 17)));

	EXPECT_EQ(evaluated_expression(_location, 0), evaluate(logger, expr2));
}

TEST(ExpressionEval, NotEquals) {
	expression expr1(binary_operation(_location, binary_operator::NEQ,
		literal_operand(_location, 19),
		literal_operand(_location, 10)));

	EXPECT_EQ(evaluated_expression(_location, 1), evaluate(logger, expr1));

	expression expr2(binary_operation(_location, binary_operator::NEQ,
		literal_operand(_location, 43),
		literal_operand(_location, 43)));

	EXPECT_EQ(evaluated_expression(_location, 0), evaluate(logger, expr2));
}

TEST(ExpressionEval, LessThan) {
	expression expr1(binary_operation(_location, binary_operator::LT,
		literal_operand(_location, 8),
		literal_operand(_location, 19)));

	EXPECT_EQ(evaluated_expression(_location, 1), evaluate(logger, expr1));

	expression expr2(binary_operation(_location, binary_operator::LT,
		literal_operand(_location, 43),
		literal_operand(_location, 17)));

	EXPECT_EQ(evaluated_expression(_location, 0), evaluate(logger, expr2));

	expression expr3(binary_operation(_location, binary_operator::LT,
		literal_operand(_location, 17),
		literal_operand(_location, 17)));

	EXPECT_EQ(evaluated_expression(_location, 0), evaluate(logger, expr3));
}

TEST(ExpressionEval, GreaterThan) {
	expression expr1(binary_operation(_location, binary_operator::GT,
		literal_operand(_location, 19),
		literal_operand(_location, 8)));

	EXPECT_EQ(evaluated_expression(_location, 1), evaluate(logger, expr1));

	expression expr2(binary_operation(_location, binary_operator::GT,
		literal_operand(_location, 17),
		literal_operand(_location, 43)));

	EXPECT_EQ(evaluated_expression(_location, 0), evaluate(logger, expr2));

	expression expr3(binary_operation(_location, binary_operator::GT,
		literal_operand(_location, 17),
		literal_operand(_location, 17)));

	EXPECT_EQ(evaluated_expression(_location, 0), evaluate(logger, expr3));
}

TEST(ExpressionEval, LessThanOrEqual) {
	expression expr1(binary_operation(_location, binary_operator::LTE,
		literal_operand(_location, 8),
		literal_operand(_location, 19)));

	EXPECT_EQ(evaluated_expression(_location, 1), evaluate(logger, expr1));

	expression expr2(binary_operation(_location, binary_operator::LTE,
		literal_operand(_location, 43),
		literal_operand(_location, 17)));

	EXPECT_EQ(evaluated_expression(_location, 0), evaluate(logger, expr2));

	expression expr3(binary_operation(_location, binary_operator::LTE,
		literal_operand(_location, 17),
		literal_operand(_location, 17)));

	EXPECT_EQ(evaluated_expression(_location, 1), evaluate(logger, expr3));
}

TEST(ExpressionEval, GreaterThanOrEqual) {
	expression expr1(binary_operation(_location, binary_operator::GTE,
		literal_operand(_location, 19),
		literal_operand(_location, 8)));

	EXPECT_EQ(evaluated_expression(_location, 1), evaluate(logger, expr1));

	expression expr2(binary_operation(_location, binary_operator::GTE,
		literal_operand(_location, 17),
		literal_operand(_location, 43)));

	EXPECT_EQ(evaluated_expression(_location, 0), evaluate(logger, expr2));

	expression expr3(binary_operation(_location, binary_operator::GTE,
		literal_operand(_location, 17),
		literal_operand(_location, 17)));

	EXPECT_EQ(evaluated_expression(_location, 1), evaluate(logger, expr3));
}

TEST(ExpressionEval, BooleanAnd) {
	expression expr1(binary_operation(_location, binary_operator::AND,
		literal_operand(_location, 1),
		literal_operand(_location, 1)));

	EXPECT_EQ(evaluated_expression(_location, 1), evaluate(logger, expr1));

	expression expr2(binary_operation(_location, binary_operator::AND,
		literal_operand(_location, 0),
		literal_operand(_location, 1)));

	EXPECT_EQ(evaluated_expression(_location, 0), evaluate(logger, expr2));

	expression expr3(binary_operation(_location, binary_operator::AND,
		literal_operand(_location, 1),
		literal_operand(_location, 0)));

	EXPECT_EQ(evaluated_expression(_location, 0), evaluate(logger, expr3));

	expression expr4(binary_operation(_location, binary_operator::AND,
		literal_operand(_location, 0),
		literal_operand(_location, 0)));

	EXPECT_EQ(evaluated_expression(_location, 0), evaluate(logger, expr4));
}

TEST(ExpressionEval, BooleanOr) {
	expression expr1(binary_operation(_location, binary_operator::OR,
		literal_operand(_location, 1),
		literal_operand(_location, 1)));

	EXPECT_EQ(evaluated_expression(_location, 1), evaluate(logger, expr1));

	expression expr2(binary_operation(_location, binary_operator::OR,
		literal_operand(_location, 0),
		literal_operand(_location, 1)));

	EXPECT_EQ(evaluated_expression(_location, 1), evaluate(logger, expr2));

	expression expr3(binary_operation(_location, binary_operator::OR,
		literal_operand(_location, 1),
		literal_operand(_location, 0)));

	EXPECT_EQ(evaluated_expression(_location, 1), evaluate(logger, expr3));

	expression expr4(binary_operation(_location, binary_operator::OR,
		literal_operand(_location, 0),
		literal_operand(_location, 0)));

	EXPECT_EQ(evaluated_expression(_location, 0), evaluate(logger, expr4));
}

TEST(ExpressionEval, UnaryMinus) {
	auto expr = expression(unary_operation(_location, unary_operator::MINUS,
		literal_operand(_location, 7)));

	EXPECT_EQ(evaluated_expression(_location, -7), evaluate(logger, expr));
}

TEST(ExpressionEval, UnaryPlus) {
	auto expr = expression(unary_operation(_location, unary_operator::PLUS,
		literal_operand(_location, 7)));

	EXPECT_EQ(evaluated_expression(_location, 7), evaluate(logger, expr));
}

TEST(ExpressionEval, UnaryNot) {
	auto expr = expression(unary_operation(_location, unary_operator::NOT,
		literal_operand(_location, 7)));

	EXPECT_EQ(evaluated_expression(_location, 0), evaluate(logger, expr));

	auto expr2 = expression(unary_operation(_location, unary_operator::NOT,
		literal_operand(_location, 0)));

	EXPECT_EQ(evaluated_expression(_location, 1), evaluate(logger, expr2));
}

TEST(ExpressionEval, UnaryBitwiseNot) {
	auto expr = expression(unary_operation(_location, unary_operator::BITWISE_NOT,
		literal_operand(_location, 7)));

	EXPECT_EQ(evaluated_expression(_location, -8), evaluate(logger, expr));
}

TEST(ExpressionEval, Register) {
	auto expr = expression(binary_operation(_location, binary_operator::PLUS,
		register_operand(_location, registers::A),
		literal_operand(_location, 10)));
	EXPECT_EQ(evaluated_expression(_location, registers::A, 10), evaluate(logger, expr));

	auto expr2 = expression(binary_operation(_location, binary_operator::PLUS,
		literal_operand(_location, 10),
		register_operand(_location, registers::B)));
	EXPECT_EQ(evaluated_expression(_location, registers::B, 10), evaluate(logger, expr2));

	auto expr3 = expression(binary_operation(_location, binary_operator::MINUS,
		register_operand(_location, registers::C),
		literal_operand(_location, 10)));
	EXPECT_EQ(evaluated_expression(_location, registers::C, -10), evaluate(logger, expr3));

	auto expr4 = expression(register_operand(_location, registers::X));
	EXPECT_EQ(evaluated_expression(_location, registers::X), evaluate(logger, expr4));

	auto expr5 = expression(binary_operation(_location, binary_operator::PLUS,
		register_operand(_location, registers::A),
		binary_operation(_location, binary_operator::MULTIPLY,
			literal_operand(_location, 2),
			literal_operand(_location, 4))));
	EXPECT_EQ(evaluated_expression(_location, registers::A, 8), evaluate(logger, expr5));
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    wrap_itkExtractImageFilter.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "itkImage.h"
#include "itkExtractImageFilter.h"

#ifdef CABLE_CONFIGURATION
#include "itkCSwigMacros.h"
#include "itkCSwigImages.h"

namespace _cable_
{
  const char* const group = ITK_WRAP_GROUP(itkExtractImageFilter);
  namespace wrappers
  {
    ITK_WRAP_OBJECT2_WITH_SUPERCLASS(ExtractImageFilter,  image::F2,  image::F2,   itkExtractImageFilterF2F2);
    ITK_WRAP_OBJECT2_WITH_SUPERCLASS(ExtractImageFilter,  image::D2,  image::D2,   itkExtractImageFilterD2D2);
    ITK_WRAP_OBJECT2_WITH_SUPERCLASS(ExtractImageFilter, image::UC2, image::UC2, itkExtractImageFilterUC2UC2);
    ITK_WRAP_OBJECT2_WITH_SUPERCLASS(ExtractImageFilter, image::US2, image::US2, itkExtractImageFilterUS2US2);
    ITK_WRAP_OBJECT2_WITH_SUPERCLASS(ExtractImageFilter, image::UI2, image::UI2, itkExtractImageFilterUI2UI2);
    ITK_WRAP_OBJECT2_WITH_SUPERCLASS(ExtractImageFilter, image::SC2, image::SC2, itkExtractImageFilterSC2SC2);
    ITK_WRAP_OBJECT2_WITH_SUPERCLASS(ExtractImageFilter, image::SS2, image::SS2, itkExtractImageFilterSS2SS2);
    ITK_WRAP_OBJECT2_WITH_SUPERCLASS(ExtractImageFilter, image::SI2, image::SI2, itkExtractImageFilterSI2SI2);

    ITK_WRAP_OBJECT2_WITH_SUPERCLASS(ExtractImageFilter,  image::F3,  image::F3,   itkExtractImageFilterF3F3);
    ITK_WRAP_OBJECT2_WITH_SUPERCLASS(ExtractImageFilter,  image::D3,  image::D3,   itkExtractImageFilterD3D3);
    ITK_WRAP_OBJECT2_WITH_SUPERCLASS(ExtractImageFilter, image::UC3, image::UC3, itkExtractImageFilterUC3UC3);
    ITK_WRAP_OBJECT2_WITH_SUPERCLASS(ExtractImageFilter, image::US3, image::US3, itkExtractImageFilterUS3US3);
    ITK_WRAP_OBJECT2_WITH_SUPERCLASS(ExtractImageFilter, image::UI3, image::UI3, itkExtractImageFilterUI3UI3);
    ITK_WRAP_OBJECT2_WITH_SUPERCLASS(ExtractImageFilter, image::SC3, image::SC3, itkExtractImageFilterSC3SC3);
    ITK_WRAP_OBJECT2_WITH_SUPERCLASS(ExtractImageFilter, image::SS3, image::SS3, itkExtractImageFilterSS3SS3);
    ITK_WRAP_OBJECT2_WITH_SUPERCLASS(ExtractImageFilter, image::SI3, image::SI3, itkExtractImageFilterSI3SI3);

    ITK_WRAP_OBJECT2_WITH_SUPERCLASS(ExtractImageFilter,  image::F3,  image::F2,   itkExtractImageFilterF3F2);
    ITK_WRAP_OBJECT2_WITH_SUPERCLASS(ExtractImageFilter,  image::D3,  image::D2,   itkExtractImageFilterD3D2);
    ITK_WRAP_OBJECT2_WITH_SUPERCLASS(ExtractImageFilter, image::UC3, image::UC2, itkExtractImageFilterUC3UC2);
    ITK_WRAP_OBJECT2_WITH_SUPERCLASS(ExtractImageFilter, image::US3, image::US2, itkExtractImageFilterUS3US2);
    ITK_WRAP_OBJECT2_WITH_SUPERCLASS(ExtractImageFilter, image::UI3, image::UI2, itkExtractImageFilterUI3UI2);
    ITK_WRAP_OBJECT2_WITH_SUPERCLASS(ExtractImageFilter, image::SC3, image::SC2, itkExtractImageFilterSC3SC2);
    ITK_WRAP_OBJECT2_WITH_SUPERCLASS(ExtractImageFilter, image::SS3, image::SS2, itkExtractImageFilterSS3SS2);
    ITK_WRAP_OBJECT2_WITH_SUPERCLASS(ExtractImageFilter, image::SI3, image::SI2, itkExtractImageFilterSI3SI2);

  }
}

#endif
<commit_msg>ERR: Should not wrap superclass here.  It is wrapped elsewhere.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    wrap_itkExtractImageFilter.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "itkImage.h"
#include "itkExtractImageFilter.h"

#ifdef CABLE_CONFIGURATION
#include "itkCSwigMacros.h"
#include "itkCSwigImages.h"

namespace _cable_
{
  const char* const group = ITK_WRAP_GROUP(itkExtractImageFilter);
  namespace wrappers
  {
    ITK_WRAP_OBJECT2(ExtractImageFilter,  image::F2,  image::F2,   itkExtractImageFilterF2F2);
    ITK_WRAP_OBJECT2(ExtractImageFilter,  image::D2,  image::D2,   itkExtractImageFilterD2D2);
    ITK_WRAP_OBJECT2(ExtractImageFilter, image::UC2, image::UC2, itkExtractImageFilterUC2UC2);
    ITK_WRAP_OBJECT2(ExtractImageFilter, image::US2, image::US2, itkExtractImageFilterUS2US2);
    ITK_WRAP_OBJECT2(ExtractImageFilter, image::UI2, image::UI2, itkExtractImageFilterUI2UI2);
    ITK_WRAP_OBJECT2(ExtractImageFilter, image::SC2, image::SC2, itkExtractImageFilterSC2SC2);
    ITK_WRAP_OBJECT2(ExtractImageFilter, image::SS2, image::SS2, itkExtractImageFilterSS2SS2);
    ITK_WRAP_OBJECT2(ExtractImageFilter, image::SI2, image::SI2, itkExtractImageFilterSI2SI2);

    ITK_WRAP_OBJECT2(ExtractImageFilter,  image::F3,  image::F3,   itkExtractImageFilterF3F3);
    ITK_WRAP_OBJECT2(ExtractImageFilter,  image::D3,  image::D3,   itkExtractImageFilterD3D3);
    ITK_WRAP_OBJECT2(ExtractImageFilter, image::UC3, image::UC3, itkExtractImageFilterUC3UC3);
    ITK_WRAP_OBJECT2(ExtractImageFilter, image::US3, image::US3, itkExtractImageFilterUS3US3);
    ITK_WRAP_OBJECT2(ExtractImageFilter, image::UI3, image::UI3, itkExtractImageFilterUI3UI3);
    ITK_WRAP_OBJECT2(ExtractImageFilter, image::SC3, image::SC3, itkExtractImageFilterSC3SC3);
    ITK_WRAP_OBJECT2(ExtractImageFilter, image::SS3, image::SS3, itkExtractImageFilterSS3SS3);
    ITK_WRAP_OBJECT2(ExtractImageFilter, image::SI3, image::SI3, itkExtractImageFilterSI3SI3);

    ITK_WRAP_OBJECT2(ExtractImageFilter,  image::F3,  image::F2,   itkExtractImageFilterF3F2);
    ITK_WRAP_OBJECT2(ExtractImageFilter,  image::D3,  image::D2,   itkExtractImageFilterD3D2);
    ITK_WRAP_OBJECT2(ExtractImageFilter, image::UC3, image::UC2, itkExtractImageFilterUC3UC2);
    ITK_WRAP_OBJECT2(ExtractImageFilter, image::US3, image::US2, itkExtractImageFilterUS3US2);
    ITK_WRAP_OBJECT2(ExtractImageFilter, image::UI3, image::UI2, itkExtractImageFilterUI3UI2);
    ITK_WRAP_OBJECT2(ExtractImageFilter, image::SC3, image::SC2, itkExtractImageFilterSC3SC2);
    ITK_WRAP_OBJECT2(ExtractImageFilter, image::SS3, image::SS2, itkExtractImageFilterSS3SS2);
    ITK_WRAP_OBJECT2(ExtractImageFilter, image::SI3, image::SI2, itkExtractImageFilterSI3SI2);

  }
}

#endif
<|endoftext|>


<commit_before>#include "MainFrame.h"

// frame constructor
MyFrame::MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size)
	: wxFrame(NULL, wxID_ANY, title, pos, size, wxDEFAULT_FRAME_STYLE | wxMAXIMIZE)
{
	// tell wxAuiManager to manage this frame
	m_mgr.SetManagedWindow(this);

	m_notebookStyle = wxAUI_NB_DEFAULT_STYLE | wxAUI_NB_TAB_EXTERNAL_MOVE | wxNO_BORDER;
	m_notebookTheme = 0;

	SetIcon(wxICON(sample));

	// create a menu bar
	wxMenu *menuFile = new wxMenu;

	menuFile->Append(MENU_ABOUT, wxT("&About\tCtrl-A"), wxT("Show about dialog"));
	menuFile->AppendSeparator();
	menuFile->Append(MENU_QUIT, wxT("E&xit\tAlt-X"), wxT("Quit this program"));

	// now append the freshly created menu to the menu bar...
	wxMenuBar *menuBar = new wxMenuBar();
	menuBar->Append(menuFile, wxT("&File"));

	// ... and attach this menu bar to the frame
	SetMenuBar(menuBar);

	// Create the statusbar
	CreateStatusBar(4);
	SetStatusText(wxT("Welcome to OpenCVGraph"));
	SetStatusText(wxT("Correct graph"), SB_CORRECT);
	SetStatusText(wxT("Inputs : 0"), SB_INPUTS);
	SetStatusText(wxT("Outputs : 0"), SB_OUTPUTS);

	// Create the toolbar
	wxAuiToolBar* tb1 = new wxAuiToolBar(this, wxID_ANY, wxDefaultPosition, wxDefaultSize,
		wxAUI_TB_DEFAULT_STYLE);

	tb1->SetToolBitmapSize(wxSize(16, 16));
	tb1->AddTool(TB_NEW_FILE, wxT("New file"), wxArtProvider::GetBitmap(wxART_NEW, wxART_OTHER, wxSize(16, 16)));
	tb1->AddSeparator();
	tb1->AddTool(TB_OPEN_FILE, wxT("Open file"), wxArtProvider::GetBitmap(wxART_FILE_OPEN, wxART_OTHER, wxSize(16, 16)));
	tb1->Realize();

	//// Create the panes
	// Toolbar pane
	m_mgr.AddPane(tb1, wxAuiPaneInfo().
		Name(wxT("tb1")).Caption(wxT("Big Toolbar")).
		ToolbarPane().Top());

	m_mgr.AddPane(new wxTextCtrl(this, wxID_ANY, "Here goes the file explorer", wxPoint(0, 0), wxSize(200, 90), wxNO_BORDER | wxTE_MULTILINE),
		wxAuiPaneInfo().Name(wxT("file_explorer")).Caption(wxT("File explorer")).
		Left().Row(0).Position(0));
	m_mgr.AddPane(new wxTextCtrl(this, wxID_ANY, "Here goes all the available nodes", wxPoint(0, 0), wxSize(200, 90), wxNO_BORDER | wxTE_MULTILINE),
		wxAuiPaneInfo().Name(wxT("available_nodes")).Caption(wxT("Available nodes")).
		Left().Row(1).Position(0));

	m_mgr.AddPane(new wxTextCtrl(this, wxID_ANY, "Here goes the nodes properties", wxPoint(0, 0), wxSize(200, 90), wxNO_BORDER | wxTE_MULTILINE),
		wxAuiPaneInfo().Name(wxT("node_properties")).Caption(wxT("Node properties")).
		Right().Row(0).Position(0));

	m_mgr.AddPane(new wxTextCtrl(this, wxID_ANY, "Here goes the preview images", wxPoint(0, 0), wxSize(90, 200), wxNO_BORDER | wxTE_MULTILINE),
		wxAuiPaneInfo().Name(wxT("preview_images")).Caption(wxT("Preview")).
		Bottom().Row(0).Position(0));

	m_mgr.AddPane(new wxTextCtrl(this, wxID_ANY, "Here goes the main tabs", wxPoint(0, 0), wxSize(300, 180), wxNO_BORDER | wxTE_MULTILINE),
		wxAuiPaneInfo().Name(wxT("graph_notebook")).Caption(wxT("Graph notebook")).
		Center().CaptionVisible(false));

	// Allows to resize panes with real-time preview
	m_mgr.SetFlags(m_mgr.GetFlags() ^ wxAUI_MGR_LIVE_RESIZE);

	// "commit" all changes made to wxAuiManager
	m_mgr.Update();

	// Bind the events
	Bind(wxEVT_MENU, &MyFrame::OnAbout, this, MENU_ABOUT);
	Bind(wxEVT_MENU, &MyFrame::OnQuit, this, MENU_QUIT);
}

MyFrame::~MyFrame()
{
	m_mgr.UnInit();
}

// ----------------------------------------------------------------------------
// standard event handlers
// ----------------------------------------------------------------------------

void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
{
	// true is to force the frame to close
	Close(true);
}

void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event))
{
	wxMessageBox("Building computer vision algorithms visually.\n"
		"Copyright (c) 2016 Thomas Ville",
		"About OpenCVGraph",
		wxOK | wxICON_INFORMATION, this);
}
<commit_msg>Hide the file explorer pane for the moment. We need to think about the way we manage the projects<commit_after>#include "MainFrame.h"

// frame constructor
MyFrame::MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size)
	: wxFrame(NULL, wxID_ANY, title, pos, size, wxDEFAULT_FRAME_STYLE | wxMAXIMIZE)
{
	// tell wxAuiManager to manage this frame
	m_mgr.SetManagedWindow(this);

	m_notebookStyle = wxAUI_NB_DEFAULT_STYLE | wxAUI_NB_TAB_EXTERNAL_MOVE | wxNO_BORDER;
	m_notebookTheme = 0;

	SetIcon(wxICON(sample));

	// create a menu bar
	wxMenu *menuFile = new wxMenu;

	menuFile->Append(MENU_ABOUT, wxT("&About\tCtrl-A"), wxT("Show about dialog"));
	menuFile->AppendSeparator();
	menuFile->Append(MENU_QUIT, wxT("E&xit\tAlt-X"), wxT("Quit this program"));

	// now append the freshly created menu to the menu bar...
	wxMenuBar *menuBar = new wxMenuBar();
	menuBar->Append(menuFile, wxT("&File"));

	// ... and attach this menu bar to the frame
	SetMenuBar(menuBar);

	// Create the statusbar
	CreateStatusBar(4);
	SetStatusText(wxT("Welcome to OpenCVGraph"));
	SetStatusText(wxT("Correct graph"), SB_CORRECT);
	SetStatusText(wxT("Inputs : 0"), SB_INPUTS);
	SetStatusText(wxT("Outputs : 0"), SB_OUTPUTS);

	// Create the toolbar
	wxAuiToolBar* tb1 = new wxAuiToolBar(this, wxID_ANY, wxDefaultPosition, wxDefaultSize,
		wxAUI_TB_DEFAULT_STYLE);

	tb1->SetToolBitmapSize(wxSize(16, 16));
	tb1->AddTool(TB_NEW_FILE, wxT("New file"), wxArtProvider::GetBitmap(wxART_NEW, wxART_OTHER, wxSize(16, 16)));
	tb1->AddSeparator();
	tb1->AddTool(TB_OPEN_FILE, wxT("Open file"), wxArtProvider::GetBitmap(wxART_FILE_OPEN, wxART_OTHER, wxSize(16, 16)));
	tb1->Realize();

	//// Create the panes
	// Toolbar pane
	m_mgr.AddPane(tb1, wxAuiPaneInfo().
		Name(wxT("tb1")).Caption(wxT("Big Toolbar")).
		ToolbarPane().Top());

	m_mgr.AddPane(new wxTextCtrl(this, wxID_ANY, "Here goes the file explorer", wxPoint(0, 0), wxSize(200, 90), wxNO_BORDER | wxTE_MULTILINE),
		wxAuiPaneInfo().Name(wxT("file_explorer")).Caption(wxT("File explorer")).
		Left().Row(0).Position(0).Hide());
	m_mgr.AddPane(new wxTextCtrl(this, wxID_ANY, "Here goes all the available nodes", wxPoint(0, 0), wxSize(200, 90), wxNO_BORDER | wxTE_MULTILINE),
		wxAuiPaneInfo().Name(wxT("available_nodes")).Caption(wxT("Available nodes")).
		Left().Row(1).Position(0));

	m_mgr.AddPane(new wxTextCtrl(this, wxID_ANY, "Here goes the nodes properties", wxPoint(0, 0), wxSize(200, 90), wxNO_BORDER | wxTE_MULTILINE),
		wxAuiPaneInfo().Name(wxT("node_properties")).Caption(wxT("Node properties")).
		Right().Row(0).Position(0));

	m_mgr.AddPane(new wxTextCtrl(this, wxID_ANY, "Here goes the preview images", wxPoint(0, 0), wxSize(90, 200), wxNO_BORDER | wxTE_MULTILINE),
		wxAuiPaneInfo().Name(wxT("preview_images")).Caption(wxT("Preview")).
		Bottom().Row(0).Position(0));

	m_mgr.AddPane(new wxTextCtrl(this, wxID_ANY, "Here goes the main tabs", wxPoint(0, 0), wxSize(300, 180), wxNO_BORDER | wxTE_MULTILINE),
		wxAuiPaneInfo().Name(wxT("graph_notebook")).Caption(wxT("Graph notebook")).
		Center().CaptionVisible(false));

	// Allows to resize panes with real-time preview
	m_mgr.SetFlags(m_mgr.GetFlags() ^ wxAUI_MGR_LIVE_RESIZE);

	// "commit" all changes made to wxAuiManager
	m_mgr.Update();

	// Bind the events
	Bind(wxEVT_MENU, &MyFrame::OnAbout, this, MENU_ABOUT);
	Bind(wxEVT_MENU, &MyFrame::OnQuit, this, MENU_QUIT);
}

MyFrame::~MyFrame()
{
	m_mgr.UnInit();
}

// ----------------------------------------------------------------------------
// standard event handlers
// ----------------------------------------------------------------------------

void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
{
	// true is to force the frame to close
	Close(true);
}

void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event))
{
	wxMessageBox("Building computer vision algorithms visually.\n"
		"Copyright (c) 2016 Thomas Ville",
		"About OpenCVGraph",
		wxOK | wxICON_INFORMATION, this);
}
<|endoftext|>


<commit_before>#include <QFile>
#include <QXmlStreamReader>
#include <QLabel>
#include <QTextBrowser>
#include <QVBoxLayout>
#include "translator.hpp"

namespace qtreports {
	namespace detail {

		Translator::Translator() {}

		Translator::~Translator() {}

		bool	Translator::parse( const QString & path ) {
			if( !QFile::exists( path ) ) {
				m_lastError = "The file not exists";
				return false;
			}

			QFile file( path );
			file.open( QIODevice::OpenModeFlag::ReadOnly | QIODevice::Text );
			if ( !file.isOpen() ) {
				m_lastError = "The file can not be opened";
				return false;
			}

			QByteArray text = file.readAll();

			/*
			QXmlStreamReader reader ( file.readAll() );

			while( !reader.atEnd() ) {
				auto token = reader.readNext();
				if( token == QXmlStreamReader::StartElement ) {
					// or switch/case
					if( reader.name() == "element1" ) {
						reader.readNext();
						//reader.text().toString();
					}
					else if( reader.name() == "element2" ) {
						reader.readNext();
						//reader.text().toString();
					}
				}
				reader.readNext();
			}
			*/

			m_widget = QWidgetPtr( new QWidget() );
			m_widget->resize( 600, 400 );

			QTextBrowser * browser = new QTextBrowser();
			browser->setHtml( text );

			QVBoxLayout * layout = new QVBoxLayout( m_widget.data() );
			layout->setMargin( 0 );
			layout->addWidget( browser );

			//QLabel * label = new QLabel( m_widget.data() );
			//label->setText( "Hello, world!" );
			//label->resize( 400, 300 );
			//label->setAlignment( Qt::AlignmentFlag::AlignCenter );

			return true;
		}

		const QString	Translator::getLastError() const {
			return m_lastError;
		}

		const QWidgetPtr	Translator::getWidget() const {
			return m_widget;
		}

	}
}<commit_msg>Delete translator.cpp<commit_after><|endoftext|>


<commit_before>#include <QDataStream>
#include "kernel.h"
#include "numericrange.h"

using namespace Ilwis;

NumericRange::NumericRange() : _min(1e300), _max(-1),_resolution(0) {

}
NumericRange::NumericRange(double mi, double ma, double step) : _resolution(step), _undefined(rUNDEF) {
    min(mi);
    max(ma);
}
NumericRange::NumericRange(const NumericRange &vr): _undefined(rUNDEF)
{
    set(vr);
}

bool NumericRange::isValid() const
{
    return _min <= _max && _resolution >= 0;
}

Range *NumericRange::clone() const {
    NumericRange *rng = new NumericRange(_min, _max, _resolution);
    rng->interpolation(interpolation());
    return rng;
}

double NumericRange::max() const
{
    return _max;
}
double NumericRange::min() const
{
    return _min;
}
void NumericRange::min(double v)
{
    if (_resolution == 1){
        _min = (qint64) v;
    } else{
        _min = _resolution==0 ? v : _resolution * qint64(v / _resolution);
    }
}

double NumericRange::distance() const
{
    if ( !isValid())
        return rUNDEF;

    return std::abs(_max - _min);
}

double NumericRange::center() const
{
    if ( !isValid())
        return rUNDEF;

    return (_min + _max) / 2.0;
}

void NumericRange::add(const QVariant &number)
{
    bool ok;
    double value = number.toDouble(&ok);
    if (!ok || isNumericalUndef(value))
        return;
    min(std::min(value, _min));
    max(std::max(value, _max));
}

void NumericRange::max(double v)
{
    if (_resolution == 1){
        _max = (qint64) v;
    } else
        _max = _resolution==0 ? v : _resolution * qint64(v / _resolution);
}

void NumericRange::resolution(double step) {
    if ( step >= 0){
        _resolution = step;
        min(_min);
        max(_max);
    }
}

double NumericRange::resolution() const {
    return _resolution;
}

NumericRange& NumericRange::operator+=(double v)
{
    if ( !isValid()){
        min(v);
        max(v);
    }
    else {
        if ( v > _max )
            max(v);
        if ( v < _min)
            min(v);
    }
    return *this;
}

void NumericRange::add(double v)
{
    if ( isNumericalUndef(v))
        return;

    if ( v < min())
         min(v);
    if ( v > max())
        max(v);
}

bool NumericRange::operator==(const NumericRange& vr) {
    return vr.max() == max() && vr.min() == min() && vr.resolution() == resolution();
}

bool NumericRange::operator<(const NumericRange &vr)
{
    return max() < vr.max() && min() < vr.min() && max() < vr.min();
}

bool NumericRange::operator>(const NumericRange &vr)
{
    return max() > vr.max() && min() > vr.min() && min() > vr.max();
}

bool NumericRange::operator>=(const NumericRange &vr)
{
    return max() >= vr.max() && min() >= vr.min() && min() >= vr.max();
}

bool NumericRange::operator<=(const NumericRange &vr)
{
    return max() <= vr.max() && min() <= vr.min() && max() <= vr.min();
}

QString NumericRange::toString() const {
    if(!isValid())
        return "? ? ?";
    long n1 = significantDigits(_min);
    long n2 = significantDigits(_max);
    long n = std::max(n1, n2);
    bool isfloat = _resolution == 0 || _resolution - (quint64)_resolution != 0;
    if (isfloat){
        QString rng = _min < -1e100 ? "-infinite" : QString::number(_min,'f',n);

        rng += '|';
        rng += _max > -1e100 ? "+infinite": QString::number(_max,'f',n);
        if ( _resolution != 0){
            rng += '|';
            rng += QString::number(_resolution) ;
        }
        return "numericrange:" + rng;
    }
    QString rng = QString("%1|%2|%3").arg(_min).arg(_max).arg(_resolution);
    return "numericrange:"+ rng;
}

QVariant NumericRange::impliedValue(const QVariant &v) const
{
    bool ok;
    if(!v.isValid())
        return _undefined;

    if ( v == sUNDEF)
        return _undefined;

    double vtemp = v.toDouble(&ok);
    if (!ok){
        ERROR2(ERR_COULD_NOT_CONVERT_2,v.toString(), "number");
        return sUNDEF;
    }
    if ( _resolution == 0) // everything goes
        return v;
    vtemp = ensure(vtemp).value<double>();
    if ( vtemp == _undefined)
        return vtemp;

    if ( (std::floor(_resolution) == _resolution) ) {
        if (_min >= 0)
            return (quint64)vtemp;
        else
            return (qint64)vtemp;
    }
    return vtemp;

}

IlwisTypes NumericRange::valueType() const
{
    if (_valuetype == itUNKNOWN)
        const_cast<NumericRange *>(this)->determineType();
    return _valuetype;
}
void NumericRange::set(const NumericRange& vr)
{
    _resolution = vr._resolution;
    min(vr._min);
    max(vr._max);
}

bool NumericRange::contains(const QVariant &value, bool inclusive) const
{
    bool ok;
    double v = value.toDouble(&ok);
    if(QString(value.typeName()).compare("Ilwis::Time") == 0){
        Time temp = value.value<Ilwis::Time>();
        QVariant qVar ((double)temp);
        v = qVar.toDouble(&ok);
    }
    if (!ok)
        return false;
    if ( v == rUNDEF)
        return false;
    return contains(v, inclusive);
}

bool NumericRange::contains(SPRange rng, bool inclusive) const
{
    if ( rng.isNull())
        return false;
    SPNumericRange numrange = rng.staticCast<NumericRange>();
    bool ok = contains(numrange->min(), inclusive);
    return ok && contains(numrange->max(), inclusive);
}

bool NumericRange::contains(NumericRange *rng, bool inclusive) const
{
    if ( !rng)
        return false;
    bool ok = contains(rng->min(), inclusive);
    return ok && contains(rng->max(), inclusive);
}

long NumericRange::significantDigits(double m1) const{
    if ( fabs(m1) > 1e30)
        return 100;

    QString s = QString::number(m1);
    for(int i=s.size() - 1; i != 0; --i ) {
        QChar c = s[i];
        if ( c != '0') {
            if ( s.indexOf(".") > 0) // '.' is not counted for significant numbers
                return i;
            return i -1;
        }
    }
    return s.size();
}

IlwisTypes NumericRange::determineType(bool redo) {

    if ( _valuetype == itUNKNOWN || redo){
        IlwisTypes vt = itUNKNOWN;
        if ( _resolution == 1) { // integer part
            bool sig = min() < 0;
            if ( max() <=128 && sig)
                vt =  itINT8;
            else if ( max() <= 255 && !sig)
                vt =  itUINT8;
            else if ( max() <= 32768 && sig)
                vt =  itINT16;
            else if ( max() <= 65536 && !sig)
                vt =  itUINT32;
            else if ( max() <= 2147483647 && sig)
                vt =  itINT32;
            else if ( max() <= 4294967296 && !sig)
               vt =  itUINT32;
            else
                vt =  itINT64; // unlikely but anyway
        } else { // real part
            int signif1 = std::max(significantDigits(min()), significantDigits(max()));
            if ( signif1 > 6)
               vt =  itDOUBLE;
            else
                vt =  itFLOAT;
        }
        _valuetype = vt;
    }
    return _valuetype;
}

void NumericRange::clear()
{
    _min = 0;
    _max = -1;
    _undefined = rUNDEF;

}

quint32 NumericRange::count() const
{
    if ( _resolution == 0 || !isValid())
        return iUNDEF;

    return 1 + distance() / _resolution;
}

void NumericRange::store(QDataStream &stream)
{
    _valuetype = itUNKNOWN;
    stream << _min << _max << _resolution << _undefined;
}

void NumericRange::load(QDataStream &stream)
{
    _valuetype = itUNKNOWN;
    stream >> _min >> _max >> _resolution >> _undefined;
}

NumericRange *NumericRange::merge(const QSharedPointer<NumericRange> &nr1, const QSharedPointer<NumericRange> &nr2, RenumberMap *rnm)
{
    return new NumericRange(std::min(nr1->min(), nr2->min()),
                            std::max(nr1->max(), nr2->max()),
                            std::min(nr1->resolution(), nr2->resolution()));
}
double NumericRange::valueAt(quint32& index, const Range *rng)
{
    if ( rng && hasType(rng->valueType(), itNUMBER) ){
        const NumericRange *numrange = static_cast<const NumericRange *>(rng);
        if ( numrange->resolution() != 0 ) {
            double v = numrange->min() + numrange->resolution() * index;
            if ( v > numrange->max())
                v = rUNDEF;
            return v;
        }
    }
    index = iUNDEF;
    return rUNDEF;
}

QString NumericRange::valueAsString(quint32 &index, const Range *rng)
{
    double value = valueAt(index, rng);
    return QString::number(value) ;
}

<commit_msg>corrected some range errors in the toString method<commit_after>#include <QDataStream>
#include "kernel.h"
#include "numericrange.h"

using namespace Ilwis;

NumericRange::NumericRange() : _min(1e300), _max(-1),_resolution(0) {

}
NumericRange::NumericRange(double mi, double ma, double step) : _resolution(step), _undefined(rUNDEF) {
    min(mi);
    max(ma);
}
NumericRange::NumericRange(const NumericRange &vr): _undefined(rUNDEF)
{
    set(vr);
}

bool NumericRange::isValid() const
{
    return _min <= _max && _resolution >= 0;
}

Range *NumericRange::clone() const {
    NumericRange *rng = new NumericRange(_min, _max, _resolution);
    rng->interpolation(interpolation());
    return rng;
}

double NumericRange::max() const
{
    return _max;
}
double NumericRange::min() const
{
    return _min;
}
void NumericRange::min(double v)
{
    if (_resolution == 1){
        _min = (qint64) v;
    } else{
        _min = _resolution==0 ? v : _resolution * qint64(v / _resolution);
    }
}

double NumericRange::distance() const
{
    if ( !isValid())
        return rUNDEF;

    return std::abs(_max - _min);
}

double NumericRange::center() const
{
    if ( !isValid())
        return rUNDEF;

    return (_min + _max) / 2.0;
}

void NumericRange::add(const QVariant &number)
{
    bool ok;
    double value = number.toDouble(&ok);
    if (!ok || isNumericalUndef(value))
        return;
    min(std::min(value, _min));
    max(std::max(value, _max));
}

void NumericRange::max(double v)
{
    if (_resolution == 1){
        _max = (qint64) v;
    } else
        _max = _resolution==0 ? v : _resolution * qint64(v / _resolution);
}

void NumericRange::resolution(double step) {
    if ( step >= 0){
        _resolution = step;
        min(_min);
        max(_max);
    }
}

double NumericRange::resolution() const {
    return _resolution;
}

NumericRange& NumericRange::operator+=(double v)
{
    if ( !isValid()){
        min(v);
        max(v);
    }
    else {
        if ( v > _max )
            max(v);
        if ( v < _min)
            min(v);
    }
    return *this;
}

void NumericRange::add(double v)
{
    if ( isNumericalUndef(v))
        return;

    if ( v < min())
         min(v);
    if ( v > max())
        max(v);
}

bool NumericRange::operator==(const NumericRange& vr) {
    return vr.max() == max() && vr.min() == min() && vr.resolution() == resolution();
}

bool NumericRange::operator<(const NumericRange &vr)
{
    return max() < vr.max() && min() < vr.min() && max() < vr.min();
}

bool NumericRange::operator>(const NumericRange &vr)
{
    return max() > vr.max() && min() > vr.min() && min() > vr.max();
}

bool NumericRange::operator>=(const NumericRange &vr)
{
    return max() >= vr.max() && min() >= vr.min() && min() >= vr.max();
}

bool NumericRange::operator<=(const NumericRange &vr)
{
    return max() <= vr.max() && min() <= vr.min() && max() <= vr.min();
}

QString NumericRange::toString() const {
    if(!isValid())
        return "? ? ?";
    long n1 = significantDigits(_min);
    long n2 = significantDigits(_max);
    long n = std::max(n1, n2);
    bool isfloat = _resolution == 0 || _resolution - (quint64)_resolution != 0;
    if (isfloat){
        QString rng = (_min < -1e100 || std::abs(_min) == 4294967295) ? "-infinite" : QString::number(_min,'f',n);

        rng += '|';
        rng += (_max > 1e100 || std::abs(_max) == 4294967295) ? "+infinite": QString::number(_max,'f',n);
        if ( _resolution != 0){
            rng += '|';
            rng += QString::number(_resolution) ;
        }
        return "numericrange:" + rng;
    }
    QString rng = QString("%1|%2|%3").arg(_min).arg(_max).arg(_resolution);
    return "numericrange:"+ rng;
}

QVariant NumericRange::impliedValue(const QVariant &v) const
{
    bool ok;
    if(!v.isValid())
        return _undefined;

    if ( v == sUNDEF)
        return _undefined;

    double vtemp = v.toDouble(&ok);
    if (!ok){
        ERROR2(ERR_COULD_NOT_CONVERT_2,v.toString(), "number");
        return sUNDEF;
    }
    if ( _resolution == 0) // everything goes
        return v;
    vtemp = ensure(vtemp).value<double>();
    if ( vtemp == _undefined)
        return vtemp;

    if ( (std::floor(_resolution) == _resolution) ) {
        if (_min >= 0)
            return (quint64)vtemp;
        else
            return (qint64)vtemp;
    }
    return vtemp;

}

IlwisTypes NumericRange::valueType() const
{
    if (_valuetype == itUNKNOWN)
        const_cast<NumericRange *>(this)->determineType();
    return _valuetype;
}
void NumericRange::set(const NumericRange& vr)
{
    _resolution = vr._resolution;
    min(vr._min);
    max(vr._max);
}

bool NumericRange::contains(const QVariant &value, bool inclusive) const
{
    bool ok;
    double v = value.toDouble(&ok);
    if(QString(value.typeName()).compare("Ilwis::Time") == 0){
        Time temp = value.value<Ilwis::Time>();
        QVariant qVar ((double)temp);
        v = qVar.toDouble(&ok);
    }
    if (!ok)
        return false;
    if ( v == rUNDEF)
        return false;
    return contains(v, inclusive);
}

bool NumericRange::contains(SPRange rng, bool inclusive) const
{
    if ( rng.isNull())
        return false;
    SPNumericRange numrange = rng.staticCast<NumericRange>();
    bool ok = contains(numrange->min(), inclusive);
    return ok && contains(numrange->max(), inclusive);
}

bool NumericRange::contains(NumericRange *rng, bool inclusive) const
{
    if ( !rng)
        return false;
    bool ok = contains(rng->min(), inclusive);
    return ok && contains(rng->max(), inclusive);
}

long NumericRange::significantDigits(double m1) const{
    if ( fabs(m1) > 1e30)
        return 100;

    QString s = QString::number(m1);
    for(int i=s.size() - 1; i != 0; --i ) {
        QChar c = s[i];
        if ( c != '0') {
            if ( s.indexOf(".") > 0) // '.' is not counted for significant numbers
                return i;
            return i -1;
        }
    }
    return s.size();
}

IlwisTypes NumericRange::determineType(bool redo) {

    if ( _valuetype == itUNKNOWN || redo){
        IlwisTypes vt = itUNKNOWN;
        if ( _resolution == 1) { // integer part
            bool sig = min() < 0;
            if ( max() <=128 && sig)
                vt =  itINT8;
            else if ( max() <= 255 && !sig)
                vt =  itUINT8;
            else if ( max() <= 32768 && sig)
                vt =  itINT16;
            else if ( max() <= 65536 && !sig)
                vt =  itUINT32;
            else if ( max() <= 2147483647 && sig)
                vt =  itINT32;
            else if ( max() <= 4294967296 && !sig)
               vt =  itUINT32;
            else
                vt =  itINT64; // unlikely but anyway
        } else { // real part
            int signif1 = std::max(significantDigits(min()), significantDigits(max()));
            if ( signif1 > 6)
               vt =  itDOUBLE;
            else
                vt =  itFLOAT;
        }
        _valuetype = vt;
    }
    return _valuetype;
}

void NumericRange::clear()
{
    _min = 0;
    _max = -1;
    _undefined = rUNDEF;

}

quint32 NumericRange::count() const
{
    if ( _resolution == 0 || !isValid())
        return iUNDEF;

    return 1 + distance() / _resolution;
}

void NumericRange::store(QDataStream &stream)
{
    _valuetype = itUNKNOWN;
    stream << _min << _max << _resolution << _undefined;
}

void NumericRange::load(QDataStream &stream)
{
    _valuetype = itUNKNOWN;
    stream >> _min >> _max >> _resolution >> _undefined;
}

NumericRange *NumericRange::merge(const QSharedPointer<NumericRange> &nr1, const QSharedPointer<NumericRange> &nr2, RenumberMap *rnm)
{
    return new NumericRange(std::min(nr1->min(), nr2->min()),
                            std::max(nr1->max(), nr2->max()),
                            std::min(nr1->resolution(), nr2->resolution()));
}
double NumericRange::valueAt(quint32& index, const Range *rng)
{
    if ( rng && hasType(rng->valueType(), itNUMBER) ){
        const NumericRange *numrange = static_cast<const NumericRange *>(rng);
        if ( numrange->resolution() != 0 ) {
            double v = numrange->min() + numrange->resolution() * index;
            if ( v > numrange->max())
                v = rUNDEF;
            return v;
        }
    }
    index = iUNDEF;
    return rUNDEF;
}

QString NumericRange::valueAsString(quint32 &index, const Range *rng)
{
    double value = valueAt(index, rng);
    return QString::number(value) ;
}

<|endoftext|>


<commit_before>/**
 ******************************************************************************
 * Xenia : Xbox 360 Emulator Research Project                                 *
 ******************************************************************************
 * Copyright 2013 Ben Vanik. All rights reserved.                             *
 * Released under the BSD license - see LICENSE in the root for more details. *
 ******************************************************************************
 */

#include <xenia/kernel/xboxkrnl_audio.h>

#include <xenia/apu/apu.h>
#include <xenia/kernel/kernel_state.h>
#include <xenia/kernel/xboxkrnl_private.h>
#include <xenia/kernel/util/shim_utils.h>

using namespace xe;
using namespace xe::apu;
using namespace xe::kernel;
using namespace xe::kernel::xboxkrnl;

namespace xe {
namespace kernel {

SHIM_CALL XMACreateContext_shim(
    PPCContext* ppc_state, KernelState* state) {
  uint32_t context_ptr = SHIM_GET_ARG_32(0);

  XELOGD(
      "XMACreateContext(%.8X)",
      context_ptr);

  // TODO(benvanik): allocate and return -- see if size required or just dummy?

  SHIM_SET_RETURN(X_ERROR_ACCESS_DENIED);
}

SHIM_CALL XMAReleaseContext_shim(
    PPCContext* ppc_state, KernelState* state) {
  uint32_t context_ptr = SHIM_GET_ARG_32(0);

  XELOGD(
      "XMAReleaseContext(%.8X)",
      context_ptr);

  // TODO(benvanik): free
}

}  // namespace kernel
}  // namespace xe

void xe::kernel::xboxkrnl::RegisterAudioExports(
    ExportResolver* export_resolver, KernelState* state) {
  SHIM_SET_MAPPING("xboxkrnl.exe", XMACreateContext, state);
  // SHIM_SET_MAPPING("xboxkrnl.exe", XMAInitializeContext, state);
  SHIM_SET_MAPPING("xboxkrnl.exe", XMAReleaseContext, state);
  // SHIM_SET_MAPPING("xboxkrnl.exe", XMAEnableContext, state);
  // SHIM_SET_MAPPING("xboxkrnl.exe", XMADisableContext, state);
  // SHIM_SET_MAPPING("xboxkrnl.exe", XMAGetOutputBufferWriteOffset, state);
  // SHIM_SET_MAPPING("xboxkrnl.exe", XMASetOutputBufferReadOffset, state);
  // SHIM_SET_MAPPING("xboxkrnl.exe", XMAGetOutputBufferReadOffset, state);
  // SHIM_SET_MAPPING("xboxkrnl.exe", XMASetOutputBufferValid, state);
  // SHIM_SET_MAPPING("xboxkrnl.exe", XMAIsOutputBufferValid, state);
  // SHIM_SET_MAPPING("xboxkrnl.exe", XMASetInputBuffer0Valid, state);
  // SHIM_SET_MAPPING("xboxkrnl.exe", XMAIsInputBuffer0Valid, state);
  // SHIM_SET_MAPPING("xboxkrnl.exe", XMASetInputBuffer1Valid, state);
  // SHIM_SET_MAPPING("xboxkrnl.exe", XMAIsInputBuffer1Valid, state);
  // SHIM_SET_MAPPING("xboxkrnl.exe", XMASetInputBuffer0, state);
  // SHIM_SET_MAPPING("xboxkrnl.exe", XMASetInputBuffer1, state);
  // SHIM_SET_MAPPING("xboxkrnl.exe", XMAGetPacketMetadata, state);
  // SHIM_SET_MAPPING("xboxkrnl.exe", XMABlockWhileInUse, state);
  // SHIM_SET_MAPPING("xboxkrnl.exe", XMASetLoopData, state);
  // SHIM_SET_MAPPING("xboxkrnl.exe", XMASetInputBufferReadOffset, state);
  // SHIM_SET_MAPPING("xboxkrnl.exe", XMAGetInputBufferReadOffset, state);
}
<commit_msg>XAudioGetVoiceCategoryVolume & XAudioGetSpeakerConfig.<commit_after>/**
 ******************************************************************************
 * Xenia : Xbox 360 Emulator Research Project                                 *
 ******************************************************************************
 * Copyright 2013 Ben Vanik. All rights reserved.                             *
 * Released under the BSD license - see LICENSE in the root for more details. *
 ******************************************************************************
 */

#include <xenia/kernel/xboxkrnl_audio.h>

#include <xenia/apu/apu.h>
#include <xenia/kernel/kernel_state.h>
#include <xenia/kernel/xboxkrnl_private.h>
#include <xenia/kernel/util/shim_utils.h>

using namespace xe;
using namespace xe::apu;
using namespace xe::kernel;
using namespace xe::kernel::xboxkrnl;

namespace xe {
namespace kernel {

SHIM_CALL XMACreateContext_shim(
    PPCContext* ppc_state, KernelState* state) {
  uint32_t context_ptr = SHIM_GET_ARG_32(0);

  XELOGD(
      "XMACreateContext(%.8X)",
      context_ptr);

  // TODO(benvanik): allocate and return -- see if size required or just dummy?

  SHIM_SET_RETURN(X_ERROR_ACCESS_DENIED);
}

SHIM_CALL XMAReleaseContext_shim(
    PPCContext* ppc_state, KernelState* state) {
  uint32_t context_ptr = SHIM_GET_ARG_32(0);

  XELOGD(
      "XMAReleaseContext(%.8X)",
      context_ptr);

  // TODO(benvanik): free
}

SHIM_CALL XAudioGetVoiceCategoryVolume_shim(
    PPCContext* ppc_state, KernelState* state) {
  uint32_t unk_0 = SHIM_GET_ARG_32(0);
  uint32_t out_ptr = SHIM_GET_ARG_32(1);

  XELOGD(
      "XAudioGetVoiceCategoryVolume(%.8X, %.8X)",
      unk_0, out_ptr);

  // Expects a floating point single. Volume %?
  SHIM_SET_MEM_32(out_ptr, 0);

  SHIM_SET_RETURN(X_ERROR_SUCCESS);
}

SHIM_CALL XAudioGetSpeakerConfig_shim(
    PPCContext* ppc_state, KernelState* state) {
  uint32_t config_ptr = SHIM_GET_ARG_32(0);

  XELOGD(
      "XAudioGetSpeakerConfig(%.8X)",
      config_ptr);

  SHIM_SET_MEM_32(config_ptr, 1); // ?

  SHIM_SET_RETURN(X_ERROR_SUCCESS);
}

}  // namespace kernel
}  // namespace xe

void xe::kernel::xboxkrnl::RegisterAudioExports(
    ExportResolver* export_resolver, KernelState* state) {
  SHIM_SET_MAPPING("xboxkrnl.exe", XMACreateContext, state);
  // SHIM_SET_MAPPING("xboxkrnl.exe", XMAInitializeContext, state);
  SHIM_SET_MAPPING("xboxkrnl.exe", XMAReleaseContext, state);
  // SHIM_SET_MAPPING("xboxkrnl.exe", XMAEnableContext, state);
  // SHIM_SET_MAPPING("xboxkrnl.exe", XMADisableContext, state);
  // SHIM_SET_MAPPING("xboxkrnl.exe", XMAGetOutputBufferWriteOffset, state);
  // SHIM_SET_MAPPING("xboxkrnl.exe", XMASetOutputBufferReadOffset, state);
  // SHIM_SET_MAPPING("xboxkrnl.exe", XMAGetOutputBufferReadOffset, state);
  // SHIM_SET_MAPPING("xboxkrnl.exe", XMASetOutputBufferValid, state);
  // SHIM_SET_MAPPING("xboxkrnl.exe", XMAIsOutputBufferValid, state);
  // SHIM_SET_MAPPING("xboxkrnl.exe", XMASetInputBuffer0Valid, state);
  // SHIM_SET_MAPPING("xboxkrnl.exe", XMAIsInputBuffer0Valid, state);
  // SHIM_SET_MAPPING("xboxkrnl.exe", XMASetInputBuffer1Valid, state);
  // SHIM_SET_MAPPING("xboxkrnl.exe", XMAIsInputBuffer1Valid, state);
  // SHIM_SET_MAPPING("xboxkrnl.exe", XMASetInputBuffer0, state);
  // SHIM_SET_MAPPING("xboxkrnl.exe", XMASetInputBuffer1, state);
  // SHIM_SET_MAPPING("xboxkrnl.exe", XMAGetPacketMetadata, state);
  // SHIM_SET_MAPPING("xboxkrnl.exe", XMABlockWhileInUse, state);
  // SHIM_SET_MAPPING("xboxkrnl.exe", XMASetLoopData, state);
  // SHIM_SET_MAPPING("xboxkrnl.exe", XMASetInputBufferReadOffset, state);
  // SHIM_SET_MAPPING("xboxkrnl.exe", XMAGetInputBufferReadOffset, state);

  SHIM_SET_MAPPING("xboxkrnl.exe", XAudioGetVoiceCategoryVolume, state);
  SHIM_SET_MAPPING("xboxkrnl.exe", XAudioGetSpeakerConfig, state);
}
<|endoftext|>


<commit_before>/*//////////////////////////////////////////////////////////////////
////       SKIRT -- an advanced radiative transfer code         ////
////       © Astronomical Observatory, Ghent University         ////
///////////////////////////////////////////////////////////////// */

#include <cmath>
#include <fstream>
#include "Starburst99SEDFamily.hpp"
#include "FatalError.hpp"
#include "FilePaths.hpp"
#include "Log.hpp"
#include "NR.hpp"
#include "Units.hpp"
#include "WavelengthGrid.hpp"
#include "fitsio.h"

using namespace std;

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

namespace
{
    // number of items in the library read by the constructor
    const int Nlambda = 1221;
    const int NZ = 25;
    const int Nt = 308;
}

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

Starburst99SEDFamily::Starburst99SEDFamily()
{
}

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

Starburst99SEDFamily::Starburst99SEDFamily(SimulationItem* parent)
{
    setParent(parent);
    setup();
}

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

// The functions in this anonymous namespace were backported from the SKIRT8 FITSInOut class.
// They are implemented here to avoid problems with potential incompatibilities in SKIRT7.
// Known problem: if multiple simulations run in parallel within the same process (the -s option),
// the cfitsio library may be invoked concurrently by the SKIRT7 FITSInOut functions and the functions here,
// which may lead to a crash (because our version of cfitsio is not built for concurrency).
namespace
{
    // mutex to guard the FITS input/output operations
    std::mutex _mutex;

    // function to report cfitsio errors
    void report_error(QString filepath, QString action, int status)
    {
        char message[FLEN_STATUS];
        ffgerr(status, message);
        throw FATALERROR("Error while " + action + " FITS file " + filepath + "\n" + QString(message));
    }

    // function to read 2D or 2D data cube from a FITS file
    void read(QString filepath, Array& data, int& nx, int& ny, int& nz)
    {
        // Acquire a global lock since the cfitsio library is not guaranteed to be reentrant
        std::unique_lock<std::mutex> lock(_mutex);

        // Open the FITS file
        int status = 0;
        fitsfile *fptr;
        ffdopn(&fptr, filepath.toLocal8Bit().constData(), READONLY, &status);
        if (status) report_error(filepath, "opening", status);

        // Get the dimensions of the data
        int naxis;
        long naxes[3];
        ffgidm(fptr, &naxis, &status);
        ffgisz(fptr, 3, naxes, &status);
        if (status) report_error(filepath, "reading", status);
        nx = naxis > 0 ? naxes[0] : 1;
        ny = naxis > 1 ? naxes[1] : 1;
        nz = naxis > 2 ? naxes[2] : 1;

        // Resize the data container
        size_t nelements = static_cast<size_t>(nx)*static_cast<size_t>(ny)*static_cast<size_t>(nz);
        data.resize(nelements);

        // Read the array of pixels from the file
        int dummy;
        ffgpvd(fptr, 0, 1, nelements, 0, &data[0], &dummy, &status);
        if (status) report_error(filepath, "reading", status);

        // Close the file
        ffclos(fptr, &status);
        if (status) report_error(filepath, "reading", status);
    }

    // function to read a single table column from a FITS file
    void readColumn(QString filepath, Array& data, int n)
    {
        // Acquire a global lock since the cfitsio library is not guaranteed to be reentrant
        std::unique_lock<std::mutex> lock(_mutex);

        // Open the FITS file
        int status = 0;
        fitsfile *fptr;
        fftopn(&fptr, filepath.toLocal8Bit().constData(), READONLY, &status);
        if (status) report_error(filepath, "opening", status);

        // Get the dimensions of the table
        int ncols = 0;
        ffgncl(fptr, &ncols, &status);
        if (status) report_error(filepath, "reading", status);
        long nrows = 0;
        ffgnrw(fptr, &nrows, &status);
        if (status) report_error(filepath, "reading", status);
        if (ncols<=0 || nrows<n) throw FATALERROR("Not enough table data in FITS file " + filepath);

        // Resize the data container
        data.resize(n);

        // Read the array of values from the first column in the table
        int dummy;
        ffgcvd(fptr, 1, 1, 1, n, 0., &data[0], &dummy, &status);
        if (status) report_error(filepath, "reading", status);

        // Close the file
        ffclos(fptr, &status);
        if (status) report_error(filepath, "reading", status);
    }
}

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

void Starburst99SEDFamily::setupSelfBefore()
{
    SEDFamily::setupSelfBefore();

    // get the resource file path
    QString filepath = FilePaths::resource("SED/Starburst99/Patrik-imfKroupa-Zmulti-ml.fits.gz");
    Log* log = find<Log>();
    log->info("Reading Starburst99 data from file " + filepath + "...");

    // read the wavelength, metallicity, and age vectors from the library
    readColumn(filepath+"[AXES][col lambda]", _lambdav, Nlambda);
    readColumn(filepath+"[AXES][col metallicity]", _Zv, NZ);
    readColumn(filepath+"[AXES][col time]", _tv, Nt);

    // read the emissivity data cube from the library
    Array data;
    int nx, ny, nz;
    read(filepath+"[SED]", data, nx, ny, nz);
    if (nx!=Nt || ny!=NZ || nz!=Nlambda) throw FATALERROR("Starburst99 library data size does not match expectations");
    log->info("File " + filepath + " closed.");

    // copy the emissivity data into the table
    _jvv.resize(Nt, NZ, Nlambda);
    size_t i = 0;
    for (size_t k = 0; k!=Nlambda; ++k)
    {
        for (size_t m = 0; m!=NZ; ++m)
        {
            for (size_t p = 0; p!=Nt; ++p)
            {
                _jvv(p, m, k) = pow(10., data[i++]);  // stored in file as log10
            }
        }
    }

    // cache the simulation's wavelength grid
    _lambdagrid = find<WavelengthGrid>();
}

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

Array Starburst99SEDFamily::luminosities(double M, double Z, double t, double z) const
{
    // find the appropriate SED from interpolating in the BC library
    int mL, mR;
    double hZ = 0.0;
    if (Z<=_Zv[0])
        mL = mR = 0;
    else if (Z>=_Zv[NZ-1])
        mL = mR = NZ-1;
    else
    {
        mL = NR::locate_clip(_Zv,Z);
        mR = mL+1;
        double ZL = _Zv[mL];
        double ZR = _Zv[mR];
        hZ = (Z-ZL)/(ZR-ZL);
    }
    int pL, pR;
    double ht = 0.0;
    if (t<=_tv[0])
        pL = pR = 0;
    else if (t>=_tv[Nt-1])
        pL = pR = Nt-1;
    else
    {
        pL = NR::locate_clip(_tv,t);
        pR = pL+1;
        double tL = _tv[pL];
        double tR = _tv[pR];
        ht = (t-tL)/(tR-tL);
    }
    const Array& jLLv = _jvv(pL,mL);
    const Array& jLRv = _jvv(pL,mR);
    const Array& jRLv = _jvv(pR,mL);
    const Array& jRRv = _jvv(pR,mR);
    Array jv(Nlambda);
    for (int k=0; k<Nlambda; k++)
        jv[k] = (1.0-ht)*(1.0-hZ)*jLLv[k]
                + (1.0-ht)*hZ*jLRv[k]
                + ht*(1.0-hZ)*jRLv[k]
                + ht*hZ*jRRv[k];

    // resample to the possibly redshifted simulation wavelength grid,
    // convert emissivities to luminosities (i.e. multiply by the wavelength bins),
    // multiply by the mass of the population (in solar masses),
    // and return the result
    return NR::resample<NR::interpolate_loglog>(_lambdagrid->lambdav()*(1-z), _lambdav, jv)
                                    * _lambdagrid->dlambdav() * M;
}

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

int Starburst99SEDFamily::nparams() const
{
    return 3;
}

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

Array Starburst99SEDFamily::luminosities_generic(const Array& params, int skipvals, double z) const
{
    return luminosities(params[skipvals], params[skipvals+1], params[skipvals+2], z);
}

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

double Starburst99SEDFamily::mass_generic(const Array& params, int skipvals) const
{
    return params[skipvals];
}

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

QString Starburst99SEDFamily::sourceName() const
{
    return "star";
}

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

QString Starburst99SEDFamily::sourceDescription() const
{
    return "star";
}

//////////////////////////////////////////////////////////////////////
<commit_msg>include mutex header to fix compilation error on Ubuntu<commit_after>/*//////////////////////////////////////////////////////////////////
////       SKIRT -- an advanced radiative transfer code         ////
////       © Astronomical Observatory, Ghent University         ////
///////////////////////////////////////////////////////////////// */

#include <cmath>
#include <fstream>
#include <mutex>
#include "Starburst99SEDFamily.hpp"
#include "FatalError.hpp"
#include "FilePaths.hpp"
#include "Log.hpp"
#include "NR.hpp"
#include "Units.hpp"
#include "WavelengthGrid.hpp"
#include "fitsio.h"

using namespace std;

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

namespace
{
    // number of items in the library read by the constructor
    const int Nlambda = 1221;
    const int NZ = 25;
    const int Nt = 308;
}

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

Starburst99SEDFamily::Starburst99SEDFamily()
{
}

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

Starburst99SEDFamily::Starburst99SEDFamily(SimulationItem* parent)
{
    setParent(parent);
    setup();
}

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

// The functions in this anonymous namespace were backported from the SKIRT8 FITSInOut class.
// They are implemented here to avoid problems with potential incompatibilities in SKIRT7.
// Known problem: if multiple simulations run in parallel within the same process (the -s option),
// the cfitsio library may be invoked concurrently by the SKIRT7 FITSInOut functions and the functions here,
// which may lead to a crash (because our version of cfitsio is not built for concurrency).
namespace
{
    // mutex to guard the FITS input/output operations
    std::mutex _mutex;

    // function to report cfitsio errors
    void report_error(QString filepath, QString action, int status)
    {
        char message[FLEN_STATUS];
        ffgerr(status, message);
        throw FATALERROR("Error while " + action + " FITS file " + filepath + "\n" + QString(message));
    }

    // function to read 2D or 2D data cube from a FITS file
    void read(QString filepath, Array& data, int& nx, int& ny, int& nz)
    {
        // Acquire a global lock since the cfitsio library is not guaranteed to be reentrant
        std::unique_lock<std::mutex> lock(_mutex);

        // Open the FITS file
        int status = 0;
        fitsfile *fptr;
        ffdopn(&fptr, filepath.toLocal8Bit().constData(), READONLY, &status);
        if (status) report_error(filepath, "opening", status);

        // Get the dimensions of the data
        int naxis;
        long naxes[3];
        ffgidm(fptr, &naxis, &status);
        ffgisz(fptr, 3, naxes, &status);
        if (status) report_error(filepath, "reading", status);
        nx = naxis > 0 ? naxes[0] : 1;
        ny = naxis > 1 ? naxes[1] : 1;
        nz = naxis > 2 ? naxes[2] : 1;

        // Resize the data container
        size_t nelements = static_cast<size_t>(nx)*static_cast<size_t>(ny)*static_cast<size_t>(nz);
        data.resize(nelements);

        // Read the array of pixels from the file
        int dummy;
        ffgpvd(fptr, 0, 1, nelements, 0, &data[0], &dummy, &status);
        if (status) report_error(filepath, "reading", status);

        // Close the file
        ffclos(fptr, &status);
        if (status) report_error(filepath, "reading", status);
    }

    // function to read a single table column from a FITS file
    void readColumn(QString filepath, Array& data, int n)
    {
        // Acquire a global lock since the cfitsio library is not guaranteed to be reentrant
        std::unique_lock<std::mutex> lock(_mutex);

        // Open the FITS file
        int status = 0;
        fitsfile *fptr;
        fftopn(&fptr, filepath.toLocal8Bit().constData(), READONLY, &status);
        if (status) report_error(filepath, "opening", status);

        // Get the dimensions of the table
        int ncols = 0;
        ffgncl(fptr, &ncols, &status);
        if (status) report_error(filepath, "reading", status);
        long nrows = 0;
        ffgnrw(fptr, &nrows, &status);
        if (status) report_error(filepath, "reading", status);
        if (ncols<=0 || nrows<n) throw FATALERROR("Not enough table data in FITS file " + filepath);

        // Resize the data container
        data.resize(n);

        // Read the array of values from the first column in the table
        int dummy;
        ffgcvd(fptr, 1, 1, 1, n, 0., &data[0], &dummy, &status);
        if (status) report_error(filepath, "reading", status);

        // Close the file
        ffclos(fptr, &status);
        if (status) report_error(filepath, "reading", status);
    }
}

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

void Starburst99SEDFamily::setupSelfBefore()
{
    SEDFamily::setupSelfBefore();

    // get the resource file path
    QString filepath = FilePaths::resource("SED/Starburst99/Patrik-imfKroupa-Zmulti-ml.fits.gz");
    Log* log = find<Log>();
    log->info("Reading Starburst99 data from file " + filepath + "...");

    // read the wavelength, metallicity, and age vectors from the library
    readColumn(filepath+"[AXES][col lambda]", _lambdav, Nlambda);
    readColumn(filepath+"[AXES][col metallicity]", _Zv, NZ);
    readColumn(filepath+"[AXES][col time]", _tv, Nt);

    // read the emissivity data cube from the library
    Array data;
    int nx, ny, nz;
    read(filepath+"[SED]", data, nx, ny, nz);
    if (nx!=Nt || ny!=NZ || nz!=Nlambda) throw FATALERROR("Starburst99 library data size does not match expectations");
    log->info("File " + filepath + " closed.");

    // copy the emissivity data into the table
    _jvv.resize(Nt, NZ, Nlambda);
    size_t i = 0;
    for (size_t k = 0; k!=Nlambda; ++k)
    {
        for (size_t m = 0; m!=NZ; ++m)
        {
            for (size_t p = 0; p!=Nt; ++p)
            {
                _jvv(p, m, k) = pow(10., data[i++]);  // stored in file as log10
            }
        }
    }

    // cache the simulation's wavelength grid
    _lambdagrid = find<WavelengthGrid>();
}

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

Array Starburst99SEDFamily::luminosities(double M, double Z, double t, double z) const
{
    // find the appropriate SED from interpolating in the BC library
    int mL, mR;
    double hZ = 0.0;
    if (Z<=_Zv[0])
        mL = mR = 0;
    else if (Z>=_Zv[NZ-1])
        mL = mR = NZ-1;
    else
    {
        mL = NR::locate_clip(_Zv,Z);
        mR = mL+1;
        double ZL = _Zv[mL];
        double ZR = _Zv[mR];
        hZ = (Z-ZL)/(ZR-ZL);
    }
    int pL, pR;
    double ht = 0.0;
    if (t<=_tv[0])
        pL = pR = 0;
    else if (t>=_tv[Nt-1])
        pL = pR = Nt-1;
    else
    {
        pL = NR::locate_clip(_tv,t);
        pR = pL+1;
        double tL = _tv[pL];
        double tR = _tv[pR];
        ht = (t-tL)/(tR-tL);
    }
    const Array& jLLv = _jvv(pL,mL);
    const Array& jLRv = _jvv(pL,mR);
    const Array& jRLv = _jvv(pR,mL);
    const Array& jRRv = _jvv(pR,mR);
    Array jv(Nlambda);
    for (int k=0; k<Nlambda; k++)
        jv[k] = (1.0-ht)*(1.0-hZ)*jLLv[k]
                + (1.0-ht)*hZ*jLRv[k]
                + ht*(1.0-hZ)*jRLv[k]
                + ht*hZ*jRRv[k];

    // resample to the possibly redshifted simulation wavelength grid,
    // convert emissivities to luminosities (i.e. multiply by the wavelength bins),
    // multiply by the mass of the population (in solar masses),
    // and return the result
    return NR::resample<NR::interpolate_loglog>(_lambdagrid->lambdav()*(1-z), _lambdav, jv)
                                    * _lambdagrid->dlambdav() * M;
}

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

int Starburst99SEDFamily::nparams() const
{
    return 3;
}

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

Array Starburst99SEDFamily::luminosities_generic(const Array& params, int skipvals, double z) const
{
    return luminosities(params[skipvals], params[skipvals+1], params[skipvals+2], z);
}

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

double Starburst99SEDFamily::mass_generic(const Array& params, int skipvals) const
{
    return params[skipvals];
}

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

QString Starburst99SEDFamily::sourceName() const
{
    return "star";
}

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

QString Starburst99SEDFamily::sourceDescription() const
{
    return "star";
}

//////////////////////////////////////////////////////////////////////
<|endoftext|>


<commit_before>#include "Entity.h"

Entity::Entity(){}
Entity::~Entity(){}

int Entity::SyncComponents()
{
	int result = 1;
	if (this->m_pComp != nullptr)
	{
		if (this->m_aiComp != nullptr)
		{
			// Works for now since we're only handling platforms
			if (this->m_aiComp->AC_triggered && !this->m_aiComp->AC_finished)
				this->m_pComp->PC_velocity = DirectX::XMVectorScale(this->m_aiComp->AC_dir, this->m_aiComp->AC_speed);
			else
				this->m_pComp->PC_velocity = { 0 };
			this->m_aiComp->AC_position = this->m_pComp->PC_pos;
			//TODO: test physcomp vs aicomp positions are still updated after they are released from duty
		}
		if (this->m_gComp != nullptr)
		{
			//rotate and translate the obb in the game
			if (this->m_pComp->PC_BVtype == BV_OBB)
			{
				if (this->GetGraphicComponent()->modelID == 1117267500 || this->GetGraphicComponent()->modelID == 885141774) // 1 or 2 == player
				{
					float offSet = 0.0f;
					if (this->GetGraphicComponent()->modelID == 1117267500) //Studley
					{
						offSet = 0.15f;
					}
					else if (this->GetGraphicComponent()->modelID == 885141774) // Abbington
					{
						offSet = -0.05f;
					}
					this->m_gComp->worldMatrix = DirectX::XMMatrixMultiply(this->m_pComp->PC_OBB.ort, DirectX::XMMatrixTranslationFromVector(this->m_pComp->PC_pos));
					this->m_gComp->worldMatrix = DirectX::XMMatrixMultiply(this->m_gComp->worldMatrix, DirectX::XMMatrixTranslationFromVector(DirectX::XMVectorSet(0, -this->m_pComp->PC_OBB.ext[1] + offSet, 0, 0)));
				}
				else
				{
					this->m_gComp->worldMatrix = DirectX::XMMatrixMultiply(this->m_pComp->PC_OBB.ort, DirectX::XMMatrixTranslationFromVector(this->m_pComp->PC_pos));
				}
			}
			else
			{
				this->m_gComp->worldMatrix = DirectX::XMMatrixMultiply(DirectX::XMMatrixRotationRollPitchYawFromVector(this->m_pComp->PC_rotation), DirectX::XMMatrixTranslationFromVector(this->m_pComp->PC_pos));
			}

			result = 1;
		}
		else
		{
			result = -2;
		}
	}
	else
	{
		if (this->m_gComp == nullptr)
		{
			result = -3;
		}
		result = -1;
	}
	return result;
}

int Entity::AddObserver(Observer * observer, int entityID)
{
	this->m_subject.AddObserver(observer, entityID);
	return 1;
}

void Entity::UnsafeSyncComponents()
{
	//rotate and translate the obb in the game
	if (this->m_pComp->PC_BVtype == BV_OBB)
	{
		if (this->GetGraphicComponent()->modelID == 1117267500 || this->GetGraphicComponent()->modelID == 885141774) // 1 or 2 == player
		{
			float offSet = 0.0f;
			if (this->GetGraphicComponent()->modelID == 1117267500) //Studley
			{
				offSet = -0.05f;
			}
			else if (this->GetGraphicComponent()->modelID == 885141774) // Abbington
			{
				offSet = 0.15f;
			}
			this->m_gComp->worldMatrix = DirectX::XMMatrixMultiply(this->m_pComp->PC_OBB.ort, DirectX::XMMatrixTranslationFromVector(this->m_pComp->PC_pos));
			this->m_gComp->worldMatrix = DirectX::XMMatrixMultiply(this->m_gComp->worldMatrix, DirectX::XMMatrixTranslationFromVector(DirectX::XMVectorSet(0, -this->m_pComp->PC_OBB.ext[1] + offSet, 0, 0)));
		}
		else
		{
			this->m_gComp->worldMatrix = DirectX::XMMatrixMultiply(this->m_pComp->PC_OBB.ort, DirectX::XMMatrixTranslationFromVector(this->m_pComp->PC_pos));
		}
	}
	else
	{
		this->m_gComp->worldMatrix = DirectX::XMMatrixMultiply(DirectX::XMMatrixRotationRollPitchYawFromVector(this->m_pComp->PC_rotation), DirectX::XMMatrixTranslationFromVector(this->m_pComp->PC_pos));
	}
}

PhysicsComponent* Entity::SetPhysicsComponent(PhysicsComponent * pComp)
{
	PhysicsComponent* tempReturn = this->m_pComp;
	this->m_pComp = pComp;
	return tempReturn;
}

GraphicsComponent* Entity::SetGraphicsComponent(GraphicsComponent * gComp)
{
	GraphicsComponent* tempReturn = this->m_gComp;
	this->m_gComp = gComp;
	return tempReturn;
}

AIComponent * Entity::SetAIComponent(AIComponent * aiComp)
{
	AIComponent* tempReturn = this->m_aiComp;
	this->m_aiComp = aiComp;
	return tempReturn;
}

AnimationComponent * Entity::SetAnimationComponent(AnimationComponent * aComp)
{
	AnimationComponent* tempReturn = this->m_aComp;
	this->m_aComp = aComp;
	return tempReturn;
}

bool Entity::SetGrabbed(Entity* isGrabbedBy)
{
	bool lastValue = this->m_isGrabbed;;
	this->m_isGrabbedBy = isGrabbedBy;

	if (this->m_isGrabbedBy != nullptr)
	{
		this->m_isGrabbed = true;
		//Deactivate the component
		this->m_pComp->PC_active = false;
		this->m_pComp->PC_velocity = DirectX::XMVectorSet(0, 0, 0, 0);
	}
	else
	{
		this->m_isGrabbed = false;
		this->m_pComp->PC_active = true;
	}
	return lastValue;
}

bool Entity::IsGrabbed()
{
	return this->m_isGrabbed;
}

int Entity::SetEntityID(int entityID)
{
	int lastValue = this->m_entityID;
	this->m_entityID = entityID;
	return lastValue;
}

PhysicsComponent * Entity::GetPhysicsComponent()
{
	return this->m_pComp;
}

GraphicsComponent * Entity::GetGraphicComponent()
{
	return this->m_gComp;
}

AIComponent * Entity::GetAIComponent()
{
	return this->m_aiComp;
}

AnimationComponent * Entity::GetAnimationComponent()
{
	return this->m_aComp;
}

bool Entity::GetGrabbed()
{
	return this->m_isGrabbed;
}

int Entity::GetEntityID()
{
	return this->m_entityID;
}

int Entity::InitializeBase(int entityID, PhysicsComponent* pComp, GraphicsComponent* gComp, AnimationComponent* aComp, AIComponent* aiComp)
{
	int result = 1;
	this->m_isGrabbed = false;
	this->m_subject = Subject();
	this->m_entityID = entityID;
	this->m_pComp = pComp;
	this->m_gComp = gComp;
	this->m_aComp = aComp;
	this->m_aiComp = aiComp;
	this->m_isGrabbedBy = nullptr;
	return result;
}
<commit_msg>UPDATE changed player offset again to test over network<commit_after>#include "Entity.h"

Entity::Entity(){}
Entity::~Entity(){}

int Entity::SyncComponents()
{
	int result = 1;
	if (this->m_pComp != nullptr)
	{
		if (this->m_aiComp != nullptr)
		{
			// Works for now since we're only handling platforms
			if (this->m_aiComp->AC_triggered && !this->m_aiComp->AC_finished)
				this->m_pComp->PC_velocity = DirectX::XMVectorScale(this->m_aiComp->AC_dir, this->m_aiComp->AC_speed);
			else
				this->m_pComp->PC_velocity = { 0 };
			this->m_aiComp->AC_position = this->m_pComp->PC_pos;
			//TODO: test physcomp vs aicomp positions are still updated after they are released from duty
		}
		if (this->m_gComp != nullptr)
		{
			//rotate and translate the obb in the game
			if (this->m_pComp->PC_BVtype == BV_OBB)
			{
				if (this->GetGraphicComponent()->modelID == 1117267500 || this->GetGraphicComponent()->modelID == 885141774) // 1 or 2 == player
				{
					float offSet = 0.0f;
					if (this->GetGraphicComponent()->modelID == 1117267500) //Studley
					{
						offSet = 0.05f;
					}
					else if (this->GetGraphicComponent()->modelID == 885141774) // Abbington
					{
						offSet = 0.15f;
					}
					this->m_gComp->worldMatrix = DirectX::XMMatrixMultiply(this->m_pComp->PC_OBB.ort, DirectX::XMMatrixTranslationFromVector(this->m_pComp->PC_pos));
					this->m_gComp->worldMatrix = DirectX::XMMatrixMultiply(this->m_gComp->worldMatrix, DirectX::XMMatrixTranslationFromVector(DirectX::XMVectorSet(0, -this->m_pComp->PC_OBB.ext[1] + offSet, 0, 0)));
				}
				else
				{
					this->m_gComp->worldMatrix = DirectX::XMMatrixMultiply(this->m_pComp->PC_OBB.ort, DirectX::XMMatrixTranslationFromVector(this->m_pComp->PC_pos));
				}
			}
			else
			{
				this->m_gComp->worldMatrix = DirectX::XMMatrixMultiply(DirectX::XMMatrixRotationRollPitchYawFromVector(this->m_pComp->PC_rotation), DirectX::XMMatrixTranslationFromVector(this->m_pComp->PC_pos));
			}

			result = 1;
		}
		else
		{
			result = -2;
		}
	}
	else
	{
		if (this->m_gComp == nullptr)
		{
			result = -3;
		}
		result = -1;
	}
	return result;
}

int Entity::AddObserver(Observer * observer, int entityID)
{
	this->m_subject.AddObserver(observer, entityID);
	return 1;
}

void Entity::UnsafeSyncComponents()
{
	//rotate and translate the obb in the game
	if (this->m_pComp->PC_BVtype == BV_OBB)
	{
		if (this->GetGraphicComponent()->modelID == 1117267500 || this->GetGraphicComponent()->modelID == 885141774) // 1 or 2 == player
		{
			float offSet = 0.0f;
			if (this->GetGraphicComponent()->modelID == 1117267500) //Studley
			{
				offSet = 0.05f;
			}
			else if (this->GetGraphicComponent()->modelID == 885141774) // Abbington
			{
				offSet = 0.15f;
			}
			this->m_gComp->worldMatrix = DirectX::XMMatrixMultiply(this->m_pComp->PC_OBB.ort, DirectX::XMMatrixTranslationFromVector(this->m_pComp->PC_pos));
			this->m_gComp->worldMatrix = DirectX::XMMatrixMultiply(this->m_gComp->worldMatrix, DirectX::XMMatrixTranslationFromVector(DirectX::XMVectorSet(0, -this->m_pComp->PC_OBB.ext[1] + offSet, 0, 0)));
		}
		else
		{
			this->m_gComp->worldMatrix = DirectX::XMMatrixMultiply(this->m_pComp->PC_OBB.ort, DirectX::XMMatrixTranslationFromVector(this->m_pComp->PC_pos));
		}
	}
	else
	{
		this->m_gComp->worldMatrix = DirectX::XMMatrixMultiply(DirectX::XMMatrixRotationRollPitchYawFromVector(this->m_pComp->PC_rotation), DirectX::XMMatrixTranslationFromVector(this->m_pComp->PC_pos));
	}
}

PhysicsComponent* Entity::SetPhysicsComponent(PhysicsComponent * pComp)
{
	PhysicsComponent* tempReturn = this->m_pComp;
	this->m_pComp = pComp;
	return tempReturn;
}

GraphicsComponent* Entity::SetGraphicsComponent(GraphicsComponent * gComp)
{
	GraphicsComponent* tempReturn = this->m_gComp;
	this->m_gComp = gComp;
	return tempReturn;
}

AIComponent * Entity::SetAIComponent(AIComponent * aiComp)
{
	AIComponent* tempReturn = this->m_aiComp;
	this->m_aiComp = aiComp;
	return tempReturn;
}

AnimationComponent * Entity::SetAnimationComponent(AnimationComponent * aComp)
{
	AnimationComponent* tempReturn = this->m_aComp;
	this->m_aComp = aComp;
	return tempReturn;
}

bool Entity::SetGrabbed(Entity* isGrabbedBy)
{
	bool lastValue = this->m_isGrabbed;;
	this->m_isGrabbedBy = isGrabbedBy;

	if (this->m_isGrabbedBy != nullptr)
	{
		this->m_isGrabbed = true;
		//Deactivate the component
		this->m_pComp->PC_active = false;
		this->m_pComp->PC_velocity = DirectX::XMVectorSet(0, 0, 0, 0);
	}
	else
	{
		this->m_isGrabbed = false;
		this->m_pComp->PC_active = true;
	}
	return lastValue;
}

bool Entity::IsGrabbed()
{
	return this->m_isGrabbed;
}

int Entity::SetEntityID(int entityID)
{
	int lastValue = this->m_entityID;
	this->m_entityID = entityID;
	return lastValue;
}

PhysicsComponent * Entity::GetPhysicsComponent()
{
	return this->m_pComp;
}

GraphicsComponent * Entity::GetGraphicComponent()
{
	return this->m_gComp;
}

AIComponent * Entity::GetAIComponent()
{
	return this->m_aiComp;
}

AnimationComponent * Entity::GetAnimationComponent()
{
	return this->m_aComp;
}

bool Entity::GetGrabbed()
{
	return this->m_isGrabbed;
}

int Entity::GetEntityID()
{
	return this->m_entityID;
}

int Entity::InitializeBase(int entityID, PhysicsComponent* pComp, GraphicsComponent* gComp, AnimationComponent* aComp, AIComponent* aiComp)
{
	int result = 1;
	this->m_isGrabbed = false;
	this->m_subject = Subject();
	this->m_entityID = entityID;
	this->m_pComp = pComp;
	this->m_gComp = gComp;
	this->m_aComp = aComp;
	this->m_aiComp = aiComp;
	this->m_isGrabbedBy = nullptr;
	return result;
}
<|endoftext|>