<commit_before>/**
 * @file hitbox.cpp
 * @brief Purpose: Contains methods that create and specify a hitbox.
 *
 * MIT License
 * Copyright (c) 2017 MindScape
 *
 * https://github.com/TecProg2017-2/mindscape/blob/master/LICENSE.md
 */

#include <string>
#include <iostream>
#include "hitbox.hpp"
#include <include/log.hpp>

using namespace engine;

/**
 * @brief This method return the width and height of the hitbox.
 *
 * @return std::pair<int, int> Dimensions of the hitbox.
 */
std::pair<int, int> Hitbox::get_dimensions() {
    return std::make_pair(hitbox.w, hitbox.h);
}

/**
 * @brief This method set the width and height of the hitbox.
 *
 * @param p_dimensions is it the pointer that sets the dimensions of hitbox.
 * @return void.
 */
void Hitbox::set_dimensions(std::pair<int, int> p_dimensions) {
    INFO("Setting all dimensions of hitboxes!");

    /*
     * Is the dimensions of the hitbox. w = width and h = height.
     * All the dimensions are in pixels.
     */
    hitbox.w = p_dimensions.first;
    hitbox.h = p_dimensions.second;
}

/**
 * @brief Sets the new coordinate of the hitbox after its movement
 *
 * this method calculate the new coordinate of the hitbox based in the its
 * coordinate plus its coordinate of the movement.
 *
 * @param go_coordinates coordinate that the hitbox will go.
 * @param p_displacement coordinate that the hitbox is.
 * @return void.
 */
void Hitbox::set_displacement(std::pair<int, int> go_coordinates,
    std::pair<int, int> p_displacement) {

    /*
     * Hitbox x and y are the coordinates of the hitbox and your movement.
     * All the coordinates are in pixels.
     */
    hitbox.x = p_displacement.first + go_coordinates.first;
    hitbox.y = p_displacement.second + go_coordinates.second;

    /*
     * Set de displacement of the hitbox.
     */
    Component::set_displacement(p_displacement);
}

/**
 * @brief Update the coordinate of the hitbox after its movement
 *
 * this method updates the coordinate of the hitbox based in the its
 * coordinate plus its coordinate of the movement.
 *
 * @param go_coordinates coordinate that the hitbox will go.
 * @return void.
 */
void Hitbox::update(std::pair<int, int> go_coordinates) {

    /*
     * Hitbox x and y are the update coordinates of the hitbox and your movement.
     * All the coordinates are in pixels.
     */
    hitbox.x = get_displacement().first + go_coordinates.first;
    hitbox.y = get_displacement().second + go_coordinates.second;
}

/**
 * @brief This method gets the coordinates of the hitbox.
 *
 * @return Returns the position in axis X and Y of the hitbox.
 */
std::pair<int, int> Hitbox::get_coordinates() {
    return std::make_pair(hitbox.x, hitbox.y);
}

/**
 * @brief Defines the collides with others hitboxes.
 *
 * this method defines the collision with two hitbox,
 * based in its coordinates and dimensions
 *
 * @param other_hitbox A hitbox object to identify collision between them.
 * @return returns true if the collision was identify.
 */
bool Hitbox::collides_with(Hitbox* other_hitbox) {
    // INFO("Identifies collision with two different hitboxes");

    int left_a = 0; /**< int. Coordinate of the hitbox in axis x */
    int right_a = 0; /**< int. Coordinate in axis x and width of the hitbox */
    int top_a = 0; /**< int. Coordinate of the hitbox in axis y */
    int bottom_a = 0; /**< int. Coordinate in axis y and height of the hitbox */

    /*
     * x coordinate and width's dimension of the hitbox a, respectively
     */
    left_a = hitbox.x;
    right_a = hitbox.x + hitbox.w;

    /*
     * y coordinate and height's dimension of the hitbox a, respectively
     */
    top_a = hitbox.y;
    bottom_a = hitbox.y + hitbox.h;

    /**< pair<int, int>. Dimensions of the hitbox. width and height */
    std::pair<int, int> other_hitbox_dimensions (0, 0);

    /**< pair<int, int>. Coordinates on the axis x and y */
    std::pair<int, int> other_hitbox_coordinates (0, 0);

    other_hitbox_coordinates = other_hitbox->get_coordinates();
    other_hitbox_dimensions = other_hitbox->get_dimensions();

    int left_b = 0; /**< int. Coordinate of the hitbox that will collide in axis x */
    int right_b = 0; /**< int. Coordinate in axis x and width of the hitbox*/

    /*
     * x coordinate and width's dimension of the hitbox b, respectively
     */
    left_b = other_hitbox_coordinates.first;
    right_b = other_hitbox_coordinates.first +
            other_hitbox_dimensions.first;

    int top_b = 0; /**< int. Coordinate of the hitbox in axis y */
    int bottom_b = 0; /**< int. Coordinate in axis y and height of the hitbox */

    /*
     * y coordinate and height's dimension of the hitbox b, respectively
     */
    top_b = other_hitbox_coordinates.second;
    bottom_b = other_hitbox_coordinates.second +
             other_hitbox_dimensions.second;

    if (bottom_a <= top_b) {
        // INFO("Collision of bottom_a hitbox with top_b hitbox");

        /* If the bottom of the hitbox a collides with the top of hitbox b */
        return false;
    }

    if (top_a >= bottom_b) {
        // INFO("Collision of top_a hitbox with bottom_b hitbox");

        /* If the top of the hitbox a collides with the bottom of hitbox b */
        return false;
    }

    if (right_a <= left_b) {
        // INFO("Collision of right_a hitbox with left_b hitbox ");

        /* If the right of the hitbox a collides with the left of hitbox b */
        return false;
    }

    if (left_a >= right_b) {
        // INFO("Collision of left_a hitbox with right_b hitbox ");

        /* If the left of the hitbox a collides with the right of hitbox b */
        return false;
    }

    return true;
}

/**
 * @brief Load and show the hitbox on the screen.
 *
 * this method load an image and initialize as a hitbox.
 *
 * @return void.
 */
void Hitbox::initialize() {
    INFO("Initializing all hitboxes");

    /**<
     * SDL_Surface. Structure that contains a collection of pixels and images of the surface.
     */
    SDL_Surface* loaded_surface = nullptr;
    loaded_surface =
     IMG_Load("../assets/images/scenes/test_scene/Fundo-Vermelho.jpg");

    SDL_Texture* new_texture = nullptr; /**< SDL_Texture. A group of pixels. */

    if (loaded_surface != NULL) {
        /* if the surface image is loaded  */

        INFO("Surfaces' loaded");

        new_texture = SDL_CreateTextureFromSurface(renderer, loaded_surface);

        if (new_texture == NULL) {
            /* if the texture is null  */
            INFO("Unable to create texture from! SDL Error: SDL_GetError()");
        }

        SDL_FreeSurface(loaded_surface);
    }
    else {
        /* print if the image surface is not loaded  */
        INFO("Unable to load image");
    }

    texture = new_texture;
}

/**
 * @brief Shows the image that was loaded and initialized on the screen
 *
 * @return void.
 */
void Hitbox::draw() {
    INFO("Drawing all hitboxes with their dimensions in rectangular format");

    SDL_Rect ret = {0, 0, 0, 0};
    ret = {0, 0, hitbox.w, hitbox.h};

    /**<
     * SDL_Rect. This render_quad tells where the image will appear in the screen.
     */
    SDL_Rect render_quad = {0, 0, 0, 0};
    render_quad = {hitbox.x, hitbox.y, hitbox.w, hitbox.h};

    SDL_RenderCopy(renderer, texture, &ret, &render_quad);
}

/**
 * @brief Help developers to debug the hitboxes.
 *
 * Help developers to debug the hitboxes because it allows you to show all hitboxes.
 *
 * @return if return true, all of hitboxes will be showed on the screen.
 */
bool Hitbox::wanna_draw_hitbox() {
    // INFO("Using a method to help the developer");

    return false;
}
<commit_msg>[ASSERT] Apply technique in hitbox.cpp<commit_after>/**
 * @file hitbox.cpp
 * @brief Purpose: Contains methods that create and specify a hitbox.
 *
 * MIT License
 * Copyright (c) 2017 MindScape
 *
 * https://github.com/TecProg2017-2/mindscape/blob/master/LICENSE.md
 */

#include <string>
#include <iostream>
#include "hitbox.hpp"
#include <include/log.hpp>
#include <assert.h>

using namespace engine;

/**
 * @brief This method return the width and height of the hitbox.
 *
 * @return std::pair<int, int> Dimensions of the hitbox.
 */
std::pair<int, int> Hitbox::get_dimensions() {
    assert(hitbox.w >= 0 && hitbox.h >= 0);

    return std::make_pair(hitbox.w, hitbox.h);
}

/**
 * @brief This method set the width and height of the hitbox.
 *
 * @param p_dimensions is it the pointer that sets the dimensions of hitbox.
 * @return void.
 */
void Hitbox::set_dimensions(std::pair<int, int> p_dimensions) {
    INFO("Setting all dimensions of hitboxes!");
    assert(p_dimensions.first >= 0 && p_dimensions.second >= 0);

    /*
     * Is the dimensions of the hitbox. w = width and h = height.
     * All the dimensions are in pixels.
     */
    hitbox.w = p_dimensions.first;
    hitbox.h = p_dimensions.second;
}

/**
 * @brief Sets the new coordinate of the hitbox after its movement
 *
 * this method calculate the new coordinate of the hitbox based in the its
 * coordinate plus its coordinate of the movement.
 *
 * @param go_coordinates coordinate that the hitbox will go.
 * @param p_displacement coordinate that the hitbox is.
 * @return void.
 */
void Hitbox::set_displacement(std::pair<int, int> go_coordinates,
    std::pair<int, int> p_displacement) {
    assert(go_coordinates.first >= 0 && go_coordinates.second >= 0);
    assert(p_displacement.first >= 0 && p_displacement.second >= 0);

    /*
     * Hitbox x and y are the coordinates of the hitbox and your movement.
     * All the coordinates are in pixels.
     */
    hitbox.x = p_displacement.first + go_coordinates.first;
    hitbox.y = p_displacement.second + go_coordinates.second;

    /*
     * Set de displacement of the hitbox.
     */
    Component::set_displacement(p_displacement);
}

/**
 * @brief Update the coordinate of the hitbox after its movement
 *
 * this method updates the coordinate of the hitbox based in the its
 * coordinate plus its coordinate of the movement.
 *
 * @param go_coordinates coordinate that the hitbox will go.
 * @return void.
 */
void Hitbox::update(std::pair<int, int> go_coordinates) {
    /*
     * Hitbox x and y are the update coordinates of the hitbox and your movement.
     * All the coordinates are in pixels.
     */
    hitbox.x = get_displacement().first + go_coordinates.first;
    hitbox.y = get_displacement().second + go_coordinates.second;
}

/**
 * @brief This method gets the coordinates of the hitbox.
 *
 * @return Returns the position in axis X and Y of the hitbox.
 */
std::pair<int, int> Hitbox::get_coordinates() {
    std::pair<int, int> coordinates = std::make_pair(hitbox.x, hitbox.y);
    return coordinates;
}

/**
 * @brief Defines the collides with others hitboxes.
 *
 * this method defines the collision with two hitbox,
 * based in its coordinates and dimensions
 *
 * @param other_hitbox A hitbox object to identify collision between them.
 * @return returns true if the collision was identify.
 */
