<commit_before>
// -*- mode: c++; c-basic-offset:4 -*-

// This file is part of libdap, A C++ implementation of the OPeNDAP Data
// Access Protocol.

// Copyright (c) 2002,2003 OPeNDAP, Inc.
// Author: James Gallagher <jgallagher@opendap.org>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// 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
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.

// (c) COPYRIGHT URI/MIT 1995-1999
// Please read the full copyright statement in the file COPYRIGHT_URI.
//
// Authors:
//      jhrg,jimg       James Gallagher <jgallagher@gso.uri.edu>

#ifdef _GNUG_
// #pragma implementation
#endif

#include "config_dap.h"

#include <string>
#include <algorithm>
#ifdef WIN32
#include <functional>
#endif

#include "Constructor.h"
#include "BTIterAdapter.h"

#include "debug.h"
#include "escaping.h"
#include "Error.h"
#include "InternalErr.h"

#ifdef TRACE_NEW
#include "trace_new.h"
#endif

using namespace std;

// Private member functions

void
Constructor::_duplicate(const Constructor &s)
{
}

// Public member functions

Constructor::Constructor(const string &n, const Type &t)
    : BaseType(n, t)
{
}

Constructor::Constructor(const Constructor &rhs) : BaseType(rhs)
{
}

Constructor::~Constructor()
{
}

Constructor &
Constructor::operator=(const Constructor &rhs)
{
    if (this == &rhs)
	return *this;

    dynamic_cast<BaseType &>(*this) = rhs; // run BaseType=

    _duplicate(rhs);

    return *this;
}

/** @name Pix interface; deprecated */
//@{
/** @brief Returns an index to the first variable in a Constructor instance.

    For a Structure, this returns the first variable, for a Sequence, it is
    the template of the variable in the first column.
*/
Pix
Constructor::first_var()
{
    if (_vars.empty())
	return 0;

    BTIterAdapter *i = new BTIterAdapter( _vars ) ;
    i->first() ;
    return i ;
}

/** @brief Increments the Constructor instance.
    This returns a pointer to the
    next ``column'' in the Constructor, not the next row. */
void
Constructor::next_var(Pix p)
{
    p.next() ;
}

/** @brief Returns a pointer to a Constructor member.
    This may be another Constructor. */
BaseType *
Constructor::var(Pix p)
{
    BTIterAdapter *i = (BTIterAdapter *)p.getIterator() ;
    if( i ) {
	return i->entry() ;
    }
    return 0 ;
}
//@}

/** Returns an iterator referencing the first structure element. */
Constructor::Vars_iter
Constructor::var_begin()
{
    return _vars.begin() ;
}

/** Returns an iterator referencing the end of the list of structure
    elements. Does not reference the last structure element. */
Constructor::Vars_iter
Constructor::var_end()
{
    return _vars.end() ;
}

/** Return the iterator for the \i ith variable.
    @param i the index
    @return The corresponding  Vars_iter */
Constructor::Vars_iter
Constructor::get_vars_iter(int i)
{
    return _vars.begin() + i;
}

void
Constructor::print_decl(ostream &os, string space, bool print_semi,
			bool constraint_info, bool constrained)
{
    if (constrained && !send_p())
	return;

    os << space << type_name() << " {" << endl;
    for (Vars_iter i = _vars.begin(); i != _vars.end(); i++)
    {
	(*i)->print_decl(os, space + "    ", true,
			 constraint_info, constrained);
    }
    os << space << "} " << id2www(name());

    if (constraint_info) {	// Used by test drivers only.
	if (send_p())
	    cout << ": Send True";
	else
	    cout << ": Send False";
    }

    if (print_semi)
	os << ";" << endl;
}

void
Constructor::print_decl(FILE *out, string space, bool print_semi,
			bool constraint_info, bool constrained)
{
    if (constrained && !send_p())
	return;

    fprintf( out, "%s%s {\n", space.c_str(), type_name().c_str() ) ;
    for (Vars_citer i = _vars.begin(); i != _vars.end(); i++)
    {
	(*i)->print_decl(out, space + "    ", true,
			 constraint_info, constrained);
    }
    fprintf( out, "%s} %s", space.c_str(), id2www( name() ).c_str() ) ;

    if (constraint_info) {	// Used by test drivers only.
	if (send_p())
	    cout << ": Send True";
	else
	    cout << ": Send False";
    }

    if (print_semi)
	fprintf( out, ";\n" ) ;
}

class PrintField : public unary_function<BaseType *, void> {
    FILE *d_out;
    string d_space;
    bool d_constrained;
public:
    PrintField(FILE *o, string s, bool c)
	: d_out(o), d_space(s), d_constrained(c) {}

    void operator()(BaseType *btp) {
	btp->print_xml(d_out, d_space, d_constrained);
    }
};

void
Constructor::print_xml(FILE *out, string space, bool constrained)
{
    bool has_attributes = false; // *** fix me
    bool has_variables = (var_begin() != var_end());

    fprintf(out, "%s<%s", space.c_str(), type_name().c_str());
    if (!name().empty())
	fprintf(out, " name=\"%s\"", id2xml(name()).c_str());

    if (has_attributes || has_variables) {
	fprintf(out, ">\n");

	get_attr_table().print_xml(out, space + "    ", constrained);

	for_each(var_begin(), var_end(),
		 PrintField(out, space + "    ", constrained));

	fprintf(out, "%s<%s/>\n", space.c_str(), type_name().c_str());
    }
    else {
	fprintf(out, "/>\n");
    }
}

/** True if the instance can be flattened and printed as a single table
    of values. For Arrays and Grids this is always false. For Structures
    and Sequences the conditions are more complex. The implementation
    provided by this class always returns false. Other classes should
    override this implementation.

    @todo Change the name to is_flattenable or something like that. 05/16/03
    jhrg

    @brief Check to see whether this variable can be printed simply.
    @return True if the instance can be printed as a single table of
    values, false otherwise. */
bool
Constructor::is_linear()
{
    return false;
}

// $Log: Constructor.cc,v $
// Revision 1.13  2004/07/19 07:25:42  rmorris
// #include <functional> for "unary_function" under win32.
//
// Revision 1.12  2004/07/07 21:08:47  jimg
// Merged with release-3-4-8FCS
//
// Revision 1.8.2.3  2004/07/02 20:41:51  jimg
// Removed (commented) the pragma interface/implementation lines. See
// the ChangeLog for more details. This fixes a build problem on HP/UX.
//
// Revision 1.11  2003/12/10 21:11:57  jimg
// Merge with 3.4. Some of the files contains erros (some tests fail). See
// the ChangeLog for information about fixes.
//
// Revision 1.10  2003/12/08 18:02:29  edavis
// Merge release-3-4 into trunk
//
// Revision 1.8.2.2  2003/09/06 22:37:50  jimg
// Updated the documentation.
//
// Revision 1.8.2.1  2003/06/05 20:15:25  jimg
// Removed many uses of strstream and replaced them with stringstream.
//
// Revision 1.9  2003/05/23 03:24:57  jimg
// Changes that add support for the DDX response. I've based this on Nathan
// Potter's work in the Java DAP software. At this point the code can
// produce a DDX from a DDS and it can merge attributes from a DAS into a
// DDS to produce a DDX fully loaded with attributes. Attribute aliases
// are not supported yet. I've also removed all traces of strstream in
// favor of stringstream. This code should no longer generate warnings
// about the use of deprecated headers.
//
// Revision 1.8  2003/04/22 19:40:27  jimg
// Merged with 3.3.1.
//
// Revision 1.7  2003/02/21 00:14:24  jimg
// Repaired copyright.
//
// Revision 1.6.2.1  2003/02/21 00:10:07  jimg
// Repaired copyright.
//
// Revision 1.6  2003/01/23 00:22:24  jimg
// Updated the copyright notice; this implementation of the DAP is
// copyrighted by OPeNDAP, Inc.
//
// Revision 1.5  2003/01/10 19:46:40  jimg
// Merged with code tagged release-3-2-10 on the release-3-2 branch. In many
// cases files were added on that branch (so they appear on the trunk for
// the first time).
//
// Revision 1.1.2.3  2002/08/08 06:54:56  jimg
// Changes for thread-safety. In many cases I found ugly places at the
// tops of files while looking for globals, et c., and I fixed them up
// (hopefully making them easier to read, ...). Only the files RCReader.cc
// and usage.cc actually use pthreads synchronization functions. In other
// cases I removed static objects where they were used for supposed
// improvements in efficiency which had never actually been verifiied (and
// which looked dubious).
//
// Revision 1.4  2002/06/18 15:36:24  tom
// Moved comments and edited to accommodate doxygen documentation-generator.
//
// Revision 1.3  2001/09/28 17:50:07  jimg
// Merged with 3.2.7.
//
// Revision 1.1.2.2  2001/09/25 20:35:28  jimg
// Added a default definition for is_linear().
//
// Revision 1.2  2001/06/15 23:49:01  jimg
// Merged with release-3-2-4.
//
// Revision 1.1.2.1  2001/06/05 16:04:39  jimg
// Created.
//
<commit_msg>Added accessors for the new reverse iterators. Also added a new method to access variables using an integer index.<commit_after>
// -*- mode: c++; c-basic-offset:4 -*-

// This file is part of libdap, A C++ implementation of the OPeNDAP Data
// Access Protocol.

// Copyright (c) 2002,2003 OPeNDAP, Inc.
// Author: James Gallagher <jgallagher@opendap.org>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// 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
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.

// (c) COPYRIGHT URI/MIT 1995-1999
// Please read the full copyright statement in the file COPYRIGHT_URI.
//
// Authors:
//      jhrg,jimg       James Gallagher <jgallagher@gso.uri.edu>

#ifdef _GNUG_
// #pragma implementation
#endif

#include "config_dap.h"

#include <string>
#include <algorithm>
#ifdef WIN32
#include <functional>
#endif

#include "Constructor.h"
#include "BTIterAdapter.h"

#include "debug.h"
#include "escaping.h"
#include "Error.h"
#include "InternalErr.h"

#ifdef TRACE_NEW
#include "trace_new.h"
#endif

using namespace std;

// Private member functions

void
Constructor::_duplicate(const Constructor &s)
{
}

// Public member functions

Constructor::Constructor(const string &n, const Type &t)
    : BaseType(n, t)
{
}

Constructor::Constructor(const Constructor &rhs) : BaseType(rhs)
{
}

Constructor::~Constructor()
{
}

Constructor &
Constructor::operator=(const Constructor &rhs)
{
    if (this == &rhs)
	return *this;

    dynamic_cast<BaseType &>(*this) = rhs; // run BaseType=

    _duplicate(rhs);

    return *this;
}

/** @name Pix interface; deprecated */
//@{
/** @brief Returns an index to the first variable in a Constructor instance.

    For a Structure, this returns the first variable, for a Sequence, it is
    the template of the variable in the first column.
*/
Pix
Constructor::first_var()
{
    if (_vars.empty())
	return 0;

    BTIterAdapter *i = new BTIterAdapter( _vars ) ;
    i->first() ;
    return i ;
}

/** @brief Increments the Constructor instance.
    This returns a pointer to the
    next ``column'' in the Constructor, not the next row. */
void
Constructor::next_var(Pix p)
{
    p.next() ;
}

/** @brief Returns a pointer to a Constructor member.
    This may be another Constructor. */
BaseType *
Constructor::var(Pix p)
{
    BTIterAdapter *i = (BTIterAdapter *)p.getIterator() ;
    if( i ) {
	return i->entry() ;
    }
    return 0 ;
}
//@}

/** Returns an iterator referencing the first structure element. */
Constructor::Vars_iter
Constructor::var_begin()
{
    return _vars.begin() ;
}

/** Returns an iterator referencing the end of the list of structure
    elements. Does not reference the last structure element. */
Constructor::Vars_iter
Constructor::var_end()
{
    return _vars.end() ;
}

/** Return a reverse iterator that references the last element. */
Constructor::Vars_riter
Constructor::var_rbegin()
{
    return _vars.rbegin();
}

/** Return a reverse iterator that references a point 'before' the first
    element. */
Constructor::Vars_riter
Constructor::var_rend()
{
    return _vars.rend();
}

/** Return the iterator for the \i ith variable.
    @param i the index
    @return The corresponding  Vars_iter */
Constructor::Vars_iter
Constructor::get_vars_iter(int i)
{
    return _vars.begin() + i;
}

/** Return the BaseType pointer for the \e ith variable.
    @param i This index
    @return The corresponding BaseType*. */
BaseType *
Constructor::get_var_index(int i)
{
    return *(_vars.begin() + i);
}

void
Constructor::print_decl(ostream &os, string space, bool print_semi,
			bool constraint_info, bool constrained)
{
    if (constrained && !send_p())
	return;

    os << space << type_name() << " {" << endl;
    for (Vars_iter i = _vars.begin(); i != _vars.end(); i++)
    {
	(*i)->print_decl(os, space + "    ", true,
			 constraint_info, constrained);
    }
    os << space << "} " << id2www(name());

    if (constraint_info) {	// Used by test drivers only.
	if (send_p())
	    cout << ": Send True";
	else
	    cout << ": Send False";
    }

    if (print_semi)
	os << ";" << endl;
}

