<commit_before>/*
 * Author: Brendan Le Foll <brendan.le.foll@intel.com>
 * Contributions: Jon Trulson <jtrulson@ics.com>
 * Contributions: Thomas Ingleby <thomas.c.ingleby@intel.com>
 * Copyright (c) 2014 - 2015 Intel Corporation.
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#pragma once

#include "uart.h"
#include "types.hpp"
#include <stdlib.h>
#include <stdexcept>
#include <cstring>

namespace mraa
{

/**
 * @brief API to UART (enabling only)
 *
 * This file defines the UART interface for libmraa
 *
 * @snippet Uart-example.cpp Interesting
 */
class Uart
{
  public:
    /**
     * Uart Constructor, takes a pin number which will map directly to the
     * linux uart number, this 'enables' the uart, nothing more
     *
     * @param uart the index of the uart set to use
     */
    Uart(int uart)
    {
        m_uart = mraa_uart_init(uart);

        if (m_uart == NULL) {
            throw std::invalid_argument("Error initialising UART");
        }
    }

    /**
     * Uart Constructor, takes a string to the path of the serial
     * interface that is needed.
     *
     * @param uart the index of the uart set to use
     */
    Uart(std::string path)
    {
        m_uart = mraa_uart_init_raw(path.c_str());

        if (m_uart == NULL) {
            throw std::invalid_argument("Error initialising UART");
        }
    }

    /**
     * Uart Constructor, takes a pointer to the UART context and initialises
     * the UART class
     *
     * @param void * to a UART context
     */
    Uart(void* uart_context)
    {
        m_uart = (mraa_uart_context) uart_context;

        if (m_uart == NULL) {
            throw std::invalid_argument("Invalid UART context");
        }
    }
    /**
     * Uart destructor
     */
    ~Uart()
    {
        mraa_uart_stop(m_uart);
    }

    /**
     * Get string with tty device path within Linux
     * For example. Could point to "/dev/ttyS0"
     *
     * @return char pointer of device path
     */
    std::string
    getDevicePath()
    {
        std::string ret_val(mraa_uart_get_dev_path(m_uart));
        return ret_val;
    }

    /**
     * Read bytes from the device into char* buffer
     *
     * @param data buffer pointer
     * @param length maximum size of buffer
     * @return numbers of bytes read
     */
    int
    read(char* data, int length)
    {
        return mraa_uart_read(m_uart, data, (size_t) length);
    }

    /**
     * Write bytes in String object to a device
     *
     * @param data buffer pointer
     * @param length maximum size of buffer
     * @return the number of bytes written, or -1 if an error occurred
     */
    int
    write(const char* data, int length)
    {
        return mraa_uart_write(m_uart, data, (size_t) length);
    }

    /**
     * Read bytes from the device into a String object
     *
     * @param length to read
     * @throws std::bad_alloc If there is no space left for read.
     * @return string of data
     */
    std::string
    readStr(int length)
    {
        char* data = (char*) malloc(sizeof(char) * length);
        if (data == NULL) {
            throw std::bad_alloc();
        }

        int v = mraa_uart_read(m_uart, data, (size_t) length);
        std::string ret(data, v);
        free(data);
        return ret;
    }

    /**
     * Write bytes in String object to a device
     *
     * @param string to write
     * @return the number of bytes written, or -1 if an error occurred
     */
    int
    writeStr(std::string data)
    {
        // this is data.length() not +1 because we want to avoid the '\0' char
        return mraa_uart_write(m_uart, data.c_str(), (data.length()));
    }

    /**
     * Check to see if data is available on the device for reading
     *
     * @param millis number of milliseconds to wait, or 0 to return immediately
     * @return true if there is data available to read, false otherwise
     */
    bool
    dataAvailable(unsigned int millis = 0)
    {
        if (mraa_uart_data_available(m_uart, millis))
            return true;
        else
            return false;
    }

    /**
     * Flush the outbound data.
     * Blocks until complete.
     *
     * @return Result of operation
     */
    Result
    flush()
    {
        return (Result) mraa_uart_flush(m_uart);
    }

    /**
     * Set the baudrate.
     * Takes an int and will attempt to decide what baudrate  is
     * to be used on the UART hardware.
     *
     * @param baud unsigned int of baudrate i.e. 9600
     * @return Result of operation
     */
    Result
    setBaudRate(unsigned int baud)
    {
        return (Result) mraa_uart_set_baudrate(m_uart, baud);
    }

    /**
     * Set the transfer mode
     * For example setting the mode to 8N1 would be
     * "dev.setMode(8,UART_PARITY_NONE , 1)"
     *
     * @param bytesize data bits
     * @param parity Parity bit setting
     * @param stopbits stop bits
     * @return Result of operation
     */
    Result
    setMode(int bytesize, UartParity parity, int stopbits)
    {
        return (Result) mraa_uart_set_mode(m_uart, bytesize, (mraa_uart_parity_t) parity, stopbits);
    }

    /**
     * Set the flowcontrol
     *
     * @param xonxoff XON/XOFF Software flow control.
     * @param rtscts RTS/CTS out of band hardware flow control
     * @return Result of operation
     */
    Result
    setFlowcontrol(bool xonxoff, bool rtscts)
    {
        return (Result) mraa_uart_set_flowcontrol(m_uart, xonxoff, rtscts);
    }

    /**
     * Set the timeout for read and write operations
     * <= 0 will disable that timeout
     *
     * @param read read timeout
     * @param write write timeout
     * @param interchar inbetween char timeout
     * @return Result of operation
     */
    Result
    setTimeout(int read, int write, int interchar)
    {
        return (Result) mraa_uart_set_timeout(m_uart, read, write, interchar);
    }

    /**
     * Set the blocking state for write operations
     *
     * @param dev The UART context
     * @param nonblock new nonblocking state
     * @return Result of operation
     */
    Result
    SetNonBlocking(bool nonblock)
    {
        return (Result) mraa_uart_set_non_blocking(m_uart, nonblock);
    }

  private:
    mraa_uart_context m_uart;
};
}
<commit_msg>uart.hpp: fix typo in write() description<commit_after>/*
 * Author: Brendan Le Foll <brendan.le.foll@intel.com>
 * Contributions: Jon Trulson <jtrulson@ics.com>
 * Contributions: Thomas Ingleby <thomas.c.ingleby@intel.com>
 * Copyright (c) 2014 - 2015 Intel Corporation.
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#pragma once

#include "uart.h"
#include "types.hpp"
#include <stdlib.h>
#include <stdexcept>
#include <cstring>

namespace mraa
{

/**
 * @brief API to UART (enabling only)
 *
 * This file defines the UART interface for libmraa
 *
 * @snippet Uart-example.cpp Interesting
 */
class Uart
{
  public:
    /**
     * Uart Constructor, takes a pin number which will map directly to the
     * linux uart number, this 'enables' the uart, nothing more
     *
     * @param uart the index of the uart set to use
     */
    Uart(int uart)
    {
        m_uart = mraa_uart_init(uart);

        if (m_uart == NULL) {
            throw std::invalid_argument("Error initialising UART");
        }
    }

    /**
     * Uart Constructor, takes a string to the path of the serial
     * interface that is needed.
     *
     * @param uart the index of the uart set to use
     */
    Uart(std::string path)
    {
        m_uart = mraa_uart_init_raw(path.c_str());

        if (m_uart == NULL) {
            throw std::invalid_argument("Error initialising UART");
        }
    }

    /**
     * Uart Constructor, takes a pointer to the UART context and initialises
     * the UART class
     *
     * @param void * to a UART context
     */
    Uart(void* uart_context)
    {
        m_uart = (mraa_uart_context) uart_context;

        if (m_uart == NULL) {
            throw std::invalid_argument("Invalid UART context");
        }
    }
    /**
     * Uart destructor
     */
    ~Uart()
    {
        mraa_uart_stop(m_uart);
    }

    /**
     * Get string with tty device path within Linux
     * For example. Could point to "/dev/ttyS0"
     *
     * @return char pointer of device path
     */
    std::string
    getDevicePath()
    {
        std::string ret_val(mraa_uart_get_dev_path(m_uart));
        return ret_val;
    }

    /**
     * Read bytes from the device into char* buffer
     *
     * @param data buffer pointer
     * @param length maximum size of buffer
     * @return numbers of bytes read
     */
    int
    read(char* data, int length)
    {
        return mraa_uart_read(m_uart, data, (size_t) length);
    }

    /**
     * Write bytes in char* buffer to a device
     *
     * @param data buffer pointer
     * @param length maximum size of buffer
     * @return the number of bytes written, or -1 if an error occurred
     */
    int
    write(const char* data, int length)
    {
        return mraa_uart_write(m_uart, data, (size_t) length);
    }

    /**
     * Read bytes from the device into a String object
     *
     * @param length to read
     * @throws std::bad_alloc If there is no space left for read.
     * @return string of data
     */
    std::string
    readStr(int length)
    {
        char* data = (char*) malloc(sizeof(char) * length);
        if (data == NULL) {
            throw std::bad_alloc();
        }

        int v = mraa_uart_read(m_uart, data, (size_t) length);
        std::string ret(data, v);
        free(data);
        return ret;
    }

    /**
     * Write bytes in String object to a device
     *
     * @param string to write
     * @return the number of bytes written, or -1 if an error occurred
     */
    int
    writeStr(std::string data)
    {
        // this is data.length() not +1 because we want to avoid the '\0' char
        return mraa_uart_write(m_uart, data.c_str(), (data.length()));
    }

    /**
     * Check to see if data is available on the device for reading
     *
     * @param millis number of milliseconds to wait, or 0 to return immediately
     * @return true if there is data available to read, false otherwise
     */
    bool
    dataAvailable(unsigned int millis = 0)
    {
        if (mraa_uart_data_available(m_uart, millis))
            return true;
        else
            return false;
    }

    /**
     * Flush the outbound data.
     * Blocks until complete.
     *
     * @return Result of operation
     */
    Result
    flush()
    {
        return (Result) mraa_uart_flush(m_uart);
    }

    /**
     * Set the baudrate.
     * Takes an int and will attempt to decide what baudrate  is
     * to be used on the UART hardware.
     *
     * @param baud unsigned int of baudrate i.e. 9600
     * @return Result of operation
     */
    Result
    setBaudRate(unsigned int baud)
    {
        return (Result) mraa_uart_set_baudrate(m_uart, baud);
    }

    /**
     * Set the transfer mode
     * For example setting the mode to 8N1 would be
     * "dev.setMode(8,UART_PARITY_NONE , 1)"
     *
     * @param bytesize data bits
     * @param parity Parity bit setting
     * @param stopbits stop bits
     * @return Result of operation
     */
    Result
    setMode(int bytesize, UartParity parity, int stopbits)
    {
        return (Result) mraa_uart_set_mode(m_uart, bytesize, (mraa_uart_parity_t) parity, stopbits);
    }

    /**
     * Set the flowcontrol
     *
     * @param xonxoff XON/XOFF Software flow control.
     * @param rtscts RTS/CTS out of band hardware flow control
     * @return Result of operation
     */
    Result
    setFlowcontrol(bool xonxoff, bool rtscts)
    {
        return (Result) mraa_uart_set_flowcontrol(m_uart, xonxoff, rtscts);
    }

    /**
     * Set the timeout for read and write operations
     * <= 0 will disable that timeout
     *
     * @param read read timeout
     * @param write write timeout
     * @param interchar inbetween char timeout
     * @return Result of operation
     */
    Result
    setTimeout(int read, int write, int interchar)
    {
        return (Result) mraa_uart_set_timeout(m_uart, read, write, interchar);
    }

    /**
     * Set the blocking state for write operations
     *
     * @param dev The UART context
     * @param nonblock new nonblocking state
     * @return Result of operation
     */
    Result
    SetNonBlocking(bool nonblock)
    {
        return (Result) mraa_uart_set_non_blocking(m_uart, nonblock);
    }

  private:
    mraa_uart_context m_uart;
};
}
<|endoftext|>


<commit_before>#include "clguetzli.h"
#include "ocl.h"

