<commit_before>/**
framenotifier_app.cpp

  Created on: 13 Oct 2015
      Author: up45
*/
#include <signal.h>
#include <string>
#include <cstring>
#include <iostream>
#include <fstream>
using namespace std;

#include <log4cxx/logger.h>
#include <log4cxx/basicconfigurator.h>
#include <log4cxx/propertyconfigurator.h>
#include <log4cxx/helpers/exception.h>
using namespace log4cxx;
using namespace log4cxx::helpers;

#include <boost/foreach.hpp>
#include <boost/program_options.hpp>
#include "boost/date_time/posix_time/posix_time.hpp"
namespace po = boost::program_options;

#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/stringbuffer.h"
using namespace rapidjson;

#include "zmq/zmq.hpp"

#include "framenotifier_data.h"

void parse_arguments(int argc, char** argv, po::variables_map& vm, LoggerPtr& logger)
{
    try
    {
        std::string config_file;

        // Declare a group of options that will allowed only on the command line
        po::options_description generic("Generic options");
        generic.add_options()
                ("help,h",
                    "Print this help message")
                ("config,c",    po::value<string>(&config_file),
                    "Specify program configuration file")
                ;

        // Declare a group of options that will be allowed both on the command line
        // and in the configuration file
        po::options_description config("Configuration options");
        config.add_options()
                ("logconfig,l",  po::value<string>(),
                    "Set the log4cxx logging configuration file")
                ("ready,r",       po::value<std::string>()->default_value("tcp://127.0.0.1:5001"),
                    "Ready ZMQ endpoint from frameReceiver")
                ("release",       po::value<std::string>()->default_value("tcp://127.0.0.1:5002"),
                        "Release frame ZMQ endpoint from frameReceiver")
                ("frames,f",     po::value<unsigned int>()->default_value(1),
                    "Set the number of frames to be notified about before terminating")
                ("sharedbuf",    po::value<std::string>()->default_value("FrameReceiverBuffer"),
                    "Set the name of the shared memory frame buffer")
                ;

        // Group the variables for parsing at the command line and/or from the configuration file
        po::options_description cmdline_options;
        cmdline_options.add(generic).add(config);
        po::options_description config_file_options;
        config_file_options.add(config);

        // Parse the command line options
        po::store(po::parse_command_line(argc, argv, cmdline_options), vm);
        po::notify(vm);

        // If the command-line help option was given, print help and exit
        if (vm.count("help"))
        {
            std::cout << "usage: frameReceiver [options]" << std::endl << std::endl;
            std::cout << cmdline_options << std::endl;
            exit(1);
        }

        // If the command line config option was given, parse the specified configuration
        // file for additional options. Note that boost::program_options gives precedence
        // to the first instance occurring. In this case, that implies that command-line
        // options have precedence over equivalent configuration file entries.
        if (vm.count("config"))
        {
            std::ifstream config_ifs(config_file.c_str());
            if (config_ifs)
            {
                LOG4CXX_DEBUG(logger, "Parsing configuration file " << config_file);
                po::store(po::parse_config_file(config_ifs, config_file_options, true), vm);
                po::notify(vm);
            }
            else
            {
                LOG4CXX_ERROR(logger, "Unable to open configuration file " << config_file << " for parsing");
                exit(1);
            }
        }

        if (vm.count("logconfig"))
        {
            PropertyConfigurator::configure(vm["logconfig"].as<string>());
            LOG4CXX_DEBUG(logger, "log4cxx config file is set to " << vm["logconfig"].as<string>());
        }

        if (vm.count("ready"))
        {
            LOG4CXX_DEBUG(logger, "Setting frame ready notification ZMQ address to " << vm["ready"].as<string>());
        }

        if (vm.count("release"))
        {
            LOG4CXX_DEBUG(logger, "Setting frame release notification ZMQ address to " << vm["release"].as<string>());
        }

        if (vm.count("frames"))
        {
            LOG4CXX_DEBUG(logger, "Setting number of frames to receive to " << vm["frames"].as<unsigned int>());
        }

    }
    catch (po::unknown_option &e)
    {
        LOG4CXX_WARN(logger, "CLI parsing error: " << e.what() << ". Will carry on...");
    }
    catch (Exception &e)
    {
        LOG4CXX_FATAL(logger, "Got Log4CXX exception: " << e.what());
        throw;
    }
    catch (exception &e)
    {
        LOG4CXX_ERROR(logger, "Got exception:" << e.what());
        throw;
    }
    catch (...)
    {
        LOG4CXX_FATAL(logger, "Exception of unknown type!");
        throw;
    }
}

int main(int argc, char** argv)
{
    int rc = 0;

    // Create a default basic logger configuration, which can be overridden by command-line option later
    BasicConfigurator::configure();

    LoggerPtr logger(Logger::getLogger("FrameNotifier"));
    po::variables_map vm;
    parse_arguments(argc, argv, vm, logger);

    SharedMemParser smp(vm["sharedbuf"].as<string>());

    // Assuming this is a P2M, our image dimensions are:
    dimensions_t p2m_dims(2); p2m_dims[0] = 1484; p2m_dims[1] = 1404;

    zmq::context_t zmq_context; // Global ZMQ context

    // The "release" ZMQ PUB socket, used to release frames back to the frameReceiver
    zmq::socket_t zsocket_release(zmq_context, ZMQ_PUB);
    zsocket_release.connect(vm["release"].as<string>().c_str());

    // The "ready" ZMQ SUB socket, used to get notifications that new frames are ready to be processed
    zmq::socket_t zsocket_ready(zmq_context, ZMQ_SUB);
    zsocket_ready.connect(vm["ready"].as<string>().c_str());
    zsocket_ready.setsockopt(ZMQ_SUBSCRIBE, "", strlen(""));
    zmq::pollitem_t poll_item;
    poll_item.socket = zsocket_ready;
    poll_item.events = ZMQ_POLLIN;
    poll_item.fd = 0;
    poll_item.revents = 0;

    // The polling loop. Polls on all elements in poll_item
    // Stop the loop by setting keep_running=false
    // Loop automatically ends if notification_count > user option "frames"
    unsigned long notification_count = 0;
    bool keep_running = true;
    LOG4CXX_DEBUG(logger, "Entering ZMQ polling loop (" << vm["ready"].as<string>().c_str() << ")");
    while (keep_running)
    {
        // Always reset the last raw events before polling
        poll_item.revents = 0;

        // Do the poll with a 10ms timeout (i.e. 10Hz poll)
        zmq::poll(&poll_item, 1, 10);

        // Check for poll error and exit the loop is one is found
        if (poll_item.revents & ZMQ_POLLERR)
        {
            LOG4CXX_ERROR(logger, "Got ZMQ error in polling. Quitting polling loop.");
            keep_running = false;
        }
        // Do work if a message is received
        else if (poll_item.revents & ZMQ_POLLIN)
        {
            LOG4CXX_DEBUG(logger, "Reading data from ZMQ socket");
            notification_count++;
            zmq::message_t msg;
            zsocket_ready.recv(&msg); // Read the message from the ready socket

            string msg_str(reinterpret_cast<char*>(msg.data()), msg.size()-1);
            LOG4CXX_DEBUG(logger, "Parsing JSON msg string: " << msg_str);
            Document msg_doc;
            msg_doc.Parse(msg_str.c_str()); // Parse the JSON string into a Document DOM object

            // Setup a string buffer and a writer so we can stringify the Document DOM object again
            StringBuffer buffer;
            PrettyWriter<StringBuffer> writer(buffer);
            msg_doc.Accept(writer);
            LOG4CXX_DEBUG(logger, "Parsed json: " << buffer.GetString());

            // Copy the data out into a Frame object
            LOG4CXX_DEBUG(logger, "Creating Frame object");
            Frame frame(smp.get_buffer_size(), p2m_dims);
            LOG4CXX_DEBUG(logger, "Copying buffer ID: " << msg_doc["params"]["buffer_id"].GetInt64());
            smp.get_frame(frame, msg_doc["params"]["buffer_id"].GetInt64());
            LOG4CXX_DEBUG(logger, "Frame completeness: " << frame.get_header()->packets_received << " packets received");

            // Clear the json string buffer and reset the writer so we can re-use them
            // after modifying the Document DOM object
            buffer.Clear();
            writer.Reset(buffer);

            // We want to return the exact same JSON message back to the frameReceiver
            // so we just modify the relevant bits: msg_val: from frame_ready to frame_release
            // and update the timestamp
            msg_doc["msg_val"].SetString("frame_release");

            // Create and update the timestamp in the JSON message
            boost::posix_time::ptime msg_timestamp = boost::posix_time::microsec_clock::local_time();
            string msg_timestamp_str = boost::posix_time::to_iso_extended_string(msg_timestamp);
            msg_doc["timestamp"].SetString(StringRef(msg_timestamp_str.c_str()));

            // Encode the JSON Document DOM object using the writer
            msg_doc.Accept(writer);
            LOG4CXX_DEBUG(logger, "Changing msg_val: " << msg_doc["msg_val"].GetString());
            string release_msg(buffer.GetString()); // Get a copy of the JSON string
            LOG4CXX_DEBUG(logger, "New json: " << release_msg);

            LOG4CXX_DEBUG(logger, "Sending release response");
            // Send the new JSON object (string) back to the frameReceiver on the "release" ZMQ socket
            size_t nbytes = zsocket_release.send(release_msg.c_str(), release_msg.size() + 1);
            LOG4CXX_DEBUG(logger, "Sent " << nbytes << " bytes");
        } else
        {
            // No new data
        }

        // Quit the loop if we have received the desired number of frames
        if (notification_count >= vm["frames"].as<unsigned int>()) keep_running=false;
    }
    return rc;
}

<commit_msg>filewriter: Using the FileWriter class in the main application<commit_after>/**
framenotifier_app.cpp

  Created on: 13 Oct 2015
      Author: up45
*/
#include <signal.h>
#include <string>
#include <cstring>
#include <iostream>
#include <fstream>
using namespace std;

#include <log4cxx/logger.h>
#include <log4cxx/basicconfigurator.h>
#include <log4cxx/propertyconfigurator.h>
#include <log4cxx/helpers/exception.h>
using namespace log4cxx;
using namespace log4cxx::helpers;

#include <boost/foreach.hpp>
#include <boost/program_options.hpp>
#include "boost/date_time/posix_time/posix_time.hpp"
namespace po = boost::program_options;

#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/stringbuffer.h"
using namespace rapidjson;

#include "zmq/zmq.hpp"

#include "framenotifier_data.h"
#include "FileWriter.h"

