<commit_before>#include "Application.h"

Application* Application::_sInst = nullptr;

void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode);
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset);
void mouse_button_callback(GLFWwindow* window, int button, int action, int mode);
void mouse_pos_callback(GLFWwindow* window, double x, double y);

void Application::Run()
{
    Start();
	float prevTime = 0.0f;
    while (!glfwWindowShouldClose(_mWindow.GetWindow()))
    {
		float currTime = glfwGetTime();
		float dt = currTime - prevTime;
		HandleInput(dt);
        Update(dt);
        Render();
		prevTime = currTime;
    }
    Destroy();
}

void Application::Start()
{
    _mWindow.Start();
    _mShader.Start(&_mWindow);
	UI::StartUI(&_mWindow);
    glfwSetKeyCallback(_mWindow.GetWindow(), &key_callback);
    glfwSetMouseButtonCallback(_mWindow.GetWindow(), &mouse_button_callback);
    glfwSetScrollCallback(_mWindow.GetWindow(), &scroll_callback);
    glfwSetCursorPosCallback(_mWindow.GetWindow(), &mouse_pos_callback);

	glfwSetInputMode(_mWindow.GetWindow(), GLFW_CURSOR, GLFW_CURSOR_NORMAL);
	firstMouse = true;

    keysDown.emplace(GLFW_KEY_W, false);
    keysDown.emplace(GLFW_KEY_A, false);
    keysDown.emplace(GLFW_KEY_S, false);
    keysDown.emplace(GLFW_KEY_D, false);
    keysDown.emplace(GLFW_KEY_Q, false);
    keysDown.emplace(GLFW_KEY_E, false);

	keysDown.emplace(GLFW_KEY_H, false);

    // Camera
    glm::vec3 cameraPos    = glm::vec3(0.0f, 0.0f, 2.0f);
    glm::vec3 cameraTarget = glm::vec3(0.0f, 0.0f, 0.0f);
    glm::vec3 up           = glm::vec3(0.0f, 1.0f, 0.0f);

    Camera::instance().Init(&_mWindow, cameraPos, cameraTarget, up);

    // Shaders
	int numShaders = 2;
    std::vector<std::string> vertShaders = {
		"resources/shaders/nmLighting.vert",
        "resources/shaders/passThru.vert",
    };

    std::vector<std::string> fragShaders = {
		"resources/shaders/nmLighting.frag",
        "resources/shaders/passThru.frag",
    };

    for (int i = 0; i < numShaders; i++)
        _mShader.SetupShaders(vertShaders[i], fragShaders[i]);

    // Depth
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    // Load Obj
	_mModels.emplace("Plane", Utils::LoadObj("resources/models/plane.obj"));
	_mModels.emplace("Sun", Utils::LoadObj("resources/models/sun.obj"));
	_mModels.emplace("Earth", Utils::LoadObj("resources/models/earth.obj"));

	_mModels.find("Plane")->second->SetPosition(glm::vec3(3.0f, 0.0f, 0.0f));

	_mModels.find("Sun")->second->SetPosition(glm::vec3(5.0f, 2.0f, 2.0f));
	_mModels.find("Sun")->second->SetScale(glm::vec3(0.5f, 0.5f, 0.5f));

	// Set default to lighting
    _mProg = 1;

	//
	ShowCredits = false;

	// Load lua script
	//_mScriptHost.Load();

	// Physics
	//PhysicsStart();
}

void Application::PhysicsStart()
{
	// Testing Physics System Currently
	glm::vec3 pos(2.0f, 2.0f, 2.0f);
	Cube cube;
	cube.SetPosition(pos);
	cube.Update();
}

void Application::Update(float dt)
{
	_mDeltaTime = dt;

    glfwPollEvents();

	UI::UpdateUI(&_mWindow);

	//printf("%f\n", dt);
	Camera::instance().Update(dt);

	_mModels.find("Earth")->second->SetRotation(0.25f, glm::vec3(0.0f, 1.0f, 0.0f));

	//PhysicsUpdate(dt);
}

void Application::PhysicsUpdate(float dt)
{
	//
	glm::vec3 pos(1.0f, 1.0f, 1.0f), rot(0.0f), scale(2.0f, 2.0f, 2.0f);
	GameObject gobj;
	gobj.SetTransform(pos, rot, scale);
	gobj.Update(_mDeltaTime);
}

void Application::Render()
{
    _mShader.Clear();

	for (auto& model : _mModels)
	{
		if (model.first == "Sun")
			model.second->Render(1, &_mShader);
		else
			model.second->Render(0, &_mShader);
	}

	UI::RenderUI();

    _mShader.Present();
}

void Application::HandleInput(float dt)
{
	if (keysDown[GLFW_KEY_W])
		Camera::instance().HandleMovement(Direction::FORWARD, dt);
	if (keysDown[GLFW_KEY_S])
		Camera::instance().HandleMovement(Direction::BACKWARD, dt);
	if (keysDown[GLFW_KEY_A])
		Camera::instance().HandleMovement(Direction::LEFT, dt);
	if (keysDown[GLFW_KEY_D])
		Camera::instance().HandleMovement(Direction::RIGHT, dt);
	if (keysDown[GLFW_KEY_Q])
		Camera::instance().HandleMovement(Direction::UP, dt);
	if (keysDown[GLFW_KEY_E])
		Camera::instance().HandleMovement(Direction::DOWN, dt);

}

void Application::HandleGLFWKey(GLFWwindow* window, int key, int scancode, int action, int mode)
{
    if (action == GLFW_RELEASE)
    {
        if (keysDown.find(key) != keysDown.end())
        {
            keysDown[key] = false;
        }
    }
    if (action == GLFW_PRESS)
    {
        if (keysDown.find(key) != keysDown.end())
        {
            keysDown[key] = true;
        }
        switch (key)
        {
        case GLFW_KEY_ESCAPE:
        {
			UI::settingsSelected = !UI::settingsSelected;
			break;
        }

        case GLFW_KEY_GRAVE_ACCENT:
        {
            UI::showMainMenuBar = !UI::showMainMenuBar;
            break;
        }

        case GLFW_KEY_F1:
        {
            UI::consoleSelected = !UI::consoleSelected;
            break;
        }

        case GLFW_KEY_F2:
        {
            UI::optionsSelected = !UI::optionsSelected;
            break;
        }

        case GLFW_KEY_F11:
        {
            UI::showTestWindow = !UI::showTestWindow;
            break;
        }
        }
    }

    ImGui_ImplGlfwGL3_KeyCallback(window, key, scancode, action, mode);
}

void Application::HandleGLFWMouseButton(GLFWwindow* window, int button, int action, int mode)
{
	if (button == GLFW_MOUSE_BUTTON_RIGHT && action == GLFW_PRESS)
		rightButtonDown = true;
	else if (button == GLFW_MOUSE_BUTTON_RIGHT && action == GLFW_RELEASE)
		rightButtonDown = false;
		// tell camera that it can do handleRotation

    // Handle mouse button
    ImGui_ImplGlfwGL3_MouseButtonCallback(window, button, action, mode);
}

void Application::HandleGLFWScroll(GLFWwindow* window, double xoffset, double yoffset)
{
    // scroll
    ImGui_ImplGlfwGL3_ScrollCallback(window, xoffset, yoffset);
}

void Application::HandleGLFWMousePos(GLFWwindow* window, double x, double y)
{
	if (firstMouse)
	{
		lastX = x;
		lastY = y;
		firstMouse = false;
	}

	float xoffset = x - lastX;
	float yoffset = lastY - y;

	lastX = x;
	lastY = y;

    // handle mouse pos
	if (rightButtonDown)
		Camera::instance().HandleRotation(xoffset, yoffset);
}

void Application::Destroy()
{
    ImGui_ImplGlfwGL3_Shutdown();
    _mShader.Destroy();
    _mWindow.Destroy();
}

// Not part of the class itself but used for key callback.
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode)
{
    Application::Inst()->HandleGLFWKey(window, key, scancode, action, mode);
}

void mouse_button_callback(GLFWwindow* window, int button, int action, int mode)
{
    Application::Inst()->HandleGLFWMouseButton(window, button, action, mode);
}

void scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
{
    Application::Inst()->HandleGLFWScroll(window, xoffset, yoffset);
}

void mouse_pos_callback(GLFWwindow* window, double x, double y)
{
    Application::Inst()->HandleGLFWMousePos(window, x, y);
}
<commit_msg>Test for slack<commit_after>#include "Application.h"

Application* Application::_sInst = nullptr;

void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode);
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset);
void mouse_button_callback(GLFWwindow* window, int button, int action, int mode);
void mouse_pos_callback(GLFWwindow* window, double x, double y);

void Application::Run()
{
    Start();
	float prevTime = 0.0f;
    while (!glfwWindowShouldClose(_mWindow.GetWindow()))
    {
		float currTime = glfwGetTime();
		float dt = currTime - prevTime;
		HandleInput(dt);
        Update(dt);
        Render();
		prevTime = currTime;
    }
    Destroy();
	//Comment
}

void Application::Start()
{
    _mWindow.Start();
    _mShader.Start(&_mWindow);
	UI::StartUI(&_mWindow);
    glfwSetKeyCallback(_mWindow.GetWindow(), &key_callback);
    glfwSetMouseButtonCallback(_mWindow.GetWindow(), &mouse_button_callback);
    glfwSetScrollCallback(_mWindow.GetWindow(), &scroll_callback);
    glfwSetCursorPosCallback(_mWindow.GetWindow(), &mouse_pos_callback);

	glfwSetInputMode(_mWindow.GetWindow(), GLFW_CURSOR, GLFW_CURSOR_NORMAL);
	firstMouse = true;

    keysDown.emplace(GLFW_KEY_W, false);
    keysDown.emplace(GLFW_KEY_A, false);
    keysDown.emplace(GLFW_KEY_S, false);
    keysDown.emplace(GLFW_KEY_D, false);
    keysDown.emplace(GLFW_KEY_Q, false);
    keysDown.emplace(GLFW_KEY_E, false);

	keysDown.emplace(GLFW_KEY_H, false);

    // Camera
    glm::vec3 cameraPos    = glm::vec3(0.0f, 0.0f, 2.0f);
    glm::vec3 cameraTarget = glm::vec3(0.0f, 0.0f, 0.0f);
    glm::vec3 up           = glm::vec3(0.0f, 1.0f, 0.0f);

    Camera::instance().Init(&_mWindow, cameraPos, cameraTarget, up);

    // Shaders
	int numShaders = 2;
    std::vector<std::string> vertShaders = {
		"resources/shaders/nmLighting.vert",
        "resources/shaders/passThru.vert",
    };

    std::vector<std::string> fragShaders = {
		"resources/shaders/nmLighting.frag",
        "resources/shaders/passThru.frag",
    };

    for (int i = 0; i < numShaders; i++)
        _mShader.SetupShaders(vertShaders[i], fragShaders[i]);

    // Depth
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    // Load Obj
	_mModels.emplace("Plane", Utils::LoadObj("resources/models/plane.obj"));
	_mModels.emplace("Sun", Utils::LoadObj("resources/models/sun.obj"));
	_mModels.emplace("Earth", Utils::LoadObj("resources/models/earth.obj"));

	_mModels.find("Plane")->second->SetPosition(glm::vec3(3.0f, 0.0f, 0.0f));

	_mModels.find("Sun")->second->SetPosition(glm::vec3(5.0f, 2.0f, 2.0f));
	_mModels.find("Sun")->second->SetScale(glm::vec3(0.5f, 0.5f, 0.5f));

	// Set default to lighting
    _mProg = 1;

	//
	ShowCredits = false;

	// Load lua script
	//_mScriptHost.Load();

	// Physics
	//PhysicsStart();
}

