<commit_before>#include "core/raytracer.h"

#include "core/image.h"

#include "core/intersection.h"
#include "core/sphere.h"
#include "core/random.h"
#include "core/polarcoord.h"
#include "core/numeric.h"
#include "core/cli_progress_bar.h"

#include <limits>

namespace euphoria::core::raytracer
{
    HitResult::HitResult
    (
        float aray_distance,
        const vec3f& aposition,
        const unit3f& anormal,
        std::shared_ptr<Material> amaterial
    )
        : ray_distance(aray_distance)
        , position(aposition)
        , normal(anormal)
        , material(amaterial)
    {
    }

    struct SphereObject : public Object
    {
        Sphere sphere;
        vec3f position;
        std::shared_ptr<Material> material;

        SphereObject
        (
            const Sphere& asphere,
            const vec3f& aposition,
            std::shared_ptr<Material> amaterial
        )
            : sphere(asphere)
            , position(aposition)
            , material(amaterial)
        {
        }

        std::optional<HitResult>
        Hit(const UnitRay3f& ray, const Range<float>& range) const override
        {
            const auto hit_index = GetIntersection
            (
                ray,
                sphere,
                position
            );
            if(IsWithin(range, hit_index))
            {
                const auto hit_position = ray.GetPoint(hit_index);
                const auto hit_normal = vec3f::FromTo(position, hit_position).GetNormalized();
                return HitResult
                {
                    hit_index,
                    hit_position,
                    hit_normal,
                    material
                };
            }
            else
            {
                return std::nullopt;
            }
        }
    };

    std::shared_ptr<Object>
    CreateSphere
    (
        const Sphere& sphere,
        const vec3f& position,
        std::shared_ptr<Material> material
    )
    {
        return std::make_shared<SphereObject>
        (
            sphere,
            position,
            material
        );
    }

    std::optional<HitResult>
    Scene::Hit(const UnitRay3f& ray, const Range<float>& range) const
    {
        std::optional<HitResult> r = std::nullopt;

        for(const auto o: objects)
        {
            const auto h = o->Hit(ray, range);
            if(r.has_value() == false)
            {
                r = h;
            }
            else
            {
                if(h.has_value())
                {
                    if(h->ray_distance < r->ray_distance)
                    {
                        r = h;
                    }
                }
            }
        }

        return r;
    }

    Rgb
    rgb(const unit3f& normal)
    {
        return Rgb
        {
            (normal.x + 1)/2,
            (normal.y + 1)/2,
            (normal.z + 1)/2
        };
    }

    vec3f RandomInUnitSphere(Random* random)
    {
        return RandomUnit3(random) * random->NextFloat01();
    }

    Material::~Material() {}

    struct DiffuseMaterial : public Material
    {
        Rgb albedo;

        explicit DiffuseMaterial(const Rgb& aalbedo)
            : albedo(aalbedo)
        {
        }

        std::optional<ScatterResult>
        Scatter
        (
            const UnitRay3f& /*ray*/,
            const HitResult& hit,
            Random* random
        ) override
        {
            const auto target = hit.position + hit.normal + RandomInUnitSphere(random);
            const auto reflected_ray = UnitRay3f::FromTo(hit.position, target);

            return ScatterResult
            {
                albedo,
                reflected_ray
            };
        }
    };

    vec3f Reflect(const vec3f& v, const unit3f& n) {
        return v - 2*dot(v,n)*n;
    }

    struct MetalMaterial : public Material
    {
        Rgb albedo;
        float fuzz;

        explicit MetalMaterial
        (
            const Rgb& aalbedo,
            float afuzz
        )
            : albedo(aalbedo)
            , fuzz(KeepWithin(R01(), afuzz))
        {
        }

        std::optional<ScatterResult>
        Scatter
        (
            const UnitRay3f& ray,
            const HitResult& hit,
            Random* random
        ) override
        {
            const auto reflected = Reflect
            (
                ray.dir,
                hit.normal
            );
            const auto scattered = UnitRay3f::FromTo
            (
                hit.position,
                reflected + fuzz * RandomInUnitSphere(random)
            );
            const auto scatter_dot = dot
            (
                scattered.dir,
                hit.normal
            );
            if(scatter_dot > 0)
            {
                return ScatterResult
                {
                    albedo,
                    scattered
                };
            }
            else
            {
                return std::nullopt;
            }
        }
    };

    std::optional<vec3f>
    Refract
    (
        const unit3f& uv,
        const unit3f& normal,
        float ni
    )
    {
        const auto dt = dot(uv, normal);
        const auto discriminant = 1.0f - ni*ni*(1.0f-dt*dt);
        if (discriminant > 0)
        {
            return ni * (uv - normal * dt) - normal * Sqrt(discriminant);
        }
        else
        {
            return std::nullopt;
        }
    }

    struct DielectricMaterial : public Material
    {
        Rgb albedo;
        float refractive_index;

        explicit DielectricMaterial
        (
            const Rgb& aalbedo,
            float arefractive_index
        )
            : albedo(aalbedo)
            , refractive_index(arefractive_index)
        {
        }

        std::optional<ScatterResult>
        Scatter
        (
            const UnitRay3f& ray,
            const HitResult& hit,
            Random* /*random*/
        ) override
        {
            const auto dot_result = dot(ray.dir, hit.normal) > 0.0f;

            const auto outward_normal = dot_result ? -hit.normal : hit.normal;
            const auto ni = dot_result ? refractive_index : 1.0f/refractive_index;

            const auto refracted = Refract(ray.dir, outward_normal, ni);

            if(refracted.has_value())
            {
                return ScatterResult
                {
                    albedo,
                    UnitRay3f::FromTo
                    (
                        hit.position,
                        refracted.value()
                    )
                };
            }
            else
            {
                const auto reflected = Reflect
                (
                    ray.dir,
                    hit.normal
                );
                return ScatterResult
                {
                    albedo,
                    UnitRay3f::FromTo
                    (
                        hit.position,
                        reflected
                    )
                };
            }
        }
    };

    std::shared_ptr<Material>
    CreateDiffuseMaterial
    (
        const Rgb& albedo
    )
    {
        return std::make_shared<DiffuseMaterial>
        (
            albedo
        );
    }

    std::shared_ptr<Material>
    CreateMetalMaterial
    (
        const Rgb& albedo,
        float fuzz
    )
    {
        return std::make_shared<MetalMaterial>
        (
            albedo,
            fuzz
        );
    }

    std::shared_ptr<Material>
    CreateDielectricMaterial
    (
        const Rgb& albedo,
        float refractive_index
    )
    {
        return std::make_shared<DielectricMaterial>
        (
            albedo,
            refractive_index
        );
    }

    Rgb
    GetColor
    (
        const Scene& scene,
        const UnitRay3f& ray,
        Random* random,
        int depth
    )
    {
        const auto h = scene.Hit
        (
            ray,
            MakeRange(0.001f, std::numeric_limits<float>::max())
        );
        if(h.has_value())
        {
            if(depth < 50)
            {
                auto scatter = h->material->Scatter
                (
                    ray,
                    h.value(),
                    random
                );
                if(scatter.has_value())
                {
                    const auto c = GetColor
                    (
                        scene,
                        scatter->scattered,
                        random,
                        depth + 1
                    );
                    return scatter->attenuation * c;
                }
                else
                {
                    return Color::Black;
                }
            }
            else
            {
                return Color::Black;
            }
        }
        const auto t = (ray.dir.y+1)/2.0f;
        return RgbTransform::Transform
        (
            Rgb(1.0f, 1.0f, 1.0f),
            t,
            Rgb(0.5f, 0.7f, 1.0f)
        );
    }

    struct Camera
    {
        vec3f lower_left_corner = vec3f{-2.0f, -1.0f, -1.0f};
        vec3f horizontal = vec3f{4.0f, 0.0f, 0.0f};
        vec3f vertical = vec3f{0.0f, 2.0f, 0.0f};
        vec3f origin = vec3f{0.0f, 0.0f, 0.0f};

        UnitRay3f GetRay(float u, float v) const
        {
            return UnitRay3f::FromTo(origin, lower_left_corner + u*horizontal + v*vertical);
        }
    };

    Rgb
    Gamma2CorrectColor(Rgb color)
    {
        return {Sqrt(color.r), Sqrt(color.g), Sqrt(color.b)};
    }

    void
    Raytrace(Image* aimage, const Scene& scene, int number_of_samples)
    {
        Image& img = *aimage;

        auto random = Random{};
        const auto camera = Camera{};

        {
        std::cout << "Rendering ";
        CliProgressBar progress;

        const int number_of_pixels = img.GetWidth() * img.GetHeight();

        for(int y=0; y<img.GetHeight(); y+=1)
        for(int x=0; x<img.GetWidth(); x+=1)
        {
            Rgb color = Color::Black;
            for(int sample = 0; sample < number_of_samples; sample += 1)
            {
                const auto u = (x + random.NextFloat01()) / static_cast<float>(img.GetWidth());
                const auto v = (y + random.NextFloat01()) / static_cast<float>(img.GetHeight());
                const auto ray = camera.GetRay(u, v);
                const auto sample_color = GetColor(scene, ray, &random, 0);
                color += sample_color;
            }
            color = color/number_of_samples;
            color = Gamma2CorrectColor(color);
            img.SetPixel(x,y, rgbi(color));
            progress.Update( (y*img.GetWidth() + x)/static_cast<float>(number_of_pixels) );
        }
        }
        std::cout << "Rendering done :)\n";
    }
}

<commit_msg>raytracer 15: fresnel effect<commit_after>#include "core/raytracer.h"

#include "core/image.h"

#include "core/intersection.h"
#include "core/sphere.h"
#include "core/random.h"
#include "core/polarcoord.h"
#include "core/numeric.h"
#include "core/cli_progress_bar.h"

#include <limits>

namespace euphoria::core::raytracer
{
    HitResult::HitResult
    (
        float aray_distance,
        const vec3f& aposition,
        const unit3f& anormal,
        std::shared_ptr<Material> amaterial
    )
        : ray_distance(aray_distance)
        , position(aposition)
        , normal(anormal)
        , material(amaterial)
    {
    }

    struct SphereObject : public Object
    {
        Sphere sphere;
        vec3f position;
        std::shared_ptr<Material> material;

        SphereObject
        (
            const Sphere& asphere,
            const vec3f& aposition,
            std::shared_ptr<Material> amaterial
        )
            : sphere(asphere)
            , position(aposition)
            , material(amaterial)
        {
        }

        std::optional<HitResult>
        Hit(const UnitRay3f& ray, const Range<float>& range) const override
        {
            const auto hit_index = GetIntersection
            (
                ray,
                sphere,
                position
            );
            if(IsWithin(range, hit_index))
            {
                const auto hit_position = ray.GetPoint(hit_index);
                const auto hit_normal = vec3f::FromTo(position, hit_position).GetNormalized();
                return HitResult
                {
                    hit_index,
                    hit_position,
                    hit_normal,
                    material
                };
            }
            else
            {
                return std::nullopt;
            }
        }
    };

