<commit_before>#ifndef __GLOBALS_HPP_INCLUDED
#define __GLOBALS_HPP_INCLUDED

#include "any_value.hpp"

// GCC (at least g++ 4.7.2) and Visual Studio 2015 do support
// setting default values of a struct using C++11 syntax.
// Clang 3.7.0 and Visual Studio 2013 do not support
// setting default values of a struct using C++11 syntax.
// Visual Studio 2013 fails to compile, whereas Clang-compiled
// executable with code with setting default values of a struct
// causes Segmentation fault upon execution of the program.
// Compilers that don't support setting default values of a struct
// are handled by setting the default values in a macro.
// http://stackoverflow.com/questions/16782103/initializing-default-values-in-a-struct/16783513#16783513
#ifdef __clang__
#elif defined(__GNUC__)
#define __STRUCT_DEFAULT_VALUES_ARE_ACCEPTED
#elif defined(_WIN32)
#if (_MSC_VER >= 1900)
#define __STRUCT_DEFAULT_VALUES_ARE_ACCEPTED
#endif
#endif

// GLEW must be included here, because `globals.hpp` may be compiled
// first, and if `GL/glew.h` is not included before `glfw3.h` (?),
// then g++ prints the following error:
// `error: #error gl.h included before glew.h`
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h> // GLfloat, GLuint etc.
#endif

// Include GLFW
#ifndef __GLFW3_H_INCLUDED
#define __GLFW3_H_INCLUDED
#include <glfw3.h>
#endif

// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif

// Include standard headers
#include <cmath>    // NAN, std::isnan, std::pow
#include <stdint.h> // uint32_t etc.
#include <string>   // std::string
#include <vector>   // std::vector

#ifndef PI
#define PI 3.14159265359f
#endif

namespace callback_system
{
    class CallbackEngine;
    class CallbackObject;
    class CallbackParameter;
}

namespace graph
{
    class Graph;
}

namespace ontology
{
    class Universe;
    class Scene;
    class Shader;
    class Material;
    class VectorFont;
    class Species;
    class Glyph;
    class Text3D;
}

typedef struct ShaderStruct
{
    ShaderStruct()
        : parent_pointer(nullptr)
    {
        // constructor.
    }
    ontology::Scene* parent_pointer; // pointer to the scene (draw list).
    std::string vertex_shader;    // filename of vertex shader.
    std::string fragment_shader;  // filename of fragment shader.
} ShaderStruct;

typedef struct MaterialStruct
{
    MaterialStruct()
        : parent_pointer(nullptr)
    {
        // constructor.
    }
    ontology::Shader* parent_pointer;   // pointer to the shader.
    std::string texture_file_format; // type of the texture file. supported file formats so far: `"bmp"`/`"BMP"`, `"dds"`/`"DDS"`.
    std::string texture_filename;    // filename of the model file.
    std::string image_path;
} MaterialStruct;

typedef struct NodeStruct
{
    NodeStruct()
        : parent_pointer(nullptr)
    {
        // constructor.
    }
    uint32_t nodeID;
    graph::Graph* parent_pointer;
    std::vector<uint32_t> neighbor_nodeIDs;
} NodeStruct;

typedef struct ObjectStruct
{
    ObjectStruct()
        : species_parent_pointer(nullptr), glyph_parent_pointer(nullptr), text3D_parent_pointer(nullptr), original_scale_vector(glm::vec3(1.0f, 1.0f, 1.0f)), rotate_angle(NAN), is_character(false)
    {
        // constructor.
    }
    ontology::Species* species_parent_pointer; // pointer to the parent `Species`.
    ontology::Glyph* glyph_parent_pointer;     // pointer to the parent `Glyph`.
    ontology::Text3D* text3D_parent_pointer;   // pointer to the parent `Text3D`.
    glm::vec3 original_scale_vector; // original scale vector.
    float rotate_angle;              // rotate angle.
    bool is_character;               // The parent of a character object is a Glyph. The parent of a regular object is a Species.
    glm::vec3 coordinate_vector;     // coordinate vector.
    glm::vec3 rotate_vector;         // rotate vector.
    glm::vec3 translate_vector;      // translate vector.
} ObjectStruct;

typedef struct SpeciesStruct
{
    SpeciesStruct()
        : parent_pointer(nullptr), is_world(false), world_radius(NAN), divisor(1.0f), triangulation_type("bilinear_interpolation")
    {
        // constructor.
    }
    // used for all files (for all species).
    ontology::Material* parent_pointer;      // pointer to the material object.
    bool is_world;                           // worlds currently do not rotate nor translate.
    float world_radius;                      // radius of sea level in kilometers. used only for worlds.
    float divisor;                           // value by which SRTM values are divided to convert them to kilometers.
    std::string model_file_format;           // type of the model file. supported file formats so far: `"bmp"`/`"BMP"`, `"obj"`/`"OBJ"`.
                                             // TODO: add support for `"SRTM"`.
    std::string model_filename;              // filename of the model file.
    // for `"bmp"` model files.
    std::string color_channel;               // color channel to use for altitude data.

    glm::vec3 light_position;                // light position.
    std::string coordinate_system;           // used only for worlds (`is_world` == `true`). valid values: `"cartesian"`.
                                             // TODO: add support for `"spherical"`. `"spherical"` is used eg. in SRTM heightmaps.
    std::string triangulation_type;
} SpeciesStruct;

#define DEFAULT_VERTEX_SCALING_FACTOR (0.001f)

typedef struct VectorFontStruct
{
    VectorFontStruct()
        : parent_pointer(nullptr), vertex_scaling_factor(DEFAULT_VERTEX_SCALING_FACTOR)
    {
        // constructor.
    }
    // used for all files (for all font).
    ontology::Material* parent_pointer;        // pointer to the material object.
    GLfloat vertex_scaling_factor;
    std::string font_file_format;           // type of the font file. supported file formats so far: `"svg"`/`"SVG"`.
    std::string font_filename;              // filename of the font file.
} VectorFontStruct;

typedef struct Text3DStruct
{
    Text3DStruct()
        : parent_pointer(nullptr), original_scale_vector(glm::vec3(1.0f, 1.0f, 1.0f)), rotate_angle(NAN)
    {
        // constructor.
    }
    ontology::VectorFont* parent_pointer; // pointer to the parent `VectorFont`.
    std::string text_string;
    const char* text_string_char;
    glm::vec3 original_scale_vector;   // original scale vector.
    float rotate_angle;                // rotate angle.
    glm::vec3 coordinate_vector;       // coordinate vector.
    glm::vec3 rotate_vector;           // rotate vector.
    glm::vec3 translate_vector;        // translate vector.
} Text3DStruct;

typedef struct GlyphStruct
{
    GlyphStruct()
        : parent_pointer(nullptr)
    {
        // constructor.
    }
    // used for all files (for all glyph).
    std::vector<std::vector<glm::vec2>>* glyph_vertex_data;
    const char* glyph_name_pointer;          // we need only a pointer, because glyphs are always created by the `VectorFont` constructor.
    const char* unicode_char_pointer;      // we need only a pointer, because glyphs are always created by the `VectorFont` constructor.
    ontology::VectorFont* parent_pointer;       // pointer to the font object.
    glm::vec3 light_position;                // light position.
} GlyphStruct;

typedef struct
{
    uint32_t screen_width;
    uint32_t screen_height;
    uint32_t x;
    uint32_t y;
    uint32_t text_size;
    uint32_t font_size;
    std::string text;
    const char* text_char;
    const char* char_font_texture_file_format;
    const char* horizontal_alignment;
    const char* vertical_alignment;
} PrintingStruct;

typedef struct
{
    double rho;
    double theta;
    double phi;
} SphericalCoordinatesStruct;

typedef struct SphericalWorldStruct
{
    SphericalWorldStruct()
        :SRTM_latitude_step_in_degrees(1.0f/1200.0f), SRTM_longitude_step_in_degrees(1.0f/1200.0f)
    {
        // constructor.
    }
    double southern_latitude;
    double northern_latitude;
    double western_longitude;
    double eastern_longitude;
    double SRTM_latitude_step_in_degrees;
    double SRTM_longitude_step_in_degrees;
} SphericalWorldStruct;

typedef struct TriangulateQuadsStruct
{
    TriangulateQuadsStruct()
        : should_ylikuutio_use_real_texture_coordinates(true)
    {
        // constructor.
    }
    uint32_t image_width;
    uint32_t image_height;
    std::string triangulation_type;
    bool should_ylikuutio_use_real_texture_coordinates;
    double sphere_radius;
    SphericalWorldStruct spherical_world_struct;
} TriangulateQuadsStruct;

typedef struct TriangulatePolygonsStruct
{
    TriangulatePolygonsStruct()
        : should_ylikuutio_use_real_texture_coordinates(true)
    {
        // constructor.
    }
    std::vector<std::vector<glm::vec2>>* input_vertices;
    bool should_ylikuutio_use_real_texture_coordinates;
} TriangulatePolygonsStruct;

typedef struct
{
    uint32_t image_width;
    uint32_t image_height;
    bool should_ylikuutio_use_real_texture_coordinates;
} BilinearInterpolationStruct;

typedef struct
{
    uint32_t image_width;
    uint32_t image_height;
    double sphere_radius;
    bool is_bilinear_interpolation_in_use;
    SphericalWorldStruct spherical_world_struct;
} TransformationStruct;

typedef datatypes::AnyValue* (*InputParametersToAnyValueCallback) (
        callback_system::CallbackEngine*,
        callback_system::CallbackObject*,
        std::vector<callback_system::CallbackParameter*>&);

namespace console
{
    class Console;
}
typedef datatypes::AnyValue* (*InputParametersToAnyValueCallbackWithConsole) (
        callback_system::CallbackEngine*,
        callback_system::CallbackObject*,
        std::vector<callback_system::CallbackParameter*>&,
        console::Console*);

typedef datatypes::AnyValue* (*ConsoleCommandCallback) (
        console::Console*,
        ontology::Universe*,
        std::vector<std::string>& command_parameters);

typedef datatypes::AnyValue* (*GetContentCallback) (
        callback_system::CallbackEngine*,
        callback_system::CallbackObject*,
        std::vector<callback_system::CallbackParameter*>&,
        uint32_t x_start,
        uint32_t y_start,
        uint32_t z_start,
        uint32_t x_size,
        uint32_t y_size,
        uint32_t z_size);

#endif
<commit_msg>`typedef struct SettingStruct {` ... }` SettingStruct`.<commit_after>#ifndef __GLOBALS_HPP_INCLUDED
#define __GLOBALS_HPP_INCLUDED

#include "any_value.hpp"