void Application::PhysicsStart()
{
	// Testing Physics System Currently
	glm::vec3 pos(2.0f, 2.0f, 2.0f);
	Cube cube;
	cube.SetPosition(pos);
	cube.Update();
}

void Application::Update(float dt)
{
	_mDeltaTime = dt;

    glfwPollEvents();

	UI::UpdateUI(&_mWindow);

	//printf("%f\n", dt);
	Camera::instance().Update(dt);

	_mModels.find("Earth")->second->SetRotation(0.25f, glm::vec3(0.0f, 1.0f, 0.0f));

	//PhysicsUpdate(dt);
}

void Application::PhysicsUpdate(float dt)
{
	//
	glm::vec3 pos(1.0f, 1.0f, 1.0f), rot(0.0f), scale(2.0f, 2.0f, 2.0f);
	GameObject gobj;
	gobj.SetTransform(pos, rot, scale);
	gobj.Update(_mDeltaTime);
}

void Application::Render()
{
    _mShader.Clear();

	for (auto& model : _mModels)
	{
		if (model.first == "Sun")
			model.second->Render(1, &_mShader);
		else
			model.second->Render(0, &_mShader);
	}

	UI::RenderUI();

    _mShader.Present();
}

void Application::HandleInput(float dt)
{
	if (keysDown[GLFW_KEY_W])
		Camera::instance().HandleMovement(Direction::FORWARD, dt);
	if (keysDown[GLFW_KEY_S])
		Camera::instance().HandleMovement(Direction::BACKWARD, dt);
	if (keysDown[GLFW_KEY_A])
		Camera::instance().HandleMovement(Direction::LEFT, dt);
	if (keysDown[GLFW_KEY_D])
		Camera::instance().HandleMovement(Direction::RIGHT, dt);
	if (keysDown[GLFW_KEY_Q])
		Camera::instance().HandleMovement(Direction::UP, dt);
	if (keysDown[GLFW_KEY_E])
		Camera::instance().HandleMovement(Direction::DOWN, dt);

}

void Application::HandleGLFWKey(GLFWwindow* window, int key, int scancode, int action, int mode)
{
    if (action == GLFW_RELEASE)
    {
        if (keysDown.find(key) != keysDown.end())
        {
            keysDown[key] = false;
        }
    }
    if (action == GLFW_PRESS)
    {
        if (keysDown.find(key) != keysDown.end())
        {
            keysDown[key] = true;
        }
        switch (key)
        {
        case GLFW_KEY_ESCAPE:
        {
			UI::settingsSelected = !UI::settingsSelected;
			break;
        }

        case GLFW_KEY_GRAVE_ACCENT:
        {
            UI::showMainMenuBar = !UI::showMainMenuBar;
            break;
        }

        case GLFW_KEY_F1:
        {
            UI::consoleSelected = !UI::consoleSelected;
            break;
        }

        case GLFW_KEY_F2:
        {
            UI::optionsSelected = !UI::optionsSelected;
            break;
        }

        case GLFW_KEY_F11:
        {
            UI::showTestWindow = !UI::showTestWindow;
            break;
        }
        }
    }

    ImGui_ImplGlfwGL3_KeyCallback(window, key, scancode, action, mode);
}

void Application::HandleGLFWMouseButton(GLFWwindow* window, int button, int action, int mode)
{
	if (button == GLFW_MOUSE_BUTTON_RIGHT && action == GLFW_PRESS)
		rightButtonDown = true;
	else if (button == GLFW_MOUSE_BUTTON_RIGHT && action == GLFW_RELEASE)
		rightButtonDown = false;
		// tell camera that it can do handleRotation

    // Handle mouse button
    ImGui_ImplGlfwGL3_MouseButtonCallback(window, button, action, mode);
}

void Application::HandleGLFWScroll(GLFWwindow* window, double xoffset, double yoffset)
{
    // scroll
    ImGui_ImplGlfwGL3_ScrollCallback(window, xoffset, yoffset);
}

void Application::HandleGLFWMousePos(GLFWwindow* window, double x, double y)
{
	if (firstMouse)
	{
		lastX = x;
		lastY = y;
		firstMouse = false;
	}

	float xoffset = x - lastX;
	float yoffset = lastY - y;

	lastX = x;
	lastY = y;

    // handle mouse pos
	if (rightButtonDown)
		Camera::instance().HandleRotation(xoffset, yoffset);
}

void Application::Destroy()
{
    ImGui_ImplGlfwGL3_Shutdown();
    _mShader.Destroy();
    _mWindow.Destroy();
}

// Not part of the class itself but used for key callback.
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode)
{
    Application::Inst()->HandleGLFWKey(window, key, scancode, action, mode);
}

void mouse_button_callback(GLFWwindow* window, int button, int action, int mode)
{
    Application::Inst()->HandleGLFWMouseButton(window, button, action, mode);
}

void scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
{
    Application::Inst()->HandleGLFWScroll(window, xoffset, yoffset);
}

void mouse_pos_callback(GLFWwindow* window, double x, double y)
{
    Application::Inst()->HandleGLFWMousePos(window, x, y);
}
<|endoftext|>


<commit_before>#include "Game.h"
#include <SDL_ttf.h>
#include <string>

Game::Game()
{
	SDL_Init(SDL_INIT_EVERYTHING);
	TTF_Init();
	Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048);
	playerScore = 0;
	AIScore = 0;
	running = true;
}

void Game::playGame()
{
	SDL_DisplayMode currentDisplaySize;
	SDL_GetCurrentDisplayMode(0, &currentDisplaySize);

	playerPaddle = (std::make_unique<Paddle>(20.0f, currentDisplaySize.h / 2.0f - 50.0f, 10, 100));
	AIPaddle = (std::make_unique<Paddle>(currentDisplaySize.w - 30.0f, currentDisplaySize.h / 2.0f - 50.0f, 10, 100));
	ball = ((std::make_unique<Ball>(currentDisplaySize.w / 2.0f, currentDisplaySize.h / 2.0f, 13.0f)));

	Graphics graphics(currentDisplaySize.w, currentDisplaySize.h);
	Input input;
	SDL_Event evt;
	Sound sound;
	Timer timer;

	while(running)
	{
		timer.setTicks();
		getEvent(input, evt, graphics);
	    updateObjects(graphics, sound, input, timer);
		renderObjects(graphics);
	}
}

void Game::getEvent(Input &input, SDL_Event &evt, Graphics &graphics)
{
	input.resetKeys();

	if (SDL_PollEvent(&evt))
	{
		if (evt.type == SDL_KEYDOWN)
		{
			if (evt.key.repeat == 0)
			{
				input.keyPressedEvent(evt);
			}
		}
		else if (evt.type == SDL_KEYUP)
		{
			input.keyReleasedEvent(evt);
		}
		else if (evt.type == SDL_QUIT)
		{
			running = false;
		}
	}

	if (input.isKeyPressed(SDL_SCANCODE_ESCAPE))
	{
		running = false;
	}

	if (input.isKeyPressed(SDL_SCANCODE_SPACE) && !ball->isBallLaunched())
	{
		ball->launchBall();
	}

	if (input.isKeyPressed(SDL_SCANCODE_F11))
	{
		int flags = SDL_GetWindowFlags(graphics.getWindowScreen());

		if (flags & SDL_WINDOW_FULLSCREEN)
		{
			SDL_SetWindowFullscreen(graphics.getWindowScreen(), 0);
		}
		else
			SDL_SetWindowFullscreen(graphics.getWindowScreen(), SDL_WINDOW_FULLSCREEN);
	}
}

void Game::updateObjects(Graphics &graphics, Sound &sound, Input input, Timer timer)
{
	float timeStep = timer.getTicks();

	if(input.isPaddleMovingUp())
	{
		playerPaddle->moveUp(timeStep);
	}
	else if(input.isPaddleMovingDown())
	{
		playerPaddle->moveDown(timeStep, graphics.SCREEN_HEIGHT - 10); // SCREEN_HEIGHT - Height of the bottom rectangle.
	}

	ball->move(timeStep);
	ball->checkForCollision(timeStep, playerPaddle.get(), AIPaddle.get(), sound, graphics.SCREEN_WIDTH, graphics.SCREEN_HEIGHT - 10);
	ball->updateScore(&playerScore, &AIScore, sound, graphics.SCREEN_WIDTH, graphics.SCREEN_HEIGHT);
}

void Game::renderObjects(Graphics &graphics)
{
	std::string playerScoreStr = std::to_string(playerScore);
	std::string AIScoreStr = std::to_string(AIScore);

	int xPlayerPos = (int)playerPaddle->PADDLE_X_POSITION;
	int yPlayerPos = (int)playerPaddle->getYPosition();

	int xAIPos = (int)AIPaddle->PADDLE_X_POSITION;
	int yAIPos = (int)AIPaddle->getYPosition();

	int playerPaddleWidth = playerPaddle->PADDLE_WIDTH;
	int playerPaddleHeight = playerPaddle->PADDLE_HEIGHT;

	int AIPaddleWidth = AIPaddle->PADDLE_WIDTH;
	int AIPaddleHeight = AIPaddle->PADDLE_HEIGHT;

	SDL_Rect playerRect = { xPlayerPos, yPlayerPos, playerPaddleWidth, playerPaddleHeight };
	SDL_Rect AIRect = { xAIPos, yAIPos, AIPaddleWidth, AIPaddleHeight };

	Sint16 ballCenterX = (Sint16)ball->getCenterX();
	Sint16 ballCenterY = (Sint16)ball->getCenterY();
	Sint16 ballRadius = (Sint16)ball->RADIUS;

	graphics.drawToScreen(&playerRect, &AIRect, ballCenterX, ballCenterY, ballRadius, playerScoreStr, AIScoreStr);
}

void Game::quitGame()
{
	Mix_Quit();
	TTF_Quit();
	SDL_Quit();
}
<commit_msg>Update Game.cpp<commit_after>#include "Game.h"
#include <SDL_ttf.h>
#include <string>

Game::Game()
{
	SDL_Init(SDL_INIT_EVERYTHING);
	TTF_Init();
	Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048);
	playerScore = 0;
	AIScore = 0;
	running = true;
}

void Game::playGame()
{
	SDL_DisplayMode currentDisplaySize;
	SDL_GetCurrentDisplayMode(0, &currentDisplaySize);

	playerPaddle = (std::make_unique<Paddle>(20.0f, currentDisplaySize.h / 2.0f - 50.0f, 10, 100));
	AIPaddle = (std::make_unique<Paddle>(currentDisplaySize.w - 30.0f, currentDisplaySize.h / 2.0f - 50.0f, 10, 100));
	ball = ((std::make_unique<Ball>(currentDisplaySize.w / 2.0f, currentDisplaySize.h / 2.0f, 13.0f)));

	Graphics graphics(currentDisplaySize.w, currentDisplaySize.h);
	Input input;
	SDL_Event evt;
	Sound sound;
	Timer timer;

	while(running)
	{
		timer.setTicks();
		getEvent(input, evt, graphics);
	    updateObjects(graphics, sound, input, timer);
		renderObjects(graphics);
	}
}