void
Constructor::print_decl(FILE *out, string space, bool print_semi,
			bool constraint_info, bool constrained)
{
    if (constrained && !send_p())
	return;

    fprintf( out, "%s%s {\n", space.c_str(), type_name().c_str() ) ;
    for (Vars_citer i = _vars.begin(); i != _vars.end(); i++)
    {
	(*i)->print_decl(out, space + "    ", true,
			 constraint_info, constrained);
    }
    fprintf( out, "%s} %s", space.c_str(), id2www( name() ).c_str() ) ;

    if (constraint_info) {	// Used by test drivers only.
	if (send_p())
	    cout << ": Send True";
	else
	    cout << ": Send False";
    }

    if (print_semi)
	fprintf( out, ";\n" ) ;
}

class PrintField : public unary_function<BaseType *, void> {
    FILE *d_out;
    string d_space;
    bool d_constrained;
public:
    PrintField(FILE *o, string s, bool c)
	: d_out(o), d_space(s), d_constrained(c) {}

    void operator()(BaseType *btp) {
	btp->print_xml(d_out, d_space, d_constrained);
    }
};

void
Constructor::print_xml(FILE *out, string space, bool constrained)
{
    bool has_attributes = false; // *** fix me
    bool has_variables = (var_begin() != var_end());

    fprintf(out, "%s<%s", space.c_str(), type_name().c_str());
    if (!name().empty())
	fprintf(out, " name=\"%s\"", id2xml(name()).c_str());

    if (has_attributes || has_variables) {
	fprintf(out, ">\n");

	get_attr_table().print_xml(out, space + "    ", constrained);

	for_each(var_begin(), var_end(),
		 PrintField(out, space + "    ", constrained));

	fprintf(out, "%s<%s/>\n", space.c_str(), type_name().c_str());
    }
    else {
	fprintf(out, "/>\n");
    }
}

/** True if the instance can be flattened and printed as a single table
    of values. For Arrays and Grids this is always false. For Structures
    and Sequences the conditions are more complex. The implementation
    provided by this class always returns false. Other classes should
    override this implementation.

    @todo Change the name to is_flattenable or something like that. 05/16/03
    jhrg

    @brief Check to see whether this variable can be printed simply.
    @return True if the instance can be printed as a single table of
    values, false otherwise. */
bool
Constructor::is_linear()
{
    return false;
}

// $Log: Constructor.cc,v $
// Revision 1.14  2004/11/16 17:56:05  jimg
// Added accessors for the new reverse iterators. Also added a new method
// to access variables using an integer index.
//
// Revision 1.13  2004/07/19 07:25:42  rmorris
// #include <functional> for "unary_function" under win32.
//
// Revision 1.12  2004/07/07 21:08:47  jimg
// Merged with release-3-4-8FCS
//
// Revision 1.8.2.3  2004/07/02 20:41:51  jimg
// Removed (commented) the pragma interface/implementation lines. See
// the ChangeLog for more details. This fixes a build problem on HP/UX.
//
// Revision 1.11  2003/12/10 21:11:57  jimg
// Merge with 3.4. Some of the files contains erros (some tests fail). See
// the ChangeLog for information about fixes.
//
// Revision 1.10  2003/12/08 18:02:29  edavis
// Merge release-3-4 into trunk
//
// Revision 1.8.2.2  2003/09/06 22:37:50  jimg
// Updated the documentation.
//
// Revision 1.8.2.1  2003/06/05 20:15:25  jimg
// Removed many uses of strstream and replaced them with stringstream.
//
// Revision 1.9  2003/05/23 03:24:57  jimg
// Changes that add support for the DDX response. I've based this on Nathan
// Potter's work in the Java DAP software. At this point the code can
// produce a DDX from a DDS and it can merge attributes from a DAS into a
// DDS to produce a DDX fully loaded with attributes. Attribute aliases
// are not supported yet. I've also removed all traces of strstream in
// favor of stringstream. This code should no longer generate warnings
// about the use of deprecated headers.
//
// Revision 1.8  2003/04/22 19:40:27  jimg
// Merged with 3.3.1.
//
// Revision 1.7  2003/02/21 00:14:24  jimg
// Repaired copyright.
//
// Revision 1.6.2.1  2003/02/21 00:10:07  jimg
// Repaired copyright.
//
// Revision 1.6  2003/01/23 00:22:24  jimg
// Updated the copyright notice; this implementation of the DAP is
// copyrighted by OPeNDAP, Inc.
//
// Revision 1.5  2003/01/10 19:46:40  jimg
// Merged with code tagged release-3-2-10 on the release-3-2 branch. In many
// cases files were added on that branch (so they appear on the trunk for
// the first time).
//
// Revision 1.1.2.3  2002/08/08 06:54:56  jimg
// Changes for thread-safety. In many cases I found ugly places at the
// tops of files while looking for globals, et c., and I fixed them up
// (hopefully making them easier to read, ...). Only the files RCReader.cc
// and usage.cc actually use pthreads synchronization functions. In other
// cases I removed static objects where they were used for supposed
// improvements in efficiency which had never actually been verifiied (and
// which looked dubious).
//
// Revision 1.4  2002/06/18 15:36:24  tom
// Moved comments and edited to accommodate doxygen documentation-generator.
//
// Revision 1.3  2001/09/28 17:50:07  jimg
// Merged with 3.2.7.
//
// Revision 1.1.2.2  2001/09/25 20:35:28  jimg
// Added a default definition for is_linear().
//
// Revision 1.2  2001/06/15 23:49:01  jimg
// Merged with release-3-2-4.
//
// Revision 1.1.2.1  2001/06/05 16:04:39  jimg
// Created.
//
<|endoftext|>


<commit_before>
// -*- mode: c++; c-basic-offset:4 -*-

// This file is part of libdap, A C++ implementation of the OPeNDAP Data
// Access Protocol.

// Copyright (c) 2002,2003 OPeNDAP, Inc.
// Author: James Gallagher <jgallagher@opendap.org>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// 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
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.

// (c) COPYRIGHT URI/MIT 1995-1999
// Please read the full copyright statement in the file COPYRIGHT_URI.
//
// Authors:
//      jhrg,jimg       James Gallagher <jgallagher@gso.uri.edu>

#include "config.h"

#include <string>
#include <algorithm>
#include <functional>

#include "Constructor.h"
//#include "BTIterAdapter.h"

#include "debug.h"
#include "escaping.h"
#include "Error.h"
#include "InternalErr.h"

using namespace std;

// Private member functions

void
Constructor::_duplicate(const Constructor &)
{
}

// Public member functions

Constructor::Constructor(const string &n, const Type &t)
    : BaseType(n, t)
{
}

Constructor::Constructor(const Constructor &rhs) : BaseType(rhs)
{
}

Constructor::~Constructor()
{
}

Constructor &
Constructor::operator=(const Constructor &rhs)
{
    if (this == &rhs)
	return *this;

    dynamic_cast<BaseType &>(*this) = rhs; // run BaseType=

    _duplicate(rhs);

    return *this;
}

/** Returns an iterator referencing the first structure element. */
Constructor::Vars_iter
Constructor::var_begin()
{
    return _vars.begin() ;
}

/** Returns an iterator referencing the end of the list of structure
    elements. Does not reference the last structure element. */
Constructor::Vars_iter
Constructor::var_end()
{
    return _vars.end() ;
}

/** Return a reverse iterator that references the last element. */
Constructor::Vars_riter
Constructor::var_rbegin()
{
    return _vars.rbegin();
}

/** Return a reverse iterator that references a point 'before' the first
    element. */
Constructor::Vars_riter
Constructor::var_rend()
{
    return _vars.rend();
}

/** Return the iterator for the \e ith variable.
    @param i the index
    @return The corresponding  Vars_iter */
Constructor::Vars_iter
Constructor::get_vars_iter(int i)
{
    return _vars.begin() + i;
}

/** Return the BaseType pointer for the \e ith variable.
    @param i This index
    @return The corresponding BaseType*. */
BaseType *
Constructor::get_var_index(int i)
{
    return *(_vars.begin() + i);
}

void
Constructor::print_decl(FILE *out, string space, bool print_semi,
			bool constraint_info, bool constrained)
{
    if (constrained && !send_p())
	return;

    fprintf( out, "%s%s {\n", space.c_str(), type_name().c_str() ) ;
    for (Vars_citer i = _vars.begin(); i != _vars.end(); i++)
    {
	(*i)->print_decl(out, space + "    ", true,
			 constraint_info, constrained);
    }
    fprintf( out, "%s} %s", space.c_str(), id2www( name() ).c_str() ) ;

    if (constraint_info) {	// Used by test drivers only.
	if (send_p())
	    cout << ": Send True";
	else
	    cout << ": Send False";
    }

    if (print_semi)
	fprintf( out, ";\n" ) ;
}

class PrintField : public unary_function<BaseType *, void> {
    FILE *d_out;
    string d_space;
    bool d_constrained;
public:
    PrintField(FILE *o, string s, bool c)
	: d_out(o), d_space(s), d_constrained(c) {}

    void operator()(BaseType *btp) {
	btp->print_xml(d_out, d_space, d_constrained);
    }
};

void
Constructor::print_xml(FILE *out, string space, bool constrained)
{
    if (constrained && !send_p())
        return;

    bool has_attributes = false; // *** fix me
    bool has_variables = (var_begin() != var_end());

    fprintf(out, "%s<%s", space.c_str(), type_name().c_str());
    if (!name().empty())
	fprintf(out, " name=\"%s\"", id2xml(name()).c_str());

    if (has_attributes || has_variables) {
	fprintf(out, ">\n");

	get_attr_table().print_xml(out, space + "    ", constrained);

	for_each(var_begin(), var_end(),
		 PrintField(out, space + "    ", constrained));

	fprintf(out, "%s</%s>\n", space.c_str(), type_name().c_str());
    }
    else {
	fprintf(out, "/>\n");
    }
}

/** True if the instance can be flattened and printed as a single table
    of values. For Arrays and Grids this is always false. For Structures
    and Sequences the conditions are more complex. The implementation
    provided by this class always returns false. Other classes should
    override this implementation.

    @todo Change the name to is_flattenable or something like that. 05/16/03
    jhrg

    @brief Check to see whether this variable can be printed simply.
    @return True if the instance can be printed as a single table of
    values, false otherwise. */
bool
Constructor::is_linear()
{
    return false;
}
<commit_msg>Constructor: Added code to merge attributes into a constructor. This method is called from DDS.<commit_after>
// -*- mode: c++; c-basic-offset:4 -*-

// This file is part of libdap, A C++ implementation of the OPeNDAP Data
// Access Protocol.

// Copyright (c) 2002,2003 OPeNDAP, Inc.
// Author: James Gallagher <jgallagher@opendap.org>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// 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
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.

// (c) COPYRIGHT URI/MIT 1995-1999
// Please read the full copyright statement in the file COPYRIGHT_URI.
//
// Authors:
//      jhrg,jimg       James Gallagher <jgallagher@gso.uri.edu>

#include "config.h"

#include <string>
#include <algorithm>
#include <functional>

#define DODS_DEBUG

#include "Constructor.h"
#include "Grid.h"
//#include "BTIterAdapter.h"

#include "debug.h"
#include "escaping.h"
#include "Error.h"
#include "InternalErr.h"

using namespace std;

// Private member functions

void
Constructor::_duplicate(const Constructor &)
{
}

// Public member functions

Constructor::Constructor(const string &n, const Type &t)
    : BaseType(n, t)
{
}

Constructor::Constructor(const Constructor &rhs) : BaseType(rhs)
{
}

Constructor::~Constructor()
{
}

Constructor &
Constructor::operator=(const Constructor &rhs)
{
    if (this == &rhs)
	return *this;

    dynamic_cast<BaseType &>(*this) = rhs; // run BaseType=

    _duplicate(rhs);

    return *this;
}

/** Returns an iterator referencing the first structure element. */
Constructor::Vars_iter
Constructor::var_begin()
{
    return _vars.begin() ;
}

/** @brief Look for the parent of an HDF4 dimension attribute

    If this attribute container's name ends in the '_dim_?' suffix, look
    for the variable to which it's attributes should be bound: For an array,
    they should be held in a sub-table of the array; for a Structure or
    Sequence, I don't think the HDF4 handler ever makes these (since those
    types don't have 'dimension' in hdf-land);  and for a Grid, the attributes
    belong with the map variables.

    @note This method does check that the \e source really is an hdf4 dimension
    attribute.

    @param source The attribute container, an AttrTable::entry instance.
    @return the BaseType to which these attributes belong or null if none
    was found. */
BaseType *
Constructor::find_hdf4_dimension_attribute_home(AttrTable::entry *source)
{
    BaseType *btp;
    string::size_type i = source->name.find("_dim_");
    if (i != string::npos && (btp = var(source->name.substr(0, i)))) {
        if (btp->is_vector_type()) {
             return btp;
        }
        else if (btp->type() == dods_grid_c) {
            // For a Grid, the hdf4 handler uses _dim_n for the n-th Map
            // i+5 points to the character holding 'n'
            int n = atoi(source->name.substr(i+5).c_str());
            DBG(cerr << "Found a Grid (" << btp->name() << ") and "
                << source->name.substr(i) << ", extracted n: " << n << endl);
            return *(dynamic_cast<Grid&>(*btp).map_begin() + n);
        }
    }

    return 0;
}