ocl_args_d_t& getOcl(void)
{
	static bool bInit = false;
	static ocl_args_d_t ocl;

	if (bInit == true) return ocl;

	bInit = true;
	SetupOpenCL(&ocl, CL_DEVICE_TYPE_GPU);

	cl_int err = SetupOpenCL(&ocl, CL_DEVICE_TYPE_GPU);
	if (CL_SUCCESS != err)
	{
		LogError("Error: clBuildProgram() for source program returned %s.\n", TranslateOpenCLError(err));
	}

	char* source = nullptr;
	size_t src_size = 0;
	ReadSourceFromFile("clguetzli\\clguetzli.cl", &source, &src_size);

	ocl.program = clCreateProgramWithSource(ocl.context, 1, (const char**)&source, &src_size, &err);

	delete[] source;

	err = clBuildProgram(ocl.program, 1, &ocl.device, "", NULL, NULL);
	if (CL_SUCCESS != err)
	{
		LogError("Error: clBuildProgram() for source program returned %s.\n", TranslateOpenCLError(err));
	}
	ocl.kernel[KERNEL_MINSQUAREVAL] = clCreateKernel(ocl.program, "MinSquareVal", &err);
	if (CL_SUCCESS != err)
	{
		LogError("Error: clCreateKernel(MinSquareVal) for source program returned %s.\n", TranslateOpenCLError(err));
	}
	ocl.kernel[KERNEL_CONVOLUTION] = clCreateKernel(ocl.program, "Convolution", &err);
	if (CL_SUCCESS != err)
	{
		LogError("Error: clCreateKernel(Convolution) for source program returned %s.\n", TranslateOpenCLError(err));
	}

	return ocl;
}

void clMinSquareVal(size_t square_size, size_t offset,
	size_t xsize, size_t ysize,
	float *values)
{
	cl_int err = CL_SUCCESS;
	ocl_args_d_t &ocl = getOcl();

	ocl.allocA(sizeof(cl_float) * xsize * ysize);
	ocl.allocC(sizeof(cl_float) * xsize * ysize);

	memcpy(ocl.inputA, values, sizeof(cl_float) * xsize * ysize);

	cl_int cloffset = offset;
	cl_int clsquare_size = square_size;

	cl_kernel kernel = ocl.kernel[KERNEL_MINSQUAREVAL];
	clSetKernelArg(kernel, 0, sizeof(cl_mem), (void*)&ocl.srcA);
	clSetKernelArg(kernel, 1, sizeof(cl_mem), (void*)&ocl.dstMem);
	clSetKernelArg(kernel, 2, sizeof(cl_int), (void*)&clsquare_size);
	clSetKernelArg(kernel, 3, sizeof(cl_int), (void*)&cloffset);

	size_t globalWorkSize[2] = { xsize, ysize };
	err = clEnqueueNDRangeKernel(ocl.commandQueue, kernel, 2, NULL, globalWorkSize, NULL, 0, NULL, NULL);
	if (CL_SUCCESS != err)
	{
		LogError("Error: clBuildProgram() for source program returned %s.\n", TranslateOpenCLError(err));
	}
	err = clFinish(ocl.commandQueue);
	if (CL_SUCCESS != err)
	{
		LogError("Error: clBuildProgram() for source program returned %s.\n", TranslateOpenCLError(err));
	}

	cl_float *resultPtr = (cl_float *)clEnqueueMapBuffer(ocl.commandQueue, ocl.dstMem, true, CL_MAP_READ, 0, sizeof(cl_float) * xsize * ysize, 0, NULL, NULL, &err);
	if (CL_SUCCESS != err)
	{
		LogError("Error: clEnqueueMapBuffer returned %s\n", TranslateOpenCLError(err));
	}
	err = clFinish(ocl.commandQueue);
	if (CL_SUCCESS != err)
	{
		LogError("Error: clFinish returned %s\n", TranslateOpenCLError(err));
	}

	memcpy(values, resultPtr, sizeof(cl_float) * xsize * ysize);
}

void clConvolution(size_t xsize, size_t ysize,
	size_t xstep,
	size_t len, size_t offset,
	const float* multipliers,
	const float* inp,
	float border_ratio,
	float* result)
{
	cl_int err = CL_SUCCESS;
	ocl_args_d_t &ocl = getOcl();

	size_t oxsize = xsize / xstep;

	ocl.allocA(sizeof(cl_float) * len);
	ocl.allocB(sizeof(cl_float) * xsize * ysize);
	ocl.allocC(sizeof(cl_float) * oxsize * ysize);

	memcpy(ocl.inputA, multipliers, sizeof(cl_float) * len);
	memcpy(ocl.inputB, inp, sizeof(cl_float) * xsize * ysize);

	cl_int clxsize = xsize;
	cl_int clxstep = xstep;
	cl_int cllen = len;
	cl_int cloffset = offset;
	cl_float clborder_ratio = border_ratio;

	cl_kernel kernel = ocl.kernel[KERNEL_CONVOLUTION];
	clSetKernelArg(kernel, 0, sizeof(cl_mem), (void*)&ocl.srcA);
	clSetKernelArg(kernel, 1, sizeof(cl_mem), (void*)&ocl.srcB);
	clSetKernelArg(kernel, 2, sizeof(cl_mem), (void*)&ocl.dstMem);
	clSetKernelArg(kernel, 3, sizeof(cl_int), (void*)&clxsize);
	clSetKernelArg(kernel, 4, sizeof(cl_int), (void*)&clxstep);
	clSetKernelArg(kernel, 5, sizeof(cl_int), (void*)&cllen);
	clSetKernelArg(kernel, 6, sizeof(cl_int), (void*)&cloffset);
	clSetKernelArg(kernel, 7, sizeof(cl_float), (void*)&clborder_ratio);

	size_t globalWorkSize[2] = { xsize / xstep, ysize };
	err = clEnqueueNDRangeKernel(ocl.commandQueue, kernel, 2, NULL, globalWorkSize, NULL, 0, NULL, NULL);
	if (CL_SUCCESS != err)
	{
		LogError("Error: clBuildProgram() for source program returned %s.\n", TranslateOpenCLError(err));
	}
	err = clFinish(ocl.commandQueue);
	if (CL_SUCCESS != err)
	{
		LogError("Error: clBuildProgram() for source program returned %s.\n", TranslateOpenCLError(err));
	}

	cl_float *resultPtr = (cl_float *)clEnqueueMapBuffer(ocl.commandQueue, ocl.dstMem, true, CL_MAP_READ, 0, sizeof(cl_float) * oxsize * ysize, 0, NULL, NULL, &err);
	if (CL_SUCCESS != err)
	{
		LogError("Error: clEnqueueMapBuffer returned %s\n", TranslateOpenCLError(err));
	}
	err = clFinish(ocl.commandQueue);
	if (CL_SUCCESS != err)
	{
		LogError("Error: clFinish returned %s\n", TranslateOpenCLError(err));
	}

	memcpy(result, resultPtr, sizeof(cl_float) * oxsize * ysize);
}<commit_msg>fix setupopencl<commit_after>#include "clguetzli.h"
#include "ocl.h"

ocl_args_d_t& getOcl(void)
{
	static bool bInit = false;
	static ocl_args_d_t ocl;

	if (bInit == true) return ocl;

	bInit = true;
	cl_int err = SetupOpenCL(&ocl, CL_DEVICE_TYPE_GPU);
	if (CL_SUCCESS != err)
	{
		LogError("Error: clBuildProgram() for source program returned %s.\n", TranslateOpenCLError(err));
	}

	char* source = nullptr;
	size_t src_size = 0;
	ReadSourceFromFile("clguetzli\\clguetzli.cl", &source, &src_size);

	ocl.program = clCreateProgramWithSource(ocl.context, 1, (const char**)&source, &src_size, &err);

	delete[] source;

	err = clBuildProgram(ocl.program, 1, &ocl.device, "", NULL, NULL);
	if (CL_SUCCESS != err)
	{
		LogError("Error: clBuildProgram() for source program returned %s.\n", TranslateOpenCLError(err));
	}
	ocl.kernel[KERNEL_MINSQUAREVAL] = clCreateKernel(ocl.program, "MinSquareVal", &err);
	if (CL_SUCCESS != err)
	{
		LogError("Error: clCreateKernel(MinSquareVal) for source program returned %s.\n", TranslateOpenCLError(err));
	}
	ocl.kernel[KERNEL_CONVOLUTION] = clCreateKernel(ocl.program, "Convolution", &err);
	if (CL_SUCCESS != err)
	{
		LogError("Error: clCreateKernel(Convolution) for source program returned %s.\n", TranslateOpenCLError(err));
	}

	return ocl;
}

void clMinSquareVal(size_t square_size, size_t offset,
	size_t xsize, size_t ysize,
	float *values)
{
	cl_int err = CL_SUCCESS;
	ocl_args_d_t &ocl = getOcl();

	ocl.allocA(sizeof(cl_float) * xsize * ysize);
	ocl.allocC(sizeof(cl_float) * xsize * ysize);

	memcpy(ocl.inputA, values, sizeof(cl_float) * xsize * ysize);

	cl_int cloffset = offset;
	cl_int clsquare_size = square_size;

	cl_kernel kernel = ocl.kernel[KERNEL_MINSQUAREVAL];
	clSetKernelArg(kernel, 0, sizeof(cl_mem), (void*)&ocl.srcA);
	clSetKernelArg(kernel, 1, sizeof(cl_mem), (void*)&ocl.dstMem);
	clSetKernelArg(kernel, 2, sizeof(cl_int), (void*)&clsquare_size);
	clSetKernelArg(kernel, 3, sizeof(cl_int), (void*)&cloffset);

	size_t globalWorkSize[2] = { xsize, ysize };
	err = clEnqueueNDRangeKernel(ocl.commandQueue, kernel, 2, NULL, globalWorkSize, NULL, 0, NULL, NULL);
	if (CL_SUCCESS != err)
	{
		LogError("Error: clBuildProgram() for source program returned %s.\n", TranslateOpenCLError(err));
	}
	err = clFinish(ocl.commandQueue);
	if (CL_SUCCESS != err)
	{
		LogError("Error: clBuildProgram() for source program returned %s.\n", TranslateOpenCLError(err));
	}

	cl_float *resultPtr = (cl_float *)clEnqueueMapBuffer(ocl.commandQueue, ocl.dstMem, true, CL_MAP_READ, 0, sizeof(cl_float) * xsize * ysize, 0, NULL, NULL, &err);
	if (CL_SUCCESS != err)
	{
		LogError("Error: clEnqueueMapBuffer returned %s\n", TranslateOpenCLError(err));
	}
	err = clFinish(ocl.commandQueue);
	if (CL_SUCCESS != err)
	{
		LogError("Error: clFinish returned %s\n", TranslateOpenCLError(err));
	}

	memcpy(values, resultPtr, sizeof(cl_float) * xsize * ysize);
}