void parse_arguments(int argc, char** argv, po::variables_map& vm, LoggerPtr& logger)
{
    try
    {
        std::string config_file;

        // Declare a group of options that will allowed only on the command line
        po::options_description generic("Generic options");
        generic.add_options()
                ("help,h",
                    "Print this help message")
                ("config,c",    po::value<string>(&config_file),
                    "Specify program configuration file")
                ;

        // Declare a group of options that will be allowed both on the command line
        // and in the configuration file
        po::options_description config("Configuration options");
        config.add_options()
                ("logconfig,l",  po::value<string>(),
                    "Set the log4cxx logging configuration file")
                ("ready,r",       po::value<std::string>()->default_value("tcp://127.0.0.1:5001"),
                    "Ready ZMQ endpoint from frameReceiver")
                ("release",       po::value<std::string>()->default_value("tcp://127.0.0.1:5002"),
                        "Release frame ZMQ endpoint from frameReceiver")
                ("frames,f",     po::value<unsigned int>()->default_value(1),
                    "Set the number of frames to be notified about before terminating")
                ("sharedbuf",    po::value<std::string>()->default_value("FrameReceiverBuffer"),
                    "Set the name of the shared memory frame buffer")
                ;

        // Group the variables for parsing at the command line and/or from the configuration file
        po::options_description cmdline_options;
        cmdline_options.add(generic).add(config);
        po::options_description config_file_options;
        config_file_options.add(config);

        // Parse the command line options
        po::store(po::parse_command_line(argc, argv, cmdline_options), vm);
        po::notify(vm);

        // If the command-line help option was given, print help and exit
        if (vm.count("help"))
        {
            std::cout << "usage: frameReceiver [options]" << std::endl << std::endl;
            std::cout << cmdline_options << std::endl;
            exit(1);
        }

        // If the command line config option was given, parse the specified configuration
        // file for additional options. Note that boost::program_options gives precedence
        // to the first instance occurring. In this case, that implies that command-line
        // options have precedence over equivalent configuration file entries.
        if (vm.count("config"))
        {
            std::ifstream config_ifs(config_file.c_str());
            if (config_ifs)
            {
                LOG4CXX_DEBUG(logger, "Parsing configuration file " << config_file);
                po::store(po::parse_config_file(config_ifs, config_file_options, true), vm);
                po::notify(vm);
            }
            else
            {
                LOG4CXX_ERROR(logger, "Unable to open configuration file " << config_file << " for parsing");
                exit(1);
            }
        }

        if (vm.count("logconfig"))
        {
            PropertyConfigurator::configure(vm["logconfig"].as<string>());
            LOG4CXX_DEBUG(logger, "log4cxx config file is set to " << vm["logconfig"].as<string>());
        }

        if (vm.count("ready"))
        {
            LOG4CXX_DEBUG(logger, "Setting frame ready notification ZMQ address to " << vm["ready"].as<string>());
        }

        if (vm.count("release"))
        {
            LOG4CXX_DEBUG(logger, "Setting frame release notification ZMQ address to " << vm["release"].as<string>());
        }

        if (vm.count("frames"))
        {
            LOG4CXX_DEBUG(logger, "Setting number of frames to receive to " << vm["frames"].as<unsigned int>());
        }

    }
    catch (po::unknown_option &e)
    {
        LOG4CXX_WARN(logger, "CLI parsing error: " << e.what() << ". Will carry on...");
    }
    catch (Exception &e)
    {
        LOG4CXX_FATAL(logger, "Got Log4CXX exception: " << e.what());
        throw;
    }
    catch (exception &e)
    {
        LOG4CXX_ERROR(logger, "Got exception:" << e.what());
        throw;
    }
    catch (...)
    {
        LOG4CXX_FATAL(logger, "Exception of unknown type!");
        throw;
    }
}

int main(int argc, char** argv)
{
    int rc = 0;

    // Create a default basic logger configuration, which can be overridden by command-line option later
    BasicConfigurator::configure();

    LoggerPtr logger(Logger::getLogger("FrameNotifier"));
    po::variables_map vm;
    parse_arguments(argc, argv, vm, logger);

    SharedMemParser smp(vm["sharedbuf"].as<string>());

    // Assuming this is a P2M, our image dimensions are:
    size_t bytes_per_pixel = 2;
    dimensions_t p2m_dims(2); p2m_dims[0] = 1484; p2m_dims[1] = 1404;

    zmq::context_t zmq_context; // Global ZMQ context

    // The "release" ZMQ PUB socket, used to release frames back to the frameReceiver
    zmq::socket_t zsocket_release(zmq_context, ZMQ_PUB);
    zsocket_release.connect(vm["release"].as<string>().c_str());

    // The "ready" ZMQ SUB socket, used to get notifications that new frames are ready to be processed
    zmq::socket_t zsocket_ready(zmq_context, ZMQ_SUB);
    zsocket_ready.connect(vm["ready"].as<string>().c_str());
    zsocket_ready.setsockopt(ZMQ_SUBSCRIBE, "", strlen(""));
    zmq::pollitem_t poll_item;
    poll_item.socket = zsocket_ready;
    poll_item.events = ZMQ_POLLIN;
    poll_item.fd = 0;
    poll_item.revents = 0;

    // The file writer object
    FileWriter hdfwr;
    hdfwr.createFile("data.h5");
    FileWriter::DatasetDefinition dset_def;
    dset_def.name = "data";
    dset_def.frame_dimensions = p2m_dims;
    dset_def.pixel = FileWriter::pixel_raw_16bit;
    dset_def.num_frames = vm["frames"].as<unsigned int>();
    hdfwr.createDataset(dset_def);

    // The polling loop. Polls on all elements in poll_item
    // Stop the loop by setting keep_running=false
    // Loop automatically ends if notification_count > user option "frames"
    unsigned long notification_count = 0;
    bool keep_running = true;
    LOG4CXX_DEBUG(logger, "Entering ZMQ polling loop (" << vm["ready"].as<string>().c_str() << ")");
    while (keep_running)
    {
        // Always reset the last raw events before polling
        poll_item.revents = 0;

        // Do the poll with a 10ms timeout (i.e. 10Hz poll)
        zmq::poll(&poll_item, 1, 10);

        // Check for poll error and exit the loop is one is found
        if (poll_item.revents & ZMQ_POLLERR)
        {
            LOG4CXX_ERROR(logger, "Got ZMQ error in polling. Quitting polling loop.");
            keep_running = false;
        }
        // Do work if a message is received
        else if (poll_item.revents & ZMQ_POLLIN)
        {
            LOG4CXX_DEBUG(logger, "Reading data from ZMQ socket");
            notification_count++;
            zmq::message_t msg;
            zsocket_ready.recv(&msg); // Read the message from the ready socket

            string msg_str(reinterpret_cast<char*>(msg.data()), msg.size()-1);
            LOG4CXX_DEBUG(logger, "Parsing JSON msg string: " << msg_str);
            Document msg_doc;
            msg_doc.Parse(msg_str.c_str()); // Parse the JSON string into a Document DOM object

            // Setup a string buffer and a writer so we can stringify the Document DOM object again
            StringBuffer buffer;
            PrettyWriter<StringBuffer> writer(buffer);
            msg_doc.Accept(writer);
            LOG4CXX_DEBUG(logger, "Parsed json: " << buffer.GetString());

            // Copy the data out into a Frame object
            LOG4CXX_DEBUG(logger, "Creating Frame object");
            Frame frame(bytes_per_pixel, p2m_dims);
            LOG4CXX_DEBUG(logger, "Copying buffer ID: " << msg_doc["params"]["buffer_id"].GetInt64());
            smp.get_frame(frame, msg_doc["params"]["buffer_id"].GetInt64());
            LOG4CXX_DEBUG(logger, "Frame completeness: " << frame.get_header()->packets_received << " packets received");

            // Clear the json string buffer and reset the writer so we can re-use them
            // after modifying the Document DOM object
            buffer.Clear();
            writer.Reset(buffer);

            // We want to return the exact same JSON message back to the frameReceiver
            // so we just modify the relevant bits: msg_val: from frame_ready to frame_release
            // and update the timestamp
            msg_doc["msg_val"].SetString("frame_release");

            // Create and update the timestamp in the JSON message
            boost::posix_time::ptime msg_timestamp = boost::posix_time::microsec_clock::local_time();
            string msg_timestamp_str = boost::posix_time::to_iso_extended_string(msg_timestamp);
            msg_doc["timestamp"].SetString(StringRef(msg_timestamp_str.c_str()));

            // Encode the JSON Document DOM object using the writer
            msg_doc.Accept(writer);
            LOG4CXX_DEBUG(logger, "Changing msg_val: " << msg_doc["msg_val"].GetString());
            string release_msg(buffer.GetString()); // Get a copy of the JSON string
            LOG4CXX_DEBUG(logger, "New json: " << release_msg);

            LOG4CXX_DEBUG(logger, "Sending release response");
            // Send the new JSON object (string) back to the frameReceiver on the "release" ZMQ socket
            size_t nbytes = zsocket_release.send(release_msg.c_str(), release_msg.size() + 1);
            LOG4CXX_DEBUG(logger, "Sent " << nbytes << " bytes");

            // Write the frame to disk
            hdfwr.writeFrame(frame);

        } else
        {
            // No new data
        }

        // Quit the loop if we have received the desired number of frames
        if (notification_count >= vm["frames"].as<unsigned int>()) keep_running=false;
    }
    hdfwr.closeFile();
    return rc;
}

<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org 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.
 *
 * OpenOffice.org 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
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _OBJECT_HXX
#define _OBJECT_HXX

#define _SVSTDARR_ULONGS
#include <types.hxx>
#include <slot.hxx>
#include <vector>
#include <tools/list.hxx>

struct SvSlotElement
{
    SvMetaSlotRef   xSlot;
    ByteString          aPrefix;
            SvSlotElement( SvMetaSlot * pS, const ByteString & rPrefix )
                : xSlot( pS )
                , aPrefix( rPrefix )
             {}
};
typedef std::vector< SvSlotElement* > SvSlotElementList;

class SvMetaClass;
typedef ::std::vector< SvMetaClass* > SvMetaClassList;

SV_DECL_REF(SvMetaClass)
class SvClassElement : public SvPersistBase
{
    SvBOOL                      aAutomation;
    ByteString                      aPrefix;
    SvMetaClassRef              xClass;
public:
            SV_DECL_PERSIST1( SvClassElement, SvPersistBase, 1 )
            SvClassElement();

    void            SetPrefix( const ByteString & rPrefix )
                    { aPrefix = rPrefix; }
    const ByteString &  GetPrefix() const
                    { return aPrefix; }

    void            SetAutomation( sal_Bool rAutomation )
                    { aAutomation = rAutomation; }
    sal_Bool            GetAutomation() const
                    { return aAutomation; }

    void            SetClass( SvMetaClass * pClass )
                    { xClass = pClass; }
    SvMetaClass *   GetClass() const
                    { return xClass; }
};

SV_DECL_IMPL_REF(SvClassElement)
SV_DECL_IMPL_PERSIST_LIST(SvClassElement,SvClassElement *)

class SvMetaModule;
SV_DECL_PERSIST_LIST(SvMetaClass,SvMetaClass *)
class SvMetaClass : public SvMetaType
{
    SvMetaAttributeMemberList   aAttrList;
    SvClassElementMemberList    aClassList;
    SvMetaClassRef              aSuperClass;
    SvBOOL                      aAutomation;
    SvMetaClassRef              xAutomationInterface;