    std::shared_ptr<Object>
    CreateSphere
    (
        const Sphere& sphere,
        const vec3f& position,
        std::shared_ptr<Material> material
    )
    {
        return std::make_shared<SphereObject>
        (
            sphere,
            position,
            material
        );
    }

    std::optional<HitResult>
    Scene::Hit(const UnitRay3f& ray, const Range<float>& range) const
    {
        std::optional<HitResult> r = std::nullopt;

        for(const auto o: objects)
        {
            const auto h = o->Hit(ray, range);
            if(r.has_value() == false)
            {
                r = h;
            }
            else
            {
                if(h.has_value())
                {
                    if(h->ray_distance < r->ray_distance)
                    {
                        r = h;
                    }
                }
            }
        }

        return r;
    }

    Rgb
    rgb(const unit3f& normal)
    {
        return Rgb
        {
            (normal.x + 1)/2,
            (normal.y + 1)/2,
            (normal.z + 1)/2
        };
    }

    vec3f RandomInUnitSphere(Random* random)
    {
        return RandomUnit3(random) * random->NextFloat01();
    }

    Material::~Material() {}

    struct DiffuseMaterial : public Material
    {
        Rgb albedo;

        explicit DiffuseMaterial(const Rgb& aalbedo)
            : albedo(aalbedo)
        {
        }

        std::optional<ScatterResult>
        Scatter
        (
            const UnitRay3f& /*ray*/,
            const HitResult& hit,
            Random* random
        ) override
        {
            const auto target = hit.position + hit.normal + RandomInUnitSphere(random);
            const auto reflected_ray = UnitRay3f::FromTo(hit.position, target);

            return ScatterResult
            {
                albedo,
                reflected_ray
            };
        }
    };

    vec3f Reflect(const vec3f& v, const unit3f& n) {
        return v - 2*dot(v,n)*n;
    }

    struct MetalMaterial : public Material
    {
        Rgb albedo;
        float fuzz;

        explicit MetalMaterial
        (
            const Rgb& aalbedo,
            float afuzz
        )
            : albedo(aalbedo)
            , fuzz(KeepWithin(R01(), afuzz))
        {
        }

        std::optional<ScatterResult>
        Scatter
        (
            const UnitRay3f& ray,
            const HitResult& hit,
            Random* random
        ) override
        {
            const auto reflected = Reflect
            (
                ray.dir,
                hit.normal
            );
            const auto scattered = UnitRay3f::FromTo
            (
                hit.position,
                reflected + fuzz * RandomInUnitSphere(random)
            );
            const auto scatter_dot = dot
            (
                scattered.dir,
                hit.normal
            );
            if(scatter_dot > 0)
            {
                return ScatterResult
                {
                    albedo,
                    scattered
                };
            }
            else
            {
                return std::nullopt;
            }
        }
    };

    std::optional<vec3f>
    Refract
    (
        const unit3f& uv,
        const unit3f& normal,
        float ni
    )
    {
        const auto dt = dot(uv, normal);
        const auto discriminant = 1.0f - ni*ni*(1.0f-dt*dt);
        if (discriminant > 0)
        {
            return ni * (uv - normal * dt) - normal * Sqrt(discriminant);
        }
        else
        {
            return std::nullopt;
        }
    }

    float
    FresnelFactor(float cosine, float ref_idx)
    {
        const auto r0 = Square
        (
            (1-ref_idx) / (1+ref_idx)
        );
        return r0 + (1-r0)*pow((1 - cosine), 5);
    }

    struct DielectricMaterial : public Material
    {
        Rgb albedo;
        float refractive_index;

        explicit DielectricMaterial
        (
            const Rgb& aalbedo,
            float arefractive_index
        )
            : albedo(aalbedo)
            , refractive_index(arefractive_index)
        {
        }

        std::optional<ScatterResult>
        Scatter
        (
            const UnitRay3f& ray,
            const HitResult& hit,
            Random* random
        ) override
        {
            const auto dr = dot(ray.dir, hit.normal);
            const auto dot_result = dr > 0.0f;

            const auto outward_normal = dot_result ? -hit.normal : hit.normal;
            const auto ni = dot_result ? refractive_index : 1.0f/refractive_index;

            const auto refracted = Refract(ray.dir, outward_normal, ni);

            if(refracted.has_value())
            {
                const auto cosine = dot_result
                    ? refractive_index * dr
                    : -dr
                    ;
                const auto reflection_probability = FresnelFactor(cosine, refractive_index);
                if( random->NextFloat01() >= reflection_probability )
                {
                    return ScatterResult
                    {
                        albedo,
                        UnitRay3f::FromTo
                        (
                            hit.position,
                            refracted.value()
                        )
                    };
                }
            }
            const auto reflected = Reflect
            (
                ray.dir,
                hit.normal
            );
            return ScatterResult
            {
                albedo,
                UnitRay3f::FromTo
                (
                    hit.position,
                    reflected
                )
            };
        }
    };

    std::shared_ptr<Material>
    CreateDiffuseMaterial
    (
        const Rgb& albedo
    )
    {
        return std::make_shared<DiffuseMaterial>
        (
            albedo
        );
    }

    std::shared_ptr<Material>
    CreateMetalMaterial
    (
        const Rgb& albedo,
        float fuzz
    )
    {
        return std::make_shared<MetalMaterial>
        (
            albedo,
            fuzz
        );
    }

    std::shared_ptr<Material>
    CreateDielectricMaterial
    (
        const Rgb& albedo,
        float refractive_index
    )
    {
        return std::make_shared<DielectricMaterial>
        (
            albedo,
            refractive_index
        );
    }

    Rgb
    GetColor
    (
        const Scene& scene,
        const UnitRay3f& ray,
        Random* random,
        int depth
    )
    {
        const auto h = scene.Hit
        (
            ray,
            MakeRange(0.001f, std::numeric_limits<float>::max())
        );
        if(h.has_value())
        {
            if(depth < 50)
            {
                auto scatter = h->material->Scatter
                (
                    ray,
                    h.value(),
                    random
                );
                if(scatter.has_value())
                {
                    const auto c = GetColor
                    (
                        scene,
                        scatter->scattered,
                        random,
                        depth + 1
                    );
                    return scatter->attenuation * c;
                }
                else
                {
                    return Color::Black;
                }
            }
            else
            {
                return Color::Black;
            }
        }
        const auto t = (ray.dir.y+1)/2.0f;
        return RgbTransform::Transform
        (
            Rgb(1.0f, 1.0f, 1.0f),
            t,
            Rgb(0.5f, 0.7f, 1.0f)
        );
    }

    struct Camera
    {
        vec3f lower_left_corner = vec3f{-2.0f, -1.0f, -1.0f};
        vec3f horizontal = vec3f{4.0f, 0.0f, 0.0f};
        vec3f vertical = vec3f{0.0f, 2.0f, 0.0f};
        vec3f origin = vec3f{0.0f, 0.0f, 0.0f};

        UnitRay3f GetRay(float u, float v) const
        {
            return UnitRay3f::FromTo(origin, lower_left_corner + u*horizontal + v*vertical);
        }
    };

    Rgb
    Gamma2CorrectColor(Rgb color)
    {
        return {Sqrt(color.r), Sqrt(color.g), Sqrt(color.b)};
    }

    void
    Raytrace(Image* aimage, const Scene& scene, int number_of_samples)
    {
        Image& img = *aimage;

        auto random = Random{};
        const auto camera = Camera{};

        {
        std::cout << "Rendering ";
        CliProgressBar progress;

        const int number_of_pixels = img.GetWidth() * img.GetHeight();

        for(int y=0; y<img.GetHeight(); y+=1)
        for(int x=0; x<img.GetWidth(); x+=1)
        {
            Rgb color = Color::Black;
            for(int sample = 0; sample < number_of_samples; sample += 1)
            {
                const auto u = (x + random.NextFloat01()) / static_cast<float>(img.GetWidth());
                const auto v = (y + random.NextFloat01()) / static_cast<float>(img.GetHeight());
                const auto ray = camera.GetRay(u, v);
                const auto sample_color = GetColor(scene, ray, &random, 0);
                color += sample_color;
            }
            color = color/number_of_samples;
            color = Gamma2CorrectColor(color);
            img.SetPixel(x,y, rgbi(color));
            progress.Update( (y*img.GetWidth() + x)/static_cast<float>(number_of_pixels) );
        }
        }
        std::cout << "Rendering done :)\n";
    }
}

<|endoftext|>


<commit_before>/*
Description:
This is a example code for Sandbox Electronics NDIR CO2 sensor module.
You can get one of those products on
http://sandboxelectronics.com

Version:
V1.0

Release Date:
2016-03-30

Author:
Tiequan Shao          info@sandboxelectronics.com

Lisence:
CC BY-NC-SA 3.0

Please keep the above information when you use this code in your project.
*/

#include <SoftwareSerial.h>
#include <NDIR_SoftwareSerial.h>
#define  RECEIVE_TIMEOUT  (100)

#if ARDUINO >= 100
    #include "Arduino.h"
#else
    #include "WProgram.h"
#endif

class SoftwareSerial;

uint8_t NDIR_SoftwareSerial::cmd_measure[9] = {0xFF,0x01,0x9C,0x00,0x00,0x00,0x00,0x00,0x63};

NDIR_SoftwareSerial::NDIR_SoftwareSerial(uint8_t rx_pin, uint8_t tx_pin) : serial(rx_pin, tx_pin, false)
{
}

uint8_t NDIR_SoftwareSerial::begin()
{
    serial.begin(9600);

    if (measure()) {
        return true;
    } else {
        return false;
    }
}

uint8_t NDIR_SoftwareSerial::measure()
{
    uint8_t i;
    uint8_t buf[9];
    uint32_t start = millis();

    serial.flush();

    for (i=0; i<9; i++) {
        serial.write(cmd_measure[i]);
    }

    for (i=0; i<9;) {
        if (serial.available()) {
            buf[i++] = serial.read();
        }

        if (millis() - start > RECEIVE_TIMEOUT) {
            return false;
        }
    }

    if (parse(buf)) {
        return true;
    }

    return false;
}

uint8_t NDIR_SoftwareSerial::parse(uint8_t *pbuf)
{
    uint8_t i;
    uint8_t checksum = 0;

    for (i=0; i<9; i++) {
        checksum += pbuf[i];
    }

    if (pbuf[0] == 0xFF && pbuf[1] == 0x9C && checksum == 0xFF) {
        ppm = (uint32_t)pbuf[2] << 24 | (uint32_t)pbuf[3] << 16 | (uint32_t)pbuf[4] << 8 | pbuf[5];
        return true;
    } else {
        return false;
    }
}
<commit_msg>Add calibration function<commit_after>/*
Description:
This is a example code for Sandbox Electronics NDIR CO2 sensor module.
You can get one of those products on
http://sandboxelectronics.com

Version:
V1.1

Release Date:
2017-11-01

Author:
Tiequan Shao          info@sandboxelectronics.com

Lisence:
CC BY-NC-SA 3.0

Please keep the above information when you use this code in your project.
*/