// GCC (at least g++ 4.7.2) and Visual Studio 2015 do support
// setting default values of a struct using C++11 syntax.
// Clang 3.7.0 and Visual Studio 2013 do not support
// setting default values of a struct using C++11 syntax.
// Visual Studio 2013 fails to compile, whereas Clang-compiled
// executable with code with setting default values of a struct
// causes Segmentation fault upon execution of the program.
// Compilers that don't support setting default values of a struct
// are handled by setting the default values in a macro.
// http://stackoverflow.com/questions/16782103/initializing-default-values-in-a-struct/16783513#16783513
#ifdef __clang__
#elif defined(__GNUC__)
#define __STRUCT_DEFAULT_VALUES_ARE_ACCEPTED
#elif defined(_WIN32)
#if (_MSC_VER >= 1900)
#define __STRUCT_DEFAULT_VALUES_ARE_ACCEPTED
#endif
#endif

// GLEW must be included here, because `globals.hpp` may be compiled
// first, and if `GL/glew.h` is not included before `glfw3.h` (?),
// then g++ prints the following error:
// `error: #error gl.h included before glew.h`
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h> // GLfloat, GLuint etc.
#endif

// Include GLFW
#ifndef __GLFW3_H_INCLUDED
#define __GLFW3_H_INCLUDED
#include <glfw3.h>
#endif

// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif

// Include standard headers
#include <cmath>    // NAN, std::isnan, std::pow
#include <stdint.h> // uint32_t etc.
#include <string>   // std::string
#include <vector>   // std::vector

#ifndef PI
#define PI 3.14159265359f
#endif

namespace config
{
    class SettingMaster;
    class Setting;
}

namespace callback_system
{
    class CallbackEngine;
    class CallbackObject;
    class CallbackParameter;
}

namespace graph
{
    class Graph;
}

namespace ontology
{
    class Universe;
    class Scene;
    class Shader;
    class Material;
    class VectorFont;
    class Species;
    class Glyph;
    class Text3D;
}

typedef struct ShaderStruct
{
    ShaderStruct()
        : parent_pointer(nullptr)
    {
        // constructor.
    }
    ontology::Scene* parent_pointer; // pointer to the scene (draw list).
    std::string vertex_shader;    // filename of vertex shader.
    std::string fragment_shader;  // filename of fragment shader.
} ShaderStruct;

typedef struct MaterialStruct
{
    MaterialStruct()
        : parent_pointer(nullptr)
    {
        // constructor.
    }
    ontology::Shader* parent_pointer;   // pointer to the shader.
    std::string texture_file_format; // type of the texture file. supported file formats so far: `"bmp"`/`"BMP"`, `"dds"`/`"DDS"`.
    std::string texture_filename;    // filename of the model file.
    std::string image_path;
} MaterialStruct;

typedef struct NodeStruct
{
    NodeStruct()
        : parent_pointer(nullptr)
    {
        // constructor.
    }
    uint32_t nodeID;
    graph::Graph* parent_pointer;
    std::vector<uint32_t> neighbor_nodeIDs;
} NodeStruct;

typedef struct ObjectStruct
{
    ObjectStruct()
        : species_parent_pointer(nullptr), glyph_parent_pointer(nullptr), text3D_parent_pointer(nullptr), original_scale_vector(glm::vec3(1.0f, 1.0f, 1.0f)), rotate_angle(NAN), is_character(false)
    {
        // constructor.
    }
    ontology::Species* species_parent_pointer; // pointer to the parent `Species`.
    ontology::Glyph* glyph_parent_pointer;     // pointer to the parent `Glyph`.
    ontology::Text3D* text3D_parent_pointer;   // pointer to the parent `Text3D`.
    glm::vec3 original_scale_vector; // original scale vector.
    float rotate_angle;              // rotate angle.
    bool is_character;               // The parent of a character object is a Glyph. The parent of a regular object is a Species.
    glm::vec3 coordinate_vector;     // coordinate vector.
    glm::vec3 rotate_vector;         // rotate vector.
    glm::vec3 translate_vector;      // translate vector.
} ObjectStruct;

typedef struct SpeciesStruct
{
    SpeciesStruct()
        : parent_pointer(nullptr), is_world(false), world_radius(NAN), divisor(1.0f), triangulation_type("bilinear_interpolation")
    {
        // constructor.
    }
    // used for all files (for all species).
    ontology::Material* parent_pointer;      // pointer to the material object.
    bool is_world;                           // worlds currently do not rotate nor translate.
    float world_radius;                      // radius of sea level in kilometers. used only for worlds.
    float divisor;                           // value by which SRTM values are divided to convert them to kilometers.
    std::string model_file_format;           // type of the model file. supported file formats so far: `"bmp"`/`"BMP"`, `"obj"`/`"OBJ"`.
                                             // TODO: add support for `"SRTM"`.
    std::string model_filename;              // filename of the model file.
    // for `"bmp"` model files.
    std::string color_channel;               // color channel to use for altitude data.

    glm::vec3 light_position;                // light position.
    std::string coordinate_system;           // used only for worlds (`is_world` == `true`). valid values: `"cartesian"`.
                                             // TODO: add support for `"spherical"`. `"spherical"` is used eg. in SRTM heightmaps.
    std::string triangulation_type;
} SpeciesStruct;

#define DEFAULT_VERTEX_SCALING_FACTOR (0.001f)

typedef struct VectorFontStruct
{
    VectorFontStruct()
        : parent_pointer(nullptr), vertex_scaling_factor(DEFAULT_VERTEX_SCALING_FACTOR)
    {
        // constructor.
    }
    // used for all files (for all font).
    ontology::Material* parent_pointer;        // pointer to the material object.
    GLfloat vertex_scaling_factor;
    std::string font_file_format;           // type of the font file. supported file formats so far: `"svg"`/`"SVG"`.
    std::string font_filename;              // filename of the font file.
} VectorFontStruct;

typedef struct Text3DStruct
{
    Text3DStruct()
        : parent_pointer(nullptr), original_scale_vector(glm::vec3(1.0f, 1.0f, 1.0f)), rotate_angle(NAN)
    {
        // constructor.
    }
    ontology::VectorFont* parent_pointer; // pointer to the parent `VectorFont`.
    std::string text_string;
    const char* text_string_char;
    glm::vec3 original_scale_vector;   // original scale vector.
    float rotate_angle;                // rotate angle.
    glm::vec3 coordinate_vector;       // coordinate vector.
    glm::vec3 rotate_vector;           // rotate vector.
    glm::vec3 translate_vector;        // translate vector.
} Text3DStruct;

typedef struct GlyphStruct
{
    GlyphStruct()
        : parent_pointer(nullptr)
    {
        // constructor.
    }
    // used for all files (for all glyph).
    std::vector<std::vector<glm::vec2>>* glyph_vertex_data;
    const char* glyph_name_pointer;          // we need only a pointer, because glyphs are always created by the `VectorFont` constructor.
    const char* unicode_char_pointer;      // we need only a pointer, because glyphs are always created by the `VectorFont` constructor.
    ontology::VectorFont* parent_pointer;       // pointer to the font object.
    glm::vec3 light_position;                // light position.
} GlyphStruct;

typedef struct SettingStruct
{
    std::string name;
    config::SettingMaster* parent_pointer;
    callback_system::CallbackEngine* activate_callback_engine_pointer;
} SettingStruct;

typedef struct
{
    uint32_t screen_width;
    uint32_t screen_height;
    uint32_t x;
    uint32_t y;
    uint32_t text_size;
    uint32_t font_size;
    std::string text;
    const char* text_char;
    const char* char_font_texture_file_format;
    const char* horizontal_alignment;
    const char* vertical_alignment;
} PrintingStruct;

typedef struct
{
    double rho;
    double theta;
    double phi;
} SphericalCoordinatesStruct;

typedef struct SphericalWorldStruct
{
    SphericalWorldStruct()
        :SRTM_latitude_step_in_degrees(1.0f/1200.0f), SRTM_longitude_step_in_degrees(1.0f/1200.0f)
    {
        // constructor.
    }
    double southern_latitude;
    double northern_latitude;
    double western_longitude;
    double eastern_longitude;
    double SRTM_latitude_step_in_degrees;
    double SRTM_longitude_step_in_degrees;
} SphericalWorldStruct;

typedef struct TriangulateQuadsStruct
{
    TriangulateQuadsStruct()
        : should_ylikuutio_use_real_texture_coordinates(true)
    {
        // constructor.
    }
    uint32_t image_width;
    uint32_t image_height;
    std::string triangulation_type;
    bool should_ylikuutio_use_real_texture_coordinates;
    double sphere_radius;
    SphericalWorldStruct spherical_world_struct;
} TriangulateQuadsStruct;

typedef struct TriangulatePolygonsStruct
{
    TriangulatePolygonsStruct()
        : should_ylikuutio_use_real_texture_coordinates(true)
    {
        // constructor.
    }
    std::vector<std::vector<glm::vec2>>* input_vertices;
    bool should_ylikuutio_use_real_texture_coordinates;
} TriangulatePolygonsStruct;

typedef struct
{
    uint32_t image_width;
    uint32_t image_height;
    bool should_ylikuutio_use_real_texture_coordinates;
} BilinearInterpolationStruct;

typedef struct
{
    uint32_t image_width;
    uint32_t image_height;
    double sphere_radius;
    bool is_bilinear_interpolation_in_use;
    SphericalWorldStruct spherical_world_struct;
} TransformationStruct;

typedef datatypes::AnyValue* (*InputParametersToAnyValueCallback) (
        callback_system::CallbackEngine*,
        callback_system::CallbackObject*,
        std::vector<callback_system::CallbackParameter*>&);

namespace console
{
    class Console;
}
typedef datatypes::AnyValue* (*InputParametersToAnyValueCallbackWithConsole) (
        callback_system::CallbackEngine*,
        callback_system::CallbackObject*,
        std::vector<callback_system::CallbackParameter*>&,
        console::Console*);

typedef datatypes::AnyValue* (*ConsoleCommandCallback) (
        console::Console*,
        ontology::Universe*,
        std::vector<std::string>& command_parameters);

typedef datatypes::AnyValue* (*GetContentCallback) (
        callback_system::CallbackEngine*,
        callback_system::CallbackObject*,
        std::vector<callback_system::CallbackParameter*>&,
        uint32_t x_start,
        uint32_t y_start,
        uint32_t z_start,
        uint32_t x_size,
        uint32_t y_size,
        uint32_t z_size);

#endif
<|endoftext|>


<commit_before>#include "UI_Text.h"
#include "j1App.h"
#include "j1Textures.h"
#include "j1Fonts.h"
#include "j1Render.h"

Text::~Text()
{
	if (outline != nullptr)
	{
		App->tex->UnLoad(outline);
		outline = nullptr;
	}
}