void clConvolution(size_t xsize, size_t ysize,
	size_t xstep,
	size_t len, size_t offset,
	const float* multipliers,
	const float* inp,
	float border_ratio,
	float* result)
{
	cl_int err = CL_SUCCESS;
	ocl_args_d_t &ocl = getOcl();

	size_t oxsize = xsize / xstep;

	ocl.allocA(sizeof(cl_float) * len);
	ocl.allocB(sizeof(cl_float) * xsize * ysize);
	ocl.allocC(sizeof(cl_float) * oxsize * ysize);

	memcpy(ocl.inputA, multipliers, sizeof(cl_float) * len);
	memcpy(ocl.inputB, inp, sizeof(cl_float) * xsize * ysize);

	cl_int clxsize = xsize;
	cl_int clxstep = xstep;
	cl_int cllen = len;
	cl_int cloffset = offset;
	cl_float clborder_ratio = border_ratio;

	cl_kernel kernel = ocl.kernel[KERNEL_CONVOLUTION];
	clSetKernelArg(kernel, 0, sizeof(cl_mem), (void*)&ocl.srcA);
	clSetKernelArg(kernel, 1, sizeof(cl_mem), (void*)&ocl.srcB);
	clSetKernelArg(kernel, 2, sizeof(cl_mem), (void*)&ocl.dstMem);
	clSetKernelArg(kernel, 3, sizeof(cl_int), (void*)&clxsize);
	clSetKernelArg(kernel, 4, sizeof(cl_int), (void*)&clxstep);
	clSetKernelArg(kernel, 5, sizeof(cl_int), (void*)&cllen);
	clSetKernelArg(kernel, 6, sizeof(cl_int), (void*)&cloffset);
	clSetKernelArg(kernel, 7, sizeof(cl_float), (void*)&clborder_ratio);

	size_t globalWorkSize[2] = { xsize / xstep, ysize };
	err = clEnqueueNDRangeKernel(ocl.commandQueue, kernel, 2, NULL, globalWorkSize, NULL, 0, NULL, NULL);
	if (CL_SUCCESS != err)
	{
		LogError("Error: clBuildProgram() for source program returned %s.\n", TranslateOpenCLError(err));
	}
	err = clFinish(ocl.commandQueue);
	if (CL_SUCCESS != err)
	{
		LogError("Error: clBuildProgram() for source program returned %s.\n", TranslateOpenCLError(err));
	}

	cl_float *resultPtr = (cl_float *)clEnqueueMapBuffer(ocl.commandQueue, ocl.dstMem, true, CL_MAP_READ, 0, sizeof(cl_float) * oxsize * ysize, 0, NULL, NULL, &err);
	if (CL_SUCCESS != err)
	{
		LogError("Error: clEnqueueMapBuffer returned %s\n", TranslateOpenCLError(err));
	}
	err = clFinish(ocl.commandQueue);
	if (CL_SUCCESS != err)
	{
		LogError("Error: clFinish returned %s\n", TranslateOpenCLError(err));
	}

	memcpy(result, resultPtr, sizeof(cl_float) * oxsize * ysize);
}<|endoftext|>


<commit_before>/*
 * Author: Brendan Le Foll <brendan.le.foll@intel.com>
 * Contributions: Jon Trulson <jtrulson@ics.com>
 * Contributions: Thomas Ingleby <thomas.c.ingleby@intel.com>
 * Copyright (c) 2014 - 2015 Intel Corporation.
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#pragma once

#include "uart.h"
#include <stdexcept>
#include <cstring>

namespace mraa
{

/**
 * @brief API to UART (enabling only)
 *
 * This file defines the UART interface for libmraa
 *
 * @snippet Uart-example.cpp Interesting
 */
class Uart
{
  public:
    /**
     * Uart Constructor, takes a pin number which will map directly to the
     * linux uart number, this 'enables' the uart, nothing more
     *
     * @param uart the index of the uart set to use
     */
    Uart(int uart)
    {
        m_uart = mraa_uart_init(uart);

        if (m_uart == NULL) {
            throw std::invalid_argument("Error initialising UART");
        }
    }

    /**
     * Uart Constructor, takes a string to the path of the serial
     * interface that is needed.
     *
     * @param uart the index of the uart set to use
     */
    Uart(std::string path)
    {
        m_uart = mraa_uart_init_raw(path.c_str());

        if (m_uart == NULL) {
            throw std::invalid_argument("Error initialising UART");
        }
    }

    /**
     * Uart destructor
     */
    ~Uart()
    {
        mraa_uart_stop(m_uart);
    }

    /**
     * Get string with tty device path within Linux
     * For example. Could point to "/dev/ttyS0"
     *
     * @return char pointer of device path
     */
    std::string
    getDevicePath()
    {
        std::string ret_val(mraa_uart_get_dev_path(m_uart));
        return ret_val;
    }

    /**
     * Read bytes from the device into char* buffer
     *
     * @param data buffer pointer
     * @param length maximum size of buffer
     * @return numbers of bytes read
     */
    int
    read(char* data, int length)
    {
        return mraa_uart_read(m_uart, data, (size_t) length);
    }

    /**
     * Write bytes in String object to a device
     *
     * @param data buffer pointer
     * @param length maximum size of buffer
     * @return the number of bytes written, or -1 if an error occurred
     */
    int
    write(const char* data, int length)
    {
        return mraa_uart_write(m_uart, data, (size_t) length);
    }

    /**
     * Read bytes from the device into a String object
     *
     * @param length to read
     * @return string of data
     */
    std::string
    readStr(int length)
    {
        char* data = (char*) malloc(sizeof(char) * length);
        int v = mraa_uart_read(m_uart, data, (size_t) length);
        std::string ret(data, v);
        free(data);
        return ret;
    }

    /**
     * Write bytes in String object to a device
     *
     * @param string to write
     * @return the number of bytes written, or -1 if an error occurred
     */
    int
    writeStr(std::string data)
    {
        // this is data.length() not +1 because we want to avoid the '\0' char
        return mraa_uart_write(m_uart, data.c_str(), (data.length()));
    }

    /**
     * Check to see if data is available on the device for reading
     *
     * @param millis number of milliseconds to wait, or 0 to return immediately
     * @return true if there is data available to read, false otherwise
     */
    bool
    dataAvailable(unsigned int millis = 0)
    {
        if (mraa_uart_data_available(m_uart, millis))
            return true;
        else
            return false;
    }

    /**
     * Flush the outbound data.
     * Blocks until complete.
     *
     * @return Result of operation
     */
    Result
    flush()
    {
        return (Result) mraa_uart_flush(m_uart);
    }

    /**
     * Set the baudrate.
     * Takes an int and will attempt to decide what baudrate  is
     * to be used on the UART hardware.
     *
     * @param baud unsigned int of baudrate i.e. 9600
     * @return Result of operation
     */
    Result
    setBaudRate(unsigned int baud)
    {
        return (Result) mraa_uart_set_baudrate(m_uart, baud);
    }

    /**
     * Set the transfer mode
     * For example setting the mode to 8N1 would be
     * "dev.setMode(8,UART_PARITY_NONE , 1)"
     *
     * @param bytesize data bits
     * @param parity Parity bit setting
     * @param stopbits stop bits
     * @return Result of operation
     */
    Result
    setMode(int bytesize, UartParity parity, int stopbits)
    {
        return (Result) mraa_uart_set_mode(m_uart, bytesize, (mraa_uart_parity_t) parity, stopbits);
    }

    /**
     * Set the flowcontrol
     *
     * @param xonxoff XON/XOFF Software flow control.
     * @param rtscts RTS/CTS out of band hardware flow control
     * @return Result of operation
     */
    Result
    setFlowcontrol(bool xonxoff, bool rtscts)
    {
        return (Result) mraa_uart_set_flowcontrol(m_uart, xonxoff, rtscts);
    }

    /**
     * Set the timeout for read and write operations
     * <= 0 will disable that timeout
     *
     * @param read read timeout
     * @param write write timeout
     * @param interchar inbetween char timeout
     * @return Result of operation
     */
    Result
    setTimeout(int read, int write, int interchar)
    {
        return (Result) mraa_uart_set_timeout(m_uart, read, write, interchar);
    }

  private:
    mraa_uart_context m_uart;
};
}
<commit_msg>uart.hpp: Added missing include for types.hpp<commit_after>/*
 * Author: Brendan Le Foll <brendan.le.foll@intel.com>
 * Contributions: Jon Trulson <jtrulson@ics.com>
 * Contributions: Thomas Ingleby <thomas.c.ingleby@intel.com>
 * Copyright (c) 2014 - 2015 Intel Corporation.
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#pragma once

#include "uart.h"
#include "types.hpp"
#include <stdexcept>
#include <cstring>

namespace mraa
{

/**
 * @brief API to UART (enabling only)
 *
 * This file defines the UART interface for libmraa
 *
 * @snippet Uart-example.cpp Interesting
 */
class Uart
{
  public:
    /**
     * Uart Constructor, takes a pin number which will map directly to the
     * linux uart number, this 'enables' the uart, nothing more
     *
     * @param uart the index of the uart set to use
     */
    Uart(int uart)
    {
        m_uart = mraa_uart_init(uart);

        if (m_uart == NULL) {
            throw std::invalid_argument("Error initialising UART");
        }
    }

    /**
     * Uart Constructor, takes a string to the path of the serial
     * interface that is needed.
     *
     * @param uart the index of the uart set to use
     */
    Uart(std::string path)
    {
        m_uart = mraa_uart_init_raw(path.c_str());

        if (m_uart == NULL) {
            throw std::invalid_argument("Error initialising UART");
        }
    }

    /**
     * Uart destructor
     */
    ~Uart()
    {
        mraa_uart_stop(m_uart);
    }

    /**
     * Get string with tty device path within Linux
     * For example. Could point to "/dev/ttyS0"
     *
     * @return char pointer of device path
     */
    std::string
    getDevicePath()
    {
        std::string ret_val(mraa_uart_get_dev_path(m_uart));
        return ret_val;
    }

    /**
     * Read bytes from the device into char* buffer
     *
     * @param data buffer pointer
     * @param length maximum size of buffer
     * @return numbers of bytes read
     */
    int
    read(char* data, int length)
    {
        return mraa_uart_read(m_uart, data, (size_t) length);
    }

    /**
     * Write bytes in String object to a device
     *
     * @param data buffer pointer
     * @param length maximum size of buffer
     * @return the number of bytes written, or -1 if an error occurred
     */
    int
    write(const char* data, int length)
    {
        return mraa_uart_write(m_uart, data, (size_t) length);
    }

    /**
     * Read bytes from the device into a String object
     *
     * @param length to read
     * @return string of data
     */
    std::string
    readStr(int length)
    {
        char* data = (char*) malloc(sizeof(char) * length);
        int v = mraa_uart_read(m_uart, data, (size_t) length);
        std::string ret(data, v);
        free(data);
        return ret;
    }

    /**
     * Write bytes in String object to a device
     *
     * @param string to write
     * @return the number of bytes written, or -1 if an error occurred
     */
    int
    writeStr(std::string data)
    {
        // this is data.length() not +1 because we want to avoid the '\0' char
        return mraa_uart_write(m_uart, data.c_str(), (data.length()));
    }

    /**
     * Check to see if data is available on the device for reading
     *
     * @param millis number of milliseconds to wait, or 0 to return immediately
     * @return true if there is data available to read, false otherwise
     */
    bool
    dataAvailable(unsigned int millis = 0)
    {
        if (mraa_uart_data_available(m_uart, millis))
            return true;
        else
            return false;
    }

    /**
     * Flush the outbound data.
     * Blocks until complete.
     *
     * @return Result of operation
     */
    Result
    flush()
    {
        return (Result) mraa_uart_flush(m_uart);
    }

    /**
     * Set the baudrate.
     * Takes an int and will attempt to decide what baudrate  is
     * to be used on the UART hardware.
     *
     * @param baud unsigned int of baudrate i.e. 9600
     * @return Result of operation
     */
    Result
    setBaudRate(unsigned int baud)
    {
        return (Result) mraa_uart_set_baudrate(m_uart, baud);
    }

    /**
     * Set the transfer mode
     * For example setting the mode to 8N1 would be
     * "dev.setMode(8,UART_PARITY_NONE , 1)"
     *
     * @param bytesize data bits
     * @param parity Parity bit setting
     * @param stopbits stop bits
     * @return Result of operation
     */
    Result
    setMode(int bytesize, UartParity parity, int stopbits)
    {
        return (Result) mraa_uart_set_mode(m_uart, bytesize, (mraa_uart_parity_t) parity, stopbits);
    }

    /**
     * Set the flowcontrol
     *
     * @param xonxoff XON/XOFF Software flow control.
     * @param rtscts RTS/CTS out of band hardware flow control
     * @return Result of operation
     */
    Result
    setFlowcontrol(bool xonxoff, bool rtscts)
    {
        return (Result) mraa_uart_set_flowcontrol(m_uart, xonxoff, rtscts);
    }

    /**
     * Set the timeout for read and write operations
     * <= 0 will disable that timeout
     *
     * @param read read timeout
     * @param write write timeout
     * @param interchar inbetween char timeout
     * @return Result of operation
     */
    Result
    setTimeout(int read, int write, int interchar)
    {
        return (Result) mraa_uart_set_timeout(m_uart, read, write, interchar);
    }