/** Given an attribute container from a table, find or make a destination
    for its contents in the current constructor variable. */
AttrTable *
Constructor::find_matching_container(AttrTable::entry *source,
                                     BaseType **dest_variable)
{
    // The attribute entry 'source' must be a container
    if (source->type != Attr_container)
        throw InternalErr(__FILE__, __LINE__, "Constructor::find_matching_container");

    // Use the name of the attribute container 'source' to figure out where
    // to put its contents.
    BaseType *btp;
    if ((btp = var(source->name))) {
        // ... matches a variable name? Use var's table
        *dest_variable = btp;
        return &btp->get_attr_table();
    }
    // As more special-case attribute containers come to light, add clauses
    // here.
    else if ((btp = find_hdf4_dimension_attribute_home(source))) {
        // ... hdf4 dimension attribute? Make a sub table and use that.
        // btp can only be an Array or a Grid Map (which is an array)
        if (btp->get_parent()->type() == dods_grid_c) {
            DBG(cerr << "Found a Grid" << endl);
            *dest_variable = btp;
            return &btp->get_attr_table();
        }
        else { // must ba a plain Array
            string::size_type i = source->name.find("_dim_");
            string ext = source->name.substr(i+1);
            *dest_variable = btp;
            return btp->get_attr_table().append_container(ext);
        }
    }
    else {
        // ... otherwise assume it's a global attribute.
        AttrTable *at = get_attr_table().find_container(source->name);
        if (!at) {
            at = new AttrTable();       // Make a new global table if needed
            get_attr_table().append_container(at, source->name);
        }

        *dest_variable = 0;
        return at;
    }
}

/** Given an Attribute entry, scavenge attributes from it and load them into
    this object and the variables it contains. Assume that the caller has
    determined the table holds attributes pertinent to only this variable.

    @note This method is technically \e unnecessary because a server (or
    client) can easily add attributes directly using the DDS::get_attr_table
    or BaseType::get_attr_table methods and then poke values in using any
    of the methods AttrTable provides. This method exists to ease the
    transition to DDS objects which contain attribute information for the
    existing servers (Since they all make DAS objects separately from the
    DDS). They could be modified to use the same AttrTable methods but
    operate on the AttrTable instances in a DDS/BaseType instead of those in
    a DAS.

    @param at Get attribute information from this Attribute table. */
void
Constructor::transfer_attributes(AttrTable::entry * entry)
{
    DBG(cerr << "Constructor::transfer_attributes, variable: " << name() <<
        endl);
    DBG(cerr << "Working on the '" << entry->
        name << "' container." << endl);
    if (entry->type != Attr_container)
        throw InternalErr(__FILE__, __LINE__,
                          "Constructor::transfer_attributes");

    AttrTable *source = entry->attributes;
    BaseType *dest_variable = 0;
    AttrTable *dest = find_matching_container(entry, &dest_variable);

    // foreach source attribute in the das_i container
    AttrTable::Attr_iter source_p = source->attr_begin();
    while (source_p != source->attr_end()) {
        DBG(cerr << "Working on the '" << (*source_p)->
            name << "' attribute" << endl);

        if ((*source_p)->type == Attr_container) {
            if (dest_variable && dest_variable->is_constructor_type()) {
                dynamic_cast <Constructor & >(*dest_variable).transfer_attributes(*source_p);
            }
            else {
                dest->append_container(new AttrTable(*(*source_p)->attributes),
                                       (*source_p)->name);
            }
        } else {
            dest->append_attr(source->get_name(source_p),
                              source->get_type(source_p),
                              source->get_attr_vector(source_p));
        }

        ++source_p;
    }
}

/** Returns an iterator referencing the end of the list of structure
    elements. Does not reference the last structure element. */
Constructor::Vars_iter
Constructor::var_end()
{
    return _vars.end() ;
}

/** Return a reverse iterator that references the last element. */
Constructor::Vars_riter
Constructor::var_rbegin()
{
    return _vars.rbegin();
}

/** Return a reverse iterator that references a point 'before' the first
    element. */
Constructor::Vars_riter
Constructor::var_rend()
{
    return _vars.rend();
}

/** Return the iterator for the \e ith variable.
    @param i the index
    @return The corresponding  Vars_iter */
Constructor::Vars_iter
Constructor::get_vars_iter(int i)
{
    return _vars.begin() + i;
}

/** Return the BaseType pointer for the \e ith variable.
    @param i This index
    @return The corresponding BaseType*. */
BaseType *
Constructor::get_var_index(int i)
{
    return *(_vars.begin() + i);
}

void
Constructor::print_decl(FILE *out, string space, bool print_semi,
			bool constraint_info, bool constrained)
{
    if (constrained && !send_p())
	return;

    fprintf( out, "%s%s {\n", space.c_str(), type_name().c_str() ) ;
    for (Vars_citer i = _vars.begin(); i != _vars.end(); i++)
    {
	(*i)->print_decl(out, space + "    ", true,
			 constraint_info, constrained);
    }
    fprintf( out, "%s} %s", space.c_str(), id2www( name() ).c_str() ) ;

    if (constraint_info) {	// Used by test drivers only.
	if (send_p())
	    cout << ": Send True";
	else
	    cout << ": Send False";
    }

    if (print_semi)
	fprintf( out, ";\n" ) ;
}

class PrintField : public unary_function<BaseType *, void> {
    FILE *d_out;
    string d_space;
    bool d_constrained;
public:
    PrintField(FILE *o, string s, bool c)
	: d_out(o), d_space(s), d_constrained(c) {}

    void operator()(BaseType *btp) {
	btp->print_xml(d_out, d_space, d_constrained);
    }
};

void
Constructor::print_xml(FILE *out, string space, bool constrained)
{
    if (constrained && !send_p())
        return;

    bool has_attributes = false; // *** fix me
    bool has_variables = (var_begin() != var_end());

    fprintf(out, "%s<%s", space.c_str(), type_name().c_str());
    if (!name().empty())
	fprintf(out, " name=\"%s\"", id2xml(name()).c_str());

    if (has_attributes || has_variables) {
	fprintf(out, ">\n");

	get_attr_table().print_xml(out, space + "    ", constrained);

	for_each(var_begin(), var_end(),
		 PrintField(out, space + "    ", constrained));

	fprintf(out, "%s</%s>\n", space.c_str(), type_name().c_str());
    }
    else {
	fprintf(out, "/>\n");
    }
}

/** True if the instance can be flattened and printed as a single table
    of values. For Arrays and Grids this is always false. For Structures
    and Sequences the conditions are more complex. The implementation
    provided by this class always returns false. Other classes should
    override this implementation.

    @todo Change the name to is_flattenable or something like that. 05/16/03
    jhrg

    @brief Check to see whether this variable can be printed simply.
    @return True if the instance can be printed as a single table of
    values, false otherwise. */
bool
Constructor::is_linear()
{
    return false;
}
<|endoftext|>


<commit_before>// includes files
#include <gl\glew.h> ///< always include glew before glfw
#include "Window.h"  ///< include after glew, never before. that include glfw too
#include "EasyErrors.h"
#include "InputManager.h"
#include "GLProgram.h"
#include "Camera3D.h"
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm\gtx\rotate_vector.hpp>
#include <stdio.h>
#include <stdlib.h>
#include <chrono>
#include "FpsCounter.h"
#include "DrawBatch.h"
#include "Block.h"

int main()
{
	auto t_start = std::chrono::high_resolution_clock::now();

	const int width = 1600;
	const int height = 1200;

	if (!glfwInit())
	{
		Debug_Log("Failed to initialize GLFW\n");
	}
	// create a window
	Window m_window;
	m_window.init(width, height, "Doxel");

	// Set up glew
	glewExperimental = GL_TRUE;
	if (glewInit() != GLEW_OK)
	{
		Debug_Log("Failed to initialize GLEW\n");
	}

	// Set up the Input Manager
	InputManager m_inputManager;
	m_inputManager.init(m_window.getGlfwWindow());

	glm::vec3 cPos = glm::vec3(0);
	Camera3D m_camera;
	m_camera.init(cPos, 45.0f,m_window.getAspectRatio(),1.0, 10000);

	glEnable(GL_DEPTH_TEST);

	DrawBatch m_drawBatch;
	m_drawBatch.init(&m_camera);

	// compile shaders, add attribes and all that
	GLProgram m_glProgram;
	m_glProgram.loadShaders("Shaders/shader.vert", "Shaders/shader.frag");

	glm::mat4 model, projection, view;
	glm::vec3 mPos(0, 0, 0);

	projection = m_camera.getProjectionMatrix();
	m_glProgram.uploadUniformMatrix("projection", 1, projection, GL_FALSE);

	FpsCounter m_fpsCounter;
	glm::vec3 lightPos(0, 100, 100);

	//ChunkStuff
	ChunkManager m_chunkManager;
	m_chunkManager.init();

	m_fpsCounter.start();

	Color8 colors[8] {Color8(255, 255, 255, 255), Color8(255, 0, 0, 255), Color8(255, 255, 0, 255), Color8(255, 0, 255, 255), Color8(0, 255, 0, 255), Color8(125, 255, 0, 255), Color8(255, 50, 120, 255), Color8(0, 255, 120, 255) };
	// This is the game loop
	while (!m_window.shouldWindowClose())
	{

		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
		m_inputManager.update();
		m_camera.update();
		// update input
		// handle input from user
		if (m_inputManager.isKeyPressed(KEYS::ESC))
		{
			m_window.setWindowClose();
		}

		if (m_inputManager.isKeyPressed(KEYS::W) || m_inputManager.isKeyHeldDown(KEYS::W)) ///< FORWARD
		{
			m_camera.applyMovement(cMove::Forward);
		}
		if (m_inputManager.isKeyPressed(KEYS::S) || m_inputManager.isKeyHeldDown(KEYS::S)) ///< BACKWARD
		{
			m_camera.applyMovement(cMove::Backward);
		}
		if (m_inputManager.isKeyPressed(KEYS::A) || m_inputManager.isKeyHeldDown(KEYS::A)) ///< LEFT
		{
			m_camera.applyMovement(cMove::Left);
		}
		if (m_inputManager.isKeyPressed(KEYS::D) || m_inputManager.isKeyHeldDown(KEYS::D)) ///< RIGHT
		{
			m_camera.applyMovement(cMove::Right);
		}
		if (m_inputManager.isKeyPressed(KEYS::Z) || m_inputManager.isKeyHeldDown(KEYS::Z)) ///<UP
		{
			m_camera.applyMovement(cMove::Up);
		}
		if (m_inputManager.isKeyPressed(KEYS::X) || m_inputManager.isKeyHeldDown(KEYS::X))///< DOWN
		{
			m_camera.applyMovement(cMove::Down);
		}
		if (m_inputManager.isKeyPressed(KEYS::Q) || m_inputManager.isKeyHeldDown(KEYS::Q))///< rotate left
		{
			m_camera.applyMovement(cMove::Rotate_Left);
		}
		if (m_inputManager.isKeyPressed(KEYS::E) || m_inputManager.isKeyHeldDown(KEYS::E))///< rotate left
		{
			m_camera.applyMovement(cMove::Rotate_Right);
		}
		if (m_inputManager.isKeyPressed(KEYS::F) || m_inputManager.isKeyHeldDown(KEYS::F))///< rotate left
		{
			m_camera.applyMovement(cMove::Roll_Left);
		}
		if (m_inputManager.isKeyPressed(KEYS::G) || m_inputManager.isKeyHeldDown(KEYS::G))///< rotate left
		{
			m_camera.applyMovement(cMove::Roll_Right);
		}
		if (m_inputManager.isKeyPressed(KEYS::C) || m_inputManager.isKeyHeldDown(KEYS::C))///< rotate left
		{
			m_camera.applyMovement(cMove::Pitch_Up);
		}
		if (m_inputManager.isKeyPressed(KEYS::V) || m_inputManager.isKeyHeldDown(KEYS::V))///< rotate left
		{
			m_camera.applyMovement(cMove::Pitch_Down);
		}
		if (m_inputManager.isKeyPressed(KEYS::UP) || m_inputManager.isKeyHeldDown(KEYS::UP))
		{
			m_camera.increaseSpeed();
		}
		if (m_inputManager.isKeyPressed(KEYS::DOWN) || m_inputManager.isKeyHeldDown(KEYS::DOWN))
		{
			m_camera.decreaseSpeed();
		}
		if (m_inputManager.isKeyPressed(KEYS::SPACE))
		{
			m_camera.setPosition(glm::vec3(0));
			m_camera.setDirection(glm::vec3(1, 1, 0));
			m_camera.setUpDir(glm::vec3(0, 0, 1));
			m_camera.setSpeed(0.1f);
		}
		if (m_inputManager.isKeyPressed(KEYS::T))
		{
			m_chunkManager.setGenMethod(GEN_METHOD::SPHERE);
		}
		if (m_inputManager.isKeyPressed(KEYS::R))
		{
			m_chunkManager.setGenMethod(GEN_METHOD::RANDOM);
		}
		if (m_inputManager.isKeyPressed(KEYS::Y))
		{
			m_chunkManager.setGenMethod(GEN_METHOD::ALL);
		}

		auto t_now = std::chrono::high_resolution_clock::now();
		float time = std::chrono::duration_cast<std::chrono::duration<float>>(t_now - t_start).count();

		// Use the glProgram
//		m_glProgram.use();
		// UPLOAD THE CAMERA MATRIX AFTER YOU CALLED THE PROGRAM.
//		m_glProgram.uploadUnifromMatrix("view", 1, view, GL_FALSE);
//		m_glProgram.uploadUnifromMatrix("model", 1, model, GL_FALSE);

		glm::mat4 view = m_camera.getViewMatrix();
		glm::mat4 mvp = projection * view * model;

		glm::vec3 lightPos = glm::vec3(cosf(time / 2)* 100,0,sinf(time / 2)* 100);
	//	glm::vec3 lightPos = m_camera.getPosition() + glm::vec3(0, 0, 50);
		m_glProgram.uploadUniformMatrix("mvp", 1, mvp, GL_FALSE);
		m_glProgram.uploadUniformMatrix("m", 1, model, GL_FALSE);
		m_glProgram.uploadUniformMatrix("v", 1, view, GL_FALSE);
		m_glProgram.uploadUniformVector3("lightPosition_worldSpace", 1, lightPos);

		m_chunkManager.update(m_camera.getPosition());

		m_drawBatch.start();

		m_chunkManager.draw(&m_drawBatch);
		m_drawBatch.draw(glm::vec3(0, 0, -0.1), glm::vec3(CHUNK_SIZE * NUM_CHUNKS, CHUNK_SIZE * NUM_CHUNKS, EPSILON), Color8(255, 255, 255, 255), true);
		m_drawBatch.draw(lightPos, glm::vec3(10, 10, 10), Color8(255, 255, 255, 255));
		m_drawBatch.end();
		m_drawBatch.renderBatch();

	//	m_glProgram.unuse();

		// update the window
		m_window.update();

		m_fpsCounter.end();
	}
	//m_debugRenderer.dispose();
	//m_chunkManager.dispose();
	m_glProgram.deleteProgram();

	m_drawBatch.dispose();
	//Close the window
	m_chunkManager.dispose();
	m_window.dispose();

	glfwTerminate();
	return 0;
}
<commit_msg>removed some colors that do nothing<commit_after>// includes files
#include <gl\glew.h> ///< always include glew before glfw
#include "Window.h"  ///< include after glew, never before. that include glfw too
#include "EasyErrors.h"
#include "InputManager.h"
#include "GLProgram.h"
#include "Camera3D.h"
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm\gtx\rotate_vector.hpp>
#include <stdio.h>
#include <stdlib.h>
#include <chrono>
#include "FpsCounter.h"
#include "DrawBatch.h"
#include "Block.h"

