text stringlengths 54 60.6k |
|---|
<commit_before>#include "linalg/ray.h"
#include "geometry/differential_geometry.h"
#include "geometry/geometry.h"
#include "scene.h"
#include "integrator/surface_integrator.h"
#include "renderer/renderer.h"
Renderer::Renderer(std::unique_ptr<SurfaceIntegrator> surface_integrator)
: surface_integrator(std::move(surface_integrator))
{}
Colorf Renderer::illumination(RayDifferential &ray, const Scene &scene, Sampler &sampler, MemoryPool &pool) const {
DifferentialGeometry dg;
if (scene.get_root().intersect(ray, dg)){
std::cout << "Node pointed @ " << reinterpret_cast<uint64_t>(dg.node)
<< ", dg is at " << reinterpret_cast<uint64_t>(&dg) << std::endl;
return surface_integrator->illumination(scene, *this, ray, dg, sampler, pool);
}
else if (scene.get_environment()){
//TODO: Compute light along the ray coming from lights
DifferentialGeometry dg;
dg.point = Point{ray.d.x, ray.d.y, ray.d.z};
return scene.get_environment()->sample(dg);
}
return Colorf{0};
}
<commit_msg>Remove debug printing from renderer<commit_after>#include "linalg/ray.h"
#include "geometry/differential_geometry.h"
#include "geometry/geometry.h"
#include "scene.h"
#include "integrator/surface_integrator.h"
#include "renderer/renderer.h"
Renderer::Renderer(std::unique_ptr<SurfaceIntegrator> surface_integrator)
: surface_integrator(std::move(surface_integrator))
{}
Colorf Renderer::illumination(RayDifferential &ray, const Scene &scene, Sampler &sampler, MemoryPool &pool) const {
DifferentialGeometry dg;
if (scene.get_root().intersect(ray, dg)){
return surface_integrator->illumination(scene, *this, ray, dg, sampler, pool);
}
else if (scene.get_environment()){
//TODO: Compute light along the ray coming from lights
DifferentialGeometry dg;
dg.point = Point{ray.d.x, ray.d.y, ray.d.z};
return scene.get_environment()->sample(dg);
}
return Colorf{0};
}
<|endoftext|> |
<commit_before>
#include "elastic/Renderer/renderer.h"
#include "floats/transform.h"
#include "nucleus/Streams/array_input_stream.h"
namespace el {
namespace {
const char* kQuadVertexShaderSource = R"source(
#version 330
layout(location = 0) in vec2 inPosition;
layout(location = 1) in vec2 inTexCoords;
out vec2 texCoords;
uniform mat4 uTransform;
uniform mat4 uTexCoordsTransform;
void main() {
texCoords = (uTexCoordsTransform * vec4(inTexCoords, 0.0, 1.0)).xy;
gl_Position = uTransform * vec4(inPosition, 0.0, 1.0);
}
)source";
const char* kQuadColorFragmentShaderSource = R"source(
#version 330
uniform vec4 uColor;
out vec4 final;
void main() {
final = uColor;
}
)source";
const char* kQuadTextureFragmentShaderSource = R"source(
#version 330
in vec2 texCoords;
out vec4 final;
uniform sampler2D uTexture;
void main() {
final = texture(uTexture, texCoords);
}
)source";
const char* kQuadFontFragmentShaderSource = R"source(
#version 330
in vec2 texCoords;
out vec4 final;
uniform sampler2D uTexture;
void main() {
float alpha = texture(uTexture, texCoords).r;
final = vec4(1.0f, 1.0f, 1.0f, alpha);
}
)source";
ca::ProgramId createProgram(ca::Renderer* renderer, nu::StringView vertexShaderSource,
nu::StringView fragmentShaderSource) {
nu::ArrayInputStream vertexStream{nu::ArrayView<U8>{
reinterpret_cast<const U8*>(vertexShaderSource.data()), vertexShaderSource.length()}};
auto vss = ca::ShaderSource::from(&vertexStream);
nu::ArrayInputStream fragmentStream{nu::ArrayView<U8>{
reinterpret_cast<const U8*>(fragmentShaderSource.data()), fragmentShaderSource.length()}};
auto fss = ca::ShaderSource::from(&fragmentStream);
return renderer->createProgram(vss, fss);
}
struct QuadVertex {
fl::Vec2 position;
fl::Vec2 texCoords;
} kQuadVertices[] = {
{{0.0f, 0.0f}, {0.0f, 0.0f}}, //
{{0.0f, 1.0f}, {0.0f, 1.0f}}, //
{{1.0f, 1.0f}, {1.0f, 1.0f}}, //
{{1.0f, 0.0f}, {1.0f, 0.0f}}, //
};
U8 kQuadIndices[] = {
0, 1, 2, //
2, 3, 0, //
};
} // namespace
Renderer::Renderer() = default;
Renderer::~Renderer() = default;
bool Renderer::initialize(ca::Renderer* renderer) {
m_renderer = renderer;
m_size = renderer->getSize();
m_quadColorProgramId =
createProgram(renderer, kQuadVertexShaderSource, kQuadColorFragmentShaderSource);
if (!isValid(m_quadColorProgramId)) {
LOG(Error) << "Could not create quad color shader program.";
return false;
}
m_quadTextureProgramId =
createProgram(renderer, kQuadVertexShaderSource, kQuadTextureFragmentShaderSource);
if (!isValid(m_quadTextureProgramId)) {
LOG(Error) << "Could not create quad texture shader program.";
return false;
}
m_quadFontProgramId =
createProgram(renderer, kQuadVertexShaderSource, kQuadFontFragmentShaderSource);
if (!isValid(m_quadTextureProgramId)) {
LOG(Error) << "Could not create quad FONT shader program.";
return false;
}
ca::VertexDefinition definition;
definition.addAttribute(ca::ComponentType::Float32, ca::ComponentCount::Two);
definition.addAttribute(ca::ComponentType::Float32, ca::ComponentCount::Two);
m_quadVertexBufferId =
renderer->createVertexBuffer(definition, kQuadVertices, sizeof(kQuadVertices));
if (!isValid(m_quadVertexBufferId)) {
LOG(Error) << "Could not create quad vertex buffer.";
return false;
}
m_quadIndexBufferId =
renderer->createIndexBuffer(ca::ComponentType::Unsigned8, kQuadIndices, sizeof(kQuadIndices));
if (!isValid(m_quadIndexBufferId)) {
LOG(Error) << "Could not create quad index buffer.";
return false;
}
m_quadTransformUniformId = renderer->createUniform("uTransform");
if (!isValid(m_quadTransformUniformId)) {
LOG(Error) << "Could not create quad transform uniform.";
return false;
}
m_quadTexCoordsTransformUniformId = renderer->createUniform("uTexCoordsTransform");
if (!isValid(m_quadTexCoordsTransformUniformId)) {
LOG(Error) << "Could not create quad tex coords transform uniform.";
return false;
}
m_quadColorUniformId = renderer->createUniform("uColor");
if (!isValid(m_quadColorUniformId)) {
LOG(Error) << "Could not create quad color uniform.";
return false;
}
m_projectionMatrix = fl::orthographicProjection(0.0f, static_cast<F32>(m_size.width), 0.0f,
static_cast<F32>(m_size.height), -1.0f, 1.0f);
return true;
}
void Renderer::resize(const fl::Size& size) {
m_size = size;
m_projectionMatrix = fl::orthographicProjection(0.0f, static_cast<F32>(m_size.width), 0.0f,
static_cast<F32>(m_size.height), -1.0f, 1.0f);
}
void Renderer::renderQuad(const fl::Rect& rect, const ca::Color& color) {
#if BUILD(DEBUG)
if (m_renderer == nullptr) {
DCHECK(m_renderer != nullptr) << "Renderer not initialized.";
return;
}
#endif // BUILD(DEBUG)
fl::Mat4 translation =
fl::translationMatrix({static_cast<F32>(rect.pos.x), static_cast<F32>(rect.pos.y), 0.0f});
fl::Mat4 scale = fl::scaleMatrix(
{static_cast<F32>(rect.size.width), static_cast<F32>(rect.size.height), 1.0f});
fl::Mat4 view = translation * scale;
ca::UniformBuffer uniforms;
uniforms.set(m_quadTransformUniformId, m_projectionMatrix * view);
// uniforms.set(m_quadTexCoordsTransformUniformId, fl::Mat4::identity);
uniforms.set(m_quadColorUniformId, color);
m_renderer->state().depth_test(false);
m_renderer->state().cull_face(false);
m_renderer->draw(ca::DrawType::Triangles, 6, m_quadColorProgramId, m_quadVertexBufferId,
m_quadIndexBufferId, ca::TextureId{}, uniforms);
}
void Renderer::renderQuad(const fl::Rect& rect, const Image& image) {
if (!image.getTextureId().isValid()) {
LOG(Warning) << "Rendering invalid image.";
return;
}
renderTexturedQuad(rect, image, {{0, 0}, image.getSize()}, m_quadTextureProgramId);
}
void Renderer::renderQuad(const fl::Rect& rect, const Image& image, const fl::Rect& subImage) {
renderTexturedQuad(rect, image, subImage, m_quadTextureProgramId);
}
void Renderer::renderText(Font* font, const fl::Pos& position, const nu::StringView& text) {
const Image& image = font->getImage();
fl::Vec2 currentPosition{static_cast<F32>(position.x), static_cast<F32>(position.y)};
for (StringLength i = 0; i < text.length(); ++i) {
Char ch = text[i];
auto& glyph = font->glyph(ch);
fl::Rect rect{(I32)std::round(currentPosition.x + glyph.offset.x),
(I32)std::round(currentPosition.y + font->getAscent() + glyph.offset.y),
glyph.rect.size.width, glyph.rect.size.height};
#if 0
LOG(Info) << "glyph " << ch << ": rect(" << rect.pos.x << ", " << rect.pos.y << ", "
<< rect.size.width << ", " << rect.size.height << "), glyph.rect(" << glyph.rect.pos.x
<< ", " << glyph.rect.pos.y << ", " << glyph.rect.size.width << ", "
<< glyph.rect.size.height << "), offset(" << glyph.offset.x << ", " << glyph.offset.y
<< ")";
#endif // 0
// renderQuad(rect, image, glyph.rect);
renderTexturedQuad(rect, image, glyph.rect, m_quadFontProgramId);
currentPosition.x += glyph.xAdvance;
}
}
void Renderer::renderTexturedQuad(const fl::Rect& rect, const Image& image,
const fl::Rect& subImage, ca::ProgramId programId) {
#if BUILD(DEBUG)
if (m_renderer == nullptr) {
DCHECK(m_renderer != nullptr) << "Renderer not initialized.";
return;
}
#endif // BUILD(DEBUG)
fl::Mat4 translation =
fl::translationMatrix({static_cast<F32>(rect.pos.x), static_cast<F32>(rect.pos.y), 0.0f});
fl::Mat4 scale = fl::scaleMatrix(
{static_cast<F32>(rect.size.width), static_cast<F32>(rect.size.height), 1.0f});
fl::Mat4 view = translation * scale;
// TRS
fl::Vec2 imageSize{static_cast<F32>(image.getSize().width),
static_cast<F32>(image.getSize().height)};
fl::Mat4 texCoordsTransform =
fl::translationMatrix({static_cast<F32>(subImage.pos.x) / imageSize.x,
static_cast<F32>(subImage.pos.y) / imageSize.y, 0.0f}) *
fl::scaleMatrix({static_cast<F32>(subImage.size.width) / imageSize.x,
static_cast<F32>(subImage.size.height) / imageSize.y, 0.0f});
ca::UniformBuffer uniforms;
uniforms.set(m_quadTransformUniformId, m_projectionMatrix * view);
uniforms.set(m_quadTexCoordsTransformUniformId, texCoordsTransform);
#if 0
LOG(Info) << "Rendering quad at (" << rect.pos.x << ", " << rect.pos.y << ", " << rect.size.width
<< ", " << rect.size.height << ")";
#endif // 0
m_renderer->state().depth_test(false);
m_renderer->state().cull_face(false);
m_renderer->draw(ca::DrawType::Triangles, 6, programId, m_quadVertexBufferId, m_quadIndexBufferId,
image.getTextureId(), uniforms);
}
} // namespace el
<commit_msg>Clean up path and variable names.<commit_after>
#include "elastic/Renderer/renderer.h"
#include "floats/transform.h"
#include "nucleus/Streams/array_input_stream.h"
namespace el {
namespace {
const char* kQuadVertexShaderSource = R"source(
#version 330
layout(location = 0) in vec2 inPosition;
layout(location = 1) in vec2 inTexCoords;
out vec2 texCoords;
uniform mat4 uTransform;
uniform mat4 uTexCoordsTransform;
void main() {
texCoords = (uTexCoordsTransform * vec4(inTexCoords, 0.0, 1.0)).xy;
gl_Position = uTransform * vec4(inPosition, 0.0, 1.0);
}
)source";
const char* kQuadColorFragmentShaderSource = R"source(
#version 330
uniform vec4 uColor;
out vec4 final;
void main() {
final = uColor;
}
)source";
const char* kQuadTextureFragmentShaderSource = R"source(
#version 330
in vec2 texCoords;
out vec4 final;
uniform sampler2D uTexture;
void main() {
final = texture(uTexture, texCoords);
}
)source";
const char* kQuadFontFragmentShaderSource = R"source(
#version 330
in vec2 texCoords;
out vec4 final;
uniform sampler2D uTexture;
void main() {
float alpha = texture(uTexture, texCoords).r;
final = vec4(1.0f, 1.0f, 1.0f, alpha);
}
)source";
ca::ProgramId createProgram(ca::Renderer* renderer, nu::StringView vertexShaderSource,
nu::StringView fragmentShaderSource) {
nu::ArrayInputStream vertexStream{nu::ArrayView<U8>{
reinterpret_cast<const U8*>(vertexShaderSource.data()), vertexShaderSource.length()}};
auto vss = ca::ShaderSource::from(&vertexStream);
nu::ArrayInputStream fragmentStream{nu::ArrayView<U8>{
reinterpret_cast<const U8*>(fragmentShaderSource.data()), fragmentShaderSource.length()}};
auto fss = ca::ShaderSource::from(&fragmentStream);
return renderer->createProgram(vss, fss);
}
struct QuadVertex {
fl::Vec2 position;
fl::Vec2 texCoords;
} kQuadVertices[] = {
{{0.0f, 0.0f}, {0.0f, 0.0f}}, //
{{0.0f, 1.0f}, {0.0f, 1.0f}}, //
{{1.0f, 1.0f}, {1.0f, 1.0f}}, //
{{1.0f, 0.0f}, {1.0f, 0.0f}}, //
};
U8 kQuadIndices[] = {
0, 1, 2, //
2, 3, 0, //
};
} // namespace
Renderer::Renderer() = default;
Renderer::~Renderer() = default;
bool Renderer::initialize(ca::Renderer* renderer) {
m_renderer = renderer;
m_size = renderer->getSize();
m_quadColorProgramId =
createProgram(renderer, kQuadVertexShaderSource, kQuadColorFragmentShaderSource);
if (!isValid(m_quadColorProgramId)) {
LOG(Error) << "Could not create quad color shader program.";
return false;
}
m_quadTextureProgramId =
createProgram(renderer, kQuadVertexShaderSource, kQuadTextureFragmentShaderSource);
if (!isValid(m_quadTextureProgramId)) {
LOG(Error) << "Could not create quad texture shader program.";
return false;
}
m_quadFontProgramId =
createProgram(renderer, kQuadVertexShaderSource, kQuadFontFragmentShaderSource);
if (!isValid(m_quadTextureProgramId)) {
LOG(Error) << "Could not create quad FONT shader program.";
return false;
}
ca::VertexDefinition definition;
definition.addAttribute(ca::ComponentType::Float32, ca::ComponentCount::Two);
definition.addAttribute(ca::ComponentType::Float32, ca::ComponentCount::Two);
m_quadVertexBufferId =
renderer->createVertexBuffer(definition, kQuadVertices, sizeof(kQuadVertices));
if (!isValid(m_quadVertexBufferId)) {
LOG(Error) << "Could not create quad vertex buffer.";
return false;
}
m_quadIndexBufferId =
renderer->createIndexBuffer(ca::ComponentType::Unsigned8, kQuadIndices, sizeof(kQuadIndices));
if (!isValid(m_quadIndexBufferId)) {
LOG(Error) << "Could not create quad index buffer.";
return false;
}
m_quadTransformUniformId = renderer->createUniform("uTransform");
if (!isValid(m_quadTransformUniformId)) {
LOG(Error) << "Could not create quad transform uniform.";
return false;
}
m_quadTexCoordsTransformUniformId = renderer->createUniform("uTexCoordsTransform");
if (!isValid(m_quadTexCoordsTransformUniformId)) {
LOG(Error) << "Could not create quad tex coords transform uniform.";
return false;
}
m_quadColorUniformId = renderer->createUniform("uColor");
if (!isValid(m_quadColorUniformId)) {
LOG(Error) << "Could not create quad color uniform.";
return false;
}
m_projectionMatrix = fl::orthographic_projection(0.0f, static_cast<F32>(m_size.width), 0.0f,
static_cast<F32>(m_size.height), -1.0f, 1.0f);
return true;
}
void Renderer::resize(const fl::Size& size) {
m_size = size;
m_projectionMatrix = fl::orthographic_projection(0.0f, static_cast<F32>(m_size.width), 0.0f,
static_cast<F32>(m_size.height), -1.0f, 1.0f);
}
void Renderer::renderQuad(const fl::Rect& rect, const ca::Color& color) {
#if BUILD(DEBUG)
if (m_renderer == nullptr) {
DCHECK(m_renderer != nullptr) << "Renderer not initialized.";
return;
}
#endif // BUILD(DEBUG)
fl::Mat4 translation =
fl::translation_matrix({static_cast<F32>(rect.pos.x), static_cast<F32>(rect.pos.y), 0.0f});
fl::Mat4 scale = fl::scale_matrix(
{static_cast<F32>(rect.size.width), static_cast<F32>(rect.size.height), 1.0f});
fl::Mat4 view = translation * scale;
ca::UniformBuffer uniforms;
uniforms.set(m_quadTransformUniformId, m_projectionMatrix * view);
// uniforms.set(m_quadTexCoordsTransformUniformId, fl::Mat4::identity);
uniforms.set(m_quadColorUniformId, color);
m_renderer->state().depth_test(false);
m_renderer->state().cull_face(false);
m_renderer->draw(ca::DrawType::Triangles, 6, m_quadColorProgramId, m_quadVertexBufferId,
m_quadIndexBufferId, ca::TextureId{}, uniforms);
}
void Renderer::renderQuad(const fl::Rect& rect, const Image& image) {
if (!image.getTextureId().isValid()) {
LOG(Warning) << "Rendering invalid image.";
return;
}
renderTexturedQuad(rect, image, {{0, 0}, image.getSize()}, m_quadTextureProgramId);
}
void Renderer::renderQuad(const fl::Rect& rect, const Image& image, const fl::Rect& subImage) {
renderTexturedQuad(rect, image, subImage, m_quadTextureProgramId);
}
void Renderer::renderText(Font* font, const fl::Pos& position, const nu::StringView& text) {
const Image& image = font->getImage();
fl::Vec2 currentPosition{static_cast<F32>(position.x), static_cast<F32>(position.y)};
for (StringLength i = 0; i < text.length(); ++i) {
Char ch = text[i];
auto& glyph = font->glyph(ch);
fl::Rect rect{(I32)std::round(currentPosition.x + glyph.offset.x),
(I32)std::round(currentPosition.y + font->getAscent() + glyph.offset.y),
glyph.rect.size.width, glyph.rect.size.height};
#if 0
LOG(Info) << "glyph " << ch << ": rect(" << rect.pos.x << ", " << rect.pos.y << ", "
<< rect.size.width << ", " << rect.size.height << "), glyph.rect(" << glyph.rect.pos.x
<< ", " << glyph.rect.pos.y << ", " << glyph.rect.size.width << ", "
<< glyph.rect.size.height << "), offset(" << glyph.offset.x << ", " << glyph.offset.y
<< ")";
#endif // 0
// renderQuad(rect, image, glyph.rect);
renderTexturedQuad(rect, image, glyph.rect, m_quadFontProgramId);
currentPosition.x += glyph.xAdvance;
}
}
void Renderer::renderTexturedQuad(const fl::Rect& rect, const Image& image,
const fl::Rect& subImage, ca::ProgramId programId) {
#if BUILD(DEBUG)
if (m_renderer == nullptr) {
DCHECK(m_renderer != nullptr) << "Renderer not initialized.";
return;
}
#endif // BUILD(DEBUG)
fl::Mat4 translation =
fl::translation_matrix({static_cast<F32>(rect.pos.x), static_cast<F32>(rect.pos.y), 0.0f});
fl::Mat4 scale = fl::scale_matrix(
{static_cast<F32>(rect.size.width), static_cast<F32>(rect.size.height), 1.0f});
fl::Mat4 view = translation * scale;
// TRS
fl::Vec2 imageSize{static_cast<F32>(image.getSize().width),
static_cast<F32>(image.getSize().height)};
fl::Mat4 texCoordsTransform =
fl::translation_matrix({static_cast<F32>(subImage.pos.x) / imageSize.x,
static_cast<F32>(subImage.pos.y) / imageSize.y, 0.0f}) *
fl::scale_matrix({static_cast<F32>(subImage.size.width) / imageSize.x,
static_cast<F32>(subImage.size.height) / imageSize.y, 0.0f});
ca::UniformBuffer uniforms;
uniforms.set(m_quadTransformUniformId, m_projectionMatrix * view);
uniforms.set(m_quadTexCoordsTransformUniformId, texCoordsTransform);
#if 0
LOG(Info) << "Rendering quad at (" << rect.pos.x << ", " << rect.pos.y << ", " << rect.size.width
<< ", " << rect.size.height << ")";
#endif // 0
m_renderer->state().depth_test(false);
m_renderer->state().cull_face(false);
m_renderer->draw(ca::DrawType::Triangles, 6, programId, m_quadVertexBufferId, m_quadIndexBufferId,
image.getTextureId(), uniforms);
}
} // namespace el
<|endoftext|> |
<commit_before>
#include "emptyScene.h"
void emptyScene::setup(){
// parameters.add(param);
loadCode("emptyScene/exampleCode.cpp");
}
void emptyScene::update(){
}
void emptyScene::draw(){
drawCode();
}
void emptyScene::drawCode(){
string codeReplaced = getCodeWithParamsReplaced();
ofDrawBitmapString(codeReplaced, 40,40);
}
<commit_msg>Update emptyScene<commit_after>
#include "emptyScene.h"
void emptyScene::setup(){
// setup pramaters
// param.set("param", 5, 0, 100);
// parameters.add(param);
loadCode("emptyScene/exampleCode.cpp");
}
void emptyScene::update(){
}
void emptyScene::draw(){
drawCode();
}
void emptyScene::drawCode(){
string codeReplaced = getCodeWithParamsReplaced();
ofDrawBitmapString(codeReplaced, 40,40);
}
<|endoftext|> |
<commit_before>/* Chemfiles, an efficient IO library for chemistry file formats
* Copyright (C) 2015 Guillaume Fraux
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/
*/
#include <sstream>
#include <stack>
#include <algorithm>
#include "chemfiles/selections/parser.hpp"
#include "chemfiles/selections/expr.hpp"
using namespace chemfiles;
using namespace selections;
// Standard shunting-yard algorithm, as described in Wikipedia
// https://en.wikipedia.org/wiki/Shunting-yard_algorithm
//
// This convert infix expressions into an AST-like expression, while checking parentheses.
// The following input:
// name == bar and x <= 56
// is converted to:
// and <= 56 x == bar name
// which is the AST for
// and
// / \
// == <=
// / \ / \
// name bar x 56
static std::vector<Token> shunting_yard(token_iterator_t token, token_iterator_t end) {
std::stack<Token> operators;
std::vector<Token> output;
while (token != end) {
if (token->type() == Token::IDENT || token->type() == Token::NUM) {
output.push_back(*token);
} else if (token->is_operator()) {
while (!operators.empty()) {
// All the operators are left-associative
if (token->precedence() <= operators.top().precedence()) {
output.push_back(operators.top());
operators.pop();
} else {
break;
}
}
operators.push(*token);
} else if (token->type() == Token::LPAREN) {
operators.push(*token);
} else if (token->type() == Token::RPAREN) {
while (!operators.empty() && operators.top().type() != Token::LPAREN) {
output.push_back(operators.top());
operators.pop();
}
if (operators.empty() || operators.top().type() != Token::LPAREN) {
throw ParserError("Parentheses mismatched");
} else {
operators.pop();
}
}
token++;
}
while (!operators.empty()) {
if (operators.top().type() == Token::LPAREN || operators.top().type() == Token::RPAREN) {
throw ParserError("Parentheses mismatched");
} else {
output.push_back(operators.top());
operators.pop();
}
}
// AST come out as reverse polish notation, let's reverse it for easier parsing after
std::reverse(std::begin(output), std::end(output));
return output;
}
static bool have_short_form(const std::string& expr) {
return expr == "name" || expr == "index";
}
/// Rewrite the token stream to convert short form for the expressions to the long one.
///
/// Short forms are expressions like `name foo` or `index 3`, which are equivalent
/// to `name == foo` and `index == 3`.
static std::vector<Token> clean_token_stream(std::vector<Token> stream) {
auto out = std::vector<Token>();
for (auto it=stream.cbegin(); it != stream.cend(); it++) {
if (it->type() == Token::IDENT && have_short_form(it->ident())) {
auto next = it + 1;
if (next != stream.cend() && !next->is_operator()) {
out.emplace_back(Token(Token::EQ));
}
}
out.emplace_back(*it);
}
return out;
}
Ast selections::dispatch_parsing(token_iterator_t& begin, const token_iterator_t& end) {
if (begin->is_boolean_op()) {
switch (begin->type()) {
case Token::AND:
return parse<AndExpr>(begin, end);
case Token::OR:
return parse<OrExpr>(begin, end);
case Token::NOT:
return parse<NotExpr>(begin, end);
default:
throw std::runtime_error("Hit the default case in dispatch_parsing");
}
} else if (begin->is_binary_op()) {
if ((end - begin) < 3 || begin[2].type() != Token::IDENT) {
std::stringstream tokens;
for (auto tok = end - 1; tok != begin - 1; tok--) {
tokens << tok->str() << " ";
}
throw ParserError("Bad binary operator: " + tokens.str());
}
auto ident = begin[2].ident();
if (ident == "name") {
return parse<NameExpr>(begin, end);
} else if (ident == "index") {
return parse<IndexExpr>(begin, end);
} else if (ident == "x" || ident == "y" || ident == "z") {
return parse<PositionExpr>(begin, end);
} else if (ident == "vx" || ident == "vy" || ident == "vz") {
return parse<VelocityExpr>(begin, end);
} else {
throw ParserError("Unknown operation: " + ident);
}
} else if (begin->type() == Token::IDENT && begin->ident() == "all") {
return parse<AllExpr>(begin, end);
} else {
throw ParserError("Could not parse the selection");
}
}
Ast selections::parse(std::vector<Token> token_stream) {
token_stream = clean_token_stream(token_stream);
auto rpn = shunting_yard(std::begin(token_stream), std::end(token_stream));
auto begin = rpn.cbegin();
const auto end = rpn.cend();
auto ast = dispatch_parsing(begin, end);
if (begin != end) throw ParserError("Could not parse the end of the selection.");
return ast;
}
<commit_msg>Cleanup comments in parser<commit_after>/* Chemfiles, an efficient IO library for chemistry file formats
* Copyright (C) 2015 Guillaume Fraux
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/
*/
#include <sstream>
#include <stack>
#include <algorithm>
#include "chemfiles/selections/parser.hpp"
#include "chemfiles/selections/expr.hpp"
using namespace chemfiles;
using namespace selections;
/* Standard shunting-yard algorithm, as described in Wikipedia
* https://en.wikipedia.org/wiki/Shunting-yard_algorithm
*
* This convert infix expressions into an AST-like expression, while checking parentheses.
* The following input:
* name == bar and x <= 56
* is converted to:
* and <= 56 x == bar name
* which is the AST for
* and
* / \
* == <=
* / \ / \
* name bar x 56
*/
static std::vector<Token> shunting_yard(token_iterator_t token, token_iterator_t end) {
std::stack<Token> operators;
std::vector<Token> output;
while (token != end) {
if (token->type() == Token::IDENT || token->type() == Token::NUM) {
output.push_back(*token);
} else if (token->is_operator()) {
while (!operators.empty()) {
// All the operators are left-associative
if (token->precedence() <= operators.top().precedence()) {
output.push_back(operators.top());
operators.pop();
} else {
break;
}
}
operators.push(*token);
} else if (token->type() == Token::LPAREN) {
operators.push(*token);
} else if (token->type() == Token::RPAREN) {
while (!operators.empty() && operators.top().type() != Token::LPAREN) {
output.push_back(operators.top());
operators.pop();
}
if (operators.empty() || operators.top().type() != Token::LPAREN) {
throw ParserError("Parentheses mismatched");
} else {
operators.pop();
}
}
token++;
}
while (!operators.empty()) {
if (operators.top().type() == Token::LPAREN || operators.top().type() == Token::RPAREN) {
throw ParserError("Parentheses mismatched");
} else {
output.push_back(operators.top());
operators.pop();
}
}
// AST come out as reverse polish notation, let's reverse it for easier parsing after
std::reverse(std::begin(output), std::end(output));
return output;
}
static bool have_short_form(const std::string& expr) {
return expr == "name" || expr == "index";
}
/* Rewrite the token stream to convert short form for the expressions to the long one.
*
* Short forms are expressions like `name foo` or `index 3`, which are equivalent
* to `name == foo` and `index == 3`.
*/
static std::vector<Token> clean_token_stream(std::vector<Token> stream) {
auto out = std::vector<Token>();
for (auto it=stream.cbegin(); it != stream.cend(); it++) {
if (it->type() == Token::IDENT && have_short_form(it->ident())) {
auto next = it + 1;
if (next != stream.cend() && !next->is_operator()) {
out.emplace_back(Token(Token::EQ));
}
}
out.emplace_back(*it);
}
return out;
}
Ast selections::dispatch_parsing(token_iterator_t& begin, const token_iterator_t& end) {
if (begin->is_boolean_op()) {
switch (begin->type()) {
case Token::AND:
return parse<AndExpr>(begin, end);
case Token::OR:
return parse<OrExpr>(begin, end);
case Token::NOT:
return parse<NotExpr>(begin, end);
default:
throw std::runtime_error("Hit the default case in dispatch_parsing");
}
} else if (begin->is_binary_op()) {
if ((end - begin) < 3 || begin[2].type() != Token::IDENT) {
std::stringstream tokens;
for (auto tok = end - 1; tok != begin - 1; tok--) {
tokens << tok->str() << " ";
}
throw ParserError("Bad binary operator: " + tokens.str());
}
auto ident = begin[2].ident();
if (ident == "name") {
return parse<NameExpr>(begin, end);
} else if (ident == "index") {
return parse<IndexExpr>(begin, end);
} else if (ident == "x" || ident == "y" || ident == "z") {
return parse<PositionExpr>(begin, end);
} else if (ident == "vx" || ident == "vy" || ident == "vz") {
return parse<VelocityExpr>(begin, end);
} else {
throw ParserError("Unknown operation: " + ident);
}
} else if (begin->type() == Token::IDENT && begin->ident() == "all") {
return parse<AllExpr>(begin, end);
} else {
throw ParserError("Could not parse the selection");
}
}
Ast selections::parse(std::vector<Token> token_stream) {
token_stream = clean_token_stream(token_stream);
auto rpn = shunting_yard(std::begin(token_stream), std::end(token_stream));
auto begin = rpn.cbegin();
const auto end = rpn.cend();
auto ast = dispatch_parsing(begin, end);
if (begin != end) throw ParserError("Could not parse the end of the selection.");
return ast;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2013 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include <iostream>
#include <cstdlib>
#ifdef LEAN_USE_LUA
#include <lua.hpp>
#include "bindings/lua/name.h"
#include "bindings/lua/numerics.h"
int main(int argc, char ** argv) {
int status, result;
lua_State *L;
L = luaL_newstate();
luaL_openlibs(L);
lean::init_name(L);
lean::init_mpz(L);
lean::init_mpq(L);
for (int i = 1; i < argc; i++) {
status = luaL_loadfile(L, argv[i]);
if (status) {
std::cerr << "Couldn't load file: " << lua_tostring(L, -1) << "\n";
return 1;
}
result = lua_pcall(L, 0, LUA_MULTRET, 0);
if (result) {
std::cerr << "Failed to run script: " << lua_tostring(L, -1) << "\n";
return 1;
}
}
lua_close(L);
return 0;
}
#else
int main() {
std::cerr << "Lean was compiled without Lua support\n";
return 1;
}
#endif
<commit_msg>fix(shell/lua): catch lean exceptions in the leanlua frontend<commit_after>/*
Copyright (c) 2013 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include <iostream>
#include <cstdlib>
#ifdef LEAN_USE_LUA
#include <lua.hpp>
#include "util/exception.h"
#include "bindings/lua/name.h"
#include "bindings/lua/numerics.h"
int main(int argc, char ** argv) {
int status, result;
lua_State *L;
L = luaL_newstate();
luaL_openlibs(L);
lean::init_name(L);
lean::init_mpz(L);
lean::init_mpq(L);
for (int i = 1; i < argc; i++) {
status = luaL_loadfile(L, argv[i]);
if (status) {
std::cerr << "Couldn't load file: " << lua_tostring(L, -1) << "\n";
return 1;
}
try {
result = lua_pcall(L, 0, LUA_MULTRET, 0);
if (result) {
std::cerr << "Failed to run script: " << lua_tostring(L, -1) << "\n";
return 1;
}
} catch (lean::exception & ex) {
std::cerr << "Lean exception when running: " << argv[i] << "\n";
std::cerr << ex.what() << "\n";
}
}
lua_close(L);
return 0;
}
#else
int main() {
std::cerr << "Lean was compiled without Lua support\n";
return 1;
}
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2011-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "base58.h"
#include "data/base58_encode_decode.json.h"
#include "data/base58_keys_invalid.json.h"
#include "data/base58_keys_valid.json.h"
#include "key.h"
#include "script/script.h"
#include "uint256.h"
#include "util.h"
#include "utilstrencodings.h"
#include "test/test_navcoin.h"
#include <boost/foreach.hpp>
#include <boost/test/unit_test.hpp>
#include <univalue.h>
extern UniValue read_json(const std::string& jsondata);
BOOST_FIXTURE_TEST_SUITE(base58_tests, BasicTestingSetup)
// Goal: test low-level base58 encoding functionality
BOOST_AUTO_TEST_CASE(base58_EncodeBase58)
{
UniValue tests = read_json(std::string(json_tests::base58_encode_decode, json_tests::base58_encode_decode + sizeof(json_tests::base58_encode_decode)));
for (unsigned int idx = 0; idx < tests.size(); idx++) {
UniValue test = tests[idx];
std::string strTest = test.write();
if (test.size() < 2) // Allow for extra stuff (useful for comments)
{
BOOST_ERROR("Bad test: " << strTest);
continue;
}
std::vector<unsigned char> sourcedata = ParseHex(test[0].get_str());
std::string base58string = test[1].get_str();
BOOST_CHECK_MESSAGE(
EncodeBase58(begin_ptr(sourcedata), end_ptr(sourcedata)) == base58string,
strTest);
}
}
// Goal: test low-level base58 decoding functionality
BOOST_AUTO_TEST_CASE(base58_DecodeBase58)
{
UniValue tests = read_json(std::string(json_tests::base58_encode_decode, json_tests::base58_encode_decode + sizeof(json_tests::base58_encode_decode)));
std::vector<unsigned char> result;
for (unsigned int idx = 0; idx < tests.size(); idx++) {
UniValue test = tests[idx];
std::string strTest = test.write();
if (test.size() < 2) // Allow for extra stuff (useful for comments)
{
BOOST_ERROR("Bad test: " << strTest);
continue;
}
std::vector<unsigned char> expected = ParseHex(test[0].get_str());
std::string base58string = test[1].get_str();
BOOST_CHECK_MESSAGE(DecodeBase58(base58string, result), strTest);
BOOST_CHECK_MESSAGE(result.size() == expected.size() && std::equal(result.begin(), result.end(), expected.begin()), strTest);
}
BOOST_CHECK(!DecodeBase58("invalid", result));
// check that DecodeBase58 skips whitespace, but still fails with unexpected non-whitespace at the end.
BOOST_CHECK(!DecodeBase58(" \t\n\v\f\r skip \r\f\v\n\t a", result));
BOOST_CHECK( DecodeBase58(" \t\n\v\f\r skip \r\f\v\n\t ", result));
std::vector<unsigned char> expected = ParseHex("971a55");
BOOST_CHECK_EQUAL_COLLECTIONS(result.begin(), result.end(), expected.begin(), expected.end());
}
// Visitor to check address type
class TestAddrTypeVisitor : public boost::static_visitor<bool>
{
private:
std::string exp_addrType;
public:
TestAddrTypeVisitor(const std::string &_exp_addrType) : exp_addrType(_exp_addrType) { }
bool operator()(const CKeyID &id) const
{
return (exp_addrType == "pubkey");
}
bool operator()(const CScriptID &id) const
{
return (exp_addrType == "script");
}
bool operator()(const CNoDestination &no) const
{
return (exp_addrType == "none");
}
};
// Visitor to check address payload
class TestPayloadVisitor : public boost::static_visitor<bool>
{
private:
std::vector<unsigned char> exp_payload;
public:
TestPayloadVisitor(std::vector<unsigned char> &_exp_payload) : exp_payload(_exp_payload) { }
bool operator()(const CKeyID &id) const
{
uint160 exp_key(exp_payload);
return exp_key == id;
}
bool operator()(const CScriptID &id) const
{
uint160 exp_key(exp_payload);
return exp_key == id;
}
bool operator()(const CNoDestination &no) const
{
return exp_payload.size() == 0;
}
};
// Goal: check that parsed keys match test payload
BOOST_AUTO_TEST_CASE(base58_keys_valid_parse)
{
UniValue tests = read_json(std::string(json_tests::base58_keys_valid, json_tests::base58_keys_valid + sizeof(json_tests::base58_keys_valid)));
std::vector<unsigned char> result;
CNavCoinSecret secret;
CNavCoinAddress addr;
SelectParams(CBaseChainParams::MAIN);
for (unsigned int idx = 0; idx < tests.size(); idx++) {
UniValue test = tests[idx];
std::string strTest = test.write();
if (test.size() < 3) // Allow for extra stuff (useful for comments)
{
BOOST_ERROR("Bad test: " << strTest);
continue;
}
std::string exp_base58string = test[0].get_str();
std::vector<unsigned char> exp_payload = ParseHex(test[1].get_str());
const UniValue &metadata = test[2].get_obj();
bool isPrivkey = find_value(metadata, "isPrivkey").get_bool();
bool isTestnet = find_value(metadata, "isTestnet").get_bool();
if (isTestnet)
SelectParams(CBaseChainParams::TESTNET);
else
SelectParams(CBaseChainParams::MAIN);
if(isPrivkey)
{
bool isCompressed = find_value(metadata, "isCompressed").get_bool();
// Must be valid private key
// Note: CNavCoinSecret::SetString tests isValid, whereas CNavCoinAddress does not!
BOOST_CHECK_MESSAGE(secret.SetString(exp_base58string), "!SetString:"+ strTest);
BOOST_CHECK_MESSAGE(secret.IsValid(), "!IsValid:" + strTest);
CKey privkey = secret.GetKey();
BOOST_CHECK_MESSAGE(privkey.IsCompressed() == isCompressed, "compressed mismatch:" + strTest);
BOOST_CHECK_MESSAGE(privkey.size() == exp_payload.size() && std::equal(privkey.begin(), privkey.end(), exp_payload.begin()), "key mismatch:" + strTest);
// Private key must be invalid public key
addr.SetString(exp_base58string);
BOOST_CHECK_MESSAGE(!addr.IsValid(), "IsValid privkey as pubkey:" + strTest);
}
else
{
BOOST_TEST_MESSAGE("sdfsdfasdf");
BOOST_TEST_MESSAGE(secret.IsValid());
std::string exp_addrType = find_value(metadata, "addrType").get_str(); // "script" or "pubkey"
// Must be valid public key
BOOST_CHECK_MESSAGE(addr.SetString(exp_base58string), "SetString:" + strTest);
// BOOST_CHECK_MESSAGE(addr.IsValid(), "!IsValid:" + strTest);
// BOOST_CHECK_MESSAGE(addr.IsScript() == (exp_addrType == "script"), "isScript mismatch" + strTest);
CTxDestination dest = addr.Get();
// BOOST_CHECK_MESSAGE(boost::apply_visitor(TestAddrTypeVisitor(exp_addrType), dest), "addrType mismatch" + strTest);
// Public key must be invalid private key
secret.SetString(exp_base58string);
BOOST_CHECK_MESSAGE(!secret.IsValid(), "IsValid pubkey as privkey:" + strTest);
}
}
}
// Goal: check that generated keys match test vectors
BOOST_AUTO_TEST_CASE(base58_keys_valid_gen)
{
UniValue tests = read_json(std::string(json_tests::base58_keys_valid, json_tests::base58_keys_valid + sizeof(json_tests::base58_keys_valid)));
std::vector<unsigned char> result;
for (unsigned int idx = 0; idx < tests.size(); idx++) {
UniValue test = tests[idx];
std::string strTest = test.write();
if (test.size() < 3) // Allow for extra stuff (useful for comments)
{
BOOST_ERROR("Bad test: " << strTest);
continue;
}
std::string exp_base58string = test[0].get_str();
std::vector<unsigned char> exp_payload = ParseHex(test[1].get_str());
const UniValue &metadata = test[2].get_obj();
bool isPrivkey = find_value(metadata, "isPrivkey").get_bool();
bool isTestnet = find_value(metadata, "isTestnet").get_bool();
if (isTestnet)
SelectParams(CBaseChainParams::TESTNET);
else
SelectParams(CBaseChainParams::MAIN);
if(isPrivkey)
{
bool isCompressed = find_value(metadata, "isCompressed").get_bool();
CKey key;
key.Set(exp_payload.begin(), exp_payload.end(), isCompressed);
assert(key.IsValid());
CNavCoinSecret secret;
secret.SetKey(key);
BOOST_CHECK_MESSAGE(secret.ToString() == exp_base58string, "result mismatch: " + strTest);
}
else
{
std::string exp_addrType = find_value(metadata, "addrType").get_str();
CTxDestination dest;
if(exp_addrType == "pubkey")
{
dest = CKeyID(uint160(exp_payload));
}
else if(exp_addrType == "script")
{
dest = CScriptID(uint160(exp_payload));
}
else if(exp_addrType == "none")
{
dest = CNoDestination();
}
else
{
BOOST_ERROR("Bad addrtype: " << strTest);
continue;
}
CNavCoinAddress addrOut;
BOOST_CHECK_MESSAGE(addrOut.Set(dest), "encode dest: " + strTest);
// BOOST_CHECK_MESSAGE(addrOut.ToString() == exp_base58string, "mismatch: " + strTest);
}
}
// Visiting a CNoDestination must fail
CNavCoinAddress dummyAddr;
CTxDestination nodest = CNoDestination();
BOOST_CHECK(!dummyAddr.Set(nodest));
SelectParams(CBaseChainParams::MAIN);
}
// Goal: check that base58 parsing code is robust against a variety of corrupted data
BOOST_AUTO_TEST_CASE(base58_keys_invalid)
{
UniValue tests = read_json(std::string(json_tests::base58_keys_invalid, json_tests::base58_keys_invalid + sizeof(json_tests::base58_keys_invalid))); // Negative testcases
std::vector<unsigned char> result;
CNavCoinSecret secret;
CNavCoinAddress addr;
for (unsigned int idx = 0; idx < tests.size(); idx++) {
UniValue test = tests[idx];
std::string strTest = test.write();
if (test.size() < 1) // Allow for extra stuff (useful for comments)
{
BOOST_ERROR("Bad test: " << strTest);
continue;
}
std::string exp_base58string = test[0].get_str();
// must be invalid as public and as private key
addr.SetString(exp_base58string);
BOOST_CHECK_MESSAGE(!addr.IsValid(), "IsValid pubkey:" + strTest);
secret.SetString(exp_base58string);
BOOST_CHECK_MESSAGE(!secret.IsValid(), "IsValid privkey:" + strTest);
}
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Fixes comments<commit_after>// Copyright (c) 2011-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "base58.h"
#include "data/base58_encode_decode.json.h"
#include "data/base58_keys_invalid.json.h"
#include "data/base58_keys_valid.json.h"
#include "key.h"
#include "script/script.h"
#include "uint256.h"
#include "util.h"
#include "utilstrencodings.h"
#include "test/test_navcoin.h"
#include <boost/foreach.hpp>
#include <boost/test/unit_test.hpp>
#include <univalue.h>
extern UniValue read_json(const std::string& jsondata);
BOOST_FIXTURE_TEST_SUITE(base58_tests, BasicTestingSetup)
// Goal: test low-level base58 encoding functionality
BOOST_AUTO_TEST_CASE(base58_EncodeBase58)
{
UniValue tests = read_json(std::string(json_tests::base58_encode_decode, json_tests::base58_encode_decode + sizeof(json_tests::base58_encode_decode)));
for (unsigned int idx = 0; idx < tests.size(); idx++) {
UniValue test = tests[idx];
std::string strTest = test.write();
if (test.size() < 2) // Allow for extra stuff (useful for comments)
{
BOOST_ERROR("Bad test: " << strTest);
continue;
}
std::vector<unsigned char> sourcedata = ParseHex(test[0].get_str());
std::string base58string = test[1].get_str();
BOOST_CHECK_MESSAGE(
EncodeBase58(begin_ptr(sourcedata), end_ptr(sourcedata)) == base58string,
strTest);
}
}
// Goal: test low-level base58 decoding functionality
BOOST_AUTO_TEST_CASE(base58_DecodeBase58)
{
UniValue tests = read_json(std::string(json_tests::base58_encode_decode, json_tests::base58_encode_decode + sizeof(json_tests::base58_encode_decode)));
std::vector<unsigned char> result;
for (unsigned int idx = 0; idx < tests.size(); idx++) {
UniValue test = tests[idx];
std::string strTest = test.write();
if (test.size() < 2) // Allow for extra stuff (useful for comments)
{
BOOST_ERROR("Bad test: " << strTest);
continue;
}
std::vector<unsigned char> expected = ParseHex(test[0].get_str());
std::string base58string = test[1].get_str();
BOOST_CHECK_MESSAGE(DecodeBase58(base58string, result), strTest);
BOOST_CHECK_MESSAGE(result.size() == expected.size() && std::equal(result.begin(), result.end(), expected.begin()), strTest);
}
BOOST_CHECK(!DecodeBase58("invalid", result));
// check that DecodeBase58 skips whitespace, but still fails with unexpected non-whitespace at the end.
BOOST_CHECK(!DecodeBase58(" \t\n\v\f\r skip \r\f\v\n\t a", result));
BOOST_CHECK( DecodeBase58(" \t\n\v\f\r skip \r\f\v\n\t ", result));
std::vector<unsigned char> expected = ParseHex("971a55");
BOOST_CHECK_EQUAL_COLLECTIONS(result.begin(), result.end(), expected.begin(), expected.end());
}
// Visitor to check address type
class TestAddrTypeVisitor : public boost::static_visitor<bool>
{
private:
std::string exp_addrType;
public:
TestAddrTypeVisitor(const std::string &_exp_addrType) : exp_addrType(_exp_addrType) { }
bool operator()(const CKeyID &id) const
{
return (exp_addrType == "pubkey");
}
bool operator()(const CScriptID &id) const
{
return (exp_addrType == "script");
}
bool operator()(const CNoDestination &no) const
{
return (exp_addrType == "none");
}
};
// Visitor to check address payload
class TestPayloadVisitor : public boost::static_visitor<bool>
{
private:
std::vector<unsigned char> exp_payload;
public:
TestPayloadVisitor(std::vector<unsigned char> &_exp_payload) : exp_payload(_exp_payload) { }
bool operator()(const CKeyID &id) const
{
uint160 exp_key(exp_payload);
return exp_key == id;
}
bool operator()(const CScriptID &id) const
{
uint160 exp_key(exp_payload);
return exp_key == id;
}
bool operator()(const CNoDestination &no) const
{
return exp_payload.size() == 0;
}
};
// Goal: check that parsed keys match test payload
BOOST_AUTO_TEST_CASE(base58_keys_valid_parse)
{
UniValue tests = read_json(std::string(json_tests::base58_keys_valid, json_tests::base58_keys_valid + sizeof(json_tests::base58_keys_valid)));
std::vector<unsigned char> result;
CNavCoinSecret secret;
CNavCoinAddress addr;
SelectParams(CBaseChainParams::MAIN);
for (unsigned int idx = 0; idx < tests.size(); idx++) {
UniValue test = tests[idx];
std::string strTest = test.write();
if (test.size() < 3) // Allow for extra stuff (useful for comments)
{
BOOST_ERROR("Bad test: " << strTest);
continue;
}
std::string exp_base58string = test[0].get_str();
std::vector<unsigned char> exp_payload = ParseHex(test[1].get_str());
const UniValue &metadata = test[2].get_obj();
bool isPrivkey = find_value(metadata, "isPrivkey").get_bool();
bool isTestnet = find_value(metadata, "isTestnet").get_bool();
if (isTestnet)
SelectParams(CBaseChainParams::TESTNET);
else
SelectParams(CBaseChainParams::MAIN);
if(isPrivkey)
{
bool isCompressed = find_value(metadata, "isCompressed").get_bool();
// Must be valid private key
// Note: CNavCoinSecret::SetString tests isValid, whereas CNavCoinAddress does not!
BOOST_CHECK_MESSAGE(secret.SetString(exp_base58string), "!SetString:"+ strTest);
BOOST_CHECK_MESSAGE(secret.IsValid(), "!IsValid:" + strTest);
CKey privkey = secret.GetKey();
BOOST_CHECK_MESSAGE(privkey.IsCompressed() == isCompressed, "compressed mismatch:" + strTest);
BOOST_CHECK_MESSAGE(privkey.size() == exp_payload.size() && std::equal(privkey.begin(), privkey.end(), exp_payload.begin()), "key mismatch:" + strTest);
// Private key must be invalid public key
addr.SetString(exp_base58string);
BOOST_CHECK_MESSAGE(!addr.IsValid(), "IsValid privkey as pubkey:" + strTest);
}
else
{
std::string exp_addrType = find_value(metadata, "addrType").get_str(); // "script" or "pubkey"
// Must be valid public key
BOOST_CHECK_MESSAGE(addr.SetString(exp_base58string), "SetString:" + strTest);
// BOOST_CHECK_MESSAGE(addr.IsValid(), "!IsValid:" + strTest);
// BOOST_CHECK_MESSAGE(addr.IsScript() == (exp_addrType == "script"), "isScript mismatch" + strTest);
CTxDestination dest = addr.Get();
// BOOST_CHECK_MESSAGE(boost::apply_visitor(TestAddrTypeVisitor(exp_addrType), dest), "addrType mismatch" + strTest);
// Public key must be invalid private key
secret.SetString(exp_base58string);
BOOST_CHECK_MESSAGE(!secret.IsValid(), "IsValid pubkey as privkey:" + strTest);
}
}
}
// Goal: check that generated keys match test vectors
BOOST_AUTO_TEST_CASE(base58_keys_valid_gen)
{
UniValue tests = read_json(std::string(json_tests::base58_keys_valid, json_tests::base58_keys_valid + sizeof(json_tests::base58_keys_valid)));
std::vector<unsigned char> result;
for (unsigned int idx = 0; idx < tests.size(); idx++) {
UniValue test = tests[idx];
std::string strTest = test.write();
if (test.size() < 3) // Allow for extra stuff (useful for comments)
{
BOOST_ERROR("Bad test: " << strTest);
continue;
}
std::string exp_base58string = test[0].get_str();
std::vector<unsigned char> exp_payload = ParseHex(test[1].get_str());
const UniValue &metadata = test[2].get_obj();
bool isPrivkey = find_value(metadata, "isPrivkey").get_bool();
bool isTestnet = find_value(metadata, "isTestnet").get_bool();
if (isTestnet)
SelectParams(CBaseChainParams::TESTNET);
else
SelectParams(CBaseChainParams::MAIN);
if(isPrivkey)
{
bool isCompressed = find_value(metadata, "isCompressed").get_bool();
CKey key;
key.Set(exp_payload.begin(), exp_payload.end(), isCompressed);
assert(key.IsValid());
CNavCoinSecret secret;
secret.SetKey(key);
BOOST_CHECK_MESSAGE(secret.ToString() == exp_base58string, "result mismatch: " + strTest);
}
else
{
std::string exp_addrType = find_value(metadata, "addrType").get_str();
CTxDestination dest;
if(exp_addrType == "pubkey")
{
dest = CKeyID(uint160(exp_payload));
}
else if(exp_addrType == "script")
{
dest = CScriptID(uint160(exp_payload));
}
else if(exp_addrType == "none")
{
dest = CNoDestination();
}
else
{
BOOST_ERROR("Bad addrtype: " << strTest);
continue;
}
CNavCoinAddress addrOut;
BOOST_CHECK_MESSAGE(addrOut.Set(dest), "encode dest: " + strTest);
// BOOST_CHECK_MESSAGE(addrOut.ToString() == exp_base58string, "mismatch: " + strTest);
}
}
// Visiting a CNoDestination must fail
CNavCoinAddress dummyAddr;
CTxDestination nodest = CNoDestination();
BOOST_CHECK(!dummyAddr.Set(nodest));
SelectParams(CBaseChainParams::MAIN);
}
// Goal: check that base58 parsing code is robust against a variety of corrupted data
BOOST_AUTO_TEST_CASE(base58_keys_invalid)
{
UniValue tests = read_json(std::string(json_tests::base58_keys_invalid, json_tests::base58_keys_invalid + sizeof(json_tests::base58_keys_invalid))); // Negative testcases
std::vector<unsigned char> result;
CNavCoinSecret secret;
CNavCoinAddress addr;
for (unsigned int idx = 0; idx < tests.size(); idx++) {
UniValue test = tests[idx];
std::string strTest = test.write();
if (test.size() < 1) // Allow for extra stuff (useful for comments)
{
BOOST_ERROR("Bad test: " << strTest);
continue;
}
std::string exp_base58string = test[0].get_str();
// must be invalid as public and as private key
addr.SetString(exp_base58string);
BOOST_CHECK_MESSAGE(!addr.IsValid(), "IsValid pubkey:" + strTest);
secret.SetString(exp_base58string);
BOOST_CHECK_MESSAGE(!secret.IsValid(), "IsValid privkey:" + strTest);
}
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>#include <cstdlib> // size_t
#include <string>
#include <stdint.h>
#include <iostream>
#include <tightdb/assert.hpp>
#include <tightdb/utilities.hpp>
#ifdef _MSC_VER
#include <intrin.h>
#else
#include <cpuid.h>
#endif
namespace tightdb {
signed char sse_support = -1;
signed char avx_support = -1;
#if defined(TIGHTDB_COMPILER_AVX) && defined(__GNUC__)
#define _XCR_XFEATURE_ENABLED_MASK 0
#if __GNUC__ > 4 || __GNUC__ == 4 && __GNUC_MINOR__ >= 4
static inline unsigned long long _xgetbv(unsigned int index){
unsigned int eax, edx;
__asm__ __volatile__("xgetbv" : "=a"(eax), "=d"(edx) : "c"(index));
return ((unsigned long long)edx << 32) | eax;
}
#else
#define _xgetbv() 0
#endif
#endif
void cpuid_init()
{
#ifdef TIGHTDB_COMPILER_SSE
int cret;
#ifdef _MSC_VER
int CPUInfo[4];
__cpuid(CPUInfo, 1);
cret = CPUInfo[2];
#else
int a = 1;
__asm ( "mov %1, %%eax; " // a into eax
"cpuid;"
"mov %%ecx, %0;" // ecx into b
:"=r"(cret) // output
:"r"(a) // input
:"%eax","%ebx","%ecx","%edx" // clobbered register
);
#endif
// Byte is atomic. Race can/will occur but that's fine
if (cret & 0x100000) // test for 4.2
sse_support = 1;
else if (cret & 0x1) // Test for 3
sse_support = 0;
else
sse_support = -2;
bool avxSupported = false;
#if (_MSC_FULL_VER >= 160040219) || defined(__GNUC__)
bool osUsesXSAVE_XRSTORE = cret & (1 << 27) || false;
bool cpuAVXSuport = cret & (1 << 28) || false;
if (osUsesXSAVE_XRSTORE && cpuAVXSuport)
{
// Check if the OS will save the YMM registers
unsigned long long xcrFeatureMask = _xgetbv(_XCR_XFEATURE_ENABLED_MASK);
avxSupported = (xcrFeatureMask & 0x6) || false;
}
#endif
if (avxSupported)
{
avx_support = 0; // AVX1 supported
}
else
{
avx_support = -1; // No AVX supported
}
// 1 is reserved for AVX2
#endif
}
// FIXME: Move all these rounding functions to the header file to
// allow inlining.
void* round_up(void* p, size_t align)
{
// FIXME: The C++ standard does not guarantee that a pointer can
// be stored in size_t. Use uintptr_t instead. The problem with
// uintptr_t, is that is is not part of C++03.
size_t r = size_t(p) % align == 0 ? 0 : align - size_t(p) % align;
return static_cast<char *>(p) + r;
}
void* round_down(void* p, size_t align)
{
// FIXME: The C++ standard does not guarantee that a pointer can
// be stored in size_t. Use uintptr_t instead. The problem with
// uintptr_t, is that is is not part of C++03.
size_t r = size_t(p);
return reinterpret_cast<void *>(r & ~(align - 1));
}
size_t round_up(size_t p, size_t align)
{
size_t r = p % align == 0 ? 0 : align - p % align;
return p + r;
}
size_t round_down(size_t p, size_t align)
{
size_t r = p;
return r & (~(align - 1));
}
void checksum_init(checksum_t* t)
{
t->remainder = 0;
t->remainder_len = 0;
t->b_val = 0x794e80091e8f2bc7ULL;
t->a_val = 0xc20f9a8b761b7e4cULL;
t->result = 0;
}
unsigned long long checksum(unsigned char* data, size_t len)
{
checksum_t t;
checksum_init(&t);
checksum_rolling(data, len, &t);
return t.result;
}
void checksum_rolling(unsigned char* data, size_t len, checksum_t* t)
{
while (t->remainder_len < 8 && len > 0)
{
t->remainder = t->remainder >> 8;
t->remainder = t->remainder | static_cast<unsigned long long>(*data) << (7*8);
t->remainder_len++;
data++;
len--;
}
if (t->remainder_len < 8)
{
t->result = t->a_val + t->b_val;
return;
}
t->a_val += t->remainder * t->b_val;
t->b_val++;
t->remainder_len = 0;
t->remainder = 0;
while (len >= 8)
{
#ifdef TIGHTDB_X86_OR_X64
t->a_val += (*reinterpret_cast<unsigned long long*>(data)) * t->b_val;
#else
unsigned long long l = 0;
for (unsigned int i = 0; i < 8; i++)
{
l = l >> 8;
l = l | static_cast<unsigned long long>(*(data + i)) << (7*8);
}
t->a_val += l * t->b_val;
#endif
t->b_val++;
len -= 8;
data += 8;
}
while (len > 0)
{
t->remainder = t->remainder >> 8;
t->remainder = t->remainder | static_cast<unsigned long long>(*data) << (7*8);
t->remainder_len++;
data++;
len--;
}
t->result = t->a_val + t->b_val;
return;
}
// popcount, counts number of set (1) bits in argument. Intrinsics has been disabled because it's just 10-20% faster
// than fallback method, so a runtime-detection of support would be more expensive in total. Popcount is supported
// with SSE42 but not with SSE3, and we don't want separate builds for each architecture - hence a runtime check would
// be required.
#if 0 // defined(_MSC_VER) && _MSC_VER >= 1500
#include <intrin.h>
int fast_popcount32(int32_t x)
{
return __popcnt(x);
}
#if defined(_M_X64)
int fast_popcount64(int64_t x)
{
return (int)__popcnt64(x);
}
#else
int fast_popcount64(int64_t x)
{
return __popcnt((unsigned)(x)) + __popcnt((unsigned)(x >> 32));
}
#endif
#elif 0 // defined(__GNUC__) && __GNUC__ >= 4 || defined(__INTEL_COMPILER) && __INTEL_COMPILER >= 900
#define fast_popcount32 __builtin_popcount
#if ULONG_MAX == 0xffffffff
int fast_popcount64(int64_t x)
{
return __builtin_popcount((unsigned)(x)) + __builtin_popcount((unsigned)(x >> 32));
}
#else
int fast_popcount64(int64_t x)
{
return __builtin_popcountll(x);
}
#endif
#else
static const char a_popcount_bits[256] = {
0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8,
};
// Masking away bits might be faster than bit shifting (which can be slow). Note that the compiler may optimize this automatically. Todo, investigate.
int fast_popcount32(int32_t x)
{
return a_popcount_bits[255 & x] + a_popcount_bits[255 & x>> 8] + a_popcount_bits[255 & x>>16] + a_popcount_bits[255 & x>>24];
}
int fast_popcount64(int64_t x)
{
return fast_popcount32(static_cast<int32_t>(x)) + fast_popcount32(static_cast<int32_t>(x >> 32));
}
#endif // select best popcount implementations
}
<commit_msg>tried to fix clang build, but it seems like __GNUC__ is defined for clang in jenkins?!<commit_after>#include <cstdlib> // size_t
#include <string>
#include <stdint.h>
#include <iostream>
#include <tightdb/assert.hpp>
#include <tightdb/utilities.hpp>
#ifdef _MSC_VER
#include <intrin.h>
#else
#include <cpuid.h>
#endif
namespace tightdb {
signed char sse_support = -1;
signed char avx_support = -1;
#if defined(TIGHTDB_COMPILER_AVX) && defined(__GNUC__)
#define _XCR_XFEATURE_ENABLED_MASK 0
#if __GNUC__ > 4 || __GNUC__ == 4 && __GNUC_MINOR__ >= 4
static inline unsigned long long _xgetbv(unsigned int index){
unsigned int eax, edx;
__asm__ __volatile__("xgetbv" : "=a"(eax), "=d"(edx) : "c"(index));
return ((unsigned long long)edx << 32) | eax;
}
#else
#define _xgetbv() 0
#endif
#endif
void cpuid_init()
{
#ifdef TIGHTDB_COMPILER_SSE
int cret;
#ifdef _MSC_VER
int CPUInfo[4];
__cpuid(CPUInfo, 1);
cret = CPUInfo[2];
#else
int a = 1;
__asm ( "mov %1, %%eax; " // a into eax
"cpuid;"
"mov %%ecx, %0;" // ecx into b
:"=r"(cret) // output
:"r"(a) // input
:"%eax","%ebx","%ecx","%edx" // clobbered register
);
#endif
// Byte is atomic. Race can/will occur but that's fine
if (cret & 0x100000) // test for 4.2
sse_support = 1;
else if (cret & 0x1) // Test for 3
sse_support = 0;
else
sse_support = -2;
bool avxSupported = false;
// seems like in jenkins builds, __GNUC__ is defined for clang?! todo fixme
#if !defined(__clang__) && ((_MSC_FULL_VER >= 160040219) || defined(__GNUC__))
bool osUsesXSAVE_XRSTORE = cret & (1 << 27) || false;
bool cpuAVXSuport = cret & (1 << 28) || false;
if (osUsesXSAVE_XRSTORE && cpuAVXSuport)
{
// Check if the OS will save the YMM registers
unsigned long long xcrFeatureMask = _xgetbv(_XCR_XFEATURE_ENABLED_MASK);
avxSupported = (xcrFeatureMask & 0x6) || false;
}
#endif
if (avxSupported)
{
avx_support = 0; // AVX1 supported
}
else
{
avx_support = -1; // No AVX supported
}
// 1 is reserved for AVX2
#endif
}
// FIXME: Move all these rounding functions to the header file to
// allow inlining.
void* round_up(void* p, size_t align)
{
// FIXME: The C++ standard does not guarantee that a pointer can
// be stored in size_t. Use uintptr_t instead. The problem with
// uintptr_t, is that is is not part of C++03.
size_t r = size_t(p) % align == 0 ? 0 : align - size_t(p) % align;
return static_cast<char *>(p) + r;
}
void* round_down(void* p, size_t align)
{
// FIXME: The C++ standard does not guarantee that a pointer can
// be stored in size_t. Use uintptr_t instead. The problem with
// uintptr_t, is that is is not part of C++03.
size_t r = size_t(p);
return reinterpret_cast<void *>(r & ~(align - 1));
}
size_t round_up(size_t p, size_t align)
{
size_t r = p % align == 0 ? 0 : align - p % align;
return p + r;
}
size_t round_down(size_t p, size_t align)
{
size_t r = p;
return r & (~(align - 1));
}
void checksum_init(checksum_t* t)
{
t->remainder = 0;
t->remainder_len = 0;
t->b_val = 0x794e80091e8f2bc7ULL;
t->a_val = 0xc20f9a8b761b7e4cULL;
t->result = 0;
}
unsigned long long checksum(unsigned char* data, size_t len)
{
checksum_t t;
checksum_init(&t);
checksum_rolling(data, len, &t);
return t.result;
}
void checksum_rolling(unsigned char* data, size_t len, checksum_t* t)
{
while (t->remainder_len < 8 && len > 0)
{
t->remainder = t->remainder >> 8;
t->remainder = t->remainder | static_cast<unsigned long long>(*data) << (7*8);
t->remainder_len++;
data++;
len--;
}
if (t->remainder_len < 8)
{
t->result = t->a_val + t->b_val;
return;
}
t->a_val += t->remainder * t->b_val;
t->b_val++;
t->remainder_len = 0;
t->remainder = 0;
while (len >= 8)
{
#ifdef TIGHTDB_X86_OR_X64
t->a_val += (*reinterpret_cast<unsigned long long*>(data)) * t->b_val;
#else
unsigned long long l = 0;
for (unsigned int i = 0; i < 8; i++)
{
l = l >> 8;
l = l | static_cast<unsigned long long>(*(data + i)) << (7*8);
}
t->a_val += l * t->b_val;
#endif
t->b_val++;
len -= 8;
data += 8;
}
while (len > 0)
{
t->remainder = t->remainder >> 8;
t->remainder = t->remainder | static_cast<unsigned long long>(*data) << (7*8);
t->remainder_len++;
data++;
len--;
}
t->result = t->a_val + t->b_val;
return;
}
// popcount, counts number of set (1) bits in argument. Intrinsics has been disabled because it's just 10-20% faster
// than fallback method, so a runtime-detection of support would be more expensive in total. Popcount is supported
// with SSE42 but not with SSE3, and we don't want separate builds for each architecture - hence a runtime check would
// be required.
#if 0 // defined(_MSC_VER) && _MSC_VER >= 1500
#include <intrin.h>
int fast_popcount32(int32_t x)
{
return __popcnt(x);
}
#if defined(_M_X64)
int fast_popcount64(int64_t x)
{
return (int)__popcnt64(x);
}
#else
int fast_popcount64(int64_t x)
{
return __popcnt((unsigned)(x)) + __popcnt((unsigned)(x >> 32));
}
#endif
#elif 0 // defined(__GNUC__) && __GNUC__ >= 4 || defined(__INTEL_COMPILER) && __INTEL_COMPILER >= 900
#define fast_popcount32 __builtin_popcount
#if ULONG_MAX == 0xffffffff
int fast_popcount64(int64_t x)
{
return __builtin_popcount((unsigned)(x)) + __builtin_popcount((unsigned)(x >> 32));
}
#else
int fast_popcount64(int64_t x)
{
return __builtin_popcountll(x);
}
#endif
#else
static const char a_popcount_bits[256] = {
0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8,
};
// Masking away bits might be faster than bit shifting (which can be slow). Note that the compiler may optimize this automatically. Todo, investigate.
int fast_popcount32(int32_t x)
{
return a_popcount_bits[255 & x] + a_popcount_bits[255 & x>> 8] + a_popcount_bits[255 & x>>16] + a_popcount_bits[255 & x>>24];
}
int fast_popcount64(int64_t x)
{
return fast_popcount32(static_cast<int32_t>(x)) + fast_popcount32(static_cast<int32_t>(x >> 32));
}
#endif // select best popcount implementations
}
<|endoftext|> |
<commit_before>#ifndef TURBO_TOOLSET_INTRINSIC_HPP
#define TURBO_TOOLSET_INTRINSIC_HPP
#include <cstdint>
namespace turbo {
namespace toolset {
inline std::uint32_t count_leading_zero(std::uint32_t input)
{
#if defined( _WIN32) && defined(_MSC_VER)
std::uint32_t result = 0U;
return (_BitScanReverse(result&, input) == 0) ? 32U : 32U - result + 1U;
#elif defined(__GNUC__) || defined(__clang__)
return (input == 0U) ? 32U : __builtin_clz(input);
#else
std::uint32_t count = 0U;
while (count < 32U && (input & 2147483648U) != 2147483648U)
{
input = input << 1;
++count;
}
return count;
#endif
}
inline std::uint64_t count_leading_zero(std::uint64_t input)
{
#if defined( _WIN32) && defined(_MSC_VER)
std::uint64_t result = 0U;
return (_BitScanReverse64(result&, input) == 0) ? 64U : 64U - result + 1U;
#else
std::uint32_t high_result = count_leading_zero((input & 0xFFFFFFFF00000000) >> 32);
return (high_result != 32U) ? high_result : count_leading_zero(input & 0x00000000FFFFFFFF) + 32U;
#endif
}
} // namespace toolset
} // namespace turbo
#endif
<commit_msg>fixed a defect in the uin64_t version of count_leading_zero where the nested call to count_leading_zero wasn't calling the uint32_t version, needs static_cast to remove ambiguity<commit_after>#ifndef TURBO_TOOLSET_INTRINSIC_HPP
#define TURBO_TOOLSET_INTRINSIC_HPP
#include <cstdint>
namespace turbo {
namespace toolset {
inline std::uint32_t count_leading_zero(std::uint32_t input)
{
#if defined( _WIN32) && defined(_MSC_VER)
std::uint32_t result = 0U;
return (_BitScanReverse(result&, input) == 0) ? 32U : 32U - result + 1U;
#elif defined(__GNUC__) || defined(__clang__)
return (input == 0U) ? 32U : __builtin_clz(input);
#else
std::uint32_t count = 0U;
while (count < 32U && (input & 2147483648U) != 2147483648U)
{
input = input << 1;
++count;
}
return count;
#endif
}
inline std::uint64_t count_leading_zero(std::uint64_t input)
{
#if defined( _WIN32) && defined(_MSC_VER)
std::uint64_t result = 0U;
return (_BitScanReverse64(result&, input) == 0) ? 64U : 64U - result + 1U;
#else
std::uint32_t high_result = count_leading_zero(static_cast<std::uint32_t>((input & 0xFFFFFFFF00000000) >> 32));
return (high_result != 32U) ? high_result : count_leading_zero(static_cast<std::uint32_t>(input & 0x00000000FFFFFFFF)) + 32U;
#endif
}
} // namespace toolset
} // namespace turbo
#endif
<|endoftext|> |
<commit_before>// Alexis Giraudet
// Théo Cesbron
#ifndef TREE_DICTIONNAIRE_HPP
#define TREE_DICTIONNAIRE_HPP
#include "abstract_dictionnaire.hpp"
#include "node.hpp"
using namespace std;
/**
* Classe tree_dictionnaire:
*
**/
template <typename V>
class tree_dictionnaire: public abstract_dictionnaire<V>
{
private:
node<char,string> _root;
public:
tree_dictionnaire();
~tree_dictionnaire();
bool contientMot(const string& mot) const;
void ajouterMot(const string& mot, const V& v);
void associerMot(const string& mot, const V& v);
void supprimerMot(const string& mot);
V valeurAssociee(const string& mot) const;
};
template <typename V>
tree_dictionnaire<V>::tree_dictionnaire()
{
;
}
template <typename V>
tree_dictionnaire<V>::~tree_dictionnaire()
{
;
}
/**
* vrai ssi la chaîne mot figure dans le tree_dictionnaire
**/
template <typename V>
bool tree_dictionnaire<V>::contientMot(const string& mot) const
{
return false;
}
/**
* ajoute la chaîne mot au tree_dictionnaire, avec la valeur v, mot étant supposé absent du tree_dictionnaire
**/
template <typename V>
void tree_dictionnaire<V>::ajouterMot(const string& mot, const V& v)
{
;
}
/**
* associe la valeur v à la chaîne mot dans le tree_dictionnaire, mot pouvant être présent ou absent du tree_dictionnaire
**/
template <typename V>
void tree_dictionnaire<V>::associerMot(const string& mot, const V& v)
{
;
}
/**
* supprime l'éventuelle chaîne mot du tree_dictionnaire
**/
template <typename V>
void tree_dictionnaire<V>::supprimerMot(const string& mot)
{
;
}
/**
* donne la valeur correspondant à la chaîne mot (supposée figurer dans le tree_dictionnaire)
**/
template <typename V>
V tree_dictionnaire<V>::valeurAssociee(const string& mot) const
{
;
}
#endif
<commit_msg>implement functions with new node structure<commit_after>// Alexis Giraudet
// Théo Cesbron
#ifndef TREE_DICTIONNAIRE_HPP
#define TREE_DICTIONNAIRE_HPP
#include "abstract_dictionnaire.hpp"
#include "node.hpp"
using namespace std;
/**
* Classe tree_dictionnaire:
*
**/
template <typename V>
class tree_dictionnaire: public abstract_dictionnaire<V>
{
private:
node<V> _root;
public:
tree_dictionnaire();
~tree_dictionnaire();
bool contientMot(const string& mot) const;
void ajouterMot(const string& mot, const V& v);
void associerMot(const string& mot, const V& v);
void supprimerMot(const string& mot);
V valeurAssociee(const string& mot) const;
};
template <typename V>
tree_dictionnaire<V>::tree_dictionnaire()
{
;
}
template <typename V>
tree_dictionnaire<V>::~tree_dictionnaire()
{
;
}
/**
* vrai ssi la chaîne mot figure dans le tree_dictionnaire
**/
template <typename V>
bool tree_dictionnaire<V>::contientMot(const string& mot) const
{
return _root.contains(mot.begin(),mot.end());
}
/**
* ajoute la chaîne mot au tree_dictionnaire, avec la valeur v, mot étant supposé absent du tree_dictionnaire
**/
template <typename V>
void tree_dictionnaire<V>::ajouterMot(const string& mot, const V& v)
{
_root.set(v,mot.begin(),mot.end());
}
/**
* associe la valeur v à la chaîne mot dans le tree_dictionnaire, mot pouvant être présent ou absent du tree_dictionnaire
**/
template <typename V>
void tree_dictionnaire<V>::associerMot(const string& mot, const V& v)
{
_root.set(v,mot.begin(),mot.end());
}
/**
* supprime l'éventuelle chaîne mot du tree_dictionnaire
**/
template <typename V>
void tree_dictionnaire<V>::supprimerMot(const string& mot)
{
;
}
/**
* donne la valeur correspondant à la chaîne mot (supposée figurer dans le tree_dictionnaire)
**/
template <typename V>
V tree_dictionnaire<V>::valeurAssociee(const string& mot) const
{
return _root.get(mot.begin(),mot.end());
}
#endif
<|endoftext|> |
<commit_before>/**
* Copyright (C) 2013 CoDyCo Project
* Author: Silvio Traversaro
* website: http://www.codyco.eu
*/
#include "kdl_codyco/treeserialization.hpp"
#include "kdl_codyco/tree_rotation.hpp"
#include <kdl/joint.hpp>
#include <algorithm>
#include <cassert>
#include <iostream>
#include <sstream>
namespace KDL {
namespace CoDyCo {
void TreeSerialization::addDFSrecursive(SegmentMap::const_iterator current_el, int & link_cnt, int & fixed_joints_cnt )
{
#ifndef NDEBUG
//std::cout << "addDFSrecursive: called with segment " << current_el->second.segment.getName() << " link_cnt " << link_cnt << " fixed_joints_cnt " << fixed_joints_cnt << std::endl;
//std::cout << "nr of junctions " << getNrOfJunctions() << " nr of DOFs " << getNrOfDOFs() << std::endl;
#endif
if( current_el->second.segment.getJoint().getType() != Joint::None ) {
dofs[current_el->second.q_nr] = current_el->second.segment.getJoint().getName();
junctions[current_el->second.q_nr] = current_el->second.segment.getJoint().getName();
} else {
assert((int)junctions.size() == getNrOfJunctions());
assert(getNrOfDOFs()+fixed_joints_cnt < (int)junctions.size());
junctions[getNrOfDOFs()+fixed_joints_cnt] = current_el->second.segment.getJoint().getName();
fixed_joints_cnt++;
}
links[link_cnt] = current_el->first;
link_cnt++;
for( unsigned int i=0; i < current_el->second.children.size(); i++ ) {
addDFSrecursive(current_el->second.children[i],link_cnt,fixed_joints_cnt);
}
}
void TreeSerialization::addDFSrecursive_only_fixed(SegmentMap::const_iterator current_el, int & fixed_joints_cnt )
{
if( current_el->second.segment.getJoint().getType() == Joint::None ) {
junctions[getNrOfDOFs()+fixed_joints_cnt] = current_el->second.segment.getJoint().getName();
fixed_joints_cnt++;
}
for( unsigned int i=0; i < current_el->second.children.size(); i++ ) {
addDFSrecursive_only_fixed(current_el->second.children[i],fixed_joints_cnt);
}
}
TreeSerialization::TreeSerialization()
{
links = std::vector<std::string>(0);
junctions = std::vector<std::string>(0);
dofs = std::vector<std::string>(0);
}
TreeSerialization::~TreeSerialization() {}
TreeSerialization::TreeSerialization(const Tree & tree)
{
links = std::vector<std::string>(tree.getNrOfSegments());
dofs = std::vector<std::string>(tree.getNrOfJoints());
junctions = std::vector<std::string>(tree.getNrOfSegments()-1);
SegmentMap::const_iterator root, real_root;
SegmentMap::const_iterator child;
int link_cnt = 0;
int fixed_joints_cnt = 0;
root = tree.getRootSegment();
/** \todo remove this assumption */
assert(root->second.children.size() != 0);
SegmentMap::const_iterator root_child = root->second.children[0];
//This should be coherent with the behaviour of UndirectedTree
if( root->second.children.size() != 1 || root_child->second.segment.getJoint().getType() != Joint::None )
{
real_root = root;
links.resize(links.size()+1);
junctions.resize(junctions.size()+1);
} else {
real_root = root->second.children[0];
}
//Add real_root link without including fake joint
links[link_cnt] = real_root->first;
link_cnt++;
for( unsigned int i=0; i < real_root->second.children.size(); i++ ) {
addDFSrecursive(real_root->second.children[i],link_cnt,fixed_joints_cnt);
}
assert(this->is_consistent(tree));
}
TreeSerialization::TreeSerialization(const Tree & tree, std::vector<std::string> & links_in, std::vector<std::string> & joints_in)
{
assert(links_in.size() == tree.getNrOfSegments());
assert(joints_in.size() == tree.getNrOfSegments()-1 || joints_in.size() == tree.getNrOfJoints() );
links = links_in;
if( joints_in.size() == tree.getNrOfSegments()-1 ) {
junctions = joints_in;
dofs = junctions;
dofs.resize(tree.getNrOfJoints());
} else {
dofs = joints_in;
junctions = dofs;
junctions.resize(tree.getNrOfSegments()-1);
int fixed_joints_cnt = 0;
SegmentMap::const_iterator root = tree.getRootSegment();
for( unsigned int i=0; i < root->second.children.size(); i++ ) {
addDFSrecursive_only_fixed(root->second.children[i],fixed_joints_cnt);
}
}
assert(this->is_consistent(tree));
}
TreeSerialization::TreeSerialization(const TreeSerialization& x)
{
links = std::vector<std::string>(0);
junctions = std::vector<std::string>(0);
dofs = std::vector<std::string>(0);
links = x.links;
junctions = x.junctions;
dofs = x.dofs;
}
int TreeSerialization::getJunctionId(std::string junction_name) const
{
std::vector<std::string>::const_iterator it;
it = std::find(junctions.begin(),junctions.end(),junction_name);
if( it != junctions.end() ) {
return it - junctions.begin();
} else {
return -1;
}
}
int TreeSerialization::getLinkId(std::string link_name) const
{
std::vector<std::string>::const_iterator it;
it = std::find(links.begin(),links.end(),link_name);
if( it != links.end() ) {
return it - links.begin();
} else {
return -1;
}
}
int TreeSerialization::getDOFId(std::string dof_name) const
{
std::vector<std::string>::const_iterator it;
it = std::find(dofs.begin(),dofs.end(),dof_name);
if( it != dofs.end() ) {
return it - dofs.begin();
} else {
return -1;
}
}
std::string TreeSerialization::getDOFName(int dof_id) const
{
return dofs[dof_id];
}
std::string TreeSerialization::getJunctionName(int junction_id) const
{
return junctions[junction_id];
}
std::string TreeSerialization::getLinkName(int link_id) const
{
return links[link_id];
}
bool TreeSerialization::is_consistent(const Tree & tree) const
{
SegmentMap::const_iterator seg;
SegmentMap::const_iterator root = tree.getRootSegment();
/** \todo remove this assumption */
assert(root->second.children.size() != 0);
SegmentMap::const_iterator root_child = root->second.children[0];
//This should be coherent with the behaviour of UndirectedTree
if( root->second.children.size() != 1 || root_child->second.segment.getJoint().getType() != Joint::None )
{
if( tree.getNrOfJoints() != dofs.size() || tree.getNrOfSegments()+1 != links.size() ) {
return false;
}
} else {
if( tree.getNrOfJoints() != dofs.size() || tree.getNrOfSegments() != links.size() ) {
return false;
}
}
unsigned int i;
const SegmentMap & seg_map = tree.getSegments();
for(i = 0; i < links.size(); i++ ) {
seg = tree.getSegment(links[i]);
if( seg == seg_map.end() ) {
return false;
}
}
for(SegmentMap::const_iterator it=seg_map.begin(); it != seg_map.end(); it++) {
if( it->second.segment.getJoint().getType() != Joint::None ) {
if( getJunctionId( it->second.segment.getJoint().getName()) == -1 ) {
return false;
}
}
}
return true;
}
int TreeSerialization::setNrOfLinks(const int new_size)
{
links.resize(new_size);
if( new_size > 0 ) {
junctions.resize(new_size-1);
} else {
junctions.resize(0);
}
return links.size();
}
int TreeSerialization::getNrOfLinks() const
{
return links.size();
}
int TreeSerialization::getNrOfJunctions() const
{
return junctions.size();
}
int TreeSerialization::setNrOfDOFs(const int new_size)
{
dofs.resize(new_size);
return dofs.size();
}
int TreeSerialization::getNrOfDOFs() const
{
return dofs.size();
}
std::string TreeSerialization::toString()
{
std::stringstream ss;
ss << "Links serialization:" << std::endl;
for( int i = 0; i < (int)links.size(); i++ ) {
ss << i << "\t: " << links[i] << std::endl;
}
ss << "Junctions serialization:" << std::endl;
for( int i = 0; i < (int)junctions.size(); i++ ) {
ss << i << "\t: " << junctions[i] << std::endl;
}
ss << "DOFs serialization:" << std::endl;
for( int i = 0; i < (int)dofs.size(); i++ ) {
ss << i << "\t: " << dofs[i] << std::endl;
}
return ss.str();
}
}
}
<commit_msg>Removed old tree_rotation header<commit_after>/**
* Copyright (C) 2013 CoDyCo Project
* Author: Silvio Traversaro
* website: http://www.codyco.eu
*/
#include "kdl_codyco/treeserialization.hpp"
#include <kdl/joint.hpp>
#include <algorithm>
#include <cassert>
#include <iostream>
#include <sstream>
namespace KDL {
namespace CoDyCo {
void TreeSerialization::addDFSrecursive(SegmentMap::const_iterator current_el, int & link_cnt, int & fixed_joints_cnt )
{
#ifndef NDEBUG
//std::cout << "addDFSrecursive: called with segment " << current_el->second.segment.getName() << " link_cnt " << link_cnt << " fixed_joints_cnt " << fixed_joints_cnt << std::endl;
//std::cout << "nr of junctions " << getNrOfJunctions() << " nr of DOFs " << getNrOfDOFs() << std::endl;
#endif
if( current_el->second.segment.getJoint().getType() != Joint::None ) {
dofs[current_el->second.q_nr] = current_el->second.segment.getJoint().getName();
junctions[current_el->second.q_nr] = current_el->second.segment.getJoint().getName();
} else {
assert((int)junctions.size() == getNrOfJunctions());
assert(getNrOfDOFs()+fixed_joints_cnt < (int)junctions.size());
junctions[getNrOfDOFs()+fixed_joints_cnt] = current_el->second.segment.getJoint().getName();
fixed_joints_cnt++;
}
links[link_cnt] = current_el->first;
link_cnt++;
for( unsigned int i=0; i < current_el->second.children.size(); i++ ) {
addDFSrecursive(current_el->second.children[i],link_cnt,fixed_joints_cnt);
}
}
void TreeSerialization::addDFSrecursive_only_fixed(SegmentMap::const_iterator current_el, int & fixed_joints_cnt )
{
if( current_el->second.segment.getJoint().getType() == Joint::None ) {
junctions[getNrOfDOFs()+fixed_joints_cnt] = current_el->second.segment.getJoint().getName();
fixed_joints_cnt++;
}
for( unsigned int i=0; i < current_el->second.children.size(); i++ ) {
addDFSrecursive_only_fixed(current_el->second.children[i],fixed_joints_cnt);
}
}
TreeSerialization::TreeSerialization()
{
links = std::vector<std::string>(0);
junctions = std::vector<std::string>(0);
dofs = std::vector<std::string>(0);
}
TreeSerialization::~TreeSerialization() {}
TreeSerialization::TreeSerialization(const Tree & tree)
{
links = std::vector<std::string>(tree.getNrOfSegments());
dofs = std::vector<std::string>(tree.getNrOfJoints());
junctions = std::vector<std::string>(tree.getNrOfSegments()-1);
SegmentMap::const_iterator root, real_root;
SegmentMap::const_iterator child;
int link_cnt = 0;
int fixed_joints_cnt = 0;
root = tree.getRootSegment();
/** \todo remove this assumption */
assert(root->second.children.size() != 0);
SegmentMap::const_iterator root_child = root->second.children[0];
//This should be coherent with the behaviour of UndirectedTree
if( root->second.children.size() != 1 || root_child->second.segment.getJoint().getType() != Joint::None )
{
real_root = root;
links.resize(links.size()+1);
junctions.resize(junctions.size()+1);
} else {
real_root = root->second.children[0];
}
//Add real_root link without including fake joint
links[link_cnt] = real_root->first;
link_cnt++;
for( unsigned int i=0; i < real_root->second.children.size(); i++ ) {
addDFSrecursive(real_root->second.children[i],link_cnt,fixed_joints_cnt);
}
assert(this->is_consistent(tree));
}
TreeSerialization::TreeSerialization(const Tree & tree, std::vector<std::string> & links_in, std::vector<std::string> & joints_in)
{
assert(links_in.size() == tree.getNrOfSegments());
assert(joints_in.size() == tree.getNrOfSegments()-1 || joints_in.size() == tree.getNrOfJoints() );
links = links_in;
if( joints_in.size() == tree.getNrOfSegments()-1 ) {
junctions = joints_in;
dofs = junctions;
dofs.resize(tree.getNrOfJoints());
} else {
dofs = joints_in;
junctions = dofs;
junctions.resize(tree.getNrOfSegments()-1);
int fixed_joints_cnt = 0;
SegmentMap::const_iterator root = tree.getRootSegment();
for( unsigned int i=0; i < root->second.children.size(); i++ ) {
addDFSrecursive_only_fixed(root->second.children[i],fixed_joints_cnt);
}
}
assert(this->is_consistent(tree));
}
TreeSerialization::TreeSerialization(const TreeSerialization& x)
{
links = std::vector<std::string>(0);
junctions = std::vector<std::string>(0);
dofs = std::vector<std::string>(0);
links = x.links;
junctions = x.junctions;
dofs = x.dofs;
}
int TreeSerialization::getJunctionId(std::string junction_name) const
{
std::vector<std::string>::const_iterator it;
it = std::find(junctions.begin(),junctions.end(),junction_name);
if( it != junctions.end() ) {
return it - junctions.begin();
} else {
return -1;
}
}
int TreeSerialization::getLinkId(std::string link_name) const
{
std::vector<std::string>::const_iterator it;
it = std::find(links.begin(),links.end(),link_name);
if( it != links.end() ) {
return it - links.begin();
} else {
return -1;
}
}
int TreeSerialization::getDOFId(std::string dof_name) const
{
std::vector<std::string>::const_iterator it;
it = std::find(dofs.begin(),dofs.end(),dof_name);
if( it != dofs.end() ) {
return it - dofs.begin();
} else {
return -1;
}
}
std::string TreeSerialization::getDOFName(int dof_id) const
{
return dofs[dof_id];
}
std::string TreeSerialization::getJunctionName(int junction_id) const
{
return junctions[junction_id];
}
std::string TreeSerialization::getLinkName(int link_id) const
{
return links[link_id];
}
bool TreeSerialization::is_consistent(const Tree & tree) const
{
SegmentMap::const_iterator seg;
SegmentMap::const_iterator root = tree.getRootSegment();
/** \todo remove this assumption */
assert(root->second.children.size() != 0);
SegmentMap::const_iterator root_child = root->second.children[0];
//This should be coherent with the behaviour of UndirectedTree
if( root->second.children.size() != 1 || root_child->second.segment.getJoint().getType() != Joint::None )
{
if( tree.getNrOfJoints() != dofs.size() || tree.getNrOfSegments()+1 != links.size() ) {
return false;
}
} else {
if( tree.getNrOfJoints() != dofs.size() || tree.getNrOfSegments() != links.size() ) {
return false;
}
}
unsigned int i;
const SegmentMap & seg_map = tree.getSegments();
for(i = 0; i < links.size(); i++ ) {
seg = tree.getSegment(links[i]);
if( seg == seg_map.end() ) {
return false;
}
}
for(SegmentMap::const_iterator it=seg_map.begin(); it != seg_map.end(); it++) {
if( it->second.segment.getJoint().getType() != Joint::None ) {
if( getJunctionId( it->second.segment.getJoint().getName()) == -1 ) {
return false;
}
}
}
return true;
}
int TreeSerialization::setNrOfLinks(const int new_size)
{
links.resize(new_size);
if( new_size > 0 ) {
junctions.resize(new_size-1);
} else {
junctions.resize(0);
}
return links.size();
}
int TreeSerialization::getNrOfLinks() const
{
return links.size();
}
int TreeSerialization::getNrOfJunctions() const
{
return junctions.size();
}
int TreeSerialization::setNrOfDOFs(const int new_size)
{
dofs.resize(new_size);
return dofs.size();
}
int TreeSerialization::getNrOfDOFs() const
{
return dofs.size();
}
std::string TreeSerialization::toString()
{
std::stringstream ss;
ss << "Links serialization:" << std::endl;
for( int i = 0; i < (int)links.size(); i++ ) {
ss << i << "\t: " << links[i] << std::endl;
}
ss << "Junctions serialization:" << std::endl;
for( int i = 0; i < (int)junctions.size(); i++ ) {
ss << i << "\t: " << junctions[i] << std::endl;
}
ss << "DOFs serialization:" << std::endl;
for( int i = 0; i < (int)dofs.size(); i++ ) {
ss << i << "\t: " << dofs[i] << std::endl;
}
return ss.str();
}
}
}
<|endoftext|> |
<commit_before>void build(Solution &s)
{
auto &tess = s.addProject("google.tesseract", "master");
tess += Git("https://github.com/tesseract-ocr/tesseract", "", "{v}");
auto cppstd = cpp17;
auto &libtesseract = tess.addTarget<LibraryTarget>("libtesseract");
{
libtesseract.setChecks("libtesseract");
libtesseract.ExportAllSymbols = true;
libtesseract.PackageDefinitions = true;
libtesseract += cppstd;
libtesseract += "include/.*"_rr;
libtesseract += "src/.*"_rr;
libtesseract -= "src/lstm/.*\\.cc"_rr;
libtesseract -= "src/training/.*"_rr;
libtesseract -=
"src/api/tesseractmain.cpp",
"src/viewer/svpaint.cpp";
libtesseract.Public += "include"_idir;
libtesseract.Protected +=
"src/opencl"_id,
"src/ccmain"_id,
"src/api"_id,
"src/dict"_id,
"src/viewer"_id,
"src/wordrec"_id,
"src/ccstruct"_id,
"src/cutil"_id,
"src/textord"_id,
"src/ccutil"_id,
"src/lstm"_id,
"src/classify"_id,
"src/arch"_id,
"src/training"_id;
if (libtesseract.getCompilerType() == CompilerType::MSVC ||
libtesseract.getCompilerType() == CompilerType::ClangCl)
{
libtesseract += "__SSE4_1__"_def;
libtesseract.CompileOptions.push_back("-arch:AVX2");
// openmp
//if (libtesseract.getOptions()["openmp"] == "true")
if (0)
{
if (libtesseract.getCompilerType() == CompilerType::MSVC)
libtesseract.CompileOptions.push_back("-openmp");
else
libtesseract.CompileOptions.push_back("-fopenmp");
libtesseract += "_OPENMP=201107"_def;
if (libtesseract.getBuildSettings().Native.ConfigurationType == ConfigurationType::Debug)
libtesseract += "vcompd.lib"_slib;
else
libtesseract += "vcomp.lib"_slib;
}
}
auto win_or_mingw =
libtesseract.getBuildSettings().TargetOS.Type == OSType::Windows ||
libtesseract.getBuildSettings().TargetOS.Type == OSType::Mingw
;
// check fma flags
libtesseract -= "src/arch/dotproductfma.cpp";
if (libtesseract.getBuildSettings().TargetOS.Type != OSType::Windows)
{
libtesseract["src/arch/dotproductavx.cpp"].args.push_back("-mavx");
libtesseract["src/arch/dotproductsse.cpp"].args.push_back("-msse4.1");
libtesseract["src/arch/intsimdmatrixsse.cpp"].args.push_back("-msse4.1");
libtesseract["src/arch/intsimdmatrixavx2.cpp"].args.push_back("-mavx2");
}
if (!win_or_mingw)
libtesseract += "pthread"_slib;
libtesseract.Public += "HAVE_CONFIG_H"_d;
libtesseract.Public += "_SILENCE_STDEXT_HASH_DEPRECATION_WARNINGS=1"_d;
libtesseract.Public += "HAVE_LIBARCHIVE"_d;
libtesseract.Interface += sw::Shared, "TESS_IMPORTS"_d;
libtesseract.Private += sw::Shared, "TESS_EXPORTS"_d;
libtesseract.Public += "org.sw.demo.danbloomberg.leptonica"_dep;
libtesseract.Public += "org.sw.demo.libarchive.libarchive"_dep;
if (win_or_mingw)
{
libtesseract.Public += "ws2_32.lib"_slib;
libtesseract.Protected += "NOMINMAX"_def;
}
libtesseract.Variables["TESSERACT_MAJOR_VERSION"] = libtesseract.Variables["PACKAGE_MAJOR_VERSION"];
libtesseract.Variables["TESSERACT_MINOR_VERSION"] = libtesseract.Variables["PACKAGE_MINOR_VERSION"];
libtesseract.Variables["TESSERACT_MICRO_VERSION"] = libtesseract.Variables["PACKAGE_PATCH_VERSION"];
libtesseract.Variables["TESSERACT_VERSION_STR"] = "master";
libtesseract.configureFile("include/tesseract/version.h.in", "tesseract/version.h");
}
//
auto &tesseract = tess.addExecutable("tesseract");
{
tesseract += cppstd;
tesseract += "src/api/tesseractmain.cpp";
tesseract += libtesseract;
}
//
auto &tessopt = tess.addStaticLibrary("tessopt");
{
tessopt += cppstd;
tessopt += "src/training/tessopt.*"_rr;
tessopt.Public += libtesseract;
}
//
auto &common_training = tess.addStaticLibrary("common_training");
{
common_training += cppstd;
common_training +=
"src/training/commandlineflags.cpp",
"src/training/commandlineflags.h",
"src/training/commontraining.cpp",
"src/training/commontraining.h",
"src/training/ctc.cpp",
"src/training/ctc.h",
"src/training/errorcounter.cpp",
"src/training/errorcounter.h",
"src/training/intfeaturedist.cpp",
"src/training/intfeaturedist.h",
"src/training/intfeaturemap.cpp",
"src/training/intfeaturemap.h",
"src/training/mastertrainer.cpp",
"src/training/mastertrainer.h",
"src/training/networkbuilder.cpp",
"src/training/networkbuilder.h",
"src/training/sampleiterator.cpp",
"src/training/sampleiterator.h",
"src/training/trainingsampleset.cpp",
"src/training/trainingsampleset.h";
common_training.Public += tessopt;
}
//
auto &unicharset_training = tess.addStaticLibrary("unicharset_training");
{
unicharset_training += cppstd;
unicharset_training +=
"src/training/fileio.*"_rr,
"src/training/icuerrorcode.*"_rr,
"src/training/icuerrorcode.h",
"src/training/lang_model_helpers.*"_rr,
"src/training/lstmtester.*"_rr,
"src/training/lstmtrainer.*"_rr,
"src/training/normstrngs.*"_rr,
"src/training/unicharset_training_utils.*"_rr,
"src/training/validat.*"_rr;
unicharset_training.Public += common_training;
unicharset_training.Public += "org.sw.demo.unicode.icu.i18n"_dep;
}
//
#define ADD_EXE(n, ...) \
auto &n = tess.addExecutable(#n); \
n += cppstd; \
n += "src/training/" #n ".*"_rr; \
n.Public += __VA_ARGS__; \
n
ADD_EXE(ambiguous_words, libtesseract);
ADD_EXE(classifier_tester, common_training);
ADD_EXE(combine_lang_model, unicharset_training);
ADD_EXE(combine_tessdata, libtesseract);
ADD_EXE(cntraining, common_training);
ADD_EXE(dawg2wordlist, libtesseract);
ADD_EXE(mftraining, common_training) += "src/training/mergenf.*"_rr;
ADD_EXE(shapeclustering, common_training);
ADD_EXE(unicharset_extractor, unicharset_training);
ADD_EXE(wordlist2dawg, libtesseract);
ADD_EXE(lstmeval, unicharset_training);
ADD_EXE(lstmtraining, unicharset_training);
ADD_EXE(set_unicharset_properties, unicharset_training);
ADD_EXE(merge_unicharsets, tessopt);
//
auto &pango_training = tess.addStaticLibrary("pango_training");
{
pango_training += cppstd;
pango_training +=
"src/training/boxchar.cpp",
"src/training/boxchar.h",
"src/training/ligature_table.cpp",
"src/training/ligature_table.h",
"src/training/pango_font_info.cpp",
"src/training/pango_font_info.h",
"src/training/stringrenderer.cpp",
"src/training/stringrenderer.h",
"src/training/tlog.cpp",
"src/training/tlog.h"
;
pango_training.Public += unicharset_training;
pango_training.Public += "org.sw.demo.gnome.pango.pangocairo"_dep;
}
ADD_EXE(text2image, pango_training);
{
text2image += cppstd;
text2image +=
"src/training/degradeimage.cpp",
"src/training/degradeimage.h",
"src/training/icuerrorcode.h",
"src/training/normstrngs.cpp",
"src/training/normstrngs.h",
"src/training/text2image.cpp",
"src/training/util.h"
;
}
auto &test = tess.addDirectory("test");
test.Scope = TargetScope::Test;
auto add_test = [&test, &s, &cppstd, &libtesseract, &pango_training](const String &name) -> decltype(auto)
{
auto &t = test.addTarget<ExecutableTarget>(name);
t += cppstd;
t += path("unittest/" + name + "_test.cc");
auto datadir = test.SourceDir / "tessdata_unittest";
t += Definition("TESSBIN_DIR=\"" + ""s + "\"");
t += Definition("TESTING_DIR=\"" + to_printable_string(normalize_path(test.SourceDir / "test/testing")) + "\"");
t += Definition("TESTDATA_DIR=\"" + to_printable_string(normalize_path(test.SourceDir / "test/testdata")) + "\"");
t += Definition("LANGDATA_DIR=\"" + to_printable_string(normalize_path(datadir / "langdata_lstm")) + "\"");
t += Definition("TESSDATA_DIR=\"" + to_printable_string(normalize_path(datadir / "tessdata")) + "\"");
t += Definition("TESSDATA_BEST_DIR=\"" + to_printable_string(normalize_path(datadir / "tessdata_best")) + "\"");
// we push all deps to all tests simplify things
t += pango_training;
t += "org.sw.demo.google.googletest.gmock.main"_dep;
t += "org.sw.demo.google.googletest.gtest.main"_dep;
t += "org.sw.demo.google.abseil"_dep;
if (t.getCompilerType() == CompilerType::MSVC)
t.CompileOptions.push_back("-utf-8");
libtesseract.addTest(t, name);
return t;
};
Strings tests{
"apiexample",
"applybox",
"baseapi",
"bitvector",
"cleanapi",
"colpartition",
"commandlineflags",
"dawg",
"denorm",
"equationdetect",
"fileio",
"heap",
"imagedata",
"indexmapbidi",
"intfeaturemap",
"intsimdmatrix",
"lang_model",
"layout",
"ligature_table",
"linlsq",
"lstm_recode",
"lstm_squashed",
"lstm",
"lstmtrainer",
"loadlang",
"mastertrainer",
"matrix",
"normstrngs",
"nthitem",
"osd",
"pagesegmode",
"pango_font_info",
"paragraphs",
"params_model",
"progress",
"qrsequence",
"recodebeam",
"rect",
"resultiterator",
"scanutils",
"shapetable",
"stats",
"stringrenderer",
"tablefind",
"tablerecog",
"tabvector",
"textlineprojection",
"tfile",
"unichar",
"unicharcompress",
"unicharset",
"validate_grapheme",
"validate_indic",
"validate_khmer",
"validate_myanmar",
"validator",
};
for (auto t : tests)
add_test(t);
}
void check(Checker &c)
{
auto &s = c.addSet("libtesseract");
s.checkFunctionExists("getline");
s.checkIncludeExists("dlfcn.h");
s.checkIncludeExists("inttypes.h");
s.checkIncludeExists("memory.h");
s.checkIncludeExists("stdint.h");
s.checkIncludeExists("stdlib.h");
s.checkIncludeExists("string.h");
s.checkIncludeExists("sys/stat.h");
s.checkIncludeExists("sys/types.h");
s.checkIncludeExists("tiffio.h");
s.checkIncludeExists("unistd.h");
s.checkTypeSize("long long int");
s.checkTypeSize("size_t");
s.checkTypeSize("void *");
s.checkTypeSize("wchar_t");
{
auto &c = s.checkSymbolExists("snprintf");
c.Parameters.Includes.push_back("stdio.h");
}
}
<commit_msg>Move training tools into their own dir.<commit_after>void build(Solution &s)
{
auto &tess = s.addProject("google.tesseract", "master");
tess += Git("https://github.com/tesseract-ocr/tesseract", "", "{v}");
auto cppstd = cpp17;
auto &libtesseract = tess.addTarget<LibraryTarget>("libtesseract");
{
libtesseract.setChecks("libtesseract");
libtesseract.ExportAllSymbols = true;
libtesseract.PackageDefinitions = true;
libtesseract += cppstd;
libtesseract += "include/.*"_rr;
libtesseract += "src/.*"_rr;
libtesseract -= "src/lstm/.*\\.cc"_rr;
libtesseract -= "src/training/.*"_rr;
libtesseract -=
"src/api/tesseractmain.cpp",
"src/viewer/svpaint.cpp";
libtesseract.Public += "include"_idir;
libtesseract.Protected +=
"src/opencl"_id,
"src/ccmain"_id,
"src/api"_id,
"src/dict"_id,
"src/viewer"_id,
"src/wordrec"_id,
"src/ccstruct"_id,
"src/cutil"_id,
"src/textord"_id,
"src/ccutil"_id,
"src/lstm"_id,
"src/classify"_id,
"src/arch"_id,
"src/training"_id;
if (libtesseract.getCompilerType() == CompilerType::MSVC ||
libtesseract.getCompilerType() == CompilerType::ClangCl)
{
libtesseract += "__SSE4_1__"_def;
libtesseract.CompileOptions.push_back("-arch:AVX2");
// openmp
//if (libtesseract.getOptions()["openmp"] == "true")
if (0)
{
if (libtesseract.getCompilerType() == CompilerType::MSVC)
libtesseract.CompileOptions.push_back("-openmp");
else
libtesseract.CompileOptions.push_back("-fopenmp");
libtesseract += "_OPENMP=201107"_def;
if (libtesseract.getBuildSettings().Native.ConfigurationType == ConfigurationType::Debug)
libtesseract += "vcompd.lib"_slib;
else
libtesseract += "vcomp.lib"_slib;
}
}
auto win_or_mingw =
libtesseract.getBuildSettings().TargetOS.Type == OSType::Windows ||
libtesseract.getBuildSettings().TargetOS.Type == OSType::Mingw
;
// check fma flags
libtesseract -= "src/arch/dotproductfma.cpp";
if (libtesseract.getBuildSettings().TargetOS.Type != OSType::Windows)
{
libtesseract["src/arch/dotproductavx.cpp"].args.push_back("-mavx");
libtesseract["src/arch/dotproductsse.cpp"].args.push_back("-msse4.1");
libtesseract["src/arch/intsimdmatrixsse.cpp"].args.push_back("-msse4.1");
libtesseract["src/arch/intsimdmatrixavx2.cpp"].args.push_back("-mavx2");
}
if (!win_or_mingw)
libtesseract += "pthread"_slib;
libtesseract.Public += "HAVE_CONFIG_H"_d;
libtesseract.Public += "_SILENCE_STDEXT_HASH_DEPRECATION_WARNINGS=1"_d;
libtesseract.Public += "HAVE_LIBARCHIVE"_d;
libtesseract.Interface += sw::Shared, "TESS_IMPORTS"_d;
libtesseract.Private += sw::Shared, "TESS_EXPORTS"_d;
libtesseract.Public += "org.sw.demo.danbloomberg.leptonica"_dep;
libtesseract.Public += "org.sw.demo.libarchive.libarchive"_dep;
if (win_or_mingw)
{
libtesseract.Public += "ws2_32.lib"_slib;
libtesseract.Protected += "NOMINMAX"_def;
}
libtesseract.Variables["TESSERACT_MAJOR_VERSION"] = libtesseract.Variables["PACKAGE_MAJOR_VERSION"];
libtesseract.Variables["TESSERACT_MINOR_VERSION"] = libtesseract.Variables["PACKAGE_MINOR_VERSION"];
libtesseract.Variables["TESSERACT_MICRO_VERSION"] = libtesseract.Variables["PACKAGE_PATCH_VERSION"];
libtesseract.Variables["TESSERACT_VERSION_STR"] = "master";
libtesseract.configureFile("include/tesseract/version.h.in", "tesseract/version.h");
}
//
auto &tesseract = tess.addExecutable("tesseract");
{
tesseract += cppstd;
tesseract += "src/api/tesseractmain.cpp";
tesseract += libtesseract;
}
auto &training = tess.addDirectory("training");
//
auto &tessopt = training.addStaticLibrary("tessopt");
{
tessopt += cppstd;
tessopt += "src/training/tessopt.*"_rr;
tessopt.Public += libtesseract;
}
//
auto &common_training = training.addStaticLibrary("common_training");
{
common_training += cppstd;
common_training +=
"src/training/commandlineflags.cpp",
"src/training/commandlineflags.h",
"src/training/commontraining.cpp",
"src/training/commontraining.h",
"src/training/ctc.cpp",
"src/training/ctc.h",
"src/training/errorcounter.cpp",
"src/training/errorcounter.h",
"src/training/intfeaturedist.cpp",
"src/training/intfeaturedist.h",
"src/training/intfeaturemap.cpp",
"src/training/intfeaturemap.h",
"src/training/mastertrainer.cpp",
"src/training/mastertrainer.h",
"src/training/networkbuilder.cpp",
"src/training/networkbuilder.h",
"src/training/sampleiterator.cpp",
"src/training/sampleiterator.h",
"src/training/trainingsampleset.cpp",
"src/training/trainingsampleset.h";
common_training.Public += tessopt;
}
//
auto &unicharset_training = training.addStaticLibrary("unicharset_training");
{
unicharset_training += cppstd;
unicharset_training +=
"src/training/fileio.*"_rr,
"src/training/icuerrorcode.*"_rr,
"src/training/icuerrorcode.h",
"src/training/lang_model_helpers.*"_rr,
"src/training/lstmtester.*"_rr,
"src/training/lstmtrainer.*"_rr,
"src/training/normstrngs.*"_rr,
"src/training/unicharset_training_utils.*"_rr,
"src/training/validat.*"_rr;
unicharset_training.Public += common_training;
unicharset_training.Public += "org.sw.demo.unicode.icu.i18n"_dep;
}
//
#define ADD_EXE(n, ...) \
auto &n = training.addExecutable(#n); \
n += cppstd; \
n += "src/training/" #n ".*"_rr; \
n.Public += __VA_ARGS__; \
n
ADD_EXE(ambiguous_words, libtesseract);
ADD_EXE(classifier_tester, common_training);
ADD_EXE(combine_lang_model, unicharset_training);
ADD_EXE(combine_tessdata, libtesseract);
ADD_EXE(cntraining, common_training);
ADD_EXE(dawg2wordlist, libtesseract);
ADD_EXE(mftraining, common_training) += "src/training/mergenf.*"_rr;
ADD_EXE(shapeclustering, common_training);
ADD_EXE(unicharset_extractor, unicharset_training);
ADD_EXE(wordlist2dawg, libtesseract);
ADD_EXE(lstmeval, unicharset_training);
ADD_EXE(lstmtraining, unicharset_training);
ADD_EXE(set_unicharset_properties, unicharset_training);
ADD_EXE(merge_unicharsets, tessopt);
//
auto &pango_training = training.addStaticLibrary("pango_training");
{
pango_training += cppstd;
pango_training +=
"src/training/boxchar.cpp",
"src/training/boxchar.h",
"src/training/ligature_table.cpp",
"src/training/ligature_table.h",
"src/training/pango_font_info.cpp",
"src/training/pango_font_info.h",
"src/training/stringrenderer.cpp",
"src/training/stringrenderer.h",
"src/training/tlog.cpp",
"src/training/tlog.h"
;
pango_training.Public += unicharset_training;
pango_training.Public += "org.sw.demo.gnome.pango.pangocairo"_dep;
}
ADD_EXE(text2image, pango_training);
{
text2image += cppstd;
text2image +=
"src/training/degradeimage.cpp",
"src/training/degradeimage.h",
"src/training/icuerrorcode.h",
"src/training/normstrngs.cpp",
"src/training/normstrngs.h",
"src/training/text2image.cpp",
"src/training/util.h"
;
}
auto &test = tess.addDirectory("test");
test.Scope = TargetScope::Test;
auto add_test = [&test, &s, &cppstd, &libtesseract, &pango_training](const String &name) -> decltype(auto)
{
auto &t = test.addTarget<ExecutableTarget>(name);
t += cppstd;
t += path("unittest/" + name + "_test.cc");
auto datadir = test.SourceDir / "tessdata_unittest";
t += Definition("TESSBIN_DIR=\"" + ""s + "\"");
t += Definition("TESTING_DIR=\"" + to_printable_string(normalize_path(test.SourceDir / "test/testing")) + "\"");
t += Definition("TESTDATA_DIR=\"" + to_printable_string(normalize_path(test.SourceDir / "test/testdata")) + "\"");
t += Definition("LANGDATA_DIR=\"" + to_printable_string(normalize_path(datadir / "langdata_lstm")) + "\"");
t += Definition("TESSDATA_DIR=\"" + to_printable_string(normalize_path(datadir / "tessdata")) + "\"");
t += Definition("TESSDATA_BEST_DIR=\"" + to_printable_string(normalize_path(datadir / "tessdata_best")) + "\"");
// we push all deps to all tests simplify things
t += pango_training;
t += "org.sw.demo.google.googletest.gmock.main"_dep;
t += "org.sw.demo.google.googletest.gtest.main"_dep;
t += "org.sw.demo.google.abseil"_dep;
if (t.getCompilerType() == CompilerType::MSVC)
t.CompileOptions.push_back("-utf-8");
libtesseract.addTest(t, name);
return t;
};
Strings tests{
"apiexample",
"applybox",
"baseapi",
"bitvector",
"cleanapi",
"colpartition",
"commandlineflags",
"dawg",
"denorm",
"equationdetect",
"fileio",
"heap",
"imagedata",
"indexmapbidi",
"intfeaturemap",
"intsimdmatrix",
"lang_model",
"layout",
"ligature_table",
"linlsq",
"lstm_recode",
"lstm_squashed",
"lstm",
"lstmtrainer",
"loadlang",
"mastertrainer",
"matrix",
"normstrngs",
"nthitem",
"osd",
"pagesegmode",
"pango_font_info",
"paragraphs",
"params_model",
"progress",
"qrsequence",
"recodebeam",
"rect",
"resultiterator",
"scanutils",
"shapetable",
"stats",
"stringrenderer",
"tablefind",
"tablerecog",
"tabvector",
"textlineprojection",
"tfile",
"unichar",
"unicharcompress",
"unicharset",
"validate_grapheme",
"validate_indic",
"validate_khmer",
"validate_myanmar",
"validator",
};
for (auto t : tests)
add_test(t);
}
void check(Checker &c)
{
auto &s = c.addSet("libtesseract");
s.checkFunctionExists("getline");
s.checkIncludeExists("dlfcn.h");
s.checkIncludeExists("inttypes.h");
s.checkIncludeExists("memory.h");
s.checkIncludeExists("stdint.h");
s.checkIncludeExists("stdlib.h");
s.checkIncludeExists("string.h");
s.checkIncludeExists("sys/stat.h");
s.checkIncludeExists("sys/types.h");
s.checkIncludeExists("tiffio.h");
s.checkIncludeExists("unistd.h");
s.checkTypeSize("long long int");
s.checkTypeSize("size_t");
s.checkTypeSize("void *");
s.checkTypeSize("wchar_t");
{
auto &c = s.checkSymbolExists("snprintf");
c.Parameters.Includes.push_back("stdio.h");
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cstdio>
using namespace std;
string replaceAll(string source, const string &target, const string &replacement)
{
string::size_type pos = 0;
while ((pos = source.find(target, pos)) != string::npos)
{
source.replace(pos, target.size(), replacement);
pos += replacement.size() > 0 ? replacement.size() : 1;
}
return source;
}
string fileNameFromPath(string path)
{
// This isn't really platform independent, but close enough...
path = replaceAll(path, "/", "\\");
return path.substr(path.rfind("\\") + 1);
}
string stripExtension(string file)
{
return file.substr(0, file.find("."));
}
string escapeSpecialChars(string input)
{
// Escape special characters in the string
input = replaceAll(input, "\\", "\\\\");
input = replaceAll(input, "\"", "\\\"");
input = replaceAll(input, "\t", "\\t");
return input;
}
void printUsage(string progname)
{
progname = fileNameFromPath(progname);
cout << "Usage: " << progname << " outfile infile0 [infile1 [infile 2 [...]]]" << endl;
cout << "Example: " << progname << " bla bla1.txt bla2.txt bla3.txt" << endl;
cout << "This will generate bla.h and bla.cpp with strings bla1, bla2 and bla3." << endl;
cout << endl;
}
int main(int argc, const char* argv[])
{
cout << "== TextToHeader v1.0 ==" << endl;
if (argc < 3)
{
cout << "Not enough args!" << endl;
printUsage(argv[0]);
return 1;
}
// Future proofing... we may want to add options later
if (argc > 1 && *argv[1] == (char)'-')
{
cout << "Options not supported!" << endl;
printUsage(argv[0]);
return 1;
}
// Parse command line
string outFileName = argv[1];
vector<string> inFileNames;
for (int i = 2; i < argc; ++i)
{
string arg = argv[i];
inFileNames.push_back(arg);
}
string headerFileName = outFileName + ".h";
string sourceFileName = outFileName + ".cpp";
ofstream header(headerFileName.c_str());
ofstream source(sourceFileName.c_str());
int res = 0;
// Generate header preamble
header
<< "#pragma once\n"
<< "// This file is generated automatically during the build process\n"
<< "// DO NOT MODIFY!\n"
<< "// Change the corresponding text files instead!\n"
<< "\n"
<< "namespace " << outFileName << "\n"
<< "{\n";
// Generate source preamble
source
<< "// This file is generated automatically during the build process\n"
<< "// DO NOT MODIFY!\n"
<< "// Change the corresponding text files instead!\n"
<< "\n"
<< "namespace " << outFileName << "\n"
<< "{\n";
// Process input files
for (vector<string>::const_iterator it = inFileNames.begin();
it != inFileNames.end() && res == 0; ++it)
{
string file = fileNameFromPath(*it);
cout << "\t" << file << endl;
// Generate header code
string varName = stripExtension(file);
header << "extern const char *" << varName << ";\n";
// Load the file and generate source code
source << "extern const char *" << varName << " = ";
string line;
ifstream inFile(it->c_str());
while (inFile.good())
{
getline(inFile, line);
line = escapeSpecialChars(line);
source << "\n\t\"" << line << "\\n\"";
}
if (inFile.fail() && !inFile.eof())
{
cerr << "Error reading " << *it << endl;
source << "\"\"";
res = 1;
}
inFile.close();
source << ";\n";
}
// Finish the file contents
header << "}\n";
source << "}\n";
header.close();
source.close();
if (res == 0)
{
cout << "Generated " << headerFileName << ", " << sourceFileName << endl;
}
else
{
// There was an error, remove the files
std::remove(headerFileName.c_str());
std::remove(sourceFileName.c_str());
}
cout << endl;
return res;
}
<commit_msg>File extension is determined by the last dot, not the first.<commit_after>#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cstdio>
using namespace std;
string replaceAll(string source, const string &target, const string &replacement)
{
string::size_type pos = 0;
while ((pos = source.find(target, pos)) != string::npos)
{
source.replace(pos, target.size(), replacement);
pos += replacement.size() > 0 ? replacement.size() : 1;
}
return source;
}
string fileNameFromPath(string path)
{
// This isn't really platform independent, but close enough...
path = replaceAll(path, "/", "\\");
return path.substr(path.rfind("\\") + 1);
}
string stripExtension(string file)
{
return file.substr(0, file.rfind("."));
}
string escapeSpecialChars(string input)
{
// Escape special characters in the string
input = replaceAll(input, "\\", "\\\\");
input = replaceAll(input, "\"", "\\\"");
input = replaceAll(input, "\t", "\\t");
return input;
}
void printUsage(string progname)
{
progname = fileNameFromPath(progname);
cout << "Usage: " << progname << " outfile infile0 [infile1 [infile 2 [...]]]" << endl;
cout << "Example: " << progname << " bla bla1.txt bla2.txt bla3.txt" << endl;
cout << "This will generate bla.h and bla.cpp with strings bla1, bla2 and bla3." << endl;
cout << endl;
}
int main(int argc, const char* argv[])
{
cout << "== TextToHeader v1.0 ==" << endl;
if (argc < 3)
{
cout << "Not enough args!" << endl;
printUsage(argv[0]);
return 1;
}
// Future proofing... we may want to add options later
if (argc > 1 && *argv[1] == (char)'-')
{
cout << "Options not supported!" << endl;
printUsage(argv[0]);
return 1;
}
// Parse command line
string outFileName = argv[1];
vector<string> inFileNames;
for (int i = 2; i < argc; ++i)
{
string arg = argv[i];
inFileNames.push_back(arg);
}
string headerFileName = outFileName + ".h";
string sourceFileName = outFileName + ".cpp";
ofstream header(headerFileName.c_str());
ofstream source(sourceFileName.c_str());
int res = 0;
// Generate header preamble
header
<< "#pragma once\n"
<< "// This file is generated automatically during the build process\n"
<< "// DO NOT MODIFY!\n"
<< "// Change the corresponding text files instead!\n"
<< "\n"
<< "namespace " << outFileName << "\n"
<< "{\n";
// Generate source preamble
source
<< "// This file is generated automatically during the build process\n"
<< "// DO NOT MODIFY!\n"
<< "// Change the corresponding text files instead!\n"
<< "\n"
<< "namespace " << outFileName << "\n"
<< "{\n";
// Process input files
for (vector<string>::const_iterator it = inFileNames.begin();
it != inFileNames.end() && res == 0; ++it)
{
string file = fileNameFromPath(*it);
cout << "\t" << file << endl;
// Generate header code
string varName = stripExtension(file);
header << "extern const char *" << varName << ";\n";
// Load the file and generate source code
source << "extern const char *" << varName << " = ";
string line;
ifstream inFile(it->c_str());
while (inFile.good())
{
getline(inFile, line);
line = escapeSpecialChars(line);
source << "\n\t\"" << line << "\\n\"";
}
if (inFile.fail() && !inFile.eof())
{
cerr << "Error reading " << *it << endl;
source << "\"\"";
res = 1;
}
inFile.close();
source << ";\n";
}
// Finish the file contents
header << "}\n";
source << "}\n";
header.close();
source.close();
if (res == 0)
{
cout << "Generated " << headerFileName << ", " << sourceFileName << endl;
}
else
{
// There was an error, remove the files
std::remove(headerFileName.c_str());
std::remove(sourceFileName.c_str());
}
cout << endl;
return res;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "paddle/fluid/jit/engine/pe_engine.h"
#include "paddle/fluid/framework/block_desc.h"
#include "paddle/fluid/framework/details/build_strategy.h"
#include "paddle/fluid/framework/details/execution_strategy.h"
#include "paddle/fluid/framework/ir/graph.h"
#include "paddle/fluid/framework/parallel_executor.h"
#include "paddle/fluid/framework/program_desc.h"
#include "paddle/phi/core/enforce.h"
namespace paddle {
namespace jit {
static ExecutionStrategy GetExecutionStrategy(const platform::Place &place) {
ExecutionStrategy execution_strategy;
auto device_type = platform::Place2DeviceType(place);
switch (device_type) {
case platform::DeviceType::CPU: {
execution_strategy.num_threads_ = 2;
break;
}
case platform::DeviceType::CUDA: {
// NOTE: According experiments, one thread is faster in
// most model training.
execution_strategy.num_threads_ = 1;
break;
}
case platform::DeviceType::XPU: {
execution_strategy.num_threads_ = 1;
break;
}
case platform::DeviceType::IPU: {
execution_strategy.num_threads_ = 1;
break;
}
default:
PADDLE_THROW(platform::errors::Unavailable("Unsupported Device type %d.",
device_type));
}
execution_strategy.use_device_ = device_type;
return execution_strategy;
}
PEEngine::PEEngine(const std::shared_ptr<FunctionInfo> &info,
const VariableMap ¶ms_dict,
const phi::Place &place)
: info_(info), place_(place) {
info_->RemoveDescFeedFetch();
PADDLE_ENFORCE_GT(
static_cast<int64_t>(info_->ProgramDesc().Block(0).OpSize()),
0,
platform::errors::PreconditionNotMet(
"There is no operator in ProgramDesc."));
utils::ShareParamsIntoScope(info_->ParamNames(), params_dict, &scope_);
VLOG(6) << framework::GenScopeTreeDebugInfo(&scope_);
CreateGraphAndPE();
}
void PEEngine::CreateGraphAndPE() {
framework::details::BuildStrategy build_strategy;
auto execution_strategy = GetExecutionStrategy(place_);
auto &program_desc = info_->ProgramDesc();
const framework::BlockDesc &global_block = program_desc.Block(0);
int64_t start_op_index = 0;
int64_t end_op_index = static_cast<int64_t>(global_block.OpSize());
graph_ = std::make_shared<Graph>(program_desc, start_op_index, end_op_index);
inner_pe_ = std::make_shared<ParallelExecutor>(
place_, &scope_, execution_strategy, build_strategy, graph_.get());
inner_pe_->PrepareVariables(&scope_);
inner_pe_->SkipMemoryReuse(/*scope_idx=*/0, info_->InputArgNames());
}
std::vector<Tensor> PEEngine::operator()(const std::vector<Tensor> &inputs) {
auto dense_tensors = utils::ToDenseTensors(inputs);
return utils::ToTensors(this->operator()(dense_tensors));
}
std::vector<DenseTensor> PEEngine::operator()(
const std::vector<DenseTensor> &inputs) {
utils::ShareIntoScope(info_->InputArgNames(), inputs, &scope_);
// update op_handle scope_map in pe->executor_->Graph
std::unordered_map<framework::Scope *, framework::Scope *> scope_map = {
{inner_pe_->GetLocalScopes().front(), &scope_}};
inner_pe_->ResetOpHandleScopeMapOfGraphs(scope_map);
// need to recreate tmp variables in new scope
inner_pe_->PrepareVariables(&scope_);
inner_pe_->RunWithoutFetch(info_->OutputArgNames());
std::vector<DenseTensor> outputs;
utils::FetchOuts(info_->OutputArgNames(), scope_, &outputs);
scope_.DropKids();
return outputs;
}
const std::shared_ptr<FunctionInfo> &PEEngine::Info() const { return info_; }
} // namespace jit
} // namespace paddle
<commit_msg>Modify PE Engine thread from 2 into 1 in JitLayer (#45356)<commit_after>// Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "paddle/fluid/jit/engine/pe_engine.h"
#include "paddle/fluid/framework/block_desc.h"
#include "paddle/fluid/framework/details/build_strategy.h"
#include "paddle/fluid/framework/details/execution_strategy.h"
#include "paddle/fluid/framework/ir/graph.h"
#include "paddle/fluid/framework/parallel_executor.h"
#include "paddle/fluid/framework/program_desc.h"
#include "paddle/phi/core/enforce.h"
namespace paddle {
namespace jit {
static ExecutionStrategy GetExecutionStrategy(const platform::Place &place) {
ExecutionStrategy execution_strategy;
auto device_type = platform::Place2DeviceType(place);
switch (device_type) {
case platform::DeviceType::CPU: {
execution_strategy.num_threads_ = 1;
break;
}
case platform::DeviceType::CUDA: {
// NOTE: According experiments, one thread is faster in
// most model training.
execution_strategy.num_threads_ = 1;
break;
}
case platform::DeviceType::XPU: {
execution_strategy.num_threads_ = 1;
break;
}
case platform::DeviceType::IPU: {
execution_strategy.num_threads_ = 1;
break;
}
default:
PADDLE_THROW(platform::errors::Unavailable("Unsupported Device type %d.",
device_type));
}
execution_strategy.use_device_ = device_type;
return execution_strategy;
}
PEEngine::PEEngine(const std::shared_ptr<FunctionInfo> &info,
const VariableMap ¶ms_dict,
const phi::Place &place)
: info_(info), place_(place) {
info_->RemoveDescFeedFetch();
PADDLE_ENFORCE_GT(
static_cast<int64_t>(info_->ProgramDesc().Block(0).OpSize()),
0,
platform::errors::PreconditionNotMet(
"There is no operator in ProgramDesc."));
utils::ShareParamsIntoScope(info_->ParamNames(), params_dict, &scope_);
VLOG(6) << framework::GenScopeTreeDebugInfo(&scope_);
CreateGraphAndPE();
}
void PEEngine::CreateGraphAndPE() {
framework::details::BuildStrategy build_strategy;
auto execution_strategy = GetExecutionStrategy(place_);
auto &program_desc = info_->ProgramDesc();
const framework::BlockDesc &global_block = program_desc.Block(0);
int64_t start_op_index = 0;
int64_t end_op_index = static_cast<int64_t>(global_block.OpSize());
graph_ = std::make_shared<Graph>(program_desc, start_op_index, end_op_index);
inner_pe_ = std::make_shared<ParallelExecutor>(
place_, &scope_, execution_strategy, build_strategy, graph_.get());
inner_pe_->PrepareVariables(&scope_);
inner_pe_->SkipMemoryReuse(/*scope_idx=*/0, info_->InputArgNames());
}
std::vector<Tensor> PEEngine::operator()(const std::vector<Tensor> &inputs) {
auto dense_tensors = utils::ToDenseTensors(inputs);
return utils::ToTensors(this->operator()(dense_tensors));
}
std::vector<DenseTensor> PEEngine::operator()(
const std::vector<DenseTensor> &inputs) {
utils::ShareIntoScope(info_->InputArgNames(), inputs, &scope_);
// update op_handle scope_map in pe->executor_->Graph
std::unordered_map<framework::Scope *, framework::Scope *> scope_map = {
{inner_pe_->GetLocalScopes().front(), &scope_}};
inner_pe_->ResetOpHandleScopeMapOfGraphs(scope_map);
// need to recreate tmp variables in new scope
inner_pe_->PrepareVariables(&scope_);
inner_pe_->RunWithoutFetch(info_->OutputArgNames());
std::vector<DenseTensor> outputs;
utils::FetchOuts(info_->OutputArgNames(), scope_, &outputs);
scope_.DropKids();
return outputs;
}
const std::shared_ptr<FunctionInfo> &PEEngine::Info() const { return info_; }
} // namespace jit
} // namespace paddle
<|endoftext|> |
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbImageViewerManager.h"
int main(int argc, char* argv[])
{
try
{
typedef double PixelType;
typedef otb::ImageViewerManager<PixelType> ManagerType;
ManagerType::Pointer manager = ManagerType::New();
manager->Show();
return Fl::run();
}
catch( itk::ExceptionObject & err )
{
std::cout << "Following otbException catch :" << std::endl;
std::cout << err << std::endl;
return EXIT_FAILURE;
}
catch( std::bad_alloc & err )
{
std::cout << "Exception bad_alloc : "<<(char*)err.what()<< std::endl;
return EXIT_FAILURE;
}
catch( ... )
{
std::cout << "Unknown Exception found !" << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>Corrections mineures GDALImageIO, et évolution ViewerManager<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbImageViewerManager.h"
int main(int argc, char* argv[])
{
try
{
typedef double PixelType;
typedef otb::ImageViewerManager<PixelType> ManagerType;
ManagerType::Pointer manager = ManagerType::New();
manager->Show();
for(int i = 1; i<argc;++i)
{
manager->OpenImage(argv[i]);
Fl::check();
}
return Fl::run();
}
catch( itk::ExceptionObject & err )
{
std::cout << "Following otbException catch :" << std::endl;
std::cout << err << std::endl;
return EXIT_FAILURE;
}
catch( std::bad_alloc & err )
{
std::cout << "Exception bad_alloc : "<<(char*)err.what()<< std::endl;
return EXIT_FAILURE;
}
catch( ... )
{
std::cout << "Unknown Exception found !" << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>// Filename: config_pnmtext.cxx
// Created by: drose (08Sep03)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) Carnegie Mellon University. All rights reserved.
//
// All use of this software is subject to the terms of the revised BSD
// license. You should have received a copy of this license along
// with this source code in a file named "LICENSE."
//
////////////////////////////////////////////////////////////////////
#include "config_pnmtext.h"
#include "dconfig.h"
Configure(config_pnmtext);
NotifyCategoryDef(pnmtext, "");
ConfigureFn(config_pnmtext) {
init_libpnmtext();
}
ConfigVariableDouble text_point_size
("text-point-size", 10.0f);
ConfigVariableDouble text_pixels_per_unit
("text-pixels-per-unit", 30.0f);
ConfigVariableDouble text_scale_factor
("text-scale-factor", 2.0f);
ConfigVariableBool text_native_antialias
("text-native-antialias", true);
////////////////////////////////////////////////////////////////////
// Function: init_libpnmtext
// Description: Initializes the library. This must be called at
// least once before any of the functions or classes in
// this library can be used. Normally it will be
// called by the static initializers and need not be
// called explicitly, but special cases exist.
////////////////////////////////////////////////////////////////////
void
init_libpnmtext() {
static bool initialized = false;
if (initialized) {
return;
}
initialized = true;
}
<commit_msg>FreetypeFace::init_type()<commit_after>// Filename: config_pnmtext.cxx
// Created by: drose (08Sep03)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) Carnegie Mellon University. All rights reserved.
//
// All use of this software is subject to the terms of the revised BSD
// license. You should have received a copy of this license along
// with this source code in a file named "LICENSE."
//
////////////////////////////////////////////////////////////////////
#include "config_pnmtext.h"
#include "dconfig.h"
#include "freetypeFace.h"
Configure(config_pnmtext);
NotifyCategoryDef(pnmtext, "");
ConfigureFn(config_pnmtext) {
init_libpnmtext();
}
ConfigVariableDouble text_point_size
("text-point-size", 10.0f);
ConfigVariableDouble text_pixels_per_unit
("text-pixels-per-unit", 30.0f);
ConfigVariableDouble text_scale_factor
("text-scale-factor", 2.0f);
ConfigVariableBool text_native_antialias
("text-native-antialias", true);
////////////////////////////////////////////////////////////////////
// Function: init_libpnmtext
// Description: Initializes the library. This must be called at
// least once before any of the functions or classes in
// this library can be used. Normally it will be
// called by the static initializers and need not be
// called explicitly, but special cases exist.
////////////////////////////////////////////////////////////////////
void
init_libpnmtext() {
static bool initialized = false;
if (initialized) {
return;
}
initialized = true;
FreetypeFace::init_type();
}
<|endoftext|> |
<commit_before>//2014.03.18 - 2014.03.19 Gustaf - CTG.
/* P R O B L E M : V A R I A B L E - L E N G T H S T R I N G M A N I P U L A T I O N
Write heap-based implementations for three required string functions:
- append
This function takes a string and a character and appends the character
to the end of the string.
- concatenate
This function takes two strings and appends the characters of the
second string onto the first.
- characterAt
This function takes a string and a number and returns the character
at that position in the string (with the first character in the string numbered zero).
Write the code with the assumption that characterAt will be called frequently,
while the other two functions will be called relatively seldom. The relative efficiency of
the operations should reflect the calling frequency.
=== PLAN ===
-
-
*/
#include <iostream>
using namespace std;
// We know we’re going to be dynamically creating our arrays,
// so we need to make our string type a pointer to char.
typedef char *arrayString;
int length(arrayString s)
{
// Determine the length of a string array.
int count = 0;
while (s[count] != 0) // not includes the "null terminator".
{
count++;
}
return count;
}
char characterAt(arrayString s, int position)
{
// NOTICE: Recall from Chapter 3 that if a pointer is assigned the address of an array,
// we can access elements in the array using normal array notation
return s[position];
}
void append(arrayString &s, char c)
{
// NOTICE: The arrayString parameter had to be a reference (&)
// because the function is going to create a new array in the heap.
int oldLength = length(s);
// NOW "oldLength" has the number of legitimate characters in the array
// (not including the terminating null character).
// new array allocated.
// +2 is the additional space for the "appended character" and the "null terminator".
arrayString newS = new char[oldLength + 2];
// copy all of the legitimate characters from the old array to the new.
for (int i = 0; i < oldLength; i++)
{
newS[i] = s[i];
}
newS[oldLength] = c; // "appended character"
newS[oldLength + 1] = 0; // "null terminator"
// To avoid a memory leak, we have to deallocate the array in the heap
// that our parameter s originally pointed to.
delete[] s;
s = newS;
}
void appendTester()
{
// WARNING: Every time you use the keyword "new", think about where and when
// the corresponding "delete" will occur.
//
// NOTICE: In this case the "delete" will happen inside the "append" function
// that will be called later.
arrayString a = new char[5];
a[0] = 't'; a[1] = 'e'; a[2] = 's'; a[3] = 't'; a[4] = 0;
append(a, '!');
cout << a << endl;
// ---
arrayString b = new char[1];
b[0] = 0;
append(b, '!');
cout << b << endl;
}
int main()
{
cout << "Variable-Length String Manipulation." << endl;
appendTester();
cout << endl;
return 0;
}
<commit_msg>Chapter 04 examples. End example of string manipulations with pointers<commit_after>//2014.03.18 - 2014.03.19 - 2014.03.20 Gustaf - CTG.
/* P R O B L E M : V A R I A B L E - L E N G T H S T R I N G M A N I P U L A T I O N
Write heap-based implementations for three required string functions:
- append
This function takes a string and a character and appends the character
to the end of the string.
- concatenate
This function takes two strings and appends the characters of the
second string onto the first.
- characterAt
This function takes a string and a number and returns the character
at that position in the string (with the first character in the string numbered zero).
Write the code with the assumption that characterAt will be called frequently,
while the other two functions will be called relatively seldom. The relative efficiency of
the operations should reflect the calling frequency.
=== PLAN ===
-
-
*/
#include <iostream>
using namespace std;
// We know we’re going to be dynamically creating our arrays,
// so we need to make our string type a pointer to char.
typedef char *arrayString;
int length(arrayString s)
{
// Determine the length of a string array.
int count = 0;
while (s[count] != 0) // not includes the "null terminator".
{
count++;
}
return count;
}
char characterAt(arrayString s, int position)
{
// NOTICE: Recall from Chapter 3 that if a pointer is assigned the address of an array,
// we can access elements in the array using normal array notation
return s[position];
// WARNING: this code places the responsibility of validating
// the second parameter on the caller.
}
void append(arrayString &s, char c)
{
// NOTICE: The arrayString parameter had to be a reference (&)
// because the function is going to create a new array in the heap.
int oldLength = length(s);
// NOW "oldLength" has the number of legitimate characters in the array
// (not including the terminating null character).
// new array allocated.
// +2 is the additional space for the "appended character" and the "null terminator".
arrayString newS = new char[oldLength + 2];
// copy all of the legitimate characters from the old array to the new.
for (int i = 0; i < oldLength; i++)
{
newS[i] = s[i];
}
newS[oldLength] = c; // "appended character"
newS[oldLength + 1] = 0; // "null terminator" at the end.
// To avoid a memory leak, we have to deallocate the array in the heap
// that our parameter s originally pointed to.
delete[] s;
s = newS;
}
void appendTester()
{
// WARNING: Every time you use the keyword "new", think about where and when
// the corresponding "delete" will occur.
//
// NOTICE: In this case the "delete" will happen inside the "append" function
// that will be called later.
arrayString a = new char[5];
a[0] = 't'; a[1] = 'e'; a[2] = 's'; a[3] = 't'; a[4] = 0;
append(a, '!');
cout << a << endl;
// ---
arrayString b = new char[1];
b[0] = 0;
append(b, '!');
cout << b << endl;
}
void concatenate(arrayString &s1, arrayString s2)
{
int s1_OldLength = length(s1);
int s2_Length = length(s2);
int s1_NewLength = s1_OldLength + s2_Length;
arrayString newS = new char[s1_NewLength + 1]; // additional space for the "null terminator".
// copy the characters from the two original strings to the new string.
for (int i = 0; i < s1_OldLength; i++)
{
newS[i] = s1[i];
}
for (int i = 0; i < s2_Length; i++)
{
newS[s1_OldLength + i] = s2[i];
}
newS[s1_NewLength] = 0; // "null terminator" at the end.
// To avoid a memory leak, we have to deallocate the array in the heap
// that our parameter s1 originally pointed to.
delete[] s1;
s1 = newS; // repoint the first parameter at the newly allocated string.
}
void concatenateTester()
{
arrayString a = new char[5];
a[0] = 't'; a[1] = 'e'; a[2] = 's'; a[3] = 't'; a[4] = 0;
arrayString b = new char[4];
b[0] = 'b'; b[1] = 'e'; b[2] = 'd'; b[3] = 0;
concatenate(a, b);
cout << a << endl;
// ---
arrayString c = new char[5];
c[0] = 't'; c[1] = 'e'; c[2] = 's'; c[3] = 't'; c[4] = 0;
arrayString d = new char[1];
d[0] = 0;
concatenate(d, c);
cout << c << endl << d << endl;
// forces the output stream to display the raw value of the pointers.
cout << (void *) c << endl << (void *) d << endl;
}
int main()
{
cout << "Variable-Length String Manipulation." << endl;
appendTester();
concatenateTester();
cout << endl;
return 0;
}
<|endoftext|> |
<commit_before>#include "docktoolbar.h"
#include "documentmanager.h"
#include "filebrowserwindow.h"
#include "filebrowserwidget.h"
#include "mainwindow.h"
#include "onefieldwindow.h"
#include "utils.h"
#include "ui_filebrowserwindow.h"
#include <QDir>
#include <QFileInfo>
#include <QMenu>
#include <QMessageBox>
static const QString SettingsFileBrowserWindow = "FileBrowserWindow";
FileBrowserWindow::FileBrowserWindow(MainWindow *pParent) :
DockWidget(pParent),
mUi(new Ui::FileBrowserWindow),
mPrevFolder(),
mKeepTrackOfPrevFolder(true)
{
// Set up the UI
mUi->setupUi(this);
// Retrieve the document manager from our parent which is the main window
mDocumentManager = pParent->documentManager();
// Create a dropdown menu for the New action
QMenu *actionNewMenu = new QMenu(this);
actionNewMenu->addAction(mUi->actionNewFolder);
actionNewMenu->addSeparator();
actionNewMenu->addAction(mUi->actionNewCellML10File);
actionNewMenu->addAction(mUi->actionNewCellML11File);
mUi->actionNew->setMenu(actionNewMenu);
// Create a toolbar with different buttons
// Note: this sadly can't be done using the design mode, so...
DockToolBar *toolbar = new DockToolBar(this);
toolbar->addAction(mUi->actionHome);
toolbar->addSeparator();
toolbar->addAction(mUi->actionParent);
toolbar->addSeparator();
toolbar->addAction(mUi->actionPrevious);
toolbar->addAction(mUi->actionNext);
toolbar->addSeparator();
toolbar->addAction(mUi->actionNew);
toolbar->addAction(mUi->actionDelete);
mUi->verticalLayout->addWidget(toolbar);
// Create and add the file browser widget
// Note: we let the widget know that we want our own custom context menu
mFileBrowserWidget = new FileBrowserWidget(this);
mUi->verticalLayout->addWidget(mFileBrowserWidget);
// We want our own context menu for the file browser widget
mFileBrowserWidget->setContextMenuPolicy(Qt::CustomContextMenu);
// Prevent objects from being dropped on the file browser widget
mFileBrowserWidget->setAcceptDrops(false);
// Some connections
connect(mFileBrowserWidget, SIGNAL(customContextMenuRequested(const QPoint &)),
this, SLOT(customContextMenu(const QPoint &)));
connect(mFileBrowserWidget->selectionModel(), SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)),
this, SLOT(currentItemChanged(const QModelIndex &, const QModelIndex &)));
connect(mFileBrowserWidget, SIGNAL(expanded(const QModelIndex &)),
this, SLOT(needUpdateActions()));
connect(mFileBrowserWidget, SIGNAL(collapsed(const QModelIndex &)),
this, SLOT(needUpdateActions()));
}
FileBrowserWindow::~FileBrowserWindow()
{
// Delete the UI
delete mUi;
}
void FileBrowserWindow::updateActions()
{
// Make sure that the various actions are properly enabled/disabled
mUi->actionHome->setEnabled( (mFileBrowserWidget->currentPath() != mFileBrowserWidget->homeFolder())
|| ( (mFileBrowserWidget->currentPath() == mFileBrowserWidget->homeFolder())
&& !mFileBrowserWidget->isCurrentPathVisible()));
mUi->actionParent->setEnabled(mFileBrowserWidget->currentPathParent() != "");
mUi->actionPrevious->setEnabled(mPrevFolders.count());
mUi->actionNext->setEnabled(mNextFolders.count());
mUi->actionNew->setEnabled(mFileBrowserWidget->isCurrentPathDirWritable());
mUi->actionDelete->setEnabled(mFileBrowserWidget->isCurrentPathWritable());
}
void FileBrowserWindow::retranslateUi()
{
// Translate the whole window
mUi->retranslateUi(this);
// Make sure that the enabled state of the various actions is correct
// (indeed, to translate everything messes things up in that respect,
// so...)
updateActions();
// Retranslate the file browser widget
mFileBrowserWidget->retranslateUi();
}
void FileBrowserWindow::loadSettings(const QSettings &pSettings,
const QString &)
{
// Retrieve the settings of the file browser widget
// Note: we must make sure that we don't keep track of the previous folder
mKeepTrackOfPrevFolder = false;
mFileBrowserWidget->loadSettings(pSettings, SettingsFileBrowserWindow);
mKeepTrackOfPrevFolder = true;
// Initialise the previous folder information
mPrevFolder = mFileBrowserWidget->currentPathDir();
// Make sure that the current path is expanded
// Note: this is important in case the current path is that of the C:\ drive
// or the root of the file system which during the loadSettings above
// won't trigger a directoryLoaded signal in the file browser widget
if (!mFileBrowserWidget->isExpanded(mFileBrowserWidget->currentIndex()))
mFileBrowserWidget->setExpanded(mFileBrowserWidget->currentIndex(), true);
}
void FileBrowserWindow::saveSettings(QSettings &pSettings, const QString &)
{
// Keep track of the settings of the file browser widget
mFileBrowserWidget->saveSettings(pSettings, SettingsFileBrowserWindow);
}
void FileBrowserWindow::customContextMenu(const QPoint &)
{
// Create a custom context menu which items match the contents of our
// toolbar
QMenu menu;
menu.addAction(mUi->actionHome);
menu.addSeparator();
menu.addAction(mUi->actionParent);
menu.addSeparator();
menu.addAction(mUi->actionPrevious);
menu.addAction(mUi->actionNext);
menu.addSeparator();
menu.addAction(mUi->actionNew);
menu.addAction(mUi->actionDelete);
menu.exec(QCursor::pos());
}
void FileBrowserWindow::needUpdateActions()
{
// Something related to the help widget requires the actions to be udpated
updateActions();
}
void FileBrowserWindow::currentItemChanged(const QModelIndex &,
const QModelIndex &)
{
if (!mKeepTrackOfPrevFolder)
// We don't want to keep track of the previous folder, so...
return;
// A new item has been selected, so we need to keep track of the old one in
// case we want to go back to it
// Retrieve the full path to the folder where the current item is located
QString crtItemDir = mFileBrowserWidget->currentPathDir();
// Check whether there is a previous folder to keep track of
// Note: to do so, we cannot rely on the previous item (i.e. the second
// parameter to this function), since both the current and previous
// items might be located in the same folder, so...
if (crtItemDir != mPrevFolder) {
// There is a previous folder to keep track of, so add it to our list of
// previous folders and consider the current folder as our future
// previous folder
mPrevFolders.append(mPrevFolder);
mPrevFolder = crtItemDir;
// Reset the list of next folders since that list doesn't make sense
// anymore
mNextFolders.clear();
}
// Since a new item has been selected, we must update the actions
updateActions();
}
void FileBrowserWindow::on_actionHome_triggered()
{
// Go to the home folder (and ask for it to be expanded)
mFileBrowserWidget->gotoHomeFolder(true);
}
void FileBrowserWindow::on_actionParent_triggered()
{
// Go to the parent folder
mFileBrowserWidget->gotoPath(mFileBrowserWidget->currentPathParent());
// Going to the parent folder may have changed some actions, so...
updateActions();
}
void FileBrowserWindow::on_actionPrevious_triggered()
{
// Go to the previous folder and move the last item from our list of
// previous folders to our list of next folders
// Note: we must make sure that we don't keep track of the previous folder
mNextFolders.append(mFileBrowserWidget->currentPath());
mKeepTrackOfPrevFolder = false;
mFileBrowserWidget->gotoPath(mPrevFolders.last());
mKeepTrackOfPrevFolder = true;
mPrevFolders.removeLast();
// Going to the previous folder may have changed some actions, so...
updateActions();
}
void FileBrowserWindow::on_actionNext_triggered()
{
// Go to the next folder and move the last item from our list of next
// folders to our list of previous folders
// Note: we must make sure that we don't keep track of the previous folder
mPrevFolders.append(mFileBrowserWidget->currentPath());
mKeepTrackOfPrevFolder = false;
mFileBrowserWidget->gotoPath(mNextFolders.last());
mKeepTrackOfPrevFolder = true;
mNextFolders.removeLast();
// Going to the next folder may have changed some actions, so...
updateActions();
}
void FileBrowserWindow::on_actionNew_triggered()
{
// The default new action is about creating a new folder, so...
on_actionNewFolder_triggered();
}
static QString FolderFileNameRegExp = "[^\\/:*?\"<>|]+";
void FileBrowserWindow::on_actionNewFolder_triggered()
{
// Get the name of the new folder
OneFieldWindow oneFieldWindow(tr("New Folder"), tr("Folder name:"),
tr("Please provide a name for the new folder."),
FolderFileNameRegExp, this);
oneFieldWindow.exec();
// Create the new folder in the current folder unless the user cancelled the
// action
if (oneFieldWindow.result() == QDialog::Accepted) {
QString folderName = mFileBrowserWidget->currentPathDir()
+QDir::separator()+oneFieldWindow.fieldValue();
if (QDir(folderName).exists()) {
// The folder already exists, so...
QMessageBox::information(this, qApp->applicationName(),
tr("Sorry, but the <strong>%1</strong> folder already exists.").arg(oneFieldWindow.fieldValue()));
} else {
// The folder doesn't already exist, so try to create it
if (QDir(mFileBrowserWidget->currentPathDir()).mkdir(oneFieldWindow.fieldValue()))
// The folder was created, so select it
mFileBrowserWidget->gotoPath(folderName, true);
else
// The folder couldn't be created, so...
QMessageBox::information(this, qApp->applicationName(),
tr("Sorry, but the <strong>%1</strong> folder could not be created.").arg(oneFieldWindow.fieldValue()));
}
}
}
void FileBrowserWindow::newCellmlFile(const CellmlVersion &pCellmlVersion)
{
// Get the name of the new CellML file
QString cellmlVersion = cellmlVersionString(pCellmlVersion);
OneFieldWindow oneFieldWindow(tr("New CellML %1 File").arg(cellmlVersion), tr("Model name:"),
tr("Please provide a name for the new CellML %1 model.").arg(cellmlVersion),
FolderFileNameRegExp, this);
oneFieldWindow.exec();
// Create the new CellML file in the current folder unless the user
// cancelled the action
if (oneFieldWindow.result() == QDialog::Accepted) {
QString cellmlFileName = mFileBrowserWidget->currentPathDir()
+QDir::separator()+oneFieldWindow.fieldValue()
+CellmlFileExtension;
if (QFileInfo(cellmlFileName).exists()) {
// The CellML file already exists, so...
QMessageBox::information(this, qApp->applicationName(),
tr("Sorry, but the <strong>%1</strong> file already exists.").arg(oneFieldWindow.fieldValue()));
} else {
// The CellML file doesn't already exist, so try to create it
if (::newCellmlFile(cellmlFileName, oneFieldWindow.fieldValue(),
pCellmlVersion)) {
// The CellML file was created, so select it
mFileBrowserWidget->gotoPath(cellmlFileName, true);
// Have the new CellML file managed
mDocumentManager->manage(cellmlFileName);
} else {
// The CellML file couldn't be created, so...
QMessageBox::information(this, qApp->applicationName(),
tr("Sorry, but the <strong>%1</strong> file could not be created.").arg(oneFieldWindow.fieldValue()));
}
}
}
}
void FileBrowserWindow::on_actionNewCellML10File_triggered()
{
newCellmlFile(Cellml_1_0);
}
void FileBrowserWindow::on_actionNewCellML11File_triggered()
{
newCellmlFile(Cellml_1_1);
}
void FileBrowserWindow::on_actionDelete_triggered()
{
// Delete the current folder/file
QString path = mFileBrowserWidget->currentPath();
QFileInfo pathFileInfo = path;
QString pathFileName = pathFileInfo.fileName();
if (!pathFileName.isEmpty()) {
// We are not at the root of the file system, so we can ask to delete
// the folder/file
bool isPathDir = pathFileInfo.isDir();
if( QMessageBox::question(this, qApp->applicationName(),
isPathDir?
tr("Do you really want to delete the <strong>%1</strong> folder?").arg(pathFileName):
tr("Do you really want to delete the <strong>%1</strong> file?").arg(pathFileName),
QMessageBox::Yes|QMessageBox::No,
QMessageBox::Yes) == QMessageBox::Yes ) {
// The user really wants to delete the folder/file, so...
if (removePath(path))
// The folder/file has been removed, so now make sure that the
// newly selected entry is visible
mFileBrowserWidget->gotoPath(mFileBrowserWidget->currentPath());
else
// The folder/file couldn't be removed, so let the user know
// about it
// Note: we should never reach this point in the case of a file,
// since the action is only triggerable if the file is
// writable (and therefore deletable), but still... better
// be safe than 'sorry'...
QMessageBox::information(this, qApp->applicationName(),
isPathDir?
tr("Sorry, but the <strong>%1</strong> folder could not be deleted.").arg(pathFileName):
tr("Sorry, but the <strong>%1</strong> file could not be deleted.").arg(pathFileName));
}
}
}
<commit_msg>Minor fix to the creation of a CellML file (not quite the right information was being displayed when trying to create a CellML file that already existed).<commit_after>#include "docktoolbar.h"
#include "documentmanager.h"
#include "filebrowserwindow.h"
#include "filebrowserwidget.h"
#include "mainwindow.h"
#include "onefieldwindow.h"
#include "utils.h"
#include "ui_filebrowserwindow.h"
#include <QDir>
#include <QFileInfo>
#include <QMenu>
#include <QMessageBox>
static const QString SettingsFileBrowserWindow = "FileBrowserWindow";
FileBrowserWindow::FileBrowserWindow(MainWindow *pParent) :
DockWidget(pParent),
mUi(new Ui::FileBrowserWindow),
mPrevFolder(),
mKeepTrackOfPrevFolder(true)
{
// Set up the UI
mUi->setupUi(this);
// Retrieve the document manager from our parent which is the main window
mDocumentManager = pParent->documentManager();
// Create a dropdown menu for the New action
QMenu *actionNewMenu = new QMenu(this);
actionNewMenu->addAction(mUi->actionNewFolder);
actionNewMenu->addSeparator();
actionNewMenu->addAction(mUi->actionNewCellML10File);
actionNewMenu->addAction(mUi->actionNewCellML11File);
mUi->actionNew->setMenu(actionNewMenu);
// Create a toolbar with different buttons
// Note: this sadly can't be done using the design mode, so...
DockToolBar *toolbar = new DockToolBar(this);
toolbar->addAction(mUi->actionHome);
toolbar->addSeparator();
toolbar->addAction(mUi->actionParent);
toolbar->addSeparator();
toolbar->addAction(mUi->actionPrevious);
toolbar->addAction(mUi->actionNext);
toolbar->addSeparator();
toolbar->addAction(mUi->actionNew);
toolbar->addAction(mUi->actionDelete);
mUi->verticalLayout->addWidget(toolbar);
// Create and add the file browser widget
// Note: we let the widget know that we want our own custom context menu
mFileBrowserWidget = new FileBrowserWidget(this);
mUi->verticalLayout->addWidget(mFileBrowserWidget);
// We want our own context menu for the file browser widget
mFileBrowserWidget->setContextMenuPolicy(Qt::CustomContextMenu);
// Prevent objects from being dropped on the file browser widget
mFileBrowserWidget->setAcceptDrops(false);
// Some connections
connect(mFileBrowserWidget, SIGNAL(customContextMenuRequested(const QPoint &)),
this, SLOT(customContextMenu(const QPoint &)));
connect(mFileBrowserWidget->selectionModel(), SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)),
this, SLOT(currentItemChanged(const QModelIndex &, const QModelIndex &)));
connect(mFileBrowserWidget, SIGNAL(expanded(const QModelIndex &)),
this, SLOT(needUpdateActions()));
connect(mFileBrowserWidget, SIGNAL(collapsed(const QModelIndex &)),
this, SLOT(needUpdateActions()));
}
FileBrowserWindow::~FileBrowserWindow()
{
// Delete the UI
delete mUi;
}
void FileBrowserWindow::updateActions()
{
// Make sure that the various actions are properly enabled/disabled
mUi->actionHome->setEnabled( (mFileBrowserWidget->currentPath() != mFileBrowserWidget->homeFolder())
|| ( (mFileBrowserWidget->currentPath() == mFileBrowserWidget->homeFolder())
&& !mFileBrowserWidget->isCurrentPathVisible()));
mUi->actionParent->setEnabled(mFileBrowserWidget->currentPathParent() != "");
mUi->actionPrevious->setEnabled(mPrevFolders.count());
mUi->actionNext->setEnabled(mNextFolders.count());
mUi->actionNew->setEnabled(mFileBrowserWidget->isCurrentPathDirWritable());
mUi->actionDelete->setEnabled(mFileBrowserWidget->isCurrentPathWritable());
}
void FileBrowserWindow::retranslateUi()
{
// Translate the whole window
mUi->retranslateUi(this);
// Make sure that the enabled state of the various actions is correct
// (indeed, to translate everything messes things up in that respect,
// so...)
updateActions();
// Retranslate the file browser widget
mFileBrowserWidget->retranslateUi();
}
void FileBrowserWindow::loadSettings(const QSettings &pSettings,
const QString &)
{
// Retrieve the settings of the file browser widget
// Note: we must make sure that we don't keep track of the previous folder
mKeepTrackOfPrevFolder = false;
mFileBrowserWidget->loadSettings(pSettings, SettingsFileBrowserWindow);
mKeepTrackOfPrevFolder = true;
// Initialise the previous folder information
mPrevFolder = mFileBrowserWidget->currentPathDir();
// Make sure that the current path is expanded
// Note: this is important in case the current path is that of the C:\ drive
// or the root of the file system which during the loadSettings above
// won't trigger a directoryLoaded signal in the file browser widget
if (!mFileBrowserWidget->isExpanded(mFileBrowserWidget->currentIndex()))
mFileBrowserWidget->setExpanded(mFileBrowserWidget->currentIndex(), true);
}
void FileBrowserWindow::saveSettings(QSettings &pSettings, const QString &)
{
// Keep track of the settings of the file browser widget
mFileBrowserWidget->saveSettings(pSettings, SettingsFileBrowserWindow);
}
void FileBrowserWindow::customContextMenu(const QPoint &)
{
// Create a custom context menu which items match the contents of our
// toolbar
QMenu menu;
menu.addAction(mUi->actionHome);
menu.addSeparator();
menu.addAction(mUi->actionParent);
menu.addSeparator();
menu.addAction(mUi->actionPrevious);
menu.addAction(mUi->actionNext);
menu.addSeparator();
menu.addAction(mUi->actionNew);
menu.addAction(mUi->actionDelete);
menu.exec(QCursor::pos());
}
void FileBrowserWindow::needUpdateActions()
{
// Something related to the help widget requires the actions to be udpated
updateActions();
}
void FileBrowserWindow::currentItemChanged(const QModelIndex &,
const QModelIndex &)
{
if (!mKeepTrackOfPrevFolder)
// We don't want to keep track of the previous folder, so...
return;
// A new item has been selected, so we need to keep track of the old one in
// case we want to go back to it
// Retrieve the full path to the folder where the current item is located
QString crtItemDir = mFileBrowserWidget->currentPathDir();
// Check whether there is a previous folder to keep track of
// Note: to do so, we cannot rely on the previous item (i.e. the second
// parameter to this function), since both the current and previous
// items might be located in the same folder, so...
if (crtItemDir != mPrevFolder) {
// There is a previous folder to keep track of, so add it to our list of
// previous folders and consider the current folder as our future
// previous folder
mPrevFolders.append(mPrevFolder);
mPrevFolder = crtItemDir;
// Reset the list of next folders since that list doesn't make sense
// anymore
mNextFolders.clear();
}
// Since a new item has been selected, we must update the actions
updateActions();
}
void FileBrowserWindow::on_actionHome_triggered()
{
// Go to the home folder (and ask for it to be expanded)
mFileBrowserWidget->gotoHomeFolder(true);
}
void FileBrowserWindow::on_actionParent_triggered()
{
// Go to the parent folder
mFileBrowserWidget->gotoPath(mFileBrowserWidget->currentPathParent());
// Going to the parent folder may have changed some actions, so...
updateActions();
}
void FileBrowserWindow::on_actionPrevious_triggered()
{
// Go to the previous folder and move the last item from our list of
// previous folders to our list of next folders
// Note: we must make sure that we don't keep track of the previous folder
mNextFolders.append(mFileBrowserWidget->currentPath());
mKeepTrackOfPrevFolder = false;
mFileBrowserWidget->gotoPath(mPrevFolders.last());
mKeepTrackOfPrevFolder = true;
mPrevFolders.removeLast();
// Going to the previous folder may have changed some actions, so...
updateActions();
}
void FileBrowserWindow::on_actionNext_triggered()
{
// Go to the next folder and move the last item from our list of next
// folders to our list of previous folders
// Note: we must make sure that we don't keep track of the previous folder
mPrevFolders.append(mFileBrowserWidget->currentPath());
mKeepTrackOfPrevFolder = false;
mFileBrowserWidget->gotoPath(mNextFolders.last());
mKeepTrackOfPrevFolder = true;
mNextFolders.removeLast();
// Going to the next folder may have changed some actions, so...
updateActions();
}
void FileBrowserWindow::on_actionNew_triggered()
{
// The default new action is about creating a new folder, so...
on_actionNewFolder_triggered();
}
static QString FolderFileNameRegExp = "[^\\/:*?\"<>|]+";
void FileBrowserWindow::on_actionNewFolder_triggered()
{
// Get the name of the new folder
OneFieldWindow oneFieldWindow(tr("New Folder"), tr("Folder name:"),
tr("Please provide a name for the new folder."),
FolderFileNameRegExp, this);
oneFieldWindow.exec();
// Create the new folder in the current folder unless the user cancelled the
// action
if (oneFieldWindow.result() == QDialog::Accepted) {
QString folderPath = mFileBrowserWidget->currentPathDir()
+QDir::separator()+oneFieldWindow.fieldValue();
if (QDir(folderPath).exists()) {
// The folder already exists, so...
QMessageBox::information(this, qApp->applicationName(),
tr("Sorry, but the <strong>%1</strong> folder already exists.").arg(oneFieldWindow.fieldValue()));
} else {
// The folder doesn't already exist, so try to create it
if (QDir(mFileBrowserWidget->currentPathDir()).mkdir(oneFieldWindow.fieldValue()))
// The folder was created, so select it
mFileBrowserWidget->gotoPath(folderPath, true);
else
// The folder couldn't be created, so...
QMessageBox::information(this, qApp->applicationName(),
tr("Sorry, but the <strong>%1</strong> folder could not be created.").arg(oneFieldWindow.fieldValue()));
}
}
}
void FileBrowserWindow::newCellmlFile(const CellmlVersion &pCellmlVersion)
{
// Get the name of the new CellML file
QString cellmlVersion = cellmlVersionString(pCellmlVersion);
OneFieldWindow oneFieldWindow(tr("New CellML %1 File").arg(cellmlVersion), tr("Model name:"),
tr("Please provide a name for the new CellML %1 model.").arg(cellmlVersion),
FolderFileNameRegExp, this);
oneFieldWindow.exec();
// Create the new CellML file in the current folder unless the user
// cancelled the action
if (oneFieldWindow.result() == QDialog::Accepted) {
QString cellmlFileName = oneFieldWindow.fieldValue()
+CellmlFileExtension;
QString cellmlFilePath = mFileBrowserWidget->currentPathDir()
+QDir::separator()+cellmlFileName;
if (QFileInfo(cellmlFilePath).exists()) {
// The CellML file already exists, so...
QMessageBox::information(this, qApp->applicationName(),
tr("Sorry, but the <strong>%1</strong> file already exists.").arg(cellmlFileName));
} else {
// The CellML file doesn't already exist, so try to create it
if (::newCellmlFile(cellmlFilePath, oneFieldWindow.fieldValue(),
pCellmlVersion)) {
// The CellML file was created, so select it
mFileBrowserWidget->gotoPath(cellmlFilePath, true);
// Have the new CellML file managed
mDocumentManager->manage(cellmlFilePath);
} else {
// The CellML file couldn't be created, so...
QMessageBox::information(this, qApp->applicationName(),
tr("Sorry, but the <strong>%1</strong> file could not be created.").arg(cellmlFileName));
}
}
}
}
void FileBrowserWindow::on_actionNewCellML10File_triggered()
{
newCellmlFile(Cellml_1_0);
}
void FileBrowserWindow::on_actionNewCellML11File_triggered()
{
newCellmlFile(Cellml_1_1);
}
void FileBrowserWindow::on_actionDelete_triggered()
{
// Delete the current folder/file
QString path = mFileBrowserWidget->currentPath();
QFileInfo pathFileInfo = path;
QString pathFileName = pathFileInfo.fileName();
if (!pathFileName.isEmpty()) {
// We are not at the root of the file system, so we can ask to delete
// the folder/file
bool isPathDir = pathFileInfo.isDir();
if( QMessageBox::question(this, qApp->applicationName(),
isPathDir?
tr("Do you really want to delete the <strong>%1</strong> folder?").arg(pathFileName):
tr("Do you really want to delete the <strong>%1</strong> file?").arg(pathFileName),
QMessageBox::Yes|QMessageBox::No,
QMessageBox::Yes) == QMessageBox::Yes ) {
// The user really wants to delete the folder/file, so...
if (removePath(path))
// The folder/file has been removed, so now make sure that the
// newly selected entry is visible
mFileBrowserWidget->gotoPath(mFileBrowserWidget->currentPath());
else
// The folder/file couldn't be removed, so let the user know
// about it
// Note: we should never reach this point in the case of a file,
// since the action is only triggerable if the file is
// writable (and therefore deletable), but still... better
// be safe than 'sorry'...
QMessageBox::information(this, qApp->applicationName(),
isPathDir?
tr("Sorry, but the <strong>%1</strong> folder could not be deleted.").arg(pathFileName):
tr("Sorry, but the <strong>%1</strong> file could not be deleted.").arg(pathFileName));
}
}
}
<|endoftext|> |
<commit_before>#include "AliHBTReaderInternal.h"
#include <TTree.h>
#include <TFile.h>
#include <TParticle.h>
#include <TError.h>
#include <AliRun.h>
#include <AliMagF.h>
#include "AliHBTRun.h"
#include "AliHBTEvent.h"
#include "AliHBTParticle.h"
#include "AliHBTParticleCut.h"
AliHBTReaderInternal test;
ClassImp(AliHBTReaderInternal)
/********************************************************************/
AliHBTReaderInternal::AliHBTReaderInternal():
fFileName(),
fPartBranch(0x0),
fTrackBranch(0x0),
fTree(0x0),
fFile(0x0)
{
//Defalut constructor
}
/********************************************************************/
AliHBTReaderInternal::AliHBTReaderInternal(const char *filename):
fFileName(filename),
fPartBranch(0x0),
fTrackBranch(0x0),
fTree(0x0),
fFile(0x0)
{
//constructor
//filename - name of file to open
}
/********************************************************************/
AliHBTReaderInternal::AliHBTReaderInternal(TObjArray* dirs, const char *filename):
AliHBTReader(dirs),
fFileName(filename),
fPartBranch(0x0),
fTrackBranch(0x0),
fTree(0x0),
fFile(0x0)
{
//ctor
//dirs contains strings with directories to look data in
//filename - name of file to open
}
/********************************************************************/
AliHBTReaderInternal::~AliHBTReaderInternal()
{
//desctructor
delete fTree;
delete fFile;
}
/********************************************************************/
void AliHBTReaderInternal::Rewind()
{
delete fTree;
fTree = 0x0;
delete fFile;
fFile = 0x0;
fCurrentDir = 0;
fNEventsRead= 0;
}
/********************************************************************/
Int_t AliHBTReaderInternal::ReadNext()
{
//reads data and puts put to the particles and tracks objects
//reurns 0 if everything is OK
//
Info("ReadNext","");
Int_t i; //iterator and some temprary values
Int_t counter;
AliHBTParticle* tpart = 0x0, *ttrack = 0x0;
TDatabasePDG* pdgdb = TDatabasePDG::Instance();
if (pdgdb == 0x0)
{
Error("ReadNext","Can not get PDG Particles Data Base");
return 1;
}
if (fParticlesEvent == 0x0) fParticlesEvent = new AliHBTEvent();
if (fTracksEvent == 0x0) fTracksEvent = new AliHBTEvent();
fParticlesEvent->Reset();
fTracksEvent->Reset();
do //do{}while; is OK even if 0 dirs specified. In that case we try to read from "./"
{
if (fTree == 0x0)
if( (i=OpenNextFile()) )
{
Error("ReadNext","Skipping directory due to problems with opening files. Errorcode %d",i);
fCurrentDir++;
continue;
}
if (fCurrentEvent == (Int_t)fTree->GetEntries())
{
delete fTree;
fTree = 0x0;
delete fFile;
fFile = 0x0;
fPartBranch = 0x0;
fTrackBranch= 0x0;
fCurrentDir++;
continue;
}
/***************************/
/***************************/
/***************************/
Info("ReadNext","Event %d",fCurrentEvent);
fTree->GetEvent(fCurrentEvent);
counter = 0;
if (fPartBranch && fTrackBranch)
{
for(i = 0; i < fPartBuffer->GetEntries(); i++)
{
tpart = dynamic_cast<AliHBTParticle*>(fPartBuffer->At(i));
ttrack = dynamic_cast<AliHBTParticle*>(fTrackBuffer->At(i));
if( tpart == 0x0 ) continue; //if returned pointer is NULL
if (ttrack->GetUID() != tpart->GetUID())
{
Error("ReadNext","Sth. is wrong: Track and Particle has different UID.");
Error("ReadNext","They probobly do not correspond to each other.");
}
for (Int_t s = 0; s < tpart->GetNumberOfPids(); s++)
{
if( pdgdb->GetParticle(tpart->GetNthPid(s)) == 0x0 ) continue; //if particle has crazy PDG code (not known to our database)
if( Pass(tpart->GetNthPid(s)) ) continue; //check if we are intersted with particles of this type
//if not take next partilce
AliHBTParticle* part = new AliHBTParticle(*tpart);
part->SetPdgCode(tpart->GetNthPid(s),tpart->GetNthPidProb(s));
if( Pass(part) )
{
delete part;
continue;
}
AliHBTParticle* track = new AliHBTParticle(*ttrack);
fParticlesEvent->AddParticle(part);
fTracksEvent->AddParticle(track);
counter++;
}
}
Info("ReadNext"," Read: %d particles and tracks.",counter);
}
else
{
if (fPartBranch)
{
Info("ReadNext","Found %d particles in total.",fPartBuffer->GetEntries());
for(i = 0; i < fPartBuffer->GetEntries(); i++)
{
tpart = dynamic_cast<AliHBTParticle*>(fPartBuffer->At(i));
if(tpart == 0x0) continue; //if returned pointer is NULL
for (Int_t s = 0; s < tpart->GetNumberOfPids(); s++)
{
if( pdgdb->GetParticle(tpart->GetNthPid(s)) == 0x0 ) continue; //if particle has crazy PDG code (not known to our database)
if( Pass(tpart->GetNthPid(s)) ) continue; //check if we are intersted with particles of this type
AliHBTParticle* part = new AliHBTParticle(*tpart);
part->SetPdgCode(tpart->GetNthPid(s),tpart->GetNthPidProb(s));
if( Pass(part) )
{
delete part;
continue;
}
fParticlesEvent->AddParticle(part);
counter++;
}
}
Info("ReadNext"," Read: %d particles.",counter);
}
else Info("ReadNext"," Read: 0 particles.");
if (fTrackBranch)
{
for(i = 0; i < fTrackBuffer->GetEntries(); i++)
{
tpart = dynamic_cast<AliHBTParticle*>(fTrackBuffer->At(i));
if(tpart == 0x0) continue; //if returned pointer is NULL
for (Int_t s = 0; s < tpart->GetNumberOfPids(); s++)
{
if( pdgdb->GetParticle(tpart->GetNthPid(s)) == 0x0 ) continue; //if particle has crazy PDG code (not known to our database)
if( Pass(tpart->GetNthPid(s)) ) continue; //check if we are intersted with particles of this type
AliHBTParticle* part = new AliHBTParticle(*tpart);
part->SetPdgCode(tpart->GetNthPid(s),tpart->GetNthPidProb(s));
if( Pass(part) )
{
delete part;
continue;
}
fTracksEvent->AddParticle(part);
counter++;
}
}
Info("ReadNext"," Read: %d tracks",counter);
}
else Info("ReadNext"," Read: 0 tracks.");
}
fPartBuffer->Delete();
fTrackBuffer->Delete();
fCurrentEvent++;
fNEventsRead++;
return 0;
}while(fCurrentDir < GetNumberOfDirs());
return 1;//no more directories to read
}
/********************************************************************/
Int_t AliHBTReaderInternal::OpenNextFile()
{
//open file in current directory
const TString& dirname = GetDirName(fCurrentDir);
if (dirname == "")
{
Error("OpenNextFile","Can not get directory name");
return 4;
}
TString filename = dirname +"/"+ fFileName;
fFile = TFile::Open(filename.Data());
if ( fFile == 0x0 )
{
Error("OpenNextFile","Can't open file named %s",filename.Data());
return 1;
}
if (fFile->IsOpen() == kFALSE)
{
Error("OpenNextFile","Can't open filenamed %s",filename.Data());
return 1;
}
fTree = (TTree*)fFile->Get("data");
if (fTree == 0x0)
{
Error("OpenNextFile","Can not get the tree.");
return 1;
}
fTrackBranch = fTree->GetBranch("tracks");//get the branch with tracks
if (fTrackBranch == 0x0) ////check if we got the branch
{//if not return with error
Info("OpenNextFile","Can't find a branch with tracks !\n");
}
else
{
if (fTrackBuffer == 0x0)
fTrackBuffer = new TClonesArray("AliHBTParticle",15000);
fTrackBranch->SetAddress(&fTrackBuffer);
}
fPartBranch = fTree->GetBranch("particles");//get the branch with particles
if (fPartBranch == 0x0) ////check if we got the branch
{//if not return with error
Info("OpenNextFile","Can't find a branch with particles !\n");
}
else
{
if (fPartBuffer == 0x0)
fPartBuffer = new TClonesArray("AliHBTParticle",15000);
fPartBranch->SetAddress(&fPartBuffer);
}
Info("OpenNextFile","________________________________________________________");
Info("OpenNextFile","Found %d event(s) in directory %s",
(Int_t)fTree->GetEntries(),GetDirName(fCurrentEvent).Data());
fCurrentEvent = 0;
return 0;
}
/********************************************************************/
Int_t AliHBTReaderInternal::Write(AliHBTReader* reader,const char* outfile, Bool_t multcheck)
{
//reads tracks from reader and writes runs to file
//reader - provides data for writing in internal format
//name of output file
//multcheck - switches of checking if particle was stored with other incarnation
// usefull e.g. when using kine data, where all particles have 100% pid prob.and saves a lot of time
Int_t i,j;
::Info("AliHBTReaderInternal::Write","________________________________________________________");
::Info("AliHBTReaderInternal::Write","________________________________________________________");
::Info("AliHBTReaderInternal::Write","________________________________________________________");
TFile *histoOutput = TFile::Open(outfile,"recreate");
if (!histoOutput->IsOpen())
{
::Error("AliHBTReaderInternal::Write","File is not opened");
return 1;
}
TTree *tracktree = new TTree("data","Tree with tracks");
TClonesArray* pbuffer = new TClonesArray("AliHBTParticle",15000);
TClonesArray* tbuffer = new TClonesArray("AliHBTParticle",15000);
TClonesArray &particles = *pbuffer;
TClonesArray &tracks = *tbuffer;
TString name("Tracks");
Int_t nt = reader->GetNumberOfTrackEvents();
Int_t np = reader->GetNumberOfPartEvents();
if (AliHBTParticle::GetDebug() > 0)
::Info("Write","Reader has %d track events and %d particles events.",nt,np);
Bool_t trck = (nt > 0) ? kTRUE : kFALSE;
Bool_t part = (np > 0) ? kTRUE : kFALSE;
TBranch *trackbranch = 0x0, *partbranch = 0x0;
if (trck) trackbranch = tracktree->Branch("tracks",&tbuffer,32000,0);
if (part) partbranch = tracktree->Branch("particles",&pbuffer,32000,0);
if ( (trck) && (part) && (np != nt))
{
::Warning("AliHBTReaderInternal::Write","Number of track and particle events is different");
}
Int_t n;
if (nt >= np ) n = nt; else n = np;
if (AliHBTParticle::GetDebug() > 0)
::Info("Write","Will loop over %d events",n);
for ( i =0;i< n; i++)
{
::Info("AliHBTReaderInternal::Write","Event %d",i+1);
Int_t counter = 0;
if (trck && (i<=nt))
{
AliHBTEvent* trackev = reader->GetTrackEvent(i);
for ( j = 0; j< trackev->GetNumberOfParticles();j++)
{
const AliHBTParticle& t = *(trackev->GetParticle(j));
if (multcheck)
{
if (FindIndex(tbuffer,t.GetUID()))
{
if (AliHBTParticle::GetDebug()>4)
{
::Info("Write","Track with Event UID %d already stored",t.GetUID());
}
continue; //not to write the same particles with other incarnations
}
}
new (tracks[counter++]) AliHBTParticle(t);
}
::Info("AliHBTReaderInternal::Write"," Tracks: %d",tracks.GetEntries());
}else ::Info("AliHBTReaderInternal::Write","NO TRACKS");
counter = 0;
if (part && (i<=np))
{
// ::Warning("AliHBTReaderInternal::Write","Find index switched off!!!");
AliHBTEvent* partev = reader->GetParticleEvent(i);
for ( j = 0; j< partev->GetNumberOfParticles();j++)
{
const AliHBTParticle& part= *(partev->GetParticle(j));
if (multcheck)
{
if (FindIndex(pbuffer,part.GetUID()))
{
if (AliHBTParticle::GetDebug()>4)
{
::Info("Write","Particle with Event UID %d already stored",part.GetUID());
}
continue; //not to write the same particles with other incarnations
}
}
new (particles[counter++]) AliHBTParticle(part);
}
::Info("AliHBTReaderInternal::Write"," Particles: %d",particles.GetEntries());
}else ::Info("AliHBTReaderInternal::Write","NO PARTICLES");
histoOutput->cd();
tracktree->Fill();
tracktree->AutoSave();
tbuffer->Delete();
pbuffer->Delete();
}
histoOutput->cd();
tracktree->Write(0,TObject::kOverwrite);
delete tracktree;
tbuffer->SetOwner();
pbuffer->SetOwner();
delete pbuffer;
delete tbuffer;
histoOutput->Close();
return 0;
}
/********************************************************************/
Bool_t AliHBTReaderInternal::FindIndex(TClonesArray* arr,Int_t idx)
{
//Checks if in the array exists already partilce with Unique ID idx
if (arr == 0x0)
{
::Error("FindIndex","Array is 0x0");
return kTRUE;
}
TIter next(arr);
AliHBTParticle* p;
while (( p = (AliHBTParticle*)next()))
{
if (p->GetUID() == idx) return kTRUE;
}
return kFALSE;
}
<commit_msg>Bug correction<commit_after>#include "AliHBTReaderInternal.h"
#include <TTree.h>
#include <TFile.h>
#include <TParticle.h>
#include <TError.h>
#include <AliRun.h>
#include <AliMagF.h>
#include "AliHBTRun.h"
#include "AliHBTEvent.h"
#include "AliHBTParticle.h"
#include "AliHBTParticleCut.h"
AliHBTReaderInternal test;
ClassImp(AliHBTReaderInternal)
/********************************************************************/
AliHBTReaderInternal::AliHBTReaderInternal():
fFileName(),
fPartBranch(0x0),
fTrackBranch(0x0),
fTree(0x0),
fFile(0x0)
{
//Defalut constructor
}
/********************************************************************/
AliHBTReaderInternal::AliHBTReaderInternal(const char *filename):
fFileName(filename),
fPartBranch(0x0),
fTrackBranch(0x0),
fTree(0x0),
fFile(0x0)
{
//constructor
//filename - name of file to open
}
/********************************************************************/
AliHBTReaderInternal::AliHBTReaderInternal(TObjArray* dirs, const char *filename):
AliHBTReader(dirs),
fFileName(filename),
fPartBranch(0x0),
fTrackBranch(0x0),
fTree(0x0),
fFile(0x0)
{
//ctor
//dirs contains strings with directories to look data in
//filename - name of file to open
}
/********************************************************************/
AliHBTReaderInternal::~AliHBTReaderInternal()
{
//desctructor
delete fTree;
delete fFile;
}
/********************************************************************/
void AliHBTReaderInternal::Rewind()
{
delete fTree;
fTree = 0x0;
delete fFile;
fFile = 0x0;
fCurrentDir = 0;
fNEventsRead= 0;
}
/********************************************************************/
Int_t AliHBTReaderInternal::ReadNext()
{
//reads data and puts put to the particles and tracks objects
//reurns 0 if everything is OK
//
Info("ReadNext","");
Int_t i; //iterator and some temprary values
Int_t counter;
AliHBTParticle* tpart = 0x0, *ttrack = 0x0;
TDatabasePDG* pdgdb = TDatabasePDG::Instance();
if (pdgdb == 0x0)
{
Error("ReadNext","Can not get PDG Particles Data Base");
return 1;
}
if (fParticlesEvent == 0x0) fParticlesEvent = new AliHBTEvent();
if (fTracksEvent == 0x0) fTracksEvent = new AliHBTEvent();
fParticlesEvent->Reset();
fTracksEvent->Reset();
do //do{}while; is OK even if 0 dirs specified. In that case we try to read from "./"
{
if (fTree == 0x0)
if( (i=OpenNextFile()) )
{
Error("ReadNext","Skipping directory due to problems with opening files. Errorcode %d",i);
fCurrentDir++;
continue;
}
if (fCurrentEvent == (Int_t)fTree->GetEntries())
{
delete fTree;
fTree = 0x0;
delete fFile;
fFile = 0x0;
fPartBranch = 0x0;
fTrackBranch= 0x0;
fCurrentDir++;
continue;
}
/***************************/
/***************************/
/***************************/
Info("ReadNext","Event %d",fCurrentEvent);
fTree->GetEvent(fCurrentEvent);
counter = 0;
if (fPartBranch && fTrackBranch)
{
for(i = 0; i < fPartBuffer->GetEntries(); i++)
{
tpart = dynamic_cast<AliHBTParticle*>(fPartBuffer->At(i));
ttrack = dynamic_cast<AliHBTParticle*>(fTrackBuffer->At(i));
if( tpart == 0x0 ) continue; //if returned pointer is NULL
if (ttrack->GetUID() != tpart->GetUID())
{
Error("ReadNext","Sth. is wrong: Track and Particle has different UID.");
Error("ReadNext","They probobly do not correspond to each other.");
}
for (Int_t s = 0; s < tpart->GetNumberOfPids(); s++)
{
if( pdgdb->GetParticle(tpart->GetNthPid(s)) == 0x0 ) continue; //if particle has crazy PDG code (not known to our database)
if( Pass(tpart->GetNthPid(s)) ) continue; //check if we are intersted with particles of this type
//if not take next partilce
AliHBTParticle* part = new AliHBTParticle(*tpart);
part->SetPdgCode(tpart->GetNthPid(s),tpart->GetNthPidProb(s));
if( Pass(part) )
{
delete part;
continue;
}
AliHBTParticle* track = new AliHBTParticle(*ttrack);
fParticlesEvent->AddParticle(part);
fTracksEvent->AddParticle(track);
counter++;
}
}
Info("ReadNext"," Read: %d particles and tracks.",counter);
}
else
{
if (fPartBranch)
{
Info("ReadNext","Found %d particles in total.",fPartBuffer->GetEntries());
for(i = 0; i < fPartBuffer->GetEntries(); i++)
{
tpart = dynamic_cast<AliHBTParticle*>(fPartBuffer->At(i));
if(tpart == 0x0) continue; //if returned pointer is NULL
for (Int_t s = 0; s < tpart->GetNumberOfPids(); s++)
{
if( pdgdb->GetParticle(tpart->GetNthPid(s)) == 0x0 ) continue; //if particle has crazy PDG code (not known to our database)
if( Pass(tpart->GetNthPid(s)) ) continue; //check if we are intersted with particles of this type
AliHBTParticle* part = new AliHBTParticle(*tpart);
part->SetPdgCode(tpart->GetNthPid(s),tpart->GetNthPidProb(s));
if( Pass(part) )
{
delete part;
continue;
}
fParticlesEvent->AddParticle(part);
counter++;
}
}
Info("ReadNext"," Read: %d particles.",counter);
}
else Info("ReadNext"," Read: 0 particles.");
if (fTrackBranch)
{
for(i = 0; i < fTrackBuffer->GetEntries(); i++)
{
tpart = dynamic_cast<AliHBTParticle*>(fTrackBuffer->At(i));
if(tpart == 0x0) continue; //if returned pointer is NULL
for (Int_t s = 0; s < tpart->GetNumberOfPids(); s++)
{
if( pdgdb->GetParticle(tpart->GetNthPid(s)) == 0x0 ) continue; //if particle has crazy PDG code (not known to our database)
if( Pass(tpart->GetNthPid(s)) ) continue; //check if we are intersted with particles of this type
AliHBTParticle* part = new AliHBTParticle(*tpart);
part->SetPdgCode(tpart->GetNthPid(s),tpart->GetNthPidProb(s));
if( Pass(part) )
{
delete part;
continue;
}
fTracksEvent->AddParticle(part);
counter++;
}
}
Info("ReadNext"," Read: %d tracks",counter);
}
else Info("ReadNext"," Read: 0 tracks.");
}
if (fPartBuffer) fPartBuffer->Delete();
if (fTrackBuffer) fTrackBuffer->Delete();
fCurrentEvent++;
fNEventsRead++;
return 0;
}while(fCurrentDir < GetNumberOfDirs());
return 1;//no more directories to read
}
/********************************************************************/
Int_t AliHBTReaderInternal::OpenNextFile()
{
//open file in current directory
const TString& dirname = GetDirName(fCurrentDir);
if (dirname == "")
{
Error("OpenNextFile","Can not get directory name");
return 4;
}
TString filename = dirname +"/"+ fFileName;
fFile = TFile::Open(filename.Data());
if ( fFile == 0x0 )
{
Error("OpenNextFile","Can't open file named %s",filename.Data());
return 1;
}
if (fFile->IsOpen() == kFALSE)
{
Error("OpenNextFile","Can't open filenamed %s",filename.Data());
return 1;
}
fTree = (TTree*)fFile->Get("data");
if (fTree == 0x0)
{
Error("OpenNextFile","Can not get the tree.");
return 1;
}
fTrackBranch = fTree->GetBranch("tracks");//get the branch with tracks
if (fTrackBranch == 0x0) ////check if we got the branch
{//if not return with error
Info("OpenNextFile","Can't find a branch with tracks !\n");
}
else
{
if (fTrackBuffer == 0x0)
fTrackBuffer = new TClonesArray("AliHBTParticle",15000);
fTrackBranch->SetAddress(&fTrackBuffer);
}
fPartBranch = fTree->GetBranch("particles");//get the branch with particles
if (fPartBranch == 0x0) ////check if we got the branch
{//if not return with error
Info("OpenNextFile","Can't find a branch with particles !\n");
}
else
{
if (fPartBuffer == 0x0)
fPartBuffer = new TClonesArray("AliHBTParticle",15000);
fPartBranch->SetAddress(&fPartBuffer);
}
Info("OpenNextFile","________________________________________________________");
Info("OpenNextFile","Found %d event(s) in directory %s",
(Int_t)fTree->GetEntries(),GetDirName(fCurrentEvent).Data());
fCurrentEvent = 0;
return 0;
}
/********************************************************************/
Int_t AliHBTReaderInternal::Write(AliHBTReader* reader,const char* outfile, Bool_t multcheck)
{
//reads tracks from reader and writes runs to file
//reader - provides data for writing in internal format
//name of output file
//multcheck - switches of checking if particle was stored with other incarnation
// usefull e.g. when using kine data, where all particles have 100% pid prob.and saves a lot of time
Int_t i,j;
::Info("AliHBTReaderInternal::Write","________________________________________________________");
::Info("AliHBTReaderInternal::Write","________________________________________________________");
::Info("AliHBTReaderInternal::Write","________________________________________________________");
TFile *histoOutput = TFile::Open(outfile,"recreate");
if (!histoOutput->IsOpen())
{
::Error("AliHBTReaderInternal::Write","File is not opened");
return 1;
}
TTree *tracktree = new TTree("data","Tree with tracks");
TClonesArray* pbuffer = new TClonesArray("AliHBTParticle",15000);
TClonesArray* tbuffer = new TClonesArray("AliHBTParticle",15000);
TClonesArray &particles = *pbuffer;
TClonesArray &tracks = *tbuffer;
TString name("Tracks");
Int_t nt = reader->GetNumberOfTrackEvents();
Int_t np = reader->GetNumberOfPartEvents();
if (AliHBTParticle::GetDebug() > 0)
::Info("Write","Reader has %d track events and %d particles events.",nt,np);
Bool_t trck = (nt > 0) ? kTRUE : kFALSE;
Bool_t part = (np > 0) ? kTRUE : kFALSE;
TBranch *trackbranch = 0x0, *partbranch = 0x0;
if (trck) trackbranch = tracktree->Branch("tracks",&tbuffer,32000,0);
if (part) partbranch = tracktree->Branch("particles",&pbuffer,32000,0);
if ( (trck) && (part) && (np != nt))
{
::Warning("AliHBTReaderInternal::Write","Number of track and particle events is different");
}
Int_t n;
if (nt >= np ) n = nt; else n = np;
if (AliHBTParticle::GetDebug() > 0)
::Info("Write","Will loop over %d events",n);
for ( i =0;i< n; i++)
{
::Info("AliHBTReaderInternal::Write","Event %d",i+1);
Int_t counter = 0;
if (trck && (i<=nt))
{
AliHBTEvent* trackev = reader->GetTrackEvent(i);
for ( j = 0; j< trackev->GetNumberOfParticles();j++)
{
const AliHBTParticle& t = *(trackev->GetParticle(j));
if (multcheck)
{
if (FindIndex(tbuffer,t.GetUID()))
{
if (AliHBTParticle::GetDebug()>4)
{
::Info("Write","Track with Event UID %d already stored",t.GetUID());
}
continue; //not to write the same particles with other incarnations
}
}
new (tracks[counter++]) AliHBTParticle(t);
}
::Info("AliHBTReaderInternal::Write"," Tracks: %d",tracks.GetEntries());
}else ::Info("AliHBTReaderInternal::Write","NO TRACKS");
counter = 0;
if (part && (i<=np))
{
// ::Warning("AliHBTReaderInternal::Write","Find index switched off!!!");
AliHBTEvent* partev = reader->GetParticleEvent(i);
for ( j = 0; j< partev->GetNumberOfParticles();j++)
{
const AliHBTParticle& part= *(partev->GetParticle(j));
if (multcheck)
{
if (FindIndex(pbuffer,part.GetUID()))
{
if (AliHBTParticle::GetDebug()>4)
{
::Info("Write","Particle with Event UID %d already stored",part.GetUID());
}
continue; //not to write the same particles with other incarnations
}
}
new (particles[counter++]) AliHBTParticle(part);
}
::Info("AliHBTReaderInternal::Write"," Particles: %d",particles.GetEntries());
}else ::Info("AliHBTReaderInternal::Write","NO PARTICLES");
histoOutput->cd();
tracktree->Fill();
tracktree->AutoSave();
tbuffer->Delete();
pbuffer->Delete();
}
histoOutput->cd();
tracktree->Write(0,TObject::kOverwrite);
delete tracktree;
tbuffer->SetOwner();
pbuffer->SetOwner();
delete pbuffer;
delete tbuffer;
histoOutput->Close();
return 0;
}
/********************************************************************/
Bool_t AliHBTReaderInternal::FindIndex(TClonesArray* arr,Int_t idx)
{
//Checks if in the array exists already partilce with Unique ID idx
if (arr == 0x0)
{
::Error("FindIndex","Array is 0x0");
return kTRUE;
}
TIter next(arr);
AliHBTParticle* p;
while (( p = (AliHBTParticle*)next()))
{
if (p->GetUID() == idx) return kTRUE;
}
return kFALSE;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2015, Baidu.com, Inc. All Rights Reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "agent/agent_impl.h"
#include "gflags/gflags.h"
#include "boost/bind.hpp"
#include "boost/algorithm/string.hpp"
#include "boost/algorithm/string/split.hpp"
#include "proto/master.pb.h"
#include "logging.h"
#include "agent/agent_internal_infos.h"
#include "agent/utils.h"
DECLARE_string(master_host);
DECLARE_string(master_port);
DECLARE_int32(agent_background_threads_num);
DECLARE_int32(agent_heartbeat_interval);
DECLARE_string(agent_ip);
DECLARE_string(agent_port);
DECLARE_int32(agent_millicores);
DECLARE_int32(agent_memory);
namespace baidu {
namespace galaxy {
AgentImpl::AgentImpl() :
master_endpoint_(),
lock_(),
background_threads_(FLAGS_agent_background_threads_num),
rpc_client_(NULL),
endpoint_(),
master_(NULL),
resource_capacity_(),
master_watcher_(NULL),
mutex_master_endpoint_() {
rpc_client_ = new RpcClient();
endpoint_ = FLAGS_agent_ip;
endpoint_.append(":");
endpoint_.append(FLAGS_agent_port);
master_watcher_ = new MasterWatcher();
background_threads_.DelayTask(
FLAGS_agent_heartbeat_interval, boost::bind(&AgentImpl::KeepHeartBeat, this));
}
AgentImpl::~AgentImpl() {
background_threads_.Stop(false);
if (rpc_client_ != NULL) {
delete rpc_client_;
rpc_client_ = NULL;
}
delete master_watcher_;
}
void AgentImpl::Query(::google::protobuf::RpcController* /*cntl*/,
const ::baidu::galaxy::QueryRequest* /*req*/,
::baidu::galaxy::QueryResponse* resp,
::google::protobuf::Closure* done) {
MutexLock scope_lock(&lock_);
resp->set_status(kOk);
AgentInfo agent_info;
agent_info.set_endpoint(endpoint_);
agent_info.mutable_total()->set_millicores(
FLAGS_agent_millicores);
agent_info.mutable_total()->set_memory(
FLAGS_agent_memory);
agent_info.mutable_assigned()->set_millicores(
FLAGS_agent_millicores - resource_capacity_.millicores);
agent_info.mutable_assigned()->set_memory(
FLAGS_agent_millicores - resource_capacity_.memory);
std::vector<PodInfo> pods;
pod_manager_.ShowPods(&pods);
std::vector<PodInfo>::iterator it = pods.begin();
for (; it != pods.end(); ++it) {
PodStatus* pod_status = agent_info.add_pods();
pod_status->CopyFrom(it->pod_status);
}
resp->mutable_agent()->CopyFrom(agent_info);
done->Run();
return;
}
void AgentImpl::CreatePodInfo(
const ::baidu::galaxy::RunPodRequest* req,
PodInfo* pod_info) {
if (pod_info == NULL) {
return;
}
pod_info->pod_id = req->podid();
pod_info->job_id = req->jobid();
pod_info->pod_desc.CopyFrom(req->pod());
pod_info->pod_status.set_podid(req->podid());
pod_info->pod_status.set_jobid(req->jobid());
pod_info->pod_status.set_state(kPodPending);
pod_info->initd_port = 0;
pod_info->initd_pid = 0;
for (int i = 0; i < pod_info->pod_desc.tasks_size(); i++) {
TaskInfo task_info;
task_info.task_id = GenerateTaskId(pod_info->pod_id);
task_info.pod_id = pod_info->pod_id;
task_info.desc.CopyFrom(pod_info->pod_desc.tasks(i));
task_info.status.set_state(kTaskPending);
task_info.initd_endpoint = "";
task_info.stage = kStagePENDING;
task_info.fail_retry_times = 0;
task_info.max_retry_times = 10;
pod_info->tasks[task_info.task_id] = task_info;
}
}
void AgentImpl::RunPod(::google::protobuf::RpcController* /*cntl*/,
const ::baidu::galaxy::RunPodRequest* req,
::baidu::galaxy::RunPodResponse* resp,
::google::protobuf::Closure* done) {
do {
MutexLock scope_lock(&lock_);
if (!req->has_podid()
|| !req->has_pod()) {
resp->set_status(kInputError);
break;
}
std::map<std::string, PodDescriptor>::iterator it =
pods_descs_.find(req->podid());
if (it != pods_descs_.end()) {
resp->set_status(kOk);
break;
}
if (AllocResource(req->pod().requirement()) != 0) {
LOG(WARNING, "pod %s alloc resource failed",
req->podid().c_str());
resp->set_status(kQuota);
break;
}
// NOTE alloc should before pods_desc set
pods_descs_[req->podid()] = req->pod();
PodInfo info;
CreatePodInfo(req, &info);
// if add failed, clean by master?
pod_manager_.AddPod(info);
resp->set_status(kOk);
} while (0);
done->Run();
return;
}
void AgentImpl::KillPod(::google::protobuf::RpcController* /*cntl*/,
const ::baidu::galaxy::KillPodRequest* req,
::baidu::galaxy::KillPodResponse* resp,
::google::protobuf::Closure* done) {
if (!req->has_podid()) {
LOG(WARNING, "master kill request has no podid");
resp->set_status(kInputError);
done->Run();
return;
}
MutexLock scope_lock(&lock_);
std::map<std::string, PodDescriptor>::iterator it =
pods_descs_.find(req->podid());
if (it == pods_descs_.end()) {
resp->set_status(kOk);
done->Run();
return;
}
pod_manager_.DeletePod(req->podid());
resp->set_status(kOk);
done->Run();
return;
}
void AgentImpl::KeepHeartBeat() {
MutexLock lock(&mutex_master_endpoint_);
if (!PingMaster()) {
LOG(WARNING, "ping master %s failed",
master_endpoint_.c_str());
}
background_threads_.DelayTask(FLAGS_agent_heartbeat_interval,
boost::bind(&AgentImpl::KeepHeartBeat, this));
return;
}
bool AgentImpl::Init() {
resource_capacity_.millicores = FLAGS_agent_millicores;
resource_capacity_.memory = FLAGS_agent_memory;
if (pod_manager_.Init() != 0) {
return false;
}
if (!RegistToMaster()) {
return false;
}
background_threads_.DelayTask(
500,
boost::bind(&AgentImpl::LoopCheckPods, this));
return true;
}
bool AgentImpl::PingMaster() {
mutex_master_endpoint_.AssertHeld();
HeartBeatRequest request;
HeartBeatResponse response;
request.set_endpoint(endpoint_);
return rpc_client_->SendRequest(master_,
&Master_Stub::HeartBeat,
&request,
&response,
5, 1);
}
void AgentImpl::LoopCheckPods() {
MutexLock scope_lock(&lock_);
std::map<std::string, PodDescriptor>::iterator it =
pods_descs_.begin();
std::vector<std::string> to_del_pod;
for (; it != pods_descs_.end(); ++it) {
if (pod_manager_.CheckPod(it->first) != 0) {
to_del_pod.push_back(it->first);
ReleaseResource(it->second.requirement());
}
}
for (size_t i = 0; i < to_del_pod.size(); i++) {
pods_descs_.erase(to_del_pod[i]);
}
background_threads_.DelayTask(
100,
boost::bind(&AgentImpl::LoopCheckPods, this));
}
void AgentImpl::HandleMasterChange(const std::string& new_master_endpoint) {
if (new_master_endpoint.empty()) {
LOG(WARNING, "the master endpoint is deleted from nexus");
}
if (new_master_endpoint != master_endpoint_) {
MutexLock lock(&mutex_master_endpoint_);
LOG(INFO, "master change to %s", new_master_endpoint.c_str());
master_endpoint_ = new_master_endpoint;
if (master_) {
delete master_;
}
if (!rpc_client_->GetStub(master_endpoint_, &master_)) {
LOG(WARNING, "connect master %s failed", master_endpoint_.c_str());
return;
}
}
}
bool AgentImpl::RegistToMaster() {
boost::function<void(const std::string)> handler;
handler = boost::bind(&AgentImpl::HandleMasterChange, this, _1);
bool ok = master_watcher_->Init(handler);
if (!ok) {
LOG(WARNING, "fail to watch on nexus");
return false;
}
MutexLock lock(&mutex_master_endpoint_);
master_endpoint_ = master_watcher_->GetMasterEndpoint();
if (!rpc_client_->GetStub(master_endpoint_, &master_)) {
LOG(WARNING, "connect master %s failed", master_endpoint_.c_str());
return false;
}
if (!PingMaster()) {
LOG(WARNING, "connect master %s failed", master_endpoint_.c_str());
}
return true;
}
int AgentImpl::AllocResource(const Resource& requirement) {
if (resource_capacity_.millicores > requirement.millicores()
&& resource_capacity_.memory > requirement.memory()) {
resource_capacity_.millicores -= requirement.millicores();
resource_capacity_.memory -= requirement.memory();
return 0;
}
return -1;
}
void AgentImpl::ReleaseResource(const Resource& requirement) {
resource_capacity_.millicores += requirement.millicores();
resource_capacity_.memory += requirement.memory();
}
} // ending namespace galaxy
} // ending namespace baidu
<commit_msg>fix agent<commit_after>// Copyright (c) 2015, Baidu.com, Inc. All Rights Reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "agent/agent_impl.h"
#include "gflags/gflags.h"
#include "boost/bind.hpp"
#include "boost/algorithm/string.hpp"
#include "boost/algorithm/string/split.hpp"
#include "proto/master.pb.h"
#include "logging.h"
#include "agent/agent_internal_infos.h"
#include "agent/utils.h"
DECLARE_string(master_host);
DECLARE_string(master_port);
DECLARE_int32(agent_background_threads_num);
DECLARE_int32(agent_heartbeat_interval);
DECLARE_string(agent_ip);
DECLARE_string(agent_port);
DECLARE_int32(agent_millicores);
DECLARE_int32(agent_memory);
namespace baidu {
namespace galaxy {
AgentImpl::AgentImpl() :
master_endpoint_(),
lock_(),
background_threads_(FLAGS_agent_background_threads_num),
rpc_client_(NULL),
endpoint_(),
master_(NULL),
resource_capacity_(),
master_watcher_(NULL),
mutex_master_endpoint_() {
rpc_client_ = new RpcClient();
endpoint_ = FLAGS_agent_ip;
endpoint_.append(":");
endpoint_.append(FLAGS_agent_port);
master_watcher_ = new MasterWatcher();
background_threads_.DelayTask(
FLAGS_agent_heartbeat_interval, boost::bind(&AgentImpl::KeepHeartBeat, this));
}
AgentImpl::~AgentImpl() {
background_threads_.Stop(false);
if (rpc_client_ != NULL) {
delete rpc_client_;
rpc_client_ = NULL;
}
delete master_watcher_;
}
void AgentImpl::Query(::google::protobuf::RpcController* /*cntl*/,
const ::baidu::galaxy::QueryRequest* /*req*/,
::baidu::galaxy::QueryResponse* resp,
::google::protobuf::Closure* done) {
MutexLock scope_lock(&lock_);
resp->set_status(kOk);
AgentInfo agent_info;
agent_info.set_endpoint(endpoint_);
agent_info.mutable_total()->set_millicores(
FLAGS_agent_millicores);
agent_info.mutable_total()->set_memory(
FLAGS_agent_memory);
agent_info.mutable_assigned()->set_millicores(
FLAGS_agent_millicores - resource_capacity_.millicores);
agent_info.mutable_assigned()->set_memory(
FLAGS_agent_memory- resource_capacity_.memory);
std::vector<PodInfo> pods;
pod_manager_.ShowPods(&pods);
std::vector<PodInfo>::iterator it = pods.begin();
for (; it != pods.end(); ++it) {
PodStatus* pod_status = agent_info.add_pods();
pod_status->CopyFrom(it->pod_status);
}
resp->mutable_agent()->CopyFrom(agent_info);
done->Run();
return;
}
void AgentImpl::CreatePodInfo(
const ::baidu::galaxy::RunPodRequest* req,
PodInfo* pod_info) {
if (pod_info == NULL) {
return;
}
pod_info->pod_id = req->podid();
pod_info->job_id = req->jobid();
pod_info->pod_desc.CopyFrom(req->pod());
pod_info->pod_status.set_podid(req->podid());
pod_info->pod_status.set_jobid(req->jobid());
pod_info->pod_status.set_state(kPodPending);
pod_info->initd_port = 0;
pod_info->initd_pid = 0;
for (int i = 0; i < pod_info->pod_desc.tasks_size(); i++) {
TaskInfo task_info;
task_info.task_id = GenerateTaskId(pod_info->pod_id);
task_info.pod_id = pod_info->pod_id;
task_info.desc.CopyFrom(pod_info->pod_desc.tasks(i));
task_info.status.set_state(kTaskPending);
task_info.initd_endpoint = "";
task_info.stage = kStagePENDING;
task_info.fail_retry_times = 0;
task_info.max_retry_times = 10;
pod_info->tasks[task_info.task_id] = task_info;
}
}
void AgentImpl::RunPod(::google::protobuf::RpcController* /*cntl*/,
const ::baidu::galaxy::RunPodRequest* req,
::baidu::galaxy::RunPodResponse* resp,
::google::protobuf::Closure* done) {
do {
MutexLock scope_lock(&lock_);
if (!req->has_podid()
|| !req->has_pod()) {
resp->set_status(kInputError);
break;
}
std::map<std::string, PodDescriptor>::iterator it =
pods_descs_.find(req->podid());
if (it != pods_descs_.end()) {
resp->set_status(kOk);
break;
}
if (AllocResource(req->pod().requirement()) != 0) {
LOG(WARNING, "pod %s alloc resource failed",
req->podid().c_str());
resp->set_status(kQuota);
break;
}
// NOTE alloc should before pods_desc set
pods_descs_[req->podid()] = req->pod();
PodInfo info;
CreatePodInfo(req, &info);
// if add failed, clean by master?
pod_manager_.AddPod(info);
resp->set_status(kOk);
} while (0);
done->Run();
return;
}
void AgentImpl::KillPod(::google::protobuf::RpcController* /*cntl*/,
const ::baidu::galaxy::KillPodRequest* req,
::baidu::galaxy::KillPodResponse* resp,
::google::protobuf::Closure* done) {
if (!req->has_podid()) {
LOG(WARNING, "master kill request has no podid");
resp->set_status(kInputError);
done->Run();
return;
}
MutexLock scope_lock(&lock_);
std::map<std::string, PodDescriptor>::iterator it =
pods_descs_.find(req->podid());
if (it == pods_descs_.end()) {
resp->set_status(kOk);
done->Run();
return;
}
pod_manager_.DeletePod(req->podid());
resp->set_status(kOk);
done->Run();
return;
}
void AgentImpl::KeepHeartBeat() {
MutexLock lock(&mutex_master_endpoint_);
if (!PingMaster()) {
LOG(WARNING, "ping master %s failed",
master_endpoint_.c_str());
}
background_threads_.DelayTask(FLAGS_agent_heartbeat_interval,
boost::bind(&AgentImpl::KeepHeartBeat, this));
return;
}
bool AgentImpl::Init() {
resource_capacity_.millicores = FLAGS_agent_millicores;
resource_capacity_.memory = FLAGS_agent_memory;
if (pod_manager_.Init() != 0) {
return false;
}
if (!RegistToMaster()) {
return false;
}
background_threads_.DelayTask(
500,
boost::bind(&AgentImpl::LoopCheckPods, this));
return true;
}
bool AgentImpl::PingMaster() {
mutex_master_endpoint_.AssertHeld();
HeartBeatRequest request;
HeartBeatResponse response;
request.set_endpoint(endpoint_);
return rpc_client_->SendRequest(master_,
&Master_Stub::HeartBeat,
&request,
&response,
5, 1);
}
void AgentImpl::LoopCheckPods() {
MutexLock scope_lock(&lock_);
std::map<std::string, PodDescriptor>::iterator it =
pods_descs_.begin();
std::vector<std::string> to_del_pod;
for (; it != pods_descs_.end(); ++it) {
if (pod_manager_.CheckPod(it->first) != 0) {
to_del_pod.push_back(it->first);
ReleaseResource(it->second.requirement());
}
}
for (size_t i = 0; i < to_del_pod.size(); i++) {
pods_descs_.erase(to_del_pod[i]);
}
background_threads_.DelayTask(
100,
boost::bind(&AgentImpl::LoopCheckPods, this));
}
void AgentImpl::HandleMasterChange(const std::string& new_master_endpoint) {
if (new_master_endpoint.empty()) {
LOG(WARNING, "the master endpoint is deleted from nexus");
}
if (new_master_endpoint != master_endpoint_) {
MutexLock lock(&mutex_master_endpoint_);
LOG(INFO, "master change to %s", new_master_endpoint.c_str());
master_endpoint_ = new_master_endpoint;
if (master_) {
delete master_;
}
if (!rpc_client_->GetStub(master_endpoint_, &master_)) {
LOG(WARNING, "connect master %s failed", master_endpoint_.c_str());
return;
}
}
}
bool AgentImpl::RegistToMaster() {
boost::function<void(const std::string)> handler;
handler = boost::bind(&AgentImpl::HandleMasterChange, this, _1);
bool ok = master_watcher_->Init(handler);
if (!ok) {
LOG(WARNING, "fail to watch on nexus");
return false;
}
MutexLock lock(&mutex_master_endpoint_);
master_endpoint_ = master_watcher_->GetMasterEndpoint();
if (!rpc_client_->GetStub(master_endpoint_, &master_)) {
LOG(WARNING, "connect master %s failed", master_endpoint_.c_str());
return false;
}
if (!PingMaster()) {
LOG(WARNING, "connect master %s failed", master_endpoint_.c_str());
}
return true;
}
int AgentImpl::AllocResource(const Resource& requirement) {
lock_.AssertHeld();
if (resource_capacity_.millicores >= requirement.millicores()
&& resource_capacity_.memory >= requirement.memory()) {
resource_capacity_.millicores -= requirement.millicores();
resource_capacity_.memory -= requirement.memory();
return 0;
}
return -1;
}
void AgentImpl::ReleaseResource(const Resource& requirement) {
lock_.AssertHeld();
resource_capacity_.millicores += requirement.millicores();
resource_capacity_.memory += requirement.memory();
}
} // ending namespace galaxy
} // ending namespace baidu
<|endoftext|> |
<commit_before>/***********************************************************************
filename: CEGUIFalTextComponent.cpp
created: Sun Jun 19 2005
author: Paul D Turner <paul@cegui.org.uk>
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
*
* 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 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.
***************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "falagard/CEGUIFalTextComponent.h"
#include "falagard/CEGUIFalXMLEnumHelper.h"
#include "CEGUIFontManager.h"
#include "CEGUIExceptions.h"
#include "CEGUIPropertyHelper.h"
#include "CEGUIFont.h"
#include "CEGUILeftAlignedRenderedString.h"
#include "CEGUIRightAlignedRenderedString.h"
#include "CEGUICentredRenderedString.h"
#include "CEGUIJustifiedRenderedString.h"
#include "CEGUIRenderedStringWordWrapper.h"
#include <iostream>
#if defined (CEGUI_USE_FRIBIDI)
#include "CEGUIFribidiVisualMapping.h"
#elif defined (CEGUI_USE_MINIBIDI)
#include "CEGUIMinibidiVisualMapping.h"
#else
#include "CEGUIBiDiVisualMapping.h"
#endif
// Start of CEGUI namespace section
namespace CEGUI
{
TextComponent::TextComponent() :
#ifndef CEGUI_BIDI_SUPPORT
d_bidiVisualMapping(0),
#elif defined (CEGUI_USE_FRIBIDI)
d_bidiVisualMapping(new FribidiVisualMapping),
#elif defined (CEGUI_USE_MINIBIDI)
d_bidiVisualMapping(new MinibidiVisualMapping),
#else
#error "BIDI Configuration is inconsistant, check your config!"
#endif
d_bidiDataValid(false),
d_formattedRenderedString(new LeftAlignedRenderedString(d_renderedString)),
d_lastHorzFormatting(HTF_LEFT_ALIGNED),
d_vertFormatting(VTF_TOP_ALIGNED),
d_horzFormatting(HTF_LEFT_ALIGNED)
{}
TextComponent::~TextComponent()
{
delete d_bidiVisualMapping;
}
TextComponent::TextComponent(const TextComponent& obj) :
FalagardComponentBase(obj),
d_textLogical(obj.d_textLogical),
#ifndef CEGUI_BIDI_SUPPORT
d_bidiVisualMapping(0),
#elif defined (CEGUI_USE_FRIBIDI)
d_bidiVisualMapping(new FribidiVisualMapping),
#elif defined (CEGUI_USE_MINIBIDI)
d_bidiVisualMapping(new MinibidiVisualMapping),
#endif
d_bidiDataValid(false),
d_renderedString(obj.d_renderedString),
d_formattedRenderedString(obj.d_formattedRenderedString),
d_lastHorzFormatting(obj.d_lastHorzFormatting),
d_font(obj.d_font),
d_vertFormatting(obj.d_vertFormatting),
d_horzFormatting(obj.d_horzFormatting),
d_textPropertyName(obj.d_textPropertyName),
d_fontPropertyName(obj.d_fontPropertyName)
{
}
TextComponent& TextComponent::operator=(const TextComponent& other)
{
if (this == &other)
return *this;
FalagardComponentBase::operator=(other);
d_textLogical = other.d_textLogical;
// note we do not assign the BiDiVisualMapping object, we just mark our
// existing one as invalid so it's data gets regenerated next time it's
// needed.
d_bidiDataValid = false;
d_renderedString = other.d_renderedString;
d_formattedRenderedString = other.d_formattedRenderedString;
d_lastHorzFormatting = other.d_lastHorzFormatting;
d_font = other.d_font;
d_vertFormatting = other.d_vertFormatting;
d_horzFormatting = other.d_horzFormatting;
d_textPropertyName = other.d_textPropertyName;
d_fontPropertyName = other.d_fontPropertyName;
return *this;
}
const String& TextComponent::getText() const
{
return d_textLogical;
}
void TextComponent::setText(const String& text)
{
d_textLogical = text;
d_bidiDataValid = false;
}
const String& TextComponent::getFont() const
{
return d_font;
}
void TextComponent::setFont(const String& font)
{
d_font = font;
}
VerticalTextFormatting TextComponent::getVerticalFormatting() const
{
return d_vertFormatting;
}
void TextComponent::setVerticalFormatting(VerticalTextFormatting fmt)
{
d_vertFormatting = fmt;
}
HorizontalTextFormatting TextComponent::getHorizontalFormatting() const
{
return d_horzFormatting;
}
void TextComponent::setHorizontalFormatting(HorizontalTextFormatting fmt)
{
d_horzFormatting = fmt;
}
void TextComponent::setupStringFormatter(const Window& window,
const RenderedString& rendered_string) const
{
const HorizontalTextFormatting horzFormatting = d_horzFormatPropertyName.empty() ? d_horzFormatting :
FalagardXMLHelper::stringToHorzTextFormat(window.getProperty(d_horzFormatPropertyName));
// no formatting change
if (horzFormatting == d_lastHorzFormatting)
{
d_formattedRenderedString->setRenderedString(rendered_string);
return;
}
d_lastHorzFormatting = horzFormatting;
switch(horzFormatting)
{
case HTF_LEFT_ALIGNED:
d_formattedRenderedString =
new LeftAlignedRenderedString(rendered_string);
break;
case HTF_CENTRE_ALIGNED:
d_formattedRenderedString =
new CentredRenderedString(rendered_string);
break;
case HTF_RIGHT_ALIGNED:
d_formattedRenderedString =
new RightAlignedRenderedString(rendered_string);
break;
case HTF_JUSTIFIED:
d_formattedRenderedString =
new JustifiedRenderedString(rendered_string);
break;
case HTF_WORDWRAP_LEFT_ALIGNED:
d_formattedRenderedString =
new RenderedStringWordWrapper
<LeftAlignedRenderedString>(rendered_string);
break;
case HTF_WORDWRAP_CENTRE_ALIGNED:
d_formattedRenderedString =
new RenderedStringWordWrapper
<CentredRenderedString>(rendered_string);
break;
case HTF_WORDWRAP_RIGHT_ALIGNED:
d_formattedRenderedString =
new RenderedStringWordWrapper
<RightAlignedRenderedString>(rendered_string);
break;
case HTF_WORDWRAP_JUSTIFIED:
d_formattedRenderedString =
new RenderedStringWordWrapper
<JustifiedRenderedString>(rendered_string);
break;
}
}
void TextComponent::render_impl(Window& srcWindow, Rect& destRect, const CEGUI::ColourRect* modColours, const Rect* clipper, bool /*clipToDisplay*/) const
{
// get font to use
Font* font;
CEGUI_TRY
{
font = d_fontPropertyName.empty() ?
(d_font.empty() ? srcWindow.getFont() : &FontManager::getSingleton().get(d_font))
: &FontManager::getSingleton().get(srcWindow.getProperty(d_fontPropertyName));
}
CEGUI_CATCH (UnknownObjectException&)
{
font = 0;
}
// exit if we have no font to use.
if (!font)
return;
const RenderedString* rs = &d_renderedString;
// do we fetch text from a property
if (!d_textPropertyName.empty())
{
// fetch text & do bi-directional reordering as needed
String vis;
#ifdef CEGUI_BIDI_SUPPORT
BiDiVisualMapping::StrIndexList l2v, v2l;
d_bidiVisualMapping->reorderFromLogicalToVisual(
srcWindow.getProperty(d_textPropertyName), vis, l2v, v2l);
#else
vis = srcWindow.getProperty(d_textPropertyName);
#endif
// parse string using parser from Window.
d_renderedString =
srcWindow.getRenderedStringParser().parse(vis, font, modColours);
}
// do we use a static text string from the looknfeel
else if (!getTextVisual().empty())
// parse string using parser from Window.
d_renderedString = srcWindow.getRenderedStringParser().
parse(getTextVisual(), font, modColours);
// do we have to override the font?
else if (font != srcWindow.getFont())
d_renderedString = srcWindow.getRenderedStringParser().
parse(srcWindow.getTextVisual(), font, modColours);
// use ready-made RenderedString from the Window itself
else
rs = &srcWindow.getRenderedString();
setupStringFormatter(srcWindow, *rs);
d_formattedRenderedString->format(destRect.getSize());
// Get total formatted height.
const float textHeight = d_formattedRenderedString->getVerticalExtent();
// handle dest area adjustments for vertical formatting.
VerticalTextFormatting vertFormatting = d_vertFormatPropertyName.empty() ? d_vertFormatting :
FalagardXMLHelper::stringToVertTextFormat(srcWindow.getProperty(d_vertFormatPropertyName));
switch(vertFormatting)
{
case VTF_CENTRE_ALIGNED:
destRect.d_top += (destRect.getHeight() - textHeight) * 0.5f;
break;
case VTF_BOTTOM_ALIGNED:
destRect.d_top = destRect.d_bottom - textHeight;
break;
default:
// default is VTF_TOP_ALIGNED, for which we take no action.
break;
}
// calculate final colours to be used
ColourRect finalColours;
initColoursRect(srcWindow, modColours, finalColours);
// offset the font little down so that it's centered within its own spacing
// destRect.d_top += (font->getLineSpacing() - font->getFontHeight()) * 0.5f;
// add geometry for text to the target window.
d_formattedRenderedString->draw(srcWindow.getGeometryBuffer(),
destRect.getPosition(),
&finalColours, clipper);
}
void TextComponent::writeXMLToStream(XMLSerializer& xml_stream) const
{
// opening tag
xml_stream.openTag("TextComponent");
// write out area
d_area.writeXMLToStream(xml_stream);
// write text element
if (!d_font.empty() && !getText().empty())
{
xml_stream.openTag("Text");
if (!d_font.empty())
xml_stream.attribute("font", d_font);
if (!getText().empty())
xml_stream.attribute("string", getText());
xml_stream.closeTag();
}
// write text property element
if (!d_textPropertyName.empty())
{
xml_stream.openTag("TextProperty")
.attribute("name", d_textPropertyName)
.closeTag();
}
// write font property element
if (!d_fontPropertyName.empty())
{
xml_stream.openTag("FontProperty")
.attribute("name", d_fontPropertyName)
.closeTag();
}
// get base class to write colours
writeColoursXML(xml_stream);
// write vert format, allowing base class to do this for us if a propety is in use
if (!writeVertFormatXML(xml_stream))
{
// was not a property, so write out explicit formatting in use
xml_stream.openTag("VertFormat")
.attribute("type", FalagardXMLHelper::vertTextFormatToString(d_vertFormatting))
.closeTag();
}
// write horz format, allowing base class to do this for us if a propety is in use
if (!writeHorzFormatXML(xml_stream))
{
// was not a property, so write out explicit formatting in use
xml_stream.openTag("HorzFormat")
.attribute("type", FalagardXMLHelper::horzTextFormatToString(d_horzFormatting))
.closeTag();
}
// closing tag
xml_stream.closeTag();
}
bool TextComponent::isTextFetchedFromProperty() const
{
return !d_textPropertyName.empty();
}
const String& TextComponent::getTextPropertySource() const
{
return d_textPropertyName;
}
void TextComponent::setTextPropertySource(const String& property)
{
d_textPropertyName = property;
}
bool TextComponent::isFontFetchedFromProperty() const
{
return !d_fontPropertyName.empty();
}
const String& TextComponent::getFontPropertySource() const
{
return d_fontPropertyName;
}
void TextComponent::setFontPropertySource(const String& property)
{
d_fontPropertyName = property;
}
const String& TextComponent::getTextVisual() const
{
// no bidi support
if (!d_bidiVisualMapping)
return d_textLogical;
if (!d_bidiDataValid)
{
d_bidiVisualMapping->updateVisual(d_textLogical);
d_bidiDataValid = true;
}
return d_bidiVisualMapping->getTextVisual();
}
float TextComponent::getHorizontalTextExtent() const
{
return d_formattedRenderedString->getHorizontalExtent();
}
float TextComponent::getVerticalTextExtent() const
{
return d_formattedRenderedString->getVerticalExtent();
}
} // End of CEGUI namespace section
<commit_msg>FIX: We were applying text colours twice in Falagard TextComponent when string to be drawn or font to use were sourced anywhere other than from the default places. Many thanks to forum member 'BrightBit' for providing test case datafiles to produce this issue. See: http://www.cegui.org.uk/mantis/view.php?id=774.<commit_after>/***********************************************************************
filename: CEGUIFalTextComponent.cpp
created: Sun Jun 19 2005
author: Paul D Turner <paul@cegui.org.uk>
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
*
* 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 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.
***************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "falagard/CEGUIFalTextComponent.h"
#include "falagard/CEGUIFalXMLEnumHelper.h"
#include "CEGUIFontManager.h"
#include "CEGUIExceptions.h"
#include "CEGUIPropertyHelper.h"
#include "CEGUIFont.h"
#include "CEGUILeftAlignedRenderedString.h"
#include "CEGUIRightAlignedRenderedString.h"
#include "CEGUICentredRenderedString.h"
#include "CEGUIJustifiedRenderedString.h"
#include "CEGUIRenderedStringWordWrapper.h"
#include <iostream>
#if defined (CEGUI_USE_FRIBIDI)
#include "CEGUIFribidiVisualMapping.h"
#elif defined (CEGUI_USE_MINIBIDI)
#include "CEGUIMinibidiVisualMapping.h"
#else
#include "CEGUIBiDiVisualMapping.h"
#endif
// Start of CEGUI namespace section
namespace CEGUI
{
TextComponent::TextComponent() :
#ifndef CEGUI_BIDI_SUPPORT
d_bidiVisualMapping(0),
#elif defined (CEGUI_USE_FRIBIDI)
d_bidiVisualMapping(new FribidiVisualMapping),
#elif defined (CEGUI_USE_MINIBIDI)
d_bidiVisualMapping(new MinibidiVisualMapping),
#else
#error "BIDI Configuration is inconsistant, check your config!"
#endif
d_bidiDataValid(false),
d_formattedRenderedString(new LeftAlignedRenderedString(d_renderedString)),
d_lastHorzFormatting(HTF_LEFT_ALIGNED),
d_vertFormatting(VTF_TOP_ALIGNED),
d_horzFormatting(HTF_LEFT_ALIGNED)
{}
TextComponent::~TextComponent()
{
delete d_bidiVisualMapping;
}
TextComponent::TextComponent(const TextComponent& obj) :
FalagardComponentBase(obj),
d_textLogical(obj.d_textLogical),
#ifndef CEGUI_BIDI_SUPPORT
d_bidiVisualMapping(0),
#elif defined (CEGUI_USE_FRIBIDI)
d_bidiVisualMapping(new FribidiVisualMapping),
#elif defined (CEGUI_USE_MINIBIDI)
d_bidiVisualMapping(new MinibidiVisualMapping),
#endif
d_bidiDataValid(false),
d_renderedString(obj.d_renderedString),
d_formattedRenderedString(obj.d_formattedRenderedString),
d_lastHorzFormatting(obj.d_lastHorzFormatting),
d_font(obj.d_font),
d_vertFormatting(obj.d_vertFormatting),
d_horzFormatting(obj.d_horzFormatting),
d_textPropertyName(obj.d_textPropertyName),
d_fontPropertyName(obj.d_fontPropertyName)
{
}
TextComponent& TextComponent::operator=(const TextComponent& other)
{
if (this == &other)
return *this;
FalagardComponentBase::operator=(other);
d_textLogical = other.d_textLogical;
// note we do not assign the BiDiVisualMapping object, we just mark our
// existing one as invalid so it's data gets regenerated next time it's
// needed.
d_bidiDataValid = false;
d_renderedString = other.d_renderedString;
d_formattedRenderedString = other.d_formattedRenderedString;
d_lastHorzFormatting = other.d_lastHorzFormatting;
d_font = other.d_font;
d_vertFormatting = other.d_vertFormatting;
d_horzFormatting = other.d_horzFormatting;
d_textPropertyName = other.d_textPropertyName;
d_fontPropertyName = other.d_fontPropertyName;
return *this;
}
const String& TextComponent::getText() const
{
return d_textLogical;
}
void TextComponent::setText(const String& text)
{
d_textLogical = text;
d_bidiDataValid = false;
}
const String& TextComponent::getFont() const
{
return d_font;
}
void TextComponent::setFont(const String& font)
{
d_font = font;
}
VerticalTextFormatting TextComponent::getVerticalFormatting() const
{
return d_vertFormatting;
}
void TextComponent::setVerticalFormatting(VerticalTextFormatting fmt)
{
d_vertFormatting = fmt;
}
HorizontalTextFormatting TextComponent::getHorizontalFormatting() const
{
return d_horzFormatting;
}
void TextComponent::setHorizontalFormatting(HorizontalTextFormatting fmt)
{
d_horzFormatting = fmt;
}
void TextComponent::setupStringFormatter(const Window& window,
const RenderedString& rendered_string) const
{
const HorizontalTextFormatting horzFormatting = d_horzFormatPropertyName.empty() ? d_horzFormatting :
FalagardXMLHelper::stringToHorzTextFormat(window.getProperty(d_horzFormatPropertyName));
// no formatting change
if (horzFormatting == d_lastHorzFormatting)
{
d_formattedRenderedString->setRenderedString(rendered_string);
return;
}
d_lastHorzFormatting = horzFormatting;
switch(horzFormatting)
{
case HTF_LEFT_ALIGNED:
d_formattedRenderedString =
new LeftAlignedRenderedString(rendered_string);
break;
case HTF_CENTRE_ALIGNED:
d_formattedRenderedString =
new CentredRenderedString(rendered_string);
break;
case HTF_RIGHT_ALIGNED:
d_formattedRenderedString =
new RightAlignedRenderedString(rendered_string);
break;
case HTF_JUSTIFIED:
d_formattedRenderedString =
new JustifiedRenderedString(rendered_string);
break;
case HTF_WORDWRAP_LEFT_ALIGNED:
d_formattedRenderedString =
new RenderedStringWordWrapper
<LeftAlignedRenderedString>(rendered_string);
break;
case HTF_WORDWRAP_CENTRE_ALIGNED:
d_formattedRenderedString =
new RenderedStringWordWrapper
<CentredRenderedString>(rendered_string);
break;
case HTF_WORDWRAP_RIGHT_ALIGNED:
d_formattedRenderedString =
new RenderedStringWordWrapper
<RightAlignedRenderedString>(rendered_string);
break;
case HTF_WORDWRAP_JUSTIFIED:
d_formattedRenderedString =
new RenderedStringWordWrapper
<JustifiedRenderedString>(rendered_string);
break;
}
}
void TextComponent::render_impl(Window& srcWindow, Rect& destRect, const CEGUI::ColourRect* modColours, const Rect* clipper, bool /*clipToDisplay*/) const
{
// get font to use
Font* font;
CEGUI_TRY
{
font = d_fontPropertyName.empty() ?
(d_font.empty() ? srcWindow.getFont() : &FontManager::getSingleton().get(d_font))
: &FontManager::getSingleton().get(srcWindow.getProperty(d_fontPropertyName));
}
CEGUI_CATCH (UnknownObjectException&)
{
font = 0;
}
// exit if we have no font to use.
if (!font)
return;
const RenderedString* rs = &d_renderedString;
// do we fetch text from a property
if (!d_textPropertyName.empty())
{
// fetch text & do bi-directional reordering as needed
String vis;
#ifdef CEGUI_BIDI_SUPPORT
BiDiVisualMapping::StrIndexList l2v, v2l;
d_bidiVisualMapping->reorderFromLogicalToVisual(
srcWindow.getProperty(d_textPropertyName), vis, l2v, v2l);
#else
vis = srcWindow.getProperty(d_textPropertyName);
#endif
// parse string using parser from Window.
d_renderedString =
srcWindow.getRenderedStringParser().parse(vis, font, 0);
}
// do we use a static text string from the looknfeel
else if (!getTextVisual().empty())
// parse string using parser from Window.
d_renderedString = srcWindow.getRenderedStringParser().
parse(getTextVisual(), font, 0);
// do we have to override the font?
else if (font != srcWindow.getFont())
d_renderedString = srcWindow.getRenderedStringParser().
parse(srcWindow.getTextVisual(), font, 0);
// use ready-made RenderedString from the Window itself
else
rs = &srcWindow.getRenderedString();
setupStringFormatter(srcWindow, *rs);
d_formattedRenderedString->format(destRect.getSize());
// Get total formatted height.
const float textHeight = d_formattedRenderedString->getVerticalExtent();
// handle dest area adjustments for vertical formatting.
VerticalTextFormatting vertFormatting = d_vertFormatPropertyName.empty() ? d_vertFormatting :
FalagardXMLHelper::stringToVertTextFormat(srcWindow.getProperty(d_vertFormatPropertyName));
switch(vertFormatting)
{
case VTF_CENTRE_ALIGNED:
destRect.d_top += (destRect.getHeight() - textHeight) * 0.5f;
break;
case VTF_BOTTOM_ALIGNED:
destRect.d_top = destRect.d_bottom - textHeight;
break;
default:
// default is VTF_TOP_ALIGNED, for which we take no action.
break;
}
// calculate final colours to be used
ColourRect finalColours;
initColoursRect(srcWindow, modColours, finalColours);
// offset the font little down so that it's centered within its own spacing
// destRect.d_top += (font->getLineSpacing() - font->getFontHeight()) * 0.5f;
// add geometry for text to the target window.
d_formattedRenderedString->draw(srcWindow.getGeometryBuffer(),
destRect.getPosition(),
&finalColours, clipper);
}
void TextComponent::writeXMLToStream(XMLSerializer& xml_stream) const
{
// opening tag
xml_stream.openTag("TextComponent");
// write out area
d_area.writeXMLToStream(xml_stream);
// write text element
if (!d_font.empty() && !getText().empty())
{
xml_stream.openTag("Text");
if (!d_font.empty())
xml_stream.attribute("font", d_font);
if (!getText().empty())
xml_stream.attribute("string", getText());
xml_stream.closeTag();
}
// write text property element
if (!d_textPropertyName.empty())
{
xml_stream.openTag("TextProperty")
.attribute("name", d_textPropertyName)
.closeTag();
}
// write font property element
if (!d_fontPropertyName.empty())
{
xml_stream.openTag("FontProperty")
.attribute("name", d_fontPropertyName)
.closeTag();
}
// get base class to write colours
writeColoursXML(xml_stream);
// write vert format, allowing base class to do this for us if a propety is in use
if (!writeVertFormatXML(xml_stream))
{
// was not a property, so write out explicit formatting in use
xml_stream.openTag("VertFormat")
.attribute("type", FalagardXMLHelper::vertTextFormatToString(d_vertFormatting))
.closeTag();
}
// write horz format, allowing base class to do this for us if a propety is in use
if (!writeHorzFormatXML(xml_stream))
{
// was not a property, so write out explicit formatting in use
xml_stream.openTag("HorzFormat")
.attribute("type", FalagardXMLHelper::horzTextFormatToString(d_horzFormatting))
.closeTag();
}
// closing tag
xml_stream.closeTag();
}
bool TextComponent::isTextFetchedFromProperty() const
{
return !d_textPropertyName.empty();
}
const String& TextComponent::getTextPropertySource() const
{
return d_textPropertyName;
}
void TextComponent::setTextPropertySource(const String& property)
{
d_textPropertyName = property;
}
bool TextComponent::isFontFetchedFromProperty() const
{
return !d_fontPropertyName.empty();
}
const String& TextComponent::getFontPropertySource() const
{
return d_fontPropertyName;
}
void TextComponent::setFontPropertySource(const String& property)
{
d_fontPropertyName = property;
}
const String& TextComponent::getTextVisual() const
{
// no bidi support
if (!d_bidiVisualMapping)
return d_textLogical;
if (!d_bidiDataValid)
{
d_bidiVisualMapping->updateVisual(d_textLogical);
d_bidiDataValid = true;
}
return d_bidiVisualMapping->getTextVisual();
}
float TextComponent::getHorizontalTextExtent() const
{
return d_formattedRenderedString->getHorizontalExtent();
}
float TextComponent::getVerticalTextExtent() const
{
return d_formattedRenderedString->getVerticalExtent();
}
} // End of CEGUI namespace section
<|endoftext|> |
<commit_before>#include "vm.hpp"
#include "sexpr.hpp"
#include "package.hpp"
namespace vm {
builtin::builtin(std::size_t argc, func_type func) {
assert(argc < argc_mask);
storage.func = func;
// std::clog << "builtin: " << std::bitset<64>(storage.bits) << std::endl;
storage.bits |= argc;
}
builtin::func_type builtin::func() const {
auto res = storage;
res.bits &= ~argc_mask;
// std::clog << "func: " << std::bitset<64>(res.bits) << std::endl;
return res.func;
}
std::size_t builtin::argc() const {
std::size_t res = storage.bits & argc_mask;
// std::clog << "argc: " << res << std::endl;
return res;
}
state::state(std::size_t size):
stack(size) {
frames.reserve(size);
frames.emplace_back(stack.next(), nullptr);
}
record::record(std::map<symbol, value> attrs):
attrs(attrs) {
std::clog << __func__ << " " << this << std::endl;
}
record::~record() {
// std::clog << __func__ << " " << this << std::endl;
}
static void run(state* s, const ir::expr& self);
template<class T>
static value run(state* s, const T& ) {
throw std::runtime_error("run unimplemented for: "
+ tool::type_name(typeid(T)));
}
static constexpr bool debug = false;
static value* top(state* s) {
return s->stack.next() - 1;
}
static void peek(state* s) {
for(std::size_t i = 0; i < s->stack.size(); ++i) {
std::clog << "\t" << i << ":\t" << *(s->stack.next() - (i + 1))<< std::endl;
}
}
template<class ... Args>
static value* push(state* s, Args&& ... args) {
value* res = new (s->stack.allocate(1)) value(std::forward<Args>(args)...);
if(debug) std::clog << "\tpush:\t" << *res << std::endl;
return res;
}
static void pop(state* s, std::size_t n) {
for(std::size_t i=0; i < n; ++i) {
if(debug) std::clog << "\tpop:\t" << *(top(s) - i) << std::endl;
(top(s) - i)->~value();
}
s->stack.deallocate(s->stack.next() - n, n);
}
static value pop(state* s) {
value res = std::move(*top(s));
pop(s, 1);
return res;
}
template<class T>
static void run(state* s, const ir::lit<T>& self) {
push(s, self.value);
}
static void run(state* s, const ir::lit<string>& self) {
push(s, gc::make_ref<string>(self.value));
}
static void run(state* s, const ir::local& self) {
assert(s->frames.back().sp);
push(s, s->frames.back().sp[self.index]);
}
static void run(state* s, const ir::capture& self) {
assert(s->frames.back().cp);
push(s, s->frames.back().cp[self.index]);
}
static void run(state* s, const ir::global& self) {
auto it = s->globals.find(self.name);
assert(it != s->globals.end());
push(s, it->second);
}
static void run(state* s, const ir::block& self) {
for(const ir::expr& e: self.items) {
run(s, e);
}
}
static void run(state* s, const ir::drop& self) {
pop(s, self.count);
}
static void run(state* s, const ir::sel& self) {
auto rec = pop(s).cast<gc::ref<record>>();
auto it = rec->attrs.find(self.attr);
assert(it != rec->attrs.end() && "record attribute error");
push(s, it->second);
}
static void run(state* s, const ir::exit& self) {
value result = pop(s);
pop(s, self.locals);
push(s, std::move(result));
}
static void run(state* s, const ref<ir::branch>& self) {
// evaluate test
const bool test = pop(s).cast<boolean>();
if(test) {
run(s, self->then);
} else {
run(s, self->alt);
}
}
static value apply(state* s, const builtin& self,
const value* args, std::size_t argc);
static value apply(state* s, const ref<closure>& self,
const value* args, std::size_t argc);
static value apply(state* s, const value& self,
const value* args, std::size_t argc);
static value unsaturated(state* s, const value& self, std::size_t expected,
const value* args, std::size_t argc) {
std::clog << "calling: " << self << " " << expected << " / " << argc << std::endl;
throw std::runtime_error("unimplemented: unsaturated");
assert(argc != expected);
if(expected > argc) {
// under-saturated: close over available arguments + function
vector<value> captures(args, args + argc);
captures.emplace_back(self);
// closure call
vector<ir::expr> items; items.reserve(1 + argc + expected);
// push closure
items.emplace_back(ir::capture(argc));
// push argc leading args from closure
for(std::size_t i = 0; i < argc; ++i) {
items.emplace_back(ir::capture(i));
}
// push remaining args come from stack
for(std::size_t i = 0, n = expected - argc; i < n; ++i) {
items.emplace_back(ir::local(i));
}
// push saturated call
items.emplace_back(ir::call{argc + expected});
return gc::make_ref<closure>(expected - argc, ir::block{std::move(items)}, std::move(captures));
} else {
// over-saturated: call expected arguments then call remaining args
// regularly
value tmp = apply(s, self, args, expected);
return tmp.match([&](const auto& self) {
return apply(s, self, args + expected, argc - expected);
});
}
}
// builtin call
static value apply(state* s, const builtin& self,
const value* args, std::size_t argc) {
if(self.argc() != argc) {
return unsaturated(s, self, self.argc(), args, argc);
}
return self.func()(args);
}
// closure call
static value apply(state* s, const gc::ref<closure>& self,
const value* args, std::size_t argc) {
if(self->argc != argc) {
return unsaturated(s, self, self->argc, args, argc);
}
// push frame
s->frames.emplace_back(args, self->captures.data());
// evaluate stuff
run(s, self->body);
// pop result
value result = pop(s);
// sanity check
assert(s->stack.next() - s->frames.back().sp == argc);
// pop frame
s->frames.pop_back();
return result;
}
template<class T>
static value apply(state* s, const T& self, const value* args, std::size_t argc) {
throw std::runtime_error("type error in application: "
+ tool::type_name(typeid(T)));
}
// main dispatch
static value call(state* s, const value* args, std::size_t argc) {
const value& self = args[-1];
// switch(self.type()) {
// case value::index_of<builtin>::value:
// return apply(s, self.cast<builtin>(), args, argc);
// case value::index_of<gc::ref<closure>>::value:
// return apply(s, self.cast<gc::ref<closure>>(), args, argc);
// default: break;
// }
// delegate call based on actual function type
return self.match([&](const auto& self) {
return apply(s, self, args, argc);
});
}
static void run(state* s, const ir::call& self) {
// arguments pointer
const value* args = s->stack.next() - self.argc;
// call function: call must cleanup the stack leaving exactly the function
// and its arguments in place
value result = call(s, args, self.argc);
// pop arguments
pop(s, self.argc);
// push function result
*top(s) = std::move(result);
}
static void run(state* s, const ref<ir::closure>& self) {
// std::clog << "closure: " << repr(self) << std::endl;
// result
auto res = gc::make_ref<closure>(self->argc, self->body);
// note: pushing closure *before* filling captures so that it can be
// captured itself (recursive definitions)
push(s, res);
const value* first = s->stack.next();
// push captured variables
for(const ir::expr& c : self->captures) {
run(s, c);
}
// TODO move values from the stack into vector
std::vector<value> captures(first, first + self->captures.size());
// pop captures
pop(s, self->captures.size());
// set result captures
res->captures = std::move(captures);
}
static void run(state* s, const ir::import& self) {
const state& pkg = package::import<state>(self.package, [&] {
state s;
package::iter(self.package, [&](ast::expr self) {
const ir::expr c = ir::compile(self);
run(&s, c);
});
return s;
});
push(s, gc::make_ref<record>(pkg.globals));
}
static void run(state* s, const ir::def& self) {
assert(s->frames.size() == 1 && "toplevel definition in local scope");
s->def(self.name, pop(s));
push(s, unit());
}
static void run(state* s, const ref<ir::use>& self) {
assert(s->frames.size() == 1 && "non-toplevel use unimplemented");
// evalute use result
run(s, self->env);
value env = pop(s);
// TODO compile local uses properly with type-system help
for(const auto& it: env.cast<gc::ref<record>>()->attrs) {
s->def(it.first, it.second);
}
push(s, unit());
}
static void run(state* s, const ir::expr& self) {
self.match([&](const auto& self) {
run(s, self);
});
}
////////////////////////////////////////////////////////////////////////////////
value eval(state* s, const ir::expr& self) {
// std::clog << repr(self) << std::endl;
run(s, self);
value res = pop(s);
collect(s);
return res;
}
std::ostream& operator<<(std::ostream& out, const value& self) {
self.match([&](const auto& self) { out << self; },
[&](const unit& self) { out << "()"; },
[&](const gc::ref<closure>& ) { out << "#<closure>"; },
[&](const builtin& ) { out << "#<builtin>"; },
[&](const boolean& self) { out << (self ? "true" : "false"); },
[&](const gc::ref<string>& self) { out << '"' << *self << '"';},
[&](const gc::ref<record>& self) {
out << "{";
bool first=true;
for(const auto& it: self->attrs) {
if(first) first = false;
else out << "; ";
out << it.first << ": " << it.second;
}
out << "}";
});
return out;
}
////////////////////////////////////////////////////////////////////////////////
struct mark_visitor {
template<class T>
void operator()(T self, bool debug) const { }
template<class T>
void operator()(gc::ref<T> self, bool debug) const {
if(debug) std::clog << " marking: " << self.get() << std::endl;
self.mark();
}
void operator()(gc::ref<record> self, bool debug) const {
self.mark();
for(auto& it : self->attrs) {
if(debug) std::clog << " visiting: " << it.first << std::endl;
it.second.visit(*this, debug);
}
}
};
static void mark(state* self, bool debug) {
for(auto& it : self->globals) {
if(debug) std::clog << "visiting: " << it.first << std::endl;
it.second.visit(mark_visitor(), debug);
}
}
void collect(state* self) {
mark(self, false);
gc::sweep();
}
}
<commit_msg>comments<commit_after>#include "vm.hpp"
#include "sexpr.hpp"
#include "package.hpp"
namespace vm {
builtin::builtin(std::size_t argc, func_type func) {
assert(argc < argc_mask);
storage.func = func;
// std::clog << "builtin: " << std::bitset<64>(storage.bits) << std::endl;
storage.bits |= argc;
}
builtin::func_type builtin::func() const {
auto res = storage;
res.bits &= ~argc_mask;
// std::clog << "func: " << std::bitset<64>(res.bits) << std::endl;
return res.func;
}
std::size_t builtin::argc() const {
std::size_t res = storage.bits & argc_mask;
// std::clog << "argc: " << res << std::endl;
return res;
}
state::state(std::size_t size):
stack(size) {
frames.reserve(size);
frames.emplace_back(stack.next(), nullptr);
}
record::record(std::map<symbol, value> attrs):
attrs(attrs) {
std::clog << __func__ << " " << this << std::endl;
}
record::~record() {
// std::clog << __func__ << " " << this << std::endl;
}
static void run(state* s, const ir::expr& self);
template<class T>
static value run(state* s, const T& ) {
throw std::runtime_error("run unimplemented for: "
+ tool::type_name(typeid(T)));
}
static constexpr bool debug = false;
static value* top(state* s) {
return s->stack.next() - 1;
}
static void peek(state* s) {
for(std::size_t i = 0; i < s->stack.size(); ++i) {
std::clog << "\t" << i << ":\t" << *(s->stack.next() - (i + 1))<< std::endl;
}
}
template<class ... Args>
static value* push(state* s, Args&& ... args) {
value* res = new (s->stack.allocate(1)) value(std::forward<Args>(args)...);
// if(debug) std::clog << "\tpush:\t" << *res << std::endl;
return res;
}
static void pop(state* s, std::size_t n) {
// for(std::size_t i=0; i < n; ++i) {
// if(debug) std::clog << "\tpop:\t" << *(top(s) - i) << std::endl;
// (top(s) - i)->~value();
// }
s->stack.deallocate(s->stack.next() - n, n);
}
static value pop(state* s) {
value res = std::move(*top(s));
pop(s, 1);
return res;
}
template<class T>
static void run(state* s, const ir::lit<T>& self) {
push(s, self.value);
}
static void run(state* s, const ir::lit<string>& self) {
push(s, gc::make_ref<string>(self.value));
}
static void run(state* s, const ir::local& self) {
assert(s->frames.back().sp);
push(s, s->frames.back().sp[self.index]);
}
static void run(state* s, const ir::capture& self) {
assert(s->frames.back().cp);
push(s, s->frames.back().cp[self.index]);
}
static void run(state* s, const ir::global& self) {
auto it = s->globals.find(self.name);
assert(it != s->globals.end());
push(s, it->second);
}
static void run(state* s, const ir::block& self) {
for(const ir::expr& e: self.items) {
run(s, e);
}
}
static void run(state* s, const ir::drop& self) {
pop(s, self.count);
}
static void run(state* s, const ir::sel& self) {
auto rec = pop(s).cast<gc::ref<record>>();
auto it = rec->attrs.find(self.attr);
assert(it != rec->attrs.end() && "record attribute error");
push(s, it->second);
}
static void run(state* s, const ir::exit& self) {
value result = pop(s);
pop(s, self.locals);
push(s, std::move(result));
}
static void run(state* s, const ref<ir::branch>& self) {
// evaluate test
const bool test = pop(s).cast<boolean>();
if(test) {
run(s, self->then);
} else {
run(s, self->alt);
}
}
static value apply(state* s, const builtin& self,
const value* args, std::size_t argc);
static value apply(state* s, const ref<closure>& self,
const value* args, std::size_t argc);
static value apply(state* s, const value& self,
const value* args, std::size_t argc);
static value unsaturated(state* s, const value& self, std::size_t expected,
const value* args, std::size_t argc) {
std::clog << "calling: " << self << " " << expected << " / " << argc << std::endl;
throw std::runtime_error("unimplemented: unsaturated");
assert(argc != expected);
if(expected > argc) {
// under-saturated: close over available arguments + function
vector<value> captures(args, args + argc);
captures.emplace_back(self);
// closure call
vector<ir::expr> items; items.reserve(1 + argc + expected);
// push closure
items.emplace_back(ir::capture(argc));
// push argc leading args from closure
for(std::size_t i = 0; i < argc; ++i) {
items.emplace_back(ir::capture(i));
}
// push remaining args come from stack
for(std::size_t i = 0, n = expected - argc; i < n; ++i) {
items.emplace_back(ir::local(i));
}
// push saturated call
items.emplace_back(ir::call{argc + expected});
return gc::make_ref<closure>(expected - argc, ir::block{std::move(items)}, std::move(captures));
} else {
// over-saturated: call expected arguments then call remaining args
// regularly
value tmp = apply(s, self, args, expected);
return tmp.match([&](const auto& self) {
return apply(s, self, args + expected, argc - expected);
});
}
}
// builtin call
static value apply(state* s, const builtin& self,
const value* args, std::size_t argc) {
if(self.argc() != argc) {
return unsaturated(s, self, self.argc(), args, argc);
}
return self.func()(args);
}
// closure call
static value apply(state* s, const gc::ref<closure>& self,
const value* args, std::size_t argc) {
if(self->argc != argc) {
return unsaturated(s, self, self->argc, args, argc);
}
// push frame
s->frames.emplace_back(args, self->captures.data());
// evaluate stuff
run(s, self->body);
// pop result
value result = pop(s);
// sanity check
assert(s->stack.next() - s->frames.back().sp == argc);
// pop frame
s->frames.pop_back();
return result;
}
template<class T>
static value apply(state* s, const T& self, const value* args, std::size_t argc) {
throw std::runtime_error("type error in application: "
+ tool::type_name(typeid(T)));
}
// main dispatch
static value call(state* s, const value* args, std::size_t argc) {
const value& self = args[-1];
// switch(self.type()) {
// case value::index_of<builtin>::value:
// return apply(s, self.cast<builtin>(), args, argc);
// case value::index_of<gc::ref<closure>>::value:
// return apply(s, self.cast<gc::ref<closure>>(), args, argc);
// default: break;
// }
// delegate call based on actual function type
return self.match([&](const auto& self) {
return apply(s, self, args, argc);
});
}
static void run(state* s, const ir::call& self) {
// arguments pointer
const value* args = s->stack.next() - self.argc;
// call function: call must cleanup the stack leaving exactly the function
// and its arguments in place
value result = call(s, args, self.argc);
// pop arguments
pop(s, self.argc);
// push function result
*top(s) = std::move(result);
}
static void run(state* s, const ref<ir::closure>& self) {
// std::clog << "closure: " << repr(self) << std::endl;
// result
auto res = gc::make_ref<closure>(self->argc, self->body);
// note: pushing closure *before* filling captures so that it can be
// captured itself (recursive definitions)
push(s, res);
const value* first = s->stack.next();
// push captured variables
for(const ir::expr& c : self->captures) {
run(s, c);
}
// TODO move values from the stack into vector
std::vector<value> captures(first, first + self->captures.size());
// pop captures
pop(s, self->captures.size());
// set result captures
res->captures = std::move(captures);
}
static void run(state* s, const ir::import& self) {
const state& pkg = package::import<state>(self.package, [&] {
state s;
package::iter(self.package, [&](ast::expr self) {
const ir::expr c = ir::compile(self);
run(&s, c);
});
return s;
});
push(s, gc::make_ref<record>(pkg.globals));
}
static void run(state* s, const ir::def& self) {
assert(s->frames.size() == 1 && "toplevel definition in local scope");
s->def(self.name, pop(s));
push(s, unit());
}
static void run(state* s, const ref<ir::use>& self) {
assert(s->frames.size() == 1 && "non-toplevel use unimplemented");
// evalute use result
run(s, self->env);
value env = pop(s);
// TODO compile local uses properly with type-system help
for(const auto& it: env.cast<gc::ref<record>>()->attrs) {
s->def(it.first, it.second);
}
push(s, unit());
}
static void run(state* s, const ir::expr& self) {
self.match([&](const auto& self) {
run(s, self);
});
}
////////////////////////////////////////////////////////////////////////////////
value eval(state* s, const ir::expr& self) {
// std::clog << repr(self) << std::endl;
run(s, self);
value res = pop(s);
collect(s);
return res;
}
std::ostream& operator<<(std::ostream& out, const value& self) {
self.match([&](const auto& self) { out << self; },
[&](const unit& self) { out << "()"; },
[&](const gc::ref<closure>& ) { out << "#<closure>"; },
[&](const builtin& ) { out << "#<builtin>"; },
[&](const boolean& self) { out << (self ? "true" : "false"); },
[&](const gc::ref<string>& self) { out << '"' << *self << '"';},
[&](const gc::ref<record>& self) {
out << "{";
bool first=true;
for(const auto& it: self->attrs) {
if(first) first = false;
else out << "; ";
out << it.first << ": " << it.second;
}
out << "}";
});
return out;
}
////////////////////////////////////////////////////////////////////////////////
struct mark_visitor {
template<class T>
void operator()(T self, bool debug) const { }
template<class T>
void operator()(gc::ref<T> self, bool debug) const {
if(debug) std::clog << " marking: " << self.get() << std::endl;
self.mark();
}
void operator()(gc::ref<record> self, bool debug) const {
self.mark();
for(auto& it : self->attrs) {
if(debug) std::clog << " visiting: " << it.first << std::endl;
it.second.visit(*this, debug);
}
}
};
static void mark(state* self, bool debug) {
for(auto& it : self->globals) {
if(debug) std::clog << "visiting: " << it.first << std::endl;
it.second.visit(mark_visitor(), debug);
}
}
void collect(state* self) {
mark(self, false);
gc::sweep();
}
}
<|endoftext|> |
<commit_before>#pragma once
#include <tuple>
#include <vector>
#include <memory>
#include <unordered_set>
#include <unordered_map>
#include "object_pool.hpp"
namespace Granite
{
class Entity;
struct ComponentIDMapping
{
public:
template <typename T>
static uint32_t get_id()
{
static uint32_t id = ids++;
return id;
}
template <typename... Ts>
static uint32_t get_group_id()
{
static uint32_t id = group_ids++;
return id;
}
private:
static uint32_t ids;
static uint32_t group_ids;
};
struct ComponentBase
{
};
class EntityGroupBase
{
public:
virtual ~EntityGroupBase() = default;
virtual void add_entity(const Entity &entity) = 0;
virtual void remove_component(uint32_t id, ComponentBase *component) = 0;
};
template <typename... Ts>
class EntityGroup : public EntityGroupBase
{
public:
EntityGroup()
{
set_ids<Ts...>(group_ids);
}
void add_entity(const Entity &entity) override final
{
}
void remove_component(uint32_t id, ComponentBase *component) override final
{
}
private:
std::vector<std::tuple<Ts *...>> groups;
std::vector<Entity *> entities;
uint32_t group_ids[sizeof...(Ts)];
template <typename U, typename... Us>
void set_ids(uint32_t *ids)
{
*ids = ComponentIDMapping::get_id<U>();
set_ids<Us...>(ids + 1);
}
template <typename U>
void set_ids(uint32_t *ids)
{
*ids = ComponentIDMapping::get_id<U>();
}
};
class ComponentAllocatorBase
{
public:
virtual ~ComponentAllocatorBase() = default;
virtual void free_component(ComponentBase *component) = 0;
};
template <typename T>
struct ComponentAllocator : public ComponentAllocatorBase
{
Util::ObjectPool<T> pool;
void free_component(ComponentBase *component) override final
{
pool.free(static_cast<T *>(component));
}
};
struct Entity
{
std::unordered_map<uint32_t, ComponentBase *> components;
};
using EntityHandle = std::shared_ptr<Entity>;
class EntityPool
{
public:
EntityHandle create_entity()
{
return std::make_shared<Entity>();
}
template <typename T, typename... Ts>
void allocate_component(Entity &entity, Ts&&... ts)
{
uint32_t id = ComponentIDMapping::get_id<T>();
auto itr = components.find(id);
if (itr == end(components))
itr = components.insert(make_pair(id, std::unique_ptr<ComponentAllocatorBase>(new ComponentAllocator<T>)));
auto *allocator = static_cast<ComponentAllocator<T> *>(itr->second.get());
auto &comp = entity.components[id];
if (comp)
{
allocator->free_component(comp);
comp = allocator->pool.allocate(std::forward<Ts>(ts)...);
}
else
{
comp = allocator->pool.allocate(std::forward<Ts>(ts)...);
for (auto &group : component_to_groups[id])
groups[group]->add_entity(entity);
}
}
void free_component(uint32_t id, ComponentBase *component)
{
components[id]->free_component(component);
for (auto &group : component_to_groups[id])
groups[group]->remove_component(id, component);
}
private:
Util::ObjectPool<Entity> entities;
std::unordered_map<uint32_t, std::unique_ptr<EntityGroupBase>> groups;
std::unordered_map<uint32_t, std::unique_ptr<ComponentAllocatorBase>> components;
std::unordered_map<uint32_t, std::unordered_set<uint32_t>> component_to_groups;
};
}<commit_msg>Plug further.<commit_after>#pragma once
#include <tuple>
#include <vector>
#include <memory>
#include <unordered_set>
#include <unordered_map>
#include <algorithm>
#include "object_pool.hpp"
namespace Granite
{
class Entity;
struct ComponentIDMapping
{
public:
template <typename T>
static uint32_t get_id()
{
static uint32_t id = ids++;
return id;
}
template <typename... Ts>
static uint32_t get_group_id()
{
static uint32_t id = group_ids++;
return id;
}
private:
static uint32_t ids;
static uint32_t group_ids;
};
struct ComponentBase
{
};
class EntityGroupBase
{
public:
virtual ~EntityGroupBase() = default;
virtual void add_entity(const Entity &entity) = 0;
virtual void remove_component(uint32_t id, ComponentBase *component) = 0;
};
class Entity
{
public:
bool has_component(uint32_t id) const
{
auto itr = components.find(id);
return itr != std::end(components) && itr->second;
}
template <typename T>
T *get_component()
{
auto itr = components.find(ComponentIDMapping::get_id<T>());
if (itr == std::end(components))
return nullptr;
return static_cast<T *>(itr->second);
}
template <typename T>
const T *get_component() const
{
auto itr = components.find(ComponentIDMapping::get_id<T>());
if (itr == std::end(components))
return nullptr;
return static_cast<T *>(itr->second);
}
std::unordered_map<uint32_t, ComponentBase *> &get_components()
{
return components;
}
private:
std::unordered_map<uint32_t, ComponentBase *> components;
};
template <typename... Ts>
class EntityGroup : public EntityGroupBase
{
public:
EntityGroup()
{
set_ids<Ts...>(group_ids);
}
void add_entity(Entity &entity) override final
{
if (has_all_components<Ts...>(entity))
{
entities.push_back(&entity);
groups.push_back(make_tuple(entity.get_component<Ts>()...));
}
}
void remove_component(uint32_t id, ComponentBase *component) override final
{
auto itr = std::find_if(begin(groups), end(groups), [&](const std::tuple<Ts *...> &t) {
return has_component(t, component);
});
if (itr == end(groups))
return;
auto offset = itr - begin(groups);
if (offset != groups.size() - 1)
{
std::swap(groups[offset], groups.back());
std::swap(entities[offset], entities.back());
}
groups.pop_back();
entities.pop_back();
}
private:
std::vector<std::tuple<Ts *...>> groups;
std::vector<Entity *> entities;
uint32_t group_ids[sizeof...(Ts)];
template <typename U, typename... Us>
void set_ids(uint32_t *ids)
{
*ids = ComponentIDMapping::get_id<U>();
set_ids<Us...>(ids + 1);
}
template <typename U>
void set_ids(uint32_t *ids)
{
*ids = ComponentIDMapping::get_id<U>();
}
template <typename U, typename... Us>
bool has_all_components(const Entity &entity)
{
return entity.has_component(ComponentIDMapping::get_id<U>()) &&
has_all_components<Us...>(entity);
}
template <typename U>
bool has_all_components(const Entity &entity)
{
return entity.has_component(ComponentIDMapping::get_id<U>());
}
};
class ComponentAllocatorBase
{
public:
virtual ~ComponentAllocatorBase() = default;
virtual void free_component(ComponentBase *component) = 0;
};
template <typename T>
struct ComponentAllocator : public ComponentAllocatorBase
{
Util::ObjectPool<T> pool;
void free_component(ComponentBase *component) override final
{
pool.free(static_cast<T *>(component));
}
};
using EntityHandle = std::shared_ptr<Entity>;
class EntityPool
{
public:
EntityHandle create_entity()
{
auto itr = EntityHandle(entity_pool.allocate(), EntityDeleter(this));
entities.push_back(itr.get());
return itr;
}
void delete_entity(Entity *entity)
{
auto &components = entity->get_components();
for (auto &component : components)
if (component.second)
free_component(component.first, component.second);
entity_pool.free(entity);
auto itr = std::find(std::begin(entities), std::end(entities), entity);
auto offset = itr - std::begin(entities);
if (offset != entities.size() - 1)
std::swap(entities[offset], entities.back());
entities.pop_back();
}
template <typename... Ts>
std::vector<std::tuple<Ts *...>> &get_component_group()
{
uint32_t group_id = ComponentIDMapping::get_group_id<Ts...>();
auto itr = groups.find(group_id);
if (itr == std::end(groups))
{
register_group<Ts...>(group_id);
itr = groups.insert(std::make_pair(group_id, std::unique_ptr<EntityGroupBase>(new EntityGroup<Ts...>())));
auto *group = static_cast<EntityGroup<Ts...> *>(itr->second.get());
for (auto &entity : entities)
group->add_entity(entity);
}
auto *group = static_cast<EntityGroup<Ts...> *>(itr->second.get());
return group;
}
template <typename T, typename... Ts>
void allocate_component(Entity &entity, Ts&&... ts)
{
uint32_t id = ComponentIDMapping::get_id<T>();
auto itr = components.find(id);
if (itr == std::end(components))
itr = components.insert(std::make_pair(id, std::unique_ptr<ComponentAllocatorBase>(new ComponentAllocator<T>)));
auto *allocator = static_cast<ComponentAllocator<T> *>(itr->second.get());
auto &comp = entity.components[id];
if (comp)
{
allocator->free_component(comp);
comp = allocator->pool.allocate(std::forward<Ts>(ts)...);
for (auto &group : component_to_groups[id])
groups[group]->add_entity(entity);
}
else
{
comp = allocator->pool.allocate(std::forward<Ts>(ts)...);
for (auto &group : component_to_groups[id])
groups[group]->add_entity(entity);
}
}
void free_component(uint32_t id, ComponentBase *component)
{
components[id]->free_component(component);
for (auto &group : component_to_groups[id])
groups[group]->remove_component(id, component);
}
private:
Util::ObjectPool<Entity> entity_pool;
std::unordered_map<uint32_t, std::unique_ptr<EntityGroupBase>> groups;
std::unordered_map<uint32_t, std::unique_ptr<ComponentAllocatorBase>> components;
std::unordered_map<uint32_t, std::unordered_set<uint32_t>> component_to_groups;
std::vector<Entity *> entities;
template <typename U, typename... Us>
void register_group(uint32_t group_id)
{
component_to_groups[ComponentIDMapping::get_id<U>()].insert(group_id);
register_group<Us...>(group_id);
}
template <typename U>
void register_group(uint32_t group_id)
{
component_to_groups[ComponentIDMapping::get_id<U>()].insert(group_id);
}
struct EntityDeleter
{
EntityDeleter(EntityPool *pool)
: pool(pool)
{
}
void operator()(Entity *entity)
{
pool->delete_entity(entity);
}
EntityPool *pool;
};
};
}<|endoftext|> |
<commit_before>/*
* Copyright (c) 2007 The Hewlett-Packard Development Company
* All rights reserved.
*
* Redistribution and use of this software in source and binary forms,
* with or without modification, are permitted provided that the
* following conditions are met:
*
* The software must be used only for Non-Commercial Use which means any
* use which is NOT directed to receiving any direct monetary
* compensation for, or commercial advantage from such use. Illustrative
* examples of non-commercial use are academic research, personal study,
* teaching, education and corporate research & development.
* Illustrative examples of commercial use are distributing products for
* commercial advantage and providing services using the software for
* commercial advantage.
*
* If you wish to use this software or functionality therein that may be
* covered by patents for commercial use, please contact:
* Director of Intellectual Property Licensing
* Office of Strategy and Technology
* Hewlett-Packard Company
* 1501 Page Mill Road
* Palo Alto, California 94304
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer. Redistributions
* in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution. Neither the name of
* the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission. No right of
* sublicense is granted herewith. Derivatives of the software and
* output created using the software may be prepared, but only for
* Non-Commercial Uses. Derivatives of the software may be shared with
* others provided: (i) the others agree to abide by the list of
* conditions herein which includes the Non-Commercial Use restrictions;
* and (ii) such Derivatives of the software include the above copyright
* notice to acknowledge the contribution from this software where
* applicable, this list of conditions and the disclaimer below.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Gabe Black
*/
#include "arch/x86/emulenv.hh"
#include "base/misc.hh"
using namespace X86ISA;
void EmulEnv::doModRM(const ExtMachInst & machInst)
{
assert(machInst.modRM.mod != 3);
//Use the SIB byte for addressing if the modrm byte calls for it.
if (machInst.modRM.rm == 4 && machInst.addrSize != 2) {
scale = 1 << machInst.sib.scale;
index = machInst.sib.index | (machInst.rex.x << 3);
base = machInst.sib.base | (machInst.rex.b << 3);
//In this special case, we don't use a base. The displacement also
//changes, but that's managed by the predecoder.
if (machInst.sib.base == INTREG_RBP && machInst.modRM.mod == 0)
base = NUM_INTREGS;
//In -this- special case, we don't use an index.
if (machInst.sib.index == INTREG_RSP)
index = NUM_INTREGS;
} else {
if (machInst.addrSize == 2) {
warn("I'm not really using 16 bit MODRM like I'm supposed to!\n");
} else {
scale = 0;
base = machInst.modRM.rm | (machInst.rex.b << 3);
if (machInst.modRM.mod == 0 && machInst.modRM.rm == 5) {
base = NUM_INTREGS;
//Since we need to use a different encoding of this
//instruction anyway, just ignore the base in those cases
// if (machInst.mode.submode == SixtyFourBitMode)
// base = NUM_INTREGS+7;
}
}
}
}
<commit_msg>X86: Fix special case with SIB index register and REX prefix.<commit_after>/*
* Copyright (c) 2007 The Hewlett-Packard Development Company
* All rights reserved.
*
* Redistribution and use of this software in source and binary forms,
* with or without modification, are permitted provided that the
* following conditions are met:
*
* The software must be used only for Non-Commercial Use which means any
* use which is NOT directed to receiving any direct monetary
* compensation for, or commercial advantage from such use. Illustrative
* examples of non-commercial use are academic research, personal study,
* teaching, education and corporate research & development.
* Illustrative examples of commercial use are distributing products for
* commercial advantage and providing services using the software for
* commercial advantage.
*
* If you wish to use this software or functionality therein that may be
* covered by patents for commercial use, please contact:
* Director of Intellectual Property Licensing
* Office of Strategy and Technology
* Hewlett-Packard Company
* 1501 Page Mill Road
* Palo Alto, California 94304
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer. Redistributions
* in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution. Neither the name of
* the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission. No right of
* sublicense is granted herewith. Derivatives of the software and
* output created using the software may be prepared, but only for
* Non-Commercial Uses. Derivatives of the software may be shared with
* others provided: (i) the others agree to abide by the list of
* conditions herein which includes the Non-Commercial Use restrictions;
* and (ii) such Derivatives of the software include the above copyright
* notice to acknowledge the contribution from this software where
* applicable, this list of conditions and the disclaimer below.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Gabe Black
*/
#include "arch/x86/emulenv.hh"
#include "base/misc.hh"
using namespace X86ISA;
void EmulEnv::doModRM(const ExtMachInst & machInst)
{
assert(machInst.modRM.mod != 3);
//Use the SIB byte for addressing if the modrm byte calls for it.
if (machInst.modRM.rm == 4 && machInst.addrSize != 2) {
scale = 1 << machInst.sib.scale;
index = machInst.sib.index | (machInst.rex.x << 3);
base = machInst.sib.base | (machInst.rex.b << 3);
//In this special case, we don't use a base. The displacement also
//changes, but that's managed by the predecoder.
if (machInst.sib.base == INTREG_RBP && machInst.modRM.mod == 0)
base = NUM_INTREGS;
//In -this- special case, we don't use an index.
if (index == INTREG_RSP)
index = NUM_INTREGS;
} else {
if (machInst.addrSize == 2) {
warn("I'm not really using 16 bit MODRM like I'm supposed to!\n");
} else {
scale = 0;
base = machInst.modRM.rm | (machInst.rex.b << 3);
if (machInst.modRM.mod == 0 && machInst.modRM.rm == 5) {
//Since we need to use a different encoding of this
//instruction anyway, just ignore the base in those cases
base = NUM_INTREGS;
}
}
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2007 The Hewlett-Packard Development Company
* All rights reserved.
*
* Redistribution and use of this software in source and binary forms,
* with or without modification, are permitted provided that the
* following conditions are met:
*
* The software must be used only for Non-Commercial Use which means any
* use which is NOT directed to receiving any direct monetary
* compensation for, or commercial advantage from such use. Illustrative
* examples of non-commercial use are academic research, personal study,
* teaching, education and corporate research & development.
* Illustrative examples of commercial use are distributing products for
* commercial advantage and providing services using the software for
* commercial advantage.
*
* If you wish to use this software or functionality therein that may be
* covered by patents for commercial use, please contact:
* Director of Intellectual Property Licensing
* Office of Strategy and Technology
* Hewlett-Packard Company
* 1501 Page Mill Road
* Palo Alto, California 94304
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer. Redistributions
* in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution. Neither the name of
* the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission. No right of
* sublicense is granted herewith. Derivatives of the software and
* output created using the software may be prepared, but only for
* Non-Commercial Uses. Derivatives of the software may be shared with
* others provided: (i) the others agree to abide by the list of
* conditions herein which includes the Non-Commercial Use restrictions;
* and (ii) such Derivatives of the software include the above copyright
* notice to acknowledge the contribution from this software where
* applicable, this list of conditions and the disclaimer below.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Gabe Black
*/
#ifndef __ARCH_X86_UTILITY_HH__
#define __ARCH_X86_UTILITY_HH__
#include "arch/x86/types.hh"
#include "base/misc.hh"
class ThreadContext;
namespace X86ISA
{
static inline bool
inUserMode(ThreadContext *tc)
{
return false;
}
inline ExtMachInst
makeExtMI(MachInst inst, ThreadContext * xc) {
return inst;
}
inline bool isCallerSaveIntegerRegister(unsigned int reg) {
panic("register classification not implemented");
return false;
}
inline bool isCalleeSaveIntegerRegister(unsigned int reg) {
panic("register classification not implemented");
return false;
}
inline bool isCallerSaveFloatRegister(unsigned int reg) {
panic("register classification not implemented");
return false;
}
inline bool isCalleeSaveFloatRegister(unsigned int reg) {
panic("register classification not implemented");
return false;
}
// Instruction address compression hooks
inline Addr realPCToFetchPC(const Addr &addr)
{
return addr;
}
inline Addr fetchPCToRealPC(const Addr &addr)
{
return addr;
}
// the size of "fetched" instructions (not necessarily the size
// of real instructions for PISA)
inline size_t fetchInstSize()
{
return sizeof(MachInst);
}
/**
* Function to insure ISA semantics about 0 registers.
* @param tc The thread context.
*/
template <class TC>
void zeroRegisters(TC *tc);
inline void initCPU(ThreadContext *tc, int cpuId)
{
panic("initCPU not implemented!\n");
}
};
#endif // __ARCH_X86_UTILITY_HH__
<commit_msg>Added missing include.<commit_after>/*
* Copyright (c) 2007 The Hewlett-Packard Development Company
* All rights reserved.
*
* Redistribution and use of this software in source and binary forms,
* with or without modification, are permitted provided that the
* following conditions are met:
*
* The software must be used only for Non-Commercial Use which means any
* use which is NOT directed to receiving any direct monetary
* compensation for, or commercial advantage from such use. Illustrative
* examples of non-commercial use are academic research, personal study,
* teaching, education and corporate research & development.
* Illustrative examples of commercial use are distributing products for
* commercial advantage and providing services using the software for
* commercial advantage.
*
* If you wish to use this software or functionality therein that may be
* covered by patents for commercial use, please contact:
* Director of Intellectual Property Licensing
* Office of Strategy and Technology
* Hewlett-Packard Company
* 1501 Page Mill Road
* Palo Alto, California 94304
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer. Redistributions
* in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution. Neither the name of
* the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission. No right of
* sublicense is granted herewith. Derivatives of the software and
* output created using the software may be prepared, but only for
* Non-Commercial Uses. Derivatives of the software may be shared with
* others provided: (i) the others agree to abide by the list of
* conditions herein which includes the Non-Commercial Use restrictions;
* and (ii) such Derivatives of the software include the above copyright
* notice to acknowledge the contribution from this software where
* applicable, this list of conditions and the disclaimer below.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Gabe Black
*/
#ifndef __ARCH_X86_UTILITY_HH__
#define __ARCH_X86_UTILITY_HH__
#include "arch/x86/types.hh"
#include "base/misc.hh"
#include "sim/host.hh"
class ThreadContext;
namespace X86ISA
{
static inline bool
inUserMode(ThreadContext *tc)
{
return false;
}
inline ExtMachInst
makeExtMI(MachInst inst, ThreadContext * xc) {
return inst;
}
inline bool isCallerSaveIntegerRegister(unsigned int reg) {
panic("register classification not implemented");
return false;
}
inline bool isCalleeSaveIntegerRegister(unsigned int reg) {
panic("register classification not implemented");
return false;
}
inline bool isCallerSaveFloatRegister(unsigned int reg) {
panic("register classification not implemented");
return false;
}
inline bool isCalleeSaveFloatRegister(unsigned int reg) {
panic("register classification not implemented");
return false;
}
// Instruction address compression hooks
inline Addr realPCToFetchPC(const Addr &addr)
{
return addr;
}
inline Addr fetchPCToRealPC(const Addr &addr)
{
return addr;
}
// the size of "fetched" instructions (not necessarily the size
// of real instructions for PISA)
inline size_t fetchInstSize()
{
return sizeof(MachInst);
}
/**
* Function to insure ISA semantics about 0 registers.
* @param tc The thread context.
*/
template <class TC>
void zeroRegisters(TC *tc);
inline void initCPU(ThreadContext *tc, int cpuId)
{
panic("initCPU not implemented!\n");
}
};
#endif // __ARCH_X86_UTILITY_HH__
<|endoftext|> |
<commit_before>//
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//
#pragma once
#include "ProfilingEvent.hpp"
#include <armnn/utility/IgnoreUnused.hpp>
#include "armnn/IProfiler.hpp"
#include "WallClockTimer.hpp"
#include <chrono>
#include <iosfwd>
#include <ctime>
#include <vector>
#include <stack>
#include <map>
namespace armnn
{
// Simple single-threaded profiler.
// Tracks events reported by BeginEvent()/EndEvent() and outputs detailed information and stats when
// Profiler::AnalyzeEventsAndWriteResults() is called.
class Profiler final : public IProfiler
{
public:
Profiler();
~Profiler();
using InstrumentPtr = std::unique_ptr<Instrument>;
// Marks the beginning of a user-defined event.
// No attempt will be made to copy the name string: it must be known at compile time.
Event* BeginEvent(const BackendId& backendId, const std::string& name, std::vector<InstrumentPtr>&& instruments);
// Marks the end of a user-defined event.
void EndEvent(Event* event);
// Enables/disables profiling.
void EnableProfiling(bool enableProfiling) override;
// Checks if profiling is enabled.
bool IsProfilingEnabled() override;
// Increments the event tag, allowing grouping of events in a user-defined manner (e.g. per inference).
void UpdateEventTag();
// Analyzes the tracked events and writes the results to the given output stream.
// Please refer to the configuration variables in Profiling.cpp to customize the information written.
void AnalyzeEventsAndWriteResults(std::ostream& outStream) const override;
// Print stats for events in JSON Format to the given output stream.
void Print(std::ostream& outStream) const override;
// Gets the color to render an event with, based on which device it denotes.
uint32_t GetEventColor(const BackendId& backendId) const;
private:
using EventPtr = std::unique_ptr<Event>;
struct Marker
{
std::size_t m_Id;
};
struct ProfilingEventStats
{
double m_TotalMs;
double m_MinMs;
double m_MaxMs;
uint32_t m_Count;
};
template<typename EventIterType>
void AnalyzeEventSequenceAndWriteResults(EventIterType first, EventIterType last, std::ostream& outStream) const;
std::map<std::string, ProfilingEventStats> CalculateProfilingEventStats() const;
void PopulateInferences(std::vector<const Event*>& outInferences, int& outBaseLevel) const;
void PopulateDescendants(std::map<const Event*, std::vector<const Event*>>& outDescendantsMap) const;
std::stack<Event*> m_Parents;
std::vector<EventPtr> m_EventSequence;
bool m_ProfilingEnabled;
private:
// Friend functions for unit testing, see ProfilerTests.cpp.
friend size_t GetProfilerEventSequenceSize(armnn::Profiler* profiler);
};
// Singleton profiler manager.
// Keeps track of all the running profiler instances.
class ProfilerManager
{
public:
// Register the given profiler as a thread local pointer.
void RegisterProfiler(Profiler* profiler);
// Gets the thread local pointer to the profiler.
Profiler* GetProfiler();
// Accesses the singleton.
static ProfilerManager& GetInstance();
private:
// The constructor is kept private so that other instances of this class (other that the singleton's)
// can't be allocated.
ProfilerManager() {}
};
// Helper to easily add event markers to the codebase.
class ScopedProfilingEvent
{
public:
using InstrumentPtr = std::unique_ptr<Instrument>;
template<typename... Args>
ScopedProfilingEvent(const BackendId& backendId, const std::string& name, Args&&... args)
: m_Event(nullptr)
, m_Profiler(ProfilerManager::GetInstance().GetProfiler())
{
if (m_Profiler && m_Profiler->IsProfilingEnabled())
{
std::vector<InstrumentPtr> instruments(0);
instruments.reserve(sizeof...(args)); //One allocation
ConstructNextInVector(instruments, std::forward<Args>(args)...);
m_Event = m_Profiler->BeginEvent(backendId, name, std::move(instruments));
}
}
~ScopedProfilingEvent()
{
if (m_Profiler && m_Event)
{
m_Profiler->EndEvent(m_Event);
}
}
private:
void ConstructNextInVector(std::vector<InstrumentPtr>& instruments)
{
IgnoreUnused(instruments);
}
template<typename Arg, typename... Args>
void ConstructNextInVector(std::vector<InstrumentPtr>& instruments, Arg&& arg, Args&&... args)
{
instruments.emplace_back(std::make_unique<Arg>(std::forward<Arg>(arg)));
ConstructNextInVector(instruments, std::forward<Args>(args)...);
}
Event* m_Event; ///< Event to track
Profiler* m_Profiler; ///< Profiler used
};
} // namespace armnn
#include <boost/preprocessor.hpp>
#define ARMNN_SCOPED_PROFILING_EVENT_WITH_INSTRUMENTS_UNIQUE_LOC(backendId, /*name,*/ ...) \
armnn::ScopedProfilingEvent BOOST_PP_CAT(e_,__LINE__)(backendId, /*name,*/ __VA_ARGS__);
// The event name must be known at compile time
#define ARMNN_SCOPED_PROFILING_EVENT_WITH_INSTRUMENTS(backendId, /*name,*/ ...) \
ARMNN_SCOPED_PROFILING_EVENT_WITH_INSTRUMENTS_UNIQUE_LOC(backendId, /*name,*/ __VA_ARGS__);
#define ARMNN_SCOPED_PROFILING_EVENT(backendId, name) \
ARMNN_SCOPED_PROFILING_EVENT_WITH_INSTRUMENTS(backendId, name, armnn::WallClockTimer())
<commit_msg>IVGCVSW-5434 Remove boost/preprocessor.hpp<commit_after>//
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//
#pragma once
#include "ProfilingEvent.hpp"
#include <armnn/utility/IgnoreUnused.hpp>
#include "armnn/IProfiler.hpp"
#include "WallClockTimer.hpp"
#include <chrono>
#include <iosfwd>
#include <ctime>
#include <vector>
#include <stack>
#include <map>
namespace armnn
{
// Simple single-threaded profiler.
// Tracks events reported by BeginEvent()/EndEvent() and outputs detailed information and stats when
// Profiler::AnalyzeEventsAndWriteResults() is called.
class Profiler final : public IProfiler
{
public:
Profiler();
~Profiler();
using InstrumentPtr = std::unique_ptr<Instrument>;
// Marks the beginning of a user-defined event.
// No attempt will be made to copy the name string: it must be known at compile time.
Event* BeginEvent(const BackendId& backendId, const std::string& name, std::vector<InstrumentPtr>&& instruments);
// Marks the end of a user-defined event.
void EndEvent(Event* event);
// Enables/disables profiling.
void EnableProfiling(bool enableProfiling) override;
// Checks if profiling is enabled.
bool IsProfilingEnabled() override;
// Increments the event tag, allowing grouping of events in a user-defined manner (e.g. per inference).
void UpdateEventTag();
// Analyzes the tracked events and writes the results to the given output stream.
// Please refer to the configuration variables in Profiling.cpp to customize the information written.
void AnalyzeEventsAndWriteResults(std::ostream& outStream) const override;
// Print stats for events in JSON Format to the given output stream.
void Print(std::ostream& outStream) const override;
// Gets the color to render an event with, based on which device it denotes.
uint32_t GetEventColor(const BackendId& backendId) const;
private:
using EventPtr = std::unique_ptr<Event>;
struct Marker
{
std::size_t m_Id;
};
struct ProfilingEventStats
{
double m_TotalMs;
double m_MinMs;
double m_MaxMs;
uint32_t m_Count;
};
template<typename EventIterType>
void AnalyzeEventSequenceAndWriteResults(EventIterType first, EventIterType last, std::ostream& outStream) const;
std::map<std::string, ProfilingEventStats> CalculateProfilingEventStats() const;
void PopulateInferences(std::vector<const Event*>& outInferences, int& outBaseLevel) const;
void PopulateDescendants(std::map<const Event*, std::vector<const Event*>>& outDescendantsMap) const;
std::stack<Event*> m_Parents;
std::vector<EventPtr> m_EventSequence;
bool m_ProfilingEnabled;
private:
// Friend functions for unit testing, see ProfilerTests.cpp.
friend size_t GetProfilerEventSequenceSize(armnn::Profiler* profiler);
};
// Singleton profiler manager.
// Keeps track of all the running profiler instances.
class ProfilerManager
{
public:
// Register the given profiler as a thread local pointer.
void RegisterProfiler(Profiler* profiler);
// Gets the thread local pointer to the profiler.
Profiler* GetProfiler();
// Accesses the singleton.
static ProfilerManager& GetInstance();
private:
// The constructor is kept private so that other instances of this class (other that the singleton's)
// can't be allocated.
ProfilerManager() {}
};
// Helper to easily add event markers to the codebase.
class ScopedProfilingEvent
{
public:
using InstrumentPtr = std::unique_ptr<Instrument>;
template<typename... Args>
ScopedProfilingEvent(const BackendId& backendId, const std::string& name, Args&&... args)
: m_Event(nullptr)
, m_Profiler(ProfilerManager::GetInstance().GetProfiler())
{
if (m_Profiler && m_Profiler->IsProfilingEnabled())
{
std::vector<InstrumentPtr> instruments(0);
instruments.reserve(sizeof...(args)); //One allocation
ConstructNextInVector(instruments, std::forward<Args>(args)...);
m_Event = m_Profiler->BeginEvent(backendId, name, std::move(instruments));
}
}
~ScopedProfilingEvent()
{
if (m_Profiler && m_Event)
{
m_Profiler->EndEvent(m_Event);
}
}
private:
void ConstructNextInVector(std::vector<InstrumentPtr>& instruments)
{
IgnoreUnused(instruments);
}
template<typename Arg, typename... Args>
void ConstructNextInVector(std::vector<InstrumentPtr>& instruments, Arg&& arg, Args&&... args)
{
instruments.emplace_back(std::make_unique<Arg>(std::forward<Arg>(arg)));
ConstructNextInVector(instruments, std::forward<Args>(args)...);
}
Event* m_Event; ///< Event to track
Profiler* m_Profiler; ///< Profiler used
};
} // namespace armnn
#define ARMNN_SCOPED_PROFILING_EVENT_WITH_INSTRUMENTS_UNIQUE_LOC_INNER(lineNumber, backendId, /*name,*/ ...) \
armnn::ScopedProfilingEvent e_ ## lineNumber(backendId, /*name,*/ __VA_ARGS__);
#define ARMNN_SCOPED_PROFILING_EVENT_WITH_INSTRUMENTS_UNIQUE_LOC(lineNumber, backendId, /*name,*/ ...) \
ARMNN_SCOPED_PROFILING_EVENT_WITH_INSTRUMENTS_UNIQUE_LOC_INNER(lineNumber, backendId, /*name,*/ __VA_ARGS__)
// The event name must be known at compile time i.e. if you are going to use this version of the macro
// in code the first argument you supply after the backendId must be the name.
// NOTE: need to pass the line number as an argument from here so by the time it gets to the UNIQUE_LOC_INNER
// above it has expanded to a string and will concat (##) correctly with the 'e_' prefix to yield a
// legal and unique variable name (so long as you don't use the macro twice on the same line).
// The concat preprocessing operator (##) very unhelpfully will not expand macros see
// https://gcc.gnu.org/onlinedocs/cpp/Concatenation.html for the gory details.
#define ARMNN_SCOPED_PROFILING_EVENT_WITH_INSTRUMENTS(backendId, /*name,*/ ...) \
ARMNN_SCOPED_PROFILING_EVENT_WITH_INSTRUMENTS_UNIQUE_LOC(__LINE__,backendId, /*name,*/ __VA_ARGS__)
#define ARMNN_SCOPED_PROFILING_EVENT(backendId, name) \
ARMNN_SCOPED_PROFILING_EVENT_WITH_INSTRUMENTS(backendId, name, armnn::WallClockTimer())
<|endoftext|> |
<commit_before>/*
+----------------------------------------------------------------------+
| PHP Version 7 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2018 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Robert Eisele (https://www.xarg.org/) |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
extern "C" {
#include "php.h"
}
#include "ext/standard/info.h"
#include "php_facedetect.h"
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/objdetect.hpp>
/* for PHP 8 */
#ifndef TSRMLS_CC
#define TSRMLS_CC
#endif
using namespace cv;
CascadeClassifier cascade;
static void php_facedetect(INTERNAL_FUNCTION_PARAMETERS, int return_type) {
#ifdef ZEND_ENGINE_3
zval array;
#else
zval *array;
#endif
zval *pArray;
char *file = NULL, *casc = NULL;
#if PHP_VERSION_ID < 70000
long flen, clen;
#else
size_t flen, clen;
#endif
Mat img;
Mat gray;
std::vector<Rect> faces;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p|p", &file, &flen, &casc, &clen) == FAILURE) {
RETURN_NULL();
}
if (access(file, R_OK) == -1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Image file is missing or could not be read.\n");
RETURN_FALSE;
}
if (casc && access(casc, R_OK) == -1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Haar-cascade file is missing or could not be read.\n");
RETURN_FALSE;
}
if (casc && !cascade.load(casc)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Haar-cascade file could not be loaded.\n");
RETURN_FALSE;
}
if (!casc && cascade.empty()) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "No Haar-cascade file loaded.\n");
RETURN_FALSE;
}
img = imread(file);
if (!img.data) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Image could not be loaded.\n");
RETURN_FALSE;
}
cvtColor(img, gray, COLOR_BGR2GRAY);
equalizeHist(gray, gray);
cascade.detectMultiScale(gray, faces, 1.1, 2, 0 | CASCADE_SCALE_IMAGE, Size(30, 30));
if (return_type) {
array_init(return_value);
for (size_t i = 0; i < faces.size(); i++) {
#ifdef ZEND_ENGINE_3
ZVAL_NEW_ARR(&array);
pArray = &array;
#else
MAKE_STD_ZVAL(array);
pArray = array;
#endif
array_init(pArray);
add_assoc_long(pArray, "x", faces[i].x);
add_assoc_long(pArray, "y", faces[i].y);
add_assoc_long(pArray, "w", faces[i].width);
add_assoc_long(pArray, "h", faces[i].height);
add_next_index_zval(return_value, pArray);
}
} else {
RETVAL_LONG(faces.size());
}
}
PHP_INI_MH(on_cascade_change) {
if (ZSTR_LEN(new_value) > 0 && cascade.load(ZSTR_VAL(new_value)))
return SUCCESS;
else
return FAILURE;
}
PHP_INI_BEGIN()
PHP_INI_ENTRY("facedetect.cascade", "", PHP_INI_ALL, on_cascade_change)
PHP_INI_END()
#if PHP_VERSION_ID < 80000
ZEND_BEGIN_ARG_INFO_EX(arginfo_face_detect, 0, 0, 1)
ZEND_ARG_INFO(0, image_path)
ZEND_ARG_INFO(0, cascade_path)
ZEND_END_ARG_INFO()
#define arginfo_face_count arginfo_face_detect
#else
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_face_detect, 0, 1, MAY_BE_FALSE|MAY_BE_ARRAY)
ZEND_ARG_TYPE_INFO(0, image_path, IS_STRING, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, cascade_path, IS_STRING, 1, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_face_count, 0, 1, MAY_BE_FALSE|MAY_BE_LONG)
ZEND_ARG_TYPE_INFO(0, image_path, IS_STRING, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, cascade_path, IS_STRING, 1, "null")
ZEND_END_ARG_INFO()
#endif
PHP_FUNCTION(face_detect) {
php_facedetect(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
}
PHP_FUNCTION(face_count) {
php_facedetect(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
}
/* {{{ PHP_MINIT_FUNCTION
*/
PHP_MINIT_FUNCTION(facedetect) {
REGISTER_INI_ENTRIES();
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MSHUTDOWN_FUNCTION
*/
PHP_MSHUTDOWN_FUNCTION(facedetect) {
UNREGISTER_INI_ENTRIES();
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MINFO_FUNCTION
*/
PHP_MINFO_FUNCTION(facedetect) {
php_info_print_table_start();
php_info_print_table_row(2, "facedetect support", "enabled");
php_info_print_table_row(2, "facedetect version", PHP_FACEDETECT_VERSION);
php_info_print_table_row(2, "OpenCV version", CV_VERSION);
php_info_print_table_end();
}
/* }}} */
/* {{{ facedetect_functions[]
*
* Every user visible function must have an entry in facedetect_functions[].
*/
const zend_function_entry facedetect_functions[] = {
PHP_FE(face_detect, arginfo_face_detect)
PHP_FE(face_count, arginfo_face_count)
PHP_FE_END
};
/* }}} */
/* {{{ facedetect_module_entry
*/
zend_module_entry facedetect_module_entry = {
STANDARD_MODULE_HEADER,
"facedetect",
facedetect_functions,
PHP_MINIT(facedetect),
PHP_MSHUTDOWN(facedetect),
NULL,
NULL,
PHP_MINFO(facedetect),
PHP_FACEDETECT_VERSION,
STANDARD_MODULE_PROPERTIES
};
/* }}} */
#ifdef COMPILE_DL_FACEDETECT
#ifdef ZTS
ZEND_TSRMLS_CACHE_DEFINE()
#endif
extern "C" {
ZEND_GET_MODULE(facedetect)
}
#endif
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
<commit_msg>fix for PHP 5<commit_after>/*
+----------------------------------------------------------------------+
| PHP Version 7 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2018 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Robert Eisele (https://www.xarg.org/) |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
extern "C" {
#include "php.h"
}
#include "ext/standard/info.h"
#include "php_facedetect.h"
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/objdetect.hpp>
/* for PHP 8 */
#ifndef TSRMLS_CC
#define TSRMLS_CC
#endif
using namespace cv;
CascadeClassifier cascade;
static void php_facedetect(INTERNAL_FUNCTION_PARAMETERS, int return_type) {
#if PHP_VERSION_ID < 70000
int flen, clen;
zval *array;
#else
size_t flen, clen;
zval array;
#endif
zval *pArray;
char *file = NULL, *casc = NULL;
Mat img;
Mat gray;
std::vector<Rect> faces;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p|p", &file, &flen, &casc, &clen) == FAILURE) {
RETURN_NULL();
}
if (access(file, R_OK) == -1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Image file is missing or could not be read.\n");
RETURN_FALSE;
}
if (casc && access(casc, R_OK) == -1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Haar-cascade file is missing or could not be read.\n");
RETURN_FALSE;
}
if (casc && !cascade.load(casc)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Haar-cascade file could not be loaded.\n");
RETURN_FALSE;
}
if (!casc && cascade.empty()) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "No Haar-cascade file loaded.\n");
RETURN_FALSE;
}
img = imread(file);
if (!img.data) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Image could not be loaded.\n");
RETURN_FALSE;
}
cvtColor(img, gray, COLOR_BGR2GRAY);
equalizeHist(gray, gray);
cascade.detectMultiScale(gray, faces, 1.1, 2, 0 | CASCADE_SCALE_IMAGE, Size(30, 30));
if (return_type) {
array_init(return_value);
for (size_t i = 0; i < faces.size(); i++) {
#if PHP_VERSION_ID >= 70000
ZVAL_NEW_ARR(&array);
pArray = &array;
#else
MAKE_STD_ZVAL(array);
pArray = array;
#endif
array_init(pArray);
add_assoc_long(pArray, "x", faces[i].x);
add_assoc_long(pArray, "y", faces[i].y);
add_assoc_long(pArray, "w", faces[i].width);
add_assoc_long(pArray, "h", faces[i].height);
add_next_index_zval(return_value, pArray);
}
} else {
RETVAL_LONG(faces.size());
}
}
PHP_INI_MH(on_cascade_change) {
#if PHP_VERSION_ID < 70000
if (new_value_length > 0 && cascade.load(new_value))
#else
if (ZSTR_LEN(new_value) > 0 && cascade.load(ZSTR_VAL(new_value)))
#endif
return SUCCESS;
else
return FAILURE;
}
PHP_INI_BEGIN()
PHP_INI_ENTRY("facedetect.cascade", "", PHP_INI_ALL, on_cascade_change)
PHP_INI_END()
#if PHP_VERSION_ID < 80000
ZEND_BEGIN_ARG_INFO_EX(arginfo_face_detect, 0, 0, 1)
ZEND_ARG_INFO(0, image_path)
ZEND_ARG_INFO(0, cascade_path)
ZEND_END_ARG_INFO()
#define arginfo_face_count arginfo_face_detect
#else
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_face_detect, 0, 1, MAY_BE_FALSE|MAY_BE_ARRAY)
ZEND_ARG_TYPE_INFO(0, image_path, IS_STRING, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, cascade_path, IS_STRING, 1, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_face_count, 0, 1, MAY_BE_FALSE|MAY_BE_LONG)
ZEND_ARG_TYPE_INFO(0, image_path, IS_STRING, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, cascade_path, IS_STRING, 1, "null")
ZEND_END_ARG_INFO()
#endif
PHP_FUNCTION(face_detect) {
php_facedetect(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
}
PHP_FUNCTION(face_count) {
php_facedetect(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
}
/* {{{ PHP_MINIT_FUNCTION
*/
PHP_MINIT_FUNCTION(facedetect) {
REGISTER_INI_ENTRIES();
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MSHUTDOWN_FUNCTION
*/
PHP_MSHUTDOWN_FUNCTION(facedetect) {
UNREGISTER_INI_ENTRIES();
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MINFO_FUNCTION
*/
PHP_MINFO_FUNCTION(facedetect) {
php_info_print_table_start();
php_info_print_table_row(2, "facedetect support", "enabled");
php_info_print_table_row(2, "facedetect version", PHP_FACEDETECT_VERSION);
php_info_print_table_row(2, "OpenCV version", CV_VERSION);
php_info_print_table_end();
}
/* }}} */
/* {{{ facedetect_functions[]
*
* Every user visible function must have an entry in facedetect_functions[].
*/
const zend_function_entry facedetect_functions[] = {
PHP_FE(face_detect, arginfo_face_detect)
PHP_FE(face_count, arginfo_face_count)
PHP_FE_END
};
/* }}} */
/* {{{ facedetect_module_entry
*/
zend_module_entry facedetect_module_entry = {
STANDARD_MODULE_HEADER,
"facedetect",
facedetect_functions,
PHP_MINIT(facedetect),
PHP_MSHUTDOWN(facedetect),
NULL,
NULL,
PHP_MINFO(facedetect),
PHP_FACEDETECT_VERSION,
STANDARD_MODULE_PROPERTIES
};
/* }}} */
#ifdef COMPILE_DL_FACEDETECT
#ifdef ZTS
ZEND_TSRMLS_CACHE_DEFINE()
#endif
extern "C" {
ZEND_GET_MODULE(facedetect)
}
#endif
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
<|endoftext|> |
<commit_before>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
//
// --------------------------------------------------------------
// Radial NC: radial non-conforming mesh generator
// --------------------------------------------------------------
//
// This miniapp TODO
//
// Compile with: make radial-nc
//
// Sample runs: radial-nc
// radial-nc TODO
#include "mfem.hpp"
#include <fstream>
#include <iostream>
using namespace mfem;
using namespace std;
struct Params
{
double r, dr;
double a, da;
double b, db;
Params() = default;
Params(double r0, double r1, double a0, double a1)
: r(r0), dr(r1 - r0), a(a0), da(a1 - a0) {}
Params(double r0, double r1, double a0, double a1, double b0, double b1)
: r(r0), dr(r1 - r0), a(a0), da(a1 - a0), b(b0), db(b1 - b0) {}
};
Mesh* Make2D(int nsteps, double rstep, double phi, double aspect, int order,
bool sfc)
{
Mesh *mesh = new Mesh(2, 0, 0);
int origin = mesh->AddVertex(0.0, 0.0);
// n is the number of steps in the polar direction
int n = 1;
while (phi * rstep / n * aspect > rstep) { n++; }
double r = rstep;
int first = mesh->AddVertex(r, 0.0);
Array<Params> params;
Array<Pair<int, int>> blocks;
// create triangles around the origin
double prev_alpha = 0.0;
for (int i = 0; i < n; i++)
{
double alpha = phi * (i+1) / n;
mesh->AddVertex(r*cos(alpha), r*sin(alpha));
mesh->AddTriangle(origin, first+i, first+i+1);
params.Append(Params(0, r, prev_alpha, alpha));
prev_alpha = alpha;
}
mesh->AddBdrSegment(origin, first, 1);
mesh->AddBdrSegment(first+n, origin, 2);
for (int k = 1; k < nsteps; k++)
{
// m is the number of polar steps of the previous row
int m = n;
int prev_first = first;
double prev_r = r;
r += rstep;
if (phi * (r + prev_r)/2 / n * aspect <= rstep)
{
if (k == 1) { blocks.Append(Pair<int, int>(mesh->GetNE(), n)); }
first = mesh->AddVertex(r, 0.0);
mesh->AddBdrSegment(prev_first, first, 1);
// create a row of quads, same number as in previous row
prev_alpha = 0.0;
for (int i = 0; i < n; i++)
{
double alpha = phi * (i+1) / n;
mesh->AddVertex(r*cos(alpha), r*sin(alpha));
mesh->AddQuad(prev_first+i, first+i, first+i+1, prev_first+i+1);
params.Append(Params(prev_r, r, prev_alpha, alpha));
prev_alpha = alpha;
}
mesh->AddBdrSegment(first+n, prev_first+n, 2);
}
else // we need to double the number of elements per row
{
n *= 2;
blocks.Append(Pair<int, int>(mesh->GetNE(), n));
// first create hanging vertices
int hang;
for (int i = 0; i < m; i++)
{
double alpha = phi * (2*i+1) / n;
int index = mesh->AddVertex(prev_r*cos(alpha), prev_r*sin(alpha));
mesh->AddVertexParents(index, prev_first+i, prev_first+i+1);
if (!i) { hang = index; }
}
first = mesh->AddVertex(r, 0.0);
int a = prev_first, b = first;
mesh->AddBdrSegment(a, b, 1);
// create a row of quad pairs
prev_alpha = 0.0;
for (int i = 0; i < m; i++)
{
int c = hang+i, e = a+1;
double alpha_half = phi * (2*i+1) / n;
int d = mesh->AddVertex(r*cos(alpha_half), r*sin(alpha_half));
double alpha = phi * (2*i+2) / n;
int f = mesh->AddVertex(r*cos(alpha), r*sin(alpha));
mesh->AddQuad(a, b, d, c);
mesh->AddQuad(c, d, f, e);
a = e, b = f;
params.Append(Params(prev_r, r, prev_alpha, alpha_half));
params.Append(Params(prev_r, r, alpha_half, alpha));
prev_alpha = alpha;
}
mesh->AddBdrSegment(b, a, 2);
}
}
for (int i = 0; i < n; i++)
{
mesh->AddBdrSegment(first+i, first+i+1, 3);
}
// reorder blocks of elements with Grid SFC ordering
if (sfc)
{
blocks.Append(Pair<int, int>(mesh->GetNE(), 0));
Array<Params> new_params(params.Size());
Array<int> ordering(mesh->GetNE());
for (int i = 0; i < blocks[0].one; i++)
{
ordering[i] = i;
new_params[i] = params[i];
}
Array<int> coords;
for (int i = 0; i < blocks.Size()-1; i++)
{
int beg = blocks[i].one;
int width = blocks[i].two;
int height = (blocks[i+1].one - blocks[i].one) / width;
NCMesh::GridSfcOrdering2D(width, height, coords);
for (int j = 0, k = 0; j < coords.Size(); k++, j += 2)
{
int sfc = ((i & 1) ? coords[j] : (width-1 - coords[j]))
+ coords[j+1]*width;
int old_index = beg + sfc;
ordering[old_index] = beg + k;
new_params[beg + k] = params[old_index];
}
}
mesh->ReorderElements(ordering, false);
mfem::Swap(params, new_params);
}
mesh->FinalizeMesh();
// create high-order curvature
if (order > 1)
{
mesh->SetCurvature(order);
GridFunction *nodes = mesh->GetNodes();
const FiniteElementSpace *fes = mesh->GetNodalFESpace();
Array<int> dofs;
MFEM_ASSERT(params.Size() == mesh->GetNE(), "");
for (int i = 0; i < mesh->GetNE(); i++)
{
const Params &par = params[i];
const IntegrationRule &ir = fes->GetFE(i)->GetNodes();
Geometry::Type geom = mesh->GetElementBaseGeometry(i);
fes->GetElementDofs(i, dofs);
for (int j = 0; j < dofs.Size(); j++)
{
double r, a;
if (geom == Geometry::SQUARE)
{
r = par.r + ir[j].x * par.dr;
a = par.a + ir[j].y * par.da;
}
else
{
double rr = ir[j].x + ir[j].y;
if (std::abs(rr) < 1e-12) { continue; }
r = par.r + rr * par.dr;
a = par.a + ir[j].y/rr * par.da;
}
(*nodes)(fes->DofToVDof(dofs[j], 0)) = r*cos(a);
(*nodes)(fes->DofToVDof(dofs[j], 1)) = r*sin(a);
}
}
nodes->RestrictConforming();
}
return mesh;
}
struct Vert : public Hashed2
{
int id;
};
int GetMidVertex(int v1, int v2, double r, double a, double b,
Mesh *mesh, HashTable<Vert> &hash)
{
int vmid = hash.FindId(v1, v2);
if (vmid < 0)
{
vmid = hash.GetId(v1, v2);
hash[vmid].id =
mesh->AddVertex(r*cos(a)*cos(b), r*sin(a)*cos(b), r*sin(b));
}
return hash[vmid].id;
}
void MakeLayer(int vx1, int vy1, int vz1, int vx2, int vy2, int vz2, int level,
double r1, double r2, double a1, double a2, double b1, double b2,
Mesh *mesh, HashTable<Vert> &hash, Array<Params> ¶ms)
{
if (level <= 0)
{
mesh->AddWedge(vx1, vy1, vz1, vx2, vy2, vz2);
params.Append(Params(r1, r2, a1, a2, b1, b2));
}
else
{
double amid = (a1+a2)/2, bmid = (b1+b2)/2;
int vxy1 = GetMidVertex(vx1, vy1, r1, amid, b1, mesh, hash);
int vyz1 = GetMidVertex(vy1, vz1, r1, a2, bmid, mesh, hash);
int vxz1 = GetMidVertex(vx1, vz1, r1, a1, bmid, mesh, hash);
int vxy2 = GetMidVertex(vx2, vy2, r2, amid, b1, mesh, hash);
int vyz2 = GetMidVertex(vy2, vz2, r2, a2, bmid, mesh, hash);
int vxz2 = GetMidVertex(vx2, vz2, r2, a1, bmid, mesh, hash);
MakeLayer(vx1, vxy1, vxz1, vx2, vxy2, vxz2, level-1, r1, r2,
a1, amid, b1, bmid, mesh, hash, params);
MakeLayer(vxy1, vy1, vyz1, vxy2, vy2, vyz2, level-1, r1, r2,
amid, a2, b1, bmid, mesh, hash, params);
MakeLayer(vxz1, vyz1, vz1, vxz2, vyz2, vz2, level-1, r1, r2,
a1, a2, bmid, b2, mesh, hash, params);
MakeLayer(vyz1, vxz1, vxy1, vyz2, vxz2, vxy2, level-1, r1, r2,
a2, a1, bmid, b1, mesh, hash, params);
}
}
Mesh* Make3D(int nsteps, double rstep, double aspect, int order)
{
Mesh *mesh = new Mesh(3, 0, 0);
HashTable<Vert> hash;
Array<Params> params;
int a = mesh->AddVertex(rstep, 0, 0);
int b = mesh->AddVertex(0, rstep, 0);
int c = mesh->AddVertex(0, 0, rstep);
double r = rstep + rstep;
int d = mesh->AddVertex(r, 0, 0);
int e = mesh->AddVertex(0, r, 0);
int f = mesh->AddVertex(0, 0, r);
const double pi2 = M_PI / 2;
MakeLayer(a, b, c, d, e, f, 2, rstep, r, 0, pi2, 0, pi2, mesh, hash, params);
mesh->FinalizeMesh();
return mesh;
}
int main(int argc, char *argv[])
{
int dim = 2;
double radius = 1.0;
int nsteps = 10;
double angle = 90;
double aspect = 1.0;
int order = 2;
bool sfc = true;
// parse command line
OptionsParser args(argc, argv);
args.AddOption(&dim, "-d", "--dim", "Mesh dimension (2 or 3).");
args.AddOption(&radius, "-r", "--radius", "Radius of the domain.");
args.AddOption(&nsteps, "-n", "--nsteps",
"Number of elements along the radial direction");
args.AddOption(&aspect, "-a", "--aspect",
"Target aspect ratio of the elements.");
args.AddOption(&angle, "-phi", "--phi", "Angular range.");
args.AddOption(&order, "-o", "--order",
"Polynomial degree of mesh curvature.");
args.AddOption(&sfc, "-sfc", "--sfc", "-no-sfc", "--no-sfc",
"Try to order elements along a space-filling curve.");
args.Parse();
if (!args.Good())
{
args.PrintUsage(cout);
return EXIT_FAILURE;
}
args.PrintOptions(cout);
// validate options
MFEM_VERIFY(dim >= 2 && dim <= 3, "");
MFEM_VERIFY(angle > 0 && angle < 360, "");
MFEM_VERIFY(nsteps > 0, "");
double phi = angle * M_PI / 180;
// generate
Mesh *mesh;
if (dim == 2)
{
mesh = Make2D(nsteps, radius/nsteps, phi, aspect, order, sfc);
}
else
{
mesh = Make3D(nsteps, radius/nsteps, aspect, order);
}
// save the final mesh
ofstream ofs("radial.mesh");
ofs.precision(8);
mesh->Print(ofs);
delete mesh;
return EXIT_SUCCESS;
}
<commit_msg>radial-nc: trying to fix 3D parametrization<commit_after>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
//
// --------------------------------------------------------------
// Radial NC: radial non-conforming mesh generator
// --------------------------------------------------------------
//
// This miniapp TODO
//
// Compile with: make radial-nc
//
// Sample runs: radial-nc
// radial-nc TODO
#include "mfem.hpp"
#include <fstream>
#include <iostream>
using namespace mfem;
using namespace std;
struct Params
{
double r, dr;
double a, da;
double b, db;
Params() = default;
Params(double r0, double r1, double a0, double a1)
: r(r0), dr(r1 - r0), a(a0), da(a1 - a0) {}
Params(double r0, double r1, double a0, double a1, double b0, double b1)
: r(r0), dr(r1 - r0), a(a0), da(a1 - a0), b(b0), db(b1 - b0) {}
};
Mesh* Make2D(int nsteps, double rstep, double phi, double aspect, int order,
bool sfc)
{
Mesh *mesh = new Mesh(2, 0, 0);
int origin = mesh->AddVertex(0.0, 0.0);
// n is the number of steps in the polar direction
int n = 1;
while (phi * rstep / n * aspect > rstep) { n++; }
double r = rstep;
int first = mesh->AddVertex(r, 0.0);
Array<Params> params;
Array<Pair<int, int>> blocks;
// create triangles around the origin
double prev_alpha = 0.0;
for (int i = 0; i < n; i++)
{
double alpha = phi * (i+1) / n;
mesh->AddVertex(r*cos(alpha), r*sin(alpha));
mesh->AddTriangle(origin, first+i, first+i+1);
params.Append(Params(0, r, prev_alpha, alpha));
prev_alpha = alpha;
}
mesh->AddBdrSegment(origin, first, 1);
mesh->AddBdrSegment(first+n, origin, 2);
for (int k = 1; k < nsteps; k++)
{
// m is the number of polar steps of the previous row
int m = n;
int prev_first = first;
double prev_r = r;
r += rstep;
if (phi * (r + prev_r)/2 / n * aspect <= rstep)
{
if (k == 1) { blocks.Append(Pair<int, int>(mesh->GetNE(), n)); }
first = mesh->AddVertex(r, 0.0);
mesh->AddBdrSegment(prev_first, first, 1);
// create a row of quads, same number as in previous row
prev_alpha = 0.0;
for (int i = 0; i < n; i++)
{
double alpha = phi * (i+1) / n;
mesh->AddVertex(r*cos(alpha), r*sin(alpha));
mesh->AddQuad(prev_first+i, first+i, first+i+1, prev_first+i+1);
params.Append(Params(prev_r, r, prev_alpha, alpha));
prev_alpha = alpha;
}
mesh->AddBdrSegment(first+n, prev_first+n, 2);
}
else // we need to double the number of elements per row
{
n *= 2;
blocks.Append(Pair<int, int>(mesh->GetNE(), n));
// first create hanging vertices
int hang;
for (int i = 0; i < m; i++)
{
double alpha = phi * (2*i+1) / n;
int index = mesh->AddVertex(prev_r*cos(alpha), prev_r*sin(alpha));
mesh->AddVertexParents(index, prev_first+i, prev_first+i+1);
if (!i) { hang = index; }
}
first = mesh->AddVertex(r, 0.0);
int a = prev_first, b = first;
mesh->AddBdrSegment(a, b, 1);
// create a row of quad pairs
prev_alpha = 0.0;
for (int i = 0; i < m; i++)
{
int c = hang+i, e = a+1;
double alpha_half = phi * (2*i+1) / n;
int d = mesh->AddVertex(r*cos(alpha_half), r*sin(alpha_half));
double alpha = phi * (2*i+2) / n;
int f = mesh->AddVertex(r*cos(alpha), r*sin(alpha));
mesh->AddQuad(a, b, d, c);
mesh->AddQuad(c, d, f, e);
a = e, b = f;
params.Append(Params(prev_r, r, prev_alpha, alpha_half));
params.Append(Params(prev_r, r, alpha_half, alpha));
prev_alpha = alpha;
}
mesh->AddBdrSegment(b, a, 2);
}
}
for (int i = 0; i < n; i++)
{
mesh->AddBdrSegment(first+i, first+i+1, 3);
}
// reorder blocks of elements with Grid SFC ordering
if (sfc)
{
blocks.Append(Pair<int, int>(mesh->GetNE(), 0));
Array<Params> new_params(params.Size());
Array<int> ordering(mesh->GetNE());
for (int i = 0; i < blocks[0].one; i++)
{
ordering[i] = i;
new_params[i] = params[i];
}
Array<int> coords;
for (int i = 0; i < blocks.Size()-1; i++)
{
int beg = blocks[i].one;
int width = blocks[i].two;
int height = (blocks[i+1].one - blocks[i].one) / width;
NCMesh::GridSfcOrdering2D(width, height, coords);
for (int j = 0, k = 0; j < coords.Size(); k++, j += 2)
{
int sfc = ((i & 1) ? coords[j] : (width-1 - coords[j]))
+ coords[j+1]*width;
int old_index = beg + sfc;
ordering[old_index] = beg + k;
new_params[beg + k] = params[old_index];
}
}
mesh->ReorderElements(ordering, false);
mfem::Swap(params, new_params);
}
mesh->FinalizeMesh();
// create high-order curvature
if (order > 1)
{
mesh->SetCurvature(order);
GridFunction *nodes = mesh->GetNodes();
const FiniteElementSpace *fes = mesh->GetNodalFESpace();
Array<int> dofs;
MFEM_ASSERT(params.Size() == mesh->GetNE(), "");
for (int i = 0; i < mesh->GetNE(); i++)
{
const Params &par = params[i];
const IntegrationRule &ir = fes->GetFE(i)->GetNodes();
Geometry::Type geom = mesh->GetElementBaseGeometry(i);
fes->GetElementDofs(i, dofs);
for (int j = 0; j < dofs.Size(); j++)
{
double r, a;
if (geom == Geometry::SQUARE)
{
r = par.r + ir[j].x * par.dr;
a = par.a + ir[j].y * par.da;
}
else
{
double rr = ir[j].x + ir[j].y;
if (std::abs(rr) < 1e-12) { continue; }
r = par.r + rr * par.dr;
a = par.a + ir[j].y/rr * par.da;
}
(*nodes)(fes->DofToVDof(dofs[j], 0)) = r*cos(a);
(*nodes)(fes->DofToVDof(dofs[j], 1)) = r*sin(a);
}
}
nodes->RestrictConforming();
}
return mesh;
}
struct Vert : public Hashed2
{
int id;
};
int GetMidVertex(int v1, int v2, double r, double a, double b,
Mesh *mesh, HashTable<Vert> &hash)
{
int vmid = hash.FindId(v1, v2);
if (vmid < 0)
{
vmid = hash.GetId(v1, v2);
hash[vmid].id =
mesh->AddVertex(r*cos(a)*cos(b), r*sin(a)*cos(b), r*sin(b));
}
return hash[vmid].id;
}
void MakeLayer(int vx1, int vy1, int vz1, int vx2, int vy2, int vz2, int level,
double r1, double r2, double a1, double a2, double a3,
double b1, double b2, Mesh *mesh, HashTable<Vert> &hash,
Array<Params> ¶ms)
{
if (level <= 0)
{
mesh->AddWedge(vx1, vy1, vz1, vx2, vy2, vz2);
params.Append(Params(r1, r2, a1, a2, b1, b2));
}
else
{
double a12 = (a1+a2)/2, a23 = (a2+a3)/2, a31 = (a3+a1)/2;
double b12 = (b1+b2)/2;
int vxy1 = GetMidVertex(vx1, vy1, r1, a12, b1, mesh, hash);
int vyz1 = GetMidVertex(vy1, vz1, r1, a23, b12, mesh, hash);
int vxz1 = GetMidVertex(vx1, vz1, r1, a31, b12, mesh, hash);
int vxy2 = GetMidVertex(vx2, vy2, r2, a12, b1, mesh, hash);
int vyz2 = GetMidVertex(vy2, vz2, r2, a23, b12, mesh, hash);
int vxz2 = GetMidVertex(vx2, vz2, r2, a31, b12, mesh, hash);
MakeLayer(vx1, vxy1, vxz1, vx2, vxy2, vxz2, level-1, r1, r2,
a1, a12, a31, b1, b12, mesh, hash, params);
MakeLayer(vxy1, vy1, vyz1, vxy2, vy2, vyz2, level-1, r1, r2,
a12, a2, a23, b1, b12, mesh, hash, params);
MakeLayer(vxz1, vyz1, vz1, vxz2, vyz2, vz2, level-1, r1, r2,
a31, a23, a3, b12, b2, mesh, hash, params);
MakeLayer(vyz1, vxz1, vxy1, vyz2, vxz2, vxy2, level-1, r1, r2,
a23, a31, a12, b12, b1, mesh, hash, params);
}
}
Mesh* Make3D(int nsteps, double rstep, double aspect, int order)
{
Mesh *mesh = new Mesh(3, 0, 0);
HashTable<Vert> hash;
Array<Params> params;
int a = mesh->AddVertex(rstep, 0, 0);
int b = mesh->AddVertex(0, rstep, 0);
int c = mesh->AddVertex(0, 0, rstep);
double r = rstep + rstep;
int d = mesh->AddVertex(r, 0, 0);
int e = mesh->AddVertex(0, r, 0);
int f = mesh->AddVertex(0, 0, r);
const double pi2 = M_PI / 2;
MakeLayer(a, b, c, d, e, f, 3, rstep, r, 0, pi2, 0, 0, pi2, mesh, hash, params);
mesh->FinalizeMesh();
return mesh;
}
int main(int argc, char *argv[])
{
int dim = 2;
double radius = 1.0;
int nsteps = 10;
double angle = 90;
double aspect = 1.0;
int order = 2;
bool sfc = true;
// parse command line
OptionsParser args(argc, argv);
args.AddOption(&dim, "-d", "--dim", "Mesh dimension (2 or 3).");
args.AddOption(&radius, "-r", "--radius", "Radius of the domain.");
args.AddOption(&nsteps, "-n", "--nsteps",
"Number of elements along the radial direction");
args.AddOption(&aspect, "-a", "--aspect",
"Target aspect ratio of the elements.");
args.AddOption(&angle, "-phi", "--phi", "Angular range.");
args.AddOption(&order, "-o", "--order",
"Polynomial degree of mesh curvature.");
args.AddOption(&sfc, "-sfc", "--sfc", "-no-sfc", "--no-sfc",
"Try to order elements along a space-filling curve.");
args.Parse();
if (!args.Good())
{
args.PrintUsage(cout);
return EXIT_FAILURE;
}
args.PrintOptions(cout);
// validate options
MFEM_VERIFY(dim >= 2 && dim <= 3, "");
MFEM_VERIFY(angle > 0 && angle < 360, "");
MFEM_VERIFY(nsteps > 0, "");
double phi = angle * M_PI / 180;
// generate
Mesh *mesh;
if (dim == 2)
{
mesh = Make2D(nsteps, radius/nsteps, phi, aspect, order, sfc);
}
else
{
mesh = Make3D(nsteps, radius/nsteps, aspect, order);
}
// save the final mesh
ofstream ofs("radial.mesh");
ofs.precision(8);
mesh->Print(ofs);
delete mesh;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>extern "C" {
#include <sys/types.h>
#include <stdio.h>
#include <jpeglib.h>
}
#include <setjmp.h>
#include <graphics/format/JPEG.h>
#include <system/System.h>
namespace lime {
struct ErrorData {
struct jpeg_error_mgr base;
jmp_buf on_error;
};
static void OnOutput (j_common_ptr cinfo) {}
static void OnError (j_common_ptr cinfo) {
ErrorData * err = (ErrorData *)cinfo->err;
longjmp (err->on_error, 1);
}
struct MySrcManager {
MySrcManager (const JOCTET *inData, int inLen) : mData (inData), mLen (inLen) {
pub.init_source = my_init_source;
pub.fill_input_buffer = my_fill_input_buffer;
pub.skip_input_data = my_skip_input_data;
pub.resync_to_restart = my_resync_to_restart;
pub.term_source = my_term_source;
pub.next_input_byte = 0;
pub.bytes_in_buffer = 0;
mUsed = false;
mEOI[0] = 0xff;
mEOI[1] = JPEG_EOI;
}
struct jpeg_source_mgr pub; /* public fields */
const JOCTET * mData;
size_t mLen;
bool mUsed;
unsigned char mEOI[2];
static void my_init_source (j_decompress_ptr cinfo) {
MySrcManager *man = (MySrcManager *)cinfo->src;
man->mUsed = false;
}
static boolean my_fill_input_buffer (j_decompress_ptr cinfo) {
MySrcManager *man = (MySrcManager *)cinfo->src;
if (man->mUsed) {
man->pub.next_input_byte = man->mEOI;
man->pub.bytes_in_buffer = 2;
} else {
man->pub.next_input_byte = man->mData;
man->pub.bytes_in_buffer = man->mLen;
man->mUsed = true;
}
return TRUE;
}
static void my_skip_input_data (j_decompress_ptr cinfo, long num_bytes) {
MySrcManager *man = (MySrcManager *)cinfo->src;
man->pub.next_input_byte += num_bytes;
man->pub.bytes_in_buffer -= num_bytes;
// was < 0 and was always false PJK 16JUN12
if (man->pub.bytes_in_buffer == 0) {
man->pub.next_input_byte = man->mEOI;
man->pub.bytes_in_buffer = 2;
}
}
static boolean my_resync_to_restart (j_decompress_ptr cinfo, int desired) {
MySrcManager *man = (MySrcManager *)cinfo->src;
man->mUsed = false;
return TRUE;
}
static void my_term_source (j_decompress_ptr cinfo) {}
};
struct MyDestManager {
enum { BUF_SIZE = 4096 };
struct jpeg_destination_mgr pub; /* public fields */
QuickVec<unsigned char> mOutput;
unsigned char mTmpBuf[BUF_SIZE];
MyDestManager () {
pub.init_destination = init_buffer;
pub.empty_output_buffer = copy_buffer;
pub.term_destination = term_buffer;
pub.next_output_byte = mTmpBuf;
pub.free_in_buffer = BUF_SIZE;
}
void CopyBuffer () {
mOutput.append (mTmpBuf, BUF_SIZE);
pub.next_output_byte = mTmpBuf;
pub.free_in_buffer = BUF_SIZE;
}
void TermBuffer () {
mOutput.append (mTmpBuf, BUF_SIZE - pub.free_in_buffer);
}
static void init_buffer (jpeg_compress_struct* cinfo) {}
static boolean copy_buffer (jpeg_compress_struct* cinfo) {
MyDestManager *man = (MyDestManager *)cinfo->dest;
man->CopyBuffer ();
return TRUE;
}
static void term_buffer (jpeg_compress_struct* cinfo) {
MyDestManager *man = (MyDestManager *)cinfo->dest;
man->TermBuffer ();
}
};
bool JPEG::Decode (Resource *resource, ImageBuffer* imageBuffer, bool decodeData) {
struct jpeg_decompress_struct cinfo;
//struct jpeg_error_mgr jerr;
//cinfo.err = jpeg_std_error (&jerr);
struct ErrorData jpegError;
cinfo.err = jpeg_std_error (&jpegError.base);
jpegError.base.error_exit = OnError;
jpegError.base.output_message = OnOutput;
FILE_HANDLE *file = NULL;
Bytes *data = NULL;
MySrcManager *manager = NULL;
if (resource->path) {
file = lime::fopen (resource->path, "rb");
if (!file) {
return false;
}
}
if (setjmp (jpegError.on_error)) {
if (file) {
lime::fclose (file);
}
if (manager) {
delete manager;
}
if (data) {
delete data;
}
jpeg_destroy_decompress (&cinfo);
return false;
}
jpeg_create_decompress (&cinfo);
jpeg_save_markers (&cinfo, JPEG_APP0 + 14, 0xFF);
if (file) {
if (file->isFile ()) {
jpeg_stdio_src (&cinfo, file->getFile ());
} else {
data = new Bytes ();
data->ReadFile (resource->path);
manager = new MySrcManager (data->b, data->length);
cinfo.src = &manager->pub;
}
} else {
manager = new MySrcManager (resource->data->b, resource->data->length);
cinfo.src = &manager->pub;
}
bool decoded = false;
if (jpeg_read_header (&cinfo, TRUE) == JPEG_HEADER_OK) {
switch (cinfo.jpeg_color_space) {
case JCS_CMYK:
case JCS_YCCK:
cinfo.out_color_space = JCS_CMYK;
break;
case JCS_GRAYSCALE:
case JCS_RGB:
case JCS_YCbCr:
default:
cinfo.out_color_space = JCS_RGB;
break;
// case JCS_BG_RGB:
// case JCS_BG_YCC:
// case JCS_UNKNOWN:
}
if (decodeData) {
jpeg_start_decompress (&cinfo);
int components = cinfo.output_components;
imageBuffer->Resize (cinfo.output_width, cinfo.output_height, 32);
unsigned char *bytes = imageBuffer->data->buffer->b;
unsigned char *scanline = new unsigned char [imageBuffer->width * components];
if (cinfo.out_color_space == JCS_CMYK) {
bool invert = false;
jpeg_saved_marker_ptr marker;
marker = cinfo.marker_list;
while (marker) {
if (marker->marker == JPEG_APP0 + 14 && marker->data_length >= 12 && !strncmp ((const char*)marker->data, "Adobe", 5)) {
// Are there other transforms?
invert = true;
}
marker = marker->next;
}
while (cinfo.output_scanline < cinfo.output_height) {
jpeg_read_scanlines (&cinfo, &scanline, 1);
const unsigned char *line = scanline;
const unsigned char *const end = line + imageBuffer->width * components;
unsigned char c, m, y, k;
while (line < end) {
if (invert) {
c = 0xFF - *line++;
m = 0xFF - *line++;
y = 0xFF - *line++;
k = 0xFF - *line++;
} else {
c = *line++;
m = *line++;
y = *line++;
k = *line++;
}
*bytes++ = (unsigned char)((0xFF - c) * (0xFF - k) / 0xFF);
*bytes++ = (unsigned char)((0xFF - m) * (0xFF - k) / 0xFF);
*bytes++ = (unsigned char)((0xFF - y) * (0xFF - k) / 0xFF);
*bytes++ = 0xFF;
}
}
} else {
while (cinfo.output_scanline < cinfo.output_height) {
jpeg_read_scanlines (&cinfo, &scanline, 1);
// convert 24-bit scanline to 32-bit
const unsigned char *line = scanline;
const unsigned char *const end = line + imageBuffer->width * components;
while (line < end) {
*bytes++ = *line++;
*bytes++ = *line++;
*bytes++ = *line++;
*bytes++ = 0xFF;
}
}
}
delete[] scanline;
jpeg_finish_decompress (&cinfo);
} else {
imageBuffer->width = cinfo.image_width;
imageBuffer->height = cinfo.image_height;
}
decoded = true;
}
if (file) {
lime::fclose (file);
}
if (manager) {
delete manager;
}
if (data) {
delete data;
}
jpeg_destroy_decompress (&cinfo);
return decoded;
}
bool JPEG::Encode (ImageBuffer *imageBuffer, Bytes *bytes, int quality) {
struct jpeg_compress_struct cinfo;
struct ErrorData jpegError;
cinfo.err = jpeg_std_error (&jpegError.base);
jpegError.base.error_exit = OnError;
jpegError.base.output_message = OnOutput;
MyDestManager dest;
int w = imageBuffer->width;
int h = imageBuffer->height;
QuickVec<unsigned char> row_buf (w * 3);
jpeg_create_compress (&cinfo);
if (setjmp (jpegError.on_error)) {
jpeg_destroy_compress (&cinfo);
return false;
}
cinfo.dest = (jpeg_destination_mgr *)&dest;
cinfo.image_width = w;
cinfo.image_height = h;
cinfo.input_components = 3;
cinfo.in_color_space = JCS_RGB;
jpeg_set_defaults (&cinfo);
jpeg_set_quality (&cinfo, quality, TRUE);
jpeg_start_compress (&cinfo, TRUE);
JSAMPROW row_pointer = &row_buf[0];
unsigned char* imageData = imageBuffer->data->buffer->b;
int stride = imageBuffer->Stride ();
while (cinfo.next_scanline < cinfo.image_height) {
const unsigned char *src = (const unsigned char *)(imageData + (stride * cinfo.next_scanline));
unsigned char *dest = &row_buf[0];
for(int x = 0; x < w; x++) {
dest[0] = src[0];
dest[1] = src[1];
dest[2] = src[2];
dest += 3;
src += 4;
}
jpeg_write_scanlines (&cinfo, &row_pointer, 1);
}
jpeg_finish_compress (&cinfo);
int size = dest.mOutput.size ();
if (size > 0) {
bytes->Resize (size);
memcpy (bytes->b, &dest.mOutput[0], size);
}
return true;
}
}
<commit_msg>Fix INT32 redefined error in libjpeg.<commit_after>#include <system/System.h>
extern "C" {
#include <sys/types.h>
#include <stdio.h>
#include <jpeglib.h>
}
#include <setjmp.h>
#include <graphics/format/JPEG.h>
namespace lime {
struct ErrorData {
struct jpeg_error_mgr base;
jmp_buf on_error;
};
static void OnOutput (j_common_ptr cinfo) {}
static void OnError (j_common_ptr cinfo) {
ErrorData * err = (ErrorData *)cinfo->err;
longjmp (err->on_error, 1);
}
struct MySrcManager {
MySrcManager (const JOCTET *inData, int inLen) : mData (inData), mLen (inLen) {
pub.init_source = my_init_source;
pub.fill_input_buffer = my_fill_input_buffer;
pub.skip_input_data = my_skip_input_data;
pub.resync_to_restart = my_resync_to_restart;
pub.term_source = my_term_source;
pub.next_input_byte = 0;
pub.bytes_in_buffer = 0;
mUsed = false;
mEOI[0] = 0xff;
mEOI[1] = JPEG_EOI;
}
struct jpeg_source_mgr pub; /* public fields */
const JOCTET * mData;
size_t mLen;
bool mUsed;
unsigned char mEOI[2];
static void my_init_source (j_decompress_ptr cinfo) {
MySrcManager *man = (MySrcManager *)cinfo->src;
man->mUsed = false;
}
static boolean my_fill_input_buffer (j_decompress_ptr cinfo) {
MySrcManager *man = (MySrcManager *)cinfo->src;
if (man->mUsed) {
man->pub.next_input_byte = man->mEOI;
man->pub.bytes_in_buffer = 2;
} else {
man->pub.next_input_byte = man->mData;
man->pub.bytes_in_buffer = man->mLen;
man->mUsed = true;
}
return TRUE;
}
static void my_skip_input_data (j_decompress_ptr cinfo, long num_bytes) {
MySrcManager *man = (MySrcManager *)cinfo->src;
man->pub.next_input_byte += num_bytes;
man->pub.bytes_in_buffer -= num_bytes;
// was < 0 and was always false PJK 16JUN12
if (man->pub.bytes_in_buffer == 0) {
man->pub.next_input_byte = man->mEOI;
man->pub.bytes_in_buffer = 2;
}
}
static boolean my_resync_to_restart (j_decompress_ptr cinfo, int desired) {
MySrcManager *man = (MySrcManager *)cinfo->src;
man->mUsed = false;
return TRUE;
}
static void my_term_source (j_decompress_ptr cinfo) {}
};
struct MyDestManager {
enum { BUF_SIZE = 4096 };
struct jpeg_destination_mgr pub; /* public fields */
QuickVec<unsigned char> mOutput;
unsigned char mTmpBuf[BUF_SIZE];
MyDestManager () {
pub.init_destination = init_buffer;
pub.empty_output_buffer = copy_buffer;
pub.term_destination = term_buffer;
pub.next_output_byte = mTmpBuf;
pub.free_in_buffer = BUF_SIZE;
}
void CopyBuffer () {
mOutput.append (mTmpBuf, BUF_SIZE);
pub.next_output_byte = mTmpBuf;
pub.free_in_buffer = BUF_SIZE;
}
void TermBuffer () {
mOutput.append (mTmpBuf, BUF_SIZE - pub.free_in_buffer);
}
static void init_buffer (jpeg_compress_struct* cinfo) {}
static boolean copy_buffer (jpeg_compress_struct* cinfo) {
MyDestManager *man = (MyDestManager *)cinfo->dest;
man->CopyBuffer ();
return TRUE;
}
static void term_buffer (jpeg_compress_struct* cinfo) {
MyDestManager *man = (MyDestManager *)cinfo->dest;
man->TermBuffer ();
}
};
bool JPEG::Decode (Resource *resource, ImageBuffer* imageBuffer, bool decodeData) {
struct jpeg_decompress_struct cinfo;
//struct jpeg_error_mgr jerr;
//cinfo.err = jpeg_std_error (&jerr);
struct ErrorData jpegError;
cinfo.err = jpeg_std_error (&jpegError.base);
jpegError.base.error_exit = OnError;
jpegError.base.output_message = OnOutput;
FILE_HANDLE *file = NULL;
Bytes *data = NULL;
MySrcManager *manager = NULL;
if (resource->path) {
file = lime::fopen (resource->path, "rb");
if (!file) {
return false;
}
}
if (setjmp (jpegError.on_error)) {
if (file) {
lime::fclose (file);
}
if (manager) {
delete manager;
}
if (data) {
delete data;
}
jpeg_destroy_decompress (&cinfo);
return false;
}
jpeg_create_decompress (&cinfo);
jpeg_save_markers (&cinfo, JPEG_APP0 + 14, 0xFF);
if (file) {
if (file->isFile ()) {
jpeg_stdio_src (&cinfo, file->getFile ());
} else {
data = new Bytes ();
data->ReadFile (resource->path);
manager = new MySrcManager (data->b, data->length);
cinfo.src = &manager->pub;
}
} else {
manager = new MySrcManager (resource->data->b, resource->data->length);
cinfo.src = &manager->pub;
}
bool decoded = false;
if (jpeg_read_header (&cinfo, TRUE) == JPEG_HEADER_OK) {
switch (cinfo.jpeg_color_space) {
case JCS_CMYK:
case JCS_YCCK:
cinfo.out_color_space = JCS_CMYK;
break;
case JCS_GRAYSCALE:
case JCS_RGB:
case JCS_YCbCr:
default:
cinfo.out_color_space = JCS_RGB;
break;
// case JCS_BG_RGB:
// case JCS_BG_YCC:
// case JCS_UNKNOWN:
}
if (decodeData) {
jpeg_start_decompress (&cinfo);
int components = cinfo.output_components;
imageBuffer->Resize (cinfo.output_width, cinfo.output_height, 32);
unsigned char *bytes = imageBuffer->data->buffer->b;
unsigned char *scanline = new unsigned char [imageBuffer->width * components];
if (cinfo.out_color_space == JCS_CMYK) {
bool invert = false;
jpeg_saved_marker_ptr marker;
marker = cinfo.marker_list;
while (marker) {
if (marker->marker == JPEG_APP0 + 14 && marker->data_length >= 12 && !strncmp ((const char*)marker->data, "Adobe", 5)) {
// Are there other transforms?
invert = true;
}
marker = marker->next;
}
while (cinfo.output_scanline < cinfo.output_height) {
jpeg_read_scanlines (&cinfo, &scanline, 1);
const unsigned char *line = scanline;
const unsigned char *const end = line + imageBuffer->width * components;
unsigned char c, m, y, k;
while (line < end) {
if (invert) {
c = 0xFF - *line++;
m = 0xFF - *line++;
y = 0xFF - *line++;
k = 0xFF - *line++;
} else {
c = *line++;
m = *line++;
y = *line++;
k = *line++;
}
*bytes++ = (unsigned char)((0xFF - c) * (0xFF - k) / 0xFF);
*bytes++ = (unsigned char)((0xFF - m) * (0xFF - k) / 0xFF);
*bytes++ = (unsigned char)((0xFF - y) * (0xFF - k) / 0xFF);
*bytes++ = 0xFF;
}
}
} else {
while (cinfo.output_scanline < cinfo.output_height) {
jpeg_read_scanlines (&cinfo, &scanline, 1);
// convert 24-bit scanline to 32-bit
const unsigned char *line = scanline;
const unsigned char *const end = line + imageBuffer->width * components;
while (line < end) {
*bytes++ = *line++;
*bytes++ = *line++;
*bytes++ = *line++;
*bytes++ = 0xFF;
}
}
}
delete[] scanline;
jpeg_finish_decompress (&cinfo);
} else {
imageBuffer->width = cinfo.image_width;
imageBuffer->height = cinfo.image_height;
}
decoded = true;
}
if (file) {
lime::fclose (file);
}
if (manager) {
delete manager;
}
if (data) {
delete data;
}
jpeg_destroy_decompress (&cinfo);
return decoded;
}
bool JPEG::Encode (ImageBuffer *imageBuffer, Bytes *bytes, int quality) {
struct jpeg_compress_struct cinfo;
struct ErrorData jpegError;
cinfo.err = jpeg_std_error (&jpegError.base);
jpegError.base.error_exit = OnError;
jpegError.base.output_message = OnOutput;
MyDestManager dest;
int w = imageBuffer->width;
int h = imageBuffer->height;
QuickVec<unsigned char> row_buf (w * 3);
jpeg_create_compress (&cinfo);
if (setjmp (jpegError.on_error)) {
jpeg_destroy_compress (&cinfo);
return false;
}
cinfo.dest = (jpeg_destination_mgr *)&dest;
cinfo.image_width = w;
cinfo.image_height = h;
cinfo.input_components = 3;
cinfo.in_color_space = JCS_RGB;
jpeg_set_defaults (&cinfo);
jpeg_set_quality (&cinfo, quality, TRUE);
jpeg_start_compress (&cinfo, TRUE);
JSAMPROW row_pointer = &row_buf[0];
unsigned char* imageData = imageBuffer->data->buffer->b;
int stride = imageBuffer->Stride ();
while (cinfo.next_scanline < cinfo.image_height) {
const unsigned char *src = (const unsigned char *)(imageData + (stride * cinfo.next_scanline));
unsigned char *dest = &row_buf[0];
for(int x = 0; x < w; x++) {
dest[0] = src[0];
dest[1] = src[1];
dest[2] = src[2];
dest += 3;
src += 4;
}
jpeg_write_scanlines (&cinfo, &row_pointer, 1);
}
jpeg_finish_compress (&cinfo);
int size = dest.mOutput.size ();
if (size > 0) {
bytes->Resize (size);
memcpy (bytes->b, &dest.mOutput[0], size);
}
return true;
}
}
<|endoftext|> |
<commit_before><commit_msg>make redirection of find command work with ROOT6<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2015-2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <compat.h>
#include <prevector.h>
#include <bench/bench.h>
struct nontrivial_t {
int x;
nontrivial_t() :x(-1) {}
};
static_assert(!IS_TRIVIALLY_CONSTRUCTIBLE<nontrivial_t>::value,
"expected nontrivial_t to not be trivially constructible");
typedef unsigned char trivial_t;
static_assert(IS_TRIVIALLY_CONSTRUCTIBLE<trivial_t>::value,
"expected trivial_t to be trivially constructible");
template <typename T>
static void PrevectorDestructor(benchmark::State& state)
{
while (state.KeepRunning()) {
for (auto x = 0; x < 1000; ++x) {
prevector<28, T> t0;
prevector<28, T> t1;
t0.resize(28);
t1.resize(29);
}
}
}
template <typename T>
static void PrevectorClear(benchmark::State& state)
{
while (state.KeepRunning()) {
for (auto x = 0; x < 1000; ++x) {
prevector<28, T> t0;
prevector<28, T> t1;
t0.resize(28);
t0.clear();
t1.resize(29);
t0.clear();
}
}
}
template <typename T>
static void PrevectorResize(benchmark::State& state)
{
while (state.KeepRunning()) {
prevector<28, T> t0;
prevector<28, T> t1;
for (auto x = 0; x < 1000; ++x) {
t0.resize(28);
t0.resize(0);
t1.resize(29);
t1.resize(0);
}
}
}
#define PREVECTOR_TEST(name, nontrivops, trivops) \
static void Prevector ## name ## Nontrivial(benchmark::State& state) { \
PrevectorResize<nontrivial_t>(state); \
} \
BENCHMARK(Prevector ## name ## Nontrivial, nontrivops); \
static void Prevector ## name ## Trivial(benchmark::State& state) { \
PrevectorResize<trivial_t>(state); \
} \
BENCHMARK(Prevector ## name ## Trivial, trivops);
PREVECTOR_TEST(Clear, 28300, 88600)
PREVECTOR_TEST(Destructor, 28800, 88900)
PREVECTOR_TEST(Resize, 28900, 90300)
<commit_msg>fix bench/prevector.cpp<commit_after>// Copyright (c) 2015-2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <compat.h>
#include <prevector.h>
#include <bench/bench.h>
struct nontrivial_t {
int x;
nontrivial_t() :x(-1) {}
};
static_assert(!IS_TRIVIALLY_CONSTRUCTIBLE<nontrivial_t>::value,
"expected nontrivial_t to not be trivially constructible");
typedef unsigned char trivial_t;
static_assert(IS_TRIVIALLY_CONSTRUCTIBLE<trivial_t>::value,
"expected trivial_t to be trivially constructible");
template <typename T>
static void PrevectorDestructor(benchmark::State& state)
{
while (state.KeepRunning()) {
for (auto x = 0; x < 1000; ++x) {
prevector<28, T> t0;
prevector<28, T> t1;
t0.resize(28);
t1.resize(29);
}
}
}
template <typename T>
static void PrevectorClear(benchmark::State& state)
{
while (state.KeepRunning()) {
for (auto x = 0; x < 1000; ++x) {
prevector<28, T> t0;
prevector<28, T> t1;
t0.resize(28);
t0.clear();
t1.resize(29);
t1.clear();
}
}
}
template <typename T>
static void PrevectorResize(benchmark::State& state)
{
while (state.KeepRunning()) {
prevector<28, T> t0;
prevector<28, T> t1;
for (auto x = 0; x < 1000; ++x) {
t0.resize(28);
t0.resize(0);
t1.resize(29);
t1.resize(0);
}
}
}
#define PREVECTOR_TEST(name, nontrivops, trivops) \
static void Prevector ## name ## Nontrivial(benchmark::State& state) { \
Prevector ## name<nontrivial_t>(state); \
} \
BENCHMARK(Prevector ## name ## Nontrivial, nontrivops); \
static void Prevector ## name ## Trivial(benchmark::State& state) { \
Prevector ## name<trivial_t>(state); \
} \
BENCHMARK(Prevector ## name ## Trivial, trivops);
PREVECTOR_TEST(Clear, 28300, 88600)
PREVECTOR_TEST(Destructor, 28800, 88900)
PREVECTOR_TEST(Resize, 28900, 90300)
<|endoftext|> |
<commit_before>/*************************************************************************/
/* area_bullet.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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 "area_bullet.h"
#include "bullet_physics_server.h"
#include "bullet_types_converter.h"
#include "bullet_utilities.h"
#include "collision_object_bullet.h"
#include "space_bullet.h"
#include <BulletCollision/CollisionDispatch/btGhostObject.h>
#include <btBulletCollisionCommon.h>
/**
@author AndreaCatania
*/
AreaBullet::AreaBullet() :
RigidCollisionObjectBullet(CollisionObjectBullet::TYPE_AREA) {
btGhost = bulletnew(btGhostObject);
reload_shapes();
setupBulletCollisionObject(btGhost);
/// Collision objects with a callback still have collision response with dynamic rigid bodies.
/// In order to use collision objects as trigger, you have to disable the collision response.
set_collision_enabled(false);
for (int i = 0; i < 5; ++i) {
call_event_res_ptr[i] = &call_event_res[i];
}
}
AreaBullet::~AreaBullet() {
// signal are handled by godot, so just clear without notify
for (int i = overlappingObjects.size() - 1; 0 <= i; --i) {
overlappingObjects[i].object->on_exit_area(this);
}
}
void AreaBullet::dispatch_callbacks() {
if (!isScratched) {
return;
}
isScratched = false;
// Reverse order because I've to remove EXIT objects
for (int i = overlappingObjects.size() - 1; 0 <= i; --i) {
OverlappingObjectData &otherObj = overlappingObjects.write[i];
switch (otherObj.state) {
case OVERLAP_STATE_ENTER:
otherObj.state = OVERLAP_STATE_INSIDE;
call_event(otherObj.object, PhysicsServer3D::AREA_BODY_ADDED);
otherObj.object->on_enter_area(this);
break;
case OVERLAP_STATE_EXIT:
call_event(otherObj.object, PhysicsServer3D::AREA_BODY_REMOVED);
otherObj.object->on_exit_area(this);
overlappingObjects.remove(i); // Remove after callback
break;
case OVERLAP_STATE_DIRTY:
case OVERLAP_STATE_INSIDE:
break;
}
}
}
void AreaBullet::call_event(CollisionObjectBullet *p_otherObject, PhysicsServer3D::AreaBodyStatus p_status) {
InOutEventCallback &event = eventsCallbacks[static_cast<int>(p_otherObject->getType())];
Object *areaGodoObject = ObjectDB::get_instance(event.event_callback_id);
if (!areaGodoObject) {
event.event_callback_id = ObjectID();
return;
}
call_event_res[0] = p_status;
call_event_res[1] = p_otherObject->get_self(); // Other body
call_event_res[2] = p_otherObject->get_instance_id(); // instance ID
call_event_res[3] = 0; // other_body_shape ID
call_event_res[4] = 0; // self_shape ID
Callable::CallError outResp;
areaGodoObject->call(event.event_callback_method, (const Variant **)call_event_res_ptr, 5, outResp);
}
void AreaBullet::scratch() {
if (isScratched) {
return;
}
isScratched = true;
}
void AreaBullet::clear_overlaps(bool p_notify) {
for (int i = overlappingObjects.size() - 1; 0 <= i; --i) {
if (p_notify) {
call_event(overlappingObjects[i].object, PhysicsServer3D::AREA_BODY_REMOVED);
}
overlappingObjects[i].object->on_exit_area(this);
}
overlappingObjects.clear();
}
void AreaBullet::remove_overlap(CollisionObjectBullet *p_object, bool p_notify) {
for (int i = overlappingObjects.size() - 1; 0 <= i; --i) {
if (overlappingObjects[i].object == p_object) {
if (p_notify) {
call_event(overlappingObjects[i].object, PhysicsServer3D::AREA_BODY_REMOVED);
}
overlappingObjects[i].object->on_exit_area(this);
overlappingObjects.remove(i);
break;
}
}
}
int AreaBullet::find_overlapping_object(CollisionObjectBullet *p_colObj) {
const int size = overlappingObjects.size();
for (int i = 0; i < size; ++i) {
if (overlappingObjects[i].object == p_colObj) {
return i;
}
}
return -1;
}
void AreaBullet::set_monitorable(bool p_monitorable) {
monitorable = p_monitorable;
}
bool AreaBullet::is_monitoring() const {
return get_godot_object_flags() & GOF_IS_MONITORING_AREA;
}
void AreaBullet::main_shape_changed() {
CRASH_COND(!get_main_shape());
btGhost->setCollisionShape(get_main_shape());
}
void AreaBullet::reload_body() {
if (space) {
space->remove_area(this);
space->add_area(this);
}
}
void AreaBullet::set_space(SpaceBullet *p_space) {
// Clear the old space if there is one
if (space) {
isScratched = false;
// Remove this object form the physics world
space->remove_area(this);
}
space = p_space;
if (space) {
space->add_area(this);
}
}
void AreaBullet::on_collision_filters_change() {
if (space) {
space->reload_collision_filters(this);
}
}
void AreaBullet::add_overlap(CollisionObjectBullet *p_otherObject) {
scratch();
overlappingObjects.push_back(OverlappingObjectData(p_otherObject, OVERLAP_STATE_ENTER));
p_otherObject->notify_new_overlap(this);
}
void AreaBullet::put_overlap_as_exit(int p_index) {
scratch();
overlappingObjects.write[p_index].state = OVERLAP_STATE_EXIT;
}
void AreaBullet::put_overlap_as_inside(int p_index) {
// This check is required to be sure this body was inside
if (OVERLAP_STATE_DIRTY == overlappingObjects[p_index].state) {
overlappingObjects.write[p_index].state = OVERLAP_STATE_INSIDE;
}
}
void AreaBullet::set_param(PhysicsServer3D::AreaParameter p_param, const Variant &p_value) {
switch (p_param) {
case PhysicsServer3D::AREA_PARAM_GRAVITY:
set_spOv_gravityMag(p_value);
break;
case PhysicsServer3D::AREA_PARAM_GRAVITY_VECTOR:
set_spOv_gravityVec(p_value);
break;
case PhysicsServer3D::AREA_PARAM_LINEAR_DAMP:
set_spOv_linearDump(p_value);
break;
case PhysicsServer3D::AREA_PARAM_ANGULAR_DAMP:
set_spOv_angularDump(p_value);
break;
case PhysicsServer3D::AREA_PARAM_PRIORITY:
set_spOv_priority(p_value);
break;
case PhysicsServer3D::AREA_PARAM_GRAVITY_IS_POINT:
set_spOv_gravityPoint(p_value);
break;
case PhysicsServer3D::AREA_PARAM_GRAVITY_DISTANCE_SCALE:
set_spOv_gravityPointDistanceScale(p_value);
break;
case PhysicsServer3D::AREA_PARAM_GRAVITY_POINT_ATTENUATION:
set_spOv_gravityPointAttenuation(p_value);
break;
default:
WARN_PRINT("Area doesn't support this parameter in the Bullet backend: " + itos(p_param));
}
}
Variant AreaBullet::get_param(PhysicsServer3D::AreaParameter p_param) const {
switch (p_param) {
case PhysicsServer3D::AREA_PARAM_GRAVITY:
return spOv_gravityMag;
case PhysicsServer3D::AREA_PARAM_GRAVITY_VECTOR:
return spOv_gravityVec;
case PhysicsServer3D::AREA_PARAM_LINEAR_DAMP:
return spOv_linearDump;
case PhysicsServer3D::AREA_PARAM_ANGULAR_DAMP:
return spOv_angularDump;
case PhysicsServer3D::AREA_PARAM_PRIORITY:
return spOv_priority;
case PhysicsServer3D::AREA_PARAM_GRAVITY_IS_POINT:
return spOv_gravityPoint;
case PhysicsServer3D::AREA_PARAM_GRAVITY_DISTANCE_SCALE:
return spOv_gravityPointDistanceScale;
case PhysicsServer3D::AREA_PARAM_GRAVITY_POINT_ATTENUATION:
return spOv_gravityPointAttenuation;
default:
WARN_PRINT("Area doesn't support this parameter in the Bullet backend: " + itos(p_param));
return Variant();
}
}
void AreaBullet::set_event_callback(Type p_callbackObjectType, ObjectID p_id, const StringName &p_method) {
InOutEventCallback &ev = eventsCallbacks[static_cast<int>(p_callbackObjectType)];
ev.event_callback_id = p_id;
ev.event_callback_method = p_method;
/// Set if monitoring
if (eventsCallbacks[0].event_callback_id.is_valid() || eventsCallbacks[1].event_callback_id.is_valid()) {
set_godot_object_flags(get_godot_object_flags() | GOF_IS_MONITORING_AREA);
} else {
set_godot_object_flags(get_godot_object_flags() & (~GOF_IS_MONITORING_AREA));
}
}
bool AreaBullet::has_event_callback(Type p_callbackObjectType) {
return eventsCallbacks[static_cast<int>(p_callbackObjectType)].event_callback_id.is_valid();
}
void AreaBullet::on_enter_area(AreaBullet *p_area) {
}
void AreaBullet::on_exit_area(AreaBullet *p_area) {
CollisionObjectBullet::on_exit_area(p_area);
}
<commit_msg>Clear a Bullet Area's overlappingObjects vector when removing an area from a space.<commit_after>/*************************************************************************/
/* area_bullet.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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 "area_bullet.h"
#include "bullet_physics_server.h"
#include "bullet_types_converter.h"
#include "bullet_utilities.h"
#include "collision_object_bullet.h"
#include "space_bullet.h"
#include <BulletCollision/CollisionDispatch/btGhostObject.h>
#include <btBulletCollisionCommon.h>
/**
@author AndreaCatania
*/
AreaBullet::AreaBullet() :
RigidCollisionObjectBullet(CollisionObjectBullet::TYPE_AREA) {
btGhost = bulletnew(btGhostObject);
reload_shapes();
setupBulletCollisionObject(btGhost);
/// Collision objects with a callback still have collision response with dynamic rigid bodies.
/// In order to use collision objects as trigger, you have to disable the collision response.
set_collision_enabled(false);
for (int i = 0; i < 5; ++i) {
call_event_res_ptr[i] = &call_event_res[i];
}
}
AreaBullet::~AreaBullet() {
// signal are handled by godot, so just clear without notify
for (int i = overlappingObjects.size() - 1; 0 <= i; --i) {
overlappingObjects[i].object->on_exit_area(this);
}
}
void AreaBullet::dispatch_callbacks() {
if (!isScratched) {
return;
}
isScratched = false;
// Reverse order because I've to remove EXIT objects
for (int i = overlappingObjects.size() - 1; 0 <= i; --i) {
OverlappingObjectData &otherObj = overlappingObjects.write[i];
switch (otherObj.state) {
case OVERLAP_STATE_ENTER:
otherObj.state = OVERLAP_STATE_INSIDE;
call_event(otherObj.object, PhysicsServer3D::AREA_BODY_ADDED);
otherObj.object->on_enter_area(this);
break;
case OVERLAP_STATE_EXIT:
call_event(otherObj.object, PhysicsServer3D::AREA_BODY_REMOVED);
otherObj.object->on_exit_area(this);
overlappingObjects.remove(i); // Remove after callback
break;
case OVERLAP_STATE_DIRTY:
case OVERLAP_STATE_INSIDE:
break;
}
}
}
void AreaBullet::call_event(CollisionObjectBullet *p_otherObject, PhysicsServer3D::AreaBodyStatus p_status) {
InOutEventCallback &event = eventsCallbacks[static_cast<int>(p_otherObject->getType())];
Object *areaGodoObject = ObjectDB::get_instance(event.event_callback_id);
if (!areaGodoObject) {
event.event_callback_id = ObjectID();
return;
}
call_event_res[0] = p_status;
call_event_res[1] = p_otherObject->get_self(); // Other body
call_event_res[2] = p_otherObject->get_instance_id(); // instance ID
call_event_res[3] = 0; // other_body_shape ID
call_event_res[4] = 0; // self_shape ID
Callable::CallError outResp;
areaGodoObject->call(event.event_callback_method, (const Variant **)call_event_res_ptr, 5, outResp);
}
void AreaBullet::scratch() {
if (isScratched) {
return;
}
isScratched = true;
}
void AreaBullet::clear_overlaps(bool p_notify) {
for (int i = overlappingObjects.size() - 1; 0 <= i; --i) {
if (p_notify) {
call_event(overlappingObjects[i].object, PhysicsServer3D::AREA_BODY_REMOVED);
}
overlappingObjects[i].object->on_exit_area(this);
}
overlappingObjects.clear();
}
void AreaBullet::remove_overlap(CollisionObjectBullet *p_object, bool p_notify) {
for (int i = overlappingObjects.size() - 1; 0 <= i; --i) {
if (overlappingObjects[i].object == p_object) {
if (p_notify) {
call_event(overlappingObjects[i].object, PhysicsServer3D::AREA_BODY_REMOVED);
}
overlappingObjects[i].object->on_exit_area(this);
overlappingObjects.remove(i);
break;
}
}
}
int AreaBullet::find_overlapping_object(CollisionObjectBullet *p_colObj) {
const int size = overlappingObjects.size();
for (int i = 0; i < size; ++i) {
if (overlappingObjects[i].object == p_colObj) {
return i;
}
}
return -1;
}
void AreaBullet::set_monitorable(bool p_monitorable) {
monitorable = p_monitorable;
}
bool AreaBullet::is_monitoring() const {
return get_godot_object_flags() & GOF_IS_MONITORING_AREA;
}
void AreaBullet::main_shape_changed() {
CRASH_COND(!get_main_shape());
btGhost->setCollisionShape(get_main_shape());
}
void AreaBullet::reload_body() {
if (space) {
space->remove_area(this);
space->add_area(this);
}
}
void AreaBullet::set_space(SpaceBullet *p_space) {
// Clear the old space if there is one
if (space) {
overlappingObjects.clear();
isScratched = false;
// Remove this object form the physics world
space->remove_area(this);
}
space = p_space;
if (space) {
space->add_area(this);
}
}
void AreaBullet::on_collision_filters_change() {
if (space) {
space->reload_collision_filters(this);
}
}
void AreaBullet::add_overlap(CollisionObjectBullet *p_otherObject) {
scratch();
overlappingObjects.push_back(OverlappingObjectData(p_otherObject, OVERLAP_STATE_ENTER));
p_otherObject->notify_new_overlap(this);
}
void AreaBullet::put_overlap_as_exit(int p_index) {
scratch();
overlappingObjects.write[p_index].state = OVERLAP_STATE_EXIT;
}
void AreaBullet::put_overlap_as_inside(int p_index) {
// This check is required to be sure this body was inside
if (OVERLAP_STATE_DIRTY == overlappingObjects[p_index].state) {
overlappingObjects.write[p_index].state = OVERLAP_STATE_INSIDE;
}
}
void AreaBullet::set_param(PhysicsServer3D::AreaParameter p_param, const Variant &p_value) {
switch (p_param) {
case PhysicsServer3D::AREA_PARAM_GRAVITY:
set_spOv_gravityMag(p_value);
break;
case PhysicsServer3D::AREA_PARAM_GRAVITY_VECTOR:
set_spOv_gravityVec(p_value);
break;
case PhysicsServer3D::AREA_PARAM_LINEAR_DAMP:
set_spOv_linearDump(p_value);
break;
case PhysicsServer3D::AREA_PARAM_ANGULAR_DAMP:
set_spOv_angularDump(p_value);
break;
case PhysicsServer3D::AREA_PARAM_PRIORITY:
set_spOv_priority(p_value);
break;
case PhysicsServer3D::AREA_PARAM_GRAVITY_IS_POINT:
set_spOv_gravityPoint(p_value);
break;
case PhysicsServer3D::AREA_PARAM_GRAVITY_DISTANCE_SCALE:
set_spOv_gravityPointDistanceScale(p_value);
break;
case PhysicsServer3D::AREA_PARAM_GRAVITY_POINT_ATTENUATION:
set_spOv_gravityPointAttenuation(p_value);
break;
default:
WARN_PRINT("Area doesn't support this parameter in the Bullet backend: " + itos(p_param));
}
}
Variant AreaBullet::get_param(PhysicsServer3D::AreaParameter p_param) const {
switch (p_param) {
case PhysicsServer3D::AREA_PARAM_GRAVITY:
return spOv_gravityMag;
case PhysicsServer3D::AREA_PARAM_GRAVITY_VECTOR:
return spOv_gravityVec;
case PhysicsServer3D::AREA_PARAM_LINEAR_DAMP:
return spOv_linearDump;
case PhysicsServer3D::AREA_PARAM_ANGULAR_DAMP:
return spOv_angularDump;
case PhysicsServer3D::AREA_PARAM_PRIORITY:
return spOv_priority;
case PhysicsServer3D::AREA_PARAM_GRAVITY_IS_POINT:
return spOv_gravityPoint;
case PhysicsServer3D::AREA_PARAM_GRAVITY_DISTANCE_SCALE:
return spOv_gravityPointDistanceScale;
case PhysicsServer3D::AREA_PARAM_GRAVITY_POINT_ATTENUATION:
return spOv_gravityPointAttenuation;
default:
WARN_PRINT("Area doesn't support this parameter in the Bullet backend: " + itos(p_param));
return Variant();
}
}
void AreaBullet::set_event_callback(Type p_callbackObjectType, ObjectID p_id, const StringName &p_method) {
InOutEventCallback &ev = eventsCallbacks[static_cast<int>(p_callbackObjectType)];
ev.event_callback_id = p_id;
ev.event_callback_method = p_method;
/// Set if monitoring
if (eventsCallbacks[0].event_callback_id.is_valid() || eventsCallbacks[1].event_callback_id.is_valid()) {
set_godot_object_flags(get_godot_object_flags() | GOF_IS_MONITORING_AREA);
} else {
set_godot_object_flags(get_godot_object_flags() & (~GOF_IS_MONITORING_AREA));
}
}
bool AreaBullet::has_event_callback(Type p_callbackObjectType) {
return eventsCallbacks[static_cast<int>(p_callbackObjectType)].event_callback_id.is_valid();
}
void AreaBullet::on_enter_area(AreaBullet *p_area) {
}
void AreaBullet::on_exit_area(AreaBullet *p_area) {
CollisionObjectBullet::on_exit_area(p_area);
}
<|endoftext|> |
<commit_before>#include "dynet/nodes.h"
#include "dynet/dynet.h"
#include "dynet/training.h"
#include "dynet/timing.h"
#include "dynet/rnn.h"
#include "dynet/gru.h"
#include "dynet/lstm.h"
#include "dynet/dict.h"
#include "dynet/expr.h"
#include "dynet/cfsm-builder.h"
#include "dynet/hsm-builder.h"
#include "dynet/globals.h"
#include "dynet/io.h"
#include "../utils/getpid.h"
#include "../utils/cl-args.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <memory>
using namespace std;
using namespace dynet;
unsigned LAYERS = 0;
unsigned INPUT_DIM = 0;
unsigned HIDDEN_DIM = 0;
unsigned VOCAB_SIZE = 0;
float DROPOUT = 0;
bool SAMPLE = false;
SoftmaxBuilder* cfsm = nullptr;
dynet::Dict d;
int kSOS;
int kEOS;
volatile bool INTERRUPTED = false;
template <class Builder>
struct RNNLanguageModel {
LookupParameter p_c;
Parameter p_R;
Parameter p_bias;
Builder builder;
explicit RNNLanguageModel(ParameterCollection& model) : builder(LAYERS, INPUT_DIM, HIDDEN_DIM, model) {
p_c = model.add_lookup_parameters(VOCAB_SIZE, {INPUT_DIM});
p_R = model.add_parameters({VOCAB_SIZE, HIDDEN_DIM});
p_bias = model.add_parameters({VOCAB_SIZE});
}
// return Expression of total loss
Expression BuildLMGraph(const vector<int>& sent, ComputationGraph& cg, bool apply_dropout) {
const unsigned slen = sent.size();
if (apply_dropout) {
builder.set_dropout(DROPOUT);
} else {
builder.disable_dropout();
}
builder.new_graph(cg); // reset RNN builder for new graph
builder.start_new_sequence();
if (cfsm) cfsm->new_graph(cg);
Expression R = parameter(cg, p_R); // hidden -> word rep parameter
Expression bias = parameter(cg, p_bias); // word bias
vector<Expression> errs(slen + 1);
Expression h_t = builder.add_input(lookup(cg, p_c, kSOS)); // read <s>
for (unsigned t = 0; t < slen; ++t) { // h_t = RNN(x_0,...,x_t)
if (cfsm) { // class-factored softmax
errs[t] = cfsm->neg_log_softmax(h_t, sent[t]);
} else { // regular softmax
Expression u_t = affine_transform({bias, R, h_t});
errs[t] = pickneglogsoftmax(u_t, sent[t]);
}
Expression x_t = lookup(cg, p_c, sent[t]);
h_t = builder.add_input(x_t);
}
// it reamins to deal predict </s>
if (cfsm) {
errs.back() = cfsm->neg_log_softmax(h_t, kEOS);
} else {
Expression u_last = affine_transform({bias, R, h_t});
errs.back() = pickneglogsoftmax(u_last, kEOS); // predict </s>
}
return sum(errs);
}
void RandomSample(int max_len = 200) {
ComputationGraph cg;
builder.new_graph(cg); // reset RNN builder for new graph
builder.start_new_sequence();
if (cfsm) cfsm->new_graph(cg);
Expression R = parameter(cg, p_R); // hidden -> word rep parameter
Expression bias = parameter(cg, p_bias); // word bias
Expression h_t = builder.add_input(lookup(cg, p_c, kSOS)); // read <s>
int cur = kSOS;
int len = 0;
while (len < max_len) {
if (cfsm) { // class-factored softmax
cur = cfsm->sample(h_t);
} else { // regular softmax
Expression u_t = affine_transform({bias, R, h_t});
Expression dist_expr = softmax(u_t);
auto dist = as_vector(cg.incremental_forward(dist_expr));
double p = rand01();
cur = 0;
for (; static_cast<unsigned>(cur) < dist.size(); ++cur) {
p -= dist[cur];
if (p < 0.0) { break; }
}
if (static_cast<unsigned>(cur) == dist.size()) cur = kEOS;
}
if (cur == kEOS) break;
++len;
cerr << (len == 1 ? "" : " ") << d.convert(cur);
Expression x_t = lookup(cg, p_c, cur);
h_t = builder.add_input(x_t);
}
cerr << endl;
}
};
void inline read_fields(string line, vector<string>& fields, string delimiter = "|||") {
string field;
int start = 0, end = 0, delim_size = delimiter.size();
while (true) {
end = line.find(delimiter, start);
fields.push_back(line.substr(start, end - start));
if (end == (int)std::string::npos) break;
start = end + delim_size;
}
}
// Read the dataset, returns the number of tokens
unsigned read_data(const string& filename,
vector<vector<int>>& data) {
unsigned num_tokens = 0;
ifstream in(filename);
assert(in);
size_t lc = 0;
string line;
while (getline(in, line)) {
++lc;
data.push_back(read_sentence(line, d));
num_tokens += data.back().size();
if (data.back().front() == kSOS || data.back().back() == kEOS) {
cerr << "sentence in " << filename << ":" << lc << " started with <s> or ended with </s>\n";
abort();
}
}
return num_tokens;
}
int main(int argc, char** argv) {
cerr << "COMMAND LINE:";
for (unsigned i = 0; i < static_cast<unsigned>(argc); ++i) cerr << ' ' << argv[i];
cerr << endl;
// Fetch dynet params ----------------------------------------------------------------------------
auto dyparams = dynet::extract_dynet_params(argc, argv);
dynet::initialize(dyparams);
// Fetch program specific parameters (see ../utils/cl-args.h) ------------------------------------
Params params;
get_args(argc, argv, params, TRAIN);
kSOS = d.convert("<s>");
kEOS = d.convert("</s>");
LAYERS = params.LAYERS;
INPUT_DIM = params.INPUT_DIM;
HIDDEN_DIM = params.HIDDEN_DIM;
SAMPLE = params.sample;
if (params.dropout_rate)
DROPOUT = params.dropout_rate;
ParameterCollection model;
if (params.clusters_file != "")
cfsm = new ClassFactoredSoftmaxBuilder(HIDDEN_DIM, params.clusters_file, d, model);
else if (params.paths_file != "")
cfsm = new HierarchicalSoftmaxBuilder(HIDDEN_DIM, params.paths_file, d, model);
float eta_decay_rate = params.eta_decay_rate;
unsigned eta_decay_onset_epoch = params.eta_decay_onset_epoch;
vector<vector<int>> training, dev, test;
string line;
int tlc = 0;
int ttoks = 0;
{
string trainf = params.train_file;
cerr << "Reading training data from " << trainf << " ...\n";
ttoks = read_data(trainf, training);
tlc = training.size();
cerr << tlc << " lines, " << ttoks << " tokens, " << d.size() << " types\n";
}
d.freeze(); // no new word types allowed
d.set_unk("<unk>");
VOCAB_SIZE = d.size();
if (!cfsm)
cfsm = new StandardSoftmaxBuilder(HIDDEN_DIM, VOCAB_SIZE, model);
if (params.test_file != "") {
string testf = params.test_file;
cerr << "Reading test data from " << testf << " ...\n";
read_data(testf, test);
}
std::unique_ptr<Trainer> trainer(new SimpleSGDTrainer(model));
trainer->learning_rate = params.eta0;
RNNLanguageModel<LSTMBuilder> lm(model);
bool has_model_to_load = params.model_file != "";
if (has_model_to_load) {
string fname = params.model_file;
cerr << "Reading parameters from " << fname << "...\n";
TextFileLoader loader(fname);
loader.populate(model);
}
bool TRAIN = (params.train_file != "");
if (TRAIN) {
int dlc = 0;
int dtoks = 0;
if (params.dev_file == "") {
cerr << "You must specify a development set (--dev file.txt) with --train" << endl;
abort();
} else {
string devf = params.dev_file;
cerr << "Reading dev data from " << devf << " ...\n";
dtoks = read_data(devf, dev);
cerr << dlc << " lines, " << dtoks << " tokens\n";
}
ostringstream os;
os << "lm"
<< '_' << DROPOUT
<< '_' << LAYERS
<< '_' << INPUT_DIM
<< '_' << HIDDEN_DIM
<< "-pid" << getpid() << ".params";
const string fname = os.str();
cerr << "Parameters will be written to: " << fname << endl;
double best = 9e+99;
unsigned report_every_i = 100;
unsigned dev_every_i_reports = 25;
unsigned si = training.size();
if (report_every_i > si) report_every_i = si;
vector<unsigned> order(training.size());
for (unsigned i = 0; i < order.size(); ++i) order[i] = i;
int report = 0;
double lines = 0;
int completed_epoch = -1;
while (!INTERRUPTED) {
if (SAMPLE) lm.RandomSample();
Timer iteration("completed in");
double loss = 0;
unsigned chars = 0;
for (unsigned i = 0; i < report_every_i; ++i) {
if (si == training.size()) {
si = 0;
cerr << "**SHUFFLE\n";
completed_epoch++;
if (eta_decay_onset_epoch && completed_epoch >= (int)eta_decay_onset_epoch)
trainer->learning_rate *= eta_decay_rate;
shuffle(order.begin(), order.end(), *rndeng);
}
// build graph for this instance
ComputationGraph cg;
auto& sent = training[order[si]];
chars += sent.size();
++si;
Expression loss_expr = lm.BuildLMGraph(sent, cg, DROPOUT > 0.f);
loss += as_scalar(cg.forward(loss_expr));
cg.backward(loss_expr);
trainer->update();
++lines;
}
report++;
cerr << '#' << report << " [epoch=" << (lines / training.size()) << " lr=" << trainer->learning_rate << "] E = " << (loss / chars) << " ppl=" << exp(loss / chars) << ' ';
// show score on dev data?
if (report % dev_every_i_reports == 0) {
double dloss = 0;
int dchars = 0;
for (auto& sent : dev) {
ComputationGraph cg;
Expression loss_expr = lm.BuildLMGraph(sent, cg, false);
dloss += as_scalar(cg.forward(loss_expr));
dchars += sent.size();
}
if (dloss < best) {
best = dloss;
TextFileSaver saver(fname);
saver.save(model);
}
cerr << "\n***DEV [epoch=" << (lines / training.size()) << "] E = " << (dloss / dchars) << " ppl=" << exp(dloss / dchars) << ' ';
}
}
} // train?
if (params.test_file != "") {
cerr << "Evaluating test data...\n";
double tloss = 0;
int tchars = 0;
for (auto& sent : test) {
ComputationGraph cg;
Expression loss_expr = lm.BuildLMGraph(sent, cg, false);
tloss += as_scalar(cg.forward(loss_expr));
tchars += sent.size();
}
cerr << "TEST -LLH = " << tloss << endl;
cerr << "TEST CROSS ENTOPY (NATS) = " << (tloss / tchars) << endl;
cerr << "TEST PPL = " << exp(tloss / tchars) << endl;
}
// N-best scoring
if (params.nbest_file != "") {
// cdec: index ||| hypothesis ||| feature=val ... ||| ...
// Moses: index ||| hypothesis ||| feature= val(s) ... ||| ...
const int HYP_FIELD = 1;
const int FEAT_FIELD = 2;
const string FEAT_NAME = "RNNLM";
// Input
string nbestf = params.nbest_file;
cerr << "Scoring N-best list " << nbestf << " ..." << endl;
shared_ptr<istream> in;
if (nbestf == "-") {
in.reset(&cin, [](...) {});
} else {
in.reset(new ifstream(nbestf));
}
// Match spacing of input file
string sep = "=";
bool sep_detected = false;
// Input lines
while (getline(*in, line)) {
vector<string> fields;
read_fields(line, fields);
// Check sep if needed
if (!sep_detected) {
sep_detected = true;
int i = fields[FEAT_FIELD].find("=");
if (fields[FEAT_FIELD].substr(i + 1, 1) == " ") {
sep = "= ";
}
}
// Score hypothesis
ComputationGraph cg;
Expression loss_expr = lm.BuildLMGraph(read_sentence(fields[HYP_FIELD], d), cg, false);
double loss = as_scalar(cg.forward(loss_expr));
// Add score
ostringstream os;
os << fields[FEAT_FIELD] << " " << FEAT_NAME << sep << loss;
fields[FEAT_FIELD] = os.str();
// Write augmented line
for (unsigned f = 0; f < fields.size(); ++f) {
if (f > 0)
cout << " ||| ";
cout << fields[f];
}
cout << endl;
}
}
}
<commit_msg>examples: attempt to fix training with standard softmax (#905)<commit_after>#include "dynet/nodes.h"
#include "dynet/dynet.h"
#include "dynet/training.h"
#include "dynet/timing.h"
#include "dynet/rnn.h"
#include "dynet/gru.h"
#include "dynet/lstm.h"
#include "dynet/dict.h"
#include "dynet/expr.h"
#include "dynet/cfsm-builder.h"
#include "dynet/hsm-builder.h"
#include "dynet/globals.h"
#include "dynet/io.h"
#include "../utils/getpid.h"
#include "../utils/cl-args.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <memory>
using namespace std;
using namespace dynet;
unsigned LAYERS = 0;
unsigned INPUT_DIM = 0;
unsigned HIDDEN_DIM = 0;
unsigned VOCAB_SIZE = 0;
float DROPOUT = 0;
bool SAMPLE = false;
SoftmaxBuilder* cfsm = nullptr;
dynet::Dict d;
int kSOS;
int kEOS;
volatile bool INTERRUPTED = false;
template <class Builder>
struct RNNLanguageModel {
LookupParameter p_c;
Parameter p_R;
Parameter p_bias;
Builder builder;
explicit RNNLanguageModel(ParameterCollection& model) : builder(LAYERS, INPUT_DIM, HIDDEN_DIM, model) {
p_c = model.add_lookup_parameters(VOCAB_SIZE, {INPUT_DIM});
p_R = model.add_parameters({VOCAB_SIZE, HIDDEN_DIM});
p_bias = model.add_parameters({VOCAB_SIZE});
}
// return Expression of total loss
Expression BuildLMGraph(const vector<int>& sent, ComputationGraph& cg, bool apply_dropout) {
const unsigned slen = sent.size();
if (apply_dropout) {
builder.set_dropout(DROPOUT);
} else {
builder.disable_dropout();
}
builder.new_graph(cg); // reset RNN builder for new graph
builder.start_new_sequence();
if (cfsm) cfsm->new_graph(cg);
Expression R = parameter(cg, p_R); // hidden -> word rep parameter
Expression bias = parameter(cg, p_bias); // word bias
vector<Expression> errs(slen + 1);
Expression h_t = builder.add_input(lookup(cg, p_c, kSOS)); // read <s>
for (unsigned t = 0; t < slen; ++t) { // h_t = RNN(x_0,...,x_t)
if (cfsm) { // class-factored softmax
errs[t] = cfsm->neg_log_softmax(h_t, sent[t]);
} else { // regular softmax
Expression u_t = affine_transform({bias, R, h_t});
errs[t] = pickneglogsoftmax(u_t, sent[t]);
}
Expression x_t = lookup(cg, p_c, sent[t]);
h_t = builder.add_input(x_t);
}
// it reamins to deal predict </s>
if (cfsm) {
errs.back() = cfsm->neg_log_softmax(h_t, kEOS);
} else {
Expression u_last = affine_transform({bias, R, h_t});
errs.back() = pickneglogsoftmax(u_last, kEOS); // predict </s>
}
return sum(errs);
}
void RandomSample(int max_len = 200) {
ComputationGraph cg;
builder.new_graph(cg); // reset RNN builder for new graph
builder.start_new_sequence();
if (cfsm) cfsm->new_graph(cg);
Expression R = parameter(cg, p_R); // hidden -> word rep parameter
Expression bias = parameter(cg, p_bias); // word bias
Expression h_t = builder.add_input(lookup(cg, p_c, kSOS)); // read <s>
int cur = kSOS;
int len = 0;
while (len < max_len) {
if (cfsm) { // class-factored softmax
cur = cfsm->sample(h_t);
} else { // regular softmax
Expression u_t = affine_transform({bias, R, h_t});
Expression dist_expr = softmax(u_t);
auto dist = as_vector(cg.incremental_forward(dist_expr));
double p = rand01();
cur = 0;
for (; static_cast<unsigned>(cur) < dist.size(); ++cur) {
p -= dist[cur];
if (p < 0.0) { break; }
}
if (static_cast<unsigned>(cur) == dist.size()) cur = kEOS;
}
if (cur == kEOS) break;
++len;
cerr << (len == 1 ? "" : " ") << d.convert(cur);
Expression x_t = lookup(cg, p_c, cur);
h_t = builder.add_input(x_t);
}
cerr << endl;
}
};
void inline read_fields(string line, vector<string>& fields, string delimiter = "|||") {
string field;
int start = 0, end = 0, delim_size = delimiter.size();
while (true) {
end = line.find(delimiter, start);
fields.push_back(line.substr(start, end - start));
if (end == (int)std::string::npos) break;
start = end + delim_size;
}
}
// Read the dataset, returns the number of tokens
unsigned read_data(const string& filename,
vector<vector<int>>& data) {
unsigned num_tokens = 0;
ifstream in(filename);
assert(in);
size_t lc = 0;
string line;
while (getline(in, line)) {
++lc;
data.push_back(read_sentence(line, d));
num_tokens += data.back().size();
if (data.back().front() == kSOS || data.back().back() == kEOS) {
cerr << "sentence in " << filename << ":" << lc << " started with <s> or ended with </s>\n";
abort();
}
}
return num_tokens;
}
int main(int argc, char** argv) {
cerr << "COMMAND LINE:";
for (unsigned i = 0; i < static_cast<unsigned>(argc); ++i) cerr << ' ' << argv[i];
cerr << endl;
// Fetch dynet params ----------------------------------------------------------------------------
auto dyparams = dynet::extract_dynet_params(argc, argv);
dynet::initialize(dyparams);
// Fetch program specific parameters (see ../utils/cl-args.h) ------------------------------------
Params params;
get_args(argc, argv, params, TRAIN);
kSOS = d.convert("<s>");
kEOS = d.convert("</s>");
LAYERS = params.LAYERS;
INPUT_DIM = params.INPUT_DIM;
HIDDEN_DIM = params.HIDDEN_DIM;
SAMPLE = params.sample;
if (params.dropout_rate)
DROPOUT = params.dropout_rate;
ParameterCollection model;
if (params.clusters_file != "")
cfsm = new ClassFactoredSoftmaxBuilder(HIDDEN_DIM, params.clusters_file, d, model);
else if (params.paths_file != "")
cfsm = new HierarchicalSoftmaxBuilder(HIDDEN_DIM, params.paths_file, d, model);
float eta_decay_rate = params.eta_decay_rate;
unsigned eta_decay_onset_epoch = params.eta_decay_onset_epoch;
vector<vector<int>> training, dev, test;
string line;
int tlc = 0;
int ttoks = 0;
{
string trainf = params.train_file;
cerr << "Reading training data from " << trainf << " ...\n";
ttoks = read_data(trainf, training);
tlc = training.size();
cerr << tlc << " lines, " << ttoks << " tokens, " << d.size() << " types\n";
}
d.freeze(); // no new word types allowed
d.set_unk("<unk>");
VOCAB_SIZE = d.size();
if (params.test_file != "") {
string testf = params.test_file;
cerr << "Reading test data from " << testf << " ...\n";
read_data(testf, test);
}
std::unique_ptr<Trainer> trainer(new SimpleSGDTrainer(model));
trainer->learning_rate = params.eta0;
RNNLanguageModel<LSTMBuilder> lm(model);
bool has_model_to_load = params.model_file != "";
if (has_model_to_load) {
string fname = params.model_file;
cerr << "Reading parameters from " << fname << "...\n";
TextFileLoader loader(fname);
loader.populate(model);
}
bool TRAIN = (params.train_file != "");
if (TRAIN) {
int dlc = 0;
int dtoks = 0;
if (params.dev_file == "") {
cerr << "You must specify a development set (--dev file.txt) with --train" << endl;
abort();
} else {
string devf = params.dev_file;
cerr << "Reading dev data from " << devf << " ...\n";
dtoks = read_data(devf, dev);
cerr << dlc << " lines, " << dtoks << " tokens\n";
}
ostringstream os;
os << "lm"
<< '_' << DROPOUT
<< '_' << LAYERS
<< '_' << INPUT_DIM
<< '_' << HIDDEN_DIM
<< "-pid" << getpid() << ".params";
const string fname = os.str();
cerr << "Parameters will be written to: " << fname << endl;
double best = 9e+99;
unsigned report_every_i = 100;
unsigned dev_every_i_reports = 25;
unsigned si = training.size();
if (report_every_i > si) report_every_i = si;
vector<unsigned> order(training.size());
for (unsigned i = 0; i < order.size(); ++i) order[i] = i;
int report = 0;
double lines = 0;
int completed_epoch = -1;
while (!INTERRUPTED) {
if (SAMPLE) lm.RandomSample();
Timer iteration("completed in");
double loss = 0;
unsigned chars = 0;
for (unsigned i = 0; i < report_every_i; ++i) {
if (si == training.size()) {
si = 0;
cerr << "**SHUFFLE\n";
completed_epoch++;
if (eta_decay_onset_epoch && completed_epoch >= (int)eta_decay_onset_epoch)
trainer->learning_rate *= eta_decay_rate;
shuffle(order.begin(), order.end(), *rndeng);
}
// build graph for this instance
ComputationGraph cg;
auto& sent = training[order[si]];
chars += sent.size();
++si;
Expression loss_expr = lm.BuildLMGraph(sent, cg, DROPOUT > 0.f);
loss += as_scalar(cg.forward(loss_expr));
cg.backward(loss_expr);
trainer->update();
++lines;
}
report++;
cerr << '#' << report << " [epoch=" << (lines / training.size()) << " lr=" << trainer->learning_rate << "] E = " << (loss / chars) << " ppl=" << exp(loss / chars) << ' ';
// show score on dev data?
if (report % dev_every_i_reports == 0) {
double dloss = 0;
int dchars = 0;
for (auto& sent : dev) {
ComputationGraph cg;
Expression loss_expr = lm.BuildLMGraph(sent, cg, false);
dloss += as_scalar(cg.forward(loss_expr));
dchars += sent.size();
}
if (dloss < best) {
best = dloss;
TextFileSaver saver(fname);
saver.save(model);
}
cerr << "\n***DEV [epoch=" << (lines / training.size()) << "] E = " << (dloss / dchars) << " ppl=" << exp(dloss / dchars) << ' ';
}
}
} // train?
if (params.test_file != "") {
cerr << "Evaluating test data...\n";
double tloss = 0;
int tchars = 0;
for (auto& sent : test) {
ComputationGraph cg;
Expression loss_expr = lm.BuildLMGraph(sent, cg, false);
tloss += as_scalar(cg.forward(loss_expr));
tchars += sent.size();
}
cerr << "TEST -LLH = " << tloss << endl;
cerr << "TEST CROSS ENTOPY (NATS) = " << (tloss / tchars) << endl;
cerr << "TEST PPL = " << exp(tloss / tchars) << endl;
}
// N-best scoring
if (params.nbest_file != "") {
// cdec: index ||| hypothesis ||| feature=val ... ||| ...
// Moses: index ||| hypothesis ||| feature= val(s) ... ||| ...
const int HYP_FIELD = 1;
const int FEAT_FIELD = 2;
const string FEAT_NAME = "RNNLM";
// Input
string nbestf = params.nbest_file;
cerr << "Scoring N-best list " << nbestf << " ..." << endl;
shared_ptr<istream> in;
if (nbestf == "-") {
in.reset(&cin, [](...) {});
} else {
in.reset(new ifstream(nbestf));
}
// Match spacing of input file
string sep = "=";
bool sep_detected = false;
// Input lines
while (getline(*in, line)) {
vector<string> fields;
read_fields(line, fields);
// Check sep if needed
if (!sep_detected) {
sep_detected = true;
int i = fields[FEAT_FIELD].find("=");
if (fields[FEAT_FIELD].substr(i + 1, 1) == " ") {
sep = "= ";
}
}
// Score hypothesis
ComputationGraph cg;
Expression loss_expr = lm.BuildLMGraph(read_sentence(fields[HYP_FIELD], d), cg, false);
double loss = as_scalar(cg.forward(loss_expr));
// Add score
ostringstream os;
os << fields[FEAT_FIELD] << " " << FEAT_NAME << sep << loss;
fields[FEAT_FIELD] = os.str();
// Write augmented line
for (unsigned f = 0; f < fields.size(); ++f) {
if (f > 0)
cout << " ||| ";
cout << fields[f];
}
cout << endl;
}
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/modules/pacing/include/paced_sender.h"
#include <assert.h>
#include "webrtc/modules/interface/module_common_types.h"
#include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
#include "webrtc/system_wrappers/interface/trace_event.h"
namespace {
// Time limit in milliseconds between packet bursts.
const int kMinPacketLimitMs = 5;
// Upper cap on process interval, in case process has not been called in a long
// time.
const int kMaxIntervalTimeMs = 30;
// Max time that the first packet in the queue can sit in the queue if no
// packets are sent, regardless of buffer state. In practice only in effect at
// low bitrates (less than 320 kbits/s).
const int kMaxQueueTimeWithoutSendingMs = 30;
} // namespace
namespace webrtc {
namespace paced_sender {
struct Packet {
Packet(uint32_t ssrc, uint16_t seq_number, int64_t capture_time_ms,
int length_in_bytes, bool retransmission)
: ssrc_(ssrc),
sequence_number_(seq_number),
capture_time_ms_(capture_time_ms),
bytes_(length_in_bytes),
retransmission_(retransmission) {
}
uint32_t ssrc_;
uint16_t sequence_number_;
int64_t capture_time_ms_;
int bytes_;
bool retransmission_;
};
// STL list style class which prevents duplicates in the list.
class PacketList {
public:
PacketList() {};
bool empty() const {
return packet_list_.empty();
}
Packet front() const {
return packet_list_.front();
}
void pop_front() {
Packet& packet = packet_list_.front();
uint16_t sequence_number = packet.sequence_number_;
packet_list_.pop_front();
sequence_number_set_.erase(sequence_number);
}
void push_back(const Packet& packet) {
if (sequence_number_set_.find(packet.sequence_number_) ==
sequence_number_set_.end()) {
// Don't insert duplicates.
packet_list_.push_back(packet);
sequence_number_set_.insert(packet.sequence_number_);
}
}
private:
std::list<Packet> packet_list_;
std::set<uint16_t> sequence_number_set_;
};
class IntervalBudget {
public:
explicit IntervalBudget(int initial_target_rate_kbps)
: target_rate_kbps_(initial_target_rate_kbps),
bytes_remaining_(0) {}
void set_target_rate_kbps(int target_rate_kbps) {
target_rate_kbps_ = target_rate_kbps;
}
void IncreaseBudget(int delta_time_ms) {
int bytes = target_rate_kbps_ * delta_time_ms / 8;
if (bytes_remaining_ < 0) {
// We overused last interval, compensate this interval.
bytes_remaining_ = bytes_remaining_ + bytes;
} else {
// If we underused last interval we can't use it this interval.
bytes_remaining_ = bytes;
}
}
void UseBudget(int bytes) {
bytes_remaining_ = std::max(bytes_remaining_ - bytes,
-500 * target_rate_kbps_ / 8);
}
int bytes_remaining() const { return bytes_remaining_; }
private:
int target_rate_kbps_;
int bytes_remaining_;
};
} // namespace paced_sender
PacedSender::PacedSender(Callback* callback, int target_bitrate_kbps,
float pace_multiplier)
: callback_(callback),
pace_multiplier_(pace_multiplier),
enabled_(false),
paused_(false),
max_queue_length_ms_(kDefaultMaxQueueLengthMs),
critsect_(CriticalSectionWrapper::CreateCriticalSection()),
media_budget_(new paced_sender::IntervalBudget(
pace_multiplier_ * target_bitrate_kbps)),
padding_budget_(new paced_sender::IntervalBudget(0)),
// No padding until UpdateBitrate is called.
pad_up_to_bitrate_budget_(new paced_sender::IntervalBudget(0)),
time_last_update_(TickTime::Now()),
capture_time_ms_last_queued_(0),
capture_time_ms_last_sent_(0),
high_priority_packets_(new paced_sender::PacketList),
normal_priority_packets_(new paced_sender::PacketList),
low_priority_packets_(new paced_sender::PacketList) {
UpdateBytesPerInterval(kMinPacketLimitMs);
}
PacedSender::~PacedSender() {
}
void PacedSender::Pause() {
CriticalSectionScoped cs(critsect_.get());
paused_ = true;
}
void PacedSender::Resume() {
CriticalSectionScoped cs(critsect_.get());
paused_ = false;
}
void PacedSender::SetStatus(bool enable) {
CriticalSectionScoped cs(critsect_.get());
enabled_ = enable;
}
bool PacedSender::Enabled() const {
CriticalSectionScoped cs(critsect_.get());
return enabled_;
}
void PacedSender::UpdateBitrate(int target_bitrate_kbps,
int max_padding_bitrate_kbps,
int pad_up_to_bitrate_kbps) {
CriticalSectionScoped cs(critsect_.get());
media_budget_->set_target_rate_kbps(pace_multiplier_ * target_bitrate_kbps);
padding_budget_->set_target_rate_kbps(max_padding_bitrate_kbps);
pad_up_to_bitrate_budget_->set_target_rate_kbps(pad_up_to_bitrate_kbps);
}
bool PacedSender::SendPacket(Priority priority, uint32_t ssrc,
uint16_t sequence_number, int64_t capture_time_ms, int bytes,
bool retransmission) {
CriticalSectionScoped cs(critsect_.get());
if (!enabled_) {
return true; // We can send now.
}
if (capture_time_ms < 0) {
capture_time_ms = TickTime::MillisecondTimestamp();
}
if (priority != kHighPriority &&
capture_time_ms > capture_time_ms_last_queued_) {
capture_time_ms_last_queued_ = capture_time_ms;
TRACE_EVENT_ASYNC_BEGIN1("webrtc_rtp", "PacedSend", capture_time_ms,
"capture_time_ms", capture_time_ms);
}
paced_sender::PacketList* packet_list = NULL;
switch (priority) {
case kHighPriority:
packet_list = high_priority_packets_.get();
break;
case kNormalPriority:
packet_list = normal_priority_packets_.get();
break;
case kLowPriority:
packet_list = low_priority_packets_.get();
break;
}
packet_list->push_back(paced_sender::Packet(ssrc, sequence_number,
capture_time_ms, bytes,
retransmission));
return false;
}
void PacedSender::set_max_queue_length_ms(int max_queue_length_ms) {
CriticalSectionScoped cs(critsect_.get());
max_queue_length_ms_ = max_queue_length_ms;
}
int PacedSender::QueueInMs() const {
CriticalSectionScoped cs(critsect_.get());
int64_t now_ms = TickTime::MillisecondTimestamp();
int64_t oldest_packet_capture_time = now_ms;
if (!high_priority_packets_->empty()) {
oldest_packet_capture_time = std::min(
oldest_packet_capture_time,
high_priority_packets_->front().capture_time_ms_);
}
if (!normal_priority_packets_->empty()) {
oldest_packet_capture_time = std::min(
oldest_packet_capture_time,
normal_priority_packets_->front().capture_time_ms_);
}
if (!low_priority_packets_->empty()) {
oldest_packet_capture_time = std::min(
oldest_packet_capture_time,
low_priority_packets_->front().capture_time_ms_);
}
return now_ms - oldest_packet_capture_time;
}
int32_t PacedSender::TimeUntilNextProcess() {
CriticalSectionScoped cs(critsect_.get());
int64_t elapsed_time_ms =
(TickTime::Now() - time_last_update_).Milliseconds();
if (elapsed_time_ms <= 0) {
return kMinPacketLimitMs;
}
if (elapsed_time_ms >= kMinPacketLimitMs) {
return 0;
}
return kMinPacketLimitMs - elapsed_time_ms;
}
int32_t PacedSender::Process() {
TickTime now = TickTime::Now();
CriticalSectionScoped cs(critsect_.get());
int elapsed_time_ms = (now - time_last_update_).Milliseconds();
time_last_update_ = now;
if (!enabled_) {
return 0;
}
if (!paused_) {
if (elapsed_time_ms > 0) {
uint32_t delta_time_ms = std::min(kMaxIntervalTimeMs, elapsed_time_ms);
UpdateBytesPerInterval(delta_time_ms);
}
paced_sender::PacketList* packet_list;
while (ShouldSendNextPacket(&packet_list)) {
if (!SendPacketFromList(packet_list))
return 0;
}
if (high_priority_packets_->empty() &&
normal_priority_packets_->empty() &&
low_priority_packets_->empty() &&
padding_budget_->bytes_remaining() > 0 &&
pad_up_to_bitrate_budget_->bytes_remaining() > 0) {
int padding_needed = std::min(
padding_budget_->bytes_remaining(),
pad_up_to_bitrate_budget_->bytes_remaining());
critsect_->Leave();
int bytes_sent = callback_->TimeToSendPadding(padding_needed);
critsect_->Enter();
media_budget_->UseBudget(bytes_sent);
padding_budget_->UseBudget(bytes_sent);
pad_up_to_bitrate_budget_->UseBudget(bytes_sent);
}
}
return 0;
}
// MUST have critsect_ when calling.
bool PacedSender::SendPacketFromList(paced_sender::PacketList* packet_list) {
uint32_t ssrc;
uint16_t sequence_number;
int64_t capture_time_ms;
bool retransmission;
GetNextPacketFromList(packet_list, &ssrc, &sequence_number,
&capture_time_ms, &retransmission);
critsect_->Leave();
const bool success = callback_->TimeToSendPacket(ssrc, sequence_number,
capture_time_ms,
retransmission);
critsect_->Enter();
// If packet cannot be sent then keep it in packet list and exit early.
// There's no need to send more packets.
if (!success) {
return false;
}
packet_list->pop_front();
const bool last_packet = packet_list->empty() ||
packet_list->front().capture_time_ms_ > capture_time_ms;
if (packet_list != high_priority_packets_.get()) {
if (capture_time_ms > capture_time_ms_last_sent_) {
capture_time_ms_last_sent_ = capture_time_ms;
} else if (capture_time_ms == capture_time_ms_last_sent_ &&
last_packet) {
TRACE_EVENT_ASYNC_END0("webrtc_rtp", "PacedSend", capture_time_ms);
}
}
return true;
}
// MUST have critsect_ when calling.
void PacedSender::UpdateBytesPerInterval(uint32_t delta_time_ms) {
media_budget_->IncreaseBudget(delta_time_ms);
padding_budget_->IncreaseBudget(delta_time_ms);
pad_up_to_bitrate_budget_->IncreaseBudget(delta_time_ms);
}
// MUST have critsect_ when calling.
bool PacedSender::ShouldSendNextPacket(paced_sender::PacketList** packet_list) {
if (media_budget_->bytes_remaining() <= 0) {
// All bytes consumed for this interval.
// Check if we have not sent in a too long time.
if ((TickTime::Now() - time_last_send_).Milliseconds() >
kMaxQueueTimeWithoutSendingMs) {
if (!high_priority_packets_->empty()) {
*packet_list = high_priority_packets_.get();
return true;
}
if (!normal_priority_packets_->empty()) {
*packet_list = normal_priority_packets_.get();
return true;
}
}
// Send any old packets to avoid queuing for too long.
if (max_queue_length_ms_ >= 0 && QueueInMs() > max_queue_length_ms_) {
int64_t high_priority_capture_time = -1;
if (!high_priority_packets_->empty()) {
high_priority_capture_time =
high_priority_packets_->front().capture_time_ms_;
*packet_list = high_priority_packets_.get();
}
if (!normal_priority_packets_->empty() && high_priority_capture_time >
normal_priority_packets_->front().capture_time_ms_) {
*packet_list = normal_priority_packets_.get();
}
if (*packet_list)
return true;
}
return false;
}
if (!high_priority_packets_->empty()) {
*packet_list = high_priority_packets_.get();
return true;
}
if (!normal_priority_packets_->empty()) {
*packet_list = normal_priority_packets_.get();
return true;
}
if (!low_priority_packets_->empty()) {
*packet_list = low_priority_packets_.get();
return true;
}
return false;
}
void PacedSender::GetNextPacketFromList(paced_sender::PacketList* packets,
uint32_t* ssrc, uint16_t* sequence_number, int64_t* capture_time_ms,
bool* retransmission) {
paced_sender::Packet packet = packets->front();
UpdateMediaBytesSent(packet.bytes_);
*sequence_number = packet.sequence_number_;
*ssrc = packet.ssrc_;
*capture_time_ms = packet.capture_time_ms_;
*retransmission = packet.retransmission_;
}
// MUST have critsect_ when calling.
void PacedSender::UpdateMediaBytesSent(int num_bytes) {
time_last_send_ = TickTime::Now();
media_budget_->UseBudget(num_bytes);
pad_up_to_bitrate_budget_->UseBudget(num_bytes);
}
} // namespace webrtc
<commit_msg>Fixes a crash in the pacer where it fails to find a normal prio packet if there are no high prio packets, given that the queue has grown too large.<commit_after>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/modules/pacing/include/paced_sender.h"
#include <assert.h>
#include "webrtc/modules/interface/module_common_types.h"
#include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
#include "webrtc/system_wrappers/interface/trace_event.h"
namespace {
// Time limit in milliseconds between packet bursts.
const int kMinPacketLimitMs = 5;
// Upper cap on process interval, in case process has not been called in a long
// time.
const int kMaxIntervalTimeMs = 30;
// Max time that the first packet in the queue can sit in the queue if no
// packets are sent, regardless of buffer state. In practice only in effect at
// low bitrates (less than 320 kbits/s).
const int kMaxQueueTimeWithoutSendingMs = 30;
} // namespace
namespace webrtc {
namespace paced_sender {
struct Packet {
Packet(uint32_t ssrc, uint16_t seq_number, int64_t capture_time_ms,
int length_in_bytes, bool retransmission)
: ssrc_(ssrc),
sequence_number_(seq_number),
capture_time_ms_(capture_time_ms),
bytes_(length_in_bytes),
retransmission_(retransmission) {
}
uint32_t ssrc_;
uint16_t sequence_number_;
int64_t capture_time_ms_;
int bytes_;
bool retransmission_;
};
// STL list style class which prevents duplicates in the list.
class PacketList {
public:
PacketList() {};
bool empty() const {
return packet_list_.empty();
}
Packet front() const {
return packet_list_.front();
}
void pop_front() {
Packet& packet = packet_list_.front();
uint16_t sequence_number = packet.sequence_number_;
packet_list_.pop_front();
sequence_number_set_.erase(sequence_number);
}
void push_back(const Packet& packet) {
if (sequence_number_set_.find(packet.sequence_number_) ==
sequence_number_set_.end()) {
// Don't insert duplicates.
packet_list_.push_back(packet);
sequence_number_set_.insert(packet.sequence_number_);
}
}
private:
std::list<Packet> packet_list_;
std::set<uint16_t> sequence_number_set_;
};
class IntervalBudget {
public:
explicit IntervalBudget(int initial_target_rate_kbps)
: target_rate_kbps_(initial_target_rate_kbps),
bytes_remaining_(0) {}
void set_target_rate_kbps(int target_rate_kbps) {
target_rate_kbps_ = target_rate_kbps;
}
void IncreaseBudget(int delta_time_ms) {
int bytes = target_rate_kbps_ * delta_time_ms / 8;
if (bytes_remaining_ < 0) {
// We overused last interval, compensate this interval.
bytes_remaining_ = bytes_remaining_ + bytes;
} else {
// If we underused last interval we can't use it this interval.
bytes_remaining_ = bytes;
}
}
void UseBudget(int bytes) {
bytes_remaining_ = std::max(bytes_remaining_ - bytes,
-500 * target_rate_kbps_ / 8);
}
int bytes_remaining() const { return bytes_remaining_; }
private:
int target_rate_kbps_;
int bytes_remaining_;
};
} // namespace paced_sender
PacedSender::PacedSender(Callback* callback, int target_bitrate_kbps,
float pace_multiplier)
: callback_(callback),
pace_multiplier_(pace_multiplier),
enabled_(false),
paused_(false),
max_queue_length_ms_(kDefaultMaxQueueLengthMs),
critsect_(CriticalSectionWrapper::CreateCriticalSection()),
media_budget_(new paced_sender::IntervalBudget(
pace_multiplier_ * target_bitrate_kbps)),
padding_budget_(new paced_sender::IntervalBudget(0)),
// No padding until UpdateBitrate is called.
pad_up_to_bitrate_budget_(new paced_sender::IntervalBudget(0)),
time_last_update_(TickTime::Now()),
capture_time_ms_last_queued_(0),
capture_time_ms_last_sent_(0),
high_priority_packets_(new paced_sender::PacketList),
normal_priority_packets_(new paced_sender::PacketList),
low_priority_packets_(new paced_sender::PacketList) {
UpdateBytesPerInterval(kMinPacketLimitMs);
}
PacedSender::~PacedSender() {
}
void PacedSender::Pause() {
CriticalSectionScoped cs(critsect_.get());
paused_ = true;
}
void PacedSender::Resume() {
CriticalSectionScoped cs(critsect_.get());
paused_ = false;
}
void PacedSender::SetStatus(bool enable) {
CriticalSectionScoped cs(critsect_.get());
enabled_ = enable;
}
bool PacedSender::Enabled() const {
CriticalSectionScoped cs(critsect_.get());
return enabled_;
}
void PacedSender::UpdateBitrate(int target_bitrate_kbps,
int max_padding_bitrate_kbps,
int pad_up_to_bitrate_kbps) {
CriticalSectionScoped cs(critsect_.get());
media_budget_->set_target_rate_kbps(pace_multiplier_ * target_bitrate_kbps);
padding_budget_->set_target_rate_kbps(max_padding_bitrate_kbps);
pad_up_to_bitrate_budget_->set_target_rate_kbps(pad_up_to_bitrate_kbps);
}
bool PacedSender::SendPacket(Priority priority, uint32_t ssrc,
uint16_t sequence_number, int64_t capture_time_ms, int bytes,
bool retransmission) {
CriticalSectionScoped cs(critsect_.get());
if (!enabled_) {
return true; // We can send now.
}
if (capture_time_ms < 0) {
capture_time_ms = TickTime::MillisecondTimestamp();
}
if (priority != kHighPriority &&
capture_time_ms > capture_time_ms_last_queued_) {
capture_time_ms_last_queued_ = capture_time_ms;
TRACE_EVENT_ASYNC_BEGIN1("webrtc_rtp", "PacedSend", capture_time_ms,
"capture_time_ms", capture_time_ms);
}
paced_sender::PacketList* packet_list = NULL;
switch (priority) {
case kHighPriority:
packet_list = high_priority_packets_.get();
break;
case kNormalPriority:
packet_list = normal_priority_packets_.get();
break;
case kLowPriority:
packet_list = low_priority_packets_.get();
break;
}
packet_list->push_back(paced_sender::Packet(ssrc, sequence_number,
capture_time_ms, bytes,
retransmission));
return false;
}
void PacedSender::set_max_queue_length_ms(int max_queue_length_ms) {
CriticalSectionScoped cs(critsect_.get());
max_queue_length_ms_ = max_queue_length_ms;
}
int PacedSender::QueueInMs() const {
CriticalSectionScoped cs(critsect_.get());
int64_t now_ms = TickTime::MillisecondTimestamp();
int64_t oldest_packet_capture_time = now_ms;
if (!high_priority_packets_->empty()) {
oldest_packet_capture_time = std::min(
oldest_packet_capture_time,
high_priority_packets_->front().capture_time_ms_);
}
if (!normal_priority_packets_->empty()) {
oldest_packet_capture_time = std::min(
oldest_packet_capture_time,
normal_priority_packets_->front().capture_time_ms_);
}
if (!low_priority_packets_->empty()) {
oldest_packet_capture_time = std::min(
oldest_packet_capture_time,
low_priority_packets_->front().capture_time_ms_);
}
return now_ms - oldest_packet_capture_time;
}
int32_t PacedSender::TimeUntilNextProcess() {
CriticalSectionScoped cs(critsect_.get());
int64_t elapsed_time_ms =
(TickTime::Now() - time_last_update_).Milliseconds();
if (elapsed_time_ms <= 0) {
return kMinPacketLimitMs;
}
if (elapsed_time_ms >= kMinPacketLimitMs) {
return 0;
}
return kMinPacketLimitMs - elapsed_time_ms;
}
int32_t PacedSender::Process() {
TickTime now = TickTime::Now();
CriticalSectionScoped cs(critsect_.get());
int elapsed_time_ms = (now - time_last_update_).Milliseconds();
time_last_update_ = now;
if (!enabled_) {
return 0;
}
if (!paused_) {
if (elapsed_time_ms > 0) {
uint32_t delta_time_ms = std::min(kMaxIntervalTimeMs, elapsed_time_ms);
UpdateBytesPerInterval(delta_time_ms);
}
paced_sender::PacketList* packet_list;
while (ShouldSendNextPacket(&packet_list)) {
if (!SendPacketFromList(packet_list))
return 0;
}
if (high_priority_packets_->empty() &&
normal_priority_packets_->empty() &&
low_priority_packets_->empty() &&
padding_budget_->bytes_remaining() > 0 &&
pad_up_to_bitrate_budget_->bytes_remaining() > 0) {
int padding_needed = std::min(
padding_budget_->bytes_remaining(),
pad_up_to_bitrate_budget_->bytes_remaining());
critsect_->Leave();
int bytes_sent = callback_->TimeToSendPadding(padding_needed);
critsect_->Enter();
media_budget_->UseBudget(bytes_sent);
padding_budget_->UseBudget(bytes_sent);
pad_up_to_bitrate_budget_->UseBudget(bytes_sent);
}
}
return 0;
}
// MUST have critsect_ when calling.
bool PacedSender::SendPacketFromList(paced_sender::PacketList* packet_list) {
uint32_t ssrc;
uint16_t sequence_number;
int64_t capture_time_ms;
bool retransmission;
GetNextPacketFromList(packet_list, &ssrc, &sequence_number,
&capture_time_ms, &retransmission);
critsect_->Leave();
const bool success = callback_->TimeToSendPacket(ssrc, sequence_number,
capture_time_ms,
retransmission);
critsect_->Enter();
// If packet cannot be sent then keep it in packet list and exit early.
// There's no need to send more packets.
if (!success) {
return false;
}
packet_list->pop_front();
const bool last_packet = packet_list->empty() ||
packet_list->front().capture_time_ms_ > capture_time_ms;
if (packet_list != high_priority_packets_.get()) {
if (capture_time_ms > capture_time_ms_last_sent_) {
capture_time_ms_last_sent_ = capture_time_ms;
} else if (capture_time_ms == capture_time_ms_last_sent_ &&
last_packet) {
TRACE_EVENT_ASYNC_END0("webrtc_rtp", "PacedSend", capture_time_ms);
}
}
return true;
}
// MUST have critsect_ when calling.
void PacedSender::UpdateBytesPerInterval(uint32_t delta_time_ms) {
media_budget_->IncreaseBudget(delta_time_ms);
padding_budget_->IncreaseBudget(delta_time_ms);
pad_up_to_bitrate_budget_->IncreaseBudget(delta_time_ms);
}
// MUST have critsect_ when calling.
bool PacedSender::ShouldSendNextPacket(paced_sender::PacketList** packet_list) {
*packet_list = NULL;
if (media_budget_->bytes_remaining() <= 0) {
// All bytes consumed for this interval.
// Check if we have not sent in a too long time.
if ((TickTime::Now() - time_last_send_).Milliseconds() >
kMaxQueueTimeWithoutSendingMs) {
if (!high_priority_packets_->empty()) {
*packet_list = high_priority_packets_.get();
return true;
}
if (!normal_priority_packets_->empty()) {
*packet_list = normal_priority_packets_.get();
return true;
}
}
// Send any old packets to avoid queuing for too long.
if (max_queue_length_ms_ >= 0 && QueueInMs() > max_queue_length_ms_) {
int64_t high_priority_capture_time = -1;
if (!high_priority_packets_->empty()) {
high_priority_capture_time =
high_priority_packets_->front().capture_time_ms_;
*packet_list = high_priority_packets_.get();
}
if (!normal_priority_packets_->empty() &&
(high_priority_capture_time == -1 || high_priority_capture_time >
normal_priority_packets_->front().capture_time_ms_)) {
*packet_list = normal_priority_packets_.get();
}
if (*packet_list)
return true;
}
return false;
}
if (!high_priority_packets_->empty()) {
*packet_list = high_priority_packets_.get();
return true;
}
if (!normal_priority_packets_->empty()) {
*packet_list = normal_priority_packets_.get();
return true;
}
if (!low_priority_packets_->empty()) {
*packet_list = low_priority_packets_.get();
return true;
}
return false;
}
void PacedSender::GetNextPacketFromList(paced_sender::PacketList* packets,
uint32_t* ssrc, uint16_t* sequence_number, int64_t* capture_time_ms,
bool* retransmission) {
paced_sender::Packet packet = packets->front();
UpdateMediaBytesSent(packet.bytes_);
*sequence_number = packet.sequence_number_;
*ssrc = packet.ssrc_;
*capture_time_ms = packet.capture_time_ms_;
*retransmission = packet.retransmission_;
}
// MUST have critsect_ when calling.
void PacedSender::UpdateMediaBytesSent(int num_bytes) {
time_last_send_ = TickTime::Now();
media_budget_->UseBudget(num_bytes);
pad_up_to_bitrate_budget_->UseBudget(num_bytes);
}
} // namespace webrtc
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* interface header */
#include "JoinMenu.h"
/* system headers */
#include <string>
#include <vector>
/* common implementation headers */
#include "FontManager.h"
/* local implementation headers */
#include "StartupInfo.h"
#include "MainMenu.h"
#include "HUDDialogStack.h"
#include "MenuDefaultKey.h"
#include "ServerStartMenu.h"
#include "ServerMenu.h"
#include "Protocol.h"
#include "HUDuiControl.h"
#include "HUDuiLabel.h"
#include "HUDuiTypeIn.h"
#include "HUDuiList.h"
#include "TimeKeeper.h"
/* from playing.h */
StartupInfo* getStartupInfo();
typedef void (*JoinGameCallback)(bool success, void* data);
void joinGame(JoinGameCallback, void* userData);
typedef void (*ConnectStatusCallback)(std::string& str);
void setConnectStatusCB(ConnectStatusCallback);
void drawFrame(const float dt);
JoinMenu* JoinMenu::activeMenu = NULL;
JoinMenu::JoinMenu() : oldErrorCallback(NULL),
serverStartMenu(NULL), serverMenu(NULL)
{
// cache font face ID
int fontFace = MainMenu::getFontFace();
// add controls
std::vector<HUDuiControl*>& list = getControls();
StartupInfo* info = getStartupInfo();
HUDuiLabel* label = new HUDuiLabel;
label->setFontFace(fontFace);
label->setString("Join Game");
list.push_back(label);
findServer = new HUDuiLabel;
findServer->setFontFace(fontFace);
findServer->setString("Find Server");
list.push_back(findServer);
connectLabel = new HUDuiLabel;
connectLabel->setFontFace(fontFace);
connectLabel->setString("Connect");
list.push_back(connectLabel);
callsign = new HUDuiTypeIn;
callsign->setFontFace(fontFace);
callsign->setLabel("Callsign:");
callsign->setMaxLength(CallSignLen - 1);
callsign->setString(info->callsign);
list.push_back(callsign);
team = new HUDuiList;
team->setFontFace(fontFace);
team->setLabel("Team:");
team->setCallback(teamCallback, NULL);
std::vector<std::string>& teams = team->getList();
// these do not need to be in enum order, but must match getTeam() & setTeam()
teams.push_back(std::string(Team::getName(AutomaticTeam)));
teams.push_back(std::string(Team::getName(RogueTeam)));
teams.push_back(std::string(Team::getName(RedTeam)));
teams.push_back(std::string(Team::getName(GreenTeam)));
teams.push_back(std::string(Team::getName(BlueTeam)));
teams.push_back(std::string(Team::getName(PurpleTeam)));
teams.push_back(std::string(Team::getName(ObserverTeam)));
team->update();
setTeam(info->team);
list.push_back(team);
server = new HUDuiTypeIn;
server->setFontFace(fontFace);
server->setLabel("Server:");
server->setMaxLength(64);
server->setString(info->serverName);
list.push_back(server);
char buffer[10];
sprintf(buffer, "%d", info->serverPort);
port = new HUDuiTypeIn;
port->setFontFace(fontFace);
port->setLabel("Port:");
port->setMaxLength(5);
port->setString(buffer);
list.push_back(port);
email = new HUDuiTypeIn;
email->setFontFace(fontFace);
email->setLabel("Email:");
email->setMaxLength(EmailLen - 1);
email->setString(info->email);
list.push_back(email);
startServer = new HUDuiLabel;
startServer->setFontFace(fontFace);
startServer->setString("Start Server");
list.push_back(startServer);
status = new HUDuiLabel;
status->setFontFace(fontFace);
status->setString("");
list.push_back(status);
failedMessage = new HUDuiLabel;
failedMessage->setFontFace(fontFace);
failedMessage->setString("");
list.push_back(failedMessage);
initNavigation(list, 1, list.size() - 3);
}
JoinMenu::~JoinMenu()
{
delete serverStartMenu;
delete serverMenu;
}
HUDuiDefaultKey* JoinMenu::getDefaultKey()
{
return MenuDefaultKey::getInstance();
}
void JoinMenu::show()
{
activeMenu = this;
StartupInfo* info = getStartupInfo();
// set fields
callsign->setString(info->callsign);
setTeam(info->team);
server->setString(info->serverName);
char buffer[10];
sprintf(buffer, "%d", info->serverPort);
port->setString(buffer);
// clear status
oldErrorCallback = NULL;
setStatus("");
}
void JoinMenu::dismiss()
{
loadInfo();
setConnectStatusCB(NULL);
activeMenu = NULL;
}
void JoinMenu::loadInfo()
{
// load startup info with current settings
StartupInfo* info = getStartupInfo();
strcpy(info->callsign, callsign->getString().c_str());
info->team = getTeam();
strcpy(info->serverName, server->getString().c_str());
info->serverPort = atoi(port->getString().c_str());
strcpy(info->email, email->getString().c_str());
}
void JoinMenu::execute()
{
HUDuiControl* focus = HUDui::getFocus();
if (focus == startServer) {
if (!serverStartMenu) serverStartMenu = new ServerStartMenu;
HUDDialogStack::get()->push(serverStartMenu);
} else if (focus == findServer) {
if (!serverMenu) serverMenu = new ServerMenu;
HUDDialogStack::get()->push(serverMenu);
} else if (focus == connectLabel) {
// load startup info
loadInfo();
// make sure we've got what we need
StartupInfo* info = getStartupInfo();
if (info->callsign[0] == '\0') {
setStatus("You must enter a callsign.");
return;
}
if (info->serverName[0] == '\0') {
setStatus("You must enter a server.");
return;
}
if (info->serverPort <= 0 || info->serverPort > 65535) {
char buffer[60];
sprintf(buffer, "Port is invalid. Try %d.", ServerPort);
setStatus(buffer);
return;
}
// let user know we're trying
setStatus("Trying...");
// schedule attempt to join game
oldErrorCallback = setErrorCallback(joinErrorCallback);
setConnectStatusCB(&connectStatusCallback);
joinGame(&joinGameCallback, this);
}
}
void JoinMenu::joinGameCallback(bool okay, void* _self)
{
JoinMenu* self = (JoinMenu*)_self;
if (okay) {
// it worked! pop all the menus.
HUDDialogStack* stack = HUDDialogStack::get();
while (stack->isActive()) stack->pop();
} else {
// failed. let user know.
self->setStatus("Connection failed.");
}
setErrorCallback(self->oldErrorCallback);
self->oldErrorCallback = NULL;
}
void JoinMenu::connectStatusCallback(std::string& str)
{
static TimeKeeper prev = TimeKeeper::getNullTime();
JoinMenu* self = activeMenu;
self->setFailedMessage(str.c_str());
// limit framerate to 2 fps - if you can't draw 2 fps you're screwed anyhow
// if we draw too many fps then people with fast connections and slow computers
// will have a problem on their hands, since we aren't multithreading
const float dt = TimeKeeper::getCurrent() - prev;
if (dt >= 0.5f) {
// render that puppy
drawFrame(dt);
prev = TimeKeeper::getCurrent();
}
}
void JoinMenu::joinErrorCallback(const char* msg)
{
JoinMenu* self = activeMenu;
self->setFailedMessage(msg);
// also forward to old callback
if (self->oldErrorCallback) (*self->oldErrorCallback)(msg);
}
void JoinMenu::setFailedMessage(const char* msg)
{
failedMessage->setString(msg);
FontManager &fm = FontManager::instance();
const float width = fm.getStrLength(MainMenu::getFontFace(),
failedMessage->getFontSize(), failedMessage->getString());
failedMessage->setPosition(center - 0.5f * width, failedMessage->getY());
}
TeamColor JoinMenu::getTeam() const
{
return team->getIndex() == 0 ? AutomaticTeam : TeamColor(team->getIndex() - 1);
}
void JoinMenu::setTeam(TeamColor teamcol)
{
team->setIndex(teamcol == AutomaticTeam ? 0 : int(teamcol) + 1);
}
void JoinMenu::setStatus(const char* msg, const std::vector<std::string> *)
{
status->setString(msg);
FontManager &fm = FontManager::instance();
const float width = fm.getStrLength(status->getFontFace(),
status->getFontSize(), status->getString());
status->setPosition(center - 0.5f * width, status->getY());
if (!oldErrorCallback) joinErrorCallback("");
}
void JoinMenu::teamCallback(HUDuiControl*, void*)
{
// do nothing (for now)
}
void JoinMenu::resize(int width, int height)
{
HUDDialog::resize(width, height);
// use a big font for title, smaller font for the rest
const float titleFontSize = (float)height / 15.0f;
const float fontSize = (float)height / 36.0f;
center = 0.5f * (float)width;
FontManager &fm = FontManager::instance();
// reposition title
std::vector<HUDuiControl*>& list = getControls();
HUDuiLabel* title = (HUDuiLabel*)list[0];
title->setFontSize(titleFontSize);
const float titleWidth = fm.getStrLength(MainMenu::getFontFace(), titleFontSize, title->getString());
const float titleHeight = fm.getStrHeight(MainMenu::getFontFace(), titleFontSize, "");
float x = 0.5f * ((float)width - titleWidth);
float y = (float)height - titleHeight;
title->setPosition(x, y);
// reposition options
x = 0.5f * ((float)width - 0.5f * titleWidth);
y -= 0.6f * titleHeight;
list[1]->setFontSize(fontSize);
const float h = fm.getStrHeight(MainMenu::getFontFace(), fontSize, "");
const int count = list.size();
for (int i = 1; i < count; i++) {
list[i]->setFontSize(fontSize);
list[i]->setPosition(x, y);
y -= 1.0f * h;
if (i <= 2 || i == 7) y -= 0.5f * h;
}
}
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>prevent an infinite loop (that happened on a frequent reconnect) on the callback<commit_after>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* interface header */
#include "JoinMenu.h"
/* system headers */
#include <string>
#include <vector>
/* common implementation headers */
#include "FontManager.h"
/* local implementation headers */
#include "StartupInfo.h"
#include "MainMenu.h"
#include "HUDDialogStack.h"
#include "MenuDefaultKey.h"
#include "ServerStartMenu.h"
#include "ServerMenu.h"
#include "Protocol.h"
#include "HUDuiControl.h"
#include "HUDuiLabel.h"
#include "HUDuiTypeIn.h"
#include "HUDuiList.h"
#include "TimeKeeper.h"
/* from playing.h */
StartupInfo* getStartupInfo();
typedef void (*JoinGameCallback)(bool success, void* data);
void joinGame(JoinGameCallback, void* userData);
typedef void (*ConnectStatusCallback)(std::string& str);
void setConnectStatusCB(ConnectStatusCallback);
void drawFrame(const float dt);
JoinMenu* JoinMenu::activeMenu = NULL;
JoinMenu::JoinMenu() : oldErrorCallback(NULL),
serverStartMenu(NULL), serverMenu(NULL)
{
// cache font face ID
int fontFace = MainMenu::getFontFace();
// add controls
std::vector<HUDuiControl*>& list = getControls();
StartupInfo* info = getStartupInfo();
HUDuiLabel* label = new HUDuiLabel;
label->setFontFace(fontFace);
label->setString("Join Game");
list.push_back(label);
findServer = new HUDuiLabel;
findServer->setFontFace(fontFace);
findServer->setString("Find Server");
list.push_back(findServer);
connectLabel = new HUDuiLabel;
connectLabel->setFontFace(fontFace);
connectLabel->setString("Connect");
list.push_back(connectLabel);
callsign = new HUDuiTypeIn;
callsign->setFontFace(fontFace);
callsign->setLabel("Callsign:");
callsign->setMaxLength(CallSignLen - 1);
callsign->setString(info->callsign);
list.push_back(callsign);
team = new HUDuiList;
team->setFontFace(fontFace);
team->setLabel("Team:");
team->setCallback(teamCallback, NULL);
std::vector<std::string>& teams = team->getList();
// these do not need to be in enum order, but must match getTeam() & setTeam()
teams.push_back(std::string(Team::getName(AutomaticTeam)));
teams.push_back(std::string(Team::getName(RogueTeam)));
teams.push_back(std::string(Team::getName(RedTeam)));
teams.push_back(std::string(Team::getName(GreenTeam)));
teams.push_back(std::string(Team::getName(BlueTeam)));
teams.push_back(std::string(Team::getName(PurpleTeam)));
teams.push_back(std::string(Team::getName(ObserverTeam)));
team->update();
setTeam(info->team);
list.push_back(team);
server = new HUDuiTypeIn;
server->setFontFace(fontFace);
server->setLabel("Server:");
server->setMaxLength(64);
server->setString(info->serverName);
list.push_back(server);
char buffer[10];
sprintf(buffer, "%d", info->serverPort);
port = new HUDuiTypeIn;
port->setFontFace(fontFace);
port->setLabel("Port:");
port->setMaxLength(5);
port->setString(buffer);
list.push_back(port);
email = new HUDuiTypeIn;
email->setFontFace(fontFace);
email->setLabel("Email:");
email->setMaxLength(EmailLen - 1);
email->setString(info->email);
list.push_back(email);
startServer = new HUDuiLabel;
startServer->setFontFace(fontFace);
startServer->setString("Start Server");
list.push_back(startServer);
status = new HUDuiLabel;
status->setFontFace(fontFace);
status->setString("");
list.push_back(status);
failedMessage = new HUDuiLabel;
failedMessage->setFontFace(fontFace);
failedMessage->setString("");
list.push_back(failedMessage);
initNavigation(list, 1, list.size() - 3);
}
JoinMenu::~JoinMenu()
{
delete serverStartMenu;
delete serverMenu;
}
HUDuiDefaultKey* JoinMenu::getDefaultKey()
{
return MenuDefaultKey::getInstance();
}
void JoinMenu::show()
{
activeMenu = this;
StartupInfo* info = getStartupInfo();
// set fields
callsign->setString(info->callsign);
setTeam(info->team);
server->setString(info->serverName);
char buffer[10];
sprintf(buffer, "%d", info->serverPort);
port->setString(buffer);
// clear status
oldErrorCallback = NULL;
setStatus("");
}
void JoinMenu::dismiss()
{
loadInfo();
setConnectStatusCB(NULL);
activeMenu = NULL;
}
void JoinMenu::loadInfo()
{
// load startup info with current settings
StartupInfo* info = getStartupInfo();
strcpy(info->callsign, callsign->getString().c_str());
info->team = getTeam();
strcpy(info->serverName, server->getString().c_str());
info->serverPort = atoi(port->getString().c_str());
strcpy(info->email, email->getString().c_str());
}
void JoinMenu::execute()
{
HUDuiControl* focus = HUDui::getFocus();
if (focus == startServer) {
if (!serverStartMenu) serverStartMenu = new ServerStartMenu;
HUDDialogStack::get()->push(serverStartMenu);
} else if (focus == findServer) {
if (!serverMenu) serverMenu = new ServerMenu;
HUDDialogStack::get()->push(serverMenu);
} else if (focus == connectLabel) {
// load startup info
loadInfo();
// make sure we've got what we need
StartupInfo* info = getStartupInfo();
if (info->callsign[0] == '\0') {
setStatus("You must enter a callsign.");
return;
}
if (info->serverName[0] == '\0') {
setStatus("You must enter a server.");
return;
}
if (info->serverPort <= 0 || info->serverPort > 65535) {
char buffer[60];
sprintf(buffer, "Port is invalid. Try %d.", ServerPort);
setStatus(buffer);
return;
}
// let user know we're trying
setStatus("Trying...");
// schedule attempt to join game
oldErrorCallback = setErrorCallback(joinErrorCallback);
setConnectStatusCB(&connectStatusCallback);
joinGame(&joinGameCallback, this);
}
}
void JoinMenu::joinGameCallback(bool okay, void* _self)
{
JoinMenu* self = (JoinMenu*)_self;
if (okay) {
// it worked! pop all the menus.
HUDDialogStack* stack = HUDDialogStack::get();
while (stack->isActive()) stack->pop();
} else {
// failed. let user know.
self->setStatus("Connection failed.");
}
setErrorCallback(self->oldErrorCallback);
self->oldErrorCallback = NULL;
}
void JoinMenu::connectStatusCallback(std::string& str)
{
static TimeKeeper prev = TimeKeeper::getNullTime();
JoinMenu* self = activeMenu;
self->setFailedMessage(str.c_str());
// limit framerate to 2 fps - if you can't draw 2 fps you're screwed anyhow
// if we draw too many fps then people with fast connections and slow computers
// will have a problem on their hands, since we aren't multithreading
const float dt = TimeKeeper::getCurrent() - prev;
if (dt >= 0.5f) {
// render that puppy
drawFrame(dt);
prev = TimeKeeper::getCurrent();
}
}
void JoinMenu::joinErrorCallback(const char* msg)
{
JoinMenu* self = activeMenu;
self->setFailedMessage(msg);
// also forward to old callback if it's not this callback
if (self->oldErrorCallback && self->oldErrorCallback != self->joinErrorCallback) {
(*self->oldErrorCallback)(msg);
}
}
void JoinMenu::setFailedMessage(const char* msg)
{
failedMessage->setString(msg);
FontManager &fm = FontManager::instance();
const float width = fm.getStrLength(MainMenu::getFontFace(),
failedMessage->getFontSize(), failedMessage->getString());
failedMessage->setPosition(center - 0.5f * width, failedMessage->getY());
}
TeamColor JoinMenu::getTeam() const
{
return team->getIndex() == 0 ? AutomaticTeam : TeamColor(team->getIndex() - 1);
}
void JoinMenu::setTeam(TeamColor teamcol)
{
team->setIndex(teamcol == AutomaticTeam ? 0 : int(teamcol) + 1);
}
void JoinMenu::setStatus(const char* msg, const std::vector<std::string> *)
{
status->setString(msg);
FontManager &fm = FontManager::instance();
const float width = fm.getStrLength(status->getFontFace(),
status->getFontSize(), status->getString());
status->setPosition(center - 0.5f * width, status->getY());
if (!oldErrorCallback) joinErrorCallback("");
}
void JoinMenu::teamCallback(HUDuiControl*, void*)
{
// do nothing (for now)
}
void JoinMenu::resize(int width, int height)
{
HUDDialog::resize(width, height);
// use a big font for title, smaller font for the rest
const float titleFontSize = (float)height / 15.0f;
const float fontSize = (float)height / 36.0f;
center = 0.5f * (float)width;
FontManager &fm = FontManager::instance();
// reposition title
std::vector<HUDuiControl*>& list = getControls();
HUDuiLabel* title = (HUDuiLabel*)list[0];
title->setFontSize(titleFontSize);
const float titleWidth = fm.getStrLength(MainMenu::getFontFace(), titleFontSize, title->getString());
const float titleHeight = fm.getStrHeight(MainMenu::getFontFace(), titleFontSize, "");
float x = 0.5f * ((float)width - titleWidth);
float y = (float)height - titleHeight;
title->setPosition(x, y);
// reposition options
x = 0.5f * ((float)width - 0.5f * titleWidth);
y -= 0.6f * titleHeight;
list[1]->setFontSize(fontSize);
const float h = fm.getStrHeight(MainMenu::getFontFace(), fontSize, "");
const int count = list.size();
for (int i = 1; i < count; i++) {
list[i]->setFontSize(fontSize);
list[i]->setPosition(x, y);
y -= 1.0f * h;
if (i <= 2 || i == 7) y -= 0.5f * h;
}
}
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* interface header */
#include "JoinMenu.h"
/* system headers */
#include <string>
#include <vector>
/* common implementation headers */
#include "FontManager.h"
/* local implementation headers */
#include "StartupInfo.h"
#include "MainMenu.h"
#include "HUDDialogStack.h"
#include "MenuDefaultKey.h"
#include "ServerStartMenu.h"
#include "ServerMenu.h"
#include "Protocol.h"
#include "HUDuiControl.h"
#include "HUDuiLabel.h"
#include "HUDuiTypeIn.h"
#include "HUDuiList.h"
#include "TimeKeeper.h"
/* from playing.h */
StartupInfo* getStartupInfo();
void joinGame();
JoinMenu* JoinMenu::activeMenu = NULL;
JoinMenu::JoinMenu() : serverStartMenu(NULL), serverMenu(NULL)
{
// cache font face ID
int fontFace = MainMenu::getFontFace();
// add controls
std::vector<HUDuiControl*>& list = getControls();
StartupInfo* info = getStartupInfo();
HUDuiLabel* label = new HUDuiLabel;
label->setFontFace(fontFace);
label->setString("Join Game");
list.push_back(label);
findServer = new HUDuiLabel;
findServer->setFontFace(fontFace);
findServer->setString("Find Server");
list.push_back(findServer);
connectLabel = new HUDuiLabel;
connectLabel->setFontFace(fontFace);
connectLabel->setString("Connect");
list.push_back(connectLabel);
callsign = new HUDuiTypeIn;
callsign->setFontFace(fontFace);
callsign->setLabel("Callsign:");
callsign->setMaxLength(CallSignLen - 1);
callsign->setString(info->callsign);
list.push_back(callsign);
password = new HUDuiTypeIn;
password->setObfuscation(true);
password->setFontFace(fontFace);
password->setLabel("Password:");
password->setMaxLength(CallSignLen - 1);
password->setString(info->password);
list.push_back(password);
team = new HUDuiList;
team->setFontFace(fontFace);
team->setLabel("Team:");
team->setCallback(teamCallback, NULL);
std::vector<std::string>& teams = team->getList();
// these do not need to be in enum order, but must match getTeam() & setTeam()
teams.push_back(std::string(Team::getName(AutomaticTeam)));
teams.push_back(std::string(Team::getName(RogueTeam)));
teams.push_back(std::string(Team::getName(RedTeam)));
teams.push_back(std::string(Team::getName(GreenTeam)));
teams.push_back(std::string(Team::getName(BlueTeam)));
teams.push_back(std::string(Team::getName(PurpleTeam)));
teams.push_back(std::string(Team::getName(ObserverTeam)));
team->update();
setTeam(info->team);
list.push_back(team);
server = new HUDuiTypeIn;
server->setFontFace(fontFace);
server->setLabel("Server:");
server->setMaxLength(64);
server->setString(info->serverName);
list.push_back(server);
char buffer[10];
sprintf(buffer, "%d", info->serverPort);
port = new HUDuiTypeIn;
port->setFontFace(fontFace);
port->setLabel("Port:");
port->setMaxLength(5);
port->setString(buffer);
list.push_back(port);
email = new HUDuiTypeIn;
email->setFontFace(fontFace);
email->setLabel("Email:");
email->setMaxLength(EmailLen - 1);
email->setString(info->email);
list.push_back(email);
startServer = new HUDuiLabel;
startServer->setFontFace(fontFace);
startServer->setString("Start Server");
list.push_back(startServer);
status = new HUDuiLabel;
status->setFontFace(fontFace);
status->setString("");
list.push_back(status);
failedMessage = new HUDuiLabel;
failedMessage->setFontFace(fontFace);
failedMessage->setString("");
list.push_back(failedMessage);
initNavigation(list, 1, list.size() - 3);
}
JoinMenu::~JoinMenu()
{
delete serverStartMenu;
delete serverMenu;
}
HUDuiDefaultKey* JoinMenu::getDefaultKey()
{
return MenuDefaultKey::getInstance();
}
void JoinMenu::show()
{
activeMenu = this;
StartupInfo* info = getStartupInfo();
// set fields
callsign->setString(info->callsign);
setTeam(info->team);
server->setString(info->serverName);
char buffer[10];
sprintf(buffer, "%d", info->serverPort);
port->setString(buffer);
// clear status
setStatus("");
setFailedMessage("");
}
void JoinMenu::dismiss()
{
loadInfo();
activeMenu = NULL;
}
void JoinMenu::loadInfo()
{
// load startup info with current settings
StartupInfo* info = getStartupInfo();
strcpy(info->callsign, callsign->getString().c_str());
info->team = getTeam();
strcpy(info->serverName, server->getString().c_str());
info->serverPort = atoi(port->getString().c_str());
strcpy(info->email, email->getString().c_str());
}
void JoinMenu::execute()
{
HUDuiControl* focus = HUDui::getFocus();
if (focus == startServer) {
if (!serverStartMenu) serverStartMenu = new ServerStartMenu;
HUDDialogStack::get()->push(serverStartMenu);
} else if (focus == findServer) {
if (!serverMenu) serverMenu = new ServerMenu;
HUDDialogStack::get()->push(serverMenu);
} else if (focus == connectLabel) {
// load startup info
loadInfo();
// make sure we've got what we need
StartupInfo* info = getStartupInfo();
if (info->callsign[0] == '\0') {
setStatus("You must enter a callsign.");
return;
}
if (info->serverName[0] == '\0') {
setStatus("You must enter a server.");
return;
}
if (info->serverPort <= 0 || info->serverPort > 65535) {
char buffer[60];
sprintf(buffer, "Port is invalid. Try %d.", ServerPort);
setStatus(buffer);
return;
}
// let user know we're trying
setStatus("Trying...");
// schedule attempt to join game
joinGame();
}
}
void JoinMenu::setFailedMessage(const char* msg)
{
failedMessage->setString(msg);
FontManager &fm = FontManager::instance();
const float width = fm.getStrLength(MainMenu::getFontFace(),
failedMessage->getFontSize(), failedMessage->getString());
failedMessage->setPosition(center - 0.5f * width, failedMessage->getY());
}
TeamColor JoinMenu::getTeam() const
{
return team->getIndex() == 0 ? AutomaticTeam : TeamColor(team->getIndex() - 1);
}
void JoinMenu::setTeam(TeamColor teamcol)
{
team->setIndex(teamcol == AutomaticTeam ? 0 : int(teamcol) + 1);
}
void JoinMenu::setStatus(const char* msg, const std::vector<std::string> *)
{
status->setString(msg);
FontManager &fm = FontManager::instance();
const float width = fm.getStrLength(status->getFontFace(),
status->getFontSize(), status->getString());
status->setPosition(center - 0.5f * width, status->getY());
}
void JoinMenu::teamCallback(HUDuiControl*, void*)
{
// do nothing (for now)
}
void JoinMenu::resize(int width, int height)
{
HUDDialog::resize(width, height);
// use a big font for title, smaller font for the rest
const float titleFontSize = (float)height / 15.0f;
const float fontSize = (float)height / 36.0f;
center = 0.5f * (float)width;
FontManager &fm = FontManager::instance();
// reposition title
std::vector<HUDuiControl*>& list = getControls();
HUDuiLabel* title = (HUDuiLabel*)list[0];
title->setFontSize(titleFontSize);
const float titleWidth = fm.getStrLength(MainMenu::getFontFace(), titleFontSize, title->getString());
const float titleHeight = fm.getStrHeight(MainMenu::getFontFace(), titleFontSize, "");
float x = 0.5f * ((float)width - titleWidth);
float y = (float)height - titleHeight;
title->setPosition(x, y);
// reposition options
x = 0.5f * ((float)width - 0.5f * titleWidth);
y -= 0.6f * titleHeight;
list[1]->setFontSize(fontSize);
const float h = fm.getStrHeight(MainMenu::getFontFace(), fontSize, "");
const int count = list.size();
for (int i = 1; i < count; i++) {
list[i]->setFontSize(fontSize);
list[i]->setPosition(x, y);
y -= 1.0f * h;
if (i <= 2 || i == 7) y -= 0.5f * h;
}
}
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>store password in startup info<commit_after>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* interface header */
#include "JoinMenu.h"
/* system headers */
#include <string>
#include <vector>
/* common implementation headers */
#include "FontManager.h"
/* local implementation headers */
#include "StartupInfo.h"
#include "MainMenu.h"
#include "HUDDialogStack.h"
#include "MenuDefaultKey.h"
#include "ServerStartMenu.h"
#include "ServerMenu.h"
#include "Protocol.h"
#include "HUDuiControl.h"
#include "HUDuiLabel.h"
#include "HUDuiTypeIn.h"
#include "HUDuiList.h"
#include "TimeKeeper.h"
/* from playing.h */
StartupInfo* getStartupInfo();
void joinGame();
JoinMenu* JoinMenu::activeMenu = NULL;
JoinMenu::JoinMenu() : serverStartMenu(NULL), serverMenu(NULL)
{
// cache font face ID
int fontFace = MainMenu::getFontFace();
// add controls
std::vector<HUDuiControl*>& list = getControls();
StartupInfo* info = getStartupInfo();
HUDuiLabel* label = new HUDuiLabel;
label->setFontFace(fontFace);
label->setString("Join Game");
list.push_back(label);
findServer = new HUDuiLabel;
findServer->setFontFace(fontFace);
findServer->setString("Find Server");
list.push_back(findServer);
connectLabel = new HUDuiLabel;
connectLabel->setFontFace(fontFace);
connectLabel->setString("Connect");
list.push_back(connectLabel);
callsign = new HUDuiTypeIn;
callsign->setFontFace(fontFace);
callsign->setLabel("Callsign:");
callsign->setMaxLength(CallSignLen - 1);
callsign->setString(info->callsign);
list.push_back(callsign);
password = new HUDuiTypeIn;
password->setObfuscation(true);
password->setFontFace(fontFace);
password->setLabel("Password:");
password->setMaxLength(CallSignLen - 1);
password->setString(info->password);
list.push_back(password);
team = new HUDuiList;
team->setFontFace(fontFace);
team->setLabel("Team:");
team->setCallback(teamCallback, NULL);
std::vector<std::string>& teams = team->getList();
// these do not need to be in enum order, but must match getTeam() & setTeam()
teams.push_back(std::string(Team::getName(AutomaticTeam)));
teams.push_back(std::string(Team::getName(RogueTeam)));
teams.push_back(std::string(Team::getName(RedTeam)));
teams.push_back(std::string(Team::getName(GreenTeam)));
teams.push_back(std::string(Team::getName(BlueTeam)));
teams.push_back(std::string(Team::getName(PurpleTeam)));
teams.push_back(std::string(Team::getName(ObserverTeam)));
team->update();
setTeam(info->team);
list.push_back(team);
server = new HUDuiTypeIn;
server->setFontFace(fontFace);
server->setLabel("Server:");
server->setMaxLength(64);
server->setString(info->serverName);
list.push_back(server);
char buffer[10];
sprintf(buffer, "%d", info->serverPort);
port = new HUDuiTypeIn;
port->setFontFace(fontFace);
port->setLabel("Port:");
port->setMaxLength(5);
port->setString(buffer);
list.push_back(port);
email = new HUDuiTypeIn;
email->setFontFace(fontFace);
email->setLabel("Email:");
email->setMaxLength(EmailLen - 1);
email->setString(info->email);
list.push_back(email);
startServer = new HUDuiLabel;
startServer->setFontFace(fontFace);
startServer->setString("Start Server");
list.push_back(startServer);
status = new HUDuiLabel;
status->setFontFace(fontFace);
status->setString("");
list.push_back(status);
failedMessage = new HUDuiLabel;
failedMessage->setFontFace(fontFace);
failedMessage->setString("");
list.push_back(failedMessage);
initNavigation(list, 1, list.size() - 3);
}
JoinMenu::~JoinMenu()
{
delete serverStartMenu;
delete serverMenu;
}
HUDuiDefaultKey* JoinMenu::getDefaultKey()
{
return MenuDefaultKey::getInstance();
}
void JoinMenu::show()
{
activeMenu = this;
StartupInfo* info = getStartupInfo();
// set fields
callsign->setString(info->callsign);
password->setString(info->password);
setTeam(info->team);
server->setString(info->serverName);
char buffer[10];
sprintf(buffer, "%d", info->serverPort);
port->setString(buffer);
// clear status
setStatus("");
setFailedMessage("");
}
void JoinMenu::dismiss()
{
loadInfo();
activeMenu = NULL;
}
void JoinMenu::loadInfo()
{
// load startup info with current settings
StartupInfo* info = getStartupInfo();
strcpy(info->callsign, callsign->getString().c_str());
strcpy(info->password, password->getString().c_str());
info->team = getTeam();
strcpy(info->serverName, server->getString().c_str());
info->serverPort = atoi(port->getString().c_str());
strcpy(info->email, email->getString().c_str());
}
void JoinMenu::execute()
{
HUDuiControl* focus = HUDui::getFocus();
if (focus == startServer) {
if (!serverStartMenu) serverStartMenu = new ServerStartMenu;
HUDDialogStack::get()->push(serverStartMenu);
} else if (focus == findServer) {
if (!serverMenu) serverMenu = new ServerMenu;
HUDDialogStack::get()->push(serverMenu);
} else if (focus == connectLabel) {
// load startup info
loadInfo();
// make sure we've got what we need
StartupInfo* info = getStartupInfo();
if (info->callsign[0] == '\0') {
setStatus("You must enter a callsign.");
return;
}
if (info->serverName[0] == '\0') {
setStatus("You must enter a server.");
return;
}
if (info->serverPort <= 0 || info->serverPort > 65535) {
char buffer[60];
sprintf(buffer, "Port is invalid. Try %d.", ServerPort);
setStatus(buffer);
return;
}
// let user know we're trying
setStatus("Trying...");
// schedule attempt to join game
joinGame();
}
}
void JoinMenu::setFailedMessage(const char* msg)
{
failedMessage->setString(msg);
FontManager &fm = FontManager::instance();
const float width = fm.getStrLength(MainMenu::getFontFace(),
failedMessage->getFontSize(), failedMessage->getString());
failedMessage->setPosition(center - 0.5f * width, failedMessage->getY());
}
TeamColor JoinMenu::getTeam() const
{
return team->getIndex() == 0 ? AutomaticTeam : TeamColor(team->getIndex() - 1);
}
void JoinMenu::setTeam(TeamColor teamcol)
{
team->setIndex(teamcol == AutomaticTeam ? 0 : int(teamcol) + 1);
}
void JoinMenu::setStatus(const char* msg, const std::vector<std::string> *)
{
status->setString(msg);
FontManager &fm = FontManager::instance();
const float width = fm.getStrLength(status->getFontFace(),
status->getFontSize(), status->getString());
status->setPosition(center - 0.5f * width, status->getY());
}
void JoinMenu::teamCallback(HUDuiControl*, void*)
{
// do nothing (for now)
}
void JoinMenu::resize(int width, int height)
{
HUDDialog::resize(width, height);
// use a big font for title, smaller font for the rest
const float titleFontSize = (float)height / 15.0f;
const float fontSize = (float)height / 36.0f;
center = 0.5f * (float)width;
FontManager &fm = FontManager::instance();
// reposition title
std::vector<HUDuiControl*>& list = getControls();
HUDuiLabel* title = (HUDuiLabel*)list[0];
title->setFontSize(titleFontSize);
const float titleWidth = fm.getStrLength(MainMenu::getFontFace(), titleFontSize, title->getString());
const float titleHeight = fm.getStrHeight(MainMenu::getFontFace(), titleFontSize, "");
float x = 0.5f * ((float)width - titleWidth);
float y = (float)height - titleHeight;
title->setPosition(x, y);
// reposition options
x = 0.5f * ((float)width - 0.5f * titleWidth);
y -= 0.6f * titleHeight;
list[1]->setFontSize(fontSize);
const float h = fm.getStrHeight(MainMenu::getFontFace(), fontSize, "");
const int count = list.size();
for (int i = 1; i < count; i++) {
list[i]->setFontSize(fontSize);
list[i]->setPosition(x, y);
y -= 1.0f * h;
if (i <= 2 || i == 7) y -= 0.5f * h;
}
}
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named LICENSE that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* interface header */
#include "GameKeeper.h"
extern PlayerInfo player[PlayerSlot];
// player lag info
LagInfo *lagInfo[PlayerSlot] = {NULL};
extern PlayerAccessInfo accessInfo[PlayerSlot];
extern PlayerState lastState[PlayerSlot];
extern DelayQueue delayq[PlayerSlot];
extern FlagHistory flagHistory[PlayerSlot];
extern Score *score[PlayerSlot];
GameKeeper::Player *GameKeeper::Player::playerList[PlayerSlot] = {NULL};
GameKeeper::Player::Player(int _playerIndex):
player(&::player[_playerIndex]), accessInfo(&::accessInfo[_playerIndex]),
lastState(&::lastState[_playerIndex]), delayq(&::delayq[_playerIndex]),
flagHistory(&::flagHistory[_playerIndex]), score(NULL),
playerIndex(_playerIndex)
{
GameKeeper::Player::playerList[playerIndex] = this;
player->initPlayer(playerIndex);
lastState->order = 0;
lagInfo = new LagInfo(player);
::lagInfo[playerIndex] = lagInfo;
score = new Score();
::score[playerIndex] = score;
}
GameKeeper::Player::~Player()
{
accessInfo->removePlayer();
player->removePlayer();
delayq->dequeuePackets();
flagHistory->clear();
delete lagInfo;
delete score;
::lagInfo[playerIndex] = NULL;
::score[playerIndex] = NULL;
GameKeeper::Player::playerList[playerIndex] = NULL;
}
GameKeeper::Player *GameKeeper::Player::getPlayerByIndex(int _playerIndex)
{
return GameKeeper::Player::playerList[_playerIndex];
}
void GameKeeper::Player::updateLatency(float &waitTime)
{
int p;
for (p = 0; p < PlayerSlot; p++)
if (playerList[p]) {
playerList[p]->lagInfo->updateLatency(waitTime);
}
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>remove excessive namespacing, make it compile on vc<commit_after>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named LICENSE that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* interface header */
#include "GameKeeper.h"
extern PlayerInfo player[PlayerSlot];
// player lag info
LagInfo *lagInfo[PlayerSlot] = {NULL};
extern PlayerAccessInfo accessInfo[PlayerSlot];
extern PlayerState lastState[PlayerSlot];
extern DelayQueue delayq[PlayerSlot];
extern FlagHistory flagHistory[PlayerSlot];
extern Score *score[PlayerSlot];
GameKeeper::Player *GameKeeper::Player::playerList[PlayerSlot] = {NULL};
GameKeeper::Player::Player(int _playerIndex):
player(&::player[_playerIndex]), accessInfo(&::accessInfo[_playerIndex]),
lastState(&::lastState[_playerIndex]), delayq(&::delayq[_playerIndex]),
flagHistory(&::flagHistory[_playerIndex]), score(NULL),
playerIndex(_playerIndex)
{
playerList[playerIndex] = this;
player->initPlayer(playerIndex);
lastState->order = 0;
lagInfo = new LagInfo(player);
::lagInfo[playerIndex] = lagInfo;
score = new Score();
::score[playerIndex] = score;
}
GameKeeper::Player::~Player()
{
accessInfo->removePlayer();
player->removePlayer();
delayq->dequeuePackets();
flagHistory->clear();
delete lagInfo;
delete score;
::lagInfo[playerIndex] = NULL;
::score[playerIndex] = NULL;
playerList[playerIndex] = NULL;
}
GameKeeper::Player *GameKeeper::Player::getPlayerByIndex(int _playerIndex)
{
return playerList[_playerIndex];
}
void GameKeeper::Player::updateLatency(float &waitTime)
{
int p;
for (p = 0; p < PlayerSlot; p++)
if (playerList[p]) {
playerList[p]->lagInfo->updateLatency(waitTime);
}
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>#include "SkillSystem.h"
#include "BulletSystem.h"
#include "interface.h"
#include "GameProcess.h"
#include "ObjectParticles.h"
CSkillSystem::CSkillSystem(CGameProcess* pGameProcess)
{
CBulletSystem::GetInstance()->SetCallback(MakeInterface(this, &CSkillSystem::OnSkillCallback));
m_pGameProcess = pGameProcess;
AddListen(BR_PARTICLE_HIT, MakeMessageFunc(this, &CSkillSystem::OnParticleHit));
}
CSkillSystem::~CSkillSystem(void)
{
CBulletSystem::ReleaseInstance();
}
int CSkillSystem::OnSkillCallback(void* pVoid)
{
_BulletCallback* pBase = (_BulletCallback*)pVoid;
switch (pBase->nMsgID)
{
case _BulletCallback::GetTargetPosition:
{
_Bullet_GetTargetPosition* pBullet = (_Bullet_GetTargetPosition*)pBase;
CRoleBase* pRole = m_pGameProcess->GetRole(pBullet->nTarget);//test
if (pRole)
{
pBullet->nRetState = 1;
pBullet->vRetPos = pRole->GetPosition() + vec3(0.0f, 0.0f, 1.2f);
pBullet->vRetDir = pRole->GetDirection();
}
else
{
pBullet->nRetState = 0;
}
}break;
case _BulletCallback::HitTarget:
{
_Bullet_HitTarget* pBullet = (_Bullet_HitTarget*)pBase;
}break;
case _BulletCallback::GetCollision:
{
_Bullet_GetCollision* pBullet = (_Bullet_GetCollision*)pBase;
//test
for (int i = 0; i < 20; i++)
{
CRoleBase* pRole = m_pGameProcess->GetRoleFormIndex(i);
if (pRole)
{
if ((pRole->GetPosition() - pBullet->vPos).length() < pBullet->fRadius + pRole->GetRoleRadius())
{
pBullet->nRetTarget = pRole->GetRoleID();
pBullet->vRetHitPoint = pRole->GetPosition() + vec3(0.0f, 0.0f, 1.2f);
}
}
}
}break;
case _BulletCallback::Blast:
{
_Bullet_Blast* pBullet = (_Bullet_Blast*)pBase;
}break;
}
return 1;
}
void CSkillSystem::Update(float ifps)
{
CBulletSystem::GetInstance()->Update();
}<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "SkillSystem.h"
#include "BulletSystem.h"
#include "interface.h"
#include "GameProcess.h"
#include "ObjectParticles.h"
CSkillSystem::CSkillSystem(CGameProcess* pGameProcess)
{
CBulletSystem::GetInstance()->SetCallback(MakeInterface(this, &CSkillSystem::OnSkillCallback));
m_pGameProcess = pGameProcess;
AddListen(BR_PARTICLE_HIT, MakeMessageFunc(this, &CSkillSystem::OnParticleHit));
}
CSkillSystem::~CSkillSystem(void)
{
CBulletSystem::ReleaseInstance();
}
int CSkillSystem::OnSkillCallback(void* pVoid)
{
_BulletCallback* pBase = (_BulletCallback*)pVoid;
switch (pBase->nMsgID)
{
case _BulletCallback::GetTargetPosition:
{
_Bullet_GetTargetPosition* pBullet = (_Bullet_GetTargetPosition*)pBase;
CRoleBase* pRole = m_pGameProcess->GetRole(pBullet->nTarget);//test
if (pRole)
{
pBullet->nRetState = 1;
pBullet->vRetPos = pRole->GetPosition() + vec3(0.0f, 0.0f, 1.2f);
pBullet->vRetDir = pRole->GetDirection();
}
else
{
pBullet->nRetState = 0;
}
}break;
case _BulletCallback::HitTarget:
{
_Bullet_HitTarget* pBullet = (_Bullet_HitTarget*)pBase;
}break;
case _BulletCallback::GetCollision:
{
_Bullet_GetCollision* pBullet = (_Bullet_GetCollision*)pBase;
//test
for (int i = 0; i < 20; i++)
{
CRoleBase* pRole = m_pGameProcess->GetRoleFormIndex(i);
if (pRole)
{
if ((pRole->GetPosition() - pBullet->vPos).length() < pBullet->fRadius + pRole->GetRoleRadius())
{
pBullet->nRetTarget = pRole->GetRoleID();
pBullet->vRetHitPoint = pRole->GetPosition() + vec3(0.0f, 0.0f, 1.2f);
}
}
}
}break;
case _BulletCallback::Blast:
{
_Bullet_Blast* pBullet = (_Bullet_Blast*)pBase;
}break;
}
return 1;
}
void CSkillSystem::Update(float ifps)
{
CBulletSystem::GetInstance()->Update();
}
void CSkillSystem::Reset()
{
CBulletSystem::GetInstance()->Reset();
}
<|endoftext|> |
<commit_before>// $Id$
/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2006 University of Edinburgh
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
***********************************************************************/
#include <cassert>
#include <limits>
#include <iostream>
#include <fstream>
#include "ngram.hh"
#include "LanguageModelKen.h"
#include "TypeDef.h"
#include "Util.h"
#include "FactorCollection.h"
#include "Phrase.h"
#include "InputFileStream.h"
#include "StaticData.h"
using namespace std;
namespace Moses
{
LanguageModelKen::LanguageModelKen(bool registerScore, ScoreIndexManager &scoreIndexManager)
:LanguageModelSingleFactor(registerScore, scoreIndexManager), m_ngram(NULL)
{
}
LanguageModelKen::~LanguageModelKen()
{
delete m_ngram;
}
bool LanguageModelKen::Load(const std::string &filePath,
FactorType factorType,
size_t nGramOrder)
{
cerr << "In LanguageModelKen::Load: nGramOrder = " << nGramOrder << " will be ignored. Using whatever the file has.\n";
m_ngram = new lm::ngram::Model(filePath.c_str());
return true;
}
/* get score of n-gram. n-gram should not be bigger than m_nGramOrder
* Specific implementation can return State and len data to be used in hypothesis pruning
* \param contextFactor n-gram to be scored
* \param finalState state used by LM. Return arg
* \param len ???
*/
float LanguageModelKen::GetValue(const vector<const Word*> &contextFactor, State* finalState, unsigned int* len) const
{
FactorType factorType = GetFactorType();
size_t count = contextFactor.size();
assert(count <= GetNGramOrder());
if (count == 0)
{
finalState = NULL;
return 0;
}
// set up context
vector<lm::WordIndex> ngramId(count);
for (size_t i = 0 ; i < count - 1 ; i++)
{
const Factor *factor = contextFactor[i]->GetFactor(factorType);
const string &word = factor->GetString();
// TODO(hieuhoang1972): precompute this.
ngramId[i] = m_ngram->GetVocabulary().Index(word);
}
// TODO(hieuhoang1972): use my stateful interface instead of this stateless one you asked heafield to kludge for you.
lm::ngram::HieuShouldRefactorMoses ret(m_ngram->SlowStatelessScore(&*ngramId.begin(), &*ngramId.end()));
if (finalState)
{
*finalState = ret.meaningless_unique_state;
}
if (len)
{
*len = ret.ngram_length;
}
return TransformLMScore(ret.prob);
}
}
<commit_msg>LanguageModelKen now without segfaults. The load function was missing some undocumented initialization. <commit_after>// $Id$
/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2006 University of Edinburgh
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
***********************************************************************/
#include <cassert>
#include <limits>
#include <iostream>
#include <fstream>
#include "ngram.hh"
#include "LanguageModelKen.h"
#include "TypeDef.h"
#include "Util.h"
#include "FactorCollection.h"
#include "Phrase.h"
#include "InputFileStream.h"
#include "StaticData.h"
using namespace std;
namespace Moses
{
LanguageModelKen::LanguageModelKen(bool registerScore, ScoreIndexManager &scoreIndexManager)
:LanguageModelSingleFactor(registerScore, scoreIndexManager), m_ngram(NULL)
{
}
LanguageModelKen::~LanguageModelKen()
{
delete m_ngram;
}
bool LanguageModelKen::Load(const std::string &filePath,
FactorType factorType,
size_t nGramOrder)
{
cerr << "In LanguageModelKen::Load: nGramOrder = " << nGramOrder << " will be ignored. Using whatever the file has.\n";
m_ngram = new lm::ngram::Model(filePath.c_str());
m_factorType = factorType;
m_nGramOrder = m_ngram->Order();
m_filePath = filePath;
FactorCollection &factorCollection = FactorCollection::Instance();
m_sentenceStart = factorCollection.AddFactor(Output, m_factorType, BOS_);
m_sentenceStartArray[m_factorType] = m_sentenceStart;
m_sentenceEnd = factorCollection.AddFactor(Output, m_factorType, EOS_);
m_sentenceEndArray[m_factorType] = m_sentenceEnd;
return true;
}
/* get score of n-gram. n-gram should not be bigger than m_nGramOrder
* Specific implementation can return State and len data to be used in hypothesis pruning
* \param contextFactor n-gram to be scored
* \param finalState state used by LM. Return arg
* \param len ???
*/
float LanguageModelKen::GetValue(const vector<const Word*> &contextFactor, State* finalState, unsigned int* len) const
{
FactorType factorType = GetFactorType();
size_t count = contextFactor.size();
assert(count <= GetNGramOrder());
if (count == 0)
{
finalState = NULL;
return 0;
}
// set up context
vector<lm::WordIndex> ngramId(count);
for (size_t i = 0 ; i < count - 1 ; i++)
{
const Factor *factor = contextFactor[i]->GetFactor(factorType);
const string &word = factor->GetString();
// TODO(hieuhoang1972): precompute this.
ngramId[i] = m_ngram->GetVocabulary().Index(word);
}
// TODO(hieuhoang1972): use my stateful interface instead of this stateless one you asked heafield to kludge for you.
lm::ngram::HieuShouldRefactorMoses ret(m_ngram->SlowStatelessScore(&*ngramId.begin(), &*ngramId.end()));
if (finalState)
{
*finalState = ret.meaningless_unique_state;
}
if (len)
{
*len = ret.ngram_length;
}
return TransformLMScore(ret.prob);
}
}
<|endoftext|> |
<commit_before>/**********************************************************************
* File: mod128.cpp (Formerly dir128.c)
* Description: Code to convert a DIR128 to an ICOORD.
* Author: Ray Smith
* Created: Tue Oct 22 11:56:09 BST 1991
*
* (C) Copyright 1991, Hewlett-Packard Ltd.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#include "mod128.h"
const int16_t idirtab[] = {
1000, 0, 998, 49, 995, 98, 989, 146,
980, 195, 970, 242, 956, 290, 941, 336,
923, 382, 903, 427, 881, 471, 857, 514,
831, 555, 803, 595, 773, 634, 740, 671,
707, 707, 671, 740, 634, 773, 595, 803,
555, 831, 514, 857, 471, 881, 427, 903,
382, 923, 336, 941, 290, 956, 242, 970,
195, 980, 146, 989, 98, 995, 49, 998,
0, 1000, -49, 998, -98, 995, -146, 989,
-195, 980, -242, 970, -290, 956, -336, 941,
-382, 923, -427, 903, -471, 881, -514, 857,
-555, 831, -595, 803, -634, 773, -671, 740,
-707, 707, -740, 671, -773, 634, -803, 595,
-831, 555, -857, 514, -881, 471, -903, 427,
-923, 382, -941, 336, -956, 290, -970, 242,
-980, 195, -989, 146, -995, 98, -998, 49,
-1000, 0, -998, -49, -995, -98, -989, -146,
-980, -195, -970, -242, -956, -290, -941, -336,
-923, -382, -903, -427, -881, -471, -857, -514,
-831, -555, -803, -595, -773, -634, -740, -671,
-707, -707, -671, -740, -634, -773, -595, -803,
-555, -831, -514, -857, -471, -881, -427, -903,
-382, -923, -336, -941, -290, -956, -242, -970,
-195, -980, -146, -989, -98, -995, -49, -998,
0, -1000, 49, -998, 98, -995, 146, -989,
195, -980, 242, -970, 290, -956, 336, -941,
382, -923, 427, -903, 471, -881, 514, -857,
555, -831, 595, -803, 634, -773, 671, -740,
707, -707, 740, -671, 773, -634, 803, -595,
831, -555, 857, -514, 881, -471, 903, -427,
923, -382, 941, -336, 956, -290, 970, -242,
980, -195, 989, -146, 995, -98, 998, -49
};
const ICOORD *dirtab = (ICOORD *) idirtab;
/**********************************************************************
* DIR128::DIR128
*
* Quantize the direction of an FCOORD to make a DIR128.
**********************************************************************/
DIR128::DIR128( //from fcoord
const FCOORD fc //vector to quantize
) {
int high, low, current; //binary search
low = 0;
if (fc.y () == 0) {
if (fc.x () >= 0)
dir = 0;
else
dir = MODULUS / 2;
return;
}
high = MODULUS;
do {
current = (high + low) / 2;
if (dirtab[current] * fc >= 0)
low = current;
else
high = current;
}
while (high - low > 1);
dir = low;
}
<commit_msg>ccstruct/mod128.cpp: Fix compiler warnings<commit_after>/**********************************************************************
* File: mod128.cpp (Formerly dir128.c)
* Description: Code to convert a DIR128 to an ICOORD.
* Author: Ray Smith
* Created: Tue Oct 22 11:56:09 BST 1991
*
* (C) Copyright 1991, Hewlett-Packard Ltd.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#include "mod128.h"
static const int16_t idirtab[] = {
1000, 0, 998, 49, 995, 98, 989, 146,
980, 195, 970, 242, 956, 290, 941, 336,
923, 382, 903, 427, 881, 471, 857, 514,
831, 555, 803, 595, 773, 634, 740, 671,
707, 707, 671, 740, 634, 773, 595, 803,
555, 831, 514, 857, 471, 881, 427, 903,
382, 923, 336, 941, 290, 956, 242, 970,
195, 980, 146, 989, 98, 995, 49, 998,
0, 1000, -49, 998, -98, 995, -146, 989,
-195, 980, -242, 970, -290, 956, -336, 941,
-382, 923, -427, 903, -471, 881, -514, 857,
-555, 831, -595, 803, -634, 773, -671, 740,
-707, 707, -740, 671, -773, 634, -803, 595,
-831, 555, -857, 514, -881, 471, -903, 427,
-923, 382, -941, 336, -956, 290, -970, 242,
-980, 195, -989, 146, -995, 98, -998, 49,
-1000, 0, -998, -49, -995, -98, -989, -146,
-980, -195, -970, -242, -956, -290, -941, -336,
-923, -382, -903, -427, -881, -471, -857, -514,
-831, -555, -803, -595, -773, -634, -740, -671,
-707, -707, -671, -740, -634, -773, -595, -803,
-555, -831, -514, -857, -471, -881, -427, -903,
-382, -923, -336, -941, -290, -956, -242, -970,
-195, -980, -146, -989, -98, -995, -49, -998,
0, -1000, 49, -998, 98, -995, 146, -989,
195, -980, 242, -970, 290, -956, 336, -941,
382, -923, 427, -903, 471, -881, 514, -857,
555, -831, 595, -803, 634, -773, 671, -740,
707, -707, 740, -671, 773, -634, 803, -595,
831, -555, 857, -514, 881, -471, 903, -427,
923, -382, 941, -336, 956, -290, 970, -242,
980, -195, 989, -146, 995, -98, 998, -49
};
const ICOORD* dirtab = reinterpret_cast<const ICOORD*>(idirtab);
/**********************************************************************
* DIR128::DIR128
*
* Quantize the direction of an FCOORD to make a DIR128.
**********************************************************************/
DIR128::DIR128( //from fcoord
const FCOORD fc //vector to quantize
) {
int high, low, current; //binary search
low = 0;
if (fc.y () == 0) {
if (fc.x () >= 0)
dir = 0;
else
dir = MODULUS / 2;
return;
}
high = MODULUS;
do {
current = (high + low) / 2;
if (dirtab[current] * fc >= 0)
low = current;
else
high = current;
}
while (high - low > 1);
dir = low;
}
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// Copyright (c) 2018 John D. Haughton
//
// 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 "Z/ZMemory.h"
#include "Z/ZQuetzal.h"
#include "Z/ZStack.h"
#include "Z/ZStory.h"
#include "STB/ConsoleApp.h"
#include <iostream>
#include <iomanip>
#define PROGRAM "QDmp"
#define DESCRIPTION "Dump Z story contents"
#define LINK "https://github.com/AnotherJohnH/Zif"
#define AUTHOR "John D. Haughton"
#define VERSION PROJ_VERSION
#define COPYRIGHT_YEAR "2018"
//!
class QDmp : public STB::ConsoleApp
{
private:
STB::Option<const char*> save_file{'s', "save", "Save file"};
std::string filename;
ZStory story;
ZQuetzal quetzal;
uint32_t pc;
uint32_t rand_state;
ZMemory memory;
ZStack stack;
int error(const std::string& message)
{
std::cerr << "ERR - " << message << std::endl;
return -1;
}
void attr(const std::string& name, const std::string& value)
{
std::cout << " \"" << name << "\": \"" << value << "\"," << std::endl;
}
void attr(const std::string& name, unsigned value)
{
std::cout << std::hex << std::setfill('0');
std::cout << " \"" << name << "\": \"0x" << value << "\"," << std::endl;
}
void dumpHeader(const ZHeader* header)
{
attr("version", header->version);
attr("flags1", header->flags1);
attr("release", header->release);
attr("himem", header->himem);
attr("initPC", header->init_pc);
attr("dict", header->dict);
attr("obj", header->obj);
attr("globalBase", header->glob);
attr("static", header->stat);
attr("gameEnd", header->getStorySize());
attr("memLimit", header->getMemoryLimit());
attr("flags2", header->flags2);
attr("abbr", header->abbr);
attr("length", header->length);
attr("checksum", header->checksum);
attr("interpNum", header->interpreter_number);
attr("interpVer", header->interpreter_version);
attr("screenLines", header->screen_lines);
attr("screenCols", header->screen_cols);
attr("screenWidth", header->screen_width);
attr("screenHeight", header->screen_height);
// attr("fontWidth", header->font_width);
// attr("fontHeight", header->font_height);
attr("routines", header->routines);
attr("staticStrings", header->static_strings);
attr("bgColour", header->background_colour);
attr("fgColour", header->foreground_colour);
attr("termChars", header->terminating_characters);
attr("widthTextStream3", header->width_text_stream3);
attr("standardRevision", header->standard_revision);
attr("alphabetTable", header->alphabet_table);
attr("headerExt", header->header_ext);
}
void dumpMemory()
{
std::cout << " \"memory\": [" << std::endl;
for(unsigned addr=0; addr<memory.getSize(); addr += 16)
{
std::cout << " {\"a\": \"" << std::setw(6) << addr << "\", \"b\": \"";
for(unsigned i=0; i<16; i++)
{
if ((addr + i) < memory.getSize())
{
std::cout << " " << std::setw(2) << unsigned(memory.get(addr + i));
}
}
std::cout << "\", \"c\": \"";
for(unsigned i=0; i<16; i++)
{
if ((addr + i) < memory.getSize())
{
uint8_t ch = memory.get(addr + i);
if (isprint(ch))
{
std::cout << ch;
}
else
{
std::cout << '.';
}
}
}
std::cout << "\"}," << std::endl;
}
std::cout << " ]," << std::endl;
}
void dumpStack()
{
std::cout << " \"stack\": [" << std::endl;
for(unsigned i=0; i<stack.size(); i++)
{
std::cout << " \"0x" << std::setw(4) << stack[i] << "\"," << std::endl;
}
std::cout << " ]" << std::endl;
}
virtual int startConsoleApp() override
{
std::cout << "{" << std::endl;
attr("story", filename);
if (!story.load(filename))
{
return error(story.getLastError());
}
const ZHeader* header = story.getHeader();
memory.configure(header);
if (save_file != nullptr)
{
attr("saveFile", (const char*)save_file);
if (!quetzal.read((const char*)save_file))
{
return error(quetzal.getLastError());
}
if (!quetzal.decode(story, pc, rand_state, memory, stack))
{
return error(quetzal.getLastError());
}
attr("PC", pc);
attr("randState", rand_state);
header = memory.getHeader();
}
else
{
memcpy(memory.getData(), story.data(), story.size());
}
dumpHeader(header);
dumpMemory();
if (save_file != nullptr)
{
dumpStack();
}
std::cout << "}" << std::endl;
return 0;
}
virtual void parseArg(const char* arg) override
{
filename = arg;
}
public:
QDmp(int argc, const char* argv[])
: ConsoleApp(PROGRAM, DESCRIPTION, LINK, AUTHOR, VERSION, COPYRIGHT_YEAR)
{
parseArgsAndStart(argc, argv);
}
};
int main(int argc, const char* argv[])
{
QDmp(argc, argv);
}
<commit_msg>Cosmetix rename of zdmp application class<commit_after>//------------------------------------------------------------------------------
// Copyright (c) 2018 John D. Haughton
//
// 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 "Z/ZMemory.h"
#include "Z/ZQuetzal.h"
#include "Z/ZStack.h"
#include "Z/ZStory.h"
#include "STB/ConsoleApp.h"
#include <iostream>
#include <iomanip>
#define PROGRAM "ZDmp"
#define DESCRIPTION "Dump Z story contents"
#define LINK "https://github.com/AnotherJohnH/Zif"
#define AUTHOR "John D. Haughton"
#define VERSION PROJ_VERSION
#define COPYRIGHT_YEAR "2018"
//!
class ZDmp : public STB::ConsoleApp
{
private:
STB::Option<const char*> save_file{'s', "save", "Save file"};
std::string filename;
ZStory story;
ZQuetzal quetzal;
uint32_t pc;
uint32_t rand_state;
ZMemory memory;
ZStack stack;
int error(const std::string& message)
{
std::cerr << "ERR - " << message << std::endl;
return -1;
}
void attr(const std::string& name, const std::string& value)
{
std::cout << " \"" << name << "\": \"" << value << "\"," << std::endl;
}
void attr(const std::string& name, unsigned value)
{
std::cout << std::hex << std::setfill('0');
std::cout << " \"" << name << "\": \"0x" << value << "\"," << std::endl;
}
void dumpHeader(const ZHeader* header)
{
attr("version", header->version);
attr("flags1", header->flags1);
attr("release", header->release);
attr("himem", header->himem);
attr("initPC", header->init_pc);
attr("dict", header->dict);
attr("obj", header->obj);
attr("globalBase", header->glob);
attr("static", header->stat);
attr("gameEnd", header->getStorySize());
attr("memLimit", header->getMemoryLimit());
attr("flags2", header->flags2);
attr("abbr", header->abbr);
attr("length", header->length);
attr("checksum", header->checksum);
attr("interpNum", header->interpreter_number);
attr("interpVer", header->interpreter_version);
attr("screenLines", header->screen_lines);
attr("screenCols", header->screen_cols);
attr("screenWidth", header->screen_width);
attr("screenHeight", header->screen_height);
// attr("fontWidth", header->font_width);
// attr("fontHeight", header->font_height);
attr("routines", header->routines);
attr("staticStrings", header->static_strings);
attr("bgColour", header->background_colour);
attr("fgColour", header->foreground_colour);
attr("termChars", header->terminating_characters);
attr("widthTextStream3", header->width_text_stream3);
attr("standardRevision", header->standard_revision);
attr("alphabetTable", header->alphabet_table);
attr("headerExt", header->header_ext);
}
void dumpMemory()
{
std::cout << " \"memory\": [" << std::endl;
for(unsigned addr=0; addr<memory.getSize(); addr += 16)
{
std::cout << " {\"a\": \"" << std::setw(6) << addr << "\", \"b\": \"";
for(unsigned i=0; i<16; i++)
{
if ((addr + i) < memory.getSize())
{
std::cout << " " << std::setw(2) << unsigned(memory.get(addr + i));
}
}
std::cout << "\", \"c\": \"";
for(unsigned i=0; i<16; i++)
{
if ((addr + i) < memory.getSize())
{
uint8_t ch = memory.get(addr + i);
if (isprint(ch))
{
std::cout << ch;
}
else
{
std::cout << '.';
}
}
}
std::cout << "\"}," << std::endl;
}
std::cout << " ]," << std::endl;
}
void dumpStack()
{
std::cout << " \"stack\": [" << std::endl;
for(unsigned i=0; i<stack.size(); i++)
{
std::cout << " \"0x" << std::setw(4) << stack[i] << "\"," << std::endl;
}
std::cout << " ]" << std::endl;
}
virtual int startConsoleApp() override
{
std::cout << "{" << std::endl;
attr("story", filename);
if (!story.load(filename))
{
return error(story.getLastError());
}
const ZHeader* header = story.getHeader();
memory.configure(header);
if (save_file != nullptr)
{
attr("saveFile", (const char*)save_file);
if (!quetzal.read((const char*)save_file))
{
return error(quetzal.getLastError());
}
if (!quetzal.decode(story, pc, rand_state, memory, stack))
{
return error(quetzal.getLastError());
}
attr("PC", pc);
attr("randState", rand_state);
header = memory.getHeader();
}
else
{
memcpy(memory.getData(), story.data(), story.size());
}
dumpHeader(header);
dumpMemory();
if (save_file != nullptr)
{
dumpStack();
}
std::cout << "}" << std::endl;
return 0;
}
virtual void parseArg(const char* arg) override
{
filename = arg;
}
public:
ZDmp(int argc, const char* argv[])
: ConsoleApp(PROGRAM, DESCRIPTION, LINK, AUTHOR, VERSION, COPYRIGHT_YEAR)
{
parseArgsAndStart(argc, argv);
}
};
int main(int argc, const char* argv[])
{
ZDmp(argc, argv);
}
<|endoftext|> |
<commit_before>#include "HttpHeader.h"
HttpHeaderInfo HttpHeaderInfo::readFromBuffer(DataBuffer& buffer)
{
HttpHeaderInfo info;
if (buffer.size() < 4 || !(strncmp((const char*)buffer.data(), "HTTP", 4) == 0 || strncmp((const char*)buffer.data(), "http", 4) == 0))
{
info.valid = false;
return info;
}
size_t pos = 0;
while (pos + 1 < buffer.size())
{
if (buffer[pos] == '\r' && buffer[pos + 1] == '\n')
{
info.dataStart = (uint32_t)pos + 2;
break;
}
std::string line;
for (size_t i = pos + 1; i < buffer.size() - 1; i++)
{
if (buffer[i] == '\r' && buffer[i + 1] == '\n')
{
line = std::string((char*)& buffer[pos], (char*)& buffer[i]);
pos = i + 2;
break;
}
}
auto vpos = line.find_first_of(':');
if (vpos != std::string::npos && line.length() > vpos + 1)
{
info.headerParameters.push_back({ line.substr(0, vpos),line.substr(vpos + 2) });
}
else
info.headerParameters.push_back({ line,"" });
}
for (auto& p : info.headerParameters)
{
if ((p.first == "Content-Length" || p.first == "CONTENT-LENGTH") && !p.second.empty())
info.dataSize = std::stoul(p.second);
}
if (info.dataStart && !info.dataSize)
info.valid = false;
if (!info.headerParameters.empty() && info.headerParameters[0].first.find("200 OK") != std::string::npos)
info.success = true;
return info;
}
<commit_msg>mark http header without data valid<commit_after>#include "HttpHeader.h"
HttpHeaderInfo HttpHeaderInfo::readFromBuffer(DataBuffer& buffer)
{
HttpHeaderInfo info;
if (buffer.size() < 4 || !(strncmp((const char*)buffer.data(), "HTTP", 4) == 0 || strncmp((const char*)buffer.data(), "http", 4) == 0))
{
info.valid = false;
return info;
}
size_t pos = 0;
while (pos + 1 < buffer.size())
{
if (buffer[pos] == '\r' && buffer[pos + 1] == '\n')
{
info.dataStart = (uint32_t)pos + 2;
break;
}
std::string line;
for (size_t i = pos + 1; i < buffer.size() - 1; i++)
{
if (buffer[i] == '\r' && buffer[i + 1] == '\n')
{
line = std::string((char*)& buffer[pos], (char*)& buffer[i]);
pos = i + 2;
break;
}
}
auto vpos = line.find_first_of(':');
if (vpos != std::string::npos && line.length() > vpos + 1)
{
info.headerParameters.push_back({ line.substr(0, vpos),line.substr(vpos + 2) });
}
else
info.headerParameters.push_back({ line,"" });
}
for (auto& p : info.headerParameters)
{
if ((p.first == "Content-Length" || p.first == "CONTENT-LENGTH") && !p.second.empty())
info.dataSize = std::stoul(p.second);
}
if (info.dataStart && !(info.dataSize || buffer.size() == info.dataStart))
info.valid = false;
if (!info.headerParameters.empty() && info.headerParameters[0].first.find("200 OK") != std::string::npos)
info.success = true;
return info;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/base/host_resolver_proc.h"
#include "build/build_config.h"
#if defined(OS_POSIX) && !defined(OS_MACOSX)
#include <resolv.h>
#endif
#include "base/logging.h"
#include "net/base/address_list.h"
#include "net/base/dns_reload_timer.h"
#include "net/base/net_errors.h"
#include "net/base/sys_addrinfo.h"
namespace net {
namespace {
bool IsAllLocalhostOfOneFamily(const struct addrinfo* ai) {
bool saw_v4_localhost = false;
bool saw_v6_localhost = false;
for (; ai != NULL; ai = ai->ai_next) {
switch (ai->ai_family) {
case AF_INET: {
const struct sockaddr_in* addr_in =
reinterpret_cast<struct sockaddr_in*>(ai->ai_addr);
if ((ntohl(addr_in->sin_addr.s_addr) & 0xff000000) == 0x7f000000)
saw_v4_localhost = true;
else
return false;
break;
}
case AF_INET6: {
const struct sockaddr_in6* addr_in6 =
reinterpret_cast<struct sockaddr_in6*>(ai->ai_addr);
if (IN6_IS_ADDR_LOOPBACK(&addr_in6->sin6_addr))
saw_v6_localhost = true;
else
return false;
break;
}
default:
NOTREACHED();
return false;
}
}
return saw_v4_localhost != saw_v6_localhost;
}
} // namespace
HostResolverProc* HostResolverProc::default_proc_ = NULL;
HostResolverProc::HostResolverProc(HostResolverProc* previous) {
SetPreviousProc(previous);
// Implicitly fall-back to the global default procedure.
if (!previous)
SetPreviousProc(default_proc_);
}
void HostResolverProc::SetPreviousProc(HostResolverProc* proc) {
HostResolverProc* current_previous = previous_proc_;
previous_proc_ = NULL;
// Now that we've guaranteed |this| is the last proc in a chain, we can
// detect potential cycles using GetLastProc().
previous_proc_ = (GetLastProc(proc) == this) ? current_previous : proc;
}
void HostResolverProc::SetLastProc(HostResolverProc* proc) {
GetLastProc(this)->SetPreviousProc(proc);
}
// static
HostResolverProc* HostResolverProc::GetLastProc(HostResolverProc* proc) {
if (proc == NULL)
return NULL;
HostResolverProc* last_proc = proc;
while (last_proc->previous_proc_ != NULL)
last_proc = last_proc->previous_proc_;
return last_proc;
}
// static
HostResolverProc* HostResolverProc::SetDefault(HostResolverProc* proc) {
HostResolverProc* old = default_proc_;
default_proc_ = proc;
return old;
}
// static
HostResolverProc* HostResolverProc::GetDefault() {
return default_proc_;
}
HostResolverProc::~HostResolverProc() {
}
int HostResolverProc::ResolveUsingPrevious(
const std::string& host,
AddressFamily address_family,
HostResolverFlags host_resolver_flags,
AddressList* addrlist,
int* os_error) {
if (previous_proc_) {
return previous_proc_->Resolve(host, address_family, host_resolver_flags,
addrlist, os_error);
}
// Final fallback is the system resolver.
return SystemHostResolverProc(host, address_family, host_resolver_flags,
addrlist, os_error);
}
int SystemHostResolverProc(const std::string& host,
AddressFamily address_family,
HostResolverFlags host_resolver_flags,
AddressList* addrlist,
int* os_error) {
static const size_t kMaxHostLength = 4096;
if (os_error)
*os_error = 0;
// The result of |getaddrinfo| for empty hosts is inconsistent across systems.
// On Windows it gives the default interface's address, whereas on Linux it
// gives an error. We will make it fail on all platforms for consistency.
if (host.empty())
return ERR_NAME_NOT_RESOLVED;
// Limit the size of hostnames that will be resolved to combat issues in some
// platform's resolvers.
if (host.size() > kMaxHostLength)
return ERR_NAME_NOT_RESOLVED;
struct addrinfo* ai = NULL;
struct addrinfo hints = {0};
switch (address_family) {
case ADDRESS_FAMILY_IPV4:
hints.ai_family = AF_INET;
break;
case ADDRESS_FAMILY_IPV6:
hints.ai_family = AF_INET6;
break;
case ADDRESS_FAMILY_UNSPECIFIED:
hints.ai_family = AF_UNSPEC;
break;
default:
NOTREACHED();
hints.ai_family = AF_UNSPEC;
}
#if defined(OS_WIN) || defined(OS_OPENBSD)
// DO NOT USE AI_ADDRCONFIG ON WINDOWS.
//
// The following comment in <winsock2.h> is the best documentation I found
// on AI_ADDRCONFIG for Windows:
// Flags used in "hints" argument to getaddrinfo()
// - AI_ADDRCONFIG is supported starting with Vista
// - default is AI_ADDRCONFIG ON whether the flag is set or not
// because the performance penalty in not having ADDRCONFIG in
// the multi-protocol stack environment is severe;
// this defaulting may be disabled by specifying the AI_ALL flag,
// in that case AI_ADDRCONFIG must be EXPLICITLY specified to
// enable ADDRCONFIG behavior
//
// Not only is AI_ADDRCONFIG unnecessary, but it can be harmful. If the
// computer is not connected to a network, AI_ADDRCONFIG causes getaddrinfo
// to fail with WSANO_DATA (11004) for "localhost", probably because of the
// following note on AI_ADDRCONFIG in the MSDN getaddrinfo page:
// The IPv4 or IPv6 loopback address is not considered a valid global
// address.
// See http://crbug.com/5234.
//
// OpenBSD does not support it, either.
hints.ai_flags = 0;
#else
hints.ai_flags = AI_ADDRCONFIG;
#endif
// On Linux AI_ADDRCONFIG doesn't consider loopback addreses, even if only
// loopback addresses are configured. So don't use it when there are only
// loopback addresses.
if (host_resolver_flags & HOST_RESOLVER_LOOPBACK_ONLY)
hints.ai_flags &= ~AI_ADDRCONFIG;
if (host_resolver_flags & HOST_RESOLVER_CANONNAME)
hints.ai_flags |= AI_CANONNAME;
// Restrict result set to only this socket type to avoid duplicates.
hints.ai_socktype = SOCK_STREAM;
int err = getaddrinfo(host.c_str(), NULL, &hints, &ai);
bool should_retry = false;
#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD)
// If we fail, re-initialise the resolver just in case there have been any
// changes to /etc/resolv.conf and retry. See http://crbug.com/11380 for info.
if (err && DnsReloadTimerHasExpired()) {
res_nclose(&_res);
if (!res_ninit(&_res))
should_retry = true;
}
#endif
// If the lookup was restricted (either by address family, or address
// detection), and the results where all localhost of a single family,
// maybe we should retry. There were several bugs related to these
// issues, for example http://crbug.com/42058 and http://crbug.com/49024
if ((hints.ai_family != AF_UNSPEC || hints.ai_flags & AI_ADDRCONFIG) &&
err == 0 && IsAllLocalhostOfOneFamily(ai)) {
if (host_resolver_flags & HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6) {
hints.ai_family = AF_UNSPEC;
should_retry = true;
}
if (hints.ai_flags & AI_ADDRCONFIG) {
hints.ai_flags &= ~AI_ADDRCONFIG;
should_retry = true;
}
}
if (should_retry) {
freeaddrinfo(ai);
ai = NULL;
err = getaddrinfo(host.c_str(), NULL, &hints, &ai);
}
if (err) {
if (os_error) {
#if defined(OS_WIN)
*os_error = WSAGetLastError();
#else
*os_error = err;
#endif
}
return ERR_NAME_NOT_RESOLVED;
}
addrlist->Adopt(ai);
return OK;
}
} // namespace net
<commit_msg>Don't call freeaddrinfo(NULL) to avoid crash on FreeBSD.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/base/host_resolver_proc.h"
#include "build/build_config.h"
#if defined(OS_POSIX) && !defined(OS_MACOSX)
#include <resolv.h>
#endif
#include "base/logging.h"
#include "net/base/address_list.h"
#include "net/base/dns_reload_timer.h"
#include "net/base/net_errors.h"
#include "net/base/sys_addrinfo.h"
namespace net {
namespace {
bool IsAllLocalhostOfOneFamily(const struct addrinfo* ai) {
bool saw_v4_localhost = false;
bool saw_v6_localhost = false;
for (; ai != NULL; ai = ai->ai_next) {
switch (ai->ai_family) {
case AF_INET: {
const struct sockaddr_in* addr_in =
reinterpret_cast<struct sockaddr_in*>(ai->ai_addr);
if ((ntohl(addr_in->sin_addr.s_addr) & 0xff000000) == 0x7f000000)
saw_v4_localhost = true;
else
return false;
break;
}
case AF_INET6: {
const struct sockaddr_in6* addr_in6 =
reinterpret_cast<struct sockaddr_in6*>(ai->ai_addr);
if (IN6_IS_ADDR_LOOPBACK(&addr_in6->sin6_addr))
saw_v6_localhost = true;
else
return false;
break;
}
default:
NOTREACHED();
return false;
}
}
return saw_v4_localhost != saw_v6_localhost;
}
} // namespace
HostResolverProc* HostResolverProc::default_proc_ = NULL;
HostResolverProc::HostResolverProc(HostResolverProc* previous) {
SetPreviousProc(previous);
// Implicitly fall-back to the global default procedure.
if (!previous)
SetPreviousProc(default_proc_);
}
void HostResolverProc::SetPreviousProc(HostResolverProc* proc) {
HostResolverProc* current_previous = previous_proc_;
previous_proc_ = NULL;
// Now that we've guaranteed |this| is the last proc in a chain, we can
// detect potential cycles using GetLastProc().
previous_proc_ = (GetLastProc(proc) == this) ? current_previous : proc;
}
void HostResolverProc::SetLastProc(HostResolverProc* proc) {
GetLastProc(this)->SetPreviousProc(proc);
}
// static
HostResolverProc* HostResolverProc::GetLastProc(HostResolverProc* proc) {
if (proc == NULL)
return NULL;
HostResolverProc* last_proc = proc;
while (last_proc->previous_proc_ != NULL)
last_proc = last_proc->previous_proc_;
return last_proc;
}
// static
HostResolverProc* HostResolverProc::SetDefault(HostResolverProc* proc) {
HostResolverProc* old = default_proc_;
default_proc_ = proc;
return old;
}
// static
HostResolverProc* HostResolverProc::GetDefault() {
return default_proc_;
}
HostResolverProc::~HostResolverProc() {
}
int HostResolverProc::ResolveUsingPrevious(
const std::string& host,
AddressFamily address_family,
HostResolverFlags host_resolver_flags,
AddressList* addrlist,
int* os_error) {
if (previous_proc_) {
return previous_proc_->Resolve(host, address_family, host_resolver_flags,
addrlist, os_error);
}
// Final fallback is the system resolver.
return SystemHostResolverProc(host, address_family, host_resolver_flags,
addrlist, os_error);
}
int SystemHostResolverProc(const std::string& host,
AddressFamily address_family,
HostResolverFlags host_resolver_flags,
AddressList* addrlist,
int* os_error) {
static const size_t kMaxHostLength = 4096;
if (os_error)
*os_error = 0;
// The result of |getaddrinfo| for empty hosts is inconsistent across systems.
// On Windows it gives the default interface's address, whereas on Linux it
// gives an error. We will make it fail on all platforms for consistency.
if (host.empty())
return ERR_NAME_NOT_RESOLVED;
// Limit the size of hostnames that will be resolved to combat issues in some
// platform's resolvers.
if (host.size() > kMaxHostLength)
return ERR_NAME_NOT_RESOLVED;
struct addrinfo* ai = NULL;
struct addrinfo hints = {0};
switch (address_family) {
case ADDRESS_FAMILY_IPV4:
hints.ai_family = AF_INET;
break;
case ADDRESS_FAMILY_IPV6:
hints.ai_family = AF_INET6;
break;
case ADDRESS_FAMILY_UNSPECIFIED:
hints.ai_family = AF_UNSPEC;
break;
default:
NOTREACHED();
hints.ai_family = AF_UNSPEC;
}
#if defined(OS_WIN) || defined(OS_OPENBSD)
// DO NOT USE AI_ADDRCONFIG ON WINDOWS.
//
// The following comment in <winsock2.h> is the best documentation I found
// on AI_ADDRCONFIG for Windows:
// Flags used in "hints" argument to getaddrinfo()
// - AI_ADDRCONFIG is supported starting with Vista
// - default is AI_ADDRCONFIG ON whether the flag is set or not
// because the performance penalty in not having ADDRCONFIG in
// the multi-protocol stack environment is severe;
// this defaulting may be disabled by specifying the AI_ALL flag,
// in that case AI_ADDRCONFIG must be EXPLICITLY specified to
// enable ADDRCONFIG behavior
//
// Not only is AI_ADDRCONFIG unnecessary, but it can be harmful. If the
// computer is not connected to a network, AI_ADDRCONFIG causes getaddrinfo
// to fail with WSANO_DATA (11004) for "localhost", probably because of the
// following note on AI_ADDRCONFIG in the MSDN getaddrinfo page:
// The IPv4 or IPv6 loopback address is not considered a valid global
// address.
// See http://crbug.com/5234.
//
// OpenBSD does not support it, either.
hints.ai_flags = 0;
#else
hints.ai_flags = AI_ADDRCONFIG;
#endif
// On Linux AI_ADDRCONFIG doesn't consider loopback addreses, even if only
// loopback addresses are configured. So don't use it when there are only
// loopback addresses.
if (host_resolver_flags & HOST_RESOLVER_LOOPBACK_ONLY)
hints.ai_flags &= ~AI_ADDRCONFIG;
if (host_resolver_flags & HOST_RESOLVER_CANONNAME)
hints.ai_flags |= AI_CANONNAME;
// Restrict result set to only this socket type to avoid duplicates.
hints.ai_socktype = SOCK_STREAM;
int err = getaddrinfo(host.c_str(), NULL, &hints, &ai);
bool should_retry = false;
#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD)
// If we fail, re-initialise the resolver just in case there have been any
// changes to /etc/resolv.conf and retry. See http://crbug.com/11380 for info.
if (err && DnsReloadTimerHasExpired()) {
res_nclose(&_res);
if (!res_ninit(&_res))
should_retry = true;
}
#endif
// If the lookup was restricted (either by address family, or address
// detection), and the results where all localhost of a single family,
// maybe we should retry. There were several bugs related to these
// issues, for example http://crbug.com/42058 and http://crbug.com/49024
if ((hints.ai_family != AF_UNSPEC || hints.ai_flags & AI_ADDRCONFIG) &&
err == 0 && IsAllLocalhostOfOneFamily(ai)) {
if (host_resolver_flags & HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6) {
hints.ai_family = AF_UNSPEC;
should_retry = true;
}
if (hints.ai_flags & AI_ADDRCONFIG) {
hints.ai_flags &= ~AI_ADDRCONFIG;
should_retry = true;
}
}
if (should_retry) {
if (ai != NULL) {
freeaddrinfo(ai);
ai = NULL;
}
err = getaddrinfo(host.c_str(), NULL, &hints, &ai);
}
if (err) {
if (os_error) {
#if defined(OS_WIN)
*os_error = WSAGetLastError();
#else
*os_error = err;
#endif
}
return ERR_NAME_NOT_RESOLVED;
}
addrlist->Adopt(ai);
return OK;
}
} // namespace net
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/base/host_resolver_proc.h"
#include "build/build_config.h"
#if defined(OS_POSIX) && !defined(OS_MACOSX)
#include <resolv.h>
#endif
#include "base/logging.h"
#include "net/base/address_list.h"
#include "net/base/dns_reload_timer.h"
#include "net/base/net_errors.h"
#include "net/base/sys_addrinfo.h"
namespace net {
namespace {
bool IsAllLocalhostOfOneFamily(const struct addrinfo* ai) {
bool saw_v4_localhost = false;
bool saw_v6_localhost = false;
for (; ai != NULL; ai = ai->ai_next) {
switch (ai->ai_family) {
case AF_INET: {
const struct sockaddr_in* addr_in =
reinterpret_cast<struct sockaddr_in*>(ai->ai_addr);
if ((ntohl(addr_in->sin_addr.s_addr) & 0xff000000) == 0x7f000000)
saw_v4_localhost = true;
else
return false;
break;
}
case AF_INET6: {
const struct sockaddr_in6* addr_in6 =
reinterpret_cast<struct sockaddr_in6*>(ai->ai_addr);
if (IN6_IS_ADDR_LOOPBACK(&addr_in6->sin6_addr))
saw_v6_localhost = true;
else
return false;
break;
}
default:
NOTREACHED();
return false;
}
}
return saw_v4_localhost != saw_v6_localhost;
}
} // namespace
HostResolverProc* HostResolverProc::default_proc_ = NULL;
HostResolverProc::HostResolverProc(HostResolverProc* previous) {
SetPreviousProc(previous);
// Implicitly fall-back to the global default procedure.
if (!previous)
SetPreviousProc(default_proc_);
}
void HostResolverProc::SetPreviousProc(HostResolverProc* proc) {
HostResolverProc* current_previous = previous_proc_;
previous_proc_ = NULL;
// Now that we've guaranteed |this| is the last proc in a chain, we can
// detect potential cycles using GetLastProc().
previous_proc_ = (GetLastProc(proc) == this) ? current_previous : proc;
}
void HostResolverProc::SetLastProc(HostResolverProc* proc) {
GetLastProc(this)->SetPreviousProc(proc);
}
// static
HostResolverProc* HostResolverProc::GetLastProc(HostResolverProc* proc) {
if (proc == NULL)
return NULL;
HostResolverProc* last_proc = proc;
while (last_proc->previous_proc_ != NULL)
last_proc = last_proc->previous_proc_;
return last_proc;
}
// static
HostResolverProc* HostResolverProc::SetDefault(HostResolverProc* proc) {
HostResolverProc* old = default_proc_;
default_proc_ = proc;
return old;
}
// static
HostResolverProc* HostResolverProc::GetDefault() {
return default_proc_;
}
HostResolverProc::~HostResolverProc() {
}
int HostResolverProc::ResolveUsingPrevious(
const std::string& host,
AddressFamily address_family,
HostResolverFlags host_resolver_flags,
AddressList* addrlist,
int* os_error) {
if (previous_proc_) {
return previous_proc_->Resolve(host, address_family, host_resolver_flags,
addrlist, os_error);
}
// Final fallback is the system resolver.
return SystemHostResolverProc(host, address_family, host_resolver_flags,
addrlist, os_error);
}
int SystemHostResolverProc(const std::string& host,
AddressFamily address_family,
HostResolverFlags host_resolver_flags,
AddressList* addrlist,
int* os_error) {
static const size_t kMaxHostLength = 4096;
if (os_error)
*os_error = 0;
// The result of |getaddrinfo| for empty hosts is inconsistent across systems.
// On Windows it gives the default interface's address, whereas on Linux it
// gives an error. We will make it fail on all platforms for consistency.
if (host.empty())
return ERR_NAME_NOT_RESOLVED;
// Limit the size of hostnames that will be resolved to combat issues in some
// platform's resolvers.
if (host.size() > kMaxHostLength)
return ERR_NAME_NOT_RESOLVED;
struct addrinfo* ai = NULL;
struct addrinfo hints = {0};
switch (address_family) {
case ADDRESS_FAMILY_IPV4:
hints.ai_family = AF_INET;
break;
case ADDRESS_FAMILY_IPV6:
hints.ai_family = AF_INET6;
break;
case ADDRESS_FAMILY_UNSPECIFIED:
hints.ai_family = AF_UNSPEC;
break;
default:
NOTREACHED();
hints.ai_family = AF_UNSPEC;
}
#if defined(OS_WIN) || defined(OS_OPENBSD)
// DO NOT USE AI_ADDRCONFIG ON WINDOWS.
//
// The following comment in <winsock2.h> is the best documentation I found
// on AI_ADDRCONFIG for Windows:
// Flags used in "hints" argument to getaddrinfo()
// - AI_ADDRCONFIG is supported starting with Vista
// - default is AI_ADDRCONFIG ON whether the flag is set or not
// because the performance penalty in not having ADDRCONFIG in
// the multi-protocol stack environment is severe;
// this defaulting may be disabled by specifying the AI_ALL flag,
// in that case AI_ADDRCONFIG must be EXPLICITLY specified to
// enable ADDRCONFIG behavior
//
// Not only is AI_ADDRCONFIG unnecessary, but it can be harmful. If the
// computer is not connected to a network, AI_ADDRCONFIG causes getaddrinfo
// to fail with WSANO_DATA (11004) for "localhost", probably because of the
// following note on AI_ADDRCONFIG in the MSDN getaddrinfo page:
// The IPv4 or IPv6 loopback address is not considered a valid global
// address.
// See http://crbug.com/5234.
//
// OpenBSD does not support it, either.
hints.ai_flags = 0;
#else
hints.ai_flags = AI_ADDRCONFIG;
#endif
// On Linux AI_ADDRCONFIG doesn't consider loopback addreses, even if only
// loopback addresses are configured. So don't use it when there are only
// loopback addresses.
if (host_resolver_flags & HOST_RESOLVER_LOOPBACK_ONLY)
hints.ai_flags &= ~AI_ADDRCONFIG;
if (host_resolver_flags & HOST_RESOLVER_CANONNAME)
hints.ai_flags |= AI_CANONNAME;
// Restrict result set to only this socket type to avoid duplicates.
hints.ai_socktype = SOCK_STREAM;
int err = getaddrinfo(host.c_str(), NULL, &hints, &ai);
bool should_retry = false;
#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD)
// If we fail, re-initialise the resolver just in case there have been any
// changes to /etc/resolv.conf and retry. See http://crbug.com/11380 for info.
if (err && DnsReloadTimerHasExpired()) {
res_nclose(&_res);
if (!res_ninit(&_res))
should_retry = true;
}
#endif
// If the lookup was restricted (either by address family, or address
// detection), and the results where all localhost of a single family,
// maybe we should retry. There were several bugs related to these
// issues, for example http://crbug.com/42058 and http://crbug.com/49024
if ((hints.ai_family != AF_UNSPEC || hints.ai_flags & AI_ADDRCONFIG) &&
err == 0 && IsAllLocalhostOfOneFamily(ai)) {
if (host_resolver_flags & HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6) {
hints.ai_family = AF_UNSPEC;
should_retry = true;
}
if (hints.ai_flags & AI_ADDRCONFIG) {
hints.ai_flags &= ~AI_ADDRCONFIG;
should_retry = true;
}
}
if (should_retry) {
freeaddrinfo(ai);
ai = NULL;
err = getaddrinfo(host.c_str(), NULL, &hints, &ai);
}
if (err) {
if (os_error) {
#if defined(OS_WIN)
*os_error = WSAGetLastError();
#else
*os_error = err;
#endif
}
return ERR_NAME_NOT_RESOLVED;
}
addrlist->Adopt(ai);
return OK;
}
} // namespace net
<commit_msg>Don't call freeaddrinfo(NULL) to avoid crash on FreeBSD.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/base/host_resolver_proc.h"
#include "build/build_config.h"
#if defined(OS_POSIX) && !defined(OS_MACOSX)
#include <resolv.h>
#endif
#include "base/logging.h"
#include "net/base/address_list.h"
#include "net/base/dns_reload_timer.h"
#include "net/base/net_errors.h"
#include "net/base/sys_addrinfo.h"
namespace net {
namespace {
bool IsAllLocalhostOfOneFamily(const struct addrinfo* ai) {
bool saw_v4_localhost = false;
bool saw_v6_localhost = false;
for (; ai != NULL; ai = ai->ai_next) {
switch (ai->ai_family) {
case AF_INET: {
const struct sockaddr_in* addr_in =
reinterpret_cast<struct sockaddr_in*>(ai->ai_addr);
if ((ntohl(addr_in->sin_addr.s_addr) & 0xff000000) == 0x7f000000)
saw_v4_localhost = true;
else
return false;
break;
}
case AF_INET6: {
const struct sockaddr_in6* addr_in6 =
reinterpret_cast<struct sockaddr_in6*>(ai->ai_addr);
if (IN6_IS_ADDR_LOOPBACK(&addr_in6->sin6_addr))
saw_v6_localhost = true;
else
return false;
break;
}
default:
NOTREACHED();
return false;
}
}
return saw_v4_localhost != saw_v6_localhost;
}
} // namespace
HostResolverProc* HostResolverProc::default_proc_ = NULL;
HostResolverProc::HostResolverProc(HostResolverProc* previous) {
SetPreviousProc(previous);
// Implicitly fall-back to the global default procedure.
if (!previous)
SetPreviousProc(default_proc_);
}
void HostResolverProc::SetPreviousProc(HostResolverProc* proc) {
HostResolverProc* current_previous = previous_proc_;
previous_proc_ = NULL;
// Now that we've guaranteed |this| is the last proc in a chain, we can
// detect potential cycles using GetLastProc().
previous_proc_ = (GetLastProc(proc) == this) ? current_previous : proc;
}
void HostResolverProc::SetLastProc(HostResolverProc* proc) {
GetLastProc(this)->SetPreviousProc(proc);
}
// static
HostResolverProc* HostResolverProc::GetLastProc(HostResolverProc* proc) {
if (proc == NULL)
return NULL;
HostResolverProc* last_proc = proc;
while (last_proc->previous_proc_ != NULL)
last_proc = last_proc->previous_proc_;
return last_proc;
}
// static
HostResolverProc* HostResolverProc::SetDefault(HostResolverProc* proc) {
HostResolverProc* old = default_proc_;
default_proc_ = proc;
return old;
}
// static
HostResolverProc* HostResolverProc::GetDefault() {
return default_proc_;
}
HostResolverProc::~HostResolverProc() {
}
int HostResolverProc::ResolveUsingPrevious(
const std::string& host,
AddressFamily address_family,
HostResolverFlags host_resolver_flags,
AddressList* addrlist,
int* os_error) {
if (previous_proc_) {
return previous_proc_->Resolve(host, address_family, host_resolver_flags,
addrlist, os_error);
}
// Final fallback is the system resolver.
return SystemHostResolverProc(host, address_family, host_resolver_flags,
addrlist, os_error);
}
int SystemHostResolverProc(const std::string& host,
AddressFamily address_family,
HostResolverFlags host_resolver_flags,
AddressList* addrlist,
int* os_error) {
static const size_t kMaxHostLength = 4096;
if (os_error)
*os_error = 0;
// The result of |getaddrinfo| for empty hosts is inconsistent across systems.
// On Windows it gives the default interface's address, whereas on Linux it
// gives an error. We will make it fail on all platforms for consistency.
if (host.empty())
return ERR_NAME_NOT_RESOLVED;
// Limit the size of hostnames that will be resolved to combat issues in some
// platform's resolvers.
if (host.size() > kMaxHostLength)
return ERR_NAME_NOT_RESOLVED;
struct addrinfo* ai = NULL;
struct addrinfo hints = {0};
switch (address_family) {
case ADDRESS_FAMILY_IPV4:
hints.ai_family = AF_INET;
break;
case ADDRESS_FAMILY_IPV6:
hints.ai_family = AF_INET6;
break;
case ADDRESS_FAMILY_UNSPECIFIED:
hints.ai_family = AF_UNSPEC;
break;
default:
NOTREACHED();
hints.ai_family = AF_UNSPEC;
}
#if defined(OS_WIN) || defined(OS_OPENBSD)
// DO NOT USE AI_ADDRCONFIG ON WINDOWS.
//
// The following comment in <winsock2.h> is the best documentation I found
// on AI_ADDRCONFIG for Windows:
// Flags used in "hints" argument to getaddrinfo()
// - AI_ADDRCONFIG is supported starting with Vista
// - default is AI_ADDRCONFIG ON whether the flag is set or not
// because the performance penalty in not having ADDRCONFIG in
// the multi-protocol stack environment is severe;
// this defaulting may be disabled by specifying the AI_ALL flag,
// in that case AI_ADDRCONFIG must be EXPLICITLY specified to
// enable ADDRCONFIG behavior
//
// Not only is AI_ADDRCONFIG unnecessary, but it can be harmful. If the
// computer is not connected to a network, AI_ADDRCONFIG causes getaddrinfo
// to fail with WSANO_DATA (11004) for "localhost", probably because of the
// following note on AI_ADDRCONFIG in the MSDN getaddrinfo page:
// The IPv4 or IPv6 loopback address is not considered a valid global
// address.
// See http://crbug.com/5234.
//
// OpenBSD does not support it, either.
hints.ai_flags = 0;
#else
hints.ai_flags = AI_ADDRCONFIG;
#endif
// On Linux AI_ADDRCONFIG doesn't consider loopback addreses, even if only
// loopback addresses are configured. So don't use it when there are only
// loopback addresses.
if (host_resolver_flags & HOST_RESOLVER_LOOPBACK_ONLY)
hints.ai_flags &= ~AI_ADDRCONFIG;
if (host_resolver_flags & HOST_RESOLVER_CANONNAME)
hints.ai_flags |= AI_CANONNAME;
// Restrict result set to only this socket type to avoid duplicates.
hints.ai_socktype = SOCK_STREAM;
int err = getaddrinfo(host.c_str(), NULL, &hints, &ai);
bool should_retry = false;
#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD)
// If we fail, re-initialise the resolver just in case there have been any
// changes to /etc/resolv.conf and retry. See http://crbug.com/11380 for info.
if (err && DnsReloadTimerHasExpired()) {
res_nclose(&_res);
if (!res_ninit(&_res))
should_retry = true;
}
#endif
// If the lookup was restricted (either by address family, or address
// detection), and the results where all localhost of a single family,
// maybe we should retry. There were several bugs related to these
// issues, for example http://crbug.com/42058 and http://crbug.com/49024
if ((hints.ai_family != AF_UNSPEC || hints.ai_flags & AI_ADDRCONFIG) &&
err == 0 && IsAllLocalhostOfOneFamily(ai)) {
if (host_resolver_flags & HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6) {
hints.ai_family = AF_UNSPEC;
should_retry = true;
}
if (hints.ai_flags & AI_ADDRCONFIG) {
hints.ai_flags &= ~AI_ADDRCONFIG;
should_retry = true;
}
}
if (should_retry) {
if (ai != NULL) {
freeaddrinfo(ai);
ai = NULL;
}
err = getaddrinfo(host.c_str(), NULL, &hints, &ai);
}
if (err) {
if (os_error) {
#if defined(OS_WIN)
*os_error = WSAGetLastError();
#else
*os_error = err;
#endif
}
return ERR_NAME_NOT_RESOLVED;
}
addrlist->Adopt(ai);
return OK;
}
} // namespace net
<|endoftext|> |
<commit_before>//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
//-------------------------------------
//
// Icon Button Control
// Draws the bitmap within a special button control. Only a single bitmap is used and the
// button will be drawn in a highlighted mode when the mouse hovers over it or when it
// has been clicked.
//
// Use mTextLocation to choose where within the button the text will be drawn, if at all.
// Use mTextMargin to set the text away from the button sides or from the bitmap.
// Use mButtonMargin to set everything away from the button sides.
// Use mErrorBitmapName to set the name of a bitmap to draw if the main bitmap cannot be found.
// Use mFitBitmapToButton to force the bitmap to fill the entire button extent. Usually used
// with no button text defined.
//
//
#include "platform/platform.h"
#include "gui/buttons/guiIconButtonCtrl.h"
#include "console/console.h"
#include "gfx/gfxDevice.h"
#include "gfx/gfxDrawUtil.h"
#include "console/consoleTypes.h"
#include "gui/core/guiCanvas.h"
#include "gui/core/guiDefaultControlRender.h"
#include "console/engineAPI.h"
static const ColorI colorWhite(255,255,255);
static const ColorI colorBlack(0,0,0);
IMPLEMENT_CONOBJECT(GuiIconButtonCtrl);
ConsoleDocClass( GuiIconButtonCtrl,
"@brief Draws the bitmap within a special button control. Only a single bitmap is used and the\n"
"button will be drawn in a highlighted mode when the mouse hovers over it or when it\n"
"has been clicked.\n\n"
"@tsexample\n"
"new GuiIconButtonCtrl(TestIconButton)\n"
"{\n"
" buttonMargin = \"4 4\";\n"
" iconBitmap = \"art/gui/lagIcon.png\";\n"
" iconLocation = \"Center\";\n"
" sizeIconToButton = \"0\";\n"
" makeIconSquare = \"1\";\n"
" textLocation = \"Bottom\";\n"
" textMargin = \"-2\";\n"
" autoSize = \"0\";\n"
" text = \"Lag Icon\";\n"
" textID = \"\"STR_LAG\"\";\n"
" buttonType = \"PushButton\";\n"
" profile = \"GuiIconButtonProfile\";\n"
"};\n"
"@endtsexample\n\n"
"@see GuiControl\n"
"@see GuiButtonCtrl\n\n"
"@ingroup GuiCore\n"
);
GuiIconButtonCtrl::GuiIconButtonCtrl()
{
mBitmapName = StringTable->EmptyString();
mTextLocation = TextLocLeft;
mIconLocation = IconLocLeft;
mTextMargin = 4;
mButtonMargin.set(4,4);
mFitBitmapToButton = false;
mMakeIconSquare = false;
mErrorBitmapName = StringTable->EmptyString();
mErrorTextureHandle = NULL;
mAutoSize = false;
setExtent(140, 30);
}
ImplementEnumType( GuiIconButtonTextLocation,
"\n\n"
"@ingroup GuiImages" )
{ GuiIconButtonCtrl::TextLocNone, "None" },
{ GuiIconButtonCtrl::TextLocBottom, "Bottom" },
{ GuiIconButtonCtrl::TextLocRight, "Right" },
{ GuiIconButtonCtrl::TextLocTop, "Top" },
{ GuiIconButtonCtrl::TextLocLeft, "Left" },
{ GuiIconButtonCtrl::TextLocCenter, "Center" },
EndImplementEnumType;
ImplementEnumType( GuiIconButtonIconLocation,
"\n\n"
"@ingroup GuiImages" )
{ GuiIconButtonCtrl::IconLocNone, "None" },
{ GuiIconButtonCtrl::IconLocLeft, "Left" },
{ GuiIconButtonCtrl::IconLocRight, "Right" },
{ GuiIconButtonCtrl::IconLocCenter, "Center" }
EndImplementEnumType;
void GuiIconButtonCtrl::initPersistFields()
{
addField( "buttonMargin", TypePoint2I, Offset( mButtonMargin, GuiIconButtonCtrl ),"Margin area around the button.\n");
addField( "iconBitmap", TypeFilename, Offset( mBitmapName, GuiIconButtonCtrl ),"Bitmap file for the icon to display on the button.\n");
addField( "iconLocation", TYPEID< IconLocation >(), Offset( mIconLocation, GuiIconButtonCtrl ),"Where to place the icon on the control. Options are 0 (None), 1 (Left), 2 (Right), 3 (Center).\n");
addField( "sizeIconToButton", TypeBool, Offset( mFitBitmapToButton, GuiIconButtonCtrl ),"If true, the icon will be scaled to be the same size as the button.\n");
addField( "makeIconSquare", TypeBool, Offset( mMakeIconSquare, GuiIconButtonCtrl ),"If true, will make sure the icon is square.\n");
addField( "textLocation", TYPEID< TextLocation >(), Offset( mTextLocation, GuiIconButtonCtrl ),"Where to place the text on the control.\n"
"Options are 0 (None), 1 (Bottom), 2 (Right), 3 (Top), 4 (Left), 5 (Center).\n");
addField( "textMargin", TypeS32, Offset( mTextMargin, GuiIconButtonCtrl ),"Margin between the icon and the text.\n");
addField( "autoSize", TypeBool, Offset( mAutoSize, GuiIconButtonCtrl ),"If true, the text and icon will be automatically sized to the size of the control.\n");
Parent::initPersistFields();
}
bool GuiIconButtonCtrl::onWake()
{
if (! Parent::onWake())
return false;
setActive(true);
setBitmap(mBitmapName);
if( mProfile )
mProfile->constructBitmapArray();
return true;
}
void GuiIconButtonCtrl::onSleep()
{
mTextureNormal = NULL;
Parent::onSleep();
}
void GuiIconButtonCtrl::inspectPostApply()
{
Parent::inspectPostApply();
}
void GuiIconButtonCtrl::onStaticModified(const char* slotName, const char* newValue)
{
if ( isProperlyAdded() && !dStricmp(slotName, "autoSize") )
resize( getPosition(), getExtent() );
}
bool GuiIconButtonCtrl::resize(const Point2I &newPosition, const Point2I &newExtent)
{
if ( !mAutoSize || !mProfile->mFont )
return Parent::resize( newPosition, newExtent );
Point2I autoExtent( mMinExtent );
if ( mIconLocation != IconLocNone )
{
autoExtent.y = mTextureNormal.getHeight() + mButtonMargin.y * 2;
autoExtent.x = mTextureNormal.getWidth() + mButtonMargin.x * 2;
}
if ( mTextLocation != TextLocNone && mButtonText && mButtonText[0] )
{
U32 strWidth = mProfile->mFont->getStrWidthPrecise( mButtonText );
if ( mTextLocation == TextLocLeft || mTextLocation == TextLocRight )
{
autoExtent.x += strWidth + mTextMargin * 2;
}
else // Top, Bottom, Center
{
strWidth += mTextMargin * 2;
if ( strWidth > autoExtent.x )
autoExtent.x = strWidth;
}
}
return Parent::resize( newPosition, autoExtent );
}
void GuiIconButtonCtrl::setBitmap(const char *name)
{
mBitmapName = StringTable->insert(name);
if(!isAwake())
return;
if (*mBitmapName)
{
mTextureNormal = GFXTexHandle( name, &GFXTexturePersistentSRGBProfile, avar("%s() - mTextureNormal (line %d)", __FUNCTION__, __LINE__) );
}
else
{
mTextureNormal = NULL;
}
// So that extent is recalculated if autoSize is set.
resize( getPosition(), getExtent() );
setUpdate();
}
void GuiIconButtonCtrl::onRender(Point2I offset, const RectI& updateRect)
{
renderButton( offset, updateRect);
}
void GuiIconButtonCtrl::renderButton( Point2I &offset, const RectI& updateRect )
{
bool highlight = mMouseOver;
bool depressed = mDepressed;
ColorI fontColor = mActive ? (highlight ? mProfile->mFontColorHL : mProfile->mFontColor) : mProfile->mFontColorNA;
RectI boundsRect(offset, getExtent());
GFXDrawUtil *drawer = GFX->getDrawUtil();
if (mDepressed || mStateOn)
{
// If there is a bitmap array then render using it.
// Otherwise use a standard fill.
if(mProfile->mUseBitmapArray && mProfile->mBitmapArrayRects.size())
renderBitmapArray(boundsRect, statePressed);
else
renderSlightlyLoweredBox(boundsRect, mProfile);
}
else if(mMouseOver && mActive)
{
// If there is a bitmap array then render using it.
// Otherwise use a standard fill.
if(mProfile->mUseBitmapArray && mProfile->mBitmapArrayRects.size())
renderBitmapArray(boundsRect, stateMouseOver);
else
renderSlightlyRaisedBox(boundsRect, mProfile);
}
else
{
// If there is a bitmap array then render using it.
// Otherwise use a standard fill.
if(mProfile->mUseBitmapArray && mProfile->mBitmapArrayRects.size())
{
if(mActive)
renderBitmapArray(boundsRect, stateNormal);
else
renderBitmapArray(boundsRect, stateDisabled);
}
else
{
drawer->drawRectFill(boundsRect, mProfile->mFillColorNA);
drawer->drawRect(boundsRect, mProfile->mBorderColorNA);
}
}
Point2I textPos = offset;
if(depressed)
textPos += Point2I(1,1);
RectI iconRect( 0, 0, 0, 0 );
// Render the icon
if ( mTextureNormal && mIconLocation != GuiIconButtonCtrl::IconLocNone )
{
// Render the normal bitmap
drawer->clearBitmapModulation();
// Maintain the bitmap size or fill the button?
if ( !mFitBitmapToButton )
{
Point2I textureSize( mTextureNormal->getWidth(), mTextureNormal->getHeight() );
iconRect.set( offset + mButtonMargin, textureSize );
if ( mIconLocation == IconLocRight )
{
iconRect.point.x = ( offset.x + getWidth() ) - ( mButtonMargin.x + textureSize.x );
iconRect.point.y = offset.y + ( getHeight() - textureSize.y ) / 2;
}
else if ( mIconLocation == IconLocLeft )
{
iconRect.point.x = offset.x + mButtonMargin.x;
iconRect.point.y = offset.y + ( getHeight() - textureSize.y ) / 2;
}
else if ( mIconLocation == IconLocCenter )
{
iconRect.point.x = offset.x + ( getWidth() - textureSize.x ) / 2;
iconRect.point.y = offset.y + ( getHeight() - textureSize.y ) / 2;
}
drawer->drawBitmapStretch( mTextureNormal, iconRect );
}
else
{
iconRect.set( offset + mButtonMargin, getExtent() - (mButtonMargin * 2) );
if ( mMakeIconSquare )
{
// Square the icon to the smaller axis extent.
if ( iconRect.extent.x < iconRect.extent.y )
iconRect.extent.y = iconRect.extent.x;
else
iconRect.extent.x = iconRect.extent.y;
}
drawer->drawBitmapStretch( mTextureNormal, iconRect );
}
}
// Render text
if ( mTextLocation != TextLocNone )
{
// Clip text to fit (appends ...),
// pad some space to keep it off our border
String text( mButtonText );
S32 textWidth = clipText( text, getWidth() - 4 - mTextMargin );
drawer->setBitmapModulation( fontColor );
if ( mTextLocation == TextLocRight )
{
Point2I start( mTextMargin, ( getHeight() - mProfile->mFont->getHeight() ) / 2 );
if ( mTextureNormal && mIconLocation != IconLocNone )
{
start.x = iconRect.extent.x + mButtonMargin.x + mTextMargin;
}
drawer->drawText( mProfile->mFont, start + offset, text, mProfile->mFontColors );
}
if ( mTextLocation == TextLocLeft )
{
Point2I start( mTextMargin, ( getHeight() - mProfile->mFont->getHeight() ) / 2 );
drawer->drawText( mProfile->mFont, start + offset, text, mProfile->mFontColors );
}
if ( mTextLocation == TextLocCenter )
{
Point2I start;
if ( mTextureNormal && mIconLocation == IconLocLeft )
{
start.set( ( getWidth() - textWidth - iconRect.extent.x ) / 2 + iconRect.extent.x,
( getHeight() - mProfile->mFont->getHeight() ) / 2 );
}
else
start.set( ( getWidth() - textWidth ) / 2, ( getHeight() - mProfile->mFont->getHeight() ) / 2 );
drawer->setBitmapModulation( fontColor );
drawer->drawText( mProfile->mFont, start + offset, text, mProfile->mFontColors );
}
if ( mTextLocation == TextLocBottom )
{
Point2I start;
start.set( ( getWidth() - textWidth ) / 2, getHeight() - mProfile->mFont->getHeight() - mTextMargin );
// If the text is longer then the box size
// it will get clipped, force Left Justify
if( textWidth > getWidth() )
start.x = 0;
drawer->setBitmapModulation( fontColor );
drawer->drawText( mProfile->mFont, start + offset, text, mProfile->mFontColors );
}
}
renderChildControls( offset, updateRect);
}
// Draw the bitmap array's borders according to the button's state.
void GuiIconButtonCtrl::renderBitmapArray(RectI &bounds, S32 state)
{
switch(state)
{
case stateNormal:
if(mProfile->mBorder == -2)
renderSizableBitmapBordersFilled(bounds, 1, mProfile);
else
renderFixedBitmapBordersFilled(bounds, 1, mProfile);
break;
case stateMouseOver:
if(mProfile->mBorder == -2)
renderSizableBitmapBordersFilled(bounds, 2, mProfile);
else
renderFixedBitmapBordersFilled(bounds, 2, mProfile);
break;
case statePressed:
if(mProfile->mBorder == -2)
renderSizableBitmapBordersFilled(bounds, 3, mProfile);
else
renderFixedBitmapBordersFilled(bounds, 3, mProfile);
break;
case stateDisabled:
if(mProfile->mBorder == -2)
renderSizableBitmapBordersFilled(bounds, 4, mProfile);
else
renderFixedBitmapBordersFilled(bounds, 4, mProfile);
break;
}
}
DefineEngineMethod( GuiIconButtonCtrl, setBitmap, void, (const char* buttonFilename),,
"@brief Set the bitmap to use for the button portion of this control.\n\n"
"@param buttonFilename Filename for the image\n"
"@tsexample\n"
"// Define the button filename\n"
"%buttonFilename = \"pearlButton\";\n\n"
"// Inform the GuiIconButtonCtrl control to update its main button graphic to the defined bitmap\n"
"%thisGuiIconButtonCtrl.setBitmap(%buttonFilename);\n"
"@endtsexample\n\n"
"@see GuiControl\n"
"@see GuiButtonCtrl\n\n")
{
char* argBuffer = Con::getArgBuffer( 512 );
Platform::makeFullPathName( buttonFilename, argBuffer, 512 );
object->setBitmap( argBuffer );
}
<commit_msg>Changes GuiIconButtonCtrl to relative paths that can be opened by the mount system.<commit_after>//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
//-------------------------------------
//
// Icon Button Control
// Draws the bitmap within a special button control. Only a single bitmap is used and the
// button will be drawn in a highlighted mode when the mouse hovers over it or when it
// has been clicked.
//
// Use mTextLocation to choose where within the button the text will be drawn, if at all.
// Use mTextMargin to set the text away from the button sides or from the bitmap.
// Use mButtonMargin to set everything away from the button sides.
// Use mErrorBitmapName to set the name of a bitmap to draw if the main bitmap cannot be found.
// Use mFitBitmapToButton to force the bitmap to fill the entire button extent. Usually used
// with no button text defined.
//
//
#include "platform/platform.h"
#include "gui/buttons/guiIconButtonCtrl.h"
#include "console/console.h"
#include "gfx/gfxDevice.h"
#include "gfx/gfxDrawUtil.h"
#include "console/consoleTypes.h"
#include "gui/core/guiCanvas.h"
#include "gui/core/guiDefaultControlRender.h"
#include "console/engineAPI.h"
static const ColorI colorWhite(255,255,255);
static const ColorI colorBlack(0,0,0);
IMPLEMENT_CONOBJECT(GuiIconButtonCtrl);
ConsoleDocClass( GuiIconButtonCtrl,
"@brief Draws the bitmap within a special button control. Only a single bitmap is used and the\n"
"button will be drawn in a highlighted mode when the mouse hovers over it or when it\n"
"has been clicked.\n\n"
"@tsexample\n"
"new GuiIconButtonCtrl(TestIconButton)\n"
"{\n"
" buttonMargin = \"4 4\";\n"
" iconBitmap = \"art/gui/lagIcon.png\";\n"
" iconLocation = \"Center\";\n"
" sizeIconToButton = \"0\";\n"
" makeIconSquare = \"1\";\n"
" textLocation = \"Bottom\";\n"
" textMargin = \"-2\";\n"
" autoSize = \"0\";\n"
" text = \"Lag Icon\";\n"
" textID = \"\"STR_LAG\"\";\n"
" buttonType = \"PushButton\";\n"
" profile = \"GuiIconButtonProfile\";\n"
"};\n"
"@endtsexample\n\n"
"@see GuiControl\n"
"@see GuiButtonCtrl\n\n"
"@ingroup GuiCore\n"
);
GuiIconButtonCtrl::GuiIconButtonCtrl()
{
mBitmapName = StringTable->EmptyString();
mTextLocation = TextLocLeft;
mIconLocation = IconLocLeft;
mTextMargin = 4;
mButtonMargin.set(4,4);
mFitBitmapToButton = false;
mMakeIconSquare = false;
mErrorBitmapName = StringTable->EmptyString();
mErrorTextureHandle = NULL;
mAutoSize = false;
setExtent(140, 30);
}
ImplementEnumType( GuiIconButtonTextLocation,
"\n\n"
"@ingroup GuiImages" )
{ GuiIconButtonCtrl::TextLocNone, "None" },
{ GuiIconButtonCtrl::TextLocBottom, "Bottom" },
{ GuiIconButtonCtrl::TextLocRight, "Right" },
{ GuiIconButtonCtrl::TextLocTop, "Top" },
{ GuiIconButtonCtrl::TextLocLeft, "Left" },
{ GuiIconButtonCtrl::TextLocCenter, "Center" },
EndImplementEnumType;
ImplementEnumType( GuiIconButtonIconLocation,
"\n\n"
"@ingroup GuiImages" )
{ GuiIconButtonCtrl::IconLocNone, "None" },
{ GuiIconButtonCtrl::IconLocLeft, "Left" },
{ GuiIconButtonCtrl::IconLocRight, "Right" },
{ GuiIconButtonCtrl::IconLocCenter, "Center" }
EndImplementEnumType;
void GuiIconButtonCtrl::initPersistFields()
{
addField( "buttonMargin", TypePoint2I, Offset( mButtonMargin, GuiIconButtonCtrl ),"Margin area around the button.\n");
addField( "iconBitmap", TypeFilename, Offset( mBitmapName, GuiIconButtonCtrl ),"Bitmap file for the icon to display on the button.\n");
addField( "iconLocation", TYPEID< IconLocation >(), Offset( mIconLocation, GuiIconButtonCtrl ),"Where to place the icon on the control. Options are 0 (None), 1 (Left), 2 (Right), 3 (Center).\n");
addField( "sizeIconToButton", TypeBool, Offset( mFitBitmapToButton, GuiIconButtonCtrl ),"If true, the icon will be scaled to be the same size as the button.\n");
addField( "makeIconSquare", TypeBool, Offset( mMakeIconSquare, GuiIconButtonCtrl ),"If true, will make sure the icon is square.\n");
addField( "textLocation", TYPEID< TextLocation >(), Offset( mTextLocation, GuiIconButtonCtrl ),"Where to place the text on the control.\n"
"Options are 0 (None), 1 (Bottom), 2 (Right), 3 (Top), 4 (Left), 5 (Center).\n");
addField( "textMargin", TypeS32, Offset( mTextMargin, GuiIconButtonCtrl ),"Margin between the icon and the text.\n");
addField( "autoSize", TypeBool, Offset( mAutoSize, GuiIconButtonCtrl ),"If true, the text and icon will be automatically sized to the size of the control.\n");
Parent::initPersistFields();
}
bool GuiIconButtonCtrl::onWake()
{
if (! Parent::onWake())
return false;
setActive(true);
setBitmap(mBitmapName);
if( mProfile )
mProfile->constructBitmapArray();
return true;
}
void GuiIconButtonCtrl::onSleep()
{
mTextureNormal = NULL;
Parent::onSleep();
}
void GuiIconButtonCtrl::inspectPostApply()
{
Parent::inspectPostApply();
}
void GuiIconButtonCtrl::onStaticModified(const char* slotName, const char* newValue)
{
if ( isProperlyAdded() && !dStricmp(slotName, "autoSize") )
resize( getPosition(), getExtent() );
}
bool GuiIconButtonCtrl::resize(const Point2I &newPosition, const Point2I &newExtent)
{
if ( !mAutoSize || !mProfile->mFont )
return Parent::resize( newPosition, newExtent );
Point2I autoExtent( mMinExtent );
if ( mIconLocation != IconLocNone )
{
autoExtent.y = mTextureNormal.getHeight() + mButtonMargin.y * 2;
autoExtent.x = mTextureNormal.getWidth() + mButtonMargin.x * 2;
}
if ( mTextLocation != TextLocNone && mButtonText && mButtonText[0] )
{
U32 strWidth = mProfile->mFont->getStrWidthPrecise( mButtonText );
if ( mTextLocation == TextLocLeft || mTextLocation == TextLocRight )
{
autoExtent.x += strWidth + mTextMargin * 2;
}
else // Top, Bottom, Center
{
strWidth += mTextMargin * 2;
if ( strWidth > autoExtent.x )
autoExtent.x = strWidth;
}
}
return Parent::resize( newPosition, autoExtent );
}
void GuiIconButtonCtrl::setBitmap(const char *name)
{
mBitmapName = Platform::makeRelativePathName(name, NULL);
if(!isAwake())
return;
if (*mBitmapName)
{
mTextureNormal = GFXTexHandle(mBitmapName, &GFXTexturePersistentSRGBProfile, avar("%s() - mTextureNormal (line %d)", __FUNCTION__, __LINE__) );
}
else
{
mTextureNormal = NULL;
}
// So that extent is recalculated if autoSize is set.
resize( getPosition(), getExtent() );
setUpdate();
}
void GuiIconButtonCtrl::onRender(Point2I offset, const RectI& updateRect)
{
renderButton( offset, updateRect);
}
void GuiIconButtonCtrl::renderButton( Point2I &offset, const RectI& updateRect )
{
bool highlight = mMouseOver;
bool depressed = mDepressed;
ColorI fontColor = mActive ? (highlight ? mProfile->mFontColorHL : mProfile->mFontColor) : mProfile->mFontColorNA;
RectI boundsRect(offset, getExtent());
GFXDrawUtil *drawer = GFX->getDrawUtil();
if (mDepressed || mStateOn)
{
// If there is a bitmap array then render using it.
// Otherwise use a standard fill.
if(mProfile->mUseBitmapArray && mProfile->mBitmapArrayRects.size())
renderBitmapArray(boundsRect, statePressed);
else
renderSlightlyLoweredBox(boundsRect, mProfile);
}
else if(mMouseOver && mActive)
{
// If there is a bitmap array then render using it.
// Otherwise use a standard fill.
if(mProfile->mUseBitmapArray && mProfile->mBitmapArrayRects.size())
renderBitmapArray(boundsRect, stateMouseOver);
else
renderSlightlyRaisedBox(boundsRect, mProfile);
}
else
{
// If there is a bitmap array then render using it.
// Otherwise use a standard fill.
if(mProfile->mUseBitmapArray && mProfile->mBitmapArrayRects.size())
{
if(mActive)
renderBitmapArray(boundsRect, stateNormal);
else
renderBitmapArray(boundsRect, stateDisabled);
}
else
{
drawer->drawRectFill(boundsRect, mProfile->mFillColorNA);
drawer->drawRect(boundsRect, mProfile->mBorderColorNA);
}
}
Point2I textPos = offset;
if(depressed)
textPos += Point2I(1,1);
RectI iconRect( 0, 0, 0, 0 );
// Render the icon
if ( mTextureNormal && mIconLocation != GuiIconButtonCtrl::IconLocNone )
{
// Render the normal bitmap
drawer->clearBitmapModulation();
// Maintain the bitmap size or fill the button?
if ( !mFitBitmapToButton )
{
Point2I textureSize( mTextureNormal->getWidth(), mTextureNormal->getHeight() );
iconRect.set( offset + mButtonMargin, textureSize );
if ( mIconLocation == IconLocRight )
{
iconRect.point.x = ( offset.x + getWidth() ) - ( mButtonMargin.x + textureSize.x );
iconRect.point.y = offset.y + ( getHeight() - textureSize.y ) / 2;
}
else if ( mIconLocation == IconLocLeft )
{
iconRect.point.x = offset.x + mButtonMargin.x;
iconRect.point.y = offset.y + ( getHeight() - textureSize.y ) / 2;
}
else if ( mIconLocation == IconLocCenter )
{
iconRect.point.x = offset.x + ( getWidth() - textureSize.x ) / 2;
iconRect.point.y = offset.y + ( getHeight() - textureSize.y ) / 2;
}
drawer->drawBitmapStretch( mTextureNormal, iconRect );
}
else
{
iconRect.set( offset + mButtonMargin, getExtent() - (mButtonMargin * 2) );
if ( mMakeIconSquare )
{
// Square the icon to the smaller axis extent.
if ( iconRect.extent.x < iconRect.extent.y )
iconRect.extent.y = iconRect.extent.x;
else
iconRect.extent.x = iconRect.extent.y;
}
drawer->drawBitmapStretch( mTextureNormal, iconRect );
}
}
// Render text
if ( mTextLocation != TextLocNone )
{
// Clip text to fit (appends ...),
// pad some space to keep it off our border
String text( mButtonText );
S32 textWidth = clipText( text, getWidth() - 4 - mTextMargin );
drawer->setBitmapModulation( fontColor );
if ( mTextLocation == TextLocRight )
{
Point2I start( mTextMargin, ( getHeight() - mProfile->mFont->getHeight() ) / 2 );
if ( mTextureNormal && mIconLocation != IconLocNone )
{
start.x = iconRect.extent.x + mButtonMargin.x + mTextMargin;
}
drawer->drawText( mProfile->mFont, start + offset, text, mProfile->mFontColors );
}
if ( mTextLocation == TextLocLeft )
{
Point2I start( mTextMargin, ( getHeight() - mProfile->mFont->getHeight() ) / 2 );
drawer->drawText( mProfile->mFont, start + offset, text, mProfile->mFontColors );
}
if ( mTextLocation == TextLocCenter )
{
Point2I start;
if ( mTextureNormal && mIconLocation == IconLocLeft )
{
start.set( ( getWidth() - textWidth - iconRect.extent.x ) / 2 + iconRect.extent.x,
( getHeight() - mProfile->mFont->getHeight() ) / 2 );
}
else
start.set( ( getWidth() - textWidth ) / 2, ( getHeight() - mProfile->mFont->getHeight() ) / 2 );
drawer->setBitmapModulation( fontColor );
drawer->drawText( mProfile->mFont, start + offset, text, mProfile->mFontColors );
}
if ( mTextLocation == TextLocBottom )
{
Point2I start;
start.set( ( getWidth() - textWidth ) / 2, getHeight() - mProfile->mFont->getHeight() - mTextMargin );
// If the text is longer then the box size
// it will get clipped, force Left Justify
if( textWidth > getWidth() )
start.x = 0;
drawer->setBitmapModulation( fontColor );
drawer->drawText( mProfile->mFont, start + offset, text, mProfile->mFontColors );
}
}
renderChildControls( offset, updateRect);
}
// Draw the bitmap array's borders according to the button's state.
void GuiIconButtonCtrl::renderBitmapArray(RectI &bounds, S32 state)
{
switch(state)
{
case stateNormal:
if(mProfile->mBorder == -2)
renderSizableBitmapBordersFilled(bounds, 1, mProfile);
else
renderFixedBitmapBordersFilled(bounds, 1, mProfile);
break;
case stateMouseOver:
if(mProfile->mBorder == -2)
renderSizableBitmapBordersFilled(bounds, 2, mProfile);
else
renderFixedBitmapBordersFilled(bounds, 2, mProfile);
break;
case statePressed:
if(mProfile->mBorder == -2)
renderSizableBitmapBordersFilled(bounds, 3, mProfile);
else
renderFixedBitmapBordersFilled(bounds, 3, mProfile);
break;
case stateDisabled:
if(mProfile->mBorder == -2)
renderSizableBitmapBordersFilled(bounds, 4, mProfile);
else
renderFixedBitmapBordersFilled(bounds, 4, mProfile);
break;
}
}
DefineEngineMethod( GuiIconButtonCtrl, setBitmap, void, (const char* buttonFilename),,
"@brief Set the bitmap to use for the button portion of this control.\n\n"
"@param buttonFilename Filename for the image\n"
"@tsexample\n"
"// Define the button filename\n"
"%buttonFilename = \"pearlButton\";\n\n"
"// Inform the GuiIconButtonCtrl control to update its main button graphic to the defined bitmap\n"
"%thisGuiIconButtonCtrl.setBitmap(%buttonFilename);\n"
"@endtsexample\n\n"
"@see GuiControl\n"
"@see GuiButtonCtrl\n\n")
{
char* argBuffer = Con::getArgBuffer( 512 );
Platform::makeFullPathName( buttonFilename, argBuffer, 512 );
object->setBitmap( argBuffer );
}
<|endoftext|> |
<commit_before><commit_msg>WIP of forward probe scoring.<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: hfi_hierarchy.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2007-11-02 16:35:26 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef ADC_DISPLAY_HFI_HIERARCHY_HXX
#define ADC_DISPLAY_HFI_HIERARCHY_HXX
// USED SERVICES
// BASE CLASSES
// COMPONENTS
// PARAMETERS
#include <ary/idl/i_comrela.hxx>
#include <ary/idl/i_types4idl.hxx>
namespace csi
{
namespace xml
{
class Element;
}
}
class HF_IdlInterface;
class HtmlEnvironment_Idl;
/** Represents a node in an pyramidic inheritance hierarchy which shall be
displayed in text mode.
*/
class HF_IdlBaseNode
{
public:
typedef ary::idl::CodeEntity CE;
typedef ary::idl::Type TYPE;
typedef ary::idl::Gate GATE;
typedef ary::idl::Ce_id Ce_id;
typedef ary::idl::Type_id Type_id;
/** Constructor for the most derived class, whose base hierarchy
is to be built.
The constructor recursively calls further constructors of
HF_IdlBaseNode for the bases of ->i_rCe.
So it builds up a complete hierarchy tree of all base classes
of ->i_rCe.
*/
HF_IdlBaseNode(
const CE & i_rCe,
const GATE & i_rGate );
/** @descr
The constructor recursively calls further constructors of
HF_IdlBaseNode for the bases of ->i_rType, if ->i_rType matches to a
->CE.
So it builds up a complete hierarchy tree of all base classes
of ->i_pEntity.
*/
HF_IdlBaseNode(
const TYPE & i_rType,
const GATE & i_rGate,
intt i_nPositionOffset,
HF_IdlBaseNode & io_rDerived );
~HF_IdlBaseNode();
/** Recursively fills ->o_rPositionList with the instances of base
classes in the order in which they will be displayed.
*/
void FillPositionList(
std::vector< const HF_IdlBaseNode* > &
o_rPositionList ) const;
/** Writes the base hierarchy of this node into ->o_rOut.
It ends at the position where the name of the most derived
class would have to be written. Example:
abc::MyClass
|
| AnotherClass
| |
+--+--XYZ
The "XYZ" would NOT be written, that is the task of the caller.
*/
void WriteBaseHierarchy(
csi::xml::Element & o_rOut,
const HF_IdlInterface &
io_rDisplayer,
const String & i_sMainNodesText );
Type_id Type() const { return nType; }
intt BaseCount() const { return nCountBases; }
intt Position() const { return nPosition; }
int Xpos() const { return 3*Position(); }
int Ypos() const { return 2*Position(); }
const HF_IdlBaseNode * Derived() const { return pDerived; }
private:
typedef std::vector< DYN HF_IdlBaseNode* > BaseList;
void GatherBases(
const CE & i_rCe,
const GATE & i_rGate );
// DATA
Type_id nType;
BaseList aBases;
intt nCountBases;
intt nPosition;
HF_IdlBaseNode * pDerived;
};
void Write_BaseHierarchy(
csi::xml::Element & o_rOut,
HtmlEnvironment_Idl &
i_env,
const ary::idl::CodeEntity &
i_rCe );
void Write_Bases(
csi::xml::Element & o_rOut,
HtmlEnvironment_Idl &
i_env,
const ary::idl::CodeEntity &
i_rCe,
std::vector<uintt> &
io_setColumns );
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.5.22); FILE MERGED 2008/03/28 16:02:03 rt 1.5.22.1: #i87441# Change license header to LPGL v3.<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: hfi_hierarchy.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 ADC_DISPLAY_HFI_HIERARCHY_HXX
#define ADC_DISPLAY_HFI_HIERARCHY_HXX
// USED SERVICES
// BASE CLASSES
// COMPONENTS
// PARAMETERS
#include <ary/idl/i_comrela.hxx>
#include <ary/idl/i_types4idl.hxx>
namespace csi
{
namespace xml
{
class Element;
}
}
class HF_IdlInterface;
class HtmlEnvironment_Idl;
/** Represents a node in an pyramidic inheritance hierarchy which shall be
displayed in text mode.
*/
class HF_IdlBaseNode
{
public:
typedef ary::idl::CodeEntity CE;
typedef ary::idl::Type TYPE;
typedef ary::idl::Gate GATE;
typedef ary::idl::Ce_id Ce_id;
typedef ary::idl::Type_id Type_id;
/** Constructor for the most derived class, whose base hierarchy
is to be built.
The constructor recursively calls further constructors of
HF_IdlBaseNode for the bases of ->i_rCe.
So it builds up a complete hierarchy tree of all base classes
of ->i_rCe.
*/
HF_IdlBaseNode(
const CE & i_rCe,
const GATE & i_rGate );
/** @descr
The constructor recursively calls further constructors of
HF_IdlBaseNode for the bases of ->i_rType, if ->i_rType matches to a
->CE.
So it builds up a complete hierarchy tree of all base classes
of ->i_pEntity.
*/
HF_IdlBaseNode(
const TYPE & i_rType,
const GATE & i_rGate,
intt i_nPositionOffset,
HF_IdlBaseNode & io_rDerived );
~HF_IdlBaseNode();
/** Recursively fills ->o_rPositionList with the instances of base
classes in the order in which they will be displayed.
*/
void FillPositionList(
std::vector< const HF_IdlBaseNode* > &
o_rPositionList ) const;
/** Writes the base hierarchy of this node into ->o_rOut.
It ends at the position where the name of the most derived
class would have to be written. Example:
abc::MyClass
|
| AnotherClass
| |
+--+--XYZ
The "XYZ" would NOT be written, that is the task of the caller.
*/
void WriteBaseHierarchy(
csi::xml::Element & o_rOut,
const HF_IdlInterface &
io_rDisplayer,
const String & i_sMainNodesText );
Type_id Type() const { return nType; }
intt BaseCount() const { return nCountBases; }
intt Position() const { return nPosition; }
int Xpos() const { return 3*Position(); }
int Ypos() const { return 2*Position(); }
const HF_IdlBaseNode * Derived() const { return pDerived; }
private:
typedef std::vector< DYN HF_IdlBaseNode* > BaseList;
void GatherBases(
const CE & i_rCe,
const GATE & i_rGate );
// DATA
Type_id nType;
BaseList aBases;
intt nCountBases;
intt nPosition;
HF_IdlBaseNode * pDerived;
};
void Write_BaseHierarchy(
csi::xml::Element & o_rOut,
HtmlEnvironment_Idl &
i_env,
const ary::idl::CodeEntity &
i_rCe );
void Write_Bases(
csi::xml::Element & o_rOut,
HtmlEnvironment_Idl &
i_env,
const ary::idl::CodeEntity &
i_rCe,
std::vector<uintt> &
io_setColumns );
#endif
<|endoftext|> |
<commit_before>/*=========================================================================
Library: CTK
Copyright (c) Kitware Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0.txt
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.
=========================================================================*/
// Qt includes
#include <QDebug>
#include <QList>
#include <QMap>
#include <QSettings>
#include <QTableWidgetItem>
#include <QVariant>
/// CTK includes
#include <ctkCheckableHeaderView.h>
#include <ctkCheckableModelHelper.h>
// ctkDICOMWidgets includes
#include "ctkDICOMServerNodeWidget.h"
#include "ui_ctkDICOMServerNodeWidget.h"
// STD includes
#include <iostream>
//----------------------------------------------------------------------------
class ctkDICOMServerNodeWidgetPrivate: public Ui_ctkDICOMServerNodeWidget
{
public:
ctkDICOMServerNodeWidgetPrivate(){}
};
//----------------------------------------------------------------------------
// ctkDICOMServerNodeWidgetPrivate methods
//----------------------------------------------------------------------------
// ctkDICOMServerNodeWidget methods
//----------------------------------------------------------------------------
ctkDICOMServerNodeWidget::ctkDICOMServerNodeWidget(QWidget* parentWidget)
: Superclass(parentWidget)
, d_ptr(new ctkDICOMServerNodeWidgetPrivate)
{
Q_D(ctkDICOMServerNodeWidget);
d->setupUi(this);
// checkable headers.
d->NodeTable->model()->setHeaderData(0, Qt::Horizontal, Qt::Unchecked, Qt::CheckStateRole);
QHeaderView* previousHeaderView = d->NodeTable->horizontalHeader();
ctkCheckableHeaderView* headerView = new ctkCheckableHeaderView(Qt::Horizontal, d->NodeTable);
headerView->setClickable(previousHeaderView->isClickable());
headerView->setMovable(previousHeaderView->isMovable());
headerView->setHighlightSections(previousHeaderView->highlightSections());
headerView->checkableModelHelper()->setPropagateDepth(-1);
d->NodeTable->setHorizontalHeader(headerView);
d->RemoveButton->setEnabled(false);
this->readSettings();
connect(d->CallingAETitle, SIGNAL(textChanged(const QString&)),
this, SLOT(saveSettings()));
connect(d->StorageAETitle, SIGNAL(textChanged(const QString&)),
this, SLOT(saveSettings()));
connect(d->StoragePort, SIGNAL(textChanged(const QString&)),
this, SLOT(saveSettings()));
connect(d->AddButton, SIGNAL(clicked()),
this, SLOT(addServerNode()));
connect(d->RemoveButton, SIGNAL(clicked()),
this, SLOT(removeCurrentServerNode()));
connect(d->NodeTable, SIGNAL(cellChanged(int,int)),
this, SLOT(saveSettings()));
connect(d->NodeTable, SIGNAL(currentItemChanged(QTableWidgetItem*, QTableWidgetItem*)),
this, SLOT(updateRemoveButtonEnableState()));
}
//----------------------------------------------------------------------------
ctkDICOMServerNodeWidget::~ctkDICOMServerNodeWidget()
{
}
//----------------------------------------------------------------------------
int ctkDICOMServerNodeWidget::addServerNode()
{
Q_D(ctkDICOMServerNodeWidget);
const int rowCount = d->NodeTable->rowCount();
d->NodeTable->setRowCount( rowCount + 1 );
QTableWidgetItem* newItem = new QTableWidgetItem;
newItem->setCheckState( Qt::Unchecked );
d->NodeTable->setItem(rowCount, NameColumn, newItem);
d->NodeTable->setCurrentCell(rowCount, NameColumn);
// The old rowCount becomes the added row index
return rowCount;
}
//----------------------------------------------------------------------------
int ctkDICOMServerNodeWidget::addServerNode(const QMap<QString, QVariant>& node)
{
Q_D(ctkDICOMServerNodeWidget);
const int row = this->addServerNode();
QTableWidgetItem *newItem;
newItem = new QTableWidgetItem( node["Name"].toString() );
newItem->setCheckState( Qt::CheckState(node["CheckState"].toInt()) );
d->NodeTable->setItem(row, NameColumn, newItem);
newItem = new QTableWidgetItem( node["AETitle"].toString() );
d->NodeTable->setItem(row, AETitleColumn, newItem);
newItem = new QTableWidgetItem( node["Address"].toString() );
d->NodeTable->setItem(row, AddressColumn, newItem);
newItem = new QTableWidgetItem( node["Port"].toString() );
d->NodeTable->setItem(row, PortColumn, newItem);
return row;
}
//----------------------------------------------------------------------------
void ctkDICOMServerNodeWidget::removeCurrentServerNode()
{
Q_D(ctkDICOMServerNodeWidget);
d->NodeTable->removeRow( d->NodeTable->currentRow() );
this->saveSettings();
this->updateRemoveButtonEnableState();
}
//----------------------------------------------------------------------------
void ctkDICOMServerNodeWidget::updateRemoveButtonEnableState()
{
Q_D(ctkDICOMServerNodeWidget);
d->RemoveButton->setEnabled(d->NodeTable->rowCount() > 0);
}
//----------------------------------------------------------------------------
void ctkDICOMServerNodeWidget::saveSettings()
{
Q_D(ctkDICOMServerNodeWidget);
QSettings settings;
const int rowCount = d->NodeTable->rowCount();
settings.setValue("ServerNodeCount", rowCount);
for (int row = 0; row < rowCount; ++row)
{
QMap<QString, QVariant> node = this->serverNodeParameters(row);
settings.setValue(QString("ServerNodes/%1").arg(row), QVariant(node));
}
settings.setValue("CallingAETitle", this->callingAETitle());
settings.setValue("StorageAETitle", this->storageAETitle());
settings.setValue("StoragePort", this->storagePort());
settings.sync();
}
//----------------------------------------------------------------------------
void ctkDICOMServerNodeWidget::readSettings()
{
Q_D(ctkDICOMServerNodeWidget);
d->NodeTable->setRowCount(0);
QSettings settings;
QMap<QString, QVariant> node;
if (settings.status() == QSettings::AccessError ||
settings.value("ServerNodeCount").toInt() == 0)
{
d->StorageAETitle->setText("CTKSTORE");
d->StoragePort->setText("11113");
d->CallingAETitle->setText("FINDSCU");
QMap<QString, QVariant> defaultServerNode;
defaultServerNode["Name"] = QString("ExampleHost");
defaultServerNode["CheckState"] = Qt::Checked;
defaultServerNode["AETitle"] = QString("ANY-SCP");
defaultServerNode["Address"] = QString("localhost");
defaultServerNode["Port"] = QString("11112");
this->addServerNode(defaultServerNode);
return;
}
d->StorageAETitle->setText(settings.value("StorageAETitle").toString());
d->StoragePort->setText(settings.value("StoragePort").toString());
d->CallingAETitle->setText(settings.value("CallingAETitle").toString());
const int count = settings.value("ServerNodeCount").toInt();
for (int row = 0; row < count; ++row)
{
node = settings.value(QString("ServerNodes/%1").arg(row)).toMap();
this->addServerNode(node);
}
}
//----------------------------------------------------------------------------
QString ctkDICOMServerNodeWidget::callingAETitle()const
{
Q_D(const ctkDICOMServerNodeWidget);
return d->CallingAETitle->text();
}
//----------------------------------------------------------------------------
QString ctkDICOMServerNodeWidget::storageAETitle()const
{
Q_D(const ctkDICOMServerNodeWidget);
return d->StorageAETitle->text();
}
//----------------------------------------------------------------------------
int ctkDICOMServerNodeWidget::storagePort()const
{
Q_D(const ctkDICOMServerNodeWidget);
bool ok = false;
int port = d->StoragePort->text().toInt(&ok);
Q_ASSERT(ok);
return port;
}
//----------------------------------------------------------------------------
QMap<QString,QVariant> ctkDICOMServerNodeWidget::parameters()const
{
Q_D(const ctkDICOMServerNodeWidget);
QMap<QString, QVariant> parameters;
parameters["CallingAETitle"] = this->callingAETitle();
parameters["StorageAETitle"] = this->storageAETitle();
parameters["StoragePort"] = this->storagePort();
return parameters;
}
//----------------------------------------------------------------------------
QStringList ctkDICOMServerNodeWidget::serverNodes()const
{
Q_D(const ctkDICOMServerNodeWidget);
QStringList nodes;
const int count = d->NodeTable->rowCount();
for (int row = 0; row < count; ++row)
{
QTableWidgetItem* item = d->NodeTable->item(row,NameColumn);
nodes << (item ? item->text() : QString(""));
}
// If there are duplicates, serverNodeParameters(QString) will behave
// strangely
Q_ASSERT(nodes.removeDuplicates() == 0);
return nodes;
}
//----------------------------------------------------------------------------
QStringList ctkDICOMServerNodeWidget::selectedServerNodes()const
{
Q_D(const ctkDICOMServerNodeWidget);
QStringList nodes;
const int count = d->NodeTable->rowCount();
for (int row = 0; row < count; ++row)
{
QTableWidgetItem* item = d->NodeTable->item(row, NameColumn);
if (item && item->checkState() == Qt::Checked)
{
nodes << item->text();
}
}
// If there are duplicates, serverNodeParameters(QString) will behave
// strangely
Q_ASSERT(nodes.removeDuplicates() == 0);
return nodes;
}
//----------------------------------------------------------------------------
QMap<QString, QVariant> ctkDICOMServerNodeWidget::serverNodeParameters(const QString &node)const
{
Q_D(const ctkDICOMServerNodeWidget);
QMap<QString, QVariant> parameters;
const int count = d->NodeTable->rowCount();
for (int row = 0; row < count; row++)
{
if ( d->NodeTable->item(row,0)->text() == node )
{
// TBD: not sure what it means to merge parameters
parameters.unite(this->serverNodeParameters(row));
}
}
return parameters;
}
//----------------------------------------------------------------------------
QMap<QString, QVariant> ctkDICOMServerNodeWidget::serverNodeParameters(int row)const
{
Q_D(const ctkDICOMServerNodeWidget);
QMap<QString, QVariant> node;
if (row < 0 || row >= d->NodeTable->rowCount())
{
return node;
}
const int columnCount = d->NodeTable->columnCount();
for (int column = 0; column < columnCount; ++column)
{
if (!d->NodeTable->item(row, column))
{
continue;
}
QString label = d->NodeTable->horizontalHeaderItem(column)->text();
node[label] = d->NodeTable->item(row, column)->data(Qt::DisplayRole);
}
node["CheckState"] = d->NodeTable->item(row, NameColumn) ?
d->NodeTable->item(row,0)->checkState() : Qt::Unchecked;
return node;
}
<commit_msg>Remove unused variable.<commit_after>/*=========================================================================
Library: CTK
Copyright (c) Kitware Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0.txt
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.
=========================================================================*/
// Qt includes
#include <QDebug>
#include <QList>
#include <QMap>
#include <QSettings>
#include <QTableWidgetItem>
#include <QVariant>
/// CTK includes
#include <ctkCheckableHeaderView.h>
#include <ctkCheckableModelHelper.h>
// ctkDICOMWidgets includes
#include "ctkDICOMServerNodeWidget.h"
#include "ui_ctkDICOMServerNodeWidget.h"
// STD includes
#include <iostream>
//----------------------------------------------------------------------------
class ctkDICOMServerNodeWidgetPrivate: public Ui_ctkDICOMServerNodeWidget
{
public:
ctkDICOMServerNodeWidgetPrivate(){}
};
//----------------------------------------------------------------------------
// ctkDICOMServerNodeWidgetPrivate methods
//----------------------------------------------------------------------------
// ctkDICOMServerNodeWidget methods
//----------------------------------------------------------------------------
ctkDICOMServerNodeWidget::ctkDICOMServerNodeWidget(QWidget* parentWidget)
: Superclass(parentWidget)
, d_ptr(new ctkDICOMServerNodeWidgetPrivate)
{
Q_D(ctkDICOMServerNodeWidget);
d->setupUi(this);
// checkable headers.
d->NodeTable->model()->setHeaderData(0, Qt::Horizontal, Qt::Unchecked, Qt::CheckStateRole);
QHeaderView* previousHeaderView = d->NodeTable->horizontalHeader();
ctkCheckableHeaderView* headerView = new ctkCheckableHeaderView(Qt::Horizontal, d->NodeTable);
headerView->setClickable(previousHeaderView->isClickable());
headerView->setMovable(previousHeaderView->isMovable());
headerView->setHighlightSections(previousHeaderView->highlightSections());
headerView->checkableModelHelper()->setPropagateDepth(-1);
d->NodeTable->setHorizontalHeader(headerView);
d->RemoveButton->setEnabled(false);
this->readSettings();
connect(d->CallingAETitle, SIGNAL(textChanged(const QString&)),
this, SLOT(saveSettings()));
connect(d->StorageAETitle, SIGNAL(textChanged(const QString&)),
this, SLOT(saveSettings()));
connect(d->StoragePort, SIGNAL(textChanged(const QString&)),
this, SLOT(saveSettings()));
connect(d->AddButton, SIGNAL(clicked()),
this, SLOT(addServerNode()));
connect(d->RemoveButton, SIGNAL(clicked()),
this, SLOT(removeCurrentServerNode()));
connect(d->NodeTable, SIGNAL(cellChanged(int,int)),
this, SLOT(saveSettings()));
connect(d->NodeTable, SIGNAL(currentItemChanged(QTableWidgetItem*, QTableWidgetItem*)),
this, SLOT(updateRemoveButtonEnableState()));
}
//----------------------------------------------------------------------------
ctkDICOMServerNodeWidget::~ctkDICOMServerNodeWidget()
{
}
//----------------------------------------------------------------------------
int ctkDICOMServerNodeWidget::addServerNode()
{
Q_D(ctkDICOMServerNodeWidget);
const int rowCount = d->NodeTable->rowCount();
d->NodeTable->setRowCount( rowCount + 1 );
QTableWidgetItem* newItem = new QTableWidgetItem;
newItem->setCheckState( Qt::Unchecked );
d->NodeTable->setItem(rowCount, NameColumn, newItem);
d->NodeTable->setCurrentCell(rowCount, NameColumn);
// The old rowCount becomes the added row index
return rowCount;
}
//----------------------------------------------------------------------------
int ctkDICOMServerNodeWidget::addServerNode(const QMap<QString, QVariant>& node)
{
Q_D(ctkDICOMServerNodeWidget);
const int row = this->addServerNode();
QTableWidgetItem *newItem;
newItem = new QTableWidgetItem( node["Name"].toString() );
newItem->setCheckState( Qt::CheckState(node["CheckState"].toInt()) );
d->NodeTable->setItem(row, NameColumn, newItem);
newItem = new QTableWidgetItem( node["AETitle"].toString() );
d->NodeTable->setItem(row, AETitleColumn, newItem);
newItem = new QTableWidgetItem( node["Address"].toString() );
d->NodeTable->setItem(row, AddressColumn, newItem);
newItem = new QTableWidgetItem( node["Port"].toString() );
d->NodeTable->setItem(row, PortColumn, newItem);
return row;
}
//----------------------------------------------------------------------------
void ctkDICOMServerNodeWidget::removeCurrentServerNode()
{
Q_D(ctkDICOMServerNodeWidget);
d->NodeTable->removeRow( d->NodeTable->currentRow() );
this->saveSettings();
this->updateRemoveButtonEnableState();
}
//----------------------------------------------------------------------------
void ctkDICOMServerNodeWidget::updateRemoveButtonEnableState()
{
Q_D(ctkDICOMServerNodeWidget);
d->RemoveButton->setEnabled(d->NodeTable->rowCount() > 0);
}
//----------------------------------------------------------------------------
void ctkDICOMServerNodeWidget::saveSettings()
{
Q_D(ctkDICOMServerNodeWidget);
QSettings settings;
const int rowCount = d->NodeTable->rowCount();
settings.setValue("ServerNodeCount", rowCount);
for (int row = 0; row < rowCount; ++row)
{
QMap<QString, QVariant> node = this->serverNodeParameters(row);
settings.setValue(QString("ServerNodes/%1").arg(row), QVariant(node));
}
settings.setValue("CallingAETitle", this->callingAETitle());
settings.setValue("StorageAETitle", this->storageAETitle());
settings.setValue("StoragePort", this->storagePort());
settings.sync();
}
//----------------------------------------------------------------------------
void ctkDICOMServerNodeWidget::readSettings()
{
Q_D(ctkDICOMServerNodeWidget);
d->NodeTable->setRowCount(0);
QSettings settings;
QMap<QString, QVariant> node;
if (settings.status() == QSettings::AccessError ||
settings.value("ServerNodeCount").toInt() == 0)
{
d->StorageAETitle->setText("CTKSTORE");
d->StoragePort->setText("11113");
d->CallingAETitle->setText("FINDSCU");
QMap<QString, QVariant> defaultServerNode;
defaultServerNode["Name"] = QString("ExampleHost");
defaultServerNode["CheckState"] = Qt::Checked;
defaultServerNode["AETitle"] = QString("ANY-SCP");
defaultServerNode["Address"] = QString("localhost");
defaultServerNode["Port"] = QString("11112");
this->addServerNode(defaultServerNode);
return;
}
d->StorageAETitle->setText(settings.value("StorageAETitle").toString());
d->StoragePort->setText(settings.value("StoragePort").toString());
d->CallingAETitle->setText(settings.value("CallingAETitle").toString());
const int count = settings.value("ServerNodeCount").toInt();
for (int row = 0; row < count; ++row)
{
node = settings.value(QString("ServerNodes/%1").arg(row)).toMap();
this->addServerNode(node);
}
}
//----------------------------------------------------------------------------
QString ctkDICOMServerNodeWidget::callingAETitle()const
{
Q_D(const ctkDICOMServerNodeWidget);
return d->CallingAETitle->text();
}
//----------------------------------------------------------------------------
QString ctkDICOMServerNodeWidget::storageAETitle()const
{
Q_D(const ctkDICOMServerNodeWidget);
return d->StorageAETitle->text();
}
//----------------------------------------------------------------------------
int ctkDICOMServerNodeWidget::storagePort()const
{
Q_D(const ctkDICOMServerNodeWidget);
bool ok = false;
int port = d->StoragePort->text().toInt(&ok);
Q_ASSERT(ok);
return port;
}
//----------------------------------------------------------------------------
QMap<QString,QVariant> ctkDICOMServerNodeWidget::parameters()const
{
QMap<QString, QVariant> parameters;
parameters["CallingAETitle"] = this->callingAETitle();
parameters["StorageAETitle"] = this->storageAETitle();
parameters["StoragePort"] = this->storagePort();
return parameters;
}
//----------------------------------------------------------------------------
QStringList ctkDICOMServerNodeWidget::serverNodes()const
{
Q_D(const ctkDICOMServerNodeWidget);
QStringList nodes;
const int count = d->NodeTable->rowCount();
for (int row = 0; row < count; ++row)
{
QTableWidgetItem* item = d->NodeTable->item(row,NameColumn);
nodes << (item ? item->text() : QString(""));
}
// If there are duplicates, serverNodeParameters(QString) will behave
// strangely
Q_ASSERT(nodes.removeDuplicates() == 0);
return nodes;
}
//----------------------------------------------------------------------------
QStringList ctkDICOMServerNodeWidget::selectedServerNodes()const
{
Q_D(const ctkDICOMServerNodeWidget);
QStringList nodes;
const int count = d->NodeTable->rowCount();
for (int row = 0; row < count; ++row)
{
QTableWidgetItem* item = d->NodeTable->item(row, NameColumn);
if (item && item->checkState() == Qt::Checked)
{
nodes << item->text();
}
}
// If there are duplicates, serverNodeParameters(QString) will behave
// strangely
Q_ASSERT(nodes.removeDuplicates() == 0);
return nodes;
}
//----------------------------------------------------------------------------
QMap<QString, QVariant> ctkDICOMServerNodeWidget::serverNodeParameters(const QString &node)const
{
Q_D(const ctkDICOMServerNodeWidget);
QMap<QString, QVariant> parameters;
const int count = d->NodeTable->rowCount();
for (int row = 0; row < count; row++)
{
if ( d->NodeTable->item(row,0)->text() == node )
{
// TBD: not sure what it means to merge parameters
parameters.unite(this->serverNodeParameters(row));
}
}
return parameters;
}
//----------------------------------------------------------------------------
QMap<QString, QVariant> ctkDICOMServerNodeWidget::serverNodeParameters(int row)const
{
Q_D(const ctkDICOMServerNodeWidget);
QMap<QString, QVariant> node;
if (row < 0 || row >= d->NodeTable->rowCount())
{
return node;
}
const int columnCount = d->NodeTable->columnCount();
for (int column = 0; column < columnCount; ++column)
{
if (!d->NodeTable->item(row, column))
{
continue;
}
QString label = d->NodeTable->horizontalHeaderItem(column)->text();
node[label] = d->NodeTable->item(row, column)->data(Qt::DisplayRole);
}
node["CheckState"] = d->NodeTable->item(row, NameColumn) ?
d->NodeTable->item(row,0)->checkState() : Qt::Unchecked;
return node;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: b2dbeziertools.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: thb $ $Date: 2004-02-16 17:03:04 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _BGFX_CURVE_B2DBEZIERTOOLS_HXX
#define _BGFX_CURVE_B2DBEZIERTOOLS_HXX
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
//////////////////////////////////////////////////////////////////////////////
namespace basegfx
{
class B2DPolygon;
class B2DCubicBezier;
class B2DQuadraticBezier;
/** Subdivide given cubic bezier segment.
This function adaptively subdivides the given bezier
segment into as much straight line segments as necessary,
such that the maximal orthogonal distance from any of the
segments to the true curve is less than the given error
value.
@param rPoly
Output polygon. The subdivided bezier segment is added to
this polygon via B2DPolygon::append().
@param rCurve
The cubic bezier curve to subdivide
@param distanceBound
Bound on the maximal distance of the approximation to the
true curve.
@return the number of line segments created
*/
sal_Int32 adaptiveSubdivideByDistance( B2DPolygon& rPoly,
const B2DCubicBezier& rCurve,
double distanceBound );
/** Subdivide given cubic bezier segment.
This function adaptively subdivides the given bezier
segment into as much quadratic bezier curve segments as
necessary, such that the maximal orthogonal distance from
any of the segments to the true curve is less than the
given error value.
@param rPoly
Output polygon. The subdivided bezier segments are added to
this polygon via B2DPolygon::append().
@param rCurve
The cubic bezier curve to subdivide
@param distanceBound
Bound on the maximal distance of the approximation to the
true curve.
@return the number of quadratic curve segments created
*/
sal_Int32 adaptiveDegreeReductionByDistance( B2DPolygon& rPoly,
const B2DCubicBezier& rCurve,
double distanceBound );
/** Subdivide given cubic bezier segment.
This function adaptively subdivides the given bezier
segment into as much straight line segments as necessary,
such that the maximal angle change between any adjacent
lines is less than the given error value.
@param rPoly
Output polygon. The subdivided bezier segment is added to
this polygon via B2DPolygon::append().
@param rCurve
The cubic bezier curve to subdivide
@param angleBound
Bound on the maximal angle difference between two adjacent
polygon lines, in degrees. Values greater than |90| are
truncated to 90 degrees. You won't use them, anyway.
@return the number of line segments created
*/
sal_Int32 adaptiveSubdivideByAngle( B2DPolygon& rPoly,
const B2DCubicBezier& rCurve,
double angleBound );
/** Subdivide given cubic bezier segment.
This function adaptively subdivides the given bezier
segment into as much quadratic bezier curve segments as
necessary, such that the maximal angle difference of the
control vectors of any generated quadratic bezier segment
is less than the given error value.
@param rPoly
Output polygon. The subdivided bezier segments are added to
this polygon via B2DPolygon::append().
@param rCurve
The cubic bezier curve to subdivide
@param distanceBound
Bound on the maximal angle difference between the control
vectors of any of the generated quadratic bezier
segments. The angle must be given in degrees. Values
greater than |90| are truncated to 90 degrees. You won't
use them, anyway.
@return the number of quadratic curve segments created
*/
sal_Int32 adaptiveDegreeReductionByAngle( B2DPolygon& rPoly,
const B2DCubicBezier& rCurve,
double angleBound );
/** Subdivide given quadratic bezier segment.
This function adaptively subdivides the given bezier
segment into as much straight line segments as necessary,
such that the maximal orthogonal distance from any of the
segments to the true curve is less than the given error
value.
@param rPoly
Output polygon. The subdivided bezier segment is added to
this polygon via B2DPolygon::append().
@param rCurve
The cubic bezier curve to subdivide
@param distanceBound
Bound on the maximal distance of the approximation to the
true curve
@return the number of line segments created
*/
sal_Int32 adaptiveSubdivideByDistance( B2DPolygon& rPoly,
const B2DQuadraticBezier& rCurve,
double distanceBound );
/** Subdivide given quadratic bezier segment.
This function adaptively subdivides the given bezier
segment into as much straight line segments as necessary,
such that the maximal angle change between any adjacent
lines is less than the given error value.
@param rPoly
Output polygon. The subdivided bezier segment is added to
this polygon via B2DPolygon::append().
@param rCurve
The cubic bezier curve to subdivide
@param angleBound
Bound on the maximal angle difference between two adjacent
polygon lines, in degrees. Values greater than |90| are
truncated to 90 degrees. You won't use them, anyway.
@return the number of line segments created
*/
sal_Int32 adaptiveSubdivideByAngle( B2DPolygon& rPoly,
const B2DQuadraticBezier& rCurve,
double angleBound );
}
#endif /* _BGFX_CURVE_B2DBEZIERTOOLS_HXX */
<commit_msg>INTEGRATION: CWS aw019 (1.6.36); FILE MERGED 2004/10/06 11:14:06 aw 1.6.36.1: #i34831#<commit_after>/*************************************************************************
*
* $RCSfile: b2dbeziertools.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: pjunck $ $Date: 2004-11-03 08:33:21 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _BGFX_CURVE_B2DBEZIERTOOLS_HXX
#define _BGFX_CURVE_B2DBEZIERTOOLS_HXX
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
//////////////////////////////////////////////////////////////////////////////
namespace basegfx
{
class B2DPolygon;
class B2DCubicBezier;
class B2DQuadraticBezier;
/** Subdivide given cubic bezier segment.
This function adaptively subdivides the given bezier
segment into as much straight line segments as necessary,
such that the maximal orthogonal distance from any of the
segments to the true curve is less than the given error
value.
@param rPoly
Output polygon. The subdivided bezier segment is added to
this polygon via B2DPolygon::append().
@param rCurve
The cubic bezier curve to subdivide
@param distanceBound
Bound on the maximal distance of the approximation to the
true curve.
@param bAddEndPoint
Defines if the end point of the segment shall be added. This
is handy for subdividing a number of segments int one destination
polygon without the need to remove double points afterwards.
@return the number of line segments created
*/
sal_Int32 adaptiveSubdivideByDistance( B2DPolygon& rPoly,
const B2DCubicBezier& rCurve,
double distanceBound,
bool bAddEndPoint );
/** Subdivide given cubic bezier segment.
This function adaptively subdivides the given bezier
segment into as much quadratic bezier curve segments as
necessary, such that the maximal orthogonal distance from
any of the segments to the true curve is less than the
given error value.
@param rPoly
Output polygon. The subdivided bezier segments are added to
this polygon via B2DPolygon::append().
@param rCurve
The cubic bezier curve to subdivide
@param distanceBound
Bound on the maximal distance of the approximation to the
true curve.
@return the number of quadratic curve segments created
*/
sal_Int32 adaptiveDegreeReductionByDistance( B2DPolygon& rPoly,
const B2DCubicBezier& rCurve,
double distanceBound );
/** Subdivide given cubic bezier segment.
This function adaptively subdivides the given bezier
segment into as much straight line segments as necessary,
such that the maximal angle change between any adjacent
lines is less than the given error value.
@param rPoly
Output polygon. The subdivided bezier segment is added to
this polygon via B2DPolygon::append().
@param rCurve
The cubic bezier curve to subdivide
@param angleBound
Bound on the maximal angle difference between two adjacent
polygon lines, in degrees. Values greater than |90| are
truncated to 90 degrees. You won't use them, anyway.
@param bAddEndPoint
Defines if the end point of the segment shall be added. This
is handy for subdividing a number of segments int one destination
polygon without the need to remove double points afterwards.
@return the number of line segments created
*/
sal_Int32 adaptiveSubdivideByAngle( B2DPolygon& rPoly,
const B2DCubicBezier& rCurve,
double angleBound,
bool bAddEndPoint);
/** Subdivide given cubic bezier segment.
This function adaptively subdivides the given bezier
segment into as much quadratic bezier curve segments as
necessary, such that the maximal angle difference of the
control vectors of any generated quadratic bezier segment
is less than the given error value.
@param rPoly
Output polygon. The subdivided bezier segments are added to
this polygon via B2DPolygon::append().
@param rCurve
The cubic bezier curve to subdivide
@param distanceBound
Bound on the maximal angle difference between the control
vectors of any of the generated quadratic bezier
segments. The angle must be given in degrees. Values
greater than |90| are truncated to 90 degrees. You won't
use them, anyway.
@return the number of quadratic curve segments created
*/
sal_Int32 adaptiveDegreeReductionByAngle( B2DPolygon& rPoly,
const B2DCubicBezier& rCurve,
double angleBound );
/** Subdivide given quadratic bezier segment.
This function adaptively subdivides the given bezier
segment into as much straight line segments as necessary,
such that the maximal orthogonal distance from any of the
segments to the true curve is less than the given error
value.
@param rPoly
Output polygon. The subdivided bezier segment is added to
this polygon via B2DPolygon::append().
@param rCurve
The cubic bezier curve to subdivide
@param distanceBound
Bound on the maximal distance of the approximation to the
true curve
@param bAddEndPoint
Defines if the end point of the segment shall be added. This
is handy for subdividing a number of segments int one destination
polygon without the need to remove double points afterwards.
@return the number of line segments created
*/
sal_Int32 adaptiveSubdivideByDistance( B2DPolygon& rPoly,
const B2DQuadraticBezier& rCurve,
double distanceBound,
bool bAddEndPoint );
/** Subdivide given quadratic bezier segment.
This function adaptively subdivides the given bezier
segment into as much straight line segments as necessary,
such that the maximal angle change between any adjacent
lines is less than the given error value.
@param rPoly
Output polygon. The subdivided bezier segment is added to
this polygon via B2DPolygon::append().
@param rCurve
The cubic bezier curve to subdivide
@param angleBound
Bound on the maximal angle difference between two adjacent
polygon lines, in degrees. Values greater than |90| are
truncated to 90 degrees. You won't use them, anyway.
@param bAddEndPoint
Defines if the end point of the segment shall be added. This
is handy for subdividing a number of segments int one destination
polygon without the need to remove double points afterwards.
@return the number of line segments created
*/
sal_Int32 adaptiveSubdivideByAngle( B2DPolygon& rPoly,
const B2DQuadraticBezier& rCurve,
double angleBound,
bool bAddEndPoint );
}
#endif /* _BGFX_CURVE_B2DBEZIERTOOLS_HXX */
<|endoftext|> |
<commit_before>/* -------------------------------------------------------------------------- *
* OpenSim: Constraint.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2016 Stanford University and the Authors *
* Author(s): Frank C. Anderson, Ajay Seth *
* *
* 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. *
* -------------------------------------------------------------------------- */
//=============================================================================
// INCLUDES
//=============================================================================
#include "Constraint.h"
#include <OpenSim/Simulation/Model/Model.h>
#include "simbody/internal/Constraint.h"
//=============================================================================
// STATICS
//=============================================================================
using namespace std;
//using namespace SimTK;
using namespace OpenSim;
//=============================================================================
// CONSTRUCTOR(S) AND DESTRUCTOR
//=============================================================================
//_____________________________________________________________________________
/**
* Default constructor.
*/
Constraint::Constraint()
{
setNull();
constructProperties();
}
//_____________________________________________________________________________
/**
* Destructor.
*/
Constraint::~Constraint()
{
}
//_____________________________________________________________________________
/**
* Set the data members of this Constraint to their null values.
*/
void Constraint::setNull(void)
{
setAuthors("Frank Anderson, Ajay Seth");
}
//_____________________________________________________________________________
/**
* Connect properties to local pointers.
*/
void Constraint::constructProperties(void)
{
constructProperty_isEnforced(true);
}
void Constraint::updateFromXMLNode(SimTK::Xml::Element& node,
int versionNumber) {
if(versionNumber < XMLDocument::getLatestVersion()) {
if(versionNumber < 30509) {
// Rename property 'isDisabled' to 'isEnforced' and
// negate the contained value.
std::string oldName{"isDisabled"};
std::string newName{"isEnforced"};
if(node.hasElement(oldName)) {
auto elem = node.getRequiredElement(oldName);
elem.setElementTag(newName);
if(elem.getValue().find("true") != std::string::npos)
elem.setValue("false");
else if(elem.getValue().find("false") != std::string::npos)
elem.setValue("true");
}
}
}
Super::updateFromXMLNode(node, versionNumber);
}
//_____________________________________________________________________________
/**
* Perform some set up functions that happen after the
* object has been deserialized or copied.
*
* @param aModel OpenSim model containing this Constraint.
*/
void Constraint::extendConnectToModel(Model& aModel)
{
Super::extendConnectToModel(aModel);
}
void Constraint::extendInitStateFromProperties(SimTK::State& s) const
{
Super::extendInitStateFromProperties(s);
SimTK::Constraint& simConstraint =
_model->updMatterSubsystem().updConstraint(_index);
// Otherwise we have to change the status of the constraint
if(get_isEnforced())
simConstraint.enable(s);
else
simConstraint.disable(s);
}
void Constraint::extendSetPropertiesFromState(const SimTK::State& state)
{
Super::extendSetPropertiesFromState(state);
set_isEnforced(isEnforced(state));
}
//=============================================================================
// UTILITY
//=============================================================================
//_____________________________________________________________________________
/**
* Update an existing Constraint with parameter values from a
* new one, but only for the parameters that were explicitly
* specified in the XML node.
*
* @param aConstraint Constraint to update from
*/
void Constraint::updateFromConstraint(SimTK::State& s,
const Constraint &aConstraint)
{
setIsEnforced(s, aConstraint.isEnforced(s));
}
//=============================================================================
// GET AND SET
//=============================================================================
//-----------------------------------------------------------------------------
// DISABLE
//-----------------------------------------------------------------------------
//_____________________________________________________________________________
/**
* Get whether or not this Constraint is enforced.
* Simbody multibody system instance is realized every time the isEnforced
* changes, BUT multiple sets to the same value have no cost.
*/
bool Constraint::isEnforced(const SimTK::State& s) const
{
return !_model->updMatterSubsystem().updConstraint(_index).isDisabled(s);
}
//_____________________________________________________________________________
/**
* Set whether or not this Constraint is enforced.
* Simbody multibody system instance is realized every time the isEnforced
* changes, BUT multiple sets to the same value have no cost.
*
* @param isEnforced If true the constraint is enabled (active).
* If false the constraint is disabled (in-active).
*/
bool Constraint::setIsEnforced(SimTK::State& s, bool isEnforced)
{
SimTK::Constraint& simConstraint =
_model->updMatterSubsystem().updConstraint(_index);
bool modelConstraintIsEnforced = !simConstraint.isDisabled(s);
// Check if we already have the correct enabling of the constraint then
// do nothing
if(isEnforced == modelConstraintIsEnforced)
return true;
// Otherwise we have to change the status of the constraint
if(isEnforced)
simConstraint.enable(s);
else
simConstraint.disable(s);
_model->updateAssemblyConditions(s);
set_isEnforced(isEnforced);
return true;
}
//-----------------------------------------------------------------------------
// FORCES
//-----------------------------------------------------------------------------
//_____________________________________________________________________________
/**
* Ask the constraint for the forces it is imposing on the system
* Simbody multibody system must be realized to at least position
* Returns: the bodyForces on those bodies being constrained (constrainedBodies)
* a SpatialVec (6 components) describing resulting torque and force
* mobilityForces acting along constrained mobilities
*
* @param state State of model
* @param bodyForcesInAncestor is a Vector of SpatialVecs contain constraint
forces
* @param mobilityForces is a Vector of forces that act along the constrained
* mobilities associated with this constraint
*/
void Constraint::
calcConstraintForces(const SimTK::State& s,
SimTK::Vector_<SimTK::SpatialVec>& bodyForcesInAncestor,
SimTK::Vector& mobilityForces) const {
SimTK::Constraint& simConstraint =
_model->updMatterSubsystem().updConstraint(_index);
if(!simConstraint.isDisabled(s)){
SimTK::Vector multipliers = simConstraint.getMultipliersAsVector(s);
simConstraint.calcConstraintForcesFromMultipliers(s, multipliers,
bodyForcesInAncestor,
mobilityForces);
}
}
/**
* Methods to query a Constraint forces for the value actually applied during simulation
* The names of the quantities (column labels) is returned by this first function
* getRecordLabels()
*/
Array<std::string> Constraint::getRecordLabels() const
{
SimTK::Constraint& simConstraint = _model->updMatterSubsystem().updConstraint(_index);
const SimTK::State &ds = _model->getWorkingState();
// number of bodies being directly constrained
int ncb = simConstraint.getNumConstrainedBodies();
// number of mobilities being directly constrained
int ncm = simConstraint.getNumConstrainedU(ds);
const BodySet &bodies = _model->getBodySet();
Array<std::string> labels("");
for(int i=0; i<ncb; ++i){
const SimTK::MobilizedBody &b = simConstraint.getMobilizedBodyFromConstrainedBody(SimTK::ConstrainedBodyIndex(i));
const SimTK::MobilizedBodyIndex &bx = b.getMobilizedBodyIndex();
Body *bod = NULL;
for(int j=0; j<bodies.getSize(); ++j ){
if(bodies[j].getMobilizedBodyIndex() == bx){
bod = &bodies[j];
break;
}
}
if(bod == NULL){
throw Exception("Constraint "+getName()+" does not have an identifiable body index.");
}
string prefix = getName()+"_"+bod->getName();
labels.append(prefix+"_Fx");
labels.append(prefix+"_Fy");
labels.append(prefix+"_Fz");
labels.append(prefix+"_Mx");
labels.append(prefix+"_My");
labels.append(prefix+"_Mz");
}
char c[2] = "";
for(int i=0; i<ncm; ++i){
sprintf(c, "%d", i);
labels.append(getName()+"_mobility_F"+c);
}
return labels;
}
/**
* Given SimTK::State object extract all the values necessary to report constraint forces, application
* location frame, etc. used in conjunction with getRecordLabels and should return same size Array
*/
Array<double> Constraint::getRecordValues(const SimTK::State& state) const
{
// EOMs are solved for accelerations (udots) and constraint multipliers (lambdas)
// simultaneously, so system must be realized to acceleration
_model->getMultibodySystem().realize(state, SimTK::Stage::Acceleration);
SimTK::Constraint& simConstraint = _model->updMatterSubsystem().updConstraint(_index);
// number of bodies being directly constrained
int ncb = simConstraint.getNumConstrainedBodies();
// number of mobilities being directly constrained
int ncm = simConstraint.getNumConstrainedU(state);
SimTK::Vector_<SimTK::SpatialVec> bodyForcesInAncestor(ncb);
bodyForcesInAncestor.setToZero();
SimTK::Vector mobilityForces(ncm, 0.0);
Array<double> values(0.0,6*ncb+ncm);
calcConstraintForces(state, bodyForcesInAncestor, mobilityForces);
for(int i=0; i<ncb; ++i){
for(int j=0; j<3; ++j){
// Simbody constraints have reaction moments first and OpenSim reports forces first
// so swap them here
values[i*6+j] = (bodyForcesInAncestor(i)[1])[j]; // moments on constrained body i
values[i*6+3+j] = (bodyForcesInAncestor(i)[0])[j]; // forces on constrained body i
}
}
for(int i=0; i<ncm; ++i){
values[6*ncb+i] = mobilityForces[i];
}
return values;
};
<commit_msg>Make version number consistent with latest rename version<commit_after>/* -------------------------------------------------------------------------- *
* OpenSim: Constraint.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2016 Stanford University and the Authors *
* Author(s): Frank C. Anderson, Ajay Seth *
* *
* 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. *
* -------------------------------------------------------------------------- */
//=============================================================================
// INCLUDES
//=============================================================================
#include "Constraint.h"
#include <OpenSim/Simulation/Model/Model.h>
#include "simbody/internal/Constraint.h"
//=============================================================================
// STATICS
//=============================================================================
using namespace std;
//using namespace SimTK;
using namespace OpenSim;
//=============================================================================
// CONSTRUCTOR(S) AND DESTRUCTOR
//=============================================================================
//_____________________________________________________________________________
/**
* Default constructor.
*/
Constraint::Constraint()
{
setNull();
constructProperties();
}
//_____________________________________________________________________________
/**
* Destructor.
*/
Constraint::~Constraint()
{
}
//_____________________________________________________________________________
/**
* Set the data members of this Constraint to their null values.
*/
void Constraint::setNull(void)
{
setAuthors("Frank Anderson, Ajay Seth");
}
//_____________________________________________________________________________
/**
* Connect properties to local pointers.
*/
void Constraint::constructProperties(void)
{
constructProperty_isEnforced(true);
}
void Constraint::updateFromXMLNode(SimTK::Xml::Element& node,
int versionNumber) {
if(versionNumber < XMLDocument::getLatestVersion()) {
if(versionNumber < 30508) {
// Rename property 'isDisabled' to 'isEnforced' and
// negate the contained value.
std::string oldName{"isDisabled"};
std::string newName{"isEnforced"};
if(node.hasElement(oldName)) {
auto elem = node.getRequiredElement(oldName);
elem.setElementTag(newName);
if(elem.getValue().find("true") != std::string::npos)
elem.setValue("false");
else if(elem.getValue().find("false") != std::string::npos)
elem.setValue("true");
}
}
}
Super::updateFromXMLNode(node, versionNumber);
}
//_____________________________________________________________________________
/**
* Perform some set up functions that happen after the
* object has been deserialized or copied.
*
* @param aModel OpenSim model containing this Constraint.
*/
void Constraint::extendConnectToModel(Model& aModel)
{
Super::extendConnectToModel(aModel);
}
void Constraint::extendInitStateFromProperties(SimTK::State& s) const
{
Super::extendInitStateFromProperties(s);
SimTK::Constraint& simConstraint =
_model->updMatterSubsystem().updConstraint(_index);
// Otherwise we have to change the status of the constraint
if(get_isEnforced())
simConstraint.enable(s);
else
simConstraint.disable(s);
}
void Constraint::extendSetPropertiesFromState(const SimTK::State& state)
{
Super::extendSetPropertiesFromState(state);
set_isEnforced(isEnforced(state));
}
//=============================================================================
// UTILITY
//=============================================================================
//_____________________________________________________________________________
/**
* Update an existing Constraint with parameter values from a
* new one, but only for the parameters that were explicitly
* specified in the XML node.
*
* @param aConstraint Constraint to update from
*/
void Constraint::updateFromConstraint(SimTK::State& s,
const Constraint &aConstraint)
{
setIsEnforced(s, aConstraint.isEnforced(s));
}
//=============================================================================
// GET AND SET
//=============================================================================
//-----------------------------------------------------------------------------
// DISABLE
//-----------------------------------------------------------------------------
//_____________________________________________________________________________
/**
* Get whether or not this Constraint is enforced.
* Simbody multibody system instance is realized every time the isEnforced
* changes, BUT multiple sets to the same value have no cost.
*/
bool Constraint::isEnforced(const SimTK::State& s) const
{
return !_model->updMatterSubsystem().updConstraint(_index).isDisabled(s);
}
//_____________________________________________________________________________
/**
* Set whether or not this Constraint is enforced.
* Simbody multibody system instance is realized every time the isEnforced
* changes, BUT multiple sets to the same value have no cost.
*
* @param isEnforced If true the constraint is enabled (active).
* If false the constraint is disabled (in-active).
*/
bool Constraint::setIsEnforced(SimTK::State& s, bool isEnforced)
{
SimTK::Constraint& simConstraint =
_model->updMatterSubsystem().updConstraint(_index);
bool modelConstraintIsEnforced = !simConstraint.isDisabled(s);
// Check if we already have the correct enabling of the constraint then
// do nothing
if(isEnforced == modelConstraintIsEnforced)
return true;
// Otherwise we have to change the status of the constraint
if(isEnforced)
simConstraint.enable(s);
else
simConstraint.disable(s);
_model->updateAssemblyConditions(s);
set_isEnforced(isEnforced);
return true;
}
//-----------------------------------------------------------------------------
// FORCES
//-----------------------------------------------------------------------------
//_____________________________________________________________________________
/**
* Ask the constraint for the forces it is imposing on the system
* Simbody multibody system must be realized to at least position
* Returns: the bodyForces on those bodies being constrained (constrainedBodies)
* a SpatialVec (6 components) describing resulting torque and force
* mobilityForces acting along constrained mobilities
*
* @param state State of model
* @param bodyForcesInAncestor is a Vector of SpatialVecs contain constraint
forces
* @param mobilityForces is a Vector of forces that act along the constrained
* mobilities associated with this constraint
*/
void Constraint::
calcConstraintForces(const SimTK::State& s,
SimTK::Vector_<SimTK::SpatialVec>& bodyForcesInAncestor,
SimTK::Vector& mobilityForces) const {
SimTK::Constraint& simConstraint =
_model->updMatterSubsystem().updConstraint(_index);
if(!simConstraint.isDisabled(s)){
SimTK::Vector multipliers = simConstraint.getMultipliersAsVector(s);
simConstraint.calcConstraintForcesFromMultipliers(s, multipliers,
bodyForcesInAncestor,
mobilityForces);
}
}
/**
* Methods to query a Constraint forces for the value actually applied during simulation
* The names of the quantities (column labels) is returned by this first function
* getRecordLabels()
*/
Array<std::string> Constraint::getRecordLabels() const
{
SimTK::Constraint& simConstraint = _model->updMatterSubsystem().updConstraint(_index);
const SimTK::State &ds = _model->getWorkingState();
// number of bodies being directly constrained
int ncb = simConstraint.getNumConstrainedBodies();
// number of mobilities being directly constrained
int ncm = simConstraint.getNumConstrainedU(ds);
const BodySet &bodies = _model->getBodySet();
Array<std::string> labels("");
for(int i=0; i<ncb; ++i){
const SimTK::MobilizedBody &b = simConstraint.getMobilizedBodyFromConstrainedBody(SimTK::ConstrainedBodyIndex(i));
const SimTK::MobilizedBodyIndex &bx = b.getMobilizedBodyIndex();
Body *bod = NULL;
for(int j=0; j<bodies.getSize(); ++j ){
if(bodies[j].getMobilizedBodyIndex() == bx){
bod = &bodies[j];
break;
}
}
if(bod == NULL){
throw Exception("Constraint "+getName()+" does not have an identifiable body index.");
}
string prefix = getName()+"_"+bod->getName();
labels.append(prefix+"_Fx");
labels.append(prefix+"_Fy");
labels.append(prefix+"_Fz");
labels.append(prefix+"_Mx");
labels.append(prefix+"_My");
labels.append(prefix+"_Mz");
}
char c[2] = "";
for(int i=0; i<ncm; ++i){
sprintf(c, "%d", i);
labels.append(getName()+"_mobility_F"+c);
}
return labels;
}
/**
* Given SimTK::State object extract all the values necessary to report constraint forces, application
* location frame, etc. used in conjunction with getRecordLabels and should return same size Array
*/
Array<double> Constraint::getRecordValues(const SimTK::State& state) const
{
// EOMs are solved for accelerations (udots) and constraint multipliers (lambdas)
// simultaneously, so system must be realized to acceleration
_model->getMultibodySystem().realize(state, SimTK::Stage::Acceleration);
SimTK::Constraint& simConstraint = _model->updMatterSubsystem().updConstraint(_index);
// number of bodies being directly constrained
int ncb = simConstraint.getNumConstrainedBodies();
// number of mobilities being directly constrained
int ncm = simConstraint.getNumConstrainedU(state);
SimTK::Vector_<SimTK::SpatialVec> bodyForcesInAncestor(ncb);
bodyForcesInAncestor.setToZero();
SimTK::Vector mobilityForces(ncm, 0.0);
Array<double> values(0.0,6*ncb+ncm);
calcConstraintForces(state, bodyForcesInAncestor, mobilityForces);
for(int i=0; i<ncb; ++i){
for(int j=0; j<3; ++j){
// Simbody constraints have reaction moments first and OpenSim reports forces first
// so swap them here
values[i*6+j] = (bodyForcesInAncestor(i)[1])[j]; // moments on constrained body i
values[i*6+3+j] = (bodyForcesInAncestor(i)[0])[j]; // forces on constrained body i
}
}
for(int i=0; i<ncm; ++i){
values[6*ncb+i] = mobilityForces[i];
}
return values;
};
<|endoftext|> |
<commit_before>#include "LandObjectDefinition.h"
#include "components/debug/Debug.h"
namespace
{
constexpr double NO_ANIMATION_SECONDS = 0.0;
}
void LandObjectDefinition::init(Radians angle, const TextureManager::IdGroup<ImageID> &imageIDs,
double animSeconds)
{
this->angle = angle;
this->imageIDs = imageIDs;
this->animSeconds = animSeconds;
}
void LandObjectDefinition::init(Radians angle, ImageID imageID)
{
TextureManager::IdGroup<ImageID> imageIDs(imageID, 1);
this->init(angle, imageIDs, NO_ANIMATION_SECONDS);
}
Radians LandObjectDefinition::getAngle() const
{
return this->angle;
}
int LandObjectDefinition::getImageCount() const
{
return this->imageIDs.getCount();
}
ImageID LandObjectDefinition::getImageID(int index) const
{
return this->imageIDs.getID(index);
}
bool LandObjectDefinition::hasAnimation() const
{
return this->animSeconds >= NO_ANIMATION_SECONDS;
}
double LandObjectDefinition::getAnimationSeconds() const
{
DebugAssert(this->hasAnimation());
return this->animSeconds;
}
<commit_msg>Revised distant land animation condition.<commit_after>#include "LandObjectDefinition.h"
#include "components/debug/Debug.h"
void LandObjectDefinition::init(Radians angle, const TextureManager::IdGroup<ImageID> &imageIDs,
double animSeconds)
{
this->angle = angle;
this->imageIDs = imageIDs;
this->animSeconds = animSeconds;
}
void LandObjectDefinition::init(Radians angle, ImageID imageID)
{
TextureManager::IdGroup<ImageID> imageIDs(imageID, 1);
constexpr double animSeconds = 0.0;
this->init(angle, imageIDs, animSeconds);
}
Radians LandObjectDefinition::getAngle() const
{
return this->angle;
}
int LandObjectDefinition::getImageCount() const
{
return this->imageIDs.getCount();
}
ImageID LandObjectDefinition::getImageID(int index) const
{
return this->imageIDs.getID(index);
}
bool LandObjectDefinition::hasAnimation() const
{
return imageIDs.getCount() > 1;
}
double LandObjectDefinition::getAnimationSeconds() const
{
DebugAssert(this->hasAnimation());
return this->animSeconds;
}
<|endoftext|> |
<commit_before>//astahlle
AliAnalysisTaskEMCALPi0V2ShSh *AddTaskEMCALPi0V2ShSh()
{
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr)
{
::Error("AddTaskEMCALPi0V2ShSh", "No analysis manager to connect to.");
return NULL;
}
if (!mgr->GetInputEventHandler())
{
::Error("AddTaskEventplane", "This task requires an input event handler");
return NULL;
}
TString inputDataType = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
Bool_t ismc=kFALSE;
ismc = (mgr->GetMCtruthEventHandler())?kTRUE:kFALSE;
cout<<"AddTaskEMCALPi0V2ShSh - MC config is: "<<ismc<<endl;
if (ismc) return 0;
UInt_t physMB = 0;
UInt_t physJet = 0;
UInt_t physGam = 0;
UInt_t physEMC = 0;
TString sGeomName = AliEMCALGeometry::GetDefaultGeometryName();
AliAnalysisTaskEMCALPi0V2ShSh *task = new AliAnalysisTaskEMCALPi0V2ShSh("EMCALPi0ShowerShV2");
task->SelectCollisionCandidates(AliVEvent::kSemiCentral);
if(!ismc)
{
RequestMemory(task, 250*1024);
mgr->AddTask(task);
AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("hist", TList::Class(),AliAnalysisManager::kOutputContainer, AliAnalysisManager::GetCommonFileName()));
mgr->ConnectInput(task, 0, cinput);
mgr->ConnectOutput(task, 1, coutput1);
}
return task;
}
<commit_msg>more fixes in the addtask<commit_after>//astahlle
AliAnalysisTaskEMCALPi0V2ShSh *AddTaskEMCALPi0V2ShSh()
{
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr)
{
::Error("AddTaskEMCALPi0V2ShSh", "No analysis manager to connect to.");
return NULL;
}
if (!mgr->GetInputEventHandler())
{
::Error("AddTaskEventplane", "This task requires an input event handler");
return NULL;
}
TString inputDataType = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
Bool_t ismc=kFALSE;
ismc = (mgr->GetMCtruthEventHandler())?kTRUE:kFALSE;
cout<<"AddTaskEMCALPi0V2ShSh - MC config is: "<<ismc<<endl;
if (ismc) return 0;
UInt_t physMB = 0;
UInt_t physJet = 0;
UInt_t physGam = 0;
UInt_t physEMC = 0;
TString sGeomName = AliEMCALGeometry::GetDefaultGeometryName();
AliAnalysisTaskEMCALPi0V2ShSh *task = new AliAnalysisTaskEMCALPi0V2ShSh("EMCALPi0ShowerShV2");
task->SelectCollisionCandidates(AliVEvent::kSemiCentral);
if(!ismc)
{
mgr->AddTask(task);
AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("hist", TList::Class(),AliAnalysisManager::kOutputContainer, Form("%s",AliAnalysisManager::GetCommonFileName()));
mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(task, 1, coutput1);
}
return task;
}
<|endoftext|> |
<commit_before>//______________________________________________________________________________
AliAnalysisTaskCEPAnalysis* AddAnalysisTaskCEP(
Bool_t isMC = kFALSE,
Bool_t isSaveAll = kFALSE,
Int_t numTracksMax = 100000)
)
{
// get the manager and task
AliAnalysisManager *aam = AliAnalysisManager::GetAnalysisManager();
// check for MonteCarlo
if (isMC) {
AliMCEventHandler* handler = new AliMCEventHandler;
handler->SetReadTR(kFALSE);
mgr->SetMCtruthEventHandler(handler);
}
// create the analysis task
UInt_t taskConfig = AliCEPBase::kBitConfigurationSet;
if (isSaveAll) taskConfig |= AliCEPBase::kBitSaveAllEvents;
taskConfig |= AliCEPBase::kBitConfigurationVersion;
TString name = TString("CEPAnalysis");
AliAnalysisTaskCEP *task = new AliAnalysisTaskCEP (
name.Data(),taskConfig, numTracksMax);
// get input and output managers
AliAnalysisDataContainer *aadci = aam->GetCommonInputContainer();
AliAnalysisDataContainer *aadco1 = aam->CreateContainer
(
Form("CEPHist"),
TList::Class(),
AliAnalysisManager::kOutputContainer,
Form("%s:CEP", AliAnalysisManager::GetCommonFileName())
);
AliAnalysisDataContainer *aadco2 = aam->CreateContainer
(
Form("CEPTree"),
TTree::Class(),
AliAnalysisManager::kOutputContainer,
Form("%s:CEP", AliAnalysisManager::GetCommonFileName())
);
// add task and connect input and output managers
aam->AddTask(task);
aam->ConnectInput (task,0,aadci);
aam->ConnectOutput(task,1,aadco1);
aam->ConnectOutput(task,2,aadco2);
// return pointer to Task
return task;
}
//______________________________________________________________________________
<commit_msg>solved mismatch between filen ame and function name in AddTaskCEPAnalysis.C<commit_after>//______________________________________________________________________________
AliAnalysisTaskCEPAnalysis* AddTaskCEPAnalysis (
Bool_t isMC = kFALSE,
Bool_t isSaveAll = kFALSE,
Int_t numTracksMax = 100000)
)
{
// get the manager and task
AliAnalysisManager *aam = AliAnalysisManager::GetAnalysisManager();
// check for MonteCarlo
if (isMC) {
AliMCEventHandler* handler = new AliMCEventHandler;
handler->SetReadTR(kFALSE);
mgr->SetMCtruthEventHandler(handler);
}
// create the analysis task
UInt_t taskConfig = AliCEPBase::kBitConfigurationSet;
if (isSaveAll) taskConfig |= AliCEPBase::kBitSaveAllEvents;
taskConfig |= AliCEPBase::kBitConfigurationVersion;
TString name = TString("CEPAnalysis");
AliAnalysisTaskCEP *task = new AliAnalysisTaskCEP (
name.Data(),taskConfig, numTracksMax);
// get input and output managers
AliAnalysisDataContainer *aadci = aam->GetCommonInputContainer();
AliAnalysisDataContainer *aadco1 = aam->CreateContainer
(
Form("CEPHist"),
TList::Class(),
AliAnalysisManager::kOutputContainer,
Form("%s:CEP", AliAnalysisManager::GetCommonFileName())
);
AliAnalysisDataContainer *aadco2 = aam->CreateContainer
(
Form("CEPTree"),
TTree::Class(),
AliAnalysisManager::kOutputContainer,
Form("%s:CEP", AliAnalysisManager::GetCommonFileName())
);
// add task and connect input and output managers
aam->AddTask(task);
aam->ConnectInput (task,0,aadci);
aam->ConnectOutput(task,1,aadco1);
aam->ConnectOutput(task,2,aadco2);
// return pointer to Task
return task;
}
//______________________________________________________________________________
<|endoftext|> |
<commit_before>/***********************************************************************
filename: CEGUIFalTextComponent.cpp
created: Sun Jun 19 2005
author: Paul D Turner <paul@cegui.org.uk>
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
*
* 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 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.
***************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "falagard/CEGUIFalTextComponent.h"
#include "falagard/CEGUIFalXMLEnumHelper.h"
#include "CEGUIFontManager.h"
#include "CEGUIExceptions.h"
#include "CEGUIPropertyHelper.h"
#include "CEGUIFont.h"
#include "CEGUILeftAlignedRenderedString.h"
#include "CEGUIRightAlignedRenderedString.h"
#include "CEGUICentredRenderedString.h"
#include "CEGUIJustifiedRenderedString.h"
#include "CEGUIRenderedStringWordWrapper.h"
#include <iostream>
#if defined (CEGUI_USE_FRIBIDI)
#include "CEGUIFribidiVisualMapping.h"
#elif defined (CEGUI_USE_MINIBIDI)
#include "CEGUIMinibidiVisualMapping.h"
#else
#include "CEGUIBiDiVisualMapping.h"
#endif
// Start of CEGUI namespace section
namespace CEGUI
{
TextComponent::TextComponent() :
#ifndef CEGUI_BIDI_SUPPORT
d_bidiVisualMapping(0),
#elif defined (CEGUI_USE_FRIBIDI)
d_bidiVisualMapping(new FribidiVisualMapping),
#elif defined (CEGUI_USE_MINIBIDI)
d_bidiVisualMapping(new MinibidiVisualMapping),
#else
#error "BIDI Configuration is inconsistant, check your config!"
#endif
d_bidiDataValid(false),
d_formattedRenderedString(new LeftAlignedRenderedString(d_renderedString)),
d_lastHorzFormatting(HTF_LEFT_ALIGNED),
d_vertFormatting(VTF_TOP_ALIGNED),
d_horzFormatting(HTF_LEFT_ALIGNED)
{}
const String& TextComponent::getText() const
{
return d_textLogical;
}
void TextComponent::setText(const String& text)
{
d_textLogical = text;
d_bidiDataValid = false;
}
const String& TextComponent::getFont() const
{
return d_font;
}
void TextComponent::setFont(const String& font)
{
d_font = font;
}
VerticalTextFormatting TextComponent::getVerticalFormatting() const
{
return d_vertFormatting;
}
void TextComponent::setVerticalFormatting(VerticalTextFormatting fmt)
{
d_vertFormatting = fmt;
}
HorizontalTextFormatting TextComponent::getHorizontalFormatting() const
{
return d_horzFormatting;
}
void TextComponent::setHorizontalFormatting(HorizontalTextFormatting fmt)
{
d_horzFormatting = fmt;
}
void TextComponent::setupStringFormatter(const Window& window,
const RenderedString& rendered_string) const
{
const HorizontalTextFormatting horzFormatting = d_horzFormatPropertyName.empty() ? d_horzFormatting :
FalagardXMLHelper::stringToHorzTextFormat(window.getProperty(d_horzFormatPropertyName));
// no formatting change
if (horzFormatting == d_lastHorzFormatting)
{
d_formattedRenderedString->setRenderedString(rendered_string);
return;
}
d_lastHorzFormatting = horzFormatting;
switch(horzFormatting)
{
case HTF_LEFT_ALIGNED:
d_formattedRenderedString =
new LeftAlignedRenderedString(rendered_string);
break;
case HTF_CENTRE_ALIGNED:
d_formattedRenderedString =
new CentredRenderedString(rendered_string);
break;
case HTF_RIGHT_ALIGNED:
d_formattedRenderedString =
new RightAlignedRenderedString(rendered_string);
break;
case HTF_JUSTIFIED:
d_formattedRenderedString =
new JustifiedRenderedString(rendered_string);
break;
case HTF_WORDWRAP_LEFT_ALIGNED:
d_formattedRenderedString =
new RenderedStringWordWrapper
<LeftAlignedRenderedString>(rendered_string);
break;
case HTF_WORDWRAP_CENTRE_ALIGNED:
d_formattedRenderedString =
new RenderedStringWordWrapper
<CentredRenderedString>(rendered_string);
break;
case HTF_WORDWRAP_RIGHT_ALIGNED:
d_formattedRenderedString =
new RenderedStringWordWrapper
<RightAlignedRenderedString>(rendered_string);
break;
case HTF_WORDWRAP_JUSTIFIED:
d_formattedRenderedString =
new RenderedStringWordWrapper
<JustifiedRenderedString>(rendered_string);
break;
}
}
void TextComponent::render_impl(Window& srcWindow, Rect& destRect, const CEGUI::ColourRect* modColours, const Rect* clipper, bool /*clipToDisplay*/) const
{
// get font to use
Font* font;
try
{
font = d_fontPropertyName.empty() ?
(d_font.empty() ? srcWindow.getFont() : &FontManager::getSingleton().get(d_font))
: &FontManager::getSingleton().get(srcWindow.getProperty(d_fontPropertyName));
}
catch (UnknownObjectException&)
{
font = 0;
}
// exit if we have no font to use.
if (!font)
return;
const RenderedString* rs = &d_renderedString;
// do we fetch text from a property
if (!d_textPropertyName.empty())
{
// fetch text & do bi-directional reordering as needed
String vis;
#ifdef CEGUI_BIDI_SUPPORT
BiDiVisualMapping::StrIndexList l2v, v2l;
d_bidiVisualMapping->reorderFromLogicalToVisual(
srcWindow.getProperty(d_textPropertyName), vis, l2v, v2l);
#else
vis = srcWindow.getProperty(d_textPropertyName);
#endif
// parse string using parser from Window.
d_renderedString =
srcWindow.getRenderedStringParser().parse(vis, font, modColours);
}
// do we use a static text string from the looknfeel
else if (!getTextVisual().empty())
// parse string using parser from Window.
d_renderedString = srcWindow.getRenderedStringParser().
parse(getTextVisual(), font, modColours);
// use ready-made RenderedString from the Window itself
else
rs = &srcWindow.getRenderedString();
setupStringFormatter(srcWindow, *rs);
d_formattedRenderedString->format(destRect.getSize());
// Get total formatted height.
const float textHeight = d_formattedRenderedString->getVerticalExtent();
// handle dest area adjustments for vertical formatting.
VerticalTextFormatting vertFormatting = d_vertFormatPropertyName.empty() ? d_vertFormatting :
FalagardXMLHelper::stringToVertTextFormat(srcWindow.getProperty(d_vertFormatPropertyName));
switch(vertFormatting)
{
case VTF_CENTRE_ALIGNED:
destRect.d_top += (destRect.getHeight() - textHeight) * 0.5f;
break;
case VTF_BOTTOM_ALIGNED:
destRect.d_top = destRect.d_bottom - textHeight;
break;
default:
// default is VTF_TOP_ALIGNED, for which we take no action.
break;
}
// calculate final colours to be used
ColourRect finalColours;
initColoursRect(srcWindow, modColours, finalColours);
// offset the font little down so that it's centered within its own spacing
// destRect.d_top += (font->getLineSpacing() - font->getFontHeight()) * 0.5f;
// add geometry for text to the target window.
d_formattedRenderedString->draw(srcWindow.getGeometryBuffer(),
destRect.getPosition(),
&finalColours, clipper);
}
void TextComponent::writeXMLToStream(XMLSerializer& xml_stream) const
{
// opening tag
xml_stream.openTag("TextComponent");
// write out area
d_area.writeXMLToStream(xml_stream);
// write text element
if (!d_font.empty() && !getText().empty())
{
xml_stream.openTag("Text");
if (!d_font.empty())
xml_stream.attribute("font", d_font);
if (!getText().empty())
xml_stream.attribute("string", getText());
xml_stream.closeTag();
}
// write text property element
if (!d_textPropertyName.empty())
{
xml_stream.openTag("TextProperty")
.attribute("name", d_textPropertyName)
.closeTag();
}
// write font property element
if (!d_fontPropertyName.empty())
{
xml_stream.openTag("FontProperty")
.attribute("name", d_fontPropertyName)
.closeTag();
}
// get base class to write colours
writeColoursXML(xml_stream);
// write vert format, allowing base class to do this for us if a propety is in use
if (!writeVertFormatXML(xml_stream))
{
// was not a property, so write out explicit formatting in use
xml_stream.openTag("VertFormat")
.attribute("type", FalagardXMLHelper::vertTextFormatToString(d_vertFormatting))
.closeTag();
}
// write horz format, allowing base class to do this for us if a propety is in use
if (!writeHorzFormatXML(xml_stream))
{
// was not a property, so write out explicit formatting in use
xml_stream.openTag("HorzFormat")
.attribute("type", FalagardXMLHelper::horzTextFormatToString(d_horzFormatting))
.closeTag();
}
// closing tag
xml_stream.closeTag();
}
bool TextComponent::isTextFetchedFromProperty() const
{
return !d_textPropertyName.empty();
}
const String& TextComponent::getTextPropertySource() const
{
return d_textPropertyName;
}
void TextComponent::setTextPropertySource(const String& property)
{
d_textPropertyName = property;
}
bool TextComponent::isFontFetchedFromProperty() const
{
return !d_fontPropertyName.empty();
}
const String& TextComponent::getFontPropertySource() const
{
return d_fontPropertyName;
}
void TextComponent::setFontPropertySource(const String& property)
{
d_fontPropertyName = property;
}
const String& TextComponent::getTextVisual() const
{
// no bidi support
if (!d_bidiVisualMapping)
return d_textLogical;
if (!d_bidiDataValid)
{
d_bidiVisualMapping->updateVisual(d_textLogical);
d_bidiDataValid = true;
}
return d_bidiVisualMapping->getTextVisual();
}
} // End of CEGUI namespace section
<commit_msg>FIX: Ensure falagard rules are applied correctly as regards to fonts and text handling.<commit_after>/***********************************************************************
filename: CEGUIFalTextComponent.cpp
created: Sun Jun 19 2005
author: Paul D Turner <paul@cegui.org.uk>
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
*
* 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 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.
***************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "falagard/CEGUIFalTextComponent.h"
#include "falagard/CEGUIFalXMLEnumHelper.h"
#include "CEGUIFontManager.h"
#include "CEGUIExceptions.h"
#include "CEGUIPropertyHelper.h"
#include "CEGUIFont.h"
#include "CEGUILeftAlignedRenderedString.h"
#include "CEGUIRightAlignedRenderedString.h"
#include "CEGUICentredRenderedString.h"
#include "CEGUIJustifiedRenderedString.h"
#include "CEGUIRenderedStringWordWrapper.h"
#include <iostream>
#if defined (CEGUI_USE_FRIBIDI)
#include "CEGUIFribidiVisualMapping.h"
#elif defined (CEGUI_USE_MINIBIDI)
#include "CEGUIMinibidiVisualMapping.h"
#else
#include "CEGUIBiDiVisualMapping.h"
#endif
// Start of CEGUI namespace section
namespace CEGUI
{
TextComponent::TextComponent() :
#ifndef CEGUI_BIDI_SUPPORT
d_bidiVisualMapping(0),
#elif defined (CEGUI_USE_FRIBIDI)
d_bidiVisualMapping(new FribidiVisualMapping),
#elif defined (CEGUI_USE_MINIBIDI)
d_bidiVisualMapping(new MinibidiVisualMapping),
#else
#error "BIDI Configuration is inconsistant, check your config!"
#endif
d_bidiDataValid(false),
d_formattedRenderedString(new LeftAlignedRenderedString(d_renderedString)),
d_lastHorzFormatting(HTF_LEFT_ALIGNED),
d_vertFormatting(VTF_TOP_ALIGNED),
d_horzFormatting(HTF_LEFT_ALIGNED)
{}
const String& TextComponent::getText() const
{
return d_textLogical;
}
void TextComponent::setText(const String& text)
{
d_textLogical = text;
d_bidiDataValid = false;
}
const String& TextComponent::getFont() const
{
return d_font;
}
void TextComponent::setFont(const String& font)
{
d_font = font;
}
VerticalTextFormatting TextComponent::getVerticalFormatting() const
{
return d_vertFormatting;
}
void TextComponent::setVerticalFormatting(VerticalTextFormatting fmt)
{
d_vertFormatting = fmt;
}
HorizontalTextFormatting TextComponent::getHorizontalFormatting() const
{
return d_horzFormatting;
}
void TextComponent::setHorizontalFormatting(HorizontalTextFormatting fmt)
{
d_horzFormatting = fmt;
}
void TextComponent::setupStringFormatter(const Window& window,
const RenderedString& rendered_string) const
{
const HorizontalTextFormatting horzFormatting = d_horzFormatPropertyName.empty() ? d_horzFormatting :
FalagardXMLHelper::stringToHorzTextFormat(window.getProperty(d_horzFormatPropertyName));
// no formatting change
if (horzFormatting == d_lastHorzFormatting)
{
d_formattedRenderedString->setRenderedString(rendered_string);
return;
}
d_lastHorzFormatting = horzFormatting;
switch(horzFormatting)
{
case HTF_LEFT_ALIGNED:
d_formattedRenderedString =
new LeftAlignedRenderedString(rendered_string);
break;
case HTF_CENTRE_ALIGNED:
d_formattedRenderedString =
new CentredRenderedString(rendered_string);
break;
case HTF_RIGHT_ALIGNED:
d_formattedRenderedString =
new RightAlignedRenderedString(rendered_string);
break;
case HTF_JUSTIFIED:
d_formattedRenderedString =
new JustifiedRenderedString(rendered_string);
break;
case HTF_WORDWRAP_LEFT_ALIGNED:
d_formattedRenderedString =
new RenderedStringWordWrapper
<LeftAlignedRenderedString>(rendered_string);
break;
case HTF_WORDWRAP_CENTRE_ALIGNED:
d_formattedRenderedString =
new RenderedStringWordWrapper
<CentredRenderedString>(rendered_string);
break;
case HTF_WORDWRAP_RIGHT_ALIGNED:
d_formattedRenderedString =
new RenderedStringWordWrapper
<RightAlignedRenderedString>(rendered_string);
break;
case HTF_WORDWRAP_JUSTIFIED:
d_formattedRenderedString =
new RenderedStringWordWrapper
<JustifiedRenderedString>(rendered_string);
break;
}
}
void TextComponent::render_impl(Window& srcWindow, Rect& destRect, const CEGUI::ColourRect* modColours, const Rect* clipper, bool /*clipToDisplay*/) const
{
// get font to use
Font* font;
try
{
font = d_fontPropertyName.empty() ?
(d_font.empty() ? srcWindow.getFont() : &FontManager::getSingleton().get(d_font))
: &FontManager::getSingleton().get(srcWindow.getProperty(d_fontPropertyName));
}
catch (UnknownObjectException&)
{
font = 0;
}
// exit if we have no font to use.
if (!font)
return;
const RenderedString* rs = &d_renderedString;
// do we fetch text from a property
if (!d_textPropertyName.empty())
{
// fetch text & do bi-directional reordering as needed
String vis;
#ifdef CEGUI_BIDI_SUPPORT
BiDiVisualMapping::StrIndexList l2v, v2l;
d_bidiVisualMapping->reorderFromLogicalToVisual(
srcWindow.getProperty(d_textPropertyName), vis, l2v, v2l);
#else
vis = srcWindow.getProperty(d_textPropertyName);
#endif
// parse string using parser from Window.
d_renderedString =
srcWindow.getRenderedStringParser().parse(vis, font, modColours);
}
// do we use a static text string from the looknfeel
else if (!getTextVisual().empty())
// parse string using parser from Window.
d_renderedString = srcWindow.getRenderedStringParser().
parse(getTextVisual(), font, modColours);
// do we have to override the font?
else if (font != srcWindow.getFont())
d_renderedString = srcWindow.getRenderedStringParser().
parse(srcWindow.getTextVisual(), font, modColours);
// use ready-made RenderedString from the Window itself
else
rs = &srcWindow.getRenderedString();
setupStringFormatter(srcWindow, *rs);
d_formattedRenderedString->format(destRect.getSize());
// Get total formatted height.
const float textHeight = d_formattedRenderedString->getVerticalExtent();
// handle dest area adjustments for vertical formatting.
VerticalTextFormatting vertFormatting = d_vertFormatPropertyName.empty() ? d_vertFormatting :
FalagardXMLHelper::stringToVertTextFormat(srcWindow.getProperty(d_vertFormatPropertyName));
switch(vertFormatting)
{
case VTF_CENTRE_ALIGNED:
destRect.d_top += (destRect.getHeight() - textHeight) * 0.5f;
break;
case VTF_BOTTOM_ALIGNED:
destRect.d_top = destRect.d_bottom - textHeight;
break;
default:
// default is VTF_TOP_ALIGNED, for which we take no action.
break;
}
// calculate final colours to be used
ColourRect finalColours;
initColoursRect(srcWindow, modColours, finalColours);
// offset the font little down so that it's centered within its own spacing
// destRect.d_top += (font->getLineSpacing() - font->getFontHeight()) * 0.5f;
// add geometry for text to the target window.
d_formattedRenderedString->draw(srcWindow.getGeometryBuffer(),
destRect.getPosition(),
&finalColours, clipper);
}
void TextComponent::writeXMLToStream(XMLSerializer& xml_stream) const
{
// opening tag
xml_stream.openTag("TextComponent");
// write out area
d_area.writeXMLToStream(xml_stream);
// write text element
if (!d_font.empty() && !getText().empty())
{
xml_stream.openTag("Text");
if (!d_font.empty())
xml_stream.attribute("font", d_font);
if (!getText().empty())
xml_stream.attribute("string", getText());
xml_stream.closeTag();
}
// write text property element
if (!d_textPropertyName.empty())
{
xml_stream.openTag("TextProperty")
.attribute("name", d_textPropertyName)
.closeTag();
}
// write font property element
if (!d_fontPropertyName.empty())
{
xml_stream.openTag("FontProperty")
.attribute("name", d_fontPropertyName)
.closeTag();
}
// get base class to write colours
writeColoursXML(xml_stream);
// write vert format, allowing base class to do this for us if a propety is in use
if (!writeVertFormatXML(xml_stream))
{
// was not a property, so write out explicit formatting in use
xml_stream.openTag("VertFormat")
.attribute("type", FalagardXMLHelper::vertTextFormatToString(d_vertFormatting))
.closeTag();
}
// write horz format, allowing base class to do this for us if a propety is in use
if (!writeHorzFormatXML(xml_stream))
{
// was not a property, so write out explicit formatting in use
xml_stream.openTag("HorzFormat")
.attribute("type", FalagardXMLHelper::horzTextFormatToString(d_horzFormatting))
.closeTag();
}
// closing tag
xml_stream.closeTag();
}
bool TextComponent::isTextFetchedFromProperty() const
{
return !d_textPropertyName.empty();
}
const String& TextComponent::getTextPropertySource() const
{
return d_textPropertyName;
}
void TextComponent::setTextPropertySource(const String& property)
{
d_textPropertyName = property;
}
bool TextComponent::isFontFetchedFromProperty() const
{
return !d_fontPropertyName.empty();
}
const String& TextComponent::getFontPropertySource() const
{
return d_fontPropertyName;
}
void TextComponent::setFontPropertySource(const String& property)
{
d_fontPropertyName = property;
}
const String& TextComponent::getTextVisual() const
{
// no bidi support
if (!d_bidiVisualMapping)
return d_textLogical;
if (!d_bidiDataValid)
{
d_bidiVisualMapping->updateVisual(d_textLogical);
d_bidiDataValid = true;
}
return d_bidiVisualMapping->getTextVisual();
}
} // End of CEGUI namespace section
<|endoftext|> |
<commit_before>/*
* THE UNICODE TEST SUITE FOR CINDER: https://github.com/arielm/Unicode
* COPYRIGHT (C) 2013, ARIEL MALKA ALL RIGHTS RESERVED.
*
* THE FOLLOWING SOURCE-CODE IS DISTRIBUTED UNDER THE MODIFIED BSD LICENSE:
* https://github.com/arielm/Unicode/blob/master/LICENSE.md
*/
/*
* USING BIDI TEXT EXAMPLES FROM:
* http://people.w3.org/rishida/scripts/bidi/
*
*
* bidi1:
* USING THE FOLLOWING:
* https://github.com/mapnik/mapnik/blob/64d5153aeaeb1c9e736bfead297dfea39b066d2c/src/text/itemizer.cpp#L90-131
*
* bidi2:
* USING THE FOLLOWING (TODO):
*
*/
#include "cinder/app/AppNative.h"
#include "unicode/unistr.h"
#include "unicode/uscript.h"
#include "unicode/ubidi.h"
using namespace std;
using namespace ci;
using namespace app;
static void spitRun(const UnicodeString &text, UBiDiDirection direction, int32_t start, int32_t end)
{
std::string tmp;
text.tempSubString(start, end - start).toUTF8String(tmp);
cout << ((direction == UBIDI_RTL) ? "RTL " : "") << "[" << start << " | " << end << "]" << endl;
cout << tmp << endl << endl;
}
static void bidi1(const string &input)
{
auto text = UnicodeString::fromUTF8(input);
int32_t start = 0;
int32_t end = text.length();
UErrorCode error = U_ZERO_ERROR;
int32_t length = end - start;
UBiDi *bidi = ubidi_openSized(length, 0, &error);
if (!bidi || U_FAILURE(error))
{
cout << "Failed to create bidi object: " << u_errorName(error) << endl;
throw;
}
ubidi_setPara(bidi, text.getBuffer() + start, length, UBIDI_DEFAULT_LTR, 0, &error);
if (U_SUCCESS(error))
{
UBiDiDirection direction = ubidi_getDirection(bidi);
if (direction != UBIDI_MIXED)
{
spitRun(text, direction, start, end);
}
else
{
// mixed-directional
int32_t count = ubidi_countRuns(bidi, &error);
if (U_SUCCESS(error))
{
for (int i=0; i<count; ++i)
{
int32_t length;
int32_t run_start;
direction = ubidi_getVisualRun(bidi, i, &run_start, &length);
run_start += start; //Add offset to compensate offset in setPara
spitRun(text, direction, run_start, run_start + length);
}
}
}
}
else
{
cout << "ICU error: " << u_errorName(error) << endl;
throw;
}
ubidi_close(bidi);
}
class Application : public AppNative
{
public:
void setup();
void draw();
};
void Application::setup()
{
bidi1("The title is مفتاح معايير الويب in Arabic.");
}
void Application::draw()
{
gl::clear(Color::gray(0.5f), false);
}
CINDER_APP_NATIVE(Application, RendererGl(RendererGl::AA_NONE))
<commit_msg>BiDI: ANDROID CODE SEEMS TO WORK...<commit_after>/*
* THE UNICODE TEST SUITE FOR CINDER: https://github.com/arielm/Unicode
* COPYRIGHT (C) 2013, ARIEL MALKA ALL RIGHTS RESERVED.
*
* THE FOLLOWING SOURCE-CODE IS DISTRIBUTED UNDER THE MODIFIED BSD LICENSE:
* https://github.com/arielm/Unicode/blob/master/LICENSE.md
*/
/*
* USING BIDI TEXT EXAMPLES FROM:
* http://people.w3.org/rishida/scripts/bidi/
*
*
* bidi1() IS USING THE FOLLOWING:
* https://github.com/mapnik/mapnik/blob/64d5153aeaeb1c9e736bfead297dfea39b066d2c/src/text/itemizer.cpp#L90-131
*
* bidi2() IS USING THE FOLLOWING:
* https://github.com/android/platform_frameworks_base/blob/677726b376402937f53ddb192dc97078b92b7c9e/core/jni/android/graphics/TextLayoutCache.cpp#L356-485
*
* RESULTS ARE COMPARABLE...
*
*
* TODO: TEST MORE EXAMPLES
*/
#include "cinder/app/AppNative.h"
#include "unicode/unistr.h"
#include "unicode/uscript.h"
#include "unicode/ubidi.h"
using namespace std;
using namespace ci;
using namespace app;
static void spitRun(const UnicodeString &text, UBiDiDirection direction, int32_t start, int32_t end)
{
std::string tmp;
text.tempSubString(start, end - start).toUTF8String(tmp);
cout << ((direction == UBIDI_RTL) ? "RTL " : "") << "[" << start << " | " << end << "]" << endl;
cout << tmp << endl << endl;
}
static void bidi1(const string &input)
{
auto text = UnicodeString::fromUTF8(input);
int32_t start = 0;
int32_t end = text.length();
// ---
UErrorCode error = U_ZERO_ERROR;
int32_t length = end - start;
UBiDi *bidi = ubidi_openSized(length, 0, &error);
if (!bidi || U_FAILURE(error))
{
cout << "Failed to create bidi object: " << u_errorName(error) << endl;
throw;
}
ubidi_setPara(bidi, text.getBuffer() + start, length, UBIDI_DEFAULT_LTR, 0, &error);
if (U_SUCCESS(error))
{
UBiDiDirection direction = ubidi_getDirection(bidi);
if (direction != UBIDI_MIXED)
{
spitRun(text, direction, start, end);
}
else
{
// mixed-directional
int32_t count = ubidi_countRuns(bidi, &error);
if (U_SUCCESS(error))
{
for (int i=0; i<count; ++i)
{
int32_t length;
int32_t run_start;
direction = ubidi_getVisualRun(bidi, i, &run_start, &length);
run_start += start; //Add offset to compensate offset in setPara
spitRun(text, direction, run_start, run_start + length);
}
}
}
}
else
{
cout << "ICU error: " << u_errorName(error) << endl;
throw;
}
ubidi_close(bidi);
}
enum
{
kBidi_LTR = 0,
kBidi_RTL = 1,
kBidi_Default_LTR = 2,
kBidi_Default_RTL = 3,
kBidi_Force_LTR = 4,
kBidi_Force_RTL = 5,
kBidi_Mask = 0x7
};
enum
{
kDirection_LTR = 0,
kDirection_RTL = 1,
kDirection_Mask = 0x1
};
static void bidi2(const string &input)
{
auto text = UnicodeString::fromUTF8(input);
const UChar *chars = text.getBuffer();
size_t start = 0;
size_t count = text.length();
size_t contextCount = count; // ???
int dirFlags = kBidi_Default_LTR;
// ---
UBiDiLevel bidiReq = 0;
bool forceLTR = false;
bool forceRTL = false;
switch (dirFlags & kBidi_Mask)
{
case kBidi_LTR: bidiReq = 0; break; // no ICU constant, canonical LTR level
case kBidi_RTL: bidiReq = 1; break; // no ICU constant, canonical RTL level
case kBidi_Default_LTR: bidiReq = UBIDI_DEFAULT_LTR; break;
case kBidi_Default_RTL: bidiReq = UBIDI_DEFAULT_RTL; break;
case kBidi_Force_LTR: forceLTR = true; break; // every char is LTR
case kBidi_Force_RTL: forceRTL = true; break; // every char is RTL
}
bool useSingleRun = false;
bool isRTL = forceRTL;
if (forceLTR || forceRTL)
{
useSingleRun = true;
}
else
{
UBiDi* bidi = ubidi_open();
if (bidi)
{
UErrorCode status = U_ZERO_ERROR;
ubidi_setPara(bidi, chars, contextCount, bidiReq, NULL, &status);
if (U_SUCCESS(status))
{
int paraDir = ubidi_getParaLevel(bidi) & kDirection_Mask; // 0 if ltr, 1 if rtl
ssize_t rc = ubidi_countRuns(bidi, &status);
if (U_SUCCESS(status) && rc == 1)
{
// Normal case: one run, status is ok
isRTL = (paraDir == 1);
useSingleRun = true;
}
else if (!U_SUCCESS(status) || rc < 1)
{
// ALOGW("Need to force to single run -- string = '%s', status = %d, rc = %d", String8(chars + start, count).string(), status, int(rc));
isRTL = (paraDir == 1);
useSingleRun = true;
}
else
{
int32_t end = start + count;
for (size_t i = 0; i < size_t(rc); ++i)
{
int32_t startRun = -1;
int32_t lengthRun = -1;
UBiDiDirection runDir = ubidi_getVisualRun(bidi, i, &startRun, &lengthRun);
if (startRun == -1 || lengthRun == -1)
{
// Something went wrong when getting the visual run, need to clear
// ALOGW("Visual run is not valid");
// outGlyphs->clear();
// outAdvances->clear();
// outPos->clear();
// *outTotalAdvance = 0;
isRTL = (paraDir == 1);
useSingleRun = true;
break;
}
if (startRun >= end)
{
continue;
}
int32_t endRun = startRun + lengthRun;
if (endRun <= int32_t(start))
{
continue;
}
if (startRun < int32_t(start))
{
startRun = int32_t(start);
}
if (endRun > end)
{
endRun = end;
}
lengthRun = endRun - startRun;
isRTL = (runDir == UBIDI_RTL);
// computeRunValues(paint, chars, startRun, lengthRun, contextCount, isRTL, outAdvances, outTotalAdvance, outBounds, outGlyphs, outPos);
spitRun(text, isRTL ? UBIDI_RTL : UBIDI_LTR, startRun, startRun + lengthRun);
}
}
}
else
{
// ALOGW("Cannot set Para");
useSingleRun = true;
isRTL = (bidiReq = 1) || (bidiReq = UBIDI_DEFAULT_RTL);
}
ubidi_close(bidi);
}
else
{
// ALOGW("Cannot ubidi_open()");
useSingleRun = true;
isRTL = (bidiReq = 1) || (bidiReq = UBIDI_DEFAULT_RTL);
}
}
// Default single run case
if (useSingleRun)
{
// computeRunValues(paint, chars, start, count, contextCount, isRTL, outAdvances, outTotalAdvance, outBounds, outGlyphs, outPos);
spitRun(text, isRTL ? UBIDI_RTL : UBIDI_LTR, start, start + count);
}
}
class Application : public AppNative
{
public:
void setup();
void draw();
};
void Application::setup()
{
// bidi1("The title is مفتاح معايير الويب in Arabic.");
bidi2("The title is مفتاح معايير الويب in Arabic.");
bidi2("foo bar");
}
void Application::draw()
{
gl::clear(Color::gray(0.5f), false);
}
CINDER_APP_NATIVE(Application, RendererGl(RendererGl::AA_NONE))
<|endoftext|> |
<commit_before>// Copyright 2004-present Facebook. All Rights Reserved.
#include "JSCHelpers.h"
#include <JavaScriptCore/JSStringRef.h>
#include <glog/logging.h>
#include "Value.h"
namespace facebook {
namespace react {
void installGlobalFunction(
JSGlobalContextRef ctx,
const char* name,
JSObjectCallAsFunctionCallback callback) {
JSStringRef jsName = JSStringCreateWithUTF8CString(name);
JSObjectRef functionObj = JSObjectMakeFunctionWithCallback(
ctx, jsName, callback);
JSObjectRef globalObject = JSContextGetGlobalObject(ctx);
JSObjectSetProperty(ctx, globalObject, jsName, functionObj, 0, NULL);
JSStringRelease(jsName);
}
JSValueRef makeJSCException(
JSContextRef ctx,
const char* exception_text) {
JSStringRef message = JSStringCreateWithUTF8CString(exception_text);
JSValueRef exceptionString = JSValueMakeString(ctx, message);
JSStringRelease(message);
return JSValueToObject(ctx, exceptionString, NULL);
}
JSValueRef evaluateScript(JSContextRef context, JSStringRef script, JSStringRef source) {
JSValueRef exn, result;
result = JSEvaluateScript(context, script, NULL, source, 0, &exn);
if (result == nullptr) {
Value exception = Value(context, exn);
std::string exceptionText = exception.toString().str();
LOG(ERROR) << "Got JS Exception: " << exceptionText;
auto line = exception.asObject().getProperty("line");
std::ostringstream locationInfo;
std::string file = source != nullptr ? String::ref(source).str() : "";
locationInfo << "(" << (file.length() ? file : "<unknown file>");
if (line != nullptr && line.isNumber()) {
locationInfo << ":" << line.asInteger();
}
locationInfo << ")";
throwJSExecutionException("%s %s", exceptionText.c_str(), locationInfo.str().c_str());
}
return result;
}
JSValueRef makeJSError(JSContextRef ctx, const char *error) {
JSValueRef nestedException = nullptr;
JSValueRef args[] = { Value(ctx, String(error)) };
JSObjectRef errorObj = JSObjectMakeError(ctx, 1, args, &nestedException);
if (nestedException != nullptr) {
return std::move(args[0]);
}
return errorObj;
}
JSValueRef translatePendingCppExceptionToJSError(JSContextRef ctx, const char *exceptionLocation) {
std::ostringstream msg;
try {
throw;
} catch (const std::bad_alloc& ex) {
throw; // We probably shouldn't try to handle this in JS
} catch (const std::exception& ex) {
msg << "C++ Exception in '" << exceptionLocation << "': " << ex.what();
return makeJSError(ctx, msg.str().c_str());
} catch (const char* ex) {
msg << "C++ Exception (thrown as a char*) in '" << exceptionLocation << "': " << ex;
return makeJSError(ctx, msg.str().c_str());
} catch (...) {
msg << "Unknown C++ Exception in '" << exceptionLocation << "'";
return makeJSError(ctx, msg.str().c_str());
}
}
} }
<commit_msg>remove useless text from js errors<commit_after>// Copyright 2004-present Facebook. All Rights Reserved.
#include "JSCHelpers.h"
#include <JavaScriptCore/JSStringRef.h>
#include <folly/String.h>
#include <glog/logging.h>
#include "Value.h"
namespace facebook {
namespace react {
void installGlobalFunction(
JSGlobalContextRef ctx,
const char* name,
JSObjectCallAsFunctionCallback callback) {
JSStringRef jsName = JSStringCreateWithUTF8CString(name);
JSObjectRef functionObj = JSObjectMakeFunctionWithCallback(
ctx, jsName, callback);
JSObjectRef globalObject = JSContextGetGlobalObject(ctx);
JSObjectSetProperty(ctx, globalObject, jsName, functionObj, 0, NULL);
JSStringRelease(jsName);
}
JSValueRef makeJSCException(
JSContextRef ctx,
const char* exception_text) {
JSStringRef message = JSStringCreateWithUTF8CString(exception_text);
JSValueRef exceptionString = JSValueMakeString(ctx, message);
JSStringRelease(message);
return JSValueToObject(ctx, exceptionString, NULL);
}
JSValueRef evaluateScript(JSContextRef context, JSStringRef script, JSStringRef source) {
JSValueRef exn, result;
result = JSEvaluateScript(context, script, NULL, source, 0, &exn);
if (result == nullptr) {
Value exception = Value(context, exn);
std::string exceptionText = exception.toString().str();
// The null/empty-ness of source tells us if the JS came from a
// file/resource, or was a constructed statement. The location
// info will include that source, if any.
std::string locationInfo = source != nullptr ? String::ref(source).str() : "";
auto line = exception.asObject().getProperty("line");
if (line != nullptr && line.isNumber()) {
if (locationInfo.empty() && line.asInteger() != 1) {
// If there is a non-trivial line number, but there was no
// location info, we include a placeholder, and the line
// number.
locationInfo = folly::to<std::string>("<unknown file>:", line.asInteger());
} else if (!locationInfo.empty()) {
// If there is location info, we always include the line
// number, regardless of its value.
locationInfo += folly::to<std::string>(":", line.asInteger());
}
}
if (!locationInfo.empty()) {
exceptionText += " (" + locationInfo + ")";
}
LOG(ERROR) << "Got JS Exception: " << exceptionText;
throwJSExecutionException("%s", exceptionText.c_str());
}
return result;
}
JSValueRef makeJSError(JSContextRef ctx, const char *error) {
JSValueRef nestedException = nullptr;
JSValueRef args[] = { Value(ctx, String(error)) };
JSObjectRef errorObj = JSObjectMakeError(ctx, 1, args, &nestedException);
if (nestedException != nullptr) {
return std::move(args[0]);
}
return errorObj;
}
JSValueRef translatePendingCppExceptionToJSError(JSContextRef ctx, const char *exceptionLocation) {
std::ostringstream msg;
try {
throw;
} catch (const std::bad_alloc& ex) {
throw; // We probably shouldn't try to handle this in JS
} catch (const std::exception& ex) {
msg << "C++ Exception in '" << exceptionLocation << "': " << ex.what();
return makeJSError(ctx, msg.str().c_str());
} catch (const char* ex) {
msg << "C++ Exception (thrown as a char*) in '" << exceptionLocation << "': " << ex;
return makeJSError(ctx, msg.str().c_str());
} catch (...) {
msg << "Unknown C++ Exception in '" << exceptionLocation << "'";
return makeJSError(ctx, msg.str().c_str());
}
}
} }
<|endoftext|> |
<commit_before>#include "splitruns.h"
#include "pvalue.h"
#include "gtest/gtest.h"
#include <gsl/gsl_cdf.h>
TEST(splitruns, split)
{
constexpr double Tobs = 15.5;
constexpr unsigned N = 12;
constexpr unsigned n = 2;
const double F = runs_cumulative(Tobs, N);
const double approx = F*F / (1.0 + Delta(Tobs, N, N));
EXPECT_NEAR(approx, runs_split_cumulative(Tobs, N, n), 1e-15);
}
void test_on_grid(const unsigned K, const unsigned N, const unsigned n, const double eps=2e-7)
{
// check for absolute difference, same as relative error when all values near one.
// agreement better when cumulative closer to one, or Tobs larger
for (auto i = 1u; i < K; ++i) {
const double Tobs = 20 + 2*i;
EXPECT_NEAR(runs_split_cumulative(Tobs, N, n), runs_cumulative(Tobs, n*N), eps)
<< " at Tobs = " << Tobs << ", N = " << N << ", and n = " << n;
}
}
TEST(splitruns, approx)
{
// compare with full results
constexpr unsigned K = 15;
constexpr unsigned N = 40;
test_on_grid(K, N, 2, 2e-7);
// test_on_grid(K, N, 3, 4e-7);
}
TEST(splitruns, hH)
{
constexpr double Tobs = 15.5;
constexpr double x = 3.3;
constexpr unsigned N = 12;
// compare to mathematica
EXPECT_NEAR(h(Tobs, N), 0.000373964, 1e-8);
EXPECT_NEAR(H(Tobs-x, Tobs, N), 0.00245352, 1e-8);
EXPECT_NEAR(Delta(Tobs, N, N), 0.00175994, 1e-8);
}
TEST(splitruns, cdf)
{
EXPECT_NEAR(gsl_cdf_chisq_P(15.5, 12), 0.784775, 1e-6);
}
TEST(splitruns, long)
{
// just use gtest to measure the time
constexpr double Tobs = 32;
constexpr unsigned N = 60;
// constexpr unsigned n = 5;
// runs_split_cumulative(Tobs, N, n, 1e-13, 1e-20);
Delta(Tobs, N, N, 1e-4, 1e-20);
}
TEST(splitruns, interpolate)
{
constexpr double Tobs = 32;
std::cout << std::setprecision(15);
double F71 = runs_split_cumulative(Tobs, 71, 5);
double F88 = runs_split_cumulative(Tobs, 88, 4);
double F89 = runs_split_cumulative(Tobs, 89, 4);
double F100 = runs_split_cumulative(Tobs, 100, 3.55);
std::cout << "F(32|5*71) = " << F71 << std::endl;
std::cout << "1/3 F(32|4*88) + 3/4 F(32|4*89) = " << (F88 + 3*F89)/4 << std::endl;
std::cout << "F(32|3.55*100) = " << F100 << std::endl;
EXPECT_NEAR(F71, F100, 3e-9);
EXPECT_NEAR(F71,(F88 + 3*F89)/4, 2e-9);
}
TEST(splitruns, bound_error)
{
// the true correction is bounded by scaling by F(T) and F(2T)
constexpr double Tobs = 8;
EXPECT_NEAR(runs_cumulative(Tobs, 100), pow(runs_cumulative(Tobs, 50), 2) - runs_cumulative(1*Tobs, 100) * Delta(Tobs, 100), 1e-3);
}
<commit_msg>[splitruns_TEST] fix for new Delta(...)<commit_after>#include "splitruns.h"
#include "pvalue.h"
#include "gtest/gtest.h"
#include <gsl/gsl_cdf.h>
TEST(splitruns, split)
{
constexpr double Tobs = 15.5;
constexpr unsigned N = 12;
constexpr unsigned n = 2;
const double F = runs_cumulative(Tobs, N);
const double approx = F*F / (1.0 + Delta(Tobs, N, N));
EXPECT_NEAR(approx, runs_split_cumulative(Tobs, N, n), 1e-15);
}
void test_on_grid(const unsigned K, const unsigned N, const unsigned n, const double eps=2e-7)
{
// check for absolute difference, same as relative error when all values near one.
// agreement better when cumulative closer to one, or Tobs larger
for (auto i = 1u; i < K; ++i) {
const double Tobs = 20 + 2*i;
EXPECT_NEAR(runs_split_cumulative(Tobs, N, n), runs_cumulative(Tobs, n*N), eps)
<< " at Tobs = " << Tobs << ", N = " << N << ", and n = " << n;
}
}
TEST(splitruns, approx)
{
// compare with full results
constexpr unsigned K = 15;
constexpr unsigned N = 40;
test_on_grid(K, N, 2, 2e-7);
// test_on_grid(K, N, 3, 4e-7);
}
TEST(splitruns, hH)
{
constexpr double Tobs = 15.5;
constexpr double x = 3.3;
constexpr unsigned N = 12;
// compare to mathematica
EXPECT_NEAR(h(Tobs, N), 0.000373964, 1e-8);
EXPECT_NEAR(H(Tobs-x, Tobs, N), 0.00245352, 1e-8);
EXPECT_NEAR(Delta(Tobs, N, N), 0.00175994, 1e-8);
}
TEST(splitruns, cdf)
{
EXPECT_NEAR(gsl_cdf_chisq_P(15.5, 12), 0.784775, 1e-6);
}
TEST(splitruns, long)
{
// just use gtest to measure the time
constexpr double Tobs = 32;
constexpr unsigned N = 60;
// constexpr unsigned n = 5;
// runs_split_cumulative(Tobs, N, n, 1e-13, 1e-20);
Delta(Tobs, N, N, 1e-4, 1e-20);
}
TEST(splitruns, interpolate)
{
constexpr double Tobs = 32;
std::cout << std::setprecision(15);
double F71 = runs_split_cumulative(Tobs, 71, 5);
double F88 = runs_split_cumulative(Tobs, 88, 4);
double F89 = runs_split_cumulative(Tobs, 89, 4);
double F100 = runs_split_cumulative(Tobs, 100, 3.55);
std::cout << "F(32|5*71) = " << F71 << std::endl;
std::cout << "1/3 F(32|4*88) + 3/4 F(32|4*89) = " << (F88 + 3*F89)/4 << std::endl;
std::cout << "F(32|3.55*100) = " << F100 << std::endl;
EXPECT_NEAR(F71, F100, 3e-9);
EXPECT_NEAR(F71,(F88 + 3*F89)/4, 2e-9);
}
TEST(splitruns, bound_error)
{
// the true correction is bounded by scaling by F(T) and F(2T)
constexpr double Tobs = 8;
EXPECT_NEAR(runs_cumulative(Tobs, 100), pow(runs_cumulative(Tobs, 50), 2) - runs_cumulative(1*Tobs, 100) * Delta(Tobs, 100, 100), 1e-3);
}
<|endoftext|> |
<commit_before>#include "splitruns.h"
#include "pvalue.h"
#include "gtest/gtest.h"
#include <gsl/gsl_cdf.h>
TEST(splitruns, split)
{
constexpr double Tobs = 15.5;
constexpr unsigned N = 12;
constexpr unsigned n = 2;
const double F = runs_cumulative(Tobs, N);
const double approx = F*F / (1.0 + Delta(Tobs, N));
EXPECT_NEAR(approx, runs_split_cumulative(Tobs, N, n), 1e-15);
}
void test_on_grid(const unsigned K, const unsigned N, const unsigned n, const double eps=2e-7)
{
// check for absolute difference, same as relative error when all values near one.
// agreement better when cumulative closer to one, or Tobs larger
for (auto i = 1u; i < K; ++i) {
const double Tobs = 20 + 2*i;
EXPECT_NEAR(runs_split_cumulative(Tobs, N, n), runs_cumulative(Tobs, n*N), eps)
<< " at Tobs = " << Tobs << ", N = " << N << ", and n = " << n;
}
}
TEST(splitruns, approx)
{
// compare with full results
constexpr unsigned K = 15;
constexpr unsigned N = 40;
test_on_grid(K, N, 2, 2e-7);
// test_on_grid(K, N, 3, 4e-7);
}
TEST(splitruns, hH)
{
constexpr double Tobs = 15.5;
constexpr double x = 3.3;
constexpr unsigned N = 12;
// compare to mathematica
EXPECT_NEAR(h(Tobs, N), 0.000373964, 1e-8);
EXPECT_NEAR(H(Tobs-x, Tobs, N), 0.00245352, 1e-8);
EXPECT_NEAR(Delta(Tobs, N), 0.00175994, 1e-8);
}
TEST(splitruns, cdf)
{
EXPECT_NEAR(gsl_cdf_chisq_P(15.5, 12), 0.784775, 1e-6);
}
TEST(splitruns, long)
{
// just use gtest to measure the time
constexpr double Tobs = 32;
constexpr unsigned N = 60;
// constexpr unsigned n = 5;
// runs_split_cumulative(Tobs, N, n, 1e-13, 1e-20);
Delta(Tobs, N, 1e-4, 1e-20);
}
TEST(splitruns, interpolate)
{
constexpr double Tobs = 32;
std::cout << std::setprecision(15);
double F71 = runs_split_cumulative(Tobs, 71, 5);
double F88 = runs_split_cumulative(Tobs, 88, 4);
double F89 = runs_split_cumulative(Tobs, 89, 4);
double F100 = runs_split_cumulative(Tobs, 100, 3.55);
std::cout << "F(32|5*71) = " << F71 << std::endl;
std::cout << "1/3 F(32|4*88) + 3/4 F(32|4*89) = " << (F88 + 3*F89)/4 << std::endl;
std::cout << "F(32|3.55*100) = " << F100 << std::endl;
EXPECT_NEAR(F71, F100, 3e-9);
EXPECT_NEAR(F71,(F88 + 3*F89)/4, 2e-9);
}
<commit_msg>[test] Add test to bound error<commit_after>#include "splitruns.h"
#include "pvalue.h"
#include "gtest/gtest.h"
#include <gsl/gsl_cdf.h>
TEST(splitruns, split)
{
constexpr double Tobs = 15.5;
constexpr unsigned N = 12;
constexpr unsigned n = 2;
const double F = runs_cumulative(Tobs, N);
const double approx = F*F / (1.0 + Delta(Tobs, N));
EXPECT_NEAR(approx, runs_split_cumulative(Tobs, N, n), 1e-15);
}
void test_on_grid(const unsigned K, const unsigned N, const unsigned n, const double eps=2e-7)
{
// check for absolute difference, same as relative error when all values near one.
// agreement better when cumulative closer to one, or Tobs larger
for (auto i = 1u; i < K; ++i) {
const double Tobs = 20 + 2*i;
EXPECT_NEAR(runs_split_cumulative(Tobs, N, n), runs_cumulative(Tobs, n*N), eps)
<< " at Tobs = " << Tobs << ", N = " << N << ", and n = " << n;
}
}
TEST(splitruns, approx)
{
// compare with full results
constexpr unsigned K = 15;
constexpr unsigned N = 40;
test_on_grid(K, N, 2, 2e-7);
// test_on_grid(K, N, 3, 4e-7);
}
TEST(splitruns, hH)
{
constexpr double Tobs = 15.5;
constexpr double x = 3.3;
constexpr unsigned N = 12;
// compare to mathematica
EXPECT_NEAR(h(Tobs, N), 0.000373964, 1e-8);
EXPECT_NEAR(H(Tobs-x, Tobs, N), 0.00245352, 1e-8);
EXPECT_NEAR(Delta(Tobs, N), 0.00175994, 1e-8);
}
TEST(splitruns, cdf)
{
EXPECT_NEAR(gsl_cdf_chisq_P(15.5, 12), 0.784775, 1e-6);
}
TEST(splitruns, long)
{
// just use gtest to measure the time
constexpr double Tobs = 32;
constexpr unsigned N = 60;
// constexpr unsigned n = 5;
// runs_split_cumulative(Tobs, N, n, 1e-13, 1e-20);
Delta(Tobs, N, 1e-4, 1e-20);
}
TEST(splitruns, interpolate)
{
constexpr double Tobs = 32;
std::cout << std::setprecision(15);
double F71 = runs_split_cumulative(Tobs, 71, 5);
double F88 = runs_split_cumulative(Tobs, 88, 4);
double F89 = runs_split_cumulative(Tobs, 89, 4);
double F100 = runs_split_cumulative(Tobs, 100, 3.55);
std::cout << "F(32|5*71) = " << F71 << std::endl;
std::cout << "1/3 F(32|4*88) + 3/4 F(32|4*89) = " << (F88 + 3*F89)/4 << std::endl;
std::cout << "F(32|3.55*100) = " << F100 << std::endl;
EXPECT_NEAR(F71, F100, 3e-9);
EXPECT_NEAR(F71,(F88 + 3*F89)/4, 2e-9);
}
TEST(splitruns, bound_error)
{
// the true correction is bounded by scaling by F(T) and F(2T)
constexpr double Tobs = 8;
EXPECT_NEAR(runs_cumulative(Tobs, 100), pow(runs_cumulative(Tobs, 50), 2) - runs_cumulative(1*Tobs, 100) * Delta(Tobs, 100), 1e-3);
}
<|endoftext|> |
<commit_before><commit_msg>Fix some clang warnings with -Wmissing-braces in rlz.<commit_after><|endoftext|> |
<commit_before>/*
DS18B20.h - Library for reading the voltage of a battery or solarcell.
See sensV for circuitry.
Created by Maurice (Mausy5043) Hendrix, FEB2015
MIT license
*/
#include "DS18B20.h"
DS18B20::DS18B20(int pin, int samples)
{
_pin = pin;
_samples = samples;
}
void DS18B20::begin(void)
{
// set up the pin!
OneWire _1wire(_pin);
_invsamples = 1.0/(float)_samples;
if ( !ds.search(_addr))
{
Serial.println("No sensor.");
}
}
float DS18B20::readTemperature(void)
{
int cntSamples = 0;
int sumSamples = 0;
float measurement = 0.0;
// add up the pre-defined number of _samples for Sample Averaging
for (cntSamples = 0; cntSamples < _samples; cntSamples++)
{
//sumSamples += analogRead(_pin);
// minimum delay on analog pins is 100ms
delay(110);
}
//measurement = (float)sumSamples * _invsamples; // Calculate avg raw value.
//measurement = map(measurement * 10, 0, 10230, 0, _ref5v * 10000) * 0.0001;
//measurement *= _r12;
//return measurement;
return -0.001;
}
<commit_msg>20150217.1457<commit_after>/*
DS18B20.h - Library for reading the voltage of a battery or solarcell.
See sensV for circuitry.
Created by Maurice (Mausy5043) Hendrix, FEB2015
MIT license
*/
#include "DS18B20.h"
DS18B20::DS18B20(int pin, int samples)
{
_pin = pin;
_samples = samples;
}
void DS18B20::begin(void)
{
// set up the pin!
OneWire _1wire(_pin);
_invsamples = 1.0/(float)_samples;
if ( !_1wire.search(_addr))
{
Serial.println("No sensor.");
}
}
float DS18B20::readTemperature(void)
{
int cntSamples = 0;
int sumSamples = 0;
float measurement = 0.0;
// add up the pre-defined number of _samples for Sample Averaging
for (cntSamples = 0; cntSamples < _samples; cntSamples++)
{
//sumSamples += analogRead(_pin);
// minimum delay on analog pins is 100ms
delay(110);
}
//measurement = (float)sumSamples * _invsamples; // Calculate avg raw value.
//measurement = map(measurement * 10, 0, 10230, 0, _ref5v * 10000) * 0.0001;
//measurement *= _r12;
//return measurement;
return -0.001;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2011-2012 Stephen Williams (steve@icarus.com)
* Copyright (c) 2014 CERN
* @author Maciej Suminski (maciej.suminski@cern.ch)
*
* This source code is free software; you can redistribute it
* and/or modify it in source code form under the terms of the GNU
* General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
# include "vtype.h"
# include "expression.h"
# include <iostream>
# include <typeinfo>
# include <cassert>
using namespace std;
int VType::decl_t::emit(ostream&out, perm_string name) const
{
return type->emit_decl(out, name, reg_flag);
}
int VType::emit_decl(ostream&out, perm_string name, bool reg_flag) const
{
int errors = 0;
if (!reg_flag)
out << "wire ";
errors += emit_def(out, name);
out << " ";
return errors;
}
int VType::emit_typedef(std::ostream&, typedef_context_t&) const
{
return 0;
}
int VTypeERROR::emit_def(ostream&out, perm_string) const
{
out << "/* ERROR */";
return 1;
}
int VTypeArray::emit_def(ostream&out, perm_string name) const
{
int errors = 0;
const VType*raw_base = basic_type();
const VTypePrimitive*base = dynamic_cast<const VTypePrimitive*> (raw_base);
if (base) {
assert(dimensions() == 1);
base->emit_def(out, empty_perm_string);
if (signed_flag_)
out << " signed";
} else {
raw_base->emit_def(out, empty_perm_string);
}
errors += emit_with_dims_(out, raw_base->can_be_packed(), name);
return errors;
}
int VTypeArray::emit_typedef(std::ostream&out, typedef_context_t&ctx) const
{
return etype_->emit_typedef(out, ctx);
}
int VTypeArray::emit_with_dims_(std::ostream&out, bool packed, perm_string name) const
{
int errors = 0;
list<const VTypeArray*> dims;
const VTypeArray*cur = this;
while (const VTypeArray*sub = dynamic_cast<const VTypeArray*> (cur->element_type())) {
dims.push_back(cur);
cur = sub;
}
dims.push_back(cur);
bool name_emitted = false;
while (! dims.empty()) {
cur = dims.front();
dims.pop_front();
if(!packed) {
emit_name(out, name);
name_emitted = true;
}
for(unsigned i = 0; i < cur->dimensions(); ++i) {
if(cur->dimension(i).is_box() && !name_emitted) {
emit_name(out, name);
name_emitted = true;
}
out << "[";
if (!cur->dimension(i).is_box()) { // if not unbounded {
errors += cur->dimension(i).msb()->emit(out, 0, 0);
out << ":";
errors += cur->dimension(i).lsb()->emit(out, 0, 0);
}
out << "]";
}
}
if(!name_emitted) {
emit_name(out, name);
}
return errors;
}
int VTypeEnum::emit_def(ostream&out, perm_string name) const
{
int errors = 0;
out << "enum integer {";
assert(names_.size() >= 1);
out << "\\" << names_[0] << " ";
for (size_t idx = 1 ; idx < names_.size() ; idx += 1)
out << ", \\" << names_[idx] << " ";
out << "}";
emit_name(out, name);
return errors;
}
int VTypePrimitive::emit_primitive_type(ostream&out) const
{
int errors = 0;
switch (type_) {
case BIT:
out << "bit";
break;
case STDLOGIC:
out << "logic";
break;
case NATURAL:
out << "int unsigned";
break;
case INTEGER:
out << "int";
break;
case REAL:
out << "real";
break;
case TIME:
out << "time";
break;
default:
assert(0);
break;
}
return errors;
}
int VTypePrimitive::emit_def(ostream&out, perm_string name) const
{
int errors = 0;
errors += emit_primitive_type(out);
emit_name(out, name);
return errors;
}
int VTypeRange::emit_def(ostream&out, perm_string name) const
{
int errors = 0;
out << "/* Internal error: Don't know how to emit range */";
errors += base_->emit_def(out, name);
return errors;
}
int VTypeRecord::emit_def(ostream&out, perm_string name) const
{
int errors = 0;
out << "struct packed {";
for (vector<element_t*>::const_iterator cur = elements_.begin()
; cur != elements_.end() ; ++cur) {
perm_string element_name = (*cur)->peek_name();
const VType*element_type = (*cur)->peek_type();
element_type->emit_def(out, empty_perm_string);
out << " \\" << element_name << " ; ";
}
out << "}";
emit_name(out, name);
return errors;
}
/*
* For VTypeDef objects, use the name of the defined type as the
* type. (We are defining a variable here, not the type itself.) The
* emit_typedef() method was presumably called to define type already.
*/
int VTypeDef::emit_def(ostream&out, perm_string name) const
{
int errors = 0;
emit_name(out, name_);
emit_name(out, name);
return errors;
}
int VTypeDef::emit_decl(ostream&out, perm_string name, bool reg_flag) const
{
int errors = 0;
if (!dynamic_cast<const VTypeEnum*>(type_))
out << (reg_flag ? "reg " : "wire ");
if(dynamic_cast<const VTypeArray*>(type_)) {
errors += type_->emit_def(out, name);
} else {
assert(name_ != empty_perm_string);
cout << "\\" << name_;
emit_name(out, name);
}
return errors;
}
int VTypeDef::emit_typedef(ostream&out, typedef_context_t&ctx) const
{
// The typedef_context_t is used by me to determine if this
// typedef has already been emitted in this architecture. If
// it has, then it is MARKED, give up. Otherwise, recurse the
// emit_typedef to make sure all sub-types that I use have
// been emitted, then emit my typedef.
typedef_topo_t&flag = ctx[this];
switch (flag) {
case MARKED:
return 0;
case PENDING:
out << "typedef \\" << name_ << " ; /* typedef cycle? */" << endl;
return 0;
case NONE:
break;
}
flag = PENDING;
int errors = type_->emit_typedef(out, ctx);
flag = MARKED;
// Array types are used directly anyway and typedefs for unpacked
// arrays do not work currently
if(dynamic_cast<const VTypeArray*>(type_))
out << "// ";
out << "typedef ";
errors += type_->emit_def(out, name_);
out << " ;" << endl;
return errors;
}
<commit_msg>vhdlpp: Special handling for STRING type during type emission.<commit_after>/*
* Copyright (c) 2011-2012 Stephen Williams (steve@icarus.com)
* Copyright (c) 2014 CERN
* @author Maciej Suminski (maciej.suminski@cern.ch)
*
* This source code is free software; you can redistribute it
* and/or modify it in source code form under the terms of the GNU
* General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
# include "vtype.h"
# include "expression.h"
# include "std_types.h"
# include <iostream>
# include <typeinfo>
# include <cassert>
using namespace std;
int VType::decl_t::emit(ostream&out, perm_string name) const
{
return type->emit_decl(out, name, reg_flag);
}
int VType::emit_decl(ostream&out, perm_string name, bool reg_flag) const
{
int errors = 0;
if (!reg_flag)
out << "wire ";
errors += emit_def(out, name);
out << " ";
return errors;
}
int VType::emit_typedef(std::ostream&, typedef_context_t&) const
{
return 0;
}
int VTypeERROR::emit_def(ostream&out, perm_string) const
{
out << "/* ERROR */";
return 1;
}
int VTypeArray::emit_def(ostream&out, perm_string name) const
{
int errors = 0;
const VType*raw_base = basic_type();
const VTypePrimitive*base = dynamic_cast<const VTypePrimitive*> (raw_base);
if (base) {
assert(dimensions() == 1);
// If this is a string type without any boundaries specified, then
// there is a direct counterpart in SV called.. 'string'
if(this == &primitive_STRING) {
out << "string";
emit_name(out, name);
return errors;
}
base->emit_def(out, empty_perm_string);
if (signed_flag_)
out << " signed";
} else {
raw_base->emit_def(out, empty_perm_string);
}
errors += emit_with_dims_(out, raw_base->can_be_packed(), name);
return errors;
}
int VTypeArray::emit_typedef(std::ostream&out, typedef_context_t&ctx) const
{
return etype_->emit_typedef(out, ctx);
}
int VTypeArray::emit_with_dims_(std::ostream&out, bool packed, perm_string name) const
{
int errors = 0;
list<const VTypeArray*> dims;
const VTypeArray*cur = this;
while (const VTypeArray*sub = dynamic_cast<const VTypeArray*> (cur->element_type())) {
dims.push_back(cur);
cur = sub;
}
dims.push_back(cur);
bool name_emitted = false;
while (! dims.empty()) {
cur = dims.front();
dims.pop_front();
if(!packed) {
emit_name(out, name);
name_emitted = true;
}
for(unsigned i = 0; i < cur->dimensions(); ++i) {
if(cur->dimension(i).is_box() && !name_emitted) {
emit_name(out, name);
name_emitted = true;
}
out << "[";
if (!cur->dimension(i).is_box()) { // if not unbounded {
errors += cur->dimension(i).msb()->emit(out, 0, 0);
out << ":";
errors += cur->dimension(i).lsb()->emit(out, 0, 0);
}
out << "]";
}
}
if(!name_emitted) {
emit_name(out, name);
}
return errors;
}
int VTypeEnum::emit_def(ostream&out, perm_string name) const
{
int errors = 0;
out << "enum integer {";
assert(names_.size() >= 1);
out << "\\" << names_[0] << " ";
for (size_t idx = 1 ; idx < names_.size() ; idx += 1)
out << ", \\" << names_[idx] << " ";
out << "}";
emit_name(out, name);
return errors;
}
int VTypePrimitive::emit_primitive_type(ostream&out) const
{
int errors = 0;
switch (type_) {
case BIT:
out << "bit";
break;
case STDLOGIC:
out << "logic";
break;
case NATURAL:
out << "int unsigned";
break;
case INTEGER:
out << "int";
break;
case REAL:
out << "real";
break;
case TIME:
out << "time";
break;
default:
assert(0);
break;
}
return errors;
}
int VTypePrimitive::emit_def(ostream&out, perm_string name) const
{
int errors = 0;
errors += emit_primitive_type(out);
emit_name(out, name);
return errors;
}
int VTypeRange::emit_def(ostream&out, perm_string name) const
{
int errors = 0;
out << "/* Internal error: Don't know how to emit range */";
errors += base_->emit_def(out, name);
return errors;
}
int VTypeRecord::emit_def(ostream&out, perm_string name) const
{
int errors = 0;
out << "struct packed {";
for (vector<element_t*>::const_iterator cur = elements_.begin()
; cur != elements_.end() ; ++cur) {
perm_string element_name = (*cur)->peek_name();
const VType*element_type = (*cur)->peek_type();
element_type->emit_def(out, empty_perm_string);
out << " \\" << element_name << " ; ";
}
out << "}";
emit_name(out, name);
return errors;
}
/*
* For VTypeDef objects, use the name of the defined type as the
* type. (We are defining a variable here, not the type itself.) The
* emit_typedef() method was presumably called to define type already.
*/
int VTypeDef::emit_def(ostream&out, perm_string name) const
{
int errors = 0;
emit_name(out, name_);
emit_name(out, name);
return errors;
}
int VTypeDef::emit_decl(ostream&out, perm_string name, bool reg_flag) const
{
int errors = 0;
if (!dynamic_cast<const VTypeEnum*>(type_))
out << (reg_flag ? "reg " : "wire ");
if(dynamic_cast<const VTypeArray*>(type_)) {
errors += type_->emit_def(out, name);
} else {
assert(name_ != empty_perm_string);
cout << "\\" << name_;
emit_name(out, name);
}
return errors;
}
int VTypeDef::emit_typedef(ostream&out, typedef_context_t&ctx) const
{
// The typedef_context_t is used by me to determine if this
// typedef has already been emitted in this architecture. If
// it has, then it is MARKED, give up. Otherwise, recurse the
// emit_typedef to make sure all sub-types that I use have
// been emitted, then emit my typedef.
typedef_topo_t&flag = ctx[this];
switch (flag) {
case MARKED:
return 0;
case PENDING:
out << "typedef \\" << name_ << " ; /* typedef cycle? */" << endl;
return 0;
case NONE:
break;
}
flag = PENDING;
int errors = type_->emit_typedef(out, ctx);
flag = MARKED;
// Array types are used directly anyway and typedefs for unpacked
// arrays do not work currently
if(dynamic_cast<const VTypeArray*>(type_))
out << "// ";
out << "typedef ";
errors += type_->emit_def(out, name_);
out << " ;" << endl;
return errors;
}
<|endoftext|> |
<commit_before>//
// MurmurHash3, by Austin Appleby
//
// Originals at:
// http://code.google.com/p/smhasher/source/browse/trunk/MurmurHash3.cpp
// http://code.google.com/p/smhasher/source/browse/trunk/MurmurHash3.h
//
// Notes:
// 1) this code assumes we can read a 4-byte value from any address
// without crashing (i.e non aligned access is supported). This is
// not a problem on Intel/x86/AMD64 machines (including new Macs)
// 2) It produces different results on little-endian and big-endian machines.
//
// Adopted for VW and contributed by Ariel Faigon.
//
#include <sys/types.h> /* defines size_t */
// Platform-specific functions and macros
// Microsoft Visual Studio
#if defined(_MSC_VER)
typedef unsigned char uint8_t;
typedef unsigned long uint32_t;
typedef unsigned __int64 uint64_t;
// Other compilers
#else // defined(_MSC_VER)
# include <stdint.h> /* defines uint32_t etc */
#endif // !defined(_MSC_VER)
//-----------------------------------------------------------------------------
// MurmurHash3 was written by Austin Appleby, and is placed in the public
// domain. The author hereby disclaims copyright to this source code.
// Note - The x86 and x64 versions do _not_ produce the same results, as the
// algorithms are optimized for their respective platforms. You can still
// compile and run any of them on any platform, but your performance with the
// non-native version will be less than optimal.
//-----------------------------------------------------------------------------
// Platform-specific functions and macros
#if defined(_MSC_VER) // Microsoft Visual Studio
# define FORCE_INLINE __forceinline
# include <stdlib.h>
# define ROTL32(x,y) _rotl(x,y)
# define BIG_CONSTANT(x) (x)
#else // Other compilers
# define FORCE_INLINE __attribute__((always_inline))
inline uint32_t rotl32 ( uint32_t x, int8_t r )
{
return (x << r) | (x >> (32 - r));
}
# define ROTL32(x,y) rotl32(x,y)
# define BIG_CONSTANT(x) (x##LLU)
#endif
//-----------------------------------------------------------------------------
// Block read - if your platform needs to do endian-swapping or can only
// handle aligned reads, do the conversion here
FORCE_INLINE uint32_t getblock ( const uint32_t * p, int i )
{
return p[i];
}
//-----------------------------------------------------------------------------
// Finalization mix - force all bits of a hash block to avalanche
FORCE_INLINE uint32_t fmix ( uint32_t h )
{
h ^= h >> 16;
h *= 0x85ebca6b;
h ^= h >> 13;
h *= 0xc2b2ae35;
h ^= h >> 16;
return h;
}
//-----------------------------------------------------------------------------
uint32_t uniform_hash (const void * key, size_t len, uint32_t seed)
{
const uint8_t * data = (const uint8_t*)key;
const int nblocks = len / 4;
uint32_t h1 = seed;
const uint32_t c1 = 0xcc9e2d51;
const uint32_t c2 = 0x1b873593;
// --- body
const uint32_t * blocks = (const uint32_t *)(data + nblocks*4);
for (int i = -nblocks; i; i++) {
uint32_t k1 = getblock(blocks,i);
k1 *= c1;
k1 = ROTL32(k1,15);
k1 *= c2;
h1 ^= k1;
h1 = ROTL32(h1,13);
h1 = h1*5+0xe6546b64;
}
// --- tail
const uint8_t * tail = (const uint8_t*)(data + nblocks*4);
uint32_t k1 = 0;
switch(len & 3) {
case 3: k1 ^= tail[2] << 16;
case 2: k1 ^= tail[1] << 8;
case 1: k1 ^= tail[0];
k1 *= c1; k1 = ROTL32(k1,15); k1 *= c2; h1 ^= k1;
}
// --- finalization
h1 ^= len;
return fmix(h1);
}
<commit_msg>more cleanups + merge two #ifdef's to one<commit_after>//
// MurmurHash3, by Austin Appleby
//
// Originals at:
// http://code.google.com/p/smhasher/source/browse/trunk/MurmurHash3.cpp
// http://code.google.com/p/smhasher/source/browse/trunk/MurmurHash3.h
//
// Notes:
// 1) this code assumes we can read a 4-byte value from any address
// without crashing (i.e non aligned access is supported). This is
// not a problem on Intel/x86/AMD64 machines (including new Macs)
// 2) It produces different results on little-endian and big-endian machines.
//
// Adopted for VW and contributed by Ariel Faigon.
//
//-----------------------------------------------------------------------------
// MurmurHash3 was written by Austin Appleby, and is placed in the public
// domain. The author hereby disclaims copyright to this source code.
// Note - The x86 and x64 versions do _not_ produce the same results, as the
// algorithms are optimized for their respective platforms. You can still
// compile and run any of them on any platform, but your performance with the
// non-native version will be less than optimal.
//-----------------------------------------------------------------------------
#include <sys/types.h> /* defines size_t */
// Platform-specific functions and macros
#if defined(_MSC_VER) // Microsoft Visual Studio
typedef unsigned char uint8_t;
typedef unsigned long uint32_t;
# define FORCE_INLINE __forceinline
# include <stdlib.h>
# define ROTL32(x,y) _rotl(x,y)
# define BIG_CONSTANT(x) (x)
#else // Other compilers
# include <stdint.h> /* defines uint32_t etc */
# define FORCE_INLINE __attribute__((always_inline))
inline uint32_t rotl32 (uint32_t x, int8_t r)
{
return (x << r) | (x >> (32 - r));
}
# define ROTL32(x,y) rotl32(x,y)
# define BIG_CONSTANT(x) (x##LLU)
#endif // !defined(_MSC_VER)
//-----------------------------------------------------------------------------
// Block read - if your platform needs to do endian-swapping or can only
// handle aligned reads, do the conversion here
FORCE_INLINE uint32_t getblock (const uint32_t * p, int i)
{
return p[i];
}
//-----------------------------------------------------------------------------
// Finalization mix - force all bits of a hash block to avalanche
FORCE_INLINE uint32_t fmix (uint32_t h)
{
h ^= h >> 16;
h *= 0x85ebca6b;
h ^= h >> 13;
h *= 0xc2b2ae35;
h ^= h >> 16;
return h;
}
//-----------------------------------------------------------------------------
uint32_t uniform_hash (const void * key, size_t len, uint32_t seed)
{
const uint8_t * data = (const uint8_t*)key;
const int nblocks = len / 4;
uint32_t h1 = seed;
const uint32_t c1 = 0xcc9e2d51;
const uint32_t c2 = 0x1b873593;
// --- body
const uint32_t * blocks = (const uint32_t *)(data + nblocks*4);
for (int i = -nblocks; i; i++) {
uint32_t k1 = getblock(blocks,i);
k1 *= c1;
k1 = ROTL32(k1,15);
k1 *= c2;
h1 ^= k1;
h1 = ROTL32(h1,13);
h1 = h1*5+0xe6546b64;
}
// --- tail
const uint8_t * tail = (const uint8_t*)(data + nblocks*4);
uint32_t k1 = 0;
switch(len & 3) {
case 3: k1 ^= tail[2] << 16;
case 2: k1 ^= tail[1] << 8;
case 1: k1 ^= tail[0];
k1 *= c1; k1 = ROTL32(k1,15); k1 *= c2; h1 ^= k1;
}
// --- finalization
h1 ^= len;
return fmix(h1);
}
<|endoftext|> |
<commit_before>//===-- WebAssemblyInstrInfo.cpp - WebAssembly Instruction Information ----===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief This file contains the WebAssembly implementation of the
/// TargetInstrInfo class.
///
//===----------------------------------------------------------------------===//
#include "WebAssemblyInstrInfo.h"
#include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
#include "WebAssemblySubtarget.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineMemOperand.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
using namespace llvm;
#define DEBUG_TYPE "wasm-instr-info"
#define GET_INSTRINFO_CTOR_DTOR
#include "WebAssemblyGenInstrInfo.inc"
WebAssemblyInstrInfo::WebAssemblyInstrInfo(const WebAssemblySubtarget &STI)
: WebAssemblyGenInstrInfo(WebAssembly::ADJCALLSTACKDOWN,
WebAssembly::ADJCALLSTACKUP),
RI(STI.getTargetTriple()) {}
void WebAssemblyInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
MachineBasicBlock::iterator I,
DebugLoc DL, unsigned DestReg,
unsigned SrcReg, bool KillSrc) const {
// This method is called by post-RA expansion, which expects only pregs to
// exist. However we need to handle both here.
auto &MRI = MBB.getParent()->getRegInfo();
const TargetRegisterClass *RC = TargetRegisterInfo::isVirtualRegister(DestReg) ?
MRI.getRegClass(DestReg) :
MRI.getTargetRegisterInfo()->getMinimalPhysRegClass(SrcReg);
unsigned CopyLocalOpcode;
if (RC == &WebAssembly::I32RegClass)
CopyLocalOpcode = WebAssembly::COPY_LOCAL_I32;
else if (RC == &WebAssembly::I64RegClass)
CopyLocalOpcode = WebAssembly::COPY_LOCAL_I64;
else if (RC == &WebAssembly::F32RegClass)
CopyLocalOpcode = WebAssembly::COPY_LOCAL_F32;
else if (RC == &WebAssembly::F64RegClass)
CopyLocalOpcode = WebAssembly::COPY_LOCAL_F64;
else
llvm_unreachable("Unexpected register class");
BuildMI(MBB, I, DL, get(CopyLocalOpcode), DestReg)
.addReg(SrcReg, KillSrc ? RegState::Kill : 0);
}
// Branch analysis.
bool WebAssemblyInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,
MachineBasicBlock *&TBB,
MachineBasicBlock *&FBB,
SmallVectorImpl<MachineOperand> &Cond,
bool /*AllowModify*/) const {
bool HaveCond = false;
for (MachineInstr &MI : iterator_range<MachineBasicBlock::instr_iterator>(
MBB.getFirstInstrTerminator(), MBB.instr_end())) {
switch (MI.getOpcode()) {
default:
// Unhandled instruction; bail out.
return true;
case WebAssembly::BR_IF:
if (HaveCond)
return true;
Cond.push_back(MachineOperand::CreateImm(true));
Cond.push_back(MI.getOperand(0));
TBB = MI.getOperand(1).getMBB();
HaveCond = true;
break;
case WebAssembly::BR_UNLESS:
if (HaveCond)
return true;
Cond.push_back(MachineOperand::CreateImm(false));
Cond.push_back(MI.getOperand(0));
TBB = MI.getOperand(1).getMBB();
HaveCond = true;
break;
case WebAssembly::BR:
if (!HaveCond)
TBB = MI.getOperand(0).getMBB();
else
FBB = MI.getOperand(0).getMBB();
break;
}
if (MI.isBarrier())
break;
}
return false;
}
unsigned WebAssemblyInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
MachineBasicBlock::instr_iterator I = MBB.instr_end();
unsigned Count = 0;
while (I != MBB.instr_begin()) {
--I;
if (I->isDebugValue())
continue;
if (!I->isTerminator())
break;
// Remove the branch.
I->eraseFromParent();
I = MBB.instr_end();
++Count;
}
return Count;
}
unsigned WebAssemblyInstrInfo::InsertBranch(MachineBasicBlock &MBB,
MachineBasicBlock *TBB,
MachineBasicBlock *FBB,
ArrayRef<MachineOperand> Cond,
DebugLoc DL) const {
if (Cond.empty()) {
if (!TBB)
return 0;
BuildMI(&MBB, DL, get(WebAssembly::BR)).addMBB(TBB);
return 1;
}
assert(Cond.size() == 2 && "Expected a flag and a successor block");
if (Cond[0].getImm()) {
BuildMI(&MBB, DL, get(WebAssembly::BR_IF))
.addOperand(Cond[1])
.addMBB(TBB);
} else {
BuildMI(&MBB, DL, get(WebAssembly::BR_UNLESS))
.addOperand(Cond[1])
.addMBB(TBB);
}
if (!FBB)
return 1;
BuildMI(&MBB, DL, get(WebAssembly::BR)).addMBB(FBB);
return 2;
}
bool WebAssemblyInstrInfo::ReverseBranchCondition(
SmallVectorImpl<MachineOperand> &Cond) const {
assert(Cond.size() == 2 && "Expected a flag and a successor block");
Cond.front() = MachineOperand::CreateImm(!Cond.front().getImm());
return false;
}
<commit_msg>[WebAssembly] Convert a regular for loop to a range-based for loop.<commit_after>//===-- WebAssemblyInstrInfo.cpp - WebAssembly Instruction Information ----===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief This file contains the WebAssembly implementation of the
/// TargetInstrInfo class.
///
//===----------------------------------------------------------------------===//
#include "WebAssemblyInstrInfo.h"
#include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
#include "WebAssemblySubtarget.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineMemOperand.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
using namespace llvm;
#define DEBUG_TYPE "wasm-instr-info"
#define GET_INSTRINFO_CTOR_DTOR
#include "WebAssemblyGenInstrInfo.inc"
WebAssemblyInstrInfo::WebAssemblyInstrInfo(const WebAssemblySubtarget &STI)
: WebAssemblyGenInstrInfo(WebAssembly::ADJCALLSTACKDOWN,
WebAssembly::ADJCALLSTACKUP),
RI(STI.getTargetTriple()) {}
void WebAssemblyInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
MachineBasicBlock::iterator I,
DebugLoc DL, unsigned DestReg,
unsigned SrcReg, bool KillSrc) const {
// This method is called by post-RA expansion, which expects only pregs to
// exist. However we need to handle both here.
auto &MRI = MBB.getParent()->getRegInfo();
const TargetRegisterClass *RC = TargetRegisterInfo::isVirtualRegister(DestReg) ?
MRI.getRegClass(DestReg) :
MRI.getTargetRegisterInfo()->getMinimalPhysRegClass(SrcReg);
unsigned CopyLocalOpcode;
if (RC == &WebAssembly::I32RegClass)
CopyLocalOpcode = WebAssembly::COPY_LOCAL_I32;
else if (RC == &WebAssembly::I64RegClass)
CopyLocalOpcode = WebAssembly::COPY_LOCAL_I64;
else if (RC == &WebAssembly::F32RegClass)
CopyLocalOpcode = WebAssembly::COPY_LOCAL_F32;
else if (RC == &WebAssembly::F64RegClass)
CopyLocalOpcode = WebAssembly::COPY_LOCAL_F64;
else
llvm_unreachable("Unexpected register class");
BuildMI(MBB, I, DL, get(CopyLocalOpcode), DestReg)
.addReg(SrcReg, KillSrc ? RegState::Kill : 0);
}
// Branch analysis.
bool WebAssemblyInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,
MachineBasicBlock *&TBB,
MachineBasicBlock *&FBB,
SmallVectorImpl<MachineOperand> &Cond,
bool /*AllowModify*/) const {
bool HaveCond = false;
for (MachineInstr &MI : MBB.terminators()) {
switch (MI.getOpcode()) {
default:
// Unhandled instruction; bail out.
return true;
case WebAssembly::BR_IF:
if (HaveCond)
return true;
Cond.push_back(MachineOperand::CreateImm(true));
Cond.push_back(MI.getOperand(0));
TBB = MI.getOperand(1).getMBB();
HaveCond = true;
break;
case WebAssembly::BR_UNLESS:
if (HaveCond)
return true;
Cond.push_back(MachineOperand::CreateImm(false));
Cond.push_back(MI.getOperand(0));
TBB = MI.getOperand(1).getMBB();
HaveCond = true;
break;
case WebAssembly::BR:
if (!HaveCond)
TBB = MI.getOperand(0).getMBB();
else
FBB = MI.getOperand(0).getMBB();
break;
}
if (MI.isBarrier())
break;
}
return false;
}
unsigned WebAssemblyInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
MachineBasicBlock::instr_iterator I = MBB.instr_end();
unsigned Count = 0;
while (I != MBB.instr_begin()) {
--I;
if (I->isDebugValue())
continue;
if (!I->isTerminator())
break;
// Remove the branch.
I->eraseFromParent();
I = MBB.instr_end();
++Count;
}
return Count;
}
unsigned WebAssemblyInstrInfo::InsertBranch(MachineBasicBlock &MBB,
MachineBasicBlock *TBB,
MachineBasicBlock *FBB,
ArrayRef<MachineOperand> Cond,
DebugLoc DL) const {
if (Cond.empty()) {
if (!TBB)
return 0;
BuildMI(&MBB, DL, get(WebAssembly::BR)).addMBB(TBB);
return 1;
}
assert(Cond.size() == 2 && "Expected a flag and a successor block");
if (Cond[0].getImm()) {
BuildMI(&MBB, DL, get(WebAssembly::BR_IF))
.addOperand(Cond[1])
.addMBB(TBB);
} else {
BuildMI(&MBB, DL, get(WebAssembly::BR_UNLESS))
.addOperand(Cond[1])
.addMBB(TBB);
}
if (!FBB)
return 1;
BuildMI(&MBB, DL, get(WebAssembly::BR)).addMBB(FBB);
return 2;
}
bool WebAssemblyInstrInfo::ReverseBranchCondition(
SmallVectorImpl<MachineOperand> &Cond) const {
assert(Cond.size() == 2 && "Expected a flag and a successor block");
Cond.front() = MachineOperand::CreateImm(!Cond.front().getImm());
return false;
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of NVIDIA CORPORATION nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "problem-shape.hpp"
#include "workload.hpp"
namespace problem
{
// ======================================== //
// Shape instance //
// ======================================== //
// See comment in .hpp file.
Shape shape_;
const Shape* GetShape()
{
return &shape_;
}
// ======================================== //
// Workload //
// ======================================== //
std::string ShapeFileName(const std::string shape_name)
{
std::string shape_file_name;
std::string shape_dir;
const char* shape_dir_env = std::getenv("TIMELOOP_PROBLEM_SHAPE_DIR");
if (shape_dir_env)
{
shape_dir = std::string(shape_dir_env) + "/";
}
else
{
const char* timeloopdir = std::getenv("TIMELOOP_DIR");
if (!timeloopdir)
{
timeloopdir = BUILD_BASE_DIR;
}
shape_dir = std::string(timeloopdir) + "/problem-shapes/";
}
shape_file_name = shape_dir + shape_name + ".cfg";
std::cerr << "MESSAGE: reading problem shapes from: " << shape_dir << std::endl;
std::cout << "MESSAGE: attempting to read problem shape from file: " << shape_file_name << std::endl;
return shape_file_name;
}
void ParseWorkload(config::CompoundConfigNode config, Workload& workload)
{
std::string shape_name;
// FIXME: replace this ShapeFileName to also use compound-config
if (!config.exists("shape"))
{
std::cerr << "WARNING: found neither a problem shape description nor a string corresponding to a to a pre-existing shape description. Assuming shape: cnn-layer." << std::endl;
config::CompoundConfig shape_config(ShapeFileName("cnn-layer").c_str());
auto shape = shape_config.getRoot().lookup("shape");
shape_.Parse(shape);
}
else if (config.lookupValue("shape", shape_name))
{
config::CompoundConfig shape_config(ShapeFileName(shape_name).c_str());
auto shape = shape_config.getRoot().lookup("shape");
shape_.Parse(shape);
}
else
{
auto shape = config.lookup("shape");
shape_.Parse(shape);
}
// Loop bounds for each problem dimension.
Workload::Bounds bounds;
for (unsigned i = 0; i < GetShape()->NumDimensions; i++)
assert(config.lookupValue(GetShape()->DimensionIDToName.at(i), bounds[i]));
workload.SetBounds(bounds);
Workload::Coefficients coefficients;
for (unsigned i = 0; i < GetShape()->NumCoefficients; i++)
{
coefficients[i] = GetShape()->DefaultCoefficients.at(i);
config.lookupValue(GetShape()->CoefficientIDToName.at(i), coefficients[i]);
}
workload.SetCoefficients(coefficients);
Workload::Densities densities;
double common_density;
if (config.lookupValue("commonDensity", common_density))
{
for (unsigned i = 0; i < GetShape()->NumDataSpaces; i++)
densities[i] = common_density;
}
else if (config.exists("densities"))
{
auto config_densities = config.lookup("densities");
for (unsigned i = 0; i < GetShape()->NumDataSpaces; i++)
assert(config_densities.lookupValue(GetShape()->DataSpaceIDToName.at(i), densities[i]));
}
else
{
for (unsigned i = 0; i < GetShape()->NumDataSpaces; i++)
densities[i] = 1.0;
}
workload.SetDensities(densities);
}
} // namespace problem
<commit_msg>[workload] Support parsing file name for problem shape directly<commit_after>/* Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of NVIDIA CORPORATION nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <cstring>
#include "problem-shape.hpp"
#include "workload.hpp"
namespace problem
{
// ======================================== //
// Shape instance //
// ======================================== //
// See comment in .hpp file.
Shape shape_;
const Shape* GetShape()
{
return &shape_;
}
// ======================================== //
// Workload //
// ======================================== //
std::string ShapeFileName(const std::string shape_name)
{
std::string shape_file_name;
std::string shape_dir;
const char* shape_dir_env = std::getenv("TIMELOOP_PROBLEM_SHAPE_DIR");
if (shape_dir_env)
{
shape_dir = std::string(shape_dir_env) + "/";
}
else
{
const char* timeloopdir = std::getenv("TIMELOOP_DIR");
if (!timeloopdir)
{
timeloopdir = BUILD_BASE_DIR;
}
shape_dir = std::string(timeloopdir) + "/problem-shapes/";
}
// support filename directly
if (std::strstr(shape_name.c_str(), ".yml") || std::strstr(shape_name.c_str(), ".yaml") || std::strstr(shape_name.c_str(), ".cfg"))
{
shape_file_name = shape_dir + shape_name;
}
else
{
shape_file_name = shape_dir + shape_name + ".cfg";
}
std::cerr << "MESSAGE: reading problem shapes from: " << shape_dir << std::endl;
std::cout << "MESSAGE: attempting to read problem shape from file: " << shape_file_name << std::endl;
return shape_file_name;
}
void ParseWorkload(config::CompoundConfigNode config, Workload& workload)
{
std::string shape_name;
if (!config.exists("shape"))
{
std::cerr << "WARNING: found neither a problem shape description nor a string corresponding to a to a pre-existing shape description. Assuming shape: cnn-layer." << std::endl;
config::CompoundConfig shape_config(ShapeFileName("cnn-layer").c_str());
auto shape = shape_config.getRoot().lookup("shape");
shape_.Parse(shape);
}
else if (config.lookupValue("shape", shape_name))
{
config::CompoundConfig shape_config(ShapeFileName(shape_name).c_str());
auto shape = shape_config.getRoot().lookup("shape");
shape_.Parse(shape);
}
else
{
auto shape = config.lookup("shape");
shape_.Parse(shape);
}
// Loop bounds for each problem dimension.
Workload::Bounds bounds;
for (unsigned i = 0; i < GetShape()->NumDimensions; i++)
assert(config.lookupValue(GetShape()->DimensionIDToName.at(i), bounds[i]));
workload.SetBounds(bounds);
Workload::Coefficients coefficients;
for (unsigned i = 0; i < GetShape()->NumCoefficients; i++)
{
coefficients[i] = GetShape()->DefaultCoefficients.at(i);
config.lookupValue(GetShape()->CoefficientIDToName.at(i), coefficients[i]);
}
workload.SetCoefficients(coefficients);
Workload::Densities densities;
double common_density;
if (config.lookupValue("commonDensity", common_density))
{
for (unsigned i = 0; i < GetShape()->NumDataSpaces; i++)
densities[i] = common_density;
}
else if (config.exists("densities"))
{
auto config_densities = config.lookup("densities");
for (unsigned i = 0; i < GetShape()->NumDataSpaces; i++)
assert(config_densities.lookupValue(GetShape()->DataSpaceIDToName.at(i), densities[i]));
}
else
{
for (unsigned i = 0; i < GetShape()->NumDataSpaces; i++)
densities[i] = 1.0;
}
workload.SetDensities(densities);
}
} // namespace problem
<|endoftext|> |
<commit_before>/*
* AscEmu Framework based on ArcEmu MMORPG Server
* Copyright (C) 2014-2016 AscEmu Team <http://www.ascemu.org/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "PlayerCache.h"
#include "WorldPacket.h"
void PlayerCache::SendPacket(WorldPacket & p) {
WorldPacket* data = new WorldPacket(p);
m_pendingPackets.push(data);
}
void PlayerCache::SendPacket(WorldPacket* p) {
m_pendingPackets.push(p);
}
<commit_msg>GCC: Include changes<commit_after>/*
* AscEmu Framework based on ArcEmu MMORPG Server
* Copyright (C) 2014-2016 AscEmu Team <http://www.ascemu.org/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "PlayerCache.h"
#include "WorldPacket.h"
#include "Unit.h"
void PlayerCache::SendPacket(WorldPacket & p) {
WorldPacket* data = new WorldPacket(p);
m_pendingPackets.push(data);
}
void PlayerCache::SendPacket(WorldPacket* p) {
m_pendingPackets.push(p);
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2012-2015 Daniele Bartolini and individual contributors.
* License: https://github.com/taylor001/crown/blob/master/LICENSE
*/
#include "scene_graph.h"
#include "quaternion.h"
#include "vector3.h"
#include "matrix3x3.h"
#include "matrix4x4.h"
#include "allocator.h"
#include "array.h"
#include <string.h> // memcpy
#include <stdint.h> // UINT_MAX
namespace crown
{
SceneGraph::SceneGraph(Allocator& a)
: _allocator(a)
, _map(a)
{
}
SceneGraph::~SceneGraph()
{
_allocator.deallocate(_data.buffer);
}
TransformInstance SceneGraph::make_instance(uint32_t i)
{
TransformInstance inst = { i };
return inst;
}
void SceneGraph::allocate(uint32_t num)
{
CE_ASSERT(num > _data.size, "num > _data.size");
const uint32_t bytes = num * (0
+ sizeof(UnitId)
+ sizeof(Matrix4x4)
+ sizeof(Pose)
+ sizeof(TransformInstance) * 4);
InstanceData new_data;
new_data.size = _data.size;
new_data.capacity = num;
new_data.buffer = _allocator.allocate(bytes);
new_data.unit = (UnitId*)(new_data.buffer);
new_data.world = (Matrix4x4*)(new_data.unit + num);
new_data.local = (Pose*)(new_data.world + num);
new_data.parent = (TransformInstance*)(new_data.local + num);
new_data.first_child = (TransformInstance*)(new_data.parent + num);
new_data.next_sibling = (TransformInstance*)(new_data.first_child + num);
new_data.prev_sibling = (TransformInstance*)(new_data.next_sibling + num);
memcpy(new_data.unit, _data.unit, _data.size * sizeof(UnitId));
memcpy(new_data.world, _data.world, _data.size * sizeof(Matrix4x4));
memcpy(new_data.local, _data.local, _data.size * sizeof(Pose));
memcpy(new_data.parent, _data.parent, _data.size * sizeof(TransformInstance));
memcpy(new_data.first_child, _data.first_child, _data.size * sizeof(TransformInstance));
memcpy(new_data.next_sibling, _data.next_sibling, _data.size * sizeof(TransformInstance));
memcpy(new_data.prev_sibling, _data.prev_sibling, _data.size * sizeof(TransformInstance));
_allocator.deallocate(_data.buffer);
_data = new_data;
}
void SceneGraph::create(const Matrix4x4& m, UnitId id)
{
if (_data.capacity == _data.size)
grow();
const uint32_t last = _data.size;
_data.unit[last] = id;
_data.world[last] = m;
_data.local[last] = m;
_data.parent[last].i = UINT32_MAX;
_data.first_child[last].i = UINT32_MAX;
_data.next_sibling[last].i = UINT32_MAX;
_data.prev_sibling[last].i = UINT32_MAX;
// FIXME
if (array::size(_map) <= id.index)
array::resize(_map, array::size(_map) + id.index + 1);
_map[id.index] = last;
++_data.size;
}
void SceneGraph::destroy(TransformInstance i)
{
const uint32_t last = _data.size - 1;
const UnitId u = _data.unit[i.i];
const UnitId last_u = _data.unit[last];
_data.unit[i.i] = _data.unit[last];
_data.world[i.i] = _data.world[last];
_data.local[i.i] = _data.local[last];
_data.parent[i.i] = _data.parent[last];
_data.first_child[i.i] = _data.first_child[last];
_data.next_sibling[i.i] = _data.next_sibling[last];
_data.prev_sibling[i.i] = _data.prev_sibling[last];
_map[last_u.index] = i.i;
_map[u.index] = UINT32_MAX;
--_data.size;
}
TransformInstance SceneGraph::get(UnitId id)
{
return make_instance(_map[id.index]);
}
void SceneGraph::set_local_position(TransformInstance i, const Vector3& pos)
{
_data.local[i.i].position = pos;
set_local(i);
}
void SceneGraph::set_local_rotation(TransformInstance i, const Quaternion& rot)
{
_data.local[i.i].rotation = matrix3x3(rot);
set_local(i);
}
void SceneGraph::set_local_scale(TransformInstance i, const Vector3& scale)
{
_data.local[i.i].scale = scale;
set_local(i);
}
void SceneGraph::set_local_pose(TransformInstance i, const Matrix4x4& pose)
{
_data.local[i.i] = pose;
set_local(i);
}
Vector3 SceneGraph::local_position(TransformInstance i) const
{
return _data.local[i.i].position;
}
Quaternion SceneGraph::local_rotation(TransformInstance i) const
{
return rotation(_data.local[i.i].rotation);
}
Vector3 SceneGraph::local_scale(TransformInstance i) const
{
return _data.local[i.i].scale;
}
Matrix4x4 SceneGraph::local_pose(TransformInstance i) const
{
Matrix4x4 tr = matrix4x4(rotation(_data.local[i.i].rotation), _data.local[i.i].position);
set_scale(tr, _data.local[i.i].scale);
return tr;
}
Vector3 SceneGraph::world_position(TransformInstance i) const
{
return translation(_data.world[i.i]);
}
Quaternion SceneGraph::world_rotation(TransformInstance i) const
{
return rotation(_data.world[i.i]);
}
Matrix4x4 SceneGraph::world_pose(TransformInstance i) const
{
return _data.world[i.i];
}
uint32_t SceneGraph::num_nodes() const
{
return _data.size;
}
void SceneGraph::link(TransformInstance child, TransformInstance parent)
{
unlink(child);
if (!is_valid(_data.first_child[parent.i]))
{
_data.first_child[parent.i] = child;
_data.parent[child.i] = parent;
}
else
{
TransformInstance prev = { UINT32_MAX };
TransformInstance node = _data.first_child[parent.i];
while (is_valid(node))
{
prev = node;
node = _data.next_sibling[node.i];
}
_data.next_sibling[prev.i] = child;
_data.first_child[child.i].i = UINT32_MAX;
_data.next_sibling[child.i].i = UINT32_MAX;
_data.prev_sibling[child.i] = prev;
}
Matrix4x4 parent_tr = _data.world[parent.i];
Matrix4x4 child_tr = _data.world[child.i];
const Vector3 cs = scale(child_tr);
Vector3 px = x(parent_tr);
Vector3 py = y(parent_tr);
Vector3 pz = z(parent_tr);
Vector3 cx = x(child_tr);
Vector3 cy = y(child_tr);
Vector3 cz = z(child_tr);
set_x(parent_tr, normalize(px));
set_y(parent_tr, normalize(py));
set_z(parent_tr, normalize(pz));
set_x(child_tr, normalize(cx));
set_y(child_tr, normalize(cy));
set_z(child_tr, normalize(cz));
const Matrix4x4 rel_tr = child_tr * get_inverted(parent_tr);
_data.local[child.i].position = translation(rel_tr);
_data.local[child.i].rotation = to_matrix3x3(rel_tr);
_data.local[child.i].scale = cs;
_data.parent[child.i] = parent;
transform(parent_tr, child);
}
void SceneGraph::unlink(TransformInstance child)
{
if (!is_valid(_data.parent[child.i]))
return;
if (!is_valid(_data.prev_sibling[child.i]))
_data.first_child[_data.parent[child.i].i] = _data.next_sibling[child.i];
else
_data.next_sibling[_data.prev_sibling[child.i].i] = _data.next_sibling[child.i];
if (is_valid(_data.next_sibling[child.i]))
_data.prev_sibling[_data.next_sibling[child.i].i] = _data.prev_sibling[child.i];
_data.parent[child.i].i = UINT32_MAX;
_data.next_sibling[child.i].i = UINT32_MAX;
_data.prev_sibling[child.i].i = UINT32_MAX;
}
bool SceneGraph::is_valid(TransformInstance i)
{
return i.i != UINT32_MAX;
}
void SceneGraph::set_local(TransformInstance i)
{
TransformInstance parent = _data.parent[i.i];
Matrix4x4 parent_tm = is_valid(parent) ? _data.world[parent.i] : MATRIX4X4_IDENTITY;
transform(parent_tm, i);
}
void SceneGraph::transform(const Matrix4x4& parent, TransformInstance i)
{
_data.world[i.i] = local_pose(i) * parent;
TransformInstance child = _data.first_child[i.i];
while (is_valid(child))
{
transform(_data.world[i.i], child);
child = _data.next_sibling[child.i];
}
}
void SceneGraph::grow()
{
allocate(_data.capacity * 2 + 1);
}
} // namespace crown
<commit_msg>Update SceneGraph<commit_after>/*
* Copyright (c) 2012-2015 Daniele Bartolini and individual contributors.
* License: https://github.com/taylor001/crown/blob/master/LICENSE
*/
#include "scene_graph.h"
#include "quaternion.h"
#include "vector3.h"
#include "matrix3x3.h"
#include "matrix4x4.h"
#include "allocator.h"
#include "array.h"
#include <string.h> // memcpy
#include <stdint.h> // UINT_MAX
namespace crown
{
SceneGraph::SceneGraph(Allocator& a)
: _allocator(a)
, _map(a)
{
}
SceneGraph::~SceneGraph()
{
_allocator.deallocate(_data.buffer);
}
TransformInstance SceneGraph::make_instance(uint32_t i)
{
TransformInstance inst = { i };
return inst;
}
void SceneGraph::allocate(uint32_t num)
{
CE_ASSERT(num > _data.size, "num > _data.size");
const uint32_t bytes = num * (0
+ sizeof(UnitId)
+ sizeof(Matrix4x4)
+ sizeof(Pose)
+ sizeof(TransformInstance) * 4);
InstanceData new_data;
new_data.size = _data.size;
new_data.capacity = num;
new_data.buffer = _allocator.allocate(bytes);
new_data.unit = (UnitId*)(new_data.buffer);
new_data.world = (Matrix4x4*)(new_data.unit + num);
new_data.local = (Pose*)(new_data.world + num);
new_data.parent = (TransformInstance*)(new_data.local + num);
new_data.first_child = (TransformInstance*)(new_data.parent + num);
new_data.next_sibling = (TransformInstance*)(new_data.first_child + num);
new_data.prev_sibling = (TransformInstance*)(new_data.next_sibling + num);
memcpy(new_data.unit, _data.unit, _data.size * sizeof(UnitId));
memcpy(new_data.world, _data.world, _data.size * sizeof(Matrix4x4));
memcpy(new_data.local, _data.local, _data.size * sizeof(Pose));
memcpy(new_data.parent, _data.parent, _data.size * sizeof(TransformInstance));
memcpy(new_data.first_child, _data.first_child, _data.size * sizeof(TransformInstance));
memcpy(new_data.next_sibling, _data.next_sibling, _data.size * sizeof(TransformInstance));
memcpy(new_data.prev_sibling, _data.prev_sibling, _data.size * sizeof(TransformInstance));
_allocator.deallocate(_data.buffer);
_data = new_data;
}
void SceneGraph::create(const Matrix4x4& m, UnitId id)
{
if (_data.capacity == _data.size)
grow();
const uint32_t last = _data.size;
_data.unit[last] = id;
_data.world[last] = m;
_data.local[last] = m;
_data.parent[last].i = UINT32_MAX;
_data.first_child[last].i = UINT32_MAX;
_data.next_sibling[last].i = UINT32_MAX;
_data.prev_sibling[last].i = UINT32_MAX;
// FIXME
if (array::size(_map) <= id.index)
array::resize(_map, array::size(_map) + id.index + 1);
_map[id.index] = last;
++_data.size;
}
void SceneGraph::destroy(TransformInstance i)
{
const uint32_t last = _data.size - 1;
const UnitId u = _data.unit[i.i];
const UnitId last_u = _data.unit[last];
_data.unit[i.i] = _data.unit[last];
_data.world[i.i] = _data.world[last];
_data.local[i.i] = _data.local[last];
_data.parent[i.i] = _data.parent[last];
_data.first_child[i.i] = _data.first_child[last];
_data.next_sibling[i.i] = _data.next_sibling[last];
_data.prev_sibling[i.i] = _data.prev_sibling[last];
_map[last_u.index] = i.i;
_map[u.index] = UINT32_MAX;
--_data.size;
}
TransformInstance SceneGraph::get(UnitId id)
{
return make_instance(_map[id.index]);
}
void SceneGraph::set_local_position(TransformInstance i, const Vector3& pos)
{
_data.local[i.i].position = pos;
set_local(i);
}
void SceneGraph::set_local_rotation(TransformInstance i, const Quaternion& rot)
{
_data.local[i.i].rotation = matrix3x3(rot);
set_local(i);
}
void SceneGraph::set_local_scale(TransformInstance i, const Vector3& scale)
{
_data.local[i.i].scale = scale;
set_local(i);
}
void SceneGraph::set_local_pose(TransformInstance i, const Matrix4x4& pose)
{
_data.local[i.i] = pose;
set_local(i);
}
Vector3 SceneGraph::local_position(TransformInstance i) const
{
return _data.local[i.i].position;
}
Quaternion SceneGraph::local_rotation(TransformInstance i) const
{
return quaternion(_data.local[i.i].rotation);
}
Vector3 SceneGraph::local_scale(TransformInstance i) const
{
return _data.local[i.i].scale;
}
Matrix4x4 SceneGraph::local_pose(TransformInstance i) const
{
Matrix4x4 tr = matrix4x4(quaternion(_data.local[i.i].rotation), _data.local[i.i].position);
set_scale(tr, _data.local[i.i].scale);
return tr;
}
Vector3 SceneGraph::world_position(TransformInstance i) const
{
return translation(_data.world[i.i]);
}
Quaternion SceneGraph::world_rotation(TransformInstance i) const
{
return rotation(_data.world[i.i]);
}
Matrix4x4 SceneGraph::world_pose(TransformInstance i) const
{
return _data.world[i.i];
}
uint32_t SceneGraph::num_nodes() const
{
return _data.size;
}
void SceneGraph::link(TransformInstance child, TransformInstance parent)
{
unlink(child);
if (!is_valid(_data.first_child[parent.i]))
{
_data.first_child[parent.i] = child;
_data.parent[child.i] = parent;
}
else
{
TransformInstance prev = { UINT32_MAX };
TransformInstance node = _data.first_child[parent.i];
while (is_valid(node))
{
prev = node;
node = _data.next_sibling[node.i];
}
_data.next_sibling[prev.i] = child;
_data.first_child[child.i].i = UINT32_MAX;
_data.next_sibling[child.i].i = UINT32_MAX;
_data.prev_sibling[child.i] = prev;
}
Matrix4x4 parent_tr = _data.world[parent.i];
Matrix4x4 child_tr = _data.world[child.i];
const Vector3 cs = scale(child_tr);
Vector3 px = x(parent_tr);
Vector3 py = y(parent_tr);
Vector3 pz = z(parent_tr);
Vector3 cx = x(child_tr);
Vector3 cy = y(child_tr);
Vector3 cz = z(child_tr);
set_x(parent_tr, normalize(px));
set_y(parent_tr, normalize(py));
set_z(parent_tr, normalize(pz));
set_x(child_tr, normalize(cx));
set_y(child_tr, normalize(cy));
set_z(child_tr, normalize(cz));
const Matrix4x4 rel_tr = child_tr * get_inverted(parent_tr);
_data.local[child.i].position = translation(rel_tr);
_data.local[child.i].rotation = to_matrix3x3(rel_tr);
_data.local[child.i].scale = cs;
_data.parent[child.i] = parent;
transform(parent_tr, child);
}
void SceneGraph::unlink(TransformInstance child)
{
if (!is_valid(_data.parent[child.i]))
return;
if (!is_valid(_data.prev_sibling[child.i]))
_data.first_child[_data.parent[child.i].i] = _data.next_sibling[child.i];
else
_data.next_sibling[_data.prev_sibling[child.i].i] = _data.next_sibling[child.i];
if (is_valid(_data.next_sibling[child.i]))
_data.prev_sibling[_data.next_sibling[child.i].i] = _data.prev_sibling[child.i];
_data.parent[child.i].i = UINT32_MAX;
_data.next_sibling[child.i].i = UINT32_MAX;
_data.prev_sibling[child.i].i = UINT32_MAX;
}
bool SceneGraph::is_valid(TransformInstance i)
{
return i.i != UINT32_MAX;
}
void SceneGraph::set_local(TransformInstance i)
{
TransformInstance parent = _data.parent[i.i];
Matrix4x4 parent_tm = is_valid(parent) ? _data.world[parent.i] : MATRIX4X4_IDENTITY;
transform(parent_tm, i);
}
void SceneGraph::transform(const Matrix4x4& parent, TransformInstance i)
{
_data.world[i.i] = local_pose(i) * parent;
TransformInstance child = _data.first_child[i.i];
while (is_valid(child))
{
transform(_data.world[i.i], child);
child = _data.next_sibling[child.i];
}
}
void SceneGraph::grow()
{
allocate(_data.capacity * 2 + 1);
}
} // namespace crown
<|endoftext|> |
<commit_before>#include <string>
#include <Poco/NumberFormatter.h>
#include <Poco/Timestamp.h>
#include <Poco/XML/XMLWriter.h>
#include <Poco/SAX/AttributesImpl.h>
#include "xmlui/Serializing.h"
#include "l10n/TimeZone.h"
#include "model/Gateway.h"
#include "model/LegacyGateway.h"
#include "model/Location.h"
#include "model/DeviceInfo.h"
#include "model/DeviceProperty.h"
#include "model/DeviceWithData.h"
#include "model/RoleInGateway.h"
#include "model/LegacyRoleInGateway.h"
#include "model/VerifiedIdentity.h"
using namespace std;
using namespace Poco;
using namespace Poco::XML;
using namespace BeeeOn;
static void prepare(AttributesImpl &attrs, const Gateway &gateway)
{
attrs.addAttribute("", "id", "id", "", gateway.id().toString());
attrs.addAttribute("", "name", "name", "", gateway.name());
attrs.addAttribute("", "longitude", "longitude", "",
std::to_string(gateway.longitude()));
attrs.addAttribute("", "latitude", "latitude", "",
std::to_string(gateway.latitude()));
if (gateway.altitude().isNull()) {
attrs.addAttribute("", "altitude", "altitude", "", "");
}
else {
attrs.addAttribute("", "altitude", "altitude", "",
std::to_string(gateway.altitude().value()));
}
attrs.addAttribute("", "version", "version", "", gateway.version());
attrs.addAttribute("", "ip", "ip", "", gateway.ipAddress().toString());
}
void BeeeOn::XmlUI::serialize(XMLWriter &output, const Gateway &gateway)
{
AttributesImpl attrs;
prepare(attrs, gateway);
output.emptyElement("", "gate", "gate", attrs);
}
void BeeeOn::XmlUI::serialize(Poco::XML::XMLWriter &output,
const std::vector<Gateway> &gateways)
{
for (auto gateway : gateways)
serialize(output, gateway);
}
void BeeeOn::XmlUI::serialize(XMLWriter &output, const LegacyGateway &gateway)
{
AttributesImpl attrs;
prepare(attrs, gateway);
attrs.addAttribute("", "owner", "owner", "",
gateway.owner().fullName());
attrs.addAttribute("", "permission", "permission", "",
gateway.accessLevel().toString());
attrs.addAttribute("", "devices", "devices", "",
to_string(gateway.deviceCount()));
attrs.addAttribute("", "users", "users", "",
to_string(gateway.userCount()));
const TimeZone &zone = gateway.timeZone();
const Timestamp now;
const int offset = zone.utcOffset().totalSeconds()
+ (zone.appliesDST(now) ? zone.dstOffset().totalSeconds() : 0);
attrs.addAttribute("", "timezone_name", "timezone_name", "",
zone.shortName(Locale::system()));
attrs.addAttribute("", "timezone", "timezone", "", to_string(offset));
attrs.addAttribute("", "status", "status", "", "available");
output.emptyElement("", "gate", "gate", attrs);
}
void BeeeOn::XmlUI::serialize(Poco::XML::XMLWriter &output,
const std::vector<LegacyGateway> &gateways)
{
for (auto gateway : gateways)
serialize(output, gateway);
}
void BeeeOn::XmlUI::serialize(XMLWriter &output, const Location &location)
{
AttributesImpl attrs;
attrs.addAttribute("", "id", "id", "", location.id().toString());
attrs.addAttribute("", "locationid", "locationid", "",
location.id().toString());
attrs.addAttribute("", "name", "name", "", location.name());
attrs.addAttribute("", "type", "type", "", "0"); // FIXME
output.emptyElement("", "location", "location", attrs);
}
void BeeeOn::XmlUI::serialize(Poco::XML::XMLWriter &output,
const std::vector<Location> &locations)
{
for (auto location : locations)
serialize(output, location);
}
void BeeeOn::XmlUI::serialize(Poco::XML::XMLWriter &output,
const DeviceWithData &device)
{
AttributesImpl attrs;
attrs.addAttribute("", "id", "id", "", device.id().toString());
attrs.addAttribute("", "euid", "euid", "", device.id().toString());
attrs.addAttribute("", "type", "type", "", device.type()->id().toString());
attrs.addAttribute("", "locationid", "locationid", "",
device.location().id().toString());
attrs.addAttribute("", "gateid", "gateid", "",
device.gateway().id().toString());
if (device.name().empty())
attrs.addAttribute("", "name", "name", "", device.type()->name());
else
attrs.addAttribute("", "name", "name", "", device.name());
const DeviceStatus &status = device.status();
attrs.addAttribute("", "status", "status", "",
device.available()? "available" : "unavailable");
attrs.addAttribute("", "time", "time", "",
to_string(status.lastSeen().epochTime()));
attrs.addAttribute("", "involved", "involved", "",
to_string(status.firstSeen().epochTime()));
attrs.addAttribute("", "init", "init", "",
status.active()? "1" : "0");
string state;
switch (status.state()) {
case DeviceStatus::STATE_INACTIVE:
state = "inactive";
break;
case DeviceStatus::STATE_INACTIVE_PENDING:
state = "inactive-pending";
break;
case DeviceStatus::STATE_ACTIVE:
state = "active";
break;
case DeviceStatus::STATE_ACTIVE_PENDING:
state = "active-pending";
break;
default:
throw IllegalStateException(
"invalid state: " + to_string(status.state()));
}
attrs.addAttribute("", "state", "state", "", state);
attrs.addAttribute("", "last-changed", "last-changed", "",
to_string(status.lastChanged().epochTime()));
const Poco::SharedPtr<DeviceInfo> info = device.type();
attrs.addAttribute("", "type_name", "type_name", "", info->name());
attrs.addAttribute("", "vendor", "vendor", "", info->vendor());
output.startElement("", "device", "device", attrs);
const auto &values = device.values();
for (auto module : *info) {
AttributesImpl attrs;
attrs.addAttribute("", "id", "id", "", module.id().toString());
// FIXME: just copy device status for now
attrs.addAttribute("", "status", "status", "",
device.available()? "available" : "unavailable");
string value = "NaN";
const unsigned int id = module.id();
if (id < values.size()) {
const ValueAt ¤t = values.at(id);
if (current.isValid())
value = NumberFormatter::format(current.value());
attrs.addAttribute("", "value", "value", "", value);
attrs.addAttribute("", "valid", "valid", "",
NumberFormatter::format(current.isValid()));
attrs.addAttribute("", "at", "at", "",
NumberFormatter::format(current.at().epochTime()));
}
attrs.addAttribute("", "type", "type", "", to_string(int(module.type()->id())));
if (!module.type()->unit().empty())
attrs.addAttribute("", "type-unit", "type-unit", "", module.type()->unit());
if (module.type()->range().isValid()) {
const auto range = module.type()->range();
if (range.hasMin()) {
attrs.addAttribute("", "type-range-min", "type-range-min", "",
to_string(range.min()));
}
if (range.hasMax()) {
attrs.addAttribute("", "type-range-max",
"type-range-max", "", to_string(range.max()));
}
if (range.hasStep()) {
attrs.addAttribute("", "type-range-step",
"type-range-step", "", to_string(range.step()));
}
}
if (!module.type()->values().empty()) {
string values;
for (const auto &pair : module.type()->values()) {
values += to_string(pair.first);
values += ":";
values += pair.second;
values += ";";
}
attrs.addAttribute("", "type-enum-values",
"type-enum-values", "", values);
}
else if (!module.subtype().isNull() && !module.subtype()->values().empty()) {
string values;
for (const auto &pair : module.subtype()->values()) {
values += to_string(pair.first);
values += ":";
values += pair.second;
values += ";";
}
attrs.addAttribute("", "type-enum-values",
"type-enum-values", "", values);
}
if (!module.name().empty())
attrs.addAttribute("", "name", "name", "", module.name());
if (!module.group().empty())
attrs.addAttribute("", "group", "group", "", module.group());
if (module.isControllable())
attrs.addAttribute("", "actuator", "actuator", "", "yes");
output.emptyElement("", "module", "module", attrs);
}
output.endElement("", "device", "device");
}
void BeeeOn::XmlUI::serialize(Poco::XML::XMLWriter &output,
const std::vector<DeviceWithData> &devices)
{
for (auto device : devices)
serialize(output, device);
}
void BeeeOn::XmlUI::serialize(Poco::XML::XMLWriter &output,
const std::list<DeviceWithData> &devices)
{
for (auto device : devices)
serialize(output, device);
}
void BeeeOn::XmlUI::serialize(Poco::XML::XMLWriter &output,
const DecryptedDeviceProperty &property,
const Device &device)
{
AttributesImpl attrs;
attrs.addAttribute("", "euid", "euid", "",
device.id().toString());
attrs.addAttribute("", "gateid", "gateid", "",
device.gateway().id().toString());
attrs.addAttribute("", "parameterkey", "parameterkey", "",
property.key().toString());
string value;
switch (property.key().raw()) {
case DevicePropertyKey::KEY_IP_ADDRESS:
value = property.asIPAddress().toString();
break;
case DevicePropertyKey::KEY_FIRMWARE:
value = property.asFirmware();
break;
case DevicePropertyKey::KEY_PASSWORD:
value = property.asPassword();
break;
default:
break;
}
attrs.addAttribute("", "parametervalue", "parametervalue", "", value);
output.emptyElement("", "device", "device", attrs);
}
static void prepare(AttributesImpl &attrs, const RoleInGateway &role)
{
attrs.addAttribute("", "id", "id", "", role.id().toString());
attrs.addAttribute("", "email", "email", "",
role.identity().email());
attrs.addAttribute("", "level", "level", "",
role.level().toString());
}
void BeeeOn::XmlUI::serialize(Poco::XML::XMLWriter &output,
const RoleInGateway &role)
{
AttributesImpl attrs;
prepare(attrs, role);
output.emptyElement("", "user", "user", attrs);
}
void BeeeOn::XmlUI::serialize(Poco::XML::XMLWriter &output,
const std::vector<RoleInGateway> &roles)
{
for (auto role : roles)
serialize(output, role);
}
void BeeeOn::XmlUI::serialize(Poco::XML::XMLWriter &output,
const LegacyRoleInGateway &role)
{
AttributesImpl attrs;
prepare(attrs, role);
if (role.isOwner()) {
attrs.addAttribute("", "permission", "permission",
"", "owner");
}
else {
attrs.addAttribute("", "permission", "permission",
"", role.level().toString());
}
attrs.addAttribute("", "gender", "gender", "", "unknown");
attrs.addAttribute("", "name", "name", "", role.firstName());
attrs.addAttribute("", "surname", "surname", "", role.lastName());
attrs.addAttribute("", "imgurl", "imgurl", "", role.picture().toString());
output.emptyElement("", "user", "user", attrs);
}
void BeeeOn::XmlUI::serialize(Poco::XML::XMLWriter &output,
const std::vector<LegacyRoleInGateway> &roles)
{
for (auto role : roles)
serialize(output, role);
}
void BeeeOn::XmlUI::serializeMyself(
Poco::XML::XMLWriter &output,
const VerifiedIdentity &identity)
{
const User &user = identity.user();
AttributesImpl attrs;
attrs.addAttribute("", "id", "id", "", identity.id().toString());
attrs.addAttribute("", "name", "name", "", user.firstName());
attrs.addAttribute("", "first_name", "first_name", "",
user.firstName());
attrs.addAttribute("", "surname", "surname", "", user.lastName());
attrs.addAttribute("", "last_name", "last_name", "",
user.lastName());
attrs.addAttribute("", "gender", "gender", "", "unknown");
attrs.addAttribute("", "email", "email", "", identity.email());
attrs.addAttribute("", "imgurl", "imgurl", "",
identity.picture().toString());
output.emptyElement("", "user", "user", attrs);
}
<commit_msg>xmlui: Serializing: fix redundant whitespace<commit_after>#include <string>
#include <Poco/NumberFormatter.h>
#include <Poco/Timestamp.h>
#include <Poco/XML/XMLWriter.h>
#include <Poco/SAX/AttributesImpl.h>
#include "xmlui/Serializing.h"
#include "l10n/TimeZone.h"
#include "model/Gateway.h"
#include "model/LegacyGateway.h"
#include "model/Location.h"
#include "model/DeviceInfo.h"
#include "model/DeviceProperty.h"
#include "model/DeviceWithData.h"
#include "model/RoleInGateway.h"
#include "model/LegacyRoleInGateway.h"
#include "model/VerifiedIdentity.h"
using namespace std;
using namespace Poco;
using namespace Poco::XML;
using namespace BeeeOn;
static void prepare(AttributesImpl &attrs, const Gateway &gateway)
{
attrs.addAttribute("", "id", "id", "", gateway.id().toString());
attrs.addAttribute("", "name", "name", "", gateway.name());
attrs.addAttribute("", "longitude", "longitude", "",
std::to_string(gateway.longitude()));
attrs.addAttribute("", "latitude", "latitude", "",
std::to_string(gateway.latitude()));
if (gateway.altitude().isNull()) {
attrs.addAttribute("", "altitude", "altitude", "", "");
}
else {
attrs.addAttribute("", "altitude", "altitude", "",
std::to_string(gateway.altitude().value()));
}
attrs.addAttribute("", "version", "version", "", gateway.version());
attrs.addAttribute("", "ip", "ip", "", gateway.ipAddress().toString());
}
void BeeeOn::XmlUI::serialize(XMLWriter &output, const Gateway &gateway)
{
AttributesImpl attrs;
prepare(attrs, gateway);
output.emptyElement("", "gate", "gate", attrs);
}
void BeeeOn::XmlUI::serialize(Poco::XML::XMLWriter &output,
const std::vector<Gateway> &gateways)
{
for (auto gateway : gateways)
serialize(output, gateway);
}
void BeeeOn::XmlUI::serialize(XMLWriter &output, const LegacyGateway &gateway)
{
AttributesImpl attrs;
prepare(attrs, gateway);
attrs.addAttribute("", "owner", "owner", "",
gateway.owner().fullName());
attrs.addAttribute("", "permission", "permission", "",
gateway.accessLevel().toString());
attrs.addAttribute("", "devices", "devices", "",
to_string(gateway.deviceCount()));
attrs.addAttribute("", "users", "users", "",
to_string(gateway.userCount()));
const TimeZone &zone = gateway.timeZone();
const Timestamp now;
const int offset = zone.utcOffset().totalSeconds()
+ (zone.appliesDST(now) ? zone.dstOffset().totalSeconds() : 0);
attrs.addAttribute("", "timezone_name", "timezone_name", "",
zone.shortName(Locale::system()));
attrs.addAttribute("", "timezone", "timezone", "", to_string(offset));
attrs.addAttribute("", "status", "status", "", "available");
output.emptyElement("", "gate", "gate", attrs);
}
void BeeeOn::XmlUI::serialize(Poco::XML::XMLWriter &output,
const std::vector<LegacyGateway> &gateways)
{
for (auto gateway : gateways)
serialize(output, gateway);
}
void BeeeOn::XmlUI::serialize(XMLWriter &output, const Location &location)
{
AttributesImpl attrs;
attrs.addAttribute("", "id", "id", "", location.id().toString());
attrs.addAttribute("", "locationid", "locationid", "",
location.id().toString());
attrs.addAttribute("", "name", "name", "", location.name());
attrs.addAttribute("", "type", "type", "", "0"); // FIXME
output.emptyElement("", "location", "location", attrs);
}
void BeeeOn::XmlUI::serialize(Poco::XML::XMLWriter &output,
const std::vector<Location> &locations)
{
for (auto location : locations)
serialize(output, location);
}
void BeeeOn::XmlUI::serialize(Poco::XML::XMLWriter &output,
const DeviceWithData &device)
{
AttributesImpl attrs;
attrs.addAttribute("", "id", "id", "", device.id().toString());
attrs.addAttribute("", "euid", "euid", "", device.id().toString());
attrs.addAttribute("", "type", "type", "", device.type()->id().toString());
attrs.addAttribute("", "locationid", "locationid", "",
device.location().id().toString());
attrs.addAttribute("", "gateid", "gateid", "",
device.gateway().id().toString());
if (device.name().empty())
attrs.addAttribute("", "name", "name", "", device.type()->name());
else
attrs.addAttribute("", "name", "name", "", device.name());
const DeviceStatus &status = device.status();
attrs.addAttribute("", "status", "status", "",
device.available()? "available" : "unavailable");
attrs.addAttribute("", "time", "time", "",
to_string(status.lastSeen().epochTime()));
attrs.addAttribute("", "involved", "involved", "",
to_string(status.firstSeen().epochTime()));
attrs.addAttribute("", "init", "init", "",
status.active()? "1" : "0");
string state;
switch (status.state()) {
case DeviceStatus::STATE_INACTIVE:
state = "inactive";
break;
case DeviceStatus::STATE_INACTIVE_PENDING:
state = "inactive-pending";
break;
case DeviceStatus::STATE_ACTIVE:
state = "active";
break;
case DeviceStatus::STATE_ACTIVE_PENDING:
state = "active-pending";
break;
default:
throw IllegalStateException(
"invalid state: " + to_string(status.state()));
}
attrs.addAttribute("", "state", "state", "", state);
attrs.addAttribute("", "last-changed", "last-changed", "",
to_string(status.lastChanged().epochTime()));
const Poco::SharedPtr<DeviceInfo> info = device.type();
attrs.addAttribute("", "type_name", "type_name", "", info->name());
attrs.addAttribute("", "vendor", "vendor", "", info->vendor());
output.startElement("", "device", "device", attrs);
const auto &values = device.values();
for (auto module : *info) {
AttributesImpl attrs;
attrs.addAttribute("", "id", "id", "", module.id().toString());
// FIXME: just copy device status for now
attrs.addAttribute("", "status", "status", "",
device.available()? "available" : "unavailable");
string value = "NaN";
const unsigned int id = module.id();
if (id < values.size()) {
const ValueAt ¤t = values.at(id);
if (current.isValid())
value = NumberFormatter::format(current.value());
attrs.addAttribute("", "value", "value", "", value);
attrs.addAttribute("", "valid", "valid", "",
NumberFormatter::format(current.isValid()));
attrs.addAttribute("", "at", "at", "",
NumberFormatter::format(current.at().epochTime()));
}
attrs.addAttribute("", "type", "type", "", to_string(int(module.type()->id())));
if (!module.type()->unit().empty())
attrs.addAttribute("", "type-unit", "type-unit", "", module.type()->unit());
if (module.type()->range().isValid()) {
const auto range = module.type()->range();
if (range.hasMin()) {
attrs.addAttribute("", "type-range-min", "type-range-min", "",
to_string(range.min()));
}
if (range.hasMax()) {
attrs.addAttribute("", "type-range-max",
"type-range-max", "", to_string(range.max()));
}
if (range.hasStep()) {
attrs.addAttribute("", "type-range-step",
"type-range-step", "", to_string(range.step()));
}
}
if (!module.type()->values().empty()) {
string values;
for (const auto &pair : module.type()->values()) {
values += to_string(pair.first);
values += ":";
values += pair.second;
values += ";";
}
attrs.addAttribute("", "type-enum-values",
"type-enum-values", "", values);
}
else if (!module.subtype().isNull() && !module.subtype()->values().empty()) {
string values;
for (const auto &pair : module.subtype()->values()) {
values += to_string(pair.first);
values += ":";
values += pair.second;
values += ";";
}
attrs.addAttribute("", "type-enum-values",
"type-enum-values", "", values);
}
if (!module.name().empty())
attrs.addAttribute("", "name", "name", "", module.name());
if (!module.group().empty())
attrs.addAttribute("", "group", "group", "", module.group());
if (module.isControllable())
attrs.addAttribute("", "actuator", "actuator", "", "yes");
output.emptyElement("", "module", "module", attrs);
}
output.endElement("", "device", "device");
}
void BeeeOn::XmlUI::serialize(Poco::XML::XMLWriter &output,
const std::vector<DeviceWithData> &devices)
{
for (auto device : devices)
serialize(output, device);
}
void BeeeOn::XmlUI::serialize(Poco::XML::XMLWriter &output,
const std::list<DeviceWithData> &devices)
{
for (auto device : devices)
serialize(output, device);
}
void BeeeOn::XmlUI::serialize(Poco::XML::XMLWriter &output,
const DecryptedDeviceProperty &property,
const Device &device)
{
AttributesImpl attrs;
attrs.addAttribute("", "euid", "euid", "",
device.id().toString());
attrs.addAttribute("", "gateid", "gateid", "",
device.gateway().id().toString());
attrs.addAttribute("", "parameterkey", "parameterkey", "",
property.key().toString());
string value;
switch (property.key().raw()) {
case DevicePropertyKey::KEY_IP_ADDRESS:
value = property.asIPAddress().toString();
break;
case DevicePropertyKey::KEY_FIRMWARE:
value = property.asFirmware();
break;
case DevicePropertyKey::KEY_PASSWORD:
value = property.asPassword();
break;
default:
break;
}
attrs.addAttribute("", "parametervalue", "parametervalue", "", value);
output.emptyElement("", "device", "device", attrs);
}
static void prepare(AttributesImpl &attrs, const RoleInGateway &role)
{
attrs.addAttribute("", "id", "id", "", role.id().toString());
attrs.addAttribute("", "email", "email", "",
role.identity().email());
attrs.addAttribute("", "level", "level", "",
role.level().toString());
}
void BeeeOn::XmlUI::serialize(Poco::XML::XMLWriter &output,
const RoleInGateway &role)
{
AttributesImpl attrs;
prepare(attrs, role);
output.emptyElement("", "user", "user", attrs);
}
void BeeeOn::XmlUI::serialize(Poco::XML::XMLWriter &output,
const std::vector<RoleInGateway> &roles)
{
for (auto role : roles)
serialize(output, role);
}
void BeeeOn::XmlUI::serialize(Poco::XML::XMLWriter &output,
const LegacyRoleInGateway &role)
{
AttributesImpl attrs;
prepare(attrs, role);
if (role.isOwner()) {
attrs.addAttribute("", "permission", "permission",
"", "owner");
}
else {
attrs.addAttribute("", "permission", "permission",
"", role.level().toString());
}
attrs.addAttribute("", "gender", "gender", "", "unknown");
attrs.addAttribute("", "name", "name", "", role.firstName());
attrs.addAttribute("", "surname", "surname", "", role.lastName());
attrs.addAttribute("", "imgurl", "imgurl", "", role.picture().toString());
output.emptyElement("", "user", "user", attrs);
}
void BeeeOn::XmlUI::serialize(Poco::XML::XMLWriter &output,
const std::vector<LegacyRoleInGateway> &roles)
{
for (auto role : roles)
serialize(output, role);
}
void BeeeOn::XmlUI::serializeMyself(
Poco::XML::XMLWriter &output,
const VerifiedIdentity &identity)
{
const User &user = identity.user();
AttributesImpl attrs;
attrs.addAttribute("", "id", "id", "", identity.id().toString());
attrs.addAttribute("", "name", "name", "", user.firstName());
attrs.addAttribute("", "first_name", "first_name", "",
user.firstName());
attrs.addAttribute("", "surname", "surname", "", user.lastName());
attrs.addAttribute("", "last_name", "last_name", "",
user.lastName());
attrs.addAttribute("", "gender", "gender", "", "unknown");
attrs.addAttribute("", "email", "email", "", identity.email());
attrs.addAttribute("", "imgurl", "imgurl", "",
identity.picture().toString());
output.emptyElement("", "user", "user", attrs);
}
<|endoftext|> |
<commit_before>/*
** This file is part of libyuni, a cross-platform C++ framework (http://libyuni.org).
**
** This Source Code Form is subject to the terms of the Mozilla Public License
** v.2.0. If a copy of the MPL was not distributed with this file, You can
** obtain one at http://mozilla.org/MPL/2.0/.
**
** github: https://github.com/libyuni/libyuni/
** gitlab: https://gitlab.com/libyuni/libyuni/ (mirror)
*/
#pragma once
#include "array.h"
namespace Yuni
{
namespace Thread
{
template<class T>
Array<T>::Array(const Array<T>& rhs)
{
typename ThreadingPolicy::MutexLocker locker(rhs);
pAutoStart = rhs.pAutoStart;
pList = rhs.pList;
}
template<class T>
inline Array<T>::Array(uint n)
{
if (n > maxThreadsLimit)
n = maxThreadsLimit;
appendNThreadsWL(n, false);
}
template<class T>
inline Array<T>::Array(uint n, bool autoStart)
: pAutoStart{autoStart}
{
if (n > maxThreadsLimit)
n = maxThreadsLimit;
appendNThreadsWL(n, autoStart);
}
template<class T>
inline Array<T>::~Array()
{
// We won't stop all remaining threads. They have to do it by themselves
// when destroyed.
// however, it would be wise to destroy them before the vtable is corrupted
clear();
}
template<class T>
inline bool Array<T>::autoStart() const
{
return (pAutoStart);
}
template<class T>
inline void Array<T>::autoStart(const bool v)
{
pAutoStart = v;
}
template<class T>
void Array<T>::clear()
{
// We will make a copy of the list to release the lock
// as soon as possible since this routine may take some time...
ThreadList copy;
{
typename ThreadingPolicy::MutexLocker locker(*this);
if (pList.empty())
return;
copy.swap(pList);
}
// the container `copy` will be destroyed here, thus all threads
}
template<class T>
void Array<T>::add(typename T::Ptr thread)
{
if (pAutoStart)
thread->start();
typename ThreadingPolicy::MutexLocker locker(*this);
pList.push_back(thread);
}
template<class T>
void Array<T>::add(typename T::Ptr thread, bool autostart)
{
if (autostart)
thread->start();
typename ThreadingPolicy::MutexLocker locker(*this);
pList.push_back(thread);
}
template<class T>
inline void Array<T>::push_back(typename T::Ptr thread)
{
typename ThreadingPolicy::MutexLocker locker(*this);
pList.push_back(thread);
}
template<class T>
void Array<T>::resize(uint n)
{
if (0 == n)
{
// When resizing to 0 elements, it is exactly equivalent to directly
// call the method clear(), which should be more efficient
clear();
return;
}
if (n > maxThreadsLimit)
n = maxThreadsLimit;
// If we have some thread to remove from the pool, we will use this copy list
// since it can take some time
ThreadList copy;
{
// Locking
typename ThreadingPolicy::MutexLocker locker(*this);
// Keeping the number of existing thread
const uint count = pList.size();
if (count == n)
return;
if (count < n)
{
// We don't have enough threads in pool. Creating a few of them...
appendNThreadsWL(n - count, pAutoStart);
return;
}
// Asking to the last threads to stop by themselves as soon as possible
// This should be done early to make them stop asynchronously.
// We may earn a lot of time like this.
for (uint i = n; i < count; ++i)
pList[i]->gracefulStop();
// Creating a list of all threads that must be removed
copy.reserve(count - n);
for (uint i = n; i < count; ++i)
copy.push_back(pList[i]);
// We can resize the vector, the removed threads will be stopped later
pList.resize(count);
}
// all unwanted threads will be stopped (probably destroyed) here
}
template<class T>
void Array<T>::start()
{
typename ThreadingPolicy::MutexLocker locker(*this);
// We can start all threads at once while locked because this operation
// should be fast enough (signal only).
if (not pList.empty())
{
const typename ThreadList::iterator end = pList.end();
for (typename ThreadList::iterator i = pList.begin(); i != end; ++i)
(*i)->start();
}
}
template<class T>
void Array<T>::gracefulStop()
{
typename ThreadingPolicy::MutexLocker locker(*this);
// We can ask to all threads to gracefully stop while locked because this operation
// should be fast enough (signal only).
if (not pList.empty())
{
const typename ThreadList::iterator end = pList.end();
for (typename ThreadList::iterator i = pList.begin(); i != end; ++i)
(*i)->gracefulStop();
}
}
template<class T>
void Array<T>::wait()
{
// We will make a copy of the list to release the lock as soon as
// possible since this routine may take some time...
ThreadList copy;
{
typename ThreadingPolicy::MutexLocker locker(*this);
if (pList.empty())
return;
copy = pList;
}
// waiting for all threads
const typename ThreadList::iterator end = copy.end();
for (typename ThreadList::iterator i = copy.begin(); i != end; ++i)
(*i)->wait();
}
template<class T>
void Array<T>::wait(uint milliseconds)
{
// We will make a copy of the list to release the lock as soon as
// possible since this routine may take some time...
ThreadList copy;
{
typename ThreadingPolicy::MutexLocker locker(*this);
if (pList.empty())
return;
copy = pList;
}
// waiting for all threads
const typename ThreadList::iterator end = copy.end();
for (typename ThreadList::iterator i = copy.begin(); i != end; ++i)
(*i)->wait(milliseconds);
}
template<class T>
void Array<T>::stop(uint timeout)
{
// We will make a copy of the list to release the lock as soon as
// possible since this routine may take some time...
ThreadList copy;
{
typename ThreadingPolicy::MutexLocker locker(*this);
if (pList.empty())
return;
copy = pList;
}
const typename ThreadList::iterator end = copy.end();
// Asking to the last threads to stop by themselves as soon as possible
// This should be done early to make them stop asynchronously.
// We may earn a lot of time like this.
for (typename ThreadList::iterator i = copy.begin(); i != end; ++i)
(*i)->gracefulStop();
// Now we can kill them if they don't cooperate...
for (typename ThreadList::iterator i = copy.begin(); i != end; ++i)
(*i)->stop(timeout);
}
template<class T>
void Array<T>::restart(uint timeout)
{
// We will make a copy of the list to release the lock as soon as
// possible since this routine may take some time...
ThreadList copy;
{
typename ThreadingPolicy::MutexLocker locker(*this);
if (pList.empty())
return;
copy = pList;
}
const typename ThreadList::iterator end = copy.end();
// Asking to the last threads to stop by themselves as soon as possible
// This should be done early to make them stop asynchronously.
// We may earn a lot of time like this.
for (typename ThreadList::iterator i = copy.begin(); i != end; ++i)
(*i)->gracefulStop();
// Now we can kill them if they don't cooperate...
for (typename ThreadList::iterator i = copy.begin(); i != end; ++i)
(*i)->stop(timeout);
// And start them again
for (typename ThreadList::iterator i = copy.begin(); i != end; ++i)
(*i)->start();
}
template<class T>
void Array<T>::wakeUp()
{
typename ThreadingPolicy::MutexLocker locker(*this);
// We can wake all threads up at once while locked because this operation
// should be fast enough (signal only).
if (not pList.empty())
{
const typename ThreadList::iterator end = pList.end();
for (typename ThreadList::iterator i = pList.begin(); i != end; ++i)
(*i)->wakeUp();
}
}
template<class T>
inline typename T::Ptr Array<T>::operator [] (uint index) const
{
typename ThreadingPolicy::MutexLocker locker(*this);
return (index < pList.size()) ? pList[index] : T::Ptr();
}
template<class T>
Array<T>& Array<T>::operator = (const Array<T>& rhs)
{
typename ThreadingPolicy::MutexLocker lockerR(rhs);
typename ThreadingPolicy::MutexLocker locker(*this);
pAutoStart = rhs.pAutoStart;
pList = rhs.pList;
return *this;
}
template<class T>
Array<T>& Array<T>::operator = (const Ptr& rhs)
{
typename Array<T>::Ptr keepReference = rhs;
typename ThreadingPolicy::MutexLocker lockerR(*keepReference);
typename ThreadingPolicy::MutexLocker locker(*this);
pAutoStart = keepReference.pAutoStart;
pList = keepReference.pList;
return *this;
}
template<class T>
Array<T>& Array<T>::operator += (const Array<T>& rhs)
{
typename ThreadingPolicy::MutexLocker lockerR(rhs);
typename ThreadingPolicy::MutexLocker locker(*this);
const typename ThreadList::const_iterator end = rhs.pList.end();
for (typename ThreadList::const_iterator i = rhs.pList.begin(); i != end; ++i)
pList.push_back(*i);
return *this;
}
template<class T>
Array<T>& Array<T>::operator += (const Ptr& rhs)
{
typename Array<T>::Ptr keepReference = rhs;
typename ThreadingPolicy::MutexLocker lockerR(*keepReference);
typename ThreadingPolicy::MutexLocker locker(*this);
const typename ThreadList::const_iterator end = keepReference->pList.end();
for (typename ThreadList::const_iterator i = keepReference->pList.begin(); i != end; ++i)
pList.push_back(*i);
return *this;
}
template<class T>
Array<T>& Array<T>::operator << (const Array<T>& rhs)
{
typename ThreadingPolicy::MutexLocker lockerR(rhs);
typename ThreadingPolicy::MutexLocker locker(*this);
const typename ThreadList::const_iterator end = rhs.pList.end();
for (typename ThreadList::const_iterator i = rhs.pList.begin(); i != end; ++i)
pList.push_back(*i);
return *this;
}
template<class T>
Array<T>& Array<T>::operator << (const Ptr& rhs)
{
typename Array<T>::Ptr keepReference = rhs;
typename ThreadingPolicy::MutexLocker lockerR(*keepReference);
typename ThreadingPolicy::MutexLocker locker(*this);
const typename ThreadList::const_iterator end = keepReference->pList.end();
for (typename ThreadList::const_iterator i = keepReference->pList.begin(); i != end; ++i)
pList.push_back(*i);
return *this;
}
template<class T>
inline Array<T>& Array<T>::operator << (T* thread)
{
add(thread);
return *this;
}
template<class T>
inline Array<T>& Array<T>::operator << (const typename T::Ptr& thread)
{
add(thread);
return *this;
}
template<class T>
inline Array<T>& Array<T>::operator += (T* thread)
{
add(thread);
return *this;
}
template<class T>
inline Array<T>& Array<T>::operator += (const typename T::Ptr& thread)
{
add(thread);
return *this;
}
template<class T>
void Array<T>::appendNThreadsWL(uint n, bool autostart)
{
// Keeping the number of existing thread
const uint count = (uint) pList.size();
if (count < n)
{
// We don't have enough threads in pool. Creating a few of them...
// We should use the variable `pAutoStart` once time only to avoid
// changes while adding the new threads
if (autostart)
{
for (uint i = count; i < n; ++i)
{
T* thread = new T();
thread->start();
pList.push_back(thread);
}
}
else
{
for (uint i = count; i < n; ++i)
pList.push_back(new T());
}
}
}
template<class T>
inline uint Array<T>::size() const
{
typename ThreadingPolicy::MutexLocker locker(*this);
return (uint) pList.size();
}
template<class T>
inline bool Array<T>::empty() const
{
typename ThreadingPolicy::MutexLocker locker(*this);
return pList.empty();
}
template<class T>
template<class PredicateT>
void Array<T>::foreachThread(const PredicateT& predicate) const
{
// We will make a copy of the list to release the lock as soon as
// possible since this routine may take some time...
// (and to prevent dead-locks)
ThreadList copy;
{
typename ThreadingPolicy::MutexLocker locker(*this);
if (pList.empty())
return;
copy = pList;
}
const typename ThreadList::const_iterator end = copy.end();
for (typename ThreadList::const_iterator i = copy.begin(); i != end; ++i)
{
if (not predicate(*i))
return;
}
}
template<class T>
template<class PredicateT>
void Array<T>::foreachThread(const PredicateT& predicate)
{
// We will make a copy of the list to release the lock as soon as
// possible since this routine may take some time...
// (and to prevent dead-locks)
ThreadList copy;
{
typename ThreadingPolicy::MutexLocker locker(*this);
if (pList.empty())
return;
copy = pList;
}
const typename ThreadList::iterator end = copy.end();
for (typename ThreadList::iterator i = copy.begin(); i != end; ++i)
{
if (not predicate(*i))
return;
}
}
} // namespace Thread
} // namespace Yuni
<commit_msg>thread array: use ranged-based for loops<commit_after>/*
** This file is part of libyuni, a cross-platform C++ framework (http://libyuni.org).
**
** This Source Code Form is subject to the terms of the Mozilla Public License
** v.2.0. If a copy of the MPL was not distributed with this file, You can
** obtain one at http://mozilla.org/MPL/2.0/.
**
** github: https://github.com/libyuni/libyuni/
** gitlab: https://gitlab.com/libyuni/libyuni/ (mirror)
*/
#pragma once
#include "array.h"
namespace Yuni
{
namespace Thread
{
template<class T>
Array<T>::Array(const Array<T>& rhs)
{
typename ThreadingPolicy::MutexLocker locker(rhs);
pAutoStart = rhs.pAutoStart;
pList = rhs.pList;
}
template<class T>
inline Array<T>::Array(uint n)
{
if (n > maxThreadsLimit)
n = maxThreadsLimit;
appendNThreadsWL(n, false);
}
template<class T>
inline Array<T>::Array(uint n, bool autoStart)
: pAutoStart{autoStart}
{
if (n > maxThreadsLimit)
n = maxThreadsLimit;
appendNThreadsWL(n, autoStart);
}
template<class T>
inline Array<T>::~Array()
{
// We won't stop all remaining threads. They have to do it by themselves
// when destroyed.
// however, it would be wise to destroy them before the vtable is corrupted
clear();
}
template<class T>
inline bool Array<T>::autoStart() const
{
return (pAutoStart);
}
template<class T>
inline void Array<T>::autoStart(const bool v)
{
pAutoStart = v;
}
template<class T>
void Array<T>::clear()
{
// We will make a copy of the list to release the lock
// as soon as possible since this routine may take some time...
ThreadList copy;
{
typename ThreadingPolicy::MutexLocker locker(*this);
if (pList.empty())
return;
copy.swap(pList);
}
// the container `copy` will be destroyed here, thus all threads
}
template<class T>
void Array<T>::add(typename T::Ptr thread)
{
if (pAutoStart)
thread->start();
typename ThreadingPolicy::MutexLocker locker(*this);
pList.push_back(thread);
}
template<class T>
void Array<T>::add(typename T::Ptr thread, bool autostart)
{
if (autostart)
thread->start();
typename ThreadingPolicy::MutexLocker locker(*this);
pList.push_back(thread);
}
template<class T>
inline void Array<T>::push_back(typename T::Ptr thread)
{
typename ThreadingPolicy::MutexLocker locker(*this);
pList.push_back(thread);
}
template<class T>
void Array<T>::resize(uint n)
{
if (0 == n)
{
// When resizing to 0 elements, it is exactly equivalent to directly
// call the method clear(), which should be more efficient
clear();
return;
}
if (n > maxThreadsLimit)
n = maxThreadsLimit;
// If we have some thread to remove from the pool, we will use this copy list
// since it can take some time
ThreadList copy;
{
// Locking
typename ThreadingPolicy::MutexLocker locker(*this);
// Keeping the number of existing thread
const uint count = pList.size();
if (count == n)
return;
if (count < n)
{
// We don't have enough threads in pool. Creating a few of them...
appendNThreadsWL(n - count, pAutoStart);
return;
}
// Asking to the last threads to stop by themselves as soon as possible
// This should be done early to make them stop asynchronously.
// We may earn a lot of time like this.
for (uint i = n; i < count; ++i)
pList[i]->gracefulStop();
// Creating a list of all threads that must be removed
copy.reserve(count - n);
for (uint i = n; i < count; ++i)
copy.push_back(pList[i]);
// We can resize the vector, the removed threads will be stopped later
pList.resize(count);
}
// all unwanted threads will be stopped (probably destroyed) here
}
template<class T>
void Array<T>::start()
{
typename ThreadingPolicy::MutexLocker locker(*this);
// We can start all threads at once while locked because this operation
// should be fast enough (signal only).
for (auto& ptr: pList)
ptr->start();
}
template<class T>
void Array<T>::gracefulStop()
{
typename ThreadingPolicy::MutexLocker locker(*this);
// We can ask to all threads to gracefully stop while locked because this operation
// should be fast enough (signal only).
for (auto& ptr: pList)
ptr->gracefulStop();
}
template<class T>
void Array<T>::wait()
{
// We will make a copy of the list to release the lock as soon as
// possible since this routine may take some time...
ThreadList copy;
{
typename ThreadingPolicy::MutexLocker locker(*this);
if (pList.empty())
return;
copy = pList;
}
for (auto& ptr: copy)
ptr->wait();
}
template<class T>
void Array<T>::wait(uint milliseconds)
{
// We will make a copy of the list to release the lock as soon as
// possible since this routine may take some time...
ThreadList copy;
{
typename ThreadingPolicy::MutexLocker locker(*this);
if (pList.empty())
return;
copy = pList;
}
for (auto& ptr: copy)
ptr->wait(milliseconds);
}
template<class T>
void Array<T>::stop(uint timeout)
{
// We will make a copy of the list to release the lock as soon as
// possible since this routine may take some time...
ThreadList copy;
{
typename ThreadingPolicy::MutexLocker locker(*this);
if (pList.empty())
return;
copy = pList;
}
// Asking to the last threads to stop by themselves as soon as possible
// This should be done early to make them stop asynchronously.
// We may earn a lot of time like this.
for (auto& ptr: copy)
ptr->gracefulStop();
// Now we can kill them if they don't cooperate...
for (auto& ptr: copy)
ptr->stop(timeout);
}
template<class T>
void Array<T>::restart(uint timeout)
{
// We will make a copy of the list to release the lock as soon as
// possible since this routine may take some time...
ThreadList copy;
{
typename ThreadingPolicy::MutexLocker locker(*this);
if (pList.empty())
return;
copy = pList;
}
// Asking to the last threads to stop by themselves as soon as possible
// This should be done early to make them stop asynchronously.
// We may earn a lot of time like this.
for (auto& ptr: copy)
ptr->gracefulStop();
// Now we can kill them if they don't cooperate...
for (auto& ptr: copy)
ptr->stop(timeout);
// And start them again
for (auto& ptr: copy)
ptr->start();
}
template<class T>
void Array<T>::wakeUp()
{
typename ThreadingPolicy::MutexLocker locker(*this);
// We can wake all threads up at once while locked because this operation
// should be fast enough (signal only).
for (auto& ptr: pList)
ptr->wakeUp();
}
template<class T>
inline typename T::Ptr Array<T>::operator [] (uint index) const
{
typename ThreadingPolicy::MutexLocker locker(*this);
return (index < pList.size()) ? pList[index] : T::Ptr();
}
template<class T>
Array<T>& Array<T>::operator = (const Array<T>& rhs)
{
typename ThreadingPolicy::MutexLocker lockerR(rhs);
typename ThreadingPolicy::MutexLocker locker(*this);
pAutoStart = rhs.pAutoStart;
pList = rhs.pList;
return *this;
}
template<class T>
Array<T>& Array<T>::operator = (const Ptr& rhs)
{
typename Array<T>::Ptr keepReference = rhs;
typename ThreadingPolicy::MutexLocker lockerR(*keepReference);
typename ThreadingPolicy::MutexLocker locker(*this);
pAutoStart = keepReference.pAutoStart;
pList = keepReference.pList;
return *this;
}
template<class T>
Array<T>& Array<T>::operator += (const Array<T>& rhs)
{
typename ThreadingPolicy::MutexLocker lockerR(rhs);
typename ThreadingPolicy::MutexLocker locker(*this);
for (auto& ptr: rhs.pList)
pList.push_back(ptr);
return *this;
}
template<class T>
Array<T>& Array<T>::operator += (const Ptr& rhs)
{
typename Array<T>::Ptr keepReference = rhs;
typename ThreadingPolicy::MutexLocker lockerR(*keepReference);
typename ThreadingPolicy::MutexLocker locker(*this);
for (auto& ptr: keepReference->pList)
pList.push_back(ptr);
return *this;
}
template<class T>
Array<T>& Array<T>::operator << (const Array<T>& rhs)
{
typename ThreadingPolicy::MutexLocker lockerR(rhs);
typename ThreadingPolicy::MutexLocker locker(*this);
for (auto& ptr: rhs.pList)
pList.push_back(ptr);
return *this;
}
template<class T>
Array<T>& Array<T>::operator << (const Ptr& rhs)
{
typename Array<T>::Ptr keepReference = rhs;
typename ThreadingPolicy::MutexLocker lockerR(*keepReference);
typename ThreadingPolicy::MutexLocker locker(*this);
for (auto& ptr: keepReference->pList)
pList.push_back(ptr);
return *this;
}
template<class T>
inline Array<T>& Array<T>::operator << (T* thread)
{
add(thread);
return *this;
}
template<class T>
inline Array<T>& Array<T>::operator << (const typename T::Ptr& thread)
{
add(thread);
return *this;
}
template<class T>
inline Array<T>& Array<T>::operator += (T* thread)
{
add(thread);
return *this;
}
template<class T>
inline Array<T>& Array<T>::operator += (const typename T::Ptr& thread)
{
add(thread);
return *this;
}
template<class T>
void Array<T>::appendNThreadsWL(uint n, bool autostart)
{
// Keeping the number of existing thread
const uint count = (uint) pList.size();
if (count < n)
{
// We don't have enough threads in pool. Creating a few of them...
// We should use the variable `pAutoStart` once time only to avoid
// changes while adding the new threads
if (autostart)
{
for (uint i = count; i < n; ++i)
{
T* thread = new T();
thread->start();
pList.push_back(thread);
}
}
else
{
for (uint i = count; i < n; ++i)
pList.push_back(new T());
}
}
}
template<class T>
inline uint Array<T>::size() const
{
typename ThreadingPolicy::MutexLocker locker(*this);
return (uint) pList.size();
}
template<class T>
inline bool Array<T>::empty() const
{
typename ThreadingPolicy::MutexLocker locker(*this);
return pList.empty();
}
template<class T>
template<class PredicateT>
void Array<T>::foreachThread(const PredicateT& predicate) const
{
// We will make a copy of the list to release the lock as soon as
// possible since this routine may take some time...
// (and to prevent dead-locks)
ThreadList copy;
{
typename ThreadingPolicy::MutexLocker locker(*this);
if (pList.empty())
return;
copy = pList;
}
for (auto& ptr: copy)
{
if (not predicate(ptr))
return;
}
}
template<class T>
template<class PredicateT>
void Array<T>::foreachThread(const PredicateT& predicate)
{
// We will make a copy of the list to release the lock as soon as
// possible since this routine may take some time...
// (and to prevent dead-locks)
ThreadList copy;
{
typename ThreadingPolicy::MutexLocker locker(*this);
if (pList.empty())
return;
copy = pList;
}
for (auto& ptr: copy)
{
if (not predicate(ptr))
return;
}
}
} // namespace Thread
} // namespace Yuni
<|endoftext|> |
<commit_before>#include "singleton_factory.hpp"
namespace {
auto invertReg = ObjectRegister<std::function<cv::Mat(cv::Mat)> >("Invert",
[](cv::Mat im){
cv::rectangle(im, cv::Point(100,100), cv::Point(200,200), cv::Scalar(255,0,0), 1);
return im; });
}
<commit_msg>Simple invert processor.<commit_after>#include "singleton_factory.hpp"
namespace {
auto invertReg = ObjectRegister<std::function<cv::Mat(cv::Mat)> >("Invert",
[](cv::Mat im){
cv::Mat dest;
// Subtract the image from a constant 255 4-channel array
cv::subtract( cv::Scalar(255, 255, 255, 255), im, dest );
// Set the alpha channel back to fully opaque
cv::add( cv::Scalar(0,0,0,255), dest, im );
return im; });
}
<|endoftext|> |
<commit_before>/*
* Written by Nitin Kumar Maharana
* nitin.maharana@gmail.com
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
//Using one stack but modifies the input tree.
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> result;
if(root == NULL)
return result;
stack<TreeNode*> memory;
TreeNode *curr;
memory.push(root);
while(!memory.empty())
{
curr = memory.top();
if(curr->left)
{
memory.push(curr->left);
curr->left = NULL;
}
else if(curr->right)
{
memory.push(curr->right);
curr->right = NULL;
}
else
{
result.push_back(curr->val);
memory.pop();
}
}
return result;
}
};
//Using one stack, Do not modify the input tree, Extra reverse operation on result vector.
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> result;
if(root == NULL)
return result;
stack<TreeNode*> memory;
TreeNode *curr;
memory.push(root);
while(!memory.empty())
{
curr = memory.top();
memory.pop();
result.push_back(curr->val);
if(curr->left)
memory.push(curr->left);
if(curr->right)
memory.push(curr->right);
}
reverse(result.begin(), result.end());
return result;
}
};
//Using one stack, No Modification, Optimized one.
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> result;
if(root == NULL)
return result;
stack<TreeNode*> memory;
TreeNode *curr, *temp;
if(root->right)
memory.push(root->right);
memory.push(root);
curr = root->left;
while(!memory.empty())
{
if(curr)
{
if(curr->right)
memory.push(curr->right);
memory.push(curr);
curr = curr->left;
}
else
{
curr = memory.top();
memory.pop();
if(!memory.empty() && curr->right == memory.top())
{
temp = memory.top();
memory.pop();
memory.push(curr);
curr = temp;
}
else
{
result.push_back(curr->val);
curr = NULL;
}
}
}
return result;
}
};<commit_msg>145. Binary Tree Postorder Traversal - Another optimized solution<commit_after>/*
* Written by Nitin Kumar Maharana
* nitin.maharana@gmail.com
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
//Using one stack but modifies the input tree.
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> result;
if(root == NULL)
return result;
stack<TreeNode*> memory;
TreeNode *curr;
memory.push(root);
while(!memory.empty())
{
curr = memory.top();
if(curr->left)
{
memory.push(curr->left);
curr->left = NULL;
}
else if(curr->right)
{
memory.push(curr->right);
curr->right = NULL;
}
else
{
result.push_back(curr->val);
memory.pop();
}
}
return result;
}
};
//Using one stack, Do not modify the input tree, Extra reverse operation on result vector.
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> result;
if(root == NULL)
return result;
stack<TreeNode*> memory;
TreeNode *curr;
memory.push(root);
while(!memory.empty())
{
curr = memory.top();
memory.pop();
result.push_back(curr->val);
if(curr->left)
memory.push(curr->left);
if(curr->right)
memory.push(curr->right);
}
reverse(result.begin(), result.end());
return result;
}
};
//Using one stack, No Modification, Optimized one.
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> result;
if(root == NULL)
return result;
stack<TreeNode*> memory;
TreeNode *curr, *temp;
if(root->right)
memory.push(root->right);
memory.push(root);
curr = root->left;
while(!memory.empty())
{
if(curr)
{
if(curr->right)
memory.push(curr->right);
memory.push(curr);
curr = curr->left;
}
else
{
curr = memory.top();
memory.pop();
if(!memory.empty() && curr->right == memory.top())
{
temp = memory.top();
memory.pop();
memory.push(curr);
curr = temp;
}
else
{
result.push_back(curr->val);
curr = NULL;
}
}
}
return result;
}
};
//Using one stack, No Modification, Optimized one.
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> result;
if(root == NULL)
return result;
stack<TreeNode*> memory;
TreeNode *curr, *last;
memory.push(root);
last = root;
while(!memory.empty())
{
curr = memory.top();
if((!curr->left && !curr->right) || curr->left == last || curr->right == last)
{
result.push_back(curr->val);
memory.pop();
last = curr;
continue;
}
if(curr->right)
memory.push(curr->right);
if(curr->left)
memory.push(curr->left);
}
return result;
}
};<|endoftext|> |
<commit_before>// -*- c-basic-offset: 2 -*-
/*
* This file is part of the KDE libraries
* Copyright (C) 1999-2000 Harri Porten (porten@kde.org)
* Copyright (C) 2004-2006 Apple Computer, Inc.
* Copyright (C) 2006 Bjoern Graf (bjoern.graf@gmail.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#include "config.h"
#include "collector.h"
#include <wtf/HashTraits.h>
#include "JSLock.h"
#include "object.h"
#include "Parser.h"
#include <math.h>
#include <stdio.h>
#include <string.h>
#if HAVE(SYS_TIME_H)
#include <sys/time.h>
#endif
#include "protect.h"
#if PLATFORM(WIN_OS)
#include <WebKitInitializer/WebKitInitializer.h>
#include <crtdbg.h>
#include <windows.h>
#endif
#if PLATFORM(QT)
#include <QDateTime>
#endif
using namespace KJS;
using namespace WTF;
static void testIsInteger();
static char* createStringWithContentsOfFile(const char* fileName);
class StopWatch
{
public:
void start();
void stop();
long getElapsedMS(); // call stop() first
private:
#if PLATFORM(QT)
uint m_startTime;
uint m_stopTime;
#elif PLATFORM(WIN_OS)
DWORD m_startTime;
DWORD m_stopTime;
#else
// Windows does not have timeval, disabling this class for now (bug 7399)
timeval m_startTime;
timeval m_stopTime;
#endif
};
void StopWatch::start()
{
#if PLATFORM(QT)
QDateTime t = QDateTime::currentDateTime();
m_startTime = t.toTime_t() * 1000 + t.time().msec();
#elif PLATFORM(WIN_OS)
m_startTime = timeGetTime();
#else
gettimeofday(&m_startTime, 0);
#endif
}
void StopWatch::stop()
{
#if PLATFORM(QT)
QDateTime t = QDateTime::currentDateTime();
m_stopTime = t.toTime_t() * 1000 + t.time().msec();
#elif PLATFORM(WIN_OS)
m_stopTime = timeGetTime();
#else
gettimeofday(&m_stopTime, 0);
#endif
}
long StopWatch::getElapsedMS()
{
#if PLATFORM(WIN_OS) || PLATFORM(QT)
return m_stopTime - m_startTime;
#else
timeval elapsedTime;
timersub(&m_stopTime, &m_startTime, &elapsedTime);
return elapsedTime.tv_sec * 1000 + lroundf(elapsedTime.tv_usec / 1000.0f);
#endif
}
class GlobalImp : public JSObject {
public:
virtual UString className() const { return "global"; }
};
class TestFunctionImp : public JSObject {
public:
TestFunctionImp(int i, int length);
virtual bool implementsCall() const { return true; }
virtual JSValue* callAsFunction(ExecState* exec, JSObject* thisObj, const List &args);
enum { Print, Debug, Quit, GC, Version, Run };
private:
int id;
};
TestFunctionImp::TestFunctionImp(int i, int length) : JSObject(), id(i)
{
putDirect(Identifier("length"), length, DontDelete | ReadOnly | DontEnum);
}
JSValue* TestFunctionImp::callAsFunction(ExecState* exec, JSObject*, const List &args)
{
switch (id) {
case Print:
printf("--> %s\n", args[0]->toString(exec).UTF8String().c_str());
return jsUndefined();
case Debug:
fprintf(stderr, "--> %s\n", args[0]->toString(exec).UTF8String().c_str());
return jsUndefined();
case GC:
{
JSLock lock;
Collector::collect();
return jsUndefined();
}
case Version:
// We need this function for compatibility with the Mozilla JS tests but for now
// we don't actually do any version-specific handling
return jsUndefined();
case Run:
{
StopWatch stopWatch;
char* fileName = strdup(args[0]->toString(exec).UTF8String().c_str());
char* script = createStringWithContentsOfFile(fileName);
if (!script)
return throwError(exec, GeneralError, "Could not open file.");
stopWatch.start();
exec->dynamicInterpreter()->evaluate(fileName, 0, script);
stopWatch.stop();
free(script);
free(fileName);
return jsNumber(stopWatch.getElapsedMS());
}
case Quit:
exit(0);
default:
abort();
}
return 0;
}
#if PLATFORM(WIN_OS)
// Use SEH for Release builds only to get rid of the crash report dialog
// (luckyly the same tests fail in Release and Debug builds so far). Need to
// be in a separate main function because the kjsmain function requires object
// unwinding.
#if defined(_DEBUG)
#define TRY
#define EXCEPT(x)
#else
#define TRY __try {
#define EXCEPT(x) } __except (EXCEPTION_EXECUTE_HANDLER) { x; }
#endif
#else
#define TRY
#define EXCEPT(x)
#endif
int kjsmain(int argc, char** argv);
int main(int argc, char** argv)
{
#if PLATFORM(WIN_OS)
if (!initializeWebKit()) {
fprintf(stderr, "Failed to initialize WebKit\n");
abort();
}
#endif
#if defined(_DEBUG) && PLATFORM(WIN_OS)
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
#endif
int res = 0;
TRY
res = kjsmain(argc, argv);
EXCEPT(res = 3)
return res;
}
bool doIt(int argc, char** argv)
{
bool success = true;
bool prettyPrint = false;
GlobalImp* global = new GlobalImp();
// create interpreter
RefPtr<Interpreter> interp = new Interpreter(global);
// add debug() function
global->put(interp->globalExec(), "debug", new TestFunctionImp(TestFunctionImp::Debug, 1));
// add "print" for compatibility with the mozilla js shell
global->put(interp->globalExec(), "print", new TestFunctionImp(TestFunctionImp::Print, 1));
// add "quit" for compatibility with the mozilla js shell
global->put(interp->globalExec(), "quit", new TestFunctionImp(TestFunctionImp::Quit, 0));
// add "gc" for compatibility with the mozilla js shell
global->put(interp->globalExec(), "gc", new TestFunctionImp(TestFunctionImp::GC, 0));
// add "version" for compatibility with the mozilla js shell
global->put(interp->globalExec(), "version", new TestFunctionImp(TestFunctionImp::Version, 1));
global->put(interp->globalExec(), "run", new TestFunctionImp(TestFunctionImp::Run, 1));
Interpreter::setShouldPrintExceptions(true);
for (int i = 1; i < argc; i++) {
const char* fileName = argv[i];
if (strcmp(fileName, "-f") == 0) // mozilla test driver script uses "-f" prefix for files
continue;
if (strcmp(fileName, "-p") == 0) {
prettyPrint = true;
continue;
}
char* script = createStringWithContentsOfFile(fileName);
if (!script) {
success = false;
break; // fail early so we can catch missing files
}
if (prettyPrint) {
int errLine = 0;
UString errMsg;
UString s = Parser::prettyPrint(script, &errLine, &errMsg);
if (s.isNull()) {
fprintf(stderr, "%s:%d: %s.\n", fileName, errLine, errMsg.UTF8String().c_str());
success = false;
free(script);
break;
}
printf("%s\n", s.UTF8String().c_str());
} else {
Completion completion = interp->evaluate(fileName, 0, script);
success = success && completion.complType() != Throw;
}
free(script);
}
return success;
}
int kjsmain(int argc, char** argv)
{
if (argc < 2) {
fprintf(stderr, "Usage: testkjs file1 [file2...]\n");
return -1;
}
testIsInteger();
JSLock lock;
bool success = doIt(argc, argv);
#ifndef NDEBUG
Collector::collect();
#endif
if (success)
fprintf(stderr, "OK.\n");
#ifdef KJS_DEBUG_MEM
Interpreter::finalCheck();
#endif
return success ? 0 : 3;
}
static void testIsInteger()
{
// Unit tests for WTF::IsInteger. Don't have a better place for them now.
// FIXME: move these once we create a unit test directory for WTF.
assert(IsInteger<bool>::value);
assert(IsInteger<char>::value);
assert(IsInteger<signed char>::value);
assert(IsInteger<unsigned char>::value);
assert(IsInteger<short>::value);
assert(IsInteger<unsigned short>::value);
assert(IsInteger<int>::value);
assert(IsInteger<unsigned int>::value);
assert(IsInteger<long>::value);
assert(IsInteger<unsigned long>::value);
assert(IsInteger<long long>::value);
assert(IsInteger<unsigned long long>::value);
assert(!IsInteger<char*>::value);
assert(!IsInteger<const char* >::value);
assert(!IsInteger<volatile char* >::value);
assert(!IsInteger<double>::value);
assert(!IsInteger<float>::value);
assert(!IsInteger<GlobalImp>::value);
}
static char* createStringWithContentsOfFile(const char* fileName)
{
char* buffer;
size_t buffer_size = 0;
size_t buffer_capacity = 1024;
buffer = (char*)malloc(buffer_capacity);
FILE* f = fopen(fileName, "r");
if (!f) {
fprintf(stderr, "Could not open file: %s\n", fileName);
free(buffer);
return 0;
}
while (!feof(f) && !ferror(f)) {
buffer_size += fread(buffer + buffer_size, 1, buffer_capacity - buffer_size, f);
if (buffer_size == buffer_capacity) { // guarantees space for trailing '\0'
buffer_capacity *= 2;
buffer = (char*)realloc(buffer, buffer_capacity);
assert(buffer);
}
assert(buffer_size < buffer_capacity);
}
fclose(f);
buffer[buffer_size] = '\0';
return buffer;
}
<commit_msg>Oh, Visual Studio, why don't you see when a project file has changed that the project needs to be rebuilt?<commit_after>// -*- c-basic-offset: 2 -*-
/*
* Copyright (C) 1999-2000 Harri Porten (porten@kde.org)
* Copyright (C) 2004-2007 Apple Inc.
* Copyright (C) 2006 Bjoern Graf (bjoern.graf@gmail.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#include "config.h"
#include "collector.h"
#include <wtf/HashTraits.h>
#include "JSLock.h"
#include "object.h"
#include "Parser.h"
#include <math.h>
#include <stdio.h>
#include <string.h>
#if HAVE(SYS_TIME_H)
#include <sys/time.h>
#endif
#include "protect.h"
#if PLATFORM(WIN_OS)
#include <WebKitInitializer/WebKitInitializer.h>
#include <crtdbg.h>
#include <windows.h>
#endif
#if PLATFORM(QT)
#include <QDateTime>
#endif
using namespace KJS;
using namespace WTF;
static void testIsInteger();
static char* createStringWithContentsOfFile(const char* fileName);
class StopWatch
{
public:
void start();
void stop();
long getElapsedMS(); // call stop() first
private:
#if PLATFORM(QT)
uint m_startTime;
uint m_stopTime;
#elif PLATFORM(WIN_OS)
DWORD m_startTime;
DWORD m_stopTime;
#else
// Windows does not have timeval, disabling this class for now (bug 7399)
timeval m_startTime;
timeval m_stopTime;
#endif
};
void StopWatch::start()
{
#if PLATFORM(QT)
QDateTime t = QDateTime::currentDateTime();
m_startTime = t.toTime_t() * 1000 + t.time().msec();
#elif PLATFORM(WIN_OS)
m_startTime = timeGetTime();
#else
gettimeofday(&m_startTime, 0);
#endif
}
void StopWatch::stop()
{
#if PLATFORM(QT)
QDateTime t = QDateTime::currentDateTime();
m_stopTime = t.toTime_t() * 1000 + t.time().msec();
#elif PLATFORM(WIN_OS)
m_stopTime = timeGetTime();
#else
gettimeofday(&m_stopTime, 0);
#endif
}
long StopWatch::getElapsedMS()
{
#if PLATFORM(WIN_OS) || PLATFORM(QT)
return m_stopTime - m_startTime;
#else
timeval elapsedTime;
timersub(&m_stopTime, &m_startTime, &elapsedTime);
return elapsedTime.tv_sec * 1000 + lroundf(elapsedTime.tv_usec / 1000.0f);
#endif
}
class GlobalImp : public JSObject {
public:
virtual UString className() const { return "global"; }
};
class TestFunctionImp : public JSObject {
public:
TestFunctionImp(int i, int length);
virtual bool implementsCall() const { return true; }
virtual JSValue* callAsFunction(ExecState* exec, JSObject* thisObj, const List &args);
enum { Print, Debug, Quit, GC, Version, Run };
private:
int id;
};
TestFunctionImp::TestFunctionImp(int i, int length) : JSObject(), id(i)
{
putDirect(Identifier("length"), length, DontDelete | ReadOnly | DontEnum);
}
JSValue* TestFunctionImp::callAsFunction(ExecState* exec, JSObject*, const List &args)
{
switch (id) {
case Print:
printf("--> %s\n", args[0]->toString(exec).UTF8String().c_str());
return jsUndefined();
case Debug:
fprintf(stderr, "--> %s\n", args[0]->toString(exec).UTF8String().c_str());
return jsUndefined();
case GC:
{
JSLock lock;
Collector::collect();
return jsUndefined();
}
case Version:
// We need this function for compatibility with the Mozilla JS tests but for now
// we don't actually do any version-specific handling
return jsUndefined();
case Run:
{
StopWatch stopWatch;
char* fileName = strdup(args[0]->toString(exec).UTF8String().c_str());
char* script = createStringWithContentsOfFile(fileName);
if (!script)
return throwError(exec, GeneralError, "Could not open file.");
stopWatch.start();
exec->dynamicInterpreter()->evaluate(fileName, 0, script);
stopWatch.stop();
free(script);
free(fileName);
return jsNumber(stopWatch.getElapsedMS());
}
case Quit:
exit(0);
default:
abort();
}
return 0;
}
#if PLATFORM(WIN_OS)
// Use SEH for Release builds only to get rid of the crash report dialog
// (luckyly the same tests fail in Release and Debug builds so far). Need to
// be in a separate main function because the kjsmain function requires object
// unwinding.
#if defined(_DEBUG)
#define TRY
#define EXCEPT(x)
#else
#define TRY __try {
#define EXCEPT(x) } __except (EXCEPTION_EXECUTE_HANDLER) { x; }
#endif
#else
#define TRY
#define EXCEPT(x)
#endif
int kjsmain(int argc, char** argv);
int main(int argc, char** argv)
{
#if PLATFORM(WIN_OS)
if (!initializeWebKit()) {
fprintf(stderr, "Failed to initialize WebKit\n");
abort();
}
#endif
#if defined(_DEBUG) && PLATFORM(WIN_OS)
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
#endif
int res = 0;
TRY
res = kjsmain(argc, argv);
EXCEPT(res = 3)
return res;
}
bool doIt(int argc, char** argv)
{
bool success = true;
bool prettyPrint = false;
GlobalImp* global = new GlobalImp();
// create interpreter
RefPtr<Interpreter> interp = new Interpreter(global);
// add debug() function
global->put(interp->globalExec(), "debug", new TestFunctionImp(TestFunctionImp::Debug, 1));
// add "print" for compatibility with the mozilla js shell
global->put(interp->globalExec(), "print", new TestFunctionImp(TestFunctionImp::Print, 1));
// add "quit" for compatibility with the mozilla js shell
global->put(interp->globalExec(), "quit", new TestFunctionImp(TestFunctionImp::Quit, 0));
// add "gc" for compatibility with the mozilla js shell
global->put(interp->globalExec(), "gc", new TestFunctionImp(TestFunctionImp::GC, 0));
// add "version" for compatibility with the mozilla js shell
global->put(interp->globalExec(), "version", new TestFunctionImp(TestFunctionImp::Version, 1));
global->put(interp->globalExec(), "run", new TestFunctionImp(TestFunctionImp::Run, 1));
Interpreter::setShouldPrintExceptions(true);
for (int i = 1; i < argc; i++) {
const char* fileName = argv[i];
if (strcmp(fileName, "-f") == 0) // mozilla test driver script uses "-f" prefix for files
continue;
if (strcmp(fileName, "-p") == 0) {
prettyPrint = true;
continue;
}
char* script = createStringWithContentsOfFile(fileName);
if (!script) {
success = false;
break; // fail early so we can catch missing files
}
if (prettyPrint) {
int errLine = 0;
UString errMsg;
UString s = Parser::prettyPrint(script, &errLine, &errMsg);
if (s.isNull()) {
fprintf(stderr, "%s:%d: %s.\n", fileName, errLine, errMsg.UTF8String().c_str());
success = false;
free(script);
break;
}
printf("%s\n", s.UTF8String().c_str());
} else {
Completion completion = interp->evaluate(fileName, 0, script);
success = success && completion.complType() != Throw;
}
free(script);
}
return success;
}
int kjsmain(int argc, char** argv)
{
if (argc < 2) {
fprintf(stderr, "Usage: testkjs file1 [file2...]\n");
return -1;
}
testIsInteger();
JSLock lock;
bool success = doIt(argc, argv);
#ifndef NDEBUG
Collector::collect();
#endif
if (success)
fprintf(stderr, "OK.\n");
#ifdef KJS_DEBUG_MEM
Interpreter::finalCheck();
#endif
return success ? 0 : 3;
}
static void testIsInteger()
{
// Unit tests for WTF::IsInteger. Don't have a better place for them now.
// FIXME: move these once we create a unit test directory for WTF.
assert(IsInteger<bool>::value);
assert(IsInteger<char>::value);
assert(IsInteger<signed char>::value);
assert(IsInteger<unsigned char>::value);
assert(IsInteger<short>::value);
assert(IsInteger<unsigned short>::value);
assert(IsInteger<int>::value);
assert(IsInteger<unsigned int>::value);
assert(IsInteger<long>::value);
assert(IsInteger<unsigned long>::value);
assert(IsInteger<long long>::value);
assert(IsInteger<unsigned long long>::value);
assert(!IsInteger<char*>::value);
assert(!IsInteger<const char* >::value);
assert(!IsInteger<volatile char* >::value);
assert(!IsInteger<double>::value);
assert(!IsInteger<float>::value);
assert(!IsInteger<GlobalImp>::value);
}
static char* createStringWithContentsOfFile(const char* fileName)
{
char* buffer;
size_t buffer_size = 0;
size_t buffer_capacity = 1024;
buffer = (char*)malloc(buffer_capacity);
FILE* f = fopen(fileName, "r");
if (!f) {
fprintf(stderr, "Could not open file: %s\n", fileName);
free(buffer);
return 0;
}
while (!feof(f) && !ferror(f)) {
buffer_size += fread(buffer + buffer_size, 1, buffer_capacity - buffer_size, f);
if (buffer_size == buffer_capacity) { // guarantees space for trailing '\0'
buffer_capacity *= 2;
buffer = (char*)realloc(buffer, buffer_capacity);
assert(buffer);
}
assert(buffer_size < buffer_capacity);
}
fclose(f);
buffer[buffer_size] = '\0';
return buffer;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/update_view.h"
#include <string>
#include "base/utf_string_conversions.h"
#include "chrome/browser/chromeos/login/helper.h"
#include "chrome/browser/chromeos/login/rounded_rect_painter.h"
#include "chrome/browser/chromeos/login/wizard_accessibility_helper.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "views/border.h"
#include "views/controls/label.h"
#include "views/controls/progress_bar.h"
#include "views/controls/throbber.h"
#include "views/focus/focus_manager.h"
#include "views/widget/widget.h"
using views::Background;
using views::Label;
using views::View;
using views::Widget;
namespace {
// TODO(nkostylev): Switch to GridLayout.
// Y offset for the 'installing updates' label.
const int kInstallingUpdatesLabelYBottomFromProgressBar = 18;
// Y offset for the progress bar.
const int kProgressBarY = 130;
// Y offset for the 'computer will restart' label.
const int kRebootLabelYFromProgressBar = 55;
// Y offset for the 'ESCAPE to skip' label.
const int kEscapeToSkipLabelY = 48;
// Progress bar width.
const int kProgressBarWidth = 420;
// Progress bar height.
const int kProgressBarHeight = 18;
// Horizontal spacing (ex. min left and right margins for label on the screen).
const int kHorizontalSpacing = 65;
// Horizontal spacing between spinner and label on the curtain screen.
const int kBetweenSpacing = 25;
// Label color.
const SkColor kLabelColor = 0xFF000000;
const SkColor kSkipLabelColor = 0xFFAA0000;
const SkColor kManualRebootLabelColor = 0xFFAA0000;
} // namespace
namespace chromeos {
UpdateView::UpdateView(chromeos::ScreenObserver* observer)
: installing_updates_label_(NULL),
preparing_updates_label_(NULL),
reboot_label_(NULL),
manual_reboot_label_(NULL),
progress_bar_(NULL),
show_curtain_(true),
show_manual_reboot_label_(false),
show_preparing_updates_label_(false),
observer_(observer) {
}
UpdateView::~UpdateView() {
}
void UpdateView::Init() {
// Use rounded-rect background.
views::Painter* painter = chromeos::CreateWizardPainter(
&chromeos::BorderDefinition::kScreenBorder);
set_background(views::Background::CreateBackgroundPainter(true, painter));
InitLabel(&installing_updates_label_);
InitLabel(&preparing_updates_label_);
InitLabel(&reboot_label_);
InitLabel(&manual_reboot_label_);
preparing_updates_label_->SetVisible(false);
manual_reboot_label_->SetVisible(false);
manual_reboot_label_->SetColor(kManualRebootLabelColor);
progress_bar_ = new views::ProgressBar();
AddChildView(progress_bar_);
// Curtain view.
InitLabel(&checking_label_);
throbber_ = CreateDefaultThrobber();
AddChildView(throbber_);
#if !defined(OFFICIAL_BUILD)
InitLabel(&escape_to_skip_label_);
escape_to_skip_label_->SetColor(kSkipLabelColor);
escape_to_skip_label_->SetText(
L"Press ESCAPE to skip (Non-official builds only)");
#endif
UpdateLocalizedStrings();
UpdateVisibility();
}
void UpdateView::Reset() {
progress_bar_->SetProgress(0);
}
void UpdateView::UpdateLocalizedStrings() {
installing_updates_label_->SetText(UTF16ToWide(l10n_util::GetStringFUTF16(
IDS_INSTALLING_UPDATE,
l10n_util::GetStringUTF16(IDS_PRODUCT_OS_NAME))));
preparing_updates_label_->SetText(
UTF16ToWide(l10n_util::GetStringUTF16(IDS_UPDATE_AVAILABLE)));
reboot_label_->SetText(
UTF16ToWide(l10n_util::GetStringUTF16(IDS_INSTALLING_UPDATE_DESC)));
manual_reboot_label_->SetText(
UTF16ToWide(l10n_util::GetStringUTF16(IDS_UPDATE_COMPLETED)));
checking_label_->SetText(
UTF16ToWide(l10n_util::GetStringUTF16(IDS_CHECKING_FOR_UPDATES)));
}
void UpdateView::AddProgress(int ticks) {
progress_bar_->AddProgress(ticks);
}
void UpdateView::SetProgress(int progress) {
progress_bar_->SetProgress(progress);
}
void UpdateView::ShowManualRebootInfo() {
show_manual_reboot_label_ = true;
UpdateVisibility();
}
void UpdateView::ShowPreparingUpdatesInfo(bool visible) {
show_preparing_updates_label_ = visible;
UpdateVisibility();
}
void UpdateView::ShowCurtain(bool show_curtain) {
if (show_curtain_ != show_curtain) {
show_curtain_ = show_curtain;
UpdateVisibility();
}
}
// Sets the bounds of the view, placing center of the view at the given
// coordinates (|x| and |y|).
static void setViewBounds(views::View* view, int x, int y) {
int preferred_width = view->GetPreferredSize().width();
int preferred_height = view->GetPreferredSize().height();
view->SetBounds(
x - preferred_width / 2,
y - preferred_height / 2,
preferred_width,
preferred_height);
}
void UpdateView::Layout() {
int max_width = width() - GetInsets().width() - 2 * kHorizontalSpacing;
int right_margin = GetInsets().right() + kHorizontalSpacing;
int max_height = height() - GetInsets().height();
int vertical_center = GetInsets().top() + max_height / 2;
installing_updates_label_->SizeToFit(max_width);
preparing_updates_label_->SizeToFit(max_width);
reboot_label_->SizeToFit(max_width);
manual_reboot_label_->SizeToFit(max_width);
progress_bar_->SetBounds(right_margin,
vertical_center - kProgressBarHeight / 2,
max_width,
kProgressBarHeight);
installing_updates_label_->SetX(right_margin);
installing_updates_label_->SetY(
progress_bar_->y() -
kInstallingUpdatesLabelYBottomFromProgressBar -
installing_updates_label_->height());
preparing_updates_label_->SetX(installing_updates_label_->x());
preparing_updates_label_->SetY(installing_updates_label_->y());
reboot_label_->SetX(right_margin);
reboot_label_->SetY(
progress_bar_->y() +
progress_bar_->height() +
kRebootLabelYFromProgressBar);
manual_reboot_label_->SetX(reboot_label_->x());
manual_reboot_label_->SetY(reboot_label_->y());
// Curtain layout is independed.
int x_center = width() / 2;
int throbber_width = throbber_->GetPreferredSize().width();
checking_label_->SizeToFit(max_width - throbber_width - kBetweenSpacing);
int checking_label_width = checking_label_->GetPreferredSize().width();
int space_half = (kBetweenSpacing + 1) / 2;
setViewBounds(
throbber_, x_center - checking_label_width / 2 - space_half,
vertical_center);
setViewBounds(
checking_label_, x_center + (throbber_width + 1) / 2 + space_half,
vertical_center);
#if !defined(OFFICIAL_BUILD)
escape_to_skip_label_->SizeToFit(max_width);
escape_to_skip_label_->SetX(right_margin);
escape_to_skip_label_->SetY(kEscapeToSkipLabelY);
#endif
SchedulePaint();
}
void UpdateView::InitLabel(views::Label** label) {
*label = new views::Label();
(*label)->SetColor(kLabelColor);
(*label)->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
(*label)->SetMultiLine(true);
ResourceBundle& res_bundle = ResourceBundle::GetSharedInstance();
gfx::Font label_font = res_bundle.GetFont(ResourceBundle::MediumFont);
(*label)->SetFont(label_font);
AddChildView(*label);
}
void UpdateView::UpdateVisibility() {
installing_updates_label_->SetVisible(!show_curtain_ &&
!show_manual_reboot_label_ &&
!show_preparing_updates_label_);
preparing_updates_label_->SetVisible(!show_curtain_ &&
!show_manual_reboot_label_ &&
show_preparing_updates_label_);
reboot_label_->SetVisible(!show_curtain_&& !show_manual_reboot_label_);
manual_reboot_label_->SetVisible(!show_curtain_ && show_manual_reboot_label_);
progress_bar_->SetVisible(!show_curtain_);
checking_label_->SetVisible(show_curtain_);
throbber_->SetVisible(show_curtain_);
if (show_curtain_) {
throbber_->Start();
} else {
throbber_->Stop();
}
}
} // namespace chromeos
<commit_msg>Fix to make OOBE update screen speak<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/update_view.h"
#include <string>
#include "base/logging.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chromeos/login/helper.h"
#include "chrome/browser/chromeos/login/rounded_rect_painter.h"
#include "chrome/browser/chromeos/login/wizard_accessibility_helper.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "views/border.h"
#include "views/controls/label.h"
#include "views/controls/progress_bar.h"
#include "views/controls/throbber.h"
#include "views/focus/focus_manager.h"
#include "views/widget/widget.h"
using views::Background;
using views::Label;
using views::View;
using views::Widget;
namespace {
// TODO(nkostylev): Switch to GridLayout.
// Y offset for the 'installing updates' label.
const int kInstallingUpdatesLabelYBottomFromProgressBar = 18;
// Y offset for the progress bar.
const int kProgressBarY = 130;
// Y offset for the 'computer will restart' label.
const int kRebootLabelYFromProgressBar = 55;
// Y offset for the 'ESCAPE to skip' label.
const int kEscapeToSkipLabelY = 48;
// Progress bar width.
const int kProgressBarWidth = 420;
// Progress bar height.
const int kProgressBarHeight = 18;
// Horizontal spacing (ex. min left and right margins for label on the screen).
const int kHorizontalSpacing = 65;
// Horizontal spacing between spinner and label on the curtain screen.
const int kBetweenSpacing = 25;
// Label color.
const SkColor kLabelColor = 0xFF000000;
const SkColor kSkipLabelColor = 0xFFAA0000;
const SkColor kManualRebootLabelColor = 0xFFAA0000;
} // namespace
namespace chromeos {
UpdateView::UpdateView(chromeos::ScreenObserver* observer)
: installing_updates_label_(NULL),
preparing_updates_label_(NULL),
reboot_label_(NULL),
manual_reboot_label_(NULL),
progress_bar_(NULL),
show_curtain_(true),
show_manual_reboot_label_(false),
show_preparing_updates_label_(false),
observer_(observer) {
}
UpdateView::~UpdateView() {
}
void UpdateView::Init() {
// Use rounded-rect background.
views::Painter* painter = chromeos::CreateWizardPainter(
&chromeos::BorderDefinition::kScreenBorder);
set_background(views::Background::CreateBackgroundPainter(true, painter));
InitLabel(&installing_updates_label_);
InitLabel(&preparing_updates_label_);
InitLabel(&reboot_label_);
InitLabel(&manual_reboot_label_);
preparing_updates_label_->SetVisible(false);
manual_reboot_label_->SetVisible(false);
manual_reboot_label_->SetColor(kManualRebootLabelColor);
progress_bar_ = new views::ProgressBar();
AddChildView(progress_bar_);
// Curtain view.
InitLabel(&checking_label_);
throbber_ = CreateDefaultThrobber();
AddChildView(throbber_);
#if !defined(OFFICIAL_BUILD)
InitLabel(&escape_to_skip_label_);
escape_to_skip_label_->SetColor(kSkipLabelColor);
escape_to_skip_label_->SetText(
L"Press ESCAPE to skip (Non-official builds only)");
#endif
UpdateLocalizedStrings();
UpdateVisibility();
}
void UpdateView::Reset() {
progress_bar_->SetProgress(0);
}
void UpdateView::UpdateLocalizedStrings() {
installing_updates_label_->SetText(UTF16ToWide(l10n_util::GetStringFUTF16(
IDS_INSTALLING_UPDATE,
l10n_util::GetStringUTF16(IDS_PRODUCT_OS_NAME))));
preparing_updates_label_->SetText(
UTF16ToWide(l10n_util::GetStringUTF16(IDS_UPDATE_AVAILABLE)));
reboot_label_->SetText(
UTF16ToWide(l10n_util::GetStringUTF16(IDS_INSTALLING_UPDATE_DESC)));
manual_reboot_label_->SetText(
UTF16ToWide(l10n_util::GetStringUTF16(IDS_UPDATE_COMPLETED)));
checking_label_->SetText(
UTF16ToWide(l10n_util::GetStringUTF16(IDS_CHECKING_FOR_UPDATES)));
}
void UpdateView::AddProgress(int ticks) {
progress_bar_->AddProgress(ticks);
}
void UpdateView::SetProgress(int progress) {
progress_bar_->SetProgress(progress);
}
void UpdateView::ShowManualRebootInfo() {
show_manual_reboot_label_ = true;
UpdateVisibility();
}
void UpdateView::ShowPreparingUpdatesInfo(bool visible) {
show_preparing_updates_label_ = visible;
UpdateVisibility();
}
void UpdateView::ShowCurtain(bool show_curtain) {
if (show_curtain_ != show_curtain) {
show_curtain_ = show_curtain;
UpdateVisibility();
}
}
// Sets the bounds of the view, placing center of the view at the given
// coordinates (|x| and |y|).
static void setViewBounds(views::View* view, int x, int y) {
int preferred_width = view->GetPreferredSize().width();
int preferred_height = view->GetPreferredSize().height();
view->SetBounds(
x - preferred_width / 2,
y - preferred_height / 2,
preferred_width,
preferred_height);
}
void UpdateView::Layout() {
int max_width = width() - GetInsets().width() - 2 * kHorizontalSpacing;
int right_margin = GetInsets().right() + kHorizontalSpacing;
int max_height = height() - GetInsets().height();
int vertical_center = GetInsets().top() + max_height / 2;
installing_updates_label_->SizeToFit(max_width);
preparing_updates_label_->SizeToFit(max_width);
reboot_label_->SizeToFit(max_width);
manual_reboot_label_->SizeToFit(max_width);
progress_bar_->SetBounds(right_margin,
vertical_center - kProgressBarHeight / 2,
max_width,
kProgressBarHeight);
installing_updates_label_->SetX(right_margin);
installing_updates_label_->SetY(
progress_bar_->y() -
kInstallingUpdatesLabelYBottomFromProgressBar -
installing_updates_label_->height());
preparing_updates_label_->SetX(installing_updates_label_->x());
preparing_updates_label_->SetY(installing_updates_label_->y());
reboot_label_->SetX(right_margin);
reboot_label_->SetY(
progress_bar_->y() +
progress_bar_->height() +
kRebootLabelYFromProgressBar);
manual_reboot_label_->SetX(reboot_label_->x());
manual_reboot_label_->SetY(reboot_label_->y());
// Curtain layout is independed.
int x_center = width() / 2;
int throbber_width = throbber_->GetPreferredSize().width();
checking_label_->SizeToFit(max_width - throbber_width - kBetweenSpacing);
int checking_label_width = checking_label_->GetPreferredSize().width();
int space_half = (kBetweenSpacing + 1) / 2;
setViewBounds(
throbber_, x_center - checking_label_width / 2 - space_half,
vertical_center);
setViewBounds(
checking_label_, x_center + (throbber_width + 1) / 2 + space_half,
vertical_center);
#if !defined(OFFICIAL_BUILD)
escape_to_skip_label_->SizeToFit(max_width);
escape_to_skip_label_->SetX(right_margin);
escape_to_skip_label_->SetY(kEscapeToSkipLabelY);
#endif
SchedulePaint();
}
void UpdateView::InitLabel(views::Label** label) {
*label = new views::Label();
(*label)->SetColor(kLabelColor);
(*label)->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
(*label)->SetMultiLine(true);
ResourceBundle& res_bundle = ResourceBundle::GetSharedInstance();
gfx::Font label_font = res_bundle.GetFont(ResourceBundle::MediumFont);
(*label)->SetFont(label_font);
AddChildView(*label);
}
void UpdateView::UpdateVisibility() {
installing_updates_label_->SetVisible(!show_curtain_ &&
!show_manual_reboot_label_ &&
!show_preparing_updates_label_);
preparing_updates_label_->SetVisible(!show_curtain_ &&
!show_manual_reboot_label_ &&
show_preparing_updates_label_);
reboot_label_->SetVisible(!show_curtain_&& !show_manual_reboot_label_);
manual_reboot_label_->SetVisible(!show_curtain_ && show_manual_reboot_label_);
progress_bar_->SetVisible(!show_curtain_);
checking_label_->SetVisible(show_curtain_);
throbber_->SetVisible(show_curtain_);
if (show_curtain_) {
throbber_->Start();
} else {
throbber_->Stop();
}
// Speak the shown label when accessibility is enabled.
const Label* label_spoken(NULL);
if (checking_label_->IsVisible()) {
label_spoken = checking_label_;
} else if (manual_reboot_label_->IsVisible()) {
label_spoken = manual_reboot_label_;
} else if (preparing_updates_label_->IsVisible()) {
label_spoken = preparing_updates_label_;
} else if (installing_updates_label_->IsVisible()) {
label_spoken = installing_updates_label_;
} else {
NOTREACHED();
}
const std::string text =
label_spoken ? WideToUTF8(label_spoken->GetText()) : std::string();
WizardAccessibilityHelper::GetInstance()->MaybeSpeak(text.c_str(), false,
true);
}
} // namespace chromeos
<|endoftext|> |
<commit_before>// Copyright (c) 2011 - 2015, GS Group, https://github.com/GSGroup
// Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted,
// provided that the above copyright notice and this permission notice appear in all copies.
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
// WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#include <stingraykit/time/Time.h>
#include <stdio.h>
#include <stingraykit/exception.h>
#include <stingraykit/serialization/Serialization.h>
#include <stingraykit/string/StringFormat.h>
#include <stingraykit/string/StringUtils.h>
#include <stingraykit/time/TimeEngine.h>
#include <stingraykit/log/Logger.h>
namespace stingray
{
static const int SecondsPerMinute = 60;
static const int MillisecondsPerMinute = SecondsPerMinute * 1000;
static const int MinutesPerHour = 60;
static const int SecondsPerHour = MinutesPerHour * SecondsPerMinute;
static const int SecondsPerDay = 24 * SecondsPerHour;
static const int DaysSinceMjd = 40587;
void TimeDuration::Serialize(ObjectOStream & ar) const
{ ar.Serialize("us", _microseconds); }
void TimeDuration::Deserialize(ObjectIStream & ar)
{
optional<s64> microseconds;
ar.Deserialize("us", microseconds);
if (microseconds)
{
_microseconds = *microseconds;
return;
}
s64 milliseconds = 0;
ar.Deserialize("ms", milliseconds);
_microseconds = milliseconds * 1000;
}
std::string TimeDuration::ToString(const std::string& format) const
{
std::string result = format.empty() ? "hh:mm:ss.lll" : format;
if (GetMilliseconds() < 0)
result.insert(0, "-");
std::string hours_placeholder = "hh";
bool has_hours = std::search(format.begin(), format.end(), hours_placeholder.begin(), hours_placeholder.end()) != format.end();
s64 abs_ms = Absolute().GetMilliseconds();
s64 hours = has_hours ? abs_ms / Hour().GetMilliseconds() : 0;
s64 minutes = (abs_ms - hours * Hour().GetMilliseconds()) / Minute().GetMilliseconds();
s64 seconds = abs_ms % Minute().GetMilliseconds() / Second().GetMilliseconds();
s64 milliseconds = abs_ms % Second().GetMilliseconds();
if (has_hours)
ReplaceAll(result, "hh", StringFormat("%1$2%", hours));
else
ReplaceAll(result, "hh", "");
ReplaceAll(result, "mm", StringFormat("%1$2%", minutes));
ReplaceAll(result, "ss", StringFormat("%1$2%", seconds));
ReplaceAll(result, "lll", StringFormat("%1$3%", milliseconds));
return result;
}
TimeDuration TimeDuration::FromString(const std::string& s)
{
int n;
char c = 0;
int components = sscanf(s.c_str(), "%d%c", &n, &c);
if (components < 1)
STINGRAYKIT_THROW("Invalid time duration format");
switch (c)
{
case 'H':
case 'h':
return FromHours(n);
case 'M':
case 'm':
return FromMinutes(n);
case 'S':
case 's':
return FromSeconds(n);
case 0:
return TimeDuration(n);
};
STINGRAYKIT_THROW("Could not parse TimeDuration!");
}
Time::Time()
: _milliseconds(0)
{ }
Time::Time(s64 milliseconds)
: _milliseconds(milliseconds)
{ }
Time Time::Now() { return Time(TimeEngine::GetMillisecondsSinceEpoch()); }
BrokenDownTime Time::BreakDown(TimeKind kind) const
{
const s64 offset = kind == TimeKind::Utc? 0 : MillisecondsPerMinute * TimeEngine::GetMinutesFromUtc();
return TimeEngine::BrokenDownFromMilliseconds(_milliseconds + offset);
}
Time Time::FromBrokenDownTime(const BrokenDownTime& bdt, TimeKind kind)
{
const s64 offset = kind == TimeKind::Utc? 0 : MillisecondsPerMinute * TimeEngine::GetMinutesFromUtc();
return Time(TimeEngine::MillisecondsFromBrokenDown(bdt) - offset);
}
std::string Time::ToString(const std::string& format, TimeKind kind) const
{ return BreakDown(kind).ToString(format); }
Time Time::FromString(const std::string& s, TimeKind kind)
{
if (s == "now")
return Time::Now();
if (s.size() > 4 && s.substr(0, 4) == "now+")
return Time::Now() + TimeDuration::FromString(s.substr(4));
s16 year, month, day;
s16 hour, minute, second;
char utcSign;
s16 utcHour, utcMinute;
bool haveDate = false;
bool haveTime = false;
bool haveSeconds = false;
bool haveUtcSign = false;
bool haveUtcHours = false;
bool haveUtcMinutes = false;
int components = sscanf(s.c_str(), "%hd.%hd.%hd %hd:%hd:%hd", &day, &month, &year, &hour, &minute, &second);
if (components >= 3)
{
haveDate = true;
if (components >= 5)
haveTime = true;
if (components >= 6)
haveSeconds = true;
}
else
{
components = sscanf(s.c_str(), "%hd/%hd/%hd %hd:%hd:%hd", &year, &month, &day, &hour, &minute, &second);
if (components >= 3)
{
haveDate = true;
if (components >= 5)
haveTime = true;
if (components >= 6)
haveSeconds = true;
}
else
{
components = sscanf(s.c_str(), "%hd:%hd:%hd", &hour, &minute, &second);
if (components >= 2)
{
haveTime = true;
if (components >= 3)
haveSeconds = true;
}
else
{
components = sscanf(s.c_str(), "%hd-%hd-%hdT%hd:%hd:%hd%c%hd:%hd", &year, &month, &day, &hour, &minute, &second, &utcSign, &utcHour, &utcMinute);
if (components >= 3)
{
haveDate = true;
if (components >= 5)
haveTime = true;
if (components >= 6)
haveSeconds = true;
if (components >= 7)
haveUtcSign = true;
if (components >= 8)
haveUtcHours = true;
if (components >= 9)
haveUtcMinutes = true;
}
else
STINGRAYKIT_THROW("Unknown time format!");
}
}
}
STINGRAYKIT_CHECK((haveDate || haveTime), "Could not parse Time!");
STINGRAYKIT_CHECK(!(!haveTime && haveSeconds), "Have seconds without hours and minutes!");
STINGRAYKIT_CHECK(!haveUtcSign || ((utcSign == 'Z' && !haveUtcHours && !haveUtcMinutes) || ((utcSign == '+' || utcSign == '-') && haveUtcHours && !(!haveUtcHours && haveUtcMinutes))), "Malformed UTC suffix");
if (haveUtcSign)
Logger::Debug() << "Time::FromString: time kind parameter will be ignored because time string have UTC sign";
BrokenDownTime bdt;
if (haveDate)
{
bdt.MonthDay = day;
bdt.Month = month;
bdt.Year = (year > 100 ? year : (year > 30 ? 1900 + year : 2000 + year));
}
else
{
bdt = Time::Now().BreakDown();
bdt.Seconds = 0;
bdt.Milliseconds = 0;
}
if (haveTime)
{
bdt.Hours = hour;
bdt.Minutes = minute;
}
if (haveSeconds)
bdt.Seconds = second;
if (haveUtcSign)
{
kind = TimeKind::Utc;
if ((utcSign == '+') || (utcSign == '-'))
{
s16 minutesFromUtc = (haveUtcHours ? (utcHour * MinutesPerHour) : 0) + (haveUtcMinutes ? utcMinute : 0);
if (utcSign == '-')
bdt.Minutes += minutesFromUtc;
else
bdt.Minutes -= minutesFromUtc;
}
else if (utcSign != 'Z')
STINGRAYKIT_THROW("Unknown UTC sign!");
}
return FromBrokenDownTime(bdt, kind);
}
void Time::Serialize(ObjectOStream & ar) const { ar.Serialize("ms", _milliseconds); }
void Time::Deserialize(ObjectIStream & ar) { ar.Deserialize("ms", _milliseconds); }
TimeZone::TimeZone()
: _minutesFromUtc()
{ }
TimeZone::TimeZone(s16 minutes)
: _minutesFromUtc(minutes)
{ STINGRAYKIT_CHECK(_minutesFromUtc >= -12 * MinutesPerHour && _minutesFromUtc <= 14 * MinutesPerHour, IndexOutOfRangeException()); }
TimeZone TimeZone::Current()
{ return TimeZone(TimeEngine::GetMinutesFromUtc()); }
std::string TimeZone::ToString() const
{
const std::string sign = _minutesFromUtc > 0? "+" : _minutesFromUtc < 0? "-" : "";
return StringBuilder() % sign % (_minutesFromUtc / MinutesPerHour) % ":" % (_minutesFromUtc % MinutesPerHour);
}
TimeZone TimeZone::FromString(const std::string& str)
{
char sign;
int hours, minutes;
STINGRAYKIT_CHECK(sscanf(str.c_str(), "%c%d:%d", &sign, &hours, &minutes) == 3, FormatException());
const int value = hours * MinutesPerHour + minutes;
return TimeZone(sign == '+'? value : -value);
}
void TimeZone::Serialize(ObjectOStream & ar) const { ar.Serialize("offset", _minutesFromUtc); }
void TimeZone::Deserialize(ObjectIStream & ar) { ar.Deserialize("offset", _minutesFromUtc); }
const s64 SecondsBetweenNtpAndUnixEpochs = 2208988800ll;
u64 Time::ToNtpTimestamp() const
{
return GetMilliseconds() / 1000 + SecondsBetweenNtpAndUnixEpochs;
}
Time Time::FromNtpTimestamp(u64 timestamp)
{
return Time((timestamp - SecondsBetweenNtpAndUnixEpochs) * 1000);
}
static inline u8 bcdValue(u8 byte)
{ return ((byte >> 4) & 0x0f) * 10 + (byte & 0x0f); }
static inline u8 bcdEncode(u8 value)
{ return ((value / 10) << 4) + value % 10; }
Time Time::MJDtoEpoch(int mjd, u32 bcdTime)
{ return Time(s64(mjd - DaysSinceMjd) * SecondsPerDay * 1000) + BCDDurationToTimeDuration(bcdTime); }
TimeDuration Time::BCDDurationToTimeDuration(u32 bcdTime)
{
return TimeDuration(s64(1000) * (SecondsPerHour * bcdValue((bcdTime >> 16) & 0xff) +
SecondsPerMinute * bcdValue((bcdTime >> 8) & 0xff) +
bcdValue(bcdTime & 0xff)));
}
int Time::GetMJD() const
{
return DaysSinceMjd + _milliseconds / (1000 * SecondsPerDay);
}
u32 Time::GetBCDTime(TimeKind kind) const
{
BrokenDownTime bdt(this->BreakDown(kind));
return (bcdEncode(bdt.Hours) << 16) + (bcdEncode(bdt.Minutes) << 8) + bcdEncode(bdt.Seconds);
}
int Time::DaysTo(const Time& endTime)
{
return (Time::FromBrokenDownTime((*this).BreakDown().GetDayStart()).GetMilliseconds() - Time::FromBrokenDownTime(endTime.BreakDown().GetDayStart()).GetMilliseconds()) / 86400000; // 1000 * 60 * 60 * 24 = 86400000
}
}
<commit_msg>Time: use same date order for slash-divided dates in To- and FromString functions<commit_after>// Copyright (c) 2011 - 2015, GS Group, https://github.com/GSGroup
// Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted,
// provided that the above copyright notice and this permission notice appear in all copies.
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
// WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#include <stingraykit/time/Time.h>
#include <stdio.h>
#include <stingraykit/exception.h>
#include <stingraykit/serialization/Serialization.h>
#include <stingraykit/string/StringFormat.h>
#include <stingraykit/string/StringUtils.h>
#include <stingraykit/time/TimeEngine.h>
#include <stingraykit/log/Logger.h>
namespace stingray
{
static const int SecondsPerMinute = 60;
static const int MillisecondsPerMinute = SecondsPerMinute * 1000;
static const int MinutesPerHour = 60;
static const int SecondsPerHour = MinutesPerHour * SecondsPerMinute;
static const int SecondsPerDay = 24 * SecondsPerHour;
static const int DaysSinceMjd = 40587;
void TimeDuration::Serialize(ObjectOStream & ar) const
{ ar.Serialize("us", _microseconds); }
void TimeDuration::Deserialize(ObjectIStream & ar)
{
optional<s64> microseconds;
ar.Deserialize("us", microseconds);
if (microseconds)
{
_microseconds = *microseconds;
return;
}
s64 milliseconds = 0;
ar.Deserialize("ms", milliseconds);
_microseconds = milliseconds * 1000;
}
std::string TimeDuration::ToString(const std::string& format) const
{
std::string result = format.empty() ? "hh:mm:ss.lll" : format;
if (GetMilliseconds() < 0)
result.insert(0, "-");
std::string hours_placeholder = "hh";
bool has_hours = std::search(format.begin(), format.end(), hours_placeholder.begin(), hours_placeholder.end()) != format.end();
s64 abs_ms = Absolute().GetMilliseconds();
s64 hours = has_hours ? abs_ms / Hour().GetMilliseconds() : 0;
s64 minutes = (abs_ms - hours * Hour().GetMilliseconds()) / Minute().GetMilliseconds();
s64 seconds = abs_ms % Minute().GetMilliseconds() / Second().GetMilliseconds();
s64 milliseconds = abs_ms % Second().GetMilliseconds();
if (has_hours)
ReplaceAll(result, "hh", StringFormat("%1$2%", hours));
else
ReplaceAll(result, "hh", "");
ReplaceAll(result, "mm", StringFormat("%1$2%", minutes));
ReplaceAll(result, "ss", StringFormat("%1$2%", seconds));
ReplaceAll(result, "lll", StringFormat("%1$3%", milliseconds));
return result;
}
TimeDuration TimeDuration::FromString(const std::string& s)
{
int n;
char c = 0;
int components = sscanf(s.c_str(), "%d%c", &n, &c);
if (components < 1)
STINGRAYKIT_THROW("Invalid time duration format");
switch (c)
{
case 'H':
case 'h':
return FromHours(n);
case 'M':
case 'm':
return FromMinutes(n);
case 'S':
case 's':
return FromSeconds(n);
case 0:
return TimeDuration(n);
};
STINGRAYKIT_THROW("Could not parse TimeDuration!");
}
Time::Time()
: _milliseconds(0)
{ }
Time::Time(s64 milliseconds)
: _milliseconds(milliseconds)
{ }
Time Time::Now() { return Time(TimeEngine::GetMillisecondsSinceEpoch()); }
BrokenDownTime Time::BreakDown(TimeKind kind) const
{
const s64 offset = kind == TimeKind::Utc? 0 : MillisecondsPerMinute * TimeEngine::GetMinutesFromUtc();
return TimeEngine::BrokenDownFromMilliseconds(_milliseconds + offset);
}
Time Time::FromBrokenDownTime(const BrokenDownTime& bdt, TimeKind kind)
{
const s64 offset = kind == TimeKind::Utc? 0 : MillisecondsPerMinute * TimeEngine::GetMinutesFromUtc();
return Time(TimeEngine::MillisecondsFromBrokenDown(bdt) - offset);
}
std::string Time::ToString(const std::string& format, TimeKind kind) const
{ return BreakDown(kind).ToString(format); }
Time Time::FromString(const std::string& s, TimeKind kind)
{
if (s == "now")
return Time::Now();
if (s.size() > 4 && s.substr(0, 4) == "now+")
return Time::Now() + TimeDuration::FromString(s.substr(4));
s16 year, month, day;
s16 hour, minute, second;
char utcSign;
s16 utcHour, utcMinute;
bool haveDate = false;
bool haveTime = false;
bool haveSeconds = false;
bool haveUtcSign = false;
bool haveUtcHours = false;
bool haveUtcMinutes = false;
int components = sscanf(s.c_str(), "%hd.%hd.%hd %hd:%hd:%hd", &day, &month, &year, &hour, &minute, &second);
if (components >= 3)
{
haveDate = true;
if (components >= 5)
haveTime = true;
if (components >= 6)
haveSeconds = true;
}
else
{
components = sscanf(s.c_str(), "%hd/%hd/%hd %hd:%hd:%hd", &day, &month, &year, &hour, &minute, &second);
if (components >= 3)
{
haveDate = true;
if (components >= 5)
haveTime = true;
if (components >= 6)
haveSeconds = true;
}
else
{
components = sscanf(s.c_str(), "%hd:%hd:%hd", &hour, &minute, &second);
if (components >= 2)
{
haveTime = true;
if (components >= 3)
haveSeconds = true;
}
else
{
components = sscanf(s.c_str(), "%hd-%hd-%hdT%hd:%hd:%hd%c%hd:%hd", &year, &month, &day, &hour, &minute, &second, &utcSign, &utcHour, &utcMinute);
if (components >= 3)
{
haveDate = true;
if (components >= 5)
haveTime = true;
if (components >= 6)
haveSeconds = true;
if (components >= 7)
haveUtcSign = true;
if (components >= 8)
haveUtcHours = true;
if (components >= 9)
haveUtcMinutes = true;
}
else
STINGRAYKIT_THROW("Unknown time format!");
}
}
}
STINGRAYKIT_CHECK((haveDate || haveTime), "Could not parse Time!");
STINGRAYKIT_CHECK(!(!haveTime && haveSeconds), "Have seconds without hours and minutes!");
STINGRAYKIT_CHECK(!haveUtcSign || ((utcSign == 'Z' && !haveUtcHours && !haveUtcMinutes) || ((utcSign == '+' || utcSign == '-') && haveUtcHours && !(!haveUtcHours && haveUtcMinutes))), "Malformed UTC suffix");
if (haveUtcSign)
Logger::Debug() << "Time::FromString: time kind parameter will be ignored because time string have UTC sign";
BrokenDownTime bdt;
if (haveDate)
{
bdt.MonthDay = day;
bdt.Month = month;
bdt.Year = (year > 100 ? year : (year > 30 ? 1900 + year : 2000 + year));
}
else
{
bdt = Time::Now().BreakDown();
bdt.Seconds = 0;
bdt.Milliseconds = 0;
}
if (haveTime)
{
bdt.Hours = hour;
bdt.Minutes = minute;
}
if (haveSeconds)
bdt.Seconds = second;
if (haveUtcSign)
{
kind = TimeKind::Utc;
if ((utcSign == '+') || (utcSign == '-'))
{
s16 minutesFromUtc = (haveUtcHours ? (utcHour * MinutesPerHour) : 0) + (haveUtcMinutes ? utcMinute : 0);
if (utcSign == '-')
bdt.Minutes += minutesFromUtc;
else
bdt.Minutes -= minutesFromUtc;
}
else if (utcSign != 'Z')
STINGRAYKIT_THROW("Unknown UTC sign!");
}
return FromBrokenDownTime(bdt, kind);
}
void Time::Serialize(ObjectOStream & ar) const { ar.Serialize("ms", _milliseconds); }
void Time::Deserialize(ObjectIStream & ar) { ar.Deserialize("ms", _milliseconds); }
TimeZone::TimeZone()
: _minutesFromUtc()
{ }
TimeZone::TimeZone(s16 minutes)
: _minutesFromUtc(minutes)
{ STINGRAYKIT_CHECK(_minutesFromUtc >= -12 * MinutesPerHour && _minutesFromUtc <= 14 * MinutesPerHour, IndexOutOfRangeException()); }
TimeZone TimeZone::Current()
{ return TimeZone(TimeEngine::GetMinutesFromUtc()); }
std::string TimeZone::ToString() const
{
const std::string sign = _minutesFromUtc > 0? "+" : _minutesFromUtc < 0? "-" : "";
return StringBuilder() % sign % (_minutesFromUtc / MinutesPerHour) % ":" % (_minutesFromUtc % MinutesPerHour);
}
TimeZone TimeZone::FromString(const std::string& str)
{
char sign;
int hours, minutes;
STINGRAYKIT_CHECK(sscanf(str.c_str(), "%c%d:%d", &sign, &hours, &minutes) == 3, FormatException());
const int value = hours * MinutesPerHour + minutes;
return TimeZone(sign == '+'? value : -value);
}
void TimeZone::Serialize(ObjectOStream & ar) const { ar.Serialize("offset", _minutesFromUtc); }
void TimeZone::Deserialize(ObjectIStream & ar) { ar.Deserialize("offset", _minutesFromUtc); }
const s64 SecondsBetweenNtpAndUnixEpochs = 2208988800ll;
u64 Time::ToNtpTimestamp() const
{
return GetMilliseconds() / 1000 + SecondsBetweenNtpAndUnixEpochs;
}
Time Time::FromNtpTimestamp(u64 timestamp)
{
return Time((timestamp - SecondsBetweenNtpAndUnixEpochs) * 1000);
}
static inline u8 bcdValue(u8 byte)
{ return ((byte >> 4) & 0x0f) * 10 + (byte & 0x0f); }
static inline u8 bcdEncode(u8 value)
{ return ((value / 10) << 4) + value % 10; }
Time Time::MJDtoEpoch(int mjd, u32 bcdTime)
{ return Time(s64(mjd - DaysSinceMjd) * SecondsPerDay * 1000) + BCDDurationToTimeDuration(bcdTime); }
TimeDuration Time::BCDDurationToTimeDuration(u32 bcdTime)
{
return TimeDuration(s64(1000) * (SecondsPerHour * bcdValue((bcdTime >> 16) & 0xff) +
SecondsPerMinute * bcdValue((bcdTime >> 8) & 0xff) +
bcdValue(bcdTime & 0xff)));
}
int Time::GetMJD() const
{
return DaysSinceMjd + _milliseconds / (1000 * SecondsPerDay);
}
u32 Time::GetBCDTime(TimeKind kind) const
{
BrokenDownTime bdt(this->BreakDown(kind));
return (bcdEncode(bdt.Hours) << 16) + (bcdEncode(bdt.Minutes) << 8) + bcdEncode(bdt.Seconds);
}
int Time::DaysTo(const Time& endTime)
{
return (Time::FromBrokenDownTime((*this).BreakDown().GetDayStart()).GetMilliseconds() - Time::FromBrokenDownTime(endTime.BreakDown().GetDayStart()).GetMilliseconds()) / 86400000; // 1000 * 60 * 60 * 24 = 86400000
}
}
<|endoftext|> |
<commit_before>#include <iostream>
using namespace std;
int main()
{
}
<commit_msg>removed empty solution<commit_after><|endoftext|> |
<commit_before>class Solution {
public:
/**
* @param nums an integer array and all positive numbers, no duplicates
* @param target an integer
* @return an integer
*/
int backPackVI(vector<int>& nums, int target) {
// Write your code here
}
};<commit_msg>Solved 564<commit_after>class Solution {
public:
/**
* @param nums an integer array and all positive numbers, no duplicates
* @param target an integer
* @return an integer
*/
std::vector<int> dp_ans;
std::vector<int> v;
int backPackVI(vector<int>& nums, int target) {
// Write your code here
sort(nums.begin(),nums.end());
if (nums.size()==0) return 0;
int n=nums.size(),i,j,k;
dp_ans.assign(target+5,0);
dp_ans[0]=1;
for (i=1;i<=target;i++){
for (auto const s:nums){
if (i-s<0) break;
dp_ans[i] +=dp_ans[i-s];
}
}
return dp_ans[target];
}
};<|endoftext|> |
<commit_before>// stl
#include <iostream>
#include <string>
//project
#include "Bot.h"
Bot::Bot()
: armiesLeft(0)
, parser(this)
, phase(NONE)
{
}
Bot::~Bot()
{
}
void Bot::playGame()
{
parser.parseInput();
}
void Bot::makeMoves()
{
/// Output No moves when you have no time left or do not want to commit any moves.
// std::cout << "No moves\n";
/// Anatomy of a single move
// std::cout << botName << " attack/transfer " << from << " " << to << " "<< armiesMoved;
/// When outputting multiple moves they must be seperated by a comma
std::vector<std::string> moves;
for(int j = 0; j < ownedRegions.size(); ++j)
{
std::stringstream move;
int i = ownedRegions[j];
if(regions[i].getArmies() > 1)
{
move << botName << " attack/transfer " << i << " " << regions[i].getNeighbor(std::rand() % regions[i].getNbNeighbors()) << " "<< (regions[i].getArmies()-1);
}
moves.push_back(move.str());
}
std::stringstream finalMoves;
for(int i = 0; i < moves.size(); ++i)
{
finalMoves << moves[i];
if(i + 1 == moves.size())
{
finalMoves << std::endl;
}
else
{
finalMoves << ",";
}
}
std::cout << finalMoves.str();
}
void Bot::addRegion(const unsigned& noRegion, const unsigned& noSuperRegion)
{
while (regions.size() <= noRegion)
{
regions.push_back(Region());
}
regions[noRegion] = Region(noRegion, noSuperRegion);
superRegions[noSuperRegion].addRegion(noRegion);
}
void Bot::addNeighbors(const unsigned& noRegion, const unsigned& neighbors)
{
regions[noRegion].addNeighbor(neighbors);
regions[neighbors].addNeighbor(noRegion);
}
void Bot::addWasteland(const unsigned &noRegion)
{
wastelands.push_back(noRegion);
}
void Bot::addSuperRegion(const unsigned& noSuperRegion, const int&reward)
{
while (superRegions.size() <= noSuperRegion)
{
superRegions.push_back(SuperRegion());
}
superRegions[noSuperRegion] = SuperRegion(reward);
}
void Bot::setBotName(const std::string& name)
{
botName = name;
}
void Bot::setOpponentBotName(const std::string& name)
{
opponentBotName = name;
}
void Bot::setArmiesLeft(const int& nbArmies)
{
armiesLeft = nbArmies;
}
void Bot::setTimebank(const int &newTimebank)
{
timebank = newTimebank;
}
void Bot::setTimePerMove(const int &newTimePerMove)
{
timePerMove = newTimePerMove;
}
void Bot::setMaxRounds(const int &newMaxRounds)
{
maxRounds = newMaxRounds;
}
void Bot::clearStartingRegions()
{
startingRegionsreceived.clear();
}
void Bot::addStartingRegion(const unsigned& noRegion)
{
startingRegionsreceived.push_back(noRegion);
}
void Bot::opponentPlacement(const unsigned &noRegion, const int &nbArmies)
{
// STUB
}
void Bot::opponentMovement(const unsigned &noRegion, const unsigned &toRegion, const int &nbArmies)
{
// STUB
}
void Bot::startDelay(const int& /* delay */)
{
// STUB
}
void Bot::setPhase(const Bot::Phase pPhase)
{
phase = pPhase;
}
void Bot::executeAction()
{
if (phase == NONE)
return;
if (phase == Bot::PICK_PREFERRED_REGION)
{
std::cout << startingRegionsreceived.front() << "\n";
}
if (phase == Bot::PLACE_ARMIES)
{
std::cout << botName << " place_armies " << ownedRegions[std::rand() % ownedRegions.size()] << " " << armiesLeft << "\n";
addArmies(ownedRegions[0], armiesLeft);
}
if (phase == Bot::ATTACK_TRANSFER )
{
makeMoves();
}
phase = NONE;
}
void Bot::updateRegion(const unsigned& noRegion, const std::string& playerName, const int& nbArmies)
{
regions[noRegion].setArmies(nbArmies);
regions[noRegion].setOwner(playerName);
if (playerName == botName)
ownedRegions.push_back(noRegion);
}
void Bot::addArmies(const unsigned& noRegion, const int& nbArmies)
{
regions[noRegion].setArmies(regions[noRegion].getArmies() + nbArmies);
}
void Bot::moveArmies(const unsigned& noRegion, const unsigned& toRegion, const int& nbArmies)
{
if (regions[noRegion].getOwner() == regions[toRegion].getOwner() && regions[noRegion].getArmies() > nbArmies)
{
regions[noRegion].setArmies(regions[noRegion].getArmies() - nbArmies);
regions[toRegion].setArmies(regions[toRegion].getArmies() + nbArmies);
}
else if (regions[noRegion].getArmies() > nbArmies)
{
regions[noRegion].setArmies(regions[noRegion].getArmies() - nbArmies);
if(regions[toRegion].getArmies() - std::round(nbArmies*0.6) <= 0)
{
regions[toRegion].setArmies(nbArmies - std::round(regions[toRegion].getArmies()*0.7));
regions[toRegion].setOwner(regions[noRegion].getOwner());
} else
{
regions[noRegion].setArmies(regions[noRegion].getArmies() + nbArmies - std::round(regions[toRegion].getArmies()*0.7));
regions[toRegion].setArmies(regions[toRegion].getArmies() - std::round(nbArmies*0.6));
}
}
}
void Bot::resetRegionsOwned()
{
ownedRegions.clear();
}
<commit_msg>cleaned up some compiler warnings<commit_after>// stl
#include <iostream>
#include <string>
//project
#include "Bot.h"
Bot::Bot()
: armiesLeft(0)
, parser(this)
, phase(NONE)
{
}
Bot::~Bot()
{
}
void Bot::playGame()
{
parser.parseInput();
}
void Bot::makeMoves()
{
/// Output No moves when you have no time left or do not want to commit any moves.
// std::cout << "No moves\n";
/// Anatomy of a single move
// std::cout << botName << " attack/transfer " << from << " " << to << " "<< armiesMoved;
/// When outputting multiple moves they must be seperated by a comma
std::vector<std::string> moves;
for(size_t j = 0; j < ownedRegions.size(); ++j)
{
std::stringstream move;
int i = ownedRegions[j];
if(regions[i].getArmies() > 1)
{
move << botName << " attack/transfer " << i << " " << regions[i].getNeighbor(std::rand() % regions[i].getNbNeighbors()) << " "<< (regions[i].getArmies()-1);
}
moves.push_back(move.str());
}
// TODO: use boost::join here as soon the server allows it
std::stringstream finalMoves;
for(size_t i = 0; i < moves.size(); ++i)
{
finalMoves << moves[i];
if(i + 1 == moves.size())
{
finalMoves << std::endl;
}
else
{
finalMoves << ",";
}
}
std::cout << finalMoves.str();
}
void Bot::addRegion(const unsigned& noRegion, const unsigned& noSuperRegion)
{
while (regions.size() <= noRegion)
{
regions.push_back(Region());
}
regions[noRegion] = Region(noRegion, noSuperRegion);
superRegions[noSuperRegion].addRegion(noRegion);
}
void Bot::addNeighbors(const unsigned& noRegion, const unsigned& neighbors)
{
regions[noRegion].addNeighbor(neighbors);
regions[neighbors].addNeighbor(noRegion);
}
void Bot::addWasteland(const unsigned &noRegion)
{
wastelands.push_back(noRegion);
}
void Bot::addSuperRegion(const unsigned& noSuperRegion, const int&reward)
{
while (superRegions.size() <= noSuperRegion)
{
superRegions.push_back(SuperRegion());
}
superRegions[noSuperRegion] = SuperRegion(reward);
}
void Bot::setBotName(const std::string& name)
{
botName = name;
}
void Bot::setOpponentBotName(const std::string& name)
{
opponentBotName = name;
}
void Bot::setArmiesLeft(const int& nbArmies)
{
armiesLeft = nbArmies;
}
void Bot::setTimebank(const int &newTimebank)
{
timebank = newTimebank;
}
void Bot::setTimePerMove(const int &newTimePerMove)
{
timePerMove = newTimePerMove;
}
void Bot::setMaxRounds(const int &newMaxRounds)
{
maxRounds = newMaxRounds;
}
void Bot::clearStartingRegions()
{
startingRegionsreceived.clear();
}
void Bot::addStartingRegion(const unsigned& noRegion)
{
startingRegionsreceived.push_back(noRegion);
}
void Bot::opponentPlacement(const unsigned & noRegion, const int & nbArmies)
{
// suppress unused variable warnings
(void)noRegion;
(void)nbArmies;
// TODO: STUB
}
void Bot::opponentMovement(const unsigned &noRegion, const unsigned &toRegion, const int &nbArmies)
{
// suppress unused variable warnings
(void)noRegion;
(void)toRegion;
(void)nbArmies;
// TODO: STUB
}
void Bot::startDelay(const int& delay)
{
// suppress unused variable warnings
(void)delay;
// TODO: STUB
}
void Bot::setPhase(const Bot::Phase pPhase)
{
phase = pPhase;
}
void Bot::executeAction()
{
if (phase == NONE)
return;
if (phase == Bot::PICK_PREFERRED_REGION)
{
std::cout << startingRegionsreceived.front() << "\n";
}
if (phase == Bot::PLACE_ARMIES)
{
std::cout << botName << " place_armies " << ownedRegions[std::rand() % ownedRegions.size()] << " " << armiesLeft << "\n";
addArmies(ownedRegions[0], armiesLeft);
}
if (phase == Bot::ATTACK_TRANSFER )
{
makeMoves();
}
phase = NONE;
}
void Bot::updateRegion(const unsigned& noRegion, const std::string& playerName, const int& nbArmies)
{
regions[noRegion].setArmies(nbArmies);
regions[noRegion].setOwner(playerName);
if (playerName == botName)
ownedRegions.push_back(noRegion);
}
void Bot::addArmies(const unsigned& noRegion, const int& nbArmies)
{
regions[noRegion].setArmies(regions[noRegion].getArmies() + nbArmies);
}
void Bot::moveArmies(const unsigned& noRegion, const unsigned& toRegion, const int& nbArmies)
{
if (regions[noRegion].getOwner() == regions[toRegion].getOwner() && regions[noRegion].getArmies() > nbArmies)
{
regions[noRegion].setArmies(regions[noRegion].getArmies() - nbArmies);
regions[toRegion].setArmies(regions[toRegion].getArmies() + nbArmies);
}
else if (regions[noRegion].getArmies() > nbArmies)
{
regions[noRegion].setArmies(regions[noRegion].getArmies() - nbArmies);
if(regions[toRegion].getArmies() - std::round(nbArmies*0.6) <= 0)
{
regions[toRegion].setArmies(nbArmies - std::round(regions[toRegion].getArmies()*0.7));
regions[toRegion].setOwner(regions[noRegion].getOwner());
} else
{
regions[noRegion].setArmies(regions[noRegion].getArmies() + nbArmies - std::round(regions[toRegion].getArmies()*0.7));
regions[toRegion].setArmies(regions[toRegion].getArmies() - std::round(nbArmies*0.6));
}
}
}
void Bot::resetRegionsOwned()
{
ownedRegions.clear();
}
<|endoftext|> |
<commit_before>#include "File.h"
std::map<__ino_t, File *> File::uk_inode;
std::multimap<fsize_t, File *> File::cx_size;
File::File(const std::string &path, const std::string &filename) {
name = filename;
relativepath.append(path) += std::string("/") += filename;
// std::cout << relativepath << std::endl;
struct stat sb;
if (stat(relativepath.c_str(), &sb) == -1) {
perror("stat");
exit(EXIT_FAILURE);
}
inode = sb.st_ino;
size = sb.st_size;
// insert into the inode table
auto r = uk_inode.insert(std::pair<__ino_t, File*>(inode, this));
if (!r.second) { //true = sucess, false = duplicate inode, must already be a hardlink
//std::cout << filename << " dup" << std::endl;
hardlink = true;
r.first->second->hardlink = true;
}
// insert into the size table
cx_size.insert(std::pair<fsize_t, File *>(size, this));
if ((cx_size.count(size) > 1) && (!hardlink)) {
auto rp = cx_size.equal_range(size); //range of file with same size
for(auto it = rp.first; it != rp.second; it++) {
if (this == it->second)
continue; //well, we don't want to link to ourselves
if (equal(*it->second))// find the other identically sized file(s)
link(it->second); //make a hardlink
}
}
}
void File::link(File* file) { //just print it out for now
std::cout << "link0: " << name << " " << inode << " ";
std::cout << "link1: " << file->name << " " << file->inode << " ";
std::cout << std::endl << std::endl;
}
bool File::equal(File &rhs) {
if ((size == 0) || (rhs.size == 0))
return false; //ignore empty files
if (size == rhs.size) {
if (sha == NULL)
calc_sha();
if (rhs.sha == NULL)
rhs.calc_sha();
return memcmp(sha, rhs.sha, EVP_MAX_MD_SIZE) == 0;
}
return false;
}
void File::calc_sha() {
EVP_MD_CTX *mdctx;
const EVP_MD *md;
char *file_buffer;
unsigned int md_len;
unsigned char *md_value = new unsigned char [EVP_MAX_MD_SIZE];
if (size == 0) { //this can happen
delete[] md_value;
return;
}
OpenSSL_add_all_digests();
md = EVP_get_digestbyname("sha512");
if(!md) {
printf("Unknown message digest \n");
exit(EXIT_FAILURE);
}
int file_descript = open(relativepath.c_str(), O_RDONLY);
if(file_descript < 0) exit(-1);
file_buffer = (char *)mmap(NULL, size, PROT_READ, MAP_SHARED, file_descript, 0);
if (file_buffer == MAP_FAILED) {
perror("mmap");
exit(EXIT_FAILURE);
}
mdctx = EVP_MD_CTX_create(); //XXX make sure this stuff is Kosher
EVP_DigestInit_ex(mdctx, md, NULL);
EVP_DigestUpdate(mdctx, file_buffer, strlen(file_buffer));
EVP_DigestFinal_ex(mdctx, md_value, &md_len);
EVP_MD_CTX_destroy(mdctx);
/* Call this once before exit. */
EVP_cleanup();
sha = md_value;
return;
};
bool File::isHardlink(File *file) {
return file->inode == this->inode;
}
<commit_msg>thats not so much a leak as a dam breach<commit_after>#include "File.h"
std::map<__ino_t, File *> File::uk_inode;
std::multimap<fsize_t, File *> File::cx_size;
File::File(const std::string &path, const std::string &filename) {
name = filename;
relativepath.append(path) += std::string("/") += filename;
// std::cout << relativepath << std::endl;
struct stat sb;
if (stat(relativepath.c_str(), &sb) == -1) {
perror("stat");
exit(EXIT_FAILURE);
}
inode = sb.st_ino;
size = sb.st_size;
// insert into the inode table
auto r = uk_inode.insert(std::pair<__ino_t, File*>(inode, this));
if (!r.second) { //true = sucess, false = duplicate inode, must already be a hardlink
//std::cout << filename << " dup" << std::endl;
hardlink = true;
r.first->second->hardlink = true;
}
// insert into the size table
cx_size.insert(std::pair<fsize_t, File *>(size, this));
if ((cx_size.count(size) > 1) && (!hardlink)) {
auto rp = cx_size.equal_range(size); //range of file with same size
for(auto it = rp.first; it != rp.second; it++) {
if (this == it->second)
continue; //well, we don't want to link to ourselves
if (equal(*it->second))// find the other identically sized file(s)
link(it->second); //make a hardlink
}
}
}
void File::link(File* file) { //just print it out for now
std::cout << "link0: " << name << " " << inode << " ";
std::cout << "link1: " << file->name << " " << file->inode << " ";
std::cout << std::endl << std::endl;
}
bool File::equal(File &rhs) {
if ((size == 0) || (rhs.size == 0))
return false; //ignore empty files
if (size == rhs.size) {
if (sha == NULL)
calc_sha();
if (rhs.sha == NULL)
rhs.calc_sha();
return memcmp(sha, rhs.sha, EVP_MAX_MD_SIZE) == 0;
}
return false;
}
void File::calc_sha() {
EVP_MD_CTX *mdctx;
const EVP_MD *md;
char *file_buffer;
unsigned int md_len;
unsigned char *md_value = new unsigned char [EVP_MAX_MD_SIZE];
if (size == 0) { //this can happen
delete[] md_value;
return;
}
OpenSSL_add_all_digests();
md = EVP_get_digestbyname("sha512");
if(!md) {
printf("Unknown message digest \n");
exit(EXIT_FAILURE);
}
int file_descript = open(relativepath.c_str(), O_RDONLY);
if(file_descript < 0) exit(-1);
file_buffer = (char *)mmap(NULL, size, PROT_READ, MAP_SHARED, file_descript, 0);
if (file_buffer == MAP_FAILED) {
perror("mmap");
exit(EXIT_FAILURE);
}
mdctx = EVP_MD_CTX_create(); //XXX make sure this stuff is Kosher
EVP_DigestInit_ex(mdctx, md, NULL);
EVP_DigestUpdate(mdctx, file_buffer, strlen(file_buffer));
EVP_DigestFinal_ex(mdctx, md_value, &md_len);
EVP_MD_CTX_destroy(mdctx);
/* Call this once before exit. */
EVP_cleanup();
munmap(file_buffer, strlen(file_buffer));
sha = md_value;
return;
};
bool File::isHardlink(File *file) {
return file->inode == this->inode;
}
<|endoftext|> |
<commit_before>/** @file
A brief file description
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
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.
*/
/****************************************************************************
*
* WebCompatibility.cc - cross platform issues dealt with here
*
*
****************************************************************************/
#include "WebCompatibility.h"
#include "MgmtSocket.h"
//-------------------------------------------------------------------------
// WebGetHostname_Xmalloc
//-------------------------------------------------------------------------
char *
WebGetHostname_Xmalloc(sockaddr_in * client_info)
{
char *hostname;
char *hostname_tmp;
#if (HOST_OS == linux)
// Why aren't we using the reentrant calls to gethostbyaddr? /leif
/*
struct hostent hostInfo;
char hostInfoBuf[256];
int _r_errno;
struct hostent *r = NULL;
struct hostent * addrp = NULL;
int res = gethostbyaddr_r((char*)&client_info->sin_addr.s_addr,
sizeof(client_info->sin_addr.s_addr), AF_INET,
&hostInfo, hostInfoBuf, 265, &addrp, &_r_errno);
if (!res && addrp) r = addrp;
*/
struct hostent *r = gethostbyaddr((char *) &client_info->sin_addr.s_addr,
sizeof(client_info->sin_addr.s_addr),
AF_INET);
#else
struct hostent *r = gethostbyaddr_r((char *) &client_info->sin_addr.s_addr,
sizeof(client_info->sin_addr.s_addr), AF_INET,
&hostInfo, hostInfoBuf, 265, &_r_errno);
#endif
hostname_tmp = r ? r->h_name : inet_ntoa(client_info->sin_addr);
size_t len = strlen(hostname_tmp) + 1;
hostname = (char *) xmalloc(len);
ink_strncpy(hostname, hostname_tmp, len);
return hostname;
}
//-------------------------------------------------------------------------
// WebFileOpenR
//-------------------------------------------------------------------------
WebHandle
WebFileOpenR(const char *file)
{
WebHandle h_file;
if ((h_file = mgmt_open(file, O_RDONLY)) <= 0) {
return WEB_HANDLE_INVALID;
}
return h_file;
}
//-------------------------------------------------------------------------
// WebFileOpenW
//-------------------------------------------------------------------------
WebHandle
WebFileOpenW(const char *file)
{
WebHandle h_file;
if ((h_file = mgmt_open_mode(file, O_WRONLY | O_APPEND | O_CREAT, 0600)) < 0) {
return WEB_HANDLE_INVALID;
}
fcntl(h_file, F_SETFD, 1);
return h_file;
}
//-------------------------------------------------------------------------
// WebFileClose
//-------------------------------------------------------------------------
void
WebFileClose(WebHandle h_file)
{
close(h_file);
}
//-------------------------------------------------------------------------
// WebFileRead
//-------------------------------------------------------------------------
int
WebFileRead(WebHandle h_file, char *buf, int size, int *bytes_read)
{
if ((*bytes_read =::read(h_file, buf, size)) < 0) {
*bytes_read = 0;
return WEB_HTTP_ERR_FAIL;
}
return WEB_HTTP_ERR_OKAY;
}
//-------------------------------------------------------------------------
// WebFileWrite
//-------------------------------------------------------------------------
int
WebFileWrite(WebHandle h_file, char *buf, int size, int *bytes_written)
{
if ((*bytes_written =::write(h_file, buf, size)) < 0) {
*bytes_written = 0;
return WEB_HTTP_ERR_FAIL;
}
return WEB_HTTP_ERR_OKAY;
}
//-------------------------------------------------------------------------
// WebFileImport_Xmalloc
//-------------------------------------------------------------------------
int
WebFileImport_Xmalloc(const char *file, char **file_buf, int *file_size)
{
int err = WEB_HTTP_ERR_OKAY;
WebHandle h_file = WEB_HANDLE_INVALID;
int bytes_read;
*file_buf = 0;
*file_size = 0;
if ((h_file = WebFileOpenR(file)) == WEB_HANDLE_INVALID)
goto Lerror;
*file_size = WebFileGetSize(h_file);
*file_buf = (char *) xmalloc(*file_size + 1);
if (WebFileRead(h_file, *file_buf, *file_size, &bytes_read) == WEB_HTTP_ERR_FAIL)
goto Lerror;
if (bytes_read != *file_size)
goto Lerror;
(*file_buf)[*file_size] = '\0';
goto Ldone;
Lerror:
if (*file_buf)
xfree(*file_buf);
*file_buf = 0;
*file_size = 0;
err = WEB_HTTP_ERR_FAIL;
Ldone:
if (h_file != WEB_HANDLE_INVALID)
WebFileClose(h_file);
return err;
}
//-------------------------------------------------------------------------
// WebFileGetSize
//-------------------------------------------------------------------------
int
WebFileGetSize(WebHandle h_file)
{
int size;
struct stat fileStats;
fstat(h_file, &fileStats);
size = fileStats.st_size;
return size;
}
//-------------------------------------------------------------------------
// WebFileGetDateGmt
//-------------------------------------------------------------------------
time_t
WebFileGetDateGmt(WebHandle h_file)
{
time_t date;
struct stat fileStats;
fstat(h_file, &fileStats);
date = fileStats.st_mtime + ink_timezone();
return date;
}
//-------------------------------------------------------------------------
// WebSeedRand
//-------------------------------------------------------------------------
void
WebSeedRand(long seed)
{
srand48(seed);
return;
}
//-------------------------------------------------------------------------
// WebRand
//-------------------------------------------------------------------------
long
WebRand()
{
// we may want to fix this later
// coverity[secure_coding]
return lrand48();
}
<commit_msg>TS-2: Use existing portable gethostbyaddr_r.<commit_after>/** @file
A brief file description
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
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.
*/
/****************************************************************************
*
* WebCompatibility.cc - cross platform issues dealt with here
*
*
****************************************************************************/
#include "WebCompatibility.h"
#include "MgmtSocket.h"
//-------------------------------------------------------------------------
// WebGetHostname_Xmalloc
//-------------------------------------------------------------------------
char *
WebGetHostname_Xmalloc(sockaddr_in * client_info)
{
ink_gethostbyaddr_r_data data;
char *hostname;
char *hostname_tmp;
struct hostent *r = ink_gethostbyaddr_r((char *) &client_info->sin_addr.s_addr,
sizeof(client_info->sin_addr.s_addr),
AF_INET,
&data);
hostname_tmp = r ? r->h_name : inet_ntoa(client_info->sin_addr);
size_t len = strlen(hostname_tmp) + 1;
hostname = (char *) xmalloc(len);
ink_strncpy(hostname, hostname_tmp, len);
return hostname;
}
//-------------------------------------------------------------------------
// WebFileOpenR
//-------------------------------------------------------------------------
WebHandle
WebFileOpenR(const char *file)
{
WebHandle h_file;
if ((h_file = mgmt_open(file, O_RDONLY)) <= 0) {
return WEB_HANDLE_INVALID;
}
return h_file;
}
//-------------------------------------------------------------------------
// WebFileOpenW
//-------------------------------------------------------------------------
WebHandle
WebFileOpenW(const char *file)
{
WebHandle h_file;
if ((h_file = mgmt_open_mode(file, O_WRONLY | O_APPEND | O_CREAT, 0600)) < 0) {
return WEB_HANDLE_INVALID;
}
fcntl(h_file, F_SETFD, 1);
return h_file;
}
//-------------------------------------------------------------------------
// WebFileClose
//-------------------------------------------------------------------------
void
WebFileClose(WebHandle h_file)
{
close(h_file);
}
//-------------------------------------------------------------------------
// WebFileRead
//-------------------------------------------------------------------------
int
WebFileRead(WebHandle h_file, char *buf, int size, int *bytes_read)
{
if ((*bytes_read =::read(h_file, buf, size)) < 0) {
*bytes_read = 0;
return WEB_HTTP_ERR_FAIL;
}
return WEB_HTTP_ERR_OKAY;
}
//-------------------------------------------------------------------------
// WebFileWrite
//-------------------------------------------------------------------------
int
WebFileWrite(WebHandle h_file, char *buf, int size, int *bytes_written)
{
if ((*bytes_written =::write(h_file, buf, size)) < 0) {
*bytes_written = 0;
return WEB_HTTP_ERR_FAIL;
}
return WEB_HTTP_ERR_OKAY;
}
//-------------------------------------------------------------------------
// WebFileImport_Xmalloc
//-------------------------------------------------------------------------
int
WebFileImport_Xmalloc(const char *file, char **file_buf, int *file_size)
{
int err = WEB_HTTP_ERR_OKAY;
WebHandle h_file = WEB_HANDLE_INVALID;
int bytes_read;
*file_buf = 0;
*file_size = 0;
if ((h_file = WebFileOpenR(file)) == WEB_HANDLE_INVALID)
goto Lerror;
*file_size = WebFileGetSize(h_file);
*file_buf = (char *) xmalloc(*file_size + 1);
if (WebFileRead(h_file, *file_buf, *file_size, &bytes_read) == WEB_HTTP_ERR_FAIL)
goto Lerror;
if (bytes_read != *file_size)
goto Lerror;
(*file_buf)[*file_size] = '\0';
goto Ldone;
Lerror:
if (*file_buf)
xfree(*file_buf);
*file_buf = 0;
*file_size = 0;
err = WEB_HTTP_ERR_FAIL;
Ldone:
if (h_file != WEB_HANDLE_INVALID)
WebFileClose(h_file);
return err;
}
//-------------------------------------------------------------------------
// WebFileGetSize
//-------------------------------------------------------------------------
int
WebFileGetSize(WebHandle h_file)
{
int size;
struct stat fileStats;
fstat(h_file, &fileStats);
size = fileStats.st_size;
return size;
}
//-------------------------------------------------------------------------
// WebFileGetDateGmt
//-------------------------------------------------------------------------
time_t
WebFileGetDateGmt(WebHandle h_file)
{
time_t date;
struct stat fileStats;
fstat(h_file, &fileStats);
date = fileStats.st_mtime + ink_timezone();
return date;
}
//-------------------------------------------------------------------------
// WebSeedRand
//-------------------------------------------------------------------------
void
WebSeedRand(long seed)
{
srand48(seed);
return;
}
//-------------------------------------------------------------------------
// WebRand
//-------------------------------------------------------------------------
long
WebRand()
{
// we may want to fix this later
// coverity[secure_coding]
return lrand48();
}
<|endoftext|> |
<commit_before>/*
* nvbio
* Copyright (c) 2011-2014, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the NVIDIA CORPORATION nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <nvbio/io/reads/reads_fastq.h>
#include <nvbio/basic/types.h>
#include <nvbio/basic/timer.h>
#include <string.h>
#include <ctype.h>
namespace nvbio {
namespace io {
///@addtogroup IO
///@{
///@addtogroup ReadsIO
///@{
///@addtogroup ReadsIODetail
///@{
int ReadDataFile_FASTQ_parser::nextChunk(ReadDataRAM *output, uint32 max_reads, uint32 max_bps)
{
uint32 n_reads = 0;
uint32 n_bps = 0;
uint8 marker;
const uint32 read_mult =
((m_flags & FORWARD) ? 1u : 0u) +
((m_flags & REVERSE) ? 1u : 0u) +
((m_flags & FORWARD_COMPLEMENT) ? 1u : 0u) +
((m_flags & REVERSE_COMPLEMENT) ? 1u : 0u);
while (n_reads + read_mult <= max_reads &&
n_bps + read_mult*ReadDataFile::LONG_READ <= max_bps)
{
// consume spaces & newlines
do {
marker = get();
// count lines
if (marker == '\n')
m_line++;
}
while (marker == '\n' || marker == ' ');
// check for EOF or read errors
if (m_file_state != FILE_OK)
break;
// if the newlines didn't end in a read marker,
// issue a parsing error...
if (marker != '@')
{
m_file_state = FILE_PARSE_ERROR;
m_error_char = marker;
return uint32(-1);
}
// read all the line
uint32 len = 0;
for (uint8 c = get(); c != '\n' && c != 0; c = get())
{
m_name[ len++ ] = c;
// expand on demand
if (m_name.size() <= len)
m_name.resize( len * 2u );
}
m_name[ len++ ] = '\0';
// check for errors
if (m_file_state != FILE_OK)
{
log_error(stderr, "incomplete read!\n");
m_error_char = 0;
return uint32(-1);
}
m_line++;
// start reading the bp read
len = 0;
for (uint8 c = get(); c != '+' && c != 0; c = get())
{
// if (isgraph(c))
if (c >= 0x21 && c <= 0x7E)
m_read_bp[ len++ ] = c;
else if (c == '\n')
m_line++;
// expand on demand
if (m_read_bp.size() <= len)
{
m_read_bp.resize( len * 2u );
m_read_q.resize( len * 2u );
}
}
// check for errors
if (m_file_state != FILE_OK)
{
log_error(stderr, "incomplete read!\n");
m_error_char = 0;
return uint32(-1);
}
// read all the line
for(uint8 c = get(); c != '\n' && c != 0; c = get()) {}
// check for errors
if (m_file_state != FILE_OK)
{
log_error(stderr, "incomplete read!\n");
m_error_char = 0;
return uint32(-1);
}
m_line++;
// start reading the quality read
len = 0;
for (uint8 c = get(); c != '\n' && c != 0; c = get())
m_read_q[ len++ ] = c;
// check for errors
if (m_file_state != FILE_OK)
{
log_error(stderr, "incomplete read!\n");
m_error_char = 0;
return uint32(-1);
}
m_line++;
if (m_flags & FORWARD)
{
output->push_back( len,
&m_name[0],
&m_read_bp[0],
&m_read_q[0],
m_quality_encoding,
m_truncate_read_len,
ReadDataRAM::NO_OP );
}
if (m_flags & REVERSE)
{
output->push_back( len,
&m_name[0],
&m_read_bp[0],
&m_read_q[0],
m_quality_encoding,
m_truncate_read_len,
ReadDataRAM::REVERSE_OP );
}
if (m_flags & FORWARD_COMPLEMENT)
{
output->push_back( len,
&m_name[0],
&m_read_bp[0],
&m_read_q[0],
m_quality_encoding,
m_truncate_read_len,
ReadDataRAM::COMPLEMENT_OP );
}
if (m_flags & REVERSE_COMPLEMENT)
{
output->push_back( len,
&m_name[0],
&m_read_bp[0],
&m_read_q[0],
m_quality_encoding,
m_truncate_read_len,
ReadDataRAM::REVERSE_COMPLEMENT_OP );
}
n_bps += read_mult * len;
n_reads += read_mult;
}
return n_reads;
}
ReadDataFile_FASTQ_gz::ReadDataFile_FASTQ_gz(const char *read_file_name,
const QualityEncoding qualities,
const uint32 max_reads,
const uint32 max_read_len,
const ReadEncoding flags)
: ReadDataFile_FASTQ_parser(read_file_name, qualities, max_reads, max_read_len, flags)
{
m_file = gzopen(read_file_name, "r");
if (!m_file) {
m_file_state = FILE_OPEN_FAILED;
} else {
m_file_state = FILE_OK;
}
gzbuffer(m_file, m_buffer_size);
}
static float time = 0.0f;
ReadDataFile_FASTQ_parser::FileState ReadDataFile_FASTQ_gz::fillBuffer(void)
{
m_buffer_size = gzread(m_file, &m_buffer[0], (uint32)m_buffer.size());
if (m_buffer_size <= 0)
{
// check for EOF separately; zlib will not always return Z_STREAM_END at EOF below
if (gzeof(m_file))
{
return FILE_EOF;
} else {
// ask zlib what happened and inform the user
int err;
const char *msg;
msg = gzerror(m_file, &err);
// we're making the assumption that we never see Z_STREAM_END here
assert(err != Z_STREAM_END);
log_error(stderr, "error processing FASTQ file: zlib error %d (%s)\n", err, msg);
return FILE_STREAM_ERROR;
}
}
return FILE_OK;
}
///@} // ReadsIODetail
///@} // ReadsIO
///@} // IO
} // namespace io
} // namespace nvbio
<commit_msg>Eliminate unused variable<commit_after>/*
* nvbio
* Copyright (c) 2011-2014, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the NVIDIA CORPORATION nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <nvbio/io/reads/reads_fastq.h>
#include <nvbio/basic/types.h>
#include <nvbio/basic/timer.h>
#include <string.h>
#include <ctype.h>
namespace nvbio {
namespace io {
///@addtogroup IO
///@{
///@addtogroup ReadsIO
///@{
///@addtogroup ReadsIODetail
///@{
int ReadDataFile_FASTQ_parser::nextChunk(ReadDataRAM *output, uint32 max_reads, uint32 max_bps)
{
uint32 n_reads = 0;
uint32 n_bps = 0;
uint8 marker;
const uint32 read_mult =
((m_flags & FORWARD) ? 1u : 0u) +
((m_flags & REVERSE) ? 1u : 0u) +
((m_flags & FORWARD_COMPLEMENT) ? 1u : 0u) +
((m_flags & REVERSE_COMPLEMENT) ? 1u : 0u);
while (n_reads + read_mult <= max_reads &&
n_bps + read_mult*ReadDataFile::LONG_READ <= max_bps)
{
// consume spaces & newlines
do {
marker = get();
// count lines
if (marker == '\n')
m_line++;
}
while (marker == '\n' || marker == ' ');
// check for EOF or read errors
if (m_file_state != FILE_OK)
break;
// if the newlines didn't end in a read marker,
// issue a parsing error...
if (marker != '@')
{
m_file_state = FILE_PARSE_ERROR;
m_error_char = marker;
return uint32(-1);
}
// read all the line
uint32 len = 0;
for (uint8 c = get(); c != '\n' && c != 0; c = get())
{
m_name[ len++ ] = c;
// expand on demand
if (m_name.size() <= len)
m_name.resize( len * 2u );
}
m_name[ len++ ] = '\0';
// check for errors
if (m_file_state != FILE_OK)
{
log_error(stderr, "incomplete read!\n");
m_error_char = 0;
return uint32(-1);
}
m_line++;
// start reading the bp read
len = 0;
for (uint8 c = get(); c != '+' && c != 0; c = get())
{
// if (isgraph(c))
if (c >= 0x21 && c <= 0x7E)
m_read_bp[ len++ ] = c;
else if (c == '\n')
m_line++;
// expand on demand
if (m_read_bp.size() <= len)
{
m_read_bp.resize( len * 2u );
m_read_q.resize( len * 2u );
}
}
// check for errors
if (m_file_state != FILE_OK)
{
log_error(stderr, "incomplete read!\n");
m_error_char = 0;
return uint32(-1);
}
// read all the line
for(uint8 c = get(); c != '\n' && c != 0; c = get()) {}
// check for errors
if (m_file_state != FILE_OK)
{
log_error(stderr, "incomplete read!\n");
m_error_char = 0;
return uint32(-1);
}
m_line++;
// start reading the quality read
len = 0;
for (uint8 c = get(); c != '\n' && c != 0; c = get())
m_read_q[ len++ ] = c;
// check for errors
if (m_file_state != FILE_OK)
{
log_error(stderr, "incomplete read!\n");
m_error_char = 0;
return uint32(-1);
}
m_line++;
if (m_flags & FORWARD)
{
output->push_back( len,
&m_name[0],
&m_read_bp[0],
&m_read_q[0],
m_quality_encoding,
m_truncate_read_len,
ReadDataRAM::NO_OP );
}
if (m_flags & REVERSE)
{
output->push_back( len,
&m_name[0],
&m_read_bp[0],
&m_read_q[0],
m_quality_encoding,
m_truncate_read_len,
ReadDataRAM::REVERSE_OP );
}
if (m_flags & FORWARD_COMPLEMENT)
{
output->push_back( len,
&m_name[0],
&m_read_bp[0],
&m_read_q[0],
m_quality_encoding,
m_truncate_read_len,
ReadDataRAM::COMPLEMENT_OP );
}
if (m_flags & REVERSE_COMPLEMENT)
{
output->push_back( len,
&m_name[0],
&m_read_bp[0],
&m_read_q[0],
m_quality_encoding,
m_truncate_read_len,
ReadDataRAM::REVERSE_COMPLEMENT_OP );
}
n_bps += read_mult * len;
n_reads += read_mult;
}
return n_reads;
}
ReadDataFile_FASTQ_gz::ReadDataFile_FASTQ_gz(const char *read_file_name,
const QualityEncoding qualities,
const uint32 max_reads,
const uint32 max_read_len,
const ReadEncoding flags)
: ReadDataFile_FASTQ_parser(read_file_name, qualities, max_reads, max_read_len, flags)
{
m_file = gzopen(read_file_name, "r");
if (!m_file) {
m_file_state = FILE_OPEN_FAILED;
} else {
m_file_state = FILE_OK;
}
gzbuffer(m_file, m_buffer_size);
}
ReadDataFile_FASTQ_parser::FileState ReadDataFile_FASTQ_gz::fillBuffer(void)
{
m_buffer_size = gzread(m_file, &m_buffer[0], (uint32)m_buffer.size());
if (m_buffer_size <= 0)
{
// check for EOF separately; zlib will not always return Z_STREAM_END at EOF below
if (gzeof(m_file))
{
return FILE_EOF;
} else {
// ask zlib what happened and inform the user
int err;
const char *msg;
msg = gzerror(m_file, &err);
// we're making the assumption that we never see Z_STREAM_END here
assert(err != Z_STREAM_END);
log_error(stderr, "error processing FASTQ file: zlib error %d (%s)\n", err, msg);
return FILE_STREAM_ERROR;
}
}
return FILE_OK;
}
///@} // ReadsIODetail
///@} // ReadsIO
///@} // IO
} // namespace io
} // namespace nvbio
<|endoftext|> |
<commit_before>#include "linearoctree.h"
#include "octantid.h"
#include "parallel_stable_sort.h"
#include <algorithm>
#include <ostream>
#include <assert.h>
std::ostream& operator<<(std::ostream& s, const LinearOctree& octree) {
s << "Octree with layers. Size: " << octree.leafs().size() << std::endl;
for (uint l = 0; l < octree.depth(); l++) {
s << "Level " << l << " leafs: " << std::endl;
for (const OctantID& octant : octree.leafs()) {
if (octant.level() == l) {
s << " " << octant << std::endl;
}
}
}
return s;
}
LinearOctree::LinearOctree() {
}
LinearOctree::LinearOctree(const OctantID& root, const container_type& leafs) : m_root(root), m_leafs(leafs) {
m_deepestLastDecendant = OctantID(getMaxXYZForOctreeDepth(root.level()) + root.coord(), 0);
}
LinearOctree::LinearOctree(const OctantID& root, const size_t& numLeafs) : m_root(root) {
m_deepestLastDecendant = OctantID(getMaxXYZForOctreeDepth(root.level()) + root.coord(), 0);
m_leafs.reserve(numLeafs);
}
const OctantID& LinearOctree::root() const {
return m_root;
}
uint LinearOctree::depth() const {
return m_root.level();
}
const LinearOctree::container_type& LinearOctree::leafs() const {
return m_leafs;
}
void LinearOctree::insert(const OctantID& octant) {
assert(octant < m_root || octant > m_deepestLastDecendant);
m_leafs.push_back(octant);
}
void LinearOctree::insert(container_type::const_iterator begin, container_type::const_iterator end) {
assert(std::all_of(begin, end, [this](const OctantID& octant) { return octant < m_root || octant > m_deepestLastDecendant; }));
m_leafs.insert(m_leafs.end(), begin, end);
}
bool LinearOctree::hasLeaf(const OctantID& octant) const {
if (!insideTreeBounds(octant)) {
return false;
}
return std::find(m_leafs.begin(), m_leafs.end(), octant) != m_leafs.end();
}
std::vector<OctantID> LinearOctree::replaceWithChildren(const OctantID& octant) {
auto children = octant.children();
replaceWithSubtree(octant, children);
return children;
}
void LinearOctree::replaceWithSubtree(const OctantID& octant, const std::vector<OctantID>& subtree) {
if (!insideTreeBounds(octant)) {
throw std::runtime_error("LinearOctree::replaceWithSubtree: Invalid parameter octant out of bounds.");
}
if (m_toRemove.insert(std::make_pair(octant.mcode(), octant.level())).second) {
m_leafs.insert(m_leafs.end(), subtree.begin(), subtree.end());
}
}
bool LinearOctree::maximumLowerBound(const OctantID& octant, OctantID& lowerBound) const {
auto it = std::lower_bound(m_leafs.begin(), m_leafs.end(), octant);
if (it != m_leafs.begin()) {
--it;
} else {
return false;
}
lowerBound = *it;
return true;
}
bool LinearOctree::insideTreeBounds(const OctantID& octant) const {
return octant >= m_root && octant <= m_deepestLastDecendant;
}
OctantID LinearOctree::deepestLastDecendant() const {
return m_deepestLastDecendant;
}
OctantID LinearOctree::deepestFirstDecendant() const {
OctantID dfd(root().mcode(), 0);
return dfd;
}
void LinearOctree::sortAndRemove() {
if (!m_toRemove.empty()) {
m_leafs.erase(std::remove_if(m_leafs.begin(), m_leafs.end(), [this](const OctantID& octant) {
auto it = m_toRemove.find(octant.mcode());
if (it != m_toRemove.end() && it->second == octant.level()) {
return true;
}
return false;
}), m_leafs.end());
m_toRemove.clear();
}
pss::parallel_stable_sort(m_leafs.begin(), m_leafs.end());
}
void LinearOctree::reserve(const size_t numLeafs) {
m_leafs.reserve(numLeafs);
}
<commit_msg>Fixed bug: Wrong assertion in linear octree<commit_after>#include "linearoctree.h"
#include "octantid.h"
#include "parallel_stable_sort.h"
#include <algorithm>
#include <ostream>
#include <assert.h>
std::ostream& operator<<(std::ostream& s, const LinearOctree& octree) {
s << "Octree with layers. Size: " << octree.leafs().size() << std::endl;
for (uint l = 0; l < octree.depth(); l++) {
s << "Level " << l << " leafs: " << std::endl;
for (const OctantID& octant : octree.leafs()) {
if (octant.level() == l) {
s << " " << octant << std::endl;
}
}
}
return s;
}
LinearOctree::LinearOctree() {
}
LinearOctree::LinearOctree(const OctantID& root, const container_type& leafs) : m_root(root), m_leafs(leafs) {
m_deepestLastDecendant = OctantID(getMaxXYZForOctreeDepth(root.level()) + root.coord(), 0);
}
LinearOctree::LinearOctree(const OctantID& root, const size_t& numLeafs) : m_root(root) {
m_deepestLastDecendant = OctantID(getMaxXYZForOctreeDepth(root.level()) + root.coord(), 0);
m_leafs.reserve(numLeafs);
}
const OctantID& LinearOctree::root() const {
return m_root;
}
uint LinearOctree::depth() const {
return m_root.level();
}
const LinearOctree::container_type& LinearOctree::leafs() const {
return m_leafs;
}
void LinearOctree::insert(const OctantID& octant) {
assert(octant >= m_root || octant <= m_deepestLastDecendant);
m_leafs.push_back(octant);
}
void LinearOctree::insert(container_type::const_iterator begin, container_type::const_iterator end) {
assert(std::all_of(begin, end, [this](const OctantID& octant) { return octant >= m_root || octant <= m_deepestLastDecendant; }));
m_leafs.insert(m_leafs.end(), begin, end);
}
bool LinearOctree::hasLeaf(const OctantID& octant) const {
if (!insideTreeBounds(octant)) {
return false;
}
return std::find(m_leafs.begin(), m_leafs.end(), octant) != m_leafs.end();
}
std::vector<OctantID> LinearOctree::replaceWithChildren(const OctantID& octant) {
auto children = octant.children();
replaceWithSubtree(octant, children);
return children;
}
void LinearOctree::replaceWithSubtree(const OctantID& octant, const std::vector<OctantID>& subtree) {
if (!insideTreeBounds(octant)) {
throw std::runtime_error("LinearOctree::replaceWithSubtree: Invalid parameter octant out of bounds.");
}
if (m_toRemove.insert(std::make_pair(octant.mcode(), octant.level())).second) {
m_leafs.insert(m_leafs.end(), subtree.begin(), subtree.end());
}
}
bool LinearOctree::maximumLowerBound(const OctantID& octant, OctantID& lowerBound) const {
auto it = std::lower_bound(m_leafs.begin(), m_leafs.end(), octant);
if (it != m_leafs.begin()) {
--it;
} else {
return false;
}
lowerBound = *it;
return true;
}
bool LinearOctree::insideTreeBounds(const OctantID& octant) const {
return octant >= m_root && octant <= m_deepestLastDecendant;
}
OctantID LinearOctree::deepestLastDecendant() const {
return m_deepestLastDecendant;
}
OctantID LinearOctree::deepestFirstDecendant() const {
OctantID dfd(root().mcode(), 0);
return dfd;
}
void LinearOctree::sortAndRemove() {
if (!m_toRemove.empty()) {
m_leafs.erase(std::remove_if(m_leafs.begin(), m_leafs.end(), [this](const OctantID& octant) {
auto it = m_toRemove.find(octant.mcode());
if (it != m_toRemove.end() && it->second == octant.level()) {
return true;
}
return false;
}), m_leafs.end());
m_toRemove.clear();
}
pss::parallel_stable_sort(m_leafs.begin(), m_leafs.end());
}
void LinearOctree::reserve(const size_t numLeafs) {
m_leafs.reserve(numLeafs);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/gtk/gtk_floating_container.h"
#include <gtk/gtk.h>
#include <gtk/gtkprivate.h>
#include <gtk/gtkmarshal.h>
#include <algorithm>
namespace {
enum {
SET_FLOATING_POSITION,
LAST_SIGNAL
};
enum {
CHILD_PROP_0,
CHILD_PROP_X,
CHILD_PROP_Y
};
// Returns the GtkFloatingContainerChild associated with |widget| (or NULL if
// |widget| not found).
GtkFloatingContainerChild* GetChild(GtkFloatingContainer* container,
GtkWidget* widget) {
for (GList* floating_children = container->floating_children;
floating_children; floating_children = g_list_next(floating_children)) {
GtkFloatingContainerChild* child =
reinterpret_cast<GtkFloatingContainerChild*>(floating_children->data);
if (child->widget == widget)
return child;
}
return NULL;
}
} // namespace
G_BEGIN_DECLS
static void gtk_floating_container_remove(GtkContainer* container,
GtkWidget* widget);
static void gtk_floating_container_forall(GtkContainer* container,
gboolean include_internals,
GtkCallback callback,
gpointer callback_data);
static void gtk_floating_container_size_request(GtkWidget* widget,
GtkRequisition* requisition);
static void gtk_floating_container_size_allocate(GtkWidget* widget,
GtkAllocation* allocation);
static void gtk_floating_container_set_child_property(GtkContainer* container,
GtkWidget* child,
guint property_id,
const GValue* value,
GParamSpec* pspec);
static void gtk_floating_container_get_child_property(GtkContainer* container,
GtkWidget* child,
guint property_id,
GValue* value,
GParamSpec* pspec);
static guint floating_container_signals[LAST_SIGNAL] = { 0 };
G_DEFINE_TYPE(GtkFloatingContainer, gtk_floating_container, GTK_TYPE_BIN)
static void gtk_floating_container_class_init(
GtkFloatingContainerClass *klass) {
GtkObjectClass* object_class =
reinterpret_cast<GtkObjectClass*>(klass);
GtkWidgetClass* widget_class =
reinterpret_cast<GtkWidgetClass*>(klass);
widget_class->size_request = gtk_floating_container_size_request;
widget_class->size_allocate = gtk_floating_container_size_allocate;
GtkContainerClass* container_class =
reinterpret_cast<GtkContainerClass*>(klass);
container_class->remove = gtk_floating_container_remove;
container_class->forall = gtk_floating_container_forall;
container_class->set_child_property =
gtk_floating_container_set_child_property;
container_class->get_child_property =
gtk_floating_container_get_child_property;
gtk_container_class_install_child_property(
container_class,
CHILD_PROP_X,
g_param_spec_int("x",
"X position",
"X position of child widget",
G_MININT,
G_MAXINT,
0,
static_cast<GParamFlags>(GTK_PARAM_READWRITE)));
gtk_container_class_install_child_property(
container_class,
CHILD_PROP_Y,
g_param_spec_int("y",
"Y position",
"Y position of child widget",
G_MININT,
G_MAXINT,
0,
static_cast<GParamFlags>(GTK_PARAM_READWRITE)));
floating_container_signals[SET_FLOATING_POSITION] =
g_signal_new("set-floating-position",
G_OBJECT_CLASS_TYPE(object_class),
static_cast<GSignalFlags>(G_SIGNAL_RUN_FIRST |
G_SIGNAL_ACTION),
NULL,
NULL, NULL,
gtk_marshal_VOID__BOXED,
G_TYPE_NONE, 1,
GDK_TYPE_RECTANGLE | G_SIGNAL_TYPE_STATIC_SCOPE);
}
static void gtk_floating_container_init(GtkFloatingContainer* container) {
GTK_WIDGET_SET_FLAGS(container, GTK_NO_WINDOW);
container->floating_children = NULL;
}
static void gtk_floating_container_remove(GtkContainer* container,
GtkWidget* widget) {
g_return_if_fail(GTK_IS_WIDGET(widget));
GtkBin* bin = GTK_BIN(container);
if (bin->child == widget) {
((GTK_CONTAINER_CLASS(gtk_floating_container_parent_class))->remove)
(container, widget);
} else {
// Handle the other case where it's in our |floating_children| list.
GtkFloatingContainer* floating = GTK_FLOATING_CONTAINER(container);
GList* children = floating->floating_children;
gboolean removed_child = false;
while (children) {
GtkFloatingContainerChild* child =
reinterpret_cast<GtkFloatingContainerChild*>(children->data);
if (child->widget == widget) {
removed_child = true;
gboolean was_visible = GTK_WIDGET_VISIBLE(widget);
gtk_widget_unparent(widget);
floating->floating_children =
g_list_remove_link(floating->floating_children, children);
g_list_free(children);
g_free(child);
if (was_visible && GTK_WIDGET_VISIBLE(container))
gtk_widget_queue_resize(GTK_WIDGET(container));
break;
}
children = children->next;
}
g_return_if_fail(removed_child);
}
}
static void gtk_floating_container_forall(GtkContainer* container,
gboolean include_internals,
GtkCallback callback,
gpointer callback_data) {
GtkBin *bin = GTK_BIN(container);
g_return_if_fail(callback != NULL);
if (bin->child)
(*callback)(bin->child, callback_data);
GtkFloatingContainer* floating = GTK_FLOATING_CONTAINER(container);
GList* children = floating->floating_children;
while (children) {
GtkFloatingContainerChild* child =
reinterpret_cast<GtkFloatingContainerChild*>(children->data);
children = children->next;
(*callback)(child->widget, callback_data);
}
}
static void gtk_floating_container_size_request(GtkWidget* widget,
GtkRequisition* requisition) {
GtkBin *bin = GTK_BIN(widget);
if (bin && bin->child) {
gtk_widget_size_request(bin->child, requisition);
} else {
requisition->width = 0;
requisition->height = 0;
}
}
static void gtk_floating_container_size_allocate(GtkWidget* widget,
GtkAllocation* allocation) {
widget->allocation = *allocation;
if (!GTK_WIDGET_NO_WINDOW(widget) && GTK_WIDGET_REALIZED(widget)) {
gdk_window_move_resize(widget->window,
allocation->x,
allocation->y,
allocation->width,
allocation->height);
}
// Give the same allocation to our GtkBin component.
GtkBin* bin = GTK_BIN(widget);
if (bin->child) {
gtk_widget_size_allocate(bin->child, allocation);
}
// We need to give whoever is pulling our strings a chance to set the "x" and
// "y" properties on all of our children.
g_signal_emit(widget, floating_container_signals[SET_FLOATING_POSITION], 0,
allocation);
// Our allocation has been set. We've asked our controller to place the other
// widgets. Pass out allocations to all our children based on where they want
// to be.
GtkFloatingContainer* container = GTK_FLOATING_CONTAINER(widget);
GList* children = container->floating_children;
GtkAllocation child_allocation;
GtkRequisition child_requisition;
while (children) {
GtkFloatingContainerChild* child =
reinterpret_cast<GtkFloatingContainerChild*>(children->data);
children = children->next;
if (GTK_WIDGET_VISIBLE(child->widget)) {
gtk_widget_size_request(child->widget, &child_requisition);
child_allocation.x = child->x;
child_allocation.y = child->y;
child_allocation.width = std::max(1, std::min(child_requisition.width,
allocation->width));
child_allocation.height = std::max(1, std::min(child_requisition.height,
allocation->height));
gtk_widget_size_allocate(child->widget, &child_allocation);
}
}
}
static void gtk_floating_container_set_child_property(GtkContainer* container,
GtkWidget* child,
guint property_id,
const GValue* value,
GParamSpec* pspec) {
GtkFloatingContainerChild* floating_child =
GetChild(GTK_FLOATING_CONTAINER(container), child);
g_return_if_fail(floating_child);
switch (property_id) {
case CHILD_PROP_X:
floating_child->x = g_value_get_int(value);
gtk_widget_child_notify(child, "x");
break;
case CHILD_PROP_Y:
floating_child->y = g_value_get_int(value);
gtk_widget_child_notify(child, "y");
break;
default:
GTK_CONTAINER_WARN_INVALID_CHILD_PROPERTY_ID(
container, property_id, pspec);
break;
};
}
static void gtk_floating_container_get_child_property(GtkContainer* container,
GtkWidget* child,
guint property_id,
GValue* value,
GParamSpec* pspec) {
GtkFloatingContainerChild* floating_child =
GetChild(GTK_FLOATING_CONTAINER(container), child);
g_return_if_fail(floating_child);
switch (property_id) {
case CHILD_PROP_X:
g_value_set_int(value, floating_child->x);
break;
case CHILD_PROP_Y:
g_value_set_int(value, floating_child->y);
break;
default:
GTK_CONTAINER_WARN_INVALID_CHILD_PROPERTY_ID(
container, property_id, pspec);
break;
};
}
GtkWidget* gtk_floating_container_new() {
return GTK_WIDGET(g_object_new(GTK_TYPE_FLOATING_CONTAINER, NULL));
}
void gtk_floating_container_add_floating(GtkFloatingContainer* container,
GtkWidget* widget) {
g_return_if_fail(GTK_IS_FLOATING_CONTAINER(container));
g_return_if_fail(GTK_IS_WIDGET(widget));
GtkFloatingContainerChild* child_info = g_new(GtkFloatingContainerChild, 1);
child_info->widget = widget;
child_info->x = 0;
child_info->y = 0;
gtk_widget_set_parent(widget, GTK_WIDGET(container));
container->floating_children =
g_list_append(container->floating_children, child_info);
}
G_END_DECLS
<commit_msg>Attempt to fix weird crasher in gtk_floating_container_forall by checking more input and calling parent class forall.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/gtk/gtk_floating_container.h"
#include <gtk/gtk.h>
#include <gtk/gtkprivate.h>
#include <gtk/gtkmarshal.h>
#include <algorithm>
namespace {
enum {
SET_FLOATING_POSITION,
LAST_SIGNAL
};
enum {
CHILD_PROP_0,
CHILD_PROP_X,
CHILD_PROP_Y
};
// Returns the GtkFloatingContainerChild associated with |widget| (or NULL if
// |widget| not found).
GtkFloatingContainerChild* GetChild(GtkFloatingContainer* container,
GtkWidget* widget) {
for (GList* floating_children = container->floating_children;
floating_children; floating_children = g_list_next(floating_children)) {
GtkFloatingContainerChild* child =
reinterpret_cast<GtkFloatingContainerChild*>(floating_children->data);
if (child->widget == widget)
return child;
}
return NULL;
}
} // namespace
G_BEGIN_DECLS
static void gtk_floating_container_remove(GtkContainer* container,
GtkWidget* widget);
static void gtk_floating_container_forall(GtkContainer* container,
gboolean include_internals,
GtkCallback callback,
gpointer callback_data);
static void gtk_floating_container_size_request(GtkWidget* widget,
GtkRequisition* requisition);
static void gtk_floating_container_size_allocate(GtkWidget* widget,
GtkAllocation* allocation);
static void gtk_floating_container_set_child_property(GtkContainer* container,
GtkWidget* child,
guint property_id,
const GValue* value,
GParamSpec* pspec);
static void gtk_floating_container_get_child_property(GtkContainer* container,
GtkWidget* child,
guint property_id,
GValue* value,
GParamSpec* pspec);
static guint floating_container_signals[LAST_SIGNAL] = { 0 };
G_DEFINE_TYPE(GtkFloatingContainer, gtk_floating_container, GTK_TYPE_BIN)
static void gtk_floating_container_class_init(
GtkFloatingContainerClass *klass) {
GtkObjectClass* object_class =
reinterpret_cast<GtkObjectClass*>(klass);
GtkWidgetClass* widget_class =
reinterpret_cast<GtkWidgetClass*>(klass);
widget_class->size_request = gtk_floating_container_size_request;
widget_class->size_allocate = gtk_floating_container_size_allocate;
GtkContainerClass* container_class =
reinterpret_cast<GtkContainerClass*>(klass);
container_class->remove = gtk_floating_container_remove;
container_class->forall = gtk_floating_container_forall;
container_class->set_child_property =
gtk_floating_container_set_child_property;
container_class->get_child_property =
gtk_floating_container_get_child_property;
gtk_container_class_install_child_property(
container_class,
CHILD_PROP_X,
g_param_spec_int("x",
"X position",
"X position of child widget",
G_MININT,
G_MAXINT,
0,
static_cast<GParamFlags>(GTK_PARAM_READWRITE)));
gtk_container_class_install_child_property(
container_class,
CHILD_PROP_Y,
g_param_spec_int("y",
"Y position",
"Y position of child widget",
G_MININT,
G_MAXINT,
0,
static_cast<GParamFlags>(GTK_PARAM_READWRITE)));
floating_container_signals[SET_FLOATING_POSITION] =
g_signal_new("set-floating-position",
G_OBJECT_CLASS_TYPE(object_class),
static_cast<GSignalFlags>(G_SIGNAL_RUN_FIRST |
G_SIGNAL_ACTION),
NULL,
NULL, NULL,
gtk_marshal_VOID__BOXED,
G_TYPE_NONE, 1,
GDK_TYPE_RECTANGLE | G_SIGNAL_TYPE_STATIC_SCOPE);
}
static void gtk_floating_container_init(GtkFloatingContainer* container) {
GTK_WIDGET_SET_FLAGS(container, GTK_NO_WINDOW);
container->floating_children = NULL;
}
static void gtk_floating_container_remove(GtkContainer* container,
GtkWidget* widget) {
g_return_if_fail(GTK_IS_WIDGET(widget));
GtkBin* bin = GTK_BIN(container);
if (bin->child == widget) {
((GTK_CONTAINER_CLASS(gtk_floating_container_parent_class))->remove)
(container, widget);
} else {
// Handle the other case where it's in our |floating_children| list.
GtkFloatingContainer* floating = GTK_FLOATING_CONTAINER(container);
GList* children = floating->floating_children;
gboolean removed_child = false;
while (children) {
GtkFloatingContainerChild* child =
reinterpret_cast<GtkFloatingContainerChild*>(children->data);
if (child->widget == widget) {
removed_child = true;
gboolean was_visible = GTK_WIDGET_VISIBLE(widget);
gtk_widget_unparent(widget);
floating->floating_children =
g_list_remove_link(floating->floating_children, children);
g_list_free(children);
g_free(child);
if (was_visible && GTK_WIDGET_VISIBLE(container))
gtk_widget_queue_resize(GTK_WIDGET(container));
break;
}
children = children->next;
}
g_return_if_fail(removed_child);
}
}
static void gtk_floating_container_forall(GtkContainer* container,
gboolean include_internals,
GtkCallback callback,
gpointer callback_data) {
g_return_if_fail(container != NULL);
g_return_if_fail(callback != NULL);
// Let GtkBin do its part of the forall.
((GTK_CONTAINER_CLASS(gtk_floating_container_parent_class))->forall)
(container, include_internals, callback, callback_data);
GtkFloatingContainer* floating = GTK_FLOATING_CONTAINER(container);
GList* children = floating->floating_children;
while (children) {
GtkFloatingContainerChild* child =
reinterpret_cast<GtkFloatingContainerChild*>(children->data);
children = children->next;
(*callback)(child->widget, callback_data);
}
}
static void gtk_floating_container_size_request(GtkWidget* widget,
GtkRequisition* requisition) {
GtkBin *bin = GTK_BIN(widget);
if (bin && bin->child) {
gtk_widget_size_request(bin->child, requisition);
} else {
requisition->width = 0;
requisition->height = 0;
}
}
static void gtk_floating_container_size_allocate(GtkWidget* widget,
GtkAllocation* allocation) {
widget->allocation = *allocation;
if (!GTK_WIDGET_NO_WINDOW(widget) && GTK_WIDGET_REALIZED(widget)) {
gdk_window_move_resize(widget->window,
allocation->x,
allocation->y,
allocation->width,
allocation->height);
}
// Give the same allocation to our GtkBin component.
GtkBin* bin = GTK_BIN(widget);
if (bin->child) {
gtk_widget_size_allocate(bin->child, allocation);
}
// We need to give whoever is pulling our strings a chance to set the "x" and
// "y" properties on all of our children.
g_signal_emit(widget, floating_container_signals[SET_FLOATING_POSITION], 0,
allocation);
// Our allocation has been set. We've asked our controller to place the other
// widgets. Pass out allocations to all our children based on where they want
// to be.
GtkFloatingContainer* container = GTK_FLOATING_CONTAINER(widget);
GList* children = container->floating_children;
GtkAllocation child_allocation;
GtkRequisition child_requisition;
while (children) {
GtkFloatingContainerChild* child =
reinterpret_cast<GtkFloatingContainerChild*>(children->data);
children = children->next;
if (GTK_WIDGET_VISIBLE(child->widget)) {
gtk_widget_size_request(child->widget, &child_requisition);
child_allocation.x = child->x;
child_allocation.y = child->y;
child_allocation.width = std::max(1, std::min(child_requisition.width,
allocation->width));
child_allocation.height = std::max(1, std::min(child_requisition.height,
allocation->height));
gtk_widget_size_allocate(child->widget, &child_allocation);
}
}
}
static void gtk_floating_container_set_child_property(GtkContainer* container,
GtkWidget* child,
guint property_id,
const GValue* value,
GParamSpec* pspec) {
GtkFloatingContainerChild* floating_child =
GetChild(GTK_FLOATING_CONTAINER(container), child);
g_return_if_fail(floating_child);
switch (property_id) {
case CHILD_PROP_X:
floating_child->x = g_value_get_int(value);
gtk_widget_child_notify(child, "x");
break;
case CHILD_PROP_Y:
floating_child->y = g_value_get_int(value);
gtk_widget_child_notify(child, "y");
break;
default:
GTK_CONTAINER_WARN_INVALID_CHILD_PROPERTY_ID(
container, property_id, pspec);
break;
};
}
static void gtk_floating_container_get_child_property(GtkContainer* container,
GtkWidget* child,
guint property_id,
GValue* value,
GParamSpec* pspec) {
GtkFloatingContainerChild* floating_child =
GetChild(GTK_FLOATING_CONTAINER(container), child);
g_return_if_fail(floating_child);
switch (property_id) {
case CHILD_PROP_X:
g_value_set_int(value, floating_child->x);
break;
case CHILD_PROP_Y:
g_value_set_int(value, floating_child->y);
break;
default:
GTK_CONTAINER_WARN_INVALID_CHILD_PROPERTY_ID(
container, property_id, pspec);
break;
};
}
GtkWidget* gtk_floating_container_new() {
return GTK_WIDGET(g_object_new(GTK_TYPE_FLOATING_CONTAINER, NULL));
}
void gtk_floating_container_add_floating(GtkFloatingContainer* container,
GtkWidget* widget) {
g_return_if_fail(GTK_IS_FLOATING_CONTAINER(container));
g_return_if_fail(GTK_IS_WIDGET(widget));
GtkFloatingContainerChild* child_info = g_new(GtkFloatingContainerChild, 1);
child_info->widget = widget;
child_info->x = 0;
child_info->y = 0;
gtk_widget_set_parent(widget, GTK_WIDGET(container));
container->floating_children =
g_list_append(container->floating_children, child_info);
}
G_END_DECLS
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_path.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/tab_contents/navigation_entry.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/notification_type.h"
#include "chrome/common/page_transition_types.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
void SimulateRendererCrash(Browser* browser) {
browser->OpenURL(GURL(chrome::kAboutCrashURL), GURL(), CURRENT_TAB,
PageTransition::TYPED);
ui_test_utils::WaitForNotification(
NotificationType::TAB_CONTENTS_DISCONNECTED);
}
} // namespace
class CrashRecoveryBrowserTest : public InProcessBrowserTest {
};
// http://crbug.com/29331 - Causes an OS crash dialog in release mode, needs to
// be fixed before it can be enabled to not cause the bots issues.
#if defined(OS_MACOSX)
#define MAYBE_Reload DISABLED_Reload
#define MAYBE_LoadInNewTab DISABLED_LoadInNewTab
#else
#define MAYBE_Reload Reload
#define MAYBE_LoadInNewTab LoadInNewTab
#endif
// Test that reload works after a crash.
IN_PROC_BROWSER_TEST_F(CrashRecoveryBrowserTest, MAYBE_Reload) {
// The title of the active tab should change each time this URL is loaded.
GURL url(
"data:text/html,<script>document.title=new Date().valueOf()</script>");
ui_test_utils::NavigateToURL(browser(), url);
string16 title_before_crash;
string16 title_after_crash;
ASSERT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(),
&title_before_crash));
SimulateRendererCrash(browser());
browser()->Reload(CURRENT_TAB);
ASSERT_TRUE(ui_test_utils::WaitForNavigationInCurrentTab(browser()));
ASSERT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(),
&title_after_crash));
EXPECT_NE(title_before_crash, title_after_crash);
}
// Tests that loading a crashed page in a new tab correctly updates the title.
// There was an earlier bug (1270510) in process-per-site in which the max page
// ID of the RenderProcessHost was stale, so the NavigationEntry in the new tab
// was not committed. This prevents regression of that bug.
IN_PROC_BROWSER_TEST_F(CrashRecoveryBrowserTest, MAYBE_LoadInNewTab) {
const FilePath::CharType* kTitle2File = FILE_PATH_LITERAL("title2.html");
ui_test_utils::NavigateToURL(browser(),
ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory),
FilePath(kTitle2File)));
string16 title_before_crash;
string16 title_after_crash;
ASSERT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(),
&title_before_crash));
SimulateRendererCrash(browser());
browser()->Reload(CURRENT_TAB);
ASSERT_TRUE(ui_test_utils::WaitForNavigationInCurrentTab(browser()));
ASSERT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(),
&title_after_crash));
EXPECT_EQ(title_before_crash, title_after_crash);
}
<commit_msg>Disable CrashRecoveryBrowserTest.LoadInNewTab as it times out occasionally.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_path.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/tab_contents/navigation_entry.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/notification_type.h"
#include "chrome/common/page_transition_types.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
void SimulateRendererCrash(Browser* browser) {
browser->OpenURL(GURL(chrome::kAboutCrashURL), GURL(), CURRENT_TAB,
PageTransition::TYPED);
ui_test_utils::WaitForNotification(
NotificationType::TAB_CONTENTS_DISCONNECTED);
}
} // namespace
class CrashRecoveryBrowserTest : public InProcessBrowserTest {
};
// http://crbug.com/29331 - Causes an OS crash dialog in release mode, needs to
// be fixed before it can be enabled to not cause the bots issues.
#if defined(OS_MACOSX)
#define MAYBE_Reload DISABLED_Reload
#define MAYBE_LoadInNewTab DISABLED_LoadInNewTab
#elif defined(OS_WIN)
// http://crbug.com/57158 - Times out sometimes on windows.
#define MAYBE_LoadInNewTab DISABLED_LoadInNewTab
#else
#define MAYBE_Reload Reload
#define MAYBE_LoadInNewTab LoadInNewTab
#endif
// Test that reload works after a crash.
IN_PROC_BROWSER_TEST_F(CrashRecoveryBrowserTest, MAYBE_Reload) {
// The title of the active tab should change each time this URL is loaded.
GURL url(
"data:text/html,<script>document.title=new Date().valueOf()</script>");
ui_test_utils::NavigateToURL(browser(), url);
string16 title_before_crash;
string16 title_after_crash;
ASSERT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(),
&title_before_crash));
SimulateRendererCrash(browser());
browser()->Reload(CURRENT_TAB);
ASSERT_TRUE(ui_test_utils::WaitForNavigationInCurrentTab(browser()));
ASSERT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(),
&title_after_crash));
EXPECT_NE(title_before_crash, title_after_crash);
}
// Tests that loading a crashed page in a new tab correctly updates the title.
// There was an earlier bug (1270510) in process-per-site in which the max page
// ID of the RenderProcessHost was stale, so the NavigationEntry in the new tab
// was not committed. This prevents regression of that bug.
IN_PROC_BROWSER_TEST_F(CrashRecoveryBrowserTest, MAYBE_LoadInNewTab) {
const FilePath::CharType* kTitle2File = FILE_PATH_LITERAL("title2.html");
ui_test_utils::NavigateToURL(browser(),
ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory),
FilePath(kTitle2File)));
string16 title_before_crash;
string16 title_after_crash;
ASSERT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(),
&title_before_crash));
SimulateRendererCrash(browser());
browser()->Reload(CURRENT_TAB);
ASSERT_TRUE(ui_test_utils::WaitForNavigationInCurrentTab(browser()));
ASSERT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(),
&title_after_crash));
EXPECT_EQ(title_before_crash, title_after_crash);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/gtk/options/fonts_page_gtk.h"
#include "app/l10n_util.h"
#include "app/l10n_util_collator.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/gtk/options/options_layout_gtk.h"
#include "chrome/browser/profile.h"
#include "chrome/common/gtk_util.h"
#include "chrome/common/pref_names.h"
#include "grit/generated_resources.h"
namespace {
// Make a Gtk font name string from a font family name and pixel size.
std::string MakeFontName(std::wstring family_name, int pixel_size) {
std::string fontname;
// TODO(mattm): We can pass in the size in pixels (px), and the font button
// actually honors it, but when you open the selector it interprets it as
// points. See crbug.com/17857
SStringPrintf(&fontname, "%s, %dpx", WideToUTF8(family_name).c_str(),
pixel_size);
return fontname;
}
} // namespace
FontsPageGtk::FontsPageGtk(Profile* profile) : OptionsPageBase(profile) {
Init();
}
FontsPageGtk::~FontsPageGtk() {
}
void FontsPageGtk::Init() {
OptionsLayoutBuilderGtk options_builder;
serif_font_button_ = gtk_font_button_new();
gtk_font_button_set_use_font(GTK_FONT_BUTTON(serif_font_button_), TRUE);
gtk_font_button_set_use_size(GTK_FONT_BUTTON(serif_font_button_), TRUE);
g_signal_connect(serif_font_button_, "font-set", G_CALLBACK(OnSerifFontSet),
this);
sans_font_button_ = gtk_font_button_new();
gtk_font_button_set_use_font(GTK_FONT_BUTTON(sans_font_button_), TRUE);
gtk_font_button_set_use_size(GTK_FONT_BUTTON(sans_font_button_), TRUE);
g_signal_connect(sans_font_button_, "font-set", G_CALLBACK(OnSansFontSet),
this);
fixed_font_button_ = gtk_font_button_new();
gtk_font_button_set_use_font(GTK_FONT_BUTTON(fixed_font_button_), TRUE);
gtk_font_button_set_use_size(GTK_FONT_BUTTON(fixed_font_button_), TRUE);
g_signal_connect(fixed_font_button_, "font-set", G_CALLBACK(OnFixedFontSet),
this);
GtkWidget* font_controls = gtk_util::CreateLabeledControlsGroup(NULL,
l10n_util::GetStringUTF8(
IDS_FONT_LANGUAGE_SETTING_FONT_SELECTOR_SERIF_LABEL).c_str(),
serif_font_button_,
l10n_util::GetStringUTF8(
IDS_FONT_LANGUAGE_SETTING_FONT_SELECTOR_SANS_SERIF_LABEL).c_str(),
sans_font_button_,
l10n_util::GetStringUTF8(
IDS_FONT_LANGUAGE_SETTING_FONT_SELECTOR_FIXED_WIDTH_LABEL).c_str(),
fixed_font_button_,
NULL);
options_builder.AddOptionGroup(l10n_util::GetStringUTF8(
IDS_FONT_LANGUAGE_SETTING_FONT_SUB_DIALOG_FONT_TITLE),
font_controls, false);
InitDefaultEncodingComboBox();
std::string encoding_group_description = l10n_util::GetStringUTF8(
IDS_FONT_LANGUAGE_SETTING_FONT_DEFAULT_ENCODING_SELECTOR_LABEL);
GtkWidget* encoding_controls = gtk_util::CreateLabeledControlsGroup(NULL,
encoding_group_description.c_str(),
default_encoding_combobox_,
NULL);
options_builder.AddOptionGroup(l10n_util::GetStringUTF8(
IDS_FONT_LANGUAGE_SETTING_FONT_SUB_DIALOG_ENCODING_TITLE),
encoding_controls, false);
page_ = options_builder.get_page_widget();
serif_name_.Init(prefs::kWebKitSerifFontFamily, profile()->GetPrefs(), this);
sans_serif_name_.Init(prefs::kWebKitSansSerifFontFamily,
profile()->GetPrefs(), this);
variable_width_size_.Init(prefs::kWebKitDefaultFontSize,
profile()->GetPrefs(), this);
fixed_width_name_.Init(prefs::kWebKitFixedFontFamily, profile()->GetPrefs(),
this);
fixed_width_size_.Init(prefs::kWebKitDefaultFixedFontSize,
profile()->GetPrefs(), this);
default_encoding_.Init(prefs::kDefaultCharset, profile()->GetPrefs(), this);
NotifyPrefChanged(NULL);
}
void FontsPageGtk::InitDefaultEncodingComboBox() {
default_encoding_combobox_ = gtk_combo_box_new_text();
g_signal_connect(G_OBJECT(default_encoding_combobox_), "changed",
G_CALLBACK(OnDefaultEncodingChanged), this);
int canonical_encoding_names_length =
CharacterEncoding::GetSupportCanonicalEncodingCount();
// Initialize the vector of all sorted encodings according to current
// UI locale.
std::string locale = g_browser_process->GetApplicationLocale();
for (int i = 0; i < canonical_encoding_names_length; i++) {
sorted_encoding_list_.push_back(CharacterEncoding::EncodingInfo(
CharacterEncoding::GetEncodingCommandIdByIndex(i)));
}
l10n_util::SortVectorWithStringKey(locale, &sorted_encoding_list_, true);
for (size_t i = 0; i < sorted_encoding_list_.size(); i++) {
gtk_combo_box_append_text(
GTK_COMBO_BOX(default_encoding_combobox_),
WideToUTF8(sorted_encoding_list_[i].encoding_display_name).c_str());
}
}
void FontsPageGtk::NotifyPrefChanged(const std::wstring* pref_name) {
if (!pref_name || *pref_name == prefs::kWebKitSerifFontFamily ||
*pref_name == prefs::kWebKitDefaultFontSize) {
gtk_font_button_set_font_name(GTK_FONT_BUTTON(serif_font_button_),
MakeFontName(serif_name_.GetValue(),
variable_width_size_.GetValue()).c_str());
}
if (!pref_name || *pref_name == prefs::kWebKitSansSerifFontFamily ||
*pref_name == prefs::kWebKitDefaultFontSize) {
gtk_font_button_set_font_name(GTK_FONT_BUTTON(sans_font_button_),
MakeFontName(sans_serif_name_.GetValue(),
variable_width_size_.GetValue()).c_str());
}
if (!pref_name || *pref_name == prefs::kWebKitFixedFontFamily ||
*pref_name == prefs::kWebKitDefaultFixedFontSize) {
gtk_font_button_set_font_name(GTK_FONT_BUTTON(fixed_font_button_),
MakeFontName(fixed_width_name_.GetValue(),
fixed_width_size_.GetValue()).c_str());
}
if (!pref_name || *pref_name == prefs::kDefaultCharset) {
const std::string current_encoding =
WideToASCII(default_encoding_.GetValue());
for (size_t i = 0; i < sorted_encoding_list_.size(); i++) {
if (CharacterEncoding::GetCanonicalEncodingNameByCommandId(
sorted_encoding_list_[i].encoding_id) == current_encoding) {
gtk_combo_box_set_active(GTK_COMBO_BOX(default_encoding_combobox_), i);
break;
}
}
}
}
void FontsPageGtk::SetFontsFromButton(StringPrefMember* name_pref,
IntegerPrefMember* size_pref,
GtkFontButton* font_button) {
PangoFontDescription* desc = pango_font_description_from_string(
gtk_font_button_get_font_name(font_button));
int size = pango_font_description_get_size(desc);
name_pref->SetValue(UTF8ToWide(pango_font_description_get_family(desc)));
size_pref->SetValue(size / PANGO_SCALE);
pango_font_description_free(desc);
// Reset the button font in px, since the chooser will have set it in points.
// Also, both sans and serif share the same size so we need to update them
// both.
NotifyPrefChanged(NULL);
}
// static
void FontsPageGtk::OnSerifFontSet(GtkFontButton* font_button,
FontsPageGtk* fonts_page) {
fonts_page->SetFontsFromButton(&fonts_page->serif_name_,
&fonts_page->variable_width_size_,
font_button);
}
// static
void FontsPageGtk::OnSansFontSet(GtkFontButton* font_button,
FontsPageGtk* fonts_page) {
fonts_page->SetFontsFromButton(&fonts_page->sans_serif_name_,
&fonts_page->variable_width_size_,
font_button);
}
// static
void FontsPageGtk::OnFixedFontSet(GtkFontButton* font_button,
FontsPageGtk* fonts_page) {
fonts_page->SetFontsFromButton(&fonts_page->fixed_width_name_,
&fonts_page->fixed_width_size_,
font_button);
}
// static
void FontsPageGtk::OnDefaultEncodingChanged(GtkComboBox* combo_box,
FontsPageGtk* fonts_page) {
int index = gtk_combo_box_get_active(combo_box);
if (index < 0 ||
static_cast<size_t>(index) >= fonts_page->sorted_encoding_list_.size()) {
NOTREACHED();
return;
}
fonts_page->default_encoding_.SetValue(
ASCIIToWide(CharacterEncoding::GetCanonicalEncodingNameByCommandId(
fonts_page->sorted_encoding_list_[index].encoding_id)));
}
<commit_msg>Linux: Font options handle font fallback better.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/gtk/options/fonts_page_gtk.h"
#include "app/l10n_util.h"
#include "app/l10n_util_collator.h"
#include "app/gfx/font.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/gtk/options/options_layout_gtk.h"
#include "chrome/browser/profile.h"
#include "chrome/common/gtk_util.h"
#include "chrome/common/pref_names.h"
#include "grit/generated_resources.h"
namespace {
// Make a Gtk font name string from a font family name and pixel size.
std::string MakeFontName(std::wstring family_name, int pixel_size) {
// The given font might not be available (the default fonts we use are not
// installed by default on some distros). So figure out which font we are
// actually falling back to and display that. (See crbug.com/31381.)
std::wstring actual_family_name = gfx::Font::CreateFont(
family_name, pixel_size).FontName();
std::string fontname;
// TODO(mattm): We can pass in the size in pixels (px), and the font button
// actually honors it, but when you open the selector it interprets it as
// points. See crbug.com/17857
SStringPrintf(&fontname, "%s, %dpx", WideToUTF8(actual_family_name).c_str(),
pixel_size);
return fontname;
}
} // namespace
FontsPageGtk::FontsPageGtk(Profile* profile) : OptionsPageBase(profile) {
Init();
}
FontsPageGtk::~FontsPageGtk() {
}
void FontsPageGtk::Init() {
OptionsLayoutBuilderGtk options_builder;
serif_font_button_ = gtk_font_button_new();
gtk_font_button_set_use_font(GTK_FONT_BUTTON(serif_font_button_), TRUE);
gtk_font_button_set_use_size(GTK_FONT_BUTTON(serif_font_button_), TRUE);
g_signal_connect(serif_font_button_, "font-set", G_CALLBACK(OnSerifFontSet),
this);
sans_font_button_ = gtk_font_button_new();
gtk_font_button_set_use_font(GTK_FONT_BUTTON(sans_font_button_), TRUE);
gtk_font_button_set_use_size(GTK_FONT_BUTTON(sans_font_button_), TRUE);
g_signal_connect(sans_font_button_, "font-set", G_CALLBACK(OnSansFontSet),
this);
fixed_font_button_ = gtk_font_button_new();
gtk_font_button_set_use_font(GTK_FONT_BUTTON(fixed_font_button_), TRUE);
gtk_font_button_set_use_size(GTK_FONT_BUTTON(fixed_font_button_), TRUE);
g_signal_connect(fixed_font_button_, "font-set", G_CALLBACK(OnFixedFontSet),
this);
GtkWidget* font_controls = gtk_util::CreateLabeledControlsGroup(NULL,
l10n_util::GetStringUTF8(
IDS_FONT_LANGUAGE_SETTING_FONT_SELECTOR_SERIF_LABEL).c_str(),
serif_font_button_,
l10n_util::GetStringUTF8(
IDS_FONT_LANGUAGE_SETTING_FONT_SELECTOR_SANS_SERIF_LABEL).c_str(),
sans_font_button_,
l10n_util::GetStringUTF8(
IDS_FONT_LANGUAGE_SETTING_FONT_SELECTOR_FIXED_WIDTH_LABEL).c_str(),
fixed_font_button_,
NULL);
options_builder.AddOptionGroup(l10n_util::GetStringUTF8(
IDS_FONT_LANGUAGE_SETTING_FONT_SUB_DIALOG_FONT_TITLE),
font_controls, false);
InitDefaultEncodingComboBox();
std::string encoding_group_description = l10n_util::GetStringUTF8(
IDS_FONT_LANGUAGE_SETTING_FONT_DEFAULT_ENCODING_SELECTOR_LABEL);
GtkWidget* encoding_controls = gtk_util::CreateLabeledControlsGroup(NULL,
encoding_group_description.c_str(),
default_encoding_combobox_,
NULL);
options_builder.AddOptionGroup(l10n_util::GetStringUTF8(
IDS_FONT_LANGUAGE_SETTING_FONT_SUB_DIALOG_ENCODING_TITLE),
encoding_controls, false);
page_ = options_builder.get_page_widget();
serif_name_.Init(prefs::kWebKitSerifFontFamily, profile()->GetPrefs(), this);
sans_serif_name_.Init(prefs::kWebKitSansSerifFontFamily,
profile()->GetPrefs(), this);
variable_width_size_.Init(prefs::kWebKitDefaultFontSize,
profile()->GetPrefs(), this);
fixed_width_name_.Init(prefs::kWebKitFixedFontFamily, profile()->GetPrefs(),
this);
fixed_width_size_.Init(prefs::kWebKitDefaultFixedFontSize,
profile()->GetPrefs(), this);
default_encoding_.Init(prefs::kDefaultCharset, profile()->GetPrefs(), this);
NotifyPrefChanged(NULL);
}
void FontsPageGtk::InitDefaultEncodingComboBox() {
default_encoding_combobox_ = gtk_combo_box_new_text();
g_signal_connect(G_OBJECT(default_encoding_combobox_), "changed",
G_CALLBACK(OnDefaultEncodingChanged), this);
int canonical_encoding_names_length =
CharacterEncoding::GetSupportCanonicalEncodingCount();
// Initialize the vector of all sorted encodings according to current
// UI locale.
std::string locale = g_browser_process->GetApplicationLocale();
for (int i = 0; i < canonical_encoding_names_length; i++) {
sorted_encoding_list_.push_back(CharacterEncoding::EncodingInfo(
CharacterEncoding::GetEncodingCommandIdByIndex(i)));
}
l10n_util::SortVectorWithStringKey(locale, &sorted_encoding_list_, true);
for (size_t i = 0; i < sorted_encoding_list_.size(); i++) {
gtk_combo_box_append_text(
GTK_COMBO_BOX(default_encoding_combobox_),
WideToUTF8(sorted_encoding_list_[i].encoding_display_name).c_str());
}
}
void FontsPageGtk::NotifyPrefChanged(const std::wstring* pref_name) {
if (!pref_name || *pref_name == prefs::kWebKitSerifFontFamily ||
*pref_name == prefs::kWebKitDefaultFontSize) {
gtk_font_button_set_font_name(GTK_FONT_BUTTON(serif_font_button_),
MakeFontName(serif_name_.GetValue(),
variable_width_size_.GetValue()).c_str());
}
if (!pref_name || *pref_name == prefs::kWebKitSansSerifFontFamily ||
*pref_name == prefs::kWebKitDefaultFontSize) {
gtk_font_button_set_font_name(GTK_FONT_BUTTON(sans_font_button_),
MakeFontName(sans_serif_name_.GetValue(),
variable_width_size_.GetValue()).c_str());
}
if (!pref_name || *pref_name == prefs::kWebKitFixedFontFamily ||
*pref_name == prefs::kWebKitDefaultFixedFontSize) {
gtk_font_button_set_font_name(GTK_FONT_BUTTON(fixed_font_button_),
MakeFontName(fixed_width_name_.GetValue(),
fixed_width_size_.GetValue()).c_str());
}
if (!pref_name || *pref_name == prefs::kDefaultCharset) {
const std::string current_encoding =
WideToASCII(default_encoding_.GetValue());
for (size_t i = 0; i < sorted_encoding_list_.size(); i++) {
if (CharacterEncoding::GetCanonicalEncodingNameByCommandId(
sorted_encoding_list_[i].encoding_id) == current_encoding) {
gtk_combo_box_set_active(GTK_COMBO_BOX(default_encoding_combobox_), i);
break;
}
}
}
}
void FontsPageGtk::SetFontsFromButton(StringPrefMember* name_pref,
IntegerPrefMember* size_pref,
GtkFontButton* font_button) {
PangoFontDescription* desc = pango_font_description_from_string(
gtk_font_button_get_font_name(font_button));
int size = pango_font_description_get_size(desc);
name_pref->SetValue(UTF8ToWide(pango_font_description_get_family(desc)));
size_pref->SetValue(size / PANGO_SCALE);
pango_font_description_free(desc);
// Reset the button font in px, since the chooser will have set it in points.
// Also, both sans and serif share the same size so we need to update them
// both.
NotifyPrefChanged(NULL);
}
// static
void FontsPageGtk::OnSerifFontSet(GtkFontButton* font_button,
FontsPageGtk* fonts_page) {
fonts_page->SetFontsFromButton(&fonts_page->serif_name_,
&fonts_page->variable_width_size_,
font_button);
}
// static
void FontsPageGtk::OnSansFontSet(GtkFontButton* font_button,
FontsPageGtk* fonts_page) {
fonts_page->SetFontsFromButton(&fonts_page->sans_serif_name_,
&fonts_page->variable_width_size_,
font_button);
}
// static
void FontsPageGtk::OnFixedFontSet(GtkFontButton* font_button,
FontsPageGtk* fonts_page) {
fonts_page->SetFontsFromButton(&fonts_page->fixed_width_name_,
&fonts_page->fixed_width_size_,
font_button);
}
// static
void FontsPageGtk::OnDefaultEncodingChanged(GtkComboBox* combo_box,
FontsPageGtk* fonts_page) {
int index = gtk_combo_box_get_active(combo_box);
if (index < 0 ||
static_cast<size_t>(index) >= fonts_page->sorted_encoding_list_.size()) {
NOTREACHED();
return;
}
fonts_page->default_encoding_.SetValue(
ASCIIToWide(CharacterEncoding::GetCanonicalEncodingNameByCommandId(
fonts_page->sorted_encoding_list_[index].encoding_id)));
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/prefs/session_startup_pref.h"
#include <string>
#include "base/values.h"
#include "chrome/browser/net/url_fixer_upper.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/prefs/scoped_user_pref_update.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/protector/protected_prefs_watcher.h"
#include "chrome/browser/protector/protector_service.h"
#include "chrome/browser/protector/protector_service_factory.h"
#include "chrome/common/pref_names.h"
#if defined(OS_MACOSX)
#include "chrome/browser/ui/cocoa/window_restore_utils.h"
#endif
using protector::ProtectedPrefsWatcher;
using protector::ProtectorServiceFactory;
namespace {
// For historical reasons the enum and value registered in the prefs don't line
// up. These are the values registered in prefs.
const int kPrefValueHomePage = 0; // Deprecated
const int kPrefValueLast = 1;
const int kPrefValueURLs = 4;
const int kPrefValueNewTab = 5;
// Converts a SessionStartupPref::Type to an integer written to prefs.
int TypeToPrefValue(SessionStartupPref::Type type) {
switch (type) {
case SessionStartupPref::LAST: return kPrefValueLast;
case SessionStartupPref::URLS: return kPrefValueURLs;
default: return kPrefValueNewTab;
}
}
void SetNewURLList(PrefService* prefs) {
ListValue new_url_pref_list;
StringValue* home_page = new StringValue(prefs->GetString(prefs::kHomePage));
new_url_pref_list.Append(home_page);
prefs->Set(prefs::kURLsToRestoreOnStartup, new_url_pref_list);
}
void URLListToPref(const base::ListValue* url_list, SessionStartupPref* pref) {
pref->urls.clear();
for (size_t i = 0; i < url_list->GetSize(); ++i) {
Value* value = NULL;
CHECK(url_list->Get(i, &value));
std::string url_text;
if (value->GetAsString(&url_text)) {
GURL fixed_url = URLFixerUpper::FixupURL(url_text, "");
pref->urls.push_back(fixed_url);
}
}
}
} // namespace
// static
void SessionStartupPref::RegisterUserPrefs(PrefService* prefs) {
prefs->RegisterIntegerPref(prefs::kRestoreOnStartup,
TypeToPrefValue(GetDefaultStartupType()),
PrefService::SYNCABLE_PREF);
prefs->RegisterListPref(prefs::kURLsToRestoreOnStartup,
PrefService::SYNCABLE_PREF);
}
// static
SessionStartupPref::Type SessionStartupPref::GetDefaultStartupType() {
#if defined(OS_CHROMEOS)
SessionStartupPref::Type type = SessionStartupPref::LAST;
#else
SessionStartupPref::Type type = SessionStartupPref::DEFAULT;
#endif
#if defined(OS_MACOSX)
// Use Lion's system preference, if it is set.
if (restore_utils::IsWindowRestoreEnabled())
type = SessionStartupPref::LAST;
#endif
return type;
}
// static
void SessionStartupPref::SetStartupPref(
Profile* profile,
const SessionStartupPref& pref) {
DCHECK(profile);
SetStartupPref(profile->GetPrefs(), pref);
}
// static
void SessionStartupPref::SetStartupPref(PrefService* prefs,
const SessionStartupPref& pref) {
DCHECK(prefs);
if (!SessionStartupPref::TypeIsManaged(prefs))
prefs->SetInteger(prefs::kRestoreOnStartup, TypeToPrefValue(pref.type));
if (!SessionStartupPref::URLsAreManaged(prefs)) {
// Always save the URLs, that way the UI can remain consistent even if the
// user changes the startup type pref.
// Ownership of the ListValue retains with the pref service.
ListPrefUpdate update(prefs, prefs::kURLsToRestoreOnStartup);
ListValue* url_pref_list = update.Get();
DCHECK(url_pref_list);
url_pref_list->Clear();
for (size_t i = 0; i < pref.urls.size(); ++i) {
url_pref_list->Set(static_cast<int>(i),
new StringValue(pref.urls[i].spec()));
}
}
}
// static
SessionStartupPref SessionStartupPref::GetStartupPref(Profile* profile) {
DCHECK(profile);
return GetStartupPref(profile->GetPrefs());
}
// static
SessionStartupPref SessionStartupPref::GetStartupPref(PrefService* prefs) {
DCHECK(prefs);
SessionStartupPref pref(
PrefValueToType(prefs->GetInteger(prefs::kRestoreOnStartup)));
// Migrate from "Open the home page" to "Open the following URLs". If the user
// had the "Open the homepage" option selected, then we need to switch them to
// "Open the following URLs" and set the list of URLs to a list containing
// just the user's homepage.
if (pref.type == SessionStartupPref::HOMEPAGE) {
prefs->SetInteger(prefs::kRestoreOnStartup, kPrefValueURLs);
pref.type = SessionStartupPref::URLS;
SetNewURLList(prefs);
}
// Always load the urls, even if the pref type isn't URLS. This way the
// preferences panels can show the user their last choice.
const ListValue* url_list = prefs->GetList(prefs::kURLsToRestoreOnStartup);
URLListToPref(url_list, &pref);
return pref;
}
// static
bool SessionStartupPref::TypeIsManaged(PrefService* prefs) {
DCHECK(prefs);
const PrefService::Preference* pref_restore =
prefs->FindPreference(prefs::kRestoreOnStartup);
DCHECK(pref_restore);
return pref_restore->IsManaged();
}
// static
bool SessionStartupPref::URLsAreManaged(PrefService* prefs) {
DCHECK(prefs);
const PrefService::Preference* pref_urls =
prefs->FindPreference(prefs::kURLsToRestoreOnStartup);
DCHECK(pref_urls);
return pref_urls->IsManaged();
}
// static
SessionStartupPref::Type SessionStartupPref::PrefValueToType(int pref_value) {
switch (pref_value) {
case kPrefValueLast: return SessionStartupPref::LAST;
case kPrefValueURLs: return SessionStartupPref::URLS;
case kPrefValueHomePage: return SessionStartupPref::HOMEPAGE;
default: return SessionStartupPref::DEFAULT;
}
}
// static
bool SessionStartupPref::DidStartupPrefChange(Profile* profile) {
ProtectedPrefsWatcher* prefs_watcher =
ProtectorServiceFactory::GetForProfile(profile)->GetPrefsWatcher();
if (prefs_watcher->DidPrefChange(prefs::kRestoreOnStartup))
return true;
#if defined(OS_MACOSX)
// On Mac OS, default value for |kRestoreOnStartup| depends on system
// settings and may be different from one run to another.
PrefService* prefs = profile->GetPrefs();
if (prefs->FindPreference(prefs::kRestoreOnStartup)->IsDefaultValue())
return false;
#endif
return prefs_watcher->DidPrefChange(prefs::kRestoreOnStartup);
}
// static
SessionStartupPref SessionStartupPref::GetStartupPrefBackup(Profile* profile) {
protector::ProtectedPrefsWatcher* prefs_watcher =
protector::ProtectorServiceFactory::GetForProfile(profile)->
GetPrefsWatcher();
int type;
CHECK(prefs_watcher->GetBackupForPref(
prefs::kRestoreOnStartup)->GetAsInteger(&type));
SessionStartupPref backup_pref(PrefValueToType(type));
const ListValue* url_list;
CHECK(prefs_watcher->GetBackupForPref(
prefs::kURLsToRestoreOnStartup)->GetAsList(&url_list));
URLListToPref(url_list, &backup_pref);
return backup_pref;
}
SessionStartupPref::SessionStartupPref(Type type) : type(type) {}
SessionStartupPref::~SessionStartupPref() {}
<commit_msg>[protector] Fix session startup prefs check.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/prefs/session_startup_pref.h"
#include <string>
#include "base/values.h"
#include "chrome/browser/net/url_fixer_upper.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/prefs/scoped_user_pref_update.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/protector/protected_prefs_watcher.h"
#include "chrome/browser/protector/protector_service.h"
#include "chrome/browser/protector/protector_service_factory.h"
#include "chrome/common/pref_names.h"
#if defined(OS_MACOSX)
#include "chrome/browser/ui/cocoa/window_restore_utils.h"
#endif
using protector::ProtectedPrefsWatcher;
using protector::ProtectorServiceFactory;
namespace {
// For historical reasons the enum and value registered in the prefs don't line
// up. These are the values registered in prefs.
const int kPrefValueHomePage = 0; // Deprecated
const int kPrefValueLast = 1;
const int kPrefValueURLs = 4;
const int kPrefValueNewTab = 5;
// Converts a SessionStartupPref::Type to an integer written to prefs.
int TypeToPrefValue(SessionStartupPref::Type type) {
switch (type) {
case SessionStartupPref::LAST: return kPrefValueLast;
case SessionStartupPref::URLS: return kPrefValueURLs;
default: return kPrefValueNewTab;
}
}
void SetNewURLList(PrefService* prefs) {
ListValue new_url_pref_list;
StringValue* home_page = new StringValue(prefs->GetString(prefs::kHomePage));
new_url_pref_list.Append(home_page);
prefs->Set(prefs::kURLsToRestoreOnStartup, new_url_pref_list);
}
void URLListToPref(const base::ListValue* url_list, SessionStartupPref* pref) {
pref->urls.clear();
for (size_t i = 0; i < url_list->GetSize(); ++i) {
Value* value = NULL;
CHECK(url_list->Get(i, &value));
std::string url_text;
if (value->GetAsString(&url_text)) {
GURL fixed_url = URLFixerUpper::FixupURL(url_text, "");
pref->urls.push_back(fixed_url);
}
}
}
} // namespace
// static
void SessionStartupPref::RegisterUserPrefs(PrefService* prefs) {
prefs->RegisterIntegerPref(prefs::kRestoreOnStartup,
TypeToPrefValue(GetDefaultStartupType()),
PrefService::SYNCABLE_PREF);
prefs->RegisterListPref(prefs::kURLsToRestoreOnStartup,
PrefService::SYNCABLE_PREF);
}
// static
SessionStartupPref::Type SessionStartupPref::GetDefaultStartupType() {
#if defined(OS_CHROMEOS)
SessionStartupPref::Type type = SessionStartupPref::LAST;
#else
SessionStartupPref::Type type = SessionStartupPref::DEFAULT;
#endif
#if defined(OS_MACOSX)
// Use Lion's system preference, if it is set.
if (restore_utils::IsWindowRestoreEnabled())
type = SessionStartupPref::LAST;
#endif
return type;
}
// static
void SessionStartupPref::SetStartupPref(
Profile* profile,
const SessionStartupPref& pref) {
DCHECK(profile);
SetStartupPref(profile->GetPrefs(), pref);
}
// static
void SessionStartupPref::SetStartupPref(PrefService* prefs,
const SessionStartupPref& pref) {
DCHECK(prefs);
if (!SessionStartupPref::TypeIsManaged(prefs))
prefs->SetInteger(prefs::kRestoreOnStartup, TypeToPrefValue(pref.type));
if (!SessionStartupPref::URLsAreManaged(prefs)) {
// Always save the URLs, that way the UI can remain consistent even if the
// user changes the startup type pref.
// Ownership of the ListValue retains with the pref service.
ListPrefUpdate update(prefs, prefs::kURLsToRestoreOnStartup);
ListValue* url_pref_list = update.Get();
DCHECK(url_pref_list);
url_pref_list->Clear();
for (size_t i = 0; i < pref.urls.size(); ++i) {
url_pref_list->Set(static_cast<int>(i),
new StringValue(pref.urls[i].spec()));
}
}
}
// static
SessionStartupPref SessionStartupPref::GetStartupPref(Profile* profile) {
DCHECK(profile);
return GetStartupPref(profile->GetPrefs());
}
// static
SessionStartupPref SessionStartupPref::GetStartupPref(PrefService* prefs) {
DCHECK(prefs);
SessionStartupPref pref(
PrefValueToType(prefs->GetInteger(prefs::kRestoreOnStartup)));
// Migrate from "Open the home page" to "Open the following URLs". If the user
// had the "Open the homepage" option selected, then we need to switch them to
// "Open the following URLs" and set the list of URLs to a list containing
// just the user's homepage.
if (pref.type == SessionStartupPref::HOMEPAGE) {
prefs->SetInteger(prefs::kRestoreOnStartup, kPrefValueURLs);
pref.type = SessionStartupPref::URLS;
SetNewURLList(prefs);
}
// Always load the urls, even if the pref type isn't URLS. This way the
// preferences panels can show the user their last choice.
const ListValue* url_list = prefs->GetList(prefs::kURLsToRestoreOnStartup);
URLListToPref(url_list, &pref);
return pref;
}
// static
bool SessionStartupPref::TypeIsManaged(PrefService* prefs) {
DCHECK(prefs);
const PrefService::Preference* pref_restore =
prefs->FindPreference(prefs::kRestoreOnStartup);
DCHECK(pref_restore);
return pref_restore->IsManaged();
}
// static
bool SessionStartupPref::URLsAreManaged(PrefService* prefs) {
DCHECK(prefs);
const PrefService::Preference* pref_urls =
prefs->FindPreference(prefs::kURLsToRestoreOnStartup);
DCHECK(pref_urls);
return pref_urls->IsManaged();
}
// static
SessionStartupPref::Type SessionStartupPref::PrefValueToType(int pref_value) {
switch (pref_value) {
case kPrefValueLast: return SessionStartupPref::LAST;
case kPrefValueURLs: return SessionStartupPref::URLS;
case kPrefValueHomePage: return SessionStartupPref::HOMEPAGE;
default: return SessionStartupPref::DEFAULT;
}
}
// static
bool SessionStartupPref::DidStartupPrefChange(Profile* profile) {
ProtectedPrefsWatcher* prefs_watcher =
ProtectorServiceFactory::GetForProfile(profile)->GetPrefsWatcher();
if (prefs_watcher->DidPrefChange(prefs::kRestoreOnStartup))
return true;
#if defined(OS_MACOSX)
// On Mac OS, default value for |kRestoreOnStartup| depends on system
// settings and may be different from one run to another.
PrefService* prefs = profile->GetPrefs();
if (prefs->FindPreference(prefs::kRestoreOnStartup)->IsDefaultValue())
return false;
#endif
return prefs_watcher->DidPrefChange(prefs::kURLsToRestoreOnStartup);
}
// static
SessionStartupPref SessionStartupPref::GetStartupPrefBackup(Profile* profile) {
protector::ProtectedPrefsWatcher* prefs_watcher =
protector::ProtectorServiceFactory::GetForProfile(profile)->
GetPrefsWatcher();
int type;
CHECK(prefs_watcher->GetBackupForPref(
prefs::kRestoreOnStartup)->GetAsInteger(&type));
SessionStartupPref backup_pref(PrefValueToType(type));
const ListValue* url_list;
CHECK(prefs_watcher->GetBackupForPref(
prefs::kURLsToRestoreOnStartup)->GetAsList(&url_list));
URLListToPref(url_list, &backup_pref);
return backup_pref;
}
SessionStartupPref::SessionStartupPref(Type type) : type(type) {}
SessionStartupPref::~SessionStartupPref() {}
<|endoftext|> |
<commit_before><commit_msg>planning: increase routing lane length check epsilon to allow projection diff.<commit_after><|endoftext|> |
<commit_before>#include <boost/test/unit_test.hpp>
#include <ze/event.h>
#include "vast/query/ast.h"
#include "vast/query/exception.h"
#include "vast/query/expression.h"
#include "vast/query/parser/query.h"
#include "vast/util/parser/parse.h"
std::vector<ze::event_ptr> events
{
new ze::event{"foo", "babba", 1.337, 42u, 100, "bar", -4.8},
new ze::event{"bar", "yadda", ze::record{false, "baz"}}
};
bool test_expression(std::string const& query, ze::event_ptr const& event)
{
vast::query::ast::query ast;
if (! vast::util::parser::parse<vast::query::parser::query>(query, ast))
throw vast::query::syntax_exception(query);
if (! vast::query::ast::validate(ast))
throw vast::query::semantic_exception("semantic error", query);
vast::query::expression expr;
expr.assign(ast);
return expr.eval(event);
}
BOOST_AUTO_TEST_CASE(type_queries)
{
std::vector<std::string> queries
{
":count == 42",
":int != +101",
":string ~ /bar/ && :int == +100",
":double >= -4.8",
":int <= -3 || :int >= +100 && :string !~ /bar/ || :double > 1.0"
};
for (auto& q : queries)
BOOST_CHECK(test_expression(q, events[0]));
for (auto& q : queries)
BOOST_CHECK(! test_expression(q, events[1]));
}
BOOST_AUTO_TEST_CASE(event_queries)
{
std::vector<std::string> true_queries
{
"foo:count == 42 || bar:string ~ /yad.*/",
"f*:count == 42 || :bool == F",
"f*$not$yet$implemented ~ /vast/ || *$not$there$yet ~ /.*[bd]{2}a/"
};
std::vector<std::string> false_queries
{
"bar:string ~ /x/ || bar:bool == T"
};
for (auto& q : true_queries)
for (auto& e : events)
BOOST_CHECK(test_expression(q, e));
for (auto& q : false_queries)
for (auto& e : events)
BOOST_CHECK(! test_expression(q, e));
}
<commit_msg>Make unit tests compile again.<commit_after>#include <boost/test/unit_test.hpp>
#include <ze/event.h>
#include "vast/query/ast.h"
#include "vast/query/exception.h"
#include "vast/query/expression.h"
#include "vast/query/parser/query.h"
#include "vast/util/parser/parse.h"
std::vector<ze::event> events
{
{"foo", "babba", 1.337, 42u, 100, "bar", -4.8},
{"bar", "yadda", ze::record{false, "baz"}}
};
bool test_expression(std::string const& query, ze::event const& event)
{
vast::query::ast::query ast;
if (! vast::util::parser::parse<vast::query::parser::query>(query, ast))
throw vast::query::syntax_exception(query);
if (! vast::query::ast::validate(ast))
throw vast::query::semantic_exception("semantic error", query);
vast::query::expression expr;
expr.assign(ast);
return expr.eval(event);
}
BOOST_AUTO_TEST_CASE(type_queries)
{
std::vector<std::string> queries
{
":count == 42",
":int != +101",
":string ~ /bar/ && :int == +100",
":double >= -4.8",
":int <= -3 || :int >= +100 && :string !~ /bar/ || :double > 1.0"
};
for (auto& q : queries)
BOOST_CHECK(test_expression(q, events[0]));
for (auto& q : queries)
BOOST_CHECK(! test_expression(q, events[1]));
}
BOOST_AUTO_TEST_CASE(event_queries)
{
std::vector<std::string> true_queries
{
"foo:count == 42 || bar:string ~ /yad.*/",
"f*:count == 42 || :bool == F",
"f*$not$yet$implemented ~ /vast/ || *$not$there$yet ~ /.*[bd]{2}a/"
};
std::vector<std::string> false_queries
{
"bar:string ~ /x/ || bar:bool == T"
};
for (auto& q : true_queries)
for (auto& e : events)
BOOST_CHECK(test_expression(q, e));
for (auto& q : false_queries)
for (auto& e : events)
BOOST_CHECK(! test_expression(q, e));
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string>
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/browser/net/url_fixer_upper.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/test/test_server.h"
namespace {
const FilePath::CharType kDocRoot[] = FILE_PATH_LITERAL("chrome/test/data");
} // namespace
typedef UITest RepostFormWarningTest;
#if defined(OS_WIN)
// http://crbug.com/47228
#define MAYBE_TestDoubleReload FLAKY_TestDoubleReload
#else
#define MAYBE_TestDoubleReload TestDoubleReload
#endif
TEST_F(RepostFormWarningTest, MAYBE_TestDoubleReload) {
net::TestServer test_server(net::TestServer::TYPE_HTTP, FilePath(kDocRoot));
ASSERT_TRUE(test_server.Start());
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
scoped_refptr<TabProxy> tab(browser->GetTab(0));
ASSERT_TRUE(tab.get());
// Load a form.
ASSERT_TRUE(tab->NavigateToURL(test_server.GetURL("files/form.html")));
// Submit it.
ASSERT_TRUE(tab->NavigateToURL(GURL(
"javascript:document.getElementById('form').submit()")));
// Try to reload it twice, checking for repost.
tab->ReloadAsync();
tab->ReloadAsync();
// Navigate away from the page (this is when the test usually crashes).
ASSERT_TRUE(tab->NavigateToURL(test_server.GetURL("bar")));
}
#if defined(OS_WIN) || defined(OS_LINUX)
// http://crbug.com/47228 && http://crbug.com/56401
#define MAYBE_TestLoginAfterRepost FLAKY_TestLoginAfterRepost
#else
#define MAYBE_TestLoginAfterRepost TestLoginAfterRepost
#endif
TEST_F(RepostFormWarningTest, MAYBE_TestLoginAfterRepost) {
net::TestServer test_server(net::TestServer::TYPE_HTTP, FilePath(kDocRoot));
ASSERT_TRUE(test_server.Start());
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
scoped_refptr<TabProxy> tab(browser->GetTab(0));
ASSERT_TRUE(tab.get());
// Load a form.
ASSERT_TRUE(tab->NavigateToURL(test_server.GetURL("files/form.html")));
// Submit it.
ASSERT_TRUE(tab->NavigateToURL(GURL(
"javascript:document.getElementById('form').submit()")));
// Try to reload it, checking for repost.
tab->ReloadAsync();
// Navigate to a page that requires authentication, bringing up another
// tab-modal sheet.
ASSERT_TRUE(tab->NavigateToURL(test_server.GetURL("auth-basic")));
// Try to reload it again.
tab->ReloadAsync();
// Navigate away from the page.
ASSERT_TRUE(tab->NavigateToURL(test_server.GetURL("bar")));
}
<commit_msg>Remove the FLAKY mark from RepostFormWarningTest.TestLoginAfterRepost on Linux.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string>
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/browser/net/url_fixer_upper.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/test/test_server.h"
namespace {
const FilePath::CharType kDocRoot[] = FILE_PATH_LITERAL("chrome/test/data");
} // namespace
typedef UITest RepostFormWarningTest;
#if defined(OS_WIN)
// http://crbug.com/47228
#define MAYBE_TestDoubleReload FLAKY_TestDoubleReload
#else
#define MAYBE_TestDoubleReload TestDoubleReload
#endif
TEST_F(RepostFormWarningTest, MAYBE_TestDoubleReload) {
net::TestServer test_server(net::TestServer::TYPE_HTTP, FilePath(kDocRoot));
ASSERT_TRUE(test_server.Start());
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
scoped_refptr<TabProxy> tab(browser->GetTab(0));
ASSERT_TRUE(tab.get());
// Load a form.
ASSERT_TRUE(tab->NavigateToURL(test_server.GetURL("files/form.html")));
// Submit it.
ASSERT_TRUE(tab->NavigateToURL(GURL(
"javascript:document.getElementById('form').submit()")));
// Try to reload it twice, checking for repost.
tab->ReloadAsync();
tab->ReloadAsync();
// Navigate away from the page (this is when the test usually crashes).
ASSERT_TRUE(tab->NavigateToURL(test_server.GetURL("bar")));
}
#if defined(OS_WIN)
// http://crbug.com/47228
#define MAYBE_TestLoginAfterRepost FLAKY_TestLoginAfterRepost
#else
#define MAYBE_TestLoginAfterRepost TestLoginAfterRepost
#endif
TEST_F(RepostFormWarningTest, MAYBE_TestLoginAfterRepost) {
net::TestServer test_server(net::TestServer::TYPE_HTTP, FilePath(kDocRoot));
ASSERT_TRUE(test_server.Start());
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
scoped_refptr<TabProxy> tab(browser->GetTab(0));
ASSERT_TRUE(tab.get());
// Load a form.
ASSERT_TRUE(tab->NavigateToURL(test_server.GetURL("files/form.html")));
// Submit it.
ASSERT_TRUE(tab->NavigateToURL(GURL(
"javascript:document.getElementById('form').submit()")));
// Try to reload it, checking for repost.
tab->ReloadAsync();
// Navigate to a page that requires authentication, bringing up another
// tab-modal sheet.
ASSERT_TRUE(tab->NavigateToURL(test_server.GetURL("auth-basic")));
// Try to reload it again.
tab->ReloadAsync();
// Navigate away from the page.
ASSERT_TRUE(tab->NavigateToURL(test_server.GetURL("bar")));
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/notifications/balloon_host.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/in_process_webkit/webkit_context.h"
#include "chrome/browser/extensions/extension_process_manager.h"
#include "chrome/browser/notifications/balloon.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/renderer_host/site_instance.h"
#include "chrome/browser/renderer_preferences_util.h"
#include "chrome/common/bindings_policy.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_type.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/renderer_preferences.h"
#include "chrome/common/url_constants.h"
BalloonHost::BalloonHost(Balloon* balloon)
: render_view_host_(NULL),
balloon_(balloon),
initialized_(false),
should_notify_on_disconnect_(false) {
DCHECK(balloon_);
// If the notification is for an extension URL, make sure to use the extension
// process to render it, so that it can communicate with other views in the
// extension.
const GURL& balloon_url = balloon_->notification().content_url();
if (balloon_url.SchemeIs(chrome::kExtensionScheme)) {
site_instance_ =
balloon_->profile()->GetExtensionProcessManager()->GetSiteInstanceForURL(
balloon_url);
} else {
site_instance_ = SiteInstance::CreateSiteInstance(balloon_->profile());
}
}
void BalloonHost::Shutdown() {
if (render_view_host_) {
NotifyDisconnect();
render_view_host_->Shutdown();
render_view_host_ = NULL;
}
}
WebPreferences BalloonHost::GetWebkitPrefs() {
WebPreferences prefs;
prefs.allow_scripts_to_close_windows = true;
return prefs;
}
void BalloonHost::Close(RenderViewHost* render_view_host) {
balloon_->CloseByScript();
}
void BalloonHost::RenderViewCreated(RenderViewHost* render_view_host) {
render_view_host->EnablePreferredSizeChangedMode(
kPreferredSizeWidth | kPreferredSizeHeightThisIsSlow);
}
void BalloonHost::RenderViewReady(RenderViewHost* render_view_host) {
should_notify_on_disconnect_ = true;
NotificationService::current()->Notify(
NotificationType::NOTIFY_BALLOON_CONNECTED,
Source<BalloonHost>(this), NotificationService::NoDetails());
}
void BalloonHost::RenderViewGone(RenderViewHost* render_view_host) {
Close(render_view_host);
}
void BalloonHost::ProcessDOMUIMessage(const std::string& message,
const ListValue* content,
const GURL& source_url,
int request_id,
bool has_callback) {
if (extension_function_dispatcher_.get()) {
extension_function_dispatcher_->HandleRequest(
message, content, source_url, request_id, has_callback);
}
}
// RenderViewHostDelegate::View methods implemented to allow links to
// open pages in new tabs.
void BalloonHost::CreateNewWindow(
int route_id,
WindowContainerType window_container_type,
const string16& frame_name) {
delegate_view_helper_.CreateNewWindow(
route_id,
balloon_->profile(),
site_instance_.get(),
DOMUIFactory::GetDOMUIType(balloon_->notification().content_url()),
this,
window_container_type,
frame_name);
}
void BalloonHost::ShowCreatedWindow(int route_id,
WindowOpenDisposition disposition,
const gfx::Rect& initial_pos,
bool user_gesture) {
// Don't allow pop-ups from notifications.
if (disposition == NEW_POPUP)
return;
TabContents* contents = delegate_view_helper_.GetCreatedWindow(route_id);
if (!contents)
return;
Browser* browser = BrowserList::GetLastActiveWithProfile(balloon_->profile());
if (!browser)
return;
browser->AddTabContents(contents, disposition, initial_pos, user_gesture);
}
void BalloonHost::UpdatePreferredSize(const gfx::Size& new_size) {
balloon_->SetContentPreferredSize(new_size);
}
RendererPreferences BalloonHost::GetRendererPrefs(Profile* profile) const {
RendererPreferences preferences;
renderer_preferences_util::UpdateFromSystemSettings(&preferences, profile);
return preferences;
}
void BalloonHost::Init() {
DCHECK(!render_view_host_) << "BalloonViewHost already initialized.";
int64 session_storage_namespace_id = balloon_->profile()->GetWebKitContext()->
dom_storage_context()->AllocateSessionStorageNamespaceId();
RenderViewHost* rvh = new RenderViewHost(site_instance_.get(),
this, MSG_ROUTING_NONE,
session_storage_namespace_id);
if (GetProfile()->GetExtensionsService()) {
extension_function_dispatcher_.reset(
ExtensionFunctionDispatcher::Create(
rvh, this, balloon_->notification().content_url()));
}
if (extension_function_dispatcher_.get()) {
rvh->AllowBindings(BindingsPolicy::EXTENSION);
rvh->set_is_extension_process(true);
}
// Do platform-specific initialization.
render_view_host_ = rvh;
InitRenderWidgetHostView();
DCHECK(render_widget_host_view());
rvh->set_view(render_widget_host_view());
rvh->CreateRenderView(GetProfile()->GetRequestContext(), string16());
rvh->NavigateToURL(balloon_->notification().content_url());
initialized_ = true;
}
void BalloonHost::NotifyDisconnect() {
if (!should_notify_on_disconnect_)
return;
should_notify_on_disconnect_ = false;
NotificationService::current()->Notify(
NotificationType::NOTIFY_BALLOON_DISCONNECTED,
Source<BalloonHost>(this), NotificationService::NoDetails());
}
<commit_msg>Fix shutdown crash by sending the close notification at a point earlier in the sequence when the NotificationService is still alive.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/notifications/balloon_host.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/in_process_webkit/webkit_context.h"
#include "chrome/browser/extensions/extension_process_manager.h"
#include "chrome/browser/notifications/balloon.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/renderer_host/site_instance.h"
#include "chrome/browser/renderer_preferences_util.h"
#include "chrome/common/bindings_policy.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_type.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/renderer_preferences.h"
#include "chrome/common/url_constants.h"
BalloonHost::BalloonHost(Balloon* balloon)
: render_view_host_(NULL),
balloon_(balloon),
initialized_(false),
should_notify_on_disconnect_(false) {
DCHECK(balloon_);
// If the notification is for an extension URL, make sure to use the extension
// process to render it, so that it can communicate with other views in the
// extension.
const GURL& balloon_url = balloon_->notification().content_url();
if (balloon_url.SchemeIs(chrome::kExtensionScheme)) {
site_instance_ =
balloon_->profile()->GetExtensionProcessManager()->GetSiteInstanceForURL(
balloon_url);
} else {
site_instance_ = SiteInstance::CreateSiteInstance(balloon_->profile());
}
}
void BalloonHost::Shutdown() {
if (render_view_host_) {
render_view_host_->Shutdown();
render_view_host_ = NULL;
}
}
WebPreferences BalloonHost::GetWebkitPrefs() {
WebPreferences prefs;
prefs.allow_scripts_to_close_windows = true;
return prefs;
}
void BalloonHost::Close(RenderViewHost* render_view_host) {
balloon_->CloseByScript();
NotifyDisconnect();
}
void BalloonHost::RenderViewCreated(RenderViewHost* render_view_host) {
render_view_host->EnablePreferredSizeChangedMode(
kPreferredSizeWidth | kPreferredSizeHeightThisIsSlow);
}
void BalloonHost::RenderViewReady(RenderViewHost* render_view_host) {
should_notify_on_disconnect_ = true;
NotificationService::current()->Notify(
NotificationType::NOTIFY_BALLOON_CONNECTED,
Source<BalloonHost>(this), NotificationService::NoDetails());
}
void BalloonHost::RenderViewGone(RenderViewHost* render_view_host) {
Close(render_view_host);
}
void BalloonHost::ProcessDOMUIMessage(const std::string& message,
const ListValue* content,
const GURL& source_url,
int request_id,
bool has_callback) {
if (extension_function_dispatcher_.get()) {
extension_function_dispatcher_->HandleRequest(
message, content, source_url, request_id, has_callback);
}
}
// RenderViewHostDelegate::View methods implemented to allow links to
// open pages in new tabs.
void BalloonHost::CreateNewWindow(
int route_id,
WindowContainerType window_container_type,
const string16& frame_name) {
delegate_view_helper_.CreateNewWindow(
route_id,
balloon_->profile(),
site_instance_.get(),
DOMUIFactory::GetDOMUIType(balloon_->notification().content_url()),
this,
window_container_type,
frame_name);
}
void BalloonHost::ShowCreatedWindow(int route_id,
WindowOpenDisposition disposition,
const gfx::Rect& initial_pos,
bool user_gesture) {
// Don't allow pop-ups from notifications.
if (disposition == NEW_POPUP)
return;
TabContents* contents = delegate_view_helper_.GetCreatedWindow(route_id);
if (!contents)
return;
Browser* browser = BrowserList::GetLastActiveWithProfile(balloon_->profile());
if (!browser)
return;
browser->AddTabContents(contents, disposition, initial_pos, user_gesture);
}
void BalloonHost::UpdatePreferredSize(const gfx::Size& new_size) {
balloon_->SetContentPreferredSize(new_size);
}
RendererPreferences BalloonHost::GetRendererPrefs(Profile* profile) const {
RendererPreferences preferences;
renderer_preferences_util::UpdateFromSystemSettings(&preferences, profile);
return preferences;
}
void BalloonHost::Init() {
DCHECK(!render_view_host_) << "BalloonViewHost already initialized.";
int64 session_storage_namespace_id = balloon_->profile()->GetWebKitContext()->
dom_storage_context()->AllocateSessionStorageNamespaceId();
RenderViewHost* rvh = new RenderViewHost(site_instance_.get(),
this, MSG_ROUTING_NONE,
session_storage_namespace_id);
if (GetProfile()->GetExtensionsService()) {
extension_function_dispatcher_.reset(
ExtensionFunctionDispatcher::Create(
rvh, this, balloon_->notification().content_url()));
}
if (extension_function_dispatcher_.get()) {
rvh->AllowBindings(BindingsPolicy::EXTENSION);
rvh->set_is_extension_process(true);
}
// Do platform-specific initialization.
render_view_host_ = rvh;
InitRenderWidgetHostView();
DCHECK(render_widget_host_view());
rvh->set_view(render_widget_host_view());
rvh->CreateRenderView(GetProfile()->GetRequestContext(), string16());
rvh->NavigateToURL(balloon_->notification().content_url());
initialized_ = true;
}
void BalloonHost::NotifyDisconnect() {
if (!should_notify_on_disconnect_)
return;
should_notify_on_disconnect_ = false;
NotificationService::current()->Notify(
NotificationType::NOTIFY_BALLOON_DISCONNECTED,
Source<BalloonHost>(this), NotificationService::NoDetails());
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <optional>
#include <vector>
#include "query-request.hh"
#include "schema_fwd.hh"
//
// Fluent builder for query::partition_slice.
//
// Selects everything by default, unless restricted. Each property can be
// restricted separately. For example, by default all static columns are
// selected, but if with_static_column() is called then only that column will
// be included. Still, all regular columns and the whole clustering range will
// be selected (unless restricted).
//
class partition_slice_builder {
std::optional<query::column_id_vector> _regular_columns;
std::optional<query::column_id_vector> _static_columns;
std::optional<std::vector<query::clustering_range>> _row_ranges;
const schema& _schema;
query::partition_slice::option_set _options;
public:
partition_slice_builder(const schema& schema);
partition_slice_builder& with_static_column(bytes name);
partition_slice_builder& with_no_static_columns();
partition_slice_builder& with_regular_column(bytes name);
partition_slice_builder& with_no_regular_columns();
partition_slice_builder& with_range(query::clustering_range range);
partition_slice_builder& with_ranges(std::vector<query::clustering_range>);
partition_slice_builder& without_partition_key_columns();
partition_slice_builder& without_clustering_key_columns();
partition_slice_builder& reversed();
query::partition_slice build();
};
<commit_msg>partition_slice_builder: add with_option()<commit_after>/*
* Copyright (C) 2015 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <optional>
#include <vector>
#include "query-request.hh"
#include "schema_fwd.hh"
//
// Fluent builder for query::partition_slice.
//
// Selects everything by default, unless restricted. Each property can be
// restricted separately. For example, by default all static columns are
// selected, but if with_static_column() is called then only that column will
// be included. Still, all regular columns and the whole clustering range will
// be selected (unless restricted).
//
class partition_slice_builder {
std::optional<query::column_id_vector> _regular_columns;
std::optional<query::column_id_vector> _static_columns;
std::optional<std::vector<query::clustering_range>> _row_ranges;
const schema& _schema;
query::partition_slice::option_set _options;
public:
partition_slice_builder(const schema& schema);
partition_slice_builder& with_static_column(bytes name);
partition_slice_builder& with_no_static_columns();
partition_slice_builder& with_regular_column(bytes name);
partition_slice_builder& with_no_regular_columns();
partition_slice_builder& with_range(query::clustering_range range);
partition_slice_builder& with_ranges(std::vector<query::clustering_range>);
partition_slice_builder& without_partition_key_columns();
partition_slice_builder& without_clustering_key_columns();
partition_slice_builder& reversed();
template <query::partition_slice::option OPTION>
partition_slice_builder& with_option() {
_options.set<OPTION>();
return *this;
}
query::partition_slice build();
};
<|endoftext|> |
<commit_before>/**
* Appcelerator Kroll - licensed under the Apache Public License 2
* see LICENSE in the root folder for details on the license.
* Copyright (c) 2008 Appcelerator, Inc. All Rights Reserved.
*/
#include "ruby_module.h"
namespace kroll {
KRubyObject::KRubyObject(VALUE object) :
object(object)
{
rb_gc_register_address(&object);
}
KRubyObject::~KRubyObject()
{
rb_gc_unregister_address(&object);
}
VALUE kobj_do_method_missing_call(VALUE args)
{
VALUE object = rb_ary_shift(args);
return rb_apply(object, rb_intern("method_missing"), args);
}
void KRubyObject::Set(const char *name, SharedValue value)
{
VALUE ruby_value = RubyUtils::ToRubyValue(value);
std::string setter_name = std::string(name) + "=";
ID set_ID = rb_intern(setter_name.c_str());
int error = 0;
if (rb_obj_respond_to(object, set_ID, Qtrue) == Qtrue)
{
rb_funcall(object, set_ID, 1, ruby_value);
}
else
{
// First try calling method missing
VALUE rargs = rb_ary_new();
rb_ary_push(rargs, object);
rb_ary_push(rargs, rb_str_new2(name));
rb_ary_push(rargs, ruby_value);
rb_protect(kobj_do_method_missing_call, rargs, &error);
}
// Last resort: set an instance variable
if (error != 0)
{
std::string iv_name = std::string("@") + name;
rb_iv_set(object, iv_name.c_str(), ruby_value);
}
}
SharedValue KRubyObject::Get(const char *name)
{
std::string iv_name = std::string("@") + name;
ID iv_ID = rb_intern(iv_name.c_str());
ID get_ID = rb_intern(name);
ID mm_ID = rb_intern("method_missing");
//int error = 0;
VALUE ruby_value = Qnil;
if (rb_obj_respond_to(object, get_ID, Qtrue) == Qtrue)
{
/*VALUE rmeth =*/
rb_funcall(object, rb_intern("method"), 1, ID2SYM(get_ID));
ruby_value = rb_funcall(object, get_ID, 1, ruby_value);
}
else if (rb_ivar_defined(object, iv_ID))
{
ruby_value = rb_ivar_get(object, iv_ID);
}
else if (rb_obj_respond_to(object, mm_ID, Qtrue) == Qtrue)
{
// If this object has a method_missing, return that
VALUE rmeth = rb_funcall(object, mm_ID, 1, ID2SYM(get_ID));
return Value::NewMethod(new KRubyMethod(rmeth, get_ID));
}
return RubyUtils::ToKrollValue(ruby_value);
}
SharedString KRubyObject::DisplayString(int levels)
{
VALUE out = rb_obj_as_string(object);
return new std::string(RubyUtils::ToString(out));
}
SharedStringList KRubyObject::GetPropertyNames()
{
SharedStringList names(new StringList());
VALUE vars = rb_obj_instance_variables(rb_obj_class(object));
for (int i = 0; i < RARRAY(vars)->len; i++)
{
VALUE prop_name = rb_ary_entry(vars, i);
std::string name = RubyUtils::ToString(prop_name);
names->push_back(new std::string(name));
}
VALUE methods = rb_funcall(object, rb_intern("methods"), 0);
for (int i = 0; i < RARRAY(vars)->len; i++)
{
VALUE meth_name = rb_ary_entry(methods, i);
std::string name = RubyUtils::ToString(meth_name);
names->push_back(new std::string(name));
}
return names;
}
VALUE KRubyObject::ToRuby()
{
return this->object;
}
}
<commit_msg>Removed unused variable<commit_after>/**
* Appcelerator Kroll - licensed under the Apache Public License 2
* see LICENSE in the root folder for details on the license.
* Copyright (c) 2008 Appcelerator, Inc. All Rights Reserved.
*/
#include "ruby_module.h"
namespace kroll {
KRubyObject::KRubyObject(VALUE object) :
object(object)
{
rb_gc_register_address(&object);
}
KRubyObject::~KRubyObject()
{
rb_gc_unregister_address(&object);
}
VALUE kobj_do_method_missing_call(VALUE args)
{
VALUE object = rb_ary_shift(args);
return rb_apply(object, rb_intern("method_missing"), args);
}
void KRubyObject::Set(const char *name, SharedValue value)
{
VALUE ruby_value = RubyUtils::ToRubyValue(value);
std::string setter_name = std::string(name) + "=";
ID set_ID = rb_intern(setter_name.c_str());
int error = 0;
if (rb_obj_respond_to(object, set_ID, Qtrue) == Qtrue)
{
rb_funcall(object, set_ID, 1, ruby_value);
}
else
{
// First try calling method missing
VALUE rargs = rb_ary_new();
rb_ary_push(rargs, object);
rb_ary_push(rargs, rb_str_new2(name));
rb_ary_push(rargs, ruby_value);
rb_protect(kobj_do_method_missing_call, rargs, &error);
}
// Last resort: set an instance variable
if (error != 0)
{
std::string iv_name = std::string("@") + name;
rb_iv_set(object, iv_name.c_str(), ruby_value);
}
}
SharedValue KRubyObject::Get(const char *name)
{
std::string iv_name = std::string("@") + name;
ID iv_ID = rb_intern(iv_name.c_str());
ID get_ID = rb_intern(name);
ID mm_ID = rb_intern("method_missing");
VALUE ruby_value = Qnil;
if (rb_obj_respond_to(object, get_ID, Qtrue) == Qtrue)
{
/*VALUE rmeth =*/
rb_funcall(object, rb_intern("method"), 1, ID2SYM(get_ID));
ruby_value = rb_funcall(object, get_ID, 1, ruby_value);
}
else if (rb_ivar_defined(object, iv_ID))
{
ruby_value = rb_ivar_get(object, iv_ID);
}
else if (rb_obj_respond_to(object, mm_ID, Qtrue) == Qtrue)
{
// If this object has a method_missing, return that
VALUE rmeth = rb_funcall(object, mm_ID, 1, ID2SYM(get_ID));
return Value::NewMethod(new KRubyMethod(rmeth, get_ID));
}
return RubyUtils::ToKrollValue(ruby_value);
}
SharedString KRubyObject::DisplayString(int levels)
{
VALUE out = rb_obj_as_string(object);
return new std::string(RubyUtils::ToString(out));
}
SharedStringList KRubyObject::GetPropertyNames()
{
SharedStringList names(new StringList());
VALUE vars = rb_obj_instance_variables(rb_obj_class(object));
for (int i = 0; i < RARRAY(vars)->len; i++)
{
VALUE prop_name = rb_ary_entry(vars, i);
std::string name = RubyUtils::ToString(prop_name);
names->push_back(new std::string(name));
}
VALUE methods = rb_funcall(object, rb_intern("methods"), 0);
for (int i = 0; i < RARRAY(vars)->len; i++)
{
VALUE meth_name = rb_ary_entry(methods, i);
std::string name = RubyUtils::ToString(meth_name);
names->push_back(new std::string(name));
}
return names;
}
VALUE KRubyObject::ToRuby()
{
return this->object;
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/views/about_network_dialog.h"
#include "base/string_util.h"
#include "base/thread.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/views/standard_layout.h"
#include "chrome/views/grid_layout.h"
#include "chrome/views/controls/button/text_button.h"
#include "chrome/views/controls/text_field.h"
#include "chrome/views/window/window.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_job.h"
#include "net/url_request/url_request_job_tracker.h"
namespace {
// We don't localize this UI since this is a developer-only feature.
const wchar_t kStartTrackingLabel[] = L"Start tracking";
const wchar_t kStopTrackingLabel[] = L"Stop tracking";
const wchar_t kShowCurrentLabel[] = L"Show Current";
const wchar_t kClearLabel[] = L"Clear";
// The singleton dialog box. This is non-NULL when a dialog is active so we
// know not to create a new one.
AboutNetworkDialog* active_dialog = NULL;
// Returns a string representing the URL, handling the case where the spec
// is invalid.
std::wstring StringForURL(const GURL& url) {
if (url.is_valid())
return UTF8ToWide(url.spec());
return UTF8ToWide(url.possibly_invalid_spec()) + L" (invalid)";
}
std::wstring URLForJob(URLRequestJob* job) {
URLRequest* request = job->request();
if (request)
return StringForURL(request->url());
return std::wstring(L"(orphaned)");
}
// JobTracker ------------------------------------------------------------------
// A JobTracker is allocated to monitor network jobs running on the IO
// thread. This allows the NetworkStatusView to remain single-threaded.
class JobTracker : public URLRequestJobTracker::JobObserver,
public base::RefCountedThreadSafe<JobTracker> {
public:
JobTracker(AboutNetworkDialog* view);
~JobTracker();
// Called by the NetworkStatusView on the main application thread.
void StartTracking();
void StopTracking();
void ReportStatus();
// URLRequestJobTracker::JobObserver methods (called on the IO thread):
virtual void OnJobAdded(URLRequestJob* job);
virtual void OnJobRemoved(URLRequestJob* job);
virtual void OnJobDone(URLRequestJob* job, const URLRequestStatus& status);
virtual void OnJobRedirect(URLRequestJob* job, const GURL& location,
int status_code);
virtual void OnBytesRead(URLRequestJob* job, int byte_count);
// The JobTracker may be deleted after NetworkStatusView is deleted.
void DetachView() { view_ = NULL; }
private:
void InvokeOnIOThread(void (JobTracker::*method)());
// Called on the IO thread
void OnStartTracking();
void OnStopTracking();
void OnReportStatus();
void AppendText(const std::wstring& text);
// Called on the main thread
void OnAppendText(const std::wstring& text);
AboutNetworkDialog* view_;
MessageLoop* view_message_loop_;
};
// main thread:
JobTracker::JobTracker(AboutNetworkDialog* view)
: view_(view),
view_message_loop_(MessageLoop::current()) {
}
JobTracker::~JobTracker() {
}
// main thread:
void JobTracker::InvokeOnIOThread(void (JobTracker::*m)()) {
base::Thread* thread = g_browser_process->io_thread();
if (!thread)
return;
thread->message_loop()->PostTask(FROM_HERE, NewRunnableMethod(this, m));
}
// main thread:
void JobTracker::StartTracking() {
DCHECK(MessageLoop::current() == view_message_loop_);
DCHECK(view_);
InvokeOnIOThread(&JobTracker::OnStartTracking);
}
// main thread:
void JobTracker::StopTracking() {
DCHECK(MessageLoop::current() == view_message_loop_);
// The tracker should not be deleted before it is removed from observer
// list.
AddRef();
InvokeOnIOThread(&JobTracker::OnStopTracking);
}
// main thread:
void JobTracker::ReportStatus() {
DCHECK(MessageLoop::current() == view_message_loop_);
InvokeOnIOThread(&JobTracker::OnReportStatus);
}
// main thread:
void JobTracker::OnAppendText(const std::wstring& text) {
DCHECK(MessageLoop::current() == view_message_loop_);
if (view_ && view_->tracking())
view_->AppendText(text);
}
// IO thread:
void JobTracker::AppendText(const std::wstring& text) {
DCHECK(MessageLoop::current() != view_message_loop_);
view_message_loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &JobTracker::OnAppendText, text));
}
// IO thread:
void JobTracker::OnStartTracking() {
DCHECK(MessageLoop::current() != view_message_loop_);
g_url_request_job_tracker.AddObserver(this);
}
// IO thread:
void JobTracker::OnStopTracking() {
DCHECK(MessageLoop::current() != view_message_loop_);
g_url_request_job_tracker.RemoveObserver(this);
// Balance the AddRef() in StopTracking() called in main thread.
Release();
}
// IO thread:
void JobTracker::OnReportStatus() {
DCHECK(MessageLoop::current() != view_message_loop_);
std::wstring text(L"\r\n===== Active Job Summary =====\r\n");
URLRequestJobTracker::JobIterator begin_job =
g_url_request_job_tracker.begin();
URLRequestJobTracker::JobIterator end_job = g_url_request_job_tracker.end();
int orphaned_count = 0;
int regular_count = 0;
for (URLRequestJobTracker::JobIterator cur = begin_job;
cur != end_job; ++cur) {
URLRequestJob* job = (*cur);
URLRequest* request = job->request();
if (!request) {
orphaned_count++;
continue;
}
regular_count++;
// active state
if (job->is_done())
text.append(L" Done: ");
else
text.append(L" Active: ");
// URL
text.append(StringForURL(request->url()));
text.append(L"\r\n");
}
if (regular_count == 0)
text.append(L" (No active jobs)\r\n");
if (orphaned_count) {
wchar_t buf[64];
swprintf(buf, arraysize(buf), L" %d orphaned jobs\r\n", orphaned_count);
text.append(buf);
}
text.append(L"=====\r\n\r\n");
AppendText(text);
}
// IO thread:
void JobTracker::OnJobAdded(URLRequestJob* job) {
DCHECK(MessageLoop::current() != view_message_loop_);
std::wstring text(L"+ New job : ");
text.append(URLForJob(job));
text.append(L"\r\n");
AppendText(text);
}
// IO thread:
void JobTracker::OnJobRemoved(URLRequestJob* job) {
DCHECK(MessageLoop::current() != view_message_loop_);
}
// IO thread:
void JobTracker::OnJobDone(URLRequestJob* job,
const URLRequestStatus& status) {
DCHECK(MessageLoop::current() != view_message_loop_);
std::wstring text;
if (status.is_success()) {
text.assign(L"- Complete: ");
} else if (status.status() == URLRequestStatus::CANCELED) {
text.assign(L"- Canceled: ");
} else if (status.status() == URLRequestStatus::HANDLED_EXTERNALLY) {
text.assign(L"- Handled externally: ");
} else {
wchar_t buf[32];
swprintf(buf, arraysize(buf), L"Failed with %d: ", status.os_error());
text.assign(buf);
}
text.append(URLForJob(job));
text.append(L"\r\n");
AppendText(text);
}
// IO thread:
void JobTracker::OnJobRedirect(URLRequestJob* job,
const GURL& location,
int status_code) {
DCHECK(MessageLoop::current() != view_message_loop_);
std::wstring text(L"- Redirect: ");
text.append(URLForJob(job));
text.append(L"\r\n ");
wchar_t buf[16];
swprintf(buf, arraysize(buf), L"(%d) to: ", status_code);
text.append(buf);
text.append(StringForURL(location));
text.append(L"\r\n");
AppendText(text);
}
void JobTracker::OnBytesRead(URLRequestJob* job, int byte_count) {
}
// The singleton job tracker associated with the dialog.
JobTracker* tracker = NULL;
} // namespace
// AboutNetworkDialog ----------------------------------------------------------
AboutNetworkDialog::AboutNetworkDialog() : tracking_(false) {
SetupControls();
tracker = new JobTracker(this);
tracker->AddRef();
}
AboutNetworkDialog::~AboutNetworkDialog() {
active_dialog = NULL;
tracker->Release();
tracker = NULL;
}
// static
void AboutNetworkDialog::RunDialog() {
if (!active_dialog) {
active_dialog = new AboutNetworkDialog;
views::Window::CreateChromeWindow(NULL, gfx::Rect(), active_dialog)->Show();
} else {
// TOOD(brettw) it would be nice to focus the existing window.
}
}
void AboutNetworkDialog::AppendText(const std::wstring& text) {
text_field_->AppendText(text);
}
void AboutNetworkDialog::SetupControls() {
views::GridLayout* layout = CreatePanelGridLayout(this);
SetLayoutManager(layout);
track_toggle_ = new views::TextButton(this, kStartTrackingLabel);
show_button_ = new views::TextButton(this, kShowCurrentLabel);
clear_button_ = new views::TextButton(this, kClearLabel);
text_field_ = new views::TextField(static_cast<views::TextField::StyleFlags>(
views::TextField::STYLE_MULTILINE));
text_field_->SetReadOnly(true);
// TODO(brettw): We may want to add this in the future. It can't be called
// from here, though, since the hwnd for the field hasn't been created yet.
//
// This raises the maximum number of chars from 32K to some large maximum,
// probably 2GB. 32K is not nearly enough for our use-case.
//SendMessageW(text_field_->GetNativeComponent(), EM_SETLIMITTEXT, 0, 0);
static const int first_column_set = 1;
views::ColumnSet* column_set = layout->AddColumnSet(first_column_set);
column_set->AddColumn(views::GridLayout::CENTER, views::GridLayout::CENTER,
33.33f, views::GridLayout::FIXED, 0, 0);
column_set->AddColumn(views::GridLayout::CENTER, views::GridLayout::CENTER,
33.33f, views::GridLayout::FIXED, 0, 0);
column_set->AddColumn(views::GridLayout::CENTER, views::GridLayout::CENTER,
33.33f, views::GridLayout::FIXED, 0, 0);
static const int text_column_set = 2;
column_set = layout->AddColumnSet(text_column_set);
column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL,
100.0f,
views::GridLayout::FIXED, 0, 0);
layout->StartRow(0, first_column_set);
layout->AddView(track_toggle_);
layout->AddView(show_button_);
layout->AddView(clear_button_);
layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
layout->StartRow(1.0f, text_column_set);
layout->AddView(text_field_);
}
gfx::Size AboutNetworkDialog::GetPreferredSize() {
return gfx::Size(800, 400);
}
views::View* AboutNetworkDialog::GetContentsView() {
return this;
}
int AboutNetworkDialog::GetDialogButtons() const {
// Don't want OK or Cancel.
return 0;
}
std::wstring AboutNetworkDialog::GetWindowTitle() const {
return L"about:network";
}
bool AboutNetworkDialog::CanResize() const {
return true;
}
void AboutNetworkDialog::ButtonPressed(views::Button* button) {
if (button == track_toggle_) {
if (tracking_) {
track_toggle_->SetText(kStartTrackingLabel);
tracking_ = false;
tracker->StopTracking();
} else {
track_toggle_->SetText(kStopTrackingLabel);
tracking_ = true;
tracker->StartTracking();
}
track_toggle_->SchedulePaint();
} else if (button == show_button_) {
tracker->ReportStatus();
} else if (button == clear_button_) {
text_field_->SetText(std::wstring());
}
}
<commit_msg>Fix crash that occurs when the about:network window is closed while still tracking network jobs.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/views/about_network_dialog.h"
#include "base/string_util.h"
#include "base/thread.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/views/standard_layout.h"
#include "chrome/views/grid_layout.h"
#include "chrome/views/controls/button/text_button.h"
#include "chrome/views/controls/text_field.h"
#include "chrome/views/window/window.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_job.h"
#include "net/url_request/url_request_job_tracker.h"
namespace {
// We don't localize this UI since this is a developer-only feature.
const wchar_t kStartTrackingLabel[] = L"Start tracking";
const wchar_t kStopTrackingLabel[] = L"Stop tracking";
const wchar_t kShowCurrentLabel[] = L"Show Current";
const wchar_t kClearLabel[] = L"Clear";
// The singleton dialog box. This is non-NULL when a dialog is active so we
// know not to create a new one.
AboutNetworkDialog* active_dialog = NULL;
// Returns a string representing the URL, handling the case where the spec
// is invalid.
std::wstring StringForURL(const GURL& url) {
if (url.is_valid())
return UTF8ToWide(url.spec());
return UTF8ToWide(url.possibly_invalid_spec()) + L" (invalid)";
}
std::wstring URLForJob(URLRequestJob* job) {
URLRequest* request = job->request();
if (request)
return StringForURL(request->url());
return std::wstring(L"(orphaned)");
}
// JobTracker ------------------------------------------------------------------
// A JobTracker is allocated to monitor network jobs running on the IO
// thread. This allows the NetworkStatusView to remain single-threaded.
class JobTracker : public URLRequestJobTracker::JobObserver,
public base::RefCountedThreadSafe<JobTracker> {
public:
JobTracker(AboutNetworkDialog* view);
~JobTracker();
// Called by the NetworkStatusView on the main application thread.
void StartTracking();
void StopTracking();
void ReportStatus();
// URLRequestJobTracker::JobObserver methods (called on the IO thread):
virtual void OnJobAdded(URLRequestJob* job);
virtual void OnJobRemoved(URLRequestJob* job);
virtual void OnJobDone(URLRequestJob* job, const URLRequestStatus& status);
virtual void OnJobRedirect(URLRequestJob* job, const GURL& location,
int status_code);
virtual void OnBytesRead(URLRequestJob* job, int byte_count);
// The JobTracker may be deleted after NetworkStatusView is deleted.
void DetachView() { view_ = NULL; }
private:
void InvokeOnIOThread(void (JobTracker::*method)());
// Called on the IO thread
void OnStartTracking();
void OnStopTracking();
void OnReportStatus();
void AppendText(const std::wstring& text);
// Called on the main thread
void OnAppendText(const std::wstring& text);
AboutNetworkDialog* view_;
MessageLoop* view_message_loop_;
};
// main thread:
JobTracker::JobTracker(AboutNetworkDialog* view)
: view_(view),
view_message_loop_(MessageLoop::current()) {
}
JobTracker::~JobTracker() {
}
// main thread:
void JobTracker::InvokeOnIOThread(void (JobTracker::*m)()) {
base::Thread* thread = g_browser_process->io_thread();
if (!thread)
return;
thread->message_loop()->PostTask(FROM_HERE, NewRunnableMethod(this, m));
}
// main thread:
void JobTracker::StartTracking() {
DCHECK(MessageLoop::current() == view_message_loop_);
DCHECK(view_);
InvokeOnIOThread(&JobTracker::OnStartTracking);
}
// main thread:
void JobTracker::StopTracking() {
DCHECK(MessageLoop::current() == view_message_loop_);
// The tracker should not be deleted before it is removed from observer
// list.
AddRef();
InvokeOnIOThread(&JobTracker::OnStopTracking);
}
// main thread:
void JobTracker::ReportStatus() {
DCHECK(MessageLoop::current() == view_message_loop_);
InvokeOnIOThread(&JobTracker::OnReportStatus);
}
// main thread:
void JobTracker::OnAppendText(const std::wstring& text) {
DCHECK(MessageLoop::current() == view_message_loop_);
if (view_ && view_->tracking())
view_->AppendText(text);
}
// IO thread:
void JobTracker::AppendText(const std::wstring& text) {
DCHECK(MessageLoop::current() != view_message_loop_);
view_message_loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &JobTracker::OnAppendText, text));
}
// IO thread:
void JobTracker::OnStartTracking() {
DCHECK(MessageLoop::current() != view_message_loop_);
g_url_request_job_tracker.AddObserver(this);
}
// IO thread:
void JobTracker::OnStopTracking() {
DCHECK(MessageLoop::current() != view_message_loop_);
g_url_request_job_tracker.RemoveObserver(this);
// Balance the AddRef() in StopTracking() called in main thread.
Release();
}
// IO thread:
void JobTracker::OnReportStatus() {
DCHECK(MessageLoop::current() != view_message_loop_);
std::wstring text(L"\r\n===== Active Job Summary =====\r\n");
URLRequestJobTracker::JobIterator begin_job =
g_url_request_job_tracker.begin();
URLRequestJobTracker::JobIterator end_job = g_url_request_job_tracker.end();
int orphaned_count = 0;
int regular_count = 0;
for (URLRequestJobTracker::JobIterator cur = begin_job;
cur != end_job; ++cur) {
URLRequestJob* job = (*cur);
URLRequest* request = job->request();
if (!request) {
orphaned_count++;
continue;
}
regular_count++;
// active state
if (job->is_done())
text.append(L" Done: ");
else
text.append(L" Active: ");
// URL
text.append(StringForURL(request->url()));
text.append(L"\r\n");
}
if (regular_count == 0)
text.append(L" (No active jobs)\r\n");
if (orphaned_count) {
wchar_t buf[64];
swprintf(buf, arraysize(buf), L" %d orphaned jobs\r\n", orphaned_count);
text.append(buf);
}
text.append(L"=====\r\n\r\n");
AppendText(text);
}
// IO thread:
void JobTracker::OnJobAdded(URLRequestJob* job) {
DCHECK(MessageLoop::current() != view_message_loop_);
std::wstring text(L"+ New job : ");
text.append(URLForJob(job));
text.append(L"\r\n");
AppendText(text);
}
// IO thread:
void JobTracker::OnJobRemoved(URLRequestJob* job) {
DCHECK(MessageLoop::current() != view_message_loop_);
}
// IO thread:
void JobTracker::OnJobDone(URLRequestJob* job,
const URLRequestStatus& status) {
DCHECK(MessageLoop::current() != view_message_loop_);
std::wstring text;
if (status.is_success()) {
text.assign(L"- Complete: ");
} else if (status.status() == URLRequestStatus::CANCELED) {
text.assign(L"- Canceled: ");
} else if (status.status() == URLRequestStatus::HANDLED_EXTERNALLY) {
text.assign(L"- Handled externally: ");
} else {
wchar_t buf[32];
swprintf(buf, arraysize(buf), L"Failed with %d: ", status.os_error());
text.assign(buf);
}
text.append(URLForJob(job));
text.append(L"\r\n");
AppendText(text);
}
// IO thread:
void JobTracker::OnJobRedirect(URLRequestJob* job,
const GURL& location,
int status_code) {
DCHECK(MessageLoop::current() != view_message_loop_);
std::wstring text(L"- Redirect: ");
text.append(URLForJob(job));
text.append(L"\r\n ");
wchar_t buf[16];
swprintf(buf, arraysize(buf), L"(%d) to: ", status_code);
text.append(buf);
text.append(StringForURL(location));
text.append(L"\r\n");
AppendText(text);
}
void JobTracker::OnBytesRead(URLRequestJob* job, int byte_count) {
}
// The singleton job tracker associated with the dialog.
JobTracker* tracker = NULL;
} // namespace
// AboutNetworkDialog ----------------------------------------------------------
AboutNetworkDialog::AboutNetworkDialog() : tracking_(false) {
SetupControls();
tracker = new JobTracker(this);
tracker->AddRef();
}
AboutNetworkDialog::~AboutNetworkDialog() {
active_dialog = NULL;
tracker->StopTracking();
tracker->Release();
tracker = NULL;
}
// static
void AboutNetworkDialog::RunDialog() {
if (!active_dialog) {
active_dialog = new AboutNetworkDialog;
views::Window::CreateChromeWindow(NULL, gfx::Rect(), active_dialog)->Show();
} else {
// TOOD(brettw) it would be nice to focus the existing window.
}
}
void AboutNetworkDialog::AppendText(const std::wstring& text) {
text_field_->AppendText(text);
}
void AboutNetworkDialog::SetupControls() {
views::GridLayout* layout = CreatePanelGridLayout(this);
SetLayoutManager(layout);
track_toggle_ = new views::TextButton(this, kStartTrackingLabel);
show_button_ = new views::TextButton(this, kShowCurrentLabel);
clear_button_ = new views::TextButton(this, kClearLabel);
text_field_ = new views::TextField(static_cast<views::TextField::StyleFlags>(
views::TextField::STYLE_MULTILINE));
text_field_->SetReadOnly(true);
// TODO(brettw): We may want to add this in the future. It can't be called
// from here, though, since the hwnd for the field hasn't been created yet.
//
// This raises the maximum number of chars from 32K to some large maximum,
// probably 2GB. 32K is not nearly enough for our use-case.
//SendMessageW(text_field_->GetNativeComponent(), EM_SETLIMITTEXT, 0, 0);
static const int first_column_set = 1;
views::ColumnSet* column_set = layout->AddColumnSet(first_column_set);
column_set->AddColumn(views::GridLayout::CENTER, views::GridLayout::CENTER,
33.33f, views::GridLayout::FIXED, 0, 0);
column_set->AddColumn(views::GridLayout::CENTER, views::GridLayout::CENTER,
33.33f, views::GridLayout::FIXED, 0, 0);
column_set->AddColumn(views::GridLayout::CENTER, views::GridLayout::CENTER,
33.33f, views::GridLayout::FIXED, 0, 0);
static const int text_column_set = 2;
column_set = layout->AddColumnSet(text_column_set);
column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL,
100.0f,
views::GridLayout::FIXED, 0, 0);
layout->StartRow(0, first_column_set);
layout->AddView(track_toggle_);
layout->AddView(show_button_);
layout->AddView(clear_button_);
layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
layout->StartRow(1.0f, text_column_set);
layout->AddView(text_field_);
}
gfx::Size AboutNetworkDialog::GetPreferredSize() {
return gfx::Size(800, 400);
}
views::View* AboutNetworkDialog::GetContentsView() {
return this;
}
int AboutNetworkDialog::GetDialogButtons() const {
// Don't want OK or Cancel.
return 0;
}
std::wstring AboutNetworkDialog::GetWindowTitle() const {
return L"about:network";
}
bool AboutNetworkDialog::CanResize() const {
return true;
}
void AboutNetworkDialog::ButtonPressed(views::Button* button) {
if (button == track_toggle_) {
if (tracking_) {
track_toggle_->SetText(kStartTrackingLabel);
tracking_ = false;
tracker->StopTracking();
} else {
track_toggle_->SetText(kStopTrackingLabel);
tracking_ = true;
tracker->StartTracking();
}
track_toggle_->SchedulePaint();
} else if (button == show_button_) {
tracker->ReportStatus();
} else if (button == clear_button_) {
text_field_->SetText(std::wstring());
}
}
<|endoftext|> |
<commit_before>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
* (C) 2019 Eddie Hung <eddie@fpgeh.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "kernel/yosys.h"
#include "kernel/sigtools.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
// for peepopt_pm
bool did_something;
#include "passes/pmgen/xilinx_srl_pm.h"
#include "passes/pmgen/ice40_dsp_pm.h"
#include "passes/pmgen/peepopt_pm.h"
void run_fixed(xilinx_srl_pm &pm)
{
auto &st = pm.st_fixed;
auto &ud = pm.ud_fixed;
auto param_def = [&ud](Cell *cell, IdString param) {
auto def = ud.default_params.at(std::make_pair(cell->type,param));
return cell->parameters.at(param, def);
};
log("Found fixed chain of length %d (%s):\n", GetSize(ud.longest_chain), log_id(st.first->type));
auto first_cell = ud.longest_chain.back();
SigSpec initval;
for (auto cell : ud.longest_chain) {
log_debug(" %s\n", log_id(cell));
if (cell->type.in(ID($_DFF_N_), ID($_DFF_P_), ID($_DFFE_NN_), ID($_DFFE_NP_), ID($_DFFE_PN_), ID($_DFFE_PP_))) {
SigBit Q = cell->getPort(ID(Q));
log_assert(Q.wire);
auto it = Q.wire->attributes.find(ID(init));
if (it != Q.wire->attributes.end()) {
auto &i = it->second[Q.offset];
initval.append(i);
i = State::Sx;
}
else
initval.append(State::Sx);
}
else if (cell->type.in(ID(FDRE), ID(FDRE_1)))
initval.append(param_def(cell, ID(INIT)));
else
log_abort();
if (cell != first_cell)
pm.autoremove(cell);
}
Cell *c = first_cell;
SigBit Q = st.first->getPort(ID(Q));
c->setPort(ID(Q), Q);
if (c->type.in(ID($_DFF_N_), ID($_DFF_P_), ID($_DFFE_NN_), ID($_DFFE_NP_), ID($_DFFE_PN_), ID($_DFFE_PP_), ID(FDRE), ID(FDRE_1))) {
c->parameters.clear();
c->setParam(ID(DEPTH), GetSize(ud.longest_chain));
c->setParam(ID(INIT), initval.as_const());
if (c->type.in(ID($_DFF_P_), ID($_DFFE_PN_), ID($_DFFE_PP_)))
c->setParam(ID(CLKPOL), 1);
else if (c->type.in(ID($_DFF_N_), ID($DFFE_NN_), ID($_DFFE_NP_), ID(FDRE_1)))
c->setParam(ID(CLKPOL), 0);
else if (c->type.in(ID(FDRE)))
c->setParam(ID(CLKPOL), param_def(c, ID(IS_C_INVERTED)).as_bool() ? 0 : 1);
else
log_abort();
if (c->type.in(ID($_DFFE_NP_), ID($_DFFE_PP_)))
c->setParam(ID(ENPOL), 1);
else if (c->type.in(ID($_DFFE_NN_), ID($_DFFE_PN_)))
c->setParam(ID(ENPOL), 0);
else
c->setParam(ID(ENPOL), 2);
if (c->type.in(ID($_DFF_N_), ID($_DFF_P_)))
c->setPort(ID(E), State::S1);
c->setPort(ID(L), GetSize(ud.longest_chain)-1);
c->type = ID($__XILINX_SHREG_);
}
else
log_abort();
log(" -> %s (%s)\n", log_id(c), log_id(c->type));
}
void run_variable(xilinx_srl_pm &pm)
{
auto &st = pm.st_variable;
auto &ud = pm.ud_variable;
log("Found variable chain of length %d (%s):\n", GetSize(ud.chain), log_id(st.first->type));
auto first_cell = ud.chain.back().first;
auto first_slice = ud.chain.back().second;
SigSpec initval;
for (const auto &i : ud.chain) {
auto cell = i.first;
auto slice = i.second;
log_debug(" %s\n", log_id(cell));
if (cell->type.in(ID($_DFF_N_), ID($_DFF_P_), ID($_DFFE_NN_), ID($_DFFE_NP_), ID($_DFFE_PN_), ID($_DFFE_PP_), ID($dff), ID($dffe))) {
SigBit Q = cell->getPort(ID(Q))[slice];
log_assert(Q.wire);
auto it = Q.wire->attributes.find(ID(init));
if (it != Q.wire->attributes.end()) {
auto &i = it->second[Q.offset];
initval.append(i);
i = State::Sx;
}
else
initval.append(State::Sx);
}
else
log_abort();
if (cell != first_cell)
cell->connections_.at(ID(Q))[slice] = pm.module->addWire(NEW_ID);
}
pm.autoremove(st.shiftx);
auto last_cell = ud.chain.front().first;
auto last_slice = ud.chain.front().second;
Cell *c = last_cell;
if (c->type.in(ID($dff), ID($dffe))) {
auto &Q = last_cell->connections_.at(ID(Q));
Q = Q[last_slice];
auto &D = first_cell->connections_.at(ID(D));
D = D[first_slice];
}
if (c->type.in(ID($_DFF_N_), ID($_DFF_P_), ID($_DFFE_NN_), ID($_DFFE_NP_), ID($_DFFE_PN_), ID($_DFFE_PP_), ID($dff), ID($dffe))) {
Const clkpol, enpol;
if (c->type.in(ID($_DFF_P_), ID($_DFFE_PN_), ID($_DFFE_PP_)))
clkpol = 1;
else if (c->type.in(ID($_DFF_N_), ID($DFFE_NN_), ID($_DFFE_NP_)))
clkpol = 0;
else if (c->type.in(ID($dff), ID($dffe))) {
clkpol = c->getParam(ID(CLK_POLARITY));
c->setPort(ID(C), c->getPort(ID(CLK)));
c->unsetPort(ID(CLK));
}
else
log_abort();
if (c->type.in(ID($_DFFE_NP_), ID($_DFFE_PP_)))
enpol = 1;
else if (c->type.in(ID($_DFFE_NN_), ID($_DFFE_PN_)))
enpol = 0;
else if (c->type.in(ID($dffe))) {
enpol = c->getParam(ID(EN_POLARITY));
c->setPort(ID(E), c->getPort(ID(EN)));
c->unsetPort(ID(EN));
}
else
enpol = 2;
c->parameters.clear();
c->setParam(ID(DEPTH), GetSize(ud.chain));
c->setParam(ID(INIT), initval.as_const());
c->setParam(ID(CLKPOL), clkpol);
c->setParam(ID(ENPOL), enpol);
if (c->type.in(ID($_DFF_N_), ID($_DFF_P_), ID($dff)))
c->setPort(ID(E), State::S1);
c->setPort(ID(L), st.shiftx->getPort(ID(B)));
c->setPort(ID(Q), st.shiftx->getPort(ID(Y)));
c->type = ID($__XILINX_SHREG_);
}
else
log_abort();
log(" -> %s (%s)\n", log_id(c), log_id(c->type));
}
struct XilinxSrlPass : public Pass {
XilinxSrlPass() : Pass("xilinx_srl", "Xilinx shift register extraction") { }
void help() YS_OVERRIDE
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" xilinx_srl [options] [selection]\n");
log("\n");
log("This pass converts chains of built-in flops (bit-level: $_DFF_[NP]_, $_DFFE_*\n");
log("and word-level: $dff, $dffe) as well as Xilinx flops (FDRE, FDRE_1) into a\n");
log("$__XILINX_SHREG cell. Chains must be of the same cell type, clock, clock polarity,\n");
log("enable, and enable polarity (where relevant).\n");
log("Flops with resets cannot be mapped to Xilinx devices and will not be inferred.");
log("\n");
log(" -minlen N\n");
log(" min length of shift register (default = 3)\n");
log("\n");
log(" -fixed\n");
log(" infer fixed-length shift registers.\n");
log("\n");
log(" -variable\n");
log(" infer variable-length shift registers (i.e. fixed-length shifts where\n");
log(" each element also fans-out to a $shiftx cell.\n");
log("\n");
}
void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
{
log_header(design, "Executing XILINX_SRL pass (Xilinx shift register extraction).\n");
bool fixed = false;
bool variable = false;
int minlen = 3;
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++)
{
if (args[argidx] == "-minlen" && argidx+1 < args.size()) {
minlen = atoi(args[++argidx].c_str());
continue;
}
if (args[argidx] == "-fixed") {
fixed = true;
continue;
}
if (args[argidx] == "-variable") {
variable = true;
continue;
}
break;
}
extra_args(args, argidx, design);
if (!fixed && !variable)
log_cmd_error("'-fixed' and/or '-variable' must be specified.\n");
for (auto module : design->selected_modules()) {
auto pm = xilinx_srl_pm(module, module->selected_cells());
pm.ud_fixed.minlen = minlen;
pm.ud_variable.minlen = minlen;
if (fixed) {
// TODO: How to get these automatically?
pm.ud_fixed.default_params[std::make_pair(ID(FDRE),ID(INIT))] = State::S0;
pm.ud_fixed.default_params[std::make_pair(ID(FDRE),ID(IS_C_INVERTED))] = State::S0;
pm.ud_fixed.default_params[std::make_pair(ID(FDRE),ID(IS_D_INVERTED))] = State::S0;
pm.ud_fixed.default_params[std::make_pair(ID(FDRE),ID(IS_R_INVERTED))] = State::S0;
pm.run_fixed(run_fixed);
}
if (variable)
pm.run_variable(run_variable);
}
}
} XilinxSrlPass;
PRIVATE_NAMESPACE_END
<commit_msg>Fix last_cell.D<commit_after>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
* (C) 2019 Eddie Hung <eddie@fpgeh.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "kernel/yosys.h"
#include "kernel/sigtools.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
// for peepopt_pm
bool did_something;
#include "passes/pmgen/xilinx_srl_pm.h"
#include "passes/pmgen/ice40_dsp_pm.h"
#include "passes/pmgen/peepopt_pm.h"
void run_fixed(xilinx_srl_pm &pm)
{
auto &st = pm.st_fixed;
auto &ud = pm.ud_fixed;
auto param_def = [&ud](Cell *cell, IdString param) {
auto def = ud.default_params.at(std::make_pair(cell->type,param));
return cell->parameters.at(param, def);
};
log("Found fixed chain of length %d (%s):\n", GetSize(ud.longest_chain), log_id(st.first->type));
auto first_cell = ud.longest_chain.back();
SigSpec initval;
for (auto cell : ud.longest_chain) {
log_debug(" %s\n", log_id(cell));
if (cell->type.in(ID($_DFF_N_), ID($_DFF_P_), ID($_DFFE_NN_), ID($_DFFE_NP_), ID($_DFFE_PN_), ID($_DFFE_PP_))) {
SigBit Q = cell->getPort(ID(Q));
log_assert(Q.wire);
auto it = Q.wire->attributes.find(ID(init));
if (it != Q.wire->attributes.end()) {
auto &i = it->second[Q.offset];
initval.append(i);
i = State::Sx;
}
else
initval.append(State::Sx);
}
else if (cell->type.in(ID(FDRE), ID(FDRE_1)))
initval.append(param_def(cell, ID(INIT)));
else
log_abort();
if (cell != first_cell)
pm.autoremove(cell);
}
Cell *c = first_cell;
SigBit Q = st.first->getPort(ID(Q));
c->setPort(ID(Q), Q);
if (c->type.in(ID($_DFF_N_), ID($_DFF_P_), ID($_DFFE_NN_), ID($_DFFE_NP_), ID($_DFFE_PN_), ID($_DFFE_PP_), ID(FDRE), ID(FDRE_1))) {
c->parameters.clear();
c->setParam(ID(DEPTH), GetSize(ud.longest_chain));
c->setParam(ID(INIT), initval.as_const());
if (c->type.in(ID($_DFF_P_), ID($_DFFE_PN_), ID($_DFFE_PP_)))
c->setParam(ID(CLKPOL), 1);
else if (c->type.in(ID($_DFF_N_), ID($DFFE_NN_), ID($_DFFE_NP_), ID(FDRE_1)))
c->setParam(ID(CLKPOL), 0);
else if (c->type.in(ID(FDRE)))
c->setParam(ID(CLKPOL), param_def(c, ID(IS_C_INVERTED)).as_bool() ? 0 : 1);
else
log_abort();
if (c->type.in(ID($_DFFE_NP_), ID($_DFFE_PP_)))
c->setParam(ID(ENPOL), 1);
else if (c->type.in(ID($_DFFE_NN_), ID($_DFFE_PN_)))
c->setParam(ID(ENPOL), 0);
else
c->setParam(ID(ENPOL), 2);
if (c->type.in(ID($_DFF_N_), ID($_DFF_P_)))
c->setPort(ID(E), State::S1);
c->setPort(ID(L), GetSize(ud.longest_chain)-1);
c->type = ID($__XILINX_SHREG_);
}
else
log_abort();
log(" -> %s (%s)\n", log_id(c), log_id(c->type));
}
void run_variable(xilinx_srl_pm &pm)
{
auto &st = pm.st_variable;
auto &ud = pm.ud_variable;
log("Found variable chain of length %d (%s):\n", GetSize(ud.chain), log_id(st.first->type));
auto first_cell = ud.chain.back().first;
auto first_slice = ud.chain.back().second;
SigSpec initval;
for (const auto &i : ud.chain) {
auto cell = i.first;
auto slice = i.second;
log_debug(" %s\n", log_id(cell));
if (cell->type.in(ID($_DFF_N_), ID($_DFF_P_), ID($_DFFE_NN_), ID($_DFFE_NP_), ID($_DFFE_PN_), ID($_DFFE_PP_), ID($dff), ID($dffe))) {
SigBit Q = cell->getPort(ID(Q))[slice];
log_assert(Q.wire);
auto it = Q.wire->attributes.find(ID(init));
if (it != Q.wire->attributes.end()) {
auto &i = it->second[Q.offset];
initval.append(i);
i = State::Sx;
}
else
initval.append(State::Sx);
}
else
log_abort();
if (cell != first_cell)
cell->connections_.at(ID(Q))[slice] = pm.module->addWire(NEW_ID);
}
pm.autoremove(st.shiftx);
auto last_cell = ud.chain.front().first;
auto last_slice = ud.chain.front().second;
Cell *c = last_cell;
if (c->type.in(ID($dff), ID($dffe))) {
auto &Q = last_cell->connections_.at(ID(Q));
Q = Q[last_slice];
last_cell->setPort(ID(D), first_cell->getPort(ID(D))[first_slice]);
}
if (c->type.in(ID($_DFF_N_), ID($_DFF_P_), ID($_DFFE_NN_), ID($_DFFE_NP_), ID($_DFFE_PN_), ID($_DFFE_PP_), ID($dff), ID($dffe))) {
Const clkpol, enpol;
if (c->type.in(ID($_DFF_P_), ID($_DFFE_PN_), ID($_DFFE_PP_)))
clkpol = 1;
else if (c->type.in(ID($_DFF_N_), ID($DFFE_NN_), ID($_DFFE_NP_)))
clkpol = 0;
else if (c->type.in(ID($dff), ID($dffe))) {
clkpol = c->getParam(ID(CLK_POLARITY));
c->setPort(ID(C), c->getPort(ID(CLK)));
c->unsetPort(ID(CLK));
}
else
log_abort();
if (c->type.in(ID($_DFFE_NP_), ID($_DFFE_PP_)))
enpol = 1;
else if (c->type.in(ID($_DFFE_NN_), ID($_DFFE_PN_)))
enpol = 0;
else if (c->type.in(ID($dffe))) {
enpol = c->getParam(ID(EN_POLARITY));
c->setPort(ID(E), c->getPort(ID(EN)));
c->unsetPort(ID(EN));
}
else
enpol = 2;
c->parameters.clear();
c->setParam(ID(DEPTH), GetSize(ud.chain));
c->setParam(ID(INIT), initval.as_const());
c->setParam(ID(CLKPOL), clkpol);
c->setParam(ID(ENPOL), enpol);
if (c->type.in(ID($_DFF_N_), ID($_DFF_P_), ID($dff)))
c->setPort(ID(E), State::S1);
c->setPort(ID(L), st.shiftx->getPort(ID(B)));
c->setPort(ID(Q), st.shiftx->getPort(ID(Y)));
c->type = ID($__XILINX_SHREG_);
}
else
log_abort();
log(" -> %s (%s)\n", log_id(c), log_id(c->type));
}
struct XilinxSrlPass : public Pass {
XilinxSrlPass() : Pass("xilinx_srl", "Xilinx shift register extraction") { }
void help() YS_OVERRIDE
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" xilinx_srl [options] [selection]\n");
log("\n");
log("This pass converts chains of built-in flops (bit-level: $_DFF_[NP]_, $_DFFE_*\n");
log("and word-level: $dff, $dffe) as well as Xilinx flops (FDRE, FDRE_1) into a\n");
log("$__XILINX_SHREG cell. Chains must be of the same cell type, clock, clock polarity,\n");
log("enable, and enable polarity (where relevant).\n");
log("Flops with resets cannot be mapped to Xilinx devices and will not be inferred.");
log("\n");
log(" -minlen N\n");
log(" min length of shift register (default = 3)\n");
log("\n");
log(" -fixed\n");
log(" infer fixed-length shift registers.\n");
log("\n");
log(" -variable\n");
log(" infer variable-length shift registers (i.e. fixed-length shifts where\n");
log(" each element also fans-out to a $shiftx cell.\n");
log("\n");
}
void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
{
log_header(design, "Executing XILINX_SRL pass (Xilinx shift register extraction).\n");
bool fixed = false;
bool variable = false;
int minlen = 3;
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++)
{
if (args[argidx] == "-minlen" && argidx+1 < args.size()) {
minlen = atoi(args[++argidx].c_str());
continue;
}
if (args[argidx] == "-fixed") {
fixed = true;
continue;
}
if (args[argidx] == "-variable") {
variable = true;
continue;
}
break;
}
extra_args(args, argidx, design);
if (!fixed && !variable)
log_cmd_error("'-fixed' and/or '-variable' must be specified.\n");
for (auto module : design->selected_modules()) {
auto pm = xilinx_srl_pm(module, module->selected_cells());
pm.ud_fixed.minlen = minlen;
pm.ud_variable.minlen = minlen;
if (fixed) {
// TODO: How to get these automatically?
pm.ud_fixed.default_params[std::make_pair(ID(FDRE),ID(INIT))] = State::S0;
pm.ud_fixed.default_params[std::make_pair(ID(FDRE),ID(IS_C_INVERTED))] = State::S0;
pm.ud_fixed.default_params[std::make_pair(ID(FDRE),ID(IS_D_INVERTED))] = State::S0;
pm.ud_fixed.default_params[std::make_pair(ID(FDRE),ID(IS_R_INVERTED))] = State::S0;
pm.run_fixed(run_fixed);
}
if (variable)
pm.run_variable(run_variable);
}
}
} XilinxSrlPass;
PRIVATE_NAMESPACE_END
<|endoftext|> |
<commit_before>/*
* opencog/atomspace/AtomSpace.cc
*
* Copyright (C) 2008-2011 OpenCog Foundation
* Copyright (C) 2002-2007 Novamente LLC
* All Rights Reserved
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "AtomSpace.h"
#include <string>
#include <iostream>
#include <fstream>
#include <list>
#include <time.h>
#include <cstdlib>
#include <pthread.h>
#include <stdlib.h>
#include <opencog/atomspace/ClassServer.h>
#include <opencog/atomspace/CompositeTruthValue.h>
#include <opencog/atomspace/HandleEntry.h>
#include <opencog/atomspace/IndefiniteTruthValue.h>
#include <opencog/atomspace/Link.h>
#include <opencog/atomspace/Node.h>
#include <opencog/atomspace/SimpleTruthValue.h>
#include <opencog/atomspace/StatisticsMonitor.h>
#include <opencog/atomspace/types.h>
#include <opencog/persist/xml/NMXmlExporter.h>
#include <opencog/util/Config.h>
#include <opencog/util/Logger.h>
#include <opencog/util/oc_assert.h>
//#define DPRINTF printf
#define DPRINTF(...)
using std::string;
using std::cerr;
using std::cout;
using std::endl;
using std::min;
using std::max;
using namespace opencog;
// ====================================================================
//
AtomSpace::AtomSpace(void)
{
atomSpaceAsync = new AtomSpaceAsync();
ownsAtomSpaceAsync = true;
#ifdef USE_ATOMSPACE_LOCAL_THREAD_CACHE
setUpCaching();
#endif
}
AtomSpace::AtomSpace(const AtomSpace& other)
{
this->atomSpaceAsync = other.atomSpaceAsync;
ownsAtomSpaceAsync = false;
#ifdef USE_ATOMSPACE_LOCAL_THREAD_CACHE
setUpCaching();
#endif
}
#ifdef USE_ATOMSPACE_LOCAL_THREAD_CACHE
void AtomSpace::setUpCaching()
{
// Initialise lru cache for getType
__getType = new _getType(this);
getTypeCached = new lru_cache_threaded<AtomSpace::_getType>(1000,*__getType);
// Initialise lru cache for getTV (disabled because we can't get TV
// changes from other threads)
//__getTV = new _getTV(this);
//getTVCached = new lru_cache<AtomSpace::_getTV>(1000,*__getTV);
c_remove = atomSpaceAsync->removeAtomSignal(
boost::bind(&AtomSpace::handleRemoveSignal, this, _1, _2));
}
#endif
AtomSpace::AtomSpace(AtomSpaceAsync& a)
{
atomSpaceAsync = &a;
ownsAtomSpaceAsync = false;
#ifdef USE_ATOMSPACE_LOCAL_THREAD_CACHE
setUpCaching();
#endif
}
AtomSpace::~AtomSpace()
{
#ifdef USE_ATOMSPACE_LOCAL_THREAD_CACHE
c_remove.disconnect();
delete __getType;
delete getTypeCached;
#endif
// Will be unnecessary once GC is implemented
if (ownsAtomSpaceAsync)
delete atomSpaceAsync;
}
#ifdef USE_ATOMSPACE_LOCAL_THREAD_CACHE
bool AtomSpace::handleRemoveSignal(AtomSpaceImpl *as, Handle h)
{
getTypeCached->remove(h);
return false;
}
#endif
Type AtomSpace::getType(Handle h) const
{
#ifdef USE_ATOMSPACE_LOCAL_THREAD_CACHE
Type t = (*getTypeCached)(h);
return t;
#else
return atomSpaceAsync->getType(h)->get_result();
#endif
}
const TruthValue* AtomSpace::getTV(Handle h, VersionHandle vh) const
{
TruthValueRequest tvr = atomSpaceAsync->getTV(h, vh);
return tvr->get_result();
//const TruthValue& result = *tvr->get_result();
// Need to clone the result's TV as it will be deleted when the request
// is.
//return TruthValue*(result.clone());
}
void AtomSpace::setTV(Handle h, const TruthValue& tv, VersionHandle vh)
{
atomSpaceAsync->setTV(h, tv, vh)->get_result();
}
AtomSpace& AtomSpace::operator=(const AtomSpace& other)
{
throw opencog::RuntimeException(TRACE_INFO,
"AtomSpace - Cannot copy an object of this class");
}
bool AtomSpace::isNode(const Handle& h) const
{
DPRINTF("AtomSpace::isNode Atom space address: %p\n", this);
Type t = getType(h);
return classserver().isA(t, NODE);
}
bool AtomSpace::isLink(const Handle& h) const
{
DPRINTF("AtomSpace::isLink Atom space address: %p\n", this);
Type t = getType(h);
return classserver().isA(t, LINK);
}
void AtomSpace::do_merge_tv(Handle h, const TruthValue& tvn)
{
const TruthValue* currentTV(getTV(h));
if (currentTV->isNullTv()) {
setTV(h, tvn);
} else {
TruthValue* mergedTV = currentTV->merge(tvn);
setTV(h, *mergedTV);
delete mergedTV;
}
}
Handle AtomSpace::addPrefixedNode(Type t, const string& prefix, const TruthValue& tvn) {
static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
srand(time(0));
static const int len = 16;
string name;
Handle result;
//Keep trying new random suffixes until you generate a new name
do {
name=prefix;
for (int i = 0; i < len; ++i) {
name+=alphanum[rand() % (sizeof(alphanum) - 1)];
}
result = getHandle(t, name);
} while(isValidHandle(result));//If the name already exists, try again
return addNode(t, name, tvn);
}
Handle AtomSpace::addRealAtom(const Atom& atom, const TruthValue& tvn)
{
DPRINTF("AtomSpace::addRealAtom\n");
const TruthValue& newTV = (tvn.isNullTv()) ? atom.getTruthValue() : tvn;
// Check if the given Atom reference is of an atom
// that was not inserted yet. If so, adds the atom. Otherwise, just sets
// result to the correct/valid handle.
Handle result;
const Node *node = dynamic_cast<const Node *>(&atom);
if (node) {
result = getHandle(node->getType(), node->getName());
if (result == Handle::UNDEFINED) {
return addNode(node->getType(), node->getName(), newTV);
}
} else {
const Link *link = dynamic_cast<const Link *>(&atom);
result = getHandle(link->getType(), link->getOutgoingSet());
if (result == Handle::UNDEFINED) {
return addLink(link->getType(), link->getOutgoingSet(), newTV);
}
}
do_merge_tv(result,newTV);
return result;
}
boost::shared_ptr<Atom> AtomSpace::cloneAtom(const Handle h) const
{
return atomSpaceAsync->getAtom(h)->get_result();
}
size_t AtomSpace::getAtomHash(const Handle h) const
{
return atomSpaceAsync->getAtomHash(h)->get_result();
}
bool AtomSpace::isValidHandle(const Handle h) const
{
return atomSpaceAsync->isValidHandle(h)->get_result();
}
bool AtomSpace::commitAtom(const Atom& a)
{
return atomSpaceAsync->commitAtom(a)->get_result();
}
AttentionValue AtomSpace::getAV(Handle h) const
{
return atomSpaceAsync->getAV(h)->get_result();
}
void AtomSpace::setAV(Handle h, const AttentionValue &av)
{
atomSpaceAsync->setAV(h,av)->get_result();
}
int AtomSpace::Nodes(VersionHandle vh) const
{
return atomSpaceAsync->nodeCount(vh)->get_result();
}
int AtomSpace::Links(VersionHandle vh) const
{
return atomSpaceAsync->linkCount(vh)->get_result();
}
void AtomSpace::decayShortTermImportance()
{
atomSpaceAsync->decayShortTermImportance()->get_result();
}
AttentionValue::sti_t AtomSpace::getAttentionalFocusBoundary() const
{
return atomSpaceAsync->atomspace.getAttentionBank().getAttentionalFocusBoundary();
}
AttentionValue::sti_t AtomSpace::setAttentionalFocusBoundary(AttentionValue::sti_t s)
{
return atomSpaceAsync->atomspace.getAttentionBank().setAttentionalFocusBoundary(s);
}
void AtomSpace::clear()
{
#ifdef USE_ATOMSPACE_LOCAL_THREAD_CACHE
{
getTypeCached->clear();
//getTVCached->clear();
}
#endif
atomSpaceAsync->clear()->get_result();
}
void AtomSpace::print(std::ostream& output,
Type type, bool subclass) const
{
atomSpaceAsync->print(output, type, subclass)->get_result();
}
<commit_msg>slightly better ordering of AtomSpace initialisation<commit_after>/*
* opencog/atomspace/AtomSpace.cc
*
* Copyright (C) 2008-2011 OpenCog Foundation
* Copyright (C) 2002-2007 Novamente LLC
* All Rights Reserved
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "AtomSpace.h"
#include <string>
#include <iostream>
#include <fstream>
#include <list>
#include <time.h>
#include <cstdlib>
#include <pthread.h>
#include <stdlib.h>
#include <opencog/atomspace/ClassServer.h>
#include <opencog/atomspace/CompositeTruthValue.h>
#include <opencog/atomspace/HandleEntry.h>
#include <opencog/atomspace/IndefiniteTruthValue.h>
#include <opencog/atomspace/Link.h>
#include <opencog/atomspace/Node.h>
#include <opencog/atomspace/SimpleTruthValue.h>
#include <opencog/atomspace/StatisticsMonitor.h>
#include <opencog/atomspace/types.h>
#include <opencog/persist/xml/NMXmlExporter.h>
#include <opencog/util/Config.h>
#include <opencog/util/Logger.h>
#include <opencog/util/oc_assert.h>
//#define DPRINTF printf
#define DPRINTF(...)
using std::string;
using std::cerr;
using std::cout;
using std::endl;
using std::min;
using std::max;
using namespace opencog;
// ====================================================================
//
AtomSpace::AtomSpace(void)
{
#ifdef USE_ATOMSPACE_LOCAL_THREAD_CACHE
// Ensure caching is ready before anything else happens
setUpCaching();
#endif
atomSpaceAsync = new AtomSpaceAsync();
ownsAtomSpaceAsync = true;
c_remove = atomSpaceAsync->removeAtomSignal(
boost::bind(&AtomSpace::handleRemoveSignal, this, _1, _2));
}
AtomSpace::AtomSpace(const AtomSpace& other)
{
#ifdef USE_ATOMSPACE_LOCAL_THREAD_CACHE
// Ensure caching is ready before anything else happens
setUpCaching();
#endif
this->atomSpaceAsync = other.atomSpaceAsync;
ownsAtomSpaceAsync = false;
c_remove = atomSpaceAsync->removeAtomSignal(
boost::bind(&AtomSpace::handleRemoveSignal, this, _1, _2));
}
#ifdef USE_ATOMSPACE_LOCAL_THREAD_CACHE
void AtomSpace::setUpCaching()
{
// Initialise lru cache for getType
__getType = new _getType(this);
getTypeCached = new lru_cache_threaded<AtomSpace::_getType>(1000,*__getType);
// Initialise lru cache for getTV (disabled because we can't get TV
// changes from other threads)
//__getTV = new _getTV(this);
//getTVCached = new lru_cache<AtomSpace::_getTV>(1000,*__getTV);
}
#endif
AtomSpace::AtomSpace(AtomSpaceAsync& a)
{
#ifdef USE_ATOMSPACE_LOCAL_THREAD_CACHE
setUpCaching();
#endif
atomSpaceAsync = &a;
ownsAtomSpaceAsync = false;
}
AtomSpace::~AtomSpace()
{
c_remove.disconnect();
#ifdef USE_ATOMSPACE_LOCAL_THREAD_CACHE
delete __getType;
delete getTypeCached;
#endif
// Will be unnecessary once GC is implemented
if (ownsAtomSpaceAsync)
delete atomSpaceAsync;
}
bool AtomSpace::handleRemoveSignal(AtomSpaceImpl *as, Handle h)
{
#ifdef USE_ATOMSPACE_LOCAL_THREAD_CACHE
getTypeCached->remove(h);
#endif
return false;
}
Type AtomSpace::getType(Handle h) const
{
#ifdef USE_ATOMSPACE_LOCAL_THREAD_CACHE
Type t = (*getTypeCached)(h);
return t;
#else
return atomSpaceAsync->getType(h)->get_result();
#endif
}
const TruthValue* AtomSpace::getTV(Handle h, VersionHandle vh) const
{
TruthValueRequest tvr = atomSpaceAsync->getTV(h, vh);
return tvr->get_result();
//const TruthValue& result = *tvr->get_result();
// Need to clone the result's TV as it will be deleted when the request
// is.
//return TruthValue*(result.clone());
}
void AtomSpace::setTV(Handle h, const TruthValue& tv, VersionHandle vh)
{
atomSpaceAsync->setTV(h, tv, vh)->get_result();
}
AtomSpace& AtomSpace::operator=(const AtomSpace& other)
{
throw opencog::RuntimeException(TRACE_INFO,
"AtomSpace - Cannot copy an object of this class");
}
bool AtomSpace::isNode(const Handle& h) const
{
DPRINTF("AtomSpace::isNode Atom space address: %p\n", this);
Type t = getType(h);
return classserver().isA(t, NODE);
}
bool AtomSpace::isLink(const Handle& h) const
{
DPRINTF("AtomSpace::isLink Atom space address: %p\n", this);
Type t = getType(h);
return classserver().isA(t, LINK);
}
void AtomSpace::do_merge_tv(Handle h, const TruthValue& tvn)
{
const TruthValue* currentTV(getTV(h));
if (currentTV->isNullTv()) {
setTV(h, tvn);
} else {
TruthValue* mergedTV = currentTV->merge(tvn);
setTV(h, *mergedTV);
delete mergedTV;
}
}
Handle AtomSpace::addPrefixedNode(Type t, const string& prefix, const TruthValue& tvn) {
static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
srand(time(0));
static const int len = 16;
string name;
Handle result;
//Keep trying new random suffixes until you generate a new name
do {
name=prefix;
for (int i = 0; i < len; ++i) {
name+=alphanum[rand() % (sizeof(alphanum) - 1)];
}
result = getHandle(t, name);
} while(isValidHandle(result));//If the name already exists, try again
return addNode(t, name, tvn);
}
Handle AtomSpace::addRealAtom(const Atom& atom, const TruthValue& tvn)
{
DPRINTF("AtomSpace::addRealAtom\n");
const TruthValue& newTV = (tvn.isNullTv()) ? atom.getTruthValue() : tvn;
// Check if the given Atom reference is of an atom
// that was not inserted yet. If so, adds the atom. Otherwise, just sets
// result to the correct/valid handle.
Handle result;
const Node *node = dynamic_cast<const Node *>(&atom);
if (node) {
result = getHandle(node->getType(), node->getName());
if (result == Handle::UNDEFINED) {
return addNode(node->getType(), node->getName(), newTV);
}
} else {
const Link *link = dynamic_cast<const Link *>(&atom);
result = getHandle(link->getType(), link->getOutgoingSet());
if (result == Handle::UNDEFINED) {
return addLink(link->getType(), link->getOutgoingSet(), newTV);
}
}
do_merge_tv(result,newTV);
return result;
}
boost::shared_ptr<Atom> AtomSpace::cloneAtom(const Handle h) const
{
return atomSpaceAsync->getAtom(h)->get_result();
}
size_t AtomSpace::getAtomHash(const Handle h) const
{
return atomSpaceAsync->getAtomHash(h)->get_result();
}
bool AtomSpace::isValidHandle(const Handle h) const
{
return atomSpaceAsync->isValidHandle(h)->get_result();
}
bool AtomSpace::commitAtom(const Atom& a)
{
return atomSpaceAsync->commitAtom(a)->get_result();
}
AttentionValue AtomSpace::getAV(Handle h) const
{
return atomSpaceAsync->getAV(h)->get_result();
}
void AtomSpace::setAV(Handle h, const AttentionValue &av)
{
atomSpaceAsync->setAV(h,av)->get_result();
}
int AtomSpace::Nodes(VersionHandle vh) const
{
return atomSpaceAsync->nodeCount(vh)->get_result();
}
int AtomSpace::Links(VersionHandle vh) const
{
return atomSpaceAsync->linkCount(vh)->get_result();
}
void AtomSpace::decayShortTermImportance()
{
atomSpaceAsync->decayShortTermImportance()->get_result();
}
AttentionValue::sti_t AtomSpace::getAttentionalFocusBoundary() const
{
return atomSpaceAsync->atomspace.getAttentionBank().getAttentionalFocusBoundary();
}
AttentionValue::sti_t AtomSpace::setAttentionalFocusBoundary(AttentionValue::sti_t s)
{
return atomSpaceAsync->atomspace.getAttentionBank().setAttentionalFocusBoundary(s);
}
void AtomSpace::clear()
{
#ifdef USE_ATOMSPACE_LOCAL_THREAD_CACHE
{
getTypeCached->clear();
//getTVCached->clear();
}
#endif
atomSpaceAsync->clear()->get_result();
}
void AtomSpace::print(std::ostream& output,
Type type, bool subclass) const
{
atomSpaceAsync->print(output, type, subclass)->get_result();
}
<|endoftext|> |
<commit_before>#include <iostream>
#include "room.hpp"
template<size_t D>
int Room<D>::image_source_model(const Eigen::Matrix<float,D,1> &source_location, int max_order)
{
/*
* This is the top-level method to run the image source model
*/
// make sure the list is empty
while (visible_sources.size() > 0)
visible_sources.pop();
// add the original (real) source
ImageSource<D> real_source;
real_source.loc = source_location;
real_source.attenuation = 1.;
real_source.order = 0;
real_source.gen_wall = -1;
real_source.parent = NULL;
// Run the image source model algorithm
image_sources_dfs(real_source, max_order);
// fill the sources array in room and return
return fill_sources();
}
template<size_t D>
int Room<D>::fill_sources()
{
int n_sources = visible_sources.size();
// Create linear arrays to store the image sources
if (n_sources > 0)
{
// resize all the arrays
sources.resize(D, n_sources);
orders.resize(n_sources);
gen_walls.resize(n_sources);
attenuations.resize(n_sources);
visible_mics.resize(microphones.cols(), n_sources);
for (int i = n_sources - 1 ; i >= 0 ; i--)
{
ImageSource<D> &top = visible_sources.top(); // sample top of stack
// fill the arrays
sources.col(i) = top.loc;
gen_walls.coeffRef(i) = top.gen_wall;
orders.coeffRef(i) = top.order;
attenuations.coeffRef(i) = top.attenuation;
visible_mics.col(i) = top.visible_mics;
visible_sources.pop(); // unstack
}
}
return 0;
}
template<size_t D>
void Room<D>::image_sources_dfs(ImageSource<D> &is, int max_order)
{
/*
* This function runs a depth first search (DFS) on the tree of image sources
*/
ImageSource<D> new_is;
// Check the visibility of the source from the different microphones
bool any_visible = false;
for (int mic = 0 ; mic < microphones.cols() ; mic++)
{
bool is_visible = is_visible_dfs(microphones.col(mic), is);
if (is_visible && !any_visible)
{
any_visible = is_visible;
is.visible_mics.resize(microphones.cols());
is.visible_mics.setZero();
}
if (any_visible)
is.visible_mics.coeffRef(mic) = is_visible;
}
if (any_visible)
visible_sources.push(is); // this should push a copy onto the stack
// If we reached maximal depth, stop
if (max_order == 0)
return;
// Then, check all the reflections across the walls
for (size_t wi=0 ; wi < walls.size() ; wi++)
{
int dir = walls[wi].reflect(is.loc, new_is.loc); // the reflected location
// We only check valid reflections (normals should point outward from the room
if (dir <= 0)
continue;
// The reflection is valid, fill in the image source attributes
new_is.attenuation = is.attenuation * (1. - walls[wi].absorption);
new_is.order = is.order + 1;
new_is.gen_wall = wi;
new_is.parent = &is;
// Run the DFS recursion (on the last element in the array, the one we just added)
image_sources_dfs(new_is, max_order - 1);
}
}
template<size_t D>
bool Room<D>::is_visible_dfs(const Eigen::Matrix<float,D,1> &p, ImageSource<D> &is)
{
/*
Returns true if the given sound source (with image source id) is visible from point p.
room - the structure that contains all the sources and stuff
p (np.array size 2 or 3) coordinates of the point where we check visibility
imageId (int) id of the image within the SoundSource object
Returns
False (0) : not visible
True (1) : visible
*/
if (is_obstructed_dfs(p, is))
return false;
if (is.parent != NULL)
{
Eigen::Matrix<float,D,1> intersection;
// get generating wall id
int wall_id = is.gen_wall;
// check if the generating wall is intersected
int ret = walls[wall_id].intersection(p, is.loc, intersection);
// The source is not visible if the ray does not intersect
// the generating wall
if (ret >= 0)
// Check visibility of intersection point from parent source
return is_visible_dfs(intersection, *(is.parent));
else
return false;
}
// If we get here this is the original, unobstructed, source
return true;
}
template<size_t D>
bool Room<D>::is_obstructed_dfs(const Eigen::Matrix<float,D,1> &p, ImageSource<D> &is)
{
/*
Checks if there is a wall obstructing the line of sight going from a source to a point.
room - the structure that contains all the sources and stuff
p (np.array size 2 or 3) coordinates of the point where we check obstruction
imageId (int) id of the image within the SoundSource object
Returns (bool)
False (0) : not obstructed
True (1) : obstructed
*/
int gen_wall_id = is.gen_wall;
// Check candidate walls for obstructions
for (size_t ow = 0 ; ow < obstructing_walls.size() ; ow++)
{
int wall_id = obstructing_walls[ow];
// generating wall can't be obstructive
if (wall_id != gen_wall_id)
{
Eigen::Matrix<float,D,1> intersection;
int ret = walls[wall_id].intersection(is.loc, p, intersection);
// There is an intersection and it is distinct from segment endpoints
if (ret == Wall<D>::Isect::VALID || ret == Wall<D>::Isect::BNDRY)
{
if (is.parent != NULL)
{
// Test if the intersection point and the image are on
// opposite sides of the generating wall
// We ignore the obstruction if it is inside the
// generating wall (it is what happens in a corner)
int img_side = walls[is.gen_wall].side(is.loc);
int intersection_side = walls[is.gen_wall].side(intersection);
if (img_side != intersection_side && intersection_side != 0)
return true;
}
else
return true;
}
}
}
return false;
}
template<size_t D>
int Room<D>::image_source_shoebox(
const Eigen::Matrix<float,D,1> &source,
const Eigen::Matrix<float,D,1> &room_size,
const Eigen::Matrix<float,2*D,1> &absorption,
int max_order
)
{
// precompute powers of the absorption coefficients
std::vector<float> transmission_pwr((max_order + 1) * 2 * D);
for (int d = 0 ; d < 2 * D ; d++)
transmission_pwr[d] = 1.;
for (int i = 1 ; i <= max_order ; i++)
for (int d = 0 ; d < 2 * D ; d++)
transmission_pwr[i * 2 * D + d] = (1. - absorption[d]) * transmission_pwr[(i-1)*2*D + d];
// make sure the list is empty
while (visible_sources.size() > 0)
visible_sources.pop();
// L1 ball of room images
int point[3] = {0, 0, 0};
// Take 2D case into account
int z_max = max_order;
if (D == 2)
z_max = 0;
// Walk on all the points of the discrete L! ball of radius max_order
for (point[2] = -z_max ; point[2] <= z_max ; point[2]++)
{
int y_max = max_order - abs(point[2]);
for (point[1] = -y_max ; point[1] <= y_max ; point[1]++)
{
int x_max = y_max - abs(point[1]);
if (x_max < 0) x_max = 0;
for (point[0] = -x_max ; point[0] <= x_max ; point[0]++)
{
visible_sources.push(ImageSource<D>());
ImageSource<D> &is = visible_sources.top();
is.visible_mics = VectorXb::Ones(microphones.cols()); // everything is visible
is.order = 0;
is.attenuation = 1.;
is.gen_wall = -1;
// Now compute the reflection, the order, and the multiplicative constant
for (int d = 0 ; d < D ; d++)
{
// Compute the reflected source
float step = abs(point[d]) % 2 == 1 ? room_size.coeff(d) - source.coeff(d) : source.coeff(d);
is.loc[d] = point[d] * room_size.coeff(d) + step;
// source order is just the sum of absolute values of reflection indices
is.order += abs(point[d]);
// attenuation can also be computed this way
int p1 = 0, p2 = 0;
if (point[d] > 0)
{
p1 = point[d]/2;
p2 = (point[d]+1)/2;
}
else if (point[d] < 0)
{
p1 = abs((point[d]-1)/2);
p2 = abs(point[d]/2);
}
is.attenuation *= transmission_pwr[2 * D * p1 + 2*d]; // 'west' absorption factor
is.attenuation *= transmission_pwr[2 * D * p2 + 2*d+1]; // 'east' absorption factor
}
}
}
}
// fill linear arrays and return status
return fill_sources();
}
<commit_msg>Corrects a warning in libroom<commit_after>#include <iostream>
#include "room.hpp"
template<size_t D>
int Room<D>::image_source_model(const Eigen::Matrix<float,D,1> &source_location, int max_order)
{
/*
* This is the top-level method to run the image source model
*/
// make sure the list is empty
while (visible_sources.size() > 0)
visible_sources.pop();
// add the original (real) source
ImageSource<D> real_source;
real_source.loc = source_location;
real_source.attenuation = 1.;
real_source.order = 0;
real_source.gen_wall = -1;
real_source.parent = NULL;
// Run the image source model algorithm
image_sources_dfs(real_source, max_order);
// fill the sources array in room and return
return fill_sources();
}
template<size_t D>
int Room<D>::fill_sources()
{
int n_sources = visible_sources.size();
// Create linear arrays to store the image sources
if (n_sources > 0)
{
// resize all the arrays
sources.resize(D, n_sources);
orders.resize(n_sources);
gen_walls.resize(n_sources);
attenuations.resize(n_sources);
visible_mics.resize(microphones.cols(), n_sources);
for (int i = n_sources - 1 ; i >= 0 ; i--)
{
ImageSource<D> &top = visible_sources.top(); // sample top of stack
// fill the arrays
sources.col(i) = top.loc;
gen_walls.coeffRef(i) = top.gen_wall;
orders.coeffRef(i) = top.order;
attenuations.coeffRef(i) = top.attenuation;
visible_mics.col(i) = top.visible_mics;
visible_sources.pop(); // unstack
}
}
return 0;
}
template<size_t D>
void Room<D>::image_sources_dfs(ImageSource<D> &is, int max_order)
{
/*
* This function runs a depth first search (DFS) on the tree of image sources
*/
ImageSource<D> new_is;
// Check the visibility of the source from the different microphones
bool any_visible = false;
for (int mic = 0 ; mic < microphones.cols() ; mic++)
{
bool is_visible = is_visible_dfs(microphones.col(mic), is);
if (is_visible && !any_visible)
{
any_visible = is_visible;
is.visible_mics.resize(microphones.cols());
is.visible_mics.setZero();
}
if (any_visible)
is.visible_mics.coeffRef(mic) = is_visible;
}
if (any_visible)
visible_sources.push(is); // this should push a copy onto the stack
// If we reached maximal depth, stop
if (max_order == 0)
return;
// Then, check all the reflections across the walls
for (size_t wi=0 ; wi < walls.size() ; wi++)
{
int dir = walls[wi].reflect(is.loc, new_is.loc); // the reflected location
// We only check valid reflections (normals should point outward from the room
if (dir <= 0)
continue;
// The reflection is valid, fill in the image source attributes
new_is.attenuation = is.attenuation * (1. - walls[wi].absorption);
new_is.order = is.order + 1;
new_is.gen_wall = wi;
new_is.parent = &is;
// Run the DFS recursion (on the last element in the array, the one we just added)
image_sources_dfs(new_is, max_order - 1);
}
}
template<size_t D>
bool Room<D>::is_visible_dfs(const Eigen::Matrix<float,D,1> &p, ImageSource<D> &is)
{
/*
Returns true if the given sound source (with image source id) is visible from point p.
room - the structure that contains all the sources and stuff
p (np.array size 2 or 3) coordinates of the point where we check visibility
imageId (int) id of the image within the SoundSource object
Returns
False (0) : not visible
True (1) : visible
*/
if (is_obstructed_dfs(p, is))
return false;
if (is.parent != NULL)
{
Eigen::Matrix<float,D,1> intersection;
// get generating wall id
int wall_id = is.gen_wall;
// check if the generating wall is intersected
int ret = walls[wall_id].intersection(p, is.loc, intersection);
// The source is not visible if the ray does not intersect
// the generating wall
if (ret >= 0)
// Check visibility of intersection point from parent source
return is_visible_dfs(intersection, *(is.parent));
else
return false;
}
// If we get here this is the original, unobstructed, source
return true;
}
template<size_t D>
bool Room<D>::is_obstructed_dfs(const Eigen::Matrix<float,D,1> &p, ImageSource<D> &is)
{
/*
Checks if there is a wall obstructing the line of sight going from a source to a point.
room - the structure that contains all the sources and stuff
p (np.array size 2 or 3) coordinates of the point where we check obstruction
imageId (int) id of the image within the SoundSource object
Returns (bool)
False (0) : not obstructed
True (1) : obstructed
*/
int gen_wall_id = is.gen_wall;
// Check candidate walls for obstructions
for (size_t ow = 0 ; ow < obstructing_walls.size() ; ow++)
{
int wall_id = obstructing_walls[ow];
// generating wall can't be obstructive
if (wall_id != gen_wall_id)
{
Eigen::Matrix<float,D,1> intersection;
int ret = walls[wall_id].intersection(is.loc, p, intersection);
// There is an intersection and it is distinct from segment endpoints
if (ret == Wall<D>::Isect::VALID || ret == Wall<D>::Isect::BNDRY)
{
if (is.parent != NULL)
{
// Test if the intersection point and the image are on
// opposite sides of the generating wall
// We ignore the obstruction if it is inside the
// generating wall (it is what happens in a corner)
int img_side = walls[is.gen_wall].side(is.loc);
int intersection_side = walls[is.gen_wall].side(intersection);
if (img_side != intersection_side && intersection_side != 0)
return true;
}
else
return true;
}
}
}
return false;
}
template<size_t D>
int Room<D>::image_source_shoebox(
const Eigen::Matrix<float,D,1> &source,
const Eigen::Matrix<float,D,1> &room_size,
const Eigen::Matrix<float,2*D,1> &absorption,
int max_order
)
{
// precompute powers of the absorption coefficients
std::vector<float> transmission_pwr((max_order + 1) * 2 * D);
for (size_t d = 0 ; d < 2 * D ; d++)
transmission_pwr[d] = 1.;
for (int i = 1 ; i <= max_order ; i++)
for (size_t d = 0 ; d < 2 * D ; d++)
transmission_pwr[i * 2 * D + d] = (1. - absorption[d]) * transmission_pwr[(i-1)*2*D + d];
// make sure the list is empty
while (visible_sources.size() > 0)
visible_sources.pop();
// L1 ball of room images
int point[3] = {0, 0, 0};
// Take 2D case into account
int z_max = max_order;
if (D == 2)
z_max = 0;
// Walk on all the points of the discrete L! ball of radius max_order
for (point[2] = -z_max ; point[2] <= z_max ; point[2]++)
{
int y_max = max_order - abs(point[2]);
for (point[1] = -y_max ; point[1] <= y_max ; point[1]++)
{
int x_max = y_max - abs(point[1]);
if (x_max < 0) x_max = 0;
for (point[0] = -x_max ; point[0] <= x_max ; point[0]++)
{
visible_sources.push(ImageSource<D>());
ImageSource<D> &is = visible_sources.top();
is.visible_mics = VectorXb::Ones(microphones.cols()); // everything is visible
is.order = 0;
is.attenuation = 1.;
is.gen_wall = -1;
// Now compute the reflection, the order, and the multiplicative constant
for (size_t d = 0 ; d < D ; d++)
{
// Compute the reflected source
float step = abs(point[d]) % 2 == 1 ? room_size.coeff(d) - source.coeff(d) : source.coeff(d);
is.loc[d] = point[d] * room_size.coeff(d) + step;
// source order is just the sum of absolute values of reflection indices
is.order += abs(point[d]);
// attenuation can also be computed this way
int p1 = 0, p2 = 0;
if (point[d] > 0)
{
p1 = point[d]/2;
p2 = (point[d]+1)/2;
}
else if (point[d] < 0)
{
p1 = abs((point[d]-1)/2);
p2 = abs(point[d]/2);
}
is.attenuation *= transmission_pwr[2 * D * p1 + 2*d]; // 'west' absorption factor
is.attenuation *= transmission_pwr[2 * D * p2 + 2*d+1]; // 'east' absorption factor
}
}
}
}
// fill linear arrays and return status
return fill_sources();
}
<|endoftext|> |
<commit_before>/*
* opencog/atomspace/AtomSpace.cc
*
* Copyright (c) 2008-2010 OpenCog Foundation
* Copyright (c) 2009, 2013 Linas Vepstas
* All Rights Reserved
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <string>
#include <iostream>
#include <fstream>
#include <list>
#include <stdlib.h>
#include <opencog/util/Logger.h>
#include <opencog/util/oc_assert.h>
#include <opencog/atoms/base/Link.h>
#include <opencog/atoms/base/Node.h>
#include <opencog/atoms/proto/types.h>
#include "AtomSpace.h"
//#define DPRINTF printf
#define DPRINTF(...)
using std::string;
using std::cerr;
using std::cout;
using std::endl;
using std::min;
using std::max;
using namespace opencog;
// ====================================================================
/**
* Transient atomspaces skip some of the initialization steps,
* so that they can be constructed more quickly. Transient atomspaces
* are typically used as scratch spaces, to hold temporary results
* during evaluation, pattern matching and inference. Such temporary
* spaces don't need some of the heavier-weight crud that atomspaces
* are festooned with.
*/
AtomSpace::AtomSpace(AtomSpace* parent, bool transient) :
_atom_table(parent? &parent->_atom_table : nullptr, this, transient),
_backing_store(nullptr),
_read_only(false)
{
}
AtomSpace::~AtomSpace()
{
}
void AtomSpace::ready_transient(AtomSpace* parent)
{
_atom_table.ready_transient(parent? &parent->_atom_table : nullptr, this);
}
void AtomSpace::clear_transient()
{
_atom_table.clear_transient();
}
// An extremely primitive permissions system.
void AtomSpace::set_read_only(void)
{
_read_only = true;
}
void AtomSpace::set_read_write(void)
{
_read_only = false;
}
bool AtomSpace::compare_atomspaces(const AtomSpace& space_first,
const AtomSpace& space_second,
bool check_truth_values,
bool emit_diagnostics)
{
// Compare sizes
if (space_first.get_size() != space_second.get_size())
{
if (emit_diagnostics)
std::cout << "compare_atomspaces - size " <<
space_first.get_size() << " != size " <<
space_second.get_size() << std::endl;
return false;
}
// Compare node count
if (space_first.get_num_nodes() != space_second.get_num_nodes())
{
if (emit_diagnostics)
std::cout << "compare_atomspaces - node count " <<
space_first.get_num_nodes() << " != node count " <<
space_second.get_num_nodes() << std::endl;
return false;
}
// Compare link count
if (space_first.get_num_links() != space_second.get_num_links())
{
if (emit_diagnostics)
std::cout << "compare_atomspaces - link count " <<
space_first.get_num_links() << " != link count " <<
space_second.get_num_links() << std::endl;
return false;
}
// If we get this far, we need to compare each individual atom.
// Get the atoms in each atomspace.
HandleSet atomsInFirstSpace, atomsInSecondSpace;
space_first.get_handleset_by_type(atomsInFirstSpace, ATOM, true);
space_second.get_handleset_by_type(atomsInSecondSpace, ATOM, true);
// Uncheck each atom in the second atomspace.
for (auto atom : atomsInSecondSpace)
atom->setUnchecked();
// Loop to see if each atom in the first has a match in the second.
const AtomTable& table_second = space_second._atom_table;
for (auto atom_first : atomsInFirstSpace)
{
Handle atom_second = table_second.getHandle(atom_first);
if( false)
{
Handle atom_second;
if (atom_first->is_node())
{
atom_second = table_second.getHandle(atom_first->get_type(),
atom_first->get_name());
}
else if (atom_first->is_link())
{
atom_second = table_second.getHandle(atom_first->get_type(),
atom_first->getOutgoingSet());
}
else
{
throw opencog::RuntimeException(TRACE_INFO,
"AtomSpace::compare_atomspaces - atom not Node or Link");
}
}
// If the atoms don't match because one of them is null.
if ((atom_first and not atom_second) or
(atom_second and not atom_first))
{
if (emit_diagnostics)
{
if (atom_first)
std::cout << "compare_atomspaces - first atom " <<
atom_first->to_string() << " != NULL " <<
std::endl;
if (atom_second)
std::cout << "compare_atomspaces - first atom " <<
"NULL != second atom " <<
atom_second->to_string() << std::endl;
}
return false;
}
// If the atoms don't match... Compare the atoms not the pointers
// which is the default if we just use Handle operator ==.
if (*((AtomPtr) atom_first) != *((AtomPtr) atom_second))
{
if (emit_diagnostics)
std::cout << "compare_atomspaces - first atom " <<
atom_first->to_string() << " != second atom " <<
atom_second->to_string() << std::endl;
return false;
}
// Check the truth values...
if (check_truth_values)
{
TruthValuePtr truth_first = atom_first->getTruthValue();
TruthValuePtr truth_second = atom_second->getTruthValue();
if (*truth_first != *truth_second)
{
if (emit_diagnostics)
std::cout << "compare_atomspaces - first truth " <<
atom_first->to_string() << " != second truth " <<
atom_second->to_string() << std::endl;
return false;
}
}
// Set the check for the second atom.
atom_second->setChecked();
}
// Make sure each atom in the second atomspace has been checked.
bool all_checked = true;
for (auto atom : atomsInSecondSpace)
{
if (!atom->isChecked())
{
if (emit_diagnostics)
std::cout << "compare_atomspaces - unchecked space atom " <<
atom->to_string() << std::endl;
all_checked = false;
}
}
if (!all_checked)
return false;
// If we get this far, then the spaces are equal.
return true;
}
bool AtomSpace::operator==(const AtomSpace& other) const
{
return compare_atomspaces(*this, other, CHECK_TRUTH_VALUES,
DONT_EMIT_DIAGNOSTICS);
}
bool AtomSpace::operator!=(const AtomSpace& other) const
{
return not operator==(other);
}
// ====================================================================
bool AtomSpace::isAttachedToBackingStore()
{
if (nullptr != _backing_store) return true;
return false;
}
void AtomSpace::registerBackingStore(BackingStore *bs)
{
if (isAttachedToBackingStore())
throw RuntimeException(TRACE_INFO,
"AtomSpace is already connected to a BackingStore.");
_backing_store = bs;
}
void AtomSpace::unregisterBackingStore(BackingStore *bs)
{
if (not isAttachedToBackingStore())
throw RuntimeException(TRACE_INFO,
"AtomSpace is not connected to a BackingStore.");
if (bs == _backing_store) _backing_store = nullptr;
}
// ====================================================================
Handle AtomSpace::add_atom(const Handle& h, bool async)
{
// Cannot add atoms to a read-only atomspce. But if it's already
// in the atomspace, return it.
if (_read_only) return _atom_table.getHandle(h);
// If it is a DeleteLink, then the addition will fail. Deal with it.
Handle rh;
try {
rh = _atom_table.add(h, async);
}
catch (const DeleteException& ex) {
// Atom deletion has not been implemented in the backing store
// This is a major to-do item.
if (_backing_store)
_backing_store->removeAtom(h, false);
}
return rh;
}
Handle AtomSpace::add_node(Type t, const string& name,
bool async)
{
// Cannot add atoms to a read-only atomspce. But if it's already
// in the atomspace, return it.
if (_read_only) return _atom_table.getHandle(t, name);
return _atom_table.add(createNode(t, name), async);
}
Handle AtomSpace::get_node(Type t, const string& name)
{
return _atom_table.getHandle(t, name);
}
Handle AtomSpace::add_link(Type t, const HandleSeq& outgoing, bool async)
{
// Cannot add atoms to a read-only atomspce. But if it's already
// in the atomspace, return it.
if (_read_only) return _atom_table.getHandle(t, outgoing);
// If it is a DeleteLink, then the addition will fail. Deal with it.
Handle rh;
try {
rh = _atom_table.add(createLink(outgoing, t), async);
}
catch (const DeleteException& ex) {
if (_backing_store) {
Handle h(createLink(outgoing, t));
_backing_store->removeAtom(h, false);
}
}
return rh;
}
Handle AtomSpace::get_link(Type t, const HandleSeq& outgoing)
{
return _atom_table.getHandle(t, outgoing);
}
void AtomSpace::store_atom(const Handle& h)
{
if (nullptr == _backing_store)
throw RuntimeException(TRACE_INFO, "No backing store");
if (_read_only)
throw RuntimeException(TRACE_INFO, "Read-only AtomSpace!");
_backing_store->storeAtom(h);
}
Handle AtomSpace::fetch_atom(const Handle& h)
{
if (nullptr == _backing_store)
throw RuntimeException(TRACE_INFO, "No backing store");
if (nullptr == h) return Handle::UNDEFINED;
// Now, get the latest values from the backing store.
// The operation here is to CLOBBER the values, NOT to merge them!
// The goal of an explicit fetch is to explicitly fetch the values,
// and not to play monkey-shines with them. If you want something
// else, then save the old TV, fetch the new TV, and combine them
// with your favorite algo.
Handle hv;
if (h->is_node()) {
hv = _backing_store->getNode(h->get_type(),
h->get_name().c_str());
}
else if (h->is_link()) {
hv = _backing_store->getLink(h->get_type(),
h->getOutgoingSet());
}
// If we found it, add it to the atomspace -- even when the
// atomspace is marked read-only; the atomspace is acting as
// a cache for the backingstore.
if (hv) return _atom_table.add(hv, false);
// If it is not found, then it cannot be added.
if (_read_only) return Handle::UNDEFINED;
return _atom_table.add(h, false);
}
Handle AtomSpace::fetch_incoming_set(Handle h, bool recursive)
{
if (nullptr == _backing_store)
throw RuntimeException(TRACE_INFO, "No backing store");
h = get_atom(h);
if (nullptr == h) return h;
// Get everything from the backing store.
_backing_store->getIncomingSet(_atom_table, h);
if (not recursive) return h;
IncomingSet vh(h->getIncomingSet());
for (const LinkPtr& lp : vh)
fetch_incoming_set(Handle(lp), true);
return h;
}
Handle AtomSpace::fetch_incoming_by_type(Handle h, Type t)
{
if (nullptr == _backing_store)
throw RuntimeException(TRACE_INFO, "No backing store");
h = get_atom(h);
if (nullptr == h) return h;
// Get everything from the backing store.
_backing_store->getIncomingByType(_atom_table, h, t);
return h;
}
void AtomSpace::fetch_valuations(Handle key, bool get_all_values)
{
if (nullptr == _backing_store)
throw RuntimeException(TRACE_INFO, "No backing store");
key = get_atom(key);
if (nullptr == key) return;
// Get everything from the backing store.
_backing_store->getValuations(_atom_table, key, get_all_values);
}
bool AtomSpace::remove_atom(Handle h, bool recursive)
{
// Removal of atoms from read-only databases is not allowed.
// It is OK to remove atoms from a read-only atomspace, because
// it is acting as a cache for the database, and removal is used
// used to free up RAM storage.
if (_backing_store and not _read_only)
_backing_store->removeAtom(h, recursive);
return 0 < _atom_table.extract(h, recursive).size();
}
// Copy-on-write for setting values.
Handle AtomSpace::set_value(const Handle& h,
const Handle& key,
const ProtoAtomPtr& value)
{
// If the atom is in a read-only atomspace (i.e. if the parent
// is read-only) and this atomspace is read-write, then make
// a copy of the atom, and then set the value.
AtomSpace* has = h->getAtomSpace();
if (has->_read_only) {
if (has != this and not _read_only) {
// Copy the atom into this atomspace
Handle copy(_atom_table.add(h, false, true));
copy->setValue(key, value);
return copy;
}
} else {
h->setValue(key, value);
return h;
}
throw opencog::RuntimeException(TRACE_INFO,
"Value not changed; AtomSpace is readonly");
return Handle::UNDEFINED;
}
// Copy-on-write for setting truth values.
Handle AtomSpace::set_truthvalue(const Handle& h, const TruthValuePtr& tvp)
{
// If the atom is in a read-only atomspace (i.e. if the parent
// is read-only) and this atomspace is read-write, then make
// a copy of the atom, and then set the value.
AtomSpace* has = h->getAtomSpace();
if (has->_read_only) {
if (has != this and not _read_only) {
// Copy the atom into this atomspace
Handle copy(_atom_table.add(h, false, true));
copy->setTruthValue(tvp);
return copy;
}
} else {
h->setTruthValue(tvp);
return h;
}
throw opencog::RuntimeException(TRACE_INFO,
"TruthValue not changed; AtomSpace is readonly");
return Handle::UNDEFINED;
}
std::string AtomSpace::to_string() const
{
std::stringstream ss;
ss << *this;
return ss.str();
}
namespace std {
ostream& operator<<(ostream& out, const opencog::AtomSpace& as) {
list<opencog::Handle> results;
as.get_handles_by_type(back_inserter(results), opencog::ATOM, true);
for (const opencog::Handle& h : results)
if (h->getIncomingSetSize() == 0)
out << h->to_string() << endl;
return out;
}
} // namespace std
<commit_msg>Typos<commit_after>/*
* opencog/atomspace/AtomSpace.cc
*
* Copyright (c) 2008-2010 OpenCog Foundation
* Copyright (c) 2009, 2013 Linas Vepstas
* All Rights Reserved
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <string>
#include <iostream>
#include <fstream>
#include <list>
#include <stdlib.h>
#include <opencog/util/Logger.h>
#include <opencog/util/oc_assert.h>
#include <opencog/atoms/base/Link.h>
#include <opencog/atoms/base/Node.h>
#include <opencog/atoms/proto/types.h>
#include "AtomSpace.h"
//#define DPRINTF printf
#define DPRINTF(...)
using std::string;
using std::cerr;
using std::cout;
using std::endl;
using std::min;
using std::max;
using namespace opencog;
// ====================================================================
/**
* Transient atomspaces skip some of the initialization steps,
* so that they can be constructed more quickly. Transient atomspaces
* are typically used as scratch spaces, to hold temporary results
* during evaluation, pattern matching and inference. Such temporary
* spaces don't need some of the heavier-weight crud that atomspaces
* are festooned with.
*/
AtomSpace::AtomSpace(AtomSpace* parent, bool transient) :
_atom_table(parent? &parent->_atom_table : nullptr, this, transient),
_backing_store(nullptr),
_read_only(false)
{
}
AtomSpace::~AtomSpace()
{
}
void AtomSpace::ready_transient(AtomSpace* parent)
{
_atom_table.ready_transient(parent? &parent->_atom_table : nullptr, this);
}
void AtomSpace::clear_transient()
{
_atom_table.clear_transient();
}
// An extremely primitive permissions system.
void AtomSpace::set_read_only(void)
{
_read_only = true;
}
void AtomSpace::set_read_write(void)
{
_read_only = false;
}
bool AtomSpace::compare_atomspaces(const AtomSpace& space_first,
const AtomSpace& space_second,
bool check_truth_values,
bool emit_diagnostics)
{
// Compare sizes
if (space_first.get_size() != space_second.get_size())
{
if (emit_diagnostics)
std::cout << "compare_atomspaces - size " <<
space_first.get_size() << " != size " <<
space_second.get_size() << std::endl;
return false;
}
// Compare node count
if (space_first.get_num_nodes() != space_second.get_num_nodes())
{
if (emit_diagnostics)
std::cout << "compare_atomspaces - node count " <<
space_first.get_num_nodes() << " != node count " <<
space_second.get_num_nodes() << std::endl;
return false;
}
// Compare link count
if (space_first.get_num_links() != space_second.get_num_links())
{
if (emit_diagnostics)
std::cout << "compare_atomspaces - link count " <<
space_first.get_num_links() << " != link count " <<
space_second.get_num_links() << std::endl;
return false;
}
// If we get this far, we need to compare each individual atom.
// Get the atoms in each atomspace.
HandleSet atomsInFirstSpace, atomsInSecondSpace;
space_first.get_handleset_by_type(atomsInFirstSpace, ATOM, true);
space_second.get_handleset_by_type(atomsInSecondSpace, ATOM, true);
// Uncheck each atom in the second atomspace.
for (auto atom : atomsInSecondSpace)
atom->setUnchecked();
// Loop to see if each atom in the first has a match in the second.
const AtomTable& table_second = space_second._atom_table;
for (auto atom_first : atomsInFirstSpace)
{
Handle atom_second = table_second.getHandle(atom_first);
if( false)
{
Handle atom_second;
if (atom_first->is_node())
{
atom_second = table_second.getHandle(atom_first->get_type(),
atom_first->get_name());
}
else if (atom_first->is_link())
{
atom_second = table_second.getHandle(atom_first->get_type(),
atom_first->getOutgoingSet());
}
else
{
throw opencog::RuntimeException(TRACE_INFO,
"AtomSpace::compare_atomspaces - atom not Node or Link");
}
}
// If the atoms don't match because one of them is null.
if ((atom_first and not atom_second) or
(atom_second and not atom_first))
{
if (emit_diagnostics)
{
if (atom_first)
std::cout << "compare_atomspaces - first atom " <<
atom_first->to_string() << " != NULL " <<
std::endl;
if (atom_second)
std::cout << "compare_atomspaces - first atom " <<
"NULL != second atom " <<
atom_second->to_string() << std::endl;
}
return false;
}
// If the atoms don't match... Compare the atoms not the pointers
// which is the default if we just use Handle operator ==.
if (*((AtomPtr) atom_first) != *((AtomPtr) atom_second))
{
if (emit_diagnostics)
std::cout << "compare_atomspaces - first atom " <<
atom_first->to_string() << " != second atom " <<
atom_second->to_string() << std::endl;
return false;
}
// Check the truth values...
if (check_truth_values)
{
TruthValuePtr truth_first = atom_first->getTruthValue();
TruthValuePtr truth_second = atom_second->getTruthValue();
if (*truth_first != *truth_second)
{
if (emit_diagnostics)
std::cout << "compare_atomspaces - first truth " <<
atom_first->to_string() << " != second truth " <<
atom_second->to_string() << std::endl;
return false;
}
}
// Set the check for the second atom.
atom_second->setChecked();
}
// Make sure each atom in the second atomspace has been checked.
bool all_checked = true;
for (auto atom : atomsInSecondSpace)
{
if (!atom->isChecked())
{
if (emit_diagnostics)
std::cout << "compare_atomspaces - unchecked space atom " <<
atom->to_string() << std::endl;
all_checked = false;
}
}
if (!all_checked)
return false;
// If we get this far, then the spaces are equal.
return true;
}
bool AtomSpace::operator==(const AtomSpace& other) const
{
return compare_atomspaces(*this, other, CHECK_TRUTH_VALUES,
DONT_EMIT_DIAGNOSTICS);
}
bool AtomSpace::operator!=(const AtomSpace& other) const
{
return not operator==(other);
}
// ====================================================================
bool AtomSpace::isAttachedToBackingStore()
{
if (nullptr != _backing_store) return true;
return false;
}
void AtomSpace::registerBackingStore(BackingStore *bs)
{
if (isAttachedToBackingStore())
throw RuntimeException(TRACE_INFO,
"AtomSpace is already connected to a BackingStore.");
_backing_store = bs;
}
void AtomSpace::unregisterBackingStore(BackingStore *bs)
{
if (not isAttachedToBackingStore())
throw RuntimeException(TRACE_INFO,
"AtomSpace is not connected to a BackingStore.");
if (bs == _backing_store) _backing_store = nullptr;
}
// ====================================================================
Handle AtomSpace::add_atom(const Handle& h, bool async)
{
// Cannot add atoms to a read-only atomspace. But if it's already
// in the atomspace, return it.
if (_read_only) return _atom_table.getHandle(h);
// If it is a DeleteLink, then the addition will fail. Deal with it.
Handle rh;
try {
rh = _atom_table.add(h, async);
}
catch (const DeleteException& ex) {
// Atom deletion has not been implemented in the backing store
// This is a major to-do item.
if (_backing_store)
_backing_store->removeAtom(h, false);
}
return rh;
}
Handle AtomSpace::add_node(Type t, const string& name,
bool async)
{
// Cannot add atoms to a read-only atomspace. But if it's already
// in the atomspace, return it.
if (_read_only) return _atom_table.getHandle(t, name);
return _atom_table.add(createNode(t, name), async);
}
Handle AtomSpace::get_node(Type t, const string& name)
{
return _atom_table.getHandle(t, name);
}
Handle AtomSpace::add_link(Type t, const HandleSeq& outgoing, bool async)
{
// Cannot add atoms to a read-only atomspace. But if it's already
// in the atomspace, return it.
if (_read_only) return _atom_table.getHandle(t, outgoing);
// If it is a DeleteLink, then the addition will fail. Deal with it.
Handle rh;
try {
rh = _atom_table.add(createLink(outgoing, t), async);
}
catch (const DeleteException& ex) {
if (_backing_store) {
Handle h(createLink(outgoing, t));
_backing_store->removeAtom(h, false);
}
}
return rh;
}
Handle AtomSpace::get_link(Type t, const HandleSeq& outgoing)
{
return _atom_table.getHandle(t, outgoing);
}
void AtomSpace::store_atom(const Handle& h)
{
if (nullptr == _backing_store)
throw RuntimeException(TRACE_INFO, "No backing store");
if (_read_only)
throw RuntimeException(TRACE_INFO, "Read-only AtomSpace!");
_backing_store->storeAtom(h);
}
Handle AtomSpace::fetch_atom(const Handle& h)
{
if (nullptr == _backing_store)
throw RuntimeException(TRACE_INFO, "No backing store");
if (nullptr == h) return Handle::UNDEFINED;
// Now, get the latest values from the backing store.
// The operation here is to CLOBBER the values, NOT to merge them!
// The goal of an explicit fetch is to explicitly fetch the values,
// and not to play monkey-shines with them. If you want something
// else, then save the old TV, fetch the new TV, and combine them
// with your favorite algo.
Handle hv;
if (h->is_node()) {
hv = _backing_store->getNode(h->get_type(),
h->get_name().c_str());
}
else if (h->is_link()) {
hv = _backing_store->getLink(h->get_type(),
h->getOutgoingSet());
}
// If we found it, add it to the atomspace -- even when the
// atomspace is marked read-only; the atomspace is acting as
// a cache for the backingstore.
if (hv) return _atom_table.add(hv, false);
// If it is not found, then it cannot be added.
if (_read_only) return Handle::UNDEFINED;
return _atom_table.add(h, false);
}
Handle AtomSpace::fetch_incoming_set(Handle h, bool recursive)
{
if (nullptr == _backing_store)
throw RuntimeException(TRACE_INFO, "No backing store");
h = get_atom(h);
if (nullptr == h) return h;
// Get everything from the backing store.
_backing_store->getIncomingSet(_atom_table, h);
if (not recursive) return h;
IncomingSet vh(h->getIncomingSet());
for (const LinkPtr& lp : vh)
fetch_incoming_set(Handle(lp), true);
return h;
}
Handle AtomSpace::fetch_incoming_by_type(Handle h, Type t)
{
if (nullptr == _backing_store)
throw RuntimeException(TRACE_INFO, "No backing store");
h = get_atom(h);
if (nullptr == h) return h;
// Get everything from the backing store.
_backing_store->getIncomingByType(_atom_table, h, t);
return h;
}
void AtomSpace::fetch_valuations(Handle key, bool get_all_values)
{
if (nullptr == _backing_store)
throw RuntimeException(TRACE_INFO, "No backing store");
key = get_atom(key);
if (nullptr == key) return;
// Get everything from the backing store.
_backing_store->getValuations(_atom_table, key, get_all_values);
}
bool AtomSpace::remove_atom(Handle h, bool recursive)
{
// Removal of atoms from read-only databases is not allowed.
// It is OK to remove atoms from a read-only atomspace, because
// it is acting as a cache for the database, and removal is used
// used to free up RAM storage.
if (_backing_store and not _read_only)
_backing_store->removeAtom(h, recursive);
return 0 < _atom_table.extract(h, recursive).size();
}
// Copy-on-write for setting values.
Handle AtomSpace::set_value(const Handle& h,
const Handle& key,
const ProtoAtomPtr& value)
{
// If the atom is in a read-only atomspace (i.e. if the parent
// is read-only) and this atomspace is read-write, then make
// a copy of the atom, and then set the value.
AtomSpace* has = h->getAtomSpace();
if (has->_read_only) {
if (has != this and not _read_only) {
// Copy the atom into this atomspace
Handle copy(_atom_table.add(h, false, true));
copy->setValue(key, value);
return copy;
}
} else {
h->setValue(key, value);
return h;
}
throw opencog::RuntimeException(TRACE_INFO,
"Value not changed; AtomSpace is readonly");
return Handle::UNDEFINED;
}
// Copy-on-write for setting truth values.
Handle AtomSpace::set_truthvalue(const Handle& h, const TruthValuePtr& tvp)
{
// If the atom is in a read-only atomspace (i.e. if the parent
// is read-only) and this atomspace is read-write, then make
// a copy of the atom, and then set the value.
AtomSpace* has = h->getAtomSpace();
if (has->_read_only) {
if (has != this and not _read_only) {
// Copy the atom into this atomspace
Handle copy(_atom_table.add(h, false, true));
copy->setTruthValue(tvp);
return copy;
}
} else {
h->setTruthValue(tvp);
return h;
}
throw opencog::RuntimeException(TRACE_INFO,
"TruthValue not changed; AtomSpace is readonly");
return Handle::UNDEFINED;
}
std::string AtomSpace::to_string() const
{
std::stringstream ss;
ss << *this;
return ss.str();
}
namespace std {
ostream& operator<<(ostream& out, const opencog::AtomSpace& as) {
list<opencog::Handle> results;
as.get_handles_by_type(back_inserter(results), opencog::ATOM, true);
for (const opencog::Handle& h : results)
if (h->getIncomingSetSize() == 0)
out << h->to_string() << endl;
return out;
}
} // namespace std
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. Use of this
// source code is governed by a BSD-style license that can be found in the
// LICENSE file.
#include "chrome/renderer/media/video_renderer_impl.h"
#include "media/base/yuv_convert.h"
VideoRendererImpl::VideoRendererImpl(WebMediaPlayerDelegateImpl* delegate)
: delegate_(delegate),
last_converted_frame_(NULL) {
}
bool VideoRendererImpl::OnInitialize(size_t width, size_t height) {
video_size_.SetSize(width, height);
bitmap_.setConfig(SkBitmap::kARGB_8888_Config, width, height);
if (bitmap_.allocPixels(NULL, NULL)) {
bitmap_.eraseRGB(0x00, 0x00, 0x00);
return true;
}
NOTREACHED();
return false;
}
void VideoRendererImpl::OnPaintNeeded() {
delegate_->PostRepaintTask();
}
// This method is always called on the renderer's thread.
void VideoRendererImpl::Paint(skia::PlatformCanvas* canvas,
const gfx::Rect& dest_rect) {
scoped_refptr<media::VideoFrame> video_frame;
GetCurrentFrame(&video_frame);
if (video_frame.get()) {
CopyToCurrentFrame(video_frame);
video_frame = NULL;
}
SkMatrix matrix;
matrix.setTranslate(static_cast<SkScalar>(dest_rect.x()),
static_cast<SkScalar>(dest_rect.y()));
if (dest_rect.width() != video_size_.width() ||
dest_rect.height() != video_size_.height()) {
matrix.preScale(
static_cast<SkScalar>(dest_rect.width() / video_size_.width()),
static_cast<SkScalar>(dest_rect.height() / video_size_.height()));
}
canvas->drawBitmapMatrix(bitmap_, matrix, NULL);
}
void VideoRendererImpl::CopyToCurrentFrame(media::VideoFrame* video_frame) {
base::TimeDelta timestamp = video_frame->GetTimestamp();
if (video_frame != last_converted_frame_ ||
timestamp != last_converted_timestamp_) {
last_converted_frame_ = video_frame;
last_converted_timestamp_ = timestamp;
media::VideoSurface frame_in;
if (video_frame->Lock(&frame_in)) {
// TODO(hclam): Support more video formats than just YV12.
DCHECK(frame_in.format == media::VideoSurface::YV12);
DCHECK(frame_in.strides[media::VideoSurface::kUPlane] ==
frame_in.strides[media::VideoSurface::kVPlane]);
DCHECK(frame_in.planes == media::VideoSurface::kNumYUVPlanes);
bitmap_.lockPixels();
media::ConvertYV12ToRGB32(frame_in.data[media::VideoSurface::kYPlane],
frame_in.data[media::VideoSurface::kUPlane],
frame_in.data[media::VideoSurface::kVPlane],
static_cast<uint8*>(bitmap_.getPixels()),
frame_in.width,
frame_in.height,
frame_in.strides[media::VideoSurface::kYPlane],
frame_in.strides[media::VideoSurface::kUPlane],
bitmap_.rowBytes());
bitmap_.unlockPixels();
video_frame->Unlock();
} else {
NOTREACHED();
}
}
}
<commit_msg>TBR=ralphl<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. Use of this
// source code is governed by a BSD-style license that can be found in the
// LICENSE file.
#include "chrome/renderer/media/video_renderer_impl.h"
#include "media/base/yuv_convert.h"
VideoRendererImpl::VideoRendererImpl(WebMediaPlayerDelegateImpl* delegate)
: delegate_(delegate),
last_converted_frame_(NULL) {
// TODO(hclam): decide whether to do the following line in this thread or
// in the render thread.
delegate_->SetVideoRenderer(this);
}
bool VideoRendererImpl::OnInitialize(size_t width, size_t height) {
video_size_.SetSize(width, height);
bitmap_.setConfig(SkBitmap::kARGB_8888_Config, width, height);
if (bitmap_.allocPixels(NULL, NULL)) {
bitmap_.eraseRGB(0x00, 0x00, 0x00);
return true;
}
NOTREACHED();
return false;
}
void VideoRendererImpl::OnPaintNeeded() {
delegate_->PostRepaintTask();
}
// This method is always called on the renderer's thread.
void VideoRendererImpl::Paint(skia::PlatformCanvas* canvas,
const gfx::Rect& dest_rect) {
scoped_refptr<media::VideoFrame> video_frame;
GetCurrentFrame(&video_frame);
if (video_frame.get()) {
CopyToCurrentFrame(video_frame);
video_frame = NULL;
}
SkMatrix matrix;
matrix.setTranslate(static_cast<SkScalar>(dest_rect.x()),
static_cast<SkScalar>(dest_rect.y()));
if (dest_rect.width() != video_size_.width() ||
dest_rect.height() != video_size_.height()) {
matrix.preScale(
static_cast<SkScalar>(dest_rect.width() / video_size_.width()),
static_cast<SkScalar>(dest_rect.height() / video_size_.height()));
}
canvas->drawBitmapMatrix(bitmap_, matrix, NULL);
}
void VideoRendererImpl::CopyToCurrentFrame(media::VideoFrame* video_frame) {
base::TimeDelta timestamp = video_frame->GetTimestamp();
if (video_frame != last_converted_frame_ ||
timestamp != last_converted_timestamp_) {
last_converted_frame_ = video_frame;
last_converted_timestamp_ = timestamp;
media::VideoSurface frame_in;
if (video_frame->Lock(&frame_in)) {
// TODO(hclam): Support more video formats than just YV12.
DCHECK(frame_in.format == media::VideoSurface::YV12);
DCHECK(frame_in.strides[media::VideoSurface::kUPlane] ==
frame_in.strides[media::VideoSurface::kVPlane]);
DCHECK(frame_in.planes == media::VideoSurface::kNumYUVPlanes);
bitmap_.lockPixels();
media::ConvertYV12ToRGB32(frame_in.data[media::VideoSurface::kYPlane],
frame_in.data[media::VideoSurface::kUPlane],
frame_in.data[media::VideoSurface::kVPlane],
static_cast<uint8*>(bitmap_.getPixels()),
frame_in.width,
frame_in.height,
frame_in.strides[media::VideoSurface::kYPlane],
frame_in.strides[media::VideoSurface::kUPlane],
bitmap_.rowBytes());
bitmap_.unlockPixels();
video_frame->Unlock();
} else {
NOTREACHED();
}
}
}
<|endoftext|> |
<commit_before><commit_msg>Fix clang warning in UDPSocketTest.<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/renderer/render_widget_fullscreen_pepper.h"
#include "chrome/common/render_messages.h"
#include "chrome/renderer/ggl/ggl.h"
#include "chrome/renderer/gpu_channel_host.h"
#include "chrome/renderer/pepper_platform_context_3d_impl.h"
#include "chrome/renderer/render_thread.h"
#include "gpu/command_buffer/client/gles2_implementation.h"
#include "third_party/WebKit/WebKit/chromium/public/WebCursorInfo.h"
#include "third_party/WebKit/WebKit/chromium/public/WebSize.h"
#include "third_party/WebKit/WebKit/chromium/public/WebWidget.h"
#include "webkit/plugins/ppapi/plugin_delegate.h"
#include "webkit/plugins/ppapi/ppapi_plugin_instance.h"
using WebKit::WebCanvas;
using WebKit::WebCompositionUnderline;
using WebKit::WebCursorInfo;
using WebKit::WebInputEvent;
using WebKit::WebRect;
using WebKit::WebSize;
using WebKit::WebString;
using WebKit::WebTextDirection;
using WebKit::WebTextInputType;
using WebKit::WebVector;
using WebKit::WebWidget;
namespace {
// WebWidget that simply wraps the pepper plugin.
class PepperWidget : public WebWidget {
public:
PepperWidget(webkit::ppapi::PluginInstance* plugin,
RenderWidgetFullscreenPepper* widget)
: plugin_(plugin),
widget_(widget),
cursor_(WebCursorInfo::TypePointer) {
}
// WebWidget API
virtual void close() {
delete this;
}
virtual WebSize size() {
return size_;
}
virtual void resize(const WebSize& size) {
size_ = size;
WebRect plugin_rect(0, 0, size_.width, size_.height);
plugin_->ViewChanged(plugin_rect, plugin_rect);
widget_->Invalidate();
}
virtual void clearCurrentAnimationTime() {
}
virtual void layout() {
}
virtual void paint(WebCanvas* canvas, const WebRect& rect) {
if (!plugin_)
return;
WebRect plugin_rect(0, 0, size_.width, size_.height);
plugin_->Paint(canvas, plugin_rect, rect);
}
virtual void composite(bool finish) {
ggl::Context* context = widget_->context();
DCHECK(context);
gpu::gles2::GLES2Implementation* gl = ggl::GetImplementation(context);
unsigned int texture = plugin_->GetBackingTextureId();
gl->BindTexture(GL_TEXTURE_2D, texture);
gl->DrawArrays(GL_TRIANGLES, 0, 3);
ggl::SwapBuffers(context);
}
virtual void themeChanged() {
NOTIMPLEMENTED();
}
virtual bool handleInputEvent(const WebInputEvent& event) {
if (!plugin_)
return false;
return plugin_->HandleInputEvent(event, &cursor_);
}
virtual void mouseCaptureLost() {
NOTIMPLEMENTED();
}
virtual void setFocus(bool focus) {
NOTIMPLEMENTED();
}
virtual bool setComposition(
const WebString& text,
const WebVector<WebCompositionUnderline>& underlines,
int selectionStart,
int selectionEnd) {
NOTIMPLEMENTED();
return false;
}
virtual bool confirmComposition() {
NOTIMPLEMENTED();
return false;
}
virtual bool confirmComposition(const WebString& text) {
NOTIMPLEMENTED();
return false;
}
virtual WebTextInputType textInputType() {
NOTIMPLEMENTED();
return WebKit::WebTextInputTypeNone;
}
virtual WebRect caretOrSelectionBounds() {
NOTIMPLEMENTED();
return WebRect();
}
virtual void setTextDirection(WebTextDirection) {
NOTIMPLEMENTED();
}
virtual bool isAcceleratedCompositingActive() const {
return widget_->context() && plugin_ &&
(plugin_->GetBackingTextureId() != 0);
}
private:
webkit::ppapi::PluginInstance* plugin_;
RenderWidgetFullscreenPepper* widget_;
WebSize size_;
WebCursorInfo cursor_;
DISALLOW_COPY_AND_ASSIGN(PepperWidget);
};
} // anonymous namespace
// static
RenderWidgetFullscreenPepper* RenderWidgetFullscreenPepper::Create(
int32 opener_id, RenderThreadBase* render_thread,
webkit::ppapi::PluginInstance* plugin) {
DCHECK_NE(MSG_ROUTING_NONE, opener_id);
scoped_refptr<RenderWidgetFullscreenPepper> widget(
new RenderWidgetFullscreenPepper(render_thread, plugin));
widget->Init(opener_id);
return widget.release();
}
RenderWidgetFullscreenPepper::RenderWidgetFullscreenPepper(
RenderThreadBase* render_thread,
webkit::ppapi::PluginInstance* plugin)
: RenderWidgetFullscreen(render_thread, WebKit::WebPopupTypeSelect),
plugin_(plugin),
#if defined(OS_MACOSX)
plugin_handle_(NULL),
#endif
context_(NULL),
buffer_(0),
program_(0) {
}
RenderWidgetFullscreenPepper::~RenderWidgetFullscreenPepper() {
DestroyContext();
}
void RenderWidgetFullscreenPepper::Invalidate() {
InvalidateRect(gfx::Rect(size_.width(), size_.height()));
}
void RenderWidgetFullscreenPepper::InvalidateRect(const WebKit::WebRect& rect) {
if (CheckCompositing()) {
scheduleComposite();
} else {
didInvalidateRect(rect);
}
}
void RenderWidgetFullscreenPepper::ScrollRect(
int dx, int dy, const WebKit::WebRect& rect) {
if (CheckCompositing()) {
scheduleComposite();
} else {
didScrollRect(dx, dy, rect);
}
}
void RenderWidgetFullscreenPepper::Destroy() {
// This function is called by the plugin instance as it's going away, so reset
// plugin_ to NULL to avoid calling into a dangling pointer e.g. on Close().
plugin_ = NULL;
Send(new ViewHostMsg_Close(routing_id_));
}
webkit::ppapi::PluginDelegate::PlatformContext3D*
RenderWidgetFullscreenPepper::CreateContext3D() {
if (!context_) {
CreateContext();
}
if (!context_)
return NULL;
return new PlatformContext3DImpl(context_);
}
void RenderWidgetFullscreenPepper::DidInitiatePaint() {
if (plugin_)
plugin_->ViewInitiatedPaint();
}
void RenderWidgetFullscreenPepper::DidFlushPaint() {
if (plugin_)
plugin_->ViewFlushedPaint();
}
void RenderWidgetFullscreenPepper::Close() {
// If the fullscreen window is closed (e.g. user pressed escape), reset to
// normal mode.
if (plugin_)
plugin_->SetFullscreen(false);
}
webkit::ppapi::PluginInstance*
RenderWidgetFullscreenPepper::GetBitmapForOptimizedPluginPaint(
const gfx::Rect& paint_bounds,
TransportDIB** dib,
gfx::Rect* location,
gfx::Rect* clip) {
if (plugin_ &&
plugin_->GetBitmapForOptimizedPluginPaint(paint_bounds, dib,
location, clip))
return plugin_;
return NULL;
}
void RenderWidgetFullscreenPepper::OnResize(const gfx::Size& size,
const gfx::Rect& resizer_rect) {
if (context_) {
gpu::gles2::GLES2Implementation* gl = ggl::GetImplementation(context_);
#if defined(OS_MACOSX)
ggl::ResizeOnscreenContext(context_, size);
#else
gl->ResizeCHROMIUM(size.width(), size.height());
#endif
gl->Viewport(0, 0, size.width(), size.height());
}
RenderWidget::OnResize(size, resizer_rect);
}
WebWidget* RenderWidgetFullscreenPepper::CreateWebWidget() {
return new PepperWidget(plugin_, this);
}
void RenderWidgetFullscreenPepper::CreateContext() {
DCHECK(!context_);
RenderThread* render_thread = RenderThread::current();
DCHECK(render_thread);
GpuChannelHost* host = render_thread->EstablishGpuChannelSync();
if (!host)
return;
gfx::NativeViewId view_id;
#if !defined(OS_MACOSX)
view_id = host_window();
#else
Send(new ViewHostMsg_AllocateFakePluginWindowHandle(
routing_id(), true, true, &plugin_handle_));
if (!plugin_handle_)
return;
view_id = static_cast<gfx::NativeViewId>(plugin_handle_);
#endif
const int32 attribs[] = {
ggl::GGL_ALPHA_SIZE, 8,
ggl::GGL_DEPTH_SIZE, 0,
ggl::GGL_STENCIL_SIZE, 0,
ggl::GGL_SAMPLES, 0,
ggl::GGL_SAMPLE_BUFFERS, 0,
ggl::GGL_NONE,
};
context_ = ggl::CreateViewContext(
host,
view_id,
routing_id(),
"GL_OES_packed_depth_stencil GL_OES_depth24",
attribs);
if (!context_ || !InitContext()) {
DestroyContext();
return;
}
ggl::SetSwapBuffersCallback(
context_,
NewCallback(this, &RenderWidgetFullscreenPepper::DidFlushPaint));
}
void RenderWidgetFullscreenPepper::DestroyContext() {
if (context_) {
gpu::gles2::GLES2Implementation* gl = ggl::GetImplementation(context_);
if (program_) {
gl->DeleteProgram(program_);
program_ = 0;
}
if (buffer_) {
gl->DeleteBuffers(1, &buffer_);
buffer_ = 0;
}
ggl::DestroyContext(context_);
context_ = NULL;
}
#if defined(OS_MACOSX)
if (plugin_handle_) {
Send(new ViewHostMsg_DestroyFakePluginWindowHandle(routing_id(),
plugin_handle_));
plugin_handle_ = NULL;
}
#endif
}
namespace {
const char kVertexShader[] =
"attribute vec2 in_tex_coord;\n"
"varying vec2 tex_coord;\n"
"void main() {\n"
" gl_Position = vec4(in_tex_coord.x * 2. - 1.,\n"
" in_tex_coord.y * 2. - 1.,\n"
" 0.,\n"
" 1.);\n"
" tex_coord = vec2(in_tex_coord.x, 1. - in_tex_coord.y);\n"
"}\n";
const char kFragmentShader[] =
"precision mediump float;\n"
"varying vec2 tex_coord;\n"
"uniform sampler2D in_texture;\n"
"void main() {\n"
" gl_FragColor = texture2D(in_texture, tex_coord);\n"
"}\n";
GLuint CreateShaderFromSource(gpu::gles2::GLES2Implementation* gl,
GLenum type,
const char* source) {
GLuint shader = gl->CreateShader(type);
gl->ShaderSource(shader, 1, &source, NULL);
gl->CompileShader(shader);
int status;
gl->GetShaderiv(shader, GL_COMPILE_STATUS, &status);
if (!status) {
int size = 0;
gl->GetShaderiv(shader, GL_INFO_LOG_LENGTH, &size);
scoped_array<char> log(new char[size]);
gl->GetShaderInfoLog(shader, size, NULL, log.get());
DLOG(ERROR) << "Compilation failed: " << log.get();
gl->DeleteShader(shader);
shader = 0;
}
return shader;
}
const float kTexCoords[] = {
0.f, 0.f,
0.f, 2.f,
2.f, 0.f,
};
} // anonymous namespace
bool RenderWidgetFullscreenPepper::InitContext() {
gpu::gles2::GLES2Implementation* gl = ggl::GetImplementation(context_);
program_ = gl->CreateProgram();
GLuint vertex_shader =
CreateShaderFromSource(gl, GL_VERTEX_SHADER, kVertexShader);
if (!vertex_shader)
return false;
gl->AttachShader(program_, vertex_shader);
gl->DeleteShader(vertex_shader);
GLuint fragment_shader =
CreateShaderFromSource(gl, GL_FRAGMENT_SHADER, kFragmentShader);
if (!fragment_shader)
return false;
gl->AttachShader(program_, fragment_shader);
gl->DeleteShader(fragment_shader);
gl->BindAttribLocation(program_, 0, "in_tex_coord");
gl->LinkProgram(program_);
int status;
gl->GetProgramiv(program_, GL_LINK_STATUS, &status);
if (!status) {
int size = 0;
gl->GetProgramiv(program_, GL_INFO_LOG_LENGTH, &size);
scoped_array<char> log(new char[size]);
gl->GetProgramInfoLog(program_, size, NULL, log.get());
DLOG(ERROR) << "Link failed: " << log.get();
return false;
}
gl->UseProgram(program_);
int texture_location = gl->GetUniformLocation(program_, "in_texture");
gl->Uniform1i(texture_location, 0);
gl->GenBuffers(1, &buffer_);
gl->BindBuffer(GL_ARRAY_BUFFER, buffer_);
gl->BufferData(GL_ARRAY_BUFFER,
sizeof(kTexCoords),
kTexCoords,
GL_STATIC_DRAW);
gl->VertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, NULL);
gl->EnableVertexAttribArray(0);
return true;
}
bool RenderWidgetFullscreenPepper::CheckCompositing() {
bool compositing = webwidget_->isAcceleratedCompositingActive();
if (compositing != is_accelerated_compositing_active_) {
didActivateAcceleratedCompositing(compositing);
}
return compositing;
}
<commit_msg>Revert 70626 - Chromium support for webkitAnimationTime property<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/renderer/render_widget_fullscreen_pepper.h"
#include "chrome/common/render_messages.h"
#include "chrome/renderer/ggl/ggl.h"
#include "chrome/renderer/gpu_channel_host.h"
#include "chrome/renderer/pepper_platform_context_3d_impl.h"
#include "chrome/renderer/render_thread.h"
#include "gpu/command_buffer/client/gles2_implementation.h"
#include "third_party/WebKit/WebKit/chromium/public/WebCursorInfo.h"
#include "third_party/WebKit/WebKit/chromium/public/WebSize.h"
#include "third_party/WebKit/WebKit/chromium/public/WebWidget.h"
#include "webkit/plugins/ppapi/plugin_delegate.h"
#include "webkit/plugins/ppapi/ppapi_plugin_instance.h"
using WebKit::WebCanvas;
using WebKit::WebCompositionUnderline;
using WebKit::WebCursorInfo;
using WebKit::WebInputEvent;
using WebKit::WebRect;
using WebKit::WebSize;
using WebKit::WebString;
using WebKit::WebTextDirection;
using WebKit::WebTextInputType;
using WebKit::WebVector;
using WebKit::WebWidget;
namespace {
// WebWidget that simply wraps the pepper plugin.
class PepperWidget : public WebWidget {
public:
PepperWidget(webkit::ppapi::PluginInstance* plugin,
RenderWidgetFullscreenPepper* widget)
: plugin_(plugin),
widget_(widget),
cursor_(WebCursorInfo::TypePointer) {
}
// WebWidget API
virtual void close() {
delete this;
}
virtual WebSize size() {
return size_;
}
virtual void resize(const WebSize& size) {
size_ = size;
WebRect plugin_rect(0, 0, size_.width, size_.height);
plugin_->ViewChanged(plugin_rect, plugin_rect);
widget_->Invalidate();
}
virtual void layout() {
}
virtual void paint(WebCanvas* canvas, const WebRect& rect) {
if (!plugin_)
return;
WebRect plugin_rect(0, 0, size_.width, size_.height);
plugin_->Paint(canvas, plugin_rect, rect);
}
virtual void composite(bool finish) {
ggl::Context* context = widget_->context();
DCHECK(context);
gpu::gles2::GLES2Implementation* gl = ggl::GetImplementation(context);
unsigned int texture = plugin_->GetBackingTextureId();
gl->BindTexture(GL_TEXTURE_2D, texture);
gl->DrawArrays(GL_TRIANGLES, 0, 3);
ggl::SwapBuffers(context);
}
virtual void themeChanged() {
NOTIMPLEMENTED();
}
virtual bool handleInputEvent(const WebInputEvent& event) {
if (!plugin_)
return false;
return plugin_->HandleInputEvent(event, &cursor_);
}
virtual void mouseCaptureLost() {
NOTIMPLEMENTED();
}
virtual void setFocus(bool focus) {
NOTIMPLEMENTED();
}
virtual bool setComposition(
const WebString& text,
const WebVector<WebCompositionUnderline>& underlines,
int selectionStart,
int selectionEnd) {
NOTIMPLEMENTED();
return false;
}
virtual bool confirmComposition() {
NOTIMPLEMENTED();
return false;
}
virtual bool confirmComposition(const WebString& text) {
NOTIMPLEMENTED();
return false;
}
virtual WebTextInputType textInputType() {
NOTIMPLEMENTED();
return WebKit::WebTextInputTypeNone;
}
virtual WebRect caretOrSelectionBounds() {
NOTIMPLEMENTED();
return WebRect();
}
virtual void setTextDirection(WebTextDirection) {
NOTIMPLEMENTED();
}
virtual bool isAcceleratedCompositingActive() const {
return widget_->context() && plugin_ &&
(plugin_->GetBackingTextureId() != 0);
}
private:
webkit::ppapi::PluginInstance* plugin_;
RenderWidgetFullscreenPepper* widget_;
WebSize size_;
WebCursorInfo cursor_;
DISALLOW_COPY_AND_ASSIGN(PepperWidget);
};
} // anonymous namespace
// static
RenderWidgetFullscreenPepper* RenderWidgetFullscreenPepper::Create(
int32 opener_id, RenderThreadBase* render_thread,
webkit::ppapi::PluginInstance* plugin) {
DCHECK_NE(MSG_ROUTING_NONE, opener_id);
scoped_refptr<RenderWidgetFullscreenPepper> widget(
new RenderWidgetFullscreenPepper(render_thread, plugin));
widget->Init(opener_id);
return widget.release();
}
RenderWidgetFullscreenPepper::RenderWidgetFullscreenPepper(
RenderThreadBase* render_thread,
webkit::ppapi::PluginInstance* plugin)
: RenderWidgetFullscreen(render_thread, WebKit::WebPopupTypeSelect),
plugin_(plugin),
#if defined(OS_MACOSX)
plugin_handle_(NULL),
#endif
context_(NULL),
buffer_(0),
program_(0) {
}
RenderWidgetFullscreenPepper::~RenderWidgetFullscreenPepper() {
DestroyContext();
}
void RenderWidgetFullscreenPepper::Invalidate() {
InvalidateRect(gfx::Rect(size_.width(), size_.height()));
}
void RenderWidgetFullscreenPepper::InvalidateRect(const WebKit::WebRect& rect) {
if (CheckCompositing()) {
scheduleComposite();
} else {
didInvalidateRect(rect);
}
}
void RenderWidgetFullscreenPepper::ScrollRect(
int dx, int dy, const WebKit::WebRect& rect) {
if (CheckCompositing()) {
scheduleComposite();
} else {
didScrollRect(dx, dy, rect);
}
}
void RenderWidgetFullscreenPepper::Destroy() {
// This function is called by the plugin instance as it's going away, so reset
// plugin_ to NULL to avoid calling into a dangling pointer e.g. on Close().
plugin_ = NULL;
Send(new ViewHostMsg_Close(routing_id_));
}
webkit::ppapi::PluginDelegate::PlatformContext3D*
RenderWidgetFullscreenPepper::CreateContext3D() {
if (!context_) {
CreateContext();
}
if (!context_)
return NULL;
return new PlatformContext3DImpl(context_);
}
void RenderWidgetFullscreenPepper::DidInitiatePaint() {
if (plugin_)
plugin_->ViewInitiatedPaint();
}
void RenderWidgetFullscreenPepper::DidFlushPaint() {
if (plugin_)
plugin_->ViewFlushedPaint();
}
void RenderWidgetFullscreenPepper::Close() {
// If the fullscreen window is closed (e.g. user pressed escape), reset to
// normal mode.
if (plugin_)
plugin_->SetFullscreen(false);
}
webkit::ppapi::PluginInstance*
RenderWidgetFullscreenPepper::GetBitmapForOptimizedPluginPaint(
const gfx::Rect& paint_bounds,
TransportDIB** dib,
gfx::Rect* location,
gfx::Rect* clip) {
if (plugin_ &&
plugin_->GetBitmapForOptimizedPluginPaint(paint_bounds, dib,
location, clip))
return plugin_;
return NULL;
}
void RenderWidgetFullscreenPepper::OnResize(const gfx::Size& size,
const gfx::Rect& resizer_rect) {
if (context_) {
gpu::gles2::GLES2Implementation* gl = ggl::GetImplementation(context_);
#if defined(OS_MACOSX)
ggl::ResizeOnscreenContext(context_, size);
#else
gl->ResizeCHROMIUM(size.width(), size.height());
#endif
gl->Viewport(0, 0, size.width(), size.height());
}
RenderWidget::OnResize(size, resizer_rect);
}
WebWidget* RenderWidgetFullscreenPepper::CreateWebWidget() {
return new PepperWidget(plugin_, this);
}
void RenderWidgetFullscreenPepper::CreateContext() {
DCHECK(!context_);
RenderThread* render_thread = RenderThread::current();
DCHECK(render_thread);
GpuChannelHost* host = render_thread->EstablishGpuChannelSync();
if (!host)
return;
gfx::NativeViewId view_id;
#if !defined(OS_MACOSX)
view_id = host_window();
#else
Send(new ViewHostMsg_AllocateFakePluginWindowHandle(
routing_id(), true, true, &plugin_handle_));
if (!plugin_handle_)
return;
view_id = static_cast<gfx::NativeViewId>(plugin_handle_);
#endif
const int32 attribs[] = {
ggl::GGL_ALPHA_SIZE, 8,
ggl::GGL_DEPTH_SIZE, 0,
ggl::GGL_STENCIL_SIZE, 0,
ggl::GGL_SAMPLES, 0,
ggl::GGL_SAMPLE_BUFFERS, 0,
ggl::GGL_NONE,
};
context_ = ggl::CreateViewContext(
host,
view_id,
routing_id(),
"GL_OES_packed_depth_stencil GL_OES_depth24",
attribs);
if (!context_ || !InitContext()) {
DestroyContext();
return;
}
ggl::SetSwapBuffersCallback(
context_,
NewCallback(this, &RenderWidgetFullscreenPepper::DidFlushPaint));
}
void RenderWidgetFullscreenPepper::DestroyContext() {
if (context_) {
gpu::gles2::GLES2Implementation* gl = ggl::GetImplementation(context_);
if (program_) {
gl->DeleteProgram(program_);
program_ = 0;
}
if (buffer_) {
gl->DeleteBuffers(1, &buffer_);
buffer_ = 0;
}
ggl::DestroyContext(context_);
context_ = NULL;
}
#if defined(OS_MACOSX)
if (plugin_handle_) {
Send(new ViewHostMsg_DestroyFakePluginWindowHandle(routing_id(),
plugin_handle_));
plugin_handle_ = NULL;
}
#endif
}
namespace {
const char kVertexShader[] =
"attribute vec2 in_tex_coord;\n"
"varying vec2 tex_coord;\n"
"void main() {\n"
" gl_Position = vec4(in_tex_coord.x * 2. - 1.,\n"
" in_tex_coord.y * 2. - 1.,\n"
" 0.,\n"
" 1.);\n"
" tex_coord = vec2(in_tex_coord.x, 1. - in_tex_coord.y);\n"
"}\n";
const char kFragmentShader[] =
"precision mediump float;\n"
"varying vec2 tex_coord;\n"
"uniform sampler2D in_texture;\n"
"void main() {\n"
" gl_FragColor = texture2D(in_texture, tex_coord);\n"
"}\n";
GLuint CreateShaderFromSource(gpu::gles2::GLES2Implementation* gl,
GLenum type,
const char* source) {
GLuint shader = gl->CreateShader(type);
gl->ShaderSource(shader, 1, &source, NULL);
gl->CompileShader(shader);
int status;
gl->GetShaderiv(shader, GL_COMPILE_STATUS, &status);
if (!status) {
int size = 0;
gl->GetShaderiv(shader, GL_INFO_LOG_LENGTH, &size);
scoped_array<char> log(new char[size]);
gl->GetShaderInfoLog(shader, size, NULL, log.get());
DLOG(ERROR) << "Compilation failed: " << log.get();
gl->DeleteShader(shader);
shader = 0;
}
return shader;
}
const float kTexCoords[] = {
0.f, 0.f,
0.f, 2.f,
2.f, 0.f,
};
} // anonymous namespace
bool RenderWidgetFullscreenPepper::InitContext() {
gpu::gles2::GLES2Implementation* gl = ggl::GetImplementation(context_);
program_ = gl->CreateProgram();
GLuint vertex_shader =
CreateShaderFromSource(gl, GL_VERTEX_SHADER, kVertexShader);
if (!vertex_shader)
return false;
gl->AttachShader(program_, vertex_shader);
gl->DeleteShader(vertex_shader);
GLuint fragment_shader =
CreateShaderFromSource(gl, GL_FRAGMENT_SHADER, kFragmentShader);
if (!fragment_shader)
return false;
gl->AttachShader(program_, fragment_shader);
gl->DeleteShader(fragment_shader);
gl->BindAttribLocation(program_, 0, "in_tex_coord");
gl->LinkProgram(program_);
int status;
gl->GetProgramiv(program_, GL_LINK_STATUS, &status);
if (!status) {
int size = 0;
gl->GetProgramiv(program_, GL_INFO_LOG_LENGTH, &size);
scoped_array<char> log(new char[size]);
gl->GetProgramInfoLog(program_, size, NULL, log.get());
DLOG(ERROR) << "Link failed: " << log.get();
return false;
}
gl->UseProgram(program_);
int texture_location = gl->GetUniformLocation(program_, "in_texture");
gl->Uniform1i(texture_location, 0);
gl->GenBuffers(1, &buffer_);
gl->BindBuffer(GL_ARRAY_BUFFER, buffer_);
gl->BufferData(GL_ARRAY_BUFFER,
sizeof(kTexCoords),
kTexCoords,
GL_STATIC_DRAW);
gl->VertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, NULL);
gl->EnableVertexAttribArray(0);
return true;
}
bool RenderWidgetFullscreenPepper::CheckCompositing() {
bool compositing = webwidget_->isAcceleratedCompositingActive();
if (compositing != is_accelerated_compositing_active_) {
didActivateAcceleratedCompositing(compositing);
}
return compositing;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2015, Aaditya Kalsi
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* \file lib.cpp
* \date 2015
*/
#include <uscheme/defs.hpp>
namespace uscheme {
const char* version(void)
{
return USCHEME_LIB_VERSION;
}
}//namespace uscheme<commit_msg>fix newlines<commit_after>/*
Copyright (c) 2015, Aaditya Kalsi
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* \file lib.cpp
* \date 2015
*/
#include <uscheme/defs.hpp>
namespace uscheme {
const char* version(void)
{
return USCHEME_LIB_VERSION;
}
}//namespace uscheme
<|endoftext|> |
<commit_before>#include "Arduino.h"
#include "RSS.h"
// #include "MemoryFree.h"
//#include "SPI.h"
//using namespace grubs;
// using namespace grubs;
// namespace grubs{
// bool c = 1;
// }
//using namespace std;
// namespace grubs{
// int blue;
// };
RSS::RSS(int N , int hits, char Rule, int channel){
_TrigArray = new bool[N];
_CV = new double[N];
_Rule = Rule;
_pos = 0;
SubD=1;
_Prox = 0;
if (Strata) {
_floor = pow(2.,channel) ; _roof = pow(2.,channel+1); }
else {
_floor = 1.0; _roof = 16.0; }
_D = !Sync; // Delay after note
G = Glide; // Glide On
_NoteDuration = NoteDuration;
_N = N;
B = false;
_channel = channel;
_iteration = 0;
_Play = true;
_counter = 0;
_HarmonicCount = (int) _floor;
_Dir = (channel+1)%1;
TriggerSubdivisions = 1;
// Write _CV to initial state (i.e. [1,2,3,4] for N = 4)
// This initial state will be overwritten if !RingChanges
for (int i = 0; i < N; i++) {
_CV[i] = i+1.;
}
// UpdateInterval();
RandomizeInitialOrder();
GenerateTriggerSequence(hits);
if (Hocket) {
Shift(-1*(channel-1),0);
}
}
void RSS::GenerateTriggerSequence(int hits){
// hits: number of notes in a bar of the defined length
hits = constrain(hits,0,_N);
// initialize the sequence
for (int i = 0 ; i<_N ; i++) {
if (i<hits) { _TrigArray[i] = true; }
else { _TrigArray[i] = false; } }
// obtain Euclidean Sequence
bjorklund(_N, hits);
//if (Debug) { PrintTriggerSequence(seq); }
}
void RSS::bjorklund(int length , int h) {
int j = 2;
int iterations = -1+length / min(h,length-h);
int leftovers = length % min(h,length-h);
for (int k = 0; k<iterations; k++) {
int l = min(h,length-h);
for (int i = 0; i<l; i++ ) {
ShiftBoolean( i*j);
if (l<h) {h--;}
length--; }
j++;
}
int l = min(h,length-h);
for (int i = 0; i<l; i++ ) {
ShiftBoolean( i*j*h/l-i*j/l);
length--; }
}
void RSS::ShiftBoolean( int a ) {
// within the boolean array, move the boolean at the end of the array to position after 'a'
bool temp = _TrigArray[_N-1];
// move values one position down to make room for the transported value
for (int i = _N-1 ; i > a+1 ; i--) {
_TrigArray[i] = _TrigArray[i-1]; }
_TrigArray[a+1] = temp;
//if (Debug) { PrintTriggerSequence(seq);
}
void RSS::PrintTriggerSequence() {
for (int i = 0; i < _N ; i++) {
Serial.print(_TrigArray[i]); Serial.print(" "); }
Serial.println();
}
void RSS::Advance() {
double Interval2 = Voices[(_channel+3)%4]->GetCV(0), cv = _CV[_pos];
if ( (((!SingleVoice && !ShiftRegisterMode) || _channel == 0) && !RingChanges) || (RingChanges && _counter<_N)){
switch (_Rule) {
case 'A': { double increment = pow(scale[random(1,s_length)],pow(-1,_Dir));
if (cv * increment > _roof || cv * increment < _floor) {
_Dir = !_Dir; increment = 1./increment;
}
cv *= increment;
break;}
case 'B': { if (cv* Interval2 > _roof || cv* Interval2 < _floor) {
_roof = 2; Interval2 = 1/FixInterval(Interval2); _roof=16;}
cv *= Interval2;
break; }
// LFO mode
case 'C': {double sine = 2+LFO(2,0.005+_channel*0.01,0,1);
cv = pow(2,sine);
break; }
case 'D': { cv = DifferenceInterval(Interval2,_channel); break; }
case 'E': {
switch (Tuning) {
case 'J': { // Just Intonation
int JI_limit = 5; // n-limit of just intervals
int JI_power = 1; // just interval power
cv = JustInterval(JI_limit,JI_power);
break;}
case 'E': { // Scale with defined number of equidistant notes per octave
double n_scale = 12.; // no. of equal intervals per octave (E tuning)
cv = _floor*(1+random(0,n_scale+1)/n_scale);
break;}
case 'P': { // Predefined Scale
cv = _floor*scale[random(0,s_length)];
break;}
case 'R': { // Random
double low = 1000.*log(_floor)/log(2);
double high = 1000.*log(_roof)/log(2);
cv = pow(2,random(low,high++)/1000.);
break;}
}
// randomly spread across octave registers
cv = FixInterval( cv*pow(2,random(0,log(_roof/_floor)/log(2))));
break;
}
case 'H': { cv = HarmonicInterval(); break; }
case 'I': { cv = Interval2*pow(InharmonicInterval(),pow(-1,random(0,2))); break; }
case 'K': {
// Use with SingeVoice mode, follows CV input
UpdateInterval();
cv = _floor+ReadLeft()*(_roof-_floor);
break;}
case 'G': { cv = scale[_n]*pow(2,_channel); SubD = 16/pow(2,_channel+1);
_n += random(-1,2); _n = constrain(_n,0,s_length-1); break; }
case 'R': {
double freq = 2.05*0.25/((base_period)/1000.);
if (InputMode) { freq *= ReadLeft(); }
// if (freq == 0) {freq = 1; Serial.println("avoid");}
cv = _floor*pow(2,Saw(log(_roof/_floor)/log(2), freq , 1*_channel/4. , 1+_channel%1));
break;}
case 'S': {
Serial.println(s_length);
int n_low,n_high;
if (Strata) {
n_low = _channel*s_length;
n_high = (_channel+1)*s_length;
}
else {
n_low = 0; n_high = 4*s_length;
}
_n = constrain(_n,n_low,n_high);
cv = scale[_n%s_length];//*pow(2,_channel); //SubD[channel] = 16/pow(2,channel+1);
cv *= pow(2,(_n)/s_length); // set octave register
if (_n<=n_low) {_Dir = 1;}//_n=low+1;}
if (_n>=n_high) {_Dir = 0;}// _n=high-1;}
int r = random(1,1000);
int stepsize = 1;
if (RandomStep(0.3)) {stepsize++;}
if (_Dir) {_n+=stepsize;}
else {_n-=stepsize;}
//if (_channel!=0) {cv = 4;}
break; }
case 'F': { cv = Interval2*pow(1.5,pow(-1,random(0,1))); break; }
// Just Intonation + Drone
case 'X': {
if (_channel == 0) { cv = 4*JustInterval(7,1)*JustInterval(7,1); }
else { cv = 4;}
break;}
}
cv = FixInterval(cv);
}
else if (RingChanges && _counter>=_N) {
if (_counter%_N==0) {
Swap(_CV, _iteration, _N);
_iteration++;
}
cv = _CV[_pos];
}
// else if (!ShiftRegisterMode && !RingChanges){ //SingleVoice mode
else if (SingleVoice){ // channel!=0
// only works perfectly when ChangeTrigOrder = 0;
// Allow user input of FM Carrier:Modulator Ratio on the fly via Serial
if (Serial.available() && _channel==3) {_Interval = Serial.parseFloat();}
//cv = Voices[0].GetCV(0)*_Interval;
cv = Voices[0]->GetCV(0)*_Interval;
if (cv < 1) {cv = 1;} // Exception for rounding error
}
// else if (ShiftRegisterMode && !RingChanges) {
else if (ShiftRegisterMode) {
cv = ApplyShiftRegister();
}
_CV[_pos] = cv;
_pos = (_pos+1)%_N;
_counter++;
// if (ProximityMode) {EvaluateProximity();}
//}
}
double RSS::FixInterval( double Interval) {
if (Interval == 0) {Interval = _floor;}
//if (Interval > r) {Interval = Interval - 2*(Interval-r);}
//if (Interval < f) {Interval = Interval + 2*(f-Interval);}
while (Interval > _roof) {Interval /= _roof/_floor;}
while (Interval < _floor) {Interval *= _roof/_floor;}
//Serial.print("Interval"); Serial.print("\t"); Serial.println(Interval);
return Interval;
}
double RSS::JustInterval( int base , int power) {
double interval = pow(random(1,base+1),random(1,power+1))/pow(random(1,base+1),random(1,power+1));
//if (interval < 1) {interval = 1./interval;}
//return interval; }
double r = random(2,8);
r /= (r-1.);
int posneg = pow(-1,random(-1,1));
r = pow(r,posneg);
return r;}
double RSS::HarmonicInterval() {
// Generates Harmonic Intervals in ascending and then descending order
double interval = _HarmonicCount;
_HarmonicCount += random(1,2) ;
if (_HarmonicCount>0.5*_roof/_floor) { _HarmonicCount -= (int) _roof/(2*_floor) ;}
interval = random(112,145)/64.;
return interval;
}
double RSS::InharmonicInterval() {
// here for now, will probably deprecate before long
const int offset = 9; // move and make static?
const int primes[] = {5,7,11,13,17,19,23,29,31,37,41,43,47,51,53,57}, p_length = 5;
static int p, lp[4]; int ind = random(0,p_length);
while (ind == lp[0] || ind == lp[1] || ind == lp[2] || ind == lp[3]) { ind = random(0,p_length); }
lp[p%4] = ind; p++;
if (Debug) {Serial.print("index: "); Serial.println(ind);}
return ( pow(2,(primes[offset+ind]+1.)/primes[offset+ind])); }
//return (primes[offset+ind]/47.); }
double RSS::DifferenceInterval(double Interval, int channel) {
// DifferenceInterval generates a set of four pitches that yield a single fundamental difference tone
// Register determines the pitch of the cluster
double Register = 10; // value should like between 2 and 15 ( ? )
// Increment determines the frequency of the difference tone, as a fraction of the cluster pitch
// Smaller values result in lower difference tones, larger values result in higher difference tones
double Increment = Register/10.;
double t = micros();
double Sweep = 120.*1000000.;
Increment *= t/(Sweep);
if (t>Sweep){_Play = 0;}
// The pitch of the difference tone can be modulated by an LFO
boolean ModulateDifferenceTone = 0;
Increment += ModulateDifferenceTone * LFO(-0.1,0.05,0,1);
if (InputMode) {Increment *= ReadLeft();}
/* Register can be modulated while keeping Increment the same to yield a pitch cluster that changes
while the difference tone remains the same */
boolean ModulateRegister = 0;
Register += ModulateRegister * LFO(Register/4,0.01,0,1);
/* The difference tone is generated by constructing a tone cluster in which
each tone is offset by equal amounts */
Interval = Register+Increment*channel*1;
//Register = Interval;
return Interval;
}
double RSS::Saw( double amplitude , double frequency , double phase , bool rising) {
unsigned long period = 1000./frequency; // [ms]
unsigned long result = millis();
result += phase*double(period);
while (result > period) {result -= period;}
if (!rising) {result = period-result;}
return amplitude * result/period;
}
// double RSS::LFO( double amplitude , double frequency , double phase , bool sine ) {
// double result = amplitude*sin(frequency*millis()/1000.*2.*pi+phase*pi); // sine-wave LFO
// if (!sine) { if ( result < 0 ) {result = 0;} else { result = amplitude; } } // half-wave square
// return result;
// }
double RSS::GetCV(int i) {
return _CV[(_pos+i)%_N];
}
bool RSS::GetTrig( int t ) {
return _TrigArray[t%_N];
}
void RSS::Transpose(double TransposeAmount) {
for (int i=0; i<_N; i++) {
_CV[i] = FixInterval(_CV[i]*TransposeAmount);} }
void RSS::OrderSequence() {
// NEEDS REWRITE
bool recurse = false; double temp;
for (int i=1; i<_N; i++) {
if (_CV[i]<_CV[i-1]) {
temp = _CV[i]; _CV[i] = _CV[i-1]; _CV[i-1] = temp; recurse = true; } }
if (recurse) {OrderSequence();} }
void RSS::Reverse() {
double temp;
for (int i=0; i<(_N-1)/2; i++) {
temp = _CV[i];
_CV[i] = _CV[_N-(i+1)];
_CV[_N-(i+1)] = temp; } }
void RSS::Invert() {
for (int i=0; i<_N; i++) {
_CV[i] = _roof/_CV[i]; } }
void RSS::FlipT() {
for (int i=0; i<_N; i++) {
_TrigArray[i] = !_TrigArray[i];}
}
void RSS::Shift( int Tshift , int Nshift ) {
bool TempTrigArray[_N]; double TempNoteArray[_N];
for (int i=0; i<_N; i++){
TempTrigArray[i] = _TrigArray[i];
TempNoteArray[i] = _CV[i];
}
for (int i = 0; i < _N; i++) {
_TrigArray[i] = TempTrigArray[(i+Tshift+_N) % _N];
_CV[i] = TempNoteArray[(i+Nshift+_N) % _N]; }
}
void RSS::SetNoteDuration(int amt){
_NoteDuration = amt;
// EXCEPTION
if (SubD!=1 && _Rule == 'E'){
_NoteDuration = 0;
}
}
double RSS::ArrayMax(double * array) {
double m = array[0];
for (int i = 1; i < 4; i++) { m = max(m,array[i]); }
return m;
}
double RSS::ArrayMin(double * array) {
double m = array[0];
for (int i = 1; i < 4; i++) { m = min(m,array[i]); }
return m;
}
void RSS::sendNote(int t) {
double val = _CV[t%_N];
// overwrite t dependence
val = _CV[(_pos-1+_N)%_N];
//_CV[_pos%(_N-1)]??
// Apply Root Shift
if (ChangeRoot) {
val *= Root; // need to modify roof to respect root?
val = FixInterval(val);
}
static unsigned long ClockStart;
if (Quantize) {
val = QuantizeNote(val);
}
double mV = 1000*log(val)/log(2); // frequency ratio to CV [mV]
double mV0 = _prevCV; // previous CV [mV]
//mV0 = mV-150; // temp
// DelayLength defines the note duration
unsigned long DelayLength = 1000*base_period; // [us]
if (_D) { DelayLength = ModDelay( mV );}
if (Phasing) {DelayLength += LFO(DelayLength,0.01,_channel-1,HIGH); mV += 0*LFO(100,0.005,_channel,HIGH);}
// GlideLength defines the glide length, if glide is on
unsigned long GlideLength = DelayLength/2.; // [us]
//GlideLength = Portamento;
if (_Rule == 'B') {
// GlideLength *= 1.25;
// Serial.println(GlideLength);
// GlideLength = max(GlideLength,300000);
// if (_channel==0) {
GlideLength = 1000*random(100,610);
//}
}
double GlideRate = (mV-mV0)/GlideLength; // [mV/us]
unsigned long BounceTime = 13000+0.15*pow(GlideLength/1000000.,1.5)*1000000.; // changed back from 13000 to 3000?
//if (Rule == 'A') {BounceTime *=random(1,1)/5.;}
int i = -1; unsigned long t_start = micros();
if (!B && !G) { GlideLength = 0; }
if (!G) { mV0 = mV; GlideRate = 0; }
unsigned long CalibrationAmt = micros()-ClockStart;
unsigned long tStart, GlideStart=micros();
while ( i == -1 || (i*100 < long(GlideLength) && BounceTime > 6000 ) ) {
tStart = micros();
if ( i == -1 || (B && (micros()-t_start)>=BounceTime && BounceTime > 3000) ) {
sendTrigger(); BounceTime = pow(BounceTime,0.99-LFO(0.0,0.01,1,1)); t_start = micros();
//sendTrigger(channel); BounceTime = pow(BounceTime,1.01-LFO(0.0,0.01,1,1)); t_start = micros();
}
if ((i+1)*100 >= GlideLength) { mV0 = mV;}
else { mV0 += double(GlideRate*100.);}
int b = mV0;
if (Detune) {b += random(-20,21);}
//if (_channel==0 && _Rule=='B') {b=random(3800,4001);}
if (Flicker) {b = flicker(b);}
Send2DAC(_channel,b);
if (i>-1) {delayMicroseconds(100-(micros()-tStart)); }
i++;
}
_prevCV = mV;
if (BZZZ) {return;}
if (Debug) {Serial.print("Voice "); Serial.print(_channel); Serial.print(": "); Serial.println(val); }
GlideLength = micros()-GlideStart;
CalibrationAmt += GlideLength;
// Adjust the post-trigger delay to account for computation time
if (CalibrationAmt < DelayLength) {
DelayLength = DelayLength-CalibrationAmt;
}
//if ( G[channel] && DelayLength>GlideLength) {DelayLength -=GlideLength;}
//else if (G[channel]) {Serial.println('z'); DelayLength = 0;}
if (_D) {
usDelay(DelayLength);
}
ClockStart = micros();
}
void RSS::sendTrigger() {
// send longer pulse, i.e. delayMicroseconds(300), for pinging filters (~300us) and LPGs (~200us) ??
if (_counter%TriggerSubdivisions!=0) {return;}
if (ProximityMode){
EvaluateProximity();
if (!_Prox) {
// in case Trig level is high, write low
digitalWrite(TrigPins[_channel],LOW);
return;
}
}
//if (SubD[channel] != 1 && Rule == 'E') {Duration = 0;} // EXCEPTION
_NoteDuration = NoteDuration;
if (FillIn) {
int i = 2;
while (_TrigArray[_pos+i]==0 && knobswitch) {//????????
_NoteDuration++; i++;
}
}
digitalWrite(TrigPins[_channel], HIGH);
if (ProximityMode) {
if (_Prox) {_NoteDuration=1;}
}
if (_NoteDuration<1) { digitalWrite(TrigPins[_channel],LOW); }
if (!Sync) { DepleteNoteDuration(); }
}
double RSS::QuantizeNote( double Note ) {
int i = 0;
while (Note>=2) {Note /= 2; i++; }
int j=0;
while (Note > scale[j] && j<s_length-1) {j++;}
if (scale[j]-Note > Note-scale[j-1]) {Note = scale[j-1];}
else {Note = scale[j];}
return Note*pow(2,i);
}
// unsigned long RSS::ModDelay(boolean Delay , double millivolts) {
// //(1,1) arguments yield no modification to delay
// unsigned long DelayLength = Delay*1000*base_period;
// DelayLength *= pow( max(base_period*(1+LFO(a2,f2,0,HIGH)+LFO(a1,f1,0,HIGH)) , 1) / base_period, D2) * pow(millivolts/2000,D1);
// if (InputMode) { DelayLength *= analogRead(LeftIn)/1023.; }
// return DelayLength;
// }
int RSS::flicker( int note ) {
static boolean flicker_switch;
if (flicker_switch) {note+=1000;}
flicker_switch = !flicker_switch;
return note;
}
bool RSS::Play(int t){
if (t%SubD == 0 && _Play) {
return true;
}
else{
return false;
}
}
double RSS::ApplyShiftRegister(){
// maybe poorly defined for ChangeTrigOrder mode
// determine current voice
bool found = false;
int i = 0;
while (!found) {
if (_channel == TrigOrder[i]){
found = true; break;
}
if (!found) {i++;}
}
// define previous voice
int j = TrigOrder[i-1];
// get shift register from previous voice
return Voices[j]->GetCV(-2);
}
void RSS::EvaluateProximity(){
// evaluate proximity of voice's pitch to that of the other voices
double ProximityRange = 0.05;
bool WithinProximity = false;
for (int i = 0; i < 4; i++) {
if (i != _channel) {
if ( abs( _CV[_pos] - Voices[i]->GetCV(0) ) < ProximityRange ) {
WithinProximity = true;
}
}
}
if (WithinProximity) {_Prox = true; }
else {_Prox = false;}
}
void RSS::RandomizeInitialOrder() {
int a, b;
for (int i=0; i<_N/2; i++) {
a = random(0,_N);
b = random(0,_N);
while (a==b) { b = random(0,_N); }
double temp = _CV[a];
_CV[a] = _CV[b];
_CV[b] = temp;
}
}
bool RSS::RandomStep(double probability) {
int r = random(0,1001);
if (r<1000*probability) {
return true;
}
else {
return false;
}
}
void RSS::UpdateInterval() {
bool ModifyStack = true;
if (ModifyStack) {
// if (SingleVoice) {
//double Formants[4] = {1, 2300./270, 3000./270, 3000./270};
//double Formants[4] = {700,760,700,760};
// double Formants[4] = {1, 870/300, 2250/300, 1};
// double Formants[4] = {1, 2000/400, 2550/400, 1};
//double Formants[4] = {1, 2000/400, 2550/400, 1};
//double Formants[4] = {1, 1700/660, 2400/660, 2400/660};
//double Formants[4] = {1.618,1.618,1,1};
double offset = 112;
double HarmonicSeparation = 1;
if (InputMode) {
HarmonicSeparation = int(10*ReadLeft());
// Serial.print("HarmonicSeparation: ");Serial.println(HarmonicSeparation);
}
for (int i = 0; i < 4; i++ ) {
// Stack[i] = offset+HarmonicSeparation*i;
int center = 128;
int degree = 16;
int harmonic = random(center-degree,center+degree+1);
//Stack[_channel] = random(112,145);
while (harmonic == Stack[0] || harmonic == Stack[1] || harmonic == Stack[2] || harmonic == Stack[3]) {
harmonic = random(center-degree,center+degree+1);
}
Stack[i] = harmonic;
}
}
double StackMin = ArrayMin(Stack);
// _Interval = Stack[_channel] / Stack[0];
for (int i = 0; i<4; i++){
Voices[i]->_Interval = Stack[i] / Stack[0];
}
if (_channel==0) {
_roof = 16.*(Stack[0]/ArrayMax(Stack));
_floor = (Stack[0]/ArrayMin(Stack));
// _floor = 1./range;
}
// Serial.print("test"); Serial.println(_Interval);
// }
}
<commit_msg>Delete RSS.cpp<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: redcom.hxx,v $
*
* $Revision: 1.1.1.1 $
*
* last change: $Author: hr $ $Date: 2000-09-18 16:45:00 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef SC_REDCOM_HXX
#define SC_REDCOM_HXX
#ifndef _SVX_POSTDLG_HXX //autogen
#include <svx/postdlg.hxx>
#endif
#ifndef SC_CHGTRACK_HXX
#include "chgtrack.hxx"
#endif
class ScDocShell;
class ScRedComDialog : public SvxPostItDialog
{
private:
ScChangeAction *pChangeAction;
ScDocShell *pDocShell;
String aComment;
DECL_LINK( PrevHdl, SvxPostItDialog* );
DECL_LINK( NextHdl, SvxPostItDialog* );
protected:
void ReInit(ScChangeAction *);
void SelectCell();
ScChangeAction *FindPrev(ScChangeAction *pAction);
ScChangeAction *FindNext(ScChangeAction *pAction);
public:
ScRedComDialog( Window* pParent, const SfxItemSet& rCoreSet,
ScDocShell *,ScChangeAction *,BOOL bPrevNext = FALSE);
~ScRedComDialog();
virtual short Execute();
};
#endif
<commit_msg>INTEGRATION: CWS dialogdiet (1.1.1.1.340); FILE MERGED 2004/01/08 14:24:43 mba 1.1.1.1.340.1: #i24117#: replace derivation from SvxPostItDialog by containment<commit_after>/*************************************************************************
*
* $RCSfile: redcom.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: hr $ $Date: 2004-02-03 20:34:15 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef SC_REDCOM_HXX
#define SC_REDCOM_HXX
#ifndef _SVX_POSTDLG_HXX //autogen
#include <svx/postdlg.hxx>
#endif
#ifndef SC_CHGTRACK_HXX
#include "chgtrack.hxx"
#endif
class ScDocShell;
class ScRedComDialog
{
private:
ScChangeAction *pChangeAction;
ScDocShell *pDocShell;
String aComment;
SvxPostItDialog* pDlg;
DECL_LINK( PrevHdl, SvxPostItDialog* );
DECL_LINK( NextHdl, SvxPostItDialog* );
protected:
void ReInit(ScChangeAction *);
void SelectCell();
ScChangeAction *FindPrev(ScChangeAction *pAction);
ScChangeAction *FindNext(ScChangeAction *pAction);
public:
ScRedComDialog( Window* pParent, const SfxItemSet& rCoreSet,
ScDocShell *,ScChangeAction *,BOOL bPrevNext = FALSE);
~ScRedComDialog();
short Execute();
};
#endif
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.