<commit_before>/*
    open source routing machine
    Copyright (C) Dennis Luxen, others 2010

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU AFFERO General Public License as published by
the Free Software Foundation; either version 3 of the License, or
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 Affero General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
or see http://www.gnu.org/licenses/agpl.txt.
 */

#include "DataStructures/QueryEdge.h"
#include "DataStructures/SharedMemoryFactory.h"
#include "DataStructures/SharedMemoryVectorWrapper.h"
#include "DataStructures/StaticGraph.h"
#include "DataStructures/StaticRTree.h"
#include "Server/DataStructures/BaseDataFacade.h"
#include "Server/DataStructures/SharedDataType.h"
#include "Util/BoostFilesystemFix.h"
#include "Util/GraphLoader.h"
#include "Util/IniFile.h"
#include "Util/SimpleLogger.h"
#include "typedefs.h"

#include <boost/integer.hpp>
#include <boost/filesystem/fstream.hpp>

#include <string>
#include <vector>

typedef StaticGraph<QueryEdge::EdgeData> QueryGraph;
typedef StaticRTree<BaseDataFacade<QueryEdge::EdgeData>::RTreeLeaf, true>::TreeNode RTreeNode;

void StoreIntegerInSharedMemory(
    const uint64_t value,
    const SharedDataType data_type)
{
        SharedMemory * memory = SharedMemoryFactory::Get(
            data_type,
            sizeof(uint64_t)
        );
        uint64_t * ptr = static_cast<uint64_t *>( memory->Ptr() );
        *ptr = value;
}

int main(int argc, char * argv[]) {
    try {
        LogPolicy::GetInstance().Unmute();
        SimpleLogger().Write() << "Checking input parameters";

        boost::filesystem::path base_path = boost::filesystem::absolute(
            (argc > 1 ? argv[1] : "server.ini")
        ).parent_path();
        IniFile server_config((argc > 1 ? argv[1] : "server.ini"));
        //check contents of config file
        if ( !server_config.Holds("hsgrData")) {
            throw OSRMException("no ram index file name in server ini");
        }
        if ( !server_config.Holds("ramIndex") ) {
            throw OSRMException("no mem index file name in server ini");
        }
        if ( !server_config.Holds("nodesData") ) {
            throw OSRMException("no nodes file name in server ini");
        }
        if ( !server_config.Holds("edgesData") ) {
            throw OSRMException("no edges file name in server ini");
        }

        //generate paths of data files
        boost::filesystem::path hsgr_path = boost::filesystem::absolute(
                server_config.GetParameter("hsgrData"),
                base_path
        );
        boost::filesystem::path ram_index_path = boost::filesystem::absolute(
                server_config.GetParameter("ramIndex"),
                base_path
        );
        boost::filesystem::path node_data_path = boost::filesystem::absolute(
                server_config.GetParameter("nodesData"),
                base_path
        );
        boost::filesystem::path edge_data_path = boost::filesystem::absolute(
                server_config.GetParameter("edgesData"),
                base_path
        );
        boost::filesystem::path name_data_path = boost::filesystem::absolute(
                server_config.GetParameter("namesData"),
                base_path
        );
        boost::filesystem::path timestamp_path = boost::filesystem::absolute(
                server_config.GetParameter("timestamp"),
                base_path
        );

        // check if data files empty
        if ( 0 == boost::filesystem::file_size( node_data_path ) ) {
            throw OSRMException("nodes file is empty");
        }
        if ( 0 == boost::filesystem::file_size( edge_data_path ) ) {
            throw OSRMException("edges file is empty");
        }

        //TODO: remove any previous data

        // Loading street names
        SimpleLogger().Write() << "Loading names index";
        uint64_t number_of_bytes = 0;
        boost::filesystem::ifstream name_stream(
            name_data_path, std::ios::binary
        );
        unsigned number_of_elements = 0;
        name_stream.read((char *)&number_of_elements, sizeof(unsigned));
        BOOST_ASSERT_MSG(0 != number_of_elements, "name file broken");
        StoreIntegerInSharedMemory(number_of_elements, NAME_INDEX_SIZE);
        number_of_bytes = sizeof(unsigned)*number_of_elements;

        SharedMemory * index_memory = SharedMemoryFactory::Get(
            NAMES_INDEX,
            number_of_bytes
        );
        unsigned * index_ptr = static_cast<unsigned *>( index_memory->Ptr() );
        name_stream.read((char*)index_ptr, number_of_bytes);

        SimpleLogger().Write() << "Loading names list";
        name_stream.read((char *)&number_of_bytes, sizeof(unsigned));
        StoreIntegerInSharedMemory(number_of_bytes, NAME_INDEX_SIZE);
        SharedMemory * char_memory  = SharedMemoryFactory::Get(
            NAMES_LIST, number_of_bytes+1
        );
        char * char_ptr = static_cast<char *>( char_memory->Ptr() );
        name_stream.read(char_ptr, number_of_bytes);
        name_stream.close();

        std::vector<QueryGraph::_StrNode> node_list;
        std::vector<QueryGraph::_StrEdge> edge_list;

        //TODO BEGIN:
        //Read directly into shared memory
        unsigned m_check_sum = 0;
        SimpleLogger().Write() << "Loading graph node list";
        uint64_t m_number_of_nodes = readHSGRFromStream(
            hsgr_path,
            node_list,
            edge_list,
            &m_check_sum
        );
        //TODO END

        StoreIntegerInSharedMemory(node_list.size(), GRAPH_NODE_LIST_SIZE);
        SharedMemory * graph_node_memory  = SharedMemoryFactory::Get(
            GRAPH_NODE_LIST,
            sizeof(QueryGraph::_StrNode)*node_list.size()
        );
        QueryGraph::_StrNode * graph_node_ptr = static_cast<QueryGraph::_StrNode *>(
            graph_node_memory->Ptr()
        );

        std::copy(node_list.begin(), node_list.end(), graph_node_ptr);

        SimpleLogger().Write() << "Loading graph edge list";
        StoreIntegerInSharedMemory(edge_list.size(), GRAPH_EDGE_LIST_SIZE);
        SharedMemory * graph_edge_memory  = SharedMemoryFactory::Get(
            GRAPH_EDGE_LIST,
            sizeof(QueryGraph::_StrEdge)*edge_list.size()
        );
        QueryGraph::_StrEdge * graph_edge_ptr = static_cast<QueryGraph::_StrEdge *>(
            graph_edge_memory->Ptr()
        );
        std::copy(edge_list.begin(), edge_list.end(), graph_edge_ptr);

        // load checksum
        SimpleLogger().Write() << "Loading check sum";
        StoreIntegerInSharedMemory(m_check_sum, CHECK_SUM);

        SimpleLogger().Write() << "Loading timestamp";
        std::string m_timestamp;
        if( boost::filesystem::exists(timestamp_path) ) {
            boost::filesystem::ifstream timestampInStream( timestamp_path );
            if(!timestampInStream) {
                SimpleLogger().Write(logWARNING) << timestamp_path << " not found";
            }
            getline(timestampInStream, m_timestamp);
            timestampInStream.close();
        }
        if(m_timestamp.empty()) {
            m_timestamp = "n/a";
        }
        if(25 < m_timestamp.length()) {
            m_timestamp.resize(25);
        }
        StoreIntegerInSharedMemory(m_timestamp.length(), TIMESTAMP_SIZE);
        SharedMemory * timestamp_memory  = SharedMemoryFactory::Get(
            TIMESTAMP, m_timestamp.length()
        );
        char * timestamp_ptr = static_cast<char *>( timestamp_memory->Ptr() );
        std::copy(
            m_timestamp.c_str(),
            m_timestamp.c_str()+m_timestamp.length(),
            timestamp_ptr
        );

        //Loading information for original edges
        boost::filesystem::ifstream edges_input_stream(
            edge_data_path,
            std::ios::binary
        );
        unsigned number_of_edges = 0;
        edges_input_stream.read((char*)&number_of_edges, sizeof(unsigned));
        SimpleLogger().Write() << "Loading via node, coordinates and turn instruction list";
        StoreIntegerInSharedMemory(number_of_edges, NAME_ID_LIST_SIZE);
        StoreIntegerInSharedMemory(number_of_edges, TURN_INSTRUCTION_LIST_SIZE);
        StoreIntegerInSharedMemory(number_of_edges, VIA_NODE_LIST_SIZE);

        SharedMemory * name_id_memory  = SharedMemoryFactory::Get(
            NAME_ID_LIST,
            number_of_edges*sizeof(unsigned)
        );
        unsigned * name_id_ptr = static_cast<unsigned *>( name_id_memory->Ptr() );

        SharedMemory *via_node_memory  = SharedMemoryFactory::Get(
            VIA_NODE_LIST,
            number_of_edges*sizeof(unsigned)
        );
        unsigned * via_node_ptr = static_cast<unsigned *>( via_node_memory->Ptr() );

        SharedMemory *turn_instruction_memory  = SharedMemoryFactory::Get(
            TURN_INSTRUCTION_LIST,
            number_of_edges*sizeof(TurnInstruction)
        );
        unsigned * turn_instructions_ptr = static_cast<unsigned *>( turn_instruction_memory->Ptr() );

        OriginalEdgeData current_edge_data;
        for(unsigned i = 0; i < number_of_edges; ++i) {
            edges_input_stream.read(
                (char*)&(current_edge_data),
                sizeof(OriginalEdgeData)
            );
            via_node_ptr[i] = current_edge_data.viaNode;
            name_id_ptr[i]  = current_edge_data.nameID;
            turn_instructions_ptr[i] = current_edge_data.turnInstruction;
        }
        edges_input_stream.close();

        // Loading list of coordinates
        SimpleLogger().Write(logDEBUG) << "Loading coordinates list";
        boost::filesystem::ifstream nodes_input_stream(
            node_data_path,
            std::ios::binary
        );
        unsigned number_of_nodes = 0;
        nodes_input_stream.read((char *)&number_of_nodes, sizeof(unsigned));
        StoreIntegerInSharedMemory(number_of_nodes, COORDINATE_LIST_SIZE);

        SharedMemory *coordinates_memory  = SharedMemoryFactory::Get(
            COORDINATE_LIST,
            number_of_nodes*sizeof(FixedPointCoordinate)
        );
        FixedPointCoordinate * coordinates_ptr = static_cast<FixedPointCoordinate *>( coordinates_memory->Ptr() );

        NodeInfo current_node;
        for(unsigned i = 0; i < number_of_nodes; ++i) {
            nodes_input_stream.read((char *)&current_node, sizeof(NodeInfo));
            coordinates_ptr[i] = FixedPointCoordinate(current_node.lat, current_node.lon);
        }
        nodes_input_stream.close();

        // Loading r-tree search data structure
        SimpleLogger().Write() << "loading r-tree search list";
        boost::filesystem::ifstream tree_node_file(
            ram_index_path,
            std::ios::binary
        );

        uint32_t tree_size = 0;
        tree_node_file.read((char*)&tree_size, sizeof(uint32_t));
        StoreIntegerInSharedMemory(tree_size, R_SEARCH_TREE_SIZE);
        //SimpleLogger().Write() << "reading " << tree_size << " tree nodes in " << (sizeof(TreeNode)*tree_size) << " bytes";
        SharedMemory * rtree_memory  = SharedMemoryFactory::Get(
            R_SEARCH_TREE,
            tree_size*sizeof(RTreeNode)
        );
        char * rtree_ptr = static_cast<char *>( rtree_memory->Ptr() );

        tree_node_file.read(rtree_ptr, sizeof(RTreeNode)*tree_size);
        tree_node_file.close();

    } catch(const std::exception & e) {
        SimpleLogger().Write(logWARNING) << "caught exception: " << e.what();
    }

    //

    return 0;
}
<commit_msg>load orig edge information<commit_after>/*
    open source routing machine
    Copyright (C) Dennis Luxen, others 2010

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU AFFERO General Public License as published by
the Free Software Foundation; either version 3 of the License, or
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 Affero General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
or see http://www.gnu.org/licenses/agpl.txt.
 */

