<commit_before>/*
  Copyright 2008-2009 Larry Gritz and the other authors and contributors.
  All Rights Reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are
  met:
  * Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.
  * Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.
  * Neither the name of the software's owners 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.

  (This is the Modified BSD License)
*/

#include <cstdlib>

#include "fits_pvt.h"

// Obligatory material to make this a recognizeable imageio plugin
extern "C" {
    DLLEXPORT int fits_imageio_version = OPENIMAGEIO_PLUGIN_VERSION;
    DLLEXPORT ImageInput *fits_input_imageio_create () {
        return new FitsInput;
    }
    DLLEXPORT const char *fits_input_extensions[] = {
        "fits", NULL
    };
}

bool
FitsInput::open (const std::string &name, ImageSpec &spec)
{
    // saving 'name' for later use
    m_filename = name;

    // checking if the file exists and can be opened in READ mode
    m_fd = fopen (m_filename.c_str (), "rb");
    if (!m_fd) {
        error ("Could not open file \"%s\"", m_filename.c_str ());
        return false;
    }

    // checking if the file is FITS file
    char magic[6] = {0};
    fread(magic, 1, 6, m_fd);
    if(strncmp (magic, "SIMPLE", 6)) {
        error ("%s isn't a FITS file", m_filename.c_str ());
        close ();
        return false;
    }
    // moving back to the start of the file
    fseek (m_fd, 0, SEEK_SET);

    subimage_search ();

    set_spec_info ();

    spec = m_spec;
    return true;
};

bool
FitsInput::read_native_scanline (int y, int z, void *data)
{
    // we return true just to support 0x0 images
    if (!m_naxes)
        return true;

    std::vector<unsigned char> data_tmp (m_spec.scanline_bytes ());
    long scanline_off = (m_spec.height - y) * m_spec.scanline_bytes ();
    fseek (m_fd, scanline_off, SEEK_CUR);
    fread (&data_tmp[0], 1, m_spec.scanline_bytes(), m_fd);

    // in FITS image data is stored in big-endian so we have to switch to
    // little-endian on little-endian machines
    if (littleendian ()) {
        if (m_spec.format == TypeDesc::USHORT)
            swap_endian ((unsigned short*)&data_tmp[0],
                         data_tmp.size () / sizeof (unsigned short));
        else if (m_spec.format == TypeDesc::UINT)
            swap_endian ((unsigned int*)&data_tmp[0],
                         data_tmp.size () / sizeof (unsigned int));
        else if (m_spec.format == TypeDesc::FLOAT)
            swap_endian ((float*)&data_tmp[0],
                         data_tmp.size () / sizeof (float));
        else if (m_spec.format == TypeDesc::DOUBLE)
            swap_endian ((double*)&data_tmp[0],
                         data_tmp.size () / sizeof (double));
    }

    memcpy (data, &data_tmp[0], data_tmp.size ());

    // after reading scanline we set file pointer to the start of image data
    fsetpos (m_fd, &m_filepos);
    return true;
};

bool
FitsInput::seek_subimage (int index, ImageSpec &newspec)
{
    if (index < 0 || index >= (int)m_subimages.size ())
        return false;

    if (index == m_cur_subimage) {
        newspec = m_spec;
        return true;
    }

    // setting file pointer to the beginning of IMAGE extension
    m_cur_subimage = index;
    fseek (m_fd, m_subimages[m_cur_subimage].offset, SEEK_SET);

    set_spec_info ();

    newspec = m_spec;
    return true;
}

void
FitsInput::set_spec_info ()
{
    keys.clear ();
    // FITS spec doesn't say anything about color space or
    // number of channels, so we read all images as if they
    // all were one-channel images
    m_spec = ImageSpec(0, 0, 1, TypeDesc::UNKNOWN);

    // reading info about current subimage
    read_fits_header ();

    // we don't deal with one dimension images
    // it's some kind of spectral data
    if (! m_spec.width || ! m_spec.height) {
        m_spec.width = m_spec.full_width = 0;
        m_spec.height = m_spec.full_height = 0;
    }

    // now we can get the current position in the file
    // this is the start of the image data
    // we will need it in the read_native_scanline method
    fgetpos(m_fd, &m_filepos);

    if (m_bitpix == 8)
        m_spec.set_format (TypeDesc::UCHAR);
    else if (m_bitpix == 16)
        m_spec.set_format (TypeDesc::USHORT);
    else if (m_bitpix == 32)
        m_spec.set_format (TypeDesc::UINT);
    else if (m_bitpix == -32)
        m_spec.set_format (TypeDesc::FLOAT);
    else if (m_bitpix == -64)
        m_spec.set_format (TypeDesc::DOUBLE);
}

bool
FitsInput::close (void)
{
    if (m_fd)
        fclose (m_fd);
    init ();
    return true;
}

void
FitsInput::read_fits_header (void)
{
    std::string fits_header (HEADER_SIZE, 0);

    // we read whole header at once
    fread (&fits_header[0], 1, HEADER_SIZE, m_fd);

    for (int i = 0; i < CARDS_PER_HEADER; ++i) {
        std::string card (CARD_SIZE, 0);
        // reading card number i
        memcpy (&card[0], &fits_header[i*CARD_SIZE], CARD_SIZE);

        std::string keyname, value;
        fits_pvt::unpack_card (card, keyname, value);

        // END means that this is end of the FITS header
        if (keyname == "END")
            return;

        if (keyname == "SIMPLE" || keyname == "XTENSION")
            continue;

        // setting up some important fields
        // m_bitpix - format of the data (eg. bpp)
        // m_naxes - number of axes
        // width, height and depth of the image
        if (keyname == "BITPIX") {
            m_bitpix = atoi (&card[10]);
            continue;
        }
        if (keyname == "NAXIS") {
            m_naxes = atoi (&card[10]);
            continue;
        }
        if (keyname == "NAXIS1") {
            m_spec.width = atoi (&card[10]);
            m_spec.full_width = m_spec.width;
            continue;
        }
        if (keyname == "NAXIS2") {
            m_spec.height = atoi (&card[10]);
            m_spec.full_height = m_spec.height;
            continue;
        }
        // ignoring other axis
        if (keyname.substr (0,5) == "NAXIS") {
            continue;
        }

        if (keyname == "ORIENTAT") {
            add_to_spec ("Orientation", value);
            continue;
        }

        if (keyname == "DATE") {
            add_to_spec ("DateTime", convert_date (value));
            continue;
        }

        // Some keywords can occure more than one time: COMMENT, HISTORY,
        // HIERARCH. We can't store more than one key with the same name in
        // ImageSpec. The workaround for this is to append a num to the keyname
        // that occurs more then one time
        if (keyname == "COMMENT" || keyname == "HISTORY"
            || keyname == "HIERARCH")
            keyname += Strutil::format ("%d", keys[keyname]++);

        add_to_spec (pystring::capitalize(keyname), value);
    }
    // if we didn't found END keyword in current header, we read next one
    read_fits_header ();
}

void
FitsInput::add_to_spec (const std::string &keyname, const std::string &value)
{
    // we don't add empty keys (or keys with empty values) to ImageSpec
    if (!keyname.size() || !value.size ())
        return;

    // COMMENT, HISTORY, HIERARCH keywords we save AS-IS
    if (keyname.substr (0, 7) == "Comment" || keyname.substr (0, 7) == "History"
        ||keyname.substr (0, 8) == "Hierarch" || keyname == "DateTime") {
        m_spec.attribute (keyname, value);
        return;
    }

    // converting string to float or integer
    bool isNumSign = (value[0] == '+' || value[0] == '-' || value[0] == '.');
    if (isdigit (value[0]) || isNumSign) {
        float val = atof (value.c_str ());
        if (val == (int)val)
            m_spec.attribute (keyname, (int)val);
        else
            m_spec.attribute (keyname, val);
    }
    else
        m_spec.attribute (keyname, value);
}

void
FitsInput::subimage_search ()
{
    // saving position of the file, just for safe)
    fpos_t fpos;
    fgetpos (m_fd, &fpos);

    // starting reading headers from the beginning of the file
    fseek (m_fd, 0, SEEK_SET);

    // we search for subimages by reading whole header and checking if it
    // starts by "SIMPLE" keyword (primary header is always image header)
    // or by "XTENSION= 'IMAGE   '" (it is image extensions)
    std::string hdu (HEADER_SIZE, 0);
    size_t offset = 0;
    while (fread (&hdu[0], 1, HEADER_SIZE, m_fd) == HEADER_SIZE) {
        if (!strncmp (&hdu[0], "SIMPLE", 6) ||
            !strncmp (&hdu[0], "XTENSION= 'IMAGE   '", 20)) {
            fits_pvt::Subimage newSub;
            newSub.number = m_subimages.size ();
            newSub.offset = offset;
            m_subimages.push_back (newSub);
        }
        offset += HEADER_SIZE;
    }
    fsetpos (m_fd, &fpos);
}

std::string
FitsInput::convert_date (const std::string &date)
{
    std::string ndate;
    if (date[4] == '-') {
        // YYYY-MM-DDThh:mm:ss convention is used since 1 January 2000
        ndate = Strutil::format ("%04u:%02u:%02u", atoi(&date[0]),
                                 atoi(&date[5]), atoi(&date[8]));
        if (date.size () >= 11 && date[10] == 'T')
            ndate += Strutil::format ("%02u:%02u:%02u", atoi (&date[11]),
                                      atoi (&date[14]), atoi (&date[17]));
        return ndate;
    }

    if (date[2] == '/') {
        // DD/MM/YY convention was used before 1 January 2000
        ndate = Strutil::format ("19%02u:%02u:%02u 00:00:00", atoi(&date[6]),
                                 atoi(&date[3]), atoi(&date[0]));
        return ndate;
    }
    // unrecognized format
    return date;
}
<commit_msg>FITS fix: incorrectly-formatted date.<commit_after>/*
  Copyright 2008-2009 Larry Gritz and the other authors and contributors.
  All Rights Reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are
  met:
  * Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.
  * Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.
  * Neither the name of the software's owners 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.

  (This is the Modified BSD License)
*/

#include <cstdlib>

#include "fits_pvt.h"