    sal_Bool                TestAttribute( SvIdlDataBase & rBase, SvTokenStream & rInStm,
                                     SvMetaAttribute & rAttr ) const;
#ifdef IDL_COMPILER
    void                WriteSlotStubs( const ByteString & rShellName,
                                        SvSlotElementList & rSlotList,
                                        ByteStringList & rList,
                                        SvStream & rOutStm );
    sal_uInt16              WriteSlotParamArray( SvIdlDataBase & rBase,
                                            SvSlotElementList & rSlotList,
                                            SvStream & rOutStm );
    sal_uInt16              WriteSlots( const ByteString & rShellName, sal_uInt16 nCount,
                                    SvSlotElementList & rSlotList,
                                    SvIdlDataBase & rBase,
                                    SvStream & rOutStm );

    void                InsertSlots( SvSlotElementList& rList, std::vector<sal_uLong>& rSuperList,
                                    SvMetaClassList & rClassList,
                                    const ByteString & rPrefix, SvIdlDataBase& rBase );

protected:
    virtual void    ReadAttributesSvIdl( SvIdlDataBase & rBase,
                                      SvTokenStream & rInStm );
    virtual void    WriteAttributesSvIdl( SvIdlDataBase & rBase,
                                    SvStream & rOutStm, sal_uInt16 nTab );
    virtual void    ReadContextSvIdl( SvIdlDataBase &,
                                     SvTokenStream & rInStm );
    virtual void    WriteContextSvIdl( SvIdlDataBase & rBase,
                                     SvStream & rOutStm, sal_uInt16 nTab );
    void            WriteOdlMembers( ByteStringList & rSuperList,
                                    sal_Bool bVariable, sal_Bool bWriteTab,
                                    SvIdlDataBase & rBase,
                                    SvStream & rOutStm, sal_uInt16 nTab );
#endif
public:
            SV_DECL_META_FACTORY1( SvMetaClass, SvMetaType, 6 )
            SvMetaClass();

    sal_Bool                GetAutomation() const
                        { return aAutomation; }
    SvMetaClass *       GetSuperClass() const
                        { return aSuperClass; }

    void                FillClasses( SvMetaClassList & rList );

    const SvClassElementMemberList&
                        GetClassList() const
                        { return aClassList; }

#ifdef IDL_COMPILER
    virtual sal_Bool        ReadSvIdl( SvIdlDataBase &, SvTokenStream & rInStm );
    virtual void        WriteSvIdl( SvIdlDataBase & rBase, SvStream & rOutStm, sal_uInt16 nTab );
    virtual void        Write( SvIdlDataBase & rBase, SvStream & rOutStm,
                                 sal_uInt16 nTab,
                                  WriteType, WriteAttribute = 0 );
    virtual void        WriteSfx( SvIdlDataBase & rBase, SvStream & rOutStm );
    virtual void        WriteHelpIds( SvIdlDataBase & rBase, SvStream & rOutStm,
                                Table* pTable );
    virtual void        WriteSrc( SvIdlDataBase & rBase, SvStream & rOutStm,
                                 Table * pTable );
    virtual void        WriteCxx( SvIdlDataBase & rBase, SvStream & rOutStm, sal_uInt16 nTab );
    virtual void        WriteHxx( SvIdlDataBase & rBase, SvStream & rOutStm, sal_uInt16 nTab );
#endif
};
SV_IMPL_REF(SvMetaClass)
SV_IMPL_PERSIST_LIST(SvMetaClass,SvMetaClass *)

#endif // _OBJECT_HXX

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Remove unneed include of <tools/list.hxx><commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org 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.
 *
 * OpenOffice.org 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
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _OBJECT_HXX
#define _OBJECT_HXX

#define _SVSTDARR_ULONGS
#include <types.hxx>
#include <slot.hxx>
#include <vector>

struct SvSlotElement
{
    SvMetaSlotRef   xSlot;
    ByteString          aPrefix;
            SvSlotElement( SvMetaSlot * pS, const ByteString & rPrefix )
                : xSlot( pS )
                , aPrefix( rPrefix )
             {}
};
typedef std::vector< SvSlotElement* > SvSlotElementList;

class SvMetaClass;
typedef ::std::vector< SvMetaClass* > SvMetaClassList;

SV_DECL_REF(SvMetaClass)
class SvClassElement : public SvPersistBase
{
    SvBOOL                      aAutomation;
    ByteString                      aPrefix;
    SvMetaClassRef              xClass;
public:
            SV_DECL_PERSIST1( SvClassElement, SvPersistBase, 1 )
            SvClassElement();

    void            SetPrefix( const ByteString & rPrefix )
                    { aPrefix = rPrefix; }
    const ByteString &  GetPrefix() const
                    { return aPrefix; }

    void            SetAutomation( sal_Bool rAutomation )
                    { aAutomation = rAutomation; }
    sal_Bool            GetAutomation() const
                    { return aAutomation; }

    void            SetClass( SvMetaClass * pClass )
                    { xClass = pClass; }
    SvMetaClass *   GetClass() const
                    { return xClass; }
};

SV_DECL_IMPL_REF(SvClassElement)
SV_DECL_IMPL_PERSIST_LIST(SvClassElement,SvClassElement *)

class SvMetaModule;
SV_DECL_PERSIST_LIST(SvMetaClass,SvMetaClass *)
class SvMetaClass : public SvMetaType
{
    SvMetaAttributeMemberList   aAttrList;
    SvClassElementMemberList    aClassList;
    SvMetaClassRef              aSuperClass;
    SvBOOL                      aAutomation;
    SvMetaClassRef              xAutomationInterface;

    sal_Bool                TestAttribute( SvIdlDataBase & rBase, SvTokenStream & rInStm,
                                     SvMetaAttribute & rAttr ) const;
#ifdef IDL_COMPILER
    void                WriteSlotStubs( const ByteString & rShellName,
                                        SvSlotElementList & rSlotList,
                                        ByteStringList & rList,
                                        SvStream & rOutStm );
    sal_uInt16              WriteSlotParamArray( SvIdlDataBase & rBase,
                                            SvSlotElementList & rSlotList,
                                            SvStream & rOutStm );
    sal_uInt16              WriteSlots( const ByteString & rShellName, sal_uInt16 nCount,
                                    SvSlotElementList & rSlotList,
                                    SvIdlDataBase & rBase,
                                    SvStream & rOutStm );

    void                InsertSlots( SvSlotElementList& rList, std::vector<sal_uLong>& rSuperList,
                                    SvMetaClassList & rClassList,
                                    const ByteString & rPrefix, SvIdlDataBase& rBase );

protected:
    virtual void    ReadAttributesSvIdl( SvIdlDataBase & rBase,
                                      SvTokenStream & rInStm );
    virtual void    WriteAttributesSvIdl( SvIdlDataBase & rBase,
                                    SvStream & rOutStm, sal_uInt16 nTab );
    virtual void    ReadContextSvIdl( SvIdlDataBase &,
                                     SvTokenStream & rInStm );
    virtual void    WriteContextSvIdl( SvIdlDataBase & rBase,
                                     SvStream & rOutStm, sal_uInt16 nTab );
    void            WriteOdlMembers( ByteStringList & rSuperList,
                                    sal_Bool bVariable, sal_Bool bWriteTab,
                                    SvIdlDataBase & rBase,
                                    SvStream & rOutStm, sal_uInt16 nTab );
#endif
public:
            SV_DECL_META_FACTORY1( SvMetaClass, SvMetaType, 6 )
            SvMetaClass();

    sal_Bool                GetAutomation() const
                        { return aAutomation; }
    SvMetaClass *       GetSuperClass() const
                        { return aSuperClass; }

    void                FillClasses( SvMetaClassList & rList );

    const SvClassElementMemberList&
                        GetClassList() const
                        { return aClassList; }

#ifdef IDL_COMPILER
    virtual sal_Bool        ReadSvIdl( SvIdlDataBase &, SvTokenStream & rInStm );
    virtual void        WriteSvIdl( SvIdlDataBase & rBase, SvStream & rOutStm, sal_uInt16 nTab );
    virtual void        Write( SvIdlDataBase & rBase, SvStream & rOutStm,
                                 sal_uInt16 nTab,
                                  WriteType, WriteAttribute = 0 );
    virtual void        WriteSfx( SvIdlDataBase & rBase, SvStream & rOutStm );
    virtual void        WriteHelpIds( SvIdlDataBase & rBase, SvStream & rOutStm,
                                Table* pTable );
    virtual void        WriteSrc( SvIdlDataBase & rBase, SvStream & rOutStm,
                                 Table * pTable );
    virtual void        WriteCxx( SvIdlDataBase & rBase, SvStream & rOutStm, sal_uInt16 nTab );
    virtual void        WriteHxx( SvIdlDataBase & rBase, SvStream & rOutStm, sal_uInt16 nTab );
#endif
};
SV_IMPL_REF(SvMetaClass)
SV_IMPL_PERSIST_LIST(SvMetaClass,SvMetaClass *)

#endif // _OBJECT_HXX

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