#include "DataStructures/QueryEdge.h"
#include "DataStructures/SharedMemoryFactory.h"
#include "DataStructures/SharedMemoryVectorWrapper.h"
#include "DataStructures/StaticGraph.h"
#include "DataStructures/StaticRTree.h"
#include "Server/DataStructures/BaseDataFacade.h"
#include "Server/DataStructures/SharedDataType.h"
#include "Util/BoostFilesystemFix.h"
#include "Util/GraphLoader.h"
#include "Util/IniFile.h"
#include "Util/SimpleLogger.h"
#include "typedefs.h"

#include <boost/integer.hpp>
#include <boost/filesystem/fstream.hpp>

#include <string>
#include <vector>

int main(int argc, char * argv[]) {
    try {
        LogPolicy::GetInstance().Unmute();
        SimpleLogger().Write() << "Checking input parameters";

        boost::filesystem::path base_path = boost::filesystem::absolute(
            (argc > 1 ? argv[1] : "server.ini")
        ).parent_path();
        IniFile server_config((argc > 1 ? argv[1] : "server.ini"));
        //check contents of config file
        if ( !server_config.Holds("hsgrData")) {
            throw OSRMException("no ram index file name in server ini");
        }
        if ( !server_config.Holds("ramIndex") ) {
            throw OSRMException("no mem index file name in server ini");
        }
        if ( !server_config.Holds("nodesData") ) {
            throw OSRMException("no nodes file name in server ini");
        }
        if ( !server_config.Holds("edgesData") ) {
            throw OSRMException("no edges file name in server ini");
        }

        //generate paths of data files
        boost::filesystem::path hsgr_path = boost::filesystem::absolute(
                server_config.GetParameter("hsgrData"),
                base_path
        );
        boost::filesystem::path ram_index_path = boost::filesystem::absolute(
                server_config.GetParameter("ramIndex"),
                base_path
        );
        boost::filesystem::path node_data_path = boost::filesystem::absolute(
                server_config.GetParameter("nodesData"),
                base_path
        );
        boost::filesystem::path edge_data_path = boost::filesystem::absolute(
                server_config.GetParameter("edgesData"),
                base_path
        );
        boost::filesystem::path name_data_path = boost::filesystem::absolute(
                server_config.GetParameter("namesData"),
                base_path
        );
        boost::filesystem::path timestamp_path = boost::filesystem::absolute(
                server_config.GetParameter("timestamp"),
                base_path
        );

        // check if data files empty
        if ( 0 == boost::filesystem::file_size( node_data_path ) ) {
            throw OSRMException("nodes file is empty");
        }
        if ( 0 == boost::filesystem::file_size( edge_data_path ) ) {
            throw OSRMException("edges file is empty");
        }

        // Allocate a memory layout in shared memory //
          SharedMemory * layout_memory = SharedMemoryFactory::Get(
            LAYOUT_1,
            sizeof(SharedDataLayout)
        );
        SharedDataLayout * shared_layout_ptr = static_cast<SharedDataLayout *>(
            layout_memory->Ptr()
        );

        //                                                             //
        // collect number of elements to store in shared memory object //
        //                                                             //
        SimpleLogger().Write() << "Collecting files sizes";
        // number of entries in name index
        boost::filesystem::ifstream name_stream(
            name_data_path, std::ios::binary
        );
        unsigned name_index_size = 0;
        name_stream.read((char *)&name_index_size, sizeof(unsigned));
        shared_layout_ptr->name_index_list_size = name_index_size;
        BOOST_ASSERT_MSG(0 != shared_layout_ptr->name_index_list_size, "name file broken");

        unsigned number_of_chars = 0;
        name_stream.read((char *)&number_of_chars, sizeof(unsigned));
        shared_layout_ptr->name_char_list_size = number_of_chars;

        //Loading information for original edges
        boost::filesystem::ifstream edges_input_stream(
            edge_data_path,
            std::ios::binary
        );
        unsigned number_of_edges = 0;
        edges_input_stream.read((char*)&number_of_edges, sizeof(unsigned));
        SimpleLogger().Write() << "number of edges: " << number_of_edges;

        shared_layout_ptr->via_node_list_size = number_of_edges;
        shared_layout_ptr->name_id_list_size = number_of_edges;
        shared_layout_ptr->turn_instruction_list_size = number_of_edges;

        //TODO load graph node size
        //TODO load graph edge size
        //TODO load search tree size

        // allocate shared memory block
        SimpleLogger().Write() << "allocating shared memory of " << shared_layout_ptr->GetSizeOfLayout() << " bytes";
        SharedMemory * shared_memory = SharedMemoryFactory::Get(
            DATA_1,
            shared_layout_ptr->GetSizeOfLayout()
        );
        char * shared_memory_ptr = static_cast<char *>(shared_memory->Ptr());

        // read actual data into shared memory object //
        // Loading street names
        SimpleLogger().Write() << "Loading names index and chars from: " << name_data_path.string();
        unsigned * name_index_ptr = (unsigned*)(
            shared_memory_ptr + shared_layout_ptr->GetNameIndexOffset()
        );
        SimpleLogger().Write(logDEBUG) << "Bytes: " << shared_layout_ptr->name_index_list_size*sizeof(unsigned);

        name_stream.read(
            (char*)name_index_ptr,
            shared_layout_ptr->name_index_list_size*sizeof(unsigned)
        );

        SimpleLogger().Write() << "Loading names char list";
        SimpleLogger().Write(logDEBUG) << "Bytes: " << shared_layout_ptr->name_char_list_size*sizeof(char);
        char * name_char_ptr = shared_memory_ptr + shared_layout_ptr->GetNameListOffset();
        name_stream.read(
            name_char_ptr,
            shared_layout_ptr->name_char_list_size*sizeof(char)
        );
        name_stream.close();

        //load original edge information
        SimpleLogger().Write() << "Loading via node, coordinates and turn instruction list";

        NodeID * via_node_ptr = (NodeID *)(
            shared_memory_ptr + shared_layout_ptr->GetViaNodeListOffset()
        );

        unsigned * name_id_ptr = (unsigned *)(
            shared_memory_ptr + shared_layout_ptr->GetNameIDListOffset()
        );

        TurnInstruction * turn_instructions_ptr = (TurnInstruction *)(
            shared_memory_ptr + shared_layout_ptr->GetTurnInstructionListOffset()
        );

        OriginalEdgeData current_edge_data;
        for(unsigned i = 0; i < number_of_edges; ++i) {
            SimpleLogger().Write() << i << "/" << number_of_edges;
            edges_input_stream.read(
                (char*)&(current_edge_data),
                sizeof(OriginalEdgeData)
            );
            via_node_ptr[i] = current_edge_data.viaNode;
            name_id_ptr[i]  = current_edge_data.nameID;
            turn_instructions_ptr[i] = current_edge_data.turnInstruction;
        }
        edges_input_stream.close();

        std::vector<QueryGraph::_StrNode> node_list;
        std::vector<QueryGraph::_StrEdge> edge_list;

        //TODO BEGIN:
        //Read directly into shared memory
        unsigned m_check_sum = 0;
        SimpleLogger().Write() << "Loading graph node list";
        uint64_t m_number_of_nodes = readHSGRFromStream(
            hsgr_path,
            node_list,
            edge_list,
            &m_check_sum
        );
        SimpleLogger().Write() << "number of nodes: " << m_number_of_nodes;
        //TODO END

        SharedMemory * graph_node_memory  = SharedMemoryFactory::Get(
            GRAPH_NODE_LIST,
            sizeof(QueryGraph::_StrNode)*node_list.size()
        );
        QueryGraph::_StrNode * graph_node_ptr = static_cast<QueryGraph::_StrNode *>(
            graph_node_memory->Ptr()
        );

        std::copy(node_list.begin(), node_list.end(), graph_node_ptr);

        SimpleLogger().Write() << "Loading graph edge list";
        SharedMemory * graph_edge_memory  = SharedMemoryFactory::Get(
            GRAPH_EDGE_LIST,
            sizeof(QueryGraph::_StrEdge)*edge_list.size()
        );
        QueryGraph::_StrEdge * graph_edge_ptr = static_cast<QueryGraph::_StrEdge *>(
            graph_edge_memory->Ptr()
        );
        std::copy(edge_list.begin(), edge_list.end(), graph_edge_ptr);

        // load checksum
        SimpleLogger().Write() << "Loading check sum";

        SimpleLogger().Write() << "Loading timestamp";
        std::string m_timestamp;
        if( boost::filesystem::exists(timestamp_path) ) {
            boost::filesystem::ifstream timestampInStream( timestamp_path );
            if(!timestampInStream) {
                SimpleLogger().Write(logWARNING) << timestamp_path << " not found";
            }
            getline(timestampInStream, m_timestamp);
            timestampInStream.close();
        }
        if(m_timestamp.empty()) {
            m_timestamp = "n/a";
        }
        if(25 < m_timestamp.length()) {
            m_timestamp.resize(25);
        }
        SharedMemory * timestamp_memory  = SharedMemoryFactory::Get(
            TIMESTAMP, m_timestamp.length()
        );
        char * timestamp_ptr = static_cast<char *>( timestamp_memory->Ptr() );
        std::copy(
            m_timestamp.c_str(),
            m_timestamp.c_str()+m_timestamp.length(),
            timestamp_ptr
        );

        //Loading information for original edges
        boost::filesystem::ifstream edges_input_stream(
            edge_data_path,
            std::ios::binary
        );
        unsigned number_of_edges = 0;
        edges_input_stream.read((char*)&number_of_edges, sizeof(unsigned));
        SimpleLogger().Write() << "number of edges: " << number_of_edges;

        // Loading list of coordinates
        SimpleLogger().Write(logDEBUG) << "Loading coordinates list";
        boost::filesystem::ifstream nodes_input_stream(
            node_data_path,
            std::ios::binary
        );
        unsigned number_of_nodes = 0;
        nodes_input_stream.read((char *)&number_of_nodes, sizeof(unsigned));
        StoreIntegerInSharedMemory(number_of_nodes, COORDINATE_LIST_SIZE);

        SharedMemory *coordinates_memory  = SharedMemoryFactory::Get(
            COORDINATE_LIST,
            number_of_nodes*sizeof(FixedPointCoordinate)
        );
        FixedPointCoordinate * coordinates_ptr = static_cast<FixedPointCoordinate *>( coordinates_memory->Ptr() );

        NodeInfo current_node;
        for(unsigned i = 0; i < number_of_nodes; ++i) {
            nodes_input_stream.read((char *)&current_node, sizeof(NodeInfo));
            coordinates_ptr[i] = FixedPointCoordinate(current_node.lat, current_node.lon);
        }
        nodes_input_stream.close();

        // Loading r-tree search data structure
        SimpleLogger().Write() << "loading r-tree search list";
        boost::filesystem::ifstream tree_node_file(
            ram_index_path,
            std::ios::binary
        );

        uint32_t tree_size = 0;
        tree_node_file.read((char*)&tree_size, sizeof(uint32_t));
        StoreIntegerInSharedMemory(tree_size, R_SEARCH_TREE_SIZE);
        //SimpleLogger().Write() << "reading " << tree_size << " tree nodes in " << (sizeof(TreeNode)*tree_size) << " bytes";
        SharedMemory * rtree_memory  = SharedMemoryFactory::Get(
            R_SEARCH_TREE,
            tree_size*sizeof(RTreeNode)
        );
        char * rtree_ptr = static_cast<char *>( rtree_memory->Ptr() );

        tree_node_file.read(rtree_ptr, sizeof(RTreeNode)*tree_size);
        tree_node_file.close();

    } catch(const std::exception & e) {
        SimpleLogger().Write(logWARNING) << "caught exception: " << e.what();
    }

    return 0;
}
<|endoftext|>