// Obligatory material to make this a recognizeable imageio plugin
extern "C" {
    DLLEXPORT int fits_imageio_version = OPENIMAGEIO_PLUGIN_VERSION;
    DLLEXPORT ImageInput *fits_input_imageio_create () {
        return new FitsInput;
    }
    DLLEXPORT const char *fits_input_extensions[] = {
        "fits", NULL
    };
}

bool
FitsInput::open (const std::string &name, ImageSpec &spec)
{
    // saving 'name' for later use
    m_filename = name;

    // checking if the file exists and can be opened in READ mode
    m_fd = fopen (m_filename.c_str (), "rb");
    if (!m_fd) {
        error ("Could not open file \"%s\"", m_filename.c_str ());
        return false;
    }

    // checking if the file is FITS file
    char magic[6] = {0};
    fread(magic, 1, 6, m_fd);
    if(strncmp (magic, "SIMPLE", 6)) {
        error ("%s isn't a FITS file", m_filename.c_str ());
        close ();
        return false;
    }
    // moving back to the start of the file
    fseek (m_fd, 0, SEEK_SET);

    subimage_search ();

    set_spec_info ();

    spec = m_spec;
    return true;
};

bool
FitsInput::read_native_scanline (int y, int z, void *data)
{
    // we return true just to support 0x0 images
    if (!m_naxes)
        return true;

    std::vector<unsigned char> data_tmp (m_spec.scanline_bytes ());
    long scanline_off = (m_spec.height - y) * m_spec.scanline_bytes ();
    fseek (m_fd, scanline_off, SEEK_CUR);
    fread (&data_tmp[0], 1, m_spec.scanline_bytes(), m_fd);

    // in FITS image data is stored in big-endian so we have to switch to
    // little-endian on little-endian machines
    if (littleendian ()) {
        if (m_spec.format == TypeDesc::USHORT)
            swap_endian ((unsigned short*)&data_tmp[0],
                         data_tmp.size () / sizeof (unsigned short));
        else if (m_spec.format == TypeDesc::UINT)
            swap_endian ((unsigned int*)&data_tmp[0],
                         data_tmp.size () / sizeof (unsigned int));
        else if (m_spec.format == TypeDesc::FLOAT)
            swap_endian ((float*)&data_tmp[0],
                         data_tmp.size () / sizeof (float));
        else if (m_spec.format == TypeDesc::DOUBLE)
            swap_endian ((double*)&data_tmp[0],
                         data_tmp.size () / sizeof (double));
    }

    memcpy (data, &data_tmp[0], data_tmp.size ());

    // after reading scanline we set file pointer to the start of image data
    fsetpos (m_fd, &m_filepos);
    return true;
};

bool
FitsInput::seek_subimage (int index, ImageSpec &newspec)
{
    if (index < 0 || index >= (int)m_subimages.size ())
        return false;

    if (index == m_cur_subimage) {
        newspec = m_spec;
        return true;
    }

    // setting file pointer to the beginning of IMAGE extension
    m_cur_subimage = index;
    fseek (m_fd, m_subimages[m_cur_subimage].offset, SEEK_SET);

    set_spec_info ();

    newspec = m_spec;
    return true;
}

void
FitsInput::set_spec_info ()
{
    keys.clear ();
    // FITS spec doesn't say anything about color space or
    // number of channels, so we read all images as if they
    // all were one-channel images
    m_spec = ImageSpec(0, 0, 1, TypeDesc::UNKNOWN);

    // reading info about current subimage
    read_fits_header ();

    // we don't deal with one dimension images
    // it's some kind of spectral data
    if (! m_spec.width || ! m_spec.height) {
        m_spec.width = m_spec.full_width = 0;
        m_spec.height = m_spec.full_height = 0;
    }

    // now we can get the current position in the file
    // this is the start of the image data
    // we will need it in the read_native_scanline method
    fgetpos(m_fd, &m_filepos);

    if (m_bitpix == 8)
        m_spec.set_format (TypeDesc::UCHAR);
    else if (m_bitpix == 16)
        m_spec.set_format (TypeDesc::USHORT);
    else if (m_bitpix == 32)
        m_spec.set_format (TypeDesc::UINT);
    else if (m_bitpix == -32)
        m_spec.set_format (TypeDesc::FLOAT);
    else if (m_bitpix == -64)
        m_spec.set_format (TypeDesc::DOUBLE);
}

bool
FitsInput::close (void)
{
    if (m_fd)
        fclose (m_fd);
    init ();
    return true;
}

void
FitsInput::read_fits_header (void)
{
    std::string fits_header (HEADER_SIZE, 0);

    // we read whole header at once
    fread (&fits_header[0], 1, HEADER_SIZE, m_fd);

    for (int i = 0; i < CARDS_PER_HEADER; ++i) {
        std::string card (CARD_SIZE, 0);
        // reading card number i
        memcpy (&card[0], &fits_header[i*CARD_SIZE], CARD_SIZE);

        std::string keyname, value;
        fits_pvt::unpack_card (card, keyname, value);

        // END means that this is end of the FITS header
        if (keyname == "END")
            return;

        if (keyname == "SIMPLE" || keyname == "XTENSION")
            continue;

        // setting up some important fields
        // m_bitpix - format of the data (eg. bpp)
        // m_naxes - number of axes
        // width, height and depth of the image
        if (keyname == "BITPIX") {
            m_bitpix = atoi (&card[10]);
            continue;
        }
        if (keyname == "NAXIS") {
            m_naxes = atoi (&card[10]);
            continue;
        }
        if (keyname == "NAXIS1") {
            m_spec.width = atoi (&card[10]);
            m_spec.full_width = m_spec.width;
            continue;
        }
        if (keyname == "NAXIS2") {
            m_spec.height = atoi (&card[10]);
            m_spec.full_height = m_spec.height;
            continue;
        }
        // ignoring other axis
        if (keyname.substr (0,5) == "NAXIS") {
            continue;
        }

        if (keyname == "ORIENTAT") {
            add_to_spec ("Orientation", value);
            continue;
        }

        if (keyname == "DATE") {
            add_to_spec ("DateTime", convert_date (value));
            continue;
        }

        // Some keywords can occure more than one time: COMMENT, HISTORY,
        // HIERARCH. We can't store more than one key with the same name in
        // ImageSpec. The workaround for this is to append a num to the keyname
        // that occurs more then one time
        if (keyname == "COMMENT" || keyname == "HISTORY"
            || keyname == "HIERARCH")
            keyname += Strutil::format ("%d", keys[keyname]++);

        add_to_spec (pystring::capitalize(keyname), value);
    }
    // if we didn't found END keyword in current header, we read next one
    read_fits_header ();
}

void
FitsInput::add_to_spec (const std::string &keyname, const std::string &value)
{
    // we don't add empty keys (or keys with empty values) to ImageSpec
    if (!keyname.size() || !value.size ())
        return;

    // COMMENT, HISTORY, HIERARCH keywords we save AS-IS
    if (keyname.substr (0, 7) == "Comment" || keyname.substr (0, 7) == "History"
        ||keyname.substr (0, 8) == "Hierarch" || keyname == "DateTime") {
        m_spec.attribute (keyname, value);
        return;
    }

    // converting string to float or integer
    bool isNumSign = (value[0] == '+' || value[0] == '-' || value[0] == '.');
    if (isdigit (value[0]) || isNumSign) {
        float val = atof (value.c_str ());
        if (val == (int)val)
            m_spec.attribute (keyname, (int)val);
        else
            m_spec.attribute (keyname, val);
    }
    else
        m_spec.attribute (keyname, value);
}

void
FitsInput::subimage_search ()
{
    // saving position of the file, just for safe)
    fpos_t fpos;
    fgetpos (m_fd, &fpos);

    // starting reading headers from the beginning of the file
    fseek (m_fd, 0, SEEK_SET);

    // we search for subimages by reading whole header and checking if it
    // starts by "SIMPLE" keyword (primary header is always image header)
    // or by "XTENSION= 'IMAGE   '" (it is image extensions)
    std::string hdu (HEADER_SIZE, 0);
    size_t offset = 0;
    while (fread (&hdu[0], 1, HEADER_SIZE, m_fd) == HEADER_SIZE) {
        if (!strncmp (&hdu[0], "SIMPLE", 6) ||
            !strncmp (&hdu[0], "XTENSION= 'IMAGE   '", 20)) {
            fits_pvt::Subimage newSub;
            newSub.number = m_subimages.size ();
            newSub.offset = offset;
            m_subimages.push_back (newSub);
        }
        offset += HEADER_SIZE;
    }
    fsetpos (m_fd, &fpos);
}

std::string
FitsInput::convert_date (const std::string &date)
{
    std::string ndate;
    if (date[4] == '-') {
        // YYYY-MM-DDThh:mm:ss convention is used since 1 January 2000
        ndate = Strutil::format ("%04u:%02u:%02u", atoi(&date[0]),
                                 atoi(&date[5]), atoi(&date[8]));
        if (date.size () >= 11 && date[10] == 'T')
            ndate += Strutil::format (" %02u:%02u:%02u", atoi (&date[11]),
                                      atoi (&date[14]), atoi (&date[17]));
        return ndate;
    }

    if (date[2] == '/') {
        // DD/MM/YY convention was used before 1 January 2000
        ndate = Strutil::format ("19%02u:%02u:%02u 00:00:00", atoi(&date[6]),
                                 atoi(&date[3]), atoi(&date[0]));
        return ndate;
    }
    // unrecognized format
    return date;
}
<|endoftext|>


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

  nomlib - C++11 cross-platform game engine

Copyright (c) 2013, 2014 Jeffrey Carpenter <i8degrees@gmail.com>
All rights reserved.

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

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. 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.

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.

******************************************************************************/
#include "nomlib/graphics/sprite/Sprite.hpp"