void Text::createTexture()
{
	if (texture != nullptr)
	{
		App->tex->UnLoad(texture);
		texture = nullptr;
	}
	if (outline != nullptr)
	{
		App->tex->UnLoad(outline);
		outline = nullptr;
	}

	uint outline_width, outline_height;
	if (outlined)
	{
		App->font->setFontOutline(font, 2);
		outline = App->font->Print(text.GetString(), outline_color, font); //Outlined texture
		App->tex->GetSize(outline, outline_width, outline_height);
	}

	App->font->setFontOutline(font, 0);
	texture = App->font->Print(text.GetString(), color, font); //Normal texture
	App->tex->GetSize(texture, tex_width, tex_height);
	section.w = tex_width;
	section.h = tex_height;

	if (outlined)
	{
		outline_offset.x = tex_width - outline_width;
		outline_offset.x /= 2/App->gui->UI_scale;
		outline_offset.y = outline_offset.x;
	}

}

void Text::setColor(SDL_Color newColor)
{
	color = newColor;
	createTexture();
}

void Text::setOutlineColor(SDL_Color newColor)
{
	outline_color = newColor;
	if (outlined)
		createTexture();
}

void Text::BlitElement()
{
	iPoint globalPos = calculateAbsolutePosition();

	if (outlined)
		App->render->Blit(outline, globalPos.x + outline_offset.x, globalPos.y + outline_offset.y, NULL, false, App->gui->UI_scale);
	App->render->Blit(texture, globalPos.x, globalPos.y, NULL, false, App->gui->UI_scale);
}

void Text::setOutlined(bool isOutlined)
{
	if (isOutlined != outlined)
	{
		outlined = isOutlined;
		createTexture();
	}
}

p2SString Text::getText() const
{
	return text;
}

void Text::setText(const char * string)
{
	text = string;
	createTexture();
}

void Text::setText(const p2SString string)
{
	text = string;
	createTexture();
}

int Text::getLength() const
{
	return text.Length();
}
<commit_msg>solved a bug with text blit<commit_after>#include "UI_Text.h"
#include "j1App.h"
#include "j1Textures.h"
#include "j1Fonts.h"
#include "j1Render.h"

Text::~Text()
{
	if (outline != nullptr)
	{
		App->tex->UnLoad(outline);
		outline = nullptr;
	}
}

void Text::createTexture()
{
	if (texture != nullptr)
	{
		App->tex->UnLoad(texture);
		texture = nullptr;
	}
	if (outline != nullptr)
	{
		App->tex->UnLoad(outline);
		outline = nullptr;
	}

	uint outline_width, outline_height;
	if (outlined)
	{
		App->font->setFontOutline(font, 2);
		outline = App->font->Print(text.GetString(), outline_color, font); //Outlined texture
		App->tex->GetSize(outline, outline_width, outline_height);
	}

	App->font->setFontOutline(font, 0);
	texture = App->font->Print(text.GetString(), color, font); //Normal texture
	App->tex->GetSize(texture, tex_width, tex_height);
	section.w = tex_width;
	section.h = tex_height;

	if (outlined)
	{
		outline_offset.x = tex_width - outline_width;
		outline_offset.x /= 2/App->gui->UI_scale;
		outline_offset.y = outline_offset.x;
	}

}

void Text::setColor(SDL_Color newColor)
{
	color = newColor;
	createTexture();
}

void Text::setOutlineColor(SDL_Color newColor)
{
	outline_color = newColor;
	if (outlined)
		createTexture();
}

void Text::BlitElement()
{
	if (texture != nullptr)
	{
		iPoint globalPos = calculateAbsolutePosition();

		if (outlined)
			App->render->Blit(outline, globalPos.x + outline_offset.x, globalPos.y + outline_offset.y, NULL, false, App->gui->UI_scale);
		App->render->Blit(texture, globalPos.x, globalPos.y, NULL, false, App->gui->UI_scale);
	}
}

void Text::setOutlined(bool isOutlined)
{
	if (isOutlined != outlined)
	{
		outlined = isOutlined;
		createTexture();
	}
}

p2SString Text::getText() const
{
	return text;
}

void Text::setText(const char * string)
{
	text = string;
	createTexture();
}

void Text::setText(const p2SString string)
{
	text = string;
	createTexture();
}

int Text::getLength() const
{
	return text.Length();
}
<|endoftext|>


<commit_before>#ifndef PI
#define PI 3.14159265359f
#endif

#ifndef GLM_FORCE_RADIANS
#define GLM_FORCE_RADIANS
#define DEGREES_TO_RADIANS(x) (x * PI / 180.0f)
#endif

#include "scene.hpp"
#include "ground_level.hpp"
#include "shader.hpp"
#include "render_templates.hpp"
#include "code/ylikuutio/hierarchy/hierarchy_templates.hpp"
#include "code/ylikuutio/common/pi.hpp"

// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h> // GLfloat, GLuint etc.
#endif

// Include standard headers
#include <cmath>    // NAN, std::isnan, std::pow
#include <iostream> // std::cout, std::cin, std::cerr
#include <stdint.h> // uint32_t etc.
#include <unordered_map> // std::unordered_map

namespace ontology
{
    class Object;

    void Scene::bind_to_parent()
    {
        // get `childID` from `Universe` and set pointer to this `Scene`.
        hierarchy::bind_child_to_parent<ontology::Scene*>(this, this->parent->scene_pointer_vector, this->parent->free_sceneID_queue, &this->parent->number_of_scenes);
    }

    Scene::~Scene()
    {
        // destructor.
        std::cout << "Scene with childID " << std::dec << this->childID << " will be destroyed.\n";

        // destroy all shaders of this scene.
        std::cout << "All shaders of this scene will be destroyed.\n";
        hierarchy::delete_children<ontology::Shader*>(this->shader_pointer_vector, &this->number_of_shaders);

        // If this is the active `Scene`, set all `Scene`-related variables to `nullptr` or invalid.
        if (this->universe->active_scene == this)
        {
            this->universe->cartesian_coordinates = nullptr;

            this->universe->direction = glm::vec3(NAN, NAN, NAN);

            this->universe->right = glm::vec3(NAN, NAN, NAN);
            this->universe->up = glm::vec3(NAN, NAN, NAN);

            this->universe->spherical_coordinates = nullptr;

            this->universe->horizontal_angle = NAN;
            this->universe->vertical_angle = NAN;

            // Make this `Scene` no more the active `Scene`.
            this->universe->active_scene = nullptr;
        }

        // set pointer to this scene to nullptr.
        this->parent->set_scene_pointer(this->childID, nullptr);
    }

    void Scene::render()
    {
        this->prerender();

        // render this `Scene` by calling `render()` function of each `Shader`.
        ontology::render_children<ontology::Shader*>(this->shader_pointer_vector);

        this->postrender();
    }

    ontology::Entity* Scene::get_parent()
    {
        return this->parent;
    }

    int32_t Scene::get_number_of_children()
    {
        return this->number_of_shaders;
    }

    int32_t Scene::get_number_of_descendants()
    {
        return -1;
    }

    // this method returns a pointer to an `Entity` using the name as key.
    ontology::Entity* Scene::get_entity(const std::string name)
    {
        if (this->name_map.count(name) != 1)
        {
            return nullptr;
        }

        return this->name_map[name];
    }

    void Scene::set_name(const std::string name)
    {
        ontology::set_name(name, this);
    }

    void Scene::set_turbo_factor(float turbo_factor)
    {
        this->turbo_factor = turbo_factor;

        if (this == this->universe->active_scene)
        {
            this->universe->turbo_factor = this->turbo_factor;
        }
    }

    void Scene::set_twin_turbo_factor(float twin_turbo_factor)
    {
        this->twin_turbo_factor = twin_turbo_factor;

        if (this == this->universe->active_scene)
        {
            this->universe->twin_turbo_factor = this->twin_turbo_factor;
        }
    }

    void Scene::set_shader_pointer(const int32_t childID, ontology::Shader* const child_pointer)
    {
        hierarchy::set_child_pointer(childID, child_pointer, this->shader_pointer_vector, this->free_shaderID_queue, &this->number_of_shaders);
    }
}
<commit_msg>Bugfix `Scene::~Scene()`: do not invalidate `Scene`-related variables.<commit_after>#ifndef PI
#define PI 3.14159265359f
#endif

#ifndef GLM_FORCE_RADIANS
#define GLM_FORCE_RADIANS
#define DEGREES_TO_RADIANS(x) (x * PI / 180.0f)
#endif

#include "scene.hpp"
#include "ground_level.hpp"
#include "shader.hpp"
#include "render_templates.hpp"
#include "code/ylikuutio/hierarchy/hierarchy_templates.hpp"
#include "code/ylikuutio/common/pi.hpp"

// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h> // GLfloat, GLuint etc.
#endif

// Include standard headers
#include <cmath>    // NAN, std::isnan, std::pow
#include <iostream> // std::cout, std::cin, std::cerr
#include <stdint.h> // uint32_t etc.
#include <unordered_map> // std::unordered_map

namespace ontology
{
    class Object;

    void Scene::bind_to_parent()
    {
        // get `childID` from `Universe` and set pointer to this `Scene`.
        hierarchy::bind_child_to_parent<ontology::Scene*>(this, this->parent->scene_pointer_vector, this->parent->free_sceneID_queue, &this->parent->number_of_scenes);
    }

    Scene::~Scene()
    {
        // destructor.
        std::cout << "Scene with childID " << std::dec << this->childID << " will be destroyed.\n";

        // destroy all shaders of this scene.
        std::cout << "All shaders of this scene will be destroyed.\n";
        hierarchy::delete_children<ontology::Shader*>(this->shader_pointer_vector, &this->number_of_shaders);

        if (this->universe->get_active_scene() == this)
        {
            // Make this `Scene` no more the active `Scene`.
            this->universe->set_active_scene(nullptr);
        }

        // set pointer to this scene to nullptr.
        this->parent->set_scene_pointer(this->childID, nullptr);
    }

    void Scene::render()
    {
        this->prerender();

        // render this `Scene` by calling `render()` function of each `Shader`.
        ontology::render_children<ontology::Shader*>(this->shader_pointer_vector);

        this->postrender();
    }

    ontology::Entity* Scene::get_parent()
    {
        return this->parent;
    }

    int32_t Scene::get_number_of_children()
    {
        return this->number_of_shaders;
    }

    int32_t Scene::get_number_of_descendants()
    {
        return -1;
    }

    // this method returns a pointer to an `Entity` using the name as key.
    ontology::Entity* Scene::get_entity(const std::string name)
    {
        if (this->name_map.count(name) != 1)
        {
            return nullptr;
        }

        return this->name_map[name];
    }

    void Scene::set_name(const std::string name)
    {
        ontology::set_name(name, this);
    }

    void Scene::set_turbo_factor(float turbo_factor)
    {
        this->turbo_factor = turbo_factor;

        if (this == this->universe->active_scene)
        {
            this->universe->turbo_factor = this->turbo_factor;
        }
    }