<commit_before>// $Id$
# ifndef CPPAD_LOCAL_OPTIMIZE_MATCH_OP_HPP
# define CPPAD_LOCAL_OPTIMIZE_MATCH_OP_HPP
/* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-16 Bradley M. Bell

CppAD is distributed under multiple licenses. This distribution is under
the terms of the
                    Eclipse Public License Version 1.0.

A copy of this license is included in the COPYING file of this distribution.
Please visit http://www.coin-or.org/CppAD/ for information on other licenses.
-------------------------------------------------------------------------- */
# include <cppad/local/optimize/hash_code.hpp>
/*!
\file match_op.hpp
Check if current operator matches a previous operator.
*/
// BEGIN_CPPAD_LOCAL_OPTIMIZE_NAMESPACE
namespace CppAD { namespace local { namespace optimize  {
/*!
Search for a previous operator that matches the current one.

\param var2op
mapping from variable index to operator index.

\param op_info
mapping from operator index to operator information

\param current
is the index of the current operator.

\li
This must be a unary or binary
operator; hence, NumArg( op_info[current].op ) is one or two.
There is one exception, NumRes( ErfOp ) == 3, but arg[0]
is the only true arguments (the others are always the same).

\li
This must not be a VecAD load or store operation; i.e.,
LtpvOp, LtvpOp, LtvvOp, StppOp, StpvOp, StvpOp, StvvOp.
It also must not be an independent variable operator InvOp.

\param hash_table_op
is a vector with size CPPAD_HASH_TABLE_SIZE
that maps a hash code to the corresponding
variable index in the operation sequence.
All the values in this table are less than current.

\param code [out]
The input value of code does not matter.
The output value of code is the hash code corresponding to
the current operation in the new operation sequence.

\return
We refer to the return value as pevious.
If pevious == 0, no match was found.
If previous != 0,
it is a pevious operator that can be used in place of current.
In addition op_info[previous].previous == 0.
*/

inline size_t match_op(
	const vector<size_t>&                              var2op         ,
	const vector<struct_op_info>&                      op_info        ,
	size_t                                             current        ,
	const vector<size_t>&                              hash_table_op  ,
	unsigned short&                                    code           )
{	// current operator
	OpCode        op         = op_info[current].op;
	const addr_t* arg        = op_info[current].arg;
	//
	// which arguments are variable
	size_t num_arg = NumArg(op);
	//
	bool   variable[2];
	variable[0] = false;
	variable[1] = false;
	switch(op)
	{	//
		case ErfOp:
		num_arg = 1; // other arugments are always the same
		//
		case AbsOp:
		case AcosOp:
		case AcoshOp:
		case AsinOp:
		case AsinhOp:
		case AtanOp:
		case AtanhOp:
		case CosOp:
		case CoshOp:
		case ExpOp:
		case Expm1Op:
		case LogOp:
		case Log1pOp:
		case SignOp:
		case SinOp:
		case SinhOp:
		case SqrtOp:
		case TanOp:
		case TanhOp:
		CPPAD_ASSERT_UNKNOWN( num_arg == 1 );
		variable[0] = true;
		break;

		case AddpvOp:
		case DisOp:
		case DivpvOp:
		case EqpvOp:
		case LepvOp:
		case LtpvOp:
		case MulpvOp:
		case NepvOp:
		case PowpvOp:
		case SubpvOp:
		case ZmulpvOp:
		CPPAD_ASSERT_UNKNOWN( num_arg == 2 );
		variable[1] = true;
		break;

		case DivvpOp:
		case LevpOp:
		case LtvpOp:
		case PowvpOp:
		case SubvpOp:
		case ZmulvpOp:
		CPPAD_ASSERT_UNKNOWN( num_arg == 2 );
		variable[0] = true;
		break;

		case AddvvOp:
		case DivvvOp:
		case EqvvOp:
		case LevvOp:
		case LtvvOp:
		case MulvvOp:
		case NevvOp:
		case PowvvOp:
		case SubvvOp:
		case ZmulvvOp:
		CPPAD_ASSERT_UNKNOWN( num_arg == 2 );
		variable[0] = true;
		variable[1] = true;
		break;

		default:
		CPPAD_ASSERT_UNKNOWN(false);
	}
	//
	// If i-th argument to current operator has a previous operator,
	// this is the i-th argument for previous operator.
	// Otherwise, it is the i-th argument for the current operator
	// (if a previous variable exists)
	addr_t arg_match[2];
	for(size_t j = 0; j < num_arg; ++j)
	{	arg_match[j] = arg[j];
		if( variable[j] )
		{	size_t previous = op_info[ var2op[arg[j]] ].previous;
			if( previous != 0 )
			{	CPPAD_ASSERT_UNKNOWN( op_info[previous].previous == 0 );
				//
				arg_match[j] = op_info[previous].i_var;
			}
		}
	}
	code = optimize_hash_code(op, num_arg, arg_match);
	//
	// candidate previous for current operator
	size_t  candidate  = hash_table_op[code];
	CPPAD_ASSERT_UNKNOWN( candidate < current );
	CPPAD_ASSERT_UNKNOWN( op_info[candidate].previous == 0 );
	//
	// check for a match
	bool match = candidate != 0;
	match     &= op == op_info[candidate].op;
	if( match )
	{	for(size_t j = 0; j < num_arg; j++)
		{	if( variable[j] )
			{	size_t previous =
					op_info[ var2op[op_info[candidate].arg[j]] ].previous;
				if( previous != 0 )
				{	CPPAD_ASSERT_UNKNOWN( op_info[previous].previous == 0 );
					//
					match &= arg_match[j] == addr_t( op_info[previous].i_var );
				}
				else
					match &= arg_match[j] == op_info[candidate].arg[j];
			}
		}
		if( match )
			return candidate;
	}

	// special case where operator is commutative
	if( (op == AddvvOp) | (op == MulvvOp ) )
	{	CPPAD_ASSERT_UNKNOWN( NumArg(op) == 2 );
		std::swap( arg_match[0], arg_match[1] );
		//
		code      = optimize_hash_code(op, num_arg, arg_match);
		candidate  = hash_table_op[code];
		CPPAD_ASSERT_UNKNOWN( candidate < current );
		CPPAD_ASSERT_UNKNOWN( op_info[candidate].previous == 0 );
		//
		match  = candidate != 0;
		match &= op == op_info[candidate].op;
		if( match )
		{	for(size_t j = 0; j < num_arg; j++)
			{	CPPAD_ASSERT_UNKNOWN( variable[j] )
				size_t previous =
					op_info[ var2op[op_info[candidate].arg[j]] ].previous;
				if( previous != 0 )
				{	CPPAD_ASSERT_UNKNOWN( op_info[previous].previous == 0 );
					//
					match &= arg_match[j] == addr_t( op_info[previous].i_var );
				}
				else
					match &= arg_match[j] == op_info[candidate].arg[j];
			}
			if( match )
				return candidate;
		}
	}
	// special op code used for no match
	return 0;
}

} } } // END_CPPAD_LOCAL_OPTIMIZE_NAMESPACE

# endif
<commit_msg>optimize branch: match_op.hpp: improve speed by making Unary special case.<commit_after>// $Id$
# ifndef CPPAD_LOCAL_OPTIMIZE_MATCH_OP_HPP
# define CPPAD_LOCAL_OPTIMIZE_MATCH_OP_HPP
/* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-16 Bradley M. Bell

CppAD is distributed under multiple licenses. This distribution is under
the terms of the
                    Eclipse Public License Version 1.0.

A copy of this license is included in the COPYING file of this distribution.
Please visit http://www.coin-or.org/CppAD/ for information on other licenses.
-------------------------------------------------------------------------- */
# include <cppad/local/optimize/hash_code.hpp>
/*!
\file match_op.hpp
Check if current operator matches a previous operator.
*/
// BEGIN_CPPAD_LOCAL_OPTIMIZE_NAMESPACE
namespace CppAD { namespace local { namespace optimize  {
/*!
Search for a previous operator that matches the current one.

\param var2op
mapping from variable index to operator index.

\param op_info
mapping from operator index to operator information

\param current
is the index of the current operator.

\li
This must be a unary or binary
operator; hence, NumArg( op_info[current].op ) is one or two.
There is one exception, NumRes( ErfOp ) == 3, but arg[0]
is the only true arguments (the others are always the same).

\li
This must not be a VecAD load or store operation; i.e.,
LtpvOp, LtvpOp, LtvvOp, StppOp, StpvOp, StvpOp, StvvOp.
It also must not be an independent variable operator InvOp.

\param hash_table_op
is a vector with size CPPAD_HASH_TABLE_SIZE
that maps a hash code to the corresponding
variable index in the operation sequence.
All the values in this table are less than current.

\param code [out]
The input value of code does not matter.
The output value of code is the hash code corresponding to
the current operation in the new operation sequence.

\return
We refer to the return value as pevious.
If pevious == 0, no match was found.
If previous != 0,
it is a pevious operator that can be used in place of current.
In addition op_info[previous].previous == 0.
*/

inline size_t match_op(
	const vector<size_t>&                              var2op         ,
	const vector<struct_op_info>&                      op_info        ,
	size_t                                             current        ,
	const vector<size_t>&                              hash_table_op  ,
	unsigned short&                                    code           )
{	// current operator
	OpCode        op         = op_info[current].op;
	const addr_t* arg        = op_info[current].arg;
	//
	// which arguments are variable
	size_t num_arg = NumArg(op);
	//
	bool   variable[2];
	variable[0] = false;
	variable[1] = false;
	//
	// If i-th argument to current operator has a previous operator,
	// this is the i-th argument for previous operator.
	// Otherwise, it is the i-th argument for the current operator
	// (if a previous variable exists)
	addr_t arg_match[2];
	switch(op)
	{	//
		case ErfOp:
		case AbsOp:
		case AcosOp:
		case AcoshOp:
		case AsinOp:
		case AsinhOp:
		case AtanOp:
		case AtanhOp:
		case CosOp:
		case CoshOp:
		case ExpOp:
		case Expm1Op:
		case LogOp:
		case Log1pOp:
		case SignOp:
		case SinOp:
		case SinhOp:
		case SqrtOp:
		case TanOp:
		case TanhOp:
		{	arg_match[0] = arg[0];
			size_t previous = op_info[ var2op[arg[0]] ].previous;
			if( previous != 0 )
			{	CPPAD_ASSERT_UNKNOWN( op_info[previous].previous == 0 );
				arg_match[0] = op_info[previous].i_var;
			}
			num_arg = 1;
			code = optimize_hash_code(op, num_arg, arg_match);
			//
			// candidate previous for current operator
			size_t candidate  = hash_table_op[code];
			CPPAD_ASSERT_UNKNOWN( candidate < current );
			CPPAD_ASSERT_UNKNOWN( op_info[candidate].previous == 0 );
			//
			if( (candidate == 0) | (op != op_info[candidate].op) )
				return 0;
			//
			// check for a match
			bool match;
			previous = op_info[ var2op[op_info[candidate].arg[0]] ].previous;
			if( previous == 0 )
				match = arg_match[0] == op_info[candidate].arg[0];
			else
			{	CPPAD_ASSERT_UNKNOWN( op_info[previous].previous == 0 );
				match = arg_match[0] == addr_t( op_info[previous].i_var );
			}
			if( match )
				return candidate;
			return 0;
		}
		break;

		case AddpvOp:
		case DisOp:
		case DivpvOp:
		case EqpvOp:
		case LepvOp:
		case LtpvOp:
		case MulpvOp:
		case NepvOp:
		case PowpvOp:
		case SubpvOp:
		case ZmulpvOp:
		CPPAD_ASSERT_UNKNOWN( num_arg == 2 );
		variable[1] = true;
		break;

		case DivvpOp:
		case LevpOp:
		case LtvpOp:
		case PowvpOp:
		case SubvpOp:
		case ZmulvpOp:
		CPPAD_ASSERT_UNKNOWN( num_arg == 2 );
		variable[0] = true;
		break;

		case AddvvOp:
		case DivvvOp:
		case EqvvOp:
		case LevvOp:
		case LtvvOp:
		case MulvvOp:
		case NevvOp:
		case PowvvOp:
		case SubvvOp:
		case ZmulvvOp:
		CPPAD_ASSERT_UNKNOWN( num_arg == 2 );
		variable[0] = true;
		variable[1] = true;
		break;

		default:
		CPPAD_ASSERT_UNKNOWN(false);
	}
	for(size_t j = 0; j < num_arg; ++j)
	{	arg_match[j] = arg[j];
		if( variable[j] )
		{	size_t previous = op_info[ var2op[arg[j]] ].previous;
			if( previous != 0 )
			{	CPPAD_ASSERT_UNKNOWN( op_info[previous].previous == 0 );
				//
				arg_match[j] = op_info[previous].i_var;
			}
		}
	}
	code = optimize_hash_code(op, num_arg, arg_match);
	//
	// candidate previous for current operator
	size_t  candidate  = hash_table_op[code];
	CPPAD_ASSERT_UNKNOWN( candidate < current );
	CPPAD_ASSERT_UNKNOWN( op_info[candidate].previous == 0 );
	//
	// check for a match
	bool match = candidate != 0;
	match     &= op == op_info[candidate].op;
	if( match )
	{	for(size_t j = 0; j < num_arg; j++)
		{	if( variable[j] )
			{	size_t previous =
					op_info[ var2op[op_info[candidate].arg[j]] ].previous;
				if( previous != 0 )
				{	CPPAD_ASSERT_UNKNOWN( op_info[previous].previous == 0 );
					//
					match &= arg_match[j] == addr_t( op_info[previous].i_var );
				}
				else
					match &= arg_match[j] == op_info[candidate].arg[j];
			}
		}
		if( match )
			return candidate;
	}

	// special case where operator is commutative
	if( (op == AddvvOp) | (op == MulvvOp ) )
	{	CPPAD_ASSERT_UNKNOWN( NumArg(op) == 2 );
		std::swap( arg_match[0], arg_match[1] );
		//
		code      = optimize_hash_code(op, num_arg, arg_match);
		candidate  = hash_table_op[code];
		CPPAD_ASSERT_UNKNOWN( candidate < current );
		CPPAD_ASSERT_UNKNOWN( op_info[candidate].previous == 0 );
		//
		match  = candidate != 0;
		match &= op == op_info[candidate].op;
		if( match )
		{	for(size_t j = 0; j < num_arg; j++)
			{	CPPAD_ASSERT_UNKNOWN( variable[j] )
				size_t previous =
					op_info[ var2op[op_info[candidate].arg[j]] ].previous;
				if( previous != 0 )
				{	CPPAD_ASSERT_UNKNOWN( op_info[previous].previous == 0 );
					//
					match &= arg_match[j] == addr_t( op_info[previous].i_var );
				}
				else
					match &= arg_match[j] == op_info[candidate].arg[j];
			}
			if( match )
				return candidate;
		}
	}
	// special op code used for no match
	return 0;
}

} } } // END_CPPAD_LOCAL_OPTIMIZE_NAMESPACE