namespace nom {

Sprite::Sprite ( void ) : state_ ( 0 ), scale_factor ( 1 )
{
NOM_LOG_TRACE ( NOM );
}

Sprite::~Sprite ( void )
{
NOM_LOG_TRACE ( NOM );
}

Sprite::Sprite ( int32 width, int32 height )  :
  Transformable { Coords ( 0, 0, width, height ) }, state_ ( 0 ),
  scale_factor ( 1 )

{
NOM_LOG_TRACE ( NOM );
}

Sprite& Sprite::operator = ( const Sprite& other )
{
  this->sprite_ = other.sprite_;
  this->set_position ( other.position().x, other.position().y );
  this->set_state ( other.state() );
  this->scale_factor = other.scale_factor;

  return *this;
}

SDL_TEXTURE::RawPtr Sprite::texture ( void ) const
{
  return this->sprite_.texture();
}

const Point2i Sprite::size ( void ) const
{
  return Point2i ( this->sprite_.width(), this->sprite_.height() );
}

const Point2i Sprite::position ( void ) const
{
  // FIXME
  return Point2i ( this->position_.x, this->position_.y );
}

uint32 Sprite::state ( void ) const
{
  return this->state_;
}

void Sprite::set_state ( uint32 state )
{
  this->state_ = state;
}

bool Sprite::load (
                    const std::string& filename,
                    bool use_cache,
                    enum Texture::Access type
                  )
{
  this->sprite_.load ( filename, use_cache, type );

  if ( this->sprite_.valid() == false )
  {
    NOM_LOG_ERR ( NOM, "Could not load sprite image file: " + filename );
    return false;
  }

  this->setSize ( this->sprite_.width(), this->sprite_.height() );

  return true;
}

void Sprite::update ( void )
{
  // FIXME
  this->sprite_.set_position ( Point2i ( this->position_.x, this->position_.y ) );
}

void Sprite::draw ( RenderTarget target ) const
{
NOM_ASSERT ( this->sprite_.valid() );

  this->sprite_.draw ( target.renderer() );
}

void Sprite::draw ( RenderTarget target, const double degrees ) const
{
  this->sprite_.draw ( target.renderer(), degrees );
}

bool Sprite::resize ( enum Texture::ResizeAlgorithm scaling_algorithm )
{
  if ( this->sprite_.valid() == false )
  {
NOM_LOG_ERR ( NOM, "Video surface is invalid." );
    return false;
  }

  if ( this->sprite_.resize ( scaling_algorithm ) == false )
  {
NOM_LOG_ERR ( NOM, "Failed to resize the video surface." );
    return false;
  }

  this->scale_factor = this->sprite_.scale_factor ( scaling_algorithm );
  this->update();

  return true;
}

} // namespace nom
<commit_msg>Sprite: Clean up err handling a bit inside load method<commit_after>/******************************************************************************

  nomlib - C++11 cross-platform game engine

Copyright (c) 2013, 2014 Jeffrey Carpenter <i8degrees@gmail.com>
All rights reserved.

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

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. 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.

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.

******************************************************************************/
#include "nomlib/graphics/sprite/Sprite.hpp"

namespace nom {

Sprite::Sprite ( void ) : state_ ( 0 ), scale_factor ( 1 )
{
NOM_LOG_TRACE ( NOM );
}

Sprite::~Sprite ( void )
{
NOM_LOG_TRACE ( NOM );
}

Sprite::Sprite ( int32 width, int32 height )  :
  Transformable { Coords ( 0, 0, width, height ) }, state_ ( 0 ),
  scale_factor ( 1 )

{
NOM_LOG_TRACE ( NOM );
}

Sprite& Sprite::operator = ( const Sprite& other )
{
  this->sprite_ = other.sprite_;
  this->set_position ( other.position().x, other.position().y );
  this->set_state ( other.state() );
  this->scale_factor = other.scale_factor;

  return *this;
}

SDL_TEXTURE::RawPtr Sprite::texture ( void ) const
{
  return this->sprite_.texture();
}

const Point2i Sprite::size ( void ) const
{
  return Point2i ( this->sprite_.width(), this->sprite_.height() );
}

const Point2i Sprite::position ( void ) const
{
  // FIXME
  return Point2i ( this->position_.x, this->position_.y );
}

uint32 Sprite::state ( void ) const
{
  return this->state_;
}

void Sprite::set_state ( uint32 state )
{
  this->state_ = state;
}

bool Sprite::load (
                    const std::string& filename,
                    bool use_cache,
                    enum Texture::Access type
                  )
{
  if ( this->sprite_.load ( filename, use_cache, type ) == false )
  {
    NOM_LOG_ERR ( NOM, "Could not load sprite image file: " + filename );
    return false;
  }

  this->setSize ( this->sprite_.width(), this->sprite_.height() );

  return true;
}

void Sprite::update ( void )
{
  // FIXME
  this->sprite_.set_position ( Point2i ( this->position_.x, this->position_.y ) );
}

void Sprite::draw ( RenderTarget target ) const
{
NOM_ASSERT ( this->sprite_.valid() );

  this->sprite_.draw ( target.renderer() );
}

void Sprite::draw ( RenderTarget target, const double degrees ) const
{
  this->sprite_.draw ( target.renderer(), degrees );
}

bool Sprite::resize ( enum Texture::ResizeAlgorithm scaling_algorithm )
{
  if ( this->sprite_.valid() == false )
  {
NOM_LOG_ERR ( NOM, "Video surface is invalid." );
    return false;
  }

  if ( this->sprite_.resize ( scaling_algorithm ) == false )
  {
NOM_LOG_ERR ( NOM, "Failed to resize the video surface." );
    return false;
  }

  this->scale_factor = this->sprite_.scale_factor ( scaling_algorithm );
  this->update();

  return true;
}

} // namespace nom
<|endoftext|>


<commit_before>// Copyright 2008-present Contributors to the OpenImageIO project.
// SPDX-License-Identifier: BSD-3-Clause
// https://github.com/OpenImageIO/oiio/blob/master/LICENSE.md

#include <OpenImageIO/imageio.h>
#include <OpenImageIO/tiffutils.h>

#include <libheif/heif_cxx.h>

// This plugin utilises libheif:
//   https://github.com/strukturag/libheif
//
// General information about HEIF/HEIC:
//
// Sources of sample images:
//     https://github.com/nokiatech/heif/tree/gh-pages/content

OIIO_PLUGIN_NAMESPACE_BEGIN

class HeifInput final : public ImageInput {
public:
    HeifInput() {}
    virtual ~HeifInput() { close(); }
    virtual const char* format_name(void) const override { return "heif"; }
    virtual int supports(string_view feature) const override
    {
        return feature == "exif";
    }
    // virtual bool valid_file(const std::string& filename) const override;
    virtual bool open(const std::string& name, ImageSpec& newspec) override;
    virtual bool open(const std::string& name, ImageSpec& newspec,
                      const ImageSpec& config) override;
    virtual bool close() override;
    virtual bool seek_subimage(int subimage, int miplevel) override;
    virtual bool read_native_scanline(int subimage, int miplevel, int y, int z,
                                      void* data) override;

private:
    std::string m_filename;
    int m_subimage      = -1;
    int m_num_subimages = 0;
    int m_has_alpha     = false;
    std::unique_ptr<heif::Context> m_ctx;
    heif_item_id m_primary_id;             // id of primary image
    std::vector<heif_item_id> m_item_ids;  // ids of all other images
    heif::ImageHandle m_ihandle;
    heif::Image m_himage;
};

// Export version number and create function symbols
OIIO_PLUGIN_EXPORTS_BEGIN

OIIO_EXPORT int heif_imageio_version = OIIO_PLUGIN_VERSION;

OIIO_EXPORT const char*
heif_imageio_library_version()
{
    return "libheif " LIBHEIF_VERSION;
}

OIIO_EXPORT ImageInput*
heif_input_imageio_create()
{
    return new HeifInput;
}

OIIO_EXPORT const char* heif_input_extensions[] = { "heic", "heif", "heics",
                                                    nullptr };

OIIO_PLUGIN_EXPORTS_END

#if 0
bool
HeifInput::valid_file(const std::string& filename) const
{
    const size_t magic_size = 12;
    uint8_t magic[magic_size];
    FILE *file = Filesystem::fopen(filename, "rb");
    fread (magic, magic_size, 1, file);
    fclose (file);
    heif_filetype_result filetype_check = heif_check_filetype(magic,12);
    return filetype_check != heif_filetype_no
            && filetype_check != heif_filetype_yes_unsupported
    // This is what the libheif example said to do, but I can't find
    // the filetype constants declared anywhere. Are they obsolete?
}
#endif

bool
HeifInput::open(const std::string& name, ImageSpec& newspec)
{
    // If user doesn't want to provide any config, just use an empty spec.
    ImageSpec config;
    return open(name, newspec, config);
}

bool
HeifInput::open(const std::string& name, ImageSpec& newspec,
                const ImageSpec& /*config*/)
{
    m_filename = name;
    m_subimage = -1;

    m_ctx.reset(new heif::Context);
    m_himage  = heif::Image();
    m_ihandle = heif::ImageHandle();

    try {
        m_ctx->read_from_file(name);
        // FIXME: should someday be read_from_reader to give full flexibility

        m_item_ids   = m_ctx->get_list_of_top_level_image_IDs();
        m_primary_id = m_ctx->get_primary_image_ID();
        for (size_t i = 0; i < m_item_ids.size(); ++i)
            if (m_item_ids[i] == m_primary_id) {
                m_item_ids.erase(m_item_ids.begin() + i);
                break;
            }
        // std::cout << " primary id: " << m_primary_id << "\n";
        // std::cout << " item ids: " << Strutil::join(m_item_ids, ", ") << "\n";
        m_num_subimages = 1 + int(m_item_ids.size());

    } catch (const heif::Error& err) {
        std::string e = err.get_message();
        errorf("%s", e.empty() ? "unknown exception" : e.c_str());
        return false;
    } catch (const std::exception& err) {
        std::string e = err.what();
        errorf("%s", e.empty() ? "unknown exception" : e.c_str());
        return false;
    }

    bool ok = seek_subimage(0, 0);
    newspec = spec();
    return ok;
}

bool
HeifInput::close()
{
    m_himage  = heif::Image();
    m_ihandle = heif::ImageHandle();
    m_ctx.reset();
    m_subimage      = -1;
    m_num_subimages = 0;
    return true;
}