int main()
{
	auto t_start = std::chrono::high_resolution_clock::now();

	const int width = 1600;
	const int height = 1200;

	if (!glfwInit())
	{
		Debug_Log("Failed to initialize GLFW\n");
	}
	// create a window
	Window m_window;
	m_window.init(width, height, "Doxel");

	// Set up glew
	glewExperimental = GL_TRUE;
	if (glewInit() != GLEW_OK)
	{
		Debug_Log("Failed to initialize GLEW\n");
	}

	// Set up the Input Manager
	InputManager m_inputManager;
	m_inputManager.init(m_window.getGlfwWindow());

	glm::vec3 cPos = glm::vec3(0);
	Camera3D m_camera;
	m_camera.init(cPos, 45.0f,m_window.getAspectRatio(),1.0, 10000);

	glEnable(GL_DEPTH_TEST);

	DrawBatch m_drawBatch;
	m_drawBatch.init(&m_camera);

	// compile shaders, add attribes and all that
	GLProgram m_glProgram;
	m_glProgram.loadShaders("Shaders/shader.vert", "Shaders/shader.frag");

	glm::mat4 model, projection, view;
	glm::vec3 mPos(0, 0, 0);

	projection = m_camera.getProjectionMatrix();
	m_glProgram.uploadUniformMatrix("projection", 1, projection, GL_FALSE);

	FpsCounter m_fpsCounter;
	glm::vec3 lightPos(0, 100, 100);

	//ChunkStuff
	ChunkManager m_chunkManager;
	m_chunkManager.init();

	m_fpsCounter.start();

	// This is the game loop
	while (!m_window.shouldWindowClose())
	{

		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
		m_inputManager.update();
		m_camera.update();
		// update input
		// handle input from user
		if (m_inputManager.isKeyPressed(KEYS::ESC))
		{
			m_window.setWindowClose();
		}

		if (m_inputManager.isKeyPressed(KEYS::W) || m_inputManager.isKeyHeldDown(KEYS::W)) ///< FORWARD
		{
			m_camera.applyMovement(cMove::Forward);
		}
		if (m_inputManager.isKeyPressed(KEYS::S) || m_inputManager.isKeyHeldDown(KEYS::S)) ///< BACKWARD
		{
			m_camera.applyMovement(cMove::Backward);
		}
		if (m_inputManager.isKeyPressed(KEYS::A) || m_inputManager.isKeyHeldDown(KEYS::A)) ///< LEFT
		{
			m_camera.applyMovement(cMove::Left);
		}
		if (m_inputManager.isKeyPressed(KEYS::D) || m_inputManager.isKeyHeldDown(KEYS::D)) ///< RIGHT
		{
			m_camera.applyMovement(cMove::Right);
		}
		if (m_inputManager.isKeyPressed(KEYS::Z) || m_inputManager.isKeyHeldDown(KEYS::Z)) ///<UP
		{
			m_camera.applyMovement(cMove::Up);
		}
		if (m_inputManager.isKeyPressed(KEYS::X) || m_inputManager.isKeyHeldDown(KEYS::X))///< DOWN
		{
			m_camera.applyMovement(cMove::Down);
		}
		if (m_inputManager.isKeyPressed(KEYS::Q) || m_inputManager.isKeyHeldDown(KEYS::Q))///< rotate left
		{
			m_camera.applyMovement(cMove::Rotate_Left);
		}
		if (m_inputManager.isKeyPressed(KEYS::E) || m_inputManager.isKeyHeldDown(KEYS::E))///< rotate left
		{
			m_camera.applyMovement(cMove::Rotate_Right);
		}
		if (m_inputManager.isKeyPressed(KEYS::F) || m_inputManager.isKeyHeldDown(KEYS::F))///< rotate left
		{
			m_camera.applyMovement(cMove::Roll_Left);
		}
		if (m_inputManager.isKeyPressed(KEYS::G) || m_inputManager.isKeyHeldDown(KEYS::G))///< rotate left
		{
			m_camera.applyMovement(cMove::Roll_Right);
		}
		if (m_inputManager.isKeyPressed(KEYS::C) || m_inputManager.isKeyHeldDown(KEYS::C))///< rotate left
		{
			m_camera.applyMovement(cMove::Pitch_Up);
		}
		if (m_inputManager.isKeyPressed(KEYS::V) || m_inputManager.isKeyHeldDown(KEYS::V))///< rotate left
		{
			m_camera.applyMovement(cMove::Pitch_Down);
		}
		if (m_inputManager.isKeyPressed(KEYS::UP) || m_inputManager.isKeyHeldDown(KEYS::UP))
		{
			m_camera.increaseSpeed();
		}
		if (m_inputManager.isKeyPressed(KEYS::DOWN) || m_inputManager.isKeyHeldDown(KEYS::DOWN))
		{
			m_camera.decreaseSpeed();
		}
		if (m_inputManager.isKeyPressed(KEYS::SPACE))
		{
			m_camera.setPosition(glm::vec3(0));
			m_camera.setDirection(glm::vec3(1, 1, 0));
			m_camera.setUpDir(glm::vec3(0, 0, 1));
			m_camera.setSpeed(0.1f);
		}
		if (m_inputManager.isKeyPressed(KEYS::T))
		{
			m_chunkManager.setGenMethod(GEN_METHOD::SPHERE);
		}
		if (m_inputManager.isKeyPressed(KEYS::R))
		{
			m_chunkManager.setGenMethod(GEN_METHOD::RANDOM);
		}
		if (m_inputManager.isKeyPressed(KEYS::Y))
		{
			m_chunkManager.setGenMethod(GEN_METHOD::ALL);
		}

		auto t_now = std::chrono::high_resolution_clock::now();
		float time = std::chrono::duration_cast<std::chrono::duration<float>>(t_now - t_start).count();

		// Use the glProgram
//		m_glProgram.use();
		// UPLOAD THE CAMERA MATRIX AFTER YOU CALLED THE PROGRAM.
//		m_glProgram.uploadUnifromMatrix("view", 1, view, GL_FALSE);
//		m_glProgram.uploadUnifromMatrix("model", 1, model, GL_FALSE);

		glm::mat4 view = m_camera.getViewMatrix();
		glm::mat4 mvp = projection * view * model;

		glm::vec3 lightPos = glm::vec3(cosf(time / 2)* 100,0,sinf(time / 2)* 100);
	//	glm::vec3 lightPos = m_camera.getPosition() + glm::vec3(0, 0, 50);
		m_glProgram.uploadUniformMatrix("mvp", 1, mvp, GL_FALSE);
		m_glProgram.uploadUniformMatrix("m", 1, model, GL_FALSE);
		m_glProgram.uploadUniformMatrix("v", 1, view, GL_FALSE);
		m_glProgram.uploadUniformVector3("lightPosition_worldSpace", 1, lightPos);

		m_chunkManager.update(m_camera.getPosition());

		m_drawBatch.start();

		m_chunkManager.draw(&m_drawBatch);
		m_drawBatch.draw(glm::vec3(0, 0, -0.1), glm::vec3(CHUNK_SIZE * NUM_CHUNKS, CHUNK_SIZE * NUM_CHUNKS, EPSILON), Color8(255, 255, 255, 255), true);
		m_drawBatch.draw(lightPos, glm::vec3(10, 10, 10), Color8(255, 255, 255, 255));
		m_drawBatch.end();
		m_drawBatch.renderBatch();

	//	m_glProgram.unuse();

		// update the window
		m_window.update();

		m_fpsCounter.end();
	}
	//m_debugRenderer.dispose();
	//m_chunkManager.dispose();
	m_glProgram.deleteProgram();

	m_drawBatch.dispose();
	//Close the window
	m_chunkManager.dispose();
	m_window.dispose();

	glfwTerminate();
	return 0;
}
<|endoftext|>


<commit_before>#include <cucumber-cpp/internal/connectors/wire/WireServer.hpp>

namespace cucumber {
namespace internal {

SocketServer::SocketServer(const ProtocolHandler *protocolHandler) :
    ios(),
    acceptor(ios),
    protocolHandler(protocolHandler) {
}

void SocketServer::listen(const port_type port) {
    tcp::endpoint endpoint(tcp::v4(), port);
    acceptor.open(endpoint.protocol());
    acceptor.set_option(tcp::acceptor::reuse_address(true));
    acceptor.bind(endpoint);
    acceptor.listen(1);
}

void SocketServer::acceptOnce() {
    tcp::iostream stream;
    acceptor.accept(*stream.rdbuf());
    processStream(stream);
}

void SocketServer::processStream(tcp::iostream &stream) {
    std::string request;
    while (getline(stream, request)) {
        stream << protocolHandler->handle(request) << std::endl << std::flush;
    }
}

}
}
<commit_msg>Fix compiler warning about member initializer order<commit_after>#include <cucumber-cpp/internal/connectors/wire/WireServer.hpp>

namespace cucumber {
namespace internal {

SocketServer::SocketServer(const ProtocolHandler *protocolHandler) :
    protocolHandler(protocolHandler),
    ios(),
    acceptor(ios) {
}

void SocketServer::listen(const port_type port) {
    tcp::endpoint endpoint(tcp::v4(), port);
    acceptor.open(endpoint.protocol());
    acceptor.set_option(tcp::acceptor::reuse_address(true));
    acceptor.bind(endpoint);
    acceptor.listen(1);
}

void SocketServer::acceptOnce() {
    tcp::iostream stream;
    acceptor.accept(*stream.rdbuf());
    processStream(stream);
}

void SocketServer::processStream(tcp::iostream &stream) {
    std::string request;
    while (getline(stream, request)) {
        stream << protocolHandler->handle(request) << std::endl << std::flush;
    }
}

}
}
<|endoftext|>