# endif
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "libpng17/png.h"

#include "png_load.h"
#include "base/logging.h"

// *image_data_ptr should be deleted with free()
// return value of 1 == success.
int pngLoad(const char *file, int *pwidth, int *pheight, unsigned char **image_data_ptr, bool flip) {
	if (flip)
		ELOG("pngLoad: flip flag not supported, image will be loaded upside down");
	png_image png;
	memset(&png, 0, sizeof(png));
	png.version = PNG_IMAGE_VERSION;

	png_image_begin_read_from_file(&png, file);

	if (PNG_IMAGE_FAILED(png))
	{
		ELOG("pngLoad: %s", png.message);
		return 0;
	}
	*pwidth = png.width;
	*pheight = png.height;
	png.format = PNG_FORMAT_RGBA;

	int stride = PNG_IMAGE_ROW_STRIDE(png);
	*image_data_ptr = (unsigned char *)malloc(PNG_IMAGE_SIZE(png));
	png_image_finish_read(&png, NULL, *image_data_ptr, stride, NULL);

	return 1;
}

int pngLoadPtr(const unsigned char *input_ptr, size_t input_len, int *pwidth, int *pheight, unsigned char **image_data_ptr,
	bool flip) {
	if (flip)
		ELOG("pngLoad: flip flag not supported, image will be loaded upside down");
	png_image png;
	memset(&png, 0, sizeof(png));
	png.version = PNG_IMAGE_VERSION;

	png_image_begin_read_from_memory(&png, input_ptr, input_len);

	if (PNG_IMAGE_FAILED(png))
	{
		ELOG("pngLoad: %s", png.message);
		return 0;
	}
	*pwidth = png.width;
	*pheight = png.height;
	png.format = PNG_FORMAT_RGBA;

	int stride = PNG_IMAGE_ROW_STRIDE(png);
	*image_data_ptr = (unsigned char *)malloc(PNG_IMAGE_SIZE(png));
	png_image_finish_read(&png, NULL, *image_data_ptr, stride, NULL);

	return 1;
}
<commit_msg>Qt: Use inbuilt png handler to resolve conflicts.<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifdef USING_QT_UI
#include <QImage>
#else
#include "libpng17/png.h"
#endif

#include "png_load.h"
#include "base/logging.h"

// *image_data_ptr should be deleted with free()
// return value of 1 == success.
int pngLoad(const char *file, int *pwidth, int *pheight, unsigned char **image_data_ptr, bool flip) {
#ifdef USING_QT_UI
	QImage image(file, "PNG");
	if (image.isNull()) {
		ELOG("pngLoad: Error loading image %s", file);
		return 0;
	}
	if (flip)
		image = image.mirrored();
	image.convertToFormat(QImage::Format_RGB32);
	*pwidth = image.width();
	*pheight = image.height();
	*image_data_ptr = (unsigned char *)malloc(image.byteCount());
	memcpy(image.bits(), *image_data_ptr, image.byteCount());
#else
	if (flip)
		ELOG("pngLoad: flip flag not supported, image will be loaded upside down");
	png_image png;
	memset(&png, 0, sizeof(png));
	png.version = PNG_IMAGE_VERSION;

	png_image_begin_read_from_file(&png, file);

	if (PNG_IMAGE_FAILED(png))
	{
		ELOG("pngLoad: %s", png.message);
		return 0;
	}
	*pwidth = png.width;
	*pheight = png.height;
	png.format = PNG_FORMAT_RGBA;

	int stride = PNG_IMAGE_ROW_STRIDE(png);
	*image_data_ptr = (unsigned char *)malloc(PNG_IMAGE_SIZE(png));
	png_image_finish_read(&png, NULL, *image_data_ptr, stride, NULL);
#endif

	return 1;
}

int pngLoadPtr(const unsigned char *input_ptr, size_t input_len, int *pwidth, int *pheight, unsigned char **image_data_ptr,
	bool flip) {
#ifdef USING_QT_UI
	QImage image;
	if (!image.loadFromData(input_ptr, input_len)) {
		ELOG("pngLoad: Error loading image");
		return 0;
	}
	if (flip)
		image = image.mirrored();
	image.convertToFormat(QImage::Format_RGB32);
	*pwidth = image.width();
	*pheight = image.height();
	*image_data_ptr = (unsigned char *)malloc(image.byteCount());
	memcpy(image.bits(), *image_data_ptr, image.byteCount());
#else
	if (flip)
		ELOG("pngLoad: flip flag not supported, image will be loaded upside down");
	png_image png;
	memset(&png, 0, sizeof(png));
	png.version = PNG_IMAGE_VERSION;

	png_image_begin_read_from_memory(&png, input_ptr, input_len);

	if (PNG_IMAGE_FAILED(png))
	{
		ELOG("pngLoad: %s", png.message);
		return 0;
	}
	*pwidth = png.width;
	*pheight = png.height;
	png.format = PNG_FORMAT_RGBA;

	int stride = PNG_IMAGE_ROW_STRIDE(png);
	*image_data_ptr = (unsigned char *)malloc(PNG_IMAGE_SIZE(png));
	png_image_finish_read(&png, NULL, *image_data_ptr, stride, NULL);
#endif

	return 1;
}
<|endoftext|>


<commit_before>#include "xchainer/elementwise.h"

#include <tuple>

#include <gtest/gtest.h>

#include "xchainer/array.h"
#include "xchainer/axes.h"
#include "xchainer/shape.h"
#include "xchainer/strides.h"
#include "xchainer/testing/array.h"
#include "xchainer/testing/context_session.h"

namespace xchainer {
namespace {

TEST(ElementwiseTest, GetSquashedStrides) {
    {
        Strides squashed = GetSquashedStrides({3, 2, 5, 4}, {0, 1, 2, 3});
        EXPECT_EQ(4, squashed.ndim());
        EXPECT_EQ(3, squashed[0]);
        EXPECT_EQ(2, squashed[1]);
        EXPECT_EQ(5, squashed[2]);
        EXPECT_EQ(4, squashed[3]);
    }
    {
        Strides squashed = GetSquashedStrides({3, 2, 5, 4}, {1, 2});
        EXPECT_EQ(2, squashed.ndim());
        EXPECT_EQ(2, squashed[0]);
        EXPECT_EQ(5, squashed[1]);
    }
    {
        Strides squashed = GetSquashedStrides({3, 2, 5, 4}, {});
        EXPECT_EQ(0, squashed.ndim());
    }
    {
        Strides squashed = GetSquashedStrides({}, {});
        EXPECT_EQ(0, squashed.ndim());
    }
}

TEST(ElementwiseTest, SquashAllDimensions) {
    testing::ContextSession context_session;
    Shape shape{3, 2, 5, 4};
    Array a = testing::BuildArray(shape).WithLinearData<float>();

    Shape squashed{};
    Axes keep{};
    std::tie(squashed, keep) = SquashShape(a);

    EXPECT_EQ(1, squashed.ndim());
    EXPECT_EQ(shape[0] * shape[1] * shape[2] * shape[3], squashed[0]);
    EXPECT_EQ(1, keep.ndim());
    EXPECT_EQ(3, keep[0]);
}

TEST(ElementwiseTest, SquashPartialDimensions) {
    testing::ContextSession context_session;
    Shape shape{3, 2, 5, 4};
    Array a = testing::BuildArray(shape).WithLinearData<float>().WithPadding({0, 2, 0, 0});

    Shape squashed{};
    Axes keep{};
    std::tie(squashed, keep) = SquashShape(a);

    EXPECT_EQ(2, squashed.ndim());
    EXPECT_EQ(shape[0] * shape[1], squashed[0]);
    EXPECT_EQ(shape[2] * shape[3], squashed[1]);
    EXPECT_EQ(2, keep.ndim());
    EXPECT_EQ(1, keep[0]);
    EXPECT_EQ(3, keep[1]);
}

TEST(ElementwiseTest, SquashUnitLengthDimensions) {
    testing::ContextSession context_session;
    Shape shape{3, 2, 1, 4};
    Array a = testing::BuildArray(shape).WithLinearData<float>().WithPadding(1);

    Shape squashed{};
    Axes keep{};
    std::tie(squashed, keep) = SquashShape(a);

    EXPECT_EQ(3, squashed.ndim());
    EXPECT_EQ(shape[0], squashed[0]);
    EXPECT_EQ(shape[1], squashed[1]);
    EXPECT_EQ(shape[3], squashed[2]);
    EXPECT_EQ(3, keep.ndim());
    EXPECT_EQ(0, keep[0]);
    EXPECT_EQ(1, keep[1]);
    EXPECT_EQ(3, keep[2]);
}

TEST(ElementwiseTest, SquashMultipleArraysDimensions) {
    testing::ContextSession context_session;
    Shape shape{3, 2, 5, 4};
    Array a = testing::BuildArray(shape).WithLinearData<float>().WithPadding({0, 2, 0, 0});
    Array b = testing::BuildArray(shape).WithLinearData<float>().WithPadding({0, 0, 1, 0});

    Shape squashed{};
    Axes keep{};
    std::tie(squashed, keep) = SquashShape(a, b);

    EXPECT_EQ(3, squashed.ndim());
    EXPECT_EQ(shape[0] * shape[1], squashed[0]);
    EXPECT_EQ(shape[2], squashed[1]);
    EXPECT_EQ(shape[3], squashed[2]);
    EXPECT_EQ(3, keep.ndim());
    EXPECT_EQ(1, keep[0]);
    EXPECT_EQ(2, keep[1]);
    EXPECT_EQ(3, keep[2]);
}

}  // namespace
}  // namespace xchainer
<commit_msg>Avoid copies in test<commit_after>#include "xchainer/elementwise.h"