#include <SoftwareSerial.h>
#include <NDIR_SoftwareSerial.h>
#define  RECEIVE_TIMEOUT  (100)

#if ARDUINO >= 100
    #include "Arduino.h"
#else
    #include "WProgram.h"
#endif

class SoftwareSerial;

uint8_t NDIR_SoftwareSerial::cmd_measure[9]       = {0xFF,0x01,0x9C,0x00,0x00,0x00,0x00,0x00,0x63};
uint8_t NDIR_SoftwareSerial::cmd_calibrateZero[9] = {0xFF,0x01,0x87,0x00,0x00,0x00,0x00,0x00,0x78};

NDIR_SoftwareSerial::NDIR_SoftwareSerial(uint8_t rx_pin, uint8_t tx_pin) : serial(rx_pin, tx_pin, false)
{
}

uint8_t NDIR_SoftwareSerial::begin()
{
    serial.begin(9600);

    if (measure()) {
        return true;
    } else {
        return false;
    }
}

uint8_t NDIR_SoftwareSerial::measure()
{
    uint8_t i;
    uint8_t buf[9];
    uint32_t start = millis();

    serial.flush();

    for (i=0; i<9; i++) {
        serial.write(cmd_measure[i]);
    }

    for (i=0; i<9;) {
        if (serial.available()) {
            buf[i++] = serial.read();
        }

        if (millis() - start > RECEIVE_TIMEOUT) {
            return false;
        }
    }

    if (parse(buf)) {
        return true;
    }

    return false;
}

void NDIR_SoftwareSerial::calibrateZero()
{
    uint8_t i;

    for (i=0; i<9; i++) {
        serial.write(cmd_calibrateZero[i]);
    }
}

uint8_t NDIR_SoftwareSerial::parse(uint8_t *pbuf)
{
    uint8_t i;
    uint8_t checksum = 0;

    for (i=0; i<9; i++) {
        checksum += pbuf[i];
    }

    if (pbuf[0] == 0xFF && pbuf[1] == 0x9C && checksum == 0xFF) {
        ppm = (uint32_t)pbuf[2] << 24 | (uint32_t)pbuf[3] << 16 | (uint32_t)pbuf[4] << 8 | pbuf[5];
        return true;
    } else {
        return false;
    }
}
<|endoftext|>


<commit_before>//
//  EmojicodeAPI.h
//  Emojicode
//
//  Created by Theo Weidmann on 12.01.15.
//  Copyright (c) 2015 Theo Weidmann. All rights reserved.
//

#ifndef EmojicodeAPI_h
#define EmojicodeAPI_h

#include "../EmojicodeShared.h"
#include <cstddef>

namespace Emojicode {

typedef unsigned char Byte;
typedef int_fast64_t EmojicodeInteger;

struct Class;
struct List;
struct Object;
class Thread;

extern Class *CL_STRING;
extern Class *CL_LIST;
extern Class *CL_DATA;
extern Class *CL_DICTIONARY;
extern Class *CL_CLOSURE;
extern Class *CL_ARRAY;

/// A one-Emojicode-word large value without type information.
union Value {
    /// Returns an undefined Value
    Value() {}
    Value(bool raw) : raw(raw) {}
    Value(EmojicodeInteger raw) : raw(raw) {}
    Value(EmojicodeChar raw) : character(raw) {}
    Value(Object *object) : object(object) {}
    Value(Value *value) : value(value) {}
    Value(double doubl) : doubl(doubl) {}
    EmojicodeInteger raw;
    EmojicodeChar character;
    double doubl;
    Object *object;
    Class *klass;
    Value *value;
    void makeNothingness() { raw = T_NOTHINGNESS; }
    void optionalSet(Value value) { raw = T_OPTIONAL_VALUE; this[1] = value; }
    void storeError(EmojicodeInteger error) { raw = T_ERROR; this[1] = error; }
    void setValueForError(Value value) { raw = T_OPTIONAL_VALUE; this[1] = value; }
};

struct Object {
    union {
        /// The class of the object
        Class *klass;
        /// Used by the Garbage Collector, do not change!
        Object *newLocation;
    };
    /** The size of this object: the size of the Object struct and the value area. */
    size_t size;

    template <typename T>
    inline T* val() {
        return reinterpret_cast<T*>(this + 1);
    }

    inline Value* variableDestination(EmojicodeInstruction index) {
        return reinterpret_cast<Value *>(reinterpret_cast<Byte *>(this) + sizeof(Object) + sizeof(Value) * index);
    }
};

/// Used to store a value when the type of the value is not known at compile time.
struct Box {
    Box(EmojicodeInteger type, Value value1) : type(type), value1(value1) {}
    Box() {}
    /// The type of the value stored in this box.
    Value type;
    Value value1;
    Value value2;
    Value value3;
    /// Returns true if this Box contains Nothingness
    bool isNothingness() const { return type.raw == T_NOTHINGNESS; }
    /// Aborts the program if this Box contains Nothingness
    void unwrapOptional() const;
    /// Makes this Box contain Nothingness
    void makeNothingness() { type.raw = T_NOTHINGNESS; }
    void copySingleValue(EmojicodeInteger type, Value value) { this->type = type; value1 = value; }
    void copy(Value *value) {  *this = *reinterpret_cast<Box *>(value); }
    void copyTo(Value *value) const { *reinterpret_cast<Box *>(value) = *this; }
};

#define STORAGE_BOX_VALUE_SIZE 4

// MARK: Callables

/** You can use this function to call a callable object. It’s internally Garbage-Collector safe. */
extern void executeCallableExtern(Object *callable, Value *args, size_t argsSize, Thread *thread, Value *destination);

// MARK: Primitive Objects

/**
 * Allocates a new object for the given class.
 * The @c value field will point to a value area as large as specified for the given class.
 * @param klass The class of the object.
 * @warning GC-invoking
 */
extern Object* newObject(Class *klass);

/**
 * Multiplies @c items by @c itemSize and terminates the program with an error if an integer
 * overflow occured.
 */
extern size_t sizeCalculationWithOverflowProtection(size_t items, size_t itemSize);

/**
 * Allocates an array with a value area of the given size.
 * @param size The size of the value area.
 * @warning GC-invoking
 */
extern Object* newArray(size_t size);

/**
 * Tries to resize the given array object to the given size and returns a pointer to the resized array.
 * @param array An array object created by @c newArray.
 * @param size The new size.
 * @returns A pointer to the resized array.
 * @warning GC-invoking
 */
extern Object* resizeArray(Object *array, size_t size);

// MARK: Garbage Collection

/**
 * Marks the object @c O pointed to by the pointer @c P to which @c of points.
 * @warning This function will modify @c P to point to an exact copy of @c O after the function call.
 */
extern void mark(Object **of);
/**
 * If the calling thread needs to be paused for the GC to run, this function will first
 * unlock @c mutex if it is not a @c nullptr pointer, then block until the GC cycle is completed
 * and finally try to acquire @c mutex. Otherwise no action is performed.
 *
 * You normally do not need to call this method from method or intializer implementations.
 */
extern void pauseForGC();
/**
 * This function allows the GC to run even while the calling thread is not paused and working.
 * You must ensure that @c disallowGCAndPauseIfNeeded is called at an appropriate time, but it must be
 * called before the calling thread finishes.
 *
 * @warning Between the call to this function and @c disallowGCAndPauseIfNeeded you must not perform
 * any allocations or other kind of GC-invoking operations.
 */
extern void allowGC();
/**
 * See @c allowGC
 */
extern void disallowGCAndPauseIfNeeded();

typedef void (*FunctionFunctionPointer)(Thread *thread);
typedef void (*Marker)(Object *self);

/// The version of a package. Must follow semantic versioning 2.0 http://semver.org
struct PackageVersion {
    PackageVersion(uint16_t major, uint16_t minor) : major(major), minor(minor) {}
    /** The major version */
    uint16_t major;
    /** The minor version */
    uint16_t minor;
};

}

#define LinkingTable Emojicode::FunctionFunctionPointer linkingTable[] =

#endif /* EmojicodeAPI_h */
<commit_msg>😡 Undef Linux macros<commit_after>//
//  EmojicodeAPI.h
//  Emojicode
//
//  Created by Theo Weidmann on 12.01.15.
//  Copyright (c) 2015 Theo Weidmann. All rights reserved.
//

#ifndef EmojicodeAPI_h
#define EmojicodeAPI_h

#include "../EmojicodeShared.h"
#include <cstddef>

namespace Emojicode {

typedef unsigned char Byte;
typedef int_fast64_t EmojicodeInteger;

struct Class;
struct List;
struct Object;
class Thread;

extern Class *CL_STRING;
extern Class *CL_LIST;
extern Class *CL_DATA;
extern Class *CL_DICTIONARY;
extern Class *CL_CLOSURE;
extern Class *CL_ARRAY;

/// A one-Emojicode-word large value without type information.
union Value {
    /// Returns an undefined Value
    Value() {}
    Value(bool raw) : raw(raw) {}
    Value(EmojicodeInteger raw) : raw(raw) {}
    Value(EmojicodeChar raw) : character(raw) {}
    Value(Object *object) : object(object) {}
    Value(Value *value) : value(value) {}
    Value(double doubl) : doubl(doubl) {}
    EmojicodeInteger raw;
    EmojicodeChar character;
    double doubl;
    Object *object;
    Class *klass;
    Value *value;
    void makeNothingness() { raw = T_NOTHINGNESS; }
    void optionalSet(Value value) { raw = T_OPTIONAL_VALUE; this[1] = value; }
    void storeError(EmojicodeInteger error) { raw = T_ERROR; this[1] = error; }
    void setValueForError(Value value) { raw = T_OPTIONAL_VALUE; this[1] = value; }
};

struct Object {
    union {
        /// The class of the object
        Class *klass;
        /// Used by the Garbage Collector, do not change!
        Object *newLocation;
    };
    /** The size of this object: the size of the Object struct and the value area. */
    size_t size;

    template <typename T>
    inline T* val() {
        return reinterpret_cast<T*>(this + 1);
    }