bool Hitbox::collides_with(Hitbox* other_hitbox) {
    // INFO("Identifies collision with two different hitboxes");
    //assert(other_hitbox);

    int left_a = 0; /**< int. Coordinate of the hitbox in axis x */
    int right_a = 0; /**< int. Coordinate in axis x and width of the hitbox */
    int top_a = 0; /**< int. Coordinate of the hitbox in axis y */
    int bottom_a = 0; /**< int. Coordinate in axis y and height of the hitbox */

    /*
     * x coordinate and width's dimension of the hitbox a, respectively
     */
    left_a = hitbox.x;
    right_a = hitbox.x + hitbox.w;

    /*
     * y coordinate and height's dimension of the hitbox a, respectively
     */
    top_a = hitbox.y;
    bottom_a = hitbox.y + hitbox.h;

    /**< pair<int, int>. Dimensions of the hitbox. width and height */
    std::pair<int, int> other_hitbox_dimensions (0, 0);

    /**< pair<int, int>. Coordinates on the axis x and y */
    std::pair<int, int> other_hitbox_coordinates (0, 0);

    other_hitbox_coordinates = other_hitbox->get_coordinates();
    other_hitbox_dimensions = other_hitbox->get_dimensions();

    int left_b = 0; /**< int. Coordinate of the hitbox that will collide in axis x */
    int right_b = 0; /**< int. Coordinate in axis x and width of the hitbox*/

    /*
     * x coordinate and width's dimension of the hitbox b, respectively
     */
    left_b = other_hitbox_coordinates.first;
    right_b = other_hitbox_coordinates.first +
            other_hitbox_dimensions.first;

    int top_b = 0; /**< int. Coordinate of the hitbox in axis y */
    int bottom_b = 0; /**< int. Coordinate in axis y and height of the hitbox */

    /*
     * y coordinate and height's dimension of the hitbox b, respectively
     */
    top_b = other_hitbox_coordinates.second;
    bottom_b = other_hitbox_coordinates.second +
             other_hitbox_dimensions.second;

    if (bottom_a <= top_b) {
        // INFO("Collision of bottom_a hitbox with top_b hitbox");

        /* If the bottom of the hitbox a collides with the top of hitbox b */
        return false;
    }

    if (top_a >= bottom_b) {
        // INFO("Collision of top_a hitbox with bottom_b hitbox");

        /* If the top of the hitbox a collides with the bottom of hitbox b */
        return false;
    }

    if (right_a <= left_b) {
        // INFO("Collision of right_a hitbox with left_b hitbox ");

        /* If the right of the hitbox a collides with the left of hitbox b */
        return false;
    }

    if (left_a >= right_b) {
        // INFO("Collision of left_a hitbox with right_b hitbox ");

        /* If the left of the hitbox a collides with the right of hitbox b */
        return false;
    }

    return true;
}

/**
 * @brief Load and show the hitbox on the screen.
 *
 * this method load an image and initialize as a hitbox.
 *
 * @return void.
 */
void Hitbox::initialize() {
    INFO("Initializing all hitboxes");

    /**<
     * SDL_Surface. Structure that contains a collection of pixels and images of the surface.
     */
    SDL_Surface* loaded_surface = nullptr;
    loaded_surface =
     IMG_Load("../assets/images/scenes/test_scene/Fundo-Vermelho.jpg");

    SDL_Texture* new_texture = nullptr; /**< SDL_Texture. A group of pixels. */

    if (loaded_surface != NULL) {
        /* if the surface image is loaded  */

        INFO("Surfaces' loaded");

        new_texture = SDL_CreateTextureFromSurface(renderer, loaded_surface);

        assert(new_texture);

        if (new_texture == NULL) {
            /* if the texture is null  */
            INFO("Unable to create texture from! SDL Error: SDL_GetError()");
        }

        SDL_FreeSurface(loaded_surface);
    }
    else {
        /* print if the image surface is not loaded  */
        INFO("Unable to load image");
    }

    texture = new_texture;
}

/**
 * @brief Shows the image that was loaded and initialized on the screen
 *
 * @return void.
 */
void Hitbox::draw() {
    INFO("Drawing all hitboxes with their dimensions in rectangular format");

    SDL_Rect ret = {0, 0, 0, 0};
    ret = {0, 0, hitbox.w, hitbox.h};

    /**<
     * SDL_Rect. This render_quad tells where the image will appear in the screen.
     */
    SDL_Rect render_quad = {0, 0, 0, 0};
    render_quad = {hitbox.x, hitbox.y, hitbox.w, hitbox.h};

    SDL_RenderCopy(renderer, texture, &ret, &render_quad);
}

/**
 * @brief Help developers to debug the hitboxes.
 *
 * Help developers to debug the hitboxes because it allows you to show all hitboxes.
 *
 * @return if return true, all of hitboxes will be showed on the screen.
 */
bool Hitbox::wanna_draw_hitbox() {
    // INFO("Using a method to help the developer");

    return false;
}
<|endoftext|>


<commit_before>#include <babylon/materials/textures/raw_texture_3d.h>

#include <babylon/engines/engine.h>
#include <babylon/engines/scene.h>
#include <babylon/materials/textures/internal_texture.h>

namespace BABYLON {

RawTexture3D::RawTexture3D(const ArrayBufferView& data, int width, int height,
                           int depth, unsigned int iFormat, Scene* scene,
                           bool generateMipMaps, bool iInvertY,
                           unsigned int iSamplingMode,
                           unsigned int iTextureType)
    : Texture{nullptr, scene, !generateMipMaps, iInvertY}, format{iFormat}
{
  _engine = scene->getEngine();

  _texture = scene->getEngine()->createRawTexture3D(data,            //
                                                    width,           //
                                                    height,          //
                                                    depth,           //
                                                    iFormat,         //
                                                    generateMipMaps, //
                                                    invertY,         //
                                                    iSamplingMode,   //
                                                    "",              //
                                                    iTextureType     //
  );

  is3D = true;
}

RawTexture3D::~RawTexture3D() = default;

void RawTexture3D::update(const ArrayBufferView& data)
{
  if (!_texture) {
    return;
  }
  _engine->updateRawTexture3D(_texture, data, _texture->format,
                              _texture->invertY, "", _texture->type);
}

} // end of namespace BABYLON
<commit_msg>Formatted RawTexture3D class<commit_after>#include <babylon/materials/textures/raw_texture_3d.h>

#include <babylon/engines/engine.h>
#include <babylon/engines/scene.h>
#include <babylon/materials/textures/internal_texture.h>

namespace BABYLON {

RawTexture3D::RawTexture3D(const ArrayBufferView& data, int width, int height, int depth,
                           unsigned int iFormat, Scene* scene, bool generateMipMaps, bool iInvertY,
                           unsigned int iSamplingMode, unsigned int iTextureType)
    : Texture{nullptr, scene, !generateMipMaps, iInvertY}, format{iFormat}
{
  _engine = scene->getEngine();

  _texture = scene->getEngine()->createRawTexture3D(data,            //
                                                    width,           //
                                                    height,          //
                                                    depth,           //
                                                    iFormat,         //
                                                    generateMipMaps, //
                                                    invertY,         //
                                                    iSamplingMode,   //
                                                    "",              //
                                                    iTextureType     //
  );

  is3D = true;
}

RawTexture3D::~RawTexture3D() = default;

void RawTexture3D::update(const ArrayBufferView& data)
{
  if (!_texture) {
    return;
  }
  _engine->updateRawTexture3D(_texture, data, _texture->format, _texture->invertY, "",
                              _texture->type);
}

} // end of namespace BABYLON
<|endoftext|>


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

   The MIT License

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

   License for the specific language governing rights and limitations under
   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.

   author: Moritz Dannhauer
   last change: 4/22/14
*/

#include <gtest/gtest.h>
#include <Core/Algorithms/Math/ConvertMatrixType.h>
#include <Core/Datatypes/DenseMatrix.h>
#include <Core/Datatypes/SparseRowMatrix.h>
#include <Core/Datatypes/MatrixComparison.h>
#include <Core/Datatypes/MatrixTypeConversions.h>

using namespace SCIRun;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Core::Algorithms::Math;

DenseColumnMatrixHandle CreateColumnMatrix()
{
    DenseColumnMatrixHandle m(boost::make_shared<DenseColumnMatrix>(3));

    (*m)(0) = 1;
    (*m)(1) = 2;
    (*m)(2) = 3;

    return m;
}

SparseRowMatrixHandle CreateSparseMatrixWithOneColumn()
{
    SparseRowMatrixHandle m(boost::make_shared<SparseRowMatrix>(3,1));
    m->insert(0,0) = 1;
    m->insert(1,0) = 2;
    m->insert(2,0) = 3;
    m->makeCompressed();
    return m;
}

DenseColumnMatrixHandle CreateColumnMatrix_2()
{
    DenseColumnMatrixHandle m(boost::make_shared<DenseColumnMatrix>(3));

    (*m)(0) = 1;
    (*m)(1) = 0;
    (*m)(2) = 0;
    return m;
}

DenseMatrixHandle CreateDenseMatrix_2()
{
    DenseMatrixHandle m(boost::make_shared<DenseMatrix>(3,3));

    (*m)(0,0) = 1;
    (*m)(0,1) = 0;
    (*m)(0,2) = 0;
    (*m)(1,0) = 0;
    (*m)(1,1) = 2;
    (*m)(1,2) = 0;
    (*m)(2,0) = 0;
    (*m)(2,1) = 0;
    (*m)(2,2) = 3;

    return m;
}

SparseRowMatrixHandle CreateSparseMatrix()
{
    SparseRowMatrixHandle m(boost::make_shared<SparseRowMatrix>(3,3));
    m->insert(0,0) = 1;
    m->insert(1,1) = 2;
    m->insert(2,2) = 3;
    m->makeCompressed();
    return m;
}

DenseMatrixHandle CreateDenseMatrix()
{
    DenseMatrixHandle m(boost::make_shared<DenseMatrix>(3,1));

    (*m)(0,0) = 1;
    (*m)(1,0) = 2;
    (*m)(2,0) = 3;

    return m;
}

TEST(ConvertMatrixTests, EmptyInput)
{
  ConvertMatrixTypeAlgorithm algo;

  MatrixHandle output_matrix1;

  try
  {
   output_matrix1 = algo.run(0);
  }
  catch(...)
  {

  }

  if (!output_matrix1)
  {
   FAIL() << "ERROR: zero input for ConvertMatrixTypeAlgorithm does not work." << std::endl;

  }

  MatrixHandle output_matrix2;
  try
  {
    output_matrix2 = algo.run(MatrixHandle());
  }
  catch(...)
  {

  }

  if (!output_matrix2)
  {
   FAIL() << "ERROR: MatrixHandle input for ConvertMatrixTypeAlgorithm does not work." << std::endl;
  }

}

TEST(ConvertMatrixTests, PassInputThrough)
{

  ConvertMatrixTypeAlgorithm algo;

  algo.set(ConvertMatrixTypeAlgorithm::PassThrough(), true);
  algo.set(ConvertMatrixTypeAlgorithm::ConvertToColumnMatrix(), false);
  algo.set(ConvertMatrixTypeAlgorithm::ConvertToDenseMatrix(), false);
  algo.set(ConvertMatrixTypeAlgorithm::ConvertToSparseRowMatrix(), false);

  MatrixHandle input1(CreateDenseMatrix());
  MatrixHandle output_matrix1 = algo.run(input1);

  if (!output_matrix1)
  {
   FAIL() << "ERROR: DenseMatrix input for ConvertMatrixTypeAlgorithm does not work." << std::endl;
  }

  auto out1 = matrix_cast::as_dense(output_matrix1);
  auto in1 = matrix_cast::as_dense(input1);

  EXPECT_EQ(in1->nrows(), out1->nrows());
  EXPECT_EQ(in1->ncols(), out1->ncols());

  for (int i = 0; i < output_matrix1->nrows(); i++)
   for (int j = 0; j < output_matrix1->ncols(); j++)
        EXPECT_EQ((*in1)(i, j),(*out1)(i, j));

  MatrixHandle input2(CreateColumnMatrix());

  MatrixHandle output_matrix2 = algo.run(input2);
  if (!output_matrix2)
  {
   FAIL() << "ERROR: DenseColumnMatrix input for ConvertMatrixTypeAlgorithm does not work." << std::endl;
  }

  auto out2 = matrix_cast::as_column(output_matrix2);
  auto in2 = matrix_cast::as_column(input2);

  EXPECT_EQ(in2->nrows(), out2->nrows());
  EXPECT_EQ(in2->ncols(), out2->ncols());

  for (int i = 0; i < output_matrix2->nrows(); i++)
   for (int j = 0; j < output_matrix2->ncols(); j++)
        EXPECT_EQ((*in2)(i, j),(*out2)(i, j));

 }

TEST(ConvertMatrixTests, DenseToColumnMatrix)
{
  ConvertMatrixTypeAlgorithm algo;

  algo.set(ConvertMatrixTypeAlgorithm::PassThrough(), false);
  algo.set(ConvertMatrixTypeAlgorithm::ConvertToColumnMatrix(), true);
  algo.set(ConvertMatrixTypeAlgorithm::ConvertToDenseMatrix(), false);
  algo.set(ConvertMatrixTypeAlgorithm::ConvertToSparseRowMatrix(), false);

  MatrixHandle input1(CreateDenseMatrix());
  MatrixHandle output_matrix1 = algo.run(input1);

  auto expected_result = CreateColumnMatrix();
  auto out1 = matrix_cast::as_column(output_matrix1);

  EXPECT_EQ(expected_result->nrows(), out1->nrows());
  EXPECT_EQ(expected_result->ncols(), out1->ncols());

 for (int i = 0; i < out1->nrows(); i++)
   for (int j = 0; j < out1->ncols(); j++)
        EXPECT_EQ((*expected_result)(i, j),(*out1)(i, j));
}