<commit_before>#include "FileClient.h"
#include <iostream>
#include <cstring>
#include <unistd.h>
#include <memory>
#include <sstream>

FileClient::FileClient() {

}

FileClient::~FileClient() {

}

uint64_t FileClient::send(
    const std::string & host,
    const unsigned short host_port,
    std::string & file_path,
    uint64_t from,
    uint64_t to)
{
    uint64_t data_length = to - from;

    if(data_length <= 0) {
        std::cerr << "Length is <= 0" << std::endl;
        return 0;
    }

    Socket host_socket;
    host_socket.connectTo(host, host_port);

    if(!sendLength(host_socket, data_length)) {
        std::cerr << "Failed to send file of length - " << data_length << std::endl;
    }

    FILE* file_to_send;
    file_to_send = fopen(file_path.c_str(), "r");

    if(!file_to_send) {
        std::cerr << "Failed to open file to send" << std::endl;
        fclose(file_to_send);
        return 0;
    }

    if(fseek(file_to_send, from, SEEK_SET)) {
        std::cerr << "Failed to seek to position " << from << std::endl;
        fclose(file_to_send);
        return 0;
    }

//    std::unique_ptr<char[]> buffer(new char[data_length]);
    std::unique_ptr<char> buffer(new char);

    while(fread(buffer.get(), sizeof(char), 1, file_to_send)) {
        if(ferror(file_to_send)) {
            std::cerr << "Failed to read file" << std::endl;
            fclose(file_to_send);
            return 0;
        }

//        std::cout << buffer.get();

        int bytes_sent = write(host_socket.getFd(), buffer.get(), strlen(buffer.get()));

        if(bytes_sent == -1) {
            std::cerr << "Failed to write to socket" << std::endl;
            fclose(file_to_send);
            return 0;
        }

        if(feof(file_to_send)) {
            break;
        }
    }

    uint64_t fileID = getFileID(host_socket);

    fclose(file_to_send);
    return fileID;
}

bool FileClient::sendLength(const Socket& host_socket, uint64_t length) {

    int byte_sent = write(host_socket.getFd(), &length, sizeof(uint64_t));

    if(byte_sent == -1) {
        return false;
    }
    return true;
}

uint64_t FileClient::getFileID(const Socket& host_socket) {
    ClientInfo server_info;
    host_socket.listen();
    server_info = host_socket.accept();

    uint64_t file_id;
    int file_read = read(server_info.sock_fd, &file_id, sizeof(uint64_t));

    if(file_read == -1) {
        std::cerr << "Failed to read from socket" << std::endl;
        return 0;
    }

    return file_id;
}

std::pair<std::string, unsigned short> FileClient::getHostAndPort(const std::string& host) {
    std::vector<std::string> hostAndPort = split(host, ":");

    std::pair<std::string, unsigned short> host_port;

    host_port.first = hostAndPort[0];
    host_port.second = strtoul(hostAndPort[1].c_str(), nullptr, 10);

    return host_port;
}

std::vector<std::string> FileClient::split(std::string str, const char* delimiter) {
    std::vector<std::string> internal;
    std::stringstream ss(str);
    std::string tok;

    while(getline(ss, tok, delimiter[0])) {
        internal.push_back(tok);
    }

    return internal;
}

<commit_msg>fixed send() wrong length<commit_after>#include "FileClient.h"
#include <iostream>
#include <cstring>
#include <unistd.h>
#include <memory>
#include <sstream>

FileClient::FileClient() {

}

FileClient::~FileClient() {

}

uint64_t FileClient::send(
    const std::string & host,
    const unsigned short host_port,
    std::string & file_path,
    uint64_t from,
    uint64_t to)
{
    uint64_t data_length = to - from;

    if(data_length <= 0) {
        std::cerr << "Length is <= 0" << std::endl;
        return 0;
    }

    Socket host_socket;
    host_socket.connectTo(host, host_port);

    if(!sendLength(host_socket, data_length)) {
        std::cerr << "Failed to send file of length - " << data_length << std::endl;
    }

    FILE* file_to_send;
    file_to_send = fopen(file_path.c_str(), "r");

    if(!file_to_send) {
        std::cerr << "Failed to open file to send" << std::endl;
        fclose(file_to_send);
        return 0;
    }

    if(fseek(file_to_send, from, SEEK_SET)) {
        std::cerr << "Failed to seek to position " << from << std::endl;
        fclose(file_to_send);
        return 0;
    }

//    std::unique_ptr<char[]> buffer(new char[data_length]);
    std::unique_ptr<char> buffer(new char);

    while(data_length) {
        fread(buffer.get(), sizeof(char), 1, file_to_send);
        --data_length;

        if(ferror(file_to_send)) {
            std::cerr << "Failed to read file" << std::endl;
            fclose(file_to_send);
            return 0;
        }

//        std::cout << buffer.get();

        int bytes_sent = write(host_socket.getFd(), buffer.get(), strlen(buffer.get()));

        if(bytes_sent == -1) {
            std::cerr << "Failed to write to socket" << std::endl;
            fclose(file_to_send);
            return 0;
        }

        if(feof(file_to_send)) {
            break;
        }
    }

    uint64_t fileID = getFileID(host_socket);
    std::cout << "FileID: " << fileID << std::endl;

    fclose(file_to_send);
    return fileID;
}

bool FileClient::sendLength(const Socket& host_socket, uint64_t length) {

    int byte_sent = write(host_socket.getFd(), &length, sizeof(uint64_t));

    if(byte_sent == -1) {
        return false;
    }
    return true;
}

uint64_t FileClient::getFileID(const Socket& host_socket) {
    uint64_t file_id;
    int file_read = read(host_socket.getFd(), &file_id, sizeof(uint64_t));

    if(file_read == -1) {
        std::cerr << "Failed to read from socket" << std::endl;
        return 0;
    }

    return file_id;
}

std::pair<std::string, unsigned short> FileClient::getHostAndPort(const std::string& host) {
    std::vector<std::string> hostAndPort = split(host, ":");

    std::pair<std::string, unsigned short> host_port;

    host_port.first = hostAndPort[0];
    host_port.second = strtoul(hostAndPort[1].c_str(), nullptr, 10);

    return host_port;
}

std::vector<std::string> FileClient::split(std::string str, const char* delimiter) {
    std::vector<std::string> internal;
    std::stringstream ss(str);
    std::string tok;

    while(getline(ss, tok, delimiter[0])) {
        internal.push_back(tok);
    }

    return internal;
}

<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Compositor.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in
**     the documentation and/or other materials provided with the
**     distribution.
**   * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names
**     of its contributors may be used to endorse or promote products derived
**     from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "waylandeglintegration.h"

#include <QtCompositor/private/qwlcompositor_p.h>
#include <QtCompositor/private/qwlsurface_p.h>
#include <qpa/qplatformnativeinterface.h>
#include <QtGui/QGuiApplication>
#include <QtGui/QOpenGLContext>
#include <qpa/qplatformscreen.h>
#include <QtGui/QWindow>
#include <QtCore/QPointer>

#include <QDebug>

#include <EGL/egl.h>
#include <EGL/eglext.h>

#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>

#ifndef EGL_WL_bind_wayland_display
typedef EGLBoolean (EGLAPIENTRYP PFNEGLBINDWAYLANDDISPLAYWL) (EGLDisplay dpy, struct wl_display *display);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLUNBINDWAYLANDDISPLAYWL) (EGLDisplay dpy, struct wl_display *display);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYWAYLANDBUFFERWL) (EGLDisplay dpy, struct wl_buffer *buffer, EGLint attribute, EGLint *value);
#endif

#ifndef EGL_KHR_image
typedef EGLImageKHR (EGLAPIENTRYP PFNEGLCREATEIMAGEKHRPROC) (EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer, const EGLint *attrib_list);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLDESTROYIMAGEKHRPROC) (EGLDisplay dpy, EGLImageKHR image);
#endif

#ifndef GL_OES_EGL_image
typedef void (GL_APIENTRYP PFNGLEGLIMAGETARGETTEXTURE2DOESPROC) (GLenum target, GLeglImageOES image);
typedef void (GL_APIENTRYP PFNGLEGLIMAGETARGETRENDERBUFFERSTORAGEOESPROC) (GLenum target, GLeglImageOES image);
#endif

QT_BEGIN_NAMESPACE

class WaylandEglIntegrationPrivate
{
public:
    WaylandEglIntegrationPrivate()
        : egl_display(EGL_NO_DISPLAY)
        , valid(false)
        , flipperConnected(false)
        , egl_bind_wayland_display(0)
        , egl_unbind_wayland_display(0)
        , egl_query_wayland_buffer(0)
        , egl_create_image(0)
        , egl_destroy_image(0)
        , gl_egl_image_target_texture_2d(0)
    { }
    EGLDisplay egl_display;
    bool valid;
    bool flipperConnected;
#ifdef EGL_WL_request_client_buffer_format
    QPointer<WaylandSurface> directRenderSurface;
#endif
    PFNEGLBINDWAYLANDDISPLAYWL egl_bind_wayland_display;
    PFNEGLUNBINDWAYLANDDISPLAYWL egl_unbind_wayland_display;
    PFNEGLQUERYWAYLANDBUFFERWL egl_query_wayland_buffer;