    void Scene::set_twin_turbo_factor(float twin_turbo_factor)
    {
        this->twin_turbo_factor = twin_turbo_factor;

        if (this == this->universe->active_scene)
        {
            this->universe->twin_turbo_factor = this->twin_turbo_factor;
        }
    }

    void Scene::set_shader_pointer(const int32_t childID, ontology::Shader* const child_pointer)
    {
        hierarchy::set_child_pointer(childID, child_pointer, this->shader_pointer_vector, this->free_shaderID_queue, &this->number_of_shaders);
    }
}
<|endoftext|>


<commit_before>#ifndef ITER_COMBINATIONS_WITH_REPLACEMENT_HPP_
#define ITER_COMBINATIONS_WITH_REPLACEMENT_HPP_

#include "iterbase.hpp"

#include <iterator>
#include <vector>
#include <type_traits>
#include <initializer_list>

namespace iter {

    template <typename Container>
    class CombinatorWithReplacement;

    template <typename Container>
    CombinatorWithReplacement<Container> combinations_with_replacement(
            Container&&, std::size_t);

    template <typename T>
    CombinatorWithReplacement<std::initializer_list<T>>
    combinations_with_replacement(
            std::initializer_list<T>, std::size_t);

    template <typename Container>
    class CombinatorWithReplacement {
        private:
            Container container;
            std::size_t length;

            friend CombinatorWithReplacement
                combinations_with_replacement<Container>(
                        Container&& ,std::size_t);
            template <typename T>
            friend CombinatorWithReplacement<std::initializer_list<T>>
            combinations_with_replacement(
                    std::initializer_list<T>, std::size_t);

           CombinatorWithReplacement(Container&& container, std::size_t n)
               : container(std::forward<Container>(container)),
               length{n}
           { }

            using CombIteratorDeref =
                std::vector<collection_item_type<Container>>;

        public:
            class Iterator :
                public std::iterator<std::input_iterator_tag,
                    CombIteratorDeref>
            {
               private:
                   typename std::remove_reference<Container>::type *container_p;
                   std::vector<iterator_type<Container>> indicies;
                   bool not_done;

               public:
                   Iterator(Container& in_container, std::size_t n)
                       : container_p{&in_container},
                       indicies(n, std::begin(in_container)),
                       not_done{n != 0}
                   { }

                   CombIteratorDeref operator*() {
                       std::vector<collection_item_type<Container>> values;
                       for (auto i : indicies) {
                           values.push_back(*i);
                       }
                       return values;
                   }

                   Iterator& operator++() {
                       for (auto iter = indicies.rbegin();
                               iter != indicies.rend();
                               ++iter) {
                           ++(*iter);
                           if (!(*iter != std::end(*this->container_p))) {
                               if ( (iter + 1) != indicies.rend()) {
                                   for (auto down = iter;
                                           down != indicies.rbegin()-1;
                                           --down) {
                                       (*down) = dumb_next(*(iter + 1));
                                   }
                               } else {
                                   not_done = false;
                                   break;
                               }
                           } else {
                               //we break because none of the rest of the items
                               //need to be incremented
                               break;
                           }
                       }
                       return *this;
                   }

                   Iterator operator++(int) {
                       auto ret = *this;
                       ++*this;
                       return ret;
                   }

                   bool operator!=(const Iterator&) const {
                       //because of the way this is done you have to start from
                       //the begining of the range and end at the end, you
                       //could break in the middle of the loop though, it's not
                       //different from the way that python's works
                       return not_done;
                   }

                   bool operator==(const Iterator& other) const {
                       return !(*this != other);
                   }

           };

           Iterator begin() {
               return {this->container, this->length};
           }

           Iterator end() {
               return {this->container, 0};
           }
    };

    template <typename Container>
    CombinatorWithReplacement<Container> combinations_with_replacement(
            Container&& container, std::size_t length) {
        return {std::forward<Container>(container), length};
    }

    template <typename T>
    CombinatorWithReplacement<std::initializer_list<T>>
    combinations_with_replacement(
            std::initializer_list<T> il, std::size_t length) {
        return {il, length};
    }
}

#endif
<commit_msg>corrects handling of init lasts<commit_after>#ifndef ITER_COMBINATIONS_WITH_REPLACEMENT_HPP_
#define ITER_COMBINATIONS_WITH_REPLACEMENT_HPP_

#include "iterbase.hpp"

#include <iterator>
#include <vector>
#include <type_traits>
#include <initializer_list>

namespace iter {

    template <typename Container>
    class CombinatorWithReplacement;

    template <typename Container>
    CombinatorWithReplacement<Container> combinations_with_replacement(
            Container&&, std::size_t);

    template <typename T>
    CombinatorWithReplacement<std::initializer_list<T>>
    combinations_with_replacement(
            std::initializer_list<T>, std::size_t);

    template <typename Container>
    class CombinatorWithReplacement {
        private:
            Container container;
            std::size_t length;

            friend CombinatorWithReplacement
                combinations_with_replacement<Container>(
                        Container&& ,std::size_t);
            template <typename T>
            friend CombinatorWithReplacement<std::initializer_list<T>>
            combinations_with_replacement(
                    std::initializer_list<T>, std::size_t);

           CombinatorWithReplacement(Container&& container, std::size_t n)
               : container(std::forward<Container>(container)),
               length{n}
           { }

            using CombIteratorDeref =
                std::vector<collection_item_type<Container>>;

        public:
            class Iterator :
                public std::iterator<std::input_iterator_tag,
                    CombIteratorDeref>
            {
               private:
                   typename std::remove_reference<Container>::type *container_p;
                   std::vector<iterator_type<Container>> indicies;
                   bool not_done;

               public:
                   Iterator(Container& in_container, std::size_t n)
                       : container_p{&in_container},
                       indicies(n, std::begin(in_container)),
                       not_done{n != 0}
                   { }

                   CombIteratorDeref operator*() {
                       std::vector<collection_item_type<Container>> values;
                       for (auto i : indicies) {
                           values.push_back(*i);
                       }
                       return values;
                   }

                   Iterator& operator++() {
                       for (auto iter = indicies.rbegin();
                               iter != indicies.rend();
                               ++iter) {
                           ++(*iter);
                           if (!(*iter != std::end(*this->container_p))) {
                               if ( (iter + 1) != indicies.rend()) {
                                   for (auto down = iter;
                                           down != indicies.rbegin()-1;
                                           --down) {
                                       (*down) = dumb_next(*(iter + 1));
                                   }
                               } else {
                                   not_done = false;
                                   break;
                               }
                           } else {
                               //we break because none of the rest of the items
                               //need to be incremented
                               break;
                           }
                       }
                       return *this;
                   }

                   Iterator operator++(int) {
                       auto ret = *this;
                       ++*this;
                       return ret;
                   }

                   bool operator!=(const Iterator&) const {
                       //because of the way this is done you have to start from
                       //the begining of the range and end at the end, you
                       //could break in the middle of the loop though, it's not
                       //different from the way that python's works
                       return not_done;
                   }

                   bool operator==(const Iterator& other) const {
                       return !(*this != other);
                   }

           };

           Iterator begin() {
               return {this->container, this->length};
           }

           Iterator end() {
               return {this->container, 0};
           }
    };

    template <typename Container>
    CombinatorWithReplacement<Container> combinations_with_replacement(
            Container&& container, std::size_t length) {
        return {std::forward<Container>(container), length};
    }

    template <typename T>
    CombinatorWithReplacement<std::initializer_list<T>>
    combinations_with_replacement(
            std::initializer_list<T> il, std::size_t length) {
        return {std::move(il), length};
    }
}

#endif
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/isteps/istep11/call_ocmb_check_for_ready.C $          */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2021                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
/**
 *  @file call_ocmb_check_for_ready.C
 *
 *  Support file for IStep: ocmb_check_for_ready
 *    Check that OCMB is ready
 *
 */

/******************************************************************************/
// Includes
/******************************************************************************/

//  Error handling support
#include <errl/errlentry.H>                     // errlHndl_t
#include <errl/errlmanager.H>
#include <errl/errludtarget.H>                  // ErrlUserDetailsTarget
#include <istepHelperFuncs.H>                   // captureError

//  FAPI support
#include <fapi2.H>
#include <plat_hwp_invoker.H>
#include <isteps/hwpisteperror.H>               // IStepError

//  Tracing support
#include <initservice/isteps_trace.H>           // g_trac_isteps_trace

//  Targeting support
#include <attributeenums.H>                     // TYPE_PROC
#include <targeting/common/utilFilter.H>        // getAllChips
#include <sbeio/sbeioif.H>
#include <util/misc.H>
#include <sys/time.h>
#include <time.h>

//  HWP call support
#include <exp_check_for_ready.H>

// Explorer error logs
#include <expscom/expscom_errlog.H>

using namespace ISTEPS_TRACE;
using namespace ISTEP_ERROR;
using namespace ERRORLOG;
using namespace TARGETING;