TEST(ConvertMatrixTests, DenseToSparseMatrix)
{
  ConvertMatrixTypeAlgorithm algo;

  algo.set(ConvertMatrixTypeAlgorithm::PassThrough(), false);
  algo.set(ConvertMatrixTypeAlgorithm::ConvertToColumnMatrix(), false);
  algo.set(ConvertMatrixTypeAlgorithm::ConvertToDenseMatrix(), false);
  algo.set(ConvertMatrixTypeAlgorithm::ConvertToSparseRowMatrix(), true);

  MatrixHandle input1(CreateDenseMatrix_2());
  MatrixHandle output_matrix1 = algo.run(input1);

  DenseMatrixHandle input=matrix_cast::as_dense(input1);
  auto output = matrix_cast::as_sparse(output_matrix1);

  EXPECT_EQ(input->nrows(), output->nrows());
  EXPECT_EQ(input->ncols(), output->ncols());

  int count_dense=0;
  for (int i = 0; i < input->nrows(); i++)
   for (int j = 0; j < input->ncols(); j++)
        if ((*input)(i,j)!=0) count_dense++;

  EXPECT_EQ(count_dense, output->nonZeros());

  for (index_type row = 0; row < output->outerSize(); row++)
    {
      for (SparseRowMatrix::InnerIterator it(*output,row); it; ++it)
        EXPECT_EQ(it.value(),(*input)(row, it.index()));
    }

}

TEST(ConvertMatrixTests, ColumnToDenseMatrix)
{
  ConvertMatrixTypeAlgorithm algo;

  algo.set(ConvertMatrixTypeAlgorithm::PassThrough(), false);
  algo.set(ConvertMatrixTypeAlgorithm::ConvertToColumnMatrix(), false);
  algo.set(ConvertMatrixTypeAlgorithm::ConvertToDenseMatrix(), true);
  algo.set(ConvertMatrixTypeAlgorithm::ConvertToSparseRowMatrix(), false);

  MatrixHandle input1(CreateColumnMatrix());
  MatrixHandle output_matrix1 = algo.run(input1);

  auto expected_result = CreateDenseMatrix();
  auto out1 = matrix_cast::as_dense(output_matrix1);

  EXPECT_EQ(expected_result->nrows(), out1->nrows());
  EXPECT_EQ(expected_result->ncols(), out1->ncols());

 for (int i = 0; i < out1->nrows(); i++)
   for (int j = 0; j < out1->ncols(); j++)
        EXPECT_EQ((*expected_result)(i, j),(*out1)(i, j));
}

TEST(ConvertMatrixTests, ColumnToSparseMatrix)
{
  ConvertMatrixTypeAlgorithm algo;

  algo.set(ConvertMatrixTypeAlgorithm::PassThrough(), false);
  algo.set(ConvertMatrixTypeAlgorithm::ConvertToColumnMatrix(), false);
  algo.set(ConvertMatrixTypeAlgorithm::ConvertToDenseMatrix(), false);
  algo.set(ConvertMatrixTypeAlgorithm::ConvertToSparseRowMatrix(), true);

  MatrixHandle input1(CreateColumnMatrix());
  MatrixHandle output_matrix1 = algo.run(input1);

  auto expected_result = CreateSparseMatrixWithOneColumn();
  auto out1 = matrix_cast::as_sparse(output_matrix1);

  EXPECT_EQ(expected_result->nrows(), out1->nrows());
  EXPECT_EQ(expected_result->ncols(), out1->ncols());

  for (int i = 0; i < out1->nrows(); i++)
   for (int j = 0; j < out1->ncols(); j++)
        EXPECT_EQ(expected_result->coeff(i, j),out1->coeff(i, j));
}

TEST(ConvertMatrixTests, SparseToColumnMatrix)
{
  ConvertMatrixTypeAlgorithm algo;

  algo.set(ConvertMatrixTypeAlgorithm::PassThrough(), false);
  algo.set(ConvertMatrixTypeAlgorithm::ConvertToColumnMatrix(), true);
  algo.set(ConvertMatrixTypeAlgorithm::ConvertToDenseMatrix(), false);
  algo.set(ConvertMatrixTypeAlgorithm::ConvertToSparseRowMatrix(), false);

  MatrixHandle input1(CreateSparseMatrixWithOneColumn());
  MatrixHandle output_matrix1 = algo.run(input1);

  auto expected_result = CreateColumnMatrix();
  auto out1 = matrix_cast::as_column(output_matrix1);

  EXPECT_EQ(expected_result->nrows(), out1->nrows());
  EXPECT_EQ(expected_result->ncols(), out1->ncols());

  for (int i = 0; i < out1->nrows(); i++)
   for (int j = 0; j < out1->ncols(); j++)
        EXPECT_EQ(expected_result->coeff(i, j),out1->coeff(i, j));

}

TEST(ConvertMatrixTests, SparseToDenseMatrix)
{
  ConvertMatrixTypeAlgorithm algo;

  algo.set(ConvertMatrixTypeAlgorithm::PassThrough(), false);
  algo.set(ConvertMatrixTypeAlgorithm::ConvertToColumnMatrix(), false);
  algo.set(ConvertMatrixTypeAlgorithm::ConvertToDenseMatrix(), true);
  algo.set(ConvertMatrixTypeAlgorithm::ConvertToSparseRowMatrix(), false);

  MatrixHandle input1(CreateSparseMatrix());
  MatrixHandle output_matrix1 = algo.run(input1);

  auto expected_result = CreateDenseMatrix_2();
  auto out1 = matrix_cast::as_dense(output_matrix1);

  EXPECT_EQ(expected_result->nrows(), out1->nrows());
  EXPECT_EQ(expected_result->ncols(), out1->ncols());

  for (int i = 0; i < out1->nrows(); i++)
   for (int j = 0; j < out1->ncols(); j++)
        EXPECT_EQ(expected_result->coeff(i, j),out1->coeff(i, j));

}
<commit_msg>Fix/improve test<commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

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

   License for the specific language governing rights and limitations under
   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.

   author: Moritz Dannhauer
   last change: 4/22/14
*/

#include <gtest/gtest.h>
#include <Core/Algorithms/Math/ConvertMatrixType.h>
#include <Core/Datatypes/DenseMatrix.h>
#include <Core/Datatypes/SparseRowMatrix.h>
#include <Core/Datatypes/MatrixComparison.h>
#include <Core/Datatypes/MatrixTypeConversions.h>

using namespace SCIRun;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Core::Algorithms::Math;
using namespace SCIRun::Core::Algorithms;

DenseColumnMatrixHandle CreateColumnMatrix()
{
    DenseColumnMatrixHandle m(boost::make_shared<DenseColumnMatrix>(3));

    (*m)(0) = 1;
    (*m)(1) = 2;
    (*m)(2) = 3;

    return m;
}

SparseRowMatrixHandle CreateSparseMatrixWithOneColumn()
{
    SparseRowMatrixHandle m(boost::make_shared<SparseRowMatrix>(3,1));
    m->insert(0,0) = 1;
    m->insert(1,0) = 2;
    m->insert(2,0) = 3;
    m->makeCompressed();
    return m;
}

DenseColumnMatrixHandle CreateColumnMatrix_2()
{
    DenseColumnMatrixHandle m(boost::make_shared<DenseColumnMatrix>(3));

    (*m)(0) = 1;
    (*m)(1) = 0;
    (*m)(2) = 0;
    return m;
}

DenseMatrixHandle CreateDenseMatrix_2()
{
    DenseMatrixHandle m(boost::make_shared<DenseMatrix>(3,3));

    (*m)(0,0) = 1;
    (*m)(0,1) = 0;
    (*m)(0,2) = 0;
    (*m)(1,0) = 0;
    (*m)(1,1) = 2;
    (*m)(1,2) = 0;
    (*m)(2,0) = 0;
    (*m)(2,1) = 0;
    (*m)(2,2) = 3;

    return m;
}

SparseRowMatrixHandle CreateSparseMatrix()
{
    SparseRowMatrixHandle m(boost::make_shared<SparseRowMatrix>(3,3));
    m->insert(0,0) = 1;
    m->insert(1,1) = 2;
    m->insert(2,2) = 3;
    m->makeCompressed();
    return m;
}

DenseMatrixHandle CreateDenseMatrix()
{
    DenseMatrixHandle m(boost::make_shared<DenseMatrix>(3,1));

    (*m)(0,0) = 1;
    (*m)(1,0) = 2;
    (*m)(2,0) = 3;

    return m;
}

TEST(ConvertMatrixTests, EmptyInput)
{
  ConvertMatrixTypeAlgorithm algo;
  EXPECT_THROW(algo.run(0), AlgorithmInputException);
  EXPECT_THROW(algo.run(MatrixHandle()), AlgorithmInputException);
}

TEST(ConvertMatrixTests, PassInputThrough)
{

  ConvertMatrixTypeAlgorithm algo;

  algo.set(ConvertMatrixTypeAlgorithm::PassThrough(), true);
  algo.set(ConvertMatrixTypeAlgorithm::ConvertToColumnMatrix(), false);
  algo.set(ConvertMatrixTypeAlgorithm::ConvertToDenseMatrix(), false);
  algo.set(ConvertMatrixTypeAlgorithm::ConvertToSparseRowMatrix(), false);

  MatrixHandle input1(CreateDenseMatrix());
  MatrixHandle output_matrix1 = algo.run(input1);

  if (!output_matrix1)
  {
   FAIL() << "ERROR: DenseMatrix input for ConvertMatrixTypeAlgorithm does not work." << std::endl;
  }

  auto out1 = matrix_cast::as_dense(output_matrix1);
  auto in1 = matrix_cast::as_dense(input1);

  EXPECT_EQ(in1->nrows(), out1->nrows());
  EXPECT_EQ(in1->ncols(), out1->ncols());

  for (int i = 0; i < output_matrix1->nrows(); i++)
   for (int j = 0; j < output_matrix1->ncols(); j++)
        EXPECT_EQ((*in1)(i, j),(*out1)(i, j));

  MatrixHandle input2(CreateColumnMatrix());

  MatrixHandle output_matrix2 = algo.run(input2);
  if (!output_matrix2)
  {
   FAIL() << "ERROR: DenseColumnMatrix input for ConvertMatrixTypeAlgorithm does not work." << std::endl;
  }

  auto out2 = matrix_cast::as_column(output_matrix2);
  auto in2 = matrix_cast::as_column(input2);

  EXPECT_EQ(in2->nrows(), out2->nrows());
  EXPECT_EQ(in2->ncols(), out2->ncols());

  for (int i = 0; i < output_matrix2->nrows(); i++)
   for (int j = 0; j < output_matrix2->ncols(); j++)
        EXPECT_EQ((*in2)(i, j),(*out2)(i, j));

 }

TEST(ConvertMatrixTests, DenseToColumnMatrix)
{
  ConvertMatrixTypeAlgorithm algo;

  algo.set(ConvertMatrixTypeAlgorithm::PassThrough(), false);
  algo.set(ConvertMatrixTypeAlgorithm::ConvertToColumnMatrix(), true);
  algo.set(ConvertMatrixTypeAlgorithm::ConvertToDenseMatrix(), false);
  algo.set(ConvertMatrixTypeAlgorithm::ConvertToSparseRowMatrix(), false);

  MatrixHandle input1(CreateDenseMatrix());
  MatrixHandle output_matrix1 = algo.run(input1);

  auto expected_result = CreateColumnMatrix();
  auto out1 = matrix_cast::as_column(output_matrix1);

  EXPECT_EQ(expected_result->nrows(), out1->nrows());
  EXPECT_EQ(expected_result->ncols(), out1->ncols());

 for (int i = 0; i < out1->nrows(); i++)
   for (int j = 0; j < out1->ncols(); j++)
        EXPECT_EQ((*expected_result)(i, j),(*out1)(i, j));
}

TEST(ConvertMatrixTests, DenseToSparseMatrix)
{
  ConvertMatrixTypeAlgorithm algo;

  algo.set(ConvertMatrixTypeAlgorithm::PassThrough(), false);
  algo.set(ConvertMatrixTypeAlgorithm::ConvertToColumnMatrix(), false);
  algo.set(ConvertMatrixTypeAlgorithm::ConvertToDenseMatrix(), false);
  algo.set(ConvertMatrixTypeAlgorithm::ConvertToSparseRowMatrix(), true);

  MatrixHandle input1(CreateDenseMatrix_2());
  MatrixHandle output_matrix1 = algo.run(input1);

  DenseMatrixHandle input=matrix_cast::as_dense(input1);
  auto output = matrix_cast::as_sparse(output_matrix1);

  EXPECT_EQ(input->nrows(), output->nrows());
  EXPECT_EQ(input->ncols(), output->ncols());

  int count_dense=0;
  for (int i = 0; i < input->nrows(); i++)
   for (int j = 0; j < input->ncols(); j++)
        if ((*input)(i,j)!=0) count_dense++;

  EXPECT_EQ(count_dense, output->nonZeros());

  for (index_type row = 0; row < output->outerSize(); row++)
    {
      for (SparseRowMatrix::InnerIterator it(*output,row); it; ++it)
        EXPECT_EQ(it.value(),(*input)(row, it.index()));
    }

}