#include <tuple>

#include <gtest/gtest.h>

#include "xchainer/array.h"
#include "xchainer/axes.h"
#include "xchainer/shape.h"
#include "xchainer/strides.h"
#include "xchainer/testing/array.h"
#include "xchainer/testing/context_session.h"

namespace xchainer {
namespace {

TEST(ElementwiseTest, GetSquashedStrides) {
    {
        Strides squashed = GetSquashedStrides({3, 2, 5, 4}, {0, 1, 2, 3});
        EXPECT_EQ(4, squashed.ndim());
        EXPECT_EQ(3, squashed[0]);
        EXPECT_EQ(2, squashed[1]);
        EXPECT_EQ(5, squashed[2]);
        EXPECT_EQ(4, squashed[3]);
    }
    {
        Strides squashed = GetSquashedStrides({3, 2, 5, 4}, {1, 2});
        EXPECT_EQ(2, squashed.ndim());
        EXPECT_EQ(2, squashed[0]);
        EXPECT_EQ(5, squashed[1]);
    }
    {
        Strides squashed = GetSquashedStrides({3, 2, 5, 4}, {});
        EXPECT_EQ(0, squashed.ndim());
    }
    {
        Strides squashed = GetSquashedStrides({}, {});
        EXPECT_EQ(0, squashed.ndim());
    }
}

TEST(ElementwiseTest, SquashAllDimensions) {
    testing::ContextSession context_session;
    Shape shape{3, 2, 5, 4};
    Array a = testing::BuildArray(shape).WithLinearData<float>();

    std::tuple<Shape, Axes> squashed_result = SquashShape(a);
    const Shape& squashed = std::get<0>(squashed_result);
    const Axes& keep = std::get<1>(squashed_result);

    EXPECT_EQ(1, squashed.ndim());
    EXPECT_EQ(shape[0] * shape[1] * shape[2] * shape[3], squashed[0]);
    EXPECT_EQ(1, keep.ndim());
    EXPECT_EQ(3, keep[0]);
}

TEST(ElementwiseTest, SquashPartialDimensions) {
    testing::ContextSession context_session;
    Shape shape{3, 2, 5, 4};
    Array a = testing::BuildArray(shape).WithLinearData<float>().WithPadding({0, 2, 0, 0});

    std::tuple<Shape, Axes> squashed_result = SquashShape(a);
    const Shape& squashed = std::get<0>(squashed_result);
    const Axes& keep = std::get<1>(squashed_result);

    EXPECT_EQ(2, squashed.ndim());
    EXPECT_EQ(shape[0] * shape[1], squashed[0]);
    EXPECT_EQ(shape[2] * shape[3], squashed[1]);
    EXPECT_EQ(2, keep.ndim());
    EXPECT_EQ(1, keep[0]);
    EXPECT_EQ(3, keep[1]);
}

TEST(ElementwiseTest, SquashUnitLengthDimensions) {
    testing::ContextSession context_session;
    Shape shape{3, 2, 1, 4};
    Array a = testing::BuildArray(shape).WithLinearData<float>().WithPadding(1);

    std::tuple<Shape, Axes> squashed_result = SquashShape(a);
    const Shape& squashed = std::get<0>(squashed_result);
    const Axes& keep = std::get<1>(squashed_result);

    EXPECT_EQ(3, squashed.ndim());
    EXPECT_EQ(shape[0], squashed[0]);
    EXPECT_EQ(shape[1], squashed[1]);
    EXPECT_EQ(shape[3], squashed[2]);
    EXPECT_EQ(3, keep.ndim());
    EXPECT_EQ(0, keep[0]);
    EXPECT_EQ(1, keep[1]);
    EXPECT_EQ(3, keep[2]);
}

TEST(ElementwiseTest, SquashMultipleArraysDimensions) {
    testing::ContextSession context_session;
    Shape shape{3, 2, 5, 4};
    Array a = testing::BuildArray(shape).WithLinearData<float>().WithPadding({0, 2, 0, 0});
    Array b = testing::BuildArray(shape).WithLinearData<float>().WithPadding({0, 0, 1, 0});

    std::tuple<Shape, Axes> squashed_result = SquashShape(a, b);
    const Shape& squashed = std::get<0>(squashed_result);
    const Axes& keep = std::get<1>(squashed_result);

    EXPECT_EQ(3, squashed.ndim());
    EXPECT_EQ(shape[0] * shape[1], squashed[0]);
    EXPECT_EQ(shape[2], squashed[1]);
    EXPECT_EQ(shape[3], squashed[2]);
    EXPECT_EQ(3, keep.ndim());
    EXPECT_EQ(1, keep[0]);
    EXPECT_EQ(2, keep[1]);
    EXPECT_EQ(3, keep[2]);
}

}  // namespace
}  // namespace xchainer
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkPropAssembly.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

 * Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

 * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
   of any contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

 * Modified source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.

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 AUTHORS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=========================================================================*/
#include "vtkPropAssembly.h"
#include "vtkViewport.h"
#include "vtkAssemblyNode.h"
#include "vtkObjectFactory.h"

//-----------------------------------------------------------------------------
vtkPropAssembly* vtkPropAssembly::New()
{
  // First try to create the object from the vtkObjectFactory
  vtkObject* ret = vtkObjectFactory::CreateInstance("vtkPropAssembly");
  if(ret)
    {
    return (vtkPropAssembly*)ret;
    }
  // If the factory was unable to create the object, then create it here.
  return new vtkPropAssembly;
}

// Construct object with no children.
vtkPropAssembly::vtkPropAssembly()
{
  this->Parts = vtkPropCollection::New();
}

vtkPropAssembly::~vtkPropAssembly()
{
  this->Parts->Delete();
  this->Parts = NULL;
}

// Add a part to the list of Parts.
void vtkPropAssembly::AddPart(vtkProp *prop)
{
  if ( ! this->Parts->IsItemPresent(prop) )
    {
    this->Parts->AddItem(prop);
    this->Modified();
    }
}

// Remove a part from the list of parts,
void vtkPropAssembly::RemovePart(vtkProp *prop)
{
  if ( this->Parts->IsItemPresent(prop) )
    {
    this->Parts->RemoveItem(prop);
    this->Modified();
    }
}

// Get the list of parts for this prop assembly.
vtkPropCollection *vtkPropAssembly::GetParts()
{
  return this->Parts;
}

// Render this assembly and all of its Parts. The rendering process is recursive.
int vtkPropAssembly::RenderTranslucentGeometry(vtkViewport *ren)
{
  vtkProp *prop;
  vtkAssemblyPath *path;
  float fraction;
  int renderedSomething=0;

  fraction = this->AllocatedRenderTime /
             (float)this->Parts->GetNumberOfItems();

  // render the Paths
  for ( this->Paths->InitTraversal(); (path = this->Paths->GetNextItem()); )
    {
    prop = path->GetLastNode()->GetProp();
    if ( prop->GetVisibility() )
      {
      prop->SetAllocatedRenderTime(fraction, ren);
      prop->PokeMatrix(path->GetLastNode()->GetMatrix());
      renderedSomething += prop->RenderTranslucentGeometry(ren);
      prop->PokeMatrix(NULL);
      }
    }

  return renderedSomething;
}

// Render this assembly and all its parts. The rendering process is recursive.
int vtkPropAssembly::RenderOpaqueGeometry(vtkViewport *ren)
{
  vtkProp *prop;
  vtkAssemblyPath *path;
  float fraction;
  int   renderedSomething=0;

  // Make sure the paths are up-to-date
  this->UpdatePaths();

  fraction = this->AllocatedRenderTime /
             (float)this->Parts->GetNumberOfItems();

  // render the Paths
  for ( this->Paths->InitTraversal(); (path = this->Paths->GetNextItem()); )
    {
    prop = path->GetLastNode()->GetProp();
    if ( prop->GetVisibility() )
      {
      prop->SetAllocatedRenderTime(fraction, ren);
      prop->PokeMatrix(path->GetLastNode()->GetMatrix());
      renderedSomething += prop->RenderOpaqueGeometry(ren);
      prop->PokeMatrix(NULL);
      }
    }

  return renderedSomething;
}

// Render this assembly and all its parts. The rendering process is recursive.
int vtkPropAssembly::RenderOverlay(vtkViewport *ren)
{
  vtkProp *prop;
  vtkAssemblyPath *path;
  float fraction;
  int   renderedSomething=0;

  // Make sure the paths are up-to-date
  this->UpdatePaths();

  fraction = this->AllocatedRenderTime /
             (float)this->Parts->GetNumberOfItems();

  for ( this->Paths->InitTraversal(); (path = this->Paths->GetNextItem()); )
    {
    prop = path->GetLastNode()->GetProp();
    if ( prop->GetVisibility() )
      {
      prop->SetAllocatedRenderTime(fraction, ren);
      prop->PokeMatrix(path->GetLastNode()->GetMatrix());
      renderedSomething += prop->RenderOverlay(ren);
      prop->PokeMatrix(NULL);
      }
    }

  return renderedSomething;
}

void vtkPropAssembly::ReleaseGraphicsResources(vtkWindow *renWin)
{
  vtkProp *part;

  vtkProp::ReleaseGraphicsResources(renWin);

  // broadcast the message down the Parts
  for ( this->Parts->InitTraversal(); (part=this->Parts->GetNextProp()); )
    {
    part->ReleaseGraphicsResources(renWin);
    }
}