namespace ISTEP_11
{
void* call_ocmb_check_for_ready (void *io_pArgs)
{
    TRACFCOMP(g_trac_isteps_trace, ENTER_MRK"call_ocmb_check_for_ready");

    errlHndl_t  l_errl = nullptr;
    IStepError l_StepError;

    // We need to do an explicit delay before our first i2c operation
    //  to Explorer to ensure we don't catch it too early in the boot
    //  and lock it up.
    const auto ocmb_delay = UTIL::assertGetToplevelTarget()
      ->getAttr<ATTR_OCMB_RESET_DELAY_SEC>();
    nanosleep(ocmb_delay,0);

    TargetHandleList functionalProcChipList;

    getAllChips(functionalProcChipList, TYPE_PROC, true);

    // loop thru the list of processors
    for (TargetHandleList::const_iterator
            l_proc_iter = functionalProcChipList.begin();
            l_proc_iter != functionalProcChipList.end();
            ++l_proc_iter)
    {
        // For each loop on an OCMB below, multiply the timeout chunk
        size_t loop_multiplier = 1;

        // Keep track of overall time
        size_t l_maxTime_secs = 0;
        timespec_t l_preLoopTime = {};
        timespec_t l_ocmbCurrentTime = {};
        clock_gettime(CLOCK_MONOTONIC, &l_preLoopTime);

        TargetHandleList l_functionalOcmbChipList;
        getChildAffinityTargets( l_functionalOcmbChipList,
                                 const_cast<Target*>(*l_proc_iter),
                                 CLASS_CHIP,
                                 TYPE_OCMB_CHIP,
                                 true);

        for (const auto & l_ocmb : l_functionalOcmbChipList)
        {
            TRACFCOMP(g_trac_isteps_trace,
                        "Start : exp_check_for_ready "
                        "for 0x%.08X", get_huid(l_ocmb));

            fapi2::Target <fapi2::TARGET_TYPE_OCMB_CHIP>
                                    l_fapi_ocmb_target(l_ocmb);

            // Save the original timeout (to be restored after exp_check_for_ready)
            // Units for the attribute are milliseconds; the value returned is > 1 second
            const auto original_timeout_ms
                = l_ocmb->getAttr<ATTR_MSS_CHECK_FOR_READY_TIMEOUT>();

            // Calculate MAX Wait Time - Round up on seconds
            // - ATTR_MSS_CHECK_FOR_READY_TIMEOUT in msec (see exp_attributes.xml)
            // - This assumes that all of the OCMBs on a processor were started at the same time
            //   and that they all have the same original_timeout value
            // - The calculation is as follows:
            // 1) Start with the 'seconds' value of the pre-loop time
            // 2) Add *double* the 'seconds' amount of the original timeout value
            //    -- the *double* is just to be on the safe side, as we're only dealing with
            //       seconds and not minutes here
            // 3) Add 3 to round up for the nanoseconds of (1) and double the milliseconds of (2)
            if (l_maxTime_secs == 0)
            {
                // If not set yet, then set it here:
                l_maxTime_secs = l_preLoopTime.tv_sec
                                 + (2 * (original_timeout_ms / MS_PER_SEC))
                                 + 3;
            }

            // exp_check_for_ready will read this attribute to know how long to
            // poll. If this number is too large and we get too many I2C error
            // logs between calls to FAPI_INVOKE_HWP, we will run out of memory.
            // So break the original timeout into smaller timeouts.
            // This will not affect how the loop below will use l_maxTime_secs to look for a timouts
            const ATTR_MSS_CHECK_FOR_READY_TIMEOUT_type smaller_timeout_ms = 10 * loop_multiplier++;
            l_ocmb->setAttr<ATTR_MSS_CHECK_FOR_READY_TIMEOUT>(smaller_timeout_ms);

            TRACFCOMP(g_trac_isteps_trace,"exp_check_for_ready: For OCMB 0x%X: "
                      "original_timeout_ms = %d, smaller_timeout_ms = %d, "
                      "l_preLoopTime.tv_sec = %lu l_maxTime_secs = %lu",
                      get_huid(l_ocmb), original_timeout_ms, smaller_timeout_ms,
                      l_preLoopTime.tv_sec, l_maxTime_secs);

            // Variable used to track attempting one more time after max time has
            // been succeeded
            bool l_one_more_try = false;

            // Retry exp_check_for_ready as many times as it takes to either
            // succeed or time out
            while (true)
            {
                // Delete the log from the previous iteration
                if( l_errl )
                {
                    delete l_errl;
                    l_errl = nullptr;
                }

                FAPI_INVOKE_HWP(l_errl,
                                exp_check_for_ready,
                                l_fapi_ocmb_target);

                // On success, quit retrying.
                if (!l_errl)
                {
                    break;
                }

                clock_gettime(CLOCK_MONOTONIC, &l_ocmbCurrentTime);
                if (l_ocmbCurrentTime.tv_sec > l_maxTime_secs)
                {
                    if (l_one_more_try == false)
                    {
                        // Do one more attempt just to be safe
                        l_one_more_try = true;
                        TRACFCOMP(g_trac_isteps_trace,"exp_check_for_ready "
                                  "Setting 'one more try' (%d) based on times: "
                                  "l_ocmbCurrentTime.tv_sec = %lu, l_maxTime_secs = %lu",
                                  l_one_more_try, l_ocmbCurrentTime.tv_sec, l_maxTime_secs);

                    }
                    else
                    {
                        // Already done "one more try" so just break
                        TRACFCOMP(g_trac_isteps_trace,"exp_check_for_ready "
                                  "Breaking as 'one more try' (%d) was already set. "
                                  "l_ocmbCurrentTime.tv_sec = %lu, l_maxTime_secs = %lu",
                                  l_one_more_try, l_ocmbCurrentTime.tv_sec, l_maxTime_secs);
                        break;
                    }
                }

            } // end of timeout loop

            // Restore original timeout value
            l_ocmb->setAttr<ATTR_MSS_CHECK_FOR_READY_TIMEOUT>(original_timeout_ms);

            if (l_errl)
            {
                TRACFCOMP(g_trac_isteps_trace,
                          "ERROR : call_ocmb_check_for_ready HWP(): "
                          "exp_check_for_ready failed on target 0x%08X."
                          TRACE_ERR_FMT,
                          get_huid(l_ocmb),
                          TRACE_ERR_ARGS(l_errl));

                // Capture error and continue to next OCMB
                captureError(l_errl, l_StepError, HWPF_COMP_ID, l_ocmb);
            }
            else
            {
                TRACFCOMP(g_trac_isteps_trace,
                          "SUCCESS : exp_check_for_ready "
                          "completed ok");

                size_t size = 0;

                TRACFCOMP(g_trac_isteps_trace,
                          "Read IDEC from OCMB 0x%.8X",
                          get_huid(l_ocmb));

                // This write gets translated into a read of the explorer chip
                // in the device driver. First, a read of the chip's IDEC
                // register occurs then ATTR_EC, ATTR_HDAT_EC, and ATTR_CHIP_ID
                // are set with the values found in that register. So, this
                // deviceWrite functions more as a setter for an OCMB target's
                // attributes.
                // Pass 2 as a va_arg to signal the ocmbIDEC function to execute
                // phase 2 of its read process.
                const uint64_t Phase2 = 2;
                l_errl = DeviceFW::deviceWrite(l_ocmb,
                                   nullptr,
                                   size,
                                   DEVICE_IDEC_ADDRESS(),
                                   Phase2);
                if (l_errl)
                {
                    // read of ID/EC failed even though we THOUGHT we were
                    // present.
                    TRACFCOMP(g_trac_isteps_trace,
                              "ERROR : call_ocmb_check_for_ready HWP(): "
                              "read IDEC failed on target 0x%08X (eid 0x%X)."
                              TRACE_ERR_FMT,
                              get_huid(l_ocmb),
                              l_errl->eid(),
                              TRACE_ERR_ARGS(l_errl));

                    // Capture error and continue to next OCMB
                    captureError(l_errl, l_StepError, HWPF_COMP_ID, l_ocmb);
                }
            } // End of if/else l_errl

        } // End of OCMB Loop

        // Grab informational Explorer logs (early IPL = true)
        EXPSCOM::createExplorerLogs(l_functionalOcmbChipList, true);
    }

    // Loop thru the list of processors and send Memory config info to SBE
    for (auto &l_procTarget: functionalProcChipList)
    {
        l_errl = SBEIO::psuSendSbeMemConfig(l_procTarget);

        if (l_errl)
        {
            TRACFCOMP(g_trac_isteps_trace,
                      ERR_MRK"ERROR : call_ocmb_check_for_ready HWP(): "
                      "psuSendSbeMemConfig failed for target 0x%.08X."
                      TRACE_ERR_FMT,
                      get_huid(l_procTarget),
                      TRACE_ERR_ARGS(l_errl));

            // Commit the error and not fail this istep due to this failure
            errlCommit( l_errl, HWPF_COMP_ID );
        }
        else
        {
            TRACFCOMP(g_trac_isteps_trace,
                      INFO_MRK"SUCCESS : call_ocmb_check_for_ready HWP(): "
                      "psuSendSbeMemConfig completed ok for target 0x%.08X.",
                      get_huid(l_procTarget));
        }
    } // for (auto &l_procTarget: functionalProcChipList)

    TRACFCOMP(g_trac_isteps_trace, EXIT_MRK"call_ocmb_check_for_ready");
    return l_StepError.getErrorHandle();
}

};
<commit_msg>Poke watchdog during OCMB readiness poll<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/isteps/istep11/call_ocmb_check_for_ready.C $          */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2021                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
/**
 *  @file call_ocmb_check_for_ready.C
 *
 *  Support file for IStep: ocmb_check_for_ready
 *    Check that OCMB is ready
 *
 */

/******************************************************************************/
// Includes
/******************************************************************************/

//  Error handling support
#include <errl/errlentry.H>                     // errlHndl_t
#include <errl/errlmanager.H>
#include <errl/errludtarget.H>                  // ErrlUserDetailsTarget
#include <istepHelperFuncs.H>                   // captureError

//  FAPI support
#include <fapi2.H>
#include <plat_hwp_invoker.H>
#include <isteps/hwpisteperror.H>               // IStepError

//  Tracing support
#include <initservice/isteps_trace.H>           // g_trac_isteps_trace

//  Targeting support
#include <attributeenums.H>                     // TYPE_PROC
#include <targeting/common/utilFilter.H>        // getAllChips
#include <sbeio/sbeioif.H>
#include <util/misc.H>
#include <sys/time.h>
#include <time.h>

//  HWP call support
#include <exp_check_for_ready.H>

// Explorer error logs
#include <expscom/expscom_errlog.H>

// sendProgressCode
#include <initservice/istepdispatcherif.H>

using namespace ISTEPS_TRACE;
using namespace ISTEP_ERROR;
using namespace ERRORLOG;
using namespace TARGETING;