<commit_before>/*
 * RInterface.hpp
 *
 * Copyright (C) 2009-12 by RStudio, Inc.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#ifndef R_INTERFACE_HPP
#define R_INTERFACE_HPP

#include <string>
#include <setjmp.h>

#ifdef _WIN32

#include <R_ext/Boolean.h>
#include <R_ext/RStartup.h>

extern "C" void R_RestoreGlobalEnvFromFile(const char *, Rboolean);
extern "C" void R_SaveGlobalEnvToFile(const char *);
extern "C" void R_Suicide(const char *);
extern "C" char *R_HomeDir(void);
extern "C" void Rf_jump_to_toplevel(void);
extern "C" void Rf_onintr(void);
#define R_ClearerrConsole void
extern "C" void R_FlushConsole();
extern "C" int R_SignalHandlers;
extern "C" void run_Rmainloop();
extern "C" void Rf_mainloop(void);
extern "C" void* R_GlobalContext;

typedef struct SEXPREC *SEXP;

#else

#define R_INTERFACE_PTRS 1
#include <Rinterface.h>

#endif

#ifdef _WIN32
// on Windows platforms, use a manual definition of sigjmp_buf that corresponds
// to how R lays out the structure in memory

typedef struct
{
  jmp_buf buf;
  int sigmask;
  int savedmask;
}
sigjmp_buf[1];
#endif

typedef struct RCNTXT {
    struct RCNTXT *nextcontext;
    int callflag;
    sigjmp_buf cjmpbuf;
    int cstacktop;
    int evaldepth;
    SEXP promargs;
    SEXP callfun;
    SEXP sysparent;
    SEXP call;
    SEXP cloenv;
    SEXP conexit;
    void (*cend)(void *);
    void *cenddata;
    void *vmax;
    int intsusp;
    SEXP handlerstack;
    SEXP restartstack;
    struct RPRSTACK *prstack;
    SEXP *nodestack;
#ifdef BC_INT_STACK
    IStackval *intstack;
#endif
    SEXP srcref;
} RCNTXT, *context;

enum {
    CTXT_TOPLEVEL = 0,
    CTXT_NEXT	  = 1,
    CTXT_BREAK	  = 2,
    CTXT_LOOP	  = 3,
    CTXT_FUNCTION = 4,
    CTXT_CCODE	  = 8,
    CTXT_RETURN	  = 12,
    CTXT_BROWSER  = 16,
    CTXT_GENERIC  = 20,
    CTXT_RESTART  = 32,
    CTXT_BUILTIN  = 64
};

namespace r {

inline RCNTXT* getGlobalContext()
{
   return static_cast<RCNTXT*>(R_GlobalContext);
}

} // namespace r

#endif // R_INTERFACE_HPP

<commit_msg>put debugger types in anonymous namespace (prevent gcc 4.9 warning)<commit_after>/*
 * RInterface.hpp
 *
 * Copyright (C) 2009-12 by RStudio, Inc.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#ifndef R_INTERFACE_HPP
#define R_INTERFACE_HPP

#include <string>
#include <setjmp.h>

#ifdef _WIN32

#include <R_ext/Boolean.h>
#include <R_ext/RStartup.h>

extern "C" void R_RestoreGlobalEnvFromFile(const char *, Rboolean);
extern "C" void R_SaveGlobalEnvToFile(const char *);
extern "C" void R_Suicide(const char *);
extern "C" char *R_HomeDir(void);
extern "C" void Rf_jump_to_toplevel(void);
extern "C" void Rf_onintr(void);
#define R_ClearerrConsole void
extern "C" void R_FlushConsole();
extern "C" int R_SignalHandlers;
extern "C" void run_Rmainloop();
extern "C" void Rf_mainloop(void);
extern "C" void* R_GlobalContext;

typedef struct SEXPREC *SEXP;

#else

#define R_INTERFACE_PTRS 1
#include <Rinterface.h>

#endif

#ifdef _WIN32
// on Windows platforms, use a manual definition of sigjmp_buf that corresponds
// to how R lays out the structure in memory

namespace {

typedef struct
{
  jmp_buf buf;
  int sigmask;
  int savedmask;
}
sigjmp_buf[1];
#endif

typedef struct RCNTXT {
    struct RCNTXT *nextcontext;
    int callflag;
    sigjmp_buf cjmpbuf;
    int cstacktop;
    int evaldepth;
    SEXP promargs;
    SEXP callfun;
    SEXP sysparent;
    SEXP call;
    SEXP cloenv;
    SEXP conexit;
    void (*cend)(void *);
    void *cenddata;
    void *vmax;
    int intsusp;
    SEXP handlerstack;
    SEXP restartstack;
    struct RPRSTACK *prstack;
    SEXP *nodestack;
#ifdef BC_INT_STACK
    IStackval *intstack;
#endif
    SEXP srcref;
} RCNTXT, *context;

enum {
    CTXT_TOPLEVEL = 0,
    CTXT_NEXT	  = 1,
    CTXT_BREAK	  = 2,
    CTXT_LOOP	  = 3,
    CTXT_FUNCTION = 4,
    CTXT_CCODE	  = 8,
    CTXT_RETURN	  = 12,
    CTXT_BROWSER  = 16,
    CTXT_GENERIC  = 20,
    CTXT_RESTART  = 32,
    CTXT_BUILTIN  = 64
};

} // anonymous namespace

namespace r {

inline RCNTXT* getGlobalContext()
{
   return static_cast<RCNTXT*>(R_GlobalContext);
}

} // namespace r

#endif // R_INTERFACE_HPP

<|endoftext|>


<commit_before>#include "SkColorPriv.h"
#include "SkTableColorFilter.h"
#include "SkUnPreMultiply.h"

class SkTable_ColorFilter : public SkColorFilter {
public:
    SkTable_ColorFilter(const uint8_t tableA[], const uint8_t tableR[],
                        const uint8_t tableG[], const uint8_t tableB[]) {
        fFlags = 0;
        uint8_t* dst = fStorage;
        if (tableA) {
            memcpy(dst, tableA, 256);
            dst += 256;
            fFlags |= kA_Flag;
        }
        if (tableR) {
            memcpy(dst, tableR, 256);
            dst += 256;
            fFlags |= kR_Flag;
        }
        if (tableG) {
            memcpy(dst, tableG, 256);
            dst += 256;
            fFlags |= kG_Flag;
        }
        if (tableB) {
            memcpy(dst, tableB, 256);
            fFlags |= kB_Flag;
        }
    }

    virtual void filterSpan(const SkPMColor src[], int count,
                            SkPMColor dst[]) SK_OVERRIDE;
    virtual void flatten(SkFlattenableWriteBuffer&) SK_OVERRIDE;
    virtual Factory getFactory() SK_OVERRIDE;

    static SkFlattenable* CreateProc(SkFlattenableReadBuffer& buffer) {
        return SkNEW_ARGS(SkTable_ColorFilter, (buffer));
    }

protected:
    SkTable_ColorFilter(SkFlattenableReadBuffer& buffer);

private:
    enum {
        kA_Flag = 1 << 0,
        kR_Flag = 1 << 1,
        kG_Flag = 1 << 2,
        kB_Flag = 1 << 3,
    };
    uint8_t fStorage[256 * 4];
    unsigned fFlags;

    typedef SkColorFilter INHERITED;
};

static const uint8_t gIdentityTable[] = {
    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
    0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
    0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
    0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F,
    0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
    0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F,
    0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
    0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F,
    0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
    0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F,
    0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
    0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F,
    0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67,
    0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F,
    0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77,
    0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F,
    0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
    0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x8F,
    0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
    0x98, 0x99, 0x9A, 0x9B, 0x9C, 0x9D, 0x9E, 0x9F,
    0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7,
    0xA8, 0xA9, 0xAA, 0xAB, 0xAC, 0xAD, 0xAE, 0xAF,
    0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7,
    0xB8, 0xB9, 0xBA, 0xBB, 0xBC, 0xBD, 0xBE, 0xBF,
    0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7,
    0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF,
    0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7,
    0xD8, 0xD9, 0xDA, 0xDB, 0xDC, 0xDD, 0xDE, 0xDF,
    0xE0, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7,
    0xE8, 0xE9, 0xEA, 0xEB, 0xEC, 0xED, 0xEE, 0xEF,
    0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7,
    0xF8, 0xF9, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0xFF
};

void SkTable_ColorFilter::filterSpan(const SkPMColor src[], int count,
                                     SkPMColor dst[]) {
    const uint8_t* table = fStorage;
    const uint8_t* tableA = gIdentityTable;
    const uint8_t* tableR = gIdentityTable;
    const uint8_t* tableG = gIdentityTable;
    const uint8_t* tableB = gIdentityTable;
    if (fFlags & kA_Flag) {
        tableA = table; table += 256;
    }
    if (fFlags & kR_Flag) {
        tableR = table; table += 256;
    }
    if (fFlags & kG_Flag) {
        tableG = table; table += 256;
    }
    if (fFlags & kB_Flag) {
        tableB = table;
    }

    const SkUnPreMultiply::Scale* scaleTable = SkUnPreMultiply::GetScaleTable();
    for (int i = 0; i < count; ++i) {
        SkPMColor c = src[i];
        unsigned a, r, g, b;
        if (0 == c) {
            a = r = g = b = 0;
        } else {
            a = SkGetPackedA32(c);
            r = SkGetPackedR32(c);
            g = SkGetPackedG32(c);
            b = SkGetPackedB32(c);

            if (a < 255) {
                SkUnPreMultiply::Scale scale = scaleTable[a];
                r = SkUnPreMultiply::ApplyScale(scale, r);
                g = SkUnPreMultiply::ApplyScale(scale, g);
                b = SkUnPreMultiply::ApplyScale(scale, b);
            }
        }
        dst[i] = SkPremultiplyARGBInline(tableA[a], tableR[r],
                                         tableG[g], tableB[b]);
    }
}

SkFlattenable::Factory SkTable_ColorFilter::getFactory() {
    return CreateProc;
}

static const uint8_t gCountNibBits[] = {
    0, 1, 1, 2,
    1, 2, 2, 3,
    1, 2, 2, 3,
    2, 3, 3, 4
};

#include "SkPackBits.h"

void SkTable_ColorFilter::flatten(SkFlattenableWriteBuffer& buffer) {
    this->INHERITED::flatten(buffer);

    uint8_t storage[5*256];
    int count = gCountNibBits[fFlags & 0xF];
    size_t size = SkPackBits::Pack8(fStorage, count * 256, storage);
    SkASSERT(size <= sizeof(storage));

//    SkDebugf("raw %d packed %d\n", count * 256, size);

    buffer.writeInt(fFlags);
    buffer.writeInt(size);
    buffer.write(storage, size);
}

SkTable_ColorFilter::SkTable_ColorFilter(SkFlattenableReadBuffer& buffer) : INHERITED(buffer) {
    uint8_t storage[5*256];

    fFlags = buffer.readInt();
    size_t size = buffer.readInt();
    buffer.read(storage, size);

    size_t raw = SkPackBits::Unpack8(storage, size, fStorage);

    SkASSERT(raw <= sizeof(fStorage));
    size_t count = gCountNibBits[fFlags & 0xF];
    SkASSERT(raw == count * 256);
}

///////////////////////////////////////////////////////////////////////////////

#ifdef SK_CPU_BENDIAN
#else
    #define SK_A32_INDEX    (3 - (SK_A32_SHIFT >> 3))
    #define SK_R32_INDEX    (3 - (SK_R32_SHIFT >> 3))
    #define SK_G32_INDEX    (3 - (SK_G32_SHIFT >> 3))
    #define SK_B32_INDEX    (3 - (SK_B32_SHIFT >> 3))
#endif

///////////////////////////////////////////////////////////////////////////////

SkColorFilter* SkTableColorFilter::Create(const uint8_t table[256]) {
    return SkNEW_ARGS(SkTable_ColorFilter, (table, table, table, table));
}

SkColorFilter* SkTableColorFilter::CreateARGB(const uint8_t tableA[256],
                                              const uint8_t tableR[256],
                                              const uint8_t tableG[256],
                                              const uint8_t tableB[256]) {
    return SkNEW_ARGS(SkTable_ColorFilter, (tableA, tableR, tableG, tableB));
}
<commit_msg>override asComponentTable()<commit_after>#include "SkColorPriv.h"
#include "SkTableColorFilter.h"
#include "SkUnPreMultiply.h"

class SkTable_ColorFilter : public SkColorFilter {
public:
    SkTable_ColorFilter(const uint8_t tableA[], const uint8_t tableR[],
                        const uint8_t tableG[], const uint8_t tableB[]) {
        fBitmap = NULL;
        fFlags = 0;

        uint8_t* dst = fStorage;
        if (tableA) {
            memcpy(dst, tableA, 256);
            dst += 256;
            fFlags |= kA_Flag;
        }
        if (tableR) {
            memcpy(dst, tableR, 256);
            dst += 256;
            fFlags |= kR_Flag;
        }
        if (tableG) {
            memcpy(dst, tableG, 256);
            dst += 256;
            fFlags |= kG_Flag;
        }
        if (tableB) {
            memcpy(dst, tableB, 256);
            fFlags |= kB_Flag;
        }
    }

    virtual bool asComponentTable(SkBitmap* table) SK_OVERRIDE;

    virtual void filterSpan(const SkPMColor src[], int count,
                            SkPMColor dst[]) SK_OVERRIDE;
    virtual void flatten(SkFlattenableWriteBuffer&) SK_OVERRIDE;
    virtual Factory getFactory() SK_OVERRIDE;

    static SkFlattenable* CreateProc(SkFlattenableReadBuffer& buffer) {
        return SkNEW_ARGS(SkTable_ColorFilter, (buffer));
    }

protected:
    SkTable_ColorFilter(SkFlattenableReadBuffer& buffer);

private:
    SkBitmap* fBitmap;

    enum {
        kA_Flag = 1 << 0,
        kR_Flag = 1 << 1,
        kG_Flag = 1 << 2,
        kB_Flag = 1 << 3,
    };
    uint8_t fStorage[256 * 4];
    unsigned fFlags;

    typedef SkColorFilter INHERITED;
};

static const uint8_t gIdentityTable[] = {
    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
    0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
    0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
    0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F,
    0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
    0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F,
    0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
    0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F,
    0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
    0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F,
    0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
    0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F,
    0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67,
    0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F,
    0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77,
    0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F,
    0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
    0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x8F,
    0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
    0x98, 0x99, 0x9A, 0x9B, 0x9C, 0x9D, 0x9E, 0x9F,
    0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7,
    0xA8, 0xA9, 0xAA, 0xAB, 0xAC, 0xAD, 0xAE, 0xAF,
    0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7,
    0xB8, 0xB9, 0xBA, 0xBB, 0xBC, 0xBD, 0xBE, 0xBF,
    0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7,
    0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF,
    0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7,
    0xD8, 0xD9, 0xDA, 0xDB, 0xDC, 0xDD, 0xDE, 0xDF,
    0xE0, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7,
    0xE8, 0xE9, 0xEA, 0xEB, 0xEC, 0xED, 0xEE, 0xEF,
    0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7,
    0xF8, 0xF9, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0xFF
};

void SkTable_ColorFilter::filterSpan(const SkPMColor src[], int count,
                                     SkPMColor dst[]) {
    const uint8_t* table = fStorage;
    const uint8_t* tableA = gIdentityTable;
    const uint8_t* tableR = gIdentityTable;
    const uint8_t* tableG = gIdentityTable;
    const uint8_t* tableB = gIdentityTable;
    if (fFlags & kA_Flag) {
        tableA = table; table += 256;
    }
    if (fFlags & kR_Flag) {
        tableR = table; table += 256;
    }
    if (fFlags & kG_Flag) {
        tableG = table; table += 256;
    }
    if (fFlags & kB_Flag) {
        tableB = table;
    }

    const SkUnPreMultiply::Scale* scaleTable = SkUnPreMultiply::GetScaleTable();
    for (int i = 0; i < count; ++i) {
        SkPMColor c = src[i];
        unsigned a, r, g, b;
        if (0 == c) {
            a = r = g = b = 0;
        } else {
            a = SkGetPackedA32(c);
            r = SkGetPackedR32(c);
            g = SkGetPackedG32(c);
            b = SkGetPackedB32(c);

            if (a < 255) {
                SkUnPreMultiply::Scale scale = scaleTable[a];
                r = SkUnPreMultiply::ApplyScale(scale, r);
                g = SkUnPreMultiply::ApplyScale(scale, g);
                b = SkUnPreMultiply::ApplyScale(scale, b);
            }
        }
        dst[i] = SkPremultiplyARGBInline(tableA[a], tableR[r],
                                         tableG[g], tableB[b]);
    }
}

SkFlattenable::Factory SkTable_ColorFilter::getFactory() {
    return CreateProc;
}

static const uint8_t gCountNibBits[] = {
    0, 1, 1, 2,
    1, 2, 2, 3,
    1, 2, 2, 3,
    2, 3, 3, 4
};

#include "SkPackBits.h"

void SkTable_ColorFilter::flatten(SkFlattenableWriteBuffer& buffer) {
    this->INHERITED::flatten(buffer);

    uint8_t storage[5*256];
    int count = gCountNibBits[fFlags & 0xF];
    size_t size = SkPackBits::Pack8(fStorage, count * 256, storage);
    SkASSERT(size <= sizeof(storage));

//    SkDebugf("raw %d packed %d\n", count * 256, size);

    buffer.writeInt(fFlags);
    buffer.writeInt(size);
    buffer.write(storage, size);
}

SkTable_ColorFilter::SkTable_ColorFilter(SkFlattenableReadBuffer& buffer) : INHERITED(buffer) {
    fBitmap = NULL;

    uint8_t storage[5*256];

    fFlags = buffer.readInt();
    size_t size = buffer.readInt();
    buffer.read(storage, size);

    size_t raw = SkPackBits::Unpack8(storage, size, fStorage);

    SkASSERT(raw <= sizeof(fStorage));
    size_t count = gCountNibBits[fFlags & 0xF];
    SkASSERT(raw == count * 256);
}

bool SkTable_ColorFilter::asComponentTable(SkBitmap* table) {
    if (table) {
        if (NULL == fBitmap) {
            fBitmap = new SkBitmap;
            fBitmap->setConfig(SkBitmap::kA8_Config, 256, 4, 256);
            fBitmap->allocPixels();
            memcpy(fBitmap->getAddr8(0, 0), fStorage, 256 * 4);
        }
        *table = *fBitmap;
    }
    return true;
}

///////////////////////////////////////////////////////////////////////////////

#ifdef SK_CPU_BENDIAN
#else
    #define SK_A32_INDEX    (3 - (SK_A32_SHIFT >> 3))
    #define SK_R32_INDEX    (3 - (SK_R32_SHIFT >> 3))
    #define SK_G32_INDEX    (3 - (SK_G32_SHIFT >> 3))
    #define SK_B32_INDEX    (3 - (SK_B32_SHIFT >> 3))
#endif

///////////////////////////////////////////////////////////////////////////////

SkColorFilter* SkTableColorFilter::Create(const uint8_t table[256]) {
    return SkNEW_ARGS(SkTable_ColorFilter, (table, table, table, table));
}

SkColorFilter* SkTableColorFilter::CreateARGB(const uint8_t tableA[256],
                                              const uint8_t tableR[256],
                                              const uint8_t tableG[256],
                                              const uint8_t tableB[256]) {
    return SkNEW_ARGS(SkTable_ColorFilter, (tableA, tableR, tableG, tableB));
}
<|endoftext|>


<commit_before>#ifdef EMSCRIPTEN
  #include <emscripten.h>
#endif
#include <iostream>
#include <SDL/SDL.h>

using namespace std;

// Native GBC display info
const int NATIVE_WIDTH   = 160;
const int NATIVE_HEIGHT  = 144;

int game_w;
int game_h;
int pixel_size_w = 5;
int pixel_size_h = 5;
bool keep_ratio = true;

// Map
Uint32 pixels_map[NATIVE_WIDTH][NATIVE_HEIGHT] = { { 0 } };
Uint32 pixels_map_actual[NATIVE_WIDTH][NATIVE_HEIGHT] = { { 1 } };

// SDL Variables
int bpp = 32;
int flags = SDL_HWSURFACE | SDL_RESIZABLE | SDL_DOUBLEBUF;
SDL_Surface* screen;
SDL_Surface* window;

/**
 * Update game dimensions
 */