  private:
    mraa_uart_context m_uart;
};
}
<|endoftext|>


<commit_before>//---------------------------------------------------------------------------
/// \file   es/storage.hpp
/// \brief  The entity/component data store
//
// Copyright 2013, nocte@hippie.nu            Released under the MIT License.
//---------------------------------------------------------------------------
#include "storage.hpp"

namespace es {

storage::storage()
    : next_id_(0)
{
    component_offsets_.push_back(0);
}

storage::~storage()
{
    for (auto i (entities_.begin()); i != entities_.end(); ++i)
        call_destructors(i);
}

storage::component_id
storage::find_component (const std::string& name) const
{
    auto found (std::find(components_.begin(), components_.end(), name));
    if (found == components_.end())
        throw std::logic_error("component does not exist");

    return std::distance(components_.begin(), found);
}

entity
storage::new_entity()
{
    auto result (entities_.emplace(next_id_, elem()).first);
    if (on_new_entity)
        on_new_entity(result);

    ++next_id_;
    return next_id_ - 1;
}

storage::iterator
storage::make (uint32_t id)
{
    if (next_id_ <= id)
        next_id_ = id + 1;

    auto result (entities_.emplace(id, elem()));
    if (result.second && on_new_entity)
        on_new_entity(result.first);

    return result.first;
}

std::pair<entity, entity>
storage::new_entities (size_t count)
{
    auto range_begin (next_id_);
    for (; count > 0; --count)
        entities_[next_id_++];

    return std::make_pair(range_begin, next_id_);
}

entity
storage::clone_entity (iterator f)
{
    auto cloned (entities_.emplace(next_id_, f->second).first);
    elem& e (cloned->second);

    // Quick check if we need to make deep copies
    if ((e.components & flat_mask_).any())
    {
        size_t off (0);
        for (int c_id (0); c_id < 64 && off < e.data.size(); ++c_id)
        {
            if (e.components[c_id])
            {
                if (!components_[c_id].is_flat())
                {
                    auto ptr (reinterpret_cast<placeholder*>(&*e.data.begin() + off));
                    ptr->clone()->move_to(e.data.begin() + off);
                }
                off += components_[c_id].size();
            }
        }
    }
    if (on_new_entity)
        on_new_entity(cloned);

    ++next_id_;
    return next_id_ - 1;
}

storage::iterator
storage::find (entity en)
{
    auto found (entities_.find(en));
    if (found == entities_.end())
        throw std::logic_error("unknown entity");

    return found;
}

storage::const_iterator
storage::find (entity en) const
{
    auto found (entities_.find(en));
    if (found == entities_.end())
        throw std::logic_error("unknown entity");

    return found;
}

size_t
storage::size() const
{
    return entities_.size();
}

bool
storage::delete_entity (entity en)
{
    auto found (find(en));
    if (found != entities_.end())
    {
        delete_entity(found);
        return true;
    }
    return false;
}

void
storage::delete_entity (iterator f)
{
    if (on_deleted_entity)
        on_deleted_entity(f);

    call_destructors(f);
    entities_.erase(f);
}

void
storage::remove_component_from_entity (iterator en, component_id c)
{
    auto& e (en->second);
    if (!e.components[c])
        return;

    size_t off (offset(e, c));
    auto& comp_info (components_[c]);
    if (!comp_info.is_flat())
    {
        auto ptr (reinterpret_cast<placeholder*>(&*e.data.begin() + off));
        if (ptr)
            ptr->~placeholder();
    }
    auto o (e.data.begin() + off);
    e.data.erase(o, o + comp_info.size());
    e.components.reset(c);
    e.dirty = true;
}

bool
storage::entity_has_component (iterator en, component_id c) const
{
    return c < components_.size() && en->second.components.test(c);
}

size_t
storage::offset (const elem& e, component_id c) const
{
    assert(c < components_.size());
    assert((c & cache_mask) < component_offsets_.size());

    size_t result (component_offsets_[((1 << c) - 1) & e.components.to_ulong() & cache_mask]);

    for (component_id search (cache_size); search < c; ++search)
    {
        if (e.components[search])
            result += components_[search].size();
    }

    return result;
}

bool
storage::check_dirty (iterator en)
{
    return en->second.dirty;
}

bool
storage::check_dirty_and_clear (iterator en)
{
    bool result (check_dirty(en));
    en->second.dirty = false;
    return result;
}

void
storage::serialize (const_iterator en, std::vector<char>& buffer) const
{
    auto& e (en->second);
    buffer.reserve(8 + e.data.size());
    buffer.resize(8);

    *(reinterpret_cast<uint64_t*>(&buffer[0])) = e.components.to_ullong();

    auto first (e.data.begin());
    auto last  (first);

    for (size_t i (0); i < components_.size(); ++i)
    {
        if (!e.components[i])
            continue;

        auto& c (components_[i]);
        if (c.is_flat())
        {
            // As long as we have a flat memory layout, just move the
            // end of the range.
            std::advance(last, c.size());
        }
        else
        {
            // If not, write the current range to the buffer.
            buffer.insert(buffer.end(), first, last);
            // Then serialize the object using the function the caller
            // provided.
            auto ptr (reinterpret_cast<const component::placeholder*>(&*last));
            ptr->serialize(buffer);
            // Reset the range.
            std::advance(last, c.size());
            first = last;
        }

        if (last >= e.data.end())
            break;
    }
    // Write the last bit after we're done.
    assert(last == e.data.end());
    buffer.insert(buffer.end(), first, e.data.end());
}

void
storage::deserialize (iterator en, const std::vector<char>& buffer)
{
    auto first (buffer.begin());
    auto& e (en->second);

    call_destructors(en);
    e.data.clear();
    e.components = *(reinterpret_cast<const uint64_t*>(&*first));

    std::advance(first, 8);
    auto last (first);

    for (size_t i (0); i < components_.size(); ++i)
    {
        if (!e.components[i])
            continue;

        auto& c (components_[i]);
        if (c.is_flat())
        {
            // As long as we have a flat memory layout, just move the
            // end of the range.
            std::advance(last, c.size());
        }
        else
        {
            // If not, write the current range to the entity data.
            e.data.insert(e.data.end(), first, last);
            // Create a new object for the component and deserialize the
            // data using the function the caller provided.
            auto ptr (c.clone());
            last = ptr->deserialize(last, buffer.end());
            first = last;
            // Move the object to the buffer.
            auto offset (e.data.size());
            e.data.resize(offset + c.size());
            ptr->move_to(e.data.begin() + offset);
        }

        if (last >= buffer.end())
            break;
    }
    // Write the last bit after we're done.
    assert(last == buffer.end());
    e.data.insert(e.data.end(), first, buffer.end());
}

void
storage::call_destructors(iterator i) const
{
    elem& e (i->second);

    // Quick check if we'll have to call any destructors.
    if ((e.components & flat_mask_).any())
    {
        size_t off (0);
        for (int search (0); search < 64 && off < e.data.size(); ++search)
        {
            if (e.components[search])
            {
                if (!components_[search].is_flat())
                {
                    auto ptr (reinterpret_cast<placeholder*>(&*e.data.begin() + off));
                    ptr->~placeholder();
                }
                off += components_[search].size();
            }
        }
    }
}

} // namespace es
<commit_msg>Fixes for Launchpad.net<commit_after>//---------------------------------------------------------------------------
/// \file   es/storage.hpp
/// \brief  The entity/component data store
//
// Copyright 2013, nocte@hippie.nu            Released under the MIT License.
//---------------------------------------------------------------------------
#include "storage.hpp"

namespace es {

storage::storage()
    : next_id_(0)
{
    component_offsets_.push_back(0);
}

storage::~storage()
{
    for (auto i (entities_.begin()); i != entities_.end(); ++i)
        call_destructors(i);
}

storage::component_id
storage::find_component (const std::string& name) const
{
    auto found (std::find(components_.begin(), components_.end(), name));
    if (found == components_.end())
        throw std::logic_error("component does not exist");

    return std::distance(components_.begin(), found);
}

entity
storage::new_entity()
{
    auto result (entities_.insert(std::make_pair(next_id_, elem())).first);
    if (on_new_entity)
        on_new_entity(result);

    ++next_id_;
    return next_id_ - 1;
}

storage::iterator
storage::make (uint32_t id)
{
    if (next_id_ <= id)
        next_id_ = id + 1;

    auto result (entities_.insert(std::make_pair(next_id_, elem())));
    if (result.second && on_new_entity)
        on_new_entity(result.first);

    return result.first;
}

std::pair<entity, entity>
storage::new_entities (size_t count)
{
    auto range_begin (next_id_);
    for (; count > 0; --count)
        entities_[next_id_++];

    return std::make_pair(range_begin, next_id_);
}

entity
storage::clone_entity (iterator f)
{
    auto cloned (entities_.insert(std::make_pair(next_id_, f->second)).first);
    elem& e (cloned->second);

    // Quick check if we need to make deep copies
    if ((e.components & flat_mask_).any())
    {
        size_t off (0);
        for (int c_id (0); c_id < 64 && off < e.data.size(); ++c_id)
        {
            if (e.components[c_id])
            {
                if (!components_[c_id].is_flat())
                {
                    auto ptr (reinterpret_cast<placeholder*>(&*e.data.begin() + off));
                    ptr->clone()->move_to(e.data.begin() + off);
                }
                off += components_[c_id].size();
            }
        }
    }
    if (on_new_entity)
        on_new_entity(cloned);

    ++next_id_;
    return next_id_ - 1;
}

storage::iterator
storage::find (entity en)
{
    auto found (entities_.find(en));
    if (found == entities_.end())
        throw std::logic_error("unknown entity");

    return found;
}

storage::const_iterator
storage::find (entity en) const
{
    auto found (entities_.find(en));
    if (found == entities_.end())
        throw std::logic_error("unknown entity");

    return found;
}

size_t
storage::size() const
{
    return entities_.size();
}

bool
storage::delete_entity (entity en)
{
    auto found (find(en));
    if (found != entities_.end())
    {
        delete_entity(found);
        return true;
    }
    return false;
}

void
storage::delete_entity (iterator f)
{
    if (on_deleted_entity)
        on_deleted_entity(f);

    call_destructors(f);
    entities_.erase(f);
}

void
storage::remove_component_from_entity (iterator en, component_id c)
{
    auto& e (en->second);
    if (!e.components[c])
        return;

    size_t off (offset(e, c));
    auto& comp_info (components_[c]);
    if (!comp_info.is_flat())
    {
        auto ptr (reinterpret_cast<placeholder*>(&*e.data.begin() + off));
        if (ptr)
            ptr->~placeholder();
    }
    auto o (e.data.begin() + off);
    e.data.erase(o, o + comp_info.size());
    e.components.reset(c);
    e.dirty = true;
}

bool
storage::entity_has_component (iterator en, component_id c) const
{
    return c < components_.size() && en->second.components.test(c);
}

size_t
storage::offset (const elem& e, component_id c) const
{
    assert(c < components_.size());
    assert((c & cache_mask) < component_offsets_.size());

    size_t result (component_offsets_[((1 << c) - 1) & e.components.to_ulong() & cache_mask]);

    for (component_id search (cache_size); search < c; ++search)
    {
        if (e.components[search])
            result += components_[search].size();
    }

    return result;
}

bool
storage::check_dirty (iterator en)
{
    return en->second.dirty;
}

bool
storage::check_dirty_and_clear (iterator en)
{
    bool result (check_dirty(en));
    en->second.dirty = false;
    return result;
}

void
storage::serialize (const_iterator en, std::vector<char>& buffer) const
{
    auto& e (en->second);
    buffer.reserve(8 + e.data.size());
    buffer.resize(8);

    *(reinterpret_cast<uint64_t*>(&buffer[0])) = e.components.to_ullong();

    auto first (e.data.begin());
    auto last  (first);

    for (size_t i (0); i < components_.size(); ++i)
    {
        if (!e.components[i])
            continue;

        auto& c (components_[i]);
        if (c.is_flat())
        {
            // As long as we have a flat memory layout, just move the
            // end of the range.
            std::advance(last, c.size());
        }
        else
        {
            // If not, write the current range to the buffer.
            buffer.insert(buffer.end(), first, last);
            // Then serialize the object using the function the caller
            // provided.
            auto ptr (reinterpret_cast<const component::placeholder*>(&*last));
            ptr->serialize(buffer);
            // Reset the range.
            std::advance(last, c.size());
            first = last;
        }

        if (last >= e.data.end())
            break;
    }
    // Write the last bit after we're done.
    assert(last == e.data.end());
    buffer.insert(buffer.end(), first, e.data.end());
}

void
storage::deserialize (iterator en, const std::vector<char>& buffer)
{
    auto first (buffer.begin());
    auto& e (en->second);

    call_destructors(en);
    e.data.clear();
    e.components = *(reinterpret_cast<const uint64_t*>(&*first));

    std::advance(first, 8);
    auto last (first);

    for (size_t i (0); i < components_.size(); ++i)
    {
        if (!e.components[i])
            continue;

        auto& c (components_[i]);
        if (c.is_flat())
        {
            // As long as we have a flat memory layout, just move the
            // end of the range.
            std::advance(last, c.size());
        }
        else
        {
            // If not, write the current range to the entity data.
            e.data.insert(e.data.end(), first, last);
            // Create a new object for the component and deserialize the
            // data using the function the caller provided.
            auto ptr (c.clone());
            last = ptr->deserialize(last, buffer.end());
            first = last;
            // Move the object to the buffer.
            auto offset (e.data.size());
            e.data.resize(offset + c.size());
            ptr->move_to(e.data.begin() + offset);
        }

        if (last >= buffer.end())
            break;
    }
    // Write the last bit after we're done.
    assert(last == buffer.end());
    e.data.insert(e.data.end(), first, buffer.end());
}

void
storage::call_destructors(iterator i) const
{
    elem& e (i->second);

    // Quick check if we'll have to call any destructors.
    if ((e.components & flat_mask_).any())
    {
        size_t off (0);
        for (int search (0); search < 64 && off < e.data.size(); ++search)
        {
            if (e.components[search])
            {
                if (!components_[search].is_flat())
                {
                    auto ptr (reinterpret_cast<placeholder*>(&*e.data.begin() + off));
                    ptr->~placeholder();
                }
                off += components_[search].size();
            }
        }
    }
}

} // namespace es
<|endoftext|>