    inline Value* variableDestination(EmojicodeInstruction index) {
        return reinterpret_cast<Value *>(reinterpret_cast<Byte *>(this) + sizeof(Object) + sizeof(Value) * index);
    }
};

/// Used to store a value when the type of the value is not known at compile time.
struct Box {
    Box(EmojicodeInteger type, Value value1) : type(type), value1(value1) {}
    Box() {}
    /// The type of the value stored in this box.
    Value type;
    Value value1;
    Value value2;
    Value value3;
    /// Returns true if this Box contains Nothingness
    bool isNothingness() const { return type.raw == T_NOTHINGNESS; }
    /// Aborts the program if this Box contains Nothingness
    void unwrapOptional() const;
    /// Makes this Box contain Nothingness
    void makeNothingness() { type.raw = T_NOTHINGNESS; }
    void copySingleValue(EmojicodeInteger type, Value value) { this->type = type; value1 = value; }
    void copy(Value *value) {  *this = *reinterpret_cast<Box *>(value); }
    void copyTo(Value *value) const { *reinterpret_cast<Box *>(value) = *this; }
};

#define STORAGE_BOX_VALUE_SIZE 4

// MARK: Callables

/** You can use this function to call a callable object. It’s internally Garbage-Collector safe. */
extern void executeCallableExtern(Object *callable, Value *args, size_t argsSize, Thread *thread, Value *destination);

// MARK: Primitive Objects

/**
 * Allocates a new object for the given class.
 * The @c value field will point to a value area as large as specified for the given class.
 * @param klass The class of the object.
 * @warning GC-invoking
 */
extern Object* newObject(Class *klass);

/**
 * Multiplies @c items by @c itemSize and terminates the program with an error if an integer
 * overflow occured.
 */
extern size_t sizeCalculationWithOverflowProtection(size_t items, size_t itemSize);

/**
 * Allocates an array with a value area of the given size.
 * @param size The size of the value area.
 * @warning GC-invoking
 */
extern Object* newArray(size_t size);

/**
 * Tries to resize the given array object to the given size and returns a pointer to the resized array.
 * @param array An array object created by @c newArray.
 * @param size The new size.
 * @returns A pointer to the resized array.
 * @warning GC-invoking
 */
extern Object* resizeArray(Object *array, size_t size);

// MARK: Garbage Collection

/**
 * Marks the object @c O pointed to by the pointer @c P to which @c of points.
 * @warning This function will modify @c P to point to an exact copy of @c O after the function call.
 */
extern void mark(Object **of);
/**
 * If the calling thread needs to be paused for the GC to run, this function will first
 * unlock @c mutex if it is not a @c nullptr pointer, then block until the GC cycle is completed
 * and finally try to acquire @c mutex. Otherwise no action is performed.
 *
 * You normally do not need to call this method from method or intializer implementations.
 */
extern void pauseForGC();
/**
 * This function allows the GC to run even while the calling thread is not paused and working.
 * You must ensure that @c disallowGCAndPauseIfNeeded is called at an appropriate time, but it must be
 * called before the calling thread finishes.
 *
 * @warning Between the call to this function and @c disallowGCAndPauseIfNeeded you must not perform
 * any allocations or other kind of GC-invoking operations.
 */
extern void allowGC();
/**
 * See @c allowGC
 */
extern void disallowGCAndPauseIfNeeded();

typedef void (*FunctionFunctionPointer)(Thread *thread);
typedef void (*Marker)(Object *self);

#undef major
#undef minor

/// The version of a package. Must follow semantic versioning 2.0 http://semver.org
struct PackageVersion {
    PackageVersion(uint16_t major, uint16_t minor) : major(major), minor(minor) {}
    /** The major version */
    uint16_t major;
    /** The minor version */
    uint16_t minor;
};

}

#define LinkingTable Emojicode::FunctionFunctionPointer linkingTable[] =

#endif /* EmojicodeAPI_h */
<|endoftext|>


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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.

Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.

============================================================================*/

#include "QmitkRegisterClasses.h"
#include "QmitkRenderWindow.h"

#include <mitkStandaloneDataStorage.h>

#include <QApplication>
#include <itksys/SystemTools.hxx>

#include <mitkAnnotationUtils.h>
#include <mitkLayoutAnnotationRenderer.h>
#include <mitkManualPlacementAnnotationRenderer.h>
#include <mitkTextAnnotation2D.h>
#include <mitkTextAnnotation3D.h>

#include <mitkIOUtil.h>

//##Documentation
//## @brief Load image (nrrd format) and display it in a 2D view
int main(int argc, char *argv[])
{
  QApplication qtapplication(argc, argv);

  if (argc < 2)
  {
    fprintf(stderr, "Usage:   %s [filename] \n\n", itksys::SystemTools::GetFilenameName(argv[0]).c_str());
    return 1;
  }

  // Register Qmitk-dependent global instances
  QmitkRegisterClasses();

  mitk::StandaloneDataStorage::Pointer ds = mitk::StandaloneDataStorage::New();

  // Load datanode (eg. many image formats, surface formats, etc.)
  mitk::IOUtil::Load(argv[1], *ds);

  // Create a RenderWindow
  QmitkRenderWindow renderWindow;

  // Tell the RenderWindow which (part of) the datastorage to render
  renderWindow.GetRenderer()->SetDataStorage(ds);

  // Initialize the RenderWindow
  auto geo = ds->ComputeBoundingGeometry3D(ds->GetAll());
  mitk::RenderingManager::GetInstance()->InitializeViews(geo);
  // mitk::RenderingManager::GetInstance()->InitializeViews();

  // Add Overlays
  //![TextAnnotation2D]
  // Create a textAnnotation2D
  mitk::TextAnnotation2D::Pointer textAnnotation = mitk::TextAnnotation2D::New();

  textAnnotation->SetText("Test!"); // set UTF-8 encoded text to render
  textAnnotation->SetFontSize(40);
  textAnnotation->SetColor(1, 0, 0); // Set text color to red
  textAnnotation->SetOpacity(1);

  // The position of the Annotation can be set to a fixed coordinate on the display.
  mitk::Point2D pos;
  pos[0] = 10;
  pos[1] = 20;
  textAnnotation->SetPosition2D(pos);

  std::string rendererID = renderWindow.GetRenderer()->GetName();

  // The LayoutAnnotationRenderer can place the TextAnnotation2D at some defined corner positions
  mitk::LayoutAnnotationRenderer::AddAnnotation(
    textAnnotation, rendererID, mitk::LayoutAnnotationRenderer::TopLeft, 5, 5, 1);
  //![TextAnnotation2D]

  //![TextAnnotation3D]
  mitk::PointSet::Pointer pointset = mitk::PointSet::New();

  // This vector is used to define an offset for the annotations, in order to show them with a margin to the actual
  // coordinate.
  mitk::Point3D offset;
  offset[0] = .5;
  offset[1] = .5;
  offset[2] = .5;

  // save references to Annotations so that they do not get deregistered
  std::vector<mitk::TextAnnotation3D::Pointer> annotationReferences;

  // Just a loop to create some points
  for (unsigned long i = 0; i < 10; i++)
  {
    // To each point, a TextAnnotation3D is created
    mitk::TextAnnotation3D::Pointer textAnnotation3D = mitk::TextAnnotation3D::New();
    mitk::Point3D point;
    point[0] = i * 20;
    point[1] = i * 30;
    point[2] = i * -50;
    pointset->InsertPoint(i, point);
    textAnnotation3D->SetText("A Point");

    // The Position is set to the point coordinate to create an annotation to the point in the PointSet.
    textAnnotation3D->SetPosition3D(point);

    // move the annotation away from the actual point
    textAnnotation3D->SetOffsetVector(offset);

    annotationReferences.push_back(textAnnotation3D);
    mitk::ManualPlacementAnnotationRenderer::AddAnnotation(textAnnotation3D, rendererID);
  }

  // Get the MicroserviceID of the registered textAnnotation
  std::string serviceID = textAnnotation->GetMicroserviceID();

  // The AnnotationUtils can retrieve any registered annotations by their microservice ID
  mitk::Annotation *annotation = mitk::AnnotationUtils::GetAnnotation(serviceID);
  // This way, it is possible to change the properties of Annotations without knowing their implementation
  annotation->SetText("changed text!");

  // also show the created pointset
  mitk::DataNode::Pointer datanode = mitk::DataNode::New();
  datanode->SetData(pointset);
  datanode->SetName("pointSet");
  ds->Add(datanode);
  //! [TextAnnotation3D]
  renderWindow.show();
  renderWindow.resize(256, 256);

  renderWindow.show();
  renderWindow.resize(256, 256);

  // cleanup: Remove References to DataStorage. This will delete the object
  ds = nullptr;
}
/**
\example Step1.cpp
*/
<commit_msg>Remove wrong example reference<commit_after>/*============================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.

Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.

============================================================================*/

#include "QmitkRegisterClasses.h"
#include "QmitkRenderWindow.h"

#include <mitkStandaloneDataStorage.h>

#include <QApplication>
#include <itksys/SystemTools.hxx>

#include <mitkAnnotationUtils.h>
#include <mitkLayoutAnnotationRenderer.h>
#include <mitkManualPlacementAnnotationRenderer.h>
#include <mitkTextAnnotation2D.h>
#include <mitkTextAnnotation3D.h>

#include <mitkIOUtil.h>

//##Documentation
//## @brief Load image (nrrd format) and display it in a 2D view
int main(int argc, char *argv[])
{
  QApplication qtapplication(argc, argv);

  if (argc < 2)
  {
    fprintf(stderr, "Usage:   %s [filename] \n\n", itksys::SystemTools::GetFilenameName(argv[0]).c_str());
    return 1;
  }

  // Register Qmitk-dependent global instances
  QmitkRegisterClasses();

  mitk::StandaloneDataStorage::Pointer ds = mitk::StandaloneDataStorage::New();

  // Load datanode (eg. many image formats, surface formats, etc.)
  mitk::IOUtil::Load(argv[1], *ds);

  // Create a RenderWindow
  QmitkRenderWindow renderWindow;

  // Tell the RenderWindow which (part of) the datastorage to render
  renderWindow.GetRenderer()->SetDataStorage(ds);

  // Initialize the RenderWindow
  auto geo = ds->ComputeBoundingGeometry3D(ds->GetAll());
  mitk::RenderingManager::GetInstance()->InitializeViews(geo);
  // mitk::RenderingManager::GetInstance()->InitializeViews();

  // Add Overlays
  //![TextAnnotation2D]
  // Create a textAnnotation2D
  mitk::TextAnnotation2D::Pointer textAnnotation = mitk::TextAnnotation2D::New();

  textAnnotation->SetText("Test!"); // set UTF-8 encoded text to render
  textAnnotation->SetFontSize(40);
  textAnnotation->SetColor(1, 0, 0); // Set text color to red
  textAnnotation->SetOpacity(1);

  // The position of the Annotation can be set to a fixed coordinate on the display.
  mitk::Point2D pos;
  pos[0] = 10;
  pos[1] = 20;
  textAnnotation->SetPosition2D(pos);

  std::string rendererID = renderWindow.GetRenderer()->GetName();

  // The LayoutAnnotationRenderer can place the TextAnnotation2D at some defined corner positions
  mitk::LayoutAnnotationRenderer::AddAnnotation(
    textAnnotation, rendererID, mitk::LayoutAnnotationRenderer::TopLeft, 5, 5, 1);
  //![TextAnnotation2D]

  //![TextAnnotation3D]
  mitk::PointSet::Pointer pointset = mitk::PointSet::New();

  // This vector is used to define an offset for the annotations, in order to show them with a margin to the actual
  // coordinate.
  mitk::Point3D offset;
  offset[0] = .5;
  offset[1] = .5;
  offset[2] = .5;

  // save references to Annotations so that they do not get deregistered
  std::vector<mitk::TextAnnotation3D::Pointer> annotationReferences;

  // Just a loop to create some points
  for (unsigned long i = 0; i < 10; i++)
  {
    // To each point, a TextAnnotation3D is created
    mitk::TextAnnotation3D::Pointer textAnnotation3D = mitk::TextAnnotation3D::New();
    mitk::Point3D point;
    point[0] = i * 20;
    point[1] = i * 30;
    point[2] = i * -50;
    pointset->InsertPoint(i, point);
    textAnnotation3D->SetText("A Point");

    // The Position is set to the point coordinate to create an annotation to the point in the PointSet.
    textAnnotation3D->SetPosition3D(point);

    // move the annotation away from the actual point
    textAnnotation3D->SetOffsetVector(offset);

    annotationReferences.push_back(textAnnotation3D);
    mitk::ManualPlacementAnnotationRenderer::AddAnnotation(textAnnotation3D, rendererID);
  }

  // Get the MicroserviceID of the registered textAnnotation
  std::string serviceID = textAnnotation->GetMicroserviceID();

  // The AnnotationUtils can retrieve any registered annotations by their microservice ID
  mitk::Annotation *annotation = mitk::AnnotationUtils::GetAnnotation(serviceID);
  // This way, it is possible to change the properties of Annotations without knowing their implementation
  annotation->SetText("changed text!");

  // also show the created pointset
  mitk::DataNode::Pointer datanode = mitk::DataNode::New();
  datanode->SetData(pointset);
  datanode->SetName("pointSet");
  ds->Add(datanode);
  //! [TextAnnotation3D]
  renderWindow.show();
  renderWindow.resize(256, 256);

  renderWindow.show();
  renderWindow.resize(256, 256);

  // cleanup: Remove References to DataStorage. This will delete the object
  ds = nullptr;
}
<|endoftext|>