void resize(int w, int h) {
    game_w = w;
    game_h = h;

    int new_pixel_size_w = game_w / NATIVE_WIDTH;
    int new_pixel_size_h = game_h / NATIVE_HEIGHT;

    if (!keep_ratio) {
        pixel_size_w = new_pixel_size_w;
        pixel_size_h = new_pixel_size_h;
    }
    else {
        pixel_size_w = min(new_pixel_size_w, new_pixel_size_h);
        pixel_size_h = pixel_size_w;
    }
}

/**
 * Draw a big pixel
 */
void drawPixel(int x, int y, Uint32 color)
{
    int container_width = game_w;
    int contained_width = NATIVE_WIDTH * pixel_size_w;
    int container_height = game_h;
    int contained_height = NATIVE_HEIGHT * pixel_size_h;

    int offset_x = (int)(((float)container_width / 2) - ((float)contained_width / 2));
    int offset_y = (int)(((float)container_height / 2) - ((float)contained_height / 2));

    x = x * pixel_size_w + offset_x;
    y = y * pixel_size_h + offset_y;

    SDL_Rect rect = { x, y, pixel_size_w, pixel_size_h };
    SDL_FillRect(window, &rect, color);
}

/**
 * Draw next frame
 */
void drawScreen(bool force = false)
{
    //TODO: control FPS with emscripten
    SDL_Flip(window);

    for (size_t i = 0; i < NATIVE_WIDTH; i++) {
        for (size_t j = 0; j < NATIVE_HEIGHT; j++) {
            if (pixels_map[i][j] != pixels_map_actual[i][j] || force) {
                pixels_map_actual[i][j] = pixels_map[i][j];
                drawPixel(i, j, pixels_map[i][j]);
            }
        }
    }
}

void processEvents()
{
    SDL_Event event;

    while(SDL_PollEvent(&event)) {
        switch(event.type) {
            case SDL_QUIT:
                exit(EXIT_SUCCESS);
                break;
            case SDL_VIDEORESIZE:
                SDL_FreeSurface(screen);
                screen = SDL_SetVideoMode(event.resize.w, event.resize.h, bpp,
                                          flags);
                resize(event.resize.w, event.resize.h);
                drawScreen(true);
        }
    }
}

/**
 * One iteration of the main loop
 */
void oneIteration()
{
    processEvents();
    drawScreen();
}

/**
 * Entry point
 */
int main(int argc, char** argv)
{
    #ifndef EMSCRIPTEN
        atexit(SDL_Quit);
    #endif

    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        cout << "Video initialization failed: " << SDL_GetError() << endl;
        exit(EXIT_FAILURE);
    }

    const SDL_VideoInfo* screen_info = SDL_GetVideoInfo();
    int screen_width  = screen_info->current_w / 2;
    int screen_height = screen_info->current_h / 2;

    #ifdef EMSCRIPTEN
        screen_width  = screen_info->current_w;
        screen_height = screen_info->current_h;
    #endif

    screen = SDL_SetVideoMode(screen_width, screen_height, bpp, flags);
    if (screen == NULL) {
        cout << "Video mode set failed: " << SDL_GetError() << endl;
        exit(EXIT_SUCCESS);
    }
    SDL_WM_SetCaption("gbcEmulator", NULL);

    window = SDL_GetVideoSurface();
    resize(window->w, window->h);

    // Generate pixels
    srand (time(NULL));
    for (size_t i = 0; i < NATIVE_WIDTH; i++) {
        for (size_t j = 0; j < NATIVE_HEIGHT; j++) {
            pixels_map[i][j] = SDL_MapRGB(window->format, rand() % 256, rand() % 256, rand() % 256);
        }
    }

    #ifdef EMSCRIPTEN
        emscripten_set_main_loop(oneIteration, 0, 1);
    #else
        while(1) {
            oneIteration();
            //60 FPS
            SDL_Delay(16);
        }

        SDL_Quit();
    #endif

    return EXIT_SUCCESS;
}
<commit_msg>Change drawscreen routine<commit_after>#ifdef EMSCRIPTEN
  #include <emscripten.h>
#endif
#include <iostream>
#include <SDL/SDL.h>

using namespace std;

// Native GBC display info
const int NATIVE_WIDTH   = 160;
const int NATIVE_HEIGHT  = 144;

int game_w;
int game_h;
int pixel_size_w = 5;
int pixel_size_h = 5;
bool keep_ratio = true;

// Map
Uint32 pixels_map[NATIVE_WIDTH][NATIVE_HEIGHT] = { { 0 } };
Uint32 pixels_map_actual[NATIVE_WIDTH][NATIVE_HEIGHT] = { { 1 } };

// SDL Variables
int bpp = 32;
int flags = SDL_HWSURFACE | SDL_RESIZABLE | SDL_DOUBLEBUF;
SDL_Surface* screen;
SDL_Surface* window;

/**
 * Update game dimensions
 */
void resize(int w, int h) {
    game_w = w;
    game_h = h;

    int new_pixel_size_w = game_w / NATIVE_WIDTH;
    int new_pixel_size_h = game_h / NATIVE_HEIGHT;

    if (!keep_ratio) {
        pixel_size_w = new_pixel_size_w;
        pixel_size_h = new_pixel_size_h;
    }
    else {
        pixel_size_w = min(new_pixel_size_w, new_pixel_size_h);
        pixel_size_h = pixel_size_w;
    }
}

/**
 * Draw a big pixel
 */
void drawPixel(int x, int y, Uint32 color)
{
    int container_width = game_w;
    int contained_width = NATIVE_WIDTH * pixel_size_w;
    int container_height = game_h;
    int contained_height = NATIVE_HEIGHT * pixel_size_h;

    int offset_x = (int)(((float)container_width / 2) - ((float)contained_width / 2));
    int offset_y = (int)(((float)container_height / 2) - ((float)contained_height / 2));

    x = x * pixel_size_w + offset_x;
    y = y * pixel_size_h + offset_y;

    SDL_Rect rect = { x, y, pixel_size_w, pixel_size_h };
    SDL_FillRect(window, &rect, color);
}

/**
 * Draw next frame
 */
void drawScreen()
{
    for (size_t i = 0; i < NATIVE_WIDTH; i++) {
        for (size_t j = 0; j < NATIVE_HEIGHT; j++) {
            pixels_map_actual[i][j] = pixels_map[i][j];
            drawPixel(i, j, pixels_map[i][j]);
        }
    }
}