void Game::getEvent(Input &input, SDL_Event &evt, Graphics &graphics)
{
	input.resetKeys();

	if (SDL_PollEvent(&evt))
	{
		if (evt.type == SDL_KEYDOWN)
		{
			if (evt.key.repeat == 0)
			{
				input.keyPressedEvent(evt);
			}
		}
		else if (evt.type == SDL_KEYUP)
		{
			input.keyReleasedEvent(evt);
		}
		else if (evt.type == SDL_QUIT)
		{
			running = false;
		}
	}

	if (input.isKeyPressed(SDL_SCANCODE_ESCAPE))
	{
		running = false;
	}

	if (input.isKeyPressed(SDL_SCANCODE_SPACE) && !ball->isBallLaunched())
	{
		ball->launchBall();
	}

	if (input.isKeyPressed(SDL_SCANCODE_F11))
	{
		int flags = SDL_GetWindowFlags(graphics.getWindowScreen());

		if (flags & SDL_WINDOW_FULLSCREEN)
		{
			SDL_SetWindowFullscreen(graphics.getWindowScreen(), 0);
		}
		else
			SDL_SetWindowFullscreen(graphics.getWindowScreen(), SDL_WINDOW_FULLSCREEN);
	}
}

void Game::updateObjects(Graphics &graphics, Sound &sound, Input input, Timer timer)
{
	float timeStep = timer.getTicks();

	if(input.isPaddleMovingUp())
	{
		playerPaddle->moveUp(timeStep);
	}
	else if(input.isPaddleMovingDown())
	{
		playerPaddle->moveDown(timeStep, graphics.SCREEN_HEIGHT - 10); // SCREEN_HEIGHT - Height of the bottom rectangle.
	}

	ball->move(timeStep);
	ball->checkForCollision(timeStep, playerPaddle.get(), AIPaddle.get(), sound, graphics.SCREEN_WIDTH, graphics.SCREEN_HEIGHT - 10);
	ball->updateScore(&playerScore, &AIScore, sound, graphics.SCREEN_WIDTH, graphics.SCREEN_HEIGHT);
}

void Game::renderObjects(Graphics &graphics)
{
	std::string playerScoreStr = std::to_string(playerScore);
	std::string AIScoreStr = std::to_string(AIScore);

	graphics.drawToScreen(playerPaddle.get(), AIPaddle.get(), ball.get(), playerScoreStr, AIScoreStr);
}