TEST(ConvertMatrixTests, ColumnToDenseMatrix)
{
  ConvertMatrixTypeAlgorithm algo;

  algo.set(ConvertMatrixTypeAlgorithm::PassThrough(), false);
  algo.set(ConvertMatrixTypeAlgorithm::ConvertToColumnMatrix(), false);
  algo.set(ConvertMatrixTypeAlgorithm::ConvertToDenseMatrix(), true);
  algo.set(ConvertMatrixTypeAlgorithm::ConvertToSparseRowMatrix(), false);

  MatrixHandle input1(CreateColumnMatrix());
  MatrixHandle output_matrix1 = algo.run(input1);

  auto expected_result = CreateDenseMatrix();
  auto out1 = matrix_cast::as_dense(output_matrix1);

  EXPECT_EQ(expected_result->nrows(), out1->nrows());
  EXPECT_EQ(expected_result->ncols(), out1->ncols());

 for (int i = 0; i < out1->nrows(); i++)
   for (int j = 0; j < out1->ncols(); j++)
        EXPECT_EQ((*expected_result)(i, j),(*out1)(i, j));
}

TEST(ConvertMatrixTests, ColumnToSparseMatrix)
{
  ConvertMatrixTypeAlgorithm algo;

  algo.set(ConvertMatrixTypeAlgorithm::PassThrough(), false);
  algo.set(ConvertMatrixTypeAlgorithm::ConvertToColumnMatrix(), false);
  algo.set(ConvertMatrixTypeAlgorithm::ConvertToDenseMatrix(), false);
  algo.set(ConvertMatrixTypeAlgorithm::ConvertToSparseRowMatrix(), true);

  MatrixHandle input1(CreateColumnMatrix());
  MatrixHandle output_matrix1 = algo.run(input1);

  auto expected_result = CreateSparseMatrixWithOneColumn();
  auto out1 = matrix_cast::as_sparse(output_matrix1);

  EXPECT_EQ(expected_result->nrows(), out1->nrows());
  EXPECT_EQ(expected_result->ncols(), out1->ncols());

  for (int i = 0; i < out1->nrows(); i++)
   for (int j = 0; j < out1->ncols(); j++)
        EXPECT_EQ(expected_result->coeff(i, j),out1->coeff(i, j));
}

TEST(ConvertMatrixTests, SparseToColumnMatrix)
{
  ConvertMatrixTypeAlgorithm algo;

  algo.set(ConvertMatrixTypeAlgorithm::PassThrough(), false);
  algo.set(ConvertMatrixTypeAlgorithm::ConvertToColumnMatrix(), true);
  algo.set(ConvertMatrixTypeAlgorithm::ConvertToDenseMatrix(), false);
  algo.set(ConvertMatrixTypeAlgorithm::ConvertToSparseRowMatrix(), false);

  MatrixHandle input1(CreateSparseMatrixWithOneColumn());
  MatrixHandle output_matrix1 = algo.run(input1);

  auto expected_result = CreateColumnMatrix();
  auto out1 = matrix_cast::as_column(output_matrix1);

  EXPECT_EQ(expected_result->nrows(), out1->nrows());
  EXPECT_EQ(expected_result->ncols(), out1->ncols());

  for (int i = 0; i < out1->nrows(); i++)
   for (int j = 0; j < out1->ncols(); j++)
        EXPECT_EQ(expected_result->coeff(i, j),out1->coeff(i, j));

}

TEST(ConvertMatrixTests, SparseToDenseMatrix)
{
  ConvertMatrixTypeAlgorithm algo;

  algo.set(ConvertMatrixTypeAlgorithm::PassThrough(), false);
  algo.set(ConvertMatrixTypeAlgorithm::ConvertToColumnMatrix(), false);
  algo.set(ConvertMatrixTypeAlgorithm::ConvertToDenseMatrix(), true);
  algo.set(ConvertMatrixTypeAlgorithm::ConvertToSparseRowMatrix(), false);

  MatrixHandle input1(CreateSparseMatrix());
  MatrixHandle output_matrix1 = algo.run(input1);

  auto expected_result = CreateDenseMatrix_2();
  auto out1 = matrix_cast::as_dense(output_matrix1);

  EXPECT_EQ(expected_result->nrows(), out1->nrows());
  EXPECT_EQ(expected_result->ncols(), out1->ncols());

  for (int i = 0; i < out1->nrows(); i++)
   for (int j = 0; j < out1->ncols(); j++)
        EXPECT_EQ(expected_result->coeff(i, j),out1->coeff(i, j));

}
<|endoftext|>


<commit_before>/**
 *  For conditions of distribution and use, see copyright notice in license.txt
 *
 *  @file   EC_LaserPointer.cpp
 *  @brief  Adds laser pointer to entity.
 */

#define MATH_OGRE_INTEROP
//#include "DebugOperatorNew.h"

#include "EC_LaserPointer.h"

#include "Framework.h"
#include "AttributeMetadata.h"
#include "Renderer.h"
#include "EC_Placeable.h"
#include "Entity.h"
#include "Scene.h"
#include "InputAPI.h"
#include "InputContext.h"
#include "MouseEvent.h"
#include "UiAPI.h"
#include "UiMainWindow.h"
#include "UiGraphicsView.h"
#include "LoggingFunctions.h"
#include "OgreWorld.h"

#include <QTimer>
#include <Ogre.h>

//#include "MemoryLeakCheck.h"

EC_LaserPointer::EC_LaserPointer(Scene *scene) :
    IComponent(scene),
    startPos(this, "Start position"),
    endPos(this, "End position"),
    color(this, "Color", Color(1.0f,0.0f,0.0f,1.0f)),
    enabled(this, "Enabled", false),
    laserObject_(0),
    canUpdate_(true),
    updateInterval_(20),
    id_(""),
    tracking(false)
{
    world_ = scene->GetWorld<OgreWorld>();

    static AttributeMetadata nonDesignableAttrData;
    static bool metadataInitialized = false;
    if(!metadataInitialized)
    {
        nonDesignableAttrData.designable = false;
        metadataInitialized = true;
    }
    startPos.SetMetadata(&nonDesignableAttrData);
    endPos.SetMetadata(&nonDesignableAttrData);

    connect(this, SIGNAL(ParentEntitySet()), this, SLOT(CreateLaser()));
}

EC_LaserPointer::~EC_LaserPointer()
{
    DestroyLaser();
}

bool EC_LaserPointer::IsVisible() const
{
    if (laserObject_)
        return laserObject_->isVisible();
    return false;
}