void processEvents()
{
    SDL_Event event;

    while(SDL_PollEvent(&event)) {
        switch(event.type) {
            case SDL_QUIT:
                exit(EXIT_SUCCESS);
                break;
            case SDL_VIDEORESIZE:
                SDL_FreeSurface(screen);
                screen = SDL_SetVideoMode(event.resize.w, event.resize.h, bpp,
                                          flags);
                resize(event.resize.w, event.resize.h);
                drawScreen();
        }
    }
}

/**
 * One iteration of the main loop
 */
void oneIteration()
{
    processEvents();
    SDL_Flip(window);
}

/**
 * Entry point
 */
int main(int argc, char** argv)
{
    #ifndef EMSCRIPTEN
        atexit(SDL_Quit);
    #endif

    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        cout << "Video initialization failed: " << SDL_GetError() << endl;
        exit(EXIT_FAILURE);
    }

    const SDL_VideoInfo* screen_info = SDL_GetVideoInfo();
    int screen_width  = screen_info->current_w / 2;
    int screen_height = screen_info->current_h / 2;

    #ifdef EMSCRIPTEN
        screen_width  = screen_info->current_w;
        screen_height = screen_info->current_h;
    #endif

    screen = SDL_SetVideoMode(screen_width, screen_height, bpp, flags);
    if (screen == NULL) {
        cout << "Video mode set failed: " << SDL_GetError() << endl;
        exit(EXIT_SUCCESS);
    }
    SDL_WM_SetCaption("gbcEmulator", NULL);

    window = SDL_GetVideoSurface();
    resize(window->w, window->h);

    // Generate pixels
    srand (time(NULL));
    for (size_t i = 0; i < NATIVE_WIDTH; i++) {
        for (size_t j = 0; j < NATIVE_HEIGHT; j++) {
            Uint32 color = rand() % 0xFFFFFFFF;
            pixels_map[i][j] = color;
            drawPixel(i, j, color);
        }
    }

    #ifdef EMSCRIPTEN
        emscripten_set_main_loop(oneIteration, 0, 1);
    #else
        while(1) {
            oneIteration();
            //60 FPS
            SDL_Delay(16);
        }

        SDL_Quit();
    #endif

    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include <common/list.h>
#include <gdb/location.h>
#include <stdlib.h>
#include <string.h>
#include <common/log.h>

gdb_location_t::gdb_location_t(){
	fullname = 0;
	filename = 0;
}

gdb_location_t::~gdb_location_t(){
	delete fullname;
	delete filename;
}

int conv_location(gdb_result_t* result, void** loc){
	gdb_result_t* r;

	if(*loc == 0)
		*loc = new gdb_location_t;

	list_for_each(result, r){
		switch(r->var_id){
		case V_LINE:
			((gdb_location_t*)*loc)->line = atoi((char*)r->value);
			break;

		case V_FILE:
			((gdb_location_t*)*loc)->filename = new char[strlen((const char*)r->value->value) + 1];
			strcpy(((gdb_location_t*)*loc)->filename, (const char*)r->value->value);
			break;

		case V_FULLNAME:
			((gdb_location_t*)*loc)->fullname = new char[strlen((const char*)r->value->value) + 1];
			strcpy(((gdb_location_t*)*loc)->fullname, (const char*)r->value->value);
			break;

		default:
			break;
		};
	}

	return 0;
}
<commit_msg>[fix gdb location conversion]<commit_after>#include <common/list.h>
#include <gdb/location.h>
#include <stdlib.h>
#include <string.h>
#include <common/log.h>

gdb_location_t::gdb_location_t(){
	fullname = 0;
	filename = 0;
}

gdb_location_t::~gdb_location_t(){
	delete fullname;
	delete filename;
}