namespace ISTEP_11
{
void* call_ocmb_check_for_ready (void *io_pArgs)
{
    TRACFCOMP(g_trac_isteps_trace, ENTER_MRK"call_ocmb_check_for_ready");

    errlHndl_t  l_errl = nullptr;
    IStepError l_StepError;

    // We need to do an explicit delay before our first i2c operation
    //  to Explorer to ensure we don't catch it too early in the boot
    //  and lock it up.
    const auto ocmb_delay = UTIL::assertGetToplevelTarget()
      ->getAttr<ATTR_OCMB_RESET_DELAY_SEC>();
    nanosleep(ocmb_delay,0);

    TargetHandleList functionalProcChipList;

    getAllChips(functionalProcChipList, TYPE_PROC, true);

    // loop thru the list of processors
    for (TargetHandleList::const_iterator
            l_proc_iter = functionalProcChipList.begin();
            l_proc_iter != functionalProcChipList.end();
            ++l_proc_iter)
    {
        // For each loop on an OCMB below, multiply the timeout chunk
        size_t loop_multiplier = 1;

        // Keep track of overall time
        size_t l_maxTime_secs = 0;
        timespec_t l_preLoopTime = {};
        timespec_t l_ocmbCurrentTime = {};
        clock_gettime(CLOCK_MONOTONIC, &l_preLoopTime);

        TargetHandleList l_functionalOcmbChipList;
        getChildAffinityTargets( l_functionalOcmbChipList,
                                 const_cast<Target*>(*l_proc_iter),
                                 CLASS_CHIP,
                                 TYPE_OCMB_CHIP,
                                 true);

        for (const auto & l_ocmb : l_functionalOcmbChipList)
        {
            TRACFCOMP(g_trac_isteps_trace,
                        "Start : exp_check_for_ready "
                        "for 0x%.08X", get_huid(l_ocmb));

            fapi2::Target <fapi2::TARGET_TYPE_OCMB_CHIP>
                                    l_fapi_ocmb_target(l_ocmb);

            // Save the original timeout (to be restored after exp_check_for_ready)
            // Units for the attribute are milliseconds; the value returned is > 1 second
            const auto original_timeout_ms
                = l_ocmb->getAttr<ATTR_MSS_CHECK_FOR_READY_TIMEOUT>();

            // Calculate MAX Wait Time - Round up on seconds
            // - ATTR_MSS_CHECK_FOR_READY_TIMEOUT in msec (see exp_attributes.xml)
            // - This assumes that all of the OCMBs on a processor were started at the same time
            //   and that they all have the same original_timeout value
            // - The calculation is as follows:
            // 1) Start with the 'seconds' value of the pre-loop time
            // 2) Add *double* the 'seconds' amount of the original timeout value
            //    -- the *double* is just to be on the safe side, as we're only dealing with
            //       seconds and not minutes here
            // 3) Add 3 to round up for the nanoseconds of (1) and double the milliseconds of (2)
            if (l_maxTime_secs == 0)
            {
                // If not set yet, then set it here:
                l_maxTime_secs = l_preLoopTime.tv_sec
                                 + (2 * (original_timeout_ms / MS_PER_SEC))
                                 + 3;
            }

            // exp_check_for_ready will read this attribute to know how long to
            // poll. If this number is too large and we get too many I2C error
            // logs between calls to FAPI_INVOKE_HWP, we will run out of memory.
            // So break the original timeout into smaller timeouts.
            // This will not affect how the loop below will use l_maxTime_secs to look for a timouts
            const ATTR_MSS_CHECK_FOR_READY_TIMEOUT_type smaller_timeout_ms = 10 * loop_multiplier++;
            l_ocmb->setAttr<ATTR_MSS_CHECK_FOR_READY_TIMEOUT>(smaller_timeout_ms);

            TRACFCOMP(g_trac_isteps_trace,"exp_check_for_ready: For OCMB 0x%X: "
                      "original_timeout_ms = %d, smaller_timeout_ms = %d, "
                      "l_preLoopTime.tv_sec = %lu l_maxTime_secs = %lu",
                      get_huid(l_ocmb), original_timeout_ms, smaller_timeout_ms,
                      l_preLoopTime.tv_sec, l_maxTime_secs);

            // Variable used to track attempting one more time after max time has
            // been succeeded
            bool l_one_more_try = false;

            // Retry exp_check_for_ready as many times as it takes to either
            // succeed or time out
            while (true)
            {
                // Each attempt can take a few minutes so poke the
                //  watchdog before each attempt
                INITSERVICE::sendProgressCode();

                // Delete the log from the previous iteration
                if( l_errl )
                {
                    delete l_errl;
                    l_errl = nullptr;
                }

                FAPI_INVOKE_HWP(l_errl,
                                exp_check_for_ready,
                                l_fapi_ocmb_target);

                // On success, quit retrying.
                if (!l_errl)
                {
                    break;
                }

                clock_gettime(CLOCK_MONOTONIC, &l_ocmbCurrentTime);
                if (l_ocmbCurrentTime.tv_sec > l_maxTime_secs)
                {
                    if (l_one_more_try == false)
                    {
                        // Do one more attempt just to be safe
                        l_one_more_try = true;
                        TRACFCOMP(g_trac_isteps_trace,"exp_check_for_ready "
                                  "Setting 'one more try' (%d) based on times: "
                                  "l_ocmbCurrentTime.tv_sec = %lu, l_maxTime_secs = %lu",
                                  l_one_more_try, l_ocmbCurrentTime.tv_sec, l_maxTime_secs);

                    }
                    else
                    {
                        // Already done "one more try" so just break
                        TRACFCOMP(g_trac_isteps_trace,"exp_check_for_ready "
                                  "Breaking as 'one more try' (%d) was already set. "
                                  "l_ocmbCurrentTime.tv_sec = %lu, l_maxTime_secs = %lu",
                                  l_one_more_try, l_ocmbCurrentTime.tv_sec, l_maxTime_secs);
                        break;
                    }
                }

            } // end of timeout loop

            // Restore original timeout value
            l_ocmb->setAttr<ATTR_MSS_CHECK_FOR_READY_TIMEOUT>(original_timeout_ms);

            if (l_errl)
            {
                TRACFCOMP(g_trac_isteps_trace,
                          "ERROR : call_ocmb_check_for_ready HWP(): "
                          "exp_check_for_ready failed on target 0x%08X."
                          TRACE_ERR_FMT,
                          get_huid(l_ocmb),
                          TRACE_ERR_ARGS(l_errl));

                // Capture error and continue to next OCMB
                captureError(l_errl, l_StepError, HWPF_COMP_ID, l_ocmb);
            }
            else
            {
                TRACFCOMP(g_trac_isteps_trace,
                          "SUCCESS : exp_check_for_ready "
                          "completed ok");

                size_t size = 0;

                TRACFCOMP(g_trac_isteps_trace,
                          "Read IDEC from OCMB 0x%.8X",
                          get_huid(l_ocmb));

                // This write gets translated into a read of the explorer chip
                // in the device driver. First, a read of the chip's IDEC
                // register occurs then ATTR_EC, ATTR_HDAT_EC, and ATTR_CHIP_ID
                // are set with the values found in that register. So, this
                // deviceWrite functions more as a setter for an OCMB target's
                // attributes.
                // Pass 2 as a va_arg to signal the ocmbIDEC function to execute
                // phase 2 of its read process.
                const uint64_t Phase2 = 2;
                l_errl = DeviceFW::deviceWrite(l_ocmb,
                                   nullptr,
                                   size,
                                   DEVICE_IDEC_ADDRESS(),
                                   Phase2);
                if (l_errl)
                {
                    // read of ID/EC failed even though we THOUGHT we were
                    // present.
                    TRACFCOMP(g_trac_isteps_trace,
                              "ERROR : call_ocmb_check_for_ready HWP(): "
                              "read IDEC failed on target 0x%08X (eid 0x%X)."
                              TRACE_ERR_FMT,
                              get_huid(l_ocmb),
                              l_errl->eid(),
                              TRACE_ERR_ARGS(l_errl));

                    // Capture error and continue to next OCMB
                    captureError(l_errl, l_StepError, HWPF_COMP_ID, l_ocmb);
                }
            } // End of if/else l_errl

        } // End of OCMB Loop

        // Grab informational Explorer logs (early IPL = true)
        EXPSCOM::createExplorerLogs(l_functionalOcmbChipList, true);
    }

    // Loop thru the list of processors and send Memory config info to SBE
    for (auto &l_procTarget: functionalProcChipList)
    {
        l_errl = SBEIO::psuSendSbeMemConfig(l_procTarget);

        if (l_errl)
        {
            TRACFCOMP(g_trac_isteps_trace,
                      ERR_MRK"ERROR : call_ocmb_check_for_ready HWP(): "
                      "psuSendSbeMemConfig failed for target 0x%.08X."
                      TRACE_ERR_FMT,
                      get_huid(l_procTarget),
                      TRACE_ERR_ARGS(l_errl));

            // Commit the error and not fail this istep due to this failure
            errlCommit( l_errl, HWPF_COMP_ID );
        }
        else
        {
            TRACFCOMP(g_trac_isteps_trace,
                      INFO_MRK"SUCCESS : call_ocmb_check_for_ready HWP(): "
                      "psuSendSbeMemConfig completed ok for target 0x%.08X.",
                      get_huid(l_procTarget));
        }
    } // for (auto &l_procTarget: functionalProcChipList)

    TRACFCOMP(g_trac_isteps_trace, EXIT_MRK"call_ocmb_check_for_ready");
    return l_StepError.getErrorHandle();
}

};
<|endoftext|>


<commit_before>/**************************************************************************
 *
 * Copyright 2013-2014 RAD Game Tools and Valve Software
 * All Rights Reserved.
 *
 * 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.
 *
 **************************************************************************/

#include "vogleditor_apicalltimelinemodel.h"
#include "vogleditor_timelineitem.h"
#include "vogleditor_qapicalltreemodel.h"
#include "vogleditor_apicalltreeitem.h"
#include "vogleditor_groupitem.h"
#include "vogleditor_frameitem.h"

vogleditor_apiCallTimelineModel::vogleditor_apiCallTimelineModel(vogleditor_apiCallTreeItem *pRootApiCall)
    : m_pRootApiCall(pRootApiCall),
      m_rawBaseTime(0)
{
    refresh();
}

void vogleditor_apiCallTimelineModel::refresh()
{
    if (m_pRootApiCall == NULL)
    {
        return;
    }

    float timelineStart = 0;
    float timelineEnd = 1;
    m_rawBaseTime = timelineStart;

    int numChildren = m_pRootApiCall->childCount();
    if (numChildren > 0)
    {
        uint64_t firstStart = 0;
        uint64_t firstEnd = 0;
        m_pRootApiCall->child(0)->frameItem()->getStartEndTimes(firstStart, firstEnd);

        uint64_t lastStart = 0;
        uint64_t lastEnd = 0;
        vogleditor_apiCallTreeItem *pLastChild = m_pRootApiCall->child(numChildren - 1);
        pLastChild->frameItem()->getStartEndTimes(lastStart, lastEnd);

        m_rawBaseTime = firstStart;
        timelineStart = u64ToFloat(firstStart - m_rawBaseTime);
        timelineEnd = u64ToFloat(lastEnd - m_rawBaseTime);
    }

    // see if we actually have to update some of this stuff
    bool skipCreation = false;
    if (m_rootItem != NULL)
    {
        if (m_rootItem->getDuration() == timelineEnd - timelineStart &&
            m_rootItem->childCount() == numChildren)
        {
            // no need to make a new root
            skipCreation = true;
        }
    }

    if (!skipCreation)
    {
        if (m_rootItem != NULL)
        {
            delete m_rootItem;
        }

        m_rootItem = new vogleditor_timelineItem(timelineStart, timelineEnd);

        // add markers for the start of each frame
        float frameStart = 0;
        for (int c = 0; c < numChildren; c++)
        {
            vogleditor_apiCallTreeItem *pFrameItem = m_pRootApiCall->child(c);
            if (pFrameItem->childCount() > 0)
            {
                frameStart = u64ToFloat(pFrameItem->startTime() - m_rawBaseTime);
                vogleditor_timelineItem *pFrameTimelineItem = new vogleditor_timelineItem(frameStart, m_rootItem);
                pFrameTimelineItem->setFrameItem(pFrameItem->frameItem());
                m_rootItem->appendChild(pFrameTimelineItem);
            }
            else
            {
                // if we get here, we are at a frame that had no api calls
            }
        }

        // recursively add children
        for (int frameIndex = 0; frameIndex < numChildren; frameIndex++)
        {
            vogleditor_apiCallTreeItem *pFrameChild = m_pRootApiCall->child(frameIndex);

            AddApiCallsToTimeline(pFrameChild, m_rootItem);
        }
    }
}