    PFNEGLCREATEIMAGEKHRPROC egl_create_image;
    PFNEGLDESTROYIMAGEKHRPROC egl_destroy_image;

    PFNGLEGLIMAGETARGETTEXTURE2DOESPROC gl_egl_image_target_texture_2d;
};

WaylandEglIntegration::WaylandEglIntegration()
    : QWaylandGraphicsHardwareIntegration()
    , d_ptr(new WaylandEglIntegrationPrivate)
{
}

void WaylandEglIntegration::initializeHardware(QtWayland::Display *waylandDisplay)
{
    Q_D(WaylandEglIntegration);

    QPlatformNativeInterface *nativeInterface = QGuiApplication::platformNativeInterface();
    if (nativeInterface) {
        d->egl_display = nativeInterface->nativeResourceForWindow("EglDisplay", m_compositor->window());
        if (d->egl_display) {
            const char *extensionString = eglQueryString(d->egl_display, EGL_EXTENSIONS);
            if (extensionString && strstr(extensionString, "EGL_WL_bind_wayland_display"))
            {
                d->egl_bind_wayland_display =
                        reinterpret_cast<PFNEGLBINDWAYLANDDISPLAYWL>(eglGetProcAddress("eglBindWaylandDisplayWL"));
                d->egl_unbind_wayland_display =
                        reinterpret_cast<PFNEGLUNBINDWAYLANDDISPLAYWL>(eglGetProcAddress("eglUnbindWaylandDisplayWL"));
                d->egl_query_wayland_buffer =
                        reinterpret_cast<PFNEGLQUERYWAYLANDBUFFERWL>(eglGetProcAddress("eglQueryWaylandBufferWL"));
                d->egl_create_image =
                        reinterpret_cast<PFNEGLCREATEIMAGEKHRPROC>(eglGetProcAddress("eglCreateImageKHR"));
                d->egl_destroy_image =
                        reinterpret_cast<PFNEGLDESTROYIMAGEKHRPROC>(eglGetProcAddress("eglDestroyImageKHR"));
                d->gl_egl_image_target_texture_2d =
                        reinterpret_cast<PFNGLEGLIMAGETARGETTEXTURE2DOESPROC>(eglGetProcAddress("glEGLImageTargetTexture2DOES"));

                if (d->egl_bind_wayland_display
                        && d->egl_unbind_wayland_display
                        && d->egl_query_wayland_buffer
                        && d->egl_create_image
                        && d->egl_destroy_image
                        && d->gl_egl_image_target_texture_2d) {
                    if (d->egl_bind_wayland_display(d->egl_display, waylandDisplay->handle())) {
                        d->valid = true;
                    }
                }
            }
        }

        if (!d->valid)
            qWarning("Failed to initialize egl display\n");
    }
}

GLuint WaylandEglIntegration::createTextureFromBuffer(struct ::wl_resource *buffer, QOpenGLContext *)
{
    Q_D(WaylandEglIntegration);
    if (!d->valid) {
        qWarning("createTextureFromBuffer() failed\n");
        return 0;
    }

    EGLImageKHR image = d->egl_create_image(d->egl_display, EGL_NO_CONTEXT,
                                          EGL_WAYLAND_BUFFER_WL,
                                          buffer, NULL);

    GLuint textureId;
    glGenTextures(1,&textureId);

    glBindTexture(GL_TEXTURE_2D, textureId);

    d->gl_egl_image_target_texture_2d(GL_TEXTURE_2D, image);

    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

    d->egl_destroy_image(d->egl_display, image);

    return textureId;
}

bool WaylandEglIntegration::isYInverted(struct ::wl_resource *buffer) const
{
#ifdef EGL_WL_request_client_buffer_format
    return eglGetBufferYInvertedWL(buffer);
#else
    return QWaylandGraphicsHardwareIntegration::isYInverted(buffer);
#endif
}

bool WaylandEglIntegration::setDirectRenderSurface(QWaylandSurface *surface)
{
    Q_D(WaylandEglIntegration);

    QPlatformScreen *screen = QPlatformScreen::platformScreenForWindow(m_compositor->window());
    QPlatformScreenPageFlipper *flipper = screen ? screen->pageFlipper() : 0;
    if (flipper && !d->flipperConnected) {
        QObject::connect(flipper, SIGNAL(bufferReleased(QPlatformScreenBuffer*)), m_compositor->handle(), SLOT(releaseBuffer(QPlatformScreenBuffer*)));
        d->flipperConnected = true;
    }
#ifdef EGL_WL_request_client_buffer_format
    int buffer_format = surface ? EGL_SCANOUT_FORMAT_WL : EGL_RENDER_FORMAT_WL;
    struct wl_client *client = 0;
    if (surface) {
        client = surface->handle()->base()->resource.client;
    } else {
        WaylandSurface *oldSurface = d->directRenderSurface.data();
        if (oldSurface)
            client = oldSurface->handle()->base()->resource.client;
    }
    if (client)
        eglRequestClientBufferFormatWL(d->egl_display, client, buffer_format);
    d->directRenderSurface = surface;
#else
    Q_UNUSED(surface);
#endif
    return flipper;
}

void *WaylandEglIntegration::lockNativeBuffer(struct ::wl_resource *buffer, QOpenGLContext *) const
{
    Q_D(const WaylandEglIntegration);

    EGLImageKHR image = d->egl_create_image(d->egl_display, EGL_NO_CONTEXT,
                                          EGL_WAYLAND_BUFFER_WL,
                                          buffer, NULL);
    return image;
}

void WaylandEglIntegration::unlockNativeBuffer(void *native_buffer, QOpenGLContext *) const
{
    Q_D(const WaylandEglIntegration);
    EGLImageKHR image = static_cast<EGLImageKHR>(native_buffer);

    d->egl_destroy_image(d->egl_display, image);
}

QSize WaylandEglIntegration::bufferSize(struct ::wl_resource *buffer) const
{
    Q_D(const WaylandEglIntegration);

    int width, height;
    d->egl_query_wayland_buffer(d->egl_display, reinterpret_cast<struct ::wl_buffer *>(buffer), EGL_WIDTH, &width);
    d->egl_query_wayland_buffer(d->egl_display, reinterpret_cast<struct ::wl_buffer *>(buffer), EGL_HEIGHT, &height);

    return QSize(width, height);
}

QT_END_NAMESPACE
<commit_msg>Add support for non default Wayland EGL implementations<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Compositor.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in
**     the documentation and/or other materials provided with the
**     distribution.
**   * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names
**     of its contributors may be used to endorse or promote products derived
**     from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "waylandeglintegration.h"

#include <QtCompositor/private/qwlcompositor_p.h>
#include <QtCompositor/private/qwlsurface_p.h>
#include <qpa/qplatformnativeinterface.h>
#include <QtGui/QGuiApplication>
#include <QtGui/QOpenGLContext>
#include <qpa/qplatformscreen.h>
#include <QtGui/QWindow>
#include <QtCore/QPointer>

#include <QDebug>

#include <EGL/egl.h>
#include <EGL/eglext.h>

#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>

#ifndef EGL_WL_bind_wayland_display
typedef EGLBoolean (EGLAPIENTRYP PFNEGLBINDWAYLANDDISPLAYWL) (EGLDisplay dpy, struct wl_display *display);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLUNBINDWAYLANDDISPLAYWL) (EGLDisplay dpy, struct wl_display *display);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYWAYLANDBUFFERWL) (EGLDisplay dpy, struct wl_buffer *buffer, EGLint attribute, EGLint *value);
#endif

#ifndef EGL_KHR_image
typedef EGLImageKHR (EGLAPIENTRYP PFNEGLCREATEIMAGEKHRPROC) (EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer, const EGLint *attrib_list);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLDESTROYIMAGEKHRPROC) (EGLDisplay dpy, EGLImageKHR image);
#endif

#ifndef GL_OES_EGL_image
typedef void (GL_APIENTRYP PFNGLEGLIMAGETARGETTEXTURE2DOESPROC) (GLenum target, GLeglImageOES image);
typedef void (GL_APIENTRYP PFNGLEGLIMAGETARGETRENDERBUFFERSTORAGEOESPROC) (GLenum target, GLeglImageOES image);
#endif

QT_BEGIN_NAMESPACE

class WaylandEglIntegrationPrivate
{
public:
    WaylandEglIntegrationPrivate()
        : egl_display(EGL_NO_DISPLAY)
        , valid(false)
        , display_bound(false)
        , flipperConnected(false)
        , egl_bind_wayland_display(0)
        , egl_unbind_wayland_display(0)
        , egl_query_wayland_buffer(0)
        , egl_create_image(0)
        , egl_destroy_image(0)
        , gl_egl_image_target_texture_2d(0)
    { }
    EGLDisplay egl_display;
    bool valid;
    bool display_bound;
    bool flipperConnected;
#ifdef EGL_WL_request_client_buffer_format
    QPointer<WaylandSurface> directRenderSurface;
#endif
    PFNEGLBINDWAYLANDDISPLAYWL egl_bind_wayland_display;
    PFNEGLUNBINDWAYLANDDISPLAYWL egl_unbind_wayland_display;
    PFNEGLQUERYWAYLANDBUFFERWL egl_query_wayland_buffer;

    PFNEGLCREATEIMAGEKHRPROC egl_create_image;
    PFNEGLDESTROYIMAGEKHRPROC egl_destroy_image;

    PFNGLEGLIMAGETARGETTEXTURE2DOESPROC gl_egl_image_target_texture_2d;
};

WaylandEglIntegration::WaylandEglIntegration()
    : QWaylandGraphicsHardwareIntegration()
    , d_ptr(new WaylandEglIntegrationPrivate)
{
}