// Get the bounds for the assembly as (Xmin,Xmax,Ymin,Ymax,Zmin,Zmax).
float *vtkPropAssembly::GetBounds()
{
  vtkProp *part;
  int i, n;
  float *bounds, bbox[24];
  int partVisible=0;

  this->Bounds[0] = this->Bounds[2] = this->Bounds[4] = VTK_LARGE_FLOAT;
  this->Bounds[1] = this->Bounds[3] = this->Bounds[5] = -VTK_LARGE_FLOAT;

  for ( this->Parts->InitTraversal(); (part=this->Parts->GetNextProp()); )
    {
    if ( part->GetVisibility() )
      {
      bounds = part->GetBounds();

      if ( bounds != NULL )
        {
        //  For the purposes of GetBounds, an object is visisble only if
        //  its visibility is on and it has visible parts.
        partVisible = 1;

        // fill out vertices of a bounding box
        bbox[ 0] = bounds[1]; bbox[ 1] = bounds[3]; bbox[ 2] = bounds[5];
        bbox[ 3] = bounds[1]; bbox[ 4] = bounds[2]; bbox[ 5] = bounds[5];
        bbox[ 6] = bounds[0]; bbox[ 7] = bounds[2]; bbox[ 8] = bounds[5];
        bbox[ 9] = bounds[0]; bbox[10] = bounds[3]; bbox[11] = bounds[5];
        bbox[12] = bounds[1]; bbox[13] = bounds[3]; bbox[14] = bounds[4];
        bbox[15] = bounds[1]; bbox[16] = bounds[2]; bbox[17] = bounds[4];
        bbox[18] = bounds[0]; bbox[19] = bounds[2]; bbox[20] = bounds[4];
        bbox[21] = bounds[0]; bbox[22] = bounds[3]; bbox[23] = bounds[4];

        for (i = 0; i < 8; i++)
          {
          for (n = 0; n < 3; n++)
            {
            if (bbox[i*3+n] < this->Bounds[n*2])
              {
              this->Bounds[n*2] = bbox[i*3+n];
              }
            if (bbox[i*3+n] > this->Bounds[n*2+1])
              {
              this->Bounds[n*2+1] = bbox[i*3+n];
              }
            }
          }//for each point of box
        }//if bounds
      }//for each part
    }//for each part

  if ( ! partVisible )
    {
    return NULL;
    }
  else
    {
    return this->Bounds;
    }
}

unsigned long int vtkPropAssembly::GetMTime()
{
  unsigned long mTime=this->vtkProp::GetMTime();
  unsigned long time;
  vtkProp *part;

  for (this->Parts->InitTraversal(); (part=this->Parts->GetNextProp()); )
    {
    time = part->GetMTime();
    mTime = ( time > mTime ? time : mTime );
    }

  return mTime;
}

// Shallow copy another vtkPropAssembly.
void vtkPropAssembly::ShallowCopy(vtkProp *prop)
{
  vtkPropAssembly *propAssembly = vtkPropAssembly::SafeDownCast(prop);
  if ( propAssembly != NULL )
    {
    this->Parts->RemoveAllItems();
    propAssembly->Parts->InitTraversal();
    for (int i=0; i<0; i++)
      {
      this->AddPart(propAssembly->Parts->GetNextProp());
      }
    }

  this->vtkProp::ShallowCopy(prop);
}

void vtkPropAssembly::InitPathTraversal()
{
  this->UpdatePaths();
  this->Paths->InitTraversal();
}

vtkAssemblyPath *vtkPropAssembly::GetNextPath()
{
  return this->Paths->GetNextItem();
}

int vtkPropAssembly::GetNumberOfPaths()
{
  this->UpdatePaths();
  return this->Paths->GetNumberOfItems();
}

// Build the assembly paths if necessary.
void vtkPropAssembly::UpdatePaths()
{
  if ( this->GetMTime() > this->PathTime )
    {
    if ( this->Paths != NULL )
      {
      this->Paths->Delete();
      this->Paths = NULL;
      }

    // Create the list to hold all the paths
    this->Paths = vtkAssemblyPaths::New();
    vtkAssemblyPath *path = vtkAssemblyPath::New();

    //add ourselves to the path to start things off
    path->AddNode(this,NULL);

    vtkProp *prop;
    // Add nodes as we proceed down the hierarchy
    for ( this->Parts->InitTraversal();
          (prop = this->Parts->GetNextProp()); )
      {
      // add a matrix, if any
      path->AddNode(prop,prop->GetMatrix());

      // dive into the hierarchy
      prop->BuildPaths(this->Paths,path);

      // when returned, pop the last node off of the
      // current path
      path->DeleteLastNode();
      }

    path->Delete();
    this->PathTime.Modified();
    }
}

void vtkPropAssembly::BuildPaths(vtkAssemblyPaths *paths,
                                 vtkAssemblyPath *path)
{
  vtkProp *prop;

  for ( this->Parts->InitTraversal();
        (prop = this->Parts->GetNextProp()); )
    {
    path->AddNode(prop,NULL);

    // dive into the hierarchy
    prop->BuildPaths(paths,path);

    // when returned, pop the last node off of the
    // current path
    path->DeleteLastNode();
    }
}

void vtkPropAssembly::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkProp::PrintSelf(os,indent);

  os << indent << "There are: " << this->Parts->GetNumberOfItems()
     << " parts in this assembly\n";
}
<commit_msg>ERR:Check for NULL and return as appropriate<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkPropAssembly.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

 * Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

 * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
   of any contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

 * Modified source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.

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 AUTHORS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=========================================================================*/
#include "vtkPropAssembly.h"
#include "vtkViewport.h"
#include "vtkAssemblyNode.h"
#include "vtkObjectFactory.h"

//-----------------------------------------------------------------------------
vtkPropAssembly* vtkPropAssembly::New()
{
  // First try to create the object from the vtkObjectFactory
  vtkObject* ret = vtkObjectFactory::CreateInstance("vtkPropAssembly");
  if(ret)
    {
    return (vtkPropAssembly*)ret;
    }
  // If the factory was unable to create the object, then create it here.
  return new vtkPropAssembly;
}

// Construct object with no children.
vtkPropAssembly::vtkPropAssembly()
{
  this->Parts = vtkPropCollection::New();
  this->Bounds[0] = this->Bounds[2] = this->Bounds[4] = VTK_LARGE_FLOAT;
  this->Bounds[1] = this->Bounds[3] = this->Bounds[5] = -VTK_LARGE_FLOAT;
}

vtkPropAssembly::~vtkPropAssembly()
{
  this->Parts->Delete();
  this->Parts = NULL;
}

// Add a part to the list of Parts.
void vtkPropAssembly::AddPart(vtkProp *prop)
{
  if ( ! this->Parts->IsItemPresent(prop) )
    {
    this->Parts->AddItem(prop);
    this->Modified();
    }
}

// Remove a part from the list of parts,
void vtkPropAssembly::RemovePart(vtkProp *prop)
{
  if ( this->Parts->IsItemPresent(prop) )
    {
    this->Parts->RemoveItem(prop);
    this->Modified();
    }
}

// Get the list of parts for this prop assembly.
vtkPropCollection *vtkPropAssembly::GetParts()
{
  return this->Parts;
}

// Render this assembly and all of its Parts. The rendering process is recursive.
int vtkPropAssembly::RenderTranslucentGeometry(vtkViewport *ren)
{
  vtkProp *prop;
  vtkAssemblyPath *path;
  float fraction;
  int renderedSomething=0;

  fraction = this->AllocatedRenderTime /
             (float)this->Parts->GetNumberOfItems();

  // render the Paths
  for ( this->Paths->InitTraversal(); (path = this->Paths->GetNextItem()); )
    {
    prop = path->GetLastNode()->GetProp();
    if ( prop->GetVisibility() )
      {
      prop->SetAllocatedRenderTime(fraction, ren);
      prop->PokeMatrix(path->GetLastNode()->GetMatrix());
      renderedSomething += prop->RenderTranslucentGeometry(ren);
      prop->PokeMatrix(NULL);
      }
    }

  return renderedSomething;
}

// Render this assembly and all its parts. The rendering process is recursive.
int vtkPropAssembly::RenderOpaqueGeometry(vtkViewport *ren)
{
  vtkProp *prop;
  vtkAssemblyPath *path;
  float fraction;
  int   renderedSomething=0;

  // Make sure the paths are up-to-date
  this->UpdatePaths();

  fraction = this->AllocatedRenderTime /
             (float)this->Parts->GetNumberOfItems();

  // render the Paths
  for ( this->Paths->InitTraversal(); (path = this->Paths->GetNextItem()); )
    {
    prop = path->GetLastNode()->GetProp();
    if ( prop->GetVisibility() )
      {
      prop->SetAllocatedRenderTime(fraction, ren);
      prop->PokeMatrix(path->GetLastNode()->GetMatrix());
      renderedSomething += prop->RenderOpaqueGeometry(ren);
      prop->PokeMatrix(NULL);
      }
    }

  return renderedSomething;
}

// Render this assembly and all its parts. The rendering process is recursive.
int vtkPropAssembly::RenderOverlay(vtkViewport *ren)
{
  vtkProp *prop;
  vtkAssemblyPath *path;
  float fraction;
  int   renderedSomething=0;

  // Make sure the paths are up-to-date
  this->UpdatePaths();

  fraction = this->AllocatedRenderTime /
             (float)this->Parts->GetNumberOfItems();

  for ( this->Paths->InitTraversal(); (path = this->Paths->GetNextItem()); )
    {
    prop = path->GetLastNode()->GetProp();
    if ( prop->GetVisibility() )
      {
      prop->SetAllocatedRenderTime(fraction, ren);
      prop->PokeMatrix(path->GetLastNode()->GetMatrix());
      renderedSomething += prop->RenderOverlay(ren);
      prop->PokeMatrix(NULL);
      }
    }

  return renderedSomething;
}

void vtkPropAssembly::ReleaseGraphicsResources(vtkWindow *renWin)
{
  vtkProp *part;

  vtkProp::ReleaseGraphicsResources(renWin);

  // broadcast the message down the Parts
  for ( this->Parts->InitTraversal(); (part=this->Parts->GetNextProp()); )
    {
    part->ReleaseGraphicsResources(renWin);
    }
}

// Get the bounds for the assembly as (Xmin,Xmax,Ymin,Ymax,Zmin,Zmax).
float *vtkPropAssembly::GetBounds()
{
  vtkProp *part;
  int i, n;
  float *bounds, bbox[24];
  int partVisible=0;

  this->Bounds[0] = this->Bounds[2] = this->Bounds[4] = VTK_LARGE_FLOAT;
  this->Bounds[1] = this->Bounds[3] = this->Bounds[5] = -VTK_LARGE_FLOAT;

  for ( this->Parts->InitTraversal(); (part=this->Parts->GetNextProp()); )
    {
    if ( part->GetVisibility() )
      {
      bounds = part->GetBounds();

      if ( bounds != NULL )
        {
        //  For the purposes of GetBounds, an object is visisble only if
        //  its visibility is on and it has visible parts.
        partVisible = 1;

        // fill out vertices of a bounding box
        bbox[ 0] = bounds[1]; bbox[ 1] = bounds[3]; bbox[ 2] = bounds[5];
        bbox[ 3] = bounds[1]; bbox[ 4] = bounds[2]; bbox[ 5] = bounds[5];
        bbox[ 6] = bounds[0]; bbox[ 7] = bounds[2]; bbox[ 8] = bounds[5];
        bbox[ 9] = bounds[0]; bbox[10] = bounds[3]; bbox[11] = bounds[5];
        bbox[12] = bounds[1]; bbox[13] = bounds[3]; bbox[14] = bounds[4];
        bbox[15] = bounds[1]; bbox[16] = bounds[2]; bbox[17] = bounds[4];
        bbox[18] = bounds[0]; bbox[19] = bounds[2]; bbox[20] = bounds[4];
        bbox[21] = bounds[0]; bbox[22] = bounds[3]; bbox[23] = bounds[4];

        for (i = 0; i < 8; i++)
          {
          for (n = 0; n < 3; n++)
            {
            if (bbox[i*3+n] < this->Bounds[n*2])
              {
              this->Bounds[n*2] = bbox[i*3+n];
              }
            if (bbox[i*3+n] > this->Bounds[n*2+1])
              {
              this->Bounds[n*2+1] = bbox[i*3+n];
              }
            }
          }//for each point of box
        }//if bounds
      }//for each part
    }//for each part

  if ( ! partVisible )
    {
    return NULL;
    }
  else
    {
    return this->Bounds;
    }
}