float vogleditor_apiCallTimelineModel::u64ToFloat(uint64_t value)
{
    // taken from: http://stackoverflow.com/questions/4400747/converting-from-unsigned-long-long-to-float-with-round-to-nearest-even
    const int mask_bit_count = 31;

    // How many bits are needed?
    int b = sizeof(uint64_t) * CHAR_BIT - 1;
    for (; b >= 0; --b)
    {
        if (value & (1ull << b))
        {
            break;
        }
    }

    // If there are few enough significant bits, use normal cast and done.
    if (b < mask_bit_count)
    {
        return static_cast<float>(value & ~1ull);
    }

    // Save off the low-order useless bits:
    uint64_t low_bits = value & ((1ull << (b - mask_bit_count)) - 1);

    // Now mask away those useless low bits:
    value &= ~((1ull << (b - mask_bit_count)) - 1);

    // Finally, decide how to round the new LSB:
    if (low_bits > ((1ull << (b - mask_bit_count)) / 2ull))
    {
        // Round up.
        value |= (1ull << (b - mask_bit_count));
    }
    else
    {
        // Round down.
        value &= ~(1ull << (b - mask_bit_count));
    }

    return static_cast<float>(value);
}

void vogleditor_apiCallTimelineModel::AddApiCallsToTimeline(vogleditor_apiCallTreeItem *pRoot, vogleditor_timelineItem *pDestRoot)
{
    int numChildren = pRoot->childCount();
    for (int c = 0; c < numChildren; c++)
    {
        vogleditor_apiCallTreeItem *pChild = pRoot->child(c);

        if (pChild->isGroup())
        {
            AddApiCallsToTimeline(pChild, pDestRoot);
        }
        else if (pChild->isApiCall())
        {
            float beginFloat = u64ToFloat(pChild->startTime() - m_rawBaseTime);
            float endFloat = u64ToFloat(pChild->endTime() - m_rawBaseTime);

            vogleditor_timelineItem *pNewItem = new vogleditor_timelineItem(beginFloat, endFloat, pDestRoot);
            pNewItem->setApiCallItem(pChild->apiCallItem());
            pDestRoot->appendChild(pNewItem);
            AddApiCallsToTimeline(pChild, pNewItem);
        }
    }
}
<commit_msg>UI: rename some local variables<commit_after>/**************************************************************************
 *
 * Copyright 2013-2014 RAD Game Tools and Valve Software
 * All Rights Reserved.
 *
 * 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.
 *
 **************************************************************************/

#include "vogleditor_apicalltimelinemodel.h"
#include "vogleditor_timelineitem.h"
#include "vogleditor_qapicalltreemodel.h"
#include "vogleditor_apicalltreeitem.h"
#include "vogleditor_groupitem.h"
#include "vogleditor_frameitem.h"

vogleditor_apiCallTimelineModel::vogleditor_apiCallTimelineModel(vogleditor_apiCallTreeItem *pRootApiCall)
    : m_pRootApiCall(pRootApiCall),
      m_rawBaseTime(0)
{
    refresh();
}

void vogleditor_apiCallTimelineModel::refresh()
{
    if (m_pRootApiCall == NULL)
    {
        return;
    }

    float timelineStart = 0;
    float timelineEnd = 1;
    m_rawBaseTime = timelineStart;

    int numChildren = m_pRootApiCall->childCount();
    if (numChildren > 0)
    {
        uint64_t firstStart = 0;
        uint64_t firstEnd = 0;
        m_pRootApiCall->child(0)->frameItem()->getStartEndTimes(firstStart, firstEnd);

        uint64_t lastStart = 0;
        uint64_t lastEnd = 0;
        vogleditor_apiCallTreeItem *pLastChild = m_pRootApiCall->child(numChildren - 1);
        pLastChild->frameItem()->getStartEndTimes(lastStart, lastEnd);

        m_rawBaseTime = firstStart;
        timelineStart = u64ToFloat(firstStart - m_rawBaseTime);
        timelineEnd = u64ToFloat(lastEnd - m_rawBaseTime);
    }

    // see if we actually have to update some of this stuff
    bool skipCreation = false;
    if (m_rootItem != NULL)
    {
        if (m_rootItem->getDuration() == timelineEnd - timelineStart &&
            m_rootItem->childCount() == numChildren)
        {
            // no need to make a new root
            skipCreation = true;
        }
    }

    if (!skipCreation)
    {
        if (m_rootItem != NULL)
        {
            delete m_rootItem;
        }

        m_rootItem = new vogleditor_timelineItem(timelineStart, timelineEnd);

        // add markers for the start of each frame
        float frameStart = 0;
        for (int c = 0; c < numChildren; c++)
        {
            vogleditor_apiCallTreeItem *pFrameItem = m_pRootApiCall->child(c);
            if (pFrameItem->childCount() > 0)
            {
                frameStart = u64ToFloat(pFrameItem->startTime() - m_rawBaseTime);
                vogleditor_timelineItem *pFrameTimelineItem = new vogleditor_timelineItem(frameStart, m_rootItem);
                pFrameTimelineItem->setFrameItem(pFrameItem->frameItem());
                m_rootItem->appendChild(pFrameTimelineItem);
            }
            else
            {
                // if we get here, we are at a frame that had no api calls
            }
        }

        // recursively add children
        for (int frameIndex = 0; frameIndex < numChildren; frameIndex++)
        {
            vogleditor_apiCallTreeItem *pFrameChild = m_pRootApiCall->child(frameIndex);

            AddApiCallsToTimeline(pFrameChild, m_rootItem);
        }
    }
}

float vogleditor_apiCallTimelineModel::u64ToFloat(uint64_t value)
{
    // taken from: http://stackoverflow.com/questions/4400747/converting-from-unsigned-long-long-to-float-with-round-to-nearest-even
    const int mask_bit_count = 31;

    // How many bits are needed?
    int b = sizeof(uint64_t) * CHAR_BIT - 1;
    for (; b >= 0; --b)
    {
        if (value & (1ull << b))
        {
            break;
        }
    }

    // If there are few enough significant bits, use normal cast and done.
    if (b < mask_bit_count)
    {
        return static_cast<float>(value & ~1ull);
    }

    // Save off the low-order useless bits:
    uint64_t low_bits = value & ((1ull << (b - mask_bit_count)) - 1);

    // Now mask away those useless low bits:
    value &= ~((1ull << (b - mask_bit_count)) - 1);

    // Finally, decide how to round the new LSB:
    if (low_bits > ((1ull << (b - mask_bit_count)) / 2ull))
    {
        // Round up.
        value |= (1ull << (b - mask_bit_count));
    }
    else
    {
        // Round down.
        value &= ~(1ull << (b - mask_bit_count));
    }

    return static_cast<float>(value);
}

void vogleditor_apiCallTimelineModel::AddApiCallsToTimeline(vogleditor_apiCallTreeItem *pParentCallTreeItem, vogleditor_timelineItem *pParentTimelineItem)
{
    int numChildren = pParentCallTreeItem->childCount();
    for (int c = 0; c < numChildren; c++)
    {
        vogleditor_apiCallTreeItem *pChildCallTreeItem = pParentCallTreeItem->child(c);

        if (pChildCallTreeItem->isGroup())
        {
            AddApiCallsToTimeline(pChildCallTreeItem, pParentTimelineItem);
        }
        else if (pChildCallTreeItem->isApiCall())
        {
            float beginFloat = u64ToFloat(pChildCallTreeItem->startTime() - m_rawBaseTime);
            float endFloat = u64ToFloat(pChildCallTreeItem->endTime() - m_rawBaseTime);

            vogleditor_timelineItem *pNewTimelineItem = new vogleditor_timelineItem(beginFloat, endFloat, pParentTimelineItem);
            pNewTimelineItem->setApiCallItem(pChildCallTreeItem->apiCallItem());
            pParentTimelineItem->appendChild(pNewTimelineItem);
            AddApiCallsToTimeline(pChildCallTreeItem, pNewTimelineItem);
        }
    }
}
<|endoftext|>


<commit_before>//
// This file is part of khmer, http://github.com/ged-lab/khmer/, and is
// Copyright (C) Michigan State University, 2009-2013. It is licensed under
// the three-clause BSD license; see doc/LICENSE.txt.
// Contact: khmer-project@idyll.org
//

#include <math.h>
#include <string>
#include <iostream>
#include <algorithm>

#include "khmer.hh"
#include "kmer_hash.hh"
#include "MurmurHash3.h"
#include "sha1.h"

using namespace std;

//
// _hash: hash a k-length DNA sequence into a 64-bit number.
//