void WaylandEglIntegration::initializeHardware(QtWayland::Display *waylandDisplay)
{
    Q_D(WaylandEglIntegration);

    const bool ignoreBindDisplay = !qgetenv("QT_WAYLAND_IGNORE_BIND_DISPLAY").isEmpty();

    QPlatformNativeInterface *nativeInterface = QGuiApplication::platformNativeInterface();
    if (!nativeInterface) {
        qWarning("Failed to initialize egl display. No native platform interface available.\n");
        return;
    }

    d->egl_display = nativeInterface->nativeResourceForWindow("EglDisplay", m_compositor->window());
    if (!d->egl_display) {
        qWarning("Failed to initialize egl display. Could not get EglDisplay for window.\n");
        return;
    }

    const char *extensionString = eglQueryString(d->egl_display, EGL_EXTENSIONS);
    if ((!extensionString || !strstr(extensionString, "EGL_WL_bind_wayland_display")) && !ignoreBindDisplay) {
        qWarning("Failed to initialize egl display. There is no EGL_WL_bind_wayland_display extension.\n");
        return;
    }

    d->egl_bind_wayland_display = reinterpret_cast<PFNEGLBINDWAYLANDDISPLAYWL>(eglGetProcAddress("eglBindWaylandDisplayWL"));
    d->egl_unbind_wayland_display = reinterpret_cast<PFNEGLUNBINDWAYLANDDISPLAYWL>(eglGetProcAddress("eglUnbindWaylandDisplayWL"));
    if (!d->egl_bind_wayland_display || !d->egl_unbind_wayland_display && !ignoreBindDisplay) {
        qWarning("Failed to initialize egl display. Could not find eglBindWaylandDisplayWL and eglUnbindWaylandDisplayWL.\n");
        return;
    }

    d->egl_query_wayland_buffer = reinterpret_cast<PFNEGLQUERYWAYLANDBUFFERWL>(eglGetProcAddress("eglQueryWaylandBufferWL"));
    if (!d->egl_query_wayland_buffer) {
        qWarning("Failed to initialize egl display. Could not find eglQueryWaylandBufferWL.\n");
        return;
    }

    d->egl_create_image = reinterpret_cast<PFNEGLCREATEIMAGEKHRPROC>(eglGetProcAddress("eglCreateImageKHR"));
    d->egl_destroy_image = reinterpret_cast<PFNEGLDESTROYIMAGEKHRPROC>(eglGetProcAddress("eglDestroyImageKHR"));
    if (!d->egl_create_image || !d->egl_destroy_image) {
        qWarning("Failed to initialize egl display. Could not find eglCreateImageKHR and eglDestroyImageKHR.\n");
        return;
    }

    d->gl_egl_image_target_texture_2d = reinterpret_cast<PFNGLEGLIMAGETARGETTEXTURE2DOESPROC>(eglGetProcAddress("glEGLImageTargetTexture2DOES"));
    if (!d->gl_egl_image_target_texture_2d) {
        qWarning("Failed to initialize egl display. Could not find glEGLImageTargetTexture2DOES.\n");
        return;
    }

    if (d->egl_bind_wayland_display && d->egl_unbind_wayland_display) {
        d->display_bound = d->egl_bind_wayland_display(d->egl_display, waylandDisplay->handle());
        if (!d->display_bound || ignoreBindDisplay) {
            qWarning("Failed to initialize egl display. Could not bind Wayland display.\n");
            return;
        }
    }

    d->valid = true;

    qWarning("EGL Wayland extension successfully initialized.%s\n", !d->display_bound ? " eglBindWaylandDisplayWL ignored" : "");
}

GLuint WaylandEglIntegration::createTextureFromBuffer(struct ::wl_resource *buffer, QOpenGLContext *)
{
    Q_D(WaylandEglIntegration);
    if (!d->valid) {
        qWarning("createTextureFromBuffer() failed\n");
        return 0;
    }

    EGLImageKHR image = d->egl_create_image(d->egl_display, EGL_NO_CONTEXT,
                                          EGL_WAYLAND_BUFFER_WL,
                                          buffer, NULL);

    GLuint textureId;
    glGenTextures(1,&textureId);

    glBindTexture(GL_TEXTURE_2D, textureId);

    d->gl_egl_image_target_texture_2d(GL_TEXTURE_2D, image);

    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

    d->egl_destroy_image(d->egl_display, image);

    return textureId;
}

bool WaylandEglIntegration::isYInverted(struct ::wl_resource *buffer) const
{
#ifdef EGL_WL_request_client_buffer_format
    return eglGetBufferYInvertedWL(buffer);
#else
    return QWaylandGraphicsHardwareIntegration::isYInverted(buffer);
#endif
}

bool WaylandEglIntegration::setDirectRenderSurface(QWaylandSurface *surface)
{
    Q_D(WaylandEglIntegration);

    QPlatformScreen *screen = QPlatformScreen::platformScreenForWindow(m_compositor->window());
    QPlatformScreenPageFlipper *flipper = screen ? screen->pageFlipper() : 0;
    if (flipper && !d->flipperConnected) {
        QObject::connect(flipper, SIGNAL(bufferReleased(QPlatformScreenBuffer*)), m_compositor->handle(), SLOT(releaseBuffer(QPlatformScreenBuffer*)));
        d->flipperConnected = true;
    }
#ifdef EGL_WL_request_client_buffer_format
    int buffer_format = surface ? EGL_SCANOUT_FORMAT_WL : EGL_RENDER_FORMAT_WL;
    struct wl_client *client = 0;
    if (surface) {
        client = surface->handle()->base()->resource.client;
    } else {
        WaylandSurface *oldSurface = d->directRenderSurface.data();
        if (oldSurface)
            client = oldSurface->handle()->base()->resource.client;
    }
    if (client)
        eglRequestClientBufferFormatWL(d->egl_display, client, buffer_format);
    d->directRenderSurface = surface;
#else
    Q_UNUSED(surface);
#endif
    return flipper;
}

void *WaylandEglIntegration::lockNativeBuffer(struct ::wl_resource *buffer, QOpenGLContext *) const
{
    Q_D(const WaylandEglIntegration);

    EGLImageKHR image = d->egl_create_image(d->egl_display, EGL_NO_CONTEXT,
                                          EGL_WAYLAND_BUFFER_WL,
                                          buffer, NULL);
    return image;
}

void WaylandEglIntegration::unlockNativeBuffer(void *native_buffer, QOpenGLContext *) const
{
    Q_D(const WaylandEglIntegration);
    EGLImageKHR image = static_cast<EGLImageKHR>(native_buffer);

    d->egl_destroy_image(d->egl_display, image);
}

QSize WaylandEglIntegration::bufferSize(struct ::wl_resource *buffer) const
{
    Q_D(const WaylandEglIntegration);

    int width, height;
    d->egl_query_wayland_buffer(d->egl_display, reinterpret_cast<struct ::wl_buffer *>(buffer), EGL_WIDTH, &width);
    d->egl_query_wayland_buffer(d->egl_display, reinterpret_cast<struct ::wl_buffer *>(buffer), EGL_HEIGHT, &height);

    return QSize(width, height);
}

QT_END_NAMESPACE
<|endoftext|>