bool
HeifInput::seek_subimage(int subimage, int miplevel)
{
    if (miplevel != 0)
        return false;

    if (subimage == m_subimage) {
        return true;  // already there
    }

    if (subimage >= m_num_subimages) {
        return false;
    }

    try {
        auto id     = (subimage == 0) ? m_primary_id : m_item_ids[subimage - 1];
        m_ihandle   = m_ctx->get_image_handle(id);
        m_has_alpha = m_ihandle.has_alpha_channel();
        auto chroma = m_has_alpha ? heif_chroma_interleaved_RGBA
                                  : heif_chroma_interleaved_RGB;
        m_himage = m_ihandle.decode_image(heif_colorspace_RGB, chroma);

    } catch (const heif::Error& err) {
        std::string e = err.get_message();
        errorf("%s", e.empty() ? "unknown exception" : e.c_str());
        return false;
    } catch (const std::exception& err) {
        std::string e = err.what();
        errorf("%s", e.empty() ? "unknown exception" : e.c_str());
        return false;
    }

    int bits = m_himage.get_bits_per_pixel(heif_channel_interleaved);
    m_spec = ImageSpec(m_ihandle.get_width(), m_ihandle.get_height(), bits / 8,
                       TypeUInt8);

    m_spec.attribute("oiio:ColorSpace", "sRGB");

    auto meta_ids = m_ihandle.get_list_of_metadata_block_IDs();
    // std::cout << "nmeta? " << meta_ids.size() << "\n";
    for (auto m : meta_ids) {
        std::vector<uint8_t> metacontents;
        try {
            metacontents = m_ihandle.get_metadata(m);
        } catch (const heif::Error& err) {
            if (err.get_code() == heif_error_Usage_error
                && err.get_subcode() == heif_suberror_Null_pointer_argument) {
                // a bug in heif_cxx.h means a 0 byte metadata causes a null
                // ptr error code, which we ignore
                continue;
            }
        }
        if (Strutil::iequals(m_ihandle.get_metadata_type(m), "Exif")
            && metacontents.size() >= 10) {
            cspan<uint8_t> s(&metacontents[10], metacontents.size() - 10);
            decode_exif(s, m_spec);
        } else if (0  // For now, skip this, I haven't seen anything useful
                   && Strutil::iequals(m_ihandle.get_metadata_type(m), "mime")
                   && Strutil::iequals(m_ihandle.get_metadata_content_type(m),
                                       "application/rdf+xml")) {
            decode_xmp(metacontents, m_spec);
        } else {
#ifdef DEBUG
            std::cout << "Don't know how to decode meta " << m
                      << " type=" << m_ihandle.get_metadata_type(m)
                      << " contenttype='"
                      << m_ihandle.get_metadata_content_type(m) << "'\n";
            std::cout << "---\n"
                      << string_view((const char*)&metacontents[0],
                                     metacontents.size())
                      << "\n---\n";
#endif
        }
    }

    // Erase the orientation metadata becaue libheif appears to be doing
    // the rotation-to-canonical-direction for us.
    m_spec.erase_attribute("Orientation");

    m_subimage = subimage;
    return true;
}

bool
HeifInput::read_native_scanline(int subimage, int miplevel, int y, int /*z*/,
                                void* data)
{
    lock_guard lock(*this);
    if (!seek_subimage(subimage, miplevel))
        return false;
    if (y < 0 || y >= m_spec.height)  // out of range scanline
        return false;

    int ystride          = 0;
    const uint8_t* hdata = m_himage.get_plane(heif_channel_interleaved,
                                              &ystride);
    if (!hdata) {
        errorf("Unknown read error");
        return false;
    }
    hdata += (y - m_spec.y) * ystride;
    memcpy(data, hdata, m_spec.width * m_spec.pixel_bytes());
    return true;
}

OIIO_PLUGIN_NAMESPACE_END
<commit_msg>Re-add the HeifInput valid_file check (#2810)<commit_after>// Copyright 2008-present Contributors to the OpenImageIO project.
// SPDX-License-Identifier: BSD-3-Clause
// https://github.com/OpenImageIO/oiio/blob/master/LICENSE.md

#include <OpenImageIO/filesystem.h>
#include <OpenImageIO/imageio.h>
#include <OpenImageIO/tiffutils.h>

#include <libheif/heif_cxx.h>

// This plugin utilises libheif:
//   https://github.com/strukturag/libheif
//
// General information about HEIF/HEIC:
//
// Sources of sample images:
//     https://github.com/nokiatech/heif/tree/gh-pages/content

OIIO_PLUGIN_NAMESPACE_BEGIN

class HeifInput final : public ImageInput {
public:
    HeifInput() {}
    virtual ~HeifInput() { close(); }
    virtual const char* format_name(void) const override { return "heif"; }
    virtual int supports(string_view feature) const override
    {
        return feature == "exif";
    }
    virtual bool valid_file(const std::string& filename) const override;
    virtual bool open(const std::string& name, ImageSpec& newspec) override;
    virtual bool open(const std::string& name, ImageSpec& newspec,
                      const ImageSpec& config) override;
    virtual bool close() override;
    virtual bool seek_subimage(int subimage, int miplevel) override;
    virtual bool read_native_scanline(int subimage, int miplevel, int y, int z,
                                      void* data) override;

private:
    std::string m_filename;
    int m_subimage      = -1;
    int m_num_subimages = 0;
    int m_has_alpha     = false;
    std::unique_ptr<heif::Context> m_ctx;
    heif_item_id m_primary_id;             // id of primary image
    std::vector<heif_item_id> m_item_ids;  // ids of all other images
    heif::ImageHandle m_ihandle;
    heif::Image m_himage;
};

// Export version number and create function symbols
OIIO_PLUGIN_EXPORTS_BEGIN

OIIO_EXPORT int heif_imageio_version = OIIO_PLUGIN_VERSION;

OIIO_EXPORT const char*
heif_imageio_library_version()
{
    return "libheif " LIBHEIF_VERSION;
}

OIIO_EXPORT ImageInput*
heif_input_imageio_create()
{
    return new HeifInput;
}

OIIO_EXPORT const char* heif_input_extensions[] = { "heic", "heif", "heics",
                                                    nullptr };

OIIO_PLUGIN_EXPORTS_END

bool
HeifInput::valid_file(const std::string& filename) const
{
    uint8_t magic[12];
    if (Filesystem::read_bytes(filename, magic, sizeof(magic)) != sizeof(magic))
        return false;
    heif_filetype_result filetype_check = heif_check_filetype(magic,
                                                              sizeof(magic));
    return filetype_check != heif_filetype_no
           && filetype_check != heif_filetype_yes_unsupported;
}

bool
HeifInput::open(const std::string& name, ImageSpec& newspec)
{
    // If user doesn't want to provide any config, just use an empty spec.
    ImageSpec config;
    return open(name, newspec, config);
}

bool
HeifInput::open(const std::string& name, ImageSpec& newspec,
                const ImageSpec& /*config*/)
{
    m_filename = name;
    m_subimage = -1;

    m_ctx.reset(new heif::Context);
    m_himage  = heif::Image();
    m_ihandle = heif::ImageHandle();

    try {
        m_ctx->read_from_file(name);
        // FIXME: should someday be read_from_reader to give full flexibility

        m_item_ids   = m_ctx->get_list_of_top_level_image_IDs();
        m_primary_id = m_ctx->get_primary_image_ID();
        for (size_t i = 0; i < m_item_ids.size(); ++i)
            if (m_item_ids[i] == m_primary_id) {
                m_item_ids.erase(m_item_ids.begin() + i);
                break;
            }
        // std::cout << " primary id: " << m_primary_id << "\n";
        // std::cout << " item ids: " << Strutil::join(m_item_ids, ", ") << "\n";
        m_num_subimages = 1 + int(m_item_ids.size());

    } catch (const heif::Error& err) {
        std::string e = err.get_message();
        errorf("%s", e.empty() ? "unknown exception" : e.c_str());
        return false;
    } catch (const std::exception& err) {
        std::string e = err.what();
        errorf("%s", e.empty() ? "unknown exception" : e.c_str());
        return false;
    }

    bool ok = seek_subimage(0, 0);
    newspec = spec();
    return ok;
}

bool
HeifInput::close()
{
    m_himage  = heif::Image();
    m_ihandle = heif::ImageHandle();
    m_ctx.reset();
    m_subimage      = -1;
    m_num_subimages = 0;
    return true;
}

bool
HeifInput::seek_subimage(int subimage, int miplevel)
{
    if (miplevel != 0)
        return false;

    if (subimage == m_subimage) {
        return true;  // already there
    }

    if (subimage >= m_num_subimages) {
        return false;
    }

    try {
        auto id     = (subimage == 0) ? m_primary_id : m_item_ids[subimage - 1];
        m_ihandle   = m_ctx->get_image_handle(id);
        m_has_alpha = m_ihandle.has_alpha_channel();
        auto chroma = m_has_alpha ? heif_chroma_interleaved_RGBA
                                  : heif_chroma_interleaved_RGB;
        m_himage = m_ihandle.decode_image(heif_colorspace_RGB, chroma);

    } catch (const heif::Error& err) {
        std::string e = err.get_message();
        errorf("%s", e.empty() ? "unknown exception" : e.c_str());
        return false;
    } catch (const std::exception& err) {
        std::string e = err.what();
        errorf("%s", e.empty() ? "unknown exception" : e.c_str());
        return false;
    }

    int bits = m_himage.get_bits_per_pixel(heif_channel_interleaved);
    m_spec = ImageSpec(m_ihandle.get_width(), m_ihandle.get_height(), bits / 8,
                       TypeUInt8);

    m_spec.attribute("oiio:ColorSpace", "sRGB");

    auto meta_ids = m_ihandle.get_list_of_metadata_block_IDs();
    // std::cout << "nmeta? " << meta_ids.size() << "\n";
    for (auto m : meta_ids) {
        std::vector<uint8_t> metacontents;
        try {
            metacontents = m_ihandle.get_metadata(m);
        } catch (const heif::Error& err) {
            if (err.get_code() == heif_error_Usage_error
                && err.get_subcode() == heif_suberror_Null_pointer_argument) {
                // a bug in heif_cxx.h means a 0 byte metadata causes a null
                // ptr error code, which we ignore
                continue;
            }
        }
        if (Strutil::iequals(m_ihandle.get_metadata_type(m), "Exif")
            && metacontents.size() >= 10) {
            cspan<uint8_t> s(&metacontents[10], metacontents.size() - 10);
            decode_exif(s, m_spec);
        } else if (0  // For now, skip this, I haven't seen anything useful
                   && Strutil::iequals(m_ihandle.get_metadata_type(m), "mime")
                   && Strutil::iequals(m_ihandle.get_metadata_content_type(m),
                                       "application/rdf+xml")) {
            decode_xmp(metacontents, m_spec);
        } else {
#ifdef DEBUG
            std::cout << "Don't know how to decode meta " << m
                      << " type=" << m_ihandle.get_metadata_type(m)
                      << " contenttype='"
                      << m_ihandle.get_metadata_content_type(m) << "'\n";
            std::cout << "---\n"
                      << string_view((const char*)&metacontents[0],
                                     metacontents.size())
                      << "\n---\n";
#endif
        }
    }

    // Erase the orientation metadata becaue libheif appears to be doing
    // the rotation-to-canonical-direction for us.
    m_spec.erase_attribute("Orientation");

    m_subimage = subimage;
    return true;
}

bool
HeifInput::read_native_scanline(int subimage, int miplevel, int y, int /*z*/,
                                void* data)
{
    lock_guard lock(*this);
    if (!seek_subimage(subimage, miplevel))
        return false;
    if (y < 0 || y >= m_spec.height)  // out of range scanline
        return false;

    int ystride          = 0;
    const uint8_t* hdata = m_himage.get_plane(heif_channel_interleaved,
                                              &ystride);
    if (!hdata) {
        errorf("Unknown read error");
        return false;
    }
    hdata += (y - m_spec.y) * ystride;
    memcpy(data, hdata, m_spec.width * m_spec.pixel_bytes());
    return true;
}

OIIO_PLUGIN_NAMESPACE_END
<|endoftext|>


<commit_before>#include "scan/Scan.h"
#include "scan/ScanIO.h"
#include "diffusion/Diffusion.h"

#include "settings.h"

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

  Settings settings(argc, argv);

  Scan scan = ScanIO::read_from(settings.inputScan);
  scan.transform()->scale_values(0, 255);

  const int& nx = scan.data()->get_nx();
  const int& ny = scan.data()->get_ny();
  const int& nz = scan.data()->get_nz();

  ImageData imageData;
  imageData.set_values(scan.data()->get_values(), nx, ny, nz, 0, 0, 0);

  Image image(imageData);

  Diffusion diffusion(image, settings.diffusionSettings);
  image = diffusion.get_result();

  image.data().set_boundary_sizes(0, 0, 0);

  scan.data()->set_data(image.data().values);

  ScanIO::write_to(settings.outputScan, scan);

}
<commit_msg>switched to new image classes<commit_after>#include "image/Image.h"