<commit_before>/* Siconos-sample version 3.0.0, Copyright INRIA 2005-2008.
 * Siconos is a program dedicated to modeling, simulation and control
 * of non smooth dynamical systems.
 * Siconos is a free software; you can redistribute it and/or modify
 * it 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.
 * Siconos 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 Siconos; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Contact: Vincent ACARY vincent.acary@inrialpes.fr
 */

// =============================== Robot arm sample (HuMAnsPa10) ===============================
//
// see modelRobot1.jpg for complete system view.
//
// Keywords: LagrangianDS, LagrangianLinear relation, Moreau TimeStepping, LCP.
//
// =============================================================================================

#include "SiconosKernel.hpp"

using namespace std;

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

    // ================= Creation of the model =======================

    // User-defined main parameters
    unsigned int nDof = 3;           // degrees of freedom for robot arm
    double t0 = 0;                   // initial computation time
    double T = 1.9;                   // final computation time
    double h = 0.005;                // time step
    double criterion = 0.0005;
    unsigned int maxIter = 20000;
    double e = 0.9;                  // restit. coef. for impact on the ground.
    double e2 = 0.0;                 // restit. coef for angular stops impacts.

    // -> mind to set the initial conditions below.

    // -------------------------
    // --- Dynamical systems ---
    // -------------------------

    // unsigned int i;
    DynamicalSystemsSet allDS; // the list of DS

    // --- DS: robot arm ---

    // The dof are angles between ground and arm and between differents parts of the arm. (See Robot.fig for more details)
    //

    // Initial position (angles in radian)
    SP::SimpleVector q0(new SimpleVector(nDof)), v0(new SimpleVector(nDof));
    (*q0)(0) = 0.05;
    (*q0)(1) = 0.05;

    SP::LagrangianDS arm(new LagrangianDS(q0, v0));

    // external plug-in
    arm->setComputeMassFunction("RobotPlugin.so", "mass");
    arm->setComputeNNLFunction("RobotPlugin.so", "NNL");
    arm->setComputeJacobianNNLqDotFunction("RobotPlugin.so", "jacobianVNNL");
    arm->setComputeJacobianNNLqFunction("RobotPlugin.so", "jacobianNNLq");

    allDS.insert(arm);

    // -------------------
    // --- Interactions---
    // -------------------

    // Two interactions:
    //  - one with Lagrangian non linear relation to define contact with ground
    //  - the other to define angles limitations (articular stops), with lagrangian linear relation
    //  Both with newton impact ns laws.

    InteractionsSet allInteractions; // The set of all interactions.

    // -- relations --

    // => arm-floor relation
    SP::NonSmoothLaw nslaw(new NewtonImpactNSL(e));
    string G = "RobotPlugin:G2";
    SP::Relation relation(new LagrangianScleronomousR("RobotPlugin:h2", G));
    SP::Interaction inter(new Interaction("floor-arm", allDS, 0, 2, nslaw, relation));

    // => angular stops

    //     SimpleMatrix H(6,3);
    //     SimpleVector b(6);
    //     H.zero();
    //     H(0,0) =-1;
    //     H(1,0) =1;
    //     H(2,1) =-1;
    //     H(3,1) =1;
    //     H(4,2) =-1;
    //     H(5,2) =1;

    //     b(0) = 1.7;
    //     b(1) = 1.7;
    //     b(2) = 0.3;
    //     b(3) = 0.3;
    //     b(4) = 3.14;
    //     b(5) = 3.14;
    double lim0 = 1.6;
    double lim1 = 3.1;  // -lim <= q[1] <= lim
    SP::SimpleMatrix H(new SimpleMatrix(4, 3));
    SP::SimpleVector b(new SimpleVector(4));
    H->zero();

    (*H)(0, 0) = -1;
    (*H)(1, 0) = 1;
    (*H)(2, 1) = -1;
    (*H)(3, 1) = 1;

    (*b)(0) = lim0;
    (*b)(1) = lim0;
    (*b)(2) = lim1;
    (*b)(3) = lim1;

    SP::NonSmoothLaw nslaw2(new NewtonImpactNSL(e2));
    SP::Relation relation2(new LagrangianLinearTIR(H, b));
    SP::Interaction inter2(new Interaction("floor-arm2", allDS, 1, 4, nslaw2, relation2));

    allInteractions.insert(inter);
    allInteractions.insert(inter2);

    // -------------
    // --- Model ---
    // -------------

    SP::Model Robot(new Model(t0, T, allDS, allInteractions));

    // ----------------
    // --- Simulation ---
    // ----------------

    // -- Time discretisation --
    SP::TimeDiscretisation t(new TimeDiscretisation(t0, h));

    SP::TimeStepping s(new TimeStepping(t));

    // -- OneStepIntegrators --
    SP::OneStepIntegrator OSI(new Moreau(arm, 0.500001));
    s->insertIntegrator(OSI);

    SP::OneStepNSProblem osnspb(new LCP("PGS"));

    osnspb->numericsSolverOptions()->iparam[0] = 30001;
    osnspb->numericsSolverOptions()->dparam[0] = 0.005;

    s->insertNonSmoothProblem(osnspb);

    cout << "=== End of model loading === " << endl;

    // =========================== End of model definition ===========================  dataPlot(k,7) = (*inter->y(0))(0);

    // ================================= Computation =================================

    // --- Simulation initialization ---
    Robot->initialize(s);
    cout << "End of model initialisation" << endl;

    int k = 0;
    int N = (int)((T - t0) / h) + 1;

    // --- Get the values to be plotted ---
    // -> saved in a matrix dataPlot
    unsigned int outputSize = 9;
    SimpleMatrix dataPlot(N + 1, outputSize);
    // For the initial time step:
    // time

    SP::SiconosVector q = arm->q();
    SP::SiconosVector vel = arm->velocity();
    SP::SiconosVector y = inter->y(0);

    dataPlot(k, 0) =  Robot->t0();
    dataPlot(k, 1) = (*q)(0);
    dataPlot(k, 2) = (*vel)(0);
    dataPlot(k, 3) = (*q)(1);
    dataPlot(k, 4) = (*vel)(1);
    dataPlot(k, 5) = (*q)(2);
    dataPlot(k, 6) = (*vel)(2);
    dataPlot(k, 7) = (*y)(0);
    dataPlot(k, 8) = (*y)(1);

    // --- Time loop ---
    cout << "Start computation ... " << endl;
    boost::timer boostTimer;
    boostTimer.restart();

    while (s->nextTime() < T)
    {
      // get current time step
      k++;
      s->newtonSolve(criterion, maxIter);
      dataPlot(k, 0) =  s->nextTime();
      dataPlot(k, 1) = (*q)(0);
      dataPlot(k, 2) = (*vel)(0);
      dataPlot(k, 3) = (*q)(1);
      dataPlot(k, 4) = (*vel)(1);
      dataPlot(k, 5) = (*q)(2);
      dataPlot(k, 6) = (*vel)(2);
      dataPlot(k, 7) = (*y)(0);
      dataPlot(k, 8) = (*y)(1);
      s->nextStep();
    }

    cout << "End of computation - Number of iterations done: " << k << endl;
    cout << "Computation Time: " << boostTimer.elapsed()  << endl;

    cout << endl << "Output writing ..." << endl;
    // --- Output files ---
    ioMatrix out("result.dat", "ascii");
    out.write(dataPlot, "noDim");
  }

  catch (SiconosException e)
  {
    cout << e.report() << endl;
  }
  catch (...)
  {
    cout << "Exception caught in \'sample/MultiBeadsColumn\'" << endl;
  }
}
<commit_msg>without SiconosSet<commit_after>/* Siconos-sample version 3.0.0, Copyright INRIA 2005-2008.
 * Siconos is a program dedicated to modeling, simulation and control
 * of non smooth dynamical systems.
 * Siconos is a free software; you can redistribute it and/or modify
 * it 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.
 * Siconos 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 Siconos; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Contact: Vincent ACARY vincent.acary@inrialpes.fr
 */

// =============================== Robot arm sample (HuMAnsPa10) ===============================
//
// see modelRobot1.jpg for complete system view.
//
// Keywords: LagrangianDS, LagrangianLinear relation, Moreau TimeStepping, LCP.
//
// =============================================================================================

#include "SiconosKernel.hpp"