unsigned long int vtkPropAssembly::GetMTime()
{
  unsigned long mTime=this->vtkProp::GetMTime();
  unsigned long time;
  vtkProp *part;

  for (this->Parts->InitTraversal(); (part=this->Parts->GetNextProp()); )
    {
    time = part->GetMTime();
    mTime = ( time > mTime ? time : mTime );
    }

  return mTime;
}

// Shallow copy another vtkPropAssembly.
void vtkPropAssembly::ShallowCopy(vtkProp *prop)
{
  vtkPropAssembly *propAssembly = vtkPropAssembly::SafeDownCast(prop);
  if ( propAssembly != NULL )
    {
    this->Parts->RemoveAllItems();
    propAssembly->Parts->InitTraversal();
    for (int i=0; i<0; i++)
      {
      this->AddPart(propAssembly->Parts->GetNextProp());
      }
    }

  this->vtkProp::ShallowCopy(prop);
}

void vtkPropAssembly::InitPathTraversal()
{
  this->UpdatePaths();
  this->Paths->InitTraversal();
}

vtkAssemblyPath *vtkPropAssembly::GetNextPath()
{
  if ( this->Paths )
    {
    return this->Paths->GetNextItem();
    }
  return NULL;
}

int vtkPropAssembly::GetNumberOfPaths()
{
  this->UpdatePaths();
  return this->Paths->GetNumberOfItems();
}

// Build the assembly paths if necessary.
void vtkPropAssembly::UpdatePaths()
{
  if ( this->GetMTime() > this->PathTime )
    {
    if ( this->Paths != NULL )
      {
      this->Paths->Delete();
      this->Paths = NULL;
      }

    // Create the list to hold all the paths
    this->Paths = vtkAssemblyPaths::New();
    vtkAssemblyPath *path = vtkAssemblyPath::New();

    //add ourselves to the path to start things off
    path->AddNode(this,NULL);

    vtkProp *prop;
    // Add nodes as we proceed down the hierarchy
    for ( this->Parts->InitTraversal();
          (prop = this->Parts->GetNextProp()); )
      {
      // add a matrix, if any
      path->AddNode(prop,prop->GetMatrix());

      // dive into the hierarchy
      prop->BuildPaths(this->Paths,path);

      // when returned, pop the last node off of the
      // current path
      path->DeleteLastNode();
      }

    path->Delete();
    this->PathTime.Modified();
    }
}

void vtkPropAssembly::BuildPaths(vtkAssemblyPaths *paths,
                                 vtkAssemblyPath *path)
{
  vtkProp *prop;

  for ( this->Parts->InitTraversal();
        (prop = this->Parts->GetNextProp()); )
    {
    path->AddNode(prop,NULL);

    // dive into the hierarchy
    prop->BuildPaths(paths,path);

    // when returned, pop the last node off of the
    // current path
    path->DeleteLastNode();
    }
}

void vtkPropAssembly::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkProp::PrintSelf(os,indent);

  os << indent << "There are: " << this->Parts->GetNumberOfItems()
     << " parts in this assembly\n";
}
<|endoftext|>


<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef HTTP_MIME_TYPES_HPP
#define HTTP_MIME_TYPES_HPP

#include <string>
#include <unordered_map>

namespace http {
//------------------------------------------------
using Extension       = std::string;
using Mime_Type       = std::string;
using Mime_Type_Table = std::unordered_map<Extension, Mime_Type>;
//------------------------------------------------
const Mime_Type_Table mime_types {
  //< Text mimes
  {"html", "text/html"},
  {"htm" , "text/html"},
  {"js"  , "text/javascript"},
  {"txt" , "text/plain"},
  {"css" , "text/css"},
  {"xml" , "text/xml"},

  //< Image mimes
  {"bmp" , "image/bmp"},
  {"gif" , "image/gif"},
  {"png" , "image/png"},
  {"jpg" , "image/jpeg"},
  {"jpeg", "image/jpeg"},
  {"ico" , "image/x-icon"},
  {"svg" , "image/svg+xml"},

  //< Audio mimes
  {"mid" , "audio/midi"},
  {"midi", "audio/midi"},
  {"kar" , "audio/midi"},
  {"mp3" , "audio/mpeg"},
  {"ogg" , "audio/ogg"},
  {"m4a" , "audio/x-m4a"},
  {"ra"  , "audio/x-realaudio"},

  //< Video mimes
  {"3gp" , "video/3gpp"},
  {"3gpp", "video/3gpp"},
  {"ts"  , "video/mp2t"},
  {"mp4" , "video/mp4"},
  {"mpg" , "video/mpeg"},
  {"mpeg", "video/mpeg"},
  {"mov" , "video/quicktime"},
  {"webm", "video/webm"},
  {"flv" , "video/x-flv"},
  {"m4v" , "video/x-m4v"},
  {"mng" , "video/x-mng"},
  {"asf" , "video/x-ms-asf"},
  {"asx" , "video/x-ms-asf"},
  {"wmv" , "video/x-ms-wmv"},
  {"avi" , "video/x-msvideo"},

  //< Application mimes
  {"zip"  , "application/zip"},
  {"7z"   , "application/x-7z-compressed"},
  {"jar"  , "application/java-archive"},
  {"war"  , "application/java-archive"},
  {"ear"  , "application/java-archive"},
  {"json" , "application/json"},
  {"pdf"  , "application/pdf"},
  {"xhtml", "application/xhtml+xml"},
  {"xspf" , "application/xspf+xml"},
  {"der" , "application/x-x509-ca-cert"},
  {"pem" , "application/x-x509-ca-cert"},
  {"crt" , "application/x-x509-ca-cert"},
  {"bin" , "application/octet-stream"},
  {"exe" , "application/octet-stream"},
  {"dll" , "application/octet-stream"},
  {"deb" , "application/octet-stream"},
  {"dmg" , "application/octet-stream"},
  {"iso" , "application/octet-stream"},
  {"img" , "application/octet-stream"},
  {"msi" , "application/octet-stream"},
  {"msp" , "application/octet-stream"},
  {"msm" , "application/octet-stream"}
}; //< mime_types

inline const Mime_Type& extension_to_type(const Extension& extension) noexcept {
  auto iter = mime_types.find(extension);
  //------------------------------------------------
  return (iter not_eq mime_types.end())
          ? iter->second
          : const_cast<Mime_Type_Table&>(mime_types)["txt"];
}

} //< namespace http

#endif //< HTTP_MIME_TYPES_HPP
<commit_msg>mime_types.hpp: Changed default mime type from txt to bin<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef HTTP_MIME_TYPES_HPP
#define HTTP_MIME_TYPES_HPP

#include <string>
#include <unordered_map>

namespace http {
//------------------------------------------------
using Extension       = std::string;
using Mime_type       = std::string;
using Mime_type_table = std::unordered_map<Extension, Mime_type>;
//------------------------------------------------
const Mime_type_table mime_types {
  //< Text mimes
  {"html", "text/html"},
  {"htm" , "text/html"},
  {"js"  , "text/javascript"},
  {"txt" , "text/plain"},
  {"css" , "text/css"},
  {"xml" , "text/xml"},

  //< Image mimes
  {"bmp" , "image/bmp"},
  {"gif" , "image/gif"},
  {"png" , "image/png"},
  {"jpg" , "image/jpeg"},
  {"jpeg", "image/jpeg"},
  {"ico" , "image/x-icon"},
  {"svg" , "image/svg+xml"},

  //< Audio mimes
  {"mid" , "audio/midi"},
  {"midi", "audio/midi"},
  {"kar" , "audio/midi"},
  {"mp3" , "audio/mpeg"},
  {"ogg" , "audio/ogg"},
  {"m4a" , "audio/x-m4a"},
  {"ra"  , "audio/x-realaudio"},

  //< Video mimes
  {"3gp" , "video/3gpp"},
  {"3gpp", "video/3gpp"},
  {"ts"  , "video/mp2t"},
  {"mp4" , "video/mp4"},
  {"mpg" , "video/mpeg"},
  {"mpeg", "video/mpeg"},
  {"mov" , "video/quicktime"},
  {"webm", "video/webm"},
  {"flv" , "video/x-flv"},
  {"m4v" , "video/x-m4v"},
  {"mng" , "video/x-mng"},
  {"asf" , "video/x-ms-asf"},
  {"asx" , "video/x-ms-asf"},
  {"wmv" , "video/x-ms-wmv"},
  {"avi" , "video/x-msvideo"},

  //< Application mimes
  {"zip"  , "application/zip"},
  {"7z"   , "application/x-7z-compressed"},
  {"jar"  , "application/java-archive"},
  {"war"  , "application/java-archive"},
  {"ear"  , "application/java-archive"},
  {"json" , "application/json"},
  {"pdf"  , "application/pdf"},
  {"xhtml", "application/xhtml+xml"},
  {"xspf" , "application/xspf+xml"},
  {"der" , "application/x-x509-ca-cert"},
  {"pem" , "application/x-x509-ca-cert"},
  {"crt" , "application/x-x509-ca-cert"},
  {"bin" , "application/octet-stream"},
  {"exe" , "application/octet-stream"},
  {"dll" , "application/octet-stream"},
  {"deb" , "application/octet-stream"},
  {"dmg" , "application/octet-stream"},
  {"iso" , "application/octet-stream"},
  {"img" , "application/octet-stream"},
  {"msi" , "application/octet-stream"},
  {"msp" , "application/octet-stream"},
  {"msm" , "application/octet-stream"}
}; //< mime_types

inline const Mime_type& extension_to_type(const Extension& extension) noexcept {
  auto it = mime_types.find(extension);
  //------------------------------------------------
  return (it not_eq mime_types.end())
          ? it->second
          : const_cast<Mime_type_table&>(mime_types)["bin"];
}

} //< namespace http

#endif //< HTTP_MIME_TYPES_HPP
<|endoftext|>