#include "settings.h"

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

  Settings settings(argc, argv);

  Image scan;
  scan.read().from(settings.inputScan);
  scan.values().scale(0, 255);

  const double stepSize = 0.125;

  scan.filter().diffusion(
                          settings.diffusionSettings.timeSteps,
                          stepSize,
                          settings.diffusionSettings.contrastLambda,
                          settings.diffusionSettings.integrationRho,
                          settings.diffusionSettings.presmoothSigma
                          );

  scan.write().to(settings.outputScan);

  return 0;

}
<|endoftext|>


<commit_before>//
//  main.cpp
//  antlr4-cpp-demo
//
//  Created by Mike Lischke on 13.03.16.
//

#include <iostream>

#include "ANTLRInputStream.h"
#include "CommonTokenStream.h"
#include "TLexer.h"
#include "TParser.h"

#include "Strings.h"

using namespace antlrcpptest;
using namespace org::antlr::v4::runtime;

int main(int argc, const char * argv[]) {

  ANTLRInputStream input(L"x * y + z;");
  TLexer lexer(&input);
  CommonTokenStream tokens(&lexer);

  TParser parser(&tokens);
  Ref<tree::ParseTree> tree = parser.main();

  std::cout << antlrcpp::ws2s(tree->toStringTree(&parser)) << std::endl;

  return 0;
}
<commit_msg>A bit more complex expression in demo parser.<commit_after>//
//  main.cpp
//  antlr4-cpp-demo
//
//  Created by Mike Lischke on 13.03.16.
//

#include <iostream>

#include "ANTLRInputStream.h"
#include "CommonTokenStream.h"
#include "TLexer.h"
#include "TParser.h"

#include "Strings.h"

using namespace antlrcpptest;
using namespace org::antlr::v4::runtime;

int main(int argc, const char * argv[]) {

  ANTLRInputStream input(L"(((x))) * y + z; a + (x * (y ? 0 : 1) + z);");
  TLexer lexer(&input);
  CommonTokenStream tokens(&lexer);

  TParser parser(&tokens);
  Ref<tree::ParseTree> tree = parser.main();

  std::cout << antlrcpp::ws2s(tree->toStringTree(&parser)) << std::endl;

  return 0;
}
<|endoftext|>


<commit_before>#include "Halide.h"

using namespace Halide;

Expr lerp(Expr a, Expr b, Expr alpha) {
    return (1.0f - alpha)*a + alpha*b;
}

int main(int argc, char **argv) {
    if (argc < 2) {
        printf("Spatial sigma is a compile-time parameter, please provide it as an argument.\n"
               "(llvm's ptx backend doesn't handle integer mods by non-consts yet)\n");
        return 0;
    }

    UniformImage input(Float(32), 2);
    Uniform<float> r_sigma;
    int s_sigma = atoi(argv[1]);
    Var x, y, z, c;

    // Add a boundary condition
    Func clamped;
    clamped(x, y) = input(clamp(x, 0, input.width()-1),
                          clamp(y, 0, input.height()-1));

    // Construct the bilateral grid
    RDom r(0, s_sigma, 0, s_sigma);
    Expr val = clamped(x * s_sigma + r.x - s_sigma/2, y * s_sigma + r.y - s_sigma/2);
    val = clamp(val, 0.0f, 1.0f);
    Expr zi = cast<int>(val * (1.0f/r_sigma) + 0.5f);
    Func grid;
    grid(x, y, zi, c) += select(c == 0, val, 1.0f);

    // Blur the grid using a five-tap filter
    Func blurx, blury, blurz;
    blurx(x, y, z) = grid(x-2, y, z) + grid(x-1, y, z)*4 + grid(x, y, z)*6 + grid(x+1, y, z)*4 + grid(x+2, y, z);
    blury(x, y, z) = blurx(x, y-2, z) + blurx(x, y-1, z)*4 + blurx(x, y, z)*6 + blurx(x, y+1, z)*4 + blurx(x, y+2, z);
    blurz(x, y, z) = blury(x, y, z-2) + blury(x, y, z-1)*4 + blury(x, y, z)*6 + blury(x, y, z+1)*4 + blury(x, y, z+2);

    // Take trilinear samples to compute the output
    val = clamp(clamped(x, y), 0.0f, 1.0f);
    Expr zv = val * (1.0f/r_sigma);
    zi = cast<int>(zv);
    Expr zf = zv - zi;
    Expr xf = cast<float>(x % s_sigma) / s_sigma;
    Expr yf = cast<float>(y % s_sigma) / s_sigma;
    Expr xi = x/s_sigma;
    Expr yi = y/s_sigma;
    Func interpolated;
    interpolated(x, y) =
        lerp(lerp(lerp(blurz(xi, yi, zi), blurz(xi+1, yi, zi), xf),
                  lerp(blurz(xi, yi+1, zi), blurz(xi+1, yi+1, zi), xf), yf),
             lerp(lerp(blurz(xi, yi, zi+1), blurz(xi+1, yi, zi+1), xf),
                  lerp(blurz(xi, yi+1, zi+1), blurz(xi+1, yi+1, zi+1), xf), yf), zf);

    // Normalize
    Func smoothed;
    smoothed(x, y) = interpolated(x, y, 0)/interpolated(x, y, 1);

    #ifndef USE_GPU
    // Best schedule for CPU
    printf("Compiling for CPU\n");
    grid.root().parallel(z);
    grid.update().transpose(y, c).transpose(x, c).parallel(y);
    blurx.root().parallel(z).vectorize(x, 4);
    blury.root().parallel(z).vectorize(x, 4);
    blurz.root().parallel(z).vectorize(x, 4);
    smoothed.root().parallel(y).vectorize(x, 4);
    #else

    printf("Compiling for GPU");
    Var gridz = grid.arg(2);
    grid.transpose(y, gridz).transpose(x, gridz).transpose(y, c).transpose(x, c)
        .root().cudaTile(x, y, 16, 16);
    grid.update().transpose(y, c).transpose(x, c).transpose(i, c).transpose(j, c)
        .root().cudaTile(x, y, 16, 16);
    c = blurx.arg(3);
    blurx.transpose(y, z).transpose(x, z).transpose(y, c).transpose(x, c)
        .root().cudaTile(x, y, 8, 8);

    c = blury.arg(3);
    blury.transpose(y, z).transpose(x, z).transpose(y, c).transpose(x, c)
        .root().cudaTile(x, y, 8, 8);

    c = blurz.arg(3);
    blurz.transpose(y, z).transpose(x, z).transpose(y, c).transpose(x, c)
        .root().cudaTile(x, y, 8, 8);

    smoothed.root().cudaTile(x, y, s_sigma, s_sigma);
    #endif

    smoothed.compileToFile("bilateral_grid", {r_sigma, input});

    // Compared to Sylvain Paris' implementation from his webpage (on
    // which this is based), for filter params s_sigma 0.1, on a 4 megapixel
    // input, on a four core x86 (2 socket core2 mac pro)
    // Filter s_sigma: 2      4       8       16      32
    // Paris (ms):     5350   1345    472     245     184
    // Us (ms):        383    142     77      62      65
    // Speedup:        14     9.5     6.1     3.9     2.8

    // Our schedule and inlining are roughly the same as his, so the
    // gain is all down to vectorizing and parallelizing. In general
    // for larger blurs our win shrinks to roughly the number of
    // cores, as the stages we don't vectorize as well dominate (we
    // don't vectorize them well because they do gathers and scatters,
    // which don't work well on x86).  For smaller blurs, our win
    // grows, because the stages that we vectorize take up all the
    // time.

    return 0;
}

<commit_msg>Cleaned up bilateral grid gpu scheduling<commit_after>#include "Halide.h"

using namespace Halide;

Expr lerp(Expr a, Expr b, Expr alpha) {
    return (1.0f - alpha)*a + alpha*b;
}

