<commit_before>#include "system/state.hh"
#include <iostream>
#include <fstream>
#include "common/array.hh"

using namespace divine;

namespace divine {

    class succ_container_t: public divine::array_t<state_t>
    {
    public:
	//!A constructor (only calls a constructor of array_t<state_t> with
	//! parameters 4096 (preallocation) and 16 (allocation step).
    succ_container_t(): array_t<state_t>(4096, 16) {}
	//!A destructor.
	~succ_container_t() {}
    };
};

// added interface functions
size_t      (*lib_get_state_variable_count)();
const char* (*lib_get_state_variable_name)(int var);
size_t      (*lib_get_state_variable_type_count)();
const char* (*lib_get_state_variable_type_name)(int type);
const int   (*lib_get_state_variable_type)(int var);
size_t      (*lib_get_state_variable_type_value_count)(int type);
const char* (*lib_get_state_variable_type_value)(int type, int value);
void        (*lib_project_state_to_int_array)(state_t state, int* proj);
void        (*lib_project_int_array_to_state)(int* proj, state_t state);
int*        (*lib_get_transition_proj)(int trans);
int         (*lib_get_transition_succ)(size_int_t transition, state_t state, succ_container_t & succ_container);
int         (*lib_get_transition_count)();
divine::state_t (*lib_new_state)();

// original interface functions
int         (*lib_get_succ)(state_t, succ_container_t &);
bool        (*lib_is_accepting)(state_t);
divine::state_t (*lib_get_initial_state)();
void        (*lib_print_state)(state_t, std::ostream & );
bool        (*lib_is_in_accepting_component)(state_t state);

extern "C" {

#include "runtime.h"
#include "dve-greybox.h"
#include "dm/dm.h"
#include "chunk_support.h"
#include <dlfcn.h>

static void dve_popt(poptContext con,
               enum poptCallbackReason reason,
                            const struct poptOption * opt,
                             const char * arg, void * data){
	(void)con;(void)opt;(void)arg;(void)data;
	switch(reason){
	case POPT_CALLBACK_REASON_PRE:
		break;
	case POPT_CALLBACK_REASON_POST:
        // TODO: add uncompiled extension, use divine to create dveC
		//GBregisterLoader("dve", DVEloadGreyboxModel);
		GBregisterLoader("dveC",DVEloadGreyboxModel);
		Warning(info,"Precompiled divine module initialized");
		return;
	case POPT_CALLBACK_REASON_OPTION:
		break;
	}
	Fatal(1,error,"unexpected call to dve_popt");
}

struct poptOption dve_options[]= {
	{ NULL, 0 , POPT_ARG_CALLBACK|POPT_CBFLAG_POST|POPT_CBFLAG_SKIPOPTION , (void*)&dve_popt, 0 , NULL , NULL },
	POPT_TABLEEND
};

typedef struct grey_box_context {
    int todo;
} *gb_context_t;

static void divine_get_initial_state(int* state)
{
    divine::state_t s = lib_get_initial_state();
    lib_project_state_to_int_array(s, state);
}

static lts_type_t ltstype;
static matrix_t dm_info;
static matrix_t sl_info;
static divine::succ_container_t cb_cont;

static int
succ_callback(TransitionCB cb, void* context)
{
    int result = cb_cont.size();
    for(size_t i=0; i < (size_t)result;++i)
    {
        int dst[lib_get_state_variable_count()];
        lib_project_state_to_int_array(cb_cont[i], dst);
        cb(context, NULL, dst);
    }
    cb_cont.clear();
    return result;
}

static int
divine_get_transitions_all(model_t self, int*src, TransitionCB cb, void*context)
{
    (void)self;
    divine::state_t s = lib_new_state();
    lib_project_int_array_to_state(src, s);
    lib_get_succ(s, cb_cont);
    return succ_callback(cb, context);
}

static int
divine_get_transitions_long(model_t self, int group, int*src, TransitionCB cb, void*context)
{
    (void)self;
    divine::state_t s = lib_new_state();
    lib_project_int_array_to_state(src, s);
    lib_get_transition_succ(group, s, cb_cont);
    return succ_callback(cb, context);
}

void DVEloadGreyboxModel(model_t model, const char *filename){
	gb_context_t ctx=(gb_context_t)RTmalloc(sizeof(struct grey_box_context));
	GBsetContext(model,ctx);

    // Open dveC file
    // TODO: call dlclose() somewhere?
    void *dlHandle = NULL;
    char* abs_filename = realpath(filename, NULL);
    if (abs_filename) {
        dlHandle = dlopen(abs_filename, RTLD_LAZY);
        free(abs_filename);
        if (dlHandle == NULL)
        {
            FatalCall (1, error, "%s, Library \"%s\" is not reachable", dlerror(), filename);
            return;
        }
    } else {
        FatalCall (1, error, "%s, Library \"%s\" is not found", dlerror(), filename);
    }

    // get functions
    lib_get_succ = (int(*)(divine::state_t, divine::succ_container_t &))
	dlsym( dlHandle, "lib_get_succ");
    lib_is_accepting = (bool(*)(divine::state_t))
	dlsym( dlHandle, "lib_is_accepting");
    lib_is_in_accepting_component = (bool(*)(divine::state_t))
	dlsym( dlHandle, "lib_is_in_accepting_component");
    lib_get_initial_state = (divine::state_t(*)())
	dlsym( dlHandle, "lib_get_initial_state");
    lib_print_state = (void(*)(divine::state_t, std::ostream &))
	dlsym( dlHandle, "lib_print_state");

    if (lib_get_succ == NULL || lib_is_accepting == NULL ||
        lib_is_in_accepting_component == NULL || lib_get_initial_state == NULL ||
        lib_print_state == NULL) {
        FatalCall (1, error, "Library \"%s\" doesn't export the required functions", filename);
    }

    // added interface functions
    lib_get_state_variable_count = (size_t (*)())
    dlsym( dlHandle, "lib_get_state_variable_count");
    lib_get_state_variable_name = (const char* (*)(int var))
    dlsym( dlHandle, "lib_get_state_variable_name" );
    lib_get_state_variable_type_count = (size_t (*)())
    dlsym( dlHandle, "lib_get_state_variable_type_count");
    lib_get_state_variable_type_name = (const char* (*)(int type))
    dlsym( dlHandle, "lib_get_state_variable_type_name");
    lib_get_state_variable_type  = (const int (*)(int var))
    dlsym( dlHandle, "lib_get_state_variable_type");
    lib_get_state_variable_type_value_count = (size_t (*)(int))
    dlsym( dlHandle, "lib_get_state_variable_type_value_count");
    lib_get_state_variable_type_value = (const char* (*)(int type, int value))
    dlsym( dlHandle, "lib_get_state_variable_type_value");
    lib_project_state_to_int_array = (void (*)(state_t state, int* proj))
    dlsym( dlHandle, "lib_project_state_to_int_array");
    lib_project_int_array_to_state = (void (*)(int* proj, state_t state))
    dlsym( dlHandle, "lib_project_int_array_to_state");
    lib_get_transition_proj = (int* (*)(int trans))
    dlsym( dlHandle, "lib_get_transition_proj");
    lib_get_transition_succ = (int (*)(size_int_t transition, state_t state, succ_container_t & succ_container))
    dlsym( dlHandle, "lib_get_transition_succ");
    lib_get_transition_count = (int (*)())
    dlsym( dlHandle, "lib_get_transition_count");
    lib_new_state = (divine::state_t (*)())
    dlsym( dlHandle, "lib_new_state");

    // test dveC file
    if (lib_get_state_variable_count == NULL || lib_get_state_variable_name == NULL ||
        lib_get_state_variable_type_count == NULL || lib_get_state_variable_type_name == NULL ||
        lib_get_state_variable_type == NULL || lib_get_state_variable_type_value_count == NULL ||
        lib_get_state_variable_type_value == NULL || lib_project_state_to_int_array == NULL ||
        lib_project_int_array_to_state == NULL || lib_get_transition_proj == NULL ||
        lib_get_transition_succ == NULL || lib_get_transition_count == NULL || lib_new_state == NULL) {
        FatalCall (1, error, "Library \"%s\" doesn't export the required functions", filename);
    }

    // get ltstypes
    int state_length = lib_get_state_variable_count();
    ltstype=lts_type_create();

    // adding types
    int ntypes = lib_get_state_variable_type_count();
    for(int i=0; i < ntypes; i++) {
        const char* type_name = lib_get_state_variable_type_name(i);
        if (lts_type_add_type(ltstype,type_name,NULL) != i) {
            Fatal(1,error,"wrong type number");
        }
    }

    lts_type_set_state_length(ltstype, state_length);

    // set state name & type
    for(int i=0; i < state_length; ++i)
    {
        const char* name = lib_get_state_variable_name(i);
        const int   type = lib_get_state_variable_type(i);
        lts_type_set_state_name(ltstype,i,name);
        lts_type_set_state_typeno(ltstype,i,type);
    }

    GBsetLTStype(model, ltstype);

    // setting values for types
    // chunk_str doesn't work
    for(int i=0; i < ntypes; i++) {
        int type_value_count = lib_get_state_variable_type_value_count(i);
        if (type_value_count > 0) {
            for(int j=0; j < type_value_count; ++j) {
                const char* type_value = lib_get_state_variable_type_value(i, j);
                GBchunkPut(model, i, (chunk){strlen(type_value),(char*)type_value});
            }
        }
    }
    lts_type_validate(ltstype);

    int ngroups = lib_get_transition_count();
	dm_create(&dm_info, ngroups, state_length);
    for(int i=0; i < dm_nrows(&dm_info); i++) {
        int* proj = lib_get_transition_proj(i);
		for(int j=0; j<state_length; j++) {
            if (proj[j]) dm_set(&dm_info, i, j);
        }
    }
	GBsetDMInfo(model, &dm_info);

    // there are no state labels
    dm_create(&sl_info, 0, state_length);
    GBsetStateLabelInfo(model, &sl_info);

    // get initial state
	int state[state_length];
    divine_get_initial_state(state);
	GBsetInitialState(model,state);

    GBsetNextStateAll  (model, divine_get_transitions_all);
    GBsetNextStateLong (model, divine_get_transitions_long);
}

} // extern "C"
<commit_msg>Added dummy label to make --cache work<commit_after>#include "system/state.hh"
#include <iostream>
#include <fstream>
#include "common/array.hh"

using namespace divine;

namespace divine {

    class succ_container_t: public divine::array_t<state_t>
    {
    public:
	//!A constructor (only calls a constructor of array_t<state_t> with
	//! parameters 4096 (preallocation) and 16 (allocation step).
    succ_container_t(): array_t<state_t>(4096, 16) {}
	//!A destructor.
	~succ_container_t() {}
    };
};

// added interface functions
size_t      (*lib_get_state_variable_count)();
const char* (*lib_get_state_variable_name)(int var);
size_t      (*lib_get_state_variable_type_count)();
const char* (*lib_get_state_variable_type_name)(int type);
const int   (*lib_get_state_variable_type)(int var);
size_t      (*lib_get_state_variable_type_value_count)(int type);
const char* (*lib_get_state_variable_type_value)(int type, int value);
void        (*lib_project_state_to_int_array)(state_t state, int* proj);
void        (*lib_project_int_array_to_state)(int* proj, state_t state);
int*        (*lib_get_transition_proj)(int trans);
int         (*lib_get_transition_succ)(size_int_t transition, state_t state, succ_container_t & succ_container);
int         (*lib_get_transition_count)();
divine::state_t (*lib_new_state)();

// original interface functions
int         (*lib_get_succ)(state_t, succ_container_t &);
bool        (*lib_is_accepting)(state_t);
divine::state_t (*lib_get_initial_state)();
void        (*lib_print_state)(state_t, std::ostream & );
bool        (*lib_is_in_accepting_component)(state_t state);

extern "C" {

#include "runtime.h"
#include "dve-greybox.h"
#include "dm/dm.h"
#include "chunk_support.h"
#include <dlfcn.h>

static void dve_popt(poptContext con,
               enum poptCallbackReason reason,
                            const struct poptOption * opt,
                             const char * arg, void * data){
	(void)con;(void)opt;(void)arg;(void)data;
	switch(reason){
	case POPT_CALLBACK_REASON_PRE:
		break;
	case POPT_CALLBACK_REASON_POST:
        // TODO: add uncompiled extension, use divine to create dveC
		//GBregisterLoader("dve", DVEloadGreyboxModel);
		GBregisterLoader("dveC",DVEloadGreyboxModel);
		Warning(info,"Precompiled divine module initialized");
		return;
	case POPT_CALLBACK_REASON_OPTION:
		break;
	}
	Fatal(1,error,"unexpected call to dve_popt");
}

struct poptOption dve_options[]= {
	{ NULL, 0 , POPT_ARG_CALLBACK|POPT_CBFLAG_POST|POPT_CBFLAG_SKIPOPTION , (void*)&dve_popt, 0 , NULL , NULL },
	POPT_TABLEEND
};

typedef struct grey_box_context {
    int todo;
} *gb_context_t;

static void divine_get_initial_state(int* state)
{
    divine::state_t s = lib_get_initial_state();
    lib_project_state_to_int_array(s, state);
}

static lts_type_t ltstype;
static matrix_t dm_info;
static matrix_t sl_info;
static divine::succ_container_t cb_cont;

static int
succ_callback(TransitionCB cb, void* context)
{
    int dummy = 42; // dummy to work with --cache
    int result = cb_cont.size();
    for(size_t i=0; i < (size_t)result;++i)
    {
        int dst[lib_get_state_variable_count()];
        lib_project_state_to_int_array(cb_cont[i], dst);
        cb(context, &dummy, dst);
    }
    cb_cont.clear();
    return result;
}

static int
divine_get_transitions_all(model_t self, int*src, TransitionCB cb, void*context)
{
    (void)self;
    divine::state_t s = lib_new_state();
    lib_project_int_array_to_state(src, s);
    lib_get_succ(s, cb_cont);
    return succ_callback(cb, context);
}

static int
divine_get_transitions_long(model_t self, int group, int*src, TransitionCB cb, void*context)
{
    (void)self;
    divine::state_t s = lib_new_state();
    lib_project_int_array_to_state(src, s);
    lib_get_transition_succ(group, s, cb_cont);
    return succ_callback(cb, context);
}

void DVEloadGreyboxModel(model_t model, const char *filename){
	gb_context_t ctx=(gb_context_t)RTmalloc(sizeof(struct grey_box_context));
	GBsetContext(model,ctx);

    // Open dveC file
    // TODO: call dlclose() somewhere?
    void *dlHandle = NULL;
    char* abs_filename = realpath(filename, NULL);
    if (abs_filename) {
        dlHandle = dlopen(abs_filename, RTLD_LAZY);
        free(abs_filename);
        if (dlHandle == NULL)
        {
            FatalCall (1, error, "%s, Library \"%s\" is not reachable", dlerror(), filename);
            return;
        }
    } else {
        FatalCall (1, error, "%s, Library \"%s\" is not found", dlerror(), filename);
    }

    // get functions
    lib_get_succ = (int(*)(divine::state_t, divine::succ_container_t &))
	dlsym( dlHandle, "lib_get_succ");
    lib_is_accepting = (bool(*)(divine::state_t))
	dlsym( dlHandle, "lib_is_accepting");
    lib_is_in_accepting_component = (bool(*)(divine::state_t))
	dlsym( dlHandle, "lib_is_in_accepting_component");
    lib_get_initial_state = (divine::state_t(*)())
	dlsym( dlHandle, "lib_get_initial_state");
    lib_print_state = (void(*)(divine::state_t, std::ostream &))
	dlsym( dlHandle, "lib_print_state");

    if (lib_get_succ == NULL || lib_is_accepting == NULL ||
        lib_is_in_accepting_component == NULL || lib_get_initial_state == NULL ||
        lib_print_state == NULL) {
        FatalCall (1, error, "Library \"%s\" doesn't export the required functions", filename);
    }

    // added interface functions
    lib_get_state_variable_count = (size_t (*)())
    dlsym( dlHandle, "lib_get_state_variable_count");
    lib_get_state_variable_name = (const char* (*)(int var))
    dlsym( dlHandle, "lib_get_state_variable_name" );
    lib_get_state_variable_type_count = (size_t (*)())
    dlsym( dlHandle, "lib_get_state_variable_type_count");
    lib_get_state_variable_type_name = (const char* (*)(int type))
    dlsym( dlHandle, "lib_get_state_variable_type_name");
    lib_get_state_variable_type  = (const int (*)(int var))
    dlsym( dlHandle, "lib_get_state_variable_type");
    lib_get_state_variable_type_value_count = (size_t (*)(int))
    dlsym( dlHandle, "lib_get_state_variable_type_value_count");
    lib_get_state_variable_type_value = (const char* (*)(int type, int value))
    dlsym( dlHandle, "lib_get_state_variable_type_value");
    lib_project_state_to_int_array = (void (*)(state_t state, int* proj))
    dlsym( dlHandle, "lib_project_state_to_int_array");
    lib_project_int_array_to_state = (void (*)(int* proj, state_t state))
    dlsym( dlHandle, "lib_project_int_array_to_state");
    lib_get_transition_proj = (int* (*)(int trans))
    dlsym( dlHandle, "lib_get_transition_proj");
    lib_get_transition_succ = (int (*)(size_int_t transition, state_t state, succ_container_t & succ_container))
    dlsym( dlHandle, "lib_get_transition_succ");
    lib_get_transition_count = (int (*)())
    dlsym( dlHandle, "lib_get_transition_count");
    lib_new_state = (divine::state_t (*)())
    dlsym( dlHandle, "lib_new_state");

    // test dveC file
    if (lib_get_state_variable_count == NULL || lib_get_state_variable_name == NULL ||
        lib_get_state_variable_type_count == NULL || lib_get_state_variable_type_name == NULL ||
        lib_get_state_variable_type == NULL || lib_get_state_variable_type_value_count == NULL ||
        lib_get_state_variable_type_value == NULL || lib_project_state_to_int_array == NULL ||
        lib_project_int_array_to_state == NULL || lib_get_transition_proj == NULL ||
        lib_get_transition_succ == NULL || lib_get_transition_count == NULL || lib_new_state == NULL) {
        FatalCall (1, error, "Library \"%s\" doesn't export the required functions", filename);
    }

    // get ltstypes
    int state_length = lib_get_state_variable_count();
    ltstype=lts_type_create();

    // adding types
    int ntypes = lib_get_state_variable_type_count();
    for(int i=0; i < ntypes; i++) {
        const char* type_name = lib_get_state_variable_type_name(i);
        if (lts_type_add_type(ltstype,type_name,NULL) != i) {
            Fatal(1,error,"wrong type number");
        }
    }

    lts_type_set_state_length(ltstype, state_length);

    // set state name & type
    for(int i=0; i < state_length; ++i)
    {
        const char* name = lib_get_state_variable_name(i);
        const int   type = lib_get_state_variable_type(i);
        lts_type_set_state_name(ltstype,i,name);
        lts_type_set_state_typeno(ltstype,i,type);
    }

    GBsetLTStype(model, ltstype);

    // setting values for types
    // chunk_str doesn't work
    for(int i=0; i < ntypes; i++) {
        int type_value_count = lib_get_state_variable_type_value_count(i);
        if (type_value_count > 0) {
            for(int j=0; j < type_value_count; ++j) {
                const char* type_value = lib_get_state_variable_type_value(i, j);
                GBchunkPut(model, i, (chunk){strlen(type_value),(char*)type_value});
            }
        }
    }
    lts_type_validate(ltstype);

    int ngroups = lib_get_transition_count();
	dm_create(&dm_info, ngroups, state_length);
    for(int i=0; i < dm_nrows(&dm_info); i++) {
        int* proj = lib_get_transition_proj(i);
		for(int j=0; j<state_length; j++) {
            if (proj[j]) dm_set(&dm_info, i, j);
        }
    }
	GBsetDMInfo(model, &dm_info);

    // there are no state labels
    dm_create(&sl_info, 0, state_length);
    GBsetStateLabelInfo(model, &sl_info);

    // get initial state
	int state[state_length];
    divine_get_initial_state(state);
	GBsetInitialState(model,state);

    GBsetNextStateAll  (model, divine_get_transitions_all);
    GBsetNextStateLong (model, divine_get_transitions_long);
}

} // extern "C"
<|endoftext|>


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

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

#include "world.hpp"
#include "shader.hpp"

extern GLFWwindow* window; // The "extern" keyword here is to access the variable "window" declared in tutorialXXX.cpp. This is a hack to keep the tutorials simple. Please avoid this.

namespace model
{
    World::World()
    {
        // constructor.
    }

    World::~World()
    {
        // destructor.
        std::cout << "This world will be destroyed.\n";

        // destroy all shaders of this world.
        std::cout << "All shaders of this world will be destroyed.\n";
        model::delete_children<model::Shader*>(this->shader_pointer_vector);
    }

    void World::render()
    {
        this->compute_matrices_from_inputs();

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

    void World::set_shader_pointer(GLuint childID, void* parent_pointer)
    {
        set_child_pointer(childID, parent_pointer, this->shader_pointer_vector, this->free_shaderID_queue);
    }

    void World::set_world_species_pointer(void* world_species_pointer)
    {
        this->world_species_pointer = world_species_pointer;
    }

    void World::compute_matrices_from_inputs()
    {
        // glfwGetTime is called only once, the first time this function is called
        static double lastTime = glfwGetTime();

        // Compute time difference between current and last frame
        double currentTime = glfwGetTime();
        float deltaTime = float(currentTime - lastTime);

        // Get mouse position
        double xpos, ypos;
        glfwGetCursorPos(window, &xpos, &ypos);

        // Reset mouse position for next frame
        glfwSetCursorPos(window, WINDOW_WIDTH/2, WINDOW_HEIGHT/2);

        if (hasMouseEverMoved || (abs(xpos) > 0.0001) || (abs(ypos) > 0.0001))
        {
            hasMouseEverMoved = true;

            // Compute new orientation
            horizontalAngle += mouseSpeed * GLfloat(WINDOW_WIDTH/2 - xpos);
            horizontalAngle = remainder(horizontalAngle, (2.0f * PI));

            if (is_invert_mouse_in_use)
            {
                // invert mouse.
                verticalAngle   -= mouseSpeed * GLfloat(WINDOW_HEIGHT/2 - ypos);
            }
            else
            {
                // don't invert mouse.
                verticalAngle   += mouseSpeed * GLfloat(WINDOW_HEIGHT/2 - ypos);
            }
            verticalAngle = remainder(verticalAngle, (2.0f * PI));
        }

        // Direction : Spherical coordinates to Cartesian coordinates conversion
        glm::vec3 direction(
                cos(verticalAngle) * sin(horizontalAngle),
                sin(verticalAngle),
                cos(verticalAngle) * cos(horizontalAngle)
                );

        // Right vector
        glm::vec3 right = glm::vec3(
                sin(horizontalAngle - PI/2.0f),
                0,
                cos(horizontalAngle - PI/2.0f)
                );

        // Up vector
        glm::vec3 up = glm::cross(right, direction);

        GLfloat temp_speed;

        // Turbo.
        if ((glfwGetKey(window, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS) && (glfwGetKey(window, GLFW_KEY_RIGHT_CONTROL) == GLFW_PRESS))
        {
            temp_speed = twin_turbo_factor * speed;
        }
        else if ((glfwGetKey(window, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS) || (glfwGetKey(window, GLFW_KEY_RIGHT_CONTROL) == GLFW_PRESS))
        {
            temp_speed = turbo_factor * speed;
        }
        else
        {
            temp_speed = speed;
        }

        // Move forward
        if (glfwGetKey(window, GLFW_KEY_UP) == GLFW_PRESS)
        {
            position += direction * deltaTime * temp_speed;
        }
        // Move backward
        if (glfwGetKey(window, GLFW_KEY_DOWN) == GLFW_PRESS)
        {
            position -= direction * deltaTime * temp_speed;
        }
        // Strafe right
        if (glfwGetKey(window, GLFW_KEY_RIGHT) == GLFW_PRESS)
        {
            position += right * deltaTime * temp_speed;
        }
        // Strafe left
        if (glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_PRESS)
        {
            position -= right * deltaTime * temp_speed;
        }

        // Move up.
        if (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS)
        {
            position.y += deltaTime * temp_speed;
        }

        // Move down.
        if (glfwGetKey(window, GLFW_KEY_ENTER) == GLFW_PRESS)
        {
            position.y -= deltaTime * temp_speed;
        }

        // Move west.
        if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
        {
            position.x -= deltaTime * temp_speed;
        }

        // Move east.
        if (glfwGetKey(window, GLFW_KEY_E) == GLFW_PRESS)
        {
            position.x += deltaTime * temp_speed;
        }

        // Move north.
        if (glfwGetKey(window, GLFW_KEY_N) == GLFW_PRESS)
        {
            position.z -= deltaTime * temp_speed;
        }

        // Move south.
        if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
        {
            position.z += deltaTime * temp_speed;
        }

        // Flight mode on.
        if (glfwGetKey(window, GLFW_KEY_F) == GLFW_PRESS)
        {
            fallSpeed = 0.0f;
            inFlightmode = true;
        }

        // Run mode on.
        if (glfwGetKey(window, GLFW_KEY_R) == GLFW_PRESS)
        {
            fallSpeed = 0.0f;
            inFlightmode = false;
        }

        if (!inFlightmode)
        {
            fallSpeed += gravity;
            position.y -= fallSpeed;
        }

        GLfloat FoV = initialFoV;// - 5 * glfwGetMouseWheel(); // Now GLFW 3 requires setting up a callback for this. It's a bit too complicated for this beginner's tutorial, so it's disabled instead.

        if (glfwGetKey(window, GLFW_KEY_I) == GLFW_PRESS)
        {
            if (is_key_I_released)
            {
                if (is_invert_mouse_in_use)
                {
                    is_invert_mouse_in_use = false;
                }
                else
                {
                    is_invert_mouse_in_use = true;
                }
            }
        }
        else
        {
            is_key_I_released = true;
        }

        // adjust position according to the ground.
        if (!inFlightmode)
        {
            if (this->world_species_pointer != NULL)
            {
                GLfloat ground_y = model::get_floor_level(static_cast<model::Species*>(this->world_species_pointer), position);

                if (!std::isnan(ground_y))
                {
                    if (position.y < ground_y)
                    {
                        position.y = ground_y;
                        fallSpeed = 0.0f;
                    }
                }
            }
        }

#ifdef TESTING_SPHERICAL_WORLD_IN_USE
        // compute spherical coordinates.
        spherical_position.rho = sqrt((position.x * position.x) + (position.y * position.y) + (position.z * position.z));
        spherical_position.theta = RADIANS_TO_DEGREES(atan2(sqrt((position.x * position.x) + (position.y * position.y)), position.z));
        spherical_position.phi = RADIANS_TO_DEGREES(atan2(position.y, position.x));
#endif

        earth_radius = EARTH_RADIUS;

        camera_position = position;
        camera_position.y += 2.0f;

        // Projection matrix : 45° Field of View, aspect ratio, display range : 0.1 unit <-> 100 units
        ProjectionMatrix = glm::perspective(FoV, ASPECT_RATIO, 0.001f, 5000.0f + 2.0f * (GLfloat) earth_radius);
        // Camera matrix
        ViewMatrix = glm::lookAt(
                camera_position,           // Camera is here
                camera_position+direction, // and looks here : at the same position, plus "direction"
                up                         // Head is up (set to 0,-1,0 to look upside-down)
                );

        // For the next frame, the "last time" will be "now"
        lastTime = currentTime;
    }
}
<commit_msg>Bugikorjaus: Invert mouse toimii nyt oikein.<commit_after>#ifndef PI
#define PI 3.14159265359f
#endif

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

#include "world.hpp"
#include "shader.hpp"

extern GLFWwindow* window; // The "extern" keyword here is to access the variable "window" declared in tutorialXXX.cpp. This is a hack to keep the tutorials simple. Please avoid this.

namespace model
{
    World::World()
    {
        // constructor.
    }

    World::~World()
    {
        // destructor.
        std::cout << "This world will be destroyed.\n";

        // destroy all shaders of this world.
        std::cout << "All shaders of this world will be destroyed.\n";
        model::delete_children<model::Shader*>(this->shader_pointer_vector);
    }

    void World::render()
    {
        this->compute_matrices_from_inputs();

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

    void World::set_shader_pointer(GLuint childID, void* parent_pointer)
    {
        set_child_pointer(childID, parent_pointer, this->shader_pointer_vector, this->free_shaderID_queue);
    }

    void World::set_world_species_pointer(void* world_species_pointer)
    {
        this->world_species_pointer = world_species_pointer;
    }

    void World::compute_matrices_from_inputs()
    {
        // glfwGetTime is called only once, the first time this function is called
        static double lastTime = glfwGetTime();

        // Compute time difference between current and last frame
        double currentTime = glfwGetTime();
        float deltaTime = float(currentTime - lastTime);

        // Get mouse position
        double xpos, ypos;
        glfwGetCursorPos(window, &xpos, &ypos);

        // Reset mouse position for next frame
        glfwSetCursorPos(window, WINDOW_WIDTH/2, WINDOW_HEIGHT/2);

        if (hasMouseEverMoved || (abs(xpos) > 0.0001) || (abs(ypos) > 0.0001))
        {
            hasMouseEverMoved = true;

            // Compute new orientation
            horizontalAngle += mouseSpeed * GLfloat(WINDOW_WIDTH/2 - xpos);
            horizontalAngle = remainder(horizontalAngle, (2.0f * PI));

            if (is_invert_mouse_in_use)
            {
                // invert mouse.
                verticalAngle   -= mouseSpeed * GLfloat(WINDOW_HEIGHT/2 - ypos);
            }
            else
            {
                // don't invert mouse.
                verticalAngle   += mouseSpeed * GLfloat(WINDOW_HEIGHT/2 - ypos);
            }
            verticalAngle = remainder(verticalAngle, (2.0f * PI));
        }

        // Direction : Spherical coordinates to Cartesian coordinates conversion
        glm::vec3 direction(
                cos(verticalAngle) * sin(horizontalAngle),
                sin(verticalAngle),
                cos(verticalAngle) * cos(horizontalAngle)
                );

        // Right vector
        glm::vec3 right = glm::vec3(
                sin(horizontalAngle - PI/2.0f),
                0,
                cos(horizontalAngle - PI/2.0f)
                );

        // Up vector
        glm::vec3 up = glm::cross(right, direction);

        GLfloat temp_speed;

        // Turbo.
        if ((glfwGetKey(window, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS) && (glfwGetKey(window, GLFW_KEY_RIGHT_CONTROL) == GLFW_PRESS))
        {
            temp_speed = twin_turbo_factor * speed;
        }
        else if ((glfwGetKey(window, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS) || (glfwGetKey(window, GLFW_KEY_RIGHT_CONTROL) == GLFW_PRESS))
        {
            temp_speed = turbo_factor * speed;
        }
        else
        {
            temp_speed = speed;
        }

        // Move forward
        if (glfwGetKey(window, GLFW_KEY_UP) == GLFW_PRESS)
        {
            position += direction * deltaTime * temp_speed;
        }
        // Move backward
        if (glfwGetKey(window, GLFW_KEY_DOWN) == GLFW_PRESS)
        {
            position -= direction * deltaTime * temp_speed;
        }
        // Strafe right
        if (glfwGetKey(window, GLFW_KEY_RIGHT) == GLFW_PRESS)
        {
            position += right * deltaTime * temp_speed;
        }
        // Strafe left
        if (glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_PRESS)
        {
            position -= right * deltaTime * temp_speed;
        }

        // Move up.
        if (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS)
        {
            position.y += deltaTime * temp_speed;
        }

        // Move down.
        if (glfwGetKey(window, GLFW_KEY_ENTER) == GLFW_PRESS)
        {
            position.y -= deltaTime * temp_speed;
        }

        // Move west.
        if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
        {
            position.x -= deltaTime * temp_speed;
        }

        // Move east.
        if (glfwGetKey(window, GLFW_KEY_E) == GLFW_PRESS)
        {
            position.x += deltaTime * temp_speed;
        }

        // Move north.
        if (glfwGetKey(window, GLFW_KEY_N) == GLFW_PRESS)
        {
            position.z -= deltaTime * temp_speed;
        }

        // Move south.
        if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
        {
            position.z += deltaTime * temp_speed;
        }

        // Flight mode on.
        if (glfwGetKey(window, GLFW_KEY_F) == GLFW_PRESS)
        {
            fallSpeed = 0.0f;
            inFlightmode = true;
        }

        // Run mode on.
        if (glfwGetKey(window, GLFW_KEY_R) == GLFW_PRESS)
        {
            fallSpeed = 0.0f;
            inFlightmode = false;
        }

        if (!inFlightmode)
        {
            fallSpeed += gravity;
            position.y -= fallSpeed;
        }

        GLfloat FoV = initialFoV;// - 5 * glfwGetMouseWheel(); // Now GLFW 3 requires setting up a callback for this. It's a bit too complicated for this beginner's tutorial, so it's disabled instead.

        if (glfwGetKey(window, GLFW_KEY_I) == GLFW_PRESS)
        {
            if (is_key_I_released)
            {
                if (is_invert_mouse_in_use)
                {
                    is_invert_mouse_in_use = false;
                }
                else
                {
                    is_invert_mouse_in_use = true;
                }
                is_key_I_released = false;
            }
        }
        else if (glfwGetKey(window, GLFW_KEY_I) == GLFW_RELEASE)
        {
            is_key_I_released = true;
        }

        // adjust position according to the ground.
        if (!inFlightmode)
        {
            if (this->world_species_pointer != NULL)
            {
                GLfloat ground_y = model::get_floor_level(static_cast<model::Species*>(this->world_species_pointer), position);

                if (!std::isnan(ground_y))
                {
                    if (position.y < ground_y)
                    {
                        position.y = ground_y;
                        fallSpeed = 0.0f;
                    }
                }
            }
        }

#ifdef TESTING_SPHERICAL_WORLD_IN_USE
        // compute spherical coordinates.
        spherical_position.rho = sqrt((position.x * position.x) + (position.y * position.y) + (position.z * position.z));
        spherical_position.theta = RADIANS_TO_DEGREES(atan2(sqrt((position.x * position.x) + (position.y * position.y)), position.z));
        spherical_position.phi = RADIANS_TO_DEGREES(atan2(position.y, position.x));
#endif

        earth_radius = EARTH_RADIUS;

        camera_position = position;
        camera_position.y += 2.0f;

        // Projection matrix : 45° Field of View, aspect ratio, display range : 0.1 unit <-> 100 units
        ProjectionMatrix = glm::perspective(FoV, ASPECT_RATIO, 0.001f, 5000.0f + 2.0f * (GLfloat) earth_radius);
        // Camera matrix
        ViewMatrix = glm::lookAt(
                camera_position,           // Camera is here
                camera_position+direction, // and looks here : at the same position, plus "direction"
                up                         // Head is up (set to 0,-1,0 to look upside-down)
                );

        // For the next frame, the "last time" will be "now"
        lastTime = currentTime;
    }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: mediator.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: vg $ $Date: 2003-04-15 16:17:41 $
 *
 *  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 _MEDIATOR_HXX
#define _MEDIATOR_HXX

#include <string.h>
#include <stdarg.h>

#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _LIST_HXX
#include <tools/list.hxx>
#endif
#ifndef _LINK_HXX
#include <tools/link.hxx>
#endif
#ifndef _VOS_PIPE_HXX_
#include <vos/pipe.hxx>
#endif
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _VOS_CONDITN_HXX_
#include <vos/conditn.hxx>
#endif
#ifndef _VOS_THREAD_HXX_
#include <vos/thread.hxx>
#endif
#if OSL_DEBUG_LEVEL > 1
#include <stdio.h>
#endif

struct MediatorMessage
{
    ULONG   m_nID;
    ULONG   m_nBytes;
    char*   m_pBytes;
    char*   m_pRun;

    MediatorMessage() : m_nID( 0 ), m_nBytes( 0 ),
        m_pBytes( NULL ), m_pRun( NULL ) {}
    MediatorMessage( ULONG nID, ULONG nBytes, char* pBytes ) :
            m_nID( nID ),m_nBytes( nBytes ), m_pRun( NULL )
        {
            m_pBytes = new char[ m_nBytes ];
            memcpy( m_pBytes, pBytes, (size_t)m_nBytes );
        }

    ~MediatorMessage()
        {
            if( m_pBytes )
                delete m_pBytes;
        }

    void Set( ULONG nBytes, char* pBytes )
        {
            if( m_pBytes )
                delete m_pBytes;
            m_nBytes = nBytes;
            m_pBytes = new char[ m_nBytes ];
            memcpy( m_pBytes, pBytes, (size_t)m_nBytes );
        }

    ULONG   ExtractULONG();
    char*   GetString();
    UINT32  GetUINT32();
    void*   GetBytes( ULONG& );
    void*   GetBytes() { ULONG nBytes; return GetBytes( nBytes ); }

    void    Rewind() { m_pRun = NULL; }
};

DECLARE_LIST( MediatorMessageList, MediatorMessage* );

class MediatorListener;

class Mediator
{
    friend class MediatorListener;
protected:
    int                                 m_nSocket;

    MediatorMessageList                 m_aMessageQueue;
    NAMESPACE_VOS(OMutex)               m_aQueueMutex;
    NAMESPACE_VOS(OMutex)               m_aSendMutex;
    // only one thread can send a message at any given time
    NAMESPACE_VOS(OCondition)           m_aNewMessageCdtn;
    MediatorListener*                   m_pListener;
    // thread to fill the queue

    ULONG                               m_nCurrentID;
    // will be constantly increased with each message sent
    bool                                m_bValid;

    Link                                m_aConnectionLostHdl;
    Link                                m_aNewMessageHdl;
public:
    Mediator( int nSocket );
    ~Mediator();

    // mark mediator as invalid. No more messages will be processed,
    // SendMessage, WaitForMessage, TransactMessage will return immediatly
    // with error
    void invalidate() { m_bValid = false; }

    ULONG SendMessage( ULONG nBytes, const char* pBytes, ULONG nMessageID = 0 );
    ULONG SendMessage( const ByteString& rMessage, ULONG nMessageID = 0 )
        {
            return SendMessage( rMessage.Len(), rMessage.GetBuffer(), nMessageID );
        }

    BOOL WaitForMessage( ULONG nTimeOut = 5000 );
    // timeout in ms
    // TRUE:  Message came in
    // FALSE: timed out
    // if timeout is set, WaitForMessage will wait even if there are messages
    // in the queue

    virtual MediatorMessage* WaitForAnswer( ULONG nMessageID );
    // wait for an answer message ( ID >= 1 << 24 )
    // the message will be removed from the queue and returned

    MediatorMessage* TransactMessage( ULONG nBytes, char* pBytes );
    // sends a message and waits for an answer

    MediatorMessage* GetNextMessage( BOOL bWait = FALSE );

    Link SetConnectionLostHdl( const Link& rLink )
        {
            Link aRet = m_aConnectionLostHdl;
            m_aConnectionLostHdl = rLink;
            return aRet;
        }

    Link SetNewMessageHdl( const Link& rLink )
        {
            Link aRet = m_aNewMessageHdl;
            m_aNewMessageHdl = rLink;
            return aRet;
        }
};

class MediatorListener : public NAMESPACE_VOS( OThread )
{
    friend class Mediator;
  private:
    Mediator*       m_pMediator;
    ::vos::OMutex   m_aMutex;

    MediatorListener( Mediator* );
    ~MediatorListener();

    virtual void run();
    virtual void onTerminated();
};

inline void medDebug( int condition, char* pFormat, ... )
{
#if OSL_DEBUG_LEVEL > 1
    if( condition )
    {
        va_list ap;
        va_start( ap, pFormat );
        vfprintf( stderr, pFormat, ap );
        va_end( ap );
    }
#endif
}

#endif // _MEDIATOR_HXX
<commit_msg>INTEGRATION: CWS vcl09 (1.3.10); FILE MERGED 2003/05/08 18:46:19 pl 1.3.10.1: #109426# make rpnp.so work on Linux<commit_after>/*************************************************************************
 *
 *  $RCSfile: mediator.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: vg $ $Date: 2003-05-28 12:37:54 $
 *
 *  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 _MEDIATOR_HXX
#define _MEDIATOR_HXX

#include <string.h>
#include <stdarg.h>

#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _LIST_HXX
#include <tools/list.hxx>
#endif
#ifndef _LINK_HXX
#include <tools/link.hxx>
#endif
#ifndef _VOS_PIPE_HXX_
#include <vos/pipe.hxx>
#endif
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _VOS_CONDITN_HXX_
#include <vos/conditn.hxx>
#endif
#ifndef _VOS_THREAD_HXX_
#include <vos/thread.hxx>
#endif
#if OSL_DEBUG_LEVEL > 1
#include <stdio.h>
#endif

struct MediatorMessage
{
    ULONG   m_nID;
    ULONG   m_nBytes;
    char*   m_pBytes;
    char*   m_pRun;

    MediatorMessage() : m_nID( 0 ), m_nBytes( 0 ),
        m_pBytes( NULL ), m_pRun( NULL ) {}
    MediatorMessage( ULONG nID, ULONG nBytes, char* pBytes ) :
            m_nID( nID ),m_nBytes( nBytes ), m_pRun( NULL )
        {
            m_pBytes = new char[ m_nBytes ];
            memcpy( m_pBytes, pBytes, (size_t)m_nBytes );
        }

    ~MediatorMessage()
        {
            if( m_pBytes )
                delete [] m_pBytes;
        }

    void Set( ULONG nBytes, char* pBytes )
        {
            if( m_pBytes )
                delete [] m_pBytes;
            m_nBytes = nBytes;
            m_pBytes = new char[ m_nBytes ];
            memcpy( m_pBytes, pBytes, (size_t)m_nBytes );
        }

    ULONG   ExtractULONG();
    char*   GetString();
    UINT32  GetUINT32();
    void*   GetBytes( ULONG& );
    void*   GetBytes() { ULONG nBytes; return GetBytes( nBytes ); }

    void    Rewind() { m_pRun = NULL; }
};

DECLARE_LIST( MediatorMessageList, MediatorMessage* );

class MediatorListener;

class Mediator
{
    friend class MediatorListener;
protected:
    int                                 m_nSocket;

    MediatorMessageList                 m_aMessageQueue;
    NAMESPACE_VOS(OMutex)               m_aQueueMutex;
    NAMESPACE_VOS(OMutex)               m_aSendMutex;
    // only one thread can send a message at any given time
    NAMESPACE_VOS(OCondition)           m_aNewMessageCdtn;
    MediatorListener*                   m_pListener;
    // thread to fill the queue

    ULONG                               m_nCurrentID;
    // will be constantly increased with each message sent
    bool                                m_bValid;

    Link                                m_aConnectionLostHdl;
    Link                                m_aNewMessageHdl;
public:
    Mediator( int nSocket );
    ~Mediator();

    // mark mediator as invalid. No more messages will be processed,
    // SendMessage, WaitForMessage, TransactMessage will return immediatly
    // with error
    void invalidate() { m_bValid = false; }

    ULONG SendMessage( ULONG nBytes, const char* pBytes, ULONG nMessageID = 0 );
    ULONG SendMessage( const ByteString& rMessage, ULONG nMessageID = 0 )
        {
            return SendMessage( rMessage.Len(), rMessage.GetBuffer(), nMessageID );
        }

    BOOL WaitForMessage( ULONG nTimeOut = 5000 );
    // timeout in ms
    // TRUE:  Message came in
    // FALSE: timed out
    // if timeout is set, WaitForMessage will wait even if there are messages
    // in the queue

    virtual MediatorMessage* WaitForAnswer( ULONG nMessageID );
    // wait for an answer message ( ID >= 1 << 24 )
    // the message will be removed from the queue and returned

    MediatorMessage* TransactMessage( ULONG nBytes, char* pBytes );
    // sends a message and waits for an answer

    MediatorMessage* GetNextMessage( BOOL bWait = FALSE );

    Link SetConnectionLostHdl( const Link& rLink )
        {
            Link aRet = m_aConnectionLostHdl;
            m_aConnectionLostHdl = rLink;
            return aRet;
        }

    Link SetNewMessageHdl( const Link& rLink )
        {
            Link aRet = m_aNewMessageHdl;
            m_aNewMessageHdl = rLink;
            return aRet;
        }
};

class MediatorListener : public NAMESPACE_VOS( OThread )
{
    friend class Mediator;
  private:
    Mediator*       m_pMediator;
    ::vos::OMutex   m_aMutex;

    MediatorListener( Mediator* );
    ~MediatorListener();

    virtual void run();
    virtual void onTerminated();
};

inline void medDebug( int condition, char* pFormat, ... )
{
#if OSL_DEBUG_LEVEL > 1
    if( condition )
    {
        va_list ap;
        va_start( ap, pFormat );
        vfprintf( stderr, pFormat, ap );
        va_end( ap );
    }
#endif
}

#endif // _MEDIATOR_HXX
<|endoftext|>


<commit_before>// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2019 Intel Corporation. All Rights Reserved.

#include "ds5/ds5-options.h"
#include "ds5/ds5-motion.h"
#include "synthetic-stream.h"
#include "motion-transform.h"

namespace librealsense
{
    template<rs2_format FORMAT> void copy_hid_axes(byte * const dest[], const byte * source, double factor)
    {
        using namespace librealsense;
        auto hid = (hid_data*)(source);

        auto res = float3{ float(hid->x), float(hid->y), float(hid->z) } *float(factor);

        librealsense::copy(dest[0], &res, sizeof(float3));
    }

    // The Accelerometer input format: signed int 16bit. data units 1LSB=0.001g;
    // Librealsense output format: floating point 32bit. units m/s^2,
    template<rs2_format FORMAT> void unpack_accel_axes(byte * const dest[], const byte * source, int width, int height, int output_size)
    {
        static constexpr float gravity = 9.80665f;          // Standard Gravitation Acceleration
        static constexpr double accelerator_transform_factor = 0.001*gravity;

        copy_hid_axes<FORMAT>(dest, source, accelerator_transform_factor);
    }

    // The Gyro input format: signed int 16bit. data units 1LSB=0.1deg/sec;
    // Librealsense output format: floating point 32bit. units rad/sec,
    template<rs2_format FORMAT> void unpack_gyro_axes(byte * const dest[], const byte * source, int width, int height, int output_size)
    {
        static const double gyro_transform_factor = deg2rad(0.1);

        copy_hid_axes<FORMAT>(dest, source, gyro_transform_factor);
    }

    motion_transform::motion_transform(rs2_format target_format, rs2_stream target_stream,
        std::shared_ptr<mm_calib_handler> mm_calib, std::shared_ptr<enable_motion_correction> mm_correct_opt)
        : motion_transform("Motion Transform", target_format, target_stream, mm_calib, mm_correct_opt)
    {}

    motion_transform::motion_transform(const char* name, rs2_format target_format, rs2_stream target_stream,
        std::shared_ptr<mm_calib_handler> mm_calib, std::shared_ptr<enable_motion_correction> mm_correct_opt)
        : functional_processing_block(name, target_format, target_stream, RS2_EXTENSION_MOTION_FRAME),
        _mm_correct_opt(mm_correct_opt)
    {
        if (mm_calib)
        {
            _imu2depth_cs_alignment_matrix = (*mm_calib).imu_to_depth_alignment();
            if (_mm_correct_opt)
            {
                auto accel_intr = (*mm_calib).get_intrinsic(RS2_STREAM_ACCEL);
                auto gyro_intr = (*mm_calib).get_intrinsic(RS2_STREAM_GYRO);
                _accel_sensitivity  = accel_intr.sensitivity;
                _accel_bias         = accel_intr.bias;
                _gyro_sensitivity   = gyro_intr.sensitivity;
                _gyro_bias          = gyro_intr.bias;
            }
        }
        else
        {
            // TODO Define L500 base transformation alignment
            _imu2depth_cs_alignment_matrix = { {1,0,0},{0,1,0}, {0,0,1} };
        }
    }

    rs2::frame motion_transform::process_frame(const rs2::frame_source& source, const rs2::frame& f)
    {
        auto&& ret = functional_processing_block::process_frame(source, f);
        correct_motion(&ret);

        return ret;
    }

    void motion_transform::correct_motion(rs2::frame* f)
    {
        auto xyz = (float3*)(f->get_data());

        if (_mm_correct_opt)
        {
            if ((_mm_correct_opt->query() > 0.f)) // TBD resolve duality of is_enabled/is_active
            {
                auto&& s = f->get_profile().stream_type();
                if (s == RS2_STREAM_ACCEL)
                    *xyz = (_accel_sensitivity * (*xyz)) - _accel_bias;

                if (s == RS2_STREAM_GYRO)
                    *xyz = _gyro_sensitivity * (*xyz) - _gyro_bias;
            }
        }

        // The IMU sensor orientation shall be aligned with depth sensor's coordinate system
        *xyz = _imu2depth_cs_alignment_matrix * (*xyz);
    }

    acceleration_transform::acceleration_transform(std::shared_ptr<mm_calib_handler> mm_calib, std::shared_ptr<enable_motion_correction> mm_correct_opt)
        : acceleration_transform("Acceleration Transform", mm_calib, mm_correct_opt)
    {}

    acceleration_transform::acceleration_transform(const char * name, std::shared_ptr<mm_calib_handler> mm_calib, std::shared_ptr<enable_motion_correction> mm_correct_opt)
        : motion_transform(name, RS2_FORMAT_MOTION_XYZ32F, RS2_STREAM_ACCEL, mm_calib, mm_correct_opt)
    {}

    void acceleration_transform::process_function(byte * const dest[], const byte * source, int width, int height, int output_size, int actual_size)
    {
        unpack_accel_axes<RS2_FORMAT_MOTION_XYZ32F>(dest, source, width, height, actual_size);
    }

    gyroscope_transform::gyroscope_transform(std::shared_ptr<mm_calib_handler> mm_calib, std::shared_ptr<enable_motion_correction> mm_correct_opt)
        : gyroscope_transform("Gyroscope Transform", mm_calib, mm_correct_opt)
    {}

    gyroscope_transform::gyroscope_transform(const char * name, std::shared_ptr<mm_calib_handler> mm_calib, std::shared_ptr<enable_motion_correction> mm_correct_opt)
        : motion_transform(name, RS2_FORMAT_MOTION_XYZ32F, RS2_STREAM_GYRO, mm_calib, mm_correct_opt)
    {}

    void gyroscope_transform::process_function(byte * const dest[], const byte * source, int width, int height, int output_size, int actual_size)
    {
        unpack_gyro_axes<RS2_FORMAT_MOTION_XYZ32F>(dest, source, width, height, actual_size);
    }
}

<commit_msg>fix imu motion correction issues<commit_after>// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2019 Intel Corporation. All Rights Reserved.

#include "ds5/ds5-options.h"
#include "ds5/ds5-motion.h"
#include "synthetic-stream.h"
#include "motion-transform.h"

namespace librealsense
{
    template<rs2_format FORMAT> void copy_hid_axes(byte * const dest[], const byte * source, double factor)
    {
        using namespace librealsense;
        auto hid = (hid_data*)(source);

        auto res = float3{ float(hid->x), float(hid->y), float(hid->z) } *float(factor);

        librealsense::copy(dest[0], &res, sizeof(float3));
    }

    // The Accelerometer input format: signed int 16bit. data units 1LSB=0.001g;
    // Librealsense output format: floating point 32bit. units m/s^2,
    template<rs2_format FORMAT> void unpack_accel_axes(byte * const dest[], const byte * source, int width, int height, int output_size)
    {
        static constexpr float gravity = 9.80665f;          // Standard Gravitation Acceleration
        static constexpr double accelerator_transform_factor = 0.001*gravity;

        copy_hid_axes<FORMAT>(dest, source, accelerator_transform_factor);
    }

    // The Gyro input format: signed int 16bit. data units 1LSB=0.1deg/sec;
    // Librealsense output format: floating point 32bit. units rad/sec,
    template<rs2_format FORMAT> void unpack_gyro_axes(byte * const dest[], const byte * source, int width, int height, int output_size)
    {
        static const double gyro_transform_factor = deg2rad(0.1);

        copy_hid_axes<FORMAT>(dest, source, gyro_transform_factor);
    }

    motion_transform::motion_transform(rs2_format target_format, rs2_stream target_stream,
        std::shared_ptr<mm_calib_handler> mm_calib, std::shared_ptr<enable_motion_correction> mm_correct_opt)
        : motion_transform("Motion Transform", target_format, target_stream, mm_calib, mm_correct_opt)
    {}

    motion_transform::motion_transform(const char* name, rs2_format target_format, rs2_stream target_stream,
        std::shared_ptr<mm_calib_handler> mm_calib, std::shared_ptr<enable_motion_correction> mm_correct_opt)
        : functional_processing_block(name, target_format, target_stream, RS2_EXTENSION_MOTION_FRAME),
        _mm_correct_opt(mm_correct_opt)
    {
        if (mm_calib)
        {
            _imu2depth_cs_alignment_matrix = (*mm_calib).imu_to_depth_alignment();
            if (_mm_correct_opt)
            {
                auto accel_intr = (*mm_calib).get_intrinsic(RS2_STREAM_ACCEL);
                auto gyro_intr = (*mm_calib).get_intrinsic(RS2_STREAM_GYRO);
                _accel_sensitivity  = accel_intr.sensitivity;
                _accel_bias         = accel_intr.bias;
                _gyro_sensitivity   = gyro_intr.sensitivity;
                _gyro_bias          = gyro_intr.bias;
            }
        }
        else
        {
            // TODO Define L500 base transformation alignment
            _imu2depth_cs_alignment_matrix = { {1,0,0},{0,1,0}, {0,0,1} };
        }
    }

    rs2::frame motion_transform::process_frame(const rs2::frame_source& source, const rs2::frame& f)
    {
        auto&& ret = functional_processing_block::process_frame(source, f);
        correct_motion(&ret);

        return ret;
    }

    void motion_transform::correct_motion(rs2::frame* f)
    {
        auto xyz = (float3*)(f->get_data());

        // The IMU sensor orientation shall be aligned with depth sensor's coordinate system
        *xyz = _imu2depth_cs_alignment_matrix * (*xyz);

        // IMU calibration is done with data in depth sensor's coordinate system, so calibration parameters should be applied for motion correction
        // in the same coordinate system
        if (_mm_correct_opt)
        {
            if ((_mm_correct_opt->query() > 0.f)) // TBD resolve duality of is_enabled/is_active
            {
                auto&& s = f->get_profile().stream_type();
                if (s == RS2_STREAM_ACCEL)
                    *xyz = (_accel_sensitivity * (*xyz)) - _accel_bias;

                if (s == RS2_STREAM_GYRO)
                    *xyz = _gyro_sensitivity * (*xyz) - _gyro_bias;
            }
        }
    }

    acceleration_transform::acceleration_transform(std::shared_ptr<mm_calib_handler> mm_calib, std::shared_ptr<enable_motion_correction> mm_correct_opt)
        : acceleration_transform("Acceleration Transform", mm_calib, mm_correct_opt)
    {}

    acceleration_transform::acceleration_transform(const char * name, std::shared_ptr<mm_calib_handler> mm_calib, std::shared_ptr<enable_motion_correction> mm_correct_opt)
        : motion_transform(name, RS2_FORMAT_MOTION_XYZ32F, RS2_STREAM_ACCEL, mm_calib, mm_correct_opt)
    {}

    void acceleration_transform::process_function(byte * const dest[], const byte * source, int width, int height, int output_size, int actual_size)
    {
        unpack_accel_axes<RS2_FORMAT_MOTION_XYZ32F>(dest, source, width, height, actual_size);
    }

    gyroscope_transform::gyroscope_transform(std::shared_ptr<mm_calib_handler> mm_calib, std::shared_ptr<enable_motion_correction> mm_correct_opt)
        : gyroscope_transform("Gyroscope Transform", mm_calib, mm_correct_opt)
    {}

    gyroscope_transform::gyroscope_transform(const char * name, std::shared_ptr<mm_calib_handler> mm_calib, std::shared_ptr<enable_motion_correction> mm_correct_opt)
        : motion_transform(name, RS2_FORMAT_MOTION_XYZ32F, RS2_STREAM_GYRO, mm_calib, mm_correct_opt)
    {}

    void gyroscope_transform::process_function(byte * const dest[], const byte * source, int width, int height, int output_size, int actual_size)
    {
        unpack_gyro_axes<RS2_FORMAT_MOTION_XYZ32F>(dest, source, width, height, actual_size);
    }
}

<|endoftext|>


<commit_before>#include "arch/runtime/runtime.hpp"
#include "arch/runtime/starter.hpp"

#include "utils.hpp"
#include <boost/bind.hpp>

#include "arch/runtime/thread_pool.hpp"
#include "do_on_thread.hpp"

int get_thread_id() {
    return linux_thread_pool_t::thread_id;
}

int get_num_threads() {
    return linux_thread_pool_t::thread_pool->n_threads;
}

int thread_local_randint(int n) {
    return linux_thread_pool_t::thread->thread_local_rng.randint(n);
}

#ifndef NDEBUG
void assert_good_thread_id(int thread) {
    rassert(thread >= 0, "(thread = %d)", thread);
    rassert(thread < get_num_threads(), "(thread = %d, n_threads = %d)", thread, get_num_threads());
}
#endif

bool continue_on_thread(int thread, linux_thread_message_t *msg) {
    assert_good_thread_id(thread);
    if (thread == linux_thread_pool_t::thread_id) {
        // The thread to continue on is the thread we are already on
        return true;
    } else {
        linux_thread_pool_t::thread->message_hub.store_message(thread, msg);
        return false;
    }
}

void call_later_on_this_thread(linux_thread_message_t *msg) {
    linux_thread_pool_t::thread->message_hub.store_message(linux_thread_pool_t::thread_id, msg);
}

struct starter_t : public thread_message_t {
    linux_thread_pool_t *tp;
    boost::function<void()> run;

    starter_t(linux_thread_pool_t *_tp, const boost::function<void()>& _fun) : tp(_tp), run(boost::bind(&starter_t::run_wrapper, this, _fun)) { }
    void on_thread_switch() {
        const int run_thread = 0;
        rassert(get_thread_id() != run_thread);
        do_on_thread(run_thread, boost::bind(&coro_t::spawn_now< boost::function<void()> >, boost::ref(run)));
    }
private:
    void run_wrapper(const boost::function<void()>& fun) {
        fun();
        tp->shutdown();
    }
};

void run_in_thread_pool(const boost::function<void()>& fun, int num_threads) {
    linux_thread_pool_t thread_pool(num_threads, false);
    starter_t starter(&thread_pool, fun);
    thread_pool.run(&starter);
}
<commit_msg>Make run_in_thread_pool() not try to switch back after spawning coroutine. Fixes #565.<commit_after>#include "arch/runtime/runtime.hpp"
#include "arch/runtime/starter.hpp"

#include "utils.hpp"
#include <boost/bind.hpp>

#include "arch/runtime/thread_pool.hpp"
#include "do_on_thread.hpp"

int get_thread_id() {
    return linux_thread_pool_t::thread_id;
}

int get_num_threads() {
    return linux_thread_pool_t::thread_pool->n_threads;
}

int thread_local_randint(int n) {
    return linux_thread_pool_t::thread->thread_local_rng.randint(n);
}

#ifndef NDEBUG
void assert_good_thread_id(int thread) {
    rassert(thread >= 0, "(thread = %d)", thread);
    rassert(thread < get_num_threads(), "(thread = %d, n_threads = %d)", thread, get_num_threads());
}
#endif

bool continue_on_thread(int thread, linux_thread_message_t *msg) {
    assert_good_thread_id(thread);
    if (thread == linux_thread_pool_t::thread_id) {
        // The thread to continue on is the thread we are already on
        return true;
    } else {
        linux_thread_pool_t::thread->message_hub.store_message(thread, msg);
        return false;
    }
}

void call_later_on_this_thread(linux_thread_message_t *msg) {
    linux_thread_pool_t::thread->message_hub.store_message(linux_thread_pool_t::thread_id, msg);
}

struct starter_t : public thread_message_t {
    linux_thread_pool_t *tp;
    boost::function<void()> run;

    starter_t(linux_thread_pool_t *_tp, const boost::function<void()>& _fun) : tp(_tp), run(boost::bind(&starter_t::run_wrapper, this, _fun)) { }
    void on_thread_switch() {
        const int run_thread = 0;
        rassert(get_thread_id() != run_thread);
        one_way_do_on_thread(run_thread, boost::bind(&coro_t::spawn_sometime< boost::function<void()> >, boost::ref(run)));
    }
private:
    void run_wrapper(const boost::function<void()>& fun) {
        fun();
        tp->shutdown();
    }
};

void run_in_thread_pool(const boost::function<void()>& fun, int num_threads) {
    linux_thread_pool_t thread_pool(num_threads, false);
    starter_t starter(&thread_pool, fun);
    thread_pool.run(&starter);
}
<|endoftext|>


<commit_before>#pragma once

#include <vector>
#include "graph.hpp"

namespace simple_graph {

template<typename V, typename E>
bool bellman_ford(const Graph<V, E> &g, size_t start_idx, size_t goal_idx, std::vector<size_t> *path)
{
    std::vector<size_t> distance(g.vertex_num(), std::numeric_limits<size_t>::max());
    std::vector<size_t> predecessor(g.vertex_num(), 0);

    distance[start_idx] = 0;

    Graph<V, E> *fg = const_cast<Graph<V, E>*>(&g);
    for (size_t i = 0; i < g.vertex_num(); ++i) {
        for (auto e : fg->edges()) {
            if (distance[e.idx1()] + e.weight() < distance[e.idx2()]) {
                distance[e.idx2()] = distance[e.idx1()] + e.weight();
                predecessor[e.idx2()] = e.idx1();
            }
        }
    }

    for (auto e : fg->edges()) {
        if (distance[e.idx1()] + e.weight() < distance[e.idx2()]) {
            return false;
        }
    }

    if (distance[goal_idx] == 0) {
        return false;
    }

    size_t idx = goal_idx;
    while (idx != start_idx) {
        path->push_back(idx);
        idx = predecessor[idx];
    }
    path->push_back(idx);
    std::reverse(path->begin(), path->end());

    return true;
}

}  // simple_graph
<commit_msg>Fix Bellman-Ford algorithm for negative edge weights<commit_after>#pragma once

#include <vector>
#include "graph.hpp"

namespace simple_graph {

template<typename V, typename E>
bool bellman_ford(const Graph<V, E> &g, size_t start_idx, size_t goal_idx, std::vector<size_t> *path)
{
    std::vector<E> distance(g.vertex_num(), std::numeric_limits<E>::max());
    std::vector<size_t> predecessor(g.vertex_num(), 0);

    distance[start_idx] = 0;

    Graph<V, E> *fg = const_cast<Graph<V, E>*>(&g);
    for (size_t i = 0; i < g.vertex_num(); ++i) {
        for (auto e : fg->edges()) {
            if (distance[e.idx1()] + e.weight() < distance[e.idx2()]) {
                distance[e.idx2()] = distance[e.idx1()] + e.weight();
                predecessor[e.idx2()] = e.idx1();
            }
        }
    }

    for (auto e : fg->edges()) {
        if (distance[e.idx1()] + e.weight() < distance[e.idx2()]) {
            return false;
        }
    }

    if (distance[goal_idx] == 0) {
        return false;
    }

    size_t idx = goal_idx;
    while (idx != start_idx) {
        path->push_back(idx);
        idx = predecessor[idx];
    }
    path->push_back(idx);
    std::reverse(path->begin(), path->end());

    return true;
}

}  // simple_graph
<|endoftext|>


<commit_before>// Copyright (c) 2016-2019 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/

#ifndef TAO_PEGTL_INTERNAL_ACTION_INPUT_HPP
#define TAO_PEGTL_INTERNAL_ACTION_INPUT_HPP

#include <cstddef>
#include <cstdint>
#include <string>
#include <string_view>

#include "iterator.hpp"

#include "../config.hpp"
#include "../position.hpp"

namespace tao
{
   namespace TAO_PEGTL_NAMESPACE
   {
      namespace internal
      {
         [[nodiscard]] inline const char* begin_c_ptr( const char* p ) noexcept
         {
            return p;
         }

         [[nodiscard]] inline const char* begin_c_ptr( const iterator& it ) noexcept
         {
            return it.data;
         }

         template< typename Input >
         class action_input
         {
         public:
            using input_t = Input;
            using iterator_t = typename Input::iterator_t;

            action_input( const iterator_t& in_begin, const Input& in_input ) noexcept
               : m_begin( in_begin ),
                 m_input( in_input )
            {
            }

            action_input( const action_input& ) = delete;
            action_input( action_input&& ) = delete;

            ~action_input() = default;

            action_input& operator=( const action_input& ) = delete;
            action_input& operator=( action_input&& ) = delete;

            [[nodiscard]] const iterator_t& iterator() const noexcept
            {
               return m_begin;
            }

            [[nodiscard]] const Input& input() const noexcept
            {
               return m_input;
            }

            [[nodiscard]] const char* begin() const noexcept
            {
               return begin_c_ptr( iterator() );
            }

            [[nodiscard]] const char* end() const noexcept
            {
               return input().current();
            }

            [[nodiscard]] bool empty() const noexcept
            {
               return begin() == end();
            }

            [[nodiscard]] std::size_t size() const noexcept
            {
               return std::size_t( end() - begin() );
            }

            [[nodiscard]] std::string string() const
            {
               return std::string( begin(), end() );
            }

            [[nodiscard]] std::string_view string_view() const noexcept
            {
               return std::string_view( begin(), size() );
            }

            [[nodiscard]] char peek_char( const std::size_t offset = 0 ) const noexcept
            {
               return begin()[ offset ];
            }

            [[nodiscard]] std::uint8_t peek_uint8( const std::size_t offset = 0 ) const noexcept
            {
               return static_cast< std::uint8_t >( peek_char( offset ) );
            }

            [[nodiscard]] TAO_PEGTL_NAMESPACE::position position() const
            {
               return input().position( iterator() );  // NOTE: Not efficient with lazy inputs.
            }

         protected:
            const iterator_t m_begin;
            const Input& m_input;
         };

      }  // namespace internal

   }  // namespace TAO_PEGTL_NAMESPACE

}  // namespace tao

#endif
<commit_msg>Modernize<commit_after>// Copyright (c) 2016-2019 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/

#ifndef TAO_PEGTL_INTERNAL_ACTION_INPUT_HPP
#define TAO_PEGTL_INTERNAL_ACTION_INPUT_HPP

#include <cstddef>
#include <cstdint>
#include <string>
#include <string_view>

#include "iterator.hpp"

#include "../config.hpp"
#include "../position.hpp"

namespace tao
{
   namespace TAO_PEGTL_NAMESPACE
   {
      namespace internal
      {
         template< typename Input >
         class action_input
         {
         public:
            using input_t = Input;
            using iterator_t = typename Input::iterator_t;

            action_input( const iterator_t& in_begin, const Input& in_input ) noexcept
               : m_begin( in_begin ),
                 m_input( in_input )
            {
            }

            action_input( const action_input& ) = delete;
            action_input( action_input&& ) = delete;

            ~action_input() = default;

            action_input& operator=( const action_input& ) = delete;
            action_input& operator=( action_input&& ) = delete;

            [[nodiscard]] const iterator_t& iterator() const noexcept
            {
               return m_begin;
            }

            [[nodiscard]] const Input& input() const noexcept
            {
               return m_input;
            }

            [[nodiscard]] const char* begin() const noexcept
            {
               if constexpr( std::is_same_v< iterator_t, const char* > ) {
                  return iterator();
               }
               else {  // NOLINT
                  return iterator().data;
               }
            }

            [[nodiscard]] const char* end() const noexcept
            {
               return input().current();
            }

            [[nodiscard]] bool empty() const noexcept
            {
               return begin() == end();
            }

            [[nodiscard]] std::size_t size() const noexcept
            {
               return std::size_t( end() - begin() );
            }

            [[nodiscard]] std::string string() const
            {
               return std::string( begin(), end() );
            }

            [[nodiscard]] std::string_view string_view() const noexcept
            {
               return std::string_view( begin(), size() );
            }

            [[nodiscard]] char peek_char( const std::size_t offset = 0 ) const noexcept
            {
               return begin()[ offset ];
            }

            [[nodiscard]] std::uint8_t peek_uint8( const std::size_t offset = 0 ) const noexcept
            {
               return static_cast< std::uint8_t >( peek_char( offset ) );
            }

            [[nodiscard]] TAO_PEGTL_NAMESPACE::position position() const
            {
               return input().position( iterator() );  // NOTE: Not efficient with lazy inputs.
            }

         protected:
            const iterator_t m_begin;
            const Input& m_input;
         };

      }  // namespace internal

   }  // namespace TAO_PEGTL_NAMESPACE

}  // namespace tao

#endif
<|endoftext|>


<commit_before>/*
** Author(s):
**  - Cedric GESTES <gestes@aldebaran-robotics.com>
**
** Copyright (C) 2013 Aldebaran Robotics
*/

#include <qi/iocolor.hpp>
#include <sstream>
#include <qi/os.hpp>

#if defined(__APPLE__) or defined(__linux__)
static std::string makeCol(char c, char modifier = -1) {
  std::stringstream ret;
  ret << "\033[" << (int)c;
  if (modifier > 0)
    ret << ";" << (int)modifier;
  ret << "m";
  return ret.str();
}

static void posix_print(std::ostream& os, qi::StreamColor col) {
  switch (col) {
  case qi::StreamColor_None:
    break;
  case qi::StreamColor_Reset:
    os << makeCol(0);
    break;
  case qi::StreamColor_Bold:
    os << makeCol(1);
    break;
  case qi::StreamColor_Faint:
    os << makeCol(2);
    break;
  case qi::StreamColor_Standout:
    os << makeCol(3);
    break;
  case qi::StreamColor_Underline:
    os << makeCol(4);
    break;
  case qi::StreamColor_Blink:
    os << makeCol(5);
    break;
  case qi::StreamColor_Overline:
    os << makeCol(6);
    break;

  case qi::StreamColor_Black:
    os << makeCol(30, 0);
    break;
  case qi::StreamColor_DarkRed:
    os << makeCol(31, 0);
    break;
  case qi::StreamColor_DarkGreen:
    os << makeCol(32, 0);
    break;
  case qi::StreamColor_Brown:
    os << makeCol(33, 0);
    break;
  case qi::StreamColor_DarkBlue:
    os << makeCol(34, 0);
    break;
  case qi::StreamColor_Purple:
    os << makeCol(35, 0);
    break;
  case qi::StreamColor_Teal:
    os << makeCol(36, 0);
    break;
  case qi::StreamColor_LightGray:
    os << makeCol(37, 0);
    break;

  case qi::StreamColor_DarkGray:
    os << makeCol(30, 1);
    break;
  case qi::StreamColor_Red:
    os << makeCol(31, 1);
    break;
  case qi::StreamColor_Green:
    os << makeCol(32, 1);
    break;
  case qi::StreamColor_Yellow:
    os << makeCol(33, 1);
    break;
  case qi::StreamColor_Blue:
    os << makeCol(34, 1);
    break;
  case qi::StreamColor_Fuchsia:
    os << makeCol(35, 1);
    break;
  case qi::StreamColor_Turquoise:
    os << makeCol(36, 1);
    break;
  case qi::StreamColor_White:
    os << makeCol(37, 1);
    break;
  };
}
#endif

namespace std {

  std::ostream& operator<<(std::ostream& os, qi::StreamColor col)
  {
    if (&os == &(std::cout) && !qi::os::isatty(1))
      return os;
    if (&os == &(std::cerr) && !qi::os::isatty(2))
      return os;
#if defined(__APPLE__) or defined(__linux__)
    posix_print(os, col);
#endif
    return os;
  }

}
<commit_msg>blind fix for windows warning<commit_after>/*
** Author(s):
**  - Cedric GESTES <gestes@aldebaran-robotics.com>
**
** Copyright (C) 2013 Aldebaran Robotics
*/

#include <qi/iocolor.hpp>
#include <sstream>
#include <qi/os.hpp>

#if defined(__APPLE__) || defined(__linux__)
static std::string makeCol(char c, char modifier = -1) {
  std::stringstream ret;
  ret << "\033[" << (int)c;
  if (modifier > 0)
    ret << ";" << (int)modifier;
  ret << "m";
  return ret.str();
}

static void posix_print(std::ostream& os, qi::StreamColor col) {
  switch (col) {
  case qi::StreamColor_None:
    break;
  case qi::StreamColor_Reset:
    os << makeCol(0);
    break;
  case qi::StreamColor_Bold:
    os << makeCol(1);
    break;
  case qi::StreamColor_Faint:
    os << makeCol(2);
    break;
  case qi::StreamColor_Standout:
    os << makeCol(3);
    break;
  case qi::StreamColor_Underline:
    os << makeCol(4);
    break;
  case qi::StreamColor_Blink:
    os << makeCol(5);
    break;
  case qi::StreamColor_Overline:
    os << makeCol(6);
    break;

  case qi::StreamColor_Black:
    os << makeCol(30, 0);
    break;
  case qi::StreamColor_DarkRed:
    os << makeCol(31, 0);
    break;
  case qi::StreamColor_DarkGreen:
    os << makeCol(32, 0);
    break;
  case qi::StreamColor_Brown:
    os << makeCol(33, 0);
    break;
  case qi::StreamColor_DarkBlue:
    os << makeCol(34, 0);
    break;
  case qi::StreamColor_Purple:
    os << makeCol(35, 0);
    break;
  case qi::StreamColor_Teal:
    os << makeCol(36, 0);
    break;
  case qi::StreamColor_LightGray:
    os << makeCol(37, 0);
    break;

  case qi::StreamColor_DarkGray:
    os << makeCol(30, 1);
    break;
  case qi::StreamColor_Red:
    os << makeCol(31, 1);
    break;
  case qi::StreamColor_Green:
    os << makeCol(32, 1);
    break;
  case qi::StreamColor_Yellow:
    os << makeCol(33, 1);
    break;
  case qi::StreamColor_Blue:
    os << makeCol(34, 1);
    break;
  case qi::StreamColor_Fuchsia:
    os << makeCol(35, 1);
    break;
  case qi::StreamColor_Turquoise:
    os << makeCol(36, 1);
    break;
  case qi::StreamColor_White:
    os << makeCol(37, 1);
    break;
  };
}
#endif

namespace std {

  std::ostream& operator<<(std::ostream& os, qi::StreamColor col)
  {
    if (&os == &(std::cout) && !qi::os::isatty(1))
      return os;
    if (&os == &(std::cerr) && !qi::os::isatty(2))
      return os;
#if defined(__APPLE__) || defined(__linux__)
    posix_print(os, col);
#endif
    return os;
  }

}
<|endoftext|>


<commit_before>#ifndef CLUSTERING_ADMINISTRATION_ISSUES_JSON_HPP_
#define CLUSTERING_ADMINISTRATION_ISSUES_JSON_HPP_

#include <string>

#include "errors.hpp"
#include <boost/uuid/uuid.hpp>

#include "utils.hpp"
#include "http/json/json_adapter.hpp"

enum _issue_type_t {
    VCLOCK_CONFLICT,
    MACHINE_DOWN,
    NAME_CONFLICT_ISSUE,
    PERSISTENCE_ISSUE,
    PINNINGS_SHARDS_MISMATCH
};

class issue_type_t {
public:
    _issue_type_t issue_type;
};

//json adapter concept for issue_type_t
template <class ctx_t>
typename json_adapter_if_t<ctx_t>::json_adapter_map_t get_json_subfields(issue_type_t *, const ctx_t &);

template <class ctx_t>
cJSON *render_as_json(issue_type_t *, const ctx_t &);

template <class ctx_t>
void apply_json_to(cJSON *, issue_type_t *, const ctx_t &);

template <class ctx_t>
void on_subfield_change(issue_type_t *, const ctx_t &);

class issue_json_t {
public:
    bool critical;
    std::string description;
    issue_type_t type;
    ticks_t time;

};

//json adapter concept for issue_json_t
template <class ctx_t>
typename json_adapter_if_t<ctx_t>::json_adapter_map_t get_json_subfields(issue_json_t *, const ctx_t &);

template <class ctx_t>
cJSON *render_as_json(issue_json_t *, const ctx_t &);

template <class ctx_t>
void apply_json_to(cJSON *, issue_json_t *, const ctx_t &);

template <class ctx_t>
void on_subfield_change(issue_json_t *, const ctx_t &);

//A local issue occurs on a single machine
class local_issue_json_t : public issue_json_t {
public:
    boost::uuids::uuid machine;
};

//json adapter concept for local_issue_json_t
template <class ctx_t>
typename json_adapter_if_t<ctx_t>::json_adapter_map_t get_json_subfields(local_issue_json_t *, const ctx_t &);

template <class ctx_t>
cJSON *render_as_json(local_issue_json_t *, const ctx_t &);

template <class ctx_t>
void apply_json_to(cJSON *, local_issue_json_t *, const ctx_t &);

template <class ctx_t>
void on_subfield_change(local_issue_json_t *, const ctx_t &);

#include "clustering/administration/issues/json.tcc"

#endif  // CLUSTERING_ADMINISTRATION_ISSUES_JSON_HPP_
<commit_msg>Added a TODO comment about local_issue_json_t.<commit_after>#ifndef CLUSTERING_ADMINISTRATION_ISSUES_JSON_HPP_
#define CLUSTERING_ADMINISTRATION_ISSUES_JSON_HPP_

#include <string>

#include "errors.hpp"
#include <boost/uuid/uuid.hpp>

#include "utils.hpp"
#include "http/json/json_adapter.hpp"

enum _issue_type_t {
    VCLOCK_CONFLICT,
    MACHINE_DOWN,
    NAME_CONFLICT_ISSUE,
    PERSISTENCE_ISSUE,
    PINNINGS_SHARDS_MISMATCH
};

class issue_type_t {
public:
    _issue_type_t issue_type;
};

//json adapter concept for issue_type_t
template <class ctx_t>
typename json_adapter_if_t<ctx_t>::json_adapter_map_t get_json_subfields(issue_type_t *, const ctx_t &);

template <class ctx_t>
cJSON *render_as_json(issue_type_t *, const ctx_t &);

template <class ctx_t>
void apply_json_to(cJSON *, issue_type_t *, const ctx_t &);

template <class ctx_t>
void on_subfield_change(issue_type_t *, const ctx_t &);

class issue_json_t {
public:
    bool critical;
    std::string description;
    issue_type_t type;
    ticks_t time;

};

//json adapter concept for issue_json_t
template <class ctx_t>
typename json_adapter_if_t<ctx_t>::json_adapter_map_t get_json_subfields(issue_json_t *, const ctx_t &);

template <class ctx_t>
cJSON *render_as_json(issue_json_t *, const ctx_t &);

template <class ctx_t>
void apply_json_to(cJSON *, issue_json_t *, const ctx_t &);

template <class ctx_t>
void on_subfield_change(issue_json_t *, const ctx_t &);

// TODO: Why the fuck is this inheriting instead of using composition?
//A local issue occurs on a single machine
class local_issue_json_t : public issue_json_t {
public:
    boost::uuids::uuid machine;
};

//json adapter concept for local_issue_json_t
template <class ctx_t>
typename json_adapter_if_t<ctx_t>::json_adapter_map_t get_json_subfields(local_issue_json_t *, const ctx_t &);

template <class ctx_t>
cJSON *render_as_json(local_issue_json_t *, const ctx_t &);

template <class ctx_t>
void apply_json_to(cJSON *, local_issue_json_t *, const ctx_t &);

template <class ctx_t>
void on_subfield_change(local_issue_json_t *, const ctx_t &);

#include "clustering/administration/issues/json.tcc"

#endif  // CLUSTERING_ADMINISTRATION_ISSUES_JSON_HPP_
<|endoftext|>