void Game::quitGame()
{
	Mix_Quit();
	TTF_Quit();
	SDL_Quit();
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2009, Piotr Korzuszek
 * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <stdlib.h>

#include <ClanLib/core.h>
#include <ClanLib/display.h>
#include <ClanLib/application.h>

#if defined(GL1)
#include <ClanLib/gl1.h>
#elif defined(GL2)
#include <ClanLib/gl.h>
#else
#error must define GL1 or GL2
#endif // GL1 || GL2

#include "common/Game.h"
#include "gfx/GameWindow.h"
#include "gfx/DebugLayer.h"
#include "gfx/Stage.h"
#include "gfx/scenes/RaceScene.h"
#include "common/Player.h"
#include "common/Properties.h"
#include "gfx/race/ui/RaceUI.h"
#include "network/client/Client.h"
#include "gfx/scenes/MainMenuScene.h"
#include "logic/race/Level.h"

#if defined(RACE_SCENE_ONLY)
RaceScene *m_raceScene;
#endif // RACE_SCENE_ONLY

class Application
{
	public:
		static int main(const std::vector<CL_String> &args);

#if defined(RACE_SCENE_ONLY)
		static void onInputPressed(const CL_InputEvent &p_event, const CL_InputState &p_state) {
			m_raceScene->onInputPressed(p_event);
		}

		static void onInputReleased(const CL_InputEvent &p_event, const CL_InputState &p_state) {
			m_raceScene->onInputReleased(p_event);
		}

#endif // RACE_SCENE_ONLY
};

// Create global application object:
// You MUST include this line or the application start-up will fail to
// locate your application object.
CL_ClanApplication app(&Application::main);

int Application::main(const std::vector<CL_String> &args)
{

	try {

		// read args properties
		for (std::vector<CL_String>::const_iterator itor = args.begin(); itor != args.end(); ++itor) {
			if (itor->substr(0, 2) == "-P") {
				const std::vector<CL_TempString> parts = CL_StringHelp::split_text(itor->substr(2), "=");

				if (parts.size() != 2) {
					CL_Console::write_line(CL_String8("cannot parse ") + *itor);
					continue;
				}

				Properties::setProperty(parts[0], parts[1]);
			}
		}

		// modules setup
		CL_Console::write_line("initializing");

		CL_SetupCore 	setup_core;
		CL_ConsoleLogger logger;

		cl_log_event("init", "initializing display");
		CL_SetupDisplay setup_display;

		Gfx::Stage::m_width = 800;
		Gfx::Stage::m_height = 600;

		cl_log_event("init", "display will be %1 x %2", Gfx::Stage::m_width, Gfx::Stage::m_height);

		cl_log_event("init", "initializing gui");
		CL_SetupGUI 	setup_gui;

		cl_log_event("init", "initializing network");
		CL_SetupNetwork setup_network;

#if defined(GL1)
		cl_log_event("init", "initializing OpenGL 1.x");
		CL_SetupGL1     setup_gl;

		CL_DisplayWindow displayWindow("Gear", Gfx::Stage::m_width, Gfx::Stage::m_height);
#elif defined(GL2)
		cl_log_event("init", "initializing OpenGL 2.x");
		CL_SetupGL     setup_gl;

		CL_OpenGLWindowDescription displayWindowDescription;

		displayWindowDescription.set_title("Gear");
		displayWindowDescription.set_size(CL_Size(Gfx::Stage::m_width, Gfx::Stage::m_height), false);
		displayWindowDescription.set_multisampling(4);

		CL_DisplayWindow displayWindow(displayWindowDescription);
#endif // GL1 || GL2

#if !defined(RACE_SCENE_ONLY)

		cl_log_event("init", "loading gui components");

		CL_GUIWindowManagerTexture windowManager(displayWindow);

		CL_GUIManager guiManager;
		CL_GUIThemeDefault guiTheme;

		guiManager.set_window_manager(windowManager);

#ifdef GL1
		//  Note - If you are using the GL1 target, you will get a perfomance increase by enabling these 2 lines
		//   It reduces the number of internal CL_FrameBuffer swaps. The GL1 target (OpenGL 1.3), performs this slowly
		//   Setting the texture group here, lets the GUI Texture Window Manager know the optimum texture size of all root components
		CL_TextureGroup texture_group(displayWindow.get_gc(), CL_Size(512, 512));
		windowManager.set_texture_group(texture_group);
#endif // GL1

		CL_ResourceManager guiResources("resources/GUIThemeAeroPacked/resources.xml");
		CL_CSSDocument cssDocument;
		cssDocument.load("resources/GUIThemeAeroPacked/theme.css");

		guiManager.set_css_document(cssDocument);
		guiTheme.set_resources(guiResources);
		guiManager.set_theme(guiTheme);

		// load resources
		cl_log_event("init", "loading general resources");

		CL_ResourceManager generalResources("resources/resources.xml");
		Gfx::Stage::m_resourceManager = &generalResources;

		CL_DisplayWindowDescription guiDesc("Gear");
		guiDesc.set_position(CL_Rect(0, 0, Gfx::Stage::getWidth(), Gfx::Stage::getHeight()), true);

		GameWindow gameWindow(&guiManager, guiDesc);

		// load debug layer
		DebugLayer debugLayer;
		Gfx::Stage::m_debugLayer = &debugLayer;

		cl_log_event("init", "launching main scene");

		MainMenuScene mainMenuScene(&gameWindow);
		Gfx::Stage::pushScene(&mainMenuScene);

		guiManager.exec(true);

#else // !RACE_SCENE_ONLY

		Game &game = Game::getInstance();

		// load resources
		CL_ResourceManager generalResources("resources/resources.xml");
		Gfx::Stage::m_resourceManager = &generalResources;

		// load debug layer
		DebugLayer debugLayer;
		Gfx::Stage::m_debugLayer = &debugLayer;

		Race::Level level;

		level.destroy();
		level.initialize("resources/level.xml");

		RaceScene raceScene(NULL);

		raceScene.destroy();
		raceScene.initialize();

		bool quit = false;

		CL_GraphicContext &gc = displayWindow.get_gc();
		raceScene.load(gc);
		m_raceScene = &raceScene;

		CL_InputDevice &keyboard = displayWindow.get_ic().get_keyboard();

		CL_SlotContainer slots;
		slots.connect_functor(keyboard.sig_key_down(), &Application::onInputPressed);
		slots.connect_functor(keyboard.sig_key_up(), &Application::onInputReleased);

		unsigned lastTime = CL_System::get_time();

		while(!quit) {
			CL_KeepAlive::process();

			const unsigned timeChange = CL_System::get_time() - lastTime;
			lastTime += timeChange;

#if !defined(NDEBUG)
			// apply iteration time change
			static float timeChangeF = 0.0f;
			const int iterSpeed = Properties::getPropertyAsInt("dbg_iterSpeed", 100);

			timeChangeF += timeChange * (iterSpeed / 100.0f);

			if (timeChangeF >= 1.0f) {
				const float total = floor(timeChangeF);
				raceScene.update((unsigned) total);

				timeChangeF -= total;
			}
#else // !NDEBUG
			raceScene.update(timeChange);
#endif // NDEBUG

			raceScene.draw(gc);

			displayWindow.flip();

			// Avoid using 100% CPU in the loop:
			static const int MS_60 = 1000 / 60;
			const int sleepTime = MS_60 - timeChange;

			if (sleepTime > 0) {
				CL_System::sleep(sleepTime);
				CL_KeepAlive::process();
			}

		}

#endif // RACE_SCENE_ONLY

	} catch (CL_Exception e) {
		CL_Console::write_line(e.message);
	}

	CL_Console::write_line("Thanks for playing :-)");

	return 0;
}
<commit_msg>Added forced close action on window close<commit_after>/*
 * Copyright (c) 2009, Piotr Korzuszek
 * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <stdlib.h>

#include <ClanLib/core.h>
#include <ClanLib/display.h>
#include <ClanLib/application.h>

#if defined(GL1)
#include <ClanLib/gl1.h>
#elif defined(GL2)
#include <ClanLib/gl.h>
#else
#error must define GL1 or GL2
#endif // GL1 || GL2

#include "common/Game.h"
#include "gfx/GameWindow.h"
#include "gfx/DebugLayer.h"
#include "gfx/Stage.h"
#include "gfx/scenes/RaceScene.h"
#include "common/Player.h"
#include "common/Properties.h"
#include "gfx/race/ui/RaceUI.h"
#include "network/client/Client.h"
#include "gfx/scenes/MainMenuScene.h"
#include "logic/race/Level.h"

#if defined(RACE_SCENE_ONLY)
RaceScene *m_raceScene;
#endif // RACE_SCENE_ONLY

class Application
{
	public:
		static int main(const std::vector<CL_String> &args);

		static void onWindowClose();

#if defined(RACE_SCENE_ONLY)
		static void onInputPressed(const CL_InputEvent &p_event, const CL_InputState &p_state) {
			m_raceScene->onInputPressed(p_event);
		}

		static void onInputReleased(const CL_InputEvent &p_event, const CL_InputState &p_state) {
			m_raceScene->onInputReleased(p_event);
		}

#endif // RACE_SCENE_ONLY
};

// Create global application object:
// You MUST include this line or the application start-up will fail to
// locate your application object.
CL_ClanApplication app(&Application::main);

int Application::main(const std::vector<CL_String> &args)
{

	try {

		// read args properties
		for (std::vector<CL_String>::const_iterator itor = args.begin(); itor != args.end(); ++itor) {
			if (itor->substr(0, 2) == "-P") {
				const std::vector<CL_TempString> parts = CL_StringHelp::split_text(itor->substr(2), "=");

				if (parts.size() != 2) {
					CL_Console::write_line(CL_String8("cannot parse ") + *itor);
					continue;
				}

				Properties::setProperty(parts[0], parts[1]);
			}
		}

		// modules setup
		CL_Console::write_line("initializing");

		CL_SetupCore 	setup_core;

		CL_ConsoleLogger logger;
		CL_SlotContainer slots;

		cl_log_event("init", "initializing display");
		CL_SetupDisplay setup_display;

		Gfx::Stage::m_width = 800;
		Gfx::Stage::m_height = 600;

		cl_log_event("init", "display will be %1 x %2", Gfx::Stage::m_width, Gfx::Stage::m_height);

		cl_log_event("init", "initializing gui");
		CL_SetupGUI 	setup_gui;

		cl_log_event("init", "initializing network");
		CL_SetupNetwork setup_network;

#if defined(GL1)
		cl_log_event("init", "initializing OpenGL 1.x");
		CL_SetupGL1     setup_gl;

		CL_DisplayWindow displayWindow("Gear", Gfx::Stage::m_width, Gfx::Stage::m_height);
#elif defined(GL2)
		cl_log_event("init", "initializing OpenGL 2.x");
		CL_SetupGL     setup_gl;

		CL_OpenGLWindowDescription displayWindowDescription;

		displayWindowDescription.set_title("Gear");
		displayWindowDescription.set_size(CL_Size(Gfx::Stage::m_width, Gfx::Stage::m_height), false);
		displayWindowDescription.set_multisampling(4);

		CL_DisplayWindow displayWindow(displayWindowDescription);
#endif // GL1 || GL2

		// window close action
		slots.connect_functor(displayWindow.sig_window_close(), &Application::onWindowClose);

#if !defined(RACE_SCENE_ONLY)

		cl_log_event("init", "loading gui components");

		CL_GUIWindowManagerTexture windowManager(displayWindow);

		CL_GUIManager guiManager;
		CL_GUIThemeDefault guiTheme;

		guiManager.set_window_manager(windowManager);

#ifdef GL1
		//  Note - If you are using the GL1 target, you will get a perfomance increase by enabling these 2 lines
		//   It reduces the number of internal CL_FrameBuffer swaps. The GL1 target (OpenGL 1.3), performs this slowly
		//   Setting the texture group here, lets the GUI Texture Window Manager know the optimum texture size of all root components
		CL_TextureGroup texture_group(displayWindow.get_gc(), CL_Size(512, 512));
		windowManager.set_texture_group(texture_group);
#endif // GL1

		CL_ResourceManager guiResources("resources/GUIThemeAeroPacked/resources.xml");
		CL_CSSDocument cssDocument;
		cssDocument.load("resources/GUIThemeAeroPacked/theme.css");

		guiManager.set_css_document(cssDocument);
		guiTheme.set_resources(guiResources);
		guiManager.set_theme(guiTheme);

		// load resources
		cl_log_event("init", "loading general resources");

		CL_ResourceManager generalResources("resources/resources.xml");
		Gfx::Stage::m_resourceManager = &generalResources;

		CL_DisplayWindowDescription guiDesc("Gear");
		guiDesc.set_position(CL_Rect(0, 0, Gfx::Stage::getWidth(), Gfx::Stage::getHeight()), true);

		GameWindow gameWindow(&guiManager, guiDesc);

		// load debug layer
		DebugLayer debugLayer;
		Gfx::Stage::m_debugLayer = &debugLayer;

		cl_log_event("init", "launching main scene");

		MainMenuScene mainMenuScene(&gameWindow);
		Gfx::Stage::pushScene(&mainMenuScene);

		guiManager.exec(true);

#else // !RACE_SCENE_ONLY

		Game &game = Game::getInstance();

		// load resources
		CL_ResourceManager generalResources("resources/resources.xml");
		Gfx::Stage::m_resourceManager = &generalResources;

		// load debug layer
		DebugLayer debugLayer;
		Gfx::Stage::m_debugLayer = &debugLayer;

		Race::Level level;

		level.destroy();
		level.initialize("resources/level.xml");

		RaceScene raceScene(NULL);

		raceScene.destroy();
		raceScene.initialize();

		bool quit = false;

		CL_GraphicContext &gc = displayWindow.get_gc();
		raceScene.load(gc);
		m_raceScene = &raceScene;

		CL_InputDevice &keyboard = displayWindow.get_ic().get_keyboard();

		slots.connect_functor(keyboard.sig_key_down(), &Application::onInputPressed);
		slots.connect_functor(keyboard.sig_key_up(), &Application::onInputReleased);

		unsigned lastTime = CL_System::get_time();

		while(!quit) {
			CL_KeepAlive::process();

			const unsigned timeChange = CL_System::get_time() - lastTime;
			lastTime += timeChange;

#if !defined(NDEBUG)
			// apply iteration time change
			static float timeChangeF = 0.0f;
			const int iterSpeed = Properties::getPropertyAsInt("dbg_iterSpeed", 100);

			timeChangeF += timeChange * (iterSpeed / 100.0f);

			if (timeChangeF >= 1.0f) {
				const float total = floor(timeChangeF);
				raceScene.update((unsigned) total);

				timeChangeF -= total;
			}
#else // !NDEBUG
			raceScene.update(timeChange);
#endif // NDEBUG

			raceScene.draw(gc);

			displayWindow.flip();

			// Avoid using 100% CPU in the loop:
			static const int MS_60 = 1000 / 60;
			const int sleepTime = MS_60 - timeChange;

			if (sleepTime > 0) {
				CL_System::sleep(sleepTime);
				CL_KeepAlive::process();
			}

		}

#endif // RACE_SCENE_ONLY

	} catch (CL_Exception e) {
		CL_Console::write_line(e.message);
	}

	CL_Console::write_line("Thanks for playing :-)");

	return 0;
}

void Application::onWindowClose()
{
	exit(0);
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */
#include <rtl/ustring.hxx>
#include <osl/module.h>
#include <stdio.h>
#define  DECLARE_FN_POINTERS 1
#include "EApi.h"
static const char *eBookLibNames[] = {
    "libebook-1.2.so.14", // bumped again (evolution-3.6)
    "libebook-1.2.so.13", // bumped again (evolution-3.4)
    "libebook-1.2.so.12", // bumped again
    "libebook-1.2.so.10", // bumped again
    "libebook-1.2.so.9",  // evolution-2.8
    "libebook-1.2.so.5",  // evolution-2.4 and 2.6+
    "libebook-1.2.so.3",  // evolution-2.2
    "libebook.so.8"       // evolution-2.0
};

typedef void (*SymbolFunc) (void);

#define SYM_MAP(a) { #a, (SymbolFunc *)&a }
struct ApiMap
{
    const char *sym_name;
    SymbolFunc *ref_value;
};

static ApiMap aCommonApiMap[] =
{
    SYM_MAP( eds_check_version ),
    SYM_MAP( e_contact_field_name ),
    SYM_MAP( e_contact_get ),
    SYM_MAP( e_contact_get_type ),
    SYM_MAP( e_contact_field_id ),
    SYM_MAP( e_book_new ),
    SYM_MAP( e_book_open ),
    SYM_MAP( e_book_get_source ),
    SYM_MAP( e_book_get_contacts ),
    SYM_MAP( e_book_query_field_test ),
    SYM_MAP( e_book_query_and ),
    SYM_MAP( e_book_query_or ),
    SYM_MAP( e_book_query_not ),
    SYM_MAP( e_book_query_ref ),
    SYM_MAP( e_book_query_unref ),
    SYM_MAP( e_book_query_from_string ),
    SYM_MAP( e_book_query_to_string ),
    SYM_MAP( e_book_query_field_exists )
};

//< 3-6 api
static ApiMap aOldApiMap[] =
{
    SYM_MAP( e_book_get_addressbooks ),
    SYM_MAP( e_book_get_uri ),
    SYM_MAP( e_book_authenticate_user ),
    SYM_MAP( e_source_group_peek_base_uri),
    SYM_MAP( e_source_peek_name ),
    SYM_MAP( e_source_get_property ),
    SYM_MAP( e_source_list_peek_groups ),
    SYM_MAP( e_source_group_peek_sources )
};

//>= 3-6 api
static ApiMap aNewApiMap[] =
{
    SYM_MAP( e_source_registry_list_sources ),
    SYM_MAP( e_source_registry_new_sync ),
    SYM_MAP( e_source_has_extension ),
    SYM_MAP( e_source_get_extension ),
    SYM_MAP( e_source_backend_get_backend_name ),
    SYM_MAP( e_source_get_display_name ),
    SYM_MAP( e_source_get_uid ),
    SYM_MAP( e_source_registry_ref_source),
    SYM_MAP( e_book_client_new ),
    SYM_MAP( e_client_open_sync ),
    SYM_MAP( e_client_get_source ),
    SYM_MAP( e_book_client_get_contacts_sync ),
    SYM_MAP( e_client_util_free_object_slist )
};
#undef SYM_MAP

static bool
tryLink( oslModule &aModule, const char *pName, ApiMap *pMap, guint nEntries )
{
    for (guint i = 0; i < nEntries; ++i)
    {
        SymbolFunc aMethod = (SymbolFunc)osl_getFunctionSymbol
            (aModule, OUString::createFromAscii ( pMap[ i ].sym_name ).pData);
        if( !aMethod )
        {
            fprintf( stderr, "Warning: missing symbol '%s' in '%s'\n",
                 pMap[ i ].sym_name, pName );
            return false;
        }
        *pMap[ i ].ref_value = aMethod;
    }
    return true;
}

bool EApiInit()
{
    oslModule aModule;

    for( guint j = 0; j < G_N_ELEMENTS( eBookLibNames ); j++ )
    {
        aModule = osl_loadModule( rtl::OUString::createFromAscii
                                  ( eBookLibNames[ j ] ).pData,
                                  SAL_LOADMODULE_DEFAULT );
        if( aModule)
        {
            if (tryLink( aModule, eBookLibNames[ j ], aCommonApiMap, G_N_ELEMENTS(aCommonApiMap)))
            {
                if (eds_check_version(3, 6, 0) == NULL)
                {
                    if (tryLink( aModule, eBookLibNames[ j ], aNewApiMap, G_N_ELEMENTS(aNewApiMap)))
                        return true;
                }
                else if (tryLink( aModule, eBookLibNames[ j ], aOldApiMap, G_N_ELEMENTS(aOldApiMap)))
                {
                    return true;
                }
            }
            osl_unloadModule( aModule );
        }
    }
    fprintf( stderr, "Can find no compliant libebook client libraries\n" );
    return false;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>evoab2: Avoid G_N_ELEMENTS when loading symbols<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */
#include <rtl/ustring.hxx>
#include <osl/module.h>
#include <stdio.h>
#define  DECLARE_FN_POINTERS 1
#include "EApi.h"
static const char *eBookLibNames[] = {
    "libebook-1.2.so.14", // bumped again (evolution-3.6)
    "libebook-1.2.so.13", // bumped again (evolution-3.4)
    "libebook-1.2.so.12", // bumped again
    "libebook-1.2.so.10", // bumped again
    "libebook-1.2.so.9",  // evolution-2.8
    "libebook-1.2.so.5",  // evolution-2.4 and 2.6+
    "libebook-1.2.so.3",  // evolution-2.2
    "libebook.so.8"       // evolution-2.0
};

typedef void (*SymbolFunc) (void);

#define SYM_MAP(a) { #a, (SymbolFunc *)&a }
struct ApiMap
{
    const char *sym_name;
    SymbolFunc *ref_value;
};

static ApiMap aCommonApiMap[] =
{
    SYM_MAP( eds_check_version ),
    SYM_MAP( e_contact_field_name ),
    SYM_MAP( e_contact_get ),
    SYM_MAP( e_contact_get_type ),
    SYM_MAP( e_contact_field_id ),
    SYM_MAP( e_book_new ),
    SYM_MAP( e_book_open ),
    SYM_MAP( e_book_get_source ),
    SYM_MAP( e_book_get_contacts ),
    SYM_MAP( e_book_query_field_test ),
    SYM_MAP( e_book_query_and ),
    SYM_MAP( e_book_query_or ),
    SYM_MAP( e_book_query_not ),
    SYM_MAP( e_book_query_ref ),
    SYM_MAP( e_book_query_unref ),
    SYM_MAP( e_book_query_from_string ),
    SYM_MAP( e_book_query_to_string ),
    SYM_MAP( e_book_query_field_exists )
};

//< 3-6 api
static ApiMap aOldApiMap[] =
{
    SYM_MAP( e_book_get_addressbooks ),
    SYM_MAP( e_book_get_uri ),
    SYM_MAP( e_book_authenticate_user ),
    SYM_MAP( e_source_group_peek_base_uri),
    SYM_MAP( e_source_peek_name ),
    SYM_MAP( e_source_get_property ),
    SYM_MAP( e_source_list_peek_groups ),
    SYM_MAP( e_source_group_peek_sources )
};

//>= 3-6 api
static ApiMap aNewApiMap[] =
{
    SYM_MAP( e_source_registry_list_sources ),
    SYM_MAP( e_source_registry_new_sync ),
    SYM_MAP( e_source_has_extension ),
    SYM_MAP( e_source_get_extension ),
    SYM_MAP( e_source_backend_get_backend_name ),
    SYM_MAP( e_source_get_display_name ),
    SYM_MAP( e_source_get_uid ),
    SYM_MAP( e_source_registry_ref_source),
    SYM_MAP( e_book_client_new ),
    SYM_MAP( e_client_open_sync ),
    SYM_MAP( e_client_get_source ),
    SYM_MAP( e_book_client_get_contacts_sync ),
    SYM_MAP( e_client_util_free_object_slist )
};
#undef SYM_MAP

template<size_t N> static bool
tryLink( oslModule &aModule, const char *pName, const ApiMap (&pMap)[N])
{
    for (guint i = 0; i < N; ++i)
    {
        SymbolFunc aMethod = (SymbolFunc)osl_getFunctionSymbol
            (aModule, OUString::createFromAscii ( pMap[ i ].sym_name ).pData);
        if( !aMethod )
        {
            fprintf( stderr, "Warning: missing symbol '%s' in '%s'\n",
                 pMap[ i ].sym_name, pName );
            return false;
        }
        *pMap[ i ].ref_value = aMethod;
    }
    return true;
}

bool EApiInit()
{
    oslModule aModule;

    for( guint j = 0; j < G_N_ELEMENTS( eBookLibNames ); j++ )
    {
        aModule = osl_loadModule( rtl::OUString::createFromAscii
                                  ( eBookLibNames[ j ] ).pData,
                                  SAL_LOADMODULE_DEFAULT );
        if( aModule)
        {
            if (tryLink( aModule, eBookLibNames[ j ], aCommonApiMap))
            {
                if (eds_check_version(3, 6, 0) == NULL)
                {
                    if (tryLink( aModule, eBookLibNames[ j ], aNewApiMap))
                        return true;
                }
                else if (tryLink( aModule, eBookLibNames[ j ], aOldApiMap))
                {
                    return true;
                }
            }
            osl_unloadModule( aModule );
        }
    }
    fprintf( stderr, "Can find no compliant libebook client libraries\n" );
    return false;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>#include "mesh_config.h"

// C++ includes
#include <iostream>
#include <vector>
#include <string>
#ifdef HAVE_GETOPT_H
// GCC 2.95.3 (and maybe others) do not include
// getopt.h in unistd.h...  Hower IBM xlC has no
// getopt.h!  This works around that.
#include <getopt.h>
#endif
#include <stdio.h>
#include <fstream>

// Local Includes
#include "libmesh.h"
#include "equation_systems.h"
#include "mesh.h"
#include "perfmon.h"
#include "enum_xdr_mode.h"

/**
 * how to use this, and command line processor
 */
void usage(char *progName)
{
  std::string baseName;
  static std::string helpList =
    "usage:\n"
    "	%s [options] ...\n"
    "\n"
    "options:\n"
    "    -d <dim>                      <dim>-dimensional mesh\n"
    "    -m <string>                   Mesh file name\n"
    "    -l <string>                   Left Equation Systems file name\n"
    "    -r <string>                   Right Equation Systems file name\n"
    "    -t <float>                    threshold\n"
    "    -a                            ASCII format (default)\n"
    "    -b                            binary format\n"
    "    -v                            Verbose\n"
    "    -q                            really quiet\n"
    "    -h                            Print help menu\n"
    "\n"
    "\n"
    " This program is used to compare equation systems to a user-specified\n"
    " threshold.  Equation systems are imported in the libMesh format\n"
    " provided through the read and write methods in class EquationSystems.\n"
    " \n"
    "  ./compare -d 3 -m grid.xda -l leftfile.dat -r rightfile.dat -b -t 1.e-8\n"
    "\n"
    " will read in the mesh grid.xda, the equation systems leftfile.dat and\n"
    " rightfile.dat in binary format and compare systems, and especially the\n"
    " floats stored in vectors.  The comparison is said to be passed when the\n"
    " floating point values agree up to the given threshold.  When no threshold\n"
    " is set the default libMesh tolerance is used.  If neither -a or -b are set,\n"
    " ASCII format is assumed.\n"
    "\n"
    " Direct questions to:\n"
    " benkirk@cfdlab.ae.utexas.edu\n";

  if (progName == NULL)
    baseName = "UNKNOWN";
  else
    baseName = progName;

  fprintf(stderr, helpList.c_str(), baseName.c_str());
  fflush(stderr);

  abort();
};

void process_cmd_line(int argc, char **argv,
		      std::vector<std::string>& names,
		      unsigned int& dim,
		      double& threshold,
		      libMeshEnums::XdrMODE& format,
		      bool& verbose,
		      bool& quiet)
{
  char optionStr[] =
    "d:m:l:r:t:abvq?h";

  int opt;

  bool format_set    = false;
  bool left_name_set = false;

  if (argc < 3)
    usage(argv[0]);

  while ((opt = getopt(argc, argv, optionStr)) != -1)
    {
      switch (opt)
	{

	  /**
	   * Get mesh file name
	   */
	case 'm':
	  {
	    if (names.empty())
	      names.push_back(optarg);
	    else
	      {
		std::cout << "ERROR: Mesh file name must preceed left file name!"
			  << std::endl;
		exit(1);
	      }
	    break;
	  }

	  /**
	   * Get the mesh dimension
	   */
	case 'd':
	  {
	    dim = atoi(optarg);
	    break;
	  }

	  /**
	   * Get left file name
	   */
	case 'l':
	  {
	    if (!left_name_set)
	      {
	        names.push_back(optarg);
		left_name_set = true;
	      }
	    else
	      {
		std::cout << "ERROR: Mesh file name must preceed right file name!"
			  << std::endl;
		exit(1);
	      }
	    break;
	  }

	  /**
	   * Get right file name
	   */
	case 'r':
	  {
	    if ((!names.empty()) && (left_name_set))
	      names.push_back(optarg);
	    else
	      {
		std::cout << "ERROR: Mesh file name and left file name must preceed "
			  << "right file name!"
			  << std::endl;
		exit(1);
	      }
	    break;
	  }

	  /**
	   * Get the comparison threshold
	   */
	case 't':
	  {
	    threshold = atof(optarg);
	    break;
	  }

	  /**
	   * Use ascii format
	   */
	case 'a':
	  {
	    if (format_set)
	      {
		std::cout << "ERROR: Equation system file format already set!"
			  << std::endl;
		exit(1);
	      }
	    else
	      {
		format = libMeshEnums::READ;
		format_set = true;
	      }
	    break;
	  }

	  /**
	   * Use binary format
	   */
	case 'b':
	  {
	    if (format_set)
	      {
		std::cout << "ERROR: Equation system file format already set!"
			  << std::endl;
		exit(1);
	      }
	    else
	      {
	        format = libMeshEnums::DECODE;
		format_set = true;
	      }
	    break;
	  }

	  /**
	   * Be verbose
	   */
	case 'v':
	  {
	    verbose = true;
	    break;
	  }

	  /**
	   * Be totally quiet, no matter what -v says
	   */
	case 'q':
	  {
	    quiet = true;
	    break;
	  }

	case 'h':
	case '?':
	  usage(argv[0]);

	default:
	  return;
	}
    }

}

/**
 * everything that is identical for the systems, and
 * should _not_ go into EquationSystems::compare(),
 * can go in this do_compare().
 */
bool do_compare (EquationSystems& les,
		 EquationSystems& res,
		 double threshold,
		 bool verbose)
{

  if (verbose)
    {
      std::cout	<< "*********   LEFT SYSTEM    *********" << std::endl;
      les.print_info  ();
      std::cout << "*********   RIGHT SYSTEM   *********" << std::endl;
      res.print_info ();
      std::cout << "********* COMPARISON PHASE *********" << std::endl
		<< std::endl;
    }

  /**
   * start comparing
   */
  bool result = les.compare(res, threshold, verbose);
  if (verbose)
    {
      std::cout	<< "*********     FINISHED     *********" << std::endl;
    }
  return result;
}

int main (int argc, char** argv)
{
  libMesh::init (argc, argv);

  // these should better be not contained in the following braces
  bool quiet = false;
  bool are_equal;

  {
    PerfMon perfmon(argv[0]);

    // default values
    std::vector<std::string> names;
    unsigned int dim                = static_cast<unsigned int>(-1);
    double threshold                = TOLERANCE;
    libMeshEnums::XdrMODE format    = libMeshEnums::READ;
    bool verbose                    = false;

    // get commands
    process_cmd_line(argc, argv,
		     names,
		     dim,
		     threshold,
		     format,
		     verbose,
		     quiet);

    if (dim == static_cast<unsigned int>(-1))
      {
	std::cout << "ERROR:  you must specify the dimension on "
		  << "the command line!\n\n"
		  << argv[0] << " -d 3 ... for example\n\n";
	error();
      }

    if (quiet)
      verbose = false;

    if (verbose)
      {
	  std::cout << "Settings:" << std::endl
		    << " dimensionality = " << dim << std::endl
		    << " mesh           = " << names[0] << std::endl
		    << " left system    = " << names[1] << std::endl
		    << " right system   = " << names[2] << std::endl
		    << " threshold      = " << threshold << std::endl
		    << " read format    = " << format << std::endl
		    << std::endl;
      }

    /**
     * build the left and right mesh for left, inut them
     */
    Mesh left_mesh  (dim);
    Mesh right_mesh (dim);

    if (!names.empty())
      {
	left_mesh.read  (names[0]);
	right_mesh.read (names[0]);

	if (verbose)
	  left_mesh.print_info();
      }

    else
      {
	std::cout << "No input specified." << std::endl;
	return 1;
      }

    /**
     * build EquationSystems objects, read them
     */
    EquationSystems left_system  (left_mesh);
    EquationSystems right_system (right_mesh);

    if (names.size() == 3)
      {
	left_system.read  (names[1], format);
	right_system.read (names[2], format);
      }
    else
      {
	std::cout << "Bad input specified." << std::endl;
	error();
      }

    are_equal = do_compare (left_system, right_system, threshold, verbose);

  }

  /**
   * let's see what do_compare found out
   */
  unsigned int our_result;

  if (are_equal)
    {
      if (!quiet)
	  std::cout << std::endl
		    << " Congrat's, up to the defined threshold, the two"
		    << std::endl
		    << " are identical."
		    << std::endl;
      our_result=0;
    }
  else
    {
      if (!quiet)
	  std::cout << std::endl
		    << " Oops, differences occured!"
		    << std::endl
		    << " Use -v to obtain more information where differences occured."
		    << std::endl;
      our_result=1;
    }

//  return libMesh::close();
  return our_result;
}
<commit_msg>include file changed name<commit_after>#include "libmesh_config.h"

// C++ includes
#include <iostream>
#include <vector>
#include <string>
#ifdef HAVE_GETOPT_H
// GCC 2.95.3 (and maybe others) do not include
// getopt.h in unistd.h...  Hower IBM xlC has no
// getopt.h!  This works around that.
#include <getopt.h>
#endif
#include <stdio.h>
#include <fstream>

// Local Includes
#include "libmesh.h"
#include "equation_systems.h"
#include "mesh.h"
#include "perfmon.h"
#include "enum_xdr_mode.h"

/**
 * how to use this, and command line processor
 */
void usage(char *progName)
{
  std::string baseName;
  static std::string helpList =
    "usage:\n"
    "	%s [options] ...\n"
    "\n"
    "options:\n"
    "    -d <dim>                      <dim>-dimensional mesh\n"
    "    -m <string>                   Mesh file name\n"
    "    -l <string>                   Left Equation Systems file name\n"
    "    -r <string>                   Right Equation Systems file name\n"
    "    -t <float>                    threshold\n"
    "    -a                            ASCII format (default)\n"
    "    -b                            binary format\n"
    "    -v                            Verbose\n"
    "    -q                            really quiet\n"
    "    -h                            Print help menu\n"
    "\n"
    "\n"
    " This program is used to compare equation systems to a user-specified\n"
    " threshold.  Equation systems are imported in the libMesh format\n"
    " provided through the read and write methods in class EquationSystems.\n"
    " \n"
    "  ./compare -d 3 -m grid.xda -l leftfile.dat -r rightfile.dat -b -t 1.e-8\n"
    "\n"
    " will read in the mesh grid.xda, the equation systems leftfile.dat and\n"
    " rightfile.dat in binary format and compare systems, and especially the\n"
    " floats stored in vectors.  The comparison is said to be passed when the\n"
    " floating point values agree up to the given threshold.  When no threshold\n"
    " is set the default libMesh tolerance is used.  If neither -a or -b are set,\n"
    " ASCII format is assumed.\n"
    "\n"
    " Direct questions to:\n"
    " benkirk@cfdlab.ae.utexas.edu\n";

  if (progName == NULL)
    baseName = "UNKNOWN";
  else
    baseName = progName;

  fprintf(stderr, helpList.c_str(), baseName.c_str());
  fflush(stderr);

  abort();
};

void process_cmd_line(int argc, char **argv,
		      std::vector<std::string>& names,
		      unsigned int& dim,
		      double& threshold,
		      libMeshEnums::XdrMODE& format,
		      bool& verbose,
		      bool& quiet)
{
  char optionStr[] =
    "d:m:l:r:t:abvq?h";

  int opt;

  bool format_set    = false;
  bool left_name_set = false;

  if (argc < 3)
    usage(argv[0]);

  while ((opt = getopt(argc, argv, optionStr)) != -1)
    {
      switch (opt)
	{

	  /**
	   * Get mesh file name
	   */
	case 'm':
	  {
	    if (names.empty())
	      names.push_back(optarg);
	    else
	      {
		std::cout << "ERROR: Mesh file name must preceed left file name!"
			  << std::endl;
		exit(1);
	      }
	    break;
	  }

	  /**
	   * Get the mesh dimension
	   */
	case 'd':
	  {
	    dim = atoi(optarg);
	    break;
	  }

	  /**
	   * Get left file name
	   */
	case 'l':
	  {
	    if (!left_name_set)
	      {
	        names.push_back(optarg);
		left_name_set = true;
	      }
	    else
	      {
		std::cout << "ERROR: Mesh file name must preceed right file name!"
			  << std::endl;
		exit(1);
	      }
	    break;
	  }

	  /**
	   * Get right file name
	   */
	case 'r':
	  {
	    if ((!names.empty()) && (left_name_set))
	      names.push_back(optarg);
	    else
	      {
		std::cout << "ERROR: Mesh file name and left file name must preceed "
			  << "right file name!"
			  << std::endl;
		exit(1);
	      }
	    break;
	  }

	  /**
	   * Get the comparison threshold
	   */
	case 't':
	  {
	    threshold = atof(optarg);
	    break;
	  }

	  /**
	   * Use ascii format
	   */
	case 'a':
	  {
	    if (format_set)
	      {
		std::cout << "ERROR: Equation system file format already set!"
			  << std::endl;
		exit(1);
	      }
	    else
	      {
		format = libMeshEnums::READ;
		format_set = true;
	      }
	    break;
	  }

	  /**
	   * Use binary format
	   */
	case 'b':
	  {
	    if (format_set)
	      {
		std::cout << "ERROR: Equation system file format already set!"
			  << std::endl;
		exit(1);
	      }
	    else
	      {
	        format = libMeshEnums::DECODE;
		format_set = true;
	      }
	    break;
	  }

	  /**
	   * Be verbose
	   */
	case 'v':
	  {
	    verbose = true;
	    break;
	  }

	  /**
	   * Be totally quiet, no matter what -v says
	   */
	case 'q':
	  {
	    quiet = true;
	    break;
	  }

	case 'h':
	case '?':
	  usage(argv[0]);

	default:
	  return;
	}
    }

}

/**
 * everything that is identical for the systems, and
 * should _not_ go into EquationSystems::compare(),
 * can go in this do_compare().
 */
bool do_compare (EquationSystems& les,
		 EquationSystems& res,
		 double threshold,
		 bool verbose)
{

  if (verbose)
    {
      std::cout	<< "*********   LEFT SYSTEM    *********" << std::endl;
      les.print_info  ();
      std::cout << "*********   RIGHT SYSTEM   *********" << std::endl;
      res.print_info ();
      std::cout << "********* COMPARISON PHASE *********" << std::endl
		<< std::endl;
    }

  /**
   * start comparing
   */
  bool result = les.compare(res, threshold, verbose);
  if (verbose)
    {
      std::cout	<< "*********     FINISHED     *********" << std::endl;
    }
  return result;
}

int main (int argc, char** argv)
{
  libMesh::init (argc, argv);

  // these should better be not contained in the following braces
  bool quiet = false;
  bool are_equal;

  {
    PerfMon perfmon(argv[0]);

    // default values
    std::vector<std::string> names;
    unsigned int dim                = static_cast<unsigned int>(-1);
    double threshold                = TOLERANCE;
    libMeshEnums::XdrMODE format    = libMeshEnums::READ;
    bool verbose                    = false;

    // get commands
    process_cmd_line(argc, argv,
		     names,
		     dim,
		     threshold,
		     format,
		     verbose,
		     quiet);

    if (dim == static_cast<unsigned int>(-1))
      {
	std::cout << "ERROR:  you must specify the dimension on "
		  << "the command line!\n\n"
		  << argv[0] << " -d 3 ... for example\n\n";
	error();
      }

    if (quiet)
      verbose = false;

    if (verbose)
      {
	  std::cout << "Settings:" << std::endl
		    << " dimensionality = " << dim << std::endl
		    << " mesh           = " << names[0] << std::endl
		    << " left system    = " << names[1] << std::endl
		    << " right system   = " << names[2] << std::endl
		    << " threshold      = " << threshold << std::endl
		    << " read format    = " << format << std::endl
		    << std::endl;
      }

    /**
     * build the left and right mesh for left, inut them
     */
    Mesh left_mesh  (dim);
    Mesh right_mesh (dim);

    if (!names.empty())
      {
	left_mesh.read  (names[0]);
	right_mesh.read (names[0]);

	if (verbose)
	  left_mesh.print_info();
      }

    else
      {
	std::cout << "No input specified." << std::endl;
	return 1;
      }

    /**
     * build EquationSystems objects, read them
     */
    EquationSystems left_system  (left_mesh);
    EquationSystems right_system (right_mesh);

    if (names.size() == 3)
      {
	left_system.read  (names[1], format);
	right_system.read (names[2], format);
      }
    else
      {
	std::cout << "Bad input specified." << std::endl;
	error();
      }

    are_equal = do_compare (left_system, right_system, threshold, verbose);

  }

  /**
   * let's see what do_compare found out
   */
  unsigned int our_result;

  if (are_equal)
    {
      if (!quiet)
	  std::cout << std::endl
		    << " Congrat's, up to the defined threshold, the two"
		    << std::endl
		    << " are identical."
		    << std::endl;
      our_result=0;
    }
  else
    {
      if (!quiet)
	  std::cout << std::endl
		    << " Oops, differences occured!"
		    << std::endl
		    << " Use -v to obtain more information where differences occured."
		    << std::endl;
      our_result=1;
    }

//  return libMesh::close();
  return our_result;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: AKeyColumns.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: oj $ $Date: 2001-05-02 12:52:32 $
 *
 *  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 _CONNECTIVITY_ADO_KEYCOLUMNS_HXX_
#define _CONNECTIVITY_ADO_KEYCOLUMNS_HXX_

#ifndef _CONNECTIVITY_SDBCX_COLLECTION_HXX_
#include "connectivity/sdbcx/VCollection.hxx"
#endif

namespace connectivity
{
    namespace ado
    {
        class OKeyColumns : public OColumns
        {
        protected:
            virtual ::com::sun::star::uno::Reference< starcontainer::XNamed > createObject(const ::rtl::OUString& _rName);
            virtual ::com::sun::star::uno::Reference< starbeans::XPropertySet > createEmptyObject();
        public:
            OKeyColumns(    ::cppu::OWeakObject& _rParent,
                            ::osl::Mutex& _rMutex,
                            const TStringVector &_rVector,
                            OTable* _pTable,
                            connectivity::sdbcx::IRefreshableColumns*   _pParent)
                        : OColumns(_rParent,_rMutex,_rVector,_pTable,_pParent)
            {
            }
        };
    }
}
#endif // _CONNECTIVITY_ADO_KEYCOLUMNS_HXX_

<commit_msg>INTEGRATION: CWS ooo19126 (1.3.352); FILE MERGED 2005/09/05 17:25:03 rt 1.3.352.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: AKeyColumns.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 06:52:30 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_ADO_KEYCOLUMNS_HXX_
#define _CONNECTIVITY_ADO_KEYCOLUMNS_HXX_

#ifndef _CONNECTIVITY_SDBCX_COLLECTION_HXX_
#include "connectivity/sdbcx/VCollection.hxx"
#endif

namespace connectivity
{
    namespace ado
    {
        class OKeyColumns : public OColumns
        {
        protected:
            virtual ::com::sun::star::uno::Reference< starcontainer::XNamed > createObject(const ::rtl::OUString& _rName);
            virtual ::com::sun::star::uno::Reference< starbeans::XPropertySet > createEmptyObject();
        public:
            OKeyColumns(    ::cppu::OWeakObject& _rParent,
                            ::osl::Mutex& _rMutex,
                            const TStringVector &_rVector,
                            OTable* _pTable,
                            connectivity::sdbcx::IRefreshableColumns*   _pParent)
                        : OColumns(_rParent,_rMutex,_rVector,_pTable,_pParent)
            {
            }
        };
    }
}
#endif // _CONNECTIVITY_ADO_KEYCOLUMNS_HXX_

<|endoftext|>


<commit_before>
/*the srv file headers_ev3/go_to_goal.h should be of the form

float64 r
float64 al
---
float64 x
float64 y
float64 t

This program enables the robot to trace an arc with the mentioned radius r and arc length al(degrees) passed as request in rosservice call
*/

//Header files required to run ROS
#include <ros.h>
#include <nav_msgs/Odometry.h>
#include <std_msgs/String.h>
#include <geometry_msgs/Twist.h>
#include <tf/transform_broadcaster.h>
#include <tf/tf.h>
#include <headers/arc.h>

//Header files required to run EV3dev
#include <iostream>
#include "ev3dev.h"
#include <thread>
#include <string.h>
#include <math.h>
#include <chrono>
//#include <errno.h>

using namespace std;
using namespace ev3dev;
using headers::arc;

char* ROSSRVR_IP = "192.168.1.11" ;
ros::NodeHandle  nh;
//string ns = "/robot3/";
const float deg2rad = M_PI/180.0;//conversion from degrees to radians
float xc = 0, yc = 0 ,tc_arc = 0; //current co-ordinates
float x = 0.0, y = 0.0, t = 0.0, tarc_offset = 0.0;//dynamic value of co-ordinates
float vx = 0, wt = 0, vl, vr,td = 0,t_error = 0,cerror = 0,tIerror = 0,tDerror = 0, old_t_error = 0, tcovered = 0;//t_error = error in theta
float t_kp = 0 , t_ki = 0 , t_kd = 0 , rt_error = 0, rtd = 0 , t_arc = 0;
char* srvrIP;
motor left_motor = OUTPUT_B, right_motor = OUTPUT_C;
string left_motor_port, right_motor_port, sensor_port ;
sensor gsense = INPUT_4;
float R=0.03,L = 0.12;//Radius of the whheel and the distance between the two wheels

float speed = R*deg2rad ;//conversion factor of linear speed to angular speed in rad/s;
int encoder[2]={0,0}, prev_encoder[2] = {0,0}, dl, dr,k=0,q=0, r = 1 ;

float t_PID()
{
  t_kp = 6; t_ki = 0; t_kd = 0;//setting PID gains
  float  omega = 0 ;
  tDerror = t_error - old_t_error;
  tIerror = tIerror + t_error;
  omega = t_kp * t_error + t_ki * tIerror + t_kd * tDerror;
  old_t_error = t_error;
  omega =  omega +  0.1*rt_error;

  //cout << "omega = "<< omega << endl;
  return omega ;
}

void svcCallback(const arc::Request & req, arc::Response & res)
{
    int count = 0;
    float  rad, arct, xcentre, ycentre ;
    rad = req.rg ; //obtaining radius
    arct = req.arcl*deg2rad ; //obtaining arc length in terms of angle in degrees
    xcentre = xc;
    ycentre = yc + rad;

    t_error = td - tc_arc ;

    while(abs(abs(tcovered/deg2rad)- abs(arct/deg2rad)) > 1)
    {

      td = atan((yc - ycentre)/(xc - xcentre));//calculating theta desired

      if((xc-xcentre>0)&&(yc-ycentre>0))//1st quadrant
        {
          td = M_PI/2 + abs(td) ;
          tcovered = M_PI/2 + abs(atan((yc-ycentre)/(xc-xcentre)))  ;
          //cout << "1111 "<<abs(atan((yc-ycentre)/(xc-xcentre)))/deg2rad<<endl;
          if(sqrt((xc-xcentre)*(xc-xcentre)+(yc-ycentre)*(yc-ycentre)) > rad + 0.0001 )
            rtd = M_PI + abs(atan((yc-ycentre)/(xc-xcentre))) ;

          if(sqrt((xc-xcentre)*(xc-xcentre)+(yc-ycentre)*(yc-ycentre)) < rad - 0.0001 )
            rtd = abs(atan((yc-ycentre)/(xc-xcentre))) ;
         }

      if((xc-xcentre<0)&&(yc-ycentre>0))//2nd quadrant
        {
          td = 3*M_PI/2 - abs(td);
          tcovered = 3*M_PI/2 - abs(atan((yc-ycentre)/(xc-xcentre))) ;
          //cout << "22222 "<<abs(atan((yc-ycentre)/(xc-xcentre)))/deg2rad<<endl;
          if(sqrt((xc-xcentre)*(xc-xcentre)+(yc-ycentre)*(yc-ycentre)) > rad + 0.0001 )
            rtd = 2*M_PI - abs(atan((yc-ycentre)/(xc-xcentre))) ;

          if(sqrt((xc-xcentre)*(xc-xcentre)+(yc-ycentre)*(yc-ycentre)) < rad - 0.0001 )
            rtd = M_PI - abs(atan((yc-ycentre)/(xc-xcentre)));
        }

      if((xc-xcentre < 0)&&(yc-ycentre<0))//3rd quadrant
        {
          td = 3*M_PI/2 + abs(td) ;
          tcovered = 3*M_PI/2 + abs(atan((yc-ycentre)/(xc-xcentre)));
          //cout << "333333 "<<abs(atan((yc-ycentre)/(xc-xcentre)))/deg2rad<<endl;
          if(sqrt((xc-xcentre)*(xc-xcentre)+(yc-ycentre)*(yc-ycentre)) > rad + 0.0001 )
            rtd = abs(atan((yc-ycentre)/(xc-xcentre)));

          if(sqrt((xc-xcentre)*(xc-xcentre)+(yc-ycentre)*(yc-ycentre)) < rad - 0.0001 )
            rtd = M_PI + abs(atan((yc-ycentre)/(xc-xcentre)));
        }

      if((xc-xcentre>0)&&(yc-ycentre<0))//4th quadrant
        {
          td = M_PI/2 - abs(td) ;
          tcovered = M_PI/2 - abs(atan((yc-ycentre)/(xc-xcentre))) ;
          //cout << "44444 "<<abs(atan((yc-ycentre)/(xc-xcentre)))/deg2rad<<endl;
          if(sqrt((xc-xcentre)*(xc-xcentre)+(yc-ycentre)*(yc-ycentre)) > rad + 0.0001 )
            rtd = M_PI - abs(atan((yc-ycentre)/(xc-xcentre))) ;

          if(sqrt((xc-xcentre)*(xc-xcentre)+(yc-ycentre)*(yc-ycentre)) < rad - 0.0001 )
            rtd = 2*M_PI -abs(atan((yc-ycentre)/(xc-xcentre)));
        }

        rt_error = rtd - tc_arc ;
        res.tc = tcovered/deg2rad ;

      cout<<"desired = "<<arct/deg2rad<<endl;
      cout<< "current ="<<tcovered/deg2rad<<endl;//(atan(xc/(yc-rad))/deg2rad) <<endl;
      t_error = td - tc_arc ;
      /*if(abs(t_error/deg2rad) > 360)
        {
          t_error = abs(td) - abs(tc);
          cout<<endl<<endl<<endl<<endl<<endl;
        }*/
      wt = t_PID();
      if(t_error/deg2rad > 350 || t_error/deg2rad > 350 )
        break ;

      vx = 0.1;
      vr = (vx+L/2*wt)/(speed);
      vl = (vx-L/2*wt)/(speed);
      //cout<<"left , right = "<<vl <<" "<<vr <<endl;
      left_motor.set_speed_regulation_enabled("on");
      right_motor.set_speed_regulation_enabled("on");
      if(vl!=0)
      {
        left_motor.set_speed_sp(vl);
        left_motor.set_command("run-forever");
      }
      else
     {
        left_motor.set_speed_sp(0);
        left_motor.set_command("run-forever");
      }
      if(vr!=0)
     {
        right_motor.set_speed_sp(vr);
        right_motor.set_command("run-forever");
     }
    else
    {
        right_motor.set_speed_sp(0);
        right_motor.set_command("run-forever");
    }

        }
      res.x = xc ;
      res.y = yc ;

      td = 0;
      tIerror = 0;
      old_t_error = 0;

  cout <<"error = "<<t_error<< endl;
  cout<<"Service request message: ("<<req.rg<<","<<req.arcl<<") received \n ";
  cout<<"Current co-ordinates are \n (x,y,theta(degress)) == ("<<xc<<","<<yc<<","<<tc_arc/deg2rad<<") \n";
  vl = 0.0 , vr = 0.0 ;
  left_motor.set_speed_sp(0);
  left_motor.set_command("run-forever");
  right_motor.set_speed_sp(0);
  right_motor.set_command("run-forever");
  tcovered = 0;
  tarc_offset = tarc_offset + tc_arc;
 /* t = 0;
  x = 0; y = 0;
  left_motor.reset();
  right_motor.reset();
  cout<<"......."<<x<<","<<y<<","<<t;*/

}
ros::ServiceServer<arc::Request, arc::Response> server("arc_srv",&svcCallback);
void odometry() //function to calculate the odometry
{
        int encoder[2]={0,0}, prev_encoder[2] = {0,0}, dl, dr;
        while(1)
        {
        encoder[0] = left_motor.position();
        encoder[1] = right_motor.position();

        //obtaining angle rotated by left and right wheels in 100 ms
        dl = encoder[0]-prev_encoder[0];
        dr = encoder[1]-prev_encoder[1];

        t = -gsense.value()*deg2rad - tarc_offset;//storing angle in radians after callibration
        //making sure the angle lies in [0,2π]
        t_arc = t;
        t_arc = t_arc/deg2rad;
        if(t_arc>0)
        {
          k = t_arc/360;
          t_arc = t_arc - k*360;

        }

        if(t_arc<0)
        {
          k = -t_arc/360;
          t_arc = t_arc + k*360;

        }

        t_arc*=deg2rad;
        tc_arc = t_arc;
        //cout << "current value = "<<tc<<endl;

        //converting angle rotated by wheels to linear displacement and printing it
        x += cos(t)*speed*(dl+dr)/2.0; xc = x;
        y += sin(t)*speed*(dl+dr)/2.0; yc = y;
        cout<<"(x,y,theta) = "<<"("<<x<<","<<y<<","<<t/deg2rad<<")"<<endl ;

        prev_encoder[0] = encoder[0];
        prev_encoder[1] = encoder[1];

        //motor.speed() returns speed in rad/s
        vl = left_motor.speed();
        vr = right_motor.speed();

        //remmapping linear and angular velocity of centroid from vl, vr
        vx = (vl+vr)/2*speed;
        wt = (vl-vr)/L*speed;

        this_thread::sleep_for(chrono::milliseconds(100));
        }
}
int main(int argc, char* argv[])
{
  if(argc<5)
  {
    cerr<<"Usage: "<<argv[0]<<" <IP address> <left motor port> <right motor port> <<gyro sensor port>\n";
    cout<<"motor port options : outA outB outC outD \n";
    cout<<"sensor port options : inA inB inC inD \n";
    return 1;
  }
  else
  {

    ROSSRVR_IP = (argv[1]);
    left_motor_port = (argv[2]);
    right_motor_port = (argv[3]);
    sensor_port = (argv[4]);
  }
  gsense = sensor(sensor_port);

  left_motor = motor(left_motor_port);
  left_motor.reset();
  left_motor.set_position(0);
  left_motor.set_speed_regulation_enabled("on");

  right_motor = motor(right_motor_port);
  right_motor.reset();
  right_motor.set_position(0);
  right_motor.set_speed_regulation_enabled("on");

  nh.initNode(ROSSRVR_IP);
  nh.advertiseService(server);

  int milliseconds = 100;
    ros::Time current_time, last_time;
  current_time = nh.now();
  last_time = nh.now();
  tf::TransformBroadcaster odom_broadcaster;
  odom_broadcaster.init(nh);
  nav_msgs::Odometry odom_msg;//creating a msg of odometry type to publish odometry
  ros::Publisher odom_pub("odom", &odom_msg);//odom is the topic and odom_msg is the message that ev3 publishes
  nh.advertise(odom_pub);

  // Set mode
  //gsense = sensor(sensor_port);
  string mode="GYRO-G&A";
  gsense.set_mode(mode);
  tarc_offset = -gsense.value()*deg2rad;//obtaining initial angle to callibrate
  //cout<<"t_offset = "<< t_offset <<endl;
  cout<<"gyroscope is callibrated"<<endl ;
  thread odom (odometry);//'threading' odometry and the main functions

  while(1)
  {
    nh.spinOnce();
    sleep(1);
    current_time = nh.now();

        //since all odometry is 6DOF we'll need a quaternion created from yaw
        geometry_msgs::Quaternion odom_quat = tf::createQuaternionFromYaw(t);

        //first, we'll publish the transform over tf
        geometry_msgs::TransformStamped odom_trans;
        odom_trans.header.stamp = current_time;
        odom_trans.header.frame_id = "odom";
        const char base_link_name[18] = "base_link";
        odom_trans.child_frame_id = base_link_name;
        odom_trans.transform.translation.x = x;
        odom_trans.transform.translation.y = y;
        odom_trans.transform.translation.z = 0.0;
        odom_trans.transform.rotation = odom_quat;

        //send the transform
        odom_broadcaster.sendTransform(odom_trans);
        // broadcaster.sendTransform( tf::StampedTransform(tf::Transform(tf::Quaternion(0, 0, t, 1), tf::Vector3(x, y, 0)),ros::Time::now(),"odom", "base_link"));

        //next, we'll publish the odometry message over ROS
        odom_msg.header.stamp = current_time;
        odom_msg.header.frame_id = "odom";

        //set the position
        odom_msg.pose.pose.position.x = x;
        odom_msg.pose.pose.position.y = y;
        odom_msg.pose.pose.position.z = 0.0;
        odom_msg.pose.pose.orientation = odom_quat;

        //set the velocity
        odom_msg.child_frame_id = base_link_name;
        odom_msg.twist.twist.linear.x = vx;
        odom_msg.twist.twist.linear.y = 0;
        odom_msg.twist.twist.angular.z = wt;

        //publish the message
        odom_pub.publish(&odom_msg);

        last_time = current_time;

    this_thread::sleep_for(std::chrono::milliseconds(milliseconds)); // sets frequency
  }

    odom.join();

    return 0;
}
<commit_msg>Delete arc_service.cpp<commit_after><|endoftext|>


<commit_before>//
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)

// spdlog usage example

#include <cstdio>

#include "spdlog/spdlog.h"

int main(int, char *[])
{
    spdlog::info("Welcome to spdlog version {}.{}.{}  !", SPDLOG_VER_MAJOR, SPDLOG_VER_MINOR, SPDLOG_VER_PATCH);
    spdlog::warn("Easy padding in numbers like {:08d}", 12);
    spdlog::critical("Support for int: {0:d};  hex: {0:x};  oct: {0:o}; bin: {0:b}", 42);
    spdlog::info("Support for floats {:03.2f}", 1.23456);
    spdlog::info("Positional args are {1} {0}..", "too", "supported");
    spdlog::info("{:>8} aligned, {:<8} aligned", "right", "left");
}<commit_msg>Fixed example<commit_after>//
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)

// spdlog usage example

#include <cstdio>

void stdout_logger_example();
void basic_example();
void rotating_example();
void daily_example();
void async_example();
void binary_example();
void trace_example();
void multi_sink_example();
void user_defined_example();
void err_handler_example();
void syslog_example();

#include "spdlog/spdlog.h"

int main(int, char *[])
{
    spdlog::info("Welcome to spdlog version {}.{}.{}  !", SPDLOG_VER_MAJOR, SPDLOG_VER_MINOR, SPDLOG_VER_PATCH);
    spdlog::warn("Easy padding in numbers like {:08d}", 12);
    spdlog::critical("Support for int: {0:d};  hex: {0:x};  oct: {0:o}; bin: {0:b}", 42);
    spdlog::info("Support for floats {:03.2f}", 1.23456);
    spdlog::info("Positional args are {1} {0}..", "too", "supported");
    spdlog::info("{:>8} aligned, {:<8} aligned", "right", "left");

    // Runtime log levels
    spdlog::set_level(spdlog::level::info); // Set global log level to info
    spdlog::debug("This message should not be displayed!");
    spdlog::set_level(spdlog::level::trace); // Set specific logger's log level
    spdlog::debug("This message should be displayed..");

    // Customize msg format for all loggers
    spdlog::set_pattern("[%H:%M:%S %z] [%^%L%$] [thread %t] %v");
    spdlog::info("This an info message with custom format");
    spdlog::set_pattern("%+"); // back to default format
    spdlog::set_level(spdlog::level::info);

    // Backtrace support
    // Loggers can store in a ring buffer all messages (including debug/trace) for later inspection.
    // When needed, call dump_backtrace() to see what happened:
    spdlog::enable_backtrace(10); // create ring buffer with capacity of 10  messages
    for (int i = 0; i < 100; i++)
    {
        spdlog::debug("Backtrace message {}", i); // not logged..
    }
    // e.g. if some error happened:
    spdlog::dump_backtrace(); // log them now!

    try
    {
        stdout_logger_example();
        basic_example();
        rotating_example();
        daily_example();
        async_example();
        binary_example();
        multi_sink_example();
        user_defined_example();
        err_handler_example();
        trace_example();

        // Flush all *registered* loggers using a worker thread every 3 seconds.
        // note: registered loggers *must* be thread safe for this to work correctly!
        spdlog::flush_every(std::chrono::seconds(3));

        // Apply some function on all registered loggers
        spdlog::apply_all([&](std::shared_ptr<spdlog::logger> l) { l->info("End of example."); });

        // Release all spdlog resources, and drop all loggers in the registry.
        // This is optional (only mandatory if using windows + async log).
        spdlog::shutdown();
    }

    // Exceptions will only be thrown upon failed logger or sink construction (not during logging).
    catch (const spdlog::spdlog_ex &ex)
    {
        std::printf("Log initialization failed: %s\n", ex.what());
        return 1;
    }
}

#include "spdlog/sinks/stdout_color_sinks.h"
// or #include "spdlog/sinks/stdout_sinks.h" if no colors needed.
void stdout_logger_example()
{
    // Create color multi threaded logger.
    auto console = spdlog::stdout_color_mt("console");
    // or for stderr:
    // auto console = spdlog::stderr_color_mt("error-logger");
}

#include "spdlog/sinks/basic_file_sink.h"
void basic_example()
{
    // Create basic file logger (not rotated).
    auto my_logger = spdlog::basic_logger_mt("file_logger", "logs/basic-log.txt");
}

#include "spdlog/sinks/rotating_file_sink.h"
void rotating_example()
{
    // Create a file rotating logger with 5mb size max and 3 rotated files.
    auto rotating_logger = spdlog::rotating_logger_mt("some_logger_name", "logs/rotating.txt", 1048576 * 5, 3);
}

#include "spdlog/sinks/daily_file_sink.h"
void daily_example()
{
    // Create a daily logger - a new file is created every day on 2:30am.
    auto daily_logger = spdlog::daily_logger_mt("daily_logger", "logs/daily.txt", 2, 30);
}

#include "spdlog/async.h"
void async_example()
{
    // Default thread pool settings can be modified *before* creating the async logger:
    // spdlog::init_thread_pool(32768, 1); // queue with max 32k items 1 backing thread.
    auto async_file = spdlog::basic_logger_mt<spdlog::async_factory>("async_file_logger", "logs/async_log.txt");
    // alternatively:
    // auto async_file = spdlog::create_async<spdlog::sinks::basic_file_sink_mt>("async_file_logger", "logs/async_log.txt");

    for (int i = 1; i < 101; ++i)
    {
        async_file->info("Async message #{}", i);
    }
}

// Log binary data as hex.
// Many types of std::container<char> types can be used.
// Iterator ranges are supported too.
// Format flags:
// {:X} - print in uppercase.
// {:s} - don't separate each byte with space.
// {:p} - don't print the position on each line start.
// {:n} - don't split the output to lines.

#include "spdlog/fmt/bin_to_hex.h"
void binary_example()
{
    std::vector<char> buf;
    for (int i = 0; i < 80; i++)
    {
        buf.push_back(static_cast<char>(i & 0xff));
    }
    spdlog::info("Binary example: {}", spdlog::to_hex(buf));
    spdlog::info("Another binary example:{:n}", spdlog::to_hex(std::begin(buf), std::begin(buf) + 10));
    // more examples:
    // logger->info("uppercase: {:X}", spdlog::to_hex(buf));
    // logger->info("uppercase, no delimiters: {:Xs}", spdlog::to_hex(buf));
    // logger->info("uppercase, no delimiters, no position info: {:Xsp}", spdlog::to_hex(buf));
}

// Compile time log levels.
// define SPDLOG_ACTIVE_LEVEL to required level (e.g. SPDLOG_LEVEL_TRACE)
void trace_example()
{
    // trace from default logger
    SPDLOG_TRACE("Some trace message.. {} ,{}", 1, 3.23);
    // debug from default logger
    SPDLOG_DEBUG("Some debug message.. {} ,{}", 1, 3.23);

    // trace from logger object
    auto logger = spdlog::get("file_logger");
    SPDLOG_LOGGER_TRACE(logger, "another trace message");
}

// A logger with multiple sinks (stdout and file) - each with a different format and log level.
void multi_sink_example()
{
    auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
    console_sink->set_level(spdlog::level::warn);
    console_sink->set_pattern("[multi_sink_example] [%^%l%$] %v");

    auto file_sink = std::make_shared<spdlog::sinks::basic_file_sink_mt>("logs/multisink.txt", true);
    file_sink->set_level(spdlog::level::trace);

    spdlog::logger logger("multi_sink", {console_sink, file_sink});
    logger.set_level(spdlog::level::debug);
    logger.warn("this should appear in both console and file");
    logger.info("this message should not appear in the console, only in the file");
}

// User defined types logging by implementing operator<<
#include "spdlog/fmt/ostr.h" // must be included
struct my_type
{
    int i;
    template<typename OStream>
    friend OStream &operator<<(OStream &os, const my_type &c)
    {
        return os << "[my_type i=" << c.i << "]";
    }
};

void user_defined_example()
{
    spdlog::info("user defined type: {}", my_type{14});
}

// Custom error handler. Will be triggered on log failure.
void err_handler_example()
{
    // can be set globally or per logger(logger->set_error_handler(..))
    spdlog::set_error_handler([](const std::string &msg) { printf("*** Custom log error handler: %s ***\n", msg.c_str()); });
}

// syslog example (linux/osx/freebsd)
#ifndef _WIN32
#include "spdlog/sinks/syslog_sink.h"
void syslog_example()
{
    std::string ident = "spdlog-example";
    auto syslog_logger = spdlog::syslog_logger_mt("syslog", ident, LOG_PID);
    syslog_logger->warn("This is warning that will end up in syslog.");
}
#endif

// Android example.
#if defined(__ANDROID__)
#include "spdlog/sinks/android_sink.h"
void android_example()
{
    std::string tag = "spdlog-android";
    auto android_logger = spdlog::android_logger_mt("android", tag);
    android_logger->critical("Use \"adb shell logcat\" to view this message.");
}

#endif
<|endoftext|>