void EC_LaserPointer::CreateLaser()
{
    if (!ViewEnabled())
        return;
    if (world_.expired())
        return;
    if (laserObject_)
    {
        LogError("EC_LaserPointer::CreateLaser: Laser pointer already created.");
        return;
    }
    Entity *parentEntity = ParentEntity();
    if (!parentEntity)
        return;
    EC_Placeable *placeable = parentEntity->GetComponent<EC_Placeable>().get();
    if (placeable)
        connect(placeable, SIGNAL(AttributeChanged(IAttribute*, AttributeChange::Type)),
            this, SLOT(HandlePlaceableAttributeChange(IAttribute*, AttributeChange::Type)));
    else
        LogWarning("Placeable is not preset, cannot connect to position changes!");

    try
    {
        Ogre::SceneManager *scene = world_.lock()->OgreSceneManager();
        id_ = world_.lock()->Renderer()->GetUniqueObjectName("laser");
        laserObject_ = scene->createManualObject(id_);
        Ogre::SceneNode* laserObjectNode = scene->getRootSceneNode()->createChildSceneNode(id_ + "_node");
        laserMaterial_ = Ogre::MaterialManager::getSingleton().create(id_ + "Material", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
        laserMaterial_->setReceiveShadows(false);
        laserMaterial_->getTechnique(0)->setLightingEnabled(true);
        UpdateColor();
        laserObjectNode->attachObject(laserObject_);

        connect(this, SIGNAL(AttributeChanged(IAttribute*, AttributeChange::Type)), this, SLOT(HandleAttributeChange(IAttribute*, AttributeChange::Type)));

        input_ = framework->Input()->RegisterInputContext(QString::fromStdString(id_), 90);
        input_->SetTakeMouseEventsOverQt(true);
        connect(input_.get(), SIGNAL(MouseMove(MouseEvent*)), this, SLOT(Update(MouseEvent*)));
    }
    catch(const Ogre::Exception &ex)
    {
        LogError("EC_LaserPointer::CreateLaser: an expection occurred: " + std::string(ex.what()));
    }
}

void EC_LaserPointer::DestroyLaser()
{
    if (!ViewEnabled())
        return;
    if (world_.expired())
        return;

    try
    {
        Ogre::SceneManager* scene = world_.lock()->OgreSceneManager();
        Ogre::SceneNode* node = dynamic_cast<Ogre::SceneNode*>(scene->getRootSceneNode()->getChild(id_ + "_node"));
        if (node)
            node->detachObject(id_);
        scene->getRootSceneNode()->removeAndDestroyChild(id_ + "_node");
        scene->destroyManualObject(id_);
    }
    catch (...) { }

    try
    {
       Ogre::MaterialManager::getSingleton().remove(id_ + "Material");
    }
    catch(...) { }

    laserObject_ = 0;
}

void EC_LaserPointer::Update(MouseEvent *e)
{
    if (!ViewEnabled())
        return;
    if (!ParentEntity())
        return;
    if (!tracking)
        return;
    if (world_.expired())
        return;

    if (enabled.Get())
    {
        if (canUpdate_)
        {
            // If mouse cursor is visible (not in first-person mode), see if we are inside the main window or there is a graphics item under the mouse
            if (framework->Input()->IsMouseCursorVisible() && (!IsMouseInsideWindow() || IsItemUnderMouse()))
            {
                laserObject_->clear();
                laserObject_->setVisible(false);
                return;
            }

            laserObject_->setVisible(true);
            RaycastResult *result = world_.lock()->Renderer()->Raycast(e->x, e->y);
            if (result && result->entity && result->entity != ParentEntity())
            {
                EC_Placeable *placeable = ParentEntity()->GetComponent<EC_Placeable>().get();
                if (placeable)
                {
                    float3 position = placeable->transform.Get().pos;
                    if (position != startPos.Get())
                        startPos.Set(position, AttributeChange::Default);
                }
                endPos.Set(result->pos, AttributeChange::Default);
                DisableUpdate();
            }
            else
            {
                laserObject_->clear();
                laserObject_->setVisible(false);
            }
        }
    }
}

void EC_LaserPointer::HandleAttributeChange(IAttribute *attribute, AttributeChange::Type change)
{
    if (!ViewEnabled())
        return;
    if (world_.expired())
        return;
    if (!laserObject_)
        return;

    if (attribute == &color)
    {
        UpdateColor();
        return;
    }
    else if (attribute == &startPos || attribute == &endPos || attribute == &enabled)
    {
        if (enabled.Get())
        {
            laserObject_->clear();
            laserObject_->begin(id_ + "Material", Ogre::RenderOperation::OT_LINE_LIST);
            laserObject_->position(startPos.Get());
            laserObject_->position(endPos.Get());
            laserObject_->end();
            laserObject_->setVisible(true);
        }
        else
        {
            laserObject_->clear();
            laserObject_->setVisible(false);
        }
    }
}

void EC_LaserPointer::HandlePlaceableAttributeChange(IAttribute *attribute, AttributeChange::Type change)
{
    if (attribute->Name() == "Transform") ///< \todo attribute name string comparison is risky - what if the name changes for some reason?
    {
        if (!ViewEnabled())
            return;
        if (world_.expired())
            return;
        if (!tracking || !enabled.Get())
            return;
        if (!canUpdate_)
            return;
        if (!ParentEntity())
            return;
        EC_Placeable *placeable = ParentEntity()->GetComponent<EC_Placeable>().get();
        if (!placeable)
            return;

        float3 position = placeable->transform.Get().pos;
        if (position != startPos.Get())
            startPos.Set(position, AttributeChange::Default);

        // If mouse cursor is visible (not in first-person mode), see if we are inside the main window or there is a graphics item under the mouse
        if (framework->Input()->IsMouseCursorVisible() && (!IsMouseInsideWindow() || IsItemUnderMouse()))
        {
            laserObject_->clear();
            laserObject_->setVisible(false);
            return;
        }

        QPoint scenePos = framework->Ui()->GraphicsView()->mapFromGlobal(QCursor::pos());
        RaycastResult *result = world_.lock()->Renderer()->Raycast(scenePos.x(), scenePos.y());
        if (result && result->entity && result->entity != ParentEntity())
        {
            endPos.Set(result->pos, AttributeChange::Default);
            DisableUpdate();
        }
        else
        {
            laserObject_->clear();
            laserObject_->setVisible(false);
        }
    }
}

void EC_LaserPointer::EnableUpdate()
{
    canUpdate_ = true;
}

void EC_LaserPointer::DisableUpdate()
{
    canUpdate_ = false;
    QTimer::singleShot(updateInterval_, this, SLOT(EnableUpdate()));
}

void EC_LaserPointer::UpdateColor()
{
    if (!ViewEnabled())
        return;
    if (world_.expired())
        return;
    if (laserMaterial_.isNull())
        return;

    laserMaterial_->getTechnique(0)->getPass(0)->setDiffuse(color.Get());
    laserMaterial_->getTechnique(0)->getPass(0)->setAmbient(color.Get());
    laserMaterial_->getTechnique(0)->getPass(0)->setSelfIllumination(color.Get());
}

bool EC_LaserPointer::IsMouseInsideWindow() const
{
    if (!framework->Ui()->MainWindow())
        return false;
    return framework->Ui()->MainWindow()->geometry().contains(QCursor::pos(), true);
}

bool EC_LaserPointer::IsItemUnderMouse() const
{
    if (!framework->Ui()->GraphicsView() || !framework->Ui()->MainWindow())
        return true;
    QPoint scenePos = framework->Ui()->GraphicsView()->mapFromGlobal(QCursor::pos());
    QGraphicsItem *itemUnderMouse = framework->Ui()->GraphicsView()->itemAt(scenePos);
    return (itemUnderMouse != 0 ? true : false);
}
<commit_msg>EC_LaserPointer: use Placeable's world position, in case the Placeble is parented, when settings laser start pos.<commit_after>/**
 *  For conditions of distribution and use, see copyright notice in license.txt
 *
 *  @file   EC_LaserPointer.cpp
 *  @brief  Adds laser pointer to entity.
 */

#define MATH_OGRE_INTEROP
//#include "DebugOperatorNew.h"

#include "EC_LaserPointer.h"

#include "Framework.h"
#include "AttributeMetadata.h"
#include "Renderer.h"
#include "EC_Placeable.h"
#include "Entity.h"
#include "Scene.h"
#include "InputAPI.h"
#include "InputContext.h"
#include "MouseEvent.h"
#include "UiAPI.h"
#include "UiMainWindow.h"
#include "UiGraphicsView.h"
#include "LoggingFunctions.h"
#include "OgreWorld.h"

#include <QTimer>
#include <Ogre.h>

//#include "MemoryLeakCheck.h"

EC_LaserPointer::EC_LaserPointer(Scene *scene) :
    IComponent(scene),
    startPos(this, "Start position"),
    endPos(this, "End position"),
    color(this, "Color", Color(1.0f,0.0f,0.0f,1.0f)),
    enabled(this, "Enabled", false),
    laserObject_(0),
    canUpdate_(true),
    updateInterval_(20),
    id_(""),
    tracking(false)
{
    world_ = scene->GetWorld<OgreWorld>();

    static AttributeMetadata nonDesignableAttrData;
    static bool metadataInitialized = false;
    if(!metadataInitialized)
    {
        nonDesignableAttrData.designable = false;
        metadataInitialized = true;
    }
    startPos.SetMetadata(&nonDesignableAttrData);
    endPos.SetMetadata(&nonDesignableAttrData);

    connect(this, SIGNAL(ParentEntitySet()), this, SLOT(CreateLaser()));
}

EC_LaserPointer::~EC_LaserPointer()
{
    DestroyLaser();
}

bool EC_LaserPointer::IsVisible() const
{
    if (laserObject_)
        return laserObject_->isVisible();
    return false;
}

void EC_LaserPointer::CreateLaser()
{
    if (!ViewEnabled())
        return;
    if (world_.expired())
        return;
    if (laserObject_)
    {
        LogError("EC_LaserPointer::CreateLaser: Laser pointer already created.");
        return;
    }
    Entity *parentEntity = ParentEntity();
    if (!parentEntity)
        return;
    EC_Placeable *placeable = parentEntity->GetComponent<EC_Placeable>().get();
    if (placeable)
        connect(placeable, SIGNAL(AttributeChanged(IAttribute*, AttributeChange::Type)),
            this, SLOT(HandlePlaceableAttributeChange(IAttribute*, AttributeChange::Type)));
    else
        LogWarning("Placeable is not preset, cannot connect to position changes!");

    try
    {
        Ogre::SceneManager *scene = world_.lock()->OgreSceneManager();
        id_ = world_.lock()->Renderer()->GetUniqueObjectName("laser");
        laserObject_ = scene->createManualObject(id_);
        Ogre::SceneNode* laserObjectNode = scene->getRootSceneNode()->createChildSceneNode(id_ + "_node");
        laserMaterial_ = Ogre::MaterialManager::getSingleton().create(id_ + "Material", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
        laserMaterial_->setReceiveShadows(false);
        laserMaterial_->getTechnique(0)->setLightingEnabled(true);
        UpdateColor();
        laserObjectNode->attachObject(laserObject_);

        connect(this, SIGNAL(AttributeChanged(IAttribute*, AttributeChange::Type)), this, SLOT(HandleAttributeChange(IAttribute*, AttributeChange::Type)));

        input_ = framework->Input()->RegisterInputContext(QString::fromStdString(id_), 90);
        input_->SetTakeMouseEventsOverQt(true);
        connect(input_.get(), SIGNAL(MouseMove(MouseEvent*)), this, SLOT(Update(MouseEvent*)));
    }
    catch(const Ogre::Exception &ex)
    {
        LogError("EC_LaserPointer::CreateLaser: an expection occurred: " + std::string(ex.what()));
    }
}

void EC_LaserPointer::DestroyLaser()
{
    if (!ViewEnabled())
        return;
    if (world_.expired())
        return;

    try
    {
        Ogre::SceneManager* scene = world_.lock()->OgreSceneManager();
        Ogre::SceneNode* node = dynamic_cast<Ogre::SceneNode*>(scene->getRootSceneNode()->getChild(id_ + "_node"));
        if (node)
            node->detachObject(id_);
        scene->getRootSceneNode()->removeAndDestroyChild(id_ + "_node");
        scene->destroyManualObject(id_);
    }
    catch (...) { }

    try
    {
       Ogre::MaterialManager::getSingleton().remove(id_ + "Material");
    }
    catch(...) { }

    laserObject_ = 0;
}

void EC_LaserPointer::Update(MouseEvent *e)
{
    if (!ViewEnabled())
        return;
    if (!ParentEntity())
        return;
    if (!tracking)
        return;
    if (world_.expired())
        return;

    if (enabled.Get())
    {
        if (canUpdate_)
        {
            // If mouse cursor is visible (not in first-person mode), see if we are inside the main window or there is a graphics item under the mouse
            if (framework->Input()->IsMouseCursorVisible() && (!IsMouseInsideWindow() || IsItemUnderMouse()))
            {
                laserObject_->clear();
                laserObject_->setVisible(false);
                return;
            }

            laserObject_->setVisible(true);
            RaycastResult *result = world_.lock()->Renderer()->Raycast(e->x, e->y);
            if (result && result->entity && result->entity != ParentEntity())
            {
                EC_Placeable *placeable = ParentEntity()->GetComponent<EC_Placeable>().get();
                if (placeable)
                {
                    float3 position = placeable->WorldPosition();
                    if (!position.Equals(startPos.Get()))
                        startPos.Set(position, AttributeChange::Default);
                }
                endPos.Set(result->pos, AttributeChange::Default);
                DisableUpdate();
            }
            else
            {
                laserObject_->clear();
                laserObject_->setVisible(false);
            }
        }
    }
}

void EC_LaserPointer::HandleAttributeChange(IAttribute *attribute, AttributeChange::Type change)
{
    if (!ViewEnabled())
        return;
    if (world_.expired())
        return;
    if (!laserObject_)
        return;

    if (attribute == &color)
    {
        UpdateColor();
        return;
    }
    else if (attribute == &startPos || attribute == &endPos || attribute == &enabled)
    {
        if (enabled.Get())
        {
            laserObject_->clear();
            laserObject_->begin(id_ + "Material", Ogre::RenderOperation::OT_LINE_LIST);
            laserObject_->position(startPos.Get());
            laserObject_->position(endPos.Get());
            laserObject_->end();
            laserObject_->setVisible(true);
        }
        else
        {
            laserObject_->clear();
            laserObject_->setVisible(false);
        }
    }
}

void EC_LaserPointer::HandlePlaceableAttributeChange(IAttribute *attribute, AttributeChange::Type change)
{
    if (attribute->Name() == "Transform") ///< \todo attribute name string comparison is risky - what if the name changes for some reason?
    {
        if (!ViewEnabled())
            return;
        if (world_.expired())
            return;
        if (!tracking || !enabled.Get())
            return;
        if (!canUpdate_)
            return;
        if (!ParentEntity())
            return;
        EC_Placeable *placeable = ParentEntity()->GetComponent<EC_Placeable>().get();
        if (!placeable)
            return;

        float3 position = placeable->WorldPosition();
        if (!position.Equals(startPos.Get()))
            startPos.Set(position, AttributeChange::Default);

        // If mouse cursor is visible (not in first-person mode), see if we are inside the main window or there is a graphics item under the mouse
        if (framework->Input()->IsMouseCursorVisible() && (!IsMouseInsideWindow() || IsItemUnderMouse()))
        {
            laserObject_->clear();
            laserObject_->setVisible(false);
            return;
        }

        QPoint scenePos = framework->Ui()->GraphicsView()->mapFromGlobal(QCursor::pos());
        RaycastResult *result = world_.lock()->Renderer()->Raycast(scenePos.x(), scenePos.y());
        if (result && result->entity && result->entity != ParentEntity())
        {
            endPos.Set(result->pos, AttributeChange::Default);
            DisableUpdate();
        }
        else
        {
            laserObject_->clear();
            laserObject_->setVisible(false);
        }
    }
}

void EC_LaserPointer::EnableUpdate()
{
    canUpdate_ = true;
}

void EC_LaserPointer::DisableUpdate()
{
    canUpdate_ = false;
    QTimer::singleShot(updateInterval_, this, SLOT(EnableUpdate()));
}

void EC_LaserPointer::UpdateColor()
{
    if (!ViewEnabled())
        return;
    if (world_.expired())
        return;
    if (laserMaterial_.isNull())
        return;

    laserMaterial_->getTechnique(0)->getPass(0)->setDiffuse(color.Get());
    laserMaterial_->getTechnique(0)->getPass(0)->setAmbient(color.Get());
    laserMaterial_->getTechnique(0)->getPass(0)->setSelfIllumination(color.Get());
}

bool EC_LaserPointer::IsMouseInsideWindow() const
{
    if (!framework->Ui()->MainWindow())
        return false;
    return framework->Ui()->MainWindow()->geometry().contains(QCursor::pos(), true);
}

bool EC_LaserPointer::IsItemUnderMouse() const
{
    if (!framework->Ui()->GraphicsView() || !framework->Ui()->MainWindow())
        return true;
    QPoint scenePos = framework->Ui()->GraphicsView()->mapFromGlobal(QCursor::pos());
    QGraphicsItem *itemUnderMouse = framework->Ui()->GraphicsView()->itemAt(scenePos);
    return (itemUnderMouse != 0 ? true : false);
}
<|endoftext|>


<commit_before>// l1_fused_dot.cpp: example program showing a fused-dot product for error free linear algebra
//
// Copyright (C) 2017 Stillwater Supercomputing, Inc.
//
// This file is part of the universal numbers project, which is released under an MIT Open Source license.

// enable the mathematical constants in cmath: old-style preprocessor magic which isn't best practice anymore
#define _USE_MATH_DEFINES
#include "stdafx.h"

#include <vector>
#include <posit>

using namespace std;
using namespace sw::unum;

/*

Mathematical 	C++ Symbol	Decimal Representation
Expression
pi				M_PI		3.14159265358979323846
pi/2			M_PI_2		1.57079632679489661923
pi/4			M_PI_4		0.785398163397448309616
1/pi			M_1_PI		0.318309886183790671538
2/pi			M_2_PI		0.636619772367581343076
2/sqrt(pi)		M_2_SQRTPI	1.12837916709551257390
sqrt(2)			M_SQRT2		1.41421356237309504880
1/sqrt(2)		M_SQRT1_2	0.707106781186547524401
e				M_E			2.71828182845904523536
log_2(e)		M_LOG2E		1.44269504088896340736
log_10(e)		M_LOG10E	0.434294481903251827651
log_e(2)		M_LN2		0.693147180559945309417
log_e(10)		M_LN10		2.30258509299404568402

*/

const double pi = 3.14159265358979323846;  // best practice for C++

template<typename Ty>
Ty minValue(const std::vector<Ty>& samples) {
	std::vector<Ty>::const_iterator it = min_element(samples.begin(), samples.end());
	return *it;
}
template<typename Ty>
Ty maxValue(const std::vector<Ty>& samples) {
	std::vector<Ty>::const_iterator it = max_element(samples.begin(), samples.end());
	return *it;
}
template<typename Ty>
ostream& DisplaySample(ostream& ostr, const Ty& value, const Ty& min, const Ty& max) {
	// min is 0 stars
	// 0   is 40 stars
	// max is 80 stars
	int maxStars = 80;
	float sample = float(value);
	float range = float(max - min);
	float midPoint = range/2.0f;
	float portion = (sample + midPoint)/range;
	int ub = int(maxStars * portion);
	for (int i = 0; i < ub; i++) {
		ostr << "*";
	}
	return ostr << std::endl;
}

template<typename Ty>
void DisplaySignal(ostream& ostr, const std::vector<Ty>& samples) {
	Ty min = minValue(samples);
	Ty max = maxValue(samples);
	// create a horizontal display
	int cnt = 0;
	ostr << fixed << setprecision(3);
	for (std::vector<Ty>::const_iterator it = samples.begin(); it != samples.end(); it++) {
		ostr << setw(3) << cnt++ << " " << setw(6) << float(*it) << " ";
		DisplaySample(ostr, *it, min, max);
	}
	ostr << setprecision(17);
}

int main(int argc, char** argv)
try {
	const size_t nbits = 16;
	const size_t es = 1;
	const size_t vecSize = 32;

	int nrOfFailedTestCases = 0;

	posit<nbits, es> p;
	vector< posit<nbits,es> > sinusoid(vecSize), cosinusoid(vecSize);

	for (int i = 0; i < vecSize; i++) {
		p = sin( (float(i) / float(vecSize)) *2.0 * pi);
		sinusoid[i] = p;
		p = cos((float(i) / float(vecSize)) *2.0 * pi);
		cosinusoid[i] = p;
	}

	DisplaySignal(std::cout, sinusoid);

	minpos_value<nbits, es>();
	// dot product
	quire<nbits, es, 2> dot_product;
	dot_product = 0.0f;
	for (int i = 0; i < vecSize; i++) {
		dot_product += quire_mul(sinusoid[i], cosinusoid[i]);
	}

	cout << "Dot product is " << dot_product << endl;

	return (nrOfFailedTestCases > 0 ? EXIT_FAILURE : EXIT_SUCCESS);
}
catch (char const* msg) {
	cerr << msg << endl;
	return EXIT_FAILURE;
}
catch (...) {
	cerr << "Caught unknown exception" << endl;
	return EXIT_FAILURE;
}
<commit_msg>Compilation fix adding missing typename<commit_after>// l1_fused_dot.cpp: example program showing a fused-dot product for error free linear algebra
//
// Copyright (C) 2017 Stillwater Supercomputing, Inc.
//
// This file is part of the universal numbers project, which is released under an MIT Open Source license.

// enable the mathematical constants in cmath: old-style preprocessor magic which isn't best practice anymore
#define _USE_MATH_DEFINES
#include "stdafx.h"

#include <vector>
#include <posit>

using namespace std;
using namespace sw::unum;

/*

Mathematical 	C++ Symbol	Decimal Representation
Expression
pi				M_PI		3.14159265358979323846
pi/2			M_PI_2		1.57079632679489661923
pi/4			M_PI_4		0.785398163397448309616
1/pi			M_1_PI		0.318309886183790671538
2/pi			M_2_PI		0.636619772367581343076
2/sqrt(pi)		M_2_SQRTPI	1.12837916709551257390
sqrt(2)			M_SQRT2		1.41421356237309504880
1/sqrt(2)		M_SQRT1_2	0.707106781186547524401
e				M_E			2.71828182845904523536
log_2(e)		M_LOG2E		1.44269504088896340736
log_10(e)		M_LOG10E	0.434294481903251827651
log_e(2)		M_LN2		0.693147180559945309417
log_e(10)		M_LN10		2.30258509299404568402

*/

const double pi = 3.14159265358979323846;  // best practice for C++

template<typename Ty>
Ty minValue(const std::vector<Ty>& samples) {
	typename std::vector<Ty>::const_iterator it = min_element(samples.begin(), samples.end());
	return *it;
}
template<typename Ty>
Ty maxValue(const std::vector<Ty>& samples) {
	typename std::vector<Ty>::const_iterator it = max_element(samples.begin(), samples.end());
	return *it;
}
template<typename Ty>
ostream& DisplaySample(ostream& ostr, const Ty& value, const Ty& min, const Ty& max) {
	// min is 0 stars
	// 0   is 40 stars
	// max is 80 stars
	int maxStars = 80;
	float sample = float(value);
	float range = float(max - min);
	float midPoint = range/2.0f;
	float portion = (sample + midPoint)/range;
	int ub = int(maxStars * portion);
	for (int i = 0; i < ub; i++) {
		ostr << "*";
	}
	return ostr << std::endl;
}

template<typename Ty>
void DisplaySignal(ostream& ostr, const std::vector<Ty>& samples) {
	Ty min = minValue(samples);
	Ty max = maxValue(samples);
	// create a horizontal display
	int cnt = 0;
	ostr << fixed << setprecision(3);
	for (typename std::vector<Ty>::const_iterator it = samples.begin(); it != samples.end(); it++) {
		ostr << setw(3) << cnt++ << " " << setw(6) << float(*it) << " ";
		DisplaySample(ostr, *it, min, max);
	}
	ostr << setprecision(17);
}

int main(int argc, char** argv)
try {
	const size_t nbits = 16;
	const size_t es = 1;
	const size_t vecSize = 32;

	int nrOfFailedTestCases = 0;

	posit<nbits, es> p;
	vector< posit<nbits,es> > sinusoid(vecSize), cosinusoid(vecSize);

	for (int i = 0; i < vecSize; i++) {
		p = sin( (float(i) / float(vecSize)) *2.0 * pi);
		sinusoid[i] = p;
		p = cos((float(i) / float(vecSize)) *2.0 * pi);
		cosinusoid[i] = p;
	}

	DisplaySignal(std::cout, sinusoid);

	minpos_value<nbits, es>();
	// dot product
	quire<nbits, es, 2> dot_product;
	dot_product = 0.0f;
	for (int i = 0; i < vecSize; i++) {
		dot_product += quire_mul(sinusoid[i], cosinusoid[i]);
	}

	cout << "Dot product is " << dot_product << endl;

	return (nrOfFailedTestCases > 0 ? EXIT_FAILURE : EXIT_SUCCESS);
}
catch (char const* msg) {
	cerr << msg << endl;
	return EXIT_FAILURE;
}
catch (...) {
	cerr << "Caught unknown exception" << endl;
	return EXIT_FAILURE;
}
<|endoftext|>


<commit_before>#include"qca.h"
#include<stdio.h>

int main(int argc, char **argv)
{
	QCA::Initializer init;
	QCString cs = (argc >= 2) ? argv[1] : "hello";

	if( !QCA::isSupported("sha1") )
		printf("SHA1 not supported!\n");
	else {
		QCA::SHA1 sha1Hash;
		QString result = sha1Hash.hashToString(cs);
		printf("sha1(\"%s\") = [%s]\n", cs.data(), result.latin1());
	}

	if( !QCA::isSupported("md5") )
		printf("MD5 not supported!\n");
	else {
		QCA::MD5 md5Hash;
		QString result = md5Hash.hashToString(cs);
		printf("md5(\"%s\") = [%s]\n", cs.data(), result.latin1());
	}

	return 0;
}

<commit_msg>Update to use static versions.<commit_after>#include"qca.h"
#include<stdio.h>

int main(int argc, char **argv)
{
	QCA::Initializer init;
	QCString cs = (argc >= 2) ? argv[1] : "hello";

	if( !QCA::isSupported("sha1") )
		printf("SHA1 not supported!\n");
	else {
		QString result = QCA::SHA1().hashToString(cs);
		printf("sha1(\"%s\") = [%s]\n", cs.data(), result.latin1());
	}

	if( !QCA::isSupported("md5") )
		printf("MD5 not supported!\n");
	else {
		QString result = QCA::MD5().hashToString(cs);
		printf("md5(\"%s\") = [%s]\n", cs.data(), result.latin1());
	}

	return 0;
}

<|endoftext|>


<commit_before>#include "debugoutput.h"

void SendDbgRegisters(SOCKET Server, BOOLEAN ProtocolGUI, DWORD EIP, VirtualRegisters Registers)
{
	char snbuffer[356];
	if (ProtocolGUI == FALSE)
	{
		snprintf(snbuffer, sizeof(snbuffer),
			"+    EAX: %08X\r\n" "    EBX: %08X\r\n"
			"    ECX: %08X\r\n" "    EDX: %08X\r\n"
			"    ESI: %08X\r\n" "    EDI: %08X\r\n"
			"    EBP: %08X\r\n" "    ESP: %08X\r\n"
			"    EIP: %08X\r\n", Registers.eax, Registers.ebx, Registers.ecx, Registers.edx,
			Registers.esi, Registers.edi, Registers.ebp, Registers.esp, EIP);
	}
	else
	{
		snprintf(snbuffer, sizeof(snbuffer),
			"+    EAX: %08X\r\n" "EBX: %08X\r\n"
			"ECX: %08X\r\n" "EDX: %08X\r\n"
			"ESI: %08X\r\n" "EDI: %08X\r\n"
			"EBP: %08X\r\n" "ESP: %08X\r\n"
			"EIP: %08X\r\n", Registers.eax, Registers.ebx, Registers.ecx, Registers.edx,
			Registers.esi, Registers.edi, Registers.ebp, Registers.esp, EIP);
	}
	send(Server, snbuffer, sizeof(snbuffer), 0);
}

void SendDbgGet(SOCKET Server, BOOLEAN ExceptionType, PoolSect segment)
{
	char snbuffer[512];
	if (ExceptionType != TRUE)
		snprintf(snbuffer, sizeof(snbuffer), "^    Exception Type: IMM\r\nSymbol: 0x%08X\r\nRetn: 0x%08X\r\n", segment.ExceptionAddress, segment.ReturnAddress);
	else
		snprintf(snbuffer, sizeof(snbuffer), "^    Exception Type: PAGE\r\nSymbol: 0x%08X\r\nRetn: 0x%08X\r\n", segment.ExceptionAddress, segment.ReturnAddress);
	send(Server, snbuffer, sizeof(snbuffer), 0);
}
<commit_msg>Update debugoutput.cpp<commit_after>#include "debugoutput.h"

void SendDbgRegisters(SOCKET Server, BOOLEAN Protocol, DWORD EIP, VirtualRegisters Registers)
{
	char snbuffer[356];
	if (Protocol == 0)
	{
		snprintf(snbuffer, sizeof(snbuffer),
			"+    EAX: %08X\r\n" "    EBX: %08X\r\n"
			"    ECX: %08X\r\n" "    EDX: %08X\r\n"
			"    ESI: %08X\r\n" "    EDI: %08X\r\n"
			"    EBP: %08X\r\n" "    ESP: %08X\r\n"
			"    EIP: %08X\r\n", Registers.eax, Registers.ebx, Registers.ecx, Registers.edx,
			Registers.esi, Registers.edi, Registers.ebp, Registers.esp, EIP);
	}
	else if (Protocol == 1)
	{
		snprintf(snbuffer, sizeof(snbuffer),
			"+    EAX: %08X\r\n" "EBX: %08X\r\n"
			"ECX: %08X\r\n" "EDX: %08X\r\n"
			"ESI: %08X\r\n" "EDI: %08X\r\n"
			"EBP: %08X\r\n" "ESP: %08X\r\n"
			"EIP: %08X\r\n", Registers.eax, Registers.ebx, Registers.ecx, Registers.edx,
			Registers.esi, Registers.edi, Registers.ebp, Registers.esp, EIP);
	}
	else if (Protocol == 2)
	{
		snprintf(snbuffer, sizeof(snbuffer),
			"+    xmm0: %f\r\n" "    xmm1: %f\r\n"
			"    xmm2: %f\r\n" "    xmm3: %f\r\n"
			"    xmm4: %f\r\n" "    xmm5: %f\r\n"
			"    xmm6: %f\r\n" "    xmm7: %f\r\n",
			Registers.xmm0, Registers.xmm1, Registers.xmm2, Registers.xmm3,
			Registers.xmm4, Registers.xmm5, Registers.xmm6, Registers.xmm7);
	}
	else if (Protocol == 3)
	{
		snprintf(snbuffer, sizeof(snbuffer),
			"+    xmm0: %f\r\n" "    xmm1: %f\r\n"
			"    xmm2: %f\r\n" "    xmm3: %f\r\n"
			"    xmm4: %f\r\n" "    xmm5: %f\r\n"
			"    xmm6: %f\r\n" "    xmm7: %f\r\n",
			Registers.dxmm0, Registers.dxmm1, Registers.dxmm2, Registers.dxmm3,
			Registers.dxmm4, Registers.dxmm5, Registers.dxmm6, Registers.dxmm7);
	}
	send(Server, snbuffer, sizeof(snbuffer), 0);
}

void SendDbgGet(SOCKET Server, BOOLEAN ExceptionType, PoolSect segment)
{
	char snbuffer[512];
	if (ExceptionType != TRUE)
		snprintf(snbuffer, sizeof(snbuffer), "^    Exception Type: IMM\r\n    Symbol: 0x%08X\r\n    Retn: 0x%08X\r\n    Index:%d\r\n", segment.ExceptionAddress, segment.ReturnAddress, segment.Index);
	else
		snprintf(snbuffer, sizeof(snbuffer), "^    Exception Type: PAGE\r\n    Symbol: 0x%08X\r\n    Retn: 0x%08X\r\n    Index:%d\r\n", segment.ExceptionAddress, segment.ReturnAddress, segment.Index);
	send(Server, snbuffer, sizeof(snbuffer), 0);
}
<|endoftext|>


<commit_before>#include "dataload_fb.h"
#include <QDataStream>
#include <QByteArray>
#include <QFile>
#include <QMessageBox>
#include "selectxaxisdialog.h"
#include <QDebug>
#include <iostream>
#include <sstream>
#include "flatbuffers/reflection.h"
#include "flatbuffers/idl.h"
#include "lz4.h"

DataLoadFlatbuffer::DataLoadFlatbuffer()
{
    _extensions.push_back( "fb");
    _extensions.push_back( "dtl");
}

const std::vector<const char*> &DataLoadFlatbuffer::compatibleFileExtensions() const
{
    return _extensions;
}

QString extractSchemaFromHeader(QDataStream* stream )
{
    QString header, line;
    do{
        line.clear();
        qint8 c;
        do{
            *stream >> c;
            line.append( c );
        }while ( c !='\n');

        header.append( line );
    }
    while (line.contains( "root_type" ) == false );

    return header;
}

std::vector<uint8_t> parseSchema(QString schema_text)
{
    flatbuffers::Parser parser;
    bool ok = parser.Parse( schema_text.toStdString().c_str(), nullptr, nullptr );

    if( !ok ) {
        qDebug() << parser.error_.c_str();
    }

    assert("Parse failed " && ok);

    parser.Serialize();

    auto data_ptr = parser.builder_.GetBufferPointer();
    auto length = parser.builder_.GetSize();

    return std::vector<uint8_t>(  &data_ptr[0], &data_ptr[length] );
}

bool decompressBlock( QDataStream* source, LZ4_streamDecode_t* lz4_stream, std::vector<char>* output, size_t* parsed_size )
{
    if( source->atEnd())
    {
        return false;
    }

    const size_t BUFFER_SIZE = 1024*512 ;
    output->resize( BUFFER_SIZE );

    char comp_buffer[LZ4_COMPRESSBOUND( BUFFER_SIZE )];
    size_t block_size = 0;

    char c[8];
    source->readRawData( c, 8);

    for (int i=0; i<8; i++ )
    {
        block_size += ((uint8_t)c[i]) << (8*i);
    }

    if( block_size <= 0 || block_size > BUFFER_SIZE) {
        return false;
    }

    const size_t readCount =  source->readRawData( comp_buffer, (size_t) block_size);

    *parsed_size = 8+ readCount;

    if(readCount != (size_t) block_size) {
        return false;
    }

    const size_t decBytes = LZ4_decompress_safe_continue(
                lz4_stream,
                comp_buffer,
                output->data(),
                block_size,
                BUFFER_SIZE );

    if(decBytes <= 0) {
        return false;
    }
    output->resize(decBytes);

    return true;
}

char* getSingleFlatbuffer(char* source, std::vector<uint8_t>* destination)
{
    uint8_t c;
    uint32_t chunk_size = 0;
    for (int i=0; i< sizeof(uint32_t); i++ )
    {
        c = (uint8_t)(*source);
        source++;
        chunk_size += c << (8*i);
    }

    if( destination) {

        destination->resize( chunk_size );
        for (uint32_t i=0; i< chunk_size; i++ )
        {
            (*destination)[i] = (uint8_t)(*source);
            source++;
        }
    }
    else{
        source += chunk_size ;
    }

    return source;
}

QStringList getFieldNamesFromSchema(const reflection::Schema* schema,
                                    flatbuffers::Table *root_table )
{
    QStringList field_names;
    auto fields = schema->root_table()->fields();

    for (uint32_t f=0; f< fields->size(); f++)
    {
        auto field = fields->Get(f);
        const char* field_name = field->name()->c_str();

        if( field->type()->base_type() == reflection::Vector)
        {
            const auto& vect = GetFieldAnyV( *root_table, *field );

            for (int v=0; v < vect->size(); v++)
            {
                std::stringstream ss;
                ss << field_name << "." << v;
                field_names.push_back(  ss.str().c_str() );
            }
        }
        else{
            field_names.push_back( field_name  );
        }
    }

    return field_names;
}

PlotDataMap DataLoadFlatbuffer::readDataFromFile(QFile *file,
                                                 std::function<void(int)> updateCompletion,
                                                 std::function<bool()> checkInterruption)
{
    float file_size = file->size();
    float parsed_size = 0;
    size_t block_size;

    PlotDataMap plot_data;

    // get the schema from the header of the file
    QDataStream file_stream(file);

    file_stream.device()->setTextModeEnabled( false );

    QString schema_text = extractSchemaFromHeader( &file_stream );

    // parse the schema
    std::vector<uint8_t> schema_buffer = parseSchema( schema_text );
    const reflection::Schema* schema = reflection::GetSchema( schema_buffer.data() );

    //--------------------------------------
    // build data

    std::vector<uint8_t> flatbuffer;
    QStringList field_names;

    auto fields = schema->root_table()->fields();

    std::vector<SharedVector> data_vectors;

    bool first_pass = true;

    int time_index = -1;
    int linecount = 0;

    SharedVector time_vector (new std::vector<double>() );

    bool interrupted = false;

    std::vector<char> decompressed_block;

    LZ4_streamDecode_t lz4_stream;

    LZ4_setStreamDecode( &lz4_stream, NULL, 0);

    while( decompressBlock( &file_stream, &lz4_stream, &decompressed_block , &block_size)
           && !interrupted )
    {
        parsed_size += block_size;

        updateCompletion( (100.0*parsed_size)/file_size );
        interrupted = checkInterruption();

        uint64_t block_size = decompressed_block.size();
        char* block_end = &decompressed_block.data()[ block_size ];
        char* block_ptr = &decompressed_block.data()[ 0 ];

        while( block_ptr !=  block_end )
        {
            block_ptr = getSingleFlatbuffer( block_ptr, &flatbuffer );

            auto root_table = flatbuffers::GetAnyRoot( flatbuffer.data() );

            // qDebug() << linecount << " " << flatbuffer.size() ;

            // at the first flatbuffer, create a vector with the names.
            if( first_pass)
            {
                field_names = getFieldNamesFromSchema( schema, root_table );

                SelectXAxisDialog* dialog = new SelectXAxisDialog( &field_names );
                dialog->exec();
                time_index = dialog->getSelectedRowNumber();

                for (int i=0; i< field_names.size(); i++)
                {
                    data_vectors.push_back( SharedVector(new std::vector<double>()) );

                    PlotDataPtr plot( new PlotData );
                    std::string name = field_names.at(i).toStdString();
                    plot->setName( name );
                    plot_data.insert( std::make_pair( name, plot ) );
                }
                first_pass = false;
            }

            int index = 0;

            if( time_index < 0) {
                time_vector->push_back( linecount++ );
            }

            for (uint32_t f=0; f< fields->size(); f++)
            {
                auto field = fields->Get(f);

                SharedVector data_vector;

                const auto& type = field->type()->base_type();

                if( type == reflection::Vector)
                {
                    const auto& vect = GetFieldAnyV( *root_table, *field );
                    const auto& vect_type = field->type()->element();

                    for (int v=0; v < vect->size(); v++)
                    {
                        data_vector = data_vectors[index];

                        double value = 0;
                        if( vect_type == reflection::Float || vect_type == reflection::Double)
                        {
                            value = flatbuffers::GetAnyVectorElemF( vect, vect_type, v);
                        }
                        else{
                            long value_int = flatbuffers::GetAnyVectorElemI( vect, vect_type, v);
                            value = value_int;
                        }

                        data_vector->push_back( value );

                        if( time_index == index) {
                            time_vector->push_back( value );
                        }
                        index++;
                    }
                }
                else{
                    data_vector = data_vectors[index];

                    double value = 0;
                    if( type == reflection::Float || type == reflection::Double)
                    {
                        value = flatbuffers::GetAnyFieldI(*root_table, *field );
                    }
                    else{
                        long value_int = flatbuffers::GetAnyFieldI(*root_table, *field );
                        value = value_int;
                    }

                    data_vector->push_back( value );

                    if( time_index == index) {
                        time_vector->push_back( value );
                    }
                    index++;
                }
            }
        }
    }

    if(interrupted)
    {
        plot_data.erase( plot_data.begin(), plot_data.end() );
    }
    else{

        for( unsigned i=0; i < field_names.size(); i++)
        {
            QString name = field_names[i];
            plot_data[ name.toStdString() ]->addData( time_vector, data_vectors[i]);
        }
    }

    return plot_data;
}

DataLoadFlatbuffer::~DataLoadFlatbuffer()
{

}
<commit_msg>work in progress, it doesn't compile<commit_after>#include "dataload_fb.h"
#include <QDataStream>
#include <QByteArray>
#include <QFile>
#include <QMessageBox>
#include "selectxaxisdialog.h"
#include <QDebug>
#include <iostream>
#include <functional>
#include "flatbuffers/idl.h"
#include "lz4.h"

enum BaseType {
  None = 0,
  Bool = 1,
  Byte = 2,
  UByte = 3,
  Short = 4,
  UShort = 5,
  Int = 6,
  UInt = 7,
  Long = 8,
  ULong = 9,
  Float = 10,
  Double = 11,
  MIN = None,
  MAX = Double
};

inline const char **EnumNamesBaseType() {
  static const char *names[] = { "None", "Bool",      "Byte", "UByte",
                                 "Short", "UShort",   "Int",  "UInt",
                                 "Long", "ULong",     "Float", "Double",
                                 nullptr };
  return names;
}

inline BaseType BaseTypeFromString( const char* type_name)
{
    const char **names = EnumNamesBaseType();

    for (int i=1; i<= BaseType::MAX; i++)
    {
        if( strcmp( names[i], type_name) == 0)
        {
            return static_cast<BaseType>( i );
        }
    }
    return BaseType::None;
}

inline int SizeOf(BaseType e) {
    static int sizes[] = { 0, 1, 1, 1,
                           2, 2, 4, 4,
                           8,8, 4, 8 };
    return sizes[static_cast<int>(e)];
}

DataLoadFlatbuffer::DataLoadFlatbuffer()
{
    _extensions.push_back( "pms");
}

const std::vector<const char*> &DataLoadFlatbuffer::compatibleFileExtensions() const
{
    return _extensions;
}

QString extractSchemaFromHeader(QDataStream* stream )
{
    QString header, line;
    do{
        line.clear();
        qint8 c;
        do{
            *stream >> c;
            line.append( c );
        }while ( c !='\n');

        header.append( line );
    }
    while (line.contains( "COMPRESSED_DATA_STARTS_NEXT" ) == false );

    return header;
}

typedef struct{
    std::vector<uint64_t> offsets;
    std::vector<BaseType> types;
    std::vector<QString> names;
    std::vector< std::function<double(void*) > > readFunction;

} Schema;

Schema parseSchemaAndGetOffsets(QString schema_text)
{
    Schema schema;
    schema.offsets.push_back( 0 );

    QStringList lines = schema_text.split(QRegExp("\n|\r\n|\r"));

    for (int i=0; i< lines.size(); i++)
    {
        QString line = lines.at(i);
        QStringList items = line.split( QRegExp("[ :]"),QString::SkipEmptyParts);
        schema.names.push_back( items.at(0) );

        QString type_name = items.at(1);

        if( type_name.compare("Float") == 0) {
            schema.readFunction.push_back( [](void* ptr) { return flatbuffers::ReadScalar<float>(ptr); } );
        }
        else if( type_name.compare("Double") == 0) {
            schema.readFunction.push_back( [](void* ptr) { return flatbuffers::ReadScalar<double>(ptr); } );
        }
        else if( type_name.compare("Bool") == 0) {
            schema.readFunction.push_back( [](void* ptr) { return flatbuffers::ReadScalar<bool>(ptr); } );
        }
        else if( type_name.compare("Byte") == 0) {
            schema.readFunction.push_back( [](void* ptr) { return flatbuffers::ReadScalar<int8_t>(ptr); } );
        }
        else if( type_name.compare("UByte") == 0) {
            schema.readFunction.push_back( [](void* ptr) { return flatbuffers::ReadScalar<uint8_t>(ptr); } );
        }
        else if( type_name.compare("Short") == 0) {
            schema.readFunction.push_back( [](void* ptr) { return flatbuffers::ReadScalar<int16_t>(ptr); } );
        }
        else if( type_name.compare("UShort") == 0) {
            schema.readFunction.push_back( [](void* ptr) { return flatbuffers::ReadScalar<uint16_t>(ptr); } );
        }
        else if( type_name.compare("Int") == 0) {
            schema.readFunction.push_back( [](void* ptr) { return flatbuffers::ReadScalar<int32_t>(ptr); } );
        }
        else if( type_name.compare("UInt") == 0) {
            schema.readFunction.push_back( [](void* ptr) { return flatbuffers::ReadScalar<uint32_t>(ptr); } );
        }
        else if( type_name.compare("Long") == 0) {
            schema.readFunction.push_back( [](void* ptr) { return flatbuffers::ReadScalar<int64_t>(ptr); } );
        }
        else if( type_name.compare("ULong") == 0) {
            schema.readFunction.push_back( [](void* ptr) { return flatbuffers::ReadScalar<uint64_t>(ptr); } );
        }

        BaseType type = BaseTypeFromString( type_name.toStdString().c_str()) ;
        schema.types.push_back( type );
        schema.offsets.push_back(  schema.offsets.back() + SizeOf(type) );

    }
    return schema;
}

bool decompressBlock( QDataStream* source, LZ4_streamDecode_t* lz4_stream, std::vector<char>* output, size_t* parsed_size )
{
    if( source->atEnd())
    {
        return false;
    }

    const size_t BUFFER_SIZE = 1024*512 ;
    output->resize( BUFFER_SIZE );

    char comp_buffer[LZ4_COMPRESSBOUND( BUFFER_SIZE )];
    size_t block_size = 0;

    char c[8];
    source->readRawData( c, 8);

    for (int i=0; i<8; i++ )
    {
        block_size += ((uint8_t)c[i]) << (8*i);
    }

    if( block_size <= 0 || block_size > BUFFER_SIZE) {
        return false;
    }

    const size_t readCount =  source->readRawData( comp_buffer, (size_t) block_size);

    *parsed_size = 8+ readCount;

    if(readCount != (size_t) block_size) {
        return false;
    }

    const size_t decBytes = LZ4_decompress_safe_continue(
                lz4_stream,
                comp_buffer,
                output->data(),
                block_size,
                BUFFER_SIZE );

    if(decBytes <= 0) {
        return false;
    }
    output->resize(decBytes);

    return true;
}

char* getSingleFlatbuffer(char* source, std::vector<uint8_t>* destination)
{
    uint8_t c;
    uint32_t chunk_size = 0;
    for (int i=0; i< sizeof(uint32_t); i++ )
    {
        c = (uint8_t)(*source);
        source++;
        chunk_size += c << (8*i);
    }

    if( destination) {

        destination->resize( chunk_size );
        for (uint32_t i=0; i< chunk_size; i++ )
        {
            (*destination)[i] = (uint8_t)(*source);
            source++;
        }
    }
    else{
        source += chunk_size ;
    }

    return source;
}

PlotDataMap DataLoadFlatbuffer::readDataFromFile(QFile *file,
                                                 std::function<void(int)> updateCompletion,
                                                 std::function<bool()> checkInterruption)
{
    float file_size = file->size();
    float parsed_size = 0;
    size_t block_size;

    PlotDataMap plot_data;

    // get the schema from the header of the file
    QDataStream file_stream(file);

    file_stream.device()->setTextModeEnabled( false );

    QString schema_text = extractSchemaFromHeader( &file_stream );

    // parse the schema
    Schema schema = parseSchemaAndGetOffsets( schema_text );

    //--------------------------------------
    // build data

    std::vector<SharedVector> data_vectors;

    int time_index = -1;
    int linecount = 0;

    SharedVector time_vector (new std::vector<double>() );

    bool interrupted = false;

    std::vector<char> decompressed_block;

    LZ4_streamDecode_t lz4_stream;

    LZ4_setStreamDecode( &lz4_stream, NULL, 0);

    while( decompressBlock( &file_stream, &lz4_stream, &decompressed_block , &block_size)
           && !interrupted )
    {
        parsed_size += block_size;

        updateCompletion( (100.0*parsed_size)/file_size );
        interrupted = checkInterruption();

        uint64_t block_size = decompressed_block.size();
        char* block_end = &decompressed_block.data()[ block_size ];
        char* block_ptr = &decompressed_block.data()[ 0 ];

        while( block_ptr !=  block_end )
        {
            block_ptr = getSingleFlatbuffer( block_ptr, &flatbuffer );

            auto root_table = flatbuffers::GetAnyRoot( flatbuffer.data() );

            // qDebug() << linecount << " " << flatbuffer.size() ;

            // at the first flatbuffer, create a vector with the names.
            if( first_pass)
            {
                field_names = getFieldNamesFromSchema( schema, root_table );

                SelectXAxisDialog* dialog = new SelectXAxisDialog( &field_names );
                dialog->exec();
                time_index = dialog->getSelectedRowNumber();

                for (int i=0; i< field_names.size(); i++)
                {
                    data_vectors.push_back( SharedVector(new std::vector<double>()) );

                    PlotDataPtr plot( new PlotData );
                    std::string name = field_names.at(i).toStdString();
                    plot->setName( name );
                    plot_data.insert( std::make_pair( name, plot ) );
                }
                first_pass = false;
            }

            int index = 0;

            if( time_index < 0) {
                time_vector->push_back( linecount++ );
            }

            for (uint32_t f=0; f< fields->size(); f++)
            {
                auto field = fields->Get(f);

                SharedVector data_vector;

                const auto& type = field->type()->base_type();

                if( type == reflection::Vector)
                {
                    const auto& vect = GetFieldAnyV( *root_table, *field );
                    const auto& vect_type = field->type()->element();

                    for (int v=0; v < vect->size(); v++)
                    {
                        data_vector = data_vectors[index];

                        double value = 0;
                        if( vect_type == reflection::Float || vect_type == reflection::Double)
                        {
                            value = flatbuffers::GetAnyVectorElemF( vect, vect_type, v);
                        }
                        else{
                            long value_int = flatbuffers::GetAnyVectorElemI( vect, vect_type, v);
                            value = value_int;
                        }

                        data_vector->push_back( value );

                        if( time_index == index) {
                            time_vector->push_back( value );
                        }
                        index++;
                    }
                }
                else{
                    data_vector = data_vectors[index];

                    double value = 0;
                    if( type == reflection::Float || type == reflection::Double)
                    {
                        value = flatbuffers::GetAnyFieldI(*root_table, *field );
                    }
                    else{
                        long value_int = flatbuffers::GetAnyFieldI(*root_table, *field );
                        value = value_int;
                    }

                    data_vector->push_back( value );

                    if( time_index == index) {
                        time_vector->push_back( value );
                    }
                    index++;
                }
            }
        }
    }

    if(interrupted)
    {
        plot_data.erase( plot_data.begin(), plot_data.end() );
    }
    else{

        for( unsigned i=0; i < field_names.size(); i++)
        {
            QString name = field_names[i];
            plot_data[ name.toStdString() ]->addData( time_vector, data_vectors[i]);
        }
    }

    return plot_data;
}

DataLoadFlatbuffer::~DataLoadFlatbuffer()
{

}
<|endoftext|>


<commit_before>
// -*- mode: c++; c-basic-offset:4 -*-

// This file is part of libdap, A C++ implementation of the OPeNDAP Data
// Access Protocol.

// Copyright (c) 2002,2003 OPeNDAP, Inc.
// Author: James Gallagher <jgallagher@opendap.org>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.

// (c) COPYRIGHT URI/MIT 1994-1999
// Please read the full copyright statement in the file COPYRIGHT_URI.
//
// Authors:
//      pwest       Patrick West <pwest@ucar.edu>

// Implementation for PassiveStructure.
//
// pwest 11/04/03

#ifdef __GNUG__
#pragma implementation
#endif

#include "config_dap.h"

static char rcsid[] not_used = {"$Id: PassiveStructure.cc,v 1.1 2004/07/09 16:34:38 pwest Exp $"};

#include <stdlib.h>

#include "PassiveStructure.h"
#include "InternalErr.h"
#include "debug.h"

#ifdef TRACE_NEW
#include "trace_new.h"
#endif

using std::cerr;
using std::endl;

/** The PassiveStructure constructor requires only the name of the variable
    to be created.  The name may be omitted, which will create a
    nameless variable.  This may be adequate for some applications.

    @param n A string containing the name of the variable to be
    created.
*/
PassiveStructure::PassiveStructure(const string &n) : Structure(n)
{
}

PassiveStructure::PassiveStructure(const PassiveStructure &copy_from) : Structure(copy_from)
{
}

BaseType *
PassiveStructure::ptr_duplicate()
{
    return new PassiveStructure(*this);
}

PassiveStructure::~PassiveStructure()
{
    DBG(cerr << "~PassiveStructure" << endl);
}

PassiveStructure &
PassiveStructure::operator=(const PassiveStructure &rhs)
{
    if (this == &rhs)
	return *this;

    dynamic_cast<BaseType &>(*this) = rhs;

    _duplicate(rhs);

    return *this;
}

bool
PassiveStructure::read( const string &dataset )
{
    set_read_p( true ) ;

    return true ;
}

// $Log: PassiveStructure.cc,v $
// Revision 1.1  2004/07/09 16:34:38  pwest
// Adding Passive Data Model objects
//
<commit_msg>implemented read<commit_after>
// -*- mode: c++; c-basic-offset:4 -*-

// This file is part of libdap, A C++ implementation of the OPeNDAP Data
// Access Protocol.

// Copyright (c) 2002,2003 OPeNDAP, Inc.
// Author: James Gallagher <jgallagher@opendap.org>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.

// (c) COPYRIGHT URI/MIT 1994-1999
// Please read the full copyright statement in the file COPYRIGHT_URI.
//
// Authors:
//      pwest       Patrick West <pwest@ucar.edu>

// Implementation for PassiveStructure.
//
// pwest 11/04/03

#ifdef __GNUG__
#pragma implementation
#endif

#include "config_dap.h"

static char rcsid[] not_used = {"$Id: PassiveStructure.cc,v 1.2 2005/02/16 22:22:36 pwest Exp $"};

#include <stdlib.h>

#include "PassiveStructure.h"
#include "InternalErr.h"
#include "debug.h"

#ifdef TRACE_NEW
#include "trace_new.h"
#endif

using std::cerr;
using std::endl;

/** The PassiveStructure constructor requires only the name of the variable
    to be created.  The name may be omitted, which will create a
    nameless variable.  This may be adequate for some applications.

    @param n A string containing the name of the variable to be
    created.
*/
PassiveStructure::PassiveStructure(const string &n) : Structure(n)
{
}

PassiveStructure::PassiveStructure(const PassiveStructure &copy_from) : Structure(copy_from)
{
}

BaseType *
PassiveStructure::ptr_duplicate()
{
    return new PassiveStructure(*this);
}

PassiveStructure::~PassiveStructure()
{
    DBG(cerr << "~PassiveStructure" << endl);
}

PassiveStructure &
PassiveStructure::operator=(const PassiveStructure &rhs)
{
    if (this == &rhs)
	return *this;

    dynamic_cast<BaseType &>(*this) = rhs;

    _duplicate(rhs);

    return *this;
}

bool
PassiveStructure::read( const string &dataset )
{
    for( Vars_iter i = _vars.begin(); i != _vars.end(); i++ )
    {
	(*i)->read( dataset ) ;
    }
    set_read_p( true ) ;

    return true ;
}

// $Log: PassiveStructure.cc,v $
// Revision 1.2  2005/02/16 22:22:36  pwest
// implemented read
//
// Revision 1.1  2004/07/09 16:34:38  pwest
// Adding Passive Data Model objects
//
<|endoftext|>