using namespace std;

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

    // ================= Creation of the model =======================

    // User-defined main parameters
    unsigned int nDof = 3;           // degrees of freedom for robot arm
    double t0 = 0;                   // initial computation time
    double T = 1.9;                   // final computation time
    double h = 0.005;                // time step
    double criterion = 0.0005;
    unsigned int maxIter = 20000;
    double e = 0.9;                  // restit. coef. for impact on the ground.
    double e2 = 0.0;                 // restit. coef for angular stops impacts.

    // -> mind to set the initial conditions below.

    // -------------------------
    // --- Dynamical systems ---
    // -------------------------

    // unsigned int i;
    // --- DS: robot arm ---

    // The dof are angles between ground and arm and between differents parts of the arm. (See Robot.fig for more details)
    //

    // Initial position (angles in radian)
    SP::SimpleVector q0(new SimpleVector(nDof)), v0(new SimpleVector(nDof));
    (*q0)(0) = 0.05;
    (*q0)(1) = 0.05;

    SP::LagrangianDS arm(new LagrangianDS(q0, v0));

    // external plug-in
    arm->setComputeMassFunction("RobotPlugin.so", "mass");
    arm->setComputeNNLFunction("RobotPlugin.so", "NNL");
    arm->setComputeJacobianNNLqDotFunction("RobotPlugin.so", "jacobianVNNL");
    arm->setComputeJacobianNNLqFunction("RobotPlugin.so", "jacobianNNLq");

    // -------------------
    // --- Interactions---
    // -------------------

    // Two interactions:
    //  - one with Lagrangian non linear relation to define contact with ground
    //  - the other to define angles limitations (articular stops), with lagrangian linear relation
    //  Both with newton impact ns laws.

    // -- relations --

    // => arm-floor relation
    SP::NonSmoothLaw nslaw(new NewtonImpactNSL(e));
    string G = "RobotPlugin:G2";
    SP::Relation relation(new LagrangianScleronomousR("RobotPlugin:h2", G));
    SP::Interaction inter(new Interaction(2, nslaw, relation, 0));

    // => angular stops

    //     SimpleMatrix H(6,3);
    //     SimpleVector b(6);
    //     H.zero();
    //     H(0,0) =-1;
    //     H(1,0) =1;
    //     H(2,1) =-1;
    //     H(3,1) =1;
    //     H(4,2) =-1;
    //     H(5,2) =1;

    //     b(0) = 1.7;
    //     b(1) = 1.7;
    //     b(2) = 0.3;
    //     b(3) = 0.3;
    //     b(4) = 3.14;
    //     b(5) = 3.14;
    double lim0 = 1.6;
    double lim1 = 3.1;  // -lim <= q[1] <= lim
    SP::SimpleMatrix H(new SimpleMatrix(4, 3));
    SP::SimpleVector b(new SimpleVector(4));
    H->zero();

    (*H)(0, 0) = -1;
    (*H)(1, 0) = 1;
    (*H)(2, 1) = -1;
    (*H)(3, 1) = 1;

    (*b)(0) = lim0;
    (*b)(1) = lim0;
    (*b)(2) = lim1;
    (*b)(3) = lim1;

    SP::NonSmoothLaw nslaw2(new NewtonImpactNSL(e2));
    SP::Relation relation2(new LagrangianLinearTIR(H, b));
    SP::Interaction inter2(new Interaction(4, nslaw2, relation2, 1));

    // -------------
    // --- Model ---
    // -------------

    SP::Model Robot(new Model(t0, T));

    // add the dynamical system in the non smooth dynamical system
    Robot->nonSmoothDynamicalSystem()->insertDynamicalSystem(arm);

    // link the interactions and the dynamical system
    Robot->nonSmoothDynamicalSystem()->link(inter, arm);
    Robot->nonSmoothDynamicalSystem()->link(inter2, arm);

    // ----------------
    // --- Simulation ---
    // ----------------

    // -- Time discretisation --
    SP::TimeDiscretisation t(new TimeDiscretisation(t0, h));

    SP::TimeStepping s(new TimeStepping(t));

    // -- OneStepIntegrators --
    SP::OneStepIntegrator OSI(new Moreau(arm, 0.500001));
    s->insertIntegrator(OSI);

    SP::OneStepNSProblem osnspb(new LCP("PGS"));

    osnspb->numericsSolverOptions()->iparam[0] = 30001;
    osnspb->numericsSolverOptions()->dparam[0] = 0.005;

    s->insertNonSmoothProblem(osnspb);

    cout << "=== End of model loading === " << endl;

    // =========================== End of model definition ===========================  dataPlot(k,7) = (*inter->y(0))(0);

    // ================================= Computation =================================

    // --- Simulation initialization ---
    Robot->initialize(s);
    cout << "End of model initialisation" << endl;

    int k = 0;
    int N = (int)((T - t0) / h) + 1;

    // --- Get the values to be plotted ---
    // -> saved in a matrix dataPlot
    unsigned int outputSize = 9;
    SimpleMatrix dataPlot(N + 1, outputSize);
    // For the initial time step:
    // time

    SP::SiconosVector q = arm->q();
    SP::SiconosVector vel = arm->velocity();
    SP::SiconosVector y = inter->y(0);

    dataPlot(k, 0) =  Robot->t0();
    dataPlot(k, 1) = (*q)(0);
    dataPlot(k, 2) = (*vel)(0);
    dataPlot(k, 3) = (*q)(1);
    dataPlot(k, 4) = (*vel)(1);
    dataPlot(k, 5) = (*q)(2);
    dataPlot(k, 6) = (*vel)(2);
    dataPlot(k, 7) = (*y)(0);
    dataPlot(k, 8) = (*y)(1);

    // --- Time loop ---
    cout << "Start computation ... " << endl;
    boost::timer boostTimer;
    boostTimer.restart();

    while (s->nextTime() < T)
    {
      // get current time step
      k++;
      s->newtonSolve(criterion, maxIter);
      dataPlot(k, 0) =  s->nextTime();
      dataPlot(k, 1) = (*q)(0);
      dataPlot(k, 2) = (*vel)(0);
      dataPlot(k, 3) = (*q)(1);
      dataPlot(k, 4) = (*vel)(1);
      dataPlot(k, 5) = (*q)(2);
      dataPlot(k, 6) = (*vel)(2);
      dataPlot(k, 7) = (*y)(0);
      dataPlot(k, 8) = (*y)(1);
      s->nextStep();
    }

    cout << "End of computation - Number of iterations done: " << k << endl;
    cout << "Computation Time: " << boostTimer.elapsed()  << endl;

    cout << endl << "Output writing ..." << endl;
    // --- Output files ---
    ioMatrix out("result.dat", "ascii");
    out.write(dataPlot, "noDim");
  }

  catch (SiconosException e)
  {
    cout << e.report() << endl;
  }
  catch (...)
  {
    cout << "Exception caught in \'sample/MultiBeadsColumn\'" << endl;
  }
}
<|endoftext|>


<commit_before>// Filename: lwoToEgg.cxx
// Created by:  drose (17Apr01)
//
////////////////////////////////////////////////////////////////////

#include "lwoToEgg.h"

#include <lwoToEggConverter.h>
#include <lwoHeader.h>
#include <lwoInputFile.h>

////////////////////////////////////////////////////////////////////
//     Function: LwoToEgg::Constructor
//       Access: Public
//  Description:
////////////////////////////////////////////////////////////////////
LwoToEgg::
LwoToEgg() :
  SomethingToEgg("MultiGen", ".lwo")
{
  add_units_options();
  add_normals_options();
  add_transform_options();

  set_program_description
    ("This program converts Lightwave Object (.lwo) files to egg.  Many "
     "rendering characteristics of Lightwave (like layered shaders, etc.) "
     "are not supported, but fundamental things like polygons and texture "
     "maps are.  This program is primarily designed to support files written "
     "by Lightwave version 6.x (LWO2 files), but it also has some limited "
     "support for version 5.x files (LWOB files).");

  redescribe_option
    ("cs",
     "Specify the coordinate system of the input " + _format_name +
     " file.  Normally, this is y-up-left.");

  redescribe_option
    ("ui",
     "Specify the units of the input Lightwave file.  By convention, "
     "this is assumed to be meters if it is unspecified.");

  _coordinate_system = CS_yup_left;
}

////////////////////////////////////////////////////////////////////
//     Function: LwoToEgg::run
//       Access: Public
//  Description:
////////////////////////////////////////////////////////////////////
void LwoToEgg::
run() {
  LwoInputFile in;

  nout << "Reading " << _input_filename << "\n";
  if (!in.open_read(_input_filename)) {
    nout << "Unable to open " << _input_filename << "\n";
    exit(1);
  }

  PT(IffChunk) chunk = in.get_chunk();
  if (chunk == (IffChunk *)NULL) {
    nout << "Unable to read " << _input_filename << "\n";
    exit(1);
  }

  if (!chunk->is_of_type(LwoHeader::get_class_type())) {
    nout << "File " << _input_filename << " is not a Lightwave Object file.\n";
    exit(1);
  }

  LwoHeader *header = DCAST(LwoHeader, chunk);
  if (!header->is_valid()) {
    nout << "File " << _input_filename
	 << " is not recognized as a Lightwave Object file.  "
	 << "Perhaps the version is too recent.\n";
    exit(1);
  }

  _data.set_coordinate_system(_coordinate_system);

  if (_input_units == DU_invalid) {
    _input_units = DU_meters;
  }

  LwoToEggConverter converter(_data);

  if (!converter.convert_lwo(header)) {
    nout << "Errors in conversion.\n";
    exit(1);
  }

  write_egg_file();
  nout << "\n";
}

int main(int argc, char *argv[]) {
  LwoToEgg prog;
  prog.parse_command_line(argc, argv);
  prog.run();
  return 0;
}
<commit_msg>*** empty log message ***<commit_after>// Filename: lwoToEgg.cxx
// Created by:  drose (17Apr01)
//
////////////////////////////////////////////////////////////////////

#include "lwoToEgg.h"

#include <lwoToEggConverter.h>
#include <lwoHeader.h>
#include <lwoInputFile.h>

////////////////////////////////////////////////////////////////////
//     Function: LwoToEgg::Constructor
//       Access: Public
//  Description:
////////////////////////////////////////////////////////////////////
LwoToEgg::
LwoToEgg() :
  SomethingToEgg("Lightwave", ".lwo")
{
  add_units_options();
  add_normals_options();
  add_transform_options();

  set_program_description
    ("This program converts Lightwave Object (.lwo) files to egg.  Many "
     "rendering characteristics of Lightwave (like layered shaders, etc.) "
     "are not supported, but fundamental things like polygons and texture "
     "maps are.  This program is primarily designed to support files written "
     "by Lightwave version 6.x (LWO2 files), but it also has some limited "
     "support for version 5.x files (LWOB files).");

  redescribe_option
    ("cs",
     "Specify the coordinate system of the input " + _format_name +
     " file.  Normally, this is y-up-left.");

  redescribe_option
    ("ui",
     "Specify the units of the input Lightwave file.  By convention, "
     "this is assumed to be meters if it is unspecified.");

  _coordinate_system = CS_yup_left;
}

////////////////////////////////////////////////////////////////////
//     Function: LwoToEgg::run
//       Access: Public
//  Description:
////////////////////////////////////////////////////////////////////
void LwoToEgg::
run() {
  LwoInputFile in;

  nout << "Reading " << _input_filename << "\n";
  if (!in.open_read(_input_filename)) {
    nout << "Unable to open " << _input_filename << "\n";
    exit(1);
  }

  PT(IffChunk) chunk = in.get_chunk();
  if (chunk == (IffChunk *)NULL) {
    nout << "Unable to read " << _input_filename << "\n";
    exit(1);
  }

  if (!chunk->is_of_type(LwoHeader::get_class_type())) {
    nout << "File " << _input_filename << " is not a Lightwave Object file.\n";
    exit(1);
  }

  LwoHeader *header = DCAST(LwoHeader, chunk);
  if (!header->is_valid()) {
    nout << "File " << _input_filename
	 << " is not recognized as a Lightwave Object file.  "
	 << "Perhaps the version is too recent.\n";
    exit(1);
  }

  _data.set_coordinate_system(_coordinate_system);

  if (_input_units == DU_invalid) {
    _input_units = DU_meters;
  }

  LwoToEggConverter converter(_data);

  if (!converter.convert_lwo(header)) {
    nout << "Errors in conversion.\n";
    exit(1);
  }

  write_egg_file();
  nout << "\n";
}