int main(int argc, char **argv) {
    if (argc < 2) {
        printf("Spatial sigma is a compile-time parameter, please provide it as an argument.\n"
               "(llvm's ptx backend doesn't handle integer mods by non-consts yet)\n");
        return 0;
    }

    UniformImage input(Float(32), 2);
    Uniform<float> r_sigma;
    int s_sigma = atoi(argv[1]);
    Var x, y, z, c;

    // Add a boundary condition
    Func clamped;
    clamped(x, y) = input(clamp(x, 0, input.width()-1),
                          clamp(y, 0, input.height()-1));

    // Construct the bilateral grid
    RDom r(0, s_sigma, 0, s_sigma);
    Expr val = clamped(x * s_sigma + r.x - s_sigma/2, y * s_sigma + r.y - s_sigma/2);
    val = clamp(val, 0.0f, 1.0f);
    Expr zi = cast<int>(val * (1.0f/r_sigma) + 0.5f);
    Func grid;
    grid(x, y, zi, c) += select(c == 0, val, 1.0f);

    // Blur the grid using a five-tap filter
    Func blurx, blury, blurz;
    blurx(x, y, z) = grid(x-2, y, z) + grid(x-1, y, z)*4 + grid(x, y, z)*6 + grid(x+1, y, z)*4 + grid(x+2, y, z);
    blury(x, y, z) = blurx(x, y-2, z) + blurx(x, y-1, z)*4 + blurx(x, y, z)*6 + blurx(x, y+1, z)*4 + blurx(x, y+2, z);
    blurz(x, y, z) = blury(x, y, z-2) + blury(x, y, z-1)*4 + blury(x, y, z)*6 + blury(x, y, z+1)*4 + blury(x, y, z+2);

    // Take trilinear samples to compute the output
    val = clamp(clamped(x, y), 0.0f, 1.0f);
    Expr zv = val * (1.0f/r_sigma);
    zi = cast<int>(zv);
    Expr zf = zv - zi;
    Expr xf = cast<float>(x % s_sigma) / s_sigma;
    Expr yf = cast<float>(y % s_sigma) / s_sigma;
    Expr xi = x/s_sigma;
    Expr yi = y/s_sigma;
    Func interpolated;
    interpolated(x, y) =
        lerp(lerp(lerp(blurz(xi, yi, zi), blurz(xi+1, yi, zi), xf),
                  lerp(blurz(xi, yi+1, zi), blurz(xi+1, yi+1, zi), xf), yf),
             lerp(lerp(blurz(xi, yi, zi+1), blurz(xi+1, yi, zi+1), xf),
                  lerp(blurz(xi, yi+1, zi+1), blurz(xi+1, yi+1, zi+1), xf), yf), zf);

    // Normalize
    Func smoothed;
    smoothed(x, y) = interpolated(x, y, 0)/interpolated(x, y, 1);

    #ifndef USE_GPU
    // Best schedule for CPU
    printf("Compiling for CPU\n");
    grid.root().parallel(z);
    grid.update().transpose(y, c).transpose(x, c).parallel(y);
    blurx.root().parallel(z).vectorize(x, 4);
    blury.root().parallel(z).vectorize(x, 4);
    blurz.root().parallel(z).vectorize(x, 4);
    smoothed.root().parallel(y).vectorize(x, 4);
    #else

    printf("Compiling for GPU");
    Var gridz = grid.arg(2);
    grid.root().cudaTile(x, y, 16, 16);
    grid.update().root().cudaTile(x, y, 16, 16);
    blurx.root().cudaTile(x, y, 8, 8);
    blury.root().cudaTile(x, y, 8, 8);
    blurz.root().cudaTile(x, y, 8, 8);
    smoothed.root().cudaTile(x, y, s_sigma, s_sigma);
    #endif

    smoothed.compileToFile("bilateral_grid", {r_sigma, input});

    // Compared to Sylvain Paris' implementation from his webpage (on
    // which this is based), for filter params s_sigma 0.1, on a 4 megapixel
    // input, on a four core x86 (2 socket core2 mac pro)
    // Filter s_sigma: 2      4       8       16      32
    // Paris (ms):     5350   1345    472     245     184
    // Us (ms):        383    142     77      62      65
    // Speedup:        14     9.5     6.1     3.9     2.8

    // Our schedule and inlining are roughly the same as his, so the
    // gain is all down to vectorizing and parallelizing. In general
    // for larger blurs our win shrinks to roughly the number of
    // cores, as the stages we don't vectorize as well dominate (we
    // don't vectorize them well because they do gathers and scatters,
    // which don't work well on x86).  For smaller blurs, our win
    // grows, because the stages that we vectorize take up all the
    // time.

    return 0;
}

<|endoftext|>


<commit_before>/*!
 * a tool to combine different set of features into binary buffer
 * not well organized code, but does it's job
 * \author Tianqi Chen: tianqi.tchen@gmail.com
 */
#define _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_DEPRECATE

#include <cstdio>
#include <cstring>
#include <ctime>
#include <cmath>
#include "../regrank/xgboost_regrank_data.h"
#include "../utils/xgboost_utils.h"

using namespace xgboost;
using namespace xgboost::booster;
using namespace xgboost::regrank;

// header in dataset
struct Header{
    FILE *fi;
    int   tmp_num;
    int   base;
    int   num_feat;
    // whether it's dense format
    bool  is_dense;
	bool  warned;

	Header( void ){ this->warned = false; this->is_dense = false; }

	inline void CheckBase( unsigned findex ){
		if( findex >= (unsigned)num_feat && ! warned ) {
			fprintf( stderr, "warning:some feature exceed bound, num_feat=%d\n", num_feat );
			warned = true;
		}
	}
};

inline int norm( std::vector<Header> &vec, int base = 0 ){
    int n = base;
    for( size_t i = 0; i < vec.size(); i ++ ){
        if( vec[i].is_dense ) vec[i].num_feat = 1;
        vec[i].base = n; n += vec[i].num_feat;
    }
    return n;
}

inline void vclose( std::vector<Header> &vec ){
    for( size_t i = 0; i < vec.size(); i ++ ){
        fclose( vec[i].fi );
    }
}

inline int readnum( std::vector<Header> &vec ){
    int n = 0;
    for( size_t i = 0; i < vec.size(); i ++ ){
        if( !vec[i].is_dense ){
            utils::Assert( fscanf( vec[i].fi, "%d", &vec[i].tmp_num ) == 1, "load num" );
            n += vec[i].tmp_num;
        }else{
            n ++;
        }
    }
    return n;
}

inline void vskip( std::vector<Header> &vec ){
    for( size_t i = 0; i < vec.size(); i ++ ){
        if( !vec[i].is_dense ){
            utils::Assert( fscanf( vec[i].fi, "%*d%*[^\n]\n" ) >= 0 );
        }else{
            utils::Assert( fscanf( vec[i].fi, "%*f\n" ) >= 0 );
        }
    }
}

class DataLoader: public DMatrix{
public:
    // whether to do node and edge feature renormalization
    int rescale;
    int linelimit;
public:
    FILE *fp, *fwlist, *fgroup;
    std::vector<Header> fheader;
    std::vector<FMatrixS::REntry> entry;
    DataLoader( void ){
        rescale = 0;
        linelimit = -1;
        fp = NULL; fwlist = NULL; fgroup = NULL;
    }
private:
    inline void Load( std::vector<unsigned> &findex, std::vector<float> &fvalue, std::vector<Header> &vec ){
        unsigned fidx; float fv;
        for( size_t i = 0; i < vec.size(); i ++ ){
            if( !vec[i].is_dense ) {
                for( int j = 0; j < vec[i].tmp_num; j ++ ){
                    utils::Assert( fscanf ( vec[i].fi, "%u:%f", &fidx, &fv ) == 2, "Error when load feat" );
                    vec[i].CheckBase( fidx );
                    fidx += vec[i].base;
                    findex.push_back( fidx ); fvalue.push_back( fv );
                }
            }else{
                utils::Assert( fscanf ( vec[i].fi, "%f", &fv ) == 1, "load feat" );
                fidx = vec[i].base;
                findex.push_back( fidx ); fvalue.push_back( fv );
            }
        }
    }
    inline void DoRescale( std::vector<float> &vec ){
        double sum = 0.0;
        for( size_t i = 0; i < vec.size(); i ++ ){
            sum += vec[i] * vec[i];
        }
        sum = sqrt( sum );
        for( size_t i = 0; i < vec.size(); i ++ ){
            vec[i] /= sum;
        }
    }
public:
    // basically we are loading all the data inside
    inline void Load( void ){
        this->data.Clear();
        float label;

        unsigned ngleft = 0, ngacc = 0;
        if( fgroup != NULL ){
            info.group_ptr.clear();
            info.group_ptr.push_back(0);
        }

        while( fscanf( fp, "%f", &label ) == 1 ){
            if( ngleft == 0 && fgroup != NULL ){
                utils::Assert( fscanf( fgroup, "%u", &ngleft ) == 1 );
            }
            ngleft -= 1; ngacc += 1;

            if( fwlist != NULL ){
                int pass;
                utils::Assert( fscanf( fwlist, "%u", &pass ) ==1 );
                if( pass == 0 ){
                    vskip( fheader ); ngacc -= 1;
                }
            }

            const int nfeat = readnum( fheader );
            std::vector<unsigned> findex;
            std::vector<float> fvalue;
            // pairs
            this->Load( findex, fvalue, fheader );
            utils::Assert( findex.size() == (unsigned)nfeat );
            if( rescale != 0 ) this->DoRescale( fvalue );
            // push back data :)
            this->info.labels.push_back( label );
            this->data.AddRow( findex, fvalue );

            if( ngleft == 0 && fgroup != NULL && ngacc != 0 ){
                info.group_ptr.push_back( info.group_ptr.back() + ngacc );
                utils::Assert( info.group_ptr.back() == data.NumRow(), "group size must match num rows" );
                ngacc = 0;
            }
            // linelimit
            if( linelimit >= 0 ) {
                if( -- linelimit <= 0 ) break;
            }
        }
        if( ngleft == 0 && fgroup != NULL && ngacc != 0 ){
            info.group_ptr.push_back( info.group_ptr.back() + ngacc );
            utils::Assert( info.group_ptr.back() == data.NumRow(), "group size must match num rows" );
        }
        this->data.InitData();
    }
};

const char *folder = "features";