<commit_before>#include "clay.hpp"

vector<OverloadPtr> typeOverloads;

void addTypeOverload(OverloadPtr x)
{
    typeOverloads.insert(typeOverloads.begin(), x);
}

void initTypeOverloads(TypePtr t)
{
    assert(!t->overloadsInitialized);

    for (unsigned i = 0; i < typeOverloads.size(); ++i) {
        OverloadPtr x = typeOverloads[i];
        EnvPtr env = new Env(x->env);
        const vector<IdentifierPtr> &pvars = x->code->patternVars;
        for (unsigned i = 0; i < pvars.size(); ++i) {
            PatternCellPtr cell = new PatternCell(pvars[i], NULL);
            addLocal(env, pvars[i], cell.ptr());
        }
        PatternPtr pattern = evaluatePattern(x->target, env);
        if (unify(pattern, t.ptr()))
            t->overloads.insert(t->overloads.begin(), x);
    }

    t->overloadsInitialized = true;
}

void initBuiltinIsStaticFlags(TypePtr t) {
    switch (t->typeKind) {

    case ARRAY_TYPE : {
        ArrayType *x = (ArrayType *)t.ptr();
        FlagsMapEntry &flags = lookupFlagsMapEntry(t.ptr(), x->size);
        assert(!flags.initialized);
        flags.initialized = true;
        flags.isStaticFlags.assign(x->size, false);
        break;
    }

    case TUPLE_TYPE : {
        TupleType *x = (TupleType *)t.ptr();
        FlagsMapEntry &flags =
            lookupFlagsMapEntry(t.ptr(), x->elementTypes.size());
        assert(!flags.initialized);
        flags.initialized = true;
        flags.isStaticFlags.assign(x->elementTypes.size(), false);
        break;
    }

    case RECORD_TYPE : {
        RecordType *x = (RecordType *)t.ptr();
        const vector<TypePtr> &fieldTypes = recordFieldTypes(x);
        FlagsMapEntry &flags = lookupFlagsMapEntry(t.ptr(), fieldTypes.size());
        assert(!flags.initialized);
        flags.initialized = true;
        flags.isStaticFlags.assign(fieldTypes.size(), false);
        break;
    }

    }
}

void verifyBuiltinConstructor(TypePtr t,
                              const vector<bool> &isStaticFlags,
                              const vector<ObjectPtr> &argsKey,
                              const vector<LocationPtr> &argLocations)
{
    switch (t->typeKind) {

    case ARRAY_TYPE : {
        ArrayType *x = (ArrayType *)t.ptr();
        if (x->size != (int)isStaticFlags.size())
            error("incorrect no. of arguments");
        for (unsigned i = 0; i < isStaticFlags.size(); ++i) {
            assert(isStaticFlags[i]);
            assert(argsKey[i]->objKind == TYPE);
            TypePtr y = (Type *)argsKey[i].ptr();
            if (y != x->elementType) {
                LocationContext loc(argLocations[i]);
                error("type mismatch");
            }
        }
        break;
    }

    case TUPLE_TYPE : {
        TupleType *x = (TupleType *)t.ptr();
        if (x->elementTypes.size() != isStaticFlags.size())
            error("incorrect no. of arguments");
        for (unsigned i = 0; i < isStaticFlags.size(); ++i) {
            assert(isStaticFlags[i]);
            assert(argsKey[i]->objKind == TYPE);
            TypePtr y = (Type *)argsKey[i].ptr();
            if (y != x->elementTypes[i]) {
                LocationContext loc(argLocations[i]);
                error("type mismatch");
            }
        }
        break;
    }

    case RECORD_TYPE : {
        RecordType *x = (RecordType *)t.ptr();
        const vector<TypePtr> &fieldTypes = recordFieldTypes(x);
        if (fieldTypes.size() != isStaticFlags.size())
            error("incorrect no. of arguments");
        for (unsigned i = 0; i < isStaticFlags.size(); ++i) {
            assert(!isStaticFlags[i]);
            assert(argsKey[i]->objKind == TYPE);
            TypePtr y = (Type *)argsKey[i].ptr();
            if (y != fieldTypes[i]) {
                LocationContext loc(argLocations[i]);
                error("type mismatch");
            }
        }
        break;
    }

    default :
        error("no matching constructor found");

    }
}
<commit_msg>fixed silly bug in 'initTypeOverloads'.<commit_after>#include "clay.hpp"

vector<OverloadPtr> typeOverloads;

void addTypeOverload(OverloadPtr x)
{
    typeOverloads.insert(typeOverloads.begin(), x);
}

void initTypeOverloads(TypePtr t)
{
    assert(!t->overloadsInitialized);

    for (unsigned i = 0; i < typeOverloads.size(); ++i) {
        OverloadPtr x = typeOverloads[i];
        EnvPtr env = new Env(x->env);
        const vector<IdentifierPtr> &pvars = x->code->patternVars;
        for (unsigned i = 0; i < pvars.size(); ++i) {
            PatternCellPtr cell = new PatternCell(pvars[i], NULL);
            addLocal(env, pvars[i], cell.ptr());
        }
        PatternPtr pattern = evaluatePattern(x->target, env);
        if (unify(pattern, t.ptr()))
            t->overloads.push_back(x);
    }

    t->overloadsInitialized = true;
}

void initBuiltinIsStaticFlags(TypePtr t) {
    switch (t->typeKind) {

    case ARRAY_TYPE : {
        ArrayType *x = (ArrayType *)t.ptr();
        FlagsMapEntry &flags = lookupFlagsMapEntry(t.ptr(), x->size);
        assert(!flags.initialized);
        flags.initialized = true;
        flags.isStaticFlags.assign(x->size, false);
        break;
    }

    case TUPLE_TYPE : {
        TupleType *x = (TupleType *)t.ptr();
        FlagsMapEntry &flags =
            lookupFlagsMapEntry(t.ptr(), x->elementTypes.size());
        assert(!flags.initialized);
        flags.initialized = true;
        flags.isStaticFlags.assign(x->elementTypes.size(), false);
        break;
    }

    case RECORD_TYPE : {
        RecordType *x = (RecordType *)t.ptr();
        const vector<TypePtr> &fieldTypes = recordFieldTypes(x);
        FlagsMapEntry &flags = lookupFlagsMapEntry(t.ptr(), fieldTypes.size());
        assert(!flags.initialized);
        flags.initialized = true;
        flags.isStaticFlags.assign(fieldTypes.size(), false);
        break;
    }

    }
}