int main(int argc, char *argv[]) {
  LwoToEgg prog;
  prog.parse_command_line(argc, argv);
  prog.run();
  return 0;
}
<|endoftext|>


<commit_before>#include "ServerScoreSystem.h"
#include "PlayerScore.h"
#include "NetworkSynced.h"
#include "PacketType.h"
#include "UpdateClientStatsPacket.h"

#include <TcpServer.h>
#include <Packet.h>

ServerScoreSystem::ServerScoreSystem( TcpServer* p_server )
	: EntitySystem( SystemType::NetworkUpdateScoresSystem,
	2, ComponentType::NetworkSynced, ComponentType::PlayerScore )
{
	m_server = p_server;

	// Update interval time:
	m_updateTimer = m_updateTimerStartValue = 1.0f;
}

ServerScoreSystem::~ServerScoreSystem()
{
}

void ServerScoreSystem::processEntities( const vector<Entity*>& p_entities )
{
	m_updateTimer -= m_world->getDelta();

	if( m_updateTimer <= 0 )
	{
		m_updateTimer = m_updateTimerStartValue;

		for( unsigned int i=0; i<p_entities.size(); i++ )
		{
			NetworkSynced* netSync = static_cast<NetworkSynced*>(
				p_entities[i]->getComponent(ComponentType::NetworkSynced));

			PlayerScore* score = static_cast<PlayerScore*>(
				p_entities[i]->getComponent(ComponentType::PlayerScore));
			score->incrementScore( 1 );

			UpdateClientStatsPacket packet;
			packet.scores[i]			= score->getScore();
			packet.playerIdentities[i]	= netSync->getNetworkIdentity();

			m_server->broadcastPacket( packet.pack() );
		}
	}
}

void ServerScoreSystem::initialize()
{

}<commit_msg>fixed a small bug<commit_after>#include "ServerScoreSystem.h"
#include "PlayerScore.h"
#include "NetworkSynced.h"
#include "PacketType.h"
#include "UpdateClientStatsPacket.h"

#include <TcpServer.h>
#include <Packet.h>

ServerScoreSystem::ServerScoreSystem( TcpServer* p_server )
	: EntitySystem( SystemType::NetworkUpdateScoresSystem,
	2, ComponentType::NetworkSynced, ComponentType::PlayerScore )
{
	m_server = p_server;

	// Update interval time:
	m_updateTimer = m_updateTimerStartValue = 1.0f;
}

ServerScoreSystem::~ServerScoreSystem()
{
}

void ServerScoreSystem::processEntities( const vector<Entity*>& p_entities )
{
	m_updateTimer -= m_world->getDelta();

	if( m_updateTimer <= 0 )
	{
		m_updateTimer = m_updateTimerStartValue;

		for( unsigned int i=0; i<p_entities.size(); i++ )
		{
			NetworkSynced* netSync = static_cast<NetworkSynced*>(
				p_entities[i]->getComponent(ComponentType::NetworkSynced));

			PlayerScore* score = static_cast<PlayerScore*>(
				p_entities[i]->getComponent(ComponentType::PlayerScore));
			score->incrementScore( 1 );

			/*UpdateClientStatsPacket packet;
			packet.scores[i]			= score->getScore();
			packet.playerIdentities[i]	= netSync->getNetworkIdentity();

			m_server->broadcastPacket( packet.pack() );*/
		}
	}
}

void ServerScoreSystem::initialize()
{

}<|endoftext|>


<commit_before><commit_msg>Bugfix #47906: Make sure a char* is valid before accessing it.  To reflect the invalid state the debug output will say "***setSignatureState2( ? )" (or "***setEncryptionState2( ? )", resp.) so the bug can be found in case this fix was only removing the symptom but not the real bug.<commit_after><|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <sfx2/templateviewitem.hxx>

#include <basegfx/matrix/b2dhommatrixtools.hxx>
#include <basegfx/polygon/b2dpolygon.hxx>
#include <drawinglayer/attribute/fillgraphicattribute.hxx>
#include <drawinglayer/primitive2d/fillgraphicprimitive2d.hxx>
#include <drawinglayer/primitive2d/polygonprimitive2d.hxx>
#include <drawinglayer/primitive2d/polypolygonprimitive2d.hxx>
#include <drawinglayer/primitive2d/textlayoutdevice.hxx>
#include <drawinglayer/primitive2d/textprimitive2d.hxx>
#include <drawinglayer/processor2d/baseprocessor2d.hxx>
#include <vcl/button.hxx>
#include <vcl/graph.hxx>

#define SUBTITLE_SCALE_FACTOR 0.85

using namespace basegfx;
using namespace basegfx::tools;
using namespace drawinglayer::attribute;
using namespace drawinglayer::primitive2d;

TemplateViewItem::TemplateViewItem (ThumbnailView &rView)
    : ThumbnailViewItem(rView),
      mnRegionId(USHRT_MAX),
      mnDocId(USHRT_MAX)
{
}

TemplateViewItem::~TemplateViewItem ()
{
}

void TemplateViewItem::calculateItemsPosition(const long nThumbnailHeight, const long nDisplayHeight,
                                              const long nPadding, sal_uInt32 nMaxTextLenght,
                                              const ThumbnailItemAttributes *pAttrs)
{
    ThumbnailViewItem::calculateItemsPosition(nThumbnailHeight,nDisplayHeight,nPadding,nMaxTextLenght, pAttrs);

    if (!maSubTitle.isEmpty())
    {
        Size aRectSize = maDrawArea.GetSize();

        drawinglayer::primitive2d::TextLayouterDevice aTextDev;
        aTextDev.setFontAttribute(pAttrs->aFontAttr,
                                  pAttrs->aFontSize.getX(), pAttrs->aFontSize.getY(),
                                  com::sun::star::lang::Locale() );

        long nSpace = (nDisplayHeight + nPadding - 2*aTextDev.getTextHeight()) / 3;

        // Set subtitle position
        maSubTitlePos.setY(maTextPos.getY() + nSpace + aTextDev.getTextHeight());
        maSubTitlePos.setX(maDrawArea.Left() +
                           (aRectSize.Width() - aTextDev.getTextWidth(maSubTitle,0,nMaxTextLenght)*SUBTITLE_SCALE_FACTOR)/2);
    }
}