int main( int argc, char *argv[] ){
    if( argc < 3 ){
        printf("Usage:xgcombine_buffer <inname> <outname> [options] -f [features] -fd [densefeatures]\n"\
               "options: -rescale -linelimit -fgroup <groupfilename> -wlist <whitelistinstance>\n");
        return 0;
    }

    DataLoader loader;
    time_t start = time( NULL );

    int mode = 0;
    for( int i = 3; i < argc; i ++ ){
        if( !strcmp( argv[i], "-f") ){
            mode = 0; continue;
        }
        if( !strcmp( argv[i], "-fd") ){
            mode = 2; continue;
        }
        if( !strcmp( argv[i], "-rescale") ){
            loader.rescale = 1; continue;
        }
        if( !strcmp( argv[i], "-wlist") ){
            loader.fwlist = utils::FopenCheck( argv[ ++i ], "r" ); continue;
        }
        if( !strcmp( argv[i], "-fgroup") ){
            loader.fgroup = utils::FopenCheck( argv[ ++i ], "r" ); continue;
        }
        if( !strcmp( argv[i], "-linelimit") ){
            loader.linelimit = atoi( argv[ ++i ] ); continue;
        }

        char name[ 256 ];
        sprintf( name, "%s/%s.%s", folder, argv[1], argv[i] );
        Header h;
        h.fi = utils::FopenCheck( name, "r" );

        if( mode == 2 ){
            h.is_dense = true; h.num_feat = 1;
            loader.fheader.push_back( h );
        }else{
            utils::Assert( fscanf( h.fi, "%d", &h.num_feat ) == 1, "num feat" );
            switch( mode ){
            case 0: loader.fheader.push_back( h ); break;
            default: ;
            }
        }
    }
    loader.fp = utils::FopenCheck( argv[1], "r" );

    printf("num_features=%d\n", norm( loader.fheader ) );
    printf("start creating buffer...\n");
    loader.Load();
    loader.SaveBinary( argv[2] );
    // close files
    fclose( loader.fp );
    if( loader.fwlist != NULL ) fclose( loader.fwlist );
    if( loader.fgroup != NULL ) fclose( loader.fgroup );
    vclose( loader.fheader );
    printf("all generation end, %lu sec used\n", (unsigned long)(time(NULL) - start) );
    return 0;
}
<commit_msg>pass test<commit_after>/*!
 * a tool to combine different set of features into binary buffer
 * not well organized code, but does it's job
 * \author Tianqi Chen: tianqi.tchen@gmail.com
 */
#define _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_DEPRECATE

#include <cstdio>
#include <cstring>
#include <ctime>
#include <cmath>
#include "../regrank/xgboost_regrank_data.h"
#include "../utils/xgboost_utils.h"

using namespace xgboost;
using namespace xgboost::booster;
using namespace xgboost::regrank;

// header in dataset
struct Header{
    FILE *fi;
    int   tmp_num;
    int   base;
    int   num_feat;
    // whether it's dense format
    bool  is_dense;
	bool  warned;

	Header( void ){ this->warned = false; this->is_dense = false; }

	inline void CheckBase( unsigned findex ){
		if( findex >= (unsigned)num_feat && ! warned ) {
			fprintf( stderr, "warning:some feature exceed bound, num_feat=%d\n", num_feat );
			warned = true;
		}
	}
};

inline int norm( std::vector<Header> &vec, int base = 0 ){
    int n = base;
    for( size_t i = 0; i < vec.size(); i ++ ){
        if( vec[i].is_dense ) vec[i].num_feat = 1;
        vec[i].base = n; n += vec[i].num_feat;
    }
    return n;
}

inline void vclose( std::vector<Header> &vec ){
    for( size_t i = 0; i < vec.size(); i ++ ){
        fclose( vec[i].fi );
    }
}

inline int readnum( std::vector<Header> &vec ){
    int n = 0;
    for( size_t i = 0; i < vec.size(); i ++ ){
        if( !vec[i].is_dense ){
            utils::Assert( fscanf( vec[i].fi, "%d", &vec[i].tmp_num ) == 1, "load num" );
            n += vec[i].tmp_num;
        }else{
            n ++;
        }
    }
    return n;
}

inline void vskip( std::vector<Header> &vec ){
    for( size_t i = 0; i < vec.size(); i ++ ){
        if( !vec[i].is_dense ){
            utils::Assert( fscanf( vec[i].fi, "%*d%*[^\n]\n" ) >= 0 );
        }else{
            utils::Assert( fscanf( vec[i].fi, "%*f\n" ) >= 0 );
        }
    }
}

class DataLoader: public DMatrix{
public:
    // whether to do node and edge feature renormalization
    int rescale;
    int linelimit;
public:
    FILE *fp, *fwlist, *fgroup;
    std::vector<Header> fheader;
    std::vector<FMatrixS::REntry> entry;
    DataLoader( void ){
        rescale = 0;
        linelimit = -1;
        fp = NULL; fwlist = NULL; fgroup = NULL;
    }
private:
    inline void Load( std::vector<unsigned> &findex, std::vector<float> &fvalue, std::vector<Header> &vec ){
        unsigned fidx; float fv;
        for( size_t i = 0; i < vec.size(); i ++ ){
            if( !vec[i].is_dense ) {
                for( int j = 0; j < vec[i].tmp_num; j ++ ){
                    utils::Assert( fscanf ( vec[i].fi, "%u:%f", &fidx, &fv ) == 2, "Error when load feat" );
                    vec[i].CheckBase( fidx );
                    fidx += vec[i].base;
                    findex.push_back( fidx ); fvalue.push_back( fv );
                }
            }else{
                utils::Assert( fscanf ( vec[i].fi, "%f", &fv ) == 1, "load feat" );
                fidx = vec[i].base;
                findex.push_back( fidx ); fvalue.push_back( fv );
            }
        }
    }
    inline void DoRescale( std::vector<float> &vec ){
        double sum = 0.0;
        for( size_t i = 0; i < vec.size(); i ++ ){
            sum += vec[i] * vec[i];
        }
        sum = sqrt( sum );
        for( size_t i = 0; i < vec.size(); i ++ ){
            vec[i] /= sum;
        }
    }
public:
    // basically we are loading all the data inside
    inline void Load( void ){
        this->data.Clear();
        float label;

        unsigned ngleft = 0, ngacc = 0;
        if( fgroup != NULL ){
            info.group_ptr.clear();
            info.group_ptr.push_back(0);
        }

        while( fscanf( fp, "%f", &label ) == 1 ){
            if( ngleft == 0 && fgroup != NULL ){
                utils::Assert( fscanf( fgroup, "%u", &ngleft ) == 1 );
            }
            ngleft -= 1; ngacc += 1;

            int pass = 1;
            if( fwlist != NULL ){
                utils::Assert( fscanf( fwlist, "%u", &pass ) ==1 );
            }
            if( pass == 0 ){
                vskip( fheader ); ngacc -= 1;
            }else{
                const int nfeat = readnum( fheader );
                std::vector<unsigned> findex;
                std::vector<float> fvalue;
                // pairs
                this->Load( findex, fvalue, fheader );
                utils::Assert( findex.size() == (unsigned)nfeat );
                if( rescale != 0 ) this->DoRescale( fvalue );
                // push back data :)
                this->info.labels.push_back( label );
                this->data.AddRow( findex, fvalue );
            }
            if( ngleft == 0 && fgroup != NULL && ngacc != 0 ){
                info.group_ptr.push_back( info.group_ptr.back() + ngacc );
                utils::Assert( info.group_ptr.back() == data.NumRow(), "group size must match num rows" );
                ngacc = 0;
            }
            // linelimit
            if( linelimit >= 0 ) {
                if( -- linelimit <= 0 ) break;
            }
        }
        if( ngleft == 0 && fgroup != NULL && ngacc != 0 ){
            info.group_ptr.push_back( info.group_ptr.back() + ngacc );
            utils::Assert( info.group_ptr.back() == data.NumRow(), "group size must match num rows" );
        }
        this->data.InitData();
    }
};

const char *folder = "features";

int main( int argc, char *argv[] ){
    if( argc < 3 ){
        printf("Usage:xgcombine_buffer <inname> <outname> [options] -f [features] -fd [densefeatures]\n"\
               "options: -rescale -linelimit -fgroup <groupfilename> -wlist <whitelistinstance>\n");
        return 0;
    }

    DataLoader loader;
    time_t start = time( NULL );

    int mode = 0;
    for( int i = 3; i < argc; i ++ ){
        if( !strcmp( argv[i], "-f") ){
            mode = 0; continue;
        }
        if( !strcmp( argv[i], "-fd") ){
            mode = 2; continue;
        }
        if( !strcmp( argv[i], "-rescale") ){
            loader.rescale = 1; continue;
        }
        if( !strcmp( argv[i], "-wlist") ){
            loader.fwlist = utils::FopenCheck( argv[ ++i ], "r" ); continue;
        }
        if( !strcmp( argv[i], "-fgroup") ){
            loader.fgroup = utils::FopenCheck( argv[ ++i ], "r" ); continue;
        }
        if( !strcmp( argv[i], "-linelimit") ){
            loader.linelimit = atoi( argv[ ++i ] ); continue;
        }

        char name[ 256 ];
        sprintf( name, "%s/%s.%s", folder, argv[1], argv[i] );
        Header h;
        h.fi = utils::FopenCheck( name, "r" );

        if( mode == 2 ){
            h.is_dense = true; h.num_feat = 1;
            loader.fheader.push_back( h );
        }else{
            utils::Assert( fscanf( h.fi, "%d", &h.num_feat ) == 1, "num feat" );
            switch( mode ){
            case 0: loader.fheader.push_back( h ); break;
            default: ;
            }
        }
    }
    loader.fp = utils::FopenCheck( argv[1], "r" );

    printf("num_features=%d\n", norm( loader.fheader ) );
    printf("start creating buffer...\n");
    loader.Load();
    loader.SaveBinary( argv[2] );
    // close files
    fclose( loader.fp );
    if( loader.fwlist != NULL ) fclose( loader.fwlist );
    if( loader.fgroup != NULL ) fclose( loader.fgroup );
    vclose( loader.fheader );
    printf("all generation end, %lu sec used\n", (unsigned long)(time(NULL) - start) );
    return 0;
}
<|endoftext|>