<commit_before>/* This file is part of QJson
 *
 * Copyright (C) 2009 Flavio Castelli <flavio.castelli@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include <QCoreApplication>
#include <QDebug>
#include <QFile>
#include <QStringList>
#include <QVariant>

#include <json_driver.hh>

int main(int argc, char *argv[]) {
  QCoreApplication app (argc, argv);

  if (app.arguments().size() != 2) {
    qFatal("You have to specify the file containing the json code");
    exit (1);
  }

  QString filename = app.arguments()[1];
  if (!QFile::exists ( filename )) {
    qFatal ("The file you specified doesn't exist!");
    exit (1);
  }

  JSonDriver driver;
  bool status;

  QFile file (filename);
  QVariant data = driver.parse (&file, &status);
  if (status) {
    qFatal("%s:%i - Error: %s", filename.toLatin1().data(), driver.errorLine(), driver.error().toLatin1().data());
    exit (1);
  }
  else {
    qDebug() << "json object successfully converted to:";
    qDebug() << data;
  }

  return 0;
}
<commit_msg>Added a new test program for qjson: it simply loads json objects from a file, converts and dump them on stdout<commit_after>/* This file is part of QJson
 *
 * Copyright (C) 2009 Flavio Castelli <flavio.castelli@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include <QCoreApplication>
#include <QDebug>
#include <QFile>
#include <QStringList>
#include <QVariant>

#include <json_driver.hh>

int main(int argc, char *argv[]) {
  QCoreApplication app (argc, argv);

  if (app.arguments().size() != 2) {
    qCritical("You have to specify the file containing the json code");
    exit (1);
  }

  QString filename = app.arguments()[1];
  if (!QFile::exists ( filename )) {
    qCritical ("The file you specified doesn't exist!");
    exit (1);
  }

  JSonDriver driver;
  bool status;

  QFile file (filename);
  QVariant data = driver.parse (&file, &status);
  if (status) {
    qCritical("%s:%i - Error: %s", filename.toLatin1().data(), driver.errorLine(), driver.error().toLatin1().data());
    exit (1);
  }
  else {
    qDebug() << "json object successfully converted to:";
    qDebug() << data;
  }

  return 0;
}

<|endoftext|>


<commit_before>#include "gamelib/core/ecs/EntityFactory.hpp"
#include "gamelib/core/ecs/EntityManager.hpp"
#include "gamelib/core/ecs/serialization.hpp"
#include "gamelib/core/res/ResourceManager.hpp"
#include "gamelib/utils/log.hpp"

namespace gamelib
{
    EntityHandle createEntity(const std::string& name)
    {
        return getSubsystem<EntityFactory>()->create(name);
    }

    EntityHandle createEntity(const std::string& name, float x, float y)
    {
        auto h = createEntity(name);
        if (h)
            getEntity(h)->getTransform().setPosition(x, y);
        return h;
    }

    EntityFactory::EntityFactory()
    { }

    EntityHandle EntityFactory::createWithDelta(const std::string& name, const Json::Value& node)
    {
        auto entmgr = getSubsystem<EntityManager>();
        auto handle = entmgr->add();

        if (!createWithDelta(name, node, getEntity(handle)))
        {
            entmgr->destroy(handle);
            handle.reset();
        }

        return handle;
    }

    bool EntityFactory::createWithDelta(const std::string& name, const Json::Value& node, Entity* ent)
    {
        // Possible segfaults when EntityManager reallocates and
        // the given ent pointer becomes invalid.
        // See also note in create(const Json::Value&).
        if (create(name, ent) && extendFromJson(node, *ent))
            return true;
        return false;
    }

    EntityHandle EntityFactory::create(const std::string& name)
    {
        auto found = _findTemplate(name);
        if (found)
            return createFromJson(*found);
        return EntityHandle();
    }

    bool EntityFactory::create(const std::string& name, Entity* ent)
    {
        auto found = _findTemplate(name);
        if (found)
            return createFromJson(*found, ent);
        return false;
    }

    EntityHandle EntityFactory::createFromJson(const Json::Value& node)
    {
        // NOTE: this could go wrong when the EntityManager needs to reallocate
        //       during the creation process, for example when a component
        //       creates new entities.
        //       In that case, creating entities during component initialization
        //       is not supported.
        auto entmgr = getSubsystem<EntityManager>();
        auto handle = entmgr->add();

        if (!createFromJson(node, getEntity(handle)))
        {
            entmgr->destroy(handle);
            handle.reset();
        }
        return handle;
    }

    bool EntityFactory::createFromJson(const Json::Value& node, Entity* ent)
    {
        assert(ent && "ent is null");
        // Possible segfaults when EntityManager reallocates and
        // the given ent pointer becomes invalid.
        // See also note in create(const Json::Value&).
        return loadFromJson(node, *ent);
    }

    ComponentPtr EntityFactory::createComponent(const std::string& name)
    {
        return _compfactory.create(name);
    }

    ComponentPtr EntityFactory::createComponentFromJson(const std::string& name, const Json::Value& node)
    {
        auto ptr = createComponent(name);
        if (ptr && ptr->loadFromJson(node))
            return ptr;
        LOG_ERROR("Failed to create component ", name);
        return nullptr;
    }

    void EntityFactory::add(const Json::Value& cfg)
    {
        add(cfg["name"].asString(), cfg);
    }

    void EntityFactory::add(const std::string& name, const Json::Value& cfg)
    {
        if (name.empty())
        {
            LOG_ERROR("Entity name must not be empty");
            return;
        }

        _entdata[name] = cfg;
        LOG_DEBUG("Registered entity ", name);
    }

    void EntityFactory::addComponent(const std::string& name, ComponentFactory::CreatorFunction callback)
    {
        _compfactory.add(name, callback);
        LOG_DEBUG("Registered component ", name);
    }

    void EntityFactory::removeEntity(const std::string& name)
    {
        auto it = _entdata.find(name);
        if (it != _entdata.end())
            _entdata.erase(it);
    }

    void EntityFactory::removeComponent(const std::string& name)
    {
        _compfactory.remove(name);
    }

    void EntityFactory::clear()
    {
        _compfactory.clear();
        _entdata.clear();
    }

    size_t EntityFactory::size() const
    {
        return _entdata.size();
    }

    const Json::Value* EntityFactory::findEntity(const std::string& name) const
    {
        auto it = _entdata.find(name);
        if (it != _entdata.end())
            return &it->second;
        return nullptr;
    }

    auto EntityFactory::_findTemplate(const std::string& name) -> const Json::Value*
    {
        auto found = findEntity(name);
        if (!found)
        {
            auto resmgr = ResourceManager::getActive();
            if (resmgr)
            {
                // loadOnce, because it auto-registers here.
                // Won't work if EntityFactory::getActive() returns another factory than this.
                auto handle = resmgr->loadOnce(name + ".ent");
                if (!handle)
                    handle = resmgr->loadOnce(name + ".entity");
                if (handle)
                    found = findEntity(name);
            }
        }
        return found;
    }
}
<commit_msg>Use getOnce rather than loadOnce<commit_after>#include "gamelib/core/ecs/EntityFactory.hpp"
#include "gamelib/core/ecs/EntityManager.hpp"
#include "gamelib/core/ecs/serialization.hpp"
#include "gamelib/core/res/ResourceManager.hpp"
#include "gamelib/utils/log.hpp"

namespace gamelib
{
    EntityHandle createEntity(const std::string& name)
    {
        return getSubsystem<EntityFactory>()->create(name);
    }

    EntityHandle createEntity(const std::string& name, float x, float y)
    {
        auto h = createEntity(name);
        if (h)
            getEntity(h)->getTransform().setPosition(x, y);
        return h;
    }

    EntityFactory::EntityFactory()
    { }

    EntityHandle EntityFactory::createWithDelta(const std::string& name, const Json::Value& node)
    {
        auto entmgr = getSubsystem<EntityManager>();
        auto handle = entmgr->add();

        if (!createWithDelta(name, node, getEntity(handle)))
        {
            entmgr->destroy(handle);
            handle.reset();
        }

        return handle;
    }

    bool EntityFactory::createWithDelta(const std::string& name, const Json::Value& node, Entity* ent)
    {
        // Possible segfaults when EntityManager reallocates and
        // the given ent pointer becomes invalid.
        // See also note in create(const Json::Value&).
        if (create(name, ent) && extendFromJson(node, *ent))
            return true;
        return false;
    }

    EntityHandle EntityFactory::create(const std::string& name)
    {
        auto found = _findTemplate(name);
        if (found)
            return createFromJson(*found);
        return EntityHandle();
    }

    bool EntityFactory::create(const std::string& name, Entity* ent)
    {
        auto found = _findTemplate(name);
        if (found)
            return createFromJson(*found, ent);
        return false;
    }

    EntityHandle EntityFactory::createFromJson(const Json::Value& node)
    {
        // NOTE: this could go wrong when the EntityManager needs to reallocate
        //       during the creation process, for example when a component
        //       creates new entities.
        //       In that case, creating entities during component initialization
        //       is not supported.
        auto entmgr = getSubsystem<EntityManager>();
        auto handle = entmgr->add();

        if (!createFromJson(node, getEntity(handle)))
        {
            entmgr->destroy(handle);
            handle.reset();
        }
        return handle;
    }

    bool EntityFactory::createFromJson(const Json::Value& node, Entity* ent)
    {
        assert(ent && "ent is null");
        // Possible segfaults when EntityManager reallocates and
        // the given ent pointer becomes invalid.
        // See also note in create(const Json::Value&).
        return loadFromJson(node, *ent);
    }

    ComponentPtr EntityFactory::createComponent(const std::string& name)
    {
        return _compfactory.create(name);
    }

    ComponentPtr EntityFactory::createComponentFromJson(const std::string& name, const Json::Value& node)
    {
        auto ptr = createComponent(name);
        if (ptr && ptr->loadFromJson(node))
            return ptr;
        LOG_ERROR("Failed to create component ", name);
        return nullptr;
    }

    void EntityFactory::add(const Json::Value& cfg)
    {
        add(cfg["name"].asString(), cfg);
    }

    void EntityFactory::add(const std::string& name, const Json::Value& cfg)
    {
        if (name.empty())
        {
            LOG_ERROR("Entity name must not be empty");
            return;
        }

        _entdata[name] = cfg;
        LOG_DEBUG("Registered entity ", name);
    }

    void EntityFactory::addComponent(const std::string& name, ComponentFactory::CreatorFunction callback)
    {
        _compfactory.add(name, callback);
        LOG_DEBUG("Registered component ", name);
    }

    void EntityFactory::removeEntity(const std::string& name)
    {
        auto it = _entdata.find(name);
        if (it != _entdata.end())
            _entdata.erase(it);
    }

    void EntityFactory::removeComponent(const std::string& name)
    {
        _compfactory.remove(name);
    }

    void EntityFactory::clear()
    {
        _compfactory.clear();
        _entdata.clear();
    }

    size_t EntityFactory::size() const
    {
        return _entdata.size();
    }

    const Json::Value* EntityFactory::findEntity(const std::string& name) const
    {
        auto it = _entdata.find(name);
        if (it != _entdata.end())
            return &it->second;
        return nullptr;
    }

    auto EntityFactory::_findTemplate(const std::string& name) -> const Json::Value*
    {
        auto found = findEntity(name);
        if (!found)
        {
            auto resmgr = ResourceManager::getActive();
            if (resmgr)
            {
                // If found, the entity autoregisters at the factory.
                // Won't work if EntityFactory::getActive() returns another factory than this.
                auto handle = resmgr->getOnce(name + ".ent");
                if (!handle)
                    handle = resmgr->getOnce(name + ".entity");
                if (handle)
                    found = findEntity(name);
            }
        }
        return found;
    }
}
<|endoftext|>


<commit_before>#include <BinaryTree.hpp>
#include <catch.hpp>

SCENARIO ("init", "[init]")
{
  BinaryTree<int> obj;
  REQUIRE(obj.root_() == nullptr);
}

SCENARIO("insert", "[insert]")
{
  BinaryTree<int> obj;
  obj.insert_node(3);
//  REQUIRE(obj.find_node(3, obj.root_())->data == 3);
}

SCENARIO("find_node", "[find_node]")
{
  BinaryTree<int> obj;
  obj.insert_node(2);
  //REQUIRE(obj.find_node(2, obj.root_()) != nullptr);
  //REQUIRE(obj.find_node(2, obj.root_())->data == 2);
}

SCENARIO("get root", "[get root]")
{
  BinaryTree<int> obj;
  obj.insert_node(4);
  //REQUIRE(obj.root_() != 0);
}

SCENARIO ("output to cout", "<<")
{
 BinaryTree<int> tree;
 tree.insert_node(3);
 //REQUIRE( std::cout << tree );
}
<commit_msg>Update init.cpp<commit_after>#include <BinaryTree.hpp>
#include <catch.hpp>

SCENARIO ("init", "[init]")
{
  BinaryTree<int> obj;
  REQUIRE(obj.root_() == nullptr);
}
<|endoftext|>


<commit_before>#include "BinaryTree.hpp"
#include <catch.hpp>

SCENARIO("default constructor")
{
	Tree<int> node;
	REQUIRE(node.root_() == nullptr);
}

SCENARIO("insert")
{
	Tree<int> tree;
	tree.insert(7);
	REQUIRE(tree.x_() == 7);
	REQUIRE(tree.left_() == nullptr);
	REQUIRE(tree.right_() == nullptr);
}

SCENARIO("search")
{
	Tree<int> tree;
	bool a;
	tree.insert(7);
	a = tree.check_search(7);
	REQUIRE(a == true);
}

SCENARIO("size")
{
	Tree<int> tree;
	int size = 0;
	tree.insert(7);
	size = tree.size(tree.root_());
	REQUIRE(size == 1);
}

SCENARIO("out_to_file", "fIn")
{
	Tree<int> tree1, tree2;
	int size1, size2;
	tree1.insert(3);
	tree1.insert(4);
	tree1.insert(2);
	tree1.out_to_file("TreeOut.txt");
	size1 = tree1.size(tree1.root_());
	tree2.fIn("TreeOut.txt");
	size2 = tree2.size(tree2.root_());
	REQUIRE(size1 == 3);
	REQUIRE(size2 == 3);
	REQUIRE(tree2.x_() == 3);
	REQUIRE(tree2.left_() != nullptr);
	REQUIRE(tree2.right_() != nullptr);
}
<commit_msg>Update init.cpp<commit_after>#include "BinaryTree.hpp"
#include <catch.hpp>

SCENARIO("default constructor")
{
	Tree<int> node;
	REQUIRE(node.root_() == nullptr);
}

SCENARIO("insert")
{
	Tree<int> tree;
	tree.insert(7);
	REQUIRE(tree.x_() == 7);
	REQUIRE(tree.left_() == nullptr);
	REQUIRE(tree.right_() == nullptr);
}

SCENARIO("search")
{
	Tree<int> tree;
	bool a;
	tree.insert(7);
	a = tree.check_search(7);
	REQUIRE(a == true);
}

SCENARIO("size")
{
	Tree<int> tree;
	int size = 0;
	tree.insert(7);
	size = tree.size(tree.root_());
	REQUIRE(size == 1);
}

SCENARIO("out_to_file", "fIn")
{
	Tree<int> tree1, tree2;
	int size1, size2;
	tree1.insert(3);
	tree1.insert(4);
	tree1.out_to_file("TreeOut.txt");
	size1 = tree1.size(tree1.root_());
	tree2.fIn("TreeOut.txt");
	size2 = tree2.size(tree2.root_());
	REQUIRE(size1 == 2);
	REQUIRE(size2 == 2);
	REQUIRE(tree2.x_() == 3);
	REQUIRE(tree2.left_() != nullptr);
	REQUIRE(tree2.right_() != nullptr);
}
<|endoftext|>


<commit_before>#include <matrix.hpp>
#include <catch.hpp>

SCENARIO("matrix init without parametrs", "[init wp]") {
	Matrix matrix;
	REQUIRE(matrix.rows() == 4);
	REQUIRE(matrix.columns() == 4);

	for (int i=0;i<matrix.rows(); i++) {
		for (int j = 0; j<matrix.columns();j++) {
			REQUIRE(matrix.Element(i,j) == 0);
		}
	}
}

SCENARIO("matrix init with parametrs", "[init withp]") {
	Matrix matrix(6,6);
	REQUIRE(matrix.rows() == 6);
	REQUIRE(matrix.columns() == 6);

	for (int i=0;i<matrix.rows(); i++) {
		for (int j = 0; j<matrix.columns();j++) {
			REQUIRE(matrix.Element(i,j) == 0);
		}
	}
}

SCENARIO("matrix init copy", "[init copy]") {
	Matrix matrix(6,6);
	Matrix matrix1(matrix);
	REQUIRE(matrix1.rows() == matrix.rows());
	REQUIRE(matrix1.columns() == matrix.columns());

	for (int i=0;i<matrix.rows(); i++) {
		for (int j = 0; j<matrix.columns();j++) {
			REQUIRE(matrix.Element(i,j) == matrix1.Element(i,j));
		}
	}
}

SCENARIO("matrix fill", "[fill]") {
	Matrix matrix(2,2);
	ofstream test1("test1.txt");
	test1 << "1 2 3 4";
	test1.close();
	matrix.fill("test1.txt");
	REQUIRE(matrix.Element(0,0) == 1);
	REQUIRE(matrix.Element(0,1) == 2);
	REQUIRE(matrix.Element(1,0) == 3);
	REQUIRE(matrix.Element(1,1) == 4);
}

SCENARIO("matrix sum", "[sum]") {
	Matrix matrix(2,2);
	Matrix matrix1(2,2);
	Matrix sum(2,2);

	ofstream test1("test1.txt");
	test1 << "1 2 3 4";
	test1.close();

	matrix.fill("test1.txt");
	matrix1.fill("test1.txt");
	//ofstream sumfile("sumfile.txt");
	//sumfile << "2 4 6 8";
	//sum.fill("sumfile.txt");
	//sumfile.close();
	REQUIRE(matrix.Element(0,0) + matrix1.Element(0,0) == 2);
	REQUIRE(matrix.Element(0,1) + matrix1.Element(0,1) == 4);
	REQUIRE(matrix.Element(1,0) + matrix1.Element(1,0) == 6);
	REQUIRE(matrix.Element(1,1) + matrix1.Element(1,1) == 8);

}

SCENARIO("matrix Proizv", "[Pro]") {
	Matrix matrix(2,2);
	Matrix matrix1(2,2);
	Matrix Pro(2,2);

	ofstream test1("test1.txt");
	test1 << "1 2 3 4";
	test1.close();

	matrix.fill("test1.txt");
	matrix1.fill("test1.txt");
	//ofstream sumfile("sumfile.txt");
	//sumfile << "2 4 6 8";
	//sum.fill("sumfile.txt");
	//sumfile.close();
	REQUIRE(matrix[0][0] * matrix1[0][0] + matrix[0][1] * matrix[1][0] == 7);
	REQUIRE(matrix[0][0] * matrix1[1][0] + matrix[0][1] * matrix[1][1] == 10);
	REQUIRE(matrix[0][1] * matrix1[0][0] + matrix[1][1] * matrix[0][1] == 15);
	REQUIRE(matrix[0][1] * matrix1[1][0] + matrix[1][1] * matrix[1][1] == 22);

}

<commit_msg>Update init.cpp<commit_after>#include <matrix.hpp>
#include <catch.hpp>

SCENARIO("matrix init without parametrs", "[init wp]") {
	Matrix matrix;
	REQUIRE(matrix.rows() == 4);
	REQUIRE(matrix.columns() == 4);

	for (int i=0;i<matrix.rows(); i++) {
		for (int j = 0; j<matrix.columns();j++) {
			REQUIRE(matrix.Element(i,j) == 0);
		}
	}
}

SCENARIO("matrix init with parametrs", "[init withp]") {
	Matrix matrix(6,6);
	REQUIRE(matrix.rows() == 6);
	REQUIRE(matrix.columns() == 6);

	for (int i=0;i<matrix.rows(); i++) {
		for (int j = 0; j<matrix.columns();j++) {
			REQUIRE(matrix.Element(i,j) == 0);
		}
	}
}

SCENARIO("matrix init copy", "[init copy]") {
	Matrix matrix(6,6);
	Matrix matrix1(matrix);
	REQUIRE(matrix1.rows() == matrix.rows());
	REQUIRE(matrix1.columns() == matrix.columns());

	for (int i=0;i<matrix.rows(); i++) {
		for (int j = 0; j<matrix.columns();j++) {
			REQUIRE(matrix.Element(i,j) == matrix1.Element(i,j));
		}
	}
}

SCENARIO("matrix fill", "[fill]") {
	Matrix matrix(2,2);
	ofstream test1("test1.txt");
	test1 << "1 2 3 4";
	test1.close();
	matrix.fill("test1.txt");
	REQUIRE(matrix.Element(0,0) == 1);
	REQUIRE(matrix.Element(0,1) == 2);
	REQUIRE(matrix.Element(1,0) == 3);
	REQUIRE(matrix.Element(1,1) == 4);
}

SCENARIO("matrix sum", "[sum]") {
	Matrix matrix(2,2);
	Matrix matrix1(2,2);
	Matrix sum(2,2);

	ofstream test1("test1.txt");
	test1 << "1 2 3 4";
	test1.close();

	matrix.fill("test1.txt");
	matrix1.fill("test1.txt");
	//ofstream sumfile("sumfile.txt");
	//sumfile << "2 4 6 8";
	//sum.fill("sumfile.txt");
	//sumfile.close();
	REQUIRE(matrix.Element(0,0) + matrix1.Element(0,0) == 2);
	REQUIRE(matrix.Element(0,1) + matrix1.Element(0,1) == 4);
	REQUIRE(matrix.Element(1,0) + matrix1.Element(1,0) == 6);
	REQUIRE(matrix.Element(1,1) + matrix1.Element(1,1) == 8);

}

SCENARIO("matrix Proizv", "[Pro]") {
	Matrix matrix(2,2);
	Matrix matrix1(2,2);
	Matrix Pro(2,2);

	ofstream test1("test1.txt");
	test1 << "1 2 3 4";
	test1.close();

	matrix.fill("test1.txt");
	matrix1.fill("test1.txt");
	//ofstream sumfile("sumfile.txt");
	//sumfile << "2 4 6 8";
	//sum.fill("sumfile.txt");
	//sumfile.close();
	REQUIRE(matrix.Element(0,0) * matrix1.Element(0,0) + matrix.Element(1,0) * matrix1.ELement(0,1) == 7);
	REQUIRE(matrix.Element(0,0) * matrix1.Element(1,0) + matrix.Element(1,0) * matrix1.ELement(1,1) == 10);
	REQUIRE(matrix.Element(0,1) * matrix1.Element(0,0) + matrix.Element(1,1) * matrix1.ELement(0,1) == 15);
	REQUIRE(matrix.Element(0,1) * matrix1.Element(1,0) + matrix.Element(1,1) * matrix1.ELement(1,1) == 7);

}

<|endoftext|>


<commit_before>#include <gtest/gtest.h>
#include <opencv2/opencv.hpp>
#ifdef _MSC_VER
#include <opencv2/opencv_lib.hpp>
#endif
#include "../include/image_utils.h"

//#pragma comment(lib,"gtestd.lib")
//#pragma comment(lib,"libcpmtd.lib")

int main(int argc, char** argv)
{
	::testing::InitGoogleTest(&argc, argv);
	int ret = RUN_ALL_TESTS();
	return ret;
}

TEST(IsEqualTest, is_equal_true)
{
	cv::Mat src = cv::imread("images/test01.png");
	EXPECT_TRUE(ImageUtils::IsEqual(src, src));
}

TEST(IsEqualTest, is_equal_false)
{
	cv::Mat src1 = cv::imread("images/test01.png");
	cv::Mat src2 = cv::imread("images/test02.png");
	EXPECT_FALSE(ImageUtils::IsEqual(src1, src2));
}

TEST(IsEqualTest, is_equal_differnt_channel)
{
	cv::Mat src1 = cv::Mat::zeros(cv::Size(64, 64), CV_8UC3);
	cv::Mat src2 = cv::Mat::zeros(cv::Size(64, 64), CV_8UC1);

	EXPECT_FALSE(ImageUtils::IsEqual(src1, src2));
}

TEST(IsEqualTest, is_equal_differnt_rows)
{
	cv::Mat src1 = cv::Mat::zeros(cv::Size(64, 64), CV_8UC1);
	cv::Mat src2 = cv::Mat::zeros(cv::Size(32, 64), CV_8UC1);
	EXPECT_FALSE(ImageUtils::IsEqual(src1, src2));
}

TEST(IsEqualTest, is_equal_differnt_cols)
{
	cv::Mat src1 = cv::Mat::zeros(cv::Size(64, 64), CV_8UC1);
	cv::Mat src2 = cv::Mat::zeros(cv::Size(64, 32), CV_8UC1);
	EXPECT_FALSE(ImageUtils::IsEqual(src1, src2));
}
<commit_msg>add test pattern.<commit_after>#include <gtest/gtest.h>
#include <opencv2/opencv.hpp>
#ifdef _MSC_VER
#include <opencv2/opencv_lib.hpp>
#endif
#include "../include/image_utils.h"

//#pragma comment(lib,"gtestd.lib")
//#pragma comment(lib,"libcpmtd.lib")

int main(int argc, char** argv)
{
	::testing::InitGoogleTest(&argc, argv);
	int ret = RUN_ALL_TESTS();
	return ret;
}

TEST(IsEqualTest, is_equal_true)
{
	cv::Mat src = cv::imread("images/test01.png");
	EXPECT_TRUE(ImageUtils::IsEqual(src, src));
}

TEST(IsEqualTest, is_equal_false)
{
	cv::Mat src1 = cv::imread("images/test01.png");
	cv::Mat src2 = cv::imread("images/test02.png");
	EXPECT_FALSE(ImageUtils::IsEqual(src1, src2));
}

TEST(IsEqualTest, is_equal_empty)
{
	cv::Mat src1;
	cv::Mat src2;
	EXPECT_TRUE(ImageUtils::IsEqual(src1, src2));
}

TEST(IsEqualTest, is_equal_differnt_channel)
{
	cv::Mat src1 = cv::Mat::zeros(cv::Size(64, 64), CV_8UC3);
	cv::Mat src2 = cv::Mat::zeros(cv::Size(64, 64), CV_8UC1);

	EXPECT_FALSE(ImageUtils::IsEqual(src1, src2));
}

TEST(IsEqualTest, is_equal_differnt_rows)
{
	cv::Mat src1 = cv::Mat::zeros(cv::Size(64, 64), CV_8UC1);
	cv::Mat src2 = cv::Mat::zeros(cv::Size(32, 64), CV_8UC1);
	EXPECT_FALSE(ImageUtils::IsEqual(src1, src2));
}

TEST(IsEqualTest, is_equal_differnt_cols)
{
	cv::Mat src1 = cv::Mat::zeros(cv::Size(64, 64), CV_8UC1);
	cv::Mat src2 = cv::Mat::zeros(cv::Size(64, 32), CV_8UC1);
	EXPECT_FALSE(ImageUtils::IsEqual(src1, src2));
}
<|endoftext|>


<commit_before>#include "factory.h"
#include <chrono>
#include <thread>

void synopsis()
{
    std::cout << "save_1min_epiphan"
              << "    [ help | "
              << "    [ xvid | h265 ]"
              << "    [ <width> <height> ]"
              << " ]"
              << std::endl;
}

int main(int argc, char ** argv)
{
    enum gg::Target codec = gg::Target::File_XviD;
    std::string codec_string = "xvid";
    int width = 10, height = 8, square_size = 60;

    if (argc >= 2)
    {
        if (std::string(argv[1]) == "help")
        {
            synopsis();
            return 0;
        }
        else
        {
            codec_string = std::string(argv[1]);
            if (codec_string == "xvid")
                codec = gg::Target::File_XviD;
            else if (codec_string == "h265")
                codec = gg::Target::File_H265;
            else
            {
                std::cerr << "Codec " << codec_string << " not recognised" << std::endl;
                synopsis();
                exit(-1);
            }

            if (argc == 3)
            {
                synopsis();
                exit(-1);
            }
            else if (argc >= 4)
            {
                width = atoi(argv[2]); height = atoi(argv[3]);
            }
        }
    }

    float fps = 20;
    int duration = 1; // min
    int num_frames = duration * 60 * fps;
    int sleep_duration = (int)(1000/fps); // ms
    VideoFrame_BGRA frame;
    cv::Mat image(height * square_size, width * square_size, CV_8UC4);

    try
    {
        gg::IVideoTarget * file = gg::Factory::create(codec);
        std::string filename;
        filename.append("1min_")
                .append(codec_string)
                .append("_colour_chessboard")
                .append(".avi");
        std::cout << "Saving to file " << filename << std::endl;
        file->init(filename, fps);
        for (int i = 0; i < num_frames; i++)
        {
            if (i % 5 == 0)
                std::cout << "Saving frame " << i+1 << " of " << num_frames
                          << "\r";
            float elapsed = (((float) i) / num_frames);
            float remaining = 1 - elapsed;
            int red = 0,
                green = 0,
                blue = 0,
                alpha = 0;
            int min_intensity = 50; // don't want black
            for (int row = 0; row < height; row++)
            {
                green = min_intensity + elapsed * (((float) row) / height) * (255 - min_intensity);
                for (int col = 0; col < width; col++)
                {
                    red = min_intensity + elapsed * (((float) col) / width) * (255 - min_intensity);
                    blue = min_intensity +
                           remaining *
                                sqrt( ((float)(row*row + col*col))
                                      /
                                      (height*height+width*width) ) * (255 - min_intensity);
                    cv::Mat square(square_size, square_size, CV_8UC4, cv::Scalar(blue, green, red, alpha));
                    square.copyTo(image(cv::Rect(col * square_size , row * square_size,
                                                 square.cols, square.rows)));
                }
            }
            frame.init_from_opencv_mat(image);
            file->append(frame);
        }
        file->finalise();
    }
    catch (gg::VideoTargetError & e)
    {
        std::cerr << e.what() << std::endl;
        return -1;
    }

    return 0;
}
<commit_msg>Issue #21: removed unused variable from test app<commit_after>#include "factory.h"
#include <chrono>
#include <thread>

void synopsis()
{
    std::cout << "save_1min_epiphan"
              << "    [ help | "
              << "    [ xvid | h265 ]"
              << "    [ <width> <height> ]"
              << " ]"
              << std::endl;
}

int main(int argc, char ** argv)
{
    enum gg::Target codec = gg::Target::File_XviD;
    std::string codec_string = "xvid";
    int width = 10, height = 8, square_size = 60;

    if (argc >= 2)
    {
        if (std::string(argv[1]) == "help")
        {
            synopsis();
            return 0;
        }
        else
        {
            codec_string = std::string(argv[1]);
            if (codec_string == "xvid")
                codec = gg::Target::File_XviD;
            else if (codec_string == "h265")
                codec = gg::Target::File_H265;
            else
            {
                std::cerr << "Codec " << codec_string << " not recognised" << std::endl;
                synopsis();
                exit(-1);
            }

            if (argc == 3)
            {
                synopsis();
                exit(-1);
            }
            else if (argc >= 4)
            {
                width = atoi(argv[2]); height = atoi(argv[3]);
            }
        }
    }

    float fps = 20;
    int duration = 1; // min
    int num_frames = duration * 60 * fps;
    VideoFrame_BGRA frame;
    cv::Mat image(height * square_size, width * square_size, CV_8UC4);

    try
    {
        gg::IVideoTarget * file = gg::Factory::create(codec);
        std::string filename;
        filename.append("1min_")
                .append(codec_string)
                .append("_colour_chessboard")
                .append(".avi");
        std::cout << "Saving to file " << filename << std::endl;
        file->init(filename, fps);
        for (int i = 0; i < num_frames; i++)
        {
            if (i % 5 == 0)
                std::cout << "Saving frame " << i+1 << " of " << num_frames
                          << "\r";
            float elapsed = (((float) i) / num_frames);
            float remaining = 1 - elapsed;
            int red = 0,
                green = 0,
                blue = 0,
                alpha = 0;
            int min_intensity = 50; // don't want black
            for (int row = 0; row < height; row++)
            {
                green = min_intensity + elapsed * (((float) row) / height) * (255 - min_intensity);
                for (int col = 0; col < width; col++)
                {
                    red = min_intensity + elapsed * (((float) col) / width) * (255 - min_intensity);
                    blue = min_intensity +
                           remaining *
                                sqrt( ((float)(row*row + col*col))
                                      /
                                      (height*height+width*width) ) * (255 - min_intensity);
                    cv::Mat square(square_size, square_size, CV_8UC4, cv::Scalar(blue, green, red, alpha));
                    square.copyTo(image(cv::Rect(col * square_size , row * square_size,
                                                 square.cols, square.rows)));
                }
            }
            frame.init_from_opencv_mat(image);
            file->append(frame);
        }
        file->finalise();
    }
    catch (gg::VideoTargetError & e)
    {
        std::cerr << e.what() << std::endl;
        return -1;
    }

    return 0;
}
<|endoftext|>


<commit_before>/*
    Copyright © 2010, 2011 Vladimír Vondruš <mosra@centrum.cz>

    This file is part of Magnum.

    Magnum is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License version 3
    only, as published by the Free Software Foundation.

    Magnum is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU Lesser General Public License version 3 for more details.
*/