namespace khmer
{

HashIntoType _hash(const char * kmer, const WordLength k,
                   HashIntoType& _h, HashIntoType& _r)
{
    // sizeof(HashIntoType) * 8 bits / 2 bits/base
    if (!(k <= sizeof(HashIntoType)*4) || !(strlen(kmer) >= k)) {
        throw khmer_exception("Supplied kmer string doesn't match the underlying k-size.");
    }

    HashIntoType h = 0, r = 0;

    h |= twobit_repr(kmer[0]);
    r |= twobit_comp(kmer[k-1]);

    for (WordLength i = 1, j = k - 2; i < k; i++, j--) {
        h = h << 2;
        r = r << 2;

        h |= twobit_repr(kmer[i]);
        r |= twobit_comp(kmer[j]);
    }

    _h = h;
    _r = r;

    return uniqify_rc(h, r);
}

// _hash: return the maximum of the forward and reverse hash.

HashIntoType _hash(const char * kmer, const WordLength k)
{
    HashIntoType h = 0;
    HashIntoType r = 0;

    return khmer::_hash(kmer, k, h, r);
}

// _hash_forward: return the hash from the forward direction only.

HashIntoType _hash_forward(const char * kmer, WordLength k)
{
    HashIntoType h = 0;
    HashIntoType r = 0;

    khmer::_hash(kmer, k, h, r);
    return h;			// return forward only
}

//
// _revhash: given an unsigned int, return the associated k-mer.
//

std::string _revhash(HashIntoType hash, WordLength k)
{
    std::string s = "";

    unsigned int val = hash & 3;
    s += revtwobit_repr(val);

    for (WordLength i = 1; i < k; i++) {
        hash = hash >> 2;
        val = hash & 3;
        s += revtwobit_repr(val);
    }

    reverse(s.begin(), s.end());

    return s;
}

std::string _revcomp(const std::string kmer)
{
    std::string out = kmer;
    int ksize = out.size();

    for (int i=0; i < ksize; ++i) {
      char complement;

      switch(kmer[i]) {
        case 'A':
          complement = 'T';
          break;
        case 'C':
          complement = 'G';
          break;
        case 'G':
          complement = 'C';
          break;
        case 'T':
          complement = 'A';
          break;
        default:
          complement = kmer[i];
          break;
      }
      out[ksize - i - 1] = complement;
    }
    return out;
}

HashIntoType _hash_murmur(const std::string kmer)
{
    HashIntoType h = 0;
    HashIntoType r = 0;

    return khmer::_hash_murmur(kmer, h, r);
}

HashIntoType _hash_murmur(const std::string kmer,
                          HashIntoType& h, HashIntoType& r)
{
    HashIntoType out[2];
    uint32_t seed = 0;

    khmer::_hash(kmer.c_str(), kmer.size(), h, r);

    MurmurHash3_x64_128(&h, sizeof(h), seed, &out);
    h = out[0];

    MurmurHash3_x64_128(&r, sizeof(r), seed, &out);
    r = out[0];

    return h ^ r;
}

HashIntoType _hash_murmur_forward(const std::string kmer)
{
    HashIntoType h = 0;
    HashIntoType r = 0;

    khmer::_hash_murmur(kmer, h, r);
    return h;
}

HashIntoType _hash_sha1(const std::string kmer)
{
    HashIntoType h = 0;
    HashIntoType r = 0;

    return khmer::_hash_sha1(kmer, h, r);
}

HashIntoType _hash_sha1(const std::string kmer,
                        HashIntoType& h, HashIntoType& r)
{
    HashIntoType buf;
    SHA1_CTX context;
    uint8_t digest[20];
    h = 0;
    r = 0;

    SHA1_Init(&context);
    SHA1_Update(&context, (uint8_t*)kmer.c_str(), kmer.size());
    SHA1_Final(&context, digest);
    for (int i=0; i < 8; i++) {
      buf = digest[i];
      h |= buf << ((7 - i) * 8);
    }

    std::string rev = khmer::_revcomp(kmer);

    SHA1_Init(&context);
    SHA1_Update(&context, (uint8_t*)rev.c_str(), rev.size());
    SHA1_Final(&context, digest);
    for (int i=0; i < 8; i++) {
      buf = digest[i];
      r |= buf << ((7 - i) * 8);
    }

    return h ^ r;
}

HashIntoType _hash_sha1_forward(const std::string kmer)
{
    HashIntoType h = 0;
    HashIntoType r = 0;

    khmer::_hash_sha1(kmer, h, r);
    return h;
}

};
<commit_msg>Revert "Trying 2-bit representation before hashing".<commit_after>//
// This file is part of khmer, http://github.com/ged-lab/khmer/, and is
// Copyright (C) Michigan State University, 2009-2013. It is licensed under
// the three-clause BSD license; see doc/LICENSE.txt.
// Contact: khmer-project@idyll.org
//

#include <math.h>
#include <string>
#include <iostream>
#include <algorithm>

#include "khmer.hh"
#include "kmer_hash.hh"
#include "MurmurHash3.h"
#include "sha1.h"

using namespace std;

//
// _hash: hash a k-length DNA sequence into a 64-bit number.
//

namespace khmer
{

HashIntoType _hash(const char * kmer, const WordLength k,
                   HashIntoType& _h, HashIntoType& _r)
{
    // sizeof(HashIntoType) * 8 bits / 2 bits/base
    if (!(k <= sizeof(HashIntoType)*4) || !(strlen(kmer) >= k)) {
        throw khmer_exception("Supplied kmer string doesn't match the underlying k-size.");
    }

    HashIntoType h = 0, r = 0;

    h |= twobit_repr(kmer[0]);
    r |= twobit_comp(kmer[k-1]);

    for (WordLength i = 1, j = k - 2; i < k; i++, j--) {
        h = h << 2;
        r = r << 2;

        h |= twobit_repr(kmer[i]);
        r |= twobit_comp(kmer[j]);
    }

    _h = h;
    _r = r;

    return uniqify_rc(h, r);
}

// _hash: return the maximum of the forward and reverse hash.

HashIntoType _hash(const char * kmer, const WordLength k)
{
    HashIntoType h = 0;
    HashIntoType r = 0;

    return khmer::_hash(kmer, k, h, r);
}

// _hash_forward: return the hash from the forward direction only.

HashIntoType _hash_forward(const char * kmer, WordLength k)
{
    HashIntoType h = 0;
    HashIntoType r = 0;

    khmer::_hash(kmer, k, h, r);
    return h;			// return forward only
}

//
// _revhash: given an unsigned int, return the associated k-mer.
//

std::string _revhash(HashIntoType hash, WordLength k)
{
    std::string s = "";

    unsigned int val = hash & 3;
    s += revtwobit_repr(val);

    for (WordLength i = 1; i < k; i++) {
        hash = hash >> 2;
        val = hash & 3;
        s += revtwobit_repr(val);
    }

    reverse(s.begin(), s.end());

    return s;
}

std::string _revcomp(const std::string kmer)
{
    std::string out = kmer;
    int ksize = out.size();

    for (int i=0; i < ksize; ++i) {
      char complement;

      switch(kmer[i]) {
        case 'A':
          complement = 'T';
          break;
        case 'C':
          complement = 'G';
          break;
        case 'G':
          complement = 'C';
          break;
        case 'T':
          complement = 'A';
          break;
        default:
          complement = kmer[i];
          break;
      }
      out[ksize - i - 1] = complement;
    }
    return out;
}

HashIntoType _hash_murmur(const std::string kmer)
{
    HashIntoType h = 0;
    HashIntoType r = 0;

    return khmer::_hash_murmur(kmer, h, r);
}

HashIntoType _hash_murmur(const std::string kmer,
                          HashIntoType& h, HashIntoType& r)
{
    HashIntoType out[2];
    uint32_t seed = 0;
    MurmurHash3_x64_128((void *)kmer.c_str(), kmer.size(), seed, &out);
    h = out[0];

    std::string rev = khmer::_revcomp(kmer);
    MurmurHash3_x64_128((void *)rev.c_str(), rev.size(), seed, &out);
    r = out[0];

    return h ^ r;
}

HashIntoType _hash_murmur_forward(const std::string kmer)
{
    HashIntoType h = 0;
    HashIntoType r = 0;

    khmer::_hash_murmur(kmer, h, r);
    return h;
}

HashIntoType _hash_sha1(const std::string kmer)
{
    HashIntoType h = 0;
    HashIntoType r = 0;

    return khmer::_hash_sha1(kmer, h, r);
}

HashIntoType _hash_sha1(const std::string kmer,
                        HashIntoType& h, HashIntoType& r)
{
    HashIntoType buf;
    SHA1_CTX context;
    uint8_t digest[20];
    h = 0;
    r = 0;

    SHA1_Init(&context);
    SHA1_Update(&context, (uint8_t*)kmer.c_str(), kmer.size());
    SHA1_Final(&context, digest);
    for (int i=0; i < 8; i++) {
      buf = digest[i];
      h |= buf << ((7 - i) * 8);
    }

    std::string rev = khmer::_revcomp(kmer);

    SHA1_Init(&context);
    SHA1_Update(&context, (uint8_t*)rev.c_str(), rev.size());
    SHA1_Final(&context, digest);
    for (int i=0; i < 8; i++) {
      buf = digest[i];
      r |= buf << ((7 - i) * 8);
    }

    return h ^ r;
}

HashIntoType _hash_sha1_forward(const std::string kmer)
{
    HashIntoType h = 0;
    HashIntoType r = 0;

    khmer::_hash_sha1(kmer, h, r);
    return h;
}

};
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: textrun.hxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef OOX_DRAWINGML_TEXTRUN_HXX
#define OOX_DRAWINGML_TEXTRUN_HXX

#include <com/sun/star/text/XTextCursor.hpp>
#include <com/sun/star/text/XText.hpp>
#include <com/sun/star/frame/XModel.hpp>

#include "oox/drawingml/textcharacterproperties.hxx"

namespace oox { namespace drawingml {

class TextRun
{
public:

    TextRun();
    virtual ~TextRun();

    TextCharacterPropertiesPtr  getTextCharacterProperties(){ return maTextCharacterPropertiesPtr; };
    ::rtl::OUString & getText() { return msText; }
    const ::rtl::OUString & getText() const { return msText; }

    virtual void                insertAt(
                                    const ::oox::core::XmlFilterBase& rFilterBase,
                                    const ::com::sun::star::uno::Reference < ::com::sun::star::text::XText > & xText,
                                    const ::com::sun::star::uno::Reference < ::com::sun::star::text::XTextCursor > &xAt,
                                    const TextCharacterPropertiesPtr& );

    void                        setLineBreak() { mbIsLineBreak = true; }
protected:
    bool                        mbIsLineBreak;
    TextCharacterPropertiesPtr  maTextCharacterPropertiesPtr;
    ::rtl::OUString             msText;
};

typedef boost::shared_ptr< TextRun > TextRunPtr;

} }

#endif  //  OOX_DRAWINGML_TEXTRUN_HXX
<commit_msg>INTEGRATION: CWS xmlfilter06 (1.5.6); FILE MERGED 2008/06/20 11:58:14 dr 1.5.6.2: line/fill/character properties rework; first steps of chart text formatting and rotation import; make line arrow import work 2008/05/27 10:40:27 dr 1.5.6.1: joined changes from CWS xmlfilter05<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: textrun.hxx,v $
 * $Revision: 1.6 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef OOX_DRAWINGML_TEXTRUN_HXX
#define OOX_DRAWINGML_TEXTRUN_HXX

#include <com/sun/star/text/XTextCursor.hpp>
#include <com/sun/star/text/XText.hpp>
#include <com/sun/star/frame/XModel.hpp>
#include "oox/drawingml/textcharacterproperties.hxx"

namespace oox { namespace drawingml {

class TextRun
{
public:
    TextRun();
    virtual ~TextRun();

    inline ::rtl::OUString&         getText() { return msText; }
    inline const ::rtl::OUString&   getText() const { return msText; }

    inline TextCharacterProperties&         getTextCharacterProperties() { return maTextCharacterProperties; }
    inline const TextCharacterProperties&   getTextCharacterProperties() const { return maTextCharacterProperties; }

    inline void                 setLineBreak() { mbIsLineBreak = true; }

    virtual void                insertAt(
                                    const ::oox::core::XmlFilterBase& rFilterBase,
                                    const ::com::sun::star::uno::Reference < ::com::sun::star::text::XText >& xText,
                                    const ::com::sun::star::uno::Reference < ::com::sun::star::text::XTextCursor >& xAt,
                                    const TextCharacterProperties& rTextCharacterStyle ) const;

private:
    ::rtl::OUString             msText;
    TextCharacterProperties     maTextCharacterProperties;
    bool                        mbIsLineBreak;
};

typedef boost::shared_ptr< TextRun > TextRunPtr;

} }

#endif  //  OOX_DRAWINGML_TEXTRUN_HXX
<|endoftext|>