<commit_before>class Solution {
public:
    /**
     * @param s: a string
     * @return: an integer
     */
    std::map<char, int> mapCtoSub;
    int lengthOfLongestSubstring(string s) {
        // write your code here
        int i,j,k,l_s=s.size();
        int max_len=0;
        for (char c='a';c<='z';c++)
        	mapCtoSub[c]=-1;

        // cout<<s<<l_s<<endl;

        for (i=0,j=0;j<l_s;j++){
        	// cout<<i<<" "<<j<<endl;
        	if (mapCtoSub[s[j]]>-1) i=max(i,mapCtoSub[s[j]]);
        	mapCtoSub[s[j]]=j;
        	int tmp_len=j-i;
        	if (tmp_len>max_len) max_len=tmp_len;

        	// cout<<i<<" "<<j<<endl;

        }

        return max_len;

    }
};<commit_msg>testing<commit_after>class Solution {
public:
    /**
     * @param s: a string
     * @return: an integer
     */
    std::map<char, int> mapCtoSub;
    int lengthOfLongestSubstring(string s) {
        // write your code here
        int i,j,k,l_s=s.size();
        int max_len=0;
        for (char c='a';c<='z';c++)
        	mapCtoSub[c]=-1;

        // cout<<s<<l_s<<endl;

        for (i=-1,j=0;j<l_s;j++){
        	// cout<<i<<" "<<j<<endl;
        	if (mapCtoSub[s[j]]>-1) i=max(i,mapCtoSub[s[j]]);
        	mapCtoSub[s[j]]=j;
        	int tmp_len=j-i;
        	if (tmp_len>max_len) max_len=tmp_len;

        	// cout<<i<<" "<<j<<endl;

        }

        return max_len;

    }
};<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: EnhancedCustomShapeEngine.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 14:56:40 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _ENHANCED_CUSTOMSHAPE_ENGINE_HXX
#define _ENHANCED_CUSTOMSHAPE_ENGINE_HXX

#ifndef _DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _STACK_HXX
#include <tools/stack.hxx>
#endif

#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/uno/RuntimeException.hpp>
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/registry/XRegistryKey.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#ifndef _CPPUHELPER_IMPLBASE3_HXX_
#include <cppuhelper/implbase3.hxx>
#endif
#ifndef __com_sun_star_awt_Rectangle_hpp_
#include <com/sun/star/awt/Rectangle.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_POLYPOLYGONBEZIERCOORDS_HPP_
#include <com/sun/star/drawing/PolyPolygonBezierCoords.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XCUSTOMSHAPEENGINE_HPP_
#include <com/sun/star/drawing/XCustomShapeEngine.hpp>
#endif

// -----------------------------------------------------------------------------

#define NMSP_IO         com::sun::star::io
#define NMSP_UNO        com::sun::star::uno
#define NMSP_BEANS      com::sun::star::beans
#define NMSP_LANG       com::sun::star::lang
#define NMSP_UTIL       com::sun::star::util
#define NMSP_SAX        com::sun::star::xml::sax
#define NMSP_LOGGING    NMSP_UTIL::logging

#define REF( _def_Obj )         NMSP_UNO::Reference< _def_Obj >
#define SEQ( _def_Obj )         NMSP_UNO::Sequence< _def_Obj >
#define B2UCONST( _def_pChar )  (rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(_def_pChar )))

// ---------------------------
// - EnhancedCustomShapeEngine -
// ---------------------------
//

class SdrObject;
class SdrObjCustomShape;
class EnhancedCustomShapeEngine : public cppu::WeakImplHelper3
<
    com::sun::star::lang::XInitialization,
    com::sun::star::lang::XServiceInfo,
    com::sun::star::drawing::XCustomShapeEngine
>
{
    REF( NMSP_LANG::XMultiServiceFactory )      mxFact;
    REF( com::sun::star::drawing::XShape )      mxShape;
    sal_Bool                                    mbForceGroupWithText;

    SdrObject* ImplForceGroupWithText( const SdrObjCustomShape* pCustoObj, SdrObject* pRenderedShape );

public:
                            EnhancedCustomShapeEngine( const REF( NMSP_LANG::XMultiServiceFactory )& rxMgr );
    virtual                 ~EnhancedCustomShapeEngine();

    // XInterface
    virtual void SAL_CALL   acquire() throw();
    virtual void SAL_CALL   release() throw();

    // XInitialization
    virtual void SAL_CALL initialize( const SEQ( NMSP_UNO::Any )& aArguments )
        throw ( NMSP_UNO::Exception, NMSP_UNO::RuntimeException );

    // XServiceInfo
    virtual rtl::OUString SAL_CALL getImplementationName()
        throw ( NMSP_UNO::RuntimeException );
    virtual sal_Bool SAL_CALL supportsService( const rtl::OUString& rServiceName )
        throw ( NMSP_UNO::RuntimeException );
    virtual SEQ( rtl::OUString ) SAL_CALL getSupportedServiceNames()
        throw ( NMSP_UNO::RuntimeException );

    // XCustomShapeEngine
    virtual REF( com::sun::star::drawing::XShape ) SAL_CALL render()
        throw ( NMSP_UNO::RuntimeException );
    virtual com::sun::star::awt::Rectangle SAL_CALL getTextBounds()
        throw ( NMSP_UNO::RuntimeException );
    virtual com::sun::star::drawing::PolyPolygonBezierCoords SAL_CALL getLineGeometry()
        throw ( NMSP_UNO::RuntimeException );
    virtual SEQ( REF( com::sun::star::drawing::XCustomShapeHandle ) ) SAL_CALL getInteraction()
        throw ( NMSP_UNO::RuntimeException );
};

rtl::OUString EnhancedCustomShapeEngine_getImplementationName()
    throw ( NMSP_UNO::RuntimeException );
sal_Bool SAL_CALL EnhancedCustomShapeEngine_supportsService( const rtl::OUString& rServiceName )
    throw( NMSP_UNO::RuntimeException );
SEQ( rtl::OUString ) SAL_CALL EnhancedCustomShapeEngine_getSupportedServiceNames()
    throw( NMSP_UNO::RuntimeException );

#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.6.852); FILE MERGED 2008/04/01 15:50:10 thb 1.6.852.3: #i85898# Stripping all external header guards 2008/04/01 12:48:02 thb 1.6.852.2: #i85898# Stripping all external header guards 2008/03/31 14:19:17 rt 1.6.852.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: EnhancedCustomShapeEngine.hxx,v $
 * $Revision: 1.7 $
 *
 * 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 _ENHANCED_CUSTOMSHAPE_ENGINE_HXX
#define _ENHANCED_CUSTOMSHAPE_ENGINE_HXX

#include <tools/debug.hxx>
#include <tools/string.hxx>
#include <tools/stack.hxx>

#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/uno/RuntimeException.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/registry/XRegistryKey.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <cppuhelper/implbase3.hxx>
#ifndef __com_sun_star_awt_Rectangle_hpp_
#include <com/sun/star/awt/Rectangle.hpp>
#endif
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/drawing/PolyPolygonBezierCoords.hpp>
#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/drawing/XCustomShapeEngine.hpp>

// -----------------------------------------------------------------------------

#define NMSP_IO         com::sun::star::io
#define NMSP_UNO        com::sun::star::uno
#define NMSP_BEANS      com::sun::star::beans
#define NMSP_LANG       com::sun::star::lang
#define NMSP_UTIL       com::sun::star::util
#define NMSP_SAX        com::sun::star::xml::sax
#define NMSP_LOGGING    NMSP_UTIL::logging

#define REF( _def_Obj )         NMSP_UNO::Reference< _def_Obj >
#define SEQ( _def_Obj )         NMSP_UNO::Sequence< _def_Obj >
#define B2UCONST( _def_pChar )  (rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(_def_pChar )))

// ---------------------------
// - EnhancedCustomShapeEngine -
// ---------------------------
//

class SdrObject;
class SdrObjCustomShape;
class EnhancedCustomShapeEngine : public cppu::WeakImplHelper3
<
    com::sun::star::lang::XInitialization,
    com::sun::star::lang::XServiceInfo,
    com::sun::star::drawing::XCustomShapeEngine
>
{
    REF( NMSP_LANG::XMultiServiceFactory )      mxFact;
    REF( com::sun::star::drawing::XShape )      mxShape;
    sal_Bool                                    mbForceGroupWithText;

    SdrObject* ImplForceGroupWithText( const SdrObjCustomShape* pCustoObj, SdrObject* pRenderedShape );

public:
                            EnhancedCustomShapeEngine( const REF( NMSP_LANG::XMultiServiceFactory )& rxMgr );
    virtual                 ~EnhancedCustomShapeEngine();

    // XInterface
    virtual void SAL_CALL   acquire() throw();
    virtual void SAL_CALL   release() throw();

    // XInitialization
    virtual void SAL_CALL initialize( const SEQ( NMSP_UNO::Any )& aArguments )
        throw ( NMSP_UNO::Exception, NMSP_UNO::RuntimeException );

    // XServiceInfo
    virtual rtl::OUString SAL_CALL getImplementationName()
        throw ( NMSP_UNO::RuntimeException );
    virtual sal_Bool SAL_CALL supportsService( const rtl::OUString& rServiceName )
        throw ( NMSP_UNO::RuntimeException );
    virtual SEQ( rtl::OUString ) SAL_CALL getSupportedServiceNames()
        throw ( NMSP_UNO::RuntimeException );

    // XCustomShapeEngine
    virtual REF( com::sun::star::drawing::XShape ) SAL_CALL render()
        throw ( NMSP_UNO::RuntimeException );
    virtual com::sun::star::awt::Rectangle SAL_CALL getTextBounds()
        throw ( NMSP_UNO::RuntimeException );
    virtual com::sun::star::drawing::PolyPolygonBezierCoords SAL_CALL getLineGeometry()
        throw ( NMSP_UNO::RuntimeException );
    virtual SEQ( REF( com::sun::star::drawing::XCustomShapeHandle ) ) SAL_CALL getInteraction()
        throw ( NMSP_UNO::RuntimeException );
};

rtl::OUString EnhancedCustomShapeEngine_getImplementationName()
    throw ( NMSP_UNO::RuntimeException );
sal_Bool SAL_CALL EnhancedCustomShapeEngine_supportsService( const rtl::OUString& rServiceName )
    throw( NMSP_UNO::RuntimeException );
SEQ( rtl::OUString ) SAL_CALL EnhancedCustomShapeEngine_getSupportedServiceNames()
    throw( NMSP_UNO::RuntimeException );

#endif
<|endoftext|>