void verifyBuiltinConstructor(TypePtr t,
                              const vector<bool> &isStaticFlags,
                              const vector<ObjectPtr> &argsKey,
                              const vector<LocationPtr> &argLocations)
{
    switch (t->typeKind) {

    case ARRAY_TYPE : {
        ArrayType *x = (ArrayType *)t.ptr();
        if (x->size != (int)isStaticFlags.size())
            error("incorrect no. of arguments");
        for (unsigned i = 0; i < isStaticFlags.size(); ++i) {
            assert(isStaticFlags[i]);
            assert(argsKey[i]->objKind == TYPE);
            TypePtr y = (Type *)argsKey[i].ptr();
            if (y != x->elementType) {
                LocationContext loc(argLocations[i]);
                error("type mismatch");
            }
        }
        break;
    }

    case TUPLE_TYPE : {
        TupleType *x = (TupleType *)t.ptr();
        if (x->elementTypes.size() != isStaticFlags.size())
            error("incorrect no. of arguments");
        for (unsigned i = 0; i < isStaticFlags.size(); ++i) {
            assert(isStaticFlags[i]);
            assert(argsKey[i]->objKind == TYPE);
            TypePtr y = (Type *)argsKey[i].ptr();
            if (y != x->elementTypes[i]) {
                LocationContext loc(argLocations[i]);
                error("type mismatch");
            }
        }
        break;
    }

    case RECORD_TYPE : {
        RecordType *x = (RecordType *)t.ptr();
        const vector<TypePtr> &fieldTypes = recordFieldTypes(x);
        if (fieldTypes.size() != isStaticFlags.size())
            error("incorrect no. of arguments");
        for (unsigned i = 0; i < isStaticFlags.size(); ++i) {
            assert(!isStaticFlags[i]);
            assert(argsKey[i]->objKind == TYPE);
            TypePtr y = (Type *)argsKey[i].ptr();
            if (y != fieldTypes[i]) {
                LocationContext loc(argLocations[i]);
                error("type mismatch");
            }
        }
        break;
    }

    default :
        error("no matching constructor found");

    }
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2013-2014 Nicholas Corgan (n.corgan@gmail.com)
 *
 * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
 * or copy at http://opensource.org/licenses/MIT)
 */

#include <cstdio>

#include <boost/assign.hpp>
#include <boost/format.hpp>

#include <pkmn/enums.hpp>
#include <pkmn/paths.hpp>
#include <pkmn/database/queries.hpp>
#include <pkmn/types/prng.hpp>

#include "SQLiteCpp/src/SQLiteC++.h"

#include "team_pokemon_modernimpl.hpp"

using namespace std;

namespace pkmn
{
    team_pokemon_modernimpl::team_pokemon_modernimpl(base_pokemon::sptr base, unsigned int game, unsigned int level,
                                                     unsigned int move1, unsigned int move2,
                                                     unsigned int move3, unsigned int move4): team_pokemon_impl(base,game,level,
                                                                                move1,move2,move3,move4)
    {
        //Random individual values
        _ivHP = _rand_gen.lcrng_next(_generation) % 32;
        _ivATK = _rand_gen.lcrng_next(_generation) % 32;
        _ivDEF = _rand_gen.lcrng_next(_generation) % 32;
        _ivSPD = _rand_gen.lcrng_next(_generation) % 32;
        _ivSATK = _rand_gen.lcrng_next(_generation) % 32;
        _ivSDEF = _rand_gen.lcrng_next(_generation) % 32;

        /*
         * Random effort values within following rules:
         *  - Sum <= 510
         *  - EV <= 255
         */
        _evHP = 256;
        _evATK = 256;
        _evDEF = 256;
        _evSPD = 256;
        _evSATK = 256;
        _evSDEF = 256;
        while((_evHP+_evATK+_evDEF+_evSPD+_evSATK+_evSDEF)>510 || _evHP>255 || _evATK>255 || _evDEF>255 || _evSPD>255 || _evSATK>255 || _evSDEF>255)
        {
            _evHP = _rand_gen.lcrng_next(_generation) % 256;
            _evATK = _rand_gen.lcrng_next(_generation) % 256;
            _evDEF = _rand_gen.lcrng_next(_generation) % 256;
            _evSPD = _rand_gen.lcrng_next(_generation) % 256;
            _evSATK = _rand_gen.lcrng_next(_generation) % 256;
            _evSDEF = _rand_gen.lcrng_next(_generation) % 256;
        }

        _gender = _determine_gender();
        _ability = _determine_ability();
        _ability = _determine_ability();

        _set_stats();
    }

    std::string team_pokemon_modernimpl::get_gender() const {return _gender;}

    std::string team_pokemon_modernimpl::get_nature() const {return _nature;}

    std::string team_pokemon_modernimpl::get_ability() const {return _ability;}

    bool team_pokemon_modernimpl::is_shiny() const
    {
        int p1, p2, E, F;
        p1 = (_personality & 0xFFFF0000) >> 16;
        p2 = _personality & 0xFFFF;
        E = _tid.public_id ^ _tid.secret_id;
        F = p1 ^ p2;
        return (E ^ F) < 8;
    }

    pkmn::dict<std::string, unsigned int> team_pokemon_modernimpl::get_stats() const
    {
        pkmn::dict<std::string, unsigned int> stats;
        stats["HP"] = _HP;
        stats["Attack"] = _ATK;
        stats["Defense"] = _DEF;
        stats["Special Attack"] = _SATK;
        stats["Special Defense"] = _SDEF;
        stats["Speed"] = _SPD;

        return stats;
    }

    pkmn::dict<std::string, unsigned int> team_pokemon_modernimpl::get_EVs() const
    {
        pkmn::dict<std::string, unsigned int> EVs;
        EVs["HP"] = _evHP;
        EVs["Attack"] = _evATK;
        EVs["Defense"] = _evDEF;
        EVs["Special Attack"] = _evSATK;
        EVs["Special Defense"] = _evSDEF;
        EVs["Speed"] = _evSPD;

        return EVs;
    }

    pkmn::dict<std::string, unsigned int> team_pokemon_modernimpl::get_IVs() const
    {
        pkmn::dict<std::string, unsigned int> IVs;
        IVs["HP"] = _ivHP;
        IVs["Attack"] = _ivATK;
        IVs["Defense"] = _ivDEF;
        IVs["Special Attack"] = _ivSATK;
        IVs["Special Defense"] = _ivSDEF;
        IVs["Speed"] = _ivSPD;

        return IVs;
    }

    void team_pokemon_modernimpl::set_personality(unsigned int personality)
    {
        _personality = personality;
        _ability = _determine_ability();
        _gender = _determine_gender();
        _ability = _determine_ability();
    }

    void team_pokemon_modernimpl::set_gender(std::string gender)
    {
        if(gender == "Male" or gender == "Female") _gender = gender;
    }

    void team_pokemon_modernimpl::set_nature(std::string nature)
    {
        //Search for given nature in database
        std::string query_string = str(boost::format("SELECT nature_id FROM nature_names WHERE name='%s'")
                                       % nature.c_str());
        SQLite::Statement nature_names_query(_db, query_string.c_str());
        if(nature_names_query.executeStep())
        {
            _nature = nature;
            _set_stats();
            return;
        }

        //If not in nature_names, check in abilities
        query_string = str(boost::format("Select id FROM natures WHERE identifier='%s'")
                           % nature);
        SQLite::Statement natures_query(_db, query_string.c_str());
        if(natures_query.executeStep())
        {
            nature[0] = tolower(nature[0]);
            _nature = nature;
            _set_stats();
        }
    }

    void team_pokemon_modernimpl::set_ability(std::string ability)
    {
        //Search for given ability in database
        std::string query_string = str(boost::format("SELECT ability_id FROM ability_names WHERE name='%s'")
                                       % ability.c_str());
        SQLite::Statement ability_names_query(_db, query_string.c_str());
        if(ability_names_query.executeStep())
        {
            _ability = ability;
            return;
        }

        //If not in ability_names, check in abilities
        query_string = str(boost::format("Select id FROM abilities WHERE identifier='%s'")
                           % ability);
        SQLite::Statement abilities_query(_db, query_string.c_str());
        if(abilities_query.executeStep())
        {
            ability[0] = tolower(ability[0]);
            _ability = ability;
        }
    }

    void team_pokemon_modernimpl::set_using_hidden_ability(bool val)
    {
        _has_hidden_ability = val;
        _ability = _determine_ability();
    }

    void team_pokemon_modernimpl::set_EV(std::string EV, unsigned int val)
    {
        if(val > 255)
        {
            cerr << "Gen 3-5 EV's must be 0-255." << endl;
            exit(EXIT_FAILURE);
        }

        if(EV == "HP")
        {
            _evHP = val;
            _HP = _get_hp();
        }
        else if(EV == "Attack")
        {
            _evATK = val;
            _ATK = _get_stat("Attack", _evATK, _ivATK);
        }
        else if(EV == "Defense")
        {
            _evDEF = val;
            _DEF = _get_stat("Defense", _evDEF, _ivDEF);
        }
        else if(EV == "Speed")
        {
            _evSPD = val;
            _SPD = _get_stat("Speed", _evSPD, _ivSPD);
        }
        else if(EV == "Special Attack")
        {
            _evSATK = val;
            _SATK = _get_stat("Special Attack", _evSATK, _ivSATK);
        }
        else if(EV == "Special Defense")
        {
            _evSDEF = val;
            _SDEF = _get_stat("Special Defense", _evSDEF, _ivSDEF);
        }
    }

    void team_pokemon_modernimpl::set_IV(std::string IV, unsigned int val)
    {
        if(val > 31)
        {
            cerr << "Gen 3-5 IV's must be 0-31." << endl;
            exit(EXIT_FAILURE);
        }

        if(IV == "HP")
        {
            _ivHP = val;
            _HP = _get_hp();
        }
        else if(IV == "Attack")
        {
            _ivATK = val;
            _ATK = _get_stat("Attack", _evATK, _ivATK);
        }
        else if(IV == "Defense")
        {
            _ivDEF = val;
            _DEF = _get_stat("Defense", _evDEF, _ivDEF);
        }
        else if(IV == "Speed")
        {
            _ivSPD = val;
            _SPD = _get_stat("Speed", _evSPD, _ivSPD);
        }
        else if(IV == "Special Attack")
        {
            _ivSATK = val;
            _SATK = _get_stat("Special Attack", _evSATK, _ivSATK);
        }
        else if(IV == "Special Defense")
        {
            _ivSDEF = val;
            _SDEF = _get_stat("Special Defense", _evSDEF, _ivSDEF);
        }
    }

    void team_pokemon_modernimpl::set_form(unsigned int form)
    {
        _base_pkmn->set_form(form);
        _set_stats();
        _ability = _determine_ability();
    }

    void team_pokemon_modernimpl::set_form(std::string form)
    {
        _base_pkmn->set_form(form);
        _set_stats();
        _ability = _determine_ability();
    }

    unsigned int team_pokemon_modernimpl::_get_hp() const
    {
        pkmn::dict<std::string, unsigned int> stats = _base_pkmn->get_base_stats();

        unsigned int hp_val = int(floor(((double(_ivHP) + (2.0*double(stats["HP"])) + (0.25*double(_evHP)) + 100.0)
                            * double(_level))/100.0 + 10.0));
        return hp_val;
    }

    unsigned int team_pokemon_modernimpl::_get_stat(std::string stat, unsigned int EV, unsigned int IV) const
    {
        //TODO: better solution
        pkmn::dict<std::string, unsigned int> stat_enums = boost::assign::map_list_of
                                                     ("HP", Stats::HP)
                                                     ("Attack", Stats::ATTACK)
                                                     ("Defense", Stats::DEFENSE)
                                                     ("Special Attack", Stats::SPECIAL_ATTACK)
                                                     ("Special Defense", Stats::SPECIAL_DEFENSE)
                                                     ("Speed", Stats::SPEED)
        ;

        pkmn::dict<std::string, unsigned int> stats = _base_pkmn->get_base_stats();
        double ability_mod = database::get_nature_stat_effect(_nature, stat_enums[stat]);

        unsigned int stat_val = int(ceil(((((double(IV) + 2.0*double(stats[stat]) + 0.25*double(EV))
                              * double(_level))/100.0) + 5.0) * ability_mod));
        return stat_val;
    }

    void team_pokemon_modernimpl::_set_stats()
    {
        if(_base_pkmn->get_species_id() == Species::SHEDINJA) _HP = 1;
        else _HP = _get_hp();
        _ATK = _get_stat("Attack", _evATK, _ivATK);
        _DEF = _get_stat("Defense", _evDEF, _ivDEF);
        _SPD = _get_stat("Speed", _evSPD, _ivSPD);
        _SATK = _get_stat("Special Attack", _evSATK, _ivSATK);
        _SDEF = _get_stat("Special Defense", _evSDEF, _ivSDEF);
    }

    std::string team_pokemon_modernimpl::_determine_ability() const
    {
        string_pair_t abilities = _base_pkmn->get_abilities();
        std::string hidden_ability = _base_pkmn->get_hidden_ability();

        if(_base_pkmn->get_species_id() == Species::NONE or _base_pkmn->get_species_id() == Species::INVALID) return "None";
        else if(_has_hidden_ability and _generation >= 5) return hidden_ability;
        else return ((_personality % 2) == 0) ? abilities.first : abilities.second;
    }

    std::string team_pokemon_modernimpl::_determine_gender() const
    {
        if(_base_pkmn->get_chance_male() + _base_pkmn->get_chance_female() == 0
        or _base_pkmn->get_species_id() == Species::NONE
        or _base_pkmn->get_species_id() == Species::INVALID) return "Genderless";
        else if(_base_pkmn->get_chance_male() == 1.0) return "Male";
        else if(_base_pkmn->get_chance_female() == 1.0) return "Female";
        else
        {
            if((_personality % 256) > int(floor(255*(1-_base_pkmn->get_chance_male())))) return "Male";
            else return "Female";
        }

        //Should never get here, this stops Clang from complaining
        return "Male";
    }
} /* namespace pkmn */
<commit_msg>team_pokemon: fixed _determine_nature<commit_after>/*
 * Copyright (c) 2013-2014 Nicholas Corgan (n.corgan@gmail.com)
 *
 * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
 * or copy at http://opensource.org/licenses/MIT)
 */

#include <cstdio>

#include <boost/assign.hpp>
#include <boost/format.hpp>

#include <pkmn/enums.hpp>
#include <pkmn/paths.hpp>
#include <pkmn/database/queries.hpp>
#include <pkmn/types/prng.hpp>

#include "SQLiteCpp/src/SQLiteC++.h"

#include "team_pokemon_modernimpl.hpp"

using namespace std;

namespace pkmn
{
    team_pokemon_modernimpl::team_pokemon_modernimpl(base_pokemon::sptr base, unsigned int game, unsigned int level,
                                                     unsigned int move1, unsigned int move2,
                                                     unsigned int move3, unsigned int move4): team_pokemon_impl(base,game,level,
                                                                                move1,move2,move3,move4)
    {
        //Random individual values
        _ivHP = _rand_gen.lcrng_next(_generation) % 32;
        _ivATK = _rand_gen.lcrng_next(_generation) % 32;
        _ivDEF = _rand_gen.lcrng_next(_generation) % 32;
        _ivSPD = _rand_gen.lcrng_next(_generation) % 32;
        _ivSATK = _rand_gen.lcrng_next(_generation) % 32;
        _ivSDEF = _rand_gen.lcrng_next(_generation) % 32;

        /*
         * Random effort values within following rules:
         *  - Sum <= 510
         *  - EV <= 255
         */
        _evHP = 256;
        _evATK = 256;
        _evDEF = 256;
        _evSPD = 256;
        _evSATK = 256;
        _evSDEF = 256;
        while((_evHP+_evATK+_evDEF+_evSPD+_evSATK+_evSDEF)>510 || _evHP>255 || _evATK>255 || _evDEF>255 || _evSPD>255 || _evSATK>255 || _evSDEF>255)
        {
            _evHP = _rand_gen.lcrng_next(_generation) % 256;
            _evATK = _rand_gen.lcrng_next(_generation) % 256;
            _evDEF = _rand_gen.lcrng_next(_generation) % 256;
            _evSPD = _rand_gen.lcrng_next(_generation) % 256;
            _evSATK = _rand_gen.lcrng_next(_generation) % 256;
            _evSDEF = _rand_gen.lcrng_next(_generation) % 256;
        }

        _gender = _determine_gender();
        _nature = _determine_nature();
        _ability = _determine_ability();

        _set_stats();
    }

    std::string team_pokemon_modernimpl::get_gender() const {return _gender;}

    std::string team_pokemon_modernimpl::get_nature() const {return _nature;}

    std::string team_pokemon_modernimpl::get_ability() const {return _ability;}

    bool team_pokemon_modernimpl::is_shiny() const
    {
        int p1, p2, E, F;
        p1 = (_personality & 0xFFFF0000) >> 16;
        p2 = _personality & 0xFFFF;
        E = _tid.public_id ^ _tid.secret_id;
        F = p1 ^ p2;
        return (E ^ F) < 8;
    }

    pkmn::dict<std::string, unsigned int> team_pokemon_modernimpl::get_stats() const
    {
        pkmn::dict<std::string, unsigned int> stats;
        stats["HP"] = _HP;
        stats["Attack"] = _ATK;
        stats["Defense"] = _DEF;
        stats["Special Attack"] = _SATK;
        stats["Special Defense"] = _SDEF;
        stats["Speed"] = _SPD;

        return stats;
    }

    pkmn::dict<std::string, unsigned int> team_pokemon_modernimpl::get_EVs() const
    {
        pkmn::dict<std::string, unsigned int> EVs;
        EVs["HP"] = _evHP;
        EVs["Attack"] = _evATK;
        EVs["Defense"] = _evDEF;
        EVs["Special Attack"] = _evSATK;
        EVs["Special Defense"] = _evSDEF;
        EVs["Speed"] = _evSPD;

        return EVs;
    }

    pkmn::dict<std::string, unsigned int> team_pokemon_modernimpl::get_IVs() const
    {
        pkmn::dict<std::string, unsigned int> IVs;
        IVs["HP"] = _ivHP;
        IVs["Attack"] = _ivATK;
        IVs["Defense"] = _ivDEF;
        IVs["Special Attack"] = _ivSATK;
        IVs["Special Defense"] = _ivSDEF;
        IVs["Speed"] = _ivSPD;

        return IVs;
    }

    void team_pokemon_modernimpl::set_personality(unsigned int personality)
    {
        _personality = personality;
        _ability = _determine_ability();
        _gender = _determine_gender();
        _nature = _determine_nature();
    }

    void team_pokemon_modernimpl::set_gender(std::string gender)
    {
        if(gender == "Male" or gender == "Female") _gender = gender;
    }

    void team_pokemon_modernimpl::set_nature(std::string nature)
    {
        //Search for given nature in database
        std::string query_string = str(boost::format("SELECT nature_id FROM nature_names WHERE name='%s'")
                                       % nature.c_str());
        SQLite::Statement nature_names_query(_db, query_string.c_str());
        if(nature_names_query.executeStep())
        {
            _nature = nature;
            _set_stats();
            return;
        }

        //If not in nature_names, check in abilities
        query_string = str(boost::format("Select id FROM natures WHERE identifier='%s'")
                           % nature);
        SQLite::Statement natures_query(_db, query_string.c_str());
        if(natures_query.executeStep())
        {
            nature[0] = tolower(nature[0]);
            _nature = nature;
            _set_stats();
        }
    }

    void team_pokemon_modernimpl::set_ability(std::string ability)
    {
        //Search for given ability in database
        std::string query_string = str(boost::format("SELECT ability_id FROM ability_names WHERE name='%s'")
                                       % ability.c_str());
        SQLite::Statement ability_names_query(_db, query_string.c_str());
        if(ability_names_query.executeStep())
        {
            _ability = ability;
            return;
        }

        //If not in ability_names, check in abilities
        query_string = str(boost::format("Select id FROM abilities WHERE identifier='%s'")
                           % ability);
        SQLite::Statement abilities_query(_db, query_string.c_str());
        if(abilities_query.executeStep())
        {
            ability[0] = tolower(ability[0]);
            _ability = ability;
        }
    }

    void team_pokemon_modernimpl::set_using_hidden_ability(bool val)
    {
        _has_hidden_ability = val;
        _ability = _determine_ability();
    }

    void team_pokemon_modernimpl::set_EV(std::string EV, unsigned int val)
    {
        if(val > 255)
        {
            cerr << "Gen 3-5 EV's must be 0-255." << endl;
            exit(EXIT_FAILURE);
        }

        if(EV == "HP")
        {
            _evHP = val;
            _HP = _get_hp();
        }
        else if(EV == "Attack")
        {
            _evATK = val;
            _ATK = _get_stat("Attack", _evATK, _ivATK);
        }
        else if(EV == "Defense")
        {
            _evDEF = val;
            _DEF = _get_stat("Defense", _evDEF, _ivDEF);
        }
        else if(EV == "Speed")
        {
            _evSPD = val;
            _SPD = _get_stat("Speed", _evSPD, _ivSPD);
        }
        else if(EV == "Special Attack")
        {
            _evSATK = val;
            _SATK = _get_stat("Special Attack", _evSATK, _ivSATK);
        }
        else if(EV == "Special Defense")
        {
            _evSDEF = val;
            _SDEF = _get_stat("Special Defense", _evSDEF, _ivSDEF);
        }
    }

    void team_pokemon_modernimpl::set_IV(std::string IV, unsigned int val)
    {
        if(val > 31)
        {
            cerr << "Gen 3-5 IV's must be 0-31." << endl;
            exit(EXIT_FAILURE);
        }

        if(IV == "HP")
        {
            _ivHP = val;
            _HP = _get_hp();
        }
        else if(IV == "Attack")
        {
            _ivATK = val;
            _ATK = _get_stat("Attack", _evATK, _ivATK);
        }
        else if(IV == "Defense")
        {
            _ivDEF = val;
            _DEF = _get_stat("Defense", _evDEF, _ivDEF);
        }
        else if(IV == "Speed")
        {
            _ivSPD = val;
            _SPD = _get_stat("Speed", _evSPD, _ivSPD);
        }
        else if(IV == "Special Attack")
        {
            _ivSATK = val;
            _SATK = _get_stat("Special Attack", _evSATK, _ivSATK);
        }
        else if(IV == "Special Defense")
        {
            _ivSDEF = val;
            _SDEF = _get_stat("Special Defense", _evSDEF, _ivSDEF);
        }
    }

    void team_pokemon_modernimpl::set_form(unsigned int form)
    {
        _base_pkmn->set_form(form);
        _set_stats();
        _ability = _determine_ability();
    }

    void team_pokemon_modernimpl::set_form(std::string form)
    {
        _base_pkmn->set_form(form);
        _set_stats();
        _ability = _determine_ability();
    }

    unsigned int team_pokemon_modernimpl::_get_hp() const
    {
        pkmn::dict<std::string, unsigned int> stats = _base_pkmn->get_base_stats();

        unsigned int hp_val = int(floor(((double(_ivHP) + (2.0*double(stats["HP"])) + (0.25*double(_evHP)) + 100.0)
                            * double(_level))/100.0 + 10.0));
        return hp_val;
    }

    unsigned int team_pokemon_modernimpl::_get_stat(std::string stat, unsigned int EV, unsigned int IV) const
    {
        //TODO: better solution
        pkmn::dict<std::string, unsigned int> stat_enums = boost::assign::map_list_of
                                                     ("HP", Stats::HP)
                                                     ("Attack", Stats::ATTACK)
                                                     ("Defense", Stats::DEFENSE)
                                                     ("Special Attack", Stats::SPECIAL_ATTACK)
                                                     ("Special Defense", Stats::SPECIAL_DEFENSE)
                                                     ("Speed", Stats::SPEED)
        ;

        pkmn::dict<std::string, unsigned int> stats = _base_pkmn->get_base_stats();
        double ability_mod = database::get_nature_stat_effect(_nature, stat_enums[stat]);

        unsigned int stat_val = int(ceil(((((double(IV) + 2.0*double(stats[stat]) + 0.25*double(EV))
                              * double(_level))/100.0) + 5.0) * ability_mod));
        return stat_val;
    }

    void team_pokemon_modernimpl::_set_stats()
    {
        if(_base_pkmn->get_species_id() == Species::SHEDINJA) _HP = 1;
        else _HP = _get_hp();
        _ATK = _get_stat("Attack", _evATK, _ivATK);
        _DEF = _get_stat("Defense", _evDEF, _ivDEF);
        _SPD = _get_stat("Speed", _evSPD, _ivSPD);
        _SATK = _get_stat("Special Attack", _evSATK, _ivSATK);
        _SDEF = _get_stat("Special Defense", _evSDEF, _ivSDEF);
    }

    std::string team_pokemon_modernimpl::_determine_ability() const
    {
        string_pair_t abilities = _base_pkmn->get_abilities();
        std::string hidden_ability = _base_pkmn->get_hidden_ability();

        if(_base_pkmn->get_species_id() == Species::NONE or _base_pkmn->get_species_id() == Species::INVALID) return "None";
        else if(_has_hidden_ability and _generation >= 5) return hidden_ability;
        else return ((_personality % 2) == 0) ? abilities.first : abilities.second;
    }

    std::string team_pokemon_modernimpl::_determine_gender() const
    {
        if(_base_pkmn->get_chance_male() + _base_pkmn->get_chance_female() == 0
        or _base_pkmn->get_species_id() == Species::NONE
        or _base_pkmn->get_species_id() == Species::INVALID) return "Genderless";
        else if(_base_pkmn->get_chance_male() == 1.0) return "Male";
        else if(_base_pkmn->get_chance_female() == 1.0) return "Female";
        else
        {
            if((_personality % 256) > int(floor(255*(1-_base_pkmn->get_chance_male())))) return "Male";
            else return "Female";
        }

        //Should never get here, this stops Clang from complaining
        return "Male";
    }

    std::string team_pokemon_modernimpl::_determine_nature() const
    {
        return database::get_nature_name(_personality % 24);
    }
} /* namespace pkmn */
<|endoftext|>


<commit_before>/*************************************************************************************
 *  Copyright (C) 2012 by Alejandro Fiestas Olivares <afiestas@kde.org>              *
 *                                                                                *
 *  This program is free software; you can redistribute it and/or                    *
 *  modify it under the terms of the GNU General Public License                      *
 *  as published by the Free Software Foundation; either version 2                   *
 *  of the License, or (at your option) any later version.                           *
 *                                                                                *
 *  This program is distributed in the hope that it will be useful,                  *
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of                   *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                    *
 *  GNU General Public License for more details.                                     *
 *                                                                                *
 *  You should have received a copy of the GNU General Public License                *
 *  along with this program; if not, write to the Free Software                      *
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA   *
 *************************************************************************************/

#include "console.h"

#include <QX11Info>
#include <QtCore/QDebug>
#include <QtCore/QDateTime>
#include <QtCore/QDir>
#include <QtCore/QTextStream>

#include <qjson/parser.h>
#include <qjson/serializer.h>

#include <kscreen/config.h>
#include <kscreen/output.h>
#include <kscreen/mode.h>
#include <kscreen/configmonitor.h>
#include <kscreen/edid.h>

#include <KStandardDirs>

using namespace KScreen;

Console::Console(QObject* parent): QObject(parent)
{
    qDebug() << "START";
    QDateTime date = QDateTime::currentDateTime();
    m_config = Config::current();
    qDebug() << "Config::current() took" << date.msecsTo(QDateTime::currentDateTime()) << "milliseconds";
}

Console::~Console()
{

}

void Console::printConfig()
{
    qDebug() << "KScreen version: " << KSCREEN_VERSION;

    if (!m_config) {
        qDebug() << "Config is invalid, probably backend couldn't load";
        return;
    }
    if (!m_config->screen()) {
        qDebug() << "No screen in the configuration, broken backend";
        return;
    }

    qDebug() << "Screen:";
    qDebug() << "\tmaxSize:" << m_config->screen()->maxSize();
    qDebug() << "\tminSize:" << m_config->screen()->minSize();
    qDebug() << "\tcurrentSize:" << m_config->screen()->currentSize();

    OutputList outputs = m_config->outputs();
    Q_FOREACH(Output *output, outputs) {
        qDebug() << "\n-----------------------------------------------------\n";
        qDebug() << "Id: " << output->id();
        qDebug() << "Name: " << output->name();
        qDebug() << "Type: " << typetoString(output->type());
        qDebug() << "Connected: " << output->isConnected();
        if (!output->isConnected()) {
            continue;
        }
        qDebug() << "Enabled: " << output->isEnabled();
        qDebug() << "Primary: " << output->isPrimary();
        qDebug() << "Rotation: " << output->rotation();
        qDebug() << "Pos: " << output->pos();
        if (output->currentMode()) {
            qDebug() << "Size: " << output->currentMode()->size();
        }
        qDebug() << "Clones: " << output->clones().isEmpty();
        qDebug() << "Mode: " << output->currentModeId();
        qDebug() << "Preferred Mode: " << output->preferredModeId();
        qDebug() << "Preferred modes: " << output->preferredModes();
        qDebug() << "Modes: ";

        ModeList modes = output->modes();
        Q_FOREACH(Mode* mode, modes) {
            qDebug() << "\t" << mode->id() << "  " << mode->name() << " " << mode->size() << " " << mode->refreshRate();
        }

        Edid* edid = output->edid();
        qDebug() << "EDID Info: ";
        if (edid && edid->isValid()) {
            qDebug() << "\tDevice ID: " << edid->deviceId();
            qDebug() << "\tName: " << edid->name();
            qDebug() << "\tVendor: " << edid->vendor();
            qDebug() << "\tSerial: " << edid->serial();
            qDebug() << "\tEISA ID: " << edid->eisaId();
            qDebug() << "\tHash: " << edid->hash();
            qDebug() << "\tWidth: " << edid->width();
            qDebug() << "\tHeight: " << edid->height();
            qDebug() << "\tGamma: " << edid->gamma();
            qDebug() << "\tRed: " << edid->red();
            qDebug() << "\tGreen: " << edid->green();
            qDebug() << "\tBlue: " << edid->blue();
            qDebug() << "\tWhite: " << edid->white();
        } else {
            qDebug() << "\tUnavailable";
        }
    }
}

QString Console::typetoString(const Output::Type& type) const
{
    switch (type) {
        case Output::Unknown:
            return QLatin1String("Unknown");
        case Output::Panel:
            return QLatin1String("Panel (Laptop)");
        case Output::VGA:
            return QLatin1String("VGA");
        case Output::DVII:
            return QLatin1String("DVI-I");
        case Output::DVIA:
            return QLatin1String("DVI-A");
        case Output::DVID:
            return QLatin1String("DVI-D");
        case Output::HDMI:
            return QLatin1String("HDMI");
        case Output::TV:
            return QLatin1String("TV");
        case Output::TVComposite:
            return QLatin1String("TV-Composite");
        case Output::TVSVideo:
            return QLatin1String("TV-SVideo");
        case Output::TVComponent:
            return QLatin1String("TV-Component");
        case Output::TVSCART:
            return QLatin1String("TV-SCART");
        case Output::TVC4:
            return QLatin1String("TV-C4");
        case Output::DisplayPort:
            return QLatin1String("DisplayPort");
        default:
            return QLatin1String("Invalid Type");

    };
}

void Console::printSerializations()
{
    QString path = KStandardDirs::locateLocal("data", "kscreen/");
    qDebug() << "Configs in: " << path;

    QDir dir(path);
    QStringList files = dir.entryList(QDir::Files);
    qDebug() << "Number of files: " << files.count() << endl;

    bool ok;
    QJson::Parser parser;
    QJson::Serializer serializer;
    serializer.setIndentMode(QJson::IndentFull);
    Q_FOREACH(const QString fileName, files) {
        ok = true;
        qDebug() << fileName;
        QFile file(path + "/" + fileName);
        file.open(QFile::ReadOnly);
        QVariant data = parser.parse(file.readAll(), &ok);
        if (!ok) {
            qDebug() << "    " << "can't parse file";
            qDebug() << "    " << parser.errorString();
            continue;
        }

        qDebug() << serializer.serialize(data) << endl;
    }
}

void Console::monitor()
{
    ConfigMonitor::instance()->addConfig(m_config);
}

void Console::monitorAndPrint()
{
    monitor();
    connect(ConfigMonitor::instance(), SIGNAL(configurationChanged()), SLOT(printConfig()));
}

#include <console.moc>
<commit_msg>Output of "Clones" bit more good looking<commit_after>/*************************************************************************************
 *  Copyright (C) 2012 by Alejandro Fiestas Olivares <afiestas@kde.org>              *
 *                                                                                *
 *  This program is free software; you can redistribute it and/or                    *
 *  modify it under the terms of the GNU General Public License                      *
 *  as published by the Free Software Foundation; either version 2                   *
 *  of the License, or (at your option) any later version.                           *
 *                                                                                *
 *  This program is distributed in the hope that it will be useful,                  *
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of                   *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                    *
 *  GNU General Public License for more details.                                     *
 *                                                                                *
 *  You should have received a copy of the GNU General Public License                *
 *  along with this program; if not, write to the Free Software                      *
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA   *
 *************************************************************************************/

#include "console.h"

#include <QX11Info>
#include <QtCore/QDebug>
#include <QtCore/QDateTime>
#include <QtCore/QDir>
#include <QtCore/QTextStream>

#include <qjson/parser.h>
#include <qjson/serializer.h>

#include <kscreen/config.h>
#include <kscreen/output.h>
#include <kscreen/mode.h>
#include <kscreen/configmonitor.h>
#include <kscreen/edid.h>

#include <KStandardDirs>

using namespace KScreen;

Console::Console(QObject* parent): QObject(parent)
{
    qDebug() << "START";
    QDateTime date = QDateTime::currentDateTime();
    m_config = Config::current();
    qDebug() << "Config::current() took" << date.msecsTo(QDateTime::currentDateTime()) << "milliseconds";
}

Console::~Console()
{

}

void Console::printConfig()
{
    qDebug() << "KScreen version: " << KSCREEN_VERSION;

    if (!m_config) {
        qDebug() << "Config is invalid, probably backend couldn't load";
        return;
    }
    if (!m_config->screen()) {
        qDebug() << "No screen in the configuration, broken backend";
        return;
    }

    qDebug() << "Screen:";
    qDebug() << "\tmaxSize:" << m_config->screen()->maxSize();
    qDebug() << "\tminSize:" << m_config->screen()->minSize();
    qDebug() << "\tcurrentSize:" << m_config->screen()->currentSize();

    OutputList outputs = m_config->outputs();
    Q_FOREACH(Output *output, outputs) {
        qDebug() << "\n-----------------------------------------------------\n";
        qDebug() << "Id: " << output->id();
        qDebug() << "Name: " << output->name();
        qDebug() << "Type: " << typetoString(output->type());
        qDebug() << "Connected: " << output->isConnected();
        if (!output->isConnected()) {
            continue;
        }
        qDebug() << "Enabled: " << output->isEnabled();
        qDebug() << "Primary: " << output->isPrimary();
        qDebug() << "Rotation: " << output->rotation();
        qDebug() << "Pos: " << output->pos();
        if (output->currentMode()) {
            qDebug() << "Size: " << output->currentMode()->size();
        }
        if (output->clones().isEmpty()) {
            qDebug() << "Clones: " << "None";
        } else {
            qDebug() << "Clones: " << output->clones().count();
        }
        qDebug() << "Mode: " << output->currentModeId();
        qDebug() << "Preferred Mode: " << output->preferredModeId();
        qDebug() << "Preferred modes: " << output->preferredModes();
        qDebug() << "Modes: ";

        ModeList modes = output->modes();
        Q_FOREACH(Mode* mode, modes) {
            qDebug() << "\t" << mode->id() << "  " << mode->name() << " " << mode->size() << " " << mode->refreshRate();
        }

        Edid* edid = output->edid();
        qDebug() << "EDID Info: ";
        if (edid && edid->isValid()) {
            qDebug() << "\tDevice ID: " << edid->deviceId();
            qDebug() << "\tName: " << edid->name();
            qDebug() << "\tVendor: " << edid->vendor();
            qDebug() << "\tSerial: " << edid->serial();
            qDebug() << "\tEISA ID: " << edid->eisaId();
            qDebug() << "\tHash: " << edid->hash();
            qDebug() << "\tWidth: " << edid->width();
            qDebug() << "\tHeight: " << edid->height();
            qDebug() << "\tGamma: " << edid->gamma();
            qDebug() << "\tRed: " << edid->red();
            qDebug() << "\tGreen: " << edid->green();
            qDebug() << "\tBlue: " << edid->blue();
            qDebug() << "\tWhite: " << edid->white();
        } else {
            qDebug() << "\tUnavailable";
        }
    }
}

QString Console::typetoString(const Output::Type& type) const
{
    switch (type) {
        case Output::Unknown:
            return QLatin1String("Unknown");
        case Output::Panel:
            return QLatin1String("Panel (Laptop)");
        case Output::VGA:
            return QLatin1String("VGA");
        case Output::DVII:
            return QLatin1String("DVI-I");
        case Output::DVIA:
            return QLatin1String("DVI-A");
        case Output::DVID:
            return QLatin1String("DVI-D");
        case Output::HDMI:
            return QLatin1String("HDMI");
        case Output::TV:
            return QLatin1String("TV");
        case Output::TVComposite:
            return QLatin1String("TV-Composite");
        case Output::TVSVideo:
            return QLatin1String("TV-SVideo");
        case Output::TVComponent:
            return QLatin1String("TV-Component");
        case Output::TVSCART:
            return QLatin1String("TV-SCART");
        case Output::TVC4:
            return QLatin1String("TV-C4");
        case Output::DisplayPort:
            return QLatin1String("DisplayPort");
        default:
            return QLatin1String("Invalid Type");

    };
}

void Console::printSerializations()
{
    QString path = KStandardDirs::locateLocal("data", "kscreen/");
    qDebug() << "Configs in: " << path;

    QDir dir(path);
    QStringList files = dir.entryList(QDir::Files);
    qDebug() << "Number of files: " << files.count() << endl;

    bool ok;
    QJson::Parser parser;
    QJson::Serializer serializer;
    serializer.setIndentMode(QJson::IndentFull);
    Q_FOREACH(const QString fileName, files) {
        ok = true;
        qDebug() << fileName;
        QFile file(path + "/" + fileName);
        file.open(QFile::ReadOnly);
        QVariant data = parser.parse(file.readAll(), &ok);
        if (!ok) {
            qDebug() << "    " << "can't parse file";
            qDebug() << "    " << parser.errorString();
            continue;
        }

        qDebug() << serializer.serialize(data) << endl;
    }
}

void Console::monitor()
{
    ConfigMonitor::instance()->addConfig(m_config);
}

void Console::monitorAndPrint()
{
    monitor();
    connect(ConfigMonitor::instance(), SIGNAL(configurationChanged()), SLOT(printConfig()));
}

#include <console.moc>
<|endoftext|>