#include "TexturedTriangle.h"

#include "Buffer.h"

using namespace std;

namespace Magnum { namespace Examples {

TexturedTriangle::TexturedTriangle(istream& textureData, Object* parent): Object(parent), mesh(Mesh::Triangles, 3), texture(textureData) {
    /* Vertices and texture coordinates, interleaved */
    GLfloat data[] = {
        -0.5f, -0.5f, 0.0f, 1.0f,   0.0f, 0.0f,  /* Lower left vertex */
        0.5f, -0.5f, 0.0f, 1.0f,    1.0f, 0.0f,  /* Lower right vertex */
        0.0f, 0.5f, 0.0f, 1.0f,     0.5f, 1.0f,  /* Top vertex */
    };

    /* Fill the mesh with data */
    Buffer* buffer = mesh.addBuffer(true);
    buffer->setData(sizeof(data), data, Buffer::DrawStatic);

    /* Bind attributes (first vertex data, then color data) */
    mesh.bindAttribute<Vector4>(buffer, TexturedIdentityShader::Vertex);
    mesh.bindAttribute<Vector2>(buffer, TexturedIdentityShader::TextureCoordinates);

    /* Texture */
    texture.setMagnificationFilter(TGATexture::Linear);
    texture.setMinificationFilter(TGATexture::Linear);
    texture.setWrapping(Math::Vector2<TGATexture::Wrapping>(TGATexture::ClampToEdge, TGATexture::ClampToEdge));
}

void TexturedTriangle::draw(const Matrix4& transformationMatrix, const Matrix4& projectionMatrix) {
    texture.bind();
    shader.use();
    shader.setTextureUniform(0);
    mesh.draw();
}

}}
<commit_msg>Adopted to Magnum changes.<commit_after>/*
    Copyright © 2010, 2011 Vladimír Vondruš <mosra@centrum.cz>

    This file is part of Magnum.

    Magnum is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License version 3
    only, as published by the Free Software Foundation.

    Magnum is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU Lesser General Public License version 3 for more details.
*/