int conv_location(gdb_result_t* result, void** loc){
	gdb_result_t* r;

	if(*loc == 0)
		*loc = new gdb_location_t;

	list_for_each(result, r){
		switch(r->var_id){
		case V_LINE:
			((gdb_location_t*)*loc)->line = atoi((char*)r->value->value);
			break;

		case V_FILE:
			((gdb_location_t*)*loc)->filename = new char[strlen((const char*)r->value->value) + 1];
			strcpy(((gdb_location_t*)*loc)->filename, (const char*)r->value->value);
			break;

		case V_FULLNAME:
			((gdb_location_t*)*loc)->fullname = new char[strlen((const char*)r->value->value) + 1];
			strcpy(((gdb_location_t*)*loc)->fullname, (const char*)r->value->value);
			break;

		default:
			break;
		};
	}

	return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <tr1/memory>
#include <queue>

#include <boost/functional.hpp>
#include <boost/program_options.hpp>
#include <boost/program_options/variables_map.hpp>

#include "corpus_tools.h"
#include "m.h"
#include "tdict.h"
#include "sampler.h"
#include "ccrp.h"

// A not very memory-efficient implementation of an N-gram LM based on PYPs
// as described in Y.-W. Teh. (2006) A Hierarchical Bayesian Language Model
// based on Pitman-Yor Processes. In Proc. ACL.

// I use templates to handle the recursive formalation of the prior, so
// the order of the model has to be specified here, at compile time:
#define kORDER 3

using namespace std;
using namespace tr1;
namespace po = boost::program_options;

shared_ptr<MT19937> prng;

void InitCommandLine(int argc, char** argv, po::variables_map* conf) {
  po::options_description opts("Configuration options");
  opts.add_options()
        ("samples,s",po::value<unsigned>()->default_value(300),"Number of samples")
        ("train,i",po::value<string>(),"Training data file")
        ("test,T",po::value<string>(),"Test data file")
        ("discount_prior_a,a",po::value<double>()->default_value(1.0), "discount ~ Beta(a,b): a=this")
        ("discount_prior_b,b",po::value<double>()->default_value(1.0), "discount ~ Beta(a,b): b=this")
        ("strength_prior_s,s",po::value<double>()->default_value(1.0), "strength ~ Gamma(s,r): s=this")
        ("strength_prior_r,r",po::value<double>()->default_value(1.0), "strength ~ Gamma(s,r): r=this")
        ("random_seed,S",po::value<uint32_t>(), "Random seed");
  po::options_description clo("Command line options");
  clo.add_options()
        ("config", po::value<string>(), "Configuration file")
        ("help", "Print this help message and exit");
  po::options_description dconfig_options, dcmdline_options;
  dconfig_options.add(opts);
  dcmdline_options.add(opts).add(clo);

  po::store(parse_command_line(argc, argv, dcmdline_options), *conf);
  if (conf->count("config")) {
    ifstream config((*conf)["config"].as<string>().c_str());
    po::store(po::parse_config_file(config, dconfig_options), *conf);
  }
  po::notify(*conf);

  if (conf->count("help") || (conf->count("train") == 0)) {
    cerr << dcmdline_options << endl;
    exit(1);
  }
}

template <unsigned N> struct PYPLM;

// uniform base distribution (0-gram model)
template<> struct PYPLM<0> {
  PYPLM(unsigned vs, double, double, double, double) : p0(1.0 / vs), draws() {}
  void increment(WordID, const vector<WordID>&, MT19937*) { ++draws; }
  void decrement(WordID, const vector<WordID>&, MT19937*) { --draws; assert(draws >= 0); }
  double prob(WordID, const vector<WordID>&) const { return p0; }
  void resample_hyperparameters(MT19937*, const unsigned, const unsigned) {}
  double log_likelihood() const { return draws * log(p0); }
  const double p0;
  int draws;
};

// represents an N-gram LM
template <unsigned N> struct PYPLM {
  PYPLM(unsigned vs, double da, double db, double ss, double sr) :
      backoff(vs, da, db, ss, sr),
      discount_a(da), discount_b(db),
      strength_s(ss), strength_r(sr),
      d(0.8), alpha(1.0), lookup(N-1) {}
  void increment(WordID w, const vector<WordID>& context, MT19937* rng) {
    const double bo = backoff.prob(w, context);
    for (unsigned i = 0; i < N-1; ++i)
      lookup[i] = context[context.size() - 1 - i];
    typename unordered_map<vector<WordID>, CCRP<WordID>, boost::hash<vector<WordID> > >::iterator it = p.find(lookup);
    if (it == p.end())
      it = p.insert(make_pair(lookup, CCRP<WordID>(d,alpha))).first;
    if (it->second.increment(w, bo, rng))
      backoff.increment(w, context, rng);
  }
  void decrement(WordID w, const vector<WordID>& context, MT19937* rng) {
    for (unsigned i = 0; i < N-1; ++i)
      lookup[i] = context[context.size() - 1 - i];
    typename unordered_map<vector<WordID>, CCRP<WordID>, boost::hash<vector<WordID> > >::iterator it = p.find(lookup);
    assert(it != p.end());
    if (it->second.decrement(w, rng))
      backoff.decrement(w, context, rng);
  }
  double prob(WordID w, const vector<WordID>& context) const {
    const double bo = backoff.prob(w, context);
    for (unsigned i = 0; i < N-1; ++i)
      lookup[i] = context[context.size() - 1 - i];
    typename unordered_map<vector<WordID>, CCRP<WordID>, boost::hash<vector<WordID> > >::const_iterator it = p.find(lookup);
    if (it == p.end()) return bo;
    return it->second.prob(w, bo);
  }

  double log_likelihood() const {
    return log_likelihood(d, alpha) + backoff.log_likelihood();
  }

  double log_likelihood(const double& dd, const double& aa) const {
    if (aa <= -dd) return -std::numeric_limits<double>::infinity();
    //double llh = Md::log_beta_density(dd, 10, 3) + Md::log_gamma_density(aa, 1, 1);
    double llh = Md::log_beta_density(dd, discount_a, discount_b) +
                 Md::log_gamma_density(aa, strength_s, strength_r);
    typename unordered_map<vector<WordID>, CCRP<WordID>, boost::hash<vector<WordID> > >::const_iterator it;
    for (it = p.begin(); it != p.end(); ++it)
      llh += it->second.log_crp_prob(dd, aa);
    return llh;
  }

  struct DiscountResampler {
    DiscountResampler(const PYPLM& m) : m_(m) {}
    const PYPLM& m_;
    double operator()(const double& proposed_discount) const {
      return m_.log_likelihood(proposed_discount, m_.alpha);
    }
  };

  struct AlphaResampler {
    AlphaResampler(const PYPLM& m) : m_(m) {}
    const PYPLM& m_;
    double operator()(const double& proposed_alpha) const {
      return m_.log_likelihood(m_.d, proposed_alpha);
    }
  };

  void resample_hyperparameters(MT19937* rng, const unsigned nloop = 5, const unsigned niterations = 10) {
    DiscountResampler dr(*this);
    AlphaResampler ar(*this);
    for (int iter = 0; iter < nloop; ++iter) {
      alpha = slice_sampler1d(ar, alpha, *rng, 0.0,
                              std::numeric_limits<double>::infinity(), 0.0, niterations, 100*niterations);
      d = slice_sampler1d(dr, d, *rng, std::numeric_limits<double>::min(),
                          1.0, 0.0, niterations, 100*niterations);
    }
    alpha = slice_sampler1d(ar, alpha, *rng, 0.0,
                            std::numeric_limits<double>::infinity(), 0.0, niterations, 100*niterations);
    typename unordered_map<vector<WordID>, CCRP<WordID>, boost::hash<vector<WordID> > >::iterator it;
    cerr << "PYPLM<" << N << ">(d=" << d << ",a=" << alpha << ") = " << log_likelihood(d, alpha) << endl;
    for (it = p.begin(); it != p.end(); ++it) {
      it->second.set_discount(d);
      it->second.set_alpha(alpha);
    }
    backoff.resample_hyperparameters(rng, nloop, niterations);
  }

  PYPLM<N-1> backoff;
  double discount_a, discount_b, strength_s, strength_r;
  double d, alpha;
  mutable vector<WordID> lookup;  // thread-local
  unordered_map<vector<WordID>, CCRP<WordID>, boost::hash<vector<WordID> > > p;
};

int main(int argc, char** argv) {
  po::variables_map conf;

  InitCommandLine(argc, argv, &conf);
  const unsigned samples = conf["samples"].as<unsigned>();
  if (conf.count("random_seed"))
    prng.reset(new MT19937(conf["random_seed"].as<uint32_t>()));
  else
    prng.reset(new MT19937);
  MT19937& rng = *prng;
  vector<vector<WordID> > corpuse;
  set<WordID> vocabe;
  const WordID kEOS = TD::Convert("</s>");
  cerr << "Reading corpus...\n";
  CorpusTools::ReadFromFile(conf["train"].as<string>(), &corpuse, &vocabe);
  cerr << "E-corpus size: " << corpuse.size() << " sentences\t (" << vocabe.size() << " word types)\n";
  vector<vector<WordID> > test;
  if (conf.count("test"))
    CorpusTools::ReadFromFile(conf["test"].as<string>(), &test);
  else
    test = corpuse;
  PYPLM<kORDER> lm(vocabe.size(),
                   conf["discount_prior_a"].as<double>(),
                   conf["discount_prior_b"].as<double>(),
                   conf["strength_prior_s"].as<double>(),
                   conf["strength_prior_r"].as<double>());
  vector<WordID> ctx(kORDER - 1, TD::Convert("<s>"));
  for (int SS=0; SS < samples; ++SS) {
    for (int ci = 0; ci < corpuse.size(); ++ci) {
      ctx.resize(kORDER - 1);
      const vector<WordID>& s = corpuse[ci];
      for (int i = 0; i <= s.size(); ++i) {
        WordID w = (i < s.size() ? s[i] : kEOS);
        if (SS > 0) lm.decrement(w, ctx, &rng);
        lm.increment(w, ctx, &rng);
        ctx.push_back(w);
      }
      if (SS > 0) lm.decrement(kEOS, ctx, &rng);
      lm.increment(kEOS, ctx, &rng);
    }
    if (SS % 10 == 9) {
      cerr << " [LLH=" << lm.log_likelihood() << "]" << endl;
      if (SS % 20 == 19) lm.resample_hyperparameters(&rng);
    } else { cerr << '.' << flush; }
  }
  double llh = 0;
  unsigned cnt = 0;
  unsigned oovs = 0;
  for (int ci = 0; ci < test.size(); ++ci) {
    ctx.resize(kORDER - 1);
    const vector<WordID>& s = test[ci];
    for (int i = 0; i <= s.size(); ++i) {
      WordID w = (i < s.size() ? s[i] : kEOS);
      double lp = log(lm.prob(w, ctx)) / log(2);
      if (i < s.size() && vocabe.count(w) == 0) {
        cerr << "**OOV ";
        ++oovs;
        lp = 0;
      }
      cerr << "p(" << TD::Convert(w) << " |";
      for (int j = ctx.size() + 1 - kORDER; j < ctx.size(); ++j)
        cerr << ' ' << TD::Convert(ctx[j]);
      cerr << ") = " << lp << endl;
      ctx.push_back(w);
      llh -= lp;
      cnt++;
    }
  }
  cerr << "  Log_10 prob: " << (-llh * log(2) / log(10)) << endl;
  cerr << "        Count: " << cnt << endl;
  cerr << "         OOVs: " << oovs << endl;
  cerr << "Cross-entropy: " << (llh / cnt) << endl;
  cerr << "   Perplexity: " << pow(2, llh / cnt) << endl;
  return 0;
}

<commit_msg>fix parameter name clash<commit_after>#include <iostream>
#include <tr1/memory>
#include <queue>

#include <boost/functional.hpp>
#include <boost/program_options.hpp>
#include <boost/program_options/variables_map.hpp>

#include "corpus_tools.h"
#include "m.h"
#include "tdict.h"
#include "sampler.h"
#include "ccrp.h"

// A not very memory-efficient implementation of an N-gram LM based on PYPs
// as described in Y.-W. Teh. (2006) A Hierarchical Bayesian Language Model
// based on Pitman-Yor Processes. In Proc. ACL.

// I use templates to handle the recursive formalation of the prior, so
// the order of the model has to be specified here, at compile time:
#define kORDER 3

using namespace std;
using namespace tr1;
namespace po = boost::program_options;

shared_ptr<MT19937> prng;

void InitCommandLine(int argc, char** argv, po::variables_map* conf) {
  po::options_description opts("Configuration options");
  opts.add_options()
        ("samples,n",po::value<unsigned>()->default_value(300),"Number of samples")
        ("train,i",po::value<string>(),"Training data file")
        ("test,T",po::value<string>(),"Test data file")
        ("discount_prior_a,a",po::value<double>()->default_value(1.0), "discount ~ Beta(a,b): a=this")
        ("discount_prior_b,b",po::value<double>()->default_value(1.0), "discount ~ Beta(a,b): b=this")
        ("strength_prior_s,s",po::value<double>()->default_value(1.0), "strength ~ Gamma(s,r): s=this")
        ("strength_prior_r,r",po::value<double>()->default_value(1.0), "strength ~ Gamma(s,r): r=this")
        ("random_seed,S",po::value<uint32_t>(), "Random seed");
  po::options_description clo("Command line options");
  clo.add_options()
        ("config", po::value<string>(), "Configuration file")
        ("help", "Print this help message and exit");
  po::options_description dconfig_options, dcmdline_options;
  dconfig_options.add(opts);
  dcmdline_options.add(opts).add(clo);

  po::store(parse_command_line(argc, argv, dcmdline_options), *conf);
  if (conf->count("config")) {
    ifstream config((*conf)["config"].as<string>().c_str());
    po::store(po::parse_config_file(config, dconfig_options), *conf);
  }
  po::notify(*conf);

  if (conf->count("help") || (conf->count("train") == 0)) {
    cerr << dcmdline_options << endl;
    exit(1);
  }
}

template <unsigned N> struct PYPLM;

// uniform base distribution (0-gram model)
template<> struct PYPLM<0> {
  PYPLM(unsigned vs, double, double, double, double) : p0(1.0 / vs), draws() {}
  void increment(WordID, const vector<WordID>&, MT19937*) { ++draws; }
  void decrement(WordID, const vector<WordID>&, MT19937*) { --draws; assert(draws >= 0); }
  double prob(WordID, const vector<WordID>&) const { return p0; }
  void resample_hyperparameters(MT19937*, const unsigned, const unsigned) {}
  double log_likelihood() const { return draws * log(p0); }
  const double p0;
  int draws;
};

// represents an N-gram LM
template <unsigned N> struct PYPLM {
  PYPLM(unsigned vs, double da, double db, double ss, double sr) :
      backoff(vs, da, db, ss, sr),
      discount_a(da), discount_b(db),
      strength_s(ss), strength_r(sr),
      d(0.8), alpha(1.0), lookup(N-1) {}
  void increment(WordID w, const vector<WordID>& context, MT19937* rng) {
    const double bo = backoff.prob(w, context);
    for (unsigned i = 0; i < N-1; ++i)
      lookup[i] = context[context.size() - 1 - i];
    typename unordered_map<vector<WordID>, CCRP<WordID>, boost::hash<vector<WordID> > >::iterator it = p.find(lookup);
    if (it == p.end())
      it = p.insert(make_pair(lookup, CCRP<WordID>(d,alpha))).first;
    if (it->second.increment(w, bo, rng))
      backoff.increment(w, context, rng);
  }
  void decrement(WordID w, const vector<WordID>& context, MT19937* rng) {
    for (unsigned i = 0; i < N-1; ++i)
      lookup[i] = context[context.size() - 1 - i];
    typename unordered_map<vector<WordID>, CCRP<WordID>, boost::hash<vector<WordID> > >::iterator it = p.find(lookup);
    assert(it != p.end());
    if (it->second.decrement(w, rng))
      backoff.decrement(w, context, rng);
  }
  double prob(WordID w, const vector<WordID>& context) const {
    const double bo = backoff.prob(w, context);
    for (unsigned i = 0; i < N-1; ++i)
      lookup[i] = context[context.size() - 1 - i];
    typename unordered_map<vector<WordID>, CCRP<WordID>, boost::hash<vector<WordID> > >::const_iterator it = p.find(lookup);
    if (it == p.end()) return bo;
    return it->second.prob(w, bo);
  }

  double log_likelihood() const {
    return log_likelihood(d, alpha) + backoff.log_likelihood();
  }

  double log_likelihood(const double& dd, const double& aa) const {
    if (aa <= -dd) return -std::numeric_limits<double>::infinity();
    //double llh = Md::log_beta_density(dd, 10, 3) + Md::log_gamma_density(aa, 1, 1);
    double llh = Md::log_beta_density(dd, discount_a, discount_b) +
                 Md::log_gamma_density(aa, strength_s, strength_r);
    typename unordered_map<vector<WordID>, CCRP<WordID>, boost::hash<vector<WordID> > >::const_iterator it;
    for (it = p.begin(); it != p.end(); ++it)
      llh += it->second.log_crp_prob(dd, aa);
    return llh;
  }

  struct DiscountResampler {
    DiscountResampler(const PYPLM& m) : m_(m) {}
    const PYPLM& m_;
    double operator()(const double& proposed_discount) const {
      return m_.log_likelihood(proposed_discount, m_.alpha);
    }
  };

  struct AlphaResampler {
    AlphaResampler(const PYPLM& m) : m_(m) {}
    const PYPLM& m_;
    double operator()(const double& proposed_alpha) const {
      return m_.log_likelihood(m_.d, proposed_alpha);
    }
  };

  void resample_hyperparameters(MT19937* rng, const unsigned nloop = 5, const unsigned niterations = 10) {
    DiscountResampler dr(*this);
    AlphaResampler ar(*this);
    for (int iter = 0; iter < nloop; ++iter) {
      alpha = slice_sampler1d(ar, alpha, *rng, 0.0,
                              std::numeric_limits<double>::infinity(), 0.0, niterations, 100*niterations);
      d = slice_sampler1d(dr, d, *rng, std::numeric_limits<double>::min(),
                          1.0, 0.0, niterations, 100*niterations);
    }
    alpha = slice_sampler1d(ar, alpha, *rng, 0.0,
                            std::numeric_limits<double>::infinity(), 0.0, niterations, 100*niterations);
    typename unordered_map<vector<WordID>, CCRP<WordID>, boost::hash<vector<WordID> > >::iterator it;
    cerr << "PYPLM<" << N << ">(d=" << d << ",a=" << alpha << ") = " << log_likelihood(d, alpha) << endl;
    for (it = p.begin(); it != p.end(); ++it) {
      it->second.set_discount(d);
      it->second.set_alpha(alpha);
    }
    backoff.resample_hyperparameters(rng, nloop, niterations);
  }

  PYPLM<N-1> backoff;
  double discount_a, discount_b, strength_s, strength_r;
  double d, alpha;
  mutable vector<WordID> lookup;  // thread-local
  unordered_map<vector<WordID>, CCRP<WordID>, boost::hash<vector<WordID> > > p;
};

int main(int argc, char** argv) {
  po::variables_map conf;

  InitCommandLine(argc, argv, &conf);
  const unsigned samples = conf["samples"].as<unsigned>();
  if (conf.count("random_seed"))
    prng.reset(new MT19937(conf["random_seed"].as<uint32_t>()));
  else
    prng.reset(new MT19937);
  MT19937& rng = *prng;
  vector<vector<WordID> > corpuse;
  set<WordID> vocabe;
  const WordID kEOS = TD::Convert("</s>");
  cerr << "Reading corpus...\n";
  CorpusTools::ReadFromFile(conf["train"].as<string>(), &corpuse, &vocabe);
  cerr << "E-corpus size: " << corpuse.size() << " sentences\t (" << vocabe.size() << " word types)\n";
  vector<vector<WordID> > test;
  if (conf.count("test"))
    CorpusTools::ReadFromFile(conf["test"].as<string>(), &test);
  else
    test = corpuse;
  PYPLM<kORDER> lm(vocabe.size(),
                   conf["discount_prior_a"].as<double>(),
                   conf["discount_prior_b"].as<double>(),
                   conf["strength_prior_s"].as<double>(),
                   conf["strength_prior_r"].as<double>());
  vector<WordID> ctx(kORDER - 1, TD::Convert("<s>"));
  for (int SS=0; SS < samples; ++SS) {
    for (int ci = 0; ci < corpuse.size(); ++ci) {
      ctx.resize(kORDER - 1);
      const vector<WordID>& s = corpuse[ci];
      for (int i = 0; i <= s.size(); ++i) {
        WordID w = (i < s.size() ? s[i] : kEOS);
        if (SS > 0) lm.decrement(w, ctx, &rng);
        lm.increment(w, ctx, &rng);
        ctx.push_back(w);
      }
      if (SS > 0) lm.decrement(kEOS, ctx, &rng);
      lm.increment(kEOS, ctx, &rng);
    }
    if (SS % 10 == 9) {
      cerr << " [LLH=" << lm.log_likelihood() << "]" << endl;
      if (SS % 20 == 19) lm.resample_hyperparameters(&rng);
    } else { cerr << '.' << flush; }
  }
  double llh = 0;
  unsigned cnt = 0;
  unsigned oovs = 0;
  for (int ci = 0; ci < test.size(); ++ci) {
    ctx.resize(kORDER - 1);
    const vector<WordID>& s = test[ci];
    for (int i = 0; i <= s.size(); ++i) {
      WordID w = (i < s.size() ? s[i] : kEOS);
      double lp = log(lm.prob(w, ctx)) / log(2);
      if (i < s.size() && vocabe.count(w) == 0) {
        cerr << "**OOV ";
        ++oovs;
        lp = 0;
      }
      cerr << "p(" << TD::Convert(w) << " |";
      for (int j = ctx.size() + 1 - kORDER; j < ctx.size(); ++j)
        cerr << ' ' << TD::Convert(ctx[j]);
      cerr << ") = " << lp << endl;
      ctx.push_back(w);
      llh -= lp;
      cnt++;
    }
  }
  cerr << "  Log_10 prob: " << (-llh * log(2) / log(10)) << endl;
  cerr << "        Count: " << cnt << endl;
  cerr << "         OOVs: " << oovs << endl;
  cerr << "Cross-entropy: " << (llh / cnt) << endl;
  cerr << "   Perplexity: " << pow(2, llh / cnt) << endl;
  return 0;
}

<|endoftext|>