void TemplateViewItem::Paint(drawinglayer::processor2d::BaseProcessor2D *pProcessor,
                                   const ThumbnailItemAttributes *pAttrs)
{
    BColor aFillColor = pAttrs->aFillColor;

    int nCount = maSubTitle.isEmpty() ? 5 : 6;
    drawinglayer::primitive2d::Primitive2DSequence aSeq(nCount);

    // Draw background
    if ( mbSelected || mbHover )
        aFillColor = pAttrs->aHighlightColor;

    aSeq[0] = Primitive2DReference( new PolyPolygonColorPrimitive2D(
                                               B2DPolyPolygon(Polygon(maDrawArea,5,5).getB2DPolygon()),
                                               aFillColor));

    // Draw thumbnail
    Size aImageSize = maPreview1.GetSizePixel();

    float fWidth = aImageSize.Width();
    float fHeight = aImageSize.Height();
    float fPosX = maPrev1Pos.getX();
    float fPosY = maPrev1Pos.getY();

    B2DPolygon aBounds;
    aBounds.append(B2DPoint(fPosX,fPosY));
    aBounds.append(B2DPoint(fPosX+fWidth,fPosY));
    aBounds.append(B2DPoint(fPosX+fWidth,fPosY+fHeight));
    aBounds.append(B2DPoint(fPosX,fPosY+fHeight));
    aBounds.setClosed(true);

    aSeq[1] = Primitive2DReference( new PolyPolygonColorPrimitive2D(
                                        B2DPolyPolygon(aBounds), Color(COL_WHITE).getBColor()));

    aSeq[2] = Primitive2DReference( new FillGraphicPrimitive2D(
                                        createTranslateB2DHomMatrix(maPrev1Pos.X(),maPrev1Pos.Y()),
                                        FillGraphicAttribute(Graphic(maPreview1),
                                                            B2DRange(
                                                                B2DPoint(0,0),
                                                                B2DPoint(aImageSize.Width(),aImageSize.Height())),
                                                            false)
                                        ));

    // draw thumbnail borders
    aSeq[3] = Primitive2DReference(createBorderLine(aBounds));

    addTextPrimitives(maTitle, pAttrs, maTextPos, aSeq);

    if (!maSubTitle.isEmpty())
    {
        addTextPrimitives(maSubTitle, pAttrs, maSubTitlePos, aSeq);
    }

    pProcessor->process(aSeq);
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */

<commit_msg>Primitive2DReference : ambiguous symbol<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <sfx2/templateviewitem.hxx>

#include <basegfx/matrix/b2dhommatrixtools.hxx>
#include <basegfx/polygon/b2dpolygon.hxx>
#include <drawinglayer/attribute/fillgraphicattribute.hxx>
#include <drawinglayer/primitive2d/fillgraphicprimitive2d.hxx>
#include <drawinglayer/primitive2d/polygonprimitive2d.hxx>
#include <drawinglayer/primitive2d/polypolygonprimitive2d.hxx>
#include <drawinglayer/primitive2d/textlayoutdevice.hxx>
#include <drawinglayer/primitive2d/textprimitive2d.hxx>
#include <drawinglayer/processor2d/baseprocessor2d.hxx>
#include <vcl/button.hxx>
#include <vcl/graph.hxx>

#define SUBTITLE_SCALE_FACTOR 0.85

using namespace basegfx;
using namespace basegfx::tools;
using namespace drawinglayer::attribute;
using namespace drawinglayer::primitive2d;

TemplateViewItem::TemplateViewItem (ThumbnailView &rView)
    : ThumbnailViewItem(rView),
      mnRegionId(USHRT_MAX),
      mnDocId(USHRT_MAX)
{
}

TemplateViewItem::~TemplateViewItem ()
{
}

void TemplateViewItem::calculateItemsPosition(const long nThumbnailHeight, const long nDisplayHeight,
                                              const long nPadding, sal_uInt32 nMaxTextLenght,
                                              const ThumbnailItemAttributes *pAttrs)
{
    ThumbnailViewItem::calculateItemsPosition(nThumbnailHeight,nDisplayHeight,nPadding,nMaxTextLenght, pAttrs);

    if (!maSubTitle.isEmpty())
    {
        Size aRectSize = maDrawArea.GetSize();

        drawinglayer::primitive2d::TextLayouterDevice aTextDev;
        aTextDev.setFontAttribute(pAttrs->aFontAttr,
                                  pAttrs->aFontSize.getX(), pAttrs->aFontSize.getY(),
                                  com::sun::star::lang::Locale() );

        long nSpace = (nDisplayHeight + nPadding - 2*aTextDev.getTextHeight()) / 3;

        // Set subtitle position
        maSubTitlePos.setY(maTextPos.getY() + nSpace + aTextDev.getTextHeight());
        maSubTitlePos.setX(maDrawArea.Left() +
                           (aRectSize.Width() - aTextDev.getTextWidth(maSubTitle,0,nMaxTextLenght)*SUBTITLE_SCALE_FACTOR)/2);
    }
}

void TemplateViewItem::Paint(drawinglayer::processor2d::BaseProcessor2D *pProcessor,
                                   const ThumbnailItemAttributes *pAttrs)
{
    BColor aFillColor = pAttrs->aFillColor;

    int nCount = maSubTitle.isEmpty() ? 5 : 6;
    drawinglayer::primitive2d::Primitive2DSequence aSeq(nCount);

    // Draw background
    if ( mbSelected || mbHover )
        aFillColor = pAttrs->aHighlightColor;

    aSeq[0] = drawinglayer::primitive2d::Primitive2DReference( new PolyPolygonColorPrimitive2D(
                                               B2DPolyPolygon(Polygon(maDrawArea,5,5).getB2DPolygon()),
                                               aFillColor));

    // Draw thumbnail
    Size aImageSize = maPreview1.GetSizePixel();

    float fWidth = aImageSize.Width();
    float fHeight = aImageSize.Height();
    float fPosX = maPrev1Pos.getX();
    float fPosY = maPrev1Pos.getY();

    B2DPolygon aBounds;
    aBounds.append(B2DPoint(fPosX,fPosY));
    aBounds.append(B2DPoint(fPosX+fWidth,fPosY));
    aBounds.append(B2DPoint(fPosX+fWidth,fPosY+fHeight));
    aBounds.append(B2DPoint(fPosX,fPosY+fHeight));
    aBounds.setClosed(true);

    aSeq[1] = Primitive2DReference( new PolyPolygonColorPrimitive2D(
                                        B2DPolyPolygon(aBounds), Color(COL_WHITE).getBColor()));

    aSeq[2] = Primitive2DReference( new FillGraphicPrimitive2D(
                                        createTranslateB2DHomMatrix(maPrev1Pos.X(),maPrev1Pos.Y()),
                                        FillGraphicAttribute(Graphic(maPreview1),
                                                            B2DRange(
                                                                B2DPoint(0,0),
                                                                B2DPoint(aImageSize.Width(),aImageSize.Height())),
                                                            false)
                                        ));

    // draw thumbnail borders
    aSeq[3] = Primitive2DReference(createBorderLine(aBounds));

    addTextPrimitives(maTitle, pAttrs, maTextPos, aSeq);

    if (!maSubTitle.isEmpty())
    {
        addTextPrimitives(maSubTitle, pAttrs, maSubTitlePos, aSeq);
    }

    pProcessor->process(aSeq);
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */

<|endoftext|>


<commit_before>// Copyright (C) 2007 Tim Moore timoore@redhat.com
//
// This program is free software; you can redistribute it and/or
// modify it 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 <osgDB/FileNameUtils>
#include <osgDB/Registry>

#include <simgear/scene/model/ModelRegistry.hxx>
#include <simgear/scene/util/SGReaderWriterOptions.hxx>

#include "SGReaderWriterBTG.hxx"
#include "obj.hxx"

using namespace simgear;

SGReaderWriterBTG::SGReaderWriterBTG()
{
    supportsExtension("btg", "SimGear btg database format");
    // supportsExtension("btg.gz", "SimGear btg database format");
}

SGReaderWriterBTG::~SGReaderWriterBTG()
{
}

const char* SGReaderWriterBTG::className() const
{
    return "BTG Database reader";
}

bool
SGReaderWriterBTG::acceptsExtension(const std::string& extension) const
{
    // trick the osg extensions match algorithm to accept btg.gz files.
    if (osgDB::convertToLowerCase(extension) == "gz")
        return true;
    return osgDB::ReaderWriter::acceptsExtension(extension);
}

osgDB::ReaderWriter::ReadResult
SGReaderWriterBTG::readNode(const std::string& fileName,
                            const osgDB::ReaderWriter::Options* options) const
{
    SGMaterialLib* matlib = 0;
    bool useRandomObjects = false;
    bool useRandomVegetation = false;
    const SGReaderWriterOptions* sgOptions;
    sgOptions = dynamic_cast<const SGReaderWriterOptions*>(options);
    if (sgOptions) {
        matlib = sgOptions->getMaterialLib();
        SGPropertyNode* propertyNode = sgOptions->getPropertyNode().get();
        if (propertyNode) {
            useRandomObjects
                = propertyNode->getBoolValue("/sim/rendering/random-objects",
                                             useRandomObjects);
            useRandomVegetation
                = propertyNode->getBoolValue("/sim/rendering/random-vegetation",
                                             useRandomVegetation);
        }
    }

    osg::Node* result = SGLoadBTG(fileName, matlib,
                                  useRandomObjects,
                                  useRandomVegetation);
    if (result)
        return result;
    else
        return ReadResult::FILE_NOT_HANDLED;
}

typedef ModelRegistryCallback<DefaultProcessPolicy, NoCachePolicy,
                              NoOptimizePolicy,
                              NoSubstitutePolicy, BuildGroupBVHPolicy>
BTGCallback;

namespace
{
ModelRegistryCallbackProxy<BTGCallback> g_btgCallbackProxy("btg");
}
<commit_msg>Fix MSVC build<commit_after>// Copyright (C) 2007 Tim Moore timoore@redhat.com
//
// This program is free software; you can redistribute it and/or
// modify it 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.
//

#ifdef HAVE_CONFIG_H
#  include <simgear_config.h>
#endif

#include <osgDB/FileNameUtils>
#include <osgDB/Registry>

#include <simgear/scene/model/ModelRegistry.hxx>
#include <simgear/scene/util/SGReaderWriterOptions.hxx>
#include <simgear/math/SGMath.hxx>

#include "SGReaderWriterBTG.hxx"
#include "obj.hxx"

using namespace simgear;

SGReaderWriterBTG::SGReaderWriterBTG()
{
    supportsExtension("btg", "SimGear btg database format");
    // supportsExtension("btg.gz", "SimGear btg database format");
}

SGReaderWriterBTG::~SGReaderWriterBTG()
{
}

const char* SGReaderWriterBTG::className() const
{
    return "BTG Database reader";
}

bool
SGReaderWriterBTG::acceptsExtension(const std::string& extension) const
{
    // trick the osg extensions match algorithm to accept btg.gz files.
    if (osgDB::convertToLowerCase(extension) == "gz")
        return true;
    return osgDB::ReaderWriter::acceptsExtension(extension);
}

osgDB::ReaderWriter::ReadResult
SGReaderWriterBTG::readNode(const std::string& fileName,
                            const osgDB::ReaderWriter::Options* options) const
{
    SGMaterialLib* matlib = 0;
    bool useRandomObjects = false;
    bool useRandomVegetation = false;
    const SGReaderWriterOptions* sgOptions;
    sgOptions = dynamic_cast<const SGReaderWriterOptions*>(options);
    if (sgOptions) {
        matlib = sgOptions->getMaterialLib();
        SGPropertyNode* propertyNode = sgOptions->getPropertyNode().get();
        if (propertyNode) {
            useRandomObjects
                = propertyNode->getBoolValue("/sim/rendering/random-objects",
                                             useRandomObjects);
            useRandomVegetation
                = propertyNode->getBoolValue("/sim/rendering/random-vegetation",
                                             useRandomVegetation);
        }
    }

    osg::Node* result = SGLoadBTG(fileName, matlib,
                                  useRandomObjects,
                                  useRandomVegetation);
    if (result)
        return result;
    else
        return ReadResult::FILE_NOT_HANDLED;
}

typedef ModelRegistryCallback<DefaultProcessPolicy, NoCachePolicy,
                              NoOptimizePolicy,
                              NoSubstitutePolicy, BuildGroupBVHPolicy>
BTGCallback;

namespace
{
ModelRegistryCallbackProxy<BTGCallback> g_btgCallbackProxy("btg");
}
<|endoftext|>


<commit_before>#ifndef SM_LOGGING_LEVELS_HPP
#define SM_LOGGING_LEVELS_HPP

// These allow you to compile-out everything below a certain severity level if necessary
#define SMCONSOLE_SEVERITY_ALL 0
#define SMCONSOLE_SEVERITY_FINEST 1
#define SMCONSOLE_SEVERITY_VERBOSE 2
#define SMCONSOLE_SEVERITY_FINER 3
#define SMCONSOLE_SEVERITY_TRACE 4
#define SMCONSOLE_SEVERITY_FINE 5
#define SMCONSOLE_SEVERITY_DEBUG 6
#define SMCONSOLE_SEVERITY_INFO 7
#define SMCONSOLE_SEVERITY_WARN 8
#define SMCONSOLE_SEVERITY_ERROR 9
#define SMCONSOLE_SEVERITY_FATAL 10
#define SMCONSOLE_SEVERITY_NONE 11

#include <string>

namespace sm {
    namespace logging {

        namespace levels
        {
            enum Level
            {
                All,
                Finest,
                Verbose,
                Finer,
                Trace,
                Fine,
                Debug,
                Info,
                Warn,
                Error,
                Fatal,

                Count
            };

            Level fromString(const std::string& level);

        }

        typedef levels::Level Level;

    } // namespace logging
} // namespace sm

#endif /* SM_LOGGING_LEVELS_HPP */
<commit_msg>Update Levels.hpp<commit_after>#ifndef SM_LOGGING_LEVELS_HPP
#define SM_LOGGING_LEVELS_HPP

// These allow you to compile-out everything below a certain severity level if necessary
#define SMCONSOLE_SEVERITY_ALL 0
#define SMCONSOLE_SEVERITY_FINEST 1
#define SMCONSOLE_SEVERITY_VERBOSE 2
#define SMCONSOLE_SEVERITY_FINER 3
#define SMCONSOLE_SEVERITY_TRACE 4
#define SMCONSOLE_SEVERITY_FINE 5
#define SMCONSOLE_SEVERITY_DEBUG 6
#define SMCONSOLE_SEVERITY_INFO 7
#define SMCONSOLE_SEVERITY_WARN 8
#define SMCONSOLE_SEVERITY_ERROR 9
#define SMCONSOLE_SEVERITY_FATAL 10
#define SMCONSOLE_SEVERITY_NONE 11

#include <string>

namespace sm {
    namespace logging {

        namespace levels
        {
            enum Level
            {
                All,
                Finest,
                Verbose,
                Finer,
                Trace,
                Fine,
                Debug,
                Info,
                Warn,
                Error,
                Fatal,

                Count
            };

            Level fromString(std::string level);

        }

        typedef levels::Level Level;

    } // namespace logging
} // namespace sm

#endif /* SM_LOGGING_LEVELS_HPP */
<|endoftext|>