#include "TexturedTriangle.h"

#include "Buffer.h"

using namespace std;

namespace Magnum { namespace Examples {

TexturedTriangle::TexturedTriangle(istream& textureData, Object* parent): Object(parent), mesh(Mesh::Triangles, 3), texture(textureData) {
    /* Vertices and texture coordinates, interleaved */
    GLfloat data[] = {
        -0.5f, -0.5f, 0.0f, 1.0f,   0.0f, 0.0f,  /* Lower left vertex */
        0.5f, -0.5f, 0.0f, 1.0f,    1.0f, 0.0f,  /* Lower right vertex */
        0.0f, 0.5f, 0.0f, 1.0f,     0.5f, 1.0f,  /* Top vertex */
    };

    /* Fill the mesh with data */
    Buffer* buffer = mesh.addBuffer(true);
    buffer->setData(sizeof(data), data, Buffer::DrawStatic);

    /* Bind attributes (first vertex data, then color data) */
    mesh.bindAttribute<Vector4>(buffer, TexturedIdentityShader::Vertex);
    mesh.bindAttribute<Vector2>(buffer, TexturedIdentityShader::TextureCoordinates);

    /* Texture */
    texture.setMagnificationFilter(TGATexture::LinearFilter);
    texture.setMinificationFilter(TGATexture::LinearFilter);
    texture.setWrapping(Math::Vector2<TGATexture::Wrapping>(TGATexture::ClampToEdge, TGATexture::ClampToEdge));
}

void TexturedTriangle::draw(const Matrix4& transformationMatrix, const Matrix4& projectionMatrix) {
    texture.bind();
    shader.use();
    shader.setTextureUniform(0);
    mesh.draw();
}

}}
<|endoftext|>