<commit_before>#define _ENABLE_ATOMIC_ALIGNMENT_FIX

#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"
#include "cinder/Text.h"

#include <string>
#include <sstream>
#include <memory>
#include <atomic>

#include "game.h"

using namespace ci;
using namespace ci::app;

using namespace wumpus;

struct Action
{
    enum class Action_type
    {
        none,
        move,
        shoot,
        quit,
        help
    } type{Action_type::none};
    int target;

    Action() = default;

    Action(Action_type type) : type{type}
    {
    }

    Action(Action_type type, int target) : type{type}, target{target}
    {
    }
};

class HuntTheWumpusApp : public App
{
public:
    void setup() override;
    void keyUp(KeyEvent event) override;
    void mouseUp(MouseEvent event) override;
    void update() override;
    void draw() override;

private:
    std::atomic<bool> isEventTriggered{false};
    std::atomic<bool> isTitleScreen{true};
    std::atomic<bool> isGameOver{false};
    std::atomic<bool> isShootEnabled{false};
    std::atomic<Action> nextAction;
    std::atomic<int> arrows;

    std::unique_ptr<Game> game;
    float consoleHeight;

    std::stringstream buffer;
    std::string outputText;

    void initialize();

    void updateAction();
    void updateRoomChange();
    void updateOutputText();

    void drawTitleScreen();
    void drawHUD();
    void drawCave();
    void drawCaveRooms();
    void drawCaveConnections();
    void drawConsole();

    vec2 getCenter(int roomNumber, vec2 caveSize) const;
    float getRadius(vec2 caveSize) const;
    bool isOnCircle(vec2 position, vec2 center, float radius) const;
};

void HuntTheWumpusApp::setup()
{
    game = std::make_unique<Game>(buffer);
    consoleHeight = 120.0f;
    initialize();
}

void HuntTheWumpusApp::initialize()
{
    game->init_hunt();
    game->inform_player_of_hazards();
    arrows = game->get_arrows();
    updateOutputText();
    isShootEnabled = false;
}

void HuntTheWumpusApp::keyUp(KeyEvent event)
{
    isEventTriggered = true;

    auto key = event.getChar();
    switch (key)
    {
    case 'm':
        isShootEnabled = false;
        break;
    case 's':
        isShootEnabled = true;
        break;
    case 'q':
        nextAction = Action(Action::Action_type::quit);
        break;
    case 'h':
        nextAction = Action(Action::Action_type::help);
        break;
    default:
        // Do nothing.
        break;
    }
}

void HuntTheWumpusApp::mouseUp(MouseEvent event)
{
    isEventTriggered = true;

    auto windowSize = gl::getViewport().second;
    vec2 caveSize(windowSize.x, windowSize.y - consoleHeight);

    // Which room did the user click on?
    for (int i = 0; i < num_rooms; ++i)
    {
        auto center = getCenter(i, caveSize);
        auto radius = getRadius(caveSize);

        if (isOnCircle(event.getPos(), center, radius))
        {
            if (isShootEnabled)
                nextAction = Action(Action::Action_type::shoot, i);
            else
                nextAction = Action(Action::Action_type::move, i);

            break;
        }
    }
}

void HuntTheWumpusApp::update()
{
    if (isEventTriggered)
    {
        isEventTriggered = false;

        if (isTitleScreen)
        {
            isTitleScreen = false;
        }
        else if (isGameOver)
        {
            isTitleScreen = true;
            isGameOver = false;
            initialize();
        }
        else
        {
            updateAction();
        }
    }
}

void HuntTheWumpusApp::updateAction()
{
    Action action = nextAction;
    nextAction = Action(Action::Action_type::none);
    switch (action.type)
    {
    case Action::Action_type::none:
    {
        break;
    }
    case Action::Action_type::move:
    {
        auto target = game->get_rooms()[action.target].number;
        if (game->can_move(target))
            game->move(target);
        updateRoomChange();
        break;
    }
    case Action::Action_type::shoot:
    {
        auto target = std::array<int, connections_per_room>{
            game->get_rooms()[action.target].number, -1, -1};
        if (game->can_shoot(target))
        {
            game->shoot(target);
            isShootEnabled = false; // Allow one shot before switching back.
        }
        updateRoomChange();
        break;
    }
    case Action::Action_type::quit:
    {
        game->quit();
        updateRoomChange();
        break;
    }
    case Action::Action_type::help:
    {
        isTitleScreen = true;
        break;
    }
    default:
    {
        throw std::logic_error("Invalid player action");
    }
    }
}

void HuntTheWumpusApp::updateRoomChange()
{
    if (game->is_hunt_over())
    {
        game->end_hunt();
        isGameOver = true;
    }
    else
    {
        game->inform_player_of_hazards();
        arrows = game->get_arrows();
    }
    updateOutputText();
}

void HuntTheWumpusApp::updateOutputText()
{
    outputText = buffer.str();
    buffer.swap(std::stringstream());
}

void HuntTheWumpusApp::draw()
{
    gl::clear();
    if (isTitleScreen)
    {
        drawTitleScreen();
    }
    else
    {
        drawHUD();
        drawCave();
        drawConsole();
    }
}

void HuntTheWumpusApp::drawTitleScreen()
{
    gl::drawString(
        Game::game_info(),
        vec2(0.0f, 0.0f),
        Color(0.0f, 1.0f, 0.0f),
        Font("Consolas", 20));
}

void HuntTheWumpusApp::drawHUD()
{
    std::string value = isShootEnabled ? "SHOOT" : "MOVE";
    value += "\n";
    value += "ARROWS: " + std::to_string(arrows);
    gl::drawString(
        value, vec2(0.0f, 0.0f), Color(0.0f, 1.0f, 0.0f), Font("Consolas", 32));
}

void HuntTheWumpusApp::drawCave()
{
    drawCaveConnections();
    drawCaveRooms();
}

void HuntTheWumpusApp::drawCaveRooms()
{
    auto windowSize = gl::getViewport().second;
    vec2 caveSize(windowSize.x, windowSize.y - consoleHeight);

    auto playerRoom = game->get_player_room();
    auto rooms = game->get_rooms();
    for (int i = 0; i < num_rooms; ++i)
    {
        auto center = getCenter(i, caveSize);
        auto radius = getRadius(caveSize);

        if (rooms[i].number == playerRoom->number)
            gl::color(Color(0.80f, 1.0f, 0.80f));
        else
            gl::color(Color(0.60f, 0.60f, 0.60f));

        gl::drawSolidCircle(center, radius);

        gl::drawString(
            std::to_string(rooms[i].number),
            center,
            Color(0.0f, 0.0f, 0.0f),
            Font("Consolas", radius));
    }
}

void HuntTheWumpusApp::drawCaveConnections()
{
    auto windowSize = gl::getViewport().second;
    vec2 caveSize(windowSize.x, windowSize.y - consoleHeight);

    auto playerRoom = game->get_player_room();
    auto rooms = game->get_rooms();
    for (int i = 0; i < num_rooms; ++i)
    {
        auto center = getCenter(i, caveSize);

        for (int j = 0; j < connections_per_room; ++j)
        {
            gl::color(Color(0.60f, 0.60f, 0.60f));
            gl::drawLine(center, getCenter(room_connections[i][j], caveSize));
        }
    }
}

void HuntTheWumpusApp::drawConsole()
{
    vec2 offset(0.0f, gl::getViewport().second.y - consoleHeight);
    gl::drawString(
        outputText, offset, Color(0.0f, 1.0f, 0.0f), Font("Consolas", 32));
}

vec2 HuntTheWumpusApp::getCenter(int roomNumber, vec2 caveSize) const
{
    auto roomRadius = 3.0f * getRadius(caveSize);
    if (roomNumber < 5)
    {
        roomNumber *= 2;
    }
    else if (roomNumber < 15)
    {
        roomNumber -= 5;
        roomRadius *= 2.0f;
    }
    else
    {
        roomNumber -= 15;
        roomNumber *= 2;
        roomNumber += 1;
        roomRadius *= 3.0f;
    }
    auto x = roomRadius * std::sinf(2.0f * (float) M_PI * roomNumber / 10.0f);
    auto y = roomRadius * std::cosf(2.0f * (float) M_PI * roomNumber / 10.0f);
    return vec2(x, y) + caveSize / 2.0f;
}

float HuntTheWumpusApp::getRadius(vec2 caveSize) const
{
    return std::min(caveSize.x, caveSize.y) / 22.5f;
}

bool HuntTheWumpusApp::isOnCircle(vec2 position, vec2 center, float radius) const
{
    auto delta = position - center;
    return delta.x * delta.x + delta.y * delta.y <= radius * radius;
}

CINDER_APP(HuntTheWumpusApp, RendererGl)
<commit_msg>Added user markings<commit_after>#define _ENABLE_ATOMIC_ALIGNMENT_FIX

#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"
#include "cinder/Text.h"

#include <array>
#include <string>
#include <sstream>
#include <memory>
#include <atomic>

#include "game.h"

using namespace ci;
using namespace ci::app;

using namespace wumpus;

struct Action
{
    enum class Action_type
    {
        none,
        move,
        shoot,
        draw,
        quit,
        help
    } type{Action_type::none};
    int target;

    Action() = default;

    Action(Action_type type) : type{type}
    {
    }

    Action(Action_type type, int target) : type{type}, target{target}
    {
    }
};

class HuntTheWumpusApp : public App
{
public:
    void setup() override;
    void keyUp(KeyEvent event) override;
    void mouseUp(MouseEvent event) override;
    void update() override;
    void draw() override;

private:
    std::atomic<bool> isEventTriggered{false};
    std::atomic<bool> isTitleScreen{true};
    std::atomic<bool> isGameOver{false};
    std::atomic<bool> isShootEnabled{false};
    std::atomic<bool> isDrawEnabled{false};
    std::atomic<Action> nextAction;
    std::atomic<int> arrows;

    std::unique_ptr<Game> game;
    float consoleHeight;

    std::stringstream buffer;
    std::string outputText;

    std::array<bool, num_rooms> markedRooms{false};

    void initialize();

    void updateAction();
    void updateRoomChange();
    void updateOutputText();

    void drawTitleScreen();
    void drawBackground();
    void drawHUD();
    void drawCave();
    void drawCaveRooms();
    void drawCaveConnections();
    void drawConsole();

    vec2 getCenter(int roomNumber, vec2 caveSize) const;
    float getRadius(vec2 caveSize) const;
    bool isOnCircle(vec2 position, vec2 center, float radius) const;
};

void HuntTheWumpusApp::setup()
{
    game = std::make_unique<Game>(buffer);
    consoleHeight = 120.0f;
    initialize();
}

void HuntTheWumpusApp::initialize()
{
    game->init_hunt();
    game->inform_player_of_hazards();
    arrows = game->get_arrows();
    updateOutputText();
    isShootEnabled = false;
    isDrawEnabled = false;
    markedRooms = {false};
}

void HuntTheWumpusApp::keyUp(KeyEvent event)
{
    isEventTriggered = true;

    auto key = event.getChar();
    switch (key)
    {
    case 'm':
        isShootEnabled = false;
        isDrawEnabled = false;
        break;
    case 's':
        isShootEnabled = true;
        isDrawEnabled = false;
        break;
    case 'd':
        isDrawEnabled = !isDrawEnabled;
        break;
    case 'q':
        nextAction = Action(Action::Action_type::quit);
        break;
    case 'h':
        nextAction = Action(Action::Action_type::help);
        break;
    default:
        // Do nothing.
        break;
    }
}

void HuntTheWumpusApp::mouseUp(MouseEvent event)
{
    isEventTriggered = true;

    auto windowSize = gl::getViewport().second;
    vec2 caveSize(windowSize.x, windowSize.y - consoleHeight);

    // Which room did the user click on?
    for (int i = 0; i < num_rooms; ++i)
    {
        auto center = getCenter(i, caveSize);
        auto radius = getRadius(caveSize);

        if (isOnCircle(event.getPos(), center, radius))
        {
            if (isDrawEnabled)
                nextAction = Action(Action::Action_type::draw, i);
            else if (isShootEnabled)
                nextAction = Action(Action::Action_type::shoot, i);
            else
                nextAction = Action(Action::Action_type::move, i);

            break;
        }
    }
}

void HuntTheWumpusApp::update()
{
    if (isEventTriggered)
    {
        isEventTriggered = false;

        if (isTitleScreen)
        {
            isTitleScreen = false;
        }
        else if (isGameOver)
        {
            isTitleScreen = true;
            isGameOver = false;
            initialize();
        }
        else
        {
            updateAction();
        }
    }
}

void HuntTheWumpusApp::updateAction()
{
    Action action = nextAction;
    nextAction = Action(Action::Action_type::none);
    switch (action.type)
    {
    case Action::Action_type::none:
    {
        break;
    }
    case Action::Action_type::move:
    {
        auto target = game->get_rooms()[action.target].number;
        if (game->can_move(target))
            game->move(target);
        updateRoomChange();
        break;
    }
    case Action::Action_type::shoot:
    {
        auto target = std::array<int, connections_per_room>{
            game->get_rooms()[action.target].number, -1, -1};
        if (game->can_shoot(target))
        {
            game->shoot(target);
            isShootEnabled = false; // Allow one shot before switching back.
        }
        updateRoomChange();
        break;
    }
    case Action::Action_type::draw:
    {
        markedRooms[action.target] = !markedRooms[action.target];
        break;
    }
    case Action::Action_type::quit:
    {
        game->quit();
        updateRoomChange();
        break;
    }
    case Action::Action_type::help:
    {
        isTitleScreen = true;
        break;
    }
    default:
    {
        throw std::logic_error("Invalid player action");
    }
    }
}

void HuntTheWumpusApp::updateRoomChange()
{
    if (game->is_hunt_over())
    {
        game->end_hunt();
        isGameOver = true;
    }
    else
    {
        game->inform_player_of_hazards();
        arrows = game->get_arrows();
    }
    updateOutputText();
}

void HuntTheWumpusApp::updateOutputText()
{
    outputText = buffer.str();
    buffer.swap(std::stringstream());
}

void HuntTheWumpusApp::draw()
{
    gl::clear();
    if (isTitleScreen)
    {
        drawTitleScreen();
    }
    else
    {
        drawBackground();
        drawHUD();
        drawCave();
        drawConsole();
    }
}

void HuntTheWumpusApp::drawTitleScreen()
{
    gl::drawString(
        Game::game_info(),
        vec2(0.0f, 0.0f),
        Color(0.0f, 1.0f, 0.0f),
        Font("Consolas", 20));
}

void HuntTheWumpusApp::drawBackground()
{
    if (isGameOver)
    {
        if (game->get_game_state() == Game_state::wumpus_dead)
        {
            gl::clear(Color(0.0f, 0.25f, 0.0f));
        }
        else
        {
            gl::clear(Color(0.25f, 0.0f, 0.0f));
        }
    }
    else if (isDrawEnabled)
    {
        gl::clear(Color(0.2f, 0.2f, 0.2f));
    }
    else if (isShootEnabled)
    {
        gl::clear(Color(0.0f, 0.0f, 0.25f));
    }
}

void HuntTheWumpusApp::drawHUD()
{
    std::string value = isShootEnabled ? "SHOOT" : "MOVE";
    value = isDrawEnabled ? "DRAW" : value;

    value += "\n";
    value += "ARROWS: " + std::to_string(arrows);
    gl::drawString(
        value, vec2(0.0f, 0.0f), Color(0.0f, 1.0f, 0.0f), Font("Consolas", 32));
}

void HuntTheWumpusApp::drawCave()
{
    drawCaveConnections();
    drawCaveRooms();
}

void HuntTheWumpusApp::drawCaveRooms()
{
    auto windowSize = gl::getViewport().second;
    vec2 caveSize(windowSize.x, windowSize.y - consoleHeight);

    auto playerRoom = game->get_player_room();
    auto rooms = game->get_rooms();
    for (int i = 0; i < num_rooms; ++i)
    {
        auto center = getCenter(i, caveSize);
        auto radius = getRadius(caveSize);

        if (rooms[i].number == playerRoom->number)
            gl::color(Color(0.80f, 1.0f, 0.80f));
        else
            gl::color(Color(0.60f, 0.60f, 0.60f));

        gl::drawSolidCircle(center, radius);

        gl::drawString(
            std::to_string(rooms[i].number),
            center,
            Color(0.0f, 0.0f, 0.0f),
            Font("Consolas", radius));

        if (markedRooms[i])
        {
            // Draw an X over the room.
            gl::color(Color(0.0f, 0.0f, 0.0f));
            gl::lineWidth(std::max(radius / 10.0f, 1.0f));

            vec2 v1(radius * 0.707f, radius * 0.707f);
            gl::drawLine(center - v1, center + v1);
            vec2 v2(radius * 0.707f, -radius * 0.707f);
            gl::drawLine(center - v2, center + v2);

            gl::lineWidth(1.0f);
        }
    }
}

void HuntTheWumpusApp::drawCaveConnections()
{
    auto windowSize = gl::getViewport().second;
    vec2 caveSize(windowSize.x, windowSize.y - consoleHeight);

    auto playerRoom = game->get_player_room();
    auto rooms = game->get_rooms();
    for (int i = 0; i < num_rooms; ++i)
    {
        auto center = getCenter(i, caveSize);

        for (int j = 0; j < connections_per_room; ++j)
        {
            gl::color(Color(0.60f, 0.60f, 0.60f));
            gl::drawLine(center, getCenter(room_connections[i][j], caveSize));
        }
    }
}

void HuntTheWumpusApp::drawConsole()
{
    vec2 offset(0.0f, gl::getViewport().second.y - consoleHeight);
    gl::drawString(
        outputText, offset, Color(0.0f, 1.0f, 0.0f), Font("Consolas", 32));
}

vec2 HuntTheWumpusApp::getCenter(int roomNumber, vec2 caveSize) const
{
    auto roomRadius = 3.0f * getRadius(caveSize);
    if (roomNumber < 5)
    {
        roomNumber *= 2;
    }
    else if (roomNumber < 15)
    {
        roomNumber -= 5;
        roomRadius *= 2.0f;
    }
    else
    {
        roomNumber -= 15;
        roomNumber *= 2;
        roomNumber += 1;
        roomRadius *= 3.0f;
    }
    auto x = roomRadius * std::sinf(2.0f * (float) M_PI * roomNumber / 10.0f);
    auto y = roomRadius * std::cosf(2.0f * (float) M_PI * roomNumber / 10.0f);
    return vec2(x, y) + caveSize / 2.0f;
}

float HuntTheWumpusApp::getRadius(vec2 caveSize) const
{
    return std::min(caveSize.x, caveSize.y) / 22.5f;
}

bool HuntTheWumpusApp::isOnCircle(vec2 position, vec2 center, float radius) const
{
    auto delta = position - center;
    return delta.x * delta.x + delta.y * delta.y <= radius * radius;
}

CINDER_APP(HuntTheWumpusApp, RendererGl)
<|endoftext|>


<commit_before>#ifdef WIN32
#include <windows.h>
#endif

#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif

#include <time.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#include "raytracing.h"
#include "mesh.h"
#include "traqueboule.h"
#include "imageWriter.h"

//This is the main application
//Most of the code in here, does not need to be modified.
//It is enough to take a look at the function "drawFrame",
//in case you want to provide your own different drawing functions

Vec3Df MyCameraPosition;

//MyLightPositions stores all the light positions to use
//for the ray tracing. Please notice, the light that is
//used for the real-time rendering is NOT one of these,
//but following the camera instead.
std::vector<Vec3Df> MyLightPositions;

//Main mesh
Mesh MyMesh;

unsigned int WindowSize_X = 800;  // resolution X
unsigned int WindowSize_Y = 800;  // resolution Y

/**
 * Main function, which is drawing an image (frame) on the screen
*/
void drawFrame( )
{
	yourDebugDraw();
}

//animation is called for every image on the screen once
void animate()
{
	MyCameraPosition=getCameraPosition();
	glutPostRedisplay();
}

void display(void);
void reshape(int w, int h);
void keyboard(unsigned char key, int x, int y);
void startRaytracing();

/**
 * Main Programme
 */
int main(int argc, char** argv)
{
    glutInit(&argc, argv);

    //framebuffer setup
    glutInitDisplayMode( GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH );

    // positioning and size of window
    glutInitWindowPosition(200, 100);
    glutInitWindowSize(WindowSize_X,WindowSize_Y);
    glutCreateWindow(argv[0]);

    //initialize viewpoint
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glTranslatef(0,0,-4);
    tbInitTransform();     // This is for the trackball, please ignore
    tbHelp();             // idem
    MyCameraPosition=getCameraPosition();

    //activate the light following the camera
      glEnable( GL_LIGHTING );
      glEnable( GL_LIGHT0 );
      glEnable(GL_COLOR_MATERIAL);
      int LightPos[4] = {0,0,2,0};
      int MatSpec [4] = {1,1,1,1};
      glLightiv(GL_LIGHT0,GL_POSITION,LightPos);

    //normals will be normalized in the graphics pipeline
    glEnable(GL_NORMALIZE);
      //clear color of the background is black.
    glClearColor (0.0, 0.0, 0.0, 0.0);

    // Activate rendering modes
      //activate depth test
    glEnable( GL_DEPTH_TEST );
      //draw front-facing triangles filled
    //and back-facing triangles as wires
      glPolygonMode(GL_FRONT,GL_FILL);
      glPolygonMode(GL_BACK,GL_LINE);
      //interpolate vertex colors over the triangles
    glShadeModel(GL_SMOOTH);

    // glut setup... to ignore
    glutReshapeFunc(reshape);
    glutKeyboardFunc(keyboard);
    glutDisplayFunc(display);
    glutMouseFunc(tbMouseFunc);    // trackball
    glutMotionFunc(tbMotionFunc);  // uses mouse
    glutIdleFunc( animate);

    init();

#if defined(FIFTYRAYS_ONLYTRACE)
    startRaytracing();
#else
	//main loop for glut... this just runs your application
    glutMainLoop();
#endif

    return 0;  // execution never reaches this point
}

/**
 * OpenGL setup - functions do not need to be changed!
 * you can SKIP AHEAD TO THE KEYBOARD FUNCTION
 */
//what to do before drawing an image
 void display(void)
{
	glPushAttrib(GL_ALL_ATTRIB_BITS);//store GL state
    // Effacer tout
    glClear( GL_COLOR_BUFFER_BIT  | GL_DEPTH_BUFFER_BIT); // clear image

    glLoadIdentity();

    tbVisuTransform(); // init trackball

    drawFrame( );    //actually draw

    glutSwapBuffers();//glut internal switch
	glPopAttrib();//return to old GL state
}
//Window changes size
void reshape(int w, int h)
{
    glViewport(0, 0, (GLsizei) w, (GLsizei) h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    //glOrtho (-1.1, 1.1, -1.1,1.1, -1000.0, 1000.0);
    gluPerspective (50, (float)w/h, 0.01, 10);
    glMatrixMode(GL_MODELVIEW);
}

//transform the x, y position on the screen into the corresponding 3D world position
void produceRay(int x_I, int y_I, Vec3Df * origin, Vec3Df * dest)
{
		int viewport[4];
		double modelview[16];
		double projection[16];
		glGetDoublev(GL_MODELVIEW_MATRIX, modelview); //recuperer matrices
		glGetDoublev(GL_PROJECTION_MATRIX, projection); //recuperer matrices
		glGetIntegerv(GL_VIEWPORT, viewport);//viewport
		int y_new = viewport[3] - y_I;

		double x, y, z;

		gluUnProject(x_I, y_new, 0, modelview, projection, viewport, &x, &y, &z);
		origin->p[0]=float(x);
		origin->p[1]=float(y);
		origin->p[2]=float(z);
		gluUnProject(x_I, y_new, 1, modelview, projection, viewport, &x, &y, &z);
		dest->p[0]=float(x);
		dest->p[1]=float(y);
		dest->p[2]=float(z);
}

// react to keyboard input
void keyboard(unsigned char key, int x, int y)
{
    printf("key %d pressed at %d,%d\n",key,x,y);
    fflush(stdout);
    switch (key)
    {
	//add/update a light based on the camera position.
	case 'L':
		MyLightPositions.push_back(getCameraPosition());
		break;
	case 'l':
		MyLightPositions[MyLightPositions.size()-1]=getCameraPosition();
		break;
	case 'r':
	{
		//Pressing r will launch the raytracing.
		cout<<"Raytracing..."<<endl;
    startRaytracing();

		break;
	}
	case 27:     // touche ESC
        exit(0);
    }

	//produce the ray for the current mouse position
	Vec3Df testRayOrigin, testRayDestination;
	produceRay(x, y, &testRayOrigin, &testRayDestination);

	yourKeyboardFunc(key,x,y, testRayOrigin, testRayDestination);
}

void startRaytracing() {
  //Setup an image with the size of the current image.
  Image result(WindowSize_X,WindowSize_Y);

  //produce the rays for each pixel, by first computing
  //the rays for the corners of the frustum.
  Vec3Df origin00, dest00;
  Vec3Df origin01, dest01;
  Vec3Df origin10, dest10;
  Vec3Df origin11, dest11;
  Vec3Df origin, dest;

  produceRay(0,0, &origin00, &dest00);
  produceRay(0,WindowSize_Y-1, &origin01, &dest01);
  produceRay(WindowSize_X-1,0, &origin10, &dest10);
  produceRay(WindowSize_X-1,WindowSize_Y-1, &origin11, &dest11);

  for (unsigned int y=0; y<WindowSize_Y;++y)
  {
//    std::cout << "Tracing row " << y + 1 << "/" << WindowSize_Y << "..." << std::endl;
    for (unsigned int x=0; x<WindowSize_X;++x)
    {
      //produce the rays for each pixel, by interpolating
      //the four rays of the frustum corners.
      float xscale=1.0f-float(x)/(WindowSize_X-1);
      float yscale=1.0f-float(y)/(WindowSize_Y-1);

      origin=yscale*(xscale*origin00+(1-xscale)*origin10)+
        (1-yscale)*(xscale*origin01+(1-xscale)*origin11);
      dest=yscale*(xscale*dest00+(1-xscale)*dest10)+
        (1-yscale)*(xscale*dest01+(1-xscale)*dest11);

      //launch raytracing for the given ray.
      Vec3Df rgb = performRayTracing(origin, dest);
      //store the result in an image
      result.setPixel(x,y, RGBValue(rgb[0], rgb[1], rgb[2]));
    }
  }

  char filename[64];

#if defined(_MSC_VER)
  _snprintf(filename, sizeof(filename), "result-%d.bmp", time(NULL));
#else
  snprintf(filename, sizeof(filename), "result-%d.bmp", time(NULL));
#endif

  result.writeImage(filename);
}
<commit_msg>Implement printing % progress of raytracing every 5%<commit_after>#ifdef WIN32
#include <windows.h>
#endif

#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif

#include <time.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#include "raytracing.h"
#include "mesh.h"
#include "traqueboule.h"
#include "imageWriter.h"

//This is the main application
//Most of the code in here, does not need to be modified.
//It is enough to take a look at the function "drawFrame",
//in case you want to provide your own different drawing functions

Vec3Df MyCameraPosition;

//MyLightPositions stores all the light positions to use
//for the ray tracing. Please notice, the light that is
//used for the real-time rendering is NOT one of these,
//but following the camera instead.
std::vector<Vec3Df> MyLightPositions;

//Main mesh
Mesh MyMesh;

unsigned int WindowSize_X = 800;  // resolution X
unsigned int WindowSize_Y = 800;  // resolution Y

/**
 * Main function, which is drawing an image (frame) on the screen
*/
void drawFrame( )
{
	yourDebugDraw();
}

//animation is called for every image on the screen once
void animate()
{
	MyCameraPosition=getCameraPosition();
	glutPostRedisplay();
}

void display(void);
void reshape(int w, int h);
void keyboard(unsigned char key, int x, int y);
void startRaytracing();

/**
 * Main Programme
 */
int main(int argc, char** argv)
{
    glutInit(&argc, argv);

    //framebuffer setup
    glutInitDisplayMode( GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH );

    // positioning and size of window
    glutInitWindowPosition(200, 100);
    glutInitWindowSize(WindowSize_X,WindowSize_Y);
    glutCreateWindow(argv[0]);

    //initialize viewpoint
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glTranslatef(0,0,-4);
    tbInitTransform();     // This is for the trackball, please ignore
    tbHelp();             // idem
    MyCameraPosition=getCameraPosition();

    //activate the light following the camera
      glEnable( GL_LIGHTING );
      glEnable( GL_LIGHT0 );
      glEnable(GL_COLOR_MATERIAL);
      int LightPos[4] = {0,0,2,0};
      int MatSpec [4] = {1,1,1,1};
      glLightiv(GL_LIGHT0,GL_POSITION,LightPos);

    //normals will be normalized in the graphics pipeline
    glEnable(GL_NORMALIZE);
      //clear color of the background is black.
    glClearColor (0.0, 0.0, 0.0, 0.0);

    // Activate rendering modes
      //activate depth test
    glEnable( GL_DEPTH_TEST );
      //draw front-facing triangles filled
    //and back-facing triangles as wires
      glPolygonMode(GL_FRONT,GL_FILL);
      glPolygonMode(GL_BACK,GL_LINE);
      //interpolate vertex colors over the triangles
    glShadeModel(GL_SMOOTH);

    // glut setup... to ignore
    glutReshapeFunc(reshape);
    glutKeyboardFunc(keyboard);
    glutDisplayFunc(display);
    glutMouseFunc(tbMouseFunc);    // trackball
    glutMotionFunc(tbMotionFunc);  // uses mouse
    glutIdleFunc( animate);

    init();

#if defined(FIFTYRAYS_ONLYTRACE)
    startRaytracing();
#else
	//main loop for glut... this just runs your application
    glutMainLoop();
#endif

    return 0;  // execution never reaches this point
}

/**
 * OpenGL setup - functions do not need to be changed!
 * you can SKIP AHEAD TO THE KEYBOARD FUNCTION
 */
//what to do before drawing an image
 void display(void)
{
	glPushAttrib(GL_ALL_ATTRIB_BITS);//store GL state
    // Effacer tout
    glClear( GL_COLOR_BUFFER_BIT  | GL_DEPTH_BUFFER_BIT); // clear image

    glLoadIdentity();

    tbVisuTransform(); // init trackball

    drawFrame( );    //actually draw

    glutSwapBuffers();//glut internal switch
	glPopAttrib();//return to old GL state
}
//Window changes size
void reshape(int w, int h)
{
    glViewport(0, 0, (GLsizei) w, (GLsizei) h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    //glOrtho (-1.1, 1.1, -1.1,1.1, -1000.0, 1000.0);
    gluPerspective (50, (float)w/h, 0.01, 10);
    glMatrixMode(GL_MODELVIEW);
}

//transform the x, y position on the screen into the corresponding 3D world position
void produceRay(int x_I, int y_I, Vec3Df * origin, Vec3Df * dest)
{
		int viewport[4];
		double modelview[16];
		double projection[16];
		glGetDoublev(GL_MODELVIEW_MATRIX, modelview); //recuperer matrices
		glGetDoublev(GL_PROJECTION_MATRIX, projection); //recuperer matrices
		glGetIntegerv(GL_VIEWPORT, viewport);//viewport
		int y_new = viewport[3] - y_I;

		double x, y, z;

		gluUnProject(x_I, y_new, 0, modelview, projection, viewport, &x, &y, &z);
		origin->p[0]=float(x);
		origin->p[1]=float(y);
		origin->p[2]=float(z);
		gluUnProject(x_I, y_new, 1, modelview, projection, viewport, &x, &y, &z);
		dest->p[0]=float(x);
		dest->p[1]=float(y);
		dest->p[2]=float(z);
}

// react to keyboard input
void keyboard(unsigned char key, int x, int y)
{
    printf("key %d pressed at %d,%d\n",key,x,y);
    fflush(stdout);
    switch (key)
    {
	//add/update a light based on the camera position.
	case 'L':
		MyLightPositions.push_back(getCameraPosition());
		break;
	case 'l':
		MyLightPositions[MyLightPositions.size()-1]=getCameraPosition();
		break;
	case 'r':
	{
		//Pressing r will launch the raytracing.
		cout<<"Raytracing..."<<endl;
    startRaytracing();

		break;
	}
	case 27:     // touche ESC
        exit(0);
    }

	//produce the ray for the current mouse position
	Vec3Df testRayOrigin, testRayDestination;
	produceRay(x, y, &testRayOrigin, &testRayDestination);

	yourKeyboardFunc(key,x,y, testRayOrigin, testRayDestination);
}

void startRaytracing() {
  //Setup an image with the size of the current image.
  Image result(WindowSize_X,WindowSize_Y);

  //produce the rays for each pixel, by first computing
  //the rays for the corners of the frustum.
  Vec3Df origin00, dest00;
  Vec3Df origin01, dest01;
  Vec3Df origin10, dest10;
  Vec3Df origin11, dest11;
  Vec3Df origin, dest;

  produceRay(0,0, &origin00, &dest00);
  produceRay(0,WindowSize_Y-1, &origin01, &dest01);
  produceRay(WindowSize_X-1,0, &origin10, &dest10);
  produceRay(WindowSize_X-1,WindowSize_Y-1, &origin11, &dest11);

  for (unsigned int y=0; y<WindowSize_Y;++y)
  {

    if (y % (WindowSize_Y / 20) == 0) {
      float perc = (float)y / (float)WindowSize_Y;
      std::cout << 100 * perc << "%" << std::endl;
    }

    for (unsigned int x=0; x<WindowSize_X;++x) {
      //produce the rays for each pixel, by interpolating
      //the four rays of the frustum corners.
      float xscale=1.0f-float(x)/(WindowSize_X-1);
      float yscale=1.0f-float(y)/(WindowSize_Y-1);

      origin=yscale*(xscale*origin00+(1-xscale)*origin10)+
        (1-yscale)*(xscale*origin01+(1-xscale)*origin11);
      dest=yscale*(xscale*dest00+(1-xscale)*dest10)+
        (1-yscale)*(xscale*dest01+(1-xscale)*dest11);

      //launch raytracing for the given ray.
      Vec3Df rgb = performRayTracing(origin, dest);
      //store the result in an image
      result.setPixel(x,y, RGBValue(rgb[0], rgb[1], rgb[2]));
    }
  }

  char filename[64];

  #if defined(_MSC_VER)
    _snprintf(filename, sizeof(filename), "result-%d.bmp", time(NULL));
  #else
    snprintf(filename, sizeof(filename), "result-%d.bmp", time(NULL));
  #endif

  result.writeImage(filename);
}
<|endoftext|>


<commit_before>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
#include <stdio.h>
#include <cmath>
#include <cblas.h>
#include <random>
#include <lapacke.h>
const double PI = 3.141592653589793238463;
const double SQRT_1_2PI = 1/sqrt(2*PI);
const double SQRT_1_2 =  1/sqrt(2);

double pdf(double z){
    //if (-0.5*pow(z,2)<-704.8){printf(" pdf underflow");}
    return SQRT_1_2PI*exp(-0.5*pow(z,2));
}
double lpdf(double z){
    //if (-0.5*pow(z,2)<-704.8){printf(" pdf underflow");}
    return log(SQRT_1_2PI) - 0.5*pow(z,2);
}

double cdf(double z){
    //if (-SQRT_1_2*z>26.55){printf(" cdf underflow");}
    return 0.5 * erfc(-SQRT_1_2*z);
}

extern "C" int EI(double* m, double* s, double y, int N, double* R){
    double S;
    double c;
    double p;
    for (int i=0; i<N; i++){
        S = (y-m[i])/s[i];
        c = cdf(S);
        p = pdf(S);
        R[i] = (y-m[i])*c+s[i]*p;
        //printf("\nm: %f s: %f y: %f S: %f cdf: %f pdf: %f",m[i],s[i],y,S,cdf(S),pdf(S));
        //TODO fix EI for values that make pdf and cdf zero
        //if (R[i]==0.){printf("_ei=0 %f %f %f||%f %f %f_[ %f %f %f]\n",y,m[i],s[i],S,pdf(S),cdf(S),log(s[i]),lpdf(S),exp(log(s[i])+lpdf(S)));}
    }
    return 0;
}

extern "C" int lEI(double* m, double* s, double y, int N, double* R){
    double S;
    double c;
    double p;
    for (int i=0; i<N; i++){
        EI(m,s,y,1,&R[i]);
        //TODO this switch to log puts a kink in the curve
        if (R[i]<=0.){

            S = (y-m[i])/s[i];
            R[i] = log(s[i])+lpdf(S);
            //printf("logversion: %f\n",R[i]);
        }
        else{
            //printf("regversion: %f %f\n",R[i], log(R[i]));
            R[i] = log(R[i]);
        }
    }
    return 0;
}

//make m draws from a multivariate Gaussian of size n where the cholesky deom of the covariance is the lower triangular matrix K
//matrix mult means the draws are down the columns of R
extern "C" int drawcov(double* K, int n, double* R, int m){
    std::random_device rand_dev;          // Use random_device to get a random seed.
    std::mt19937 rand_engine(rand_dev()); //seed merseene twister with random number
    std::normal_distribution<double> nmdist(0., 1.); //normal unit dist
    for (int i=0;i<n*m;i++){
        R[i] = nmdist(rand_engine);

    }
    cblas_dtrmm(CblasRowMajor,CblasLeft,CblasLower,CblasNoTrans,CblasNonUnit,n,m,1.,K,n,R,m);
    return 0;

}

//as drawcov but for the original covariance matrix. K is overwritten.
extern "C" int drawk(double* K_in, int n, double* R, int m){
    int j = -19;
    int jitter=0;
    int info = 1;
    std::vector<double>K = std::vector<double>(n*n);
    while (info != 0){
        for (int i=0; i<n; i++){
            for (int j=0; j<n; j++){
                K[i*n+j]=K_in[i*n+j];
            }
            K[i*n+i]+=jitter*pow(10,j);
        }

        info = LAPACKE_dpotrf(LAPACK_ROW_MAJOR,'L',n,&K[0],n);
        j+=1;
        jitter=1;
    }
    if(j>=-17){
        printf("Adding 10e%d diagonal to covariance in drawk\n",j-1);
    }
    drawcov(&K[0],n, &R[0], m);
    return 0;
}<commit_msg>move EI to work for multiple X in logEI<commit_after>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
#include <stdio.h>
#include <cmath>
#include <cblas.h>
#include <random>
#include <lapacke.h>
const double PI = 3.141592653589793238463;
const double SQRT_1_2PI = 1/sqrt(2*PI);
const double SQRT_1_2 =  1/sqrt(2);

double pdf(double z){
    //if (-0.5*pow(z,2)<-704.8){printf(" pdf underflow");}
    return SQRT_1_2PI*exp(-0.5*pow(z,2));
}
double lpdf(double z){
    //if (-0.5*pow(z,2)<-704.8){printf(" pdf underflow");}
    return log(SQRT_1_2PI) - 0.5*pow(z,2);
}

double cdf(double z){
    //if (-SQRT_1_2*z>26.55){printf(" cdf underflow");}
    return 0.5 * erfc(-SQRT_1_2*z);
}

extern "C" int EI(double* m, double* s, double y, int N, double* R){
    double S;
    double c;
    double p;
    for (int i=0; i<N; i++){
        S = (y-m[i])/s[i];
        c = cdf(S);
        p = pdf(S);
        R[i] = (y-m[i])*c+s[i]*p;
        //printf("\nm: %f s: %f y: %f S: %f cdf: %f pdf: %f",m[i],s[i],y,S,cdf(S),pdf(S));
        //TODO fix EI for values that make pdf and cdf zero
        //if (R[i]==0.){printf("_ei=0 %f %f %f||%f %f %f_[ %f %f %f]\n",y,m[i],s[i],S,pdf(S),cdf(S),log(s[i]),lpdf(S),exp(log(s[i])+lpdf(S)));}
    }
    return 0;
}

extern "C" int lEI(double* m, double* s, double y, int N, double* R){
    double S;
    double c;
    double p;
    EI(m,s,y,N,R);
    for (int i=0; i<N; i++){
        //TODO this switch to log puts a kink in the curve
        if (R[i]<=0.){

            S = (y-m[i])/s[i];
            R[i] = log(s[i])+lpdf(S);
            //printf("logversion: %f\n",R[i]);
        }
        else{
            //printf("regversion: %f %f\n",R[i], log(R[i]));
            R[i] = log(R[i]);
        }
    }
    return 0;
}

//make m draws from a multivariate Gaussian of size n where the cholesky deom of the covariance is the lower triangular matrix K
//matrix mult means the draws are down the columns of R
extern "C" int drawcov(double* K, int n, double* R, int m){
    std::random_device rand_dev;          // Use random_device to get a random seed.
    std::mt19937 rand_engine(rand_dev()); //seed merseene twister with random number
    std::normal_distribution<double> nmdist(0., 1.); //normal unit dist
    for (int i=0;i<n*m;i++){
        R[i] = nmdist(rand_engine);

    }
    cblas_dtrmm(CblasRowMajor,CblasLeft,CblasLower,CblasNoTrans,CblasNonUnit,n,m,1.,K,n,R,m);
    return 0;

}

//as drawcov but for the original covariance matrix. K is overwritten.
extern "C" int drawk(double* K_in, int n, double* R, int m){
    int j = -19;
    int jitter=0;
    int info = 1;
    std::vector<double>K = std::vector<double>(n*n);
    while (info != 0){
        for (int i=0; i<n; i++){
            for (int j=0; j<n; j++){
                K[i*n+j]=K_in[i*n+j];
            }
            K[i*n+i]+=jitter*pow(10,j);
        }

        info = LAPACKE_dpotrf(LAPACK_ROW_MAJOR,'L',n,&K[0],n);
        j+=1;
        jitter=1;
    }
    if(j>=-17){
        printf("Adding 10e%d diagonal to covariance in drawk\n",j-1);
    }
    drawcov(&K[0],n, &R[0], m);
    return 0;
}<|endoftext|>


<commit_before>// @(#)root/graf:$Name:  $:$Id: TMultiGraph.cxx,v 1.11 2002/11/06 21:16:43 brun Exp $
// Author: Rene Brun   12/10/2000

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "TROOT.h"
#include "TMultiGraph.h"
#include "TGraph.h"
#include "TH1.h"
#include "TVirtualPad.h"
#include "Riostream.h"

#include <ctype.h>

ClassImp(TMultiGraph)

//______________________________________________________________________________
//
//   A TMultiGraph is a collection of TGraph (or derived) objects
//   Use TMultiGraph::Add to add a new graph to the list.
//   The TMultiGraph owns the objects in the list.
//   Drawing options are the same as for TGraph
//   Example;
//     TGraph *gr1 = new TGraph(...
//     TGraphErrors *gr2 = new TGraphErrors(...
//     TMultiGraph *mg = new TMultiGraph();
//     mg->Add(gr1,"lp");
//     mg->Add(gr2,"cp");
//     mg->Draw("a");
//
//  The drawing option for each TGraph may be specified as an optional
//  second argument of the Add function.
//  If a draw option is specified, it will be used to draw the graph,
//  otherwise the graph will be drawn with the option specified in
//  TMultiGraph::Draw

//______________________________________________________________________________
TMultiGraph::TMultiGraph(): TNamed()
{
// TMultiGraph default constructor

   fGraphs    = 0;
   fHistogram = 0;
   fMaximum   = -1111;
   fMinimum   = -1111;
}

//______________________________________________________________________________
TMultiGraph::TMultiGraph(const char *name, const char *title)
       : TNamed(name,title)
{
// constructor with name and title
   fGraphs    = 0;
   fHistogram = 0;
   fMaximum   = -1111;
   fMinimum   = -1111;
}

//______________________________________________________________________________
TMultiGraph::~TMultiGraph()
{
// TMultiGraph destructor

   if (!fGraphs) return;
   TGraph *g;
   TIter   next(fGraphs);
   while ((g = (TGraph*) next())) {
     g->ResetBit(kMustCleanup);
   }
   fGraphs->Delete();
   delete fGraphs;
   fGraphs = 0;
   delete fHistogram;
   fHistogram = 0;
}

//______________________________________________________________________________
void TMultiGraph::Add(TGraph *graph, Option_t *chopt)
{
   // add a new graph to the list of graphs
   // note that the graph is now owned by the TMultigraph.
   // Deleting the TMultiGraph object will automatically delete the graphs.
   // You should not delete the graphs when the TMultigraph is still active.

   if (!fGraphs) fGraphs = new TList();
   graph->SetBit(kMustCleanup);
   fGraphs->Add(graph,chopt);
}

//______________________________________________________________________________
void TMultiGraph::Browse(TBrowser *)
{
    Draw("alp");
    gPad->Update();
}

//______________________________________________________________________________
Int_t TMultiGraph::DistancetoPrimitive(Int_t px, Int_t py)
{
// Compute distance from point px,py to each graph
//

//*-*- Are we on the axis?
   const Int_t kMaxDiff = 10;
   Int_t distance = 9999;
   if (fHistogram) {
      distance = fHistogram->DistancetoPrimitive(px,py);
      if (distance <= 0) return distance;
   }

//*-*- Loop on the list of graphs
   if (!fGraphs) return distance;
   TGraph *g;
   TIter   next(fGraphs);
   while ((g = (TGraph*) next())) {
      Int_t dist = g->DistancetoPrimitive(px,py);
      if (dist <= 0) return 0;
      if (dist < kMaxDiff) {gPad->SetSelected(g); return dist;}
   }
   return distance;
}

//______________________________________________________________________________
void TMultiGraph::Draw(Option_t *option)
{
//*-*-*-*-*-*-*-*-*-*-*Draw this multigraph with its current attributes*-*-*-*-*-*-*
//*-*                  ==========================================
//
//   Options to draw a graph are described in TGraph::PainGraph
//
//  The drawing option for each TGraph may be specified as an optional
//  second argument of the Add function.
//  If a draw option is specified, it will be used to draw the graph,
//  otherwise the graph will be drawn with the option specified in
//  TMultiGraph::Draw

  AppendPad(option);
}

//______________________________________________________________________________
TH1F *TMultiGraph::GetHistogram() const
{
//    Returns a pointer to the histogram used to draw the axis
//    Takes into account the two following cases.
//       1- option 'A' was specified in TMultiGraph::Draw. Return fHistogram
//       2- user had called TPad::DrawFrame. return pointer to hframe histogram

   if (fHistogram) return fHistogram;
   if (!gPad) return 0;
   gPad->Modified();
   gPad->Update();
   if (fHistogram) return fHistogram;
   TH1F *h1 = (TH1F*)gPad->FindObject("hframe");
   return h1;
}

//______________________________________________________________________________
TAxis *TMultiGraph::GetXaxis() const
{
   // Get x axis of the graph.

   if (!gPad) return 0;
   TH1 *h = GetHistogram();
   if (!h) return 0;
   return h->GetXaxis();
}

//______________________________________________________________________________
TAxis *TMultiGraph::GetYaxis() const
{
   // Get y axis of the graph.

   if (!gPad) return 0;
   TH1 *h = GetHistogram();
   if (!h) return 0;
   return h->GetYaxis();
}

//______________________________________________________________________________
void TMultiGraph::Paint(Option_t *option)
{
// paint all the graphs of this multigraph

  if (fGraphs->GetSize() == 0) return;

  char *l;
  static char chopt[33];
  Int_t nch = strlen(option);
  Int_t i;
  for (i=0;i<nch;i++) chopt[i] = toupper(option[i]);
  chopt[nch] = 0;
  Double_t *x, *y;
  TGraph *g;

  l = strstr(chopt,"A");
  if (l) {
     *l = ' ';
     TIter   next(fGraphs);
     Int_t npt = 100;
     Double_t maximum, minimum, rwxmin, rwxmax, rwymin, rwymax, uxmin, uxmax, dx, dy;
     rwxmin    = gPad->GetUxmin();
     rwxmax    = gPad->GetUxmax();
     rwymin    = gPad->GetUymin();
     rwymax    = gPad->GetUymax();
     char *xtitle = 0;
     char *ytitle = 0;
     Int_t firstx = 0;
     Int_t lastx  = 0;

     if (fHistogram) {
        //cleanup in case of a previous unzoom
        if (fHistogram->GetMinimum() >= fHistogram->GetMaximum()) {
           Int_t nch = strlen(fHistogram->GetXaxis()->GetTitle());
           firstx = fHistogram->GetXaxis()->GetFirst();
           lastx  = fHistogram->GetXaxis()->GetLast();
           if (nch) {
              xtitle = new char[nch+1];
              strcpy(xtitle,fHistogram->GetXaxis()->GetTitle());
           }
           nch = strlen(fHistogram->GetYaxis()->GetTitle());
           if (nch) {
              ytitle = new char[nch+1];
              strcpy(ytitle,fHistogram->GetYaxis()->GetTitle());
           }
           delete fHistogram;
           fHistogram = 0;
        }
     }
     if (fHistogram) {
        minimum = fHistogram->GetYaxis()->GetXmin();
        maximum = fHistogram->GetYaxis()->GetXmax();
        uxmin   = gPad->PadtoX(rwxmin);
        uxmax   = gPad->PadtoX(rwxmax);
     } else {
        rwxmin = 1e100;
        rwxmax = -rwxmin;
        rwymin = rwxmin;
        rwymax = -rwymin;
        while ((g = (TGraph*) next())) {
           Int_t npoints = g->GetN();
           x = g->GetX();
           y = g->GetY();
           for (i=0;i<npoints;i++) {
              if (x[i] < rwxmin) rwxmin = x[i];
              if (x[i] > rwxmax) rwxmax = x[i];
              if (y[i] < rwymin) rwymin = y[i];
              if (y[i] > rwymax) rwymax = y[i];
           }
           g->ComputeRange(rwxmin, rwymin, rwxmax, rwymax);
           if (g->GetN() > npt) npt = g->GetN();
        }
        if (rwxmin == rwxmax) rwxmax += 1.;
        if (rwymin == rwymax) rwymax += 1.;
        dx = 0.05*(rwxmax-rwxmin);
        dy = 0.05*(rwymax-rwymin);
        uxmin    = rwxmin - dx;
        uxmax    = rwxmax + dx;
        minimum  = rwymin - dy;
        maximum  = rwymax + dy;
     }

     if (fMinimum != -1111) rwymin = minimum = fMinimum;
     if (fMaximum != -1111) rwymax = maximum = fMaximum;
     if (uxmin < 0 && rwxmin >= 0) {
        if (gPad->GetLogx()) uxmin = 0.9*rwxmin;
        //else                 uxmin = 0;
     }
     if (uxmax > 0 && rwxmax <= 0) {
        if (gPad->GetLogx()) uxmax = 1.1*rwxmax;
        //else                 uxmax = 0;
     }
     if (minimum < 0 && rwymin >= 0) {
        if(gPad->GetLogy()) minimum = 0.9*rwymin;
        //else                minimum = 0;
     }
     if (maximum > 0 && rwymax <= 0) {
        if(gPad->GetLogy()) maximum = 1.1*rwymax;
        //else                maximum = 0;
     }
     if (minimum <= 0 && gPad->GetLogy()) minimum = 0.001*maximum;
     if (uxmin <= 0 && gPad->GetLogx()) {
        if (uxmax > 1000) uxmin = 1;
        else              uxmin = 0.001*uxmax;
     }
     rwymin = minimum;
     rwymax = maximum;
     if (fHistogram) {
        fHistogram->GetYaxis()->SetLimits(rwymin,rwymax);
     }

//*-*-  Create a temporary histogram to draw the axis
     if (!fHistogram) {
        // the graph is created with at least as many channels as there are points
        // to permit zooming on the full range
        rwxmin = uxmin;
        rwxmax = uxmax;
        fHistogram = new TH1F(GetName(),GetTitle(),npt,rwxmin,rwxmax);
        if (!fHistogram) return;
        fHistogram->SetMinimum(rwymin);
        fHistogram->SetBit(TH1::kNoStats);
        fHistogram->SetMaximum(rwymax);
        fHistogram->GetYaxis()->SetLimits(rwymin,rwymax);
        fHistogram->SetDirectory(0);
        if (xtitle) {fHistogram->GetXaxis()->SetTitle(xtitle); delete [] xtitle;}
        if (ytitle) {fHistogram->GetYaxis()->SetTitle(ytitle); delete [] ytitle;}
        if (firstx != lastx) fHistogram->GetXaxis()->SetRange(firstx,lastx);
     }
     fHistogram->Paint("0");
   }

   if (fGraphs) {
      TObjOptLink *lnk = (TObjOptLink*)fGraphs->FirstLink();
      TObject *obj;

      while (lnk) {
         obj = lnk->GetObject();
         if (strlen(lnk->GetOption())) obj->Paint(lnk->GetOption());
         else                          obj->Paint(chopt);
         lnk = (TObjOptLink*)lnk->Next();
      }
   }
}

//______________________________________________________________________________
void TMultiGraph::Print(Option_t *option) const
{
// Print the list of graphs

   TGraph *g;
   if (fGraphs) {
     TIter   next(fGraphs);
     while ((g = (TGraph*) next())) {
       g->Print(option);
     }
   }
}

//______________________________________________________________________________
void TMultiGraph::RecursiveRemove(TObject *obj)
{
   // Recursively remove this object from a list. Typically implemented
   // by classes that can contain mulitple references to a same object.

   if (!fGraphs) return;
   TObject *objr = fGraphs->Remove(obj);
   if (!objr) return;
   delete fHistogram; fHistogram = 0;
   if (gPad) gPad->Modified();
}

//______________________________________________________________________________
void TMultiGraph::SavePrimitive(ofstream &out, Option_t *option)
{
    // Save primitive as a C++ statement(s) on output stream out

   char quote = '"';
   out<<"   "<<endl;
   if (gROOT->ClassSaved(TMultiGraph::Class())) {
       out<<"   ";
   } else {
       out<<"   TMultiGraph *";
   }
   out<<"multigraph = new TMultiGraph();"<<endl;
   out<<"   multigraph->SetName("<<quote<<GetName()<<quote<<");"<<endl;
   out<<"   multigraph->SetTitle("<<quote<<GetTitle()<<quote<<");"<<endl;

   TGraph *g;
   if (fGraphs) {
     TIter   next(fGraphs);
     while ((g = (TGraph*) next())) {
       g->SavePrimitive(out,"multigraph");
     }
   }
   out<<"   multigraph->Draw("
      <<quote<<option<<quote<<");"<<endl;
}

//______________________________________________________________________________
void TMultiGraph::SetMaximum(Double_t maximum)
{
   fMaximum = maximum;
   if (fHistogram)  fHistogram->SetMaximum(maximum);
}

//______________________________________________________________________________
void TMultiGraph::SetMinimum(Double_t minimum)
{
   fMinimum = minimum;
   if (fHistogram) fHistogram->SetMinimum(minimum);
}
<commit_msg>In TMultiGraph::Paint optimize the computation of the minimum and maximum along y.<commit_after>// @(#)root/graf:$Name:  $:$Id: TMultiGraph.cxx,v 1.12 2003/05/16 13:12:07 brun Exp $
// Author: Rene Brun   12/10/2000

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "TROOT.h"
#include "TMultiGraph.h"
#include "TGraph.h"
#include "TH1.h"
#include "TVirtualPad.h"
#include "Riostream.h"

#include <ctype.h>

ClassImp(TMultiGraph)

//______________________________________________________________________________
//
//   A TMultiGraph is a collection of TGraph (or derived) objects
//   Use TMultiGraph::Add to add a new graph to the list.
//   The TMultiGraph owns the objects in the list.
//   Drawing options are the same as for TGraph
//   Example;
//     TGraph *gr1 = new TGraph(...
//     TGraphErrors *gr2 = new TGraphErrors(...
//     TMultiGraph *mg = new TMultiGraph();
//     mg->Add(gr1,"lp");
//     mg->Add(gr2,"cp");
//     mg->Draw("a");
//
//  The drawing option for each TGraph may be specified as an optional
//  second argument of the Add function.
//  If a draw option is specified, it will be used to draw the graph,
//  otherwise the graph will be drawn with the option specified in
//  TMultiGraph::Draw

//______________________________________________________________________________
TMultiGraph::TMultiGraph(): TNamed()
{
// TMultiGraph default constructor

   fGraphs    = 0;
   fHistogram = 0;
   fMaximum   = -1111;
   fMinimum   = -1111;
}

//______________________________________________________________________________
TMultiGraph::TMultiGraph(const char *name, const char *title)
       : TNamed(name,title)
{
// constructor with name and title
   fGraphs    = 0;
   fHistogram = 0;
   fMaximum   = -1111;
   fMinimum   = -1111;
}

//______________________________________________________________________________
TMultiGraph::~TMultiGraph()
{
// TMultiGraph destructor

   if (!fGraphs) return;
   TGraph *g;
   TIter   next(fGraphs);
   while ((g = (TGraph*) next())) {
     g->ResetBit(kMustCleanup);
   }
   fGraphs->Delete();
   delete fGraphs;
   fGraphs = 0;
   delete fHistogram;
   fHistogram = 0;
}

//______________________________________________________________________________
void TMultiGraph::Add(TGraph *graph, Option_t *chopt)
{
   // add a new graph to the list of graphs
   // note that the graph is now owned by the TMultigraph.
   // Deleting the TMultiGraph object will automatically delete the graphs.
   // You should not delete the graphs when the TMultigraph is still active.

   if (!fGraphs) fGraphs = new TList();
   graph->SetBit(kMustCleanup);
   fGraphs->Add(graph,chopt);
}

//______________________________________________________________________________
void TMultiGraph::Browse(TBrowser *)
{
    Draw("alp");
    gPad->Update();
}

//______________________________________________________________________________
Int_t TMultiGraph::DistancetoPrimitive(Int_t px, Int_t py)
{
// Compute distance from point px,py to each graph
//

//*-*- Are we on the axis?
   const Int_t kMaxDiff = 10;
   Int_t distance = 9999;
   if (fHistogram) {
      distance = fHistogram->DistancetoPrimitive(px,py);
      if (distance <= 0) return distance;
   }

//*-*- Loop on the list of graphs
   if (!fGraphs) return distance;
   TGraph *g;
   TIter   next(fGraphs);
   while ((g = (TGraph*) next())) {
      Int_t dist = g->DistancetoPrimitive(px,py);
      if (dist <= 0) return 0;
      if (dist < kMaxDiff) {gPad->SetSelected(g); return dist;}
   }
   return distance;
}

//______________________________________________________________________________
void TMultiGraph::Draw(Option_t *option)
{
//*-*-*-*-*-*-*-*-*-*-*Draw this multigraph with its current attributes*-*-*-*-*-*-*
//*-*                  ==========================================
//
//   Options to draw a graph are described in TGraph::PainGraph
//
//  The drawing option for each TGraph may be specified as an optional
//  second argument of the Add function.
//  If a draw option is specified, it will be used to draw the graph,
//  otherwise the graph will be drawn with the option specified in
//  TMultiGraph::Draw

  AppendPad(option);
}

//______________________________________________________________________________
TH1F *TMultiGraph::GetHistogram() const
{
//    Returns a pointer to the histogram used to draw the axis
//    Takes into account the two following cases.
//       1- option 'A' was specified in TMultiGraph::Draw. Return fHistogram
//       2- user had called TPad::DrawFrame. return pointer to hframe histogram

   if (fHistogram) return fHistogram;
   if (!gPad) return 0;
   gPad->Modified();
   gPad->Update();
   if (fHistogram) return fHistogram;
   TH1F *h1 = (TH1F*)gPad->FindObject("hframe");
   return h1;
}

//______________________________________________________________________________
TAxis *TMultiGraph::GetXaxis() const
{
   // Get x axis of the graph.

   if (!gPad) return 0;
   TH1 *h = GetHistogram();
   if (!h) return 0;
   return h->GetXaxis();
}

//______________________________________________________________________________
TAxis *TMultiGraph::GetYaxis() const
{
   // Get y axis of the graph.

   if (!gPad) return 0;
   TH1 *h = GetHistogram();
   if (!h) return 0;
   return h->GetYaxis();
}

//______________________________________________________________________________
void TMultiGraph::Paint(Option_t *option)
{
// paint all the graphs of this multigraph

  if (fGraphs->GetSize() == 0) return;

  char *l;
  static char chopt[33];
  Int_t nch = strlen(option);
  Int_t i;
  for (i=0;i<nch;i++) chopt[i] = toupper(option[i]);
  chopt[nch] = 0;
  Double_t *x, *y;
  TGraph *g;

  l = strstr(chopt,"A");
  if (l) {
     *l = ' ';
     TIter   next(fGraphs);
     Int_t npt = 100;
     Double_t maximum, minimum, rwxmin, rwxmax, rwymin, rwymax, uxmin, uxmax, dx, dy;
     rwxmin    = gPad->GetUxmin();
     rwxmax    = gPad->GetUxmax();
     rwymin    = gPad->GetUymin();
     rwymax    = gPad->GetUymax();
     char *xtitle = 0;
     char *ytitle = 0;
     Int_t firstx = 0;
     Int_t lastx  = 0;

     if (fHistogram) {
        //cleanup in case of a previous unzoom
        if (fHistogram->GetMinimum() >= fHistogram->GetMaximum()) {
           Int_t nch = strlen(fHistogram->GetXaxis()->GetTitle());
           firstx = fHistogram->GetXaxis()->GetFirst();
           lastx  = fHistogram->GetXaxis()->GetLast();
           if (nch) {
              xtitle = new char[nch+1];
              strcpy(xtitle,fHistogram->GetXaxis()->GetTitle());
           }
           nch = strlen(fHistogram->GetYaxis()->GetTitle());
           if (nch) {
              ytitle = new char[nch+1];
              strcpy(ytitle,fHistogram->GetYaxis()->GetTitle());
           }
           delete fHistogram;
           fHistogram = 0;
        }
     }
     if (fHistogram) {
        minimum = fHistogram->GetYaxis()->GetXmin();
        maximum = fHistogram->GetYaxis()->GetXmax();
        uxmin   = gPad->PadtoX(rwxmin);
        uxmax   = gPad->PadtoX(rwxmax);
     } else {
        rwxmin = 1e100;
        rwxmax = -rwxmin;
        rwymin = rwxmin;
        rwymax = -rwymin;
        while ((g = (TGraph*) next())) {
           Int_t npoints = g->GetN();
           x = g->GetX();
           y = g->GetY();
           for (i=0;i<npoints;i++) {
              if (x[i] < rwxmin) rwxmin = x[i];
              if (x[i] > rwxmax) rwxmax = x[i];
              if (y[i] < rwymin) rwymin = y[i];
              if (y[i] > rwymax) rwymax = y[i];
           }
           g->ComputeRange(rwxmin, rwymin, rwxmax, rwymax);
           if (g->GetN() > npt) npt = g->GetN();
        }
        if (rwxmin == rwxmax) rwxmax += 1.;
        if (rwymin == rwymax) rwymax += 1.;
        dx = 0.05*(rwxmax-rwxmin);
        dy = 0.05*(rwymax-rwymin);
        uxmin    = rwxmin - dx;
        uxmax    = rwxmax + dx;
        minimum  = rwymin - dy;
        maximum  = rwymax + dy;
        if (minimum < 0 && rwymin >= 0) minimum = 0;
        if (maximum > 0 && rwymax <= 0) maximum = 0;
     }

     if (fMinimum != -1111) rwymin = minimum = fMinimum;
     if (fMaximum != -1111) rwymax = maximum = fMaximum;
     if (uxmin < 0 && rwxmin >= 0) {
        if (gPad->GetLogx()) uxmin = 0.9*rwxmin;
        //else                 uxmin = 0;
     }
     if (uxmax > 0 && rwxmax <= 0) {
        if (gPad->GetLogx()) uxmax = 1.1*rwxmax;
        //else                 uxmax = 0;
     }
     if (minimum < 0 && rwymin >= 0) {
        if(gPad->GetLogy()) minimum = 0.9*rwymin;
        //else                minimum = 0;
     }
     if (maximum > 0 && rwymax <= 0) {
        if(gPad->GetLogy()) maximum = 1.1*rwymax;
        //else                maximum = 0;
     }
     if (minimum <= 0 && gPad->GetLogy()) minimum = 0.001*maximum;
     if (uxmin <= 0 && gPad->GetLogx()) {
        if (uxmax > 1000) uxmin = 1;
        else              uxmin = 0.001*uxmax;
     }
     rwymin = minimum;
     rwymax = maximum;
     if (fHistogram) {
        fHistogram->GetYaxis()->SetLimits(rwymin,rwymax);
     }

//*-*-  Create a temporary histogram to draw the axis
     if (!fHistogram) {
        // the graph is created with at least as many channels as there are points
        // to permit zooming on the full range
        rwxmin = uxmin;
        rwxmax = uxmax;
        fHistogram = new TH1F(GetName(),GetTitle(),npt,rwxmin,rwxmax);
        if (!fHistogram) return;
        fHistogram->SetMinimum(rwymin);
        fHistogram->SetBit(TH1::kNoStats);
        fHistogram->SetMaximum(rwymax);
        fHistogram->GetYaxis()->SetLimits(rwymin,rwymax);
        fHistogram->SetDirectory(0);
        if (xtitle) {fHistogram->GetXaxis()->SetTitle(xtitle); delete [] xtitle;}
        if (ytitle) {fHistogram->GetYaxis()->SetTitle(ytitle); delete [] ytitle;}
        if (firstx != lastx) fHistogram->GetXaxis()->SetRange(firstx,lastx);
     }
     fHistogram->Paint("0");
   }

   if (fGraphs) {
      TObjOptLink *lnk = (TObjOptLink*)fGraphs->FirstLink();
      TObject *obj;

      while (lnk) {
         obj = lnk->GetObject();
         if (strlen(lnk->GetOption())) obj->Paint(lnk->GetOption());
         else                          obj->Paint(chopt);
         lnk = (TObjOptLink*)lnk->Next();
      }
   }
}

//______________________________________________________________________________
void TMultiGraph::Print(Option_t *option) const
{
// Print the list of graphs

   TGraph *g;
   if (fGraphs) {
     TIter   next(fGraphs);
     while ((g = (TGraph*) next())) {
       g->Print(option);
     }
   }
}

//______________________________________________________________________________
void TMultiGraph::RecursiveRemove(TObject *obj)
{
   // Recursively remove this object from a list. Typically implemented
   // by classes that can contain mulitple references to a same object.

   if (!fGraphs) return;
   TObject *objr = fGraphs->Remove(obj);
   if (!objr) return;
   delete fHistogram; fHistogram = 0;
   if (gPad) gPad->Modified();
}

//______________________________________________________________________________
void TMultiGraph::SavePrimitive(ofstream &out, Option_t *option)
{
    // Save primitive as a C++ statement(s) on output stream out

   char quote = '"';
   out<<"   "<<endl;
   if (gROOT->ClassSaved(TMultiGraph::Class())) {
       out<<"   ";
   } else {
       out<<"   TMultiGraph *";
   }
   out<<"multigraph = new TMultiGraph();"<<endl;
   out<<"   multigraph->SetName("<<quote<<GetName()<<quote<<");"<<endl;
   out<<"   multigraph->SetTitle("<<quote<<GetTitle()<<quote<<");"<<endl;

   TGraph *g;
   if (fGraphs) {
     TIter   next(fGraphs);
     while ((g = (TGraph*) next())) {
       g->SavePrimitive(out,"multigraph");
     }
   }
   out<<"   multigraph->Draw("
      <<quote<<option<<quote<<");"<<endl;
}

//______________________________________________________________________________
void TMultiGraph::SetMaximum(Double_t maximum)
{
   fMaximum = maximum;
   if (fHistogram)  fHistogram->SetMaximum(maximum);
}

//______________________________________________________________________________
void TMultiGraph::SetMinimum(Double_t minimum)
{
   fMinimum = minimum;
   if (fHistogram) fHistogram->SetMinimum(minimum);
}
<|endoftext|>


<commit_before>#ifndef NAMELESSGUI_BUTTON_HPP
#define NAMELESSGUI_BUTTON_HPP

#include <string>
#include <SFML/Graphics/Texture.hpp>
#include <SFML/Graphics/RenderTarget.hpp>
#include <SFML/Graphics/Text.hpp>
#include <SFML/Window/Event.hpp>

#include "gui/ng/spritewidget.hpp"

namespace namelessgui
{
	class Button : public SpriteWidget
	{
		public:
			enum STATES
			{
				ES_INACTIVE,
				ES_ACTIVE,
				ES_HOVER
			};

			Button(sf::Window* window, float width, float height, std::string text = "",
				const sf::Texture* textureactive = NULL,
				const sf::Texture* textureinainactive = NULL,
				const sf::Texture* texutrehover = NULL);
			~Button();

			void setText(std::string text);
			std::string getText();
			void setState(STATES state);
			STATES getState() const;

			void setPosition(float x, float y);
			void setPosition(const sf::Vector2f& position);

			void setTextures(const sf::Texture* textureinactive,
				const sf::Texture* textureactive,
				const sf::Texture* texturehover);

			// void draw(sf::RenderTarget& target,
			// 	sf::RenderStates states = sf::RenderStates::Default) const;
			void updateSprite();

		protected:
			sf::Text* text;

			private:
			// Slots
			void leftMousebuttonPressedSlot();
			void mouseEnteredSlot();
			void clickedSlot();
			void mouseLeftSlot();

			STATES state;
			sf::Font* defaultfont;

			const sf::Texture* textures[3];
	};
}

#endif
<commit_msg>Fixed indention in gui/ng/button.hpp.<commit_after>#ifndef NAMELESSGUI_BUTTON_HPP
#define NAMELESSGUI_BUTTON_HPP

#include <string>
#include <SFML/Graphics/Texture.hpp>
#include <SFML/Graphics/RenderTarget.hpp>
#include <SFML/Graphics/Text.hpp>
#include <SFML/Window/Event.hpp>

#include "gui/ng/spritewidget.hpp"

namespace namelessgui
{
	class Button : public SpriteWidget
	{
		public:
			enum STATES
			{
				ES_INACTIVE,
				ES_ACTIVE,
				ES_HOVER
			};

			Button(sf::Window* window, float width, float height, std::string text = "",
				const sf::Texture* textureactive = NULL,
				const sf::Texture* textureinainactive = NULL,
				const sf::Texture* texutrehover = NULL);
			~Button();

			void setText(std::string text);
			std::string getText();
			void setState(STATES state);
			STATES getState() const;

			void setPosition(float x, float y);
			void setPosition(const sf::Vector2f& position);

			void setTextures(const sf::Texture* textureinactive,
				const sf::Texture* textureactive,
				const sf::Texture* texturehover);

			// void draw(sf::RenderTarget& target,
			// 	sf::RenderStates states = sf::RenderStates::Default) const;
			void updateSprite();

		protected:
			sf::Text* text;

		private:
			// Slots
			void leftMousebuttonPressedSlot();
			void mouseEnteredSlot();
			void clickedSlot();
			void mouseLeftSlot();

			STATES state;
			sf::Font* defaultfont;

			const sf::Texture* textures[3];
	};
}

#endif
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the <organization> nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "CppUTest/TestHarness.h"
#include "CppUTest/TestOutput.h"
#include "CppUTest/TestTestingFixture.h"
#include "CppUTestExt/MockCheckedActualCall.h"
#include "CppUTestExt/MockCheckedExpectedCall.h"
#include "CppUTestExt/MockExpectedCallsList.h"
#include "CppUTestExt/MockFailure.h"
#include "MockFailureReporterForTest.h"

#define CHECK_TEST_FAILS_PROPER_WITH_TEXT(text) fixture.checkTestFailsWithProperTestLocation(text, __FILE__, __LINE__)

TEST_GROUP(FakeLongLongs)
{
    TestTestingFixture fixture;
};

#ifndef CPPUTEST_USE_LONG_LONG

static void _actualCallWithFakeLongLongParameter()
{
    cpputest_longlong value = {0};

    mock().expectOneCall("foo").withParameter("bar", 0);
    mock().actualCall("foo").withParameter("bar", value);
    TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE

TEST(FakeLongLongs, ActualCallWithFakeLongLongParameterFAILS)
{
    fixture.runTestWithMethod(_actualCallWithFakeLongLongParameter);
    mock().clear();
    CHECK_TEST_FAILS_PROPER_WITH_TEXT("Long Long type is not supported");
}

static void _actualCallWithFakeUnsignedLongLongParameter()
{
    cpputest_ulonglong value = {0};

    mock().expectOneCall("foo").withParameter("bar", 0);
    mock().actualCall("foo").withParameter("bar", value);
    TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE

TEST(FakeLongLongs, ActualCallWithFakeUnsignedLongLongParameterFAILS)
{
    fixture.runTestWithMethod(_actualCallWithFakeUnsignedLongLongParameter);
    mock().clear();
    CHECK_TEST_FAILS_PROPER_WITH_TEXT("Unsigned Long Long type is not supported");
}

static void _actualCallWithFakeLongLongReturn()
{
    mock().expectOneCall("foo").andReturnValue(0);
    mock().actualCall("foo").returnLongLongIntValue();
    TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE

TEST(FakeLongLongs, ActualCallWithFakeLongLongReturnFAILS)
{
    fixture.runTestWithMethod(_actualCallWithFakeLongLongReturn);
    mock().clear();
    CHECK_TEST_FAILS_PROPER_WITH_TEXT("Long Long type is not supported");
}

static void _actualCallWithFakeUnsignedLongLongReturn()
{
    mock().expectOneCall("foo").andReturnValue(0);
    mock().actualCall("foo").returnUnsignedLongLongIntValue();
    TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE

TEST(FakeLongLongs, ActualCallWithFakeUnsignedLongLongReturnFAILS)
{
    fixture.runTestWithMethod(_actualCallWithFakeUnsignedLongLongReturn);
    mock().clear();
    CHECK_TEST_FAILS_PROPER_WITH_TEXT("Unsigned Long Long type is not supported");
}

static void _expectOneCallWithFakeLongLongParameter()
{
    cpputest_longlong value = {0};

    mock().expectOneCall("foo").withParameter("bar", value);
    mock().actualCall("foo").withParameter("bar", 0);
    TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE

TEST(FakeLongLongs, ExpectedCallWithFakeLongLongParameterFAILS)
{
    fixture.runTestWithMethod(_expectOneCallWithFakeLongLongParameter);
    mock().clear();
    CHECK_TEST_FAILS_PROPER_WITH_TEXT("Long Long type is not supported");
}

static void _expectOneCallWithFakeUnsignedLongLongParameter()
{
    cpputest_ulonglong value = {0};

    mock().expectOneCall("foo").withParameter("bar", value);
    mock().actualCall("foo").withParameter("bar", 0);
    TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE

TEST(FakeLongLongs, ExpectedCallWithFakeUnsignedLongLongParameterFAILS)
{
    fixture.runTestWithMethod(_expectOneCallWithFakeUnsignedLongLongParameter);
    mock().clear();
    CHECK_TEST_FAILS_PROPER_WITH_TEXT("Unsigned Long Long type is not supported");
}

static void _expectOneCallWithFakeLongLongReturn()
{
    cpputest_longlong value = {0};

    mock().expectOneCall("foo").andReturnValue(value);
    mock().actualCall("foo").returnIntValue();
    TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE

TEST(FakeLongLongs, ExpectedCallWithFakeLongLongReturnFAILS)
{
    fixture.runTestWithMethod(_expectOneCallWithFakeLongLongReturn);
    mock().clear();
    CHECK_TEST_FAILS_PROPER_WITH_TEXT("Long Long type is not supported");
}

static void _expectOneCallWithFakeUnsignedLongLongReturn()
{
    cpputest_ulonglong value = {0};

    mock().expectOneCall("foo").andReturnValue(value);
    mock().actualCall("foo").returnIntValue();
    TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE

TEST(FakeLongLongs, ExpectedCallWithFakeUnsignedLongLongReturnFAILS)
{
    fixture.runTestWithMethod(_expectOneCallWithFakeUnsignedLongLongReturn);
    mock().clear();
    CHECK_TEST_FAILS_PROPER_WITH_TEXT("Unsigned Long Long type is not supported");
}

#endif
<commit_msg>Removed unused macro warning<commit_after>/*
 * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the <organization> nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "CppUTest/TestHarness.h"
#include "CppUTest/TestOutput.h"
#include "CppUTest/TestTestingFixture.h"
#include "CppUTestExt/MockCheckedActualCall.h"
#include "CppUTestExt/MockCheckedExpectedCall.h"
#include "CppUTestExt/MockExpectedCallsList.h"
#include "CppUTestExt/MockFailure.h"
#include "MockFailureReporterForTest.h"

TEST_GROUP(FakeLongLongs)
{
    TestTestingFixture fixture;
};

#ifndef CPPUTEST_USE_LONG_LONG

#define CHECK_TEST_FAILS_PROPER_WITH_TEXT(text) fixture.checkTestFailsWithProperTestLocation(text, __FILE__, __LINE__)

static void _actualCallWithFakeLongLongParameter()
{
    cpputest_longlong value = {0};

    mock().expectOneCall("foo").withParameter("bar", 0);
    mock().actualCall("foo").withParameter("bar", value);
    TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE

TEST(FakeLongLongs, ActualCallWithFakeLongLongParameterFAILS)
{
    fixture.runTestWithMethod(_actualCallWithFakeLongLongParameter);
    mock().clear();
    CHECK_TEST_FAILS_PROPER_WITH_TEXT("Long Long type is not supported");
}

static void _actualCallWithFakeUnsignedLongLongParameter()
{
    cpputest_ulonglong value = {0};

    mock().expectOneCall("foo").withParameter("bar", 0);
    mock().actualCall("foo").withParameter("bar", value);
    TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE

TEST(FakeLongLongs, ActualCallWithFakeUnsignedLongLongParameterFAILS)
{
    fixture.runTestWithMethod(_actualCallWithFakeUnsignedLongLongParameter);
    mock().clear();
    CHECK_TEST_FAILS_PROPER_WITH_TEXT("Unsigned Long Long type is not supported");
}

static void _actualCallWithFakeLongLongReturn()
{
    mock().expectOneCall("foo").andReturnValue(0);
    mock().actualCall("foo").returnLongLongIntValue();
    TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE

TEST(FakeLongLongs, ActualCallWithFakeLongLongReturnFAILS)
{
    fixture.runTestWithMethod(_actualCallWithFakeLongLongReturn);
    mock().clear();
    CHECK_TEST_FAILS_PROPER_WITH_TEXT("Long Long type is not supported");
}

static void _actualCallWithFakeUnsignedLongLongReturn()
{
    mock().expectOneCall("foo").andReturnValue(0);
    mock().actualCall("foo").returnUnsignedLongLongIntValue();
    TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE

TEST(FakeLongLongs, ActualCallWithFakeUnsignedLongLongReturnFAILS)
{
    fixture.runTestWithMethod(_actualCallWithFakeUnsignedLongLongReturn);
    mock().clear();
    CHECK_TEST_FAILS_PROPER_WITH_TEXT("Unsigned Long Long type is not supported");
}

static void _expectOneCallWithFakeLongLongParameter()
{
    cpputest_longlong value = {0};

    mock().expectOneCall("foo").withParameter("bar", value);
    mock().actualCall("foo").withParameter("bar", 0);
    TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE

TEST(FakeLongLongs, ExpectedCallWithFakeLongLongParameterFAILS)
{
    fixture.runTestWithMethod(_expectOneCallWithFakeLongLongParameter);
    mock().clear();
    CHECK_TEST_FAILS_PROPER_WITH_TEXT("Long Long type is not supported");
}

static void _expectOneCallWithFakeUnsignedLongLongParameter()
{
    cpputest_ulonglong value = {0};

    mock().expectOneCall("foo").withParameter("bar", value);
    mock().actualCall("foo").withParameter("bar", 0);
    TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE

TEST(FakeLongLongs, ExpectedCallWithFakeUnsignedLongLongParameterFAILS)
{
    fixture.runTestWithMethod(_expectOneCallWithFakeUnsignedLongLongParameter);
    mock().clear();
    CHECK_TEST_FAILS_PROPER_WITH_TEXT("Unsigned Long Long type is not supported");
}

static void _expectOneCallWithFakeLongLongReturn()
{
    cpputest_longlong value = {0};

    mock().expectOneCall("foo").andReturnValue(value);
    mock().actualCall("foo").returnIntValue();
    TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE

TEST(FakeLongLongs, ExpectedCallWithFakeLongLongReturnFAILS)
{
    fixture.runTestWithMethod(_expectOneCallWithFakeLongLongReturn);
    mock().clear();
    CHECK_TEST_FAILS_PROPER_WITH_TEXT("Long Long type is not supported");
}

static void _expectOneCallWithFakeUnsignedLongLongReturn()
{
    cpputest_ulonglong value = {0};

    mock().expectOneCall("foo").andReturnValue(value);
    mock().actualCall("foo").returnIntValue();
    TestTestingFixture::lineExecutedAfterCheck(); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE

TEST(FakeLongLongs, ExpectedCallWithFakeUnsignedLongLongReturnFAILS)
{
    fixture.runTestWithMethod(_expectOneCallWithFakeUnsignedLongLongReturn);
    mock().clear();
    CHECK_TEST_FAILS_PROPER_WITH_TEXT("Unsigned Long Long type is not supported");
}

#endif
<|endoftext|>