text
stringlengths 54
60.6k
|
|---|
<commit_before>/**
* Exception_handler.cpp
*
* Set the exception handler
*
* @author Toon Schoenmakers <toon.schoenmakers@copernica.com>
*/
/**
* Dependencies
*/
#include "includes.h"
/**
* Open the PHP namespace
*/
namespace Php {
/**
* Set a std::function as a php exception handler
*/
Value set_exception_handler(const std::function<Value(Parameters ¶ms)> &handler)
{
// create a functor which wraps our callback
Function functor(handler);
// initialize our output value
Value output;
// turn our user_exception_handler into a Value so we can return the original one later on
if (EG(user_exception_handler)) output = EG(user_exception_handler);
// detach so we have the zval
auto value = functor.detach(true);
// allocate the user_exception_handler
ALLOC_ZVAL(EG(user_exception_handler));
// copy our zval into the user_exception_handler
MAKE_COPY_ZVAL(&value, EG(user_exception_handler));
// return the original handler
return output;
}
/**
* Set a std::function as a php error handler
*/
Value set_error_handler(const std::function<Value(Parameters ¶ms)> &handler, Error error)
{
// create the functor which wraps our callback
Function functor(handler);
// initialize our output value
Value output;
// turn our user_error_handler into a Value if we have one, just so we can return it later on
if (EG(user_error_handler)) output = EG(user_error_handler);
// detach so we have the zval
auto value = functor.detach(true);
// alocate the user_error_handler
ALLOC_ZVAL(EG(user_error_handler));
// copy our zval into the user_error_handler
MAKE_COPY_ZVAL(&value, EG(user_error_handler));
EG(user_error_handler_error_reporting) = (int) error;
// return the original handler
return output;
}
/**
* Modify the error reporting level, will return the old error reporting level.
*/
Value error_reporting(Error error)
{
// store the old error reporting value
Value output(EG(error_reporting));
// create a small temporary buffer
char str[21];
// write the level into this buffer
int size = sprintf(str, "%d", (int) error);
// if we failed for some reason we bail out
if (size < 0) return false;
// alter the ini on the fly
zend_alter_ini_entry("error_reporting", sizeof("error_reporting"), str, size, ZEND_INI_USER, ZEND_INI_STAGE_RUNTIME);
// return the output
return output;
}
/**
* End of namespace
*/
}
<commit_msg>Fix compiler errors when compiling for a multi-threading environment, fixes issue #226<commit_after>/**
* Exception_handler.cpp
*
* Set the exception handler
*
* @author Toon Schoenmakers <toon.schoenmakers@copernica.com>
*/
/**
* Dependencies
*/
#include "includes.h"
/**
* Open the PHP namespace
*/
namespace Php {
/**
* Set a std::function as a php exception handler
*/
Value set_exception_handler(const std::function<Value(Parameters ¶ms)> &handler)
{
// we need the tsrm_ls variable
TSRMLS_FETCH();
// create a functor which wraps our callback
Function functor(handler);
// initialize our output value
Value output;
// turn our user_exception_handler into a Value so we can return the original one later on
if (EG(user_exception_handler)) output = EG(user_exception_handler);
// detach so we have the zval
auto value = functor.detach(true);
// allocate the user_exception_handler
ALLOC_ZVAL(EG(user_exception_handler));
// copy our zval into the user_exception_handler
MAKE_COPY_ZVAL(&value, EG(user_exception_handler));
// return the original handler
return output;
}
/**
* Set a std::function as a php error handler
*/
Value set_error_handler(const std::function<Value(Parameters ¶ms)> &handler, Error error)
{
// we need the tsrm_ls variable
TSRMLS_FETCH();
// create the functor which wraps our callback
Function functor(handler);
// initialize our output value
Value output;
// turn our user_error_handler into a Value if we have one, just so we can return it later on
if (EG(user_error_handler)) output = EG(user_error_handler);
// detach so we have the zval
auto value = functor.detach(true);
// alocate the user_error_handler
ALLOC_ZVAL(EG(user_error_handler));
// copy our zval into the user_error_handler
MAKE_COPY_ZVAL(&value, EG(user_error_handler));
EG(user_error_handler_error_reporting) = (int) error;
// return the original handler
return output;
}
/**
* Modify the error reporting level, will return the old error reporting level.
*/
Value error_reporting(Error error)
{
// we need the tsrm_ls variable
TSRMLS_FETCH();
// store the old error reporting value
Value output(EG(error_reporting));
// create a small temporary buffer
char str[21];
// write the level into this buffer
int size = sprintf(str, "%d", (int) error);
// if we failed for some reason we bail out
if (size < 0) return false;
// alter the ini on the fly
zend_alter_ini_entry("error_reporting", sizeof("error_reporting"), str, size, ZEND_INI_USER, ZEND_INI_STAGE_RUNTIME);
// return the output
return output;
}
/**
* End of namespace
*/
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <algorithm>
#include "libtorrent/entry.hpp"
#include <boost/bind.hpp>
#include <boost/next_prior.hpp>
#if defined(_MSC_VER)
namespace std
{
using ::isprint;
}
#define for if (false) {} else for
#endif
namespace
{
template <class T>
void call_destructor(T* o)
{
assert(o);
o->~T();
}
struct compare_string
{
compare_string(char const* s): m_str(s) {}
bool operator()(
std::pair<std::string
, libtorrent::entry> const& e) const
{
return e.first == m_str;
}
char const* m_str;
};
}
namespace libtorrent
{
namespace detail
{
char const* integer_to_str(char* buf, int size, entry::integer_type val)
{
int sign = 0;
if (val < 0)
{
sign = 1;
val = -val;
}
buf[--size] = '\0';
if (val == 0) buf[--size] = '0';
for (; size > sign && val != 0;)
{
buf[--size] = '0' + char(val % 10);
val /= 10;
}
if (sign) buf[--size] = '-';
return buf + size;
}
}
entry& entry::operator[](char const* key)
{
dictionary_type::iterator i = std::find_if(
dict().begin()
, dict().end()
, compare_string(key));
if (i != dict().end()) return i->second;
dictionary_type::iterator ret = dict().insert(
dict().end()
, std::make_pair(std::string(key), entry()));
return ret->second;
}
entry& entry::operator[](std::string const& key)
{
return (*this)[key.c_str()];
}
entry* entry::find_key(char const* key)
{
dictionary_type::iterator i = std::find_if(
dict().begin()
, dict().end()
, compare_string(key));
if (i == dict().end()) return 0;
return &i->second;
}
entry const* entry::find_key(char const* key) const
{
dictionary_type::const_iterator i = std::find_if(
dict().begin()
, dict().end()
, compare_string(key));
if (i == dict().end()) return 0;
return &i->second;
}
const entry& entry::operator[](char const* key) const
{
dictionary_type::const_iterator i = std::find_if(
dict().begin()
, dict().end()
, compare_string(key));
if (i == dict().end()) throw type_error("key not found");
return i->second;
}
const entry& entry::operator[](std::string const& key) const
{
return (*this)[key.c_str()];
}
entry::entry(const dictionary_type& v)
{
new(data) dictionary_type(v);
m_type = dictionary_t;
}
entry::entry(const string_type& v)
{
new(data) string_type(v);
m_type = string_t;
}
entry::entry(const list_type& v)
{
new(data) list_type(v);
m_type = list_t;
}
entry::entry(const integer_type& v)
{
new(data) integer_type(v);
m_type = int_t;
}
void entry::operator=(const dictionary_type& v)
{
destruct();
new(data) dictionary_type(v);
m_type = dictionary_t;
}
void entry::operator=(const string_type& v)
{
destruct();
new(data) string_type(v);
m_type = string_t;
}
void entry::operator=(const list_type& v)
{
destruct();
new(data) list_type(v);
m_type = list_t;
}
void entry::operator=(const integer_type& v)
{
destruct();
new(data) integer_type(v);
m_type = int_t;
}
bool entry::operator==(entry const& e) const
{
if (m_type != e.m_type) return false;
switch(m_type)
{
case int_t:
return integer() == e.integer();
case string_t:
return string() == e.string();
case list_t:
return list() == e.list();
case dictionary_t:
return dict() == e.dict();
default:
assert(m_type == undefined_t);
return true;
}
}
void entry::construct(data_type t)
{
m_type = t;
switch(m_type)
{
case int_t:
new(data) integer_type;
break;
case string_t:
new(data) string_type;
break;
case list_t:
new(data) list_type;
break;
case dictionary_t:
new (data) dictionary_type;
break;
default:
assert(m_type == undefined_t);
m_type = undefined_t;
}
}
void entry::copy(const entry& e)
{
m_type = e.m_type;
switch(m_type)
{
case int_t:
new(data) integer_type(e.integer());
break;
case string_t:
new(data) string_type(e.string());
break;
case list_t:
new(data) list_type(e.list());
break;
case dictionary_t:
new (data) dictionary_type(e.dict());
break;
default:
m_type = undefined_t;
}
}
void entry::destruct()
{
switch(m_type)
{
case int_t:
call_destructor(reinterpret_cast<integer_type*>(data));
break;
case string_t:
call_destructor(reinterpret_cast<string_type*>(data));
break;
case list_t:
call_destructor(reinterpret_cast<list_type*>(data));
break;
case dictionary_t:
call_destructor(reinterpret_cast<dictionary_type*>(data));
break;
default:
assert(m_type == undefined_t);
break;
}
}
void entry::print(std::ostream& os, int indent) const
{
assert(indent >= 0);
for (int i = 0; i < indent; ++i) os << " ";
switch (m_type)
{
case int_t:
os << integer() << "\n";
break;
case string_t:
{
bool binary_string = false;
for (std::string::const_iterator i = string().begin(); i != string().end(); ++i)
{
if (!std::isprint(static_cast<unsigned char>(*i)))
{
binary_string = true;
break;
}
}
if (binary_string)
{
os.unsetf(std::ios_base::dec);
os.setf(std::ios_base::hex);
for (std::string::const_iterator i = string().begin(); i != string().end(); ++i)
os << static_cast<unsigned int>((unsigned char)*i);
os.unsetf(std::ios_base::hex);
os.setf(std::ios_base::dec);
os << "\n";
}
else
{
os << string() << "\n";
}
} break;
case list_t:
{
os << "list\n";
for (list_type::const_iterator i = list().begin(); i != list().end(); ++i)
{
i->print(os, indent+1);
}
} break;
case dictionary_t:
{
os << "dictionary\n";
for (dictionary_type::const_iterator i = dict().begin(); i != dict().end(); ++i)
{
for (int j = 0; j < indent+1; ++j) os << " ";
os << "[" << i->first << "]";
if (i->second.type() != entry::string_t && i->second.type() != entry::int_t) os << "\n";
else os << " ";
i->second.print(os, indent+2);
}
} break;
default:
os << "<uninitialized>\n";
}
}
}
<commit_msg>optimizations to entry (using std::maps find instead of linear search)<commit_after>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <algorithm>
#include "libtorrent/entry.hpp"
#include <boost/bind.hpp>
#include <boost/next_prior.hpp>
#if defined(_MSC_VER)
namespace std
{
using ::isprint;
}
#define for if (false) {} else for
#endif
namespace
{
template <class T>
void call_destructor(T* o)
{
assert(o);
o->~T();
}
struct compare_string
{
compare_string(char const* s): m_str(s) {}
bool operator()(
std::pair<std::string
, libtorrent::entry> const& e) const
{
return e.first == m_str;
}
char const* m_str;
};
}
namespace libtorrent
{
namespace detail
{
char const* integer_to_str(char* buf, int size, entry::integer_type val)
{
int sign = 0;
if (val < 0)
{
sign = 1;
val = -val;
}
buf[--size] = '\0';
if (val == 0) buf[--size] = '0';
for (; size > sign && val != 0;)
{
buf[--size] = '0' + char(val % 10);
val /= 10;
}
if (sign) buf[--size] = '-';
return buf + size;
}
}
entry& entry::operator[](char const* key)
{
dictionary_type::iterator i = dict().find(key);
if (i != dict().end()) return i->second;
dictionary_type::iterator ret = dict().insert(
dict().begin()
, std::make_pair(std::string(key), entry()));
return ret->second;
}
entry& entry::operator[](std::string const& key)
{
return (*this)[key.c_str()];
}
entry* entry::find_key(char const* key)
{
dictionary_type::iterator i = std::find_if(
dict().begin()
, dict().end()
, compare_string(key));
if (i == dict().end()) return 0;
return &i->second;
}
entry const* entry::find_key(char const* key) const
{
dictionary_type::const_iterator i = dict().find(key);
if (i == dict().end()) return 0;
return &i->second;
}
const entry& entry::operator[](char const* key) const
{
dictionary_type::const_iterator i = dict().find(key);
if (i == dict().end()) throw type_error(
(std::string("key not found: ") + key).c_str());
return i->second;
}
const entry& entry::operator[](std::string const& key) const
{
return (*this)[key.c_str()];
}
entry::entry(const dictionary_type& v)
{
new(data) dictionary_type(v);
m_type = dictionary_t;
}
entry::entry(const string_type& v)
{
new(data) string_type(v);
m_type = string_t;
}
entry::entry(const list_type& v)
{
new(data) list_type(v);
m_type = list_t;
}
entry::entry(const integer_type& v)
{
new(data) integer_type(v);
m_type = int_t;
}
void entry::operator=(const dictionary_type& v)
{
destruct();
new(data) dictionary_type(v);
m_type = dictionary_t;
}
void entry::operator=(const string_type& v)
{
destruct();
new(data) string_type(v);
m_type = string_t;
}
void entry::operator=(const list_type& v)
{
destruct();
new(data) list_type(v);
m_type = list_t;
}
void entry::operator=(const integer_type& v)
{
destruct();
new(data) integer_type(v);
m_type = int_t;
}
bool entry::operator==(entry const& e) const
{
if (m_type != e.m_type) return false;
switch(m_type)
{
case int_t:
return integer() == e.integer();
case string_t:
return string() == e.string();
case list_t:
return list() == e.list();
case dictionary_t:
return dict() == e.dict();
default:
assert(m_type == undefined_t);
return true;
}
}
void entry::construct(data_type t)
{
m_type = t;
switch(m_type)
{
case int_t:
new(data) integer_type;
break;
case string_t:
new(data) string_type;
break;
case list_t:
new(data) list_type;
break;
case dictionary_t:
new (data) dictionary_type;
break;
default:
assert(m_type == undefined_t);
m_type = undefined_t;
}
}
void entry::copy(const entry& e)
{
m_type = e.m_type;
switch(m_type)
{
case int_t:
new(data) integer_type(e.integer());
break;
case string_t:
new(data) string_type(e.string());
break;
case list_t:
new(data) list_type(e.list());
break;
case dictionary_t:
new (data) dictionary_type(e.dict());
break;
default:
m_type = undefined_t;
}
}
void entry::destruct()
{
switch(m_type)
{
case int_t:
call_destructor(reinterpret_cast<integer_type*>(data));
break;
case string_t:
call_destructor(reinterpret_cast<string_type*>(data));
break;
case list_t:
call_destructor(reinterpret_cast<list_type*>(data));
break;
case dictionary_t:
call_destructor(reinterpret_cast<dictionary_type*>(data));
break;
default:
assert(m_type == undefined_t);
break;
}
}
void entry::print(std::ostream& os, int indent) const
{
assert(indent >= 0);
for (int i = 0; i < indent; ++i) os << " ";
switch (m_type)
{
case int_t:
os << integer() << "\n";
break;
case string_t:
{
bool binary_string = false;
for (std::string::const_iterator i = string().begin(); i != string().end(); ++i)
{
if (!std::isprint(static_cast<unsigned char>(*i)))
{
binary_string = true;
break;
}
}
if (binary_string)
{
os.unsetf(std::ios_base::dec);
os.setf(std::ios_base::hex);
for (std::string::const_iterator i = string().begin(); i != string().end(); ++i)
os << static_cast<unsigned int>((unsigned char)*i);
os.unsetf(std::ios_base::hex);
os.setf(std::ios_base::dec);
os << "\n";
}
else
{
os << string() << "\n";
}
} break;
case list_t:
{
os << "list\n";
for (list_type::const_iterator i = list().begin(); i != list().end(); ++i)
{
i->print(os, indent+1);
}
} break;
case dictionary_t:
{
os << "dictionary\n";
for (dictionary_type::const_iterator i = dict().begin(); i != dict().end(); ++i)
{
for (int j = 0; j < indent+1; ++j) os << " ";
os << "[" << i->first << "]";
if (i->second.type() != entry::string_t && i->second.type() != entry::int_t) os << "\n";
else os << " ";
i->second.print(os, indent+2);
}
} break;
default:
os << "<uninitialized>\n";
}
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: alienwarn.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2007-04-26 10:10:14 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sfx2.hxx"
#include "alienwarn.hxx"
#include "sfxresid.hxx"
#include "sfxuno.hxx"
#include "alienwarn.hrc"
#include "dialog.hrc"
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_SAVEOPT_HXX
#include <svtools/saveopt.hxx>
#endif
// class SfxAlienWarningDialog -------------------------------------------
SfxAlienWarningDialog::SfxAlienWarningDialog( Window* pParent, const String& _rFormatName ) :
SfxModalDialog( pParent, SfxResId( RID_DLG_ALIEN_WARNING ) ),
m_aQueryImage ( this, SfxResId( FI_QUERY ) ),
m_aInfoText ( this, SfxResId( FT_INFOTEXT ) ),
m_aYesBtn ( this, SfxResId( PB_YES ) ),
m_aNoBtn ( this, SfxResId( PB_NO ) ),
m_aMoreInfoBtn ( this, SfxResId( PB_MOREINFO ) ),
m_aOptionLine ( this, SfxResId( FL_OPTION ) ),
m_aWarningOffBox( this, SfxResId( CB_WARNING_OFF ) )
{
FreeResource();
// set questionmark image
m_aQueryImage.SetImage( QueryBox::GetStandardImage() );
// replace formatname
String sInfoText = m_aInfoText.GetText();
sInfoText.SearchAndReplaceAll( DEFINE_CONST_UNICODE("%FORMATNAME"), _rFormatName );
m_aInfoText.SetText( sInfoText );
// load value of "warning off" checkbox from save options
m_aWarningOffBox.Check( SvtSaveOptions().IsWarnAlienFormat() == sal_False );
// set focus to "No" button
m_aNoBtn.GrabFocus();
// pb: #i43989# we have no online help for this dialog at the moment
// -> hide the "more info" button
m_aMoreInfoBtn.Hide();
// calculate and set the size of the dialog and its controls
InitSize();
}
// -----------------------------------------------------------------------
SfxAlienWarningDialog::~SfxAlienWarningDialog()
{
// save value of "warning off" checkbox, if necessary
SvtSaveOptions aSaveOpt;
sal_Bool bChecked = !m_aWarningOffBox.IsChecked();
if ( aSaveOpt.IsWarnAlienFormat() != bChecked )
aSaveOpt.SetWarnAlienFormat( bChecked );
}
// -----------------------------------------------------------------------
void SfxAlienWarningDialog::InitSize()
{
// if the button text is too wide, then broaden the button
long nTxtW = m_aMoreInfoBtn.GetTextWidth( m_aMoreInfoBtn.GetText() );
long nCtrlW = m_aMoreInfoBtn.GetSizePixel().Width();
if ( nTxtW >= nCtrlW )
{
long nDelta = nTxtW - nCtrlW;
nDelta += 6; // a little more space looks better
Point aNextPoint = m_aNoBtn.GetPosPixel();
aNextPoint.X() += m_aNoBtn.GetSizePixel().Width();
Point aNewPoint = m_aMoreInfoBtn.GetPosPixel();
aNewPoint.X() -= nDelta;
if ( aNextPoint.X() >= aNewPoint.X() )
{
long nSpace = aNextPoint.X() - aNewPoint.X();
nSpace += 2;
nDelta -= nSpace;
aNewPoint.X() += nSpace;
}
Size aNewSize = m_aMoreInfoBtn.GetSizePixel();
aNewSize.Width() += nDelta;
m_aMoreInfoBtn.SetPosSizePixel( aNewPoint, aNewSize );
}
// text of checkbox to wide -> add new line
nTxtW = m_aWarningOffBox.GetTextWidth( m_aWarningOffBox.GetText() );
nCtrlW = m_aWarningOffBox.GetSizePixel().Width();
if ( nTxtW >= nCtrlW )
{
long nTextHeight = m_aWarningOffBox.GetTextHeight();
Size aNewSize = m_aWarningOffBox.GetSizePixel();
aNewSize.Height() += nTextHeight;
m_aWarningOffBox.SetSizePixel( aNewSize );
aNewSize = GetSizePixel();
aNewSize.Height() += nTextHeight;
SetSizePixel( aNewSize );
}
// align the size of the information text control (FixedText) to its content
Size aMinSize = m_aInfoText.CalcMinimumSize( m_aInfoText.GetSizePixel().Width() );
long nTxtH = aMinSize.Height();
long nCtrlH = m_aInfoText.GetSizePixel().Height();
long nDelta = ( nCtrlH - nTxtH );
Size aNewSize = m_aInfoText.GetSizePixel();
aNewSize.Height() -= nDelta;
m_aInfoText.SetSizePixel( aNewSize );
// new position for the succeeding windows
Window* pWins[] =
{
&m_aYesBtn, &m_aNoBtn, &m_aMoreInfoBtn, &m_aOptionLine, &m_aWarningOffBox
};
Window** pCurrent = pWins;
for ( sal_uInt32 i = 0; i < sizeof( pWins ) / sizeof( pWins[ 0 ] ); ++i, ++pCurrent )
{
Point aNewPos = (*pCurrent)->GetPosPixel();
aNewPos.Y() -= nDelta;
(*pCurrent)->SetPosPixel( aNewPos );
}
// new size of the dialog
aNewSize = GetSizePixel();
aNewSize.Height() -= nDelta;
SetSizePixel( aNewSize );
}
<commit_msg>INTEGRATION: CWS vgbugs07 (1.8.32); FILE MERGED 2007/06/04 13:34:46 vg 1.8.32.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: alienwarn.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: hr $ $Date: 2007-06-27 23:09:13 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sfx2.hxx"
#include "alienwarn.hxx"
#include "sfxresid.hxx"
#include <sfx2/sfxuno.hxx>
#include "alienwarn.hrc"
#include "dialog.hrc"
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_SAVEOPT_HXX
#include <svtools/saveopt.hxx>
#endif
// class SfxAlienWarningDialog -------------------------------------------
SfxAlienWarningDialog::SfxAlienWarningDialog( Window* pParent, const String& _rFormatName ) :
SfxModalDialog( pParent, SfxResId( RID_DLG_ALIEN_WARNING ) ),
m_aQueryImage ( this, SfxResId( FI_QUERY ) ),
m_aInfoText ( this, SfxResId( FT_INFOTEXT ) ),
m_aYesBtn ( this, SfxResId( PB_YES ) ),
m_aNoBtn ( this, SfxResId( PB_NO ) ),
m_aMoreInfoBtn ( this, SfxResId( PB_MOREINFO ) ),
m_aOptionLine ( this, SfxResId( FL_OPTION ) ),
m_aWarningOffBox( this, SfxResId( CB_WARNING_OFF ) )
{
FreeResource();
// set questionmark image
m_aQueryImage.SetImage( QueryBox::GetStandardImage() );
// replace formatname
String sInfoText = m_aInfoText.GetText();
sInfoText.SearchAndReplaceAll( DEFINE_CONST_UNICODE("%FORMATNAME"), _rFormatName );
m_aInfoText.SetText( sInfoText );
// load value of "warning off" checkbox from save options
m_aWarningOffBox.Check( SvtSaveOptions().IsWarnAlienFormat() == sal_False );
// set focus to "No" button
m_aNoBtn.GrabFocus();
// pb: #i43989# we have no online help for this dialog at the moment
// -> hide the "more info" button
m_aMoreInfoBtn.Hide();
// calculate and set the size of the dialog and its controls
InitSize();
}
// -----------------------------------------------------------------------
SfxAlienWarningDialog::~SfxAlienWarningDialog()
{
// save value of "warning off" checkbox, if necessary
SvtSaveOptions aSaveOpt;
sal_Bool bChecked = !m_aWarningOffBox.IsChecked();
if ( aSaveOpt.IsWarnAlienFormat() != bChecked )
aSaveOpt.SetWarnAlienFormat( bChecked );
}
// -----------------------------------------------------------------------
void SfxAlienWarningDialog::InitSize()
{
// if the button text is too wide, then broaden the button
long nTxtW = m_aMoreInfoBtn.GetTextWidth( m_aMoreInfoBtn.GetText() );
long nCtrlW = m_aMoreInfoBtn.GetSizePixel().Width();
if ( nTxtW >= nCtrlW )
{
long nDelta = nTxtW - nCtrlW;
nDelta += 6; // a little more space looks better
Point aNextPoint = m_aNoBtn.GetPosPixel();
aNextPoint.X() += m_aNoBtn.GetSizePixel().Width();
Point aNewPoint = m_aMoreInfoBtn.GetPosPixel();
aNewPoint.X() -= nDelta;
if ( aNextPoint.X() >= aNewPoint.X() )
{
long nSpace = aNextPoint.X() - aNewPoint.X();
nSpace += 2;
nDelta -= nSpace;
aNewPoint.X() += nSpace;
}
Size aNewSize = m_aMoreInfoBtn.GetSizePixel();
aNewSize.Width() += nDelta;
m_aMoreInfoBtn.SetPosSizePixel( aNewPoint, aNewSize );
}
// text of checkbox to wide -> add new line
nTxtW = m_aWarningOffBox.GetTextWidth( m_aWarningOffBox.GetText() );
nCtrlW = m_aWarningOffBox.GetSizePixel().Width();
if ( nTxtW >= nCtrlW )
{
long nTextHeight = m_aWarningOffBox.GetTextHeight();
Size aNewSize = m_aWarningOffBox.GetSizePixel();
aNewSize.Height() += nTextHeight;
m_aWarningOffBox.SetSizePixel( aNewSize );
aNewSize = GetSizePixel();
aNewSize.Height() += nTextHeight;
SetSizePixel( aNewSize );
}
// align the size of the information text control (FixedText) to its content
Size aMinSize = m_aInfoText.CalcMinimumSize( m_aInfoText.GetSizePixel().Width() );
long nTxtH = aMinSize.Height();
long nCtrlH = m_aInfoText.GetSizePixel().Height();
long nDelta = ( nCtrlH - nTxtH );
Size aNewSize = m_aInfoText.GetSizePixel();
aNewSize.Height() -= nDelta;
m_aInfoText.SetSizePixel( aNewSize );
// new position for the succeeding windows
Window* pWins[] =
{
&m_aYesBtn, &m_aNoBtn, &m_aMoreInfoBtn, &m_aOptionLine, &m_aWarningOffBox
};
Window** pCurrent = pWins;
for ( sal_uInt32 i = 0; i < sizeof( pWins ) / sizeof( pWins[ 0 ] ); ++i, ++pCurrent )
{
Point aNewPos = (*pCurrent)->GetPosPixel();
aNewPos.Y() -= nDelta;
(*pCurrent)->SetPosPixel( aNewPos );
}
// new size of the dialog
aNewSize = GetSizePixel();
aNewSize.Height() -= nDelta;
SetSizePixel( aNewSize );
}
<|endoftext|>
|
<commit_before>// Formatting library for C++
//
// Copyright (c) 2012 - 2016, Victor Zverovich
// All rights reserved.
//
// For the license information refer to format.h.
#include "fmt/format-inl.h"
FMT_BEGIN_NAMESPACE
template struct FMT_API internal::basic_data<void>;
// Workaround a bug in MSVC2013 that prevents instantiation of format_float.
int (*instantiate_format_float)(double, int, internal::float_spec,
internal::buffer<char>&) =
internal::format_float;
#ifndef FMT_STATIC_THOUSANDS_SEPARATOR
template FMT_API internal::locale_ref::locale_ref(const std::locale& loc);
template FMT_API std::locale internal::locale_ref::get<std::locale>() const;
#endif
// Explicit instantiations for char.
template FMT_API std::string internal::grouping_impl<char>(locale_ref);
template FMT_API char internal::thousands_sep_impl(locale_ref);
template FMT_API char internal::decimal_point_impl(locale_ref);
template FMT_API void internal::buffer<char>::append(const char*, const char*);
template FMT_API void internal::arg_map<format_context>::init(
const basic_format_args<format_context>& args);
template FMT_API std::string internal::vformat<char>(
string_view, basic_format_args<format_context>);
template FMT_API format_context::iterator internal::vformat_to(
internal::buffer<char>&, string_view, basic_format_args<format_context>);
template FMT_API int internal::format_float(double, int, internal::float_spec,
internal::buffer<char>&);
template FMT_API int internal::format_float(long double, int,
internal::float_spec,
internal::buffer<char>&);
// Explicit instantiations for wchar_t.
template FMT_API std::string internal::grouping_impl<wchar_t>(locale_ref);
template FMT_API wchar_t internal::thousands_sep_impl(locale_ref);
template FMT_API wchar_t internal::decimal_point_impl(locale_ref);
template FMT_API void internal::buffer<wchar_t>::append(const wchar_t*,
const wchar_t*);
template FMT_API void internal::arg_map<wformat_context>::init(
const basic_format_args<wformat_context>&);
template FMT_API std::wstring internal::vformat<wchar_t>(
wstring_view, basic_format_args<wformat_context>);
FMT_END_NAMESPACE
<commit_msg>Instantiate snprintf_float<commit_after>// Formatting library for C++
//
// Copyright (c) 2012 - 2016, Victor Zverovich
// All rights reserved.
//
// For the license information refer to format.h.
#include "fmt/format-inl.h"
FMT_BEGIN_NAMESPACE
template struct FMT_API internal::basic_data<void>;
// Workaround a bug in MSVC2013 that prevents instantiation of format_float.
int (*instantiate_format_float)(double, int, internal::float_spec,
internal::buffer<char>&) =
internal::format_float;
#ifndef FMT_STATIC_THOUSANDS_SEPARATOR
template FMT_API internal::locale_ref::locale_ref(const std::locale& loc);
template FMT_API std::locale internal::locale_ref::get<std::locale>() const;
#endif
// Explicit instantiations for char.
template FMT_API std::string internal::grouping_impl<char>(locale_ref);
template FMT_API char internal::thousands_sep_impl(locale_ref);
template FMT_API char internal::decimal_point_impl(locale_ref);
template FMT_API void internal::buffer<char>::append(const char*, const char*);
template FMT_API void internal::arg_map<format_context>::init(
const basic_format_args<format_context>& args);
template FMT_API std::string internal::vformat<char>(
string_view, basic_format_args<format_context>);
template FMT_API format_context::iterator internal::vformat_to(
internal::buffer<char>&, string_view, basic_format_args<format_context>);
template FMT_API int internal::snprintf_float(double, int, internal::float_spec,
internal::buffer<char>&);
template FMT_API int internal::snprintf_float(long double, int,
internal::float_spec,
internal::buffer<char>&);
template FMT_API int internal::format_float(double, int, internal::float_spec,
internal::buffer<char>&);
template FMT_API int internal::format_float(long double, int,
internal::float_spec,
internal::buffer<char>&);
// Explicit instantiations for wchar_t.
template FMT_API std::string internal::grouping_impl<wchar_t>(locale_ref);
template FMT_API wchar_t internal::thousands_sep_impl(locale_ref);
template FMT_API wchar_t internal::decimal_point_impl(locale_ref);
template FMT_API void internal::buffer<wchar_t>::append(const wchar_t*,
const wchar_t*);
template FMT_API void internal::arg_map<wformat_context>::init(
const basic_format_args<wformat_context>&);
template FMT_API std::wstring internal::vformat<wchar_t>(
wstring_view, basic_format_args<wformat_context>);
FMT_END_NAMESPACE
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012 Thomas Kemmer <tkemmer@computer.org>
*
* http://code.google.com/p/stlencoders/
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef STLENCODERS_LOOKUP_HPP
#define STLENCODERS_LOOKUP_HPP
namespace stlencoders {
template<template<char> class LUT, class T>
inline const T& lookup(char c, const T& def)
{
static const T table[256] = {
LUT<'\000'>::value, LUT<'\001'>::value, LUT<'\002'>::value, LUT<'\003'>::value,
LUT<'\004'>::value, LUT<'\005'>::value, LUT<'\006'>::value, LUT<'\007'>::value,
LUT<'\010'>::value, LUT<'\011'>::value, LUT<'\012'>::value, LUT<'\013'>::value,
LUT<'\014'>::value, LUT<'\015'>::value, LUT<'\016'>::value, LUT<'\017'>::value,
LUT<'\020'>::value, LUT<'\021'>::value, LUT<'\022'>::value, LUT<'\023'>::value,
LUT<'\024'>::value, LUT<'\025'>::value, LUT<'\026'>::value, LUT<'\027'>::value,
LUT<'\030'>::value, LUT<'\031'>::value, LUT<'\032'>::value, LUT<'\033'>::value,
LUT<'\034'>::value, LUT<'\035'>::value, LUT<'\036'>::value, LUT<'\037'>::value,
LUT<'\040'>::value, LUT<'\041'>::value, LUT<'\042'>::value, LUT<'\043'>::value,
LUT<'\044'>::value, LUT<'\045'>::value, LUT<'\046'>::value, LUT<'\047'>::value,
LUT<'\050'>::value, LUT<'\051'>::value, LUT<'\052'>::value, LUT<'\053'>::value,
LUT<'\054'>::value, LUT<'\055'>::value, LUT<'\056'>::value, LUT<'\057'>::value,
LUT<'\060'>::value, LUT<'\061'>::value, LUT<'\062'>::value, LUT<'\063'>::value,
LUT<'\064'>::value, LUT<'\065'>::value, LUT<'\066'>::value, LUT<'\067'>::value,
LUT<'\070'>::value, LUT<'\071'>::value, LUT<'\072'>::value, LUT<'\073'>::value,
LUT<'\074'>::value, LUT<'\075'>::value, LUT<'\076'>::value, LUT<'\077'>::value,
LUT<'\100'>::value, LUT<'\101'>::value, LUT<'\102'>::value, LUT<'\103'>::value,
LUT<'\104'>::value, LUT<'\105'>::value, LUT<'\106'>::value, LUT<'\107'>::value,
LUT<'\110'>::value, LUT<'\111'>::value, LUT<'\112'>::value, LUT<'\113'>::value,
LUT<'\114'>::value, LUT<'\115'>::value, LUT<'\116'>::value, LUT<'\117'>::value,
LUT<'\120'>::value, LUT<'\121'>::value, LUT<'\122'>::value, LUT<'\123'>::value,
LUT<'\124'>::value, LUT<'\125'>::value, LUT<'\126'>::value, LUT<'\127'>::value,
LUT<'\130'>::value, LUT<'\131'>::value, LUT<'\132'>::value, LUT<'\133'>::value,
LUT<'\134'>::value, LUT<'\135'>::value, LUT<'\136'>::value, LUT<'\137'>::value,
LUT<'\140'>::value, LUT<'\141'>::value, LUT<'\142'>::value, LUT<'\143'>::value,
LUT<'\144'>::value, LUT<'\145'>::value, LUT<'\146'>::value, LUT<'\147'>::value,
LUT<'\150'>::value, LUT<'\151'>::value, LUT<'\152'>::value, LUT<'\153'>::value,
LUT<'\154'>::value, LUT<'\155'>::value, LUT<'\156'>::value, LUT<'\157'>::value,
LUT<'\160'>::value, LUT<'\161'>::value, LUT<'\162'>::value, LUT<'\163'>::value,
LUT<'\164'>::value, LUT<'\165'>::value, LUT<'\166'>::value, LUT<'\167'>::value,
LUT<'\170'>::value, LUT<'\171'>::value, LUT<'\172'>::value, LUT<'\173'>::value,
LUT<'\174'>::value, LUT<'\175'>::value, LUT<'\176'>::value, LUT<'\177'>::value,
LUT<'\200'>::value, LUT<'\201'>::value, LUT<'\202'>::value, LUT<'\203'>::value,
LUT<'\204'>::value, LUT<'\205'>::value, LUT<'\206'>::value, LUT<'\207'>::value,
LUT<'\210'>::value, LUT<'\211'>::value, LUT<'\212'>::value, LUT<'\213'>::value,
LUT<'\214'>::value, LUT<'\215'>::value, LUT<'\216'>::value, LUT<'\217'>::value,
LUT<'\220'>::value, LUT<'\221'>::value, LUT<'\222'>::value, LUT<'\223'>::value,
LUT<'\224'>::value, LUT<'\225'>::value, LUT<'\226'>::value, LUT<'\227'>::value,
LUT<'\230'>::value, LUT<'\231'>::value, LUT<'\232'>::value, LUT<'\233'>::value,
LUT<'\234'>::value, LUT<'\235'>::value, LUT<'\236'>::value, LUT<'\237'>::value,
LUT<'\240'>::value, LUT<'\241'>::value, LUT<'\242'>::value, LUT<'\243'>::value,
LUT<'\244'>::value, LUT<'\245'>::value, LUT<'\246'>::value, LUT<'\247'>::value,
LUT<'\250'>::value, LUT<'\251'>::value, LUT<'\252'>::value, LUT<'\253'>::value,
LUT<'\254'>::value, LUT<'\255'>::value, LUT<'\256'>::value, LUT<'\257'>::value,
LUT<'\260'>::value, LUT<'\261'>::value, LUT<'\262'>::value, LUT<'\263'>::value,
LUT<'\264'>::value, LUT<'\265'>::value, LUT<'\266'>::value, LUT<'\267'>::value,
LUT<'\270'>::value, LUT<'\271'>::value, LUT<'\272'>::value, LUT<'\273'>::value,
LUT<'\274'>::value, LUT<'\275'>::value, LUT<'\276'>::value, LUT<'\277'>::value,
LUT<'\300'>::value, LUT<'\301'>::value, LUT<'\302'>::value, LUT<'\303'>::value,
LUT<'\304'>::value, LUT<'\305'>::value, LUT<'\306'>::value, LUT<'\307'>::value,
LUT<'\310'>::value, LUT<'\311'>::value, LUT<'\312'>::value, LUT<'\313'>::value,
LUT<'\314'>::value, LUT<'\315'>::value, LUT<'\316'>::value, LUT<'\317'>::value,
LUT<'\320'>::value, LUT<'\321'>::value, LUT<'\322'>::value, LUT<'\323'>::value,
LUT<'\324'>::value, LUT<'\325'>::value, LUT<'\326'>::value, LUT<'\327'>::value,
LUT<'\330'>::value, LUT<'\331'>::value, LUT<'\332'>::value, LUT<'\333'>::value,
LUT<'\334'>::value, LUT<'\335'>::value, LUT<'\336'>::value, LUT<'\337'>::value,
LUT<'\340'>::value, LUT<'\341'>::value, LUT<'\342'>::value, LUT<'\343'>::value,
LUT<'\344'>::value, LUT<'\345'>::value, LUT<'\346'>::value, LUT<'\347'>::value,
LUT<'\350'>::value, LUT<'\351'>::value, LUT<'\352'>::value, LUT<'\353'>::value,
LUT<'\354'>::value, LUT<'\355'>::value, LUT<'\356'>::value, LUT<'\357'>::value,
LUT<'\360'>::value, LUT<'\361'>::value, LUT<'\362'>::value, LUT<'\363'>::value,
LUT<'\364'>::value, LUT<'\365'>::value, LUT<'\366'>::value, LUT<'\367'>::value,
LUT<'\370'>::value, LUT<'\371'>::value, LUT<'\372'>::value, LUT<'\373'>::value,
LUT<'\374'>::value, LUT<'\375'>::value, LUT<'\376'>::value, LUT<'\377'>::value
};
if (static_cast<unsigned char>(c) < 256)
return table[static_cast<unsigned char>(c)];
else
return def;
}
}
#endif
<commit_msg>fix warning<commit_after>/*
* Copyright (c) 2012 Thomas Kemmer <tkemmer@computer.org>
*
* http://code.google.com/p/stlencoders/
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef STLENCODERS_LOOKUP_HPP
#define STLENCODERS_LOOKUP_HPP
namespace stlencoders {
template<template<char> class LUT, class T>
inline const T& lookup(char c, const T& def)
{
static const T table[256] = {
LUT<'\000'>::value, LUT<'\001'>::value, LUT<'\002'>::value, LUT<'\003'>::value,
LUT<'\004'>::value, LUT<'\005'>::value, LUT<'\006'>::value, LUT<'\007'>::value,
LUT<'\010'>::value, LUT<'\011'>::value, LUT<'\012'>::value, LUT<'\013'>::value,
LUT<'\014'>::value, LUT<'\015'>::value, LUT<'\016'>::value, LUT<'\017'>::value,
LUT<'\020'>::value, LUT<'\021'>::value, LUT<'\022'>::value, LUT<'\023'>::value,
LUT<'\024'>::value, LUT<'\025'>::value, LUT<'\026'>::value, LUT<'\027'>::value,
LUT<'\030'>::value, LUT<'\031'>::value, LUT<'\032'>::value, LUT<'\033'>::value,
LUT<'\034'>::value, LUT<'\035'>::value, LUT<'\036'>::value, LUT<'\037'>::value,
LUT<'\040'>::value, LUT<'\041'>::value, LUT<'\042'>::value, LUT<'\043'>::value,
LUT<'\044'>::value, LUT<'\045'>::value, LUT<'\046'>::value, LUT<'\047'>::value,
LUT<'\050'>::value, LUT<'\051'>::value, LUT<'\052'>::value, LUT<'\053'>::value,
LUT<'\054'>::value, LUT<'\055'>::value, LUT<'\056'>::value, LUT<'\057'>::value,
LUT<'\060'>::value, LUT<'\061'>::value, LUT<'\062'>::value, LUT<'\063'>::value,
LUT<'\064'>::value, LUT<'\065'>::value, LUT<'\066'>::value, LUT<'\067'>::value,
LUT<'\070'>::value, LUT<'\071'>::value, LUT<'\072'>::value, LUT<'\073'>::value,
LUT<'\074'>::value, LUT<'\075'>::value, LUT<'\076'>::value, LUT<'\077'>::value,
LUT<'\100'>::value, LUT<'\101'>::value, LUT<'\102'>::value, LUT<'\103'>::value,
LUT<'\104'>::value, LUT<'\105'>::value, LUT<'\106'>::value, LUT<'\107'>::value,
LUT<'\110'>::value, LUT<'\111'>::value, LUT<'\112'>::value, LUT<'\113'>::value,
LUT<'\114'>::value, LUT<'\115'>::value, LUT<'\116'>::value, LUT<'\117'>::value,
LUT<'\120'>::value, LUT<'\121'>::value, LUT<'\122'>::value, LUT<'\123'>::value,
LUT<'\124'>::value, LUT<'\125'>::value, LUT<'\126'>::value, LUT<'\127'>::value,
LUT<'\130'>::value, LUT<'\131'>::value, LUT<'\132'>::value, LUT<'\133'>::value,
LUT<'\134'>::value, LUT<'\135'>::value, LUT<'\136'>::value, LUT<'\137'>::value,
LUT<'\140'>::value, LUT<'\141'>::value, LUT<'\142'>::value, LUT<'\143'>::value,
LUT<'\144'>::value, LUT<'\145'>::value, LUT<'\146'>::value, LUT<'\147'>::value,
LUT<'\150'>::value, LUT<'\151'>::value, LUT<'\152'>::value, LUT<'\153'>::value,
LUT<'\154'>::value, LUT<'\155'>::value, LUT<'\156'>::value, LUT<'\157'>::value,
LUT<'\160'>::value, LUT<'\161'>::value, LUT<'\162'>::value, LUT<'\163'>::value,
LUT<'\164'>::value, LUT<'\165'>::value, LUT<'\166'>::value, LUT<'\167'>::value,
LUT<'\170'>::value, LUT<'\171'>::value, LUT<'\172'>::value, LUT<'\173'>::value,
LUT<'\174'>::value, LUT<'\175'>::value, LUT<'\176'>::value, LUT<'\177'>::value,
LUT<'\200'>::value, LUT<'\201'>::value, LUT<'\202'>::value, LUT<'\203'>::value,
LUT<'\204'>::value, LUT<'\205'>::value, LUT<'\206'>::value, LUT<'\207'>::value,
LUT<'\210'>::value, LUT<'\211'>::value, LUT<'\212'>::value, LUT<'\213'>::value,
LUT<'\214'>::value, LUT<'\215'>::value, LUT<'\216'>::value, LUT<'\217'>::value,
LUT<'\220'>::value, LUT<'\221'>::value, LUT<'\222'>::value, LUT<'\223'>::value,
LUT<'\224'>::value, LUT<'\225'>::value, LUT<'\226'>::value, LUT<'\227'>::value,
LUT<'\230'>::value, LUT<'\231'>::value, LUT<'\232'>::value, LUT<'\233'>::value,
LUT<'\234'>::value, LUT<'\235'>::value, LUT<'\236'>::value, LUT<'\237'>::value,
LUT<'\240'>::value, LUT<'\241'>::value, LUT<'\242'>::value, LUT<'\243'>::value,
LUT<'\244'>::value, LUT<'\245'>::value, LUT<'\246'>::value, LUT<'\247'>::value,
LUT<'\250'>::value, LUT<'\251'>::value, LUT<'\252'>::value, LUT<'\253'>::value,
LUT<'\254'>::value, LUT<'\255'>::value, LUT<'\256'>::value, LUT<'\257'>::value,
LUT<'\260'>::value, LUT<'\261'>::value, LUT<'\262'>::value, LUT<'\263'>::value,
LUT<'\264'>::value, LUT<'\265'>::value, LUT<'\266'>::value, LUT<'\267'>::value,
LUT<'\270'>::value, LUT<'\271'>::value, LUT<'\272'>::value, LUT<'\273'>::value,
LUT<'\274'>::value, LUT<'\275'>::value, LUT<'\276'>::value, LUT<'\277'>::value,
LUT<'\300'>::value, LUT<'\301'>::value, LUT<'\302'>::value, LUT<'\303'>::value,
LUT<'\304'>::value, LUT<'\305'>::value, LUT<'\306'>::value, LUT<'\307'>::value,
LUT<'\310'>::value, LUT<'\311'>::value, LUT<'\312'>::value, LUT<'\313'>::value,
LUT<'\314'>::value, LUT<'\315'>::value, LUT<'\316'>::value, LUT<'\317'>::value,
LUT<'\320'>::value, LUT<'\321'>::value, LUT<'\322'>::value, LUT<'\323'>::value,
LUT<'\324'>::value, LUT<'\325'>::value, LUT<'\326'>::value, LUT<'\327'>::value,
LUT<'\330'>::value, LUT<'\331'>::value, LUT<'\332'>::value, LUT<'\333'>::value,
LUT<'\334'>::value, LUT<'\335'>::value, LUT<'\336'>::value, LUT<'\337'>::value,
LUT<'\340'>::value, LUT<'\341'>::value, LUT<'\342'>::value, LUT<'\343'>::value,
LUT<'\344'>::value, LUT<'\345'>::value, LUT<'\346'>::value, LUT<'\347'>::value,
LUT<'\350'>::value, LUT<'\351'>::value, LUT<'\352'>::value, LUT<'\353'>::value,
LUT<'\354'>::value, LUT<'\355'>::value, LUT<'\356'>::value, LUT<'\357'>::value,
LUT<'\360'>::value, LUT<'\361'>::value, LUT<'\362'>::value, LUT<'\363'>::value,
LUT<'\364'>::value, LUT<'\365'>::value, LUT<'\366'>::value, LUT<'\367'>::value,
LUT<'\370'>::value, LUT<'\371'>::value, LUT<'\372'>::value, LUT<'\373'>::value,
LUT<'\374'>::value, LUT<'\375'>::value, LUT<'\376'>::value, LUT<'\377'>::value
};
if (static_cast<unsigned>(c) < sizeof(table))
return table[static_cast<unsigned>(c)];
else
return def;
}
}
#endif
<|endoftext|>
|
<commit_before>#include <GLFW/glfw3.h>
int main(void)
{
GLFWwindow* window;
/* Initialize the library */
if (!glfwInit())
return -1;
/* Create a windowed mode window and its OpenGL context */
window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
if (!window)
{
glfwTerminate();
return -1;
}
/* Make the window's context current */
glfwMakeContextCurrent(window);
/* Loop until the user closes the window */
while (!glfwWindowShouldClose(window))
{
/* Render here */
glClearColor(0.2f, 0.3f, 0.4f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
/* Swap front and back buffers */
glfwSwapBuffers(window);
/* Poll for and process events */
glfwPollEvents();
}
glfwTerminate();
return 0;
}
<commit_msg>basic input<commit_after>#include <GLFW/glfw3.h>
#include <cstdlib>
#include <iostream>
const int WIDTH = 1280;
const int HEIGHT = 720;
float blueOffset = 0;
float greenOffset = 0;
bool keys[512];
void processInput();
int main(int argc, char* argv[])
{
if (!glfwInit()) {
return EXIT_FAILURE;
}
glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE);
GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "Fuzzy", nullptr, nullptr);
if (!window) {
glfwTerminate();
return EXIT_FAILURE;
}
GLFWmonitor* monitor = glfwGetPrimaryMonitor();
const GLFWvidmode* vidmode = glfwGetVideoMode(monitor);
glfwSetWindowPos(window, (vidmode->width - WIDTH) / 2, (vidmode->height - HEIGHT) / 2);
glfwSetKeyCallback(window, [](GLFWwindow* window, int key, int scancode, int action, int mods) {
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) {
glfwSetWindowShouldClose(window, GLFW_TRUE);
}
if (action == GLFW_PRESS) {
keys[key] = true;
} else if (action == GLFW_RELEASE) {
keys[key] = false;
}
});
glfwMakeContextCurrent(window);
while (!glfwWindowShouldClose(window)) {
glfwPollEvents();
processInput();
glClearColor(0.5f, greenOffset, blueOffset, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glfwSwapBuffers(window);
}
glfwTerminate();
return EXIT_SUCCESS;
}
void processInput() {
float step = 0.0005f;
if (keys[GLFW_KEY_UP] == GLFW_PRESS) {
if (blueOffset < 1.0f) {
blueOffset += step;
}
}
if (keys[GLFW_KEY_DOWN] == GLFW_PRESS) {
if (blueOffset > 0.f) {
blueOffset -= step;
}
}
if (keys[GLFW_KEY_RIGHT] == GLFW_PRESS) {
if (greenOffset < 1.0f) {
greenOffset += step;
}
}
if (keys[GLFW_KEY_LEFT] == GLFW_PRESS) {
if (greenOffset > 0.f) {
greenOffset -= step;
}
}
}
<|endoftext|>
|
<commit_before>#include <stan/math/rev/mat.hpp>
#include <boost/random.hpp>
#include <stan/math/prim/scal/prob/lognormal_rng.hpp>
#include <gtest/gtest.h>
// very small michaelis menten example
#include <test/unit/math/rev/arr/functor/coupled_mm.hpp>
#include <test/unit/util.hpp>
#include <vector>
// test which triggers the too much work exception from odeint
TEST(StanOde_tooMuchWork_test, cvodes_coupled_mm) {
coupled_mm_ode_fun f_;
boost::ecuyer1988 rng;
// initial value and parameters from model definition
double t0 = 0;
std::vector<double> ts_long;
ts_long.push_back(1E10);
std::vector<double> ts_short;
ts_short.push_back(1);
std::vector<double> data;
std::vector<int> data_int;
for(std::size_t i = 0; i < 1000; i++) {
stan::math::start_nested();
std::vector<stan::math::var> theta_v(4);
theta_v[0] = stan::math::lognormal_rng(1, 2, rng);
theta_v[1] = stan::math::lognormal_rng(-1, 2, rng);
theta_v[2] = stan::math::lognormal_rng(-1, 2, rng);
theta_v[3] = stan::math::lognormal_rng(-2, 2, rng);
std::vector<stan::math::var> y0_v(2);
y0_v[0] = stan::math::lognormal_rng(5, 2, rng);
y0_v[1] = stan::math::lognormal_rng(-1, 2, rng);
std::vector<std::vector<stan::math::var> > res = stan::math::integrate_ode_bdf(f_, y0_v, t0, ts_long, theta_v, data,
data_int, 0, 1E-10, 1E-10, 10000);
stan::math::grad(res[0][0].vi_);
stan::math::recover_memory_nested();
}
}
<commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0 (tags/google/stable/2017-11-14)<commit_after>#include <stan/math/rev/mat.hpp>
#include <boost/random.hpp>
#include <stan/math/prim/scal/prob/lognormal_rng.hpp>
#include <gtest/gtest.h>
// very small michaelis menten example
#include <test/unit/math/rev/arr/functor/coupled_mm.hpp>
#include <test/unit/util.hpp>
#include <vector>
// test which triggers the too much work exception from odeint
TEST(StanOde_tooMuchWork_test, cvodes_coupled_mm) {
coupled_mm_ode_fun f_;
boost::ecuyer1988 rng;
// initial value and parameters from model definition
double t0 = 0;
std::vector<double> ts_long;
ts_long.push_back(1E10);
std::vector<double> ts_short;
ts_short.push_back(1);
std::vector<double> data;
std::vector<int> data_int;
for (std::size_t i = 0; i < 1000; i++) {
stan::math::start_nested();
std::vector<stan::math::var> theta_v(4);
theta_v[0] = stan::math::lognormal_rng(1, 2, rng);
theta_v[1] = stan::math::lognormal_rng(-1, 2, rng);
theta_v[2] = stan::math::lognormal_rng(-1, 2, rng);
theta_v[3] = stan::math::lognormal_rng(-2, 2, rng);
std::vector<stan::math::var> y0_v(2);
y0_v[0] = stan::math::lognormal_rng(5, 2, rng);
y0_v[1] = stan::math::lognormal_rng(-1, 2, rng);
std::vector<std::vector<stan::math::var> > res
= stan::math::integrate_ode_bdf(f_, y0_v, t0, ts_long, theta_v, data,
data_int, 0, 1E-10, 1E-10, 10000);
stan::math::grad(res[0][0].vi_);
stan::math::recover_memory_nested();
}
}
<|endoftext|>
|
<commit_before>// a layer of 3d clouds
//
// Written by Harald JOHNSEN, started April 2005.
//
// Copyright (C) 2005 Harald JOHNSEN - hjohnsen@evc.net
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
//
#ifndef _CLOUDFIELD_HXX
#define _CLOUDFIELD_HXX
#include <plib/sg.h>
#include <simgear/compiler.h>
#include <vector>
#include <osgDB/ReaderWriter>
#include <osg/ref_ptr>
#include <osg/Array>
#include <osg/Geometry>
#include <osg/Group>
#include <osg/Switch>
namespace osg
{
class Fog;
class StateSet;
class Vec4f;
}
#include <simgear/misc/sg_path.hxx>
#include <simgear/structure/Singleton.hxx>
#include <Simgear/math/SGMath.hxx>
using std::vector;
class SGNewCloud;
/**
* A layer of 3D clouds.
*/
class SGCloudField {
private:
class Cloud {
public:
SGNewCloud *aCloud;
sgVec3 pos;
bool visible;
};
float Rnd(float);
// We create a quadtree two levels deep
static const int BRANCH_SIZE = 16;
static const int QUADTREE_SIZE = 32;
// this is a relative position only, with that we can move all clouds at once
sgVec3 relative_position;
// double lon, lat;
osg::ref_ptr<osg::Group> field_root;
osg::ref_ptr<osg::MatrixTransform> field_transform;
osg::ref_ptr<osg::PositionAttitudeTransform> altitude_transform;
osg::ref_ptr<osg::Switch> field_group[QUADTREE_SIZE][QUADTREE_SIZE];
osg::ref_ptr<osg::LOD> quad[BRANCH_SIZE][BRANCH_SIZE];
osg::ref_ptr<osg::LOD> field_lod;
double deltax, deltay, alt;
double last_course;
sgSphere field_sphere;
float last_coverage;
float coverage;
SGGeoc cld_pos;
int reposition_count;
struct CloudFog : public simgear::Singleton<CloudFog>
{
CloudFog();
osg::ref_ptr<osg::Fog> fog;
};
public:
SGCloudField();
~SGCloudField();
void clear(void);
// add one cloud, data is not copied, ownership given
void addCloud( SGVec3f& pos, SGNewCloud *cloud);
/**
* reposition the cloud layer at the specified origin and
* orientation.
* @param p position vector
* @param up the local up vector
* @param lon specifies a rotation about the Z axis
* @param lat specifies a rotation about the new Y axis
* @param dt the time elapsed since the last call
* @param asl altitude of the layer
*/
bool reposition( const SGVec3f& p, const SGVec3f& up,
double lon, double lat, double dt, int asl);
osg::Group* getNode() { return field_root.get(); }
// visibility distance for clouds in meters
static float CloudVis;
static sgVec3 view_vec, view_X, view_Y;
static float view_distance;
static double timer_dt;
static float fieldSize;
bool defined3D;
float getCoverage(void) { return coverage; }
void setCoverage(float c) { coverage = c; }
static float getVisRange(void) { return view_distance; }
static void setVisRange(float d) { view_distance = d; }
void applyCoverage(void);
void applyVisRange(void);
static osg::Fog* getFog()
{
return CloudFog::instance()->fog.get();
}
static void updateFog(double visibility, const osg::Vec4f& color);
};
#endif // _CLOUDFIELD_HXX
<commit_msg>fix a typo<commit_after>// a layer of 3d clouds
//
// Written by Harald JOHNSEN, started April 2005.
//
// Copyright (C) 2005 Harald JOHNSEN - hjohnsen@evc.net
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
//
#ifndef _CLOUDFIELD_HXX
#define _CLOUDFIELD_HXX
#include <plib/sg.h>
#include <simgear/compiler.h>
#include <vector>
#include <osgDB/ReaderWriter>
#include <osg/ref_ptr>
#include <osg/Array>
#include <osg/Geometry>
#include <osg/Group>
#include <osg/Switch>
namespace osg
{
class Fog;
class StateSet;
class Vec4f;
}
#include <simgear/misc/sg_path.hxx>
#include <simgear/structure/Singleton.hxx>
#include <simgear/math/SGMath.hxx>
using std::vector;
class SGNewCloud;
/**
* A layer of 3D clouds.
*/
class SGCloudField {
private:
class Cloud {
public:
SGNewCloud *aCloud;
sgVec3 pos;
bool visible;
};
float Rnd(float);
// We create a quadtree two levels deep
static const int BRANCH_SIZE = 16;
static const int QUADTREE_SIZE = 32;
// this is a relative position only, with that we can move all clouds at once
sgVec3 relative_position;
// double lon, lat;
osg::ref_ptr<osg::Group> field_root;
osg::ref_ptr<osg::MatrixTransform> field_transform;
osg::ref_ptr<osg::PositionAttitudeTransform> altitude_transform;
osg::ref_ptr<osg::Switch> field_group[QUADTREE_SIZE][QUADTREE_SIZE];
osg::ref_ptr<osg::LOD> quad[BRANCH_SIZE][BRANCH_SIZE];
osg::ref_ptr<osg::LOD> field_lod;
double deltax, deltay, alt;
double last_course;
sgSphere field_sphere;
float last_coverage;
float coverage;
SGGeoc cld_pos;
int reposition_count;
struct CloudFog : public simgear::Singleton<CloudFog>
{
CloudFog();
osg::ref_ptr<osg::Fog> fog;
};
public:
SGCloudField();
~SGCloudField();
void clear(void);
// add one cloud, data is not copied, ownership given
void addCloud( SGVec3f& pos, SGNewCloud *cloud);
/**
* reposition the cloud layer at the specified origin and
* orientation.
* @param p position vector
* @param up the local up vector
* @param lon specifies a rotation about the Z axis
* @param lat specifies a rotation about the new Y axis
* @param dt the time elapsed since the last call
* @param asl altitude of the layer
*/
bool reposition( const SGVec3f& p, const SGVec3f& up,
double lon, double lat, double dt, int asl);
osg::Group* getNode() { return field_root.get(); }
// visibility distance for clouds in meters
static float CloudVis;
static sgVec3 view_vec, view_X, view_Y;
static float view_distance;
static double timer_dt;
static float fieldSize;
bool defined3D;
float getCoverage(void) { return coverage; }
void setCoverage(float c) { coverage = c; }
static float getVisRange(void) { return view_distance; }
static void setVisRange(float d) { view_distance = d; }
void applyCoverage(void);
void applyVisRange(void);
static osg::Fog* getFog()
{
return CloudFog::instance()->fog.get();
}
static void updateFog(double visibility, const osg::Vec4f& color);
};
#endif // _CLOUDFIELD_HXX
<|endoftext|>
|
<commit_before>#include"all_defines.hpp"
#include"objects.hpp"
#include"heaps.hpp"
#include"types.hpp"
#include<cstdlib>
#include<stdint.h>
/*-----------------------------------------------------------------------------
Semispaces
-----------------------------------------------------------------------------*/
Semispace::Semispace(size_t nsz)
: max(nsz) {
mem = std::malloc(nsz);
if(!mem) throw std::bad_alloc();
allocpt = mem;
// check alignment
intptr_t tmp = reinterpret_cast<intptr_t>(allocpt);
if(tmp & Object::tag_mask) {
char* callocpt = allocpt;
callocpt += Object::alignment - (tmp & Object::tag_mask);
allocpt = callocpt;
}
allocstart = allocpt;
char* cmem = mem;
char* clifoallocpt = cmem + nsz;
// adjust for alignment
tmp = reinterpret_cast<intptr_t>(lifoallocpt);
clifoallocpt -= (tmp & Object::tag_mask);
lifoallocpt = clifoallocpt;
}
Semispace::~Semispace() {
Generic* gp;
size_t step;
char* mvpt;
char* endpt;
/*TODO: consider refactoring*/
/*----Delete normally-allocated memory----*/
mvpt = allocstart;
endpt = allocpt;
while(mvpt < endpt) {
gp = (Generic*)(void*) mvpt;
step = gp->real_size();
gp->~Generic();
mvpt += step;
}
/*----Delete lifo-allocated memory----*/
mvpt = lifoallocpt;
endpt = lifoallocstart;
while(mvpt < endpt) {
gp = (Generic*)(void*) mvpt;
step = gp->real_size();
gp->~Generic();
mvpt += step;
}
}
/*
sz must be computed using the exact same
computation used in real_size() of the
object to be allocated. This includes
alignment.
*/
void* Semispace::alloc(size_t sz) {
prev_alloc = sz;
void* tmp = allocpt;
char* callocpt = allocpt;
callocpt += sz;
allocpt = callocpt;
return tmp;
}
/*should be used only for most recent allocation
(i.e. should be used for freeing memory when the
constructor throws.)
*/
void Semispace::dealloc(void* pt) {
#ifdef DEBUG
char* callocpt = allocpt;
callocpt -= prev_alloc;
if(callocpt != pt) throw_DeallocError(pt);
#endif
allocpt = pt;
}
void* Semispace::lifo_alloc(size_t sz) {
prevalloc = sz;
char* clifoallocpt = lifoallocpt;
clifoallocpt -= sz;
lifoallocpt = clifoallocpt;
return lifoallocpt;
}
void Semispace::lifo_dealloc(void* pt) {
/*if we can't deallocate, just ignore*/
if(pt != lifoallocpt) return;
size_t sz = ((Generic*) pt)->real_size();
((Generic*) pt)->~Generic();
char* clifoallocpt = pt;
clifoallocpt += sz;
lifoallocpt = clifoallocpt;
}
/*This function should be used only when the
constructor for the object fails. It does
*not* properly destroy the object.
*/
void Semispace::lifo_dealloc_abort(void* pt) {
#ifdef DEBUG
if(pt != lifoallocpt) throw_DeallocError(pt);
#endif
char* clifoallocpt = lifoallocpt;
clifoallocpt += prev_alloc;
lifoallocpt = clifoallocpt;
}
/*TODO*/
void Semispace::clone(boost::scoped_ptr<Semispace>& sp, Generic*& g);
/*-----------------------------------------------------------------------------
Heaps
-----------------------------------------------------------------------------*/
/*copy and modify GC class*/
class GCTraverser : public GenericTraverser {
Semispace* nsp;
public:
explicit GCTraverser(Semispace* nnsp) : nsp(nnsp) { }
void traverse(Object::ref& r) {
if(is_a<Generic*>(r)) {
Generic* gp = as_a<Generic*>(r);
BrokenHeart* bp = dynamic_cast<BrokenHeart*>(gp);
if(bp) { //broken heart
r = Object::to_ref(bp->to);
} else { //unbroken
Generic* ngp = gp->clone(nsp);
gp->break_heart(ngp);
r = Object::to_ref(ngp);
}
} else return;
}
};
static void cheney_collection(Semispace* nsp) {
GCTraverser gc(nsp);
/*step 1: initial traverse*/
scan_root_object(gc);
/*step 2: non-root traverse*/
/*notice that we traverse the new semispace
this is a two-pointer Cheney collector, with mvpt
being one pointer and nsp->allocpt the other one
*/
char* mvpt = nsp->allocstart;
while(mvpt < ((char*) nsp->allocpt)) {
Generic* gp = (Generic*)(void*) mvpt;
size_t obsz = gp->real_size();
gp->traverse_references(gc);
mvpt += obsz;
}
}
void Heap::GC(size_t insurance) {
/*Determine the sizes of all semispaces*/
size_t total = main->used() + insurance +
(other_spaces) ? other_spaces->used_total() :
/*otherwise*/ 0 ;
if(tight) total *= 2;
/*get a new Semispace*/
boost::scoped_ptr<Semispace> nsp(new Semispace(total));
/*traverse*/
cheney_collection(&*nsp);
/*replace*/
main.swap(nsp);
nsp.reset();
other_spaces.reset();
/*determine if resizing is appropriate*/
if(main->used() + insurance <= total / 4) {
/*semispace a bit large... make it smaller*/
nsp.reset(new Semispace(total / 2));
cheney_collection(&*nsp);
main.swap(nsp);
nsp.reset();
} else if(main->used() + insurance >= (total / 4) * 3) {
tight = 1;
}
}
<commit_msg>src/heaps.cpp: Added proper casts<commit_after>#include"all_defines.hpp"
#include"objects.hpp"
#include"heaps.hpp"
#include"types.hpp"
#include<cstdlib>
#include<stdint.h>
/*-----------------------------------------------------------------------------
Semispaces
-----------------------------------------------------------------------------*/
Semispace::Semispace(size_t nsz)
: max(nsz) {
mem = std::malloc(nsz);
if(!mem) throw std::bad_alloc();
allocpt = mem;
// check alignment
intptr_t tmp = reinterpret_cast<intptr_t>(allocpt);
if(tmp & Object::tag_mask) {
char* callocpt = (char*)allocpt;
callocpt += Object::alignment - (tmp & Object::tag_mask);
allocpt = callocpt;
}
allocstart = allocpt;
char* cmem = (char*)mem;
char* clifoallocpt = cmem + nsz;
// adjust for alignment
tmp = reinterpret_cast<intptr_t>(lifoallocpt);
clifoallocpt -= (tmp & Object::tag_mask);
lifoallocpt = clifoallocpt;
}
Semispace::~Semispace() {
Generic* gp;
size_t step;
char* mvpt;
char* endpt;
/*TODO: consider refactoring*/
/*----Delete normally-allocated memory----*/
mvpt = (char*) allocstart;
endpt = (char*) allocpt;
while(mvpt < endpt) {
gp = (Generic*)(void*) mvpt;
step = gp->real_size();
gp->~Generic();
mvpt += step;
}
/*----Delete lifo-allocated memory----*/
mvpt = (char*) lifoallocpt;
endpt = (char*) lifoallocstart;
while(mvpt < endpt) {
gp = (Generic*)(void*) mvpt;
step = gp->real_size();
gp->~Generic();
mvpt += step;
}
}
/*
sz must be computed using the exact same
computation used in real_size() of the
object to be allocated. This includes
alignment.
*/
void* Semispace::alloc(size_t sz) {
prev_alloc = sz;
void* tmp = allocpt;
char* callocpt = (char*) allocpt;
callocpt += sz;
allocpt = callocpt;
return tmp;
}
/*should be used only for most recent allocation
(i.e. should be used for freeing memory when the
constructor throws.)
*/
void Semispace::dealloc(void* pt) {
#ifdef DEBUG
char* callocpt = allocpt;
callocpt -= prev_alloc;
if(callocpt != pt) throw_DeallocError(pt);
#endif
allocpt = pt;
}
void* Semispace::lifo_alloc(size_t sz) {
prevalloc = sz;
char* clifoallocpt = lifoallocpt;
clifoallocpt -= sz;
lifoallocpt = clifoallocpt;
return lifoallocpt;
}
void Semispace::lifo_dealloc(void* pt) {
/*if we can't deallocate, just ignore*/
if(pt != lifoallocpt) return;
size_t sz = ((Generic*) pt)->real_size();
((Generic*) pt)->~Generic();
char* clifoallocpt = pt;
clifoallocpt += sz;
lifoallocpt = clifoallocpt;
}
/*This function should be used only when the
constructor for the object fails. It does
*not* properly destroy the object.
*/
void Semispace::lifo_dealloc_abort(void* pt) {
#ifdef DEBUG
if(pt != lifoallocpt) throw_DeallocError(pt);
#endif
char* clifoallocpt = lifoallocpt;
clifoallocpt += prev_alloc;
lifoallocpt = clifoallocpt;
}
/*TODO*/
void Semispace::clone(boost::scoped_ptr<Semispace>& sp, Generic*& g);
/*-----------------------------------------------------------------------------
Heaps
-----------------------------------------------------------------------------*/
/*copy and modify GC class*/
class GCTraverser : public GenericTraverser {
Semispace* nsp;
public:
explicit GCTraverser(Semispace* nnsp) : nsp(nnsp) { }
void traverse(Object::ref& r) {
if(is_a<Generic*>(r)) {
Generic* gp = as_a<Generic*>(r);
BrokenHeart* bp = dynamic_cast<BrokenHeart*>(gp);
if(bp) { //broken heart
r = Object::to_ref(bp->to);
} else { //unbroken
Generic* ngp = gp->clone(nsp);
gp->break_heart(ngp);
r = Object::to_ref(ngp);
}
} else return;
}
};
static void cheney_collection(Semispace* nsp) {
GCTraverser gc(nsp);
/*step 1: initial traverse*/
scan_root_object(gc);
/*step 2: non-root traverse*/
/*notice that we traverse the new semispace
this is a two-pointer Cheney collector, with mvpt
being one pointer and nsp->allocpt the other one
*/
char* mvpt = nsp->allocstart;
while(mvpt < ((char*) nsp->allocpt)) {
Generic* gp = (Generic*)(void*) mvpt;
size_t obsz = gp->real_size();
gp->traverse_references(gc);
mvpt += obsz;
}
}
void Heap::GC(size_t insurance) {
/*Determine the sizes of all semispaces*/
size_t total = main->used() + insurance +
(other_spaces) ? other_spaces->used_total() :
/*otherwise*/ 0 ;
if(tight) total *= 2;
/*get a new Semispace*/
boost::scoped_ptr<Semispace> nsp(new Semispace(total));
/*traverse*/
cheney_collection(&*nsp);
/*replace*/
main.swap(nsp);
nsp.reset();
other_spaces.reset();
/*determine if resizing is appropriate*/
if(main->used() + insurance <= total / 4) {
/*semispace a bit large... make it smaller*/
nsp.reset(new Semispace(total / 2));
cheney_collection(&*nsp);
main.swap(nsp);
nsp.reset();
} else if(main->used() + insurance >= (total / 4) * 3) {
tight = 1;
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
#include "appshell_extensions.h"
#include "client_handler.h"
#include <algorithm>
#include <CommDlg.h>
#include <ShlObj.h>
#include <Shlwapi.h>
#include <stdio.h>
#include <sys/stat.h>
#define CLOSING_PROP L"CLOSING"
extern CefRefPtr<ClientHandler> g_handler;
// Forward declarations for functions at the bottom of this file
void ConvertToNativePath(ExtensionString& filename);
void ConvertToUnixPath(ExtensionString& filename);
int ConvertErrnoCode(int errorCode, bool isReading = true);
int ConvertWinErrorCode(int errorCode, bool isReading = true);
static int CALLBACK SetInitialPathCallback(HWND hWnd, UINT uMsg, LPARAM lParam, LPARAM lpData)
{
if (BFFM_INITIALIZED == uMsg && NULL != lpData)
{
SendMessage(hWnd, BFFM_SETSELECTION, TRUE, lpData);
}
return 0;
}
int32 ShowOpenDialog(bool allowMulitpleSelection,
bool chooseDirectory,
ExtensionString title,
ExtensionString initialDirectory,
ExtensionString fileTypes,
CefRefPtr<CefListValue>& selectedFiles)
{
wchar_t szFile[MAX_PATH];
szFile[0] = 0;
// TODO (issue #64) - This method should be using IFileDialog instead of the
/* outdated SHGetPathFromIDList and GetOpenFileName.
Useful function to parse fileTypesStr:
template<class T>
int inline findAndReplaceString(T& source, const T& find, const T& replace)
{
int num=0;
int fLen = find.size();
int rLen = replace.size();
for (int pos=0; (pos=source.find(find, pos))!=T::npos; pos+=rLen)
{
num++;
source.replace(pos, fLen, replace);
}
return num;
}
*/
if (chooseDirectory) {
BROWSEINFO bi = {0};
bi.hwndOwner = GetActiveWindow();
bi.lpszTitle = title.c_str();
bi.ulFlags = BIF_NEWDIALOGSTYLE;
bi.lpfn = SetInitialPathCallback;
bi.lParam = (LPARAM)initialDirectory.c_str();
LPITEMIDLIST pidl = SHBrowseForFolder(&bi);
if (pidl != 0) {
if (SHGetPathFromIDList(pidl, szFile)) {
// Add directory path to the result
selectedFiles->SetString(0, szFile);
}
IMalloc* pMalloc = NULL;
SHGetMalloc(&pMalloc);
if (pMalloc) {
pMalloc->Free(pidl);
pMalloc->Release();
}
}
} else {
OPENFILENAME ofn;
ZeroMemory(&ofn, sizeof(ofn));
ofn.hwndOwner = GetActiveWindow();
ofn.lStructSize = sizeof(ofn);
ofn.lpstrFile = szFile;
ofn.nMaxFile = MAX_PATH;
// TODO (issue #65) - Use passed in file types. Note, when fileTypesStr is null, all files should be shown
/* findAndReplaceString( fileTypesStr, std::string(" "), std::string(";*."));
LPCWSTR allFilesFilter = L"All Files\0*.*\0\0";*/
ofn.lpstrFilter = L"All Files\0*.*\0Web Files\0*.js;*.css;*.htm;*.html\0\0";
ofn.lpstrInitialDir = initialDirectory.c_str();
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR | OFN_EXPLORER;
if (allowMulitpleSelection)
ofn.Flags |= OFN_ALLOWMULTISELECT;
if (GetOpenFileName(&ofn)) {
if (allowMulitpleSelection) {
// Multiple selection encodes the files differently
// If multiple files are selected, the first null terminator
// signals end of directory that the files are all in
std::wstring dir(szFile);
// Check for two null terminators, which signal that only one file
// was selected
if (szFile[dir.length() + 1] == '\0') {
ExtensionString filePath(dir);
ConvertToUnixPath(filePath);
selectedFiles->SetString(0, filePath);
} else {
// Multiple files are selected
wchar_t fullPath[MAX_PATH];
for (int i = (dir.length() + 1), fileIndex = 0; ; fileIndex++) {
// Get the next file name
std::wstring file(&szFile[i]);
// Two adjacent null characters signal the end of the files
if (file.length() == 0)
break;
// The filename is relative to the directory that was specified as
// the first string
if (PathCombine(fullPath, dir.c_str(), file.c_str()) != NULL) {
ExtensionString filePath(fullPath);
ConvertToUnixPath(filePath);
selectedFiles->SetString(fileIndex, filePath);
}
// Go to the start of the next file name
i += file.length() + 1;
}
}
} else {
// If multiple files are not allowed, add the single file
selectedFiles->SetString(0, szFile);
}
}
}
return NO_ERROR;
}
int32 ReadDir(ExtensionString path, CefRefPtr<CefListValue>& directoryContents)
{
if (path.length() && path[path.length() - 1] != '/')
path += '/';
path += '*';
WIN32_FIND_DATA ffd;
HANDLE hFind = FindFirstFile(path.c_str(), &ffd);
std::vector<ExtensionString> resultFiles;
std::vector<ExtensionString> resultDirs;
if (hFind != INVALID_HANDLE_VALUE) {
do {
// Ignore '.' and '..'
if (!wcscmp(ffd.cFileName, L".") || !wcscmp(ffd.cFileName, L".."))
continue;
// Collect file and directory names separately
if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
resultDirs.push_back(ExtensionString(ffd.cFileName));
} else {
resultFiles.push_back(ExtensionString(ffd.cFileName));
}
}
while (FindNextFile(hFind, &ffd) != 0);
FindClose(hFind);
}
else {
return ConvertWinErrorCode(GetLastError());
}
// On Windows, list directories first, then files
size_t i, total = 0;
for (i = 0; i < resultDirs.size(); i++)
directoryContents->SetString(total++, resultDirs[i]);
for (i = 0; i < resultFiles.size(); i++)
directoryContents->SetString(total++, resultFiles[i]);
return NO_ERROR;
}
int32 GetFileModificationTime(ExtensionString filename, uint32& modtime, bool& isDir)
{
DWORD dwAttr = GetFileAttributes(filename.c_str());
if (dwAttr == INVALID_FILE_ATTRIBUTES) {
return ConvertWinErrorCode(GetLastError());
}
isDir = ((dwAttr & FILE_ATTRIBUTE_DIRECTORY) != 0);
// Remove trailing "/", if present. _wstat will fail with a "file not found"
// error if a directory has a trailing '/' in the name.
if (filename[filename.length() - 1] == '/')
filename[filename.length() - 1] = 0;
struct _stat buffer;
if(_wstat(filename.c_str(), &buffer) == -1) {
return ConvertErrnoCode(errno);
}
modtime = buffer.st_mtime;
return NO_ERROR;
}
int32 ReadFile(ExtensionString filename, ExtensionString encoding, std::string& contents)
{
if (encoding != L"utf8")
return ERR_UNSUPPORTED_ENCODING;
DWORD dwAttr;
dwAttr = GetFileAttributes(filename.c_str());
if (INVALID_FILE_ATTRIBUTES == dwAttr)
return ConvertWinErrorCode(GetLastError());
if (dwAttr & FILE_ATTRIBUTE_DIRECTORY)
return ERR_CANT_READ;
HANDLE hFile = CreateFile(filename.c_str(), GENERIC_READ,
0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
int32 error = NO_ERROR;
if (INVALID_HANDLE_VALUE == hFile)
return ConvertWinErrorCode(GetLastError());
DWORD dwFileSize = GetFileSize(hFile, NULL);
DWORD dwBytesRead;
char* buffer = (char*)malloc(dwFileSize);
if (buffer && ReadFile(hFile, buffer, dwFileSize, &dwBytesRead, NULL)) {
contents = std::string(buffer, dwFileSize);
}
else {
if (!buffer)
error = ERR_UNKNOWN;
else
error = ConvertWinErrorCode(GetLastError());
}
CloseHandle(hFile);
if (buffer)
free(buffer);
return error;
}
int32 WriteFile(ExtensionString filename, std::string contents, ExtensionString encoding)
{
if (encoding != L"utf8")
return ERR_UNSUPPORTED_ENCODING;
HANDLE hFile = CreateFile(filename.c_str(), GENERIC_WRITE,
0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
DWORD dwBytesWritten;
int error = NO_ERROR;
if (INVALID_HANDLE_VALUE == hFile)
return ConvertWinErrorCode(GetLastError(), false);
// TODO (issue 67) - Should write to temp file and handle encoding
if (!WriteFile(hFile, contents.c_str(), contents.length(), &dwBytesWritten, NULL)) {
error = ConvertWinErrorCode(GetLastError(), false);
}
CloseHandle(hFile);
return error;
}
int32 SetPosixPermissions(ExtensionString filename, int32 mode)
{
DWORD dwAttr = GetFileAttributes(filename.c_str());
if (dwAttr == INVALID_FILE_ATTRIBUTES)
return ERR_NOT_FOUND;
if ((dwAttr & FILE_ATTRIBUTE_DIRECTORY) != 0)
return NO_ERROR;
bool write = (mode & 0200) != 0;
bool read = (mode & 0400) != 0;
int mask = (write ? _S_IWRITE : 0) | (read ? _S_IREAD : 0);
if (_wchmod(filename.c_str(), mask) == -1) {
return ConvertErrnoCode(errno);
}
return NO_ERROR;
}
int32 DeleteFileOrDirectory(ExtensionString filename)
{
DWORD dwAttr = GetFileAttributes(filename.c_str());
if ((dwAttr & FILE_ATTRIBUTE_DIRECTORY) != 0)
return ERR_NOT_FILE;
if (!DeleteFile(filename.c_str()))
return ConvertWinErrorCode(GetLastError());
return NO_ERROR;
}
void CloseWindow(CefRefPtr<CefBrowser> browser)
{
if (browser.get() && g_handler.get()) {
HWND browserHwnd = browser->GetHost()->GetWindowHandle();
SetProp(browserHwnd, CLOSING_PROP, (HANDLE)1);
browser->GetHost()->CloseBrowser();
}
}
void BringBrowserWindowToFront(CefRefPtr<CefBrowser> browser)
{
if (browser.get()) {
HWND hwnd = browser->GetHost()->GetWindowHandle();
if (hwnd)
::BringWindowToTop(hwnd);
}
}
void ConvertToNativePath(ExtensionString& filename)
{
// Convert '/' to '\'
replace(filename.begin(), filename.end(), '/', '\\');
}
void ConvertToUnixPath(ExtensionString& filename)
{
// Convert '\\' to '/'
replace(filename.begin(), filename.end(), '\\', '/');
}
// Maps errors from errno.h to the brackets error codes
// found in brackets_extensions.js
int ConvertErrnoCode(int errorCode, bool isReading)
{
switch (errorCode) {
case NO_ERROR:
return NO_ERROR;
case EINVAL:
return ERR_INVALID_PARAMS;
case ENOENT:
return ERR_NOT_FOUND;
default:
return ERR_UNKNOWN;
}
}
// Maps errors from WinError.h to the brackets error codes
// found in brackets_extensions.js
int ConvertWinErrorCode(int errorCode, bool isReading)
{
switch (errorCode) {
case NO_ERROR:
return NO_ERROR;
case ERROR_PATH_NOT_FOUND:
case ERROR_FILE_NOT_FOUND:
return ERR_NOT_FOUND;
case ERROR_ACCESS_DENIED:
return isReading ? ERR_CANT_READ : ERR_CANT_WRITE;
case ERROR_WRITE_PROTECT:
return ERR_CANT_WRITE;
case ERROR_HANDLE_DISK_FULL:
return ERR_OUT_OF_SPACE;
default:
return ERR_UNKNOWN;
}
}
<commit_msg>Fix whitespace issues, pathnames for selecting a folder, and error code in DeleteFileOrDirectory()<commit_after>/*
* Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
#include "appshell_extensions.h"
#include "client_handler.h"
#include <algorithm>
#include <CommDlg.h>
#include <ShlObj.h>
#include <Shlwapi.h>
#include <stdio.h>
#include <sys/stat.h>
#define CLOSING_PROP L"CLOSING"
extern CefRefPtr<ClientHandler> g_handler;
// Forward declarations for functions at the bottom of this file
void ConvertToNativePath(ExtensionString& filename);
void ConvertToUnixPath(ExtensionString& filename);
int ConvertErrnoCode(int errorCode, bool isReading = true);
int ConvertWinErrorCode(int errorCode, bool isReading = true);
static int CALLBACK SetInitialPathCallback(HWND hWnd, UINT uMsg, LPARAM lParam, LPARAM lpData)
{
if (BFFM_INITIALIZED == uMsg && NULL != lpData)
{
SendMessage(hWnd, BFFM_SETSELECTION, TRUE, lpData);
}
return 0;
}
int32 ShowOpenDialog(bool allowMulitpleSelection,
bool chooseDirectory,
ExtensionString title,
ExtensionString initialDirectory,
ExtensionString fileTypes,
CefRefPtr<CefListValue>& selectedFiles)
{
wchar_t szFile[MAX_PATH];
szFile[0] = 0;
// TODO (issue #64) - This method should be using IFileDialog instead of the
/* outdated SHGetPathFromIDList and GetOpenFileName.
Useful function to parse fileTypesStr:
template<class T>
int inline findAndReplaceString(T& source, const T& find, const T& replace)
{
int num=0;
int fLen = find.size();
int rLen = replace.size();
for (int pos=0; (pos=source.find(find, pos))!=T::npos; pos+=rLen)
{
num++;
source.replace(pos, fLen, replace);
}
return num;
}
*/
if (chooseDirectory) {
BROWSEINFO bi = {0};
bi.hwndOwner = GetActiveWindow();
bi.lpszTitle = title.c_str();
bi.ulFlags = BIF_NEWDIALOGSTYLE;
bi.lpfn = SetInitialPathCallback;
bi.lParam = (LPARAM)initialDirectory.c_str();
LPITEMIDLIST pidl = SHBrowseForFolder(&bi);
if (pidl != 0) {
if (SHGetPathFromIDList(pidl, szFile)) {
// Add directory path to the result
ExtensionString pathName(szFile);
ConvertToUnixPath(pathName);
selectedFiles->SetString(0, pathName);
}
IMalloc* pMalloc = NULL;
SHGetMalloc(&pMalloc);
if (pMalloc) {
pMalloc->Free(pidl);
pMalloc->Release();
}
}
} else {
OPENFILENAME ofn;
ZeroMemory(&ofn, sizeof(ofn));
ofn.hwndOwner = GetActiveWindow();
ofn.lStructSize = sizeof(ofn);
ofn.lpstrFile = szFile;
ofn.nMaxFile = MAX_PATH;
// TODO (issue #65) - Use passed in file types. Note, when fileTypesStr is null, all files should be shown
/* findAndReplaceString( fileTypesStr, std::string(" "), std::string(";*."));
LPCWSTR allFilesFilter = L"All Files\0*.*\0\0";*/
ofn.lpstrFilter = L"All Files\0*.*\0Web Files\0*.js;*.css;*.htm;*.html\0\0";
ofn.lpstrInitialDir = initialDirectory.c_str();
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR | OFN_EXPLORER;
if (allowMulitpleSelection)
ofn.Flags |= OFN_ALLOWMULTISELECT;
if (GetOpenFileName(&ofn)) {
if (allowMulitpleSelection) {
// Multiple selection encodes the files differently
// If multiple files are selected, the first null terminator
// signals end of directory that the files are all in
std::wstring dir(szFile);
// Check for two null terminators, which signal that only one file
// was selected
if (szFile[dir.length() + 1] == '\0') {
ExtensionString filePath(dir);
ConvertToUnixPath(filePath);
selectedFiles->SetString(0, filePath);
} else {
// Multiple files are selected
wchar_t fullPath[MAX_PATH];
for (int i = (dir.length() + 1), fileIndex = 0; ; fileIndex++) {
// Get the next file name
std::wstring file(&szFile[i]);
// Two adjacent null characters signal the end of the files
if (file.length() == 0)
break;
// The filename is relative to the directory that was specified as
// the first string
if (PathCombine(fullPath, dir.c_str(), file.c_str()) != NULL) {
ExtensionString filePath(fullPath);
ConvertToUnixPath(filePath);
selectedFiles->SetString(fileIndex, filePath);
}
// Go to the start of the next file name
i += file.length() + 1;
}
}
} else {
// If multiple files are not allowed, add the single file
selectedFiles->SetString(0, szFile);
}
}
}
return NO_ERROR;
}
int32 ReadDir(ExtensionString path, CefRefPtr<CefListValue>& directoryContents)
{
if (path.length() && path[path.length() - 1] != '/')
path += '/';
path += '*';
WIN32_FIND_DATA ffd;
HANDLE hFind = FindFirstFile(path.c_str(), &ffd);
std::vector<ExtensionString> resultFiles;
std::vector<ExtensionString> resultDirs;
if (hFind != INVALID_HANDLE_VALUE) {
do {
// Ignore '.' and '..'
if (!wcscmp(ffd.cFileName, L".") || !wcscmp(ffd.cFileName, L".."))
continue;
// Collect file and directory names separately
if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
resultDirs.push_back(ExtensionString(ffd.cFileName));
} else {
resultFiles.push_back(ExtensionString(ffd.cFileName));
}
}
while (FindNextFile(hFind, &ffd) != 0);
FindClose(hFind);
}
else {
return ConvertWinErrorCode(GetLastError());
}
// On Windows, list directories first, then files
size_t i, total = 0;
for (i = 0; i < resultDirs.size(); i++)
directoryContents->SetString(total++, resultDirs[i]);
for (i = 0; i < resultFiles.size(); i++)
directoryContents->SetString(total++, resultFiles[i]);
return NO_ERROR;
}
int32 GetFileModificationTime(ExtensionString filename, uint32& modtime, bool& isDir)
{
DWORD dwAttr = GetFileAttributes(filename.c_str());
if (dwAttr == INVALID_FILE_ATTRIBUTES) {
return ConvertWinErrorCode(GetLastError());
}
isDir = ((dwAttr & FILE_ATTRIBUTE_DIRECTORY) != 0);
// Remove trailing "/", if present. _wstat will fail with a "file not found"
// error if a directory has a trailing '/' in the name.
if (filename[filename.length() - 1] == '/')
filename[filename.length() - 1] = 0;
struct _stat buffer;
if(_wstat(filename.c_str(), &buffer) == -1) {
return ConvertErrnoCode(errno);
}
modtime = buffer.st_mtime;
return NO_ERROR;
}
int32 ReadFile(ExtensionString filename, ExtensionString encoding, std::string& contents)
{
if (encoding != L"utf8")
return ERR_UNSUPPORTED_ENCODING;
DWORD dwAttr;
dwAttr = GetFileAttributes(filename.c_str());
if (INVALID_FILE_ATTRIBUTES == dwAttr)
return ConvertWinErrorCode(GetLastError());
if (dwAttr & FILE_ATTRIBUTE_DIRECTORY)
return ERR_CANT_READ;
HANDLE hFile = CreateFile(filename.c_str(), GENERIC_READ,
0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
int32 error = NO_ERROR;
if (INVALID_HANDLE_VALUE == hFile)
return ConvertWinErrorCode(GetLastError());
DWORD dwFileSize = GetFileSize(hFile, NULL);
DWORD dwBytesRead;
char* buffer = (char*)malloc(dwFileSize);
if (buffer && ReadFile(hFile, buffer, dwFileSize, &dwBytesRead, NULL)) {
contents = std::string(buffer, dwFileSize);
}
else {
if (!buffer)
error = ERR_UNKNOWN;
else
error = ConvertWinErrorCode(GetLastError());
}
CloseHandle(hFile);
if (buffer)
free(buffer);
return error;
}
int32 WriteFile(ExtensionString filename, std::string contents, ExtensionString encoding)
{
if (encoding != L"utf8")
return ERR_UNSUPPORTED_ENCODING;
HANDLE hFile = CreateFile(filename.c_str(), GENERIC_WRITE,
0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
DWORD dwBytesWritten;
int error = NO_ERROR;
if (INVALID_HANDLE_VALUE == hFile)
return ConvertWinErrorCode(GetLastError(), false);
// TODO (issue 67) - Should write to temp file and handle encoding
if (!WriteFile(hFile, contents.c_str(), contents.length(), &dwBytesWritten, NULL)) {
error = ConvertWinErrorCode(GetLastError(), false);
}
CloseHandle(hFile);
return error;
}
int32 SetPosixPermissions(ExtensionString filename, int32 mode)
{
DWORD dwAttr = GetFileAttributes(filename.c_str());
if (dwAttr == INVALID_FILE_ATTRIBUTES)
return ERR_NOT_FOUND;
if ((dwAttr & FILE_ATTRIBUTE_DIRECTORY) != 0)
return NO_ERROR;
bool write = (mode & 0200) != 0;
bool read = (mode & 0400) != 0;
int mask = (write ? _S_IWRITE : 0) | (read ? _S_IREAD : 0);
if (_wchmod(filename.c_str(), mask) == -1) {
return ConvertErrnoCode(errno);
}
return NO_ERROR;
}
int32 DeleteFileOrDirectory(ExtensionString filename)
{
DWORD dwAttr = GetFileAttributes(filename.c_str());
if (dwAttr == INVALID_FILE_ATTRIBUTES)
return ERR_NOT_FOUND;
if ((dwAttr & FILE_ATTRIBUTE_DIRECTORY) != 0)
return ERR_NOT_FILE;
if (!DeleteFile(filename.c_str()))
return ConvertWinErrorCode(GetLastError());
return NO_ERROR;
}
void CloseWindow(CefRefPtr<CefBrowser> browser)
{
if (browser.get() && g_handler.get()) {
HWND browserHwnd = browser->GetHost()->GetWindowHandle();
SetProp(browserHwnd, CLOSING_PROP, (HANDLE)1);
browser->GetHost()->CloseBrowser();
}
}
void BringBrowserWindowToFront(CefRefPtr<CefBrowser> browser)
{
if (browser.get()) {
HWND hwnd = browser->GetHost()->GetWindowHandle();
if (hwnd)
::BringWindowToTop(hwnd);
}
}
void ConvertToNativePath(ExtensionString& filename)
{
// Convert '/' to '\'
replace(filename.begin(), filename.end(), '/', '\\');
}
void ConvertToUnixPath(ExtensionString& filename)
{
// Convert '\\' to '/'
replace(filename.begin(), filename.end(), '\\', '/');
}
// Maps errors from errno.h to the brackets error codes
// found in brackets_extensions.js
int ConvertErrnoCode(int errorCode, bool isReading)
{
switch (errorCode) {
case NO_ERROR:
return NO_ERROR;
case EINVAL:
return ERR_INVALID_PARAMS;
case ENOENT:
return ERR_NOT_FOUND;
default:
return ERR_UNKNOWN;
}
}
// Maps errors from WinError.h to the brackets error codes
// found in brackets_extensions.js
int ConvertWinErrorCode(int errorCode, bool isReading)
{
switch (errorCode) {
case NO_ERROR:
return NO_ERROR;
case ERROR_PATH_NOT_FOUND:
case ERROR_FILE_NOT_FOUND:
return ERR_NOT_FOUND;
case ERROR_ACCESS_DENIED:
return isReading ? ERR_CANT_READ : ERR_CANT_WRITE;
case ERROR_WRITE_PROTECT:
return ERR_CANT_WRITE;
case ERROR_HANDLE_DISK_FULL:
return ERR_OUT_OF_SPACE;
default:
return ERR_UNKNOWN;
}
}
<|endoftext|>
|
<commit_before>#include "input.h"
InputHandler::InputHandler(sf::Window* Window, Player* Player, Renderer* Renderer) : app(Window), player(Player), renderer(Renderer) {
app->ShowMouseCursor(false);
}
bool fullscreen = false;
void InputHandler::handleEvent(sf::Event Event) {
// Close window : exit
if (Event.Type == sf::Event::Closed)
app->Close();
// Escape key : exit
if ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::Escape))
app->Close();
// Spacebar : jump
if ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::Space))
player->Jump();
// F5 : regenerate terrain
if ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::F5))
renderer->terrain.Regenerate();
// F11 : toggle fullscreen
if ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::F11)) {
fullscreen = !fullscreen;
app->Close();
app->Create(sf::VideoMode(800, 600, 32), "MineCube", (fullscreen ? sf::Style::Fullscreen : sf::Style::Resize|sf::Style::Close));
renderer->InitGraphics();
app->ShowMouseCursor(false);
}
// Resize event : adjust viewport
if (Event.Type == sf::Event::Resized)
glViewport(0, 0, Event.Size.Width, Event.Size.Height);
}
float ElapsedTime;
float mouseDeltaX, mouseDeltaY;
void InputHandler::handleEvents() {
const sf::Input& Input = app->GetInput();
// Constant movement speed
ElapsedTime = Clock.GetElapsedTime();
Clock.Reset();
// Handle held keys
if ((Input.IsKeyDown(sf::Key::S))) player->Forward(-ElapsedTime);
if ((Input.IsKeyDown(sf::Key::W))) player->Forward( ElapsedTime);
if ((Input.IsKeyDown(sf::Key::D))) player->Strafe(-ElapsedTime);
if ((Input.IsKeyDown(sf::Key::A))) player->Strafe( ElapsedTime);
if ((Input.IsKeyDown(sf::Key::Z))) player->Speed++;
if ((Input.IsKeyDown(sf::Key::X))) player->Speed--;
// Handle other events
sf::Event Event;
while (app->GetEvent(Event))
{
handleEvent(Event);
}
// Rotate view based on mouse movement
mouseDeltaX = Input.GetMouseX() - 100;
mouseDeltaY = Input.GetMouseY() - 100;
app->SetCursorPosition(100, 100);
if (!(mouseDeltaX == -100 && mouseDeltaY == -100) && !(mouseDeltaX == 0 && mouseDeltaY == 0))
player->ChangeRotation((mouseDeltaY/10), (mouseDeltaX/10));
player->DoStep(ElapsedTime);
}
<commit_msg>Don't need to close the window, as of 2008<commit_after>#include "input.h"
InputHandler::InputHandler(sf::Window* Window, Player* Player, Renderer* Renderer) : app(Window), player(Player), renderer(Renderer) {
app->ShowMouseCursor(false);
}
bool fullscreen = false;
void InputHandler::handleEvent(sf::Event Event) {
// Close window : exit
if (Event.Type == sf::Event::Closed)
app->Close();
// Escape key : exit
if ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::Escape))
app->Close();
// Spacebar : jump
if ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::Space))
player->Jump();
// F5 : regenerate terrain
if ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::F5))
renderer->terrain.Regenerate();
// F11 : toggle fullscreen
if ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::F11)) {
fullscreen = !fullscreen;
app->Create(sf::VideoMode(800, 600, 32), "MineCube", (fullscreen ? sf::Style::Fullscreen : sf::Style::Resize|sf::Style::Close));
renderer->InitGraphics();
app->ShowMouseCursor(false);
}
// Resize event : adjust viewport
if (Event.Type == sf::Event::Resized)
glViewport(0, 0, Event.Size.Width, Event.Size.Height);
}
float ElapsedTime;
float mouseDeltaX, mouseDeltaY;
void InputHandler::handleEvents() {
const sf::Input& Input = app->GetInput();
// Constant movement speed
ElapsedTime = Clock.GetElapsedTime();
Clock.Reset();
// Handle held keys
if ((Input.IsKeyDown(sf::Key::S))) player->Forward(-ElapsedTime);
if ((Input.IsKeyDown(sf::Key::W))) player->Forward( ElapsedTime);
if ((Input.IsKeyDown(sf::Key::D))) player->Strafe(-ElapsedTime);
if ((Input.IsKeyDown(sf::Key::A))) player->Strafe( ElapsedTime);
if ((Input.IsKeyDown(sf::Key::Z))) player->Speed++;
if ((Input.IsKeyDown(sf::Key::X))) player->Speed--;
// Handle other events
sf::Event Event;
while (app->GetEvent(Event))
{
handleEvent(Event);
}
// Rotate view based on mouse movement
mouseDeltaX = Input.GetMouseX() - 100;
mouseDeltaY = Input.GetMouseY() - 100;
app->SetCursorPosition(100, 100);
if (!(mouseDeltaX == -100 && mouseDeltaY == -100) && !(mouseDeltaX == 0 && mouseDeltaY == 0))
player->ChangeRotation((mouseDeltaY/10), (mouseDeltaX/10));
player->DoStep(ElapsedTime);
}
<|endoftext|>
|
<commit_before>#include <errno.h>
#include <sys/ioctl.h>
#include "nan.h"
using namespace v8;
using namespace node;
NAN_METHOD(Ioctl) {
NanScope();
Local<Object> buf;
int length = args.Length();
assert((length == 2) || (length == 3));
void* argp = NULL;
if (!args[0]->IsInt32()) {
NanThrowTypeError("Argument 0 Must be an Integer");
}
if (!args[1]->IsUint32()) {
NanThrowTypeError("Argument 1 Must be an Integer");
}
if (length == 3) {
if (args[2]->IsInt32()) {
argp = reinterpret_cast<void*>(args[2]->Int32Value());
} else {
buf = args[2]->ToObject();
if (!Buffer::HasInstance(buf)) {
NanThrowTypeError("Argument 2 Must be an Integer or a Buffer");
}
argp = Buffer::Data(buf);
}
}
int fd = args[0]->Int32Value();
unsigned long request = args[1]->IntegerValue();
int res = ioctl(fd, request, argp);
if (res == -1) {
res = -errno;
}
NanReturnValue(NanNew(res));
}
void InitAll(Handle<Object> exports) {
exports->Set(NanNew("ioctl"),
NanNew<FunctionTemplate>(Ioctl)->GetFunction());
}
NODE_MODULE(ioctl, InitAll)
<commit_msg>src: fix the case when no ioctl third ioctl param<commit_after>#include <errno.h>
#include <sys/ioctl.h>
#include "nan.h"
using namespace v8;
using namespace node;
NAN_METHOD(Ioctl) {
NanScope();
Local<Object> buf;
int length = args.Length();
assert(length == 3);
void* argp = NULL;
if (!args[0]->IsInt32()) {
NanThrowTypeError("Argument 0 Must be an Integer");
}
if (!args[1]->IsUint32()) {
NanThrowTypeError("Argument 1 Must be an Integer");
}
if (!args[2]->IsUndefined()) {
if (args[2]->IsInt32()) {
argp = reinterpret_cast<void*>(args[2]->Int32Value());
} else {
buf = args[2]->ToObject();
if (!Buffer::HasInstance(buf)) {
NanThrowTypeError("Argument 2 Must be an Integer or a Buffer");
}
argp = Buffer::Data(buf);
}
}
int fd = args[0]->Int32Value();
unsigned long request = args[1]->IntegerValue();
int res = ioctl(fd, request, argp);
if (res == -1) {
res = -errno;
}
NanReturnValue(NanNew(res));
}
void InitAll(Handle<Object> exports) {
exports->Set(NanNew("ioctl"),
NanNew<FunctionTemplate>(Ioctl)->GetFunction());
}
NODE_MODULE(ioctl, InitAll)
<|endoftext|>
|
<commit_before>/*
*
* Copyright 2017 Asylo authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <arpa/inet.h>
#include "asylo/platform/arch/include/trusted/host_calls.h"
#ifdef __cplusplus
extern "C" {
#endif
static inline uint32_t flip_endian_32(uint32_t u32_in) {
const char *in = reinterpret_cast<const char *>(&u32_in);
char out[4];
out[0] = in[3];
out[1] = in[2];
out[2] = in[1];
out[3] = in[0];
return *reinterpret_cast<uint32_t *>(out);
}
static inline uint16_t flip_endian_16(uint16_t u16_in) {
const char *in = reinterpret_cast<const char *>(&u16_in);
char out[2];
out[0] = in[1];
out[1] = in[0];
return *reinterpret_cast<uint16_t *>(out);
}
uint32_t htonl(uint32_t hostlong) {
#ifdef __LITTLE_ENDIAN
return flip_endian_32(hostlong);
#endif
return hostlong;
}
uint16_t htons(uint16_t hostshort) {
#ifdef __LITTLE_ENDIAN
return flip_endian_16(hostshort);
#endif
return hostshort;
}
uint32_t ntohl(uint32_t netlong) {
#ifdef __LITTLE_ENDIAN
return flip_endian_32(netlong);
#endif
return netlong;
}
uint16_t ntohs(uint16_t netshort) {
#ifdef __LITTLE_ENDIAN
return flip_endian_16(netshort);
#endif
return netshort;
}
const char *inet_ntop(int af, const void *src, char *dst, socklen_t size) {
return enc_untrusted_inet_ntop(af, src, dst, size);
}
int inet_pton(int af, const char *src, void *dst) {
return enc_untrusted_inet_pton(af, src, dst);
}
#ifdef __cplusplus
} // extern "C"
#endif
<commit_msg>Update endianness swaps to use byteswap intrinsics<commit_after>/*
*
* Copyright 2017 Asylo authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <arpa/inet.h>
#include <byteswap.h>
#include "asylo/platform/arch/include/trusted/host_calls.h"
extern "C" {
uint32_t htonl(uint32_t hostlong) {
#ifdef __LITTLE_ENDIAN
return bswap_32(hostlong);
#else
return hostlong;
#endif
}
uint16_t htons(uint16_t hostshort) {
#ifdef __LITTLE_ENDIAN
return bswap_16(hostshort);
#else
return hostshort;
#endif
}
uint32_t ntohl(uint32_t netlong) {
#ifdef __LITTLE_ENDIAN
return bswap_32(netlong);
#else
return netlong;
#endif
}
uint16_t ntohs(uint16_t netshort) {
#ifdef __LITTLE_ENDIAN
return bswap_16(netshort);
#else
return netshort;
#endif
}
const char *inet_ntop(int af, const void *src, char *dst, socklen_t size) {
return enc_untrusted_inet_ntop(af, src, dst, size);
}
int inet_pton(int af, const char *src, void *dst) {
return enc_untrusted_inet_pton(af, src, dst);
}
} // extern "C"
<|endoftext|>
|
<commit_before>#include <iostream>
#include <vector>
#include "gomory_lex.h"
GomoryLex::GomoryLex(const rapidjson::Value& root) : GomoryNaive(root) {
original_obj_coeffs = (double*)malloc(num_vars*sizeof(double));
del_lex_constr_ids = (int*)malloc(num_vars*sizeof(int));
grb_error = GRBgetdblattrlist(model, GRB_DBL_ATTR_OBJ, num_vars,
cut_coeff_ids, original_obj_coeffs);
grb_error = GRBgetintattr(model, "NumConstrs", &original_num_constrs);
}
GomoryLex::~GomoryLex(void) {
free(del_lex_constr_ids);
free(original_obj_coeffs);
}
void GomoryLex::LexSimplex(void) {
grb_error = GRBgetintattr(model, "NumConstrs", &num_constrs);
double sol_i;
grb_error = GRBgetdblattrelement(model, "X", 0, &sol_i);
int id[1] = {0};
double vid[1] = {1.0};
grb_error = GRBaddconstr(model, 1, id, vid, GRB_EQUAL, sol_i, NULL);
del_lex_constr_ids[0] = num_constrs;
for (unsigned int j = 1; j < num_vars; j++) {
for (unsigned int k = 0; k < num_vars; k++) {
if (k == j) {
grb_error = GRBsetdblattrelement(model, GRB_DBL_ATTR_OBJ, k, 1.0);
} else {
grb_error = GRBsetdblattrelement(model, GRB_DBL_ATTR_OBJ, k, 0.0);
}
}
grb_error = GRBoptimize(model);
int id[1] = {j};
double vid[1] = {1.0};
double sol_j;
grb_error = GRBgetdblattrelement(model, "X", j, &sol_j);
grb_error = GRBaddconstr(model, 1, id, vid, GRB_EQUAL, sol_j, NULL);
del_lex_constr_ids[j] = num_constrs + j;
}
grb_error = GRBoptimize(model);
// Restore the objective to that of the original problem.
for (unsigned int j = 0; j < num_vars; j++) {
grb_error = GRBsetdblattrelement(model, GRB_DBL_ATTR_OBJ, j, original_obj_coeffs[j]);
}
grb_error = GRBdelconstrs(model, num_vars, del_lex_constr_ids);
grb_error = GRBoptimize(model);
}
int GomoryLex::PurgeCuts(void) {
grb_error = GRBgetintattr(model, "NumConstrs", &num_constrs);
std::vector<int> purge_cut_ids;
for (int i = original_num_constrs; i < num_constrs; i++) {
double constraint_slack;
grb_error = GRBgetdblattrelement(model, "Slack", i, &constraint_slack);
if (fabs(constraint_slack) > 1.0e-6) {
purge_cut_ids.push_back(i);
}
}
grb_error = GRBdelconstrs(model, (int)purge_cut_ids.size(), purge_cut_ids.data());
grb_error = GRBoptimize(model);
return purge_cut_ids.size();
}
int GomoryLex::Step(void) {
if (objective_value != old_objective_value || iter_since_purge >= 1000) {
iter_since_purge = 0;
int num_constrs_purged = PurgeCuts();
old_objective_value = objective_value;
}
UpdateBasisData();
//int cut_id = GetLeastFractionalIndex();
//int cut_id = GetMostFractionalIndex();
int cut_id = GetRandomIndex();
//int cut_id = *frac_int_vars.begin();
if (num_vars == num_int_vars) {
// If all of the variables were integer, use the pure integer cut.
LexSimplex();
num_cuts += AddPureCut(cut_id);
} else {
// Otherwise, use the mixed-integer cut.
LexSimplex();
num_cuts += AddMixedCut(cut_id);
}
grb_error = GRBoptimize(model);
grb_error = GRBgetdblattr(model, GRB_DBL_ATTR_OBJVAL, &objective_value);
iter_since_purge++;
return UpdateVariableData();
}
void GomoryLex::Run(void) {
grb_error = GRBoptimize(model);
grb_error = GRBgetdblattr(model, GRB_DBL_ATTR_OBJVAL, &objective_value);
old_objective_value = objective_value;
int num_frac_vars = UpdateVariableData();
iter_since_purge = 0;
while (num_frac_vars > 0) {
num_frac_vars = Step();
PrintStep();
}
grb_error = GRBwrite(model, solution_path.c_str());
}
<commit_msg>Updating lexicographic method.<commit_after>#include <iostream>
#include <vector>
#include "gomory_lex.h"
GomoryLex::GomoryLex(const rapidjson::Value& root) : GomoryNaive(root) {
original_obj_coeffs = (double*)malloc(num_vars*sizeof(double));
del_lex_constr_ids = (int*)malloc(num_vars*sizeof(int));
grb_error = GRBgetdblattrlist(model, GRB_DBL_ATTR_OBJ, num_vars,
cut_coeff_ids, original_obj_coeffs);
grb_error = GRBgetintattr(model, "NumConstrs", &original_num_constrs);
}
GomoryLex::~GomoryLex(void) {
free(del_lex_constr_ids);
free(original_obj_coeffs);
}
void GomoryLex::LexSimplex(void) {
grb_error = GRBgetintattr(model, "NumConstrs", &num_constrs);
double sol_i;
grb_error = GRBgetdblattrelement(model, "X", 0, &sol_i);
int id[1] = {0};
double vid[1] = {1.0};
grb_error = GRBaddconstr(model, 1, id, vid, GRB_EQUAL, sol_i, NULL);
del_lex_constr_ids[0] = num_constrs;
for (unsigned int j = 1; j < num_vars; j++) {
for (unsigned int k = 0; k < num_vars; k++) {
if (k == j) {
grb_error = GRBsetdblattrelement(model, GRB_DBL_ATTR_OBJ, k, 1.0);
} else {
grb_error = GRBsetdblattrelement(model, GRB_DBL_ATTR_OBJ, k, 0.0);
}
}
grb_error = GRBoptimize(model);
int id[1] = {j};
double vid[1] = {1.0};
double sol_j;
grb_error = GRBgetdblattrelement(model, "X", j, &sol_j);
grb_error = GRBaddconstr(model, 1, id, vid, GRB_EQUAL, sol_j, NULL);
del_lex_constr_ids[j] = num_constrs + j;
}
grb_error = GRBoptimize(model);
// Restore the objective to that of the original problem.
for (unsigned int j = 0; j < num_vars; j++) {
grb_error = GRBsetdblattrelement(model, GRB_DBL_ATTR_OBJ, j, original_obj_coeffs[j]);
}
grb_error = GRBdelconstrs(model, num_vars, del_lex_constr_ids);
grb_error = GRBoptimize(model);
}
int GomoryLex::PurgeCuts(void) {
grb_error = GRBgetintattr(model, "NumConstrs", &num_constrs);
std::vector<int> purge_cut_ids;
for (int i = original_num_constrs; i < num_constrs; i++) {
double constraint_slack;
grb_error = GRBgetdblattrelement(model, "Slack", i, &constraint_slack);
if (fabs(constraint_slack) > 1.0e-6) {
purge_cut_ids.push_back(i);
}
}
grb_error = GRBdelconstrs(model, (int)purge_cut_ids.size(), purge_cut_ids.data());
grb_error = GRBoptimize(model);
return purge_cut_ids.size();
}
int GomoryLex::Step(void) {
if (objective_value != old_objective_value || iter_since_purge >= original_num_constrs * 10) {
iter_since_purge = 0;
int num_constrs_purged = PurgeCuts();
old_objective_value = objective_value;
}
UpdateBasisData();
//int cut_id = GetLeastFractionalIndex();
//int cut_id = GetMostFractionalIndex();
int cut_id = GetRandomIndex();
//int cut_id = *frac_int_vars.begin();
if (num_vars == num_int_vars) {
// If all of the variables were integer, use the pure integer cut.
LexSimplex();
num_cuts += AddPureCut(cut_id);
} else {
// Otherwise, use the mixed-integer cut.
LexSimplex();
num_cuts += AddMixedCut(cut_id);
}
grb_error = GRBoptimize(model);
grb_error = GRBgetdblattr(model, GRB_DBL_ATTR_OBJVAL, &objective_value);
iter_since_purge++;
return UpdateVariableData();
}
void GomoryLex::Run(void) {
grb_error = GRBoptimize(model);
grb_error = GRBgetdblattr(model, GRB_DBL_ATTR_OBJVAL, &objective_value);
old_objective_value = objective_value;
int num_frac_vars = UpdateVariableData();
iter_since_purge = 0;
while (num_frac_vars > 0) {
num_frac_vars = Step();
PrintStep();
}
grb_error = GRBwrite(model, solution_path.c_str());
}
<|endoftext|>
|
<commit_before>#include "atlas/hlr/LoadLibrary.hpp"
#include <atlas/core/Platform.hpp>
#include <fmt/printf.h>
#if defined(ATLAS_PLATFORM_WINDOWS)
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
#endif
namespace atlas::hlr
{
#if defined(ATLAS_PLATFORM_WINDOWS)
void* loadLibraryHandle(std::string const& libraryName)
{
void* handle = LoadLibrary(libraryName.c_str());
if (handle == nullptr)
{
auto errorCode = GetLastError();
fmt::print(stderr, "error: LoadLibrary returned error code {}\n",
errorCode);
}
return handle;
}
void* loadRawFunctionPtr(void* handle, std::string const& functionName)
{
if (handle == nullptr)
{
fmt::print(stderr, "error: null library handle\n");
return nullptr;
}
HMODULE h = reinterpret_cast<HMODULE>(handle);
FARPROC procAddress = GetProcAddress(h, functionName.c_str());
if (procAddress == nullptr)
{
auto errorCode = GetLastError();
fmt::print(stderr, "error: GetProcAddress returned error code {}\n",
errorCode);
}
return procAddress;
}
void unloadLibraryHandle(void* handle)
{
HMODULE h = reinterpret_cast<HMODULE>(handle);
FreeLibrary(h);
}
#else
#endif
} // namespace atlas::hlr
<commit_msg>[brief] Tidies up HLR module.<commit_after>#include "atlas/hlr/LoadLibrary.hpp"
#include <atlas/core/Platform.hpp>
#include <fmt/printf.h>
#if defined(ATLAS_PLATFORM_WINDOWS)
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
#endif
namespace atlas::hlr
{
#if defined(ATLAS_PLATFORM_WINDOWS)
void* loadLibraryHandle(std::string const& libraryName)
{
void* handle = LoadLibrary(libraryName.c_str());
if (handle == nullptr)
{
auto errorCode = GetLastError();
fmt::print(stderr, "error: LoadLibrary returned error code {}\n",
errorCode);
}
return handle;
}
void* loadRawFunctionPtr(void* handle, std::string const& functionName)
{
if (handle == nullptr)
{
fmt::print(stderr, "error: null library handle\n");
return nullptr;
}
auto h = reinterpret_cast<HMODULE>(handle);
FARPROC procAddress = GetProcAddress(h, functionName.c_str());
if (procAddress == nullptr)
{
auto errorCode = GetLastError();
fmt::print(stderr, "error: GetProcAddress returned error code {}\n",
errorCode);
}
return procAddress;
}
void unloadLibraryHandle(void* handle)
{
auto h = reinterpret_cast<HMODULE>(handle);
FreeLibrary(h);
}
#else
#endif
} // namespace atlas::hlr
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: ik_exception.hxx,v $
*
* $Revision: 1.1 $
*
* last change: $Author: np $ $Date: 2002-11-01 17:11:53 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef ARY_IDL_IK_EXCEPTION_HXX
#define ARY_IDL_IK_EXCEPTION_HXX
// USED SERVICES
// BASE CLASSES
#include <ary/idl/ik_ce.hxx>
// COMPONENTS
// PARAMETERS
namespace ary
{
namespace idl
{
namespace ifc_exception
{
using ifc_ce::Dyn_CeIterator;
using ifc_ce::DocText;
struct attr: public ifc_ce::attr
{
static Type_id Base(
const CodeEntity & i_ce );
static void Get_Elements(
Dyn_CeIterator & o_result,
const CodeEntity & i_ce );
};
struct xref : public ifc_ce::xref
{
static void Get_Derivations(
Dyn_CeIterator & o_result,
const CodeEntity & i_ce );
static void Get_RaisingFunctions(
Dyn_CeIterator & o_result,
const CodeEntity & i_ce );
};
struct doc : public ifc_ce::doc
{
};
} // namespace ifc_exception
} // namespace idl
} // namespace ary
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.1.132); FILE MERGED 2005/09/05 13:09:25 rt 1.1.132.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ik_exception.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-07 16:15:24 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef ARY_IDL_IK_EXCEPTION_HXX
#define ARY_IDL_IK_EXCEPTION_HXX
// USED SERVICES
// BASE CLASSES
#include <ary/idl/ik_ce.hxx>
// COMPONENTS
// PARAMETERS
namespace ary
{
namespace idl
{
namespace ifc_exception
{
using ifc_ce::Dyn_CeIterator;
using ifc_ce::DocText;
struct attr: public ifc_ce::attr
{
static Type_id Base(
const CodeEntity & i_ce );
static void Get_Elements(
Dyn_CeIterator & o_result,
const CodeEntity & i_ce );
};
struct xref : public ifc_ce::xref
{
static void Get_Derivations(
Dyn_CeIterator & o_result,
const CodeEntity & i_ce );
static void Get_RaisingFunctions(
Dyn_CeIterator & o_result,
const CodeEntity & i_ce );
};
struct doc : public ifc_ce::doc
{
};
} // namespace ifc_exception
} // namespace idl
} // namespace ary
#endif
<|endoftext|>
|
<commit_before>extern "C" void kmain(void* /*mbd*/, u32 magic)
{
if ( magic != 0x2BADB002 )
{
/* Something went not according to specs. Print an error */
/* message and halt, but do *not* rely on the multiboot */
/* data structure. */
}
/* You could either use multiboot.h */
/* (http://www.gnu.org/software/grub/manual/multiboot/multiboot.html#multiboot_002eh) */
/* or do your offsets yourself. The following is merely an example. */
//char * boot_loader_name =(char*) ((long*)mbd)[16];
/* Print a letter to screen to see everything is working: */
unsigned char *videoram = (unsigned char *) 0xb8000;
int arr[5] = {0, 2, 4, 6, 8};
for(int x : arr) {
videoram[x] = 65; /* character 'A' */
videoram[x+1] = 0x07; /* light grey (7) on black (0). */
}
}
<commit_msg>Add barebones VGA text-mode display driver.<commit_after>const int console_width = 80;
const int console_height = 25;
const u8 color = 0x07; /* light grey (7) on black (0). */
u16 volatile* videoram = (u16 volatile*) 0xb8000;
void clear_screen() {
for(int i = 0; i < console_height * console_width; i++)
videoram[i] = (color << 8) | ' ';
}
void put_char_at(char c, int row, int col) {
videoram[row * console_width + col] = (color << 8) | c;
}
int position = 0;
void put_char(char c) {
put_char_at(c, 0, position); // TODO Handle end of line wrapping.
position++;
}
void put_string(const char* str) {
for(int i = 0; str[i]; i++)
put_char(str[i]);
}
extern "C" void kmain(void* /*mbd*/, u32 magic)
{
if ( magic != 0x2BADB002 )
{
/* Something went not according to specs. Print an error */
/* message and halt, but do *not* rely on the multiboot */
/* data structure. */
}
/* You could either use multiboot.h */
/* (http://www.gnu.org/software/grub/manual/multiboot/multiboot.html#multiboot_002eh) */
/* or do your offsets yourself. The following is merely an example. */
//char * boot_loader_name =(char*) ((long*)mbd)[16];
/* Print a string to screen to see everything is working: */
clear_screen();
put_string("This is a test!");
}
<|endoftext|>
|
<commit_before>/******************************************************************************
* Copyright (C) 2010 by Robert Tolliver *
* Robb.Tolli@gmail.com *
* *
* This file is part of Birthstone. *
* *
* Birthstone is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* Birthstone is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with Birthstone. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
#include "lexer.h"
#include <ostream>
#include <cctype>
#include <cstdlib>
#include <iostream>
#include <sstream>
std::map <std::string, Token> Lexer::sKeywords;
Lexer::Lexer(std::istream &input)
: mInput(&input), mLineNum(1), mToken(Sym::END)
{
setupKeywords();
}
Lexer::Lexer(const Lexer &lexer)
: mInput(lexer.mInput), mLineNum(1), mToken(Sym::END)
{}
Lexer::~Lexer() {}
void Lexer::setupKeywords()
{
if (sKeywords.empty())
{
sKeywords["if"] = Sym::IF;
sKeywords["elif"] = Sym::ELIF;
sKeywords["else"] = Sym::ELSE;
sKeywords["while"] = Sym::WHILE;
sKeywords["until"] = Sym::UNTIL;
sKeywords["for"] = Sym::FOR;
sKeywords["in"] = Sym::IN;
sKeywords["break"] = Sym::BREAK;
sKeywords["continue"] = Sym::CONT;
sKeywords["read"] = Sym::READ;
sKeywords["write"] = Sym::WRITE;
sKeywords["print"] = Sym::PRINT;
sKeywords["def"] = Sym::DEF;
sKeywords["class"] = Sym::CLASS;
sKeywords["and"] = Sym::AND;
sKeywords["or"] = Sym::OR;
sKeywords["not"] = Sym::NOT;
sKeywords["true"] = Token(Sym::BOOL, true);
sKeywords["false"] = Token(Sym::BOOL, false);
sKeywords["exit"] = Sym::QUIT;
sKeywords["quit"] = Sym::QUIT;
}
}
const Token &Lexer::getNext()
{
char ch = mInput->peek();
if (mInput->eof())
mToken = Token(Sym::END);
else if (ch == '#')
{
do
{
mInput->get();
ch = mInput->peek();
} while (!(mInput->eof()) && (ch != '\n'));
++mLineNum;
mInput->get();
return getNext();
}
else if (ch == ' ' || ch == '\t')
{
mInput->get();
return getNext();
}
else if (ch == '\n')
{
++mLineNum;
mInput->get();
return getNext();
}
else if (ch == '(')
{
mInput->get();
mToken = Sym::O_PARAN;
}
else if (ch == ')')
{
mInput->get();
mToken = Sym::C_PARAN;
}
else if (ch == '[')
{
mInput->get();
mToken = Sym::O_BRACKET;
}
else if (ch == ']')
{
mInput->get();
mToken = Sym::C_BRACKET;
}
else if (ch == '{')
{
mInput->get();
mToken = Sym::O_BRACE;
}
else if (ch == '}')
{
mInput->get();
mToken = Sym::C_BRACE;
}
else if (ch == ';')
{
mInput->get();
mToken = Sym::SC;
}
else if (ch == ',')
{
mInput->get();
mToken = Sym::COMMA;
}
else if (isalpha(ch) || ch == '_')
{
std::string mTokenStr;
mTokenStr.reserve(20);
do
{
mTokenStr += ch;
mInput->get();
ch = mInput->peek();
} while (!(mInput->eof()) && (isalnum(ch) || ch == '_'));
std::map <std::string, Token>::iterator it = sKeywords.find(mTokenStr);
if (it != sKeywords.end()) // keyword
mToken = it->second;
else //identifier
mToken = Token(Sym::ID, mTokenStr);
}
else if ((ch == '"') || (ch == '\''))
{
char quote = ch;
std::string mTokenStr;
mTokenStr.reserve(20);
mInput->get();
ch = mInput->peek();
while (!(mInput->eof()) && (ch != quote))
{
if (ch == '\\')
{
mInput->get();
ch = mInput->peek();
switch (ch)
{
case 't':
ch = '\t';
break;
case 'n':
ch = '\n';
break;
// \\, \', \" will work because we just want to add the
// character after the \ to the string
}
}
mTokenStr += ch;
mInput->get();
ch = mInput->peek();
}
mInput->get();
mToken = Token(Sym::STR, mTokenStr);
}
else if (ch == '+')
{
mInput->get();
ch = mInput->peek();
if (ch == '=')
{
mInput->get();
mToken = Sym::PLUS_EQ;
}
else
mToken = Sym::PLUS;
}
else if (ch == '*')
{
mInput->get();
mToken = Sym::TIMES;
}
else if (ch == '/')
{
mInput->get();
mToken = Sym::DIVIDE;
}
else if ((ch == '-') || (ch == '.') || isdigit(ch))
{
bool minus = false;
std::string mTokenStr;
mTokenStr.reserve(10);
if (ch == '-')
{
mInput->get();
ch = mInput->peek();
if ((!isdigit(ch) && (ch != '.'))
|| (mToken.getType() == Sym::NUM) || (mToken.getType() == Sym::ID)
|| (mToken.getType() == Sym::STR))
minus = true;
else
mTokenStr += '-';
}
if (minus)
mToken = Token(Sym::MINUS);
else
{
bool foundPoint = false;
do
{
foundPoint = (ch == '.') || foundPoint;
mTokenStr += ch;
mInput->get();
ch = mInput->peek();
} while(!(mInput->eof()) && (isdigit(ch) || (!foundPoint && (ch == '.'))));
mToken = Token(Sym::NUM, atof(mTokenStr.c_str()));
}
}
else if (ch == '<')
{
mInput->get();
ch = mInput->peek();
if (ch == '=')
{
mInput->get();
mToken = Token(Sym::LESS_EQ);
}
else
mToken = Token(Sym::LESS);
}
else if (ch == '>')
{
mInput->get();
ch = mInput->peek();
if (ch == '=')
{
mInput->get();
mToken = Token(Sym::GREATER_EQ);
}
else
mToken = Token(Sym::GREATER);
}
else if (ch == '=')
{
mInput->get();
ch = mInput->peek();
if (ch == '=')
{
mInput->get();
mToken = Token(Sym::EQ);
}
else
mToken = Token(Sym::ASSIGN);
}
else if (ch == '&')
{
mInput->get();
ch = mInput->peek();
if (ch == '&')
{
mInput->get();
mToken = Token(Sym::AND);
}
else
mToken = Token(Sym::FAIL, std::string("expected: \"&&\" found \"&") + ch + "\"");
}
else if (ch == '|')
{
mInput->get();
ch = mInput->peek();
if (ch == '|')
{
mInput->get();
mToken = Token(Sym::OR);
}
else
mToken = Token(Sym::FAIL, std::string("expected: \"||\" found \"|") + ch + "\"");
}
else if (ch == '!')
{
mInput->get();
ch = mInput->peek();
if (ch == '=')
{
mInput->get();
mToken = Token(Sym::NOT_EQ);
}
else
mToken = Token(Sym::NOT);
}
else if (ch == ':')
{
mInput->get();
ch = mInput->peek();
if (ch == '=')
{
mInput->get();
mToken = Token(Sym::INIT);
}
else
mToken = Token(Sym::FAIL, std::string("expected: ':=' found ':") + ch + "'");
}
else
{
mInput->get();
mToken = Token(Sym::FAIL, std::string("Invalid mToken: '") + ch + '\'');
}
return mToken;
}
unsigned int Lexer::getLine() const { return mLineNum; }
Lexer &Lexer::operator=(const Lexer &lexer)
{
mInput = lexer.mInput;
}
#ifdef BS_LEXER_DEBUG
#include <iostream>
#include <sstream>
int main ()
{
while (true)
{
std::string str;
std::stringstream stream;
std::cout << "Type some commands (Ctrl-C to exit): ";
std::getline(std::cin, str);
stream.str(str);
Lexer lex(stream);
Token token = lex.getNext();
std::cout << " ";
while ((token.getType() != Sym::END) /*&& (token.getType() != FAIL)*/)
{
std::cout << token << ' ';
token = lex.getNext();
}
// std::cFAIL << token; // show the <END> token
std::cout << std::endl;
}
}
#endif // BS_LEXER_DEBUG
<commit_msg>added escaped newlines in strings<commit_after>/******************************************************************************
* Copyright (C) 2010 by Robert Tolliver *
* Robb.Tolli@gmail.com *
* *
* This file is part of Birthstone. *
* *
* Birthstone is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* Birthstone is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with Birthstone. If not, see <http://www.gnu.org/licenses/>. *
* *
******************************************************************************/
#include "lexer.h"
#include <ostream>
#include <cctype>
#include <cstdlib>
#include <iostream>
#include <sstream>
std::map <std::string, Token> Lexer::sKeywords;
Lexer::Lexer(std::istream &input)
: mInput(&input), mLineNum(1), mToken(Sym::END)
{
setupKeywords();
}
Lexer::Lexer(const Lexer &lexer)
: mInput(lexer.mInput), mLineNum(1), mToken(Sym::END)
{}
Lexer::~Lexer() {}
void Lexer::setupKeywords()
{
if (sKeywords.empty())
{
sKeywords["if"] = Sym::IF;
sKeywords["elif"] = Sym::ELIF;
sKeywords["else"] = Sym::ELSE;
sKeywords["while"] = Sym::WHILE;
sKeywords["until"] = Sym::UNTIL;
sKeywords["for"] = Sym::FOR;
sKeywords["in"] = Sym::IN;
sKeywords["break"] = Sym::BREAK;
sKeywords["continue"] = Sym::CONT;
sKeywords["read"] = Sym::READ;
sKeywords["write"] = Sym::WRITE;
sKeywords["print"] = Sym::PRINT;
sKeywords["def"] = Sym::DEF;
sKeywords["class"] = Sym::CLASS;
sKeywords["and"] = Sym::AND;
sKeywords["or"] = Sym::OR;
sKeywords["not"] = Sym::NOT;
sKeywords["true"] = Token(Sym::BOOL, true);
sKeywords["false"] = Token(Sym::BOOL, false);
sKeywords["exit"] = Sym::QUIT;
sKeywords["quit"] = Sym::QUIT;
}
}
const Token &Lexer::getNext()
{
char ch = mInput->peek();
if (mInput->eof())
mToken = Token(Sym::END);
else if (ch == '#')
{
do
{
mInput->get();
ch = mInput->peek();
} while (!(mInput->eof()) && (ch != '\n'));
++mLineNum;
mInput->get();
return getNext();
}
else if (ch == ' ' || ch == '\t')
{
mInput->get();
return getNext();
}
else if (ch == '\n')
{
++mLineNum;
mInput->get();
return getNext();
}
else if (ch == '(')
{
mInput->get();
mToken = Sym::O_PARAN;
}
else if (ch == ')')
{
mInput->get();
mToken = Sym::C_PARAN;
}
else if (ch == '[')
{
mInput->get();
mToken = Sym::O_BRACKET;
}
else if (ch == ']')
{
mInput->get();
mToken = Sym::C_BRACKET;
}
else if (ch == '{')
{
mInput->get();
mToken = Sym::O_BRACE;
}
else if (ch == '}')
{
mInput->get();
mToken = Sym::C_BRACE;
}
else if (ch == ';')
{
mInput->get();
mToken = Sym::SC;
}
else if (ch == ',')
{
mInput->get();
mToken = Sym::COMMA;
}
else if (isalpha(ch) || ch == '_')
{
std::string mTokenStr;
mTokenStr.reserve(20);
do
{
mTokenStr += ch;
mInput->get();
ch = mInput->peek();
} while (!(mInput->eof()) && (isalnum(ch) || ch == '_'));
std::map <std::string, Token>::iterator it = sKeywords.find(mTokenStr);
if (it != sKeywords.end()) // keyword
mToken = it->second;
else //identifier
mToken = Token(Sym::ID, mTokenStr);
}
else if ((ch == '"') || (ch == '\''))
{
char quote = ch;
std::string mTokenStr;
mTokenStr.reserve(20);
mInput->get();
ch = mInput->peek();
while (!(mInput->eof()) && (ch != quote))
{
if (ch == '\\')
{
mInput->get();
ch = mInput->peek();
switch (ch)
{
case '\n':
ch = mInput->peek();
break;
case '\r':
ch = mInput->peek();
if (ch == '\n')
ch = mInput->peek();
break;
case 't':
ch = '\t';
break;
case 'n':
ch = '\n';
break;
// \\, \', \" will work because we just want to add the
// character after the \ to the string
}
}
mTokenStr += ch;
mInput->get();
ch = mInput->peek();
}
mInput->get();
mToken = Token(Sym::STR, mTokenStr);
}
else if (ch == '+')
{
mInput->get();
ch = mInput->peek();
if (ch == '=')
{
mInput->get();
mToken = Sym::PLUS_EQ;
}
else
mToken = Sym::PLUS;
}
else if (ch == '*')
{
mInput->get();
mToken = Sym::TIMES;
}
else if (ch == '/')
{
mInput->get();
mToken = Sym::DIVIDE;
}
else if ((ch == '-') || (ch == '.') || isdigit(ch))
{
bool minus = false;
std::string mTokenStr;
mTokenStr.reserve(10);
if (ch == '-')
{
mInput->get();
ch = mInput->peek();
if ((!isdigit(ch) && (ch != '.'))
|| (mToken.getType() == Sym::NUM) || (mToken.getType() == Sym::ID)
|| (mToken.getType() == Sym::STR))
minus = true;
else
mTokenStr += '-';
}
if (minus)
mToken = Token(Sym::MINUS);
else
{
bool foundPoint = false;
do
{
foundPoint = (ch == '.') || foundPoint;
mTokenStr += ch;
mInput->get();
ch = mInput->peek();
} while(!(mInput->eof()) && (isdigit(ch) || (!foundPoint && (ch == '.'))));
mToken = Token(Sym::NUM, atof(mTokenStr.c_str()));
}
}
else if (ch == '<')
{
mInput->get();
ch = mInput->peek();
if (ch == '=')
{
mInput->get();
mToken = Token(Sym::LESS_EQ);
}
else
mToken = Token(Sym::LESS);
}
else if (ch == '>')
{
mInput->get();
ch = mInput->peek();
if (ch == '=')
{
mInput->get();
mToken = Token(Sym::GREATER_EQ);
}
else
mToken = Token(Sym::GREATER);
}
else if (ch == '=')
{
mInput->get();
ch = mInput->peek();
if (ch == '=')
{
mInput->get();
mToken = Token(Sym::EQ);
}
else
mToken = Token(Sym::ASSIGN);
}
else if (ch == '&')
{
mInput->get();
ch = mInput->peek();
if (ch == '&')
{
mInput->get();
mToken = Token(Sym::AND);
}
else
mToken = Token(Sym::FAIL, std::string("expected: \"&&\" found \"&") + ch + "\"");
}
else if (ch == '|')
{
mInput->get();
ch = mInput->peek();
if (ch == '|')
{
mInput->get();
mToken = Token(Sym::OR);
}
else
mToken = Token(Sym::FAIL, std::string("expected: \"||\" found \"|") + ch + "\"");
}
else if (ch == '!')
{
mInput->get();
ch = mInput->peek();
if (ch == '=')
{
mInput->get();
mToken = Token(Sym::NOT_EQ);
}
else
mToken = Token(Sym::NOT);
}
else if (ch == ':')
{
mInput->get();
ch = mInput->peek();
if (ch == '=')
{
mInput->get();
mToken = Token(Sym::INIT);
}
else
mToken = Token(Sym::FAIL, std::string("expected: ':=' found ':") + ch + "'");
}
else
{
mInput->get();
mToken = Token(Sym::FAIL, std::string("Invalid mToken: '") + ch + '\'');
}
return mToken;
}
unsigned int Lexer::getLine() const { return mLineNum; }
Lexer &Lexer::operator=(const Lexer &lexer)
{
mInput = lexer.mInput;
}
#ifdef BS_LEXER_DEBUG
#include <iostream>
#include <sstream>
int main ()
{
while (true)
{
std::string str;
std::stringstream stream;
std::cout << "Type some commands (Ctrl-C to exit): ";
std::getline(std::cin, str);
stream.str(str);
Lexer lex(stream);
Token token = lex.getNext();
std::cout << " ";
while ((token.getType() != Sym::END) /*&& (token.getType() != FAIL)*/)
{
std::cout << token << ' ';
token = lex.getNext();
}
// std::cFAIL << token; // show the <END> token
std::cout << std::endl;
}
}
#endif // BS_LEXER_DEBUG
<|endoftext|>
|
<commit_before>//
// Aspia Project
// Copyright (C) 2020 Dmitry Chapyshev <dmitry@aspia.ru>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//
#include "router/database_sqlite.h"
#include "base/logging.h"
#include "base/files/base_paths.h"
#include "base/strings/unicode.h"
#include "build/build_config.h"
#include <optional>
namespace router {
namespace {
template <typename T>
std::optional<T> readInteger(sqlite3_stmt* statement, int column)
{
int column_type = sqlite3_column_type(statement, column);
if (column_type != SQLITE_INTEGER)
{
LOG(LS_ERROR) << "Type is not SQLITE_INTEGER";
return std::nullopt;
}
return static_cast<T>(sqlite3_column_int64(statement, column));
}
std::optional<base::ByteArray> readBlob(sqlite3_stmt* statement, int column)
{
int column_type = sqlite3_column_type(statement, column);
if (column_type != SQLITE_BLOB)
{
LOG(LS_ERROR) << "Type is not SQLITE_BLOB";
return std::nullopt;
}
int blob_size = sqlite3_column_bytes(statement, column);
if (blob_size <= 0)
{
LOG(LS_ERROR) << "Field has an invalid size";
return std::nullopt;
}
const void* blob = sqlite3_column_blob(statement, column);
if (!blob)
{
LOG(LS_ERROR) << "Failed to get the pointer to the field";
return std::nullopt;
}
return base::fromData(blob, static_cast<size_t>(blob_size));
}
std::optional<std::string> readText(sqlite3_stmt* statement, int column)
{
int column_type = sqlite3_column_type(statement, column);
if (column_type != SQLITE_TEXT)
{
LOG(LS_ERROR) << "Type is not SQLITE_TEXT";
return std::nullopt;
}
int string_size = sqlite3_column_bytes(statement, column);
if (string_size <= 0)
{
LOG(LS_ERROR) << "Field has an invalid size";
return std::nullopt;
}
const uint8_t* string = sqlite3_column_text(statement, column);
if (!string)
{
LOG(LS_ERROR) << "Failed to get the pointer to the field";
return std::nullopt;
}
return std::string(reinterpret_cast<const char*>(string), string_size);
}
std::optional<std::u16string> readText16(sqlite3_stmt* statement, int column)
{
std::optional<std::string> str = readText(statement, column);
if (!str.has_value())
return std::nullopt;
return base::utf16FromUtf8(str.value());
}
std::optional<net::User> readUser(sqlite3_stmt* statement)
{
std::optional<uint64_t> entry_id = readInteger<uint64_t>(statement, 0);
if (!entry_id.has_value())
{
LOG(LS_ERROR) << "Failed to get field 'id'";
return std::nullopt;
}
std::optional<std::u16string> name = readText16(statement, 1);
if (!name.has_value())
{
LOG(LS_ERROR) << "Failed to get field 'name'";
return std::nullopt;
}
std::optional<std::string> group = readText(statement, 2);
if (!group.has_value())
{
LOG(LS_ERROR) << "Failed to get field 'group'";
return std::nullopt;
}
std::optional<base::ByteArray> salt = readBlob(statement, 3);
if (!salt.has_value())
{
LOG(LS_ERROR) << "Failed to get field 'salt'";
return std::nullopt;
}
std::optional<base::ByteArray> verifier = readBlob(statement, 4);
if (!verifier.has_value())
{
LOG(LS_ERROR) << "Failed to get field 'verifier'";
return std::nullopt;
}
std::optional<uint32_t> sessions = readInteger<uint32_t>(statement, 5);
if (!sessions.has_value())
{
LOG(LS_ERROR) << "Failed to get field 'sessions'";
return std::nullopt;
}
std::optional<uint32_t> flags = readInteger<uint32_t>(statement, 6);
if (!flags.has_value())
{
LOG(LS_ERROR) << "Failed to get field 'flags'";
return std::nullopt;
}
net::User user;
user.entry_id = entry_id.value();
user.name = std::move(name.value());
user.group = std::move(group.value());
user.salt = std::move(salt.value());
user.verifier = std::move(verifier.value());
user.sessions = sessions.value();
user.flags = flags.value();
return user;
}
} // namespace
DatabaseSqlite::DatabaseSqlite(sqlite3* db)
: db_(db)
{
DCHECK(db_);
}
DatabaseSqlite::~DatabaseSqlite()
{
sqlite3_close(db_);
}
// static
std::unique_ptr<DatabaseSqlite> DatabaseSqlite::open()
{
std::filesystem::path file_path = filePath();
if (file_path.empty())
{
LOG(LS_WARNING) << "Invalid file path";
return nullptr;
}
sqlite3* db = nullptr;
int error_code = sqlite3_open(file_path.u8string().c_str(), &db);
if (error_code != SQLITE_OK)
{
LOG(LS_WARNING) << "sqlite3_open failed: " << sqlite3_errstr(error_code);
return nullptr;
}
return std::unique_ptr<DatabaseSqlite>(new DatabaseSqlite(db));
}
// static
std::filesystem::path DatabaseSqlite::filePath()
{
std::filesystem::path file_path;
#if defined(OS_WIN)
if (!base::BasePaths::currentExecDir(&file_path))
return std::filesystem::path();
file_path.append(u"aspia_router.db3");
#else // defined(OS_*)
#error Not implemented
#endif // defined(OS_*)
return file_path;
}
net::UserList DatabaseSqlite::userList() const
{
const char kQuery[] = "SELECT * FROM users";
sqlite3_stmt* statement;
int error_code = sqlite3_prepare(db_, kQuery, std::size(kQuery), &statement, nullptr);
if (error_code != SQLITE_OK)
{
LOG(LS_ERROR) << "sqlite3_prepare failed: " << sqlite3_errstr(error_code);
return net::UserList();
}
net::UserList users;
for (;;)
{
if (sqlite3_step(statement) != SQLITE_ROW)
break;
std::optional<net::User> user = readUser(statement);
if (user.has_value())
users.add(std::move(user.value()));
}
sqlite3_finalize(statement);
return users;
}
bool DatabaseSqlite::addUser(const net::User& user)
{
NOTIMPLEMENTED();
return false;
}
bool DatabaseSqlite::removeUser(uint64_t entry_id)
{
NOTIMPLEMENTED();
return false;
}
uint64_t DatabaseSqlite::peerId(std::string_view key) const
{
NOTIMPLEMENTED();
return 0;
}
} // namespace router
<commit_msg>Implemented users management in database.<commit_after>//
// Aspia Project
// Copyright (C) 2020 Dmitry Chapyshev <dmitry@aspia.ru>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//
#include "router/database_sqlite.h"
#include "base/logging.h"
#include "base/files/base_paths.h"
#include "base/strings/strcat.h"
#include "base/strings/unicode.h"
#include "build/build_config.h"
#include <optional>
namespace router {
namespace {
bool writeText(sqlite3_stmt* statement, const std::string& text, int column)
{
int error_code = sqlite3_bind_text(statement, column, text.c_str(), text.length(), SQLITE_STATIC);
if (error_code != SQLITE_OK)
{
LOG(LS_ERROR) << "sqlite3_bind_text failed: " << sqlite3_errstr(error_code)
<< " (column: " << column << ")";
return false;
}
return true;
}
bool writeBlob(sqlite3_stmt* statement, const base::ByteArray& blob, int column)
{
int error_code = sqlite3_bind_blob(statement, column, blob.data(), blob.size(), SQLITE_STATIC);
if (error_code != SQLITE_OK)
{
LOG(LS_ERROR) << "sqlite3_bind_blob failed: " << sqlite3_errstr(error_code)
<< " (column: " << column << ")";
return false;
}
return true;
}
bool writeInt(sqlite3_stmt* statement, int number, int column)
{
int error_code = sqlite3_bind_int(statement, column, number);
if (error_code != SQLITE_OK)
{
LOG(LS_ERROR) << "sqlite3_bind_int failed: " << sqlite3_errstr(error_code)
<< " (column: " << column << ")";
return false;
}
return true;
}
bool writeInt64(sqlite3_stmt* statement, int64_t number, int column)
{
int error_code = sqlite3_bind_int64(statement, column, number);
if (error_code != SQLITE_OK)
{
LOG(LS_ERROR) << "sqlite3_bind_int64 failed: " << sqlite3_errstr(error_code)
<< " (column: " << column << ")";
return false;
}
return true;
}
template <typename T>
std::optional<T> readInteger(sqlite3_stmt* statement, int column)
{
int column_type = sqlite3_column_type(statement, column);
if (column_type != SQLITE_INTEGER)
{
LOG(LS_ERROR) << "Type is not SQLITE_INTEGER";
return std::nullopt;
}
return static_cast<T>(sqlite3_column_int64(statement, column));
}
std::optional<base::ByteArray> readBlob(sqlite3_stmt* statement, int column)
{
int column_type = sqlite3_column_type(statement, column);
if (column_type != SQLITE_BLOB)
{
LOG(LS_ERROR) << "Type is not SQLITE_BLOB";
return std::nullopt;
}
int blob_size = sqlite3_column_bytes(statement, column);
if (blob_size <= 0)
{
LOG(LS_ERROR) << "Field has an invalid size";
return std::nullopt;
}
const void* blob = sqlite3_column_blob(statement, column);
if (!blob)
{
LOG(LS_ERROR) << "Failed to get the pointer to the field";
return std::nullopt;
}
return base::fromData(blob, static_cast<size_t>(blob_size));
}
std::optional<std::string> readText(sqlite3_stmt* statement, int column)
{
int column_type = sqlite3_column_type(statement, column);
if (column_type != SQLITE_TEXT)
{
LOG(LS_ERROR) << "Type is not SQLITE_TEXT";
return std::nullopt;
}
int string_size = sqlite3_column_bytes(statement, column);
if (string_size <= 0)
{
LOG(LS_ERROR) << "Field has an invalid size";
return std::nullopt;
}
const uint8_t* string = sqlite3_column_text(statement, column);
if (!string)
{
LOG(LS_ERROR) << "Failed to get the pointer to the field";
return std::nullopt;
}
return std::string(reinterpret_cast<const char*>(string), string_size);
}
std::optional<std::u16string> readText16(sqlite3_stmt* statement, int column)
{
std::optional<std::string> str = readText(statement, column);
if (!str.has_value())
return std::nullopt;
return base::utf16FromUtf8(str.value());
}
std::optional<net::User> readUser(sqlite3_stmt* statement)
{
std::optional<uint64_t> entry_id = readInteger<uint64_t>(statement, 0);
if (!entry_id.has_value())
{
LOG(LS_ERROR) << "Failed to get field 'id'";
return std::nullopt;
}
std::optional<std::u16string> name = readText16(statement, 1);
if (!name.has_value())
{
LOG(LS_ERROR) << "Failed to get field 'name'";
return std::nullopt;
}
std::optional<std::string> group = readText(statement, 2);
if (!group.has_value())
{
LOG(LS_ERROR) << "Failed to get field 'group'";
return std::nullopt;
}
std::optional<base::ByteArray> salt = readBlob(statement, 3);
if (!salt.has_value())
{
LOG(LS_ERROR) << "Failed to get field 'salt'";
return std::nullopt;
}
std::optional<base::ByteArray> verifier = readBlob(statement, 4);
if (!verifier.has_value())
{
LOG(LS_ERROR) << "Failed to get field 'verifier'";
return std::nullopt;
}
std::optional<uint32_t> sessions = readInteger<uint32_t>(statement, 5);
if (!sessions.has_value())
{
LOG(LS_ERROR) << "Failed to get field 'sessions'";
return std::nullopt;
}
std::optional<uint32_t> flags = readInteger<uint32_t>(statement, 6);
if (!flags.has_value())
{
LOG(LS_ERROR) << "Failed to get field 'flags'";
return std::nullopt;
}
net::User user;
user.entry_id = entry_id.value();
user.name = std::move(name.value());
user.group = std::move(group.value());
user.salt = std::move(salt.value());
user.verifier = std::move(verifier.value());
user.sessions = sessions.value();
user.flags = flags.value();
return user;
}
} // namespace
DatabaseSqlite::DatabaseSqlite(sqlite3* db)
: db_(db)
{
DCHECK(db_);
}
DatabaseSqlite::~DatabaseSqlite()
{
sqlite3_close(db_);
}
// static
std::unique_ptr<DatabaseSqlite> DatabaseSqlite::open()
{
std::filesystem::path file_path = filePath();
if (file_path.empty())
{
LOG(LS_WARNING) << "Invalid file path";
return nullptr;
}
sqlite3* db = nullptr;
int error_code = sqlite3_open(file_path.u8string().c_str(), &db);
if (error_code != SQLITE_OK)
{
LOG(LS_WARNING) << "sqlite3_open failed: " << sqlite3_errstr(error_code);
return nullptr;
}
return std::unique_ptr<DatabaseSqlite>(new DatabaseSqlite(db));
}
// static
std::filesystem::path DatabaseSqlite::filePath()
{
std::filesystem::path file_path;
#if defined(OS_WIN)
if (!base::BasePaths::currentExecDir(&file_path))
return std::filesystem::path();
file_path.append(u"aspia_router.db3");
#else // defined(OS_*)
#error Not implemented
#endif // defined(OS_*)
return file_path;
}
net::UserList DatabaseSqlite::userList() const
{
const char kQuery[] = "SELECT * FROM users";
sqlite3_stmt* statement;
int error_code = sqlite3_prepare(db_, kQuery, std::size(kQuery), &statement, nullptr);
if (error_code != SQLITE_OK)
{
LOG(LS_ERROR) << "sqlite3_prepare failed: " << sqlite3_errstr(error_code);
return net::UserList();
}
net::UserList users;
for (;;)
{
if (sqlite3_step(statement) != SQLITE_ROW)
break;
std::optional<net::User> user = readUser(statement);
if (user.has_value())
users.add(std::move(user.value()));
}
sqlite3_finalize(statement);
return users;
}
bool DatabaseSqlite::addUser(const net::User& user)
{
if (!user.isValid())
return false;
static const char kQuery[] =
"INSERT INTO users (name, group, salt, verifier, sessions, flags) VALUES (?, ?, ?, ?, ?, ?)";
sqlite3_stmt* statement = nullptr;
int error_code = sqlite3_prepare(db_, kQuery, std::size(kQuery), &statement, nullptr);
if (error_code != SQLITE_OK)
{
LOG(LS_ERROR) << "sqlite3_prepare failed: " << sqlite3_errstr(error_code);
return false;
}
do
{
if (!writeText(statement, base::utf8FromUtf16(user.name), 1))
break;
if (!writeText(statement, user.group, 2))
break;
if (!writeBlob(statement, user.salt, 3))
break;
if (!writeBlob(statement, user.verifier, 4))
break;
if (!writeInt(statement, static_cast<int>(user.sessions), 5))
break;
if (!writeInt(statement, static_cast<int>(user.flags), 6))
break;
error_code = sqlite3_step(statement);
if (error_code != SQLITE_OK)
{
LOG(LS_ERROR) << "sqlite3_step failed: " << sqlite3_errstr(error_code);
}
}
while (false);
sqlite3_finalize(statement);
return true;
}
bool DatabaseSqlite::removeUser(uint64_t entry_id)
{
static const char kQuery[] = "DELETE FROM users WHERE id=?";
sqlite3_stmt* statement = nullptr;
int error_code = sqlite3_prepare(db_, kQuery, std::size(kQuery), &statement, nullptr);
if (error_code != SQLITE_OK)
{
LOG(LS_ERROR) << "sqlite3_prepare failed: " << sqlite3_errstr(error_code);
return false;
}
do
{
if (!writeInt64(statement, static_cast<int64_t>(entry_id), 1))
break;
error_code = sqlite3_step(statement);
if (error_code != SQLITE_OK)
{
LOG(LS_ERROR) << "sqlite3_step failed: " << sqlite3_errstr(error_code);
}
}
while (false);
sqlite3_finalize(statement);
return true;
}
uint64_t DatabaseSqlite::peerId(std::string_view key) const
{
NOTIMPLEMENTED();
return 0;
}
} // namespace router
<|endoftext|>
|
<commit_before>#include "OsreEdApp.h"
#include "Modules/ModuleBase.h"
#include "Modules/InspectorModule/InspectorModule.h"
#include <osre/Platform/AbstractWindow.h>
#include <osre/Platform/PlatformOperations.h>
#include <osre/RenderBackend/RenderBackendService.h>
#include <osre/RenderBackend/RenderCommon.h>
#include <osre/Scene/TrackBall.h>
#include <osre/App/AssimpWrapper.h>
#include <osre/UI/Canvas.h>
#include <osre/UI/Panel.h>
#include <osre/IO/Directory.h>
#include <osre/IO/Uri.h>
#include <osre/App/Entity.h>
namespace OSRE {
namespace Editor {
using namespace ::OSRE::App;
using namespace ::OSRE::RenderBackend;
static const ui32 HorizontalMargin = 2;
static const ui32 VerticalMargin = 2;
OsreEdApp::UiScreen::UiScreen() :
m_canvas( nullptr ),
m_mainPanel( nullptr ),
m_logPanel( nullptr ),
m_modelPanel( nullptr ) {
// empty
}
OsreEdApp::OsreEdApp(int argc, char *argv[]) :
AppBase(argc, (const char **)argv, "api", "The render API"),
mUiScreen(),
mModuleArray(),
mModulePathArray(),
mTrackBall( nullptr ){
// empty
}
OsreEdApp::~OsreEdApp() {
// empty
}
bool OsreEdApp::addModulePath( const String &path ) {
if (path.empty()) {
return false;
}
if (mModulePathArray.find(path) == nullptr) {
mModulePathArray.add(path);
}
return true;
}
bool OsreEdApp::registerModule( ModuleBase *mod ) {
if (nullptr == mod) {
return false;
}
if (nullptr == mModuleArray.find(mod) ) {
mModuleArray.add(mod);
}
return true;
}
bool OsreEdApp::loadModules() {
// Load registered modules
for (size_t i = 0; i < mModuleArray.size(); ++i) {
ModuleBase *mod = mModuleArray[i];
if (!mod->load(this)) {
return false;
}
}
return true;
}
UI::Panel *OsreEdApp::getRootPanel() const {
return mUiScreen.m_mainPanel;
}
bool OsreEdApp::onCreate() {
if (!AppBase::onCreate()) {
return false;
}
//registerModule(new InspectorModule());
//loadModules();
/*Rect2ui r;
AppBase::getRootWindow()->getWindowsRect(r);*/
/*mUiScreen.m_canvas = AppBase::createScreen("OsreEd");
mUiScreen.m_canvas->setRect(r);
mUiScreen.m_mainPanel = new UI::Panel("main_panel", mUiScreen.m_canvas);
mUiScreen.m_mainPanel->setRect(r);
mUiScreen.m_logPanel = new UI::Panel("log_panel", mUiScreen.m_mainPanel);
mUiScreen.m_logPanel->setHeadline("Log");
mUiScreen.m_logPanel->setRect(r.getX1() + HorizontalMargin, r.getY1() + r.getHeight() / 3,
r.getWidth() - 2 * HorizontalMargin, r.getHeight() - (r.getY1() + r.getHeight() / 3) - 2 * VerticalMargin);
mUiScreen.m_modelPanel = new UI::Panel("model_panel", mUiScreen.m_mainPanel);
mUiScreen.m_modelPanel->setHeadline("Model");*/
AppBase::setWindowsTitle("OSRE ED! Press o to import an Asset");
return true;
}
void OsreEdApp::loadAsset(const IO::Uri &modelLoc) {
AssimpWrapper assimpWrapper(*getIdContainer());
if (!assimpWrapper.importAsset(modelLoc, 0)) {
return;
}
RenderBackendService *rbSrv = getRenderBackendService();
if (nullptr == rbSrv) {
return;
}
Platform::AbstractWindow *rootWindow = getRootWindow();
if (nullptr == rootWindow) {
return;
}
mStage = AppBase::createStage("ModelLoading");
AppBase::setActiveStage(mStage);
m_view = mStage->addView("default_view", nullptr);
AppBase::setActiveView(m_view);
Rect2ui windowsRect;
rootWindow->getWindowsRect(windowsRect);
mTrackBall = new Scene::TrackBall("trackball", windowsRect.getWidth(), windowsRect.getHeight());
m_view->setProjectionParameters(60.f, (f32)windowsRect.m_width, (f32)windowsRect.m_height, 0.01f, 1000.f);
Entity *entity = assimpWrapper.getEntity();
World *world = getActiveWorld();
world->addEntity(entity);
m_view->observeBoundingBox(entity->getAABB());
m_modelNode = entity->getNode();
}
void OsreEdApp::onUpdate() {
if (AppBase::isKeyPressed(Platform::KEY_O)) {
IO::Uri modelLoc;
Platform::PlatformOperations::getFileOpenDialog("*", modelLoc);
if (modelLoc.isValid()) {
loadAsset(modelLoc);
}
}
i32 x = 0, y = 0;
if (AppBase::isMouseMoved(x, y)) {
}
/*for (ui32 i = 0; i < mModuleArray.size(); ++i) {
mModuleArray[i]->update();
}*/
// Rotate the model
glm::mat4 rot(1.0);
m_transformMatrix.m_model = glm::rotate(rot, m_angle, glm::vec3(0, 1, 1));
m_angle += 0.01f;
RenderBackendService *rbSrv = getRenderBackendService();
rbSrv->beginPass(PipelinePass::getPassNameById(RenderPassId));
rbSrv->beginRenderBatch("b1");
rbSrv->setMatrix(MatrixType::Model, m_transformMatrix.m_model);
rbSrv->endRenderBatch();
rbSrv->endPass();
AppBase::onUpdate();
}
bool OsreEdApp::onDestroy() {
return true;
}
} // namespace Editor
} // namespace OSRE
<commit_msg>add menu to osre_ed.<commit_after>#include "OsreEdApp.h"
#include "Modules/ModuleBase.h"
#include "Modules/InspectorModule/InspectorModule.h"
#include <osre/Platform/AbstractWindow.h>
#include <osre/Platform/PlatformOperations.h>
#include <osre/RenderBackend/RenderBackendService.h>
#include <osre/RenderBackend/RenderCommon.h>
#include <osre/Scene/TrackBall.h>
#include <osre/App/AssimpWrapper.h>
#include <osre/UI/Canvas.h>
#include <osre/UI/Panel.h>
#include <osre/IO/Directory.h>
#include <osre/IO/Uri.h>
#include <osre/App/Entity.h>
#include "Engine/Platform/win32/Win32Window.h"
namespace OSRE {
namespace Editor {
using namespace ::OSRE::App;
using namespace ::OSRE::RenderBackend;
static const ui32 HorizontalMargin = 2;
static const ui32 VerticalMargin = 2;
#ifdef OSRE_WINDOWS
#define IDM_FILE_NEW 1
#define IDM_FILE_OPEN 2
#define IDM_FILE_SAVE 3
#define IDM_FILE_IMPORT 4
#define IDM_FILE_QUIT 5
#define IDM_INFO_VERSION 6
void AddFileMenus(HWND hwnd) {
HMENU hMenubar;
HMENU hMenu;
hMenubar = CreateMenu();
hMenu = CreateMenu();
AppendMenuW(hMenu, MF_STRING, IDM_FILE_NEW, L"&New");
AppendMenuW(hMenu, MF_STRING, IDM_FILE_OPEN, L"&Open Project");
AppendMenuW(hMenu, MF_STRING, IDM_FILE_SAVE, L"&Save Project");
AppendMenuW(hMenu, MF_SEPARATOR, 0, NULL);
AppendMenuW(hMenu, MF_STRING, IDM_FILE_OPEN, L"&Import");
AppendMenuW(hMenu, MF_SEPARATOR, 0, NULL);
AppendMenuW(hMenu, MF_STRING, IDM_FILE_QUIT, L"&Quit");
AppendMenuW(hMenubar, MF_POPUP, (UINT_PTR)hMenu, L"&File");
hMenu = CreateMenu();
AppendMenuW(hMenu, MF_STRING, IDM_INFO_VERSION, L"&Version");
AppendMenuW(hMenubar, MF_POPUP, (UINT_PTR)hMenu, L"&Info");
SetMenu(hwnd, hMenubar);
}
#endif // OSRE_WINDOWS
OsreEdApp::UiScreen::UiScreen() :
m_canvas( nullptr ),
m_mainPanel( nullptr ),
m_logPanel( nullptr ),
m_modelPanel( nullptr ) {
// empty
}
OsreEdApp::OsreEdApp(int argc, char *argv[]) :
AppBase(argc, (const char **)argv, "api", "The render API"),
mUiScreen(),
mModuleArray(),
mModulePathArray(),
mTrackBall( nullptr ){
// empty
}
OsreEdApp::~OsreEdApp() {
// empty
}
bool OsreEdApp::addModulePath( const String &path ) {
if (path.empty()) {
return false;
}
if (mModulePathArray.find(path) == nullptr) {
mModulePathArray.add(path);
}
return true;
}
bool OsreEdApp::registerModule( ModuleBase *mod ) {
if (nullptr == mod) {
return false;
}
if (nullptr == mModuleArray.find(mod) ) {
mModuleArray.add(mod);
}
return true;
}
bool OsreEdApp::loadModules() {
// Load registered modules
for (size_t i = 0; i < mModuleArray.size(); ++i) {
ModuleBase *mod = mModuleArray[i];
if (!mod->load(this)) {
return false;
}
}
return true;
}
UI::Panel *OsreEdApp::getRootPanel() const {
return mUiScreen.m_mainPanel;
}
bool OsreEdApp::onCreate() {
if (!AppBase::onCreate()) {
return false;
}
//registerModule(new InspectorModule());
//loadModules();
/*Rect2ui r;
AppBase::getRootWindow()->getWindowsRect(r);*/
/*mUiScreen.m_canvas = AppBase::createScreen("OsreEd");
mUiScreen.m_canvas->setRect(r);
mUiScreen.m_mainPanel = new UI::Panel("main_panel", mUiScreen.m_canvas);
mUiScreen.m_mainPanel->setRect(r);
mUiScreen.m_logPanel = new UI::Panel("log_panel", mUiScreen.m_mainPanel);
mUiScreen.m_logPanel->setHeadline("Log");
mUiScreen.m_logPanel->setRect(r.getX1() + HorizontalMargin, r.getY1() + r.getHeight() / 3,
r.getWidth() - 2 * HorizontalMargin, r.getHeight() - (r.getY1() + r.getHeight() / 3) - 2 * VerticalMargin);
mUiScreen.m_modelPanel = new UI::Panel("model_panel", mUiScreen.m_mainPanel);
mUiScreen.m_modelPanel->setHeadline("Model");*/
AppBase::setWindowsTitle("OSRE ED! Press o to import an Asset");
Platform::Win32Window *w = (Platform::Win32Window *)getRootWindow();
if (nullptr != w) {
AddFileMenus(w->getHWnd());
}
return true;
}
void OsreEdApp::loadAsset(const IO::Uri &modelLoc) {
AssimpWrapper assimpWrapper(*getIdContainer());
if (!assimpWrapper.importAsset(modelLoc, 0)) {
return;
}
RenderBackendService *rbSrv = getRenderBackendService();
if (nullptr == rbSrv) {
return;
}
Platform::AbstractWindow *rootWindow = getRootWindow();
if (nullptr == rootWindow) {
return;
}
mStage = AppBase::createStage("ModelLoading");
AppBase::setActiveStage(mStage);
m_view = mStage->addView("default_view", nullptr);
AppBase::setActiveView(m_view);
Rect2ui windowsRect;
rootWindow->getWindowsRect(windowsRect);
mTrackBall = new Scene::TrackBall("trackball", windowsRect.getWidth(), windowsRect.getHeight());
m_view->setProjectionParameters(60.f, (f32)windowsRect.m_width, (f32)windowsRect.m_height, 0.01f, 1000.f);
Entity *entity = assimpWrapper.getEntity();
World *world = getActiveWorld();
world->addEntity(entity);
m_view->observeBoundingBox(entity->getAABB());
m_modelNode = entity->getNode();
}
void OsreEdApp::onUpdate() {
if (AppBase::isKeyPressed(Platform::KEY_O)) {
IO::Uri modelLoc;
Platform::PlatformOperations::getFileOpenDialog("*", modelLoc);
if (modelLoc.isValid()) {
loadAsset(modelLoc);
}
}
i32 x = 0, y = 0;
if (AppBase::isMouseMoved(x, y)) {
}
/*for (ui32 i = 0; i < mModuleArray.size(); ++i) {
mModuleArray[i]->update();
}*/
// Rotate the model
glm::mat4 rot(1.0);
m_transformMatrix.m_model = glm::rotate(rot, m_angle, glm::vec3(0, 1, 1));
m_angle += 0.01f;
RenderBackendService *rbSrv = getRenderBackendService();
rbSrv->beginPass(PipelinePass::getPassNameById(RenderPassId));
rbSrv->beginRenderBatch("b1");
rbSrv->setMatrix(MatrixType::Model, m_transformMatrix.m_model);
rbSrv->endRenderBatch();
rbSrv->endPass();
AppBase::onUpdate();
}
bool OsreEdApp::onDestroy() {
return true;
}
} // namespace Editor
} // namespace OSRE
<|endoftext|>
|
<commit_before>#include <chrono>
#include <iostream>
#include "peers.hpp"
#include "config.hpp"
#include "requestHandler.hpp"
Peers::Peers() {
pMap = PeerMap();
it = std::begin(pMap);
auto time_point = std::chrono::system_clock::now();
auto duration = time_point.time_since_epoch();
lastUpdate = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
}
Peer* Peers::getPeer(const std::string& peerID, long long now) {
lastUpdate = now;
try {
return &pMap.at(peerID);
} catch (const std::exception& e) {
return nullptr;
}
}
Peer* Peers::addPeer(const Request& req, unsigned int fid, long long now) {
User* u = nullptr;
if (Config::get("type") == "private")
u = RequestHandler::getUser(req.at("passkey"));
Peer* p = new Peer(req.at("ip"), u, req.at("left") == "0", std::stoul(req.at("left")), fid, req.at("user-agent"), req.at("peer_id"));
pMap.emplace(req.at("peer_id"), *p);
lastUpdate = now;
return p;
}
void Peers::removePeer(const Request& req) {
pMap.erase(req.at("peer_id"));
}
Peer* Peers::nextPeer(long long now) {
while (pMap.size() > 0) {
if (it == std::end(pMap)) {
it = std::begin(pMap);
} else if (it->second.timedOut(now)) {
pMap.erase(it++);
} else {
PeerMap::iterator tmp = it;
it = std::next(it);
return &tmp->second;
}
}
return nullptr;
}
unsigned long Peers::size () {
return pMap.size();
}
bool Peers::timedOut(long long now, Database* db)
{
auto it = pMap.begin();
bool changed = false;
while (it != pMap.end()) {
if (it->second.timedOut(now)) {
if (Config::get("type") == "public")
pMap.erase(it);
else {
it->second.inactive();
db->recordPeer(&it->second, now);
changed = true;
}
}
++it;
}
return changed;
}
<commit_msg>remove inactive peers from memory<commit_after>#include <chrono>
#include <iostream>
#include "peers.hpp"
#include "config.hpp"
#include "requestHandler.hpp"
Peers::Peers() {
pMap = PeerMap();
it = std::begin(pMap);
auto time_point = std::chrono::system_clock::now();
auto duration = time_point.time_since_epoch();
lastUpdate = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
}
Peer* Peers::getPeer(const std::string& peerID, long long now) {
lastUpdate = now;
try {
return &pMap.at(peerID);
} catch (const std::exception& e) {
return nullptr;
}
}
Peer* Peers::addPeer(const Request& req, unsigned int fid, long long now) {
User* u = nullptr;
if (Config::get("type") == "private")
u = RequestHandler::getUser(req.at("passkey"));
Peer* p = new Peer(req.at("ip"), u, req.at("left") == "0", std::stoul(req.at("left")), fid, req.at("user-agent"), req.at("peer_id"));
pMap.emplace(req.at("peer_id"), *p);
lastUpdate = now;
return p;
}
void Peers::removePeer(const Request& req) {
pMap.erase(req.at("peer_id"));
}
Peer* Peers::nextPeer(long long now) {
while (pMap.size() > 0) {
if (it == std::end(pMap)) {
it = std::begin(pMap);
} else if (it->second.timedOut(now)) {
pMap.erase(it++);
} else {
PeerMap::iterator tmp = it;
it = std::next(it);
return &tmp->second;
}
}
return nullptr;
}
unsigned long Peers::size () {
return pMap.size();
}
bool Peers::timedOut(long long now, Database* db)
{
auto it = pMap.begin();
bool changed = false;
while (it != pMap.end()) {
if (it->second.timedOut(now)) {
if (Config::get("type") == "private") {
it->second.inactive();
db->recordPeer(&it->second, now);
changed = true;
}
}
pMap.erase(it++);
}
return changed;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: txtcmp.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 14:12:20 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _TXTCMP_HXX
#define _TXTCMP_HXX
#include <unotools/textsearch.hxx>
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.3.774); FILE MERGED 2008/03/31 13:00:57 rt 1.3.774.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: txtcmp.hxx,v $
* $Revision: 1.4 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _TXTCMP_HXX
#define _TXTCMP_HXX
#include <unotools/textsearch.hxx>
#endif
<|endoftext|>
|
<commit_before>/*
*
* Resource loader, functions for loading all supported data types
* - Loads scene information from json
* - Loads textures form TGA's
* - Loads models from 3ds
*
*/
#include "resourceloader.hpp"
#include <glm/glm.hpp>
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include <FreeImage.h>
#include <json.hpp>
#include <memory>
#include <vector>
#include <fstream>
#include <iostream>
#include <Utilities/exceptions.hpp>
#include <Core/glapi.hpp>
#include <Resources/model3d.hpp>
#include <Models/line.hpp>
#include <Models/staticmodel.hpp>
using namespace gl;
using json = nlohmann::json;
std::shared_ptr<IRenderObject> LoadStaticModelJSON(json object) {
std::string type = "";
std::string name = "";
try {
type = object["datatype"];
} catch (std::domain_error& error) {
type = "normal";
}
try {
name = object["name"];
} catch (std::domain_error& error) {
name = "null";
}
std::shared_ptr<IRenderObject> rObject;
if(type == "normal") {
rObject = std::make_shared<StaticModel>(ResourceLoader::LoadModel3D(object["filename"]));
} else if(type == "raw") {
std::vector<glm::vec3> verts;
std::vector<std::vector<float>> vertsf = object["vertices"];
for(std::vector<float> vert : vertsf) {
if(vert.size() != 3) {
throw bad_resource("Vertex data size is not 3", name);
}
verts.push_back(glm::vec3(vert[0], vert[1], vert[2]));
}
std::vector<GLuint> indices;
std::vector<uint> indicesf = object["indices"];
for(uint index : indicesf) {
if(index >= verts.size()) {
throw bad_resource("Index is out of range", name);
}
indices.push_back(index);
}
std::vector<glm::vec3> norms;
try {
std::vector<std::vector<float>> normsf = object["normals"];
for(std::vector<float> norm : normsf) {
if(norm.size() != 3) {
throw bad_resource("Normal data size is not 3", name);
}
norms.push_back(glm::vec3(norm[0], norm[1], norm[2]));
}
} catch (std::domain_error& error) {
norms.clear();
for(uint i = 0; i < verts.size(); i++) {
norms.push_back(glm::vec3(0.0f));
}
}
std::vector<glm::vec2> uvs;
try {
std::vector<std::vector<float>> uvsf = object["uvs"];
for(std::vector<float> uv : uvsf) {
if(uv.size() != 2) {
throw bad_resource("UV data size is not 2", name);
}
uvs.push_back(glm::vec2(uv[0], uv[1]));
}
} catch (std::domain_error& error) {
uvs.clear();
for(uint i = 0; i < verts.size(); i++) {
uvs.push_back(glm::vec2(0.0f));
}
}
std::vector<Model3D::Vertex> vertices;
for(uint i = 0; i < verts.size(); i++) {
vertices.push_back(Model3D::Vertex(verts[i], norms[i], uvs[i]));
}
std::vector<std::shared_ptr<Model3D::Mesh>> meshes;
meshes.push_back(std::make_shared<Model3D::Mesh>(vertices, indices));
meshes[0]->SetMatName("texture");
std::unordered_map<std::string, std::shared_ptr<Texture>> textures;
textures["texture"] = ResourceLoader::LoadTexture(object["matname"], true);
rObject = std::make_shared<StaticModel>(std::make_shared<Model3D>(meshes, textures));
} else {
throw bad_resource("Unknown data type", name);
}
try {
std::vector<float> scale = object["scale"];
if(scale.size() != 3) {
throw std::domain_error("scale data size is not 3");
}
rObject->Scale(glm::vec3(scale[0], scale[1], scale[2]));
} catch (std::domain_error& error) {}
try {
std::vector<float> translation = object["translation"];
if(translation.size() != 3) {
throw bad_resource("translation data size is not 3", name);
}
rObject->Translate(glm::vec3(translation[0], translation[1], translation[2]));
} catch (std::domain_error& error) {}
try {
std::vector<float> rotation = object["rotation"];
if(rotation.size() != 3) {
throw bad_resource("Rotation data size is not 3", name);
}
} catch (std::domain_error& error) {}
return rObject;
}
std::shared_ptr<IRenderObject> LoadLineJSON(json object) {
glm::vec3 head, tail, color;
std::string name;
try {
name = object["name"];
} catch (std::domain_error& error) {
name = "null";
}
std::vector<float> head3f = object["head"];
if(head3f.size() == 3) {
head = glm::vec3(head3f[0], head3f[1], head3f[2]);
} else {
throw bad_resource("head data size is not 3", name);
}
std::vector<float> tail3f = object["tail"];
if(tail3f.size() == 3) {
tail = glm::vec3(tail3f[0], tail3f[1], tail3f[2]);
} else {
throw bad_resource("tail data size is not 3", name);
}
std::vector<float> color3f = object["color"];
if(head3f.size() == 3) {
color = glm::vec3(color3f[0], color3f[1], color3f[2]);
} else {
throw bad_resource("color data size is not 3", name);
}
return std::make_shared<Line>(head, tail, color);
}
std::vector<std::shared_ptr<IRenderObject>> ResourceLoader::LoadScene(std::string filename) {
std::vector<std::shared_ptr<IRenderObject>> renderObjects;
filename = "Scenes/" + filename + ".json";
std::string contents;
std::ifstream in(filename, std::ios::in | std::ios::binary);
if (in) {
in.seekg(0, std::ios::end);
contents.resize(in.tellg());
in.seekg(0, std::ios::beg);
in.read(&contents[0], contents.size());
in.close();
} else {
throw generic_exception(filename + " doesn't exist");
}
try {
json scene = json::parse(contents);
std::vector<json> objects = scene["staticObjects"];
for(json object : objects) {
std::string type = "";
std::string name = "";
try {
type = object["type"];
std::shared_ptr<IRenderObject> rObject;
if(type == "line") {
rObject = LoadLineJSON(object);
} else if(type == "staticmodel") {
rObject = LoadStaticModelJSON(object);
}
if(rObject != nullptr) {
renderObjects.push_back(rObject);
}
} catch (bad_resource& error) {
std::cout << "[" << error.GetResourceName() << "] " << error.GetError() << std::endl;
}
}
} catch(std::exception& error) {
std::cout << "Parsing of " << filename << " failed : " << error.what() << std::endl;
}
return renderObjects;
}
std::shared_ptr<Texture> ResourceLoader::LoadTexture(std::string filename, bool genMipMaps) {
FIBITMAP *img;
filename = "./Textures/" + filename + ".tga";
FREE_IMAGE_FORMAT format = FreeImage_GetFIFFromFilename(filename.c_str());
if(!FreeImage_FIFSupportsReading(format)) {
throw bad_resource("FreeImage can't read from file", filename);
}
if(format == FIF_UNKNOWN) {
throw bad_resource("Unknown format", filename);
}
img = FreeImage_Load(format, filename.c_str());
if(!img) {
throw bad_resource("Couldn't load image data", filename);
}
if(FreeImage_GetBPP(img) != 32) {
FIBITMAP* oldImg = img;
img = FreeImage_ConvertTo32Bits(oldImg);
FreeImage_Unload(oldImg);
}
int height, width;
width = FreeImage_GetWidth(img);
height = FreeImage_GetHeight(img);
unsigned char* bytes = FreeImage_GetBits(img);
if(bytes == nullptr) {
FreeImage_Unload(img);
throw bad_resource("couldn't load image bytes", filename);
}
GLuint glTexture;
glBindTexture(GL_TEXTURE_2D, 0);
glGenTextures(1, &glTexture);
glBindTexture(GL_TEXTURE_2D, glTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_BGRA, GL_UNSIGNED_BYTE, bytes);
if(genMipMaps) {
glGenerateMipmap(GL_TEXTURE_2D);
}
glBindTexture(GL_TEXTURE_2D, 0);
if(!glIsTexture(glTexture)) {
FreeImage_Unload(img);
throw bad_resource("texture is not valid", filename);
}
FreeImage_Unload(img);
std::shared_ptr<Texture> texture = std::make_shared<Texture>();
texture->SetFileName(filename);
texture->SetTexture(glTexture);
return texture;
}
void CopyaiMat(const aiMatrix4x4* from, glm::mat4& to) {
to[0][0] = from->a1; to[1][0] = from->a2;
to[2][0] = from->a3; to[3][0] = from->a4;
to[0][1] = from->b1; to[1][1] = from->b2;
to[2][1] = from->b3; to[3][1] = from->b4;
to[0][2] = from->c1; to[1][2] = from->c2;
to[2][2] = from->c3; to[3][2] = from->c4;
to[0][3] = from->d1; to[1][3] = from->d2;
to[2][3] = from->d3; to[3][3] = from->d4;
}
void LoadNode(const aiScene* scene, const aiNode* node, std::vector<std::shared_ptr<Model3D::Mesh>>& meshes) {
for(uint i = 0; i < node->mNumChildren; i++) {
LoadNode(scene, node->mChildren[i], meshes);
}
for(uint i = 0; i < node->mNumMeshes; i++) {
aiMesh* mesh = scene->mMeshes[node->mMeshes[i]];
std::vector<Model3D::Vertex> vertices;
for(uint j = 0; j < mesh->mNumVertices; j++) {
Model3D::Vertex vertex;
vertex.position = glm::vec3(mesh->mVertices[j].x, mesh->mVertices[j].y, mesh->mVertices[j].z);
vertex.normal = (mesh->HasNormals())
? glm::vec3(mesh->mNormals[j].x, mesh->mNormals[j].y, mesh->mNormals[j].z)
: glm::vec3(0.0f, 0.0f, 0.0f);
vertex.texCoord = (mesh->HasTextureCoords(0))
? glm::vec2(mesh->mTextureCoords[0][j].x, mesh->mTextureCoords[0][j].y)
: glm::vec2(0.0f, 0.0f);
vertices.push_back(vertex);
}
std::vector<uint> indices;
if(mesh->HasFaces()) {
for(uint j = 0; j < mesh->mNumFaces; j++) {
aiFace face = mesh->mFaces[j];
for(uint k = 0; k < face.mNumIndices; k++) {
indices.push_back(face.mIndices[k]);
}
}
} else {
throw bad_resource("Node was missing faces, load cancled");
}
glm::mat4x4 transformation;
CopyaiMat(&node->mTransformation, transformation);
std::shared_ptr<Model3D::Mesh> rmesh = std::make_shared<Model3D::Mesh>(vertices, indices);
rmesh->SetTransformation(transformation);
rmesh->SetMatIndex(mesh->mMaterialIndex);
meshes.push_back(rmesh);
}
}
std::shared_ptr<Model3D> ResourceLoader::LoadModel3D(std::string modelname) throw(bad_resource) {
std::string filename = "Models/" + modelname + ".3ds";
Assimp::Importer importer;
const aiScene* scene = importer.ReadFile(filename.c_str(),
aiProcess_CalcTangentSpace |
aiProcess_Triangulate |
aiProcess_JoinIdenticalVertices |
aiProcess_SortByPType);
if(!scene || !scene->mRootNode || scene->mFlags == AI_SCENE_FLAGS_INCOMPLETE) {
throw bad_resource(importer.GetErrorString(), filename);
}
auto model = std::make_shared<Model3D>();
aiMaterial** materials = scene->mMaterials;
std::unordered_map<std::string, std::shared_ptr<Texture>> textures;
for(uint i = 0; i < scene->mNumMaterials; i++) {
aiString aName;
materials[i]->Get(AI_MATKEY_NAME, aName);
std::string name = std::string(aName.C_Str());
if(textures.find(name) == textures.end()) {
try {
std::shared_ptr<Texture> temp = LoadTexture(modelname + "/" + name, true);
if(temp != nullptr) {
textures[name] = temp;
}
} catch (bad_resource& error) {
std::cout << "[" << error.GetResourceName() << "] " << error.GetError() << std::endl;
}
}
}
model->SetTextures(textures);
std::vector<std::shared_ptr<Model3D::Mesh>> meshes;
LoadNode(scene, scene->mRootNode, meshes);
for(std::shared_ptr<Model3D::Mesh>& mesh : meshes) {
aiString aName;
uint index = mesh->GetMatIndex();
if(index < scene->mNumMaterials) {
materials[mesh->GetMatIndex()]->Get(AI_MATKEY_NAME, aName);
mesh->SetMatName(std::string(aName.C_Str()));
}
}
model->SetMeshes(meshes);
return model;
}
<commit_msg>stupid error fixed<commit_after>/*
*
* Resource loader, functions for loading all supported data types
* - Loads scene information from json
* - Loads textures form TGA's
* - Loads models from 3ds
*
*/
#include "resourceloader.hpp"
#include <glm/glm.hpp>
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include <FreeImage.h>
#include <json.hpp>
#include <memory>
#include <vector>
#include <fstream>
#include <iostream>
#include <Utilities/exceptions.hpp>
#include <Core/glapi.hpp>
#include <Resources/model3d.hpp>
#include <Models/line.hpp>
#include <Models/staticmodel.hpp>
using namespace gl;
using json = nlohmann::json;
std::shared_ptr<IRenderObject> LoadStaticModelJSON(json object) {
std::string type = "";
std::string name = "";
try {
type = object["datatype"];
} catch (std::domain_error& error) {
type = "normal";
}
try {
name = object["name"];
} catch (std::domain_error& error) {
name = "null";
}
std::shared_ptr<IRenderObject> rObject;
if(type == "normal") {
rObject = std::make_shared<StaticModel>(ResourceLoader::LoadModel3D(object["filename"]));
} else if(type == "raw") {
std::vector<glm::vec3> verts;
std::vector<std::vector<float>> vertsf = object["vertices"];
for(std::vector<float> vert : vertsf) {
if(vert.size() != 3) {
throw bad_resource("Vertex data size is not 3", name);
}
verts.push_back(glm::vec3(vert[0], vert[1], vert[2]));
}
std::vector<GLuint> indices;
std::vector<uint> indicesf = object["indices"];
for(uint index : indicesf) {
if(index >= verts.size()) {
throw bad_resource("Index is out of range", name);
}
indices.push_back(index);
}
std::vector<glm::vec3> norms;
try {
std::vector<std::vector<float>> normsf = object["normals"];
for(std::vector<float> norm : normsf) {
if(norm.size() != 3) {
throw bad_resource("Normal data size is not 3", name);
}
norms.push_back(glm::vec3(norm[0], norm[1], norm[2]));
}
} catch (std::domain_error& error) {
norms.clear();
for(uint i = 0; i < verts.size(); i++) {
norms.push_back(glm::vec3(0.0f));
}
}
std::vector<glm::vec2> uvs;
try {
std::vector<std::vector<float>> uvsf = object["uvs"];
for(std::vector<float> uv : uvsf) {
if(uv.size() != 2) {
throw bad_resource("UV data size is not 2", name);
}
uvs.push_back(glm::vec2(uv[0], uv[1]));
}
} catch (std::domain_error& error) {
uvs.clear();
for(uint i = 0; i < verts.size(); i++) {
uvs.push_back(glm::vec2(0.0f));
}
}
std::vector<Model3D::Vertex> vertices;
for(uint i = 0; i < verts.size(); i++) {
vertices.push_back(Model3D::Vertex(verts[i], norms[i], uvs[i]));
}
std::vector<std::shared_ptr<Model3D::Mesh>> meshes;
meshes.push_back(std::make_shared<Model3D::Mesh>(vertices, indices));
meshes[0]->SetMatName("texture");
std::unordered_map<std::string, std::shared_ptr<Texture>> textures;
textures["texture"] = ResourceLoader::LoadTexture(object["matname"], true);
rObject = std::make_shared<StaticModel>(std::make_shared<Model3D>(meshes, textures));
} else {
throw bad_resource("Unknown data type", name);
}
try {
std::vector<float> scale = object["scale"];
if(scale.size() != 3) {
throw std::domain_error("scale data size is not 3");
}
rObject->Scale(glm::vec3(scale[0], scale[1], scale[2]));
} catch (std::domain_error& error) {}
try {
std::vector<float> translation = object["translation"];
if(translation.size() != 3) {
throw bad_resource("translation data size is not 3", name);
}
rObject->Translate(glm::vec3(translation[0], translation[1], translation[2]));
} catch (std::domain_error& error) {}
try {
std::vector<float> rotation = object["rotation"];
if(rotation.size() != 3) {
throw bad_resource("Rotation data size is not 3", name);
}
} catch (std::domain_error& error) {}
return rObject;
}
std::shared_ptr<IRenderObject> LoadLineJSON(json object) {
glm::vec3 head, tail, color;
std::string name;
try {
name = object["name"];
} catch (std::domain_error& error) {
name = "null";
}
std::vector<float> head3f = object["head"];
if(head3f.size() == 3) {
head = glm::vec3(head3f[0], head3f[1], head3f[2]);
} else {
throw bad_resource("head data size is not 3", name);
}
std::vector<float> tail3f = object["tail"];
if(tail3f.size() == 3) {
tail = glm::vec3(tail3f[0], tail3f[1], tail3f[2]);
} else {
throw bad_resource("tail data size is not 3", name);
}
std::vector<float> color3f = object["color"];
if(head3f.size() == 3) {
color = glm::vec3(color3f[0], color3f[1], color3f[2]);
} else {
throw bad_resource("color data size is not 3", name);
}
return std::make_shared<Line>(head, tail, color);
}
std::vector<std::shared_ptr<IRenderObject>> ResourceLoader::LoadScene(std::string filename) {
std::vector<std::shared_ptr<IRenderObject>> renderObjects;
filename = "Scenes/" + filename + ".json";
std::string contents;
std::ifstream in(filename, std::ios::in | std::ios::binary);
if (in) {
in.seekg(0, std::ios::end);
contents.resize(in.tellg());
in.seekg(0, std::ios::beg);
in.read(&contents[0], contents.size());
in.close();
} else {
throw generic_exception(filename + " doesn't exist");
}
try {
json scene = json::parse(contents);
std::vector<json> objects = scene["staticObjects"];
for(json object : objects) {
std::string type = "";
std::string name = "";
try {
type = object["type"];
std::shared_ptr<IRenderObject> rObject;
if(type == "line") {
rObject = LoadLineJSON(object);
} else if(type == "staticmodel") {
rObject = LoadStaticModelJSON(object);
}
if(rObject != nullptr) {
renderObjects.push_back(rObject);
}
} catch (bad_resource& error) {
std::cout << "[" << error.GetResourceName() << "] " << error.GetError() << std::endl;
}
}
} catch(std::exception& error) {
std::cout << "Parsing of " << filename << " failed : " << error.what() << std::endl;
}
return renderObjects;
}
std::shared_ptr<Texture> ResourceLoader::LoadTexture(std::string filename, bool genMipMaps) {
FIBITMAP *img;
filename = "./Textures/" + filename + ".tga";
FREE_IMAGE_FORMAT format = FreeImage_GetFIFFromFilename(filename.c_str());
if(!FreeImage_FIFSupportsReading(format)) {
throw bad_resource("FreeImage can't read from file", filename);
}
if(format == FIF_UNKNOWN) {
throw bad_resource("Unknown format", filename);
}
img = FreeImage_Load(format, filename.c_str());
if(!img) {
throw bad_resource("Couldn't load image data", filename);
}
if(FreeImage_GetBPP(img) != 32) {
FIBITMAP* oldImg = img;
img = FreeImage_ConvertTo32Bits(oldImg);
FreeImage_Unload(oldImg);
}
int height, width;
width = FreeImage_GetWidth(img);
height = FreeImage_GetHeight(img);
unsigned char* bytes = FreeImage_GetBits(img);
if(bytes == nullptr) {
FreeImage_Unload(img);
throw bad_resource("couldn't load image bytes", filename);
}
GLuint glTexture;
glBindTexture(GL_TEXTURE_2D, 0);
glGenTextures(1, &glTexture);
glBindTexture(GL_TEXTURE_2D, glTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_BGRA, GL_UNSIGNED_BYTE, bytes);
if(genMipMaps) {
glGenerateMipmap(GL_TEXTURE_2D);
}
glBindTexture(GL_TEXTURE_2D, 0);
if(!glIsTexture(glTexture)) {
FreeImage_Unload(img);
throw bad_resource("texture is not valid", filename);
}
FreeImage_Unload(img);
std::shared_ptr<Texture> texture = std::make_shared<Texture>();
texture->SetFileName(filename);
texture->SetTexture(glTexture);
return texture;
}
void CopyaiMat(const aiMatrix4x4* from, glm::mat4& to) {
to[0][0] = from->a1; to[1][0] = from->a2;
to[2][0] = from->a3; to[3][0] = from->a4;
to[0][1] = from->b1; to[1][1] = from->b2;
to[2][1] = from->b3; to[3][1] = from->b4;
to[0][2] = from->c1; to[1][2] = from->c2;
to[2][2] = from->c3; to[3][2] = from->c4;
to[0][3] = from->d1; to[1][3] = from->d2;
to[2][3] = from->d3; to[3][3] = from->d4;
}
void LoadNode(const aiScene* scene, const aiNode* node, std::vector<std::shared_ptr<Model3D::Mesh>>& meshes) {
for(uint i = 0; i < node->mNumChildren; i++) {
LoadNode(scene, node->mChildren[i], meshes);
}
for(uint i = 0; i < node->mNumMeshes; i++) {
aiMesh* mesh = scene->mMeshes[node->mMeshes[i]];
std::vector<Model3D::Vertex> vertices;
for(uint j = 0; j < mesh->mNumVertices; j++) {
Model3D::Vertex vertex;
vertex.position = glm::vec3(mesh->mVertices[j].x, mesh->mVertices[j].y, mesh->mVertices[j].z);
vertex.normal = (mesh->HasNormals())
? glm::vec3(mesh->mNormals[j].x, mesh->mNormals[j].y, mesh->mNormals[j].z)
: glm::vec3(0.0f, 0.0f, 0.0f);
vertex.texCoord = (mesh->HasTextureCoords(0))
? glm::vec2(mesh->mTextureCoords[0][j].x, mesh->mTextureCoords[0][j].y)
: glm::vec2(0.0f, 0.0f);
vertices.push_back(vertex);
}
std::vector<uint> indices;
if(mesh->HasFaces()) {
for(uint j = 0; j < mesh->mNumFaces; j++) {
aiFace face = mesh->mFaces[j];
for(uint k = 0; k < face.mNumIndices; k++) {
indices.push_back(face.mIndices[k]);
}
}
} else {
throw bad_resource("Node was missing faces, load cancled");
}
glm::mat4x4 transformation;
CopyaiMat(&node->mTransformation, transformation);
std::shared_ptr<Model3D::Mesh> rmesh = std::make_shared<Model3D::Mesh>(vertices, indices);
rmesh->SetTransformation(transformation);
rmesh->SetMatIndex(mesh->mMaterialIndex);
meshes.push_back(rmesh);
}
}
std::shared_ptr<Model3D> ResourceLoader::LoadModel3D(std::string modelname) {
std::string filename = "Models/" + modelname + ".3ds";
Assimp::Importer importer;
const aiScene* scene = importer.ReadFile(filename.c_str(),
aiProcess_CalcTangentSpace |
aiProcess_Triangulate |
aiProcess_JoinIdenticalVertices |
aiProcess_SortByPType);
if(!scene || !scene->mRootNode || scene->mFlags == AI_SCENE_FLAGS_INCOMPLETE) {
throw bad_resource(importer.GetErrorString(), filename);
}
auto model = std::make_shared<Model3D>();
aiMaterial** materials = scene->mMaterials;
std::unordered_map<std::string, std::shared_ptr<Texture>> textures;
for(uint i = 0; i < scene->mNumMaterials; i++) {
aiString aName;
materials[i]->Get(AI_MATKEY_NAME, aName);
std::string name = std::string(aName.C_Str());
if(textures.find(name) == textures.end()) {
try {
std::shared_ptr<Texture> temp = LoadTexture(modelname + "/" + name, true);
if(temp != nullptr) {
textures[name] = temp;
}
} catch (bad_resource& error) {
std::cout << "[" << error.GetResourceName() << "] " << error.GetError() << std::endl;
}
}
}
model->SetTextures(textures);
std::vector<std::shared_ptr<Model3D::Mesh>> meshes;
LoadNode(scene, scene->mRootNode, meshes);
for(std::shared_ptr<Model3D::Mesh>& mesh : meshes) {
aiString aName;
uint index = mesh->GetMatIndex();
if(index < scene->mNumMaterials) {
materials[mesh->GetMatIndex()]->Get(AI_MATKEY_NAME, aName);
mesh->SetMatName(std::string(aName.C_Str()));
}
}
model->SetMeshes(meshes);
return model;
}
<|endoftext|>
|
<commit_before>// Copyright 2018 The clvk authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "memory.hpp"
#include "queue.hpp"
cvk_executor_thread_pool gThreadPool;
cvk_command_queue* cvk_event::queue() const
{
CVK_ASSERT(!is_user_event());
return m_command->queue();
}
cl_command_type cvk_event::command_type() const
{
CVK_ASSERT(!is_user_event());
return m_command->type();
}
_cl_command_queue::_cl_command_queue(cvk_context *ctx, cvk_device *device,
cl_command_queue_properties properties) :
api_object(ctx),
m_device(device),
m_properties(properties),
m_executor(nullptr),
m_command_pool(VK_NULL_HANDLE)
{
m_groups.push_back(new cvk_command_group());
if (properties & CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE) {
cvk_warn_fn("out-of-order execution enabled, will be ignored");
}
m_vulkan_queue = device->vulkan_queue_allocate();
m_vulkan_queue_family = device->vulkan_queue_family();
}
cl_int cvk_command_queue::init() {
// Create command pool
VkCommandPoolCreateInfo createInfo = {
VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
nullptr,
0, // flags
m_vulkan_queue_family
};
VkResult res = vkCreateCommandPool(m_device->vulkan_device(), &createInfo, nullptr, &m_command_pool);
if (res != VK_SUCCESS) {
return CL_OUT_OF_RESOURCES;
}
return CL_SUCCESS;
}
_cl_command_queue::~_cl_command_queue() {
if (m_executor != nullptr) {
gThreadPool.return_executor(m_executor);
}
if (m_command_pool != VK_NULL_HANDLE) {
vkDestroyCommandPool(m_device->vulkan_device(), m_command_pool, nullptr);
}
}
void cvk_command_queue::enqueue_command(cvk_command *cmd, cvk_event **event) {
std::lock_guard<std::mutex> lock(m_lock);
m_groups.back()->commands.push_back(cmd);
cmd->event()->retain();
cvk_debug_fn("enqueued command %p, event %p", cmd, cmd->event());
cmd->event()->set_profiling_info_from_monotonic_clock(CL_PROFILING_COMMAND_QUEUED);
if (event != nullptr) {
*event = cmd->event();
cvk_debug_fn("returning event %p", *event);
}
}
void cvk_command_queue::enqueue_command_with_deps(cvk_command *cmd, cl_uint num_dep_events,
cvk_event *const* dep_events, cvk_event **event) {
cmd->set_dependencies(num_dep_events, dep_events);
enqueue_command(cmd, event);
}
void cvk_executor_thread::executor() {
std::unique_lock<std::mutex> lock(m_lock);
while (!m_shutdown) {
if (m_groups.size() == 0) {
m_cv.wait(lock);
}
if (m_shutdown) {
continue;
}
auto group = m_groups.front();
m_groups.pop_front();
cvk_debug_fn("received group %p", group);
lock.unlock();
while (group->commands.size() > 0) {
cvk_command *cmd = group->commands.front();
cvk_debug_fn("executing command %p, event %p", cmd, cmd->event());
if (m_profiling) {
cmd->event()->set_profiling_info_from_monotonic_clock(CL_PROFILING_COMMAND_START);
}
cl_int status = cmd->execute();
cvk_debug_fn("command returned %d", status);
if (m_profiling) {
cmd->event()->set_profiling_info_from_monotonic_clock(CL_PROFILING_COMMAND_END);
}
cmd->event()->set_status(status);
group->commands.pop_front();
delete cmd;
}
lock.lock();
delete group;
}
}
cl_int cvk_command_queue::flush(cvk_event** event) {
cvk_info_fn("queue = %p, event = %p", this, event);
// Get command group to the executor's queue
cvk_command_group *group;
{
std::lock_guard<std::mutex> lock(m_lock);
group = m_groups.front();
if (group->commands.size() == 0) {
return CL_SUCCESS;
}
m_groups.pop_front();
m_groups.push_back(new cvk_command_group());
}
cvk_debug_fn("groups.size() = %zu", m_groups.size());
CVK_ASSERT(group->commands.size() > 0);
// Set event state and profiling info
for (auto cmd : group->commands) {
cmd->event()->set_status(CL_SUBMITTED);
if (has_property(CL_QUEUE_PROFILING_ENABLE)) {
cmd->event()->set_profiling_info_from_monotonic_clock(CL_PROFILING_COMMAND_SUBMIT);
}
}
// Create execution thread if it doesn't exist
{
std::lock_guard<std::mutex> lock(m_lock);
if (m_executor == nullptr) {
m_executor = gThreadPool.get_executor(this);
}
}
if (event != nullptr) {
*event = group->commands.back()->event();
cvk_debug_fn("returned event %p", *event);
}
// Submit command group to executor
m_executor->send_group(group);
return CL_SUCCESS;
}
bool cvk_command_queue::allocate_command_buffer(VkCommandBuffer *buf) {
std::lock_guard<std::mutex> lock(m_lock);
VkCommandBufferAllocateInfo commandBufferAllocateInfo = {
VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
0,
m_command_pool,
VK_COMMAND_BUFFER_LEVEL_PRIMARY,
1 // commandBufferCount
};
VkResult res = vkAllocateCommandBuffers(m_device->vulkan_device(), &commandBufferAllocateInfo, buf);
if (res != VK_SUCCESS) {
return false;
}
return true;
}
void cvk_command_queue::free_command_buffer(VkCommandBuffer buf) {
vkFreeCommandBuffers(m_device->vulkan_device(), m_command_pool, 1, &buf);
}
cl_int cvk_command_kernel::build() {
auto vklimits = m_queue->device()->vulkan_limits();
// Check we have a valid dispatch size
for (cl_uint i = 0; i < 3; ++i) {
if (m_num_wg[i] > vklimits.maxComputeWorkGroupCount[i]) {
cvk_error_fn("global work size exceeds device limits");
// There is no suitable error code to report this
// use something
return CL_INVALID_WORK_ITEM_SIZE;
}
}
if (m_wg_size[0] * m_wg_size[1] * m_wg_size[2] > vklimits.maxComputeWorkGroupInvocations) {
return CL_INVALID_WORK_GROUP_SIZE;
}
for (int i = 0; i < 3; i++) {
if (m_wg_size[i] > vklimits.maxComputeWorkGroupSize[i]) {
return CL_INVALID_WORK_ITEM_SIZE;
}
}
// TODO check against the size specified at compile time, if any
// Setup descriptors
if (!m_kernel->setup_descriptor_set(&m_descriptor_set, m_pod_buffer)) {
return CL_OUT_OF_RESOURCES;
}
// Create and populate the command buffer
if (!m_queue->allocate_command_buffer(&m_command_buffer)) {
return CL_OUT_OF_RESOURCES;
}
VkCommandBufferBeginInfo beginInfo = {
VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
nullptr,
VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
nullptr // pInheritanceInfo
};
VkResult res = vkBeginCommandBuffer(m_command_buffer, &beginInfo);
if (res != VK_SUCCESS) {
return CL_OUT_OF_RESOURCES;
}
VkPipeline pipeline = m_kernel->get_pipeline(
m_wg_size[0],
m_wg_size[1],
m_wg_size[2]
);
if (pipeline == VK_NULL_HANDLE) {
return CL_OUT_OF_RESOURCES;
}
vkCmdBindPipeline(m_command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline);
vkCmdBindDescriptorSets(m_command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE,
m_kernel->pipeline_layout(), 0, 1, &m_descriptor_set, 0, 0);
vkCmdDispatch(m_command_buffer, m_num_wg[0], m_num_wg[1], m_num_wg[2]);
res = vkEndCommandBuffer(m_command_buffer);
if (res != VK_SUCCESS) {
return CL_OUT_OF_RESOURCES;
}
return CL_SUCCESS;
}
cl_int cvk_command_kernel::do_action()
{
VkSubmitInfo submitInfo = {
VK_STRUCTURE_TYPE_SUBMIT_INFO,
nullptr,
0, // waitSemaphoreCOunt
nullptr, // pWaitSemaphores
nullptr, // pWaitDstStageMask
1, // commandBufferCount
&m_command_buffer,
0, // signalSemaphoreCount
nullptr, // pSignalSemaphores
};
auto queue = m_queue->vulkan_queue();
VkResult res = vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE);
if (res != VK_SUCCESS) {
cvk_error_fn("could not submit work to queue");
return CL_OUT_OF_RESOURCES;
}
res = vkQueueWaitIdle(queue);
if (res != VK_SUCCESS) {
cvk_error_fn("could not wait for queue to become idle: %s", vulkan_error_string(res));
return CL_OUT_OF_RESOURCES;
}
m_queue->free_command_buffer(m_command_buffer);
return CL_COMPLETE;
}
cl_int cvk_command_copy::do_action()
{
bool success = false;
switch (m_type) {
case CL_COMMAND_WRITE_BUFFER:
success = m_mem->copy_from(m_ptr, m_offset, m_size);
break;
case CL_COMMAND_READ_BUFFER:
success = m_mem->copy_to(m_ptr, m_offset, m_size);
break;
default:
CVK_ASSERT(false);
break;
}
return success ? CL_COMPLETE : CL_OUT_OF_RESOURCES;
}
struct rectangle {
public:
void set_params(size_t *origin, size_t slicep, size_t rowp) {
m_origin[0] = origin[0];
m_origin[1] = origin[1];
m_origin[2] = origin[2];
m_slice_pitch = slicep;
m_row_pitch = rowp;
}
size_t get_row_offset(size_t slice, size_t row) {
return m_slice_pitch * (m_origin[2] + slice) + m_row_pitch * (m_origin[1] + row) + m_origin[0];
}
private:
size_t m_origin[3];
size_t m_slice_pitch;
size_t m_row_pitch;
};
struct memobj_map_holder {
memobj_map_holder(cvk_mem *memobj) : m_mem(memobj), m_mapped(false) {}
~memobj_map_holder() {
if (m_mapped) {
m_mem->unmap();
}
}
bool CHECK_RETURN map() {
m_mapped = m_mem->map();
return m_mapped;
}
private:
cvk_mem *m_mem;
bool m_mapped;
};
cl_int cvk_command_copy_rect::do_action()
{
uintptr_t dst_base, src_base;
rectangle rsrc, rdst;
memobj_map_holder map_holder{m_mem};
if (!map_holder.map()) {
return CL_OUT_OF_RESOURCES;
}
switch (m_type) {
case CL_COMMAND_READ_BUFFER_RECT:
dst_base = reinterpret_cast<uintptr_t>(m_ptr);
src_base = reinterpret_cast<uintptr_t>(m_mem->host_va());
rsrc.set_params(m_buffer_origin, m_buffer_slice_pitch, m_buffer_row_pitch);
rdst.set_params(m_host_origin, m_host_slice_pitch, m_host_row_pitch);
break;
case CL_COMMAND_WRITE_BUFFER_RECT:
dst_base = reinterpret_cast<uintptr_t>(m_mem->host_va());
src_base = reinterpret_cast<uintptr_t>(m_ptr);
rsrc.set_params(m_host_origin, m_host_slice_pitch, m_host_row_pitch);
rdst.set_params(m_buffer_origin, m_buffer_slice_pitch, m_buffer_row_pitch);
break;
default:
return CL_INVALID_OPERATION;
}
for (size_t slice = 0; slice < m_region[2]; slice++) {
cvk_debug_fn("slice = %zu", slice);
for (size_t row = 0; row < m_region[1]; row++) {
cvk_debug_fn("row = %zu", row);
uintptr_t dst = dst_base + rdst.get_row_offset(slice, row);
uintptr_t src = src_base + rsrc.get_row_offset(slice, row);
memcpy(reinterpret_cast<void*>(dst), reinterpret_cast<void*>(src), m_region[0]);
}
}
return CL_COMPLETE;
}
cl_int cvk_command_copy_buffer::do_action()
{
bool success = m_src_buffer->copy_to(m_dst_buffer, m_src_offset, m_dst_offset, m_size);
return success ? CL_COMPLETE : CL_OUT_OF_RESOURCES;
}
cl_int cvk_command_fill::do_action()
{
memobj_map_holder map_holder{m_mem};
if (!map_holder.map()) {
return CL_OUT_OF_RESOURCES;
}
uintptr_t begin = reinterpret_cast<uintptr_t>(m_mem->host_va()) + m_offset;
uintptr_t end = begin + m_size;
uintptr_t address = begin;
while (address < end) {
memcpy(reinterpret_cast<void*>(address), m_pattern.get(), m_pattern_size);
address += m_pattern_size;
}
return CL_COMPLETE;
}
cl_int cvk_command_map::do_action()
{
bool success = true;
if (m_mem->has_flags(CL_MEM_USE_HOST_PTR)) {
success = m_mem->copy_to(m_mem->host_ptr(), m_offset, m_size);
}
return success ? CL_COMPLETE : CL_OUT_OF_RESOURCES;
}
cl_int cvk_command_unmap::do_action()
{
m_mem->unmap();
return CL_COMPLETE;
}
<commit_msg>Fix event leak<commit_after>// Copyright 2018 The clvk authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "memory.hpp"
#include "queue.hpp"
cvk_executor_thread_pool gThreadPool;
cvk_command_queue* cvk_event::queue() const
{
CVK_ASSERT(!is_user_event());
return m_command->queue();
}
cl_command_type cvk_event::command_type() const
{
CVK_ASSERT(!is_user_event());
return m_command->type();
}
_cl_command_queue::_cl_command_queue(cvk_context *ctx, cvk_device *device,
cl_command_queue_properties properties) :
api_object(ctx),
m_device(device),
m_properties(properties),
m_executor(nullptr),
m_command_pool(VK_NULL_HANDLE)
{
m_groups.push_back(new cvk_command_group());
if (properties & CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE) {
cvk_warn_fn("out-of-order execution enabled, will be ignored");
}
m_vulkan_queue = device->vulkan_queue_allocate();
m_vulkan_queue_family = device->vulkan_queue_family();
}
cl_int cvk_command_queue::init() {
// Create command pool
VkCommandPoolCreateInfo createInfo = {
VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
nullptr,
0, // flags
m_vulkan_queue_family
};
VkResult res = vkCreateCommandPool(m_device->vulkan_device(), &createInfo, nullptr, &m_command_pool);
if (res != VK_SUCCESS) {
return CL_OUT_OF_RESOURCES;
}
return CL_SUCCESS;
}
_cl_command_queue::~_cl_command_queue() {
if (m_executor != nullptr) {
gThreadPool.return_executor(m_executor);
}
if (m_command_pool != VK_NULL_HANDLE) {
vkDestroyCommandPool(m_device->vulkan_device(), m_command_pool, nullptr);
}
}
void cvk_command_queue::enqueue_command(cvk_command *cmd, cvk_event **event) {
std::lock_guard<std::mutex> lock(m_lock);
m_groups.back()->commands.push_back(cmd);
cvk_debug_fn("enqueued command %p, event %p", cmd, cmd->event());
cmd->event()->set_profiling_info_from_monotonic_clock(CL_PROFILING_COMMAND_QUEUED);
if (event != nullptr) {
// The event will be returned to the app, retain it for the user
cmd->event()->retain();
*event = cmd->event();
cvk_debug_fn("returning event %p", *event);
}
}
void cvk_command_queue::enqueue_command_with_deps(cvk_command *cmd, cl_uint num_dep_events,
cvk_event *const* dep_events, cvk_event **event) {
cmd->set_dependencies(num_dep_events, dep_events);
enqueue_command(cmd, event);
}
void cvk_executor_thread::executor() {
std::unique_lock<std::mutex> lock(m_lock);
while (!m_shutdown) {
if (m_groups.size() == 0) {
m_cv.wait(lock);
}
if (m_shutdown) {
continue;
}
auto group = m_groups.front();
m_groups.pop_front();
cvk_debug_fn("received group %p", group);
lock.unlock();
while (group->commands.size() > 0) {
cvk_command *cmd = group->commands.front();
cvk_debug_fn("executing command %p, event %p", cmd, cmd->event());
if (m_profiling) {
cmd->event()->set_profiling_info_from_monotonic_clock(CL_PROFILING_COMMAND_START);
}
cl_int status = cmd->execute();
cvk_debug_fn("command returned %d", status);
if (m_profiling) {
cmd->event()->set_profiling_info_from_monotonic_clock(CL_PROFILING_COMMAND_END);
}
cmd->event()->set_status(status);
group->commands.pop_front();
delete cmd;
}
lock.lock();
delete group;
}
}
cl_int cvk_command_queue::flush(cvk_event** event) {
cvk_info_fn("queue = %p, event = %p", this, event);
// Get command group to the executor's queue
cvk_command_group *group;
{
std::lock_guard<std::mutex> lock(m_lock);
group = m_groups.front();
if (group->commands.size() == 0) {
return CL_SUCCESS;
}
m_groups.pop_front();
m_groups.push_back(new cvk_command_group());
}
cvk_debug_fn("groups.size() = %zu", m_groups.size());
CVK_ASSERT(group->commands.size() > 0);
// Set event state and profiling info
for (auto cmd : group->commands) {
cmd->event()->set_status(CL_SUBMITTED);
if (has_property(CL_QUEUE_PROFILING_ENABLE)) {
cmd->event()->set_profiling_info_from_monotonic_clock(CL_PROFILING_COMMAND_SUBMIT);
}
}
// Create execution thread if it doesn't exist
{
std::lock_guard<std::mutex> lock(m_lock);
if (m_executor == nullptr) {
m_executor = gThreadPool.get_executor(this);
}
}
if (event != nullptr) {
*event = group->commands.back()->event();
cvk_debug_fn("returned event %p", *event);
}
// Submit command group to executor
m_executor->send_group(group);
return CL_SUCCESS;
}
bool cvk_command_queue::allocate_command_buffer(VkCommandBuffer *buf) {
std::lock_guard<std::mutex> lock(m_lock);
VkCommandBufferAllocateInfo commandBufferAllocateInfo = {
VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
0,
m_command_pool,
VK_COMMAND_BUFFER_LEVEL_PRIMARY,
1 // commandBufferCount
};
VkResult res = vkAllocateCommandBuffers(m_device->vulkan_device(), &commandBufferAllocateInfo, buf);
if (res != VK_SUCCESS) {
return false;
}
return true;
}
void cvk_command_queue::free_command_buffer(VkCommandBuffer buf) {
vkFreeCommandBuffers(m_device->vulkan_device(), m_command_pool, 1, &buf);
}
cl_int cvk_command_kernel::build() {
auto vklimits = m_queue->device()->vulkan_limits();
// Check we have a valid dispatch size
for (cl_uint i = 0; i < 3; ++i) {
if (m_num_wg[i] > vklimits.maxComputeWorkGroupCount[i]) {
cvk_error_fn("global work size exceeds device limits");
// There is no suitable error code to report this
// use something
return CL_INVALID_WORK_ITEM_SIZE;
}
}
if (m_wg_size[0] * m_wg_size[1] * m_wg_size[2] > vklimits.maxComputeWorkGroupInvocations) {
return CL_INVALID_WORK_GROUP_SIZE;
}
for (int i = 0; i < 3; i++) {
if (m_wg_size[i] > vklimits.maxComputeWorkGroupSize[i]) {
return CL_INVALID_WORK_ITEM_SIZE;
}
}
// TODO check against the size specified at compile time, if any
// Setup descriptors
if (!m_kernel->setup_descriptor_set(&m_descriptor_set, m_pod_buffer)) {
return CL_OUT_OF_RESOURCES;
}
// Create and populate the command buffer
if (!m_queue->allocate_command_buffer(&m_command_buffer)) {
return CL_OUT_OF_RESOURCES;
}
VkCommandBufferBeginInfo beginInfo = {
VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
nullptr,
VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
nullptr // pInheritanceInfo
};
VkResult res = vkBeginCommandBuffer(m_command_buffer, &beginInfo);
if (res != VK_SUCCESS) {
return CL_OUT_OF_RESOURCES;
}
VkPipeline pipeline = m_kernel->get_pipeline(
m_wg_size[0],
m_wg_size[1],
m_wg_size[2]
);
if (pipeline == VK_NULL_HANDLE) {
return CL_OUT_OF_RESOURCES;
}
vkCmdBindPipeline(m_command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline);
vkCmdBindDescriptorSets(m_command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE,
m_kernel->pipeline_layout(), 0, 1, &m_descriptor_set, 0, 0);
vkCmdDispatch(m_command_buffer, m_num_wg[0], m_num_wg[1], m_num_wg[2]);
res = vkEndCommandBuffer(m_command_buffer);
if (res != VK_SUCCESS) {
return CL_OUT_OF_RESOURCES;
}
return CL_SUCCESS;
}
cl_int cvk_command_kernel::do_action()
{
VkSubmitInfo submitInfo = {
VK_STRUCTURE_TYPE_SUBMIT_INFO,
nullptr,
0, // waitSemaphoreCOunt
nullptr, // pWaitSemaphores
nullptr, // pWaitDstStageMask
1, // commandBufferCount
&m_command_buffer,
0, // signalSemaphoreCount
nullptr, // pSignalSemaphores
};
auto queue = m_queue->vulkan_queue();
VkResult res = vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE);
if (res != VK_SUCCESS) {
cvk_error_fn("could not submit work to queue");
return CL_OUT_OF_RESOURCES;
}
res = vkQueueWaitIdle(queue);
if (res != VK_SUCCESS) {
cvk_error_fn("could not wait for queue to become idle: %s", vulkan_error_string(res));
return CL_OUT_OF_RESOURCES;
}
m_queue->free_command_buffer(m_command_buffer);
return CL_COMPLETE;
}
cl_int cvk_command_copy::do_action()
{
bool success = false;
switch (m_type) {
case CL_COMMAND_WRITE_BUFFER:
success = m_mem->copy_from(m_ptr, m_offset, m_size);
break;
case CL_COMMAND_READ_BUFFER:
success = m_mem->copy_to(m_ptr, m_offset, m_size);
break;
default:
CVK_ASSERT(false);
break;
}
return success ? CL_COMPLETE : CL_OUT_OF_RESOURCES;
}
struct rectangle {
public:
void set_params(size_t *origin, size_t slicep, size_t rowp) {
m_origin[0] = origin[0];
m_origin[1] = origin[1];
m_origin[2] = origin[2];
m_slice_pitch = slicep;
m_row_pitch = rowp;
}
size_t get_row_offset(size_t slice, size_t row) {
return m_slice_pitch * (m_origin[2] + slice) + m_row_pitch * (m_origin[1] + row) + m_origin[0];
}
private:
size_t m_origin[3];
size_t m_slice_pitch;
size_t m_row_pitch;
};
struct memobj_map_holder {
memobj_map_holder(cvk_mem *memobj) : m_mem(memobj), m_mapped(false) {}
~memobj_map_holder() {
if (m_mapped) {
m_mem->unmap();
}
}
bool CHECK_RETURN map() {
m_mapped = m_mem->map();
return m_mapped;
}
private:
cvk_mem *m_mem;
bool m_mapped;
};
cl_int cvk_command_copy_rect::do_action()
{
uintptr_t dst_base, src_base;
rectangle rsrc, rdst;
memobj_map_holder map_holder{m_mem};
if (!map_holder.map()) {
return CL_OUT_OF_RESOURCES;
}
switch (m_type) {
case CL_COMMAND_READ_BUFFER_RECT:
dst_base = reinterpret_cast<uintptr_t>(m_ptr);
src_base = reinterpret_cast<uintptr_t>(m_mem->host_va());
rsrc.set_params(m_buffer_origin, m_buffer_slice_pitch, m_buffer_row_pitch);
rdst.set_params(m_host_origin, m_host_slice_pitch, m_host_row_pitch);
break;
case CL_COMMAND_WRITE_BUFFER_RECT:
dst_base = reinterpret_cast<uintptr_t>(m_mem->host_va());
src_base = reinterpret_cast<uintptr_t>(m_ptr);
rsrc.set_params(m_host_origin, m_host_slice_pitch, m_host_row_pitch);
rdst.set_params(m_buffer_origin, m_buffer_slice_pitch, m_buffer_row_pitch);
break;
default:
return CL_INVALID_OPERATION;
}
for (size_t slice = 0; slice < m_region[2]; slice++) {
cvk_debug_fn("slice = %zu", slice);
for (size_t row = 0; row < m_region[1]; row++) {
cvk_debug_fn("row = %zu", row);
uintptr_t dst = dst_base + rdst.get_row_offset(slice, row);
uintptr_t src = src_base + rsrc.get_row_offset(slice, row);
memcpy(reinterpret_cast<void*>(dst), reinterpret_cast<void*>(src), m_region[0]);
}
}
return CL_COMPLETE;
}
cl_int cvk_command_copy_buffer::do_action()
{
bool success = m_src_buffer->copy_to(m_dst_buffer, m_src_offset, m_dst_offset, m_size);
return success ? CL_COMPLETE : CL_OUT_OF_RESOURCES;
}
cl_int cvk_command_fill::do_action()
{
memobj_map_holder map_holder{m_mem};
if (!map_holder.map()) {
return CL_OUT_OF_RESOURCES;
}
uintptr_t begin = reinterpret_cast<uintptr_t>(m_mem->host_va()) + m_offset;
uintptr_t end = begin + m_size;
uintptr_t address = begin;
while (address < end) {
memcpy(reinterpret_cast<void*>(address), m_pattern.get(), m_pattern_size);
address += m_pattern_size;
}
return CL_COMPLETE;
}
cl_int cvk_command_map::do_action()
{
bool success = true;
if (m_mem->has_flags(CL_MEM_USE_HOST_PTR)) {
success = m_mem->copy_to(m_mem->host_ptr(), m_offset, m_size);
}
return success ? CL_COMPLETE : CL_OUT_OF_RESOURCES;
}
cl_int cvk_command_unmap::do_action()
{
m_mem->unmap();
return CL_COMPLETE;
}
<|endoftext|>
|
<commit_before>#include <cstdio>
#include <utility>
#include "reader.hh"
#include "lisp_ptr.hh"
#include "token.hh"
#include "number.hh"
#include "cons.hh"
#include "symbol.hh"
using namespace std;
namespace {
Lisp_ptr read_la(FILE*, Token&&);
Lisp_ptr read_list(FILE* f){
Token t = tokenize(f);
// first check
if(!t){
return Lisp_ptr{};
}else if(t.type() == Token::Type::notation){
auto n = t.get<Token::Notation>();
if(n == Token::Notation::r_paren){ // empty list
return Cons::NIL;
}else if(n == Token::Notation::dot){ // error: dotted list has no car.
return {};
}
}
// main loop
Cons* c = new Cons();
const Lisp_ptr head{c};
while(1){
Lisp_ptr datum{read_la(f, move(t))};
if(!datum){
return Lisp_ptr{};
}
c->rplaca(datum);
// check next token
t = tokenize(f);
if(!t){
// TODO: free cons's contents (here or in free_cons_list())
free_cons_list(head);
return Lisp_ptr{};
}else if(t.type() == Token::Type::notation){
auto n = t.get<Token::Notation>();
if(n == Token::Notation::r_paren){ // proper list
c->rplacd(Cons::NIL);
goto end;
}else if(n == Token::Notation::dot){ // dotted list
c->rplacd(read(f));
t = tokenize(f);
if(t.type() != Token::Type::notation
|| t.get<Token::Notation>() != Token::Notation::r_paren){
return Lisp_ptr{}; // error: dotted list has two or more cdrs.
}
goto end;
}
}
// readying next cons
Cons* new_c = new Cons();
c->rplacd(Lisp_ptr{new_c});
c = new_c;
}
end:
// if(c->cdr() == undef) ...
return head;
}
Lisp_ptr read_vector(FILE* f){
Vector* v = new Vector();
while(1){
auto t = tokenize(f);
if(!t){
// TODO: free vector's contents
delete v;
return Lisp_ptr{};
}else if((t.type() == Token::Type::notation)
&& (t.get<Token::Notation>()
== Token::Notation::r_paren)){
goto end;
}else{
Lisp_ptr datum{read_la(f, move(t))};
if(!datum){
return Lisp_ptr{};
}
v->emplace_back(datum);
}
}
end:
return Lisp_ptr{v};
}
Lisp_ptr read_abbrev(const char* name, FILE* f){
Lisp_ptr first{intern(VM.symtable, name)};
Lisp_ptr second{read(f)};
return Lisp_ptr{new Cons{first, Lisp_ptr{new Cons{second, Cons::NIL}}}};
}
Lisp_ptr read_la(FILE* f, Token&& tok){
switch(tok.type()){
// simple datum
case Token::Type::boolean:
return Lisp_ptr(tok.move<bool>());
case Token::Type::number:
return Lisp_ptr(new Number(tok.move<Number>()));
case Token::Type::character:
return Lisp_ptr(tok.move<char>());
case Token::Type::string:
return Lisp_ptr(new String(tok.move<string>()));
case Token::Type::identifier:
return Lisp_ptr{intern(VM.symtable, tok.move<string>())};
// compound datum
case Token::Type::notation:
switch(auto n = tok.move<Token::Notation>()){
case Token::Notation::l_paren: // list
return read_list(f);
case Token::Notation::vector_paren: // vector
return read_vector(f);
// abbrev prefix
case Token::Notation::quote:
return read_abbrev("quote", f);
case Token::Notation::quasiquote:
return read_abbrev("quasiquote", f);
case Token::Notation::comma:
return read_abbrev("unquote", f);
case Token::Notation::comma_at:
return read_abbrev("unquote-splicing", f);
case Token::Notation::l_bracket:
case Token::Notation::l_brace:
fprintf(stderr, "reader error: not supported notation! (type=%s)\n",
stringify(n));
return Lisp_ptr{};
case Token::Notation::r_paren:
case Token::Notation::r_bracket:
case Token::Notation::r_brace:
fprintf(stderr, "reader error: closing notation appeared alone! (type=%s)\n",
stringify(n));
return Lisp_ptr{};
case Token::Notation::dot:
case Token::Notation::bar:
default:
fprintf(stderr, "reader error: unexpected notation was passed! (type=%s)\n",
stringify(n));
return Lisp_ptr{};
}
case Token::Type::uninitialized:
default:
fprintf(stderr, "reader error: unknown token was passed! (type=%s)\n",
stringify(tok.type()));
return Lisp_ptr{};
}
}
} // namespace
Lisp_ptr read(FILE* f){
return read_la(f, tokenize(f));
}
<commit_msg>bitly cleanup in reader<commit_after>#include <cstdio>
#include <utility>
#include "reader.hh"
#include "lisp_ptr.hh"
#include "token.hh"
#include "number.hh"
#include "cons.hh"
#include "symbol.hh"
using namespace std;
namespace {
Lisp_ptr read_la(FILE*, Token&&);
Lisp_ptr read_list(FILE* f){
Token t = tokenize(f);
// first check
if(!t){
return Lisp_ptr{};
}else if(t.type() == Token::Type::notation){
auto n = t.get<Token::Notation>();
if(n == Token::Notation::r_paren){ // empty list
return Cons::NIL;
}else if(n == Token::Notation::dot){ // error: dotted list has no car.
return {};
}
}
// main loop
Cons* c = new Cons();
const Lisp_ptr head{c};
while(1){
Lisp_ptr datum{read_la(f, move(t))};
if(!datum){
return Lisp_ptr{};
}
c->rplaca(datum);
// check next token
t = tokenize(f);
if(!t){
// TODO: free cons's contents (here or in free_cons_list())
free_cons_list(head);
return Lisp_ptr{};
}else if(t.type() == Token::Type::notation){
auto n = t.get<Token::Notation>();
if(n == Token::Notation::r_paren){ // proper list
c->rplacd(Cons::NIL);
goto end;
}else if(n == Token::Notation::dot){ // dotted list
c->rplacd(read(f));
t = tokenize(f);
if(t.type() != Token::Type::notation
|| t.get<Token::Notation>() != Token::Notation::r_paren){
return Lisp_ptr{}; // error: dotted list has two or more cdrs.
}
goto end;
}
}
// readying next cons
Cons* new_c = new Cons();
c->rplacd(Lisp_ptr{new_c});
c = new_c;
}
end:
// if(c->cdr() == undef) ...
return head;
}
Lisp_ptr read_vector(FILE* f){
Vector* v = new Vector();
while(1){
auto t = tokenize(f);
if(!t){
// TODO: free vector's contents
delete v;
return Lisp_ptr{};
}else if((t.type() == Token::Type::notation)
&& (t.get<Token::Notation>()
== Token::Notation::r_paren)){
return Lisp_ptr{v};
}else{
Lisp_ptr datum{read_la(f, move(t))};
if(!datum){
return Lisp_ptr{};
}
v->emplace_back(datum);
}
}
}
Lisp_ptr read_abbrev(const char* name, FILE* f){
Lisp_ptr first{intern(VM.symtable, name)};
Lisp_ptr second{read(f)};
return Lisp_ptr{new Cons{first, Lisp_ptr{new Cons{second, Cons::NIL}}}};
}
Lisp_ptr read_la(FILE* f, Token&& tok){
switch(tok.type()){
// simple datum
case Token::Type::boolean:
return Lisp_ptr(tok.move<bool>());
case Token::Type::number:
return Lisp_ptr(new Number(tok.move<Number>()));
case Token::Type::character:
return Lisp_ptr(tok.move<char>());
case Token::Type::string:
return Lisp_ptr(new String(tok.move<string>()));
case Token::Type::identifier:
return Lisp_ptr{intern(VM.symtable, tok.move<string>())};
// compound datum
case Token::Type::notation:
switch(auto n = tok.move<Token::Notation>()){
case Token::Notation::l_paren: // list
return read_list(f);
case Token::Notation::vector_paren: // vector
return read_vector(f);
// abbrev prefix
case Token::Notation::quote:
return read_abbrev("quote", f);
case Token::Notation::quasiquote:
return read_abbrev("quasiquote", f);
case Token::Notation::comma:
return read_abbrev("unquote", f);
case Token::Notation::comma_at:
return read_abbrev("unquote-splicing", f);
case Token::Notation::l_bracket:
case Token::Notation::l_brace:
fprintf(stderr, "reader error: not supported notation! (type=%s)\n",
stringify(n));
return Lisp_ptr{};
case Token::Notation::r_paren:
case Token::Notation::r_bracket:
case Token::Notation::r_brace:
fprintf(stderr, "reader error: closing notation appeared alone! (type=%s)\n",
stringify(n));
return Lisp_ptr{};
case Token::Notation::dot:
case Token::Notation::bar:
default:
fprintf(stderr, "reader error: unexpected notation was passed! (type=%s)\n",
stringify(n));
return Lisp_ptr{};
}
case Token::Type::uninitialized:
default:
fprintf(stderr, "reader error: unknown token was passed! (type=%s)\n",
stringify(tok.type()));
return Lisp_ptr{};
}
}
} // namespace
Lisp_ptr read(FILE* f){
return read_la(f, tokenize(f));
}
<|endoftext|>
|
<commit_before>// Copyright (C) 2009, 2010 by Florent Lamiraux, Thomas Moulard, JRL.
//
// This file is part of the hpp-corbaserver.
//
// This software is provided "as is" without warranty of any kind,
// either expressed or implied, including but not limited to the
// implied warranties of fitness for a particular purpose.
//
// See the COPYING file for more information.
#include "hpp/corbaserver/server.hh"
#include <errno.h>
#include <pthread.h>
#include <iostream>
#include <dlfcn.h>
#include <hpp/util/debug.hh>
#include <hpp/core/plugin.hh>
#include <hpp/corbaserver/server-plugin.hh>
#include "hpp/corbaserver/tools-idl.hh"
#include "basic-server.hh"
#include "hpp/corbaserver/servant-base.hh"
namespace hpp
{
namespace corbaServer
{
using CORBA::Exception;
using CORBA::Object_var;
using CORBA::SystemException;
using CORBA::ORB_init;
using CORBA::PolicyList;
using omniORB::fatalException;
namespace
{
/// \brief Forward logging messages to hpp logging mechanism.
/// If debug is disabled, CORBA logging will be disabled too.
///
/// Tracing has to be enabled in your ``omniORB.cfg'' to use this
/// feature.
/// See ``omniORB configuration and API'' > ``Tracing options''
/// section of omniORB manual for more information.
void logFunction (const char* msg);
void logFunction (const char* hppDebugStatement (msg))
{
hppDout (info, "omniORB: " << msg);
}
void usage (const char* app)
{
std::cerr << "Usage: " << app << " [options] ..." << '\n'
<< " --name <name>" << '\n'
<< " --help" << '\n'
<< " --single-thread" << '\n'
<< " --multi-thread" << std::endl;
}
} // end of anonymous namespace.
class Tools : public virtual POA_hpp::Tools
{
public:
Tools () : server_ (NULL) {};
void setServer (Server* server)
{
server_ = server;
}
virtual CORBA::Boolean loadServerPlugin (const char* context, const char* pluginName) throw (Error)
{
try {
std::string c (context), pn (pluginName);
return server_->loadPlugin (c, pn);
} catch (const std::exception& e) {
throw hpp::Error (e.what ());
}
}
virtual CORBA::Boolean createContext (const char* context) throw (Error)
{
try {
std::string c (context);
return server_->createContext (c);
} catch (const std::exception& e) {
throw hpp::Error (e.what ());
}
}
virtual void deleteServant (const char* id) throw (Error)
{
try {
CORBA::Object_ptr obj = server_->orb()->string_to_object (id);
PortableServer::ObjectId_var objectId = server_->poa()->reference_to_id (obj);
// Remove reference in servant object map
ServantBase_var servant = server_->poa()->id_to_servant(objectId.in());
server_->removeServant (servant.in());
// Deactivate object
server_->poa()->deactivate_object(objectId.in());
} catch (const std::exception& e) {
throw hpp::Error (e.what ());
}
}
virtual void shutdown ()
{
server_->requestShutdown(false);
}
private:
Server* server_;
};
Server::Server(core::ProblemSolverPtr_t problemSolver, int argc,
const char *argv[], bool inMultiThread) :
multiThread_ (inMultiThread),
problemSolverMap_ (new ProblemSolverMap (problemSolver))
{
// Register log function.
omniORB::setLogFunction (&logFunction);
parseArguments (argc, argv);
initORBandServers (argc, argv, multiThread_);
}
Server::Server(ProblemSolverMapPtr_t problemSolverMap, int argc,
const char *argv[], bool inMultiThread) :
multiThread_ (inMultiThread),
problemSolverMap_ (problemSolverMap)
{
// Register log function.
omniORB::setLogFunction (&logFunction);
parseArguments (argc, argv);
initORBandServers (argc, argv, multiThread_);
}
/// \brief Shutdown CORBA server
Server::~Server()
{
}
/// CORBA SERVER INITIALIZATION
void Server::initORBandServers(int argc, const char* argv[],
bool inMultiThread)
{
Object_var obj;
PortableServer::ThreadPolicy_var threadPolicy;
PortableServer::POA_var rootPoa;
/// ORB init
orb_ = ORB_init (argc, const_cast<char **> (argv));
if (is_nil(orb_)) {
std::string msg ("failed to initialize ORB");
hppDout (error, msg.c_str ());
throw std::runtime_error (msg.c_str ());
}
/// ORB init
obj = orb_->resolve_initial_references("RootPOA");
/// Create thread policy
//
// Make the CORBA object single-threaded to avoid GUI krash
//
// Create a sigle threaded policy object
rootPoa = PortableServer::POA::_narrow(obj);
if (inMultiThread) {
threadPolicy = rootPoa->create_thread_policy
(PortableServer::ORB_CTRL_MODEL);
}
else {
threadPolicy = rootPoa->create_thread_policy
(PortableServer::MAIN_THREAD_MODEL);
}
/// Duplicate thread policy
PolicyList policyList;
policyList.length(1);
policyList[0] = PortableServer::ThreadPolicy::_duplicate(threadPolicy);
try {
poa_ = rootPoa->create_POA
("child", PortableServer::POAManager::_nil(), policyList);
} catch (PortableServer::POA::AdapterAlreadyExists& /*e*/) {
poa_ = rootPoa->find_POA ("child", false);
}
// Destroy policy object
threadPolicy->destroy();
}
void Server::parseArguments (int argc, const char* argv[])
{
mainContextId_ = "corbaserver";
for (int i = 1; i < argc; ++i) {
if (strcmp(argv[i], "--name") == 0) {
if (i < argc - 1) {
mainContextId_ = argv[i+1];
++i;
}
else usage(argv[0]);
std::cout << "Server main context: " << mainContextId_ << std::endl;
} else if (strcmp(argv[i], "--help") == 0) {
usage(argv[0]);
} else if (strcmp(argv[i], "--single-thread") == 0) {
multiThread_ = false;
std::cout << "Switched to single thread mode." << std::endl;
} else if (strcmp(argv[i], "--multi-thread") == 0) {
std::cout << "Switched to multi-thread mode." << std::endl;
multiThread_ = true;
}
}
}
void Server::startCorbaServer()
{
// Create Server interface
tools_ = new Tools ();
tools_->setServer (this);
/*servantId_ = */ poa_->activate_object(tools_);
CosNaming::NamingContext_var rootContext;
Object_var localObj;
CosNaming::Name contextName;
try {
// Obtain a reference to the root context of the Name service:
localObj = orb_->resolve_initial_references("NameService");
} catch(const CORBA::Exception& e) {
hppCorbaDout (error, "CORBA::Exception " << e._name() << ":"
<< e._rep_id() << " : failed to get the name service");
return;
}
try {
// Narrow the reference returned.
rootContext = CosNaming::NamingContext::_narrow(localObj);
if( is_nil(rootContext) ) {
hppCorbaDout (error, "Failed to narrow the root naming context.");
return;
}
}
catch(CORBA::ORB::InvalidName& ex) {
// This should not happen!
hppCorbaDout (error, "Service required is invalid [does not exist].");
return;
} catch(const CORBA::Exception& e) {
hppCorbaDout (error, "CORBA::Exception " << e._name() << ":"
<< e._rep_id() << " : failed to narrow the root naming context");
return;
}
try {
// Bind a context called "hpp" to the root context:
localObj = tools_->_this();
contextName.length(1);
contextName[0].id = (const char*) "hpp"; // string copied
contextName[0].kind = (const char*) "tools"; // string copied
// Note on kind: The kind field is used to indicate the type
// of the object. This is to avoid conventions such as that used
// by files (name.type -- e.g. hpp.ps = postscript etc.)
try {
rootContext->bind(contextName, localObj);
}
catch(CosNaming::NamingContext::AlreadyBound& ex)
{
rootContext->rebind(contextName, localObj);
}
}
catch(CORBA::COMM_FAILURE& ex) {
hppCorbaDout (error, "Caught system exception COMM_FAILURE -- "
"unable to contact the naming service.");
return;
}
catch(CORBA::SystemException&) {
hppCorbaDout (error, "Caught a SystemException while creating the context.");
return;
}
tools_->_remove_ref();
// Creation of main context
createContext (mainContextId());
}
bool Server::createContext (const std::string& name)
{
if (contexts_.find (name) != contexts_.end())
return false;
getContext (name);
return true;
}
core::ProblemSolverPtr_t Server::problemSolver ()
{
return problemSolverMap_->selected();
}
ProblemSolverMapPtr_t Server::problemSolverMap ()
{
return problemSolverMap_;
}
Server::Context& Server::getContext (const std::string& name)
{
if (contexts_.find (name) != contexts_.end()) {
return contexts_[name];
}
Context context;
context.main = ServerPluginPtr_t (new BasicServer (this));
ProblemSolverMapPtr_t psm (new ProblemSolverMap (*problemSolverMap_));
context.main->setProblemSolverMap (psm);
context.main->startCorbaServer ("hpp", name);
return contexts_.insert (std::make_pair(name, context)).first->second;
}
bool Server::loadPlugin (const std::string& contextName,
const std::string& libFilename)
{
// Load the plugin
std::string lib = core::plugin::findPluginLibrary (libFilename);
typedef ::hpp::corbaServer::ServerPlugin* (*PluginFunction_t) (Server*);
// Clear old errors
const char* error = dlerror ();
//void* library = dlopen(lib.c_str(), RTLD_NOW|RTLD_GLOBAL);
void* library = dlopen(lib.c_str(), RTLD_NOW);
error = dlerror ();
if (error != NULL) {
hppDout (error, "Error loading library " << lib << ": " << error);
return false;
}
if (library == NULL) {
// uncaught error ?
return false;
}
PluginFunction_t function = reinterpret_cast<PluginFunction_t>(dlsym(library, "createServerPlugin"));
error = dlerror ();
if (error != NULL) {
#ifdef HPP_DEBUG
hppDout (error, "Error loading library:\n" << error);
#else
std::cerr << "Error loading library:\n" << error << std::endl;
#endif
return false;
}
if (function == NULL) {
hppDout (error, "Symbol createServerPlugin of (correctly loaded) library " << lib << " is NULL.");
return false;
}
// Get the context.
Context& context = getContext (contextName);
ServerPluginPtr_t plugin (function(this));
if (!plugin) return false;
const std::string name = plugin->name();
if (context.plugins.find (name) != context.plugins.end()) {
hppDout (info, "Plugin " << lib << " already loaded.");
return false;
}
context.plugins[name] = plugin;
plugin->setProblemSolverMap (context.main->problemSolverMap());
plugin->startCorbaServer ("hpp", contextName);
// I don't think we should do that because the symbols should not be removed...
// dlclose (library);
return true;
}
/// \brief If CORBA requests are pending, process them
int Server::processRequest (bool loop)
{
if (loop)
{
hppDout (info, "start processing CORBA requests for ever.");
orb_->run();
}
else
{
if (orb_->work_pending())
orb_->perform_work();
}
return 0;
}
void Server::requestShutdown (bool wait)
{
orb_->shutdown (wait);
}
PortableServer::Servant Server::getServant (ServantKey servantKey) const
{
ServantKeyToServantMap_t::const_iterator _servant
= servantKeyToServantMap_.find (servantKey);
if (_servant == servantKeyToServantMap_.end())
return NULL;
return _servant->second;
}
void Server::addServantKeyAndServant (ServantKey servantKey, PortableServer::Servant servant)
{
typedef std::pair<ServantToServantKeyMap_t::iterator, bool> Ret_t;
Ret_t ret = servantToServantKeyMap_.insert (std::make_pair(servant, servantKey));
if (!ret.second) // Object not added because it already exists
{
std::cerr << "An servant object was lost." << std::endl;
ret.first->second = servantKey;
}
typedef std::pair<ServantKeyToServantMap_t::iterator, bool> Ret2_t;
Ret2_t ret2 = servantKeyToServantMap_.insert (std::make_pair(servantKey, servant));
if (!ret2.second)
ret2.first->second = servant;
}
void Server::removeServant (PortableServer::Servant servant)
{
ServantToServantKeyMap_t::iterator _it = servantToServantKeyMap_.find(servant);
if (_it == servantToServantKeyMap_.end()) return;
servantKeyToServantMap_.erase (_it->second);
servantToServantKeyMap_.erase (_it);
}
} // end of namespace corbaServer.
} // end of namespace hpp.
<commit_msg>Update handling of errors in server.<commit_after>// Copyright (C) 2009, 2010 by Florent Lamiraux, Thomas Moulard, JRL.
//
// This file is part of the hpp-corbaserver.
//
// This software is provided "as is" without warranty of any kind,
// either expressed or implied, including but not limited to the
// implied warranties of fitness for a particular purpose.
//
// See the COPYING file for more information.
#include "hpp/corbaserver/server.hh"
#include <errno.h>
#include <pthread.h>
#include <iostream>
#include <dlfcn.h>
#include <hpp/util/debug.hh>
#include <hpp/util/exception-factory.hh>
#include <hpp/core/plugin.hh>
#include <hpp/corbaserver/server-plugin.hh>
#include "hpp/corbaserver/tools-idl.hh"
#include "basic-server.hh"
#include "hpp/corbaserver/servant-base.hh"
namespace hpp
{
namespace corbaServer
{
using CORBA::Exception;
using CORBA::Object_var;
using CORBA::SystemException;
using CORBA::ORB_init;
using CORBA::PolicyList;
using omniORB::fatalException;
namespace
{
/// \brief Forward logging messages to hpp logging mechanism.
/// If debug is disabled, CORBA logging will be disabled too.
///
/// Tracing has to be enabled in your ``omniORB.cfg'' to use this
/// feature.
/// See ``omniORB configuration and API'' > ``Tracing options''
/// section of omniORB manual for more information.
void logFunction (const char* msg);
void logFunction (const char* hppDebugStatement (msg))
{
hppDout (info, "omniORB: " << msg);
}
void usage (const char* app)
{
std::cerr << "Usage: " << app << " [options] ..." << '\n'
<< " --name <name>" << '\n'
<< " --help" << '\n'
<< " --single-thread" << '\n'
<< " --multi-thread" << std::endl;
}
} // end of anonymous namespace.
class Tools : public virtual POA_hpp::Tools
{
public:
Tools () : server_ (NULL) {};
void setServer (Server* server)
{
server_ = server;
}
virtual CORBA::Boolean loadServerPlugin (const char* context, const char* pluginName) throw (Error)
{
try {
std::string c (context), pn (pluginName);
return server_->loadPlugin (c, pn);
} catch (const std::exception& e) {
throw hpp::Error (e.what ());
}
}
virtual CORBA::Boolean createContext (const char* context) throw (Error)
{
try {
std::string c (context);
return server_->createContext (c);
} catch (const std::exception& e) {
throw hpp::Error (e.what ());
}
}
virtual void deleteServant (const char* id) throw (Error)
{
try {
CORBA::Object_ptr obj = server_->orb()->string_to_object (id);
PortableServer::ObjectId_var objectId = server_->poa()->reference_to_id (obj);
// Remove reference in servant object map
ServantBase_var servant = server_->poa()->id_to_servant(objectId.in());
server_->removeServant (servant.in());
// Deactivate object
server_->poa()->deactivate_object(objectId.in());
} catch (const std::exception& e) {
throw hpp::Error (e.what ());
}
}
virtual void shutdown ()
{
server_->requestShutdown(false);
}
private:
Server* server_;
};
Server::Server(core::ProblemSolverPtr_t problemSolver, int argc,
const char *argv[], bool inMultiThread) :
multiThread_ (inMultiThread),
problemSolverMap_ (new ProblemSolverMap (problemSolver))
{
// Register log function.
omniORB::setLogFunction (&logFunction);
parseArguments (argc, argv);
initORBandServers (argc, argv, multiThread_);
}
Server::Server(ProblemSolverMapPtr_t problemSolverMap, int argc,
const char *argv[], bool inMultiThread) :
multiThread_ (inMultiThread),
problemSolverMap_ (problemSolverMap)
{
// Register log function.
omniORB::setLogFunction (&logFunction);
parseArguments (argc, argv);
initORBandServers (argc, argv, multiThread_);
}
/// \brief Shutdown CORBA server
Server::~Server()
{
}
/// CORBA SERVER INITIALIZATION
void Server::initORBandServers(int argc, const char* argv[],
bool inMultiThread)
{
Object_var obj;
PortableServer::ThreadPolicy_var threadPolicy;
PortableServer::POA_var rootPoa;
/// ORB init
orb_ = ORB_init (argc, const_cast<char **> (argv));
if (is_nil(orb_)) {
std::string msg ("failed to initialize ORB");
hppDout (error, msg.c_str ());
throw std::runtime_error (msg.c_str ());
}
/// ORB init
obj = orb_->resolve_initial_references("RootPOA");
/// Create thread policy
//
// Make the CORBA object single-threaded to avoid GUI krash
//
// Create a sigle threaded policy object
rootPoa = PortableServer::POA::_narrow(obj);
if (inMultiThread) {
threadPolicy = rootPoa->create_thread_policy
(PortableServer::ORB_CTRL_MODEL);
}
else {
threadPolicy = rootPoa->create_thread_policy
(PortableServer::MAIN_THREAD_MODEL);
}
/// Duplicate thread policy
PolicyList policyList;
policyList.length(1);
policyList[0] = PortableServer::ThreadPolicy::_duplicate(threadPolicy);
try {
poa_ = rootPoa->create_POA
("child", PortableServer::POAManager::_nil(), policyList);
} catch (PortableServer::POA::AdapterAlreadyExists& /*e*/) {
poa_ = rootPoa->find_POA ("child", false);
}
// Destroy policy object
threadPolicy->destroy();
}
void Server::parseArguments (int argc, const char* argv[])
{
mainContextId_ = "corbaserver";
for (int i = 1; i < argc; ++i) {
if (strcmp(argv[i], "--name") == 0) {
if (i < argc - 1) {
mainContextId_ = argv[i+1];
++i;
}
else usage(argv[0]);
std::cout << "Server main context: " << mainContextId_ << std::endl;
} else if (strcmp(argv[i], "--help") == 0) {
usage(argv[0]);
} else if (strcmp(argv[i], "--single-thread") == 0) {
multiThread_ = false;
std::cout << "Switched to single thread mode." << std::endl;
} else if (strcmp(argv[i], "--multi-thread") == 0) {
std::cout << "Switched to multi-thread mode." << std::endl;
multiThread_ = true;
}
}
}
void Server::startCorbaServer()
{
// Create Server interface
tools_ = new Tools ();
tools_->setServer (this);
/*servantId_ = */ poa_->activate_object(tools_);
CosNaming::NamingContext_var rootContext;
Object_var localObj;
CosNaming::Name contextName;
try {
// Obtain a reference to the root context of the Name service:
localObj = orb_->resolve_initial_references("NameService");
} catch(const CORBA::Exception& e) {
hppCorbaDout (error, "CORBA::Exception " << e._name() << ":"
<< e._rep_id() << " : failed to get the name service");
return;
}
try {
// Narrow the reference returned.
rootContext = CosNaming::NamingContext::_narrow(localObj);
if( is_nil(rootContext) ) {
hppCorbaDout (error, "Failed to narrow the root naming context.");
return;
}
}
catch(CORBA::ORB::InvalidName& ex) {
// This should not happen!
hppCorbaDout (error, "Service required is invalid [does not exist].");
return;
} catch(const CORBA::Exception& e) {
hppCorbaDout (error, "CORBA::Exception " << e._name() << ":"
<< e._rep_id() << " : failed to narrow the root naming context");
return;
}
try {
// Bind a context called "hpp" to the root context:
localObj = tools_->_this();
contextName.length(1);
contextName[0].id = (const char*) "hpp"; // string copied
contextName[0].kind = (const char*) "tools"; // string copied
// Note on kind: The kind field is used to indicate the type
// of the object. This is to avoid conventions such as that used
// by files (name.type -- e.g. hpp.ps = postscript etc.)
try {
rootContext->bind(contextName, localObj);
}
catch(CosNaming::NamingContext::AlreadyBound& ex)
{
rootContext->rebind(contextName, localObj);
}
}
catch(CORBA::COMM_FAILURE& ex) {
hppCorbaDout (error, "Caught system exception COMM_FAILURE -- "
"unable to contact the naming service.");
return;
}
catch(CORBA::SystemException&) {
hppCorbaDout (error, "Caught a SystemException while creating the context.");
return;
}
tools_->_remove_ref();
// Creation of main context
createContext (mainContextId());
}
bool Server::createContext (const std::string& name)
{
if (contexts_.find (name) != contexts_.end())
return false;
getContext (name);
return true;
}
core::ProblemSolverPtr_t Server::problemSolver ()
{
return problemSolverMap_->selected();
}
ProblemSolverMapPtr_t Server::problemSolverMap ()
{
return problemSolverMap_;
}
Server::Context& Server::getContext (const std::string& name)
{
if (contexts_.find (name) != contexts_.end()) {
return contexts_[name];
}
Context context;
context.main = ServerPluginPtr_t (new BasicServer (this));
ProblemSolverMapPtr_t psm (new ProblemSolverMap (*problemSolverMap_));
context.main->setProblemSolverMap (psm);
context.main->startCorbaServer ("hpp", name);
return contexts_.insert (std::make_pair(name, context)).first->second;
}
bool Server::loadPlugin (const std::string& contextName,
const std::string& libFilename)
{
// Load the plugin
std::string lib = core::plugin::findPluginLibrary (libFilename);
typedef ::hpp::corbaServer::ServerPlugin* (*PluginFunction_t) (Server*);
// Clear old errors
const char* error = dlerror ();
//void* library = dlopen(lib.c_str(), RTLD_NOW|RTLD_GLOBAL);
void* library = dlopen(lib.c_str(), RTLD_NOW);
error = dlerror ();
if (error != NULL) {
HPP_THROW (std::runtime_error, "Error loading library " << lib << ": " << error);
}
if (library == NULL) {
// uncaught error ?
HPP_THROW (std::runtime_error, "Unknown error while loading library " << lib << ".");
}
PluginFunction_t function = reinterpret_cast<PluginFunction_t>(dlsym(library, "createServerPlugin"));
error = dlerror ();
if (error != NULL) {
HPP_THROW (std::runtime_error, "Error loading library " << lib << ": " << error);
}
if (function == NULL) {
HPP_THROW (std::runtime_error, "Symbol createServerPlugin of (correctly loaded) library " << lib << " is NULL.");
}
// Get the context.
Context& context = getContext (contextName);
ServerPluginPtr_t plugin (function(this));
if (!plugin) return false;
const std::string name = plugin->name();
if (context.plugins.find (name) != context.plugins.end()) {
hppDout (info, "Plugin " << lib << " already loaded.");
return false;
}
context.plugins[name] = plugin;
plugin->setProblemSolverMap (context.main->problemSolverMap());
plugin->startCorbaServer ("hpp", contextName);
// I don't think we should do that because the symbols should not be removed...
// dlclose (library);
return true;
}
/// \brief If CORBA requests are pending, process them
int Server::processRequest (bool loop)
{
if (loop)
{
hppDout (info, "start processing CORBA requests for ever.");
orb_->run();
}
else
{
if (orb_->work_pending())
orb_->perform_work();
}
return 0;
}
void Server::requestShutdown (bool wait)
{
orb_->shutdown (wait);
}
PortableServer::Servant Server::getServant (ServantKey servantKey) const
{
ServantKeyToServantMap_t::const_iterator _servant
= servantKeyToServantMap_.find (servantKey);
if (_servant == servantKeyToServantMap_.end())
return NULL;
return _servant->second;
}
void Server::addServantKeyAndServant (ServantKey servantKey, PortableServer::Servant servant)
{
typedef std::pair<ServantToServantKeyMap_t::iterator, bool> Ret_t;
Ret_t ret = servantToServantKeyMap_.insert (std::make_pair(servant, servantKey));
if (!ret.second) // Object not added because it already exists
{
std::cerr << "An servant object was lost." << std::endl;
ret.first->second = servantKey;
}
typedef std::pair<ServantKeyToServantMap_t::iterator, bool> Ret2_t;
Ret2_t ret2 = servantKeyToServantMap_.insert (std::make_pair(servantKey, servant));
if (!ret2.second)
ret2.first->second = servant;
}
void Server::removeServant (PortableServer::Servant servant)
{
ServantToServantKeyMap_t::iterator _it = servantToServantKeyMap_.find(servant);
if (_it == servantToServantKeyMap_.end()) return;
servantKeyToServantMap_.erase (_it->second);
servantToServantKeyMap_.erase (_it);
}
} // end of namespace corbaServer.
} // end of namespace hpp.
<|endoftext|>
|
<commit_before>// $Id$
/*
Copyright (c) 2007-2009, Trustees of The Leland Stanford Junior University
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
Neither the name of the Stanford University nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*stats.cpp
*
*class stores statistics gnerated by the trafficmanager such as the latency
*hope count of the the flits
*
*reset option resets the min and max alues of this statistiscs
*/
#include "booksim.hpp"
#include <math.h>
#include <iostream>
#include <stdio.h>
#include "stats.hpp"
Stats::Stats( Module *parent, const string &name,
double bin_size, int num_bins ) :
Module( parent, name ),
_num_bins( num_bins ), _bin_size( bin_size )
{
_hist = new int [_num_bins];
Clear( );
}
Stats::~Stats( )
{
delete [] _hist;
}
void Stats::Clear( )
{
_num_samples = 0;
_sample_sum = 0.0;
for ( int b = 0; b < _num_bins; ++b ) {
_hist[b] = 0;
}
_reset = true;
}
double Stats::Average( ) const
{
return _sample_sum / (double)_num_samples;
}
double Stats::Min( ) const
{
return _min;
}
double Stats::Max( ) const
{
return _max;
}
int Stats::NumSamples( ) const
{
return _num_samples;
}
void Stats::AddSample( double val )
{
int b;
_num_samples++;
_sample_sum += val;
if ( _reset ) {
_reset = false;
_max = val;
_min = val;
} else {
if ( val > _max ) { _max = val; }
if ( val < _min ) { _min = val; }
}
b = (int)floor( val / _bin_size );
if ( b < 0 ) { b = 0; }
else if ( b >= _num_bins ) { b = _num_bins - 1; }
_hist[b]++;
}
void Stats::AddSample( int val )
{
AddSample( (double)val );
}
void Stats::Display( ) const
{
int b;
cout << "[ ";
for ( b = 0; b < _num_bins; ++b ) {
cout << _hist[b] << " ";
}
cout << "]" << endl;
FILE *ostream=fopen("stat","w");
for ( b = 0; b < _num_bins; ++b ) {
int temp = (int)(b*_bin_size);
fprintf(ostream,"%d %d \n",temp,_hist[b] );
}
fclose(ostream);
}
<commit_msg>prevent Stats::Display() from writing out histogram data into a (hard-coded) file named 'stats' in the current working directory<commit_after>// $Id$
/*
Copyright (c) 2007-2009, Trustees of The Leland Stanford Junior University
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
Neither the name of the Stanford University nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*stats.cpp
*
*class stores statistics gnerated by the trafficmanager such as the latency
*hope count of the the flits
*
*reset option resets the min and max alues of this statistiscs
*/
#include "booksim.hpp"
#include <math.h>
#include <iostream>
#include <stdio.h>
#include "stats.hpp"
Stats::Stats( Module *parent, const string &name,
double bin_size, int num_bins ) :
Module( parent, name ),
_num_bins( num_bins ), _bin_size( bin_size )
{
_hist = new int [_num_bins];
Clear( );
}
Stats::~Stats( )
{
delete [] _hist;
}
void Stats::Clear( )
{
_num_samples = 0;
_sample_sum = 0.0;
for ( int b = 0; b < _num_bins; ++b ) {
_hist[b] = 0;
}
_reset = true;
}
double Stats::Average( ) const
{
return _sample_sum / (double)_num_samples;
}
double Stats::Min( ) const
{
return _min;
}
double Stats::Max( ) const
{
return _max;
}
int Stats::NumSamples( ) const
{
return _num_samples;
}
void Stats::AddSample( double val )
{
int b;
_num_samples++;
_sample_sum += val;
if ( _reset ) {
_reset = false;
_max = val;
_min = val;
} else {
if ( val > _max ) { _max = val; }
if ( val < _min ) { _min = val; }
}
b = (int)floor( val / _bin_size );
if ( b < 0 ) { b = 0; }
else if ( b >= _num_bins ) { b = _num_bins - 1; }
_hist[b]++;
}
void Stats::AddSample( int val )
{
AddSample( (double)val );
}
void Stats::Display( ) const
{
int b;
cout << "[ ";
for ( b = 0; b < _num_bins; ++b ) {
cout << _hist[b] << " ";
}
cout << "]" << endl;
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2022 Snowplow Analytics Ltd. All rights reserved.
This program is licensed to you under the Apache License Version 2.0,
and you may not use this file except in compliance with the Apache License Version 2.0.
You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
Unless required by applicable law or agreed to in writing,
software distributed under the Apache License Version 2.0 is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
#include "utils.hpp"
using namespace snowplow;
using std::hex;
using std::nouppercase;
using std::ostringstream;
using std::runtime_error;
using std::setw;
using std::stringstream;
using std::to_string;
using std::uppercase;
using std::chrono::duration_cast;
using std::chrono::milliseconds;
using std::chrono::system_clock;
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__)
string Utils::get_uuid4() {
UUID uuid = {0};
string uid;
::UuidCreate(&uuid);
RPC_CSTR szUuid = NULL;
if (::UuidToStringA(&uuid, &szUuid) == RPC_S_OK) {
uid = (char *)szUuid;
::RpcStringFreeA(&szUuid);
} else {
throw runtime_error("FATAL: Could not generate unique UUID");
}
return uid;
}
#elif defined(__APPLE__)
string Utils::get_uuid4() {
CFUUIDRef cf_uuid_ref = CFUUIDCreate(kCFAllocatorDefault);
CFStringRef cf_uuid_str_ref = CFUUIDCreateString(kCFAllocatorDefault, cf_uuid_ref);
string uuid(CFStringGetCStringPtr(cf_uuid_str_ref, kCFStringEncodingUTF8));
transform(uuid.begin(), uuid.end(), uuid.begin(), ::tolower);
CFRelease(cf_uuid_ref);
CFRelease(cf_uuid_str_ref);
return uuid;
}
#endif
string Utils::int_list_to_string(list<int> *int_list, const string &delimiter) {
stringstream s;
int i;
list<int>::iterator it;
int length = int_list->size();
for (i = 0, it = int_list->begin(); it != int_list->end(); ++it, ++i) {
s << *it;
if (i < length - 1) {
s << delimiter;
}
}
return s.str();
}
string Utils::map_to_query_string(map<string, string> m) {
stringstream s;
int i;
map<string, string>::iterator it;
int length = m.size();
for (i = 0, it = m.begin(); it != m.end(); ++it, ++i) {
s << Utils::url_encode(it->first) << "=" << Utils::url_encode(it->second);
if (i < length - 1) {
s << "&";
}
}
return s.str();
}
string Utils::url_encode(string value) {
ostringstream escaped;
string::iterator i;
escaped.fill('0');
escaped << hex;
for (i = value.begin(); i != value.end(); ++i) {
char c = (*i);
if (isalnum(c) || c == '-' || c == '_' || c == '.') {
escaped << c;
continue;
}
escaped << uppercase;
escaped << '%' << uppercase << setw(2) << int((unsigned char)c);
escaped << nouppercase;
}
return escaped.str();
}
string Utils::serialize_payload(Payload payload) {
json j_map(payload.get());
return j_map.dump();
}
Payload Utils::deserialize_json_str(const string &json_str) {
Payload p;
json j = json::parse(json_str);
for (json::iterator it = j.begin(); it != j.end(); ++it) {
p.add(it.key(), it.value());
}
return p;
}
unsigned long long Utils::get_unix_epoch_ms() {
return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
}
// --- Desktop Context
SelfDescribingJson *Utils::m_desktop_context = 0;
SelfDescribingJson Utils::get_desktop_context() {
if (!m_desktop_context) {
json data;
data[SNOWPLOW_DESKTOP_OS_TYPE] = get_os_type();
data[SNOWPLOW_DESKTOP_OS_VERSION] = get_os_version();
data[SNOWPLOW_DESKTOP_OS_SERVICE_PACK] = get_os_service_pack();
data[SNOWPLOW_DESKTOP_OS_IS_64_BIT] = get_os_is_64bit();
data[SNOWPLOW_DESKTOP_DEVICE_MANU] = get_device_manufacturer();
data[SNOWPLOW_DESKTOP_DEVICE_MODEL] = get_device_model();
data[SNOWPLOW_DESKTOP_DEVICE_PROC_COUNT] = get_device_processor_count();
m_desktop_context = new SelfDescribingJson(SNOWPLOW_SCHEMA_DESKTOP_CONTEXT, data);
}
SelfDescribingJson copy = *m_desktop_context;
return copy;
}
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__)
string Utils::get_os_type() {
return "Windows";
}
string Utils::get_os_version() {
OSVERSIONINFOEX osviex;
::ZeroMemory(&osviex, sizeof(OSVERSIONINFOEX));
osviex.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
::GetVersionEx((LPOSVERSIONINFO)&osviex);
return to_string(osviex.dwMajorVersion) + "." + to_string(osviex.dwMinorVersion) + "." + to_string(osviex.dwBuildNumber);
}
string Utils::get_os_service_pack() {
OSVERSIONINFOEX osviex;
::ZeroMemory(&osviex, sizeof(OSVERSIONINFOEX));
osviex.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
::GetVersionEx((LPOSVERSIONINFO)&osviex);
return to_string(osviex.wServicePackMajor) + "." + to_string(osviex.wServicePackMinor);
}
string Utils::get_device_manufacturer() {
return "";
}
string Utils::get_device_model() {
return "";
}
bool Utils::get_os_is_64bit() {
#if defined(_WIN64)
return true;
#elif defined(_WIN32)
BOOL f64 = FALSE;
return IsWow64Process(GetCurrentProcess(), &f64) && f64;
#else
return false;
#endif
}
int Utils::get_device_processor_count() {
SYSTEM_INFO sysinfo;
GetSystemInfo(&sysinfo);
return sysinfo.dwNumberOfProcessors;
}
#elif defined(__APPLE__)
string Utils::get_os_type() {
return "macOS";
}
string Utils::get_os_version() {
return get_os_version_objc();
}
string Utils::get_os_service_pack() {
return "";
}
string Utils::get_device_manufacturer() {
return "Apple Inc.";
}
string Utils::get_device_model() {
char str[256];
size_t size = sizeof(str);
int ret = sysctlbyname("hw.model", str, &size, NULL, 0);
return str;
}
bool Utils::get_os_is_64bit() {
#if INTPTR_MAX == INT64_MAX
return true;
#else
return false;
#endif
}
int Utils::get_device_processor_count() {
return std::thread::hardware_concurrency();
}
#endif
<commit_msg>Add support for Linux when generating UUIDs (close #46)<commit_after>/*
Copyright (c) 2022 Snowplow Analytics Ltd. All rights reserved.
This program is licensed to you under the Apache License Version 2.0,
and you may not use this file except in compliance with the Apache License Version 2.0.
You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
Unless required by applicable law or agreed to in writing,
software distributed under the Apache License Version 2.0 is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
#include "utils.hpp"
using namespace snowplow;
using std::hex;
using std::nouppercase;
using std::ostringstream;
using std::runtime_error;
using std::setw;
using std::stringstream;
using std::to_string;
using std::uppercase;
using std::chrono::duration_cast;
using std::chrono::milliseconds;
using std::chrono::system_clock;
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__)
string Utils::get_uuid4() {
UUID uuid = {0};
string uid;
::UuidCreate(&uuid);
RPC_CSTR szUuid = NULL;
if (::UuidToStringA(&uuid, &szUuid) == RPC_S_OK) {
uid = (char *)szUuid;
::RpcStringFreeA(&szUuid);
} else {
throw runtime_error("FATAL: Could not generate unique UUID");
}
return uid;
}
#elif defined(__APPLE__)
string Utils::get_uuid4() {
CFUUIDRef cf_uuid_ref = CFUUIDCreate(kCFAllocatorDefault);
CFStringRef cf_uuid_str_ref = CFUUIDCreateString(kCFAllocatorDefault, cf_uuid_ref);
string uuid(CFStringGetCStringPtr(cf_uuid_str_ref, kCFStringEncodingUTF8));
transform(uuid.begin(), uuid.end(), uuid.begin(), ::tolower);
CFRelease(cf_uuid_ref);
CFRelease(cf_uuid_str_ref);
return uuid;
}
#else
#include <uuid/uuid.h>
string Utils::get_uuid4() {
uuid_t uuid;
char str[200];
uuid_generate_random(uuid);
uuid_unparse(uuid, str);
return string(str);
}
#endif
string Utils::int_list_to_string(list<int> *int_list, const string &delimiter) {
stringstream s;
int i;
list<int>::iterator it;
int length = int_list->size();
for (i = 0, it = int_list->begin(); it != int_list->end(); ++it, ++i) {
s << *it;
if (i < length - 1) {
s << delimiter;
}
}
return s.str();
}
string Utils::map_to_query_string(map<string, string> m) {
stringstream s;
int i;
map<string, string>::iterator it;
int length = m.size();
for (i = 0, it = m.begin(); it != m.end(); ++it, ++i) {
s << Utils::url_encode(it->first) << "=" << Utils::url_encode(it->second);
if (i < length - 1) {
s << "&";
}
}
return s.str();
}
string Utils::url_encode(string value) {
ostringstream escaped;
string::iterator i;
escaped.fill('0');
escaped << hex;
for (i = value.begin(); i != value.end(); ++i) {
char c = (*i);
if (isalnum(c) || c == '-' || c == '_' || c == '.') {
escaped << c;
continue;
}
escaped << uppercase;
escaped << '%' << uppercase << setw(2) << int((unsigned char)c);
escaped << nouppercase;
}
return escaped.str();
}
string Utils::serialize_payload(Payload payload) {
json j_map(payload.get());
return j_map.dump();
}
Payload Utils::deserialize_json_str(const string &json_str) {
Payload p;
json j = json::parse(json_str);
for (json::iterator it = j.begin(); it != j.end(); ++it) {
p.add(it.key(), it.value());
}
return p;
}
unsigned long long Utils::get_unix_epoch_ms() {
return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
}
// --- Desktop Context
SelfDescribingJson *Utils::m_desktop_context = 0;
SelfDescribingJson Utils::get_desktop_context() {
if (!m_desktop_context) {
json data;
data[SNOWPLOW_DESKTOP_OS_TYPE] = get_os_type();
data[SNOWPLOW_DESKTOP_OS_VERSION] = get_os_version();
data[SNOWPLOW_DESKTOP_OS_SERVICE_PACK] = get_os_service_pack();
data[SNOWPLOW_DESKTOP_OS_IS_64_BIT] = get_os_is_64bit();
data[SNOWPLOW_DESKTOP_DEVICE_MANU] = get_device_manufacturer();
data[SNOWPLOW_DESKTOP_DEVICE_MODEL] = get_device_model();
data[SNOWPLOW_DESKTOP_DEVICE_PROC_COUNT] = get_device_processor_count();
m_desktop_context = new SelfDescribingJson(SNOWPLOW_SCHEMA_DESKTOP_CONTEXT, data);
}
SelfDescribingJson copy = *m_desktop_context;
return copy;
}
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__)
string Utils::get_os_type() {
return "Windows";
}
string Utils::get_os_version() {
OSVERSIONINFOEX osviex;
::ZeroMemory(&osviex, sizeof(OSVERSIONINFOEX));
osviex.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
::GetVersionEx((LPOSVERSIONINFO)&osviex);
return to_string(osviex.dwMajorVersion) + "." + to_string(osviex.dwMinorVersion) + "." + to_string(osviex.dwBuildNumber);
}
string Utils::get_os_service_pack() {
OSVERSIONINFOEX osviex;
::ZeroMemory(&osviex, sizeof(OSVERSIONINFOEX));
osviex.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
::GetVersionEx((LPOSVERSIONINFO)&osviex);
return to_string(osviex.wServicePackMajor) + "." + to_string(osviex.wServicePackMinor);
}
string Utils::get_device_manufacturer() {
return "";
}
string Utils::get_device_model() {
return "";
}
bool Utils::get_os_is_64bit() {
#if defined(_WIN64)
return true;
#elif defined(_WIN32)
BOOL f64 = FALSE;
return IsWow64Process(GetCurrentProcess(), &f64) && f64;
#else
return false;
#endif
}
int Utils::get_device_processor_count() {
SYSTEM_INFO sysinfo;
GetSystemInfo(&sysinfo);
return sysinfo.dwNumberOfProcessors;
}
#elif defined(__APPLE__)
string Utils::get_os_type() {
return "macOS";
}
string Utils::get_os_version() {
return get_os_version_objc();
}
string Utils::get_os_service_pack() {
return "";
}
string Utils::get_device_manufacturer() {
return "Apple Inc.";
}
string Utils::get_device_model() {
char str[256];
size_t size = sizeof(str);
int ret = sysctlbyname("hw.model", str, &size, NULL, 0);
return str;
}
bool Utils::get_os_is_64bit() {
#if INTPTR_MAX == INT64_MAX
return true;
#else
return false;
#endif
}
int Utils::get_device_processor_count() {
return std::thread::hardware_concurrency();
}
#endif
<|endoftext|>
|
<commit_before>#include "utils.h"
#include "jwtxx/jwt.h" // Key::Error
#include <openssl/pem.h>
#include <openssl/x509.h>
#include <openssl/err.h>
#include <algorithm> // std::min
#include <exception>
#include <cstring> // strerror
#include <cstdio> // fopen, fclose
#include <cerrno> // errno
namespace Utils = JWTXX::Utils;
namespace
{
struct PasswordCallbackTester
{
explicit PasswordCallbackTester(const JWTXX::Key::PasswordCallback& cb) noexcept : callback(cb) {}
JWTXX::Key::PasswordCallback callback;
std::exception_ptr exception;
};
struct FileCloser
{
void operator()(FILE* fp) const noexcept { fclose(fp); }
};
typedef std::unique_ptr<FILE, FileCloser> FilePtr;
struct X509Deleter
{
void operator()(X509* cert) const noexcept { X509_free(cert); }
};
typedef std::unique_ptr<X509, X509Deleter> X509Ptr;
std::string sysError() noexcept
{
return strerror(errno);
}
Utils::EVPKeyPtr readPublicKey(const std::string& src)
{
// src is file name
FilePtr fp(fopen(src.c_str(), "rb"));
if (fp)
return Utils::EVPKeyPtr(PEM_read_PUBKEY(fp.get(), nullptr, nullptr, nullptr));
// src is key data
BIO* bio = BIO_new_mem_buf(src.data(), static_cast<int>(src.size()));
Utils::EVPKeyPtr key(PEM_read_bio_PUBKEY(bio, nullptr, nullptr, nullptr));
BIO_free(bio);
return key;
}
Utils::EVPKeyPtr readCert(const std::string& fileName)
{
FilePtr fp(fopen(fileName.c_str(), "rb"));
if (!fp)
throw JWTXX::Key::Error("Can't open key file '" + fileName + "'. " + sysError());
X509Ptr cert(PEM_read_X509(fp.get(), nullptr, nullptr, nullptr));
if (!cert)
return {};
return Utils::EVPKeyPtr(X509_get_pubkey(cert.get()));
}
int passwordCallback(char* buf, int size, int /*rwflag*/, void* data)
{
if (data == nullptr)
return 0;
PasswordCallbackTester& tester = *static_cast<PasswordCallbackTester*>(data);
try
{
auto password = tester.callback();
std::strncpy(buf, password.c_str(), size - 1);
buf[size - 1] = '\0';
return std::min<int>(size, password.length());
}
catch (...)
{
tester.exception = std::current_exception();
return 0;
}
}
}
Utils::EVPKeyPtr Utils::readPEMPrivateKey(const std::string& fileName, const JWTXX::Key::PasswordCallback& cb)
{
FilePtr fp(fopen(fileName.c_str(), "rb"));
if (!fp)
throw Key::Error("Can't open key file '" + fileName + "'. " + sysError());
try
{
PasswordCallbackTester tester(cb);
EVPKeyPtr key(PEM_read_PrivateKey(fp.get(), nullptr, passwordCallback, &tester));
if (tester.exception)
std::rethrow_exception(tester.exception);
if (!key)
throw Key::Error("Can't read private key '" + fileName + "'. " + OPENSSLError());
return key;
}
catch (const PasswordCallbackError&)
{
throw Key::Error("Can't read password-protected private key '" + fileName + "' without a password callback function.");
}
}
Utils::EVPKeyPtr Utils::readPEMPublicKey(const std::string& fileName)
{
auto key = readPublicKey(fileName);
std::string pkError;
if (!key)
{
pkError = OPENSSLError();
key = readCert(fileName);
}
if (!key)
throw Key::Error("File '" + fileName + "' is neither public key (" + pkError + ") nor certificate (" + OPENSSLError() + ").");
return key;
}
std::string Utils::OPENSSLError() noexcept
{
char buf[256];
ERR_error_string_n(ERR_get_error(), buf, sizeof(buf));
return buf;
}
Utils::Triple Utils::split(const std::string& token)
{
auto pos = token.find_first_of('.');
if (pos == std::string::npos)
throw JWT::ParseError("JWT should have at least 2 parts separated by a dot.");
auto spos = token.find_first_of('.', pos + 1);
if (spos == std::string::npos)
return std::make_tuple(token.substr(0, pos),
token.substr(pos + 1, token.length() - pos - 1),
"");
return std::make_tuple(token.substr(0, pos),
token.substr(pos + 1, spos - pos - 1),
token.substr(spos + 1, token.length() - spos - 1));
}
<commit_msg>Fix casting<commit_after>#include "utils.h"
#include "jwtxx/jwt.h" // Key::Error
#include <openssl/pem.h>
#include <openssl/x509.h>
#include <openssl/err.h>
#include <algorithm> // std::min
#include <exception>
#include <cstring> // strerror
#include <cstdio> // fopen, fclose
#include <cerrno> // errno
namespace Utils = JWTXX::Utils;
namespace
{
struct PasswordCallbackTester
{
explicit PasswordCallbackTester(const JWTXX::Key::PasswordCallback& cb) noexcept : callback(cb) {}
JWTXX::Key::PasswordCallback callback;
std::exception_ptr exception;
};
struct FileCloser
{
void operator()(FILE* fp) const noexcept { fclose(fp); }
};
typedef std::unique_ptr<FILE, FileCloser> FilePtr;
struct X509Deleter
{
void operator()(X509* cert) const noexcept { X509_free(cert); }
};
typedef std::unique_ptr<X509, X509Deleter> X509Ptr;
std::string sysError() noexcept
{
return strerror(errno);
}
Utils::EVPKeyPtr readPublicKey(const std::string& src)
{
// src is file name
FilePtr fp(fopen(src.c_str(), "rb"));
if (fp)
return Utils::EVPKeyPtr(PEM_read_PUBKEY(fp.get(), nullptr, nullptr, nullptr));
// src is key data
BIO* bio = BIO_new_mem_buf((void*)src.data(), static_cast<int>(src.size()));
Utils::EVPKeyPtr key(PEM_read_bio_PUBKEY(bio, nullptr, nullptr, nullptr));
BIO_free(bio);
return key;
}
Utils::EVPKeyPtr readCert(const std::string& fileName)
{
FilePtr fp(fopen(fileName.c_str(), "rb"));
if (!fp)
throw JWTXX::Key::Error("Can't open key file '" + fileName + "'. " + sysError());
X509Ptr cert(PEM_read_X509(fp.get(), nullptr, nullptr, nullptr));
if (!cert)
return {};
return Utils::EVPKeyPtr(X509_get_pubkey(cert.get()));
}
int passwordCallback(char* buf, int size, int /*rwflag*/, void* data)
{
if (data == nullptr)
return 0;
PasswordCallbackTester& tester = *static_cast<PasswordCallbackTester*>(data);
try
{
auto password = tester.callback();
std::strncpy(buf, password.c_str(), size - 1);
buf[size - 1] = '\0';
return std::min<int>(size, password.length());
}
catch (...)
{
tester.exception = std::current_exception();
return 0;
}
}
}
Utils::EVPKeyPtr Utils::readPEMPrivateKey(const std::string& fileName, const JWTXX::Key::PasswordCallback& cb)
{
FilePtr fp(fopen(fileName.c_str(), "rb"));
if (!fp)
throw Key::Error("Can't open key file '" + fileName + "'. " + sysError());
try
{
PasswordCallbackTester tester(cb);
EVPKeyPtr key(PEM_read_PrivateKey(fp.get(), nullptr, passwordCallback, &tester));
if (tester.exception)
std::rethrow_exception(tester.exception);
if (!key)
throw Key::Error("Can't read private key '" + fileName + "'. " + OPENSSLError());
return key;
}
catch (const PasswordCallbackError&)
{
throw Key::Error("Can't read password-protected private key '" + fileName + "' without a password callback function.");
}
}
Utils::EVPKeyPtr Utils::readPEMPublicKey(const std::string& fileName)
{
auto key = readPublicKey(fileName);
std::string pkError;
if (!key)
{
pkError = OPENSSLError();
key = readCert(fileName);
}
if (!key)
throw Key::Error("File '" + fileName + "' is neither public key (" + pkError + ") nor certificate (" + OPENSSLError() + ").");
return key;
}
std::string Utils::OPENSSLError() noexcept
{
char buf[256];
ERR_error_string_n(ERR_get_error(), buf, sizeof(buf));
return buf;
}
Utils::Triple Utils::split(const std::string& token)
{
auto pos = token.find_first_of('.');
if (pos == std::string::npos)
throw JWT::ParseError("JWT should have at least 2 parts separated by a dot.");
auto spos = token.find_first_of('.', pos + 1);
if (spos == std::string::npos)
return std::make_tuple(token.substr(0, pos),
token.substr(pos + 1, token.length() - pos - 1),
"");
return std::make_tuple(token.substr(0, pos),
token.substr(pos + 1, spos - pos - 1),
token.substr(spos + 1, token.length() - spos - 1));
}
<|endoftext|>
|
<commit_before>/*
* IceWM - Resource paths
* Copyright (C) 2001 The Authors of IceWM
*
* Release under terms of the GNU Library General Public License
*
* 2001/03/24: Mathias Hasselmann <mathias.hasselmann@gmx.net>
* - initial version
*/
#include "config.h"
#include "ylib.h"
#include "default.h"
#include "ypixbuf.h"
#include "base.h"
#include "ypaths.h"
#include "yapp.h"
#include "yprefs.h"
#include "intl.h"
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <limits.h>
#include <fcntl.h>
void YResourcePaths::addDir(const upath& dir) {
if (dir.dirExists())
fPaths.append(new upath(dir));
}
ref<YResourcePaths> YResourcePaths::subdirs(upath subdir, bool themeOnly) {
ref<YResourcePaths> paths(new YResourcePaths());
upath xdgDir(YApplication::getXdgConfDir());
upath homeDir(YApplication::getPrivConfDir());
upath themeDir(upath(themeName).parent());
if (themeName && *themeName == '/') {
MSG(("Searching `%s' resources at absolute location", cstring(subdir.path()).c_str()));
if (themeOnly) {
paths->addDir(themeDir);
} else {
paths->addDir(xdgDir);
paths->addDir(homeDir);
paths->addDir(themeDir);
paths->addDir(YApplication::getConfigDir());
paths->addDir(YApplication::getLibDir());
}
} else {
MSG(("Searching `%s' resources at relative locations", cstring(subdir.path()).c_str()));
upath themes("/themes/");
upath themesPlusThemeDir(themes + themeDir);
if (themeOnly) {
paths->addDir(xdgDir + themesPlusThemeDir);
paths->addDir(homeDir + themesPlusThemeDir);
paths->addDir(YApplication::getConfigDir() + themesPlusThemeDir);
paths->addDir(YApplication::getLibDir() + themesPlusThemeDir);
} else {
paths->addDir(xdgDir + themesPlusThemeDir);
paths->addDir(xdgDir);
paths->addDir(homeDir + themesPlusThemeDir);
paths->addDir(homeDir);
paths->addDir(YApplication::getConfigDir() + themesPlusThemeDir);
paths->addDir(YApplication::getConfigDir());
paths->addDir(YApplication::getLibDir() + themesPlusThemeDir);
paths->addDir(YApplication::getLibDir());
}
}
DBG {
MSG(("Initial search path:"));
for (int i = 0; i < paths->getCount(); i++) {
upath path = paths->getPath(i) + "/icons/";
cstring cs(path.path());
MSG(("%s", cs.c_str()));
}
}
paths->verifyPaths(subdir);
return paths;
}
void YResourcePaths::verifyPaths(upath base) {
for (int i = getCount(); --i >= 0; ) {
upath path = getPath(i) + base;
if (!path.isReadable()) {
fPaths.remove(i);
}
}
}
template<class Pict>
void YResourcePaths::loadPict(const upath& baseName, ref<Pict>* pict) const {
for (int i = 0; i < getCount(); ++i) {
upath path = getPath(i) + baseName;
if (path.fileExists()) {
if (path.isReadable()) {
if ((*pict = Pict::load(path)) != null) {
return;
} else
warn(_("Out of memory for image %s"),
path.string().c_str());
} else
warn(_("Image not readable: %s"), path.string().c_str());
}
}
#ifdef DEBUG
if (debug)
warn(_("Could not find image %s"), baseName.string().c_str());
#endif
}
ref<YPixmap> YResourcePaths::loadPixmap(upath base, upath name) const {
ref<YPixmap> p;
loadPict(base + name, &p);
return p;
}
ref<YImage> YResourcePaths::loadImage(upath base, upath name) const {
ref<YImage> p;
loadPict(base + name, &p);
return p;
}
<commit_msg>Better support theme names which don't have a slash or a .theme extensions.<commit_after>/*
* IceWM - Resource paths
* Copyright (C) 2001 The Authors of IceWM
*
* Release under terms of the GNU Library General Public License
*
* 2001/03/24: Mathias Hasselmann <mathias.hasselmann@gmx.net>
* - initial version
*/
#include "config.h"
#include "ylib.h"
#include "default.h"
#include "ypixbuf.h"
#include "base.h"
#include "ypaths.h"
#include "yapp.h"
#include "yprefs.h"
#include "intl.h"
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <limits.h>
#include <fcntl.h>
void YResourcePaths::addDir(const upath& dir) {
if (dir.dirExists())
fPaths.append(new upath(dir));
}
ref<YResourcePaths> YResourcePaths::subdirs(upath subdir, bool themeOnly) {
ref<YResourcePaths> paths(new YResourcePaths());
upath xdgDir(YApplication::getXdgConfDir());
upath homeDir(YApplication::getPrivConfDir());
upath themeFile(themeName);
pstring themeExt(themeFile.getExtension());
upath themeDir(themeExt.isEmpty() ? themeFile : themeFile.parent());
if (themeDir.isAbsolute()) {
MSG(("Searching `%s' resources at absolute location", cstring(subdir.path()).c_str()));
if (themeOnly) {
paths->addDir(themeDir);
} else {
paths->addDir(xdgDir);
paths->addDir(homeDir);
paths->addDir(themeDir);
paths->addDir(YApplication::getConfigDir());
paths->addDir(YApplication::getLibDir());
}
} else {
MSG(("Searching `%s' resources at relative locations", cstring(subdir.path()).c_str()));
upath themes("/themes/");
upath themesPlusThemeDir(themes + themeDir);
if (themeOnly) {
paths->addDir(xdgDir + themesPlusThemeDir);
paths->addDir(homeDir + themesPlusThemeDir);
paths->addDir(YApplication::getConfigDir() + themesPlusThemeDir);
paths->addDir(YApplication::getLibDir() + themesPlusThemeDir);
} else {
paths->addDir(xdgDir + themesPlusThemeDir);
paths->addDir(xdgDir);
paths->addDir(homeDir + themesPlusThemeDir);
paths->addDir(homeDir);
paths->addDir(YApplication::getConfigDir() + themesPlusThemeDir);
paths->addDir(YApplication::getConfigDir());
paths->addDir(YApplication::getLibDir() + themesPlusThemeDir);
paths->addDir(YApplication::getLibDir());
}
}
DBG {
MSG(("Initial search path:"));
for (int i = 0; i < paths->getCount(); i++) {
upath path = paths->getPath(i) + "/icons/";
cstring cs(path.path());
MSG(("%s", cs.c_str()));
}
}
paths->verifyPaths(subdir);
return paths;
}
void YResourcePaths::verifyPaths(upath base) {
for (int i = getCount(); --i >= 0; ) {
upath path = getPath(i) + base;
if (!path.isReadable()) {
fPaths.remove(i);
}
}
}
template<class Pict>
void YResourcePaths::loadPict(const upath& baseName, ref<Pict>* pict) const {
for (int i = 0; i < getCount(); ++i) {
upath path = getPath(i) + baseName;
if (path.fileExists()) {
if (path.isReadable()) {
if ((*pict = Pict::load(path)) != null) {
return;
} else
warn(_("Out of memory for image %s"),
path.string().c_str());
} else
warn(_("Image not readable: %s"), path.string().c_str());
}
}
#ifdef DEBUG
if (debug)
warn(_("Could not find image %s"), baseName.string().c_str());
#endif
}
ref<YPixmap> YResourcePaths::loadPixmap(upath base, upath name) const {
ref<YPixmap> p;
loadPict(base + name, &p);
return p;
}
ref<YImage> YResourcePaths::loadImage(upath base, upath name) const {
ref<YImage> p;
loadPict(base + name, &p);
return p;
}
<|endoftext|>
|
<commit_before>/**************************************************************************
* Copyright(c) 1998-2008, ALICE Experiment at CERN, all rights reserved. *
* See http://aliceinfo.cern.ch/Offline/AliRoot/License.html for *
* full copyright notice. *
**************************************************************************/
////////////////////////////////////////////////////////////////////////////
//
// AliEveEventSelector class
// selects events according to given criteria
//
// origin: Mikolaj Krzewicki, Nikhef, Mikolaj.Krzewicki@cern.ch
//
////////////////////////////////////////////////////////////////////////////
#include "AliEveEventSelector.h"
#include "AliEveEventManager.h"
#include "AliESD.h"
#include "AliESDEvent.h"
#include "AliESDRun.h"
#include <TEntryList.h>
#include <TDirectory.h>
#include <TTree.h>
#include <TObjArray.h>
#include <TRegexp.h>
#include <TROOT.h>
ClassImp(AliEveEventSelector)
//_____________________________________________________________________________
AliEveEventSelector::AliEveEventSelector(AliEveEventManager* evman):
fPEventManager(evman),
fWrapAround(kFALSE),
fSelectOnString(kFALSE),
fString(""),
fPEntryList(0),
fEntryListId(0),
fLastTreeSize(-1),
fSelectOnTriggerType(kFALSE),
fTriggerType(""),
fSelectOnTriggerString(kFALSE),
fTriggerSelectionString(""),
fTriggerMaskPatternString("trgmask"),
fSelectOnMultiplicity(kFALSE),
fMultiplicityLow(0),
fMultiplicityHigh(0)
{
//ctor
}
//_____________________________________________________________________________
void AliEveEventSelector::SetSelectionString( const TString& str )
{
//selection string setter
//takes care of producing a list of entries passing selection
TTree* pESDTree = fPEventManager->GetESDTree();
if (!pESDTree || fString==str) return;//don't waist time
fString = str;
if (str == "" ) return;//on reset don't recalculate
pESDTree->Draw( ">>listofentries", fString, "entrylist");
fPEntryList = dynamic_cast<TEntryList*>(gDirectory->Get("listofentries"));
}
//_____________________________________________________________________________
void AliEveEventSelector::SetSelectionString( const char* str )
{
//selection string setter
TString ts = str;
SetSelectionString(ts);
}
//_____________________________________________________________________________
void AliEveEventSelector::SetTriggerType( const TString& type )
{
//trigger type setter
fTriggerType = type;
}
//_____________________________________________________________________________
void AliEveEventSelector::SetTriggerType( const char* type)
{
//trigger type setter
TString ts = type;
SetTriggerType(ts);
}
//_____________________________________________________________________________
void AliEveEventSelector::UpdateEntryList()
{
//update the entrylist from if file changed
TTree* pESDTree = fPEventManager->GetESDTree();
if (!pESDTree) return;
Long64_t treesize = fPEventManager->GetMaxEventId()+1;
if (treesize<=fLastTreeSize) return; //nothing changed, do nothing
pESDTree->Draw(">>+fPEntryList", fString, "entrylist",
fLastTreeSize+1, treesize-fLastTreeSize );
fLastTreeSize = treesize;
}
//_____________________________________________________________________________
void AliEveEventSelector::Update()
{
//refresh stuff
UpdateEntryList();
}
//_____________________________________________________________________________
Bool_t AliEveEventSelector::FindNext( Int_t& output )
{
//does the magick of selecting the next event
static const TEveException kEH("AliEveEventSelector::GetNext ");
TTree* pESDTree = fPEventManager->GetESDTree();
if (!pESDTree) return kFALSE;
AliESDEvent* pESDEvent = fPEventManager->GetESD();
Int_t eventId = fPEventManager->GetEventId();
Int_t fMaxEventId = fPEventManager->GetMaxEventId();
if (!fSelectOnString)
{
// pure non-string
for (Int_t i = eventId+1; i<fMaxEventId+1; i++)
{
if (pESDTree->GetEntry(i) <= 0)
throw (kEH + "failed getting required event from ESD.");
if (CheckOtherSelection(pESDEvent))
{
output = i;
return kTRUE;
}
}
if (!fWrapAround) return kFALSE;
for (Int_t i = 0; i<eventId+1; i++)
{
if (pESDTree->GetEntry(i) <= 0)
throw (kEH + "failed getting required event from ESD.");
if (CheckOtherSelection(pESDEvent))
{
output = i;
return kTRUE;
}
}
return kFALSE;
}
else
{
//select using the entrylist
UpdateEntryList(); //update entry list if tree got bigger
for (Long64_t i=fEntryListId+1; i<fPEntryList->GetN(); i++ )
{
Long64_t entry = fPEntryList->GetEntry(i);
if (pESDTree->GetEntry(entry) <= 0)
throw (kEH + "failed getting required event from ESD.");
if (CheckOtherSelection(pESDEvent))
{
output = entry;
fEntryListId = i;
return kTRUE;
}
}
if (!fWrapAround) return kFALSE;
for (Long64_t i=0; i<fEntryListId+1; i++ )
{
Long64_t entry = fPEntryList->GetEntry(i);
if (pESDTree->GetEntry(entry) <= 0)
throw (kEH + "failed getting required event from ESD.");
if (CheckOtherSelection(pESDEvent))
{
output = entry;
fEntryListId=i;
return kTRUE;
}
}
return kFALSE;
}
return kFALSE;
}
//_____________________________________________________________________________
Bool_t AliEveEventSelector::FindPrev( Int_t& output )
{
//does the magick of selecting the previous event
static const TEveException kEH("AliEveEventSelector::GetNext ");
TTree* pESDTree = fPEventManager->GetESDTree();
if (!pESDTree) return kFALSE;
AliESDEvent* pESDEvent = fPEventManager->GetESD();
Int_t eventId = fPEventManager->GetEventId();
Int_t fMaxEventId = fPEventManager->GetMaxEventId();
if (!fSelectOnString)
{
// pure non-string
for (Int_t i = eventId-1; i>-1; i--)
{
if (pESDTree->GetEntry(i) <= 0)
throw (kEH + "failed getting required event from ESD.");
if (CheckOtherSelection(pESDEvent))
{
output = i;
return kTRUE;
}
}
if (!fWrapAround) return kFALSE;
for (Int_t i = fMaxEventId; i>eventId-1; i--)
{
if (pESDTree->GetEntry(i) <= 0)
throw (kEH + "failed getting required event from ESD.");
if (CheckOtherSelection(pESDEvent))
{
output = i;
return kTRUE;
}
}
return kFALSE;
}
else
{
//select using the entrylist
for (Long64_t i=fEntryListId-1; i>-1; i--)
{
Long64_t entry = fPEntryList->GetEntry(i);
if (pESDTree->GetEntry(entry) <= 0)
throw (kEH + "failed getting required event from ESD.");
if (CheckOtherSelection(pESDEvent))
{
output = entry;
fEntryListId = i;
return kTRUE;
}
}
if (!fWrapAround) return kFALSE;
for (Long64_t i=fPEntryList->GetN()-1; i>fEntryListId-1; i--)
{
Long64_t entry = fPEntryList->GetEntry(i);
if (pESDTree->GetEntry(entry) <= 0)
throw (kEH + "failed getting required event from ESD.");
if (CheckOtherSelection(pESDEvent))
{
output = entry;
fEntryListId=i;
return kTRUE;
}
}
return kFALSE;
}
return kFALSE;
}
//_____________________________________________________________________________
Bool_t AliEveEventSelector::CheckOtherSelection( AliESDEvent* pESDEvent )
{
//checks the event for any other hardcoded selection criteria
Bool_t ret=kTRUE;
//trigger stuff
if (fSelectOnTriggerType)
{
TString firedtrclasses = pESDEvent->GetFiredTriggerClasses();
if (!(firedtrclasses.Contains(fTriggerType))) return kFALSE;
//if (!pESDEvent->IsTriggerClassFired(fTriggerType.Data())) return kFALSE;
}
if (fSelectOnMultiplicity)
{
Int_t mult = pESDEvent->GetNumberOfTracks();
Int_t mhigh = (fMultiplicityHigh==0)?100000000:fMultiplicityHigh;
if (mult<fMultiplicityLow || mult>mhigh) return kFALSE;
}
if (fSelectOnTriggerString)
{
ULong64_t triggermask = pESDEvent->GetTriggerMask();
TString triggermaskstr;
triggermaskstr += triggermask;
TString selstr(fTriggerSelectionString); //make copy
selstr.ReplaceAll(fTriggerMaskPatternString,triggermaskstr);
//Int_t returncode;
Bool_t result = static_cast<Bool_t>(gROOT->ProcessLine(selstr));//,&returncode));
//if (!returncode) return kFALSE;
if (!result) return kFALSE;
}
return ret;
}
//_____________________________________________________________________________
void AliEveEventSelector::SetTriggerSelectionString( TString str )
{
//parses and sets the trigger selection formula
const AliESDRun* run = fPEventManager->GetESD()->GetESDRun();
for (Int_t i=0; i<run->kNTriggerClasses; i++)
{
TString name(run->GetTriggerClass(i));
if (name.IsNull()) continue;
TString valuestr("(");
valuestr += fTriggerMaskPatternString;
valuestr += "&";
valuestr += static_cast<ULong64_t>(1<<i);
valuestr += ")";
str.ReplaceAll(name,valuestr);
}//for i
fTriggerSelectionString = str;
}
<commit_msg>Fixing coverity 17942<commit_after>/**************************************************************************
* Copyright(c) 1998-2008, ALICE Experiment at CERN, all rights reserved. *
* See http://aliceinfo.cern.ch/Offline/AliRoot/License.html for *
* full copyright notice. *
**************************************************************************/
////////////////////////////////////////////////////////////////////////////
//
// AliEveEventSelector class
// selects events according to given criteria
//
// origin: Mikolaj Krzewicki, Nikhef, Mikolaj.Krzewicki@cern.ch
//
////////////////////////////////////////////////////////////////////////////
#include "AliEveEventSelector.h"
#include "AliEveEventManager.h"
#include "AliESD.h"
#include "AliESDEvent.h"
#include "AliESDRun.h"
#include <TEntryList.h>
#include <TDirectory.h>
#include <TTree.h>
#include <TObjArray.h>
#include <TRegexp.h>
#include <TROOT.h>
ClassImp(AliEveEventSelector)
//_____________________________________________________________________________
AliEveEventSelector::AliEveEventSelector(AliEveEventManager* evman):
fPEventManager(evman),
fWrapAround(kFALSE),
fSelectOnString(kFALSE),
fString(""),
fPEntryList(0),
fEntryListId(0),
fLastTreeSize(-1),
fSelectOnTriggerType(kFALSE),
fTriggerType(""),
fSelectOnTriggerString(kFALSE),
fTriggerSelectionString(""),
fTriggerMaskPatternString("trgmask"),
fSelectOnMultiplicity(kFALSE),
fMultiplicityLow(0),
fMultiplicityHigh(0)
{
//ctor
}
//_____________________________________________________________________________
void AliEveEventSelector::SetSelectionString( const TString& str )
{
//selection string setter
//takes care of producing a list of entries passing selection
TTree* pESDTree = fPEventManager->GetESDTree();
if (!pESDTree || fString==str) return;//don't waist time
fString = str;
if (str == "" ) return;//on reset don't recalculate
pESDTree->Draw( ">>listofentries", fString, "entrylist");
fPEntryList = dynamic_cast<TEntryList*>(gDirectory->Get("listofentries"));
}
//_____________________________________________________________________________
void AliEveEventSelector::SetSelectionString( const char* str )
{
//selection string setter
TString ts = str;
SetSelectionString(ts);
}
//_____________________________________________________________________________
void AliEveEventSelector::SetTriggerType( const TString& type )
{
//trigger type setter
fTriggerType = type;
}
//_____________________________________________________________________________
void AliEveEventSelector::SetTriggerType( const char* type)
{
//trigger type setter
TString ts = type;
SetTriggerType(ts);
}
//_____________________________________________________________________________
void AliEveEventSelector::UpdateEntryList()
{
//update the entrylist from if file changed
TTree* pESDTree = fPEventManager->GetESDTree();
if (!pESDTree) return;
Long64_t treesize = fPEventManager->GetMaxEventId()+1;
if (treesize<=fLastTreeSize) return; //nothing changed, do nothing
pESDTree->Draw(">>+fPEntryList", fString, "entrylist",
fLastTreeSize+1, treesize-fLastTreeSize );
fLastTreeSize = treesize;
}
//_____________________________________________________________________________
void AliEveEventSelector::Update()
{
//refresh stuff
UpdateEntryList();
}
//_____________________________________________________________________________
Bool_t AliEveEventSelector::FindNext( Int_t& output )
{
//does the magick of selecting the next event
static const TEveException kEH("AliEveEventSelector::GetNext ");
TTree* pESDTree = fPEventManager->GetESDTree();
if (!pESDTree) return kFALSE;
AliESDEvent* pESDEvent = fPEventManager->GetESD();
Int_t eventId = fPEventManager->GetEventId();
Int_t fMaxEventId = fPEventManager->GetMaxEventId();
if (!fSelectOnString)
{
// pure non-string
for (Int_t i = eventId+1; i<fMaxEventId+1; i++)
{
if (pESDTree->GetEntry(i) <= 0)
throw (kEH + "failed getting required event from ESD.");
if (CheckOtherSelection(pESDEvent))
{
output = i;
return kTRUE;
}
}
if (!fWrapAround) return kFALSE;
for (Int_t i = 0; i<eventId+1; i++)
{
if (pESDTree->GetEntry(i) <= 0)
throw (kEH + "failed getting required event from ESD.");
if (CheckOtherSelection(pESDEvent))
{
output = i;
return kTRUE;
}
}
return kFALSE;
}
else
{
//select using the entrylist
UpdateEntryList(); //update entry list if tree got bigger
for (Long64_t i=fEntryListId+1; i<fPEntryList->GetN(); i++ )
{
Long64_t entry = fPEntryList->GetEntry(i);
if (pESDTree->GetEntry(entry) <= 0)
throw (kEH + "failed getting required event from ESD.");
if (CheckOtherSelection(pESDEvent))
{
output = entry;
fEntryListId = i;
return kTRUE;
}
}
if (!fWrapAround) return kFALSE;
for (Long64_t i=0; i<fEntryListId+1; i++ )
{
Long64_t entry = fPEntryList->GetEntry(i);
if (pESDTree->GetEntry(entry) <= 0)
throw (kEH + "failed getting required event from ESD.");
if (CheckOtherSelection(pESDEvent))
{
output = entry;
fEntryListId=i;
return kTRUE;
}
}
return kFALSE;
}
return kFALSE;
}
//_____________________________________________________________________________
Bool_t AliEveEventSelector::FindPrev( Int_t& output )
{
//does the magick of selecting the previous event
static const TEveException kEH("AliEveEventSelector::GetNext ");
TTree* pESDTree = fPEventManager->GetESDTree();
if (!pESDTree) return kFALSE;
AliESDEvent* pESDEvent = fPEventManager->GetESD();
Int_t eventId = fPEventManager->GetEventId();
Int_t fMaxEventId = fPEventManager->GetMaxEventId();
if (!fSelectOnString)
{
// pure non-string
for (Int_t i = eventId-1; i>-1; i--)
{
if (pESDTree->GetEntry(i) <= 0)
throw (kEH + "failed getting required event from ESD.");
if (CheckOtherSelection(pESDEvent))
{
output = i;
return kTRUE;
}
}
if (!fWrapAround) return kFALSE;
for (Int_t i = fMaxEventId; i>eventId-1; i--)
{
if (pESDTree->GetEntry(i) <= 0)
throw (kEH + "failed getting required event from ESD.");
if (CheckOtherSelection(pESDEvent))
{
output = i;
return kTRUE;
}
}
return kFALSE;
}
else
{
//select using the entrylist
for (Long64_t i=fEntryListId-1; i>-1; i--)
{
Long64_t entry = fPEntryList->GetEntry(i);
if (pESDTree->GetEntry(entry) <= 0)
throw (kEH + "failed getting required event from ESD.");
if (CheckOtherSelection(pESDEvent))
{
output = entry;
fEntryListId = i;
return kTRUE;
}
}
if (!fWrapAround) return kFALSE;
for (Long64_t i=fPEntryList->GetN()-1; i>fEntryListId-1; i--)
{
Long64_t entry = fPEntryList->GetEntry(i);
if (pESDTree->GetEntry(entry) <= 0)
throw (kEH + "failed getting required event from ESD.");
if (CheckOtherSelection(pESDEvent))
{
output = entry;
fEntryListId=i;
return kTRUE;
}
}
return kFALSE;
}
return kFALSE;
}
//_____________________________________________________________________________
Bool_t AliEveEventSelector::CheckOtherSelection( AliESDEvent* pESDEvent )
{
//checks the event for any other hardcoded selection criteria
Bool_t ret=kTRUE;
//trigger stuff
if (fSelectOnTriggerType)
{
TString firedtrclasses = pESDEvent->GetFiredTriggerClasses();
if (!(firedtrclasses.Contains(fTriggerType))) return kFALSE;
//if (!pESDEvent->IsTriggerClassFired(fTriggerType.Data())) return kFALSE;
}
if (fSelectOnMultiplicity)
{
Int_t mult = pESDEvent->GetNumberOfTracks();
Int_t mhigh = (fMultiplicityHigh==0)?100000000:fMultiplicityHigh;
if (mult<fMultiplicityLow || mult>mhigh) return kFALSE;
}
if (fSelectOnTriggerString)
{
ULong64_t triggermask = pESDEvent->GetTriggerMask();
TString triggermaskstr;
triggermaskstr += triggermask;
TString selstr(fTriggerSelectionString); //make copy
selstr.ReplaceAll(fTriggerMaskPatternString,triggermaskstr);
//Int_t returncode;
Bool_t result = static_cast<Bool_t>(gROOT->ProcessLine(selstr));//,&returncode));
//if (!returncode) return kFALSE;
if (!result) return kFALSE;
}
return ret;
}
//_____________________________________________________________________________
void AliEveEventSelector::SetTriggerSelectionString( TString str )
{
//parses and sets the trigger selection formula
const AliESDRun* run = fPEventManager->GetESD()->GetESDRun();
for (Int_t i=0; i<run->kNTriggerClasses; i++)
{
TString name(run->GetTriggerClass(i));
if (name.IsNull()) continue;
TString valuestr("(");
valuestr += fTriggerMaskPatternString;
valuestr += "&";
valuestr += static_cast<ULong64_t>(1)<<i;
valuestr += ")";
str.ReplaceAll(name,valuestr);
}//for i
fTriggerSelectionString = str;
}
<|endoftext|>
|
<commit_before>#include "ofApp.h"
#include "asio.hpp" //For socket integration
#include "oscpkt.hh" //For OSC Serialzation
#include "ofxAubio.h" //for aubio
//---------------------Global Var: ASIO------------------------------------
std::string s;
using asio::ip::udp;
asio::io_service io_service;
#define PORT "1331"
//---------------------Global Var: OSC-------------------------------------
using namespace oscpkt;
PacketWriter pkt;
Message msg;
const void * message;
int size;
//---------------------UDP Classes-----------------------------------------
class UDPClient
{
public:
UDPClient(
asio::io_service& io_service,
const std::string& host,
const std::string& port
) : io_service_(io_service), socket_(io_service, udp::endpoint(udp::v4(), 0)) {
udp::resolver resolver(io_service_);
udp::resolver::query query(udp::v4(), host, port);
udp::resolver::iterator iter = resolver.resolve(query);
endpoint_ = *iter;
}
~UDPClient()
{
socket_.close();
}
void send(const std::string& msg) {
socket_.send_to(asio::buffer(msg, msg.size()), endpoint_);
}
void send_osc(const void *msg, int size) {
socket_.send_to(asio::buffer(msg, size), endpoint_);
}
private:
asio::io_service& io_service_;
udp::socket socket_;
udp::endpoint endpoint_;
};
UDPClient client(io_service, "localhost", PORT);
//--------------------------------------------------------------
void ofApp::setup(){
ofBackground(34, 34, 34);
ofSetFrameRate(60);
int sampleRate = 44100;
//int bufferSize = 512;
int outChannels = 0;
int inChannels = 2;
//--------------essentia setup
// setup the sound stream
soundStream.setup(this, outChannels, inChannels, sampleRate, bufferSize, 3);
//setup ofxAudioAnalyzer with the SAME PARAMETERS
audioAnalyzer.setup(sampleRate, bufferSize, inChannels);
//--------------filterbank setup
ofSetVerticalSync(true);
ofBackground(54, 54, 54);
ofSetFrameRate(60);
int ticksPerBuffer = 8;
int midiMin = 21;
int midiMax = 108;
filterBank.setup(bufferSize, midiMin, midiMax, inChannels, BANDWIDTH, sampleRate, 1.0);
filterBank.setColor(ofColor::orange);
//--------------aubio setup
// setup onset object
onset.setup();
//onset.setup("mkl", 2 * bufferSize, bufferSize, sampleRate);
// listen to onset event
ofAddListener(onset.gotOnset, this, &ofApp::onsetEvent);
// setup pitch object
pitch.setup();
//pitch.setup("yinfft", 8 * bufferSize, bufferSize, sampleRate);
// setup beat object
beat.setup();
//beat.setup("default", 2 * bufferSize, bufferSize, samplerate);
// listen to beat event
ofAddListener(beat.gotBeat, this, &ofApp::beatEvent);
// setup mel bands object
bands.setup();
}
//--------------------------------------------------------------
void ofApp::update(){
smooth = ofClamp(ofGetMouseX() / (float)ofGetWidth(), 0.0, 1.0);
//get the analysis values
rms_l = audioAnalyzer.getValue(RMS, 0, smooth);
rms_r = audioAnalyzer.getValue(RMS, 1, smooth);
//-:get Values:
rms = audioAnalyzer.getValue(RMS, 0, smoothing);
power = audioAnalyzer.getValue(POWER, 0, smoothing);
pitchFreq = audioAnalyzer.getValue(PITCH_FREQ, 0, smoothing);
pitchConf = audioAnalyzer.getValue(PITCH_CONFIDENCE, 0, smoothing);
pitchSalience = audioAnalyzer.getValue(PITCH_SALIENCE, 0, smoothing);
inharmonicity = audioAnalyzer.getValue(INHARMONICITY, 0, smoothing);
hfc = audioAnalyzer.getValue(HFC, 0, smoothing);
specComp = audioAnalyzer.getValue(SPECTRAL_COMPLEXITY, 0, smoothing);
centroid = audioAnalyzer.getValue(CENTROID, 0, smoothing);
rollOff = audioAnalyzer.getValue(ROLL_OFF, 0, smoothing);
oddToEven = audioAnalyzer.getValue(ODD_TO_EVEN, 0, smoothing);
strongPeak = audioAnalyzer.getValue(STRONG_PEAK, 0, smoothing);
strongDecay = audioAnalyzer.getValue(STRONG_DECAY, 0, smoothing);
//Normalized values for graphic meters:
pitchFreqNorm = audioAnalyzer.getValue(PITCH_FREQ, 0, smoothing, TRUE);
hfcNorm = audioAnalyzer.getValue(HFC, 0, smoothing, TRUE);
specCompNorm = audioAnalyzer.getValue(SPECTRAL_COMPLEXITY, 0, smoothing, TRUE);
centroidNorm = audioAnalyzer.getValue(CENTROID, 0, smoothing, TRUE);
rollOffNorm = audioAnalyzer.getValue(ROLL_OFF, 0, smoothing, TRUE);
oddToEvenNorm = audioAnalyzer.getValue(ODD_TO_EVEN, 0, smoothing, TRUE);
strongPeakNorm = audioAnalyzer.getValue(STRONG_PEAK, 0, smoothing, TRUE);
strongDecayNorm = audioAnalyzer.getValue(STRONG_DECAY, 0, smoothing, TRUE);
dissonance = audioAnalyzer.getValue(DISSONANCE, 0, smoothing);
//Vector Parameters
spectrum = audioAnalyzer.getValues(SPECTRUM, 0, smoothing);
melBands = audioAnalyzer.getValues(MEL_BANDS, 0, smoothing);
mfcc = audioAnalyzer.getValues(MFCC, 0, smoothing);
hpcp = audioAnalyzer.getValues(HPCP, 0, smoothing);
tristimulus = audioAnalyzer.getValues(TRISTIMULUS, 0, smoothing);
//Boolean Parameter
isOnset = audioAnalyzer.getOnsetValue(0);
//For Testing
std::cout<<"centroidNorm:"<<centroidNorm<<endl ;
std::cout<<"strongDecayNorm:"<<strongDecayNorm<<endl ;
// Make & Send OSC Object
pkt.startBundle();
pkt.addMessage(msg.init("/essentia/rms").pushFloat(rms));
pkt.addMessage(msg.init("/essentia/power").pushFloat(power));
pkt.addMessage(msg.init("/essentia/pitchFreq").pushFloat(pitchFreq));
pkt.addMessage(msg.init("/essentia/pitchConf").pushFloat(pitchConf));
pkt.addMessage(msg.init("/essentia/pitchSalience").pushFloat(pitchSalience));
pkt.addMessage(msg.init("/essentia/inharmonicity").pushFloat(inharmonicity));
pkt.addMessage(msg.init("/essentia/hfc").pushFloat(hfc));
pkt.addMessage(msg.init("/essentia/specComp").pushFloat(specComp));
pkt.addMessage(msg.init("/essentia/centroid").pushFloat(centroid));
pkt.addMessage(msg.init("/essentia/rollOff").pushFloat(rollOff));
pkt.addMessage(msg.init("/essentia/oddToEven").pushFloat(oddToEven));
pkt.addMessage(msg.init("/essentia/strongPeak").pushFloat(strongPeak));
pkt.addMessage(msg.init("/essentia/strongDecay").pushFloat(strongDecay));
//Normalized values for graphic meters:
pkt.addMessage(msg.init("/essentia/pitchFreqNorm").pushFloat(pitchFreqNorm));
pkt.addMessage(msg.init("/essentia/hfcNorm").pushFloat(hfcNorm));
pkt.addMessage(msg.init("/essentia/specCompNorm").pushFloat(specCompNorm));
pkt.addMessage(msg.init("/essentia/centroidNorm").pushFloat(centroidNorm));
pkt.addMessage(msg.init("/essentia/rollOffNorm").pushFloat(rollOffNorm));
pkt.addMessage(msg.init("/essentia/oddToEvenNorm").pushFloat(oddToEvenNorm));
pkt.addMessage(msg.init("/essentia/strongPeakNorm").pushFloat(strongPeakNorm));
pkt.addMessage(msg.init("/essentia/strongDecayNorm").pushFloat(strongDecayNorm));
// Boolean, mapped to onset.
pkt.addMessage(msg.init("/essentia/isOnset").pushFloat(isOnset));
// Vector Parameters
int spectrum_size=spectrum.size(); //257
pkt.addMessage(msg.init("/essentia/spectrum"));
for(int n=0; n<spectrum_size; n++)
{ msg.pushFloat(spectrum[n]);
}
int melBands_size=melBands.size(); //24
pkt.addMessage(msg.init("/essentia/melBands"));
for(int n=0; n<melBands_size; n++)
{ msg.pushFloat(melBands[n]);
}
int mfcc_size=mfcc.size(); //13
pkt.addMessage(msg.init("/essentia/mfcc"));
for(int n=0; n<mfcc_size; n++)
{ msg.pushFloat(mfcc[n]);
}
int hpcp_size=hpcp.size(); //12
pkt.addMessage(msg.init("/essentia/hpcp"));
for(int n=0; n<hpcp_size; n++)
{ msg.pushFloat(hpcp[n]);
}
int tristimulus_size=tristimulus.size(); //3
pkt.addMessage(msg.init("/essentia/tristimulus"));
for(int n=0; n<tristimulus_size; n++)
{ msg.pushFloat(tristimulus[n]);
}
// Polyphonic Pitch from Filterbank
float * polyphonic_pitch_pointer;
float log_smth_energy;
polyphonic_pitch_pointer=filterBank.getSmthEnergies();
log_smth_energy = LIN2dB (polyphonic_pitch_pointer[filterBank.midiMinVar]);
pkt.addMessage(msg.init("/essentia/PolyphonicPitch").pushFloat(log_smth_energy));
std::cout<<"Midi Min= "<<filterBank.midiMinVar<<endl;
std::cout<<"Midi Min= "<<filterBank.midiMaxVar<<endl;
for(int n=filterBank.midiMinVar+1; n<filterBank.midiMaxVar; n++) // 88
{ log_smth_energy = LIN2dB (polyphonic_pitch_pointer[n]);
std::cout<<log_smth_energy<<" ";
msg.pushFloat(log_smth_energy);
}
std::cout<<endl;
pkt.endBundle();
if (pkt.isOk()) {
message=pkt.packetData();
size= pkt.packetSize();
client.send_osc(message, size);
}
msg.clear();
pkt.Reset();
}
//--------------------------------------------------------------
void ofApp::draw(){
/* ofSetColor(ofColor::cyan);
float xpos = ofGetWidth() *.5;
float ypos = ofGetHeight() - ofGetHeight() * rms_r;
float radius = 5 + 100*rms_l;
ofDrawCircle(xpos, ypos, radius);
//----------------
ofSetColor(225);
ofDrawBitmapString("ofxAudioAnalyzer - RMS SMOOTHING INPUT EXAMPLE", 32, 32);
string infoString = "RMS Left: " + ofToString(rms_l) +
"\nRMS Right: " + ofToString(rms_r) +
"\nSmoothing (mouse x): " + ofToString(smooth);
ofDrawBitmapString(infoString, 32, 579);*/
ofSetColor(225);
ofNoFill();
float chSz = bufferSize/3;
// draw the left input channel:
{
ofPushStyle();
ofPushMatrix();
ofTranslate(100, 15, 0);
ofSetColor(225);
ofDrawBitmapString("Left Channel", 4, 18);
ofSetLineWidth(1);
ofRect(0, 0, chSz, 200);
ofSetColor(ofColor::orange);
ofSetLineWidth(3);
ofBeginShape();
for (int i = 0; i < bufferSize; i++){
ofVertex(i/(bufferSize/chSz), 100 - filterBank.getLeftBuffer()[i]*45);
}
ofEndShape(false);
ofPopMatrix();
ofPopStyle();
}
// draw the right input channel:
{
ofPushStyle();
ofPushMatrix();
ofTranslate(200+chSz, 15, 0);
ofSetColor(225);
ofDrawBitmapString("Right Channel", 4, 18);
ofSetLineWidth(1);
ofRect(0, 0, chSz, 200);
ofSetColor(ofColor::orange);
ofSetLineWidth(3);
ofBeginShape();
for (int i = 0; i < bufferSize; i++){
ofVertex(i/(bufferSize/chSz), 100 - filterBank.getRightBuffer()[i]*45);
}
ofEndShape(false);
ofPopMatrix();
ofPopStyle();
}
//Draw FilterBank
{
ofPushStyle();
ofPushMatrix();
ofTranslate (100,250,0);
filterBank.draw(800,400);
ofPopMatrix();
ofPopStyle();
}
ofSetColor(225);
string reportString = "Sampling Rate: "+ ofToString(SR) +"\nBuffer size: "+ ofToString(bufferSize);
ofDrawBitmapString(reportString, 10, 700);
}
//--------------------------------------------------------------
void ofApp::audioIn(ofSoundBuffer &inBuffer){
//ANALYZE SOUNDBUFFER:
audioAnalyzer.analyze(inBuffer);
//Analyze Input Buffer with ofxFilterbank
vector <float> temp;
temp = inBuffer.getBuffer();
float *p = &temp[0];
filterBank.analyze(p);
}
//--------------------------------------------------------------
void ofApp::exit(){
ofSoundStreamStop();
audioAnalyzer.exit();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
//==========Aubio
//----
void ofApp::onsetEvent(float & time) {
//ofLog() << "got onset at " << time << " s";
gotOnset = true;
}
//----
void ofApp::beatEvent(float & time) {
//ofLog() << "got beat at " << time << " s";
gotBeat = true;
}
<commit_msg>Aubio is incorporated into Essentia<commit_after>#include "ofApp.h"
#include "asio.hpp" //For socket integration
#include "oscpkt.hh" //For OSC Serialzation
#include "ofxAubio.h" //for aubio
//---------------------Global Var: ASIO------------------------------------
std::string s;
using asio::ip::udp;
asio::io_service io_service;
#define PORT "1331"
//---------------------Global Var: OSC-------------------------------------
using namespace oscpkt;
PacketWriter pkt;
Message msg;
const void * message;
int size;
//---------------------UDP Classes-----------------------------------------
class UDPClient
{
public:
UDPClient(
asio::io_service& io_service,
const std::string& host,
const std::string& port
) : io_service_(io_service), socket_(io_service, udp::endpoint(udp::v4(), 0)) {
udp::resolver resolver(io_service_);
udp::resolver::query query(udp::v4(), host, port);
udp::resolver::iterator iter = resolver.resolve(query);
endpoint_ = *iter;
}
~UDPClient()
{
socket_.close();
}
void send(const std::string& msg) {
socket_.send_to(asio::buffer(msg, msg.size()), endpoint_);
}
void send_osc(const void *msg, int size) {
socket_.send_to(asio::buffer(msg, size), endpoint_);
}
private:
asio::io_service& io_service_;
udp::socket socket_;
udp::endpoint endpoint_;
};
UDPClient client(io_service, "localhost", PORT);
//--------------------------------------------------------------
void ofApp::setup(){
ofBackground(34, 34, 34);
ofSetFrameRate(60);
int sampleRate = 44100;
//int bufferSize = 512;
int outChannels = 0;
int inChannels = 2;
//--------------essentia setup
// setup the sound stream
soundStream.setup(this, outChannels, inChannels, sampleRate, bufferSize, 3);
//setup ofxAudioAnalyzer with the SAME PARAMETERS
audioAnalyzer.setup(sampleRate, bufferSize, inChannels);
//--------------filterbank setup
ofSetVerticalSync(true);
ofBackground(54, 54, 54);
ofSetFrameRate(60);
int ticksPerBuffer = 8;
int midiMin = 21;
int midiMax = 108;
filterBank.setup(bufferSize, midiMin, midiMax, inChannels, BANDWIDTH, sampleRate, 1.0);
filterBank.setColor(ofColor::orange);
//--------------aubio setup
// setup onset object
onset.setup();
//onset.setup("mkl", 2 * bufferSize, bufferSize, sampleRate);
// listen to onset event
ofAddListener(onset.gotOnset, this, &ofApp::onsetEvent);
// setup pitch object
pitch.setup();
//pitch.setup("yinfft", 8 * bufferSize, bufferSize, sampleRate);
// setup beat object
beat.setup();
//beat.setup("default", 2 * bufferSize, bufferSize, samplerate);
// listen to beat event
ofAddListener(beat.gotBeat, this, &ofApp::beatEvent);
// setup mel bands object
bands.setup();
}
//--------------------------------------------------------------
void ofApp::update(){
smooth = ofClamp(ofGetMouseX() / (float)ofGetWidth(), 0.0, 1.0);
//get the analysis values
rms_l = audioAnalyzer.getValue(RMS, 0, smooth);
rms_r = audioAnalyzer.getValue(RMS, 1, smooth);
//-:get Values:
rms = audioAnalyzer.getValue(RMS, 0, smoothing);
power = audioAnalyzer.getValue(POWER, 0, smoothing);
pitchFreq = audioAnalyzer.getValue(PITCH_FREQ, 0, smoothing);
pitchConf = audioAnalyzer.getValue(PITCH_CONFIDENCE, 0, smoothing);
pitchSalience = audioAnalyzer.getValue(PITCH_SALIENCE, 0, smoothing);
inharmonicity = audioAnalyzer.getValue(INHARMONICITY, 0, smoothing);
hfc = audioAnalyzer.getValue(HFC, 0, smoothing);
specComp = audioAnalyzer.getValue(SPECTRAL_COMPLEXITY, 0, smoothing);
centroid = audioAnalyzer.getValue(CENTROID, 0, smoothing);
rollOff = audioAnalyzer.getValue(ROLL_OFF, 0, smoothing);
oddToEven = audioAnalyzer.getValue(ODD_TO_EVEN, 0, smoothing);
strongPeak = audioAnalyzer.getValue(STRONG_PEAK, 0, smoothing);
strongDecay = audioAnalyzer.getValue(STRONG_DECAY, 0, smoothing);
//Normalized values for graphic meters:
pitchFreqNorm = audioAnalyzer.getValue(PITCH_FREQ, 0, smoothing, TRUE);
hfcNorm = audioAnalyzer.getValue(HFC, 0, smoothing, TRUE);
specCompNorm = audioAnalyzer.getValue(SPECTRAL_COMPLEXITY, 0, smoothing, TRUE);
centroidNorm = audioAnalyzer.getValue(CENTROID, 0, smoothing, TRUE);
rollOffNorm = audioAnalyzer.getValue(ROLL_OFF, 0, smoothing, TRUE);
oddToEvenNorm = audioAnalyzer.getValue(ODD_TO_EVEN, 0, smoothing, TRUE);
strongPeakNorm = audioAnalyzer.getValue(STRONG_PEAK, 0, smoothing, TRUE);
strongDecayNorm = audioAnalyzer.getValue(STRONG_DECAY, 0, smoothing, TRUE);
dissonance = audioAnalyzer.getValue(DISSONANCE, 0, smoothing);
//Vector Parameters
spectrum = audioAnalyzer.getValues(SPECTRUM, 0, smoothing);
melBands = audioAnalyzer.getValues(MEL_BANDS, 0, smoothing);
mfcc = audioAnalyzer.getValues(MFCC, 0, smoothing);
hpcp = audioAnalyzer.getValues(HPCP, 0, smoothing);
tristimulus = audioAnalyzer.getValues(TRISTIMULUS, 0, smoothing);
//Boolean Parameter
isOnset = audioAnalyzer.getOnsetValue(0);
//For Testing
std::cout<<"centroidNorm:"<<centroidNorm<<endl ;
std::cout<<"strongDecayNorm:"<<strongDecayNorm<<endl ;
// Make & Send OSC Object
pkt.startBundle();
pkt.addMessage(msg.init("/essentia/rms").pushFloat(rms));
pkt.addMessage(msg.init("/essentia/power").pushFloat(power));
pkt.addMessage(msg.init("/essentia/pitchFreq").pushFloat(pitchFreq));
pkt.addMessage(msg.init("/essentia/pitchConf").pushFloat(pitchConf));
pkt.addMessage(msg.init("/essentia/pitchSalience").pushFloat(pitchSalience));
pkt.addMessage(msg.init("/essentia/inharmonicity").pushFloat(inharmonicity));
pkt.addMessage(msg.init("/essentia/hfc").pushFloat(hfc));
pkt.addMessage(msg.init("/essentia/specComp").pushFloat(specComp));
pkt.addMessage(msg.init("/essentia/centroid").pushFloat(centroid));
pkt.addMessage(msg.init("/essentia/rollOff").pushFloat(rollOff));
pkt.addMessage(msg.init("/essentia/oddToEven").pushFloat(oddToEven));
pkt.addMessage(msg.init("/essentia/strongPeak").pushFloat(strongPeak));
pkt.addMessage(msg.init("/essentia/strongDecay").pushFloat(strongDecay));
//Normalized values for graphic meters:
pkt.addMessage(msg.init("/essentia/pitchFreqNorm").pushFloat(pitchFreqNorm));
pkt.addMessage(msg.init("/essentia/hfcNorm").pushFloat(hfcNorm));
pkt.addMessage(msg.init("/essentia/specCompNorm").pushFloat(specCompNorm));
pkt.addMessage(msg.init("/essentia/centroidNorm").pushFloat(centroidNorm));
pkt.addMessage(msg.init("/essentia/rollOffNorm").pushFloat(rollOffNorm));
pkt.addMessage(msg.init("/essentia/oddToEvenNorm").pushFloat(oddToEvenNorm));
pkt.addMessage(msg.init("/essentia/strongPeakNorm").pushFloat(strongPeakNorm));
pkt.addMessage(msg.init("/essentia/strongDecayNorm").pushFloat(strongDecayNorm));
// Boolean, mapped to onset.
pkt.addMessage(msg.init("/essentia/isOnset").pushFloat(isOnset));
// Vector Parameters
int spectrum_size=spectrum.size(); //257
pkt.addMessage(msg.init("/essentia/spectrum"));
for(int n=0; n<spectrum_size; n++)
{ msg.pushFloat(spectrum[n]);
}
int melBands_size=melBands.size(); //24
pkt.addMessage(msg.init("/essentia/melBands"));
for(int n=0; n<melBands_size; n++)
{ msg.pushFloat(melBands[n]);
}
int mfcc_size=mfcc.size(); //13
pkt.addMessage(msg.init("/essentia/mfcc"));
for(int n=0; n<mfcc_size; n++)
{ msg.pushFloat(mfcc[n]);
}
int hpcp_size=hpcp.size(); //12
pkt.addMessage(msg.init("/essentia/hpcp"));
for(int n=0; n<hpcp_size; n++)
{ msg.pushFloat(hpcp[n]);
}
int tristimulus_size=tristimulus.size(); //3
pkt.addMessage(msg.init("/essentia/tristimulus"));
for(int n=0; n<tristimulus_size; n++)
{ msg.pushFloat(tristimulus[n]);
}
// Polyphonic Pitch from Filterbank
float * polyphonic_pitch_pointer;
float log_smth_energy;
polyphonic_pitch_pointer=filterBank.getSmthEnergies();
log_smth_energy = LIN2dB (polyphonic_pitch_pointer[filterBank.midiMinVar]);
pkt.addMessage(msg.init("/essentia/PolyphonicPitch").pushFloat(log_smth_energy));
std::cout<<"Midi Min= "<<filterBank.midiMinVar<<endl;
std::cout<<"Midi Min= "<<filterBank.midiMaxVar<<endl;
for(int n=filterBank.midiMinVar+1; n<filterBank.midiMaxVar; n++) // 88
{ log_smth_energy = LIN2dB (polyphonic_pitch_pointer[n]);
std::cout<<log_smth_energy<<" ";
msg.pushFloat(log_smth_energy);
}
std::cout<<endl;
// Onsets, BPM and monophonic pitch from Aubio
onset.setThreshold(onsetThreshold);
onsetNovelty = onset.novelty;
onsetThresholdedNovelty = onset.thresholdedNovelty;
std::cout<<"Onset Threshold Novelty:"<<onsetThresholdedNovelty<<endl ;
// update pitch info
pitchConfidence = pitch.pitchConfidence;
if (pitch.latestPitch) midiPitch = pitch.latestPitch;
std::cout<<"Pitch:"<<midiPitch<<endl ;
// update BPM
bpm = beat.bpm;
std::cout<<"BPM:"<<bpm<<endl ;
pkt.addMessage(msg.init("/aubio/onset").pushFloat(onset.thresholdedNovelty));
pkt.addMessage(msg.init("/aubio/midiPitch").pushFloat(pitch.latestPitch));
pkt.addMessage(msg.init("/aubio/bpm").pushFloat(beat.bpm));
pkt.endBundle();
if (pkt.isOk()) {
message=pkt.packetData();
size= pkt.packetSize();
client.send_osc(message, size);
}
msg.clear();
pkt.Reset();
}
//--------------------------------------------------------------
void ofApp::draw(){
/* ofSetColor(ofColor::cyan);
float xpos = ofGetWidth() *.5;
float ypos = ofGetHeight() - ofGetHeight() * rms_r;
float radius = 5 + 100*rms_l;
ofDrawCircle(xpos, ypos, radius);
//----------------
ofSetColor(225);
ofDrawBitmapString("ofxAudioAnalyzer - RMS SMOOTHING INPUT EXAMPLE", 32, 32);
string infoString = "RMS Left: " + ofToString(rms_l) +
"\nRMS Right: " + ofToString(rms_r) +
"\nSmoothing (mouse x): " + ofToString(smooth);
ofDrawBitmapString(infoString, 32, 579);*/
ofSetColor(225);
ofNoFill();
float chSz = bufferSize/3;
// draw the left input channel:
{
ofPushStyle();
ofPushMatrix();
ofTranslate(100, 15, 0);
ofSetColor(225);
ofDrawBitmapString("Left Channel", 4, 18);
ofSetLineWidth(1);
ofRect(0, 0, chSz, 200);
ofSetColor(ofColor::orange);
ofSetLineWidth(3);
ofBeginShape();
for (int i = 0; i < bufferSize; i++){
ofVertex(i/(bufferSize/chSz), 100 - filterBank.getLeftBuffer()[i]*45);
}
ofEndShape(false);
ofPopMatrix();
ofPopStyle();
}
// draw the right input channel:
{
ofPushStyle();
ofPushMatrix();
ofTranslate(200+chSz, 15, 0);
ofSetColor(225);
ofDrawBitmapString("Right Channel", 4, 18);
ofSetLineWidth(1);
ofRect(0, 0, chSz, 200);
ofSetColor(ofColor::orange);
ofSetLineWidth(3);
ofBeginShape();
for (int i = 0; i < bufferSize; i++){
ofVertex(i/(bufferSize/chSz), 100 - filterBank.getRightBuffer()[i]*45);
}
ofEndShape(false);
ofPopMatrix();
ofPopStyle();
}
//Draw FilterBank
{
ofPushStyle();
ofPushMatrix();
ofTranslate (100,250,0);
filterBank.draw(800,400);
ofPopMatrix();
ofPopStyle();
}
ofSetColor(225);
string reportString = "Sampling Rate: "+ ofToString(SR) +"\nBuffer size: "+ ofToString(bufferSize);
ofDrawBitmapString(reportString, 10, 700);
}
//--------------------------------------------------------------
void ofApp::audioIn(ofSoundBuffer &inBuffer){
//ANALYZE SOUNDBUFFER:
audioAnalyzer.analyze(inBuffer);
//Analyze Input Buffer with ofxFilterbank
vector <float> temp;
temp = inBuffer.getBuffer();
float *p = &temp[0];
filterBank.analyze(p);
int inChannels=2;
//Aubio
// compute onset detection
onset.audioIn(p, bufferSize, inChannels);
// compute pitch detection
pitch.audioIn(p, bufferSize, inChannels);
// compute beat location
beat.audioIn(p, bufferSize, inChannels);
// compute bands
bands.audioIn(p, bufferSize, inChannels);
}
//--------------------------------------------------------------
void ofApp::exit(){
ofSoundStreamStop();
audioAnalyzer.exit();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
//==========Aubio
//----
void ofApp::onsetEvent(float & time) {
//ofLog() << "got onset at " << time << " s";
gotOnset = true;
}
//----
void ofApp::beatEvent(float & time) {
//ofLog() << "got beat at " << time << " s";
gotBeat = true;
}
<|endoftext|>
|
<commit_before>#include <algorithm>
#include <iostream>
#include <sstream>
#include <iomanip>
#include "antsUtilities.h"
#include <algorithm>
#include "itkTransform.h"
#include "itkCompositeTransform.h"
#include "itkDisplacementFieldTransform.h"
#include "antsCommandLineParser.h"
#include "itkantsReadWriteTransform.h"
#include "itkTransformFactory.h"
namespace ants
{
static bool MatOffRegistered[2] = { false, false };
template <unsigned int VImageDimension>
void RegisterMatOff()
{
if( !MatOffRegistered[VImageDimension - 2] )
{
MatOffRegistered[VImageDimension - 2] = true;
// Register the matrix offset transform base class to the
// transform factory for compatibility with the current ANTs.
typedef itk::MatrixOffsetTransformBase<double, VImageDimension,
VImageDimension> MatrixOffsetTransformType;
itk::TransformFactory<MatrixOffsetTransformType>::RegisterTransform();
}
}
/**
* print the usage and exit
*/
void PrintGenericUsageStatement()
{
antscout << "Usage: CompositeTransformUtil --disassemble <CompositeTransform FileName>"
<< " <transform name prefix>" << std::endl
<< "or" << std::endl
<< "CompositeTransformUtil --assemble <CompositeTransform> "
<< "<transform 1> <transform 2 > ... <transform N>" << std::endl;
}
/**
* given a composite transform, write out all its component
* transforms.
*/
template <unsigned int VImageDimension>
int
Disassemble(itk::TransformBase *transform, const std::string & transformName, const std::string & prefix)
{
typedef itk::CompositeTransform<double, VImageDimension> CompositeTransformType;
typedef typename CompositeTransformType::TransformTypePointer TransformPointer;
typedef typename itk::DisplacementFieldTransform<double, VImageDimension> DisplacementFieldTransformType;
typedef typename DisplacementFieldTransformType::DisplacementFieldType DisplacementFieldType;
CompositeTransformType *composite = dynamic_cast<CompositeTransformType *>(transform);
if( composite == 0 )
{
antscout << "Transform File " << transformName << " is a "
<< transform->GetNameOfClass() << " not a Composite Transform."
<< std::endl;
return EXIT_FAILURE;
}
const unsigned int numTransforms = composite->GetNumberOfTransforms();
for( unsigned int i = 0; i < numTransforms; ++i )
{
TransformPointer curXfrm = composite->GetNthTransform(i);
DisplacementFieldTransformType *dispXfrm =
dynamic_cast<DisplacementFieldTransformType *>(curXfrm.GetPointer() );
std::stringstream fname;
fname << std::setfill('0') << std::setw(2) << i
<< "_" << prefix << "_"
<< curXfrm->GetNameOfClass();
if( dispXfrm != 0 )
{
fname << ".nii.gz"; // if it's a displacement field transform
}
else
{
fname << ".txt";
}
itk::ants::WriteTransform<VImageDimension>(curXfrm, fname.str() );
}
return EXIT_SUCCESS;
}
int Disassemble(const std::string & CompositeName,
const std::string & Prefix)
{
itk::TransformBase::Pointer transform = itk::ants::ReadTransform<2>(CompositeName).GetPointer();
if( transform.IsNull() )
{
transform = itk::ants::ReadTransform<3>(CompositeName).GetPointer();
if( transform.IsNull() )
{
return EXIT_FAILURE; // ReadTransform prints error messages on
// failure.
}
}
const unsigned int inDim(transform->GetInputSpaceDimension() );
const unsigned int outDim(transform->GetOutputSpaceDimension() );
if( inDim != outDim )
{
antscout << "Can't handle mixed input & output dimension: input("
<< inDim << ") output (" << outDim << ")" << std::endl;
return EXIT_FAILURE;
}
switch( inDim )
{
case 2:
return Disassemble<2>(transform, CompositeName, Prefix);
case 3:
return Disassemble<3>(transform, CompositeName, Prefix);
default:
antscout << "Unknown dimension " << inDim << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
template <unsigned int VImageDimension>
int
Assemble(const std::string & CompositeName,
const std::vector<std::string> & transformNames,
typename itk::CompositeTransform<double, VImageDimension>::TransformType::Pointer & firstTransform)
{
typedef itk::CompositeTransform<double, VImageDimension> CompositeTransformType;
typedef typename CompositeTransformType::TransformType TransformType;
typename CompositeTransformType::Pointer composite = CompositeTransformType::New();
composite->AddTransform(firstTransform);
for( unsigned int i = 1; i < transformNames.size(); ++i )
{
typename TransformType::Pointer curXfrm = itk::ants::ReadTransform<VImageDimension>(transformNames[i]);
if( curXfrm.IsNull() )
{
return EXIT_FAILURE; // ReadTransform will complain if anything goes wrong.
}
composite->AddTransform(curXfrm);
}
typename TransformType::Pointer genericXfrmPtr = composite.GetPointer();
return itk::ants::WriteTransform<VImageDimension>(genericXfrmPtr, CompositeName);
}
int Assemble(const std::string & CompositeName,
const std::vector<std::string> & transformNames)
{
typedef itk::CompositeTransform<double, 2>::TransformType Transform2DType;
typedef itk::CompositeTransform<double, 3>::TransformType Transform3DType;
Transform2DType::Pointer transform2D = itk::ants::ReadTransform<2>(transformNames[0]);
if( transform2D.IsNotNull() )
{
return Assemble<2>(CompositeName, transformNames, transform2D);
}
Transform3DType::Pointer transform3D = itk::ants::ReadTransform<3>(transformNames[0]);
if( transform3D.IsNotNull() )
{
return Assemble<3>(CompositeName, transformNames, transform3D);
}
return EXIT_FAILURE;
}
// entry point for the library; parameter 'args' is equivalent to 'argv' in (argc,argv) of commandline parameters to
// 'main()'
int CompositeTransformUtil( std::vector<std::string> args, std::ostream* out_stream = NULL )
{
// put the arguments coming in as 'args' into standard (argc,argv) format;
// 'args' doesn't have the command name as first, argument, so add it manually;
// 'args' may have adjacent arguments concatenated into one argument,
// which the parser should handle
args.insert( args.begin(), "CompositeTransformUtil" );
std::remove( args.begin(), args.end(), std::string( "" ) );
std::remove( args.begin(), args.end(), std::string( "" ) );
int argc = args.size();
char* * argv = new char *[args.size() + 1];
for( unsigned int i = 0; i < args.size(); ++i )
{
// allocate space for the string plus a null character
argv[i] = new char[args[i].length() + 1];
std::strncpy( argv[i], args[i].c_str(), args[i].length() );
// place the null character in the end
argv[i][args[i].length()] = '\0';
}
argv[argc] = 0;
// class to automatically cleanup argv upon destruction
class Cleanup_argv
{
public:
Cleanup_argv( char* * argv_, int argc_plus_one_ ) : argv( argv_ ), argc_plus_one( argc_plus_one_ )
{
}
~Cleanup_argv()
{
for( unsigned int i = 0; i < argc_plus_one; ++i )
{
delete[] argv[i];
}
delete[] argv;
}
private:
char* * argv;
unsigned int argc_plus_one;
};
Cleanup_argv cleanup_argv( argv, argc + 1 );
antscout->set_stream( out_stream );
if( argc >= 2 && ( std::string( argv[1] ) == std::string("--help") || std::string( argv[1] ) == std::string("-h") ) )
{
PrintGenericUsageStatement();
return EXIT_SUCCESS;
}
if( argc < 2 )
{
PrintGenericUsageStatement();
return EXIT_FAILURE;
}
++argv; --argc;
std::string action(*argv);
++argv; --argc;
if( argc == 0 )
{
antscout << "Missing CompositeTransformName" << std::endl;
PrintGenericUsageStatement();
return EXIT_FAILURE;
}
RegisterMatOff<2>();
RegisterMatOff<3>();
std::string CompositeName(*argv);
++argv; --argc;
if( action == "--disassemble" )
{
if( argc == 0 )
{
antscout << "Missing output transforms prefix" << std::endl;
PrintGenericUsageStatement();
return EXIT_FAILURE;
}
std::string Prefix(*argv);
return Disassemble(CompositeName, Prefix);
}
else if( action != "--assemble" )
{
antscout << "Unknown action " << action << std::endl;
PrintGenericUsageStatement();
return EXIT_FAILURE;
}
std::vector<std::string> transformNames;
while( argc > 0 )
{
std::string transformName(*argv);
++argv; --argc;
transformNames.push_back(transformName);
}
if( transformNames.size() < 1 )
{
antscout << "Missing transform names to "
<< "assemble into a composite transform"
<< std::endl;
PrintGenericUsageStatement();
return EXIT_FAILURE;
}
return Assemble(CompositeName, transformNames);
}
} // namespace ants
<commit_msg>BUG: Logic for composing transforms<commit_after>#include <algorithm>
#include <iostream>
#include <sstream>
#include <iomanip>
#include "antsUtilities.h"
#include <algorithm>
#include "itkTransform.h"
#include "itkCompositeTransform.h"
#include "itkDisplacementFieldTransform.h"
#include "antsCommandLineParser.h"
#include "itkantsReadWriteTransform.h"
#include "itkTransformFactory.h"
namespace ants
{
static bool MatOffRegistered[2] = { false, false };
template <unsigned int VImageDimension>
void RegisterMatOff()
{
if( !MatOffRegistered[VImageDimension - 2] )
{
MatOffRegistered[VImageDimension - 2] = true;
// Register the matrix offset transform base class to the
// transform factory for compatibility with the current ANTs.
typedef itk::MatrixOffsetTransformBase<double, VImageDimension,
VImageDimension> MatrixOffsetTransformType;
itk::TransformFactory<MatrixOffsetTransformType>::RegisterTransform();
}
}
/**
* print the usage and exit
*/
static void PrintGenericUsageStatement()
{
antscout << "Usage: CompositeTransformUtil --disassemble <CompositeTransform FileName>"
<< " <transform name prefix>" << std::endl
<< "or" << std::endl
<< "CompositeTransformUtil --assemble <CompositeTransform> "
<< "<transform 1> <transform 2 > ... <transform N>" << std::endl;
}
/**
* given a composite transform, write out all its component
* transforms.
*/
template <unsigned int VImageDimension>
int
Disassemble(itk::TransformBase *transform, const std::string & transformName, const std::string & prefix)
{
typedef itk::CompositeTransform<double, VImageDimension> CompositeTransformType;
typedef typename CompositeTransformType::TransformTypePointer TransformPointer;
typedef typename itk::DisplacementFieldTransform<double, VImageDimension> DisplacementFieldTransformType;
typedef typename DisplacementFieldTransformType::DisplacementFieldType DisplacementFieldType;
CompositeTransformType *composite = dynamic_cast<CompositeTransformType *>(transform);
if( composite == 0 )
{
antscout << "Transform File " << transformName << " is a "
<< transform->GetNameOfClass() << " not a Composite Transform."
<< std::endl;
return EXIT_FAILURE;
}
const unsigned int numTransforms = composite->GetNumberOfTransforms();
for( unsigned int i = 0; i < numTransforms; ++i )
{
TransformPointer curXfrm = composite->GetNthTransform(i);
DisplacementFieldTransformType *dispXfrm =
dynamic_cast<DisplacementFieldTransformType *>(curXfrm.GetPointer() );
std::stringstream fname;
fname << std::setfill('0') << std::setw(2) << i
<< "_" << prefix << "_"
<< curXfrm->GetNameOfClass();
if( dispXfrm != 0 )
{
fname << ".nii.gz"; // if it's a displacement field transform
}
else
{
fname << ".mat"; // .txt does not have enough precision!
}
itk::ants::WriteTransform<VImageDimension>(curXfrm, fname.str() );
}
return EXIT_SUCCESS;
}
static int Disassemble(const std::string & CompositeName,
const std::string & Prefix)
{
itk::TransformBase::Pointer transform = itk::ants::ReadTransform<2>(CompositeName).GetPointer();
if( transform.IsNull() )
{
transform = itk::ants::ReadTransform<3>(CompositeName).GetPointer();
if( transform.IsNull() )
{
return EXIT_FAILURE; // ReadTransform prints error messages on
// failure.
}
}
const unsigned int inDim(transform->GetInputSpaceDimension() );
const unsigned int outDim(transform->GetOutputSpaceDimension() );
if( inDim != outDim )
{
antscout << "Can't handle mixed input & output dimension: input("
<< inDim << ") output (" << outDim << ")" << std::endl;
return EXIT_FAILURE;
}
switch( inDim )
{
case 2:
return Disassemble<2>(transform, CompositeName, Prefix);
case 3:
return Disassemble<3>(transform, CompositeName, Prefix);
default:
antscout << "Unknown dimension " << inDim << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
template <unsigned int VImageDimension>
int
Assemble(const std::string & CompositeName,
const std::vector<std::string> & transformNames,
const typename itk::Transform<double, VImageDimension, VImageDimension>::Pointer & firstTransform)
{
typedef itk::CompositeTransform<double, VImageDimension> CompositeTransformType;
typedef typename CompositeTransformType::TransformType TransformType;
typename CompositeTransformType::Pointer composite = CompositeTransformType::New();
composite->AddTransform(firstTransform);
for( unsigned int i = 1; i < transformNames.size(); ++i )
{
typename TransformType::Pointer curXfrm = itk::ants::ReadTransform<VImageDimension>(transformNames[i]);
if( curXfrm.IsNull() )
{
return EXIT_FAILURE; // ReadTransform will complain if anything goes wrong.
}
composite->AddTransform(curXfrm);
}
typename TransformType::Pointer genericXfrmPtr = composite.GetPointer();
return itk::ants::WriteTransform<VImageDimension>(genericXfrmPtr, CompositeName);
}
static int Assemble(const std::string & CompositeName,
const std::vector<std::string> & transformNames)
{
{
itk::Transform<double, 2, 2>::Pointer FirstTransform = itk::ants::ReadTransform<2>(transformNames[0]);
if( FirstTransform.IsNotNull() )
{
return Assemble<2>(CompositeName, transformNames, FirstTransform);
}
}
{
itk::Transform<double, 3, 3>::Pointer FirstTransform = itk::ants::ReadTransform<3>(transformNames[0]);
if( FirstTransform.IsNotNull() )
{
return Assemble<3>(CompositeName, transformNames, FirstTransform);
}
}
return EXIT_FAILURE;
}
// entry point for the library; parameter 'args' is equivalent to 'argv' in (argc,argv) of commandline parameters to
// 'main()'
int CompositeTransformUtil( std::vector<std::string> args, std::ostream* out_stream = NULL )
{
// put the arguments coming in as 'args' into standard (argc,argv) format;
// 'args' doesn't have the command name as first, argument, so add it manually;
// 'args' may have adjacent arguments concatenated into one argument,
// which the parser should handle
args.insert( args.begin(), "CompositeTransformUtil" );
std::remove( args.begin(), args.end(), std::string( "" ) );
std::remove( args.begin(), args.end(), std::string( "" ) );
unsigned int argc = args.size();
char* * argv = new char *[argc + 1];
for( unsigned int i = 0; i < argc; ++i )
{
// allocate space for the string plus a null character
argv[i] = new char[args[i].length() + 1];
std::strncpy( argv[i], args[i].c_str(), args[i].length() );
// place the null character in the end
argv[i][args[i].length()] = '\0';
}
argv[argc] = 0;
// class to automatically cleanup argv upon destruction
class Cleanup_argv
{
public:
Cleanup_argv( char* * argv_, int argc_plus_one_ ) : argv( argv_ ), argc_plus_one( argc_plus_one_ )
{
}
~Cleanup_argv()
{
for( unsigned int i = 0; i < argc_plus_one; ++i )
{
delete[] argv[i];
}
delete[] argv;
}
private:
char* * argv;
unsigned int argc_plus_one;
};
Cleanup_argv cleanup_argv( argv, argc + 1 );
antscout->set_stream( out_stream );
if( argc >= 2 && ( std::string( argv[1] ) == std::string("--help") || std::string( argv[1] ) == std::string("-h") ) )
{
PrintGenericUsageStatement();
return EXIT_SUCCESS;
}
if( argc < 2 )
{
PrintGenericUsageStatement();
return EXIT_FAILURE;
}
++argv; --argc;
std::string action(*argv);
++argv; --argc;
if( argc == 0 )
{
antscout << "Missing CompositeTransformName" << std::endl;
PrintGenericUsageStatement();
return EXIT_FAILURE;
}
RegisterMatOff<2>();
RegisterMatOff<3>();
std::string CompositeName(*argv);
++argv; --argc;
if( action == "--disassemble" )
{
if( argc == 0 )
{
antscout << "Missing output transforms prefix" << std::endl;
PrintGenericUsageStatement();
return EXIT_FAILURE;
}
std::string Prefix(*argv);
return Disassemble(CompositeName, Prefix);
}
else if( action != "--assemble" )
{
antscout << "Unknown action " << action << std::endl;
PrintGenericUsageStatement();
return EXIT_FAILURE;
}
std::vector<std::string> transformNames;
do
{
std::string transformName(*argv);
++argv; --argc;
transformNames.push_back(transformName);
}
while( argc != 0 );
if( transformNames.size() < 1 )
{
antscout << "Missing transform names to "
<< "assemble into a composite transform"
<< std::endl;
PrintGenericUsageStatement();
return EXIT_FAILURE;
}
return Assemble(CompositeName, transformNames);
}
} // namespace ants
<|endoftext|>
|
<commit_before>/*
*
* Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved.
*
* 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.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* 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
*
* Contact information: MeVis Medical Solutions AG, Universitaetsallee 29,
* 28359 Bremen, Germany or:
*
* http://www.mevis.de
*
*/
#include "PythonQt_QtAll.h"
#include "PythonQt.h"
void PythonQt_init_QtGui(PyObject*);
void PythonQt_init_QtSvg(PyObject*);
void PythonQt_init_QtSql(PyObject*);
void PythonQt_init_QtNetwork(PyObject*);
void PythonQt_init_QtCore(PyObject*);
void PythonQt_init_QtWebKit(PyObject*);
void PythonQt_init_QtOpenGL(PyObject*);
void PythonQt_init_QtXml(PyObject*);
void PythonQt_init_QtXmlPatterns(PyObject*);
void PythonQt_init_QtUiTools(PyObject*);
void PythonQt_init_QtPhonon(PyObject*);
namespace PythonQt_QtAll
{
PYTHONQT_QTALL_EXPORT void init() {
PythonQt_init_QtCore(0);
PythonQt_init_QtNetwork(0);
PythonQt_init_QtGui(0);
PythonQt_init_QtXml(0);
PythonQt_init_QtSvg(0);
PythonQt_init_QtSql(0);
PythonQt_init_QtWebKit(0);
PythonQt_init_QtOpenGL(0);
PythonQt_init_QtUiTools(0);
// Does not compile yet:
// PythonQt_init_QtXmlPatterns(0);
// PythonQt_init_QtPhonon(0);
};
};
<commit_msg>removed phonon and xmlpatterns, which never worked<commit_after>/*
*
* Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved.
*
* 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.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* 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
*
* Contact information: MeVis Medical Solutions AG, Universitaetsallee 29,
* 28359 Bremen, Germany or:
*
* http://www.mevis.de
*
*/
#include "PythonQt_QtAll.h"
#include "PythonQt.h"
void PythonQt_init_QtGui(PyObject*);
void PythonQt_init_QtSvg(PyObject*);
void PythonQt_init_QtSql(PyObject*);
void PythonQt_init_QtNetwork(PyObject*);
void PythonQt_init_QtCore(PyObject*);
void PythonQt_init_QtWebKit(PyObject*);
void PythonQt_init_QtOpenGL(PyObject*);
void PythonQt_init_QtXml(PyObject*);
void PythonQt_init_QtUiTools(PyObject*);
namespace PythonQt_QtAll
{
PYTHONQT_QTALL_EXPORT void init() {
PythonQt_init_QtCore(0);
PythonQt_init_QtNetwork(0);
PythonQt_init_QtGui(0);
PythonQt_init_QtXml(0);
PythonQt_init_QtSvg(0);
PythonQt_init_QtSql(0);
PythonQt_init_QtWebKit(0);
PythonQt_init_QtOpenGL(0);
PythonQt_init_QtUiTools(0);
};
};
<|endoftext|>
|
<commit_before>#ifndef ALIGNED_BASE_HPP_INCLUDED
#define ALIGNED_BASE_HPP_INCLUDED
#include <cstddef>
#include <exception>
#include "RoundUp.hpp"
#include "IsPowerOfTwo.hpp"
#define ALIGNMENT_MUST_BE_A_POWER_OF_2_ERROR_MESSAGE "Alignment must be a power of 2"
template<typename T, std::size_t Alignment = -1>
class AlignedBase {
static_assert(IsPowerOfTwo<std::size_t, Alignment>::Result, ALIGNMENT_MUST_BE_A_POWER_OF_2_ERROR_MESSAGE);
protected:
static const std::size_t sizeOfTPaddedToAlignment = RoundUp<std::size_t, sizeof(T), Alignment>::Result;
};
template<typename T>
class AlignedBase<T, -1> {
public:
class AlignmentException : public std::exception {
friend class AlignedBase<T, -1>;
AlignmentException() : std::exception(ALIGNMENT_MUST_BE_A_POWER_OF_2_ERROR_MESSAGE) {}
};
AlignedBase & operator=(AlignedBase const &) = delete;
protected:
std::size_t const sizeOfTPaddedToAlignment;
AlignedBase(std::size_t alignment) : sizeOfTPaddedToAlignment(roundUp(sizeof(T), alignment)) {
if (!isPowerOfTwo(alignment))
throw new AlignmentException();
}
};
#undef ALIGNMENT_MUST_BE_A_MULTIPLE_OF_2
#endif<commit_msg>undef typo<commit_after>#ifndef ALIGNED_BASE_HPP_INCLUDED
#define ALIGNED_BASE_HPP_INCLUDED
#include <cstddef>
#include <exception>
#include "RoundUp.hpp"
#include "IsPowerOfTwo.hpp"
#define ALIGNMENT_MUST_BE_A_POWER_OF_2_ERROR_MESSAGE "Alignment must be a power of 2"
template<typename T, std::size_t Alignment = -1>
class AlignedBase {
static_assert(IsPowerOfTwo<std::size_t, Alignment>::Result, ALIGNMENT_MUST_BE_A_POWER_OF_2_ERROR_MESSAGE);
protected:
static const std::size_t sizeOfTPaddedToAlignment = RoundUp<std::size_t, sizeof(T), Alignment>::Result;
};
template<typename T>
class AlignedBase<T, -1> {
public:
class AlignmentException : public std::exception {
friend class AlignedBase<T, -1>;
AlignmentException() : std::exception(ALIGNMENT_MUST_BE_A_POWER_OF_2_ERROR_MESSAGE) {}
};
AlignedBase & operator=(AlignedBase const &) = delete;
protected:
std::size_t const sizeOfTPaddedToAlignment;
AlignedBase(std::size_t alignment) : sizeOfTPaddedToAlignment(roundUp(sizeof(T), alignment)) {
if (!isPowerOfTwo(alignment))
throw new AlignmentException();
}
};
#undef ALIGNMENT_MUST_BE_A_POWER_OF_2_ERROR_MESSAGE
#endif<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: $RCSfile: MeasureImageSimilarity.cxx,v $
Language: C++
Date: $Date: 2009/01/05 20:09:47 $
Version: $Revision: 1.19 $
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "ReadWriteImage.h"
#include "itkDiscreteGaussianImageFilter.h"
#include "itkAvantsMutualInformationRegistrationFunction.h"
#include "itkProbabilisticRegistrationFunction.h"
#include "itkCrossCorrelationRegistrationFunction.h"
// #include "itkLandmarkCrossCorrelationRegistrationFunction.h"
template <unsigned int ImageDimension>
int MeasureImageSimilarity(unsigned int argc, char *argv[])
{
typedef float PixelType;
typedef itk::Vector<float,ImageDimension> VectorType;
typedef itk::Image<VectorType,ImageDimension> FieldType;
typedef itk::Image<PixelType,ImageDimension> ImageType;
typedef itk::ImageFileWriter<ImageType> writertype;
typedef typename ImageType::IndexType IndexType;
typedef typename ImageType::SizeType SizeType;
typedef typename ImageType::SpacingType SpacingType;
typedef itk::AffineTransform<double,ImageDimension> AffineTransformType;
typedef itk::LinearInterpolateImageFunction<ImageType,double> InterpolatorType1;
typedef itk::ImageRegionIteratorWithIndex<ImageType> Iterator;
typedef itk::Image<float,2> JointHistType;
typedef itk::ImageFileWriter<JointHistType> jhwritertype;
// get command line params
unsigned int argct=2;
unsigned int whichmetric = atoi(argv[argct]); argct++;
std::string fn1 = std::string(argv[argct]); argct++;
std::string fn2 = std::string(argv[argct]); argct++;
std::string logfilename="";
if (argc > argct) logfilename = std::string(argv[argct]); argct++;
std::string imgfilename="";
if (argc > argct) imgfilename = std::string(argv[argct]); argct++;
double targetvalue=0;
if (argc > argct) targetvalue = atof(argv[argct]); argct++;
double epsilontolerance=1.e20;
if (argc > argct) epsilontolerance = atof(argv[argct]); argct++;
typename ImageType::Pointer image1 = NULL;
ReadImage<ImageType>(image1, fn1.c_str());
typename ImageType::Pointer image2 = NULL;
ReadImage<ImageType>(image2, fn2.c_str());
/*
typedef itk::ImageRegionIteratorWithIndex<FieldType> VIterator;
typename FieldType::Pointer field=FieldType::New();
field->SetLargestPossibleRegion( image1->GetLargestPossibleRegion() );
field->SetBufferedRegion( image1->GetLargestPossibleRegion() );
field->SetLargestPossibleRegion( image1->GetLargestPossibleRegion() );
field->Allocate();
field->SetSpacing(image1->GetSpacing());
field->SetOrigin(image1->GetOrigin());
VectorType zero;
zero.Fill(0);
VIterator vfIter2( field, field->GetLargestPossibleRegion() );
for( vfIter2.GoToBegin(); !vfIter2.IsAtEnd(); ++vfIter2 )
{
IndexType index=vfIter2.GetIndex();
vfIter2.Set(zero);
}
*/
typename ImageType::Pointer metricimg=ImageType::New();
metricimg->SetRegions( image1->GetLargestPossibleRegion() );
metricimg->Allocate();
metricimg->SetSpacing(image1->GetSpacing());
metricimg->SetOrigin(image1->GetOrigin());
metricimg->SetDirection(image1->GetDirection());
Iterator iter( metricimg, metricimg->GetLargestPossibleRegion() );
for( iter.GoToBegin(); !iter.IsAtEnd(); ++iter ) iter.Set(0);
typedef ImageType FixedImageType;
typedef ImageType MovingImageType;
typedef FieldType DeformationFieldType;
// Choose the similarity metric
typedef itk::AvantsMutualInformationRegistrationFunction<FixedImageType,MovingImageType,DeformationFieldType> MIMetricType;
typedef itk::CrossCorrelationRegistrationFunction<FixedImageType,MovingImageType,DeformationFieldType> CCMetricType;
//typedef itk::LandmarkCrossCorrelationRegistrationFunction<FixedImageType,MovingImageType,DeformationFieldType> MetricType;
//typename
typename MIMetricType::Pointer mimet=MIMetricType::New();
typename CCMetricType::Pointer ccmet=CCMetricType::New();
// int nbins=32;
typename CCMetricType::RadiusType hradius;
typename CCMetricType::RadiusType ccradius;
ccradius.Fill(2);
typename MIMetricType::RadiusType miradius;
miradius.Fill(0);
// mimet->SetDeformationField(field);
mimet->SetFixedImage(image1);
mimet->SetMovingImage(image2);
mimet->SetRadius(miradius);
mimet->SetGradientStep(1.e2);
mimet->SetNormalizeGradient(false);
// ccmet->SetDeformationField(field);
ccmet->SetFixedImage(image1);
ccmet->SetMovingImage(image2);
ccmet->SetRadius(ccradius);
ccmet->SetGradientStep(1.e2);
ccmet->SetNormalizeGradient(false);
double metricvalue=0;
std::string metricname="";
if (whichmetric == 0)
{
hradius=miradius;
unsigned long ct = 0;
for( iter.GoToBegin(); !iter.IsAtEnd(); ++iter )
{
IndexType index=iter.GetIndex();
double fval=image1->GetPixel(index);
double mval=image2->GetPixel(index);
metricvalue+=fabs(fval-mval);
metricimg->SetPixel(index,fabs(fval-mval));
ct++;
}
metricvalue/=(float)ct;
metricname="MSQ ";
}
else if (whichmetric == 1 ) // imagedifference
{
hradius=ccradius;
metricname="CC ";
std::cout << metricname << std::endl;
ccmet->InitializeIteration();
metricvalue=ccmet->ComputeCrossCorrelation()*(-1.0);
}
else
{
hradius=miradius;
mimet->InitializeIteration();
metricvalue=mimet->ComputeMutualInformation();
metricname="MI ";
}
std::cout << fn1 << " : " << fn2 << " => " << metricname << metricvalue << std::endl;
if (logfilename.length() > 3 ){
std::ofstream logfile;
logfile.open(logfilename.c_str(), std::ofstream::app);
if (logfile.good())
{
logfile << fn1 << " : " << fn2 << " => " << metricname << metricvalue << std::endl;
}
else std::cout << " cant open file ";
logfile.close();
}
if (imgfilename.length() > 3 ){
std::cout << "Only Implemented for MSQ " << std::endl;
typedef itk::ImageFileWriter<ImageType> writertype;
typename writertype::Pointer w= writertype::New();
w->SetInput(metricimg);
w->SetFileName(imgfilename.c_str());
w->Write(); // met->WriteImages();
/*
typename MetricType::NeighborhoodType asamIt( hradius, field,field->GetLargestPossibleRegion());
unsigned long ct = 0;
double totval = 0;
for( vfIter2.GoToBegin(); !vfIter2.IsAtEnd(); ++vfIter2 )
{
IndexType index=vfIter2.GetIndex();
double val=0;
asamIt.SetLocation(index);
// met->ComputeUpdate( asamIt, gd);
met->ComputeMetricAtPairB(index, zero);
metricimg->SetPixel(index, val);
//if (ct % 10000 == 0)
// std::cout << val << " index " << index << std::endl;
// asamIt.SetLocation(index);
// totval+=met->localProbabilistic;
ct++;
}
std::cout << " AvantsMI : " << totval/(double)ct << " E " << met->GetEnergy() << std::endl;
std::cout << " write begin " << std::endl;
std::cout << " write end " << std::endl;
*/
}
double diff = ((double)metricvalue - (double) targetvalue);
std::cout << " targetvalue " << targetvalue << " metricvalue " << metricvalue << " diff " << diff << " toler " << epsilontolerance << std::endl;
if ( diff < epsilontolerance) return EXIT_SUCCESS;
else return EXIT_FAILURE;
}
int main(int argc, char *argv[])
{
if ( argc < 3 )
{ std::cout << "Basic useage ex: " << std::endl;
std::cout << argv[0] << " ImageDimension whichmetric image1.ext image2.ext {logfile} {outimage.ext} {target-value} {epsilon-tolerance}" << std::endl;
std::cout << " outimage (Not Implemented) and logfile are optional " << std::endl;
std::cout <<" target-value and epsilon-tolerance set goals for the metric value -- if the metric value is within epsilon-tolerance of the target-value, then the test succeeds " << std::endl;
std::cout << " Metric 0 - MeanSquareDifference, 1 - Cross-Correlation, 2-Mutual Information " << std::endl;
return 1;
}
int metricsuccess=EXIT_FAILURE;
// Get the image dimension
switch( atoi(argv[1]))
{
case 2:
metricsuccess=MeasureImageSimilarity<2>(argc,argv);
break;
case 3:
metricsuccess=MeasureImageSimilarity<3>(argc,argv);
break;
default:
std::cerr << "Unsupported dimension" << std::endl;
exit( EXIT_FAILURE );
}
std::cout << " Failure? " << metricsuccess << std::endl;
return metricsuccess;
}
<commit_msg> neg value in CC metric <commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: $RCSfile: MeasureImageSimilarity.cxx,v $
Language: C++
Date: $Date: 2009/01/05 20:09:47 $
Version: $Revision: 1.19 $
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "ReadWriteImage.h"
#include "itkDiscreteGaussianImageFilter.h"
#include "itkAvantsMutualInformationRegistrationFunction.h"
#include "itkProbabilisticRegistrationFunction.h"
#include "itkCrossCorrelationRegistrationFunction.h"
// #include "itkLandmarkCrossCorrelationRegistrationFunction.h"
template <unsigned int ImageDimension>
int MeasureImageSimilarity(unsigned int argc, char *argv[])
{
typedef float PixelType;
typedef itk::Vector<float,ImageDimension> VectorType;
typedef itk::Image<VectorType,ImageDimension> FieldType;
typedef itk::Image<PixelType,ImageDimension> ImageType;
typedef itk::ImageFileWriter<ImageType> writertype;
typedef typename ImageType::IndexType IndexType;
typedef typename ImageType::SizeType SizeType;
typedef typename ImageType::SpacingType SpacingType;
typedef itk::AffineTransform<double,ImageDimension> AffineTransformType;
typedef itk::LinearInterpolateImageFunction<ImageType,double> InterpolatorType1;
typedef itk::ImageRegionIteratorWithIndex<ImageType> Iterator;
typedef itk::Image<float,2> JointHistType;
typedef itk::ImageFileWriter<JointHistType> jhwritertype;
// get command line params
unsigned int argct=2;
unsigned int whichmetric = atoi(argv[argct]); argct++;
std::string fn1 = std::string(argv[argct]); argct++;
std::string fn2 = std::string(argv[argct]); argct++;
std::string logfilename="";
if (argc > argct) logfilename = std::string(argv[argct]); argct++;
std::string imgfilename="";
if (argc > argct) imgfilename = std::string(argv[argct]); argct++;
double targetvalue=0;
if (argc > argct) targetvalue = atof(argv[argct]); argct++;
double epsilontolerance=1.e20;
if (argc > argct) epsilontolerance = atof(argv[argct]); argct++;
typename ImageType::Pointer image1 = NULL;
ReadImage<ImageType>(image1, fn1.c_str());
typename ImageType::Pointer image2 = NULL;
ReadImage<ImageType>(image2, fn2.c_str());
/*
typedef itk::ImageRegionIteratorWithIndex<FieldType> VIterator;
typename FieldType::Pointer field=FieldType::New();
field->SetLargestPossibleRegion( image1->GetLargestPossibleRegion() );
field->SetBufferedRegion( image1->GetLargestPossibleRegion() );
field->SetLargestPossibleRegion( image1->GetLargestPossibleRegion() );
field->Allocate();
field->SetSpacing(image1->GetSpacing());
field->SetOrigin(image1->GetOrigin());
VectorType zero;
zero.Fill(0);
VIterator vfIter2( field, field->GetLargestPossibleRegion() );
for( vfIter2.GoToBegin(); !vfIter2.IsAtEnd(); ++vfIter2 )
{
IndexType index=vfIter2.GetIndex();
vfIter2.Set(zero);
}
*/
typename ImageType::Pointer metricimg=ImageType::New();
metricimg->SetRegions( image1->GetLargestPossibleRegion() );
metricimg->Allocate();
metricimg->SetSpacing(image1->GetSpacing());
metricimg->SetOrigin(image1->GetOrigin());
metricimg->SetDirection(image1->GetDirection());
Iterator iter( metricimg, metricimg->GetLargestPossibleRegion() );
for( iter.GoToBegin(); !iter.IsAtEnd(); ++iter ) iter.Set(0);
typedef ImageType FixedImageType;
typedef ImageType MovingImageType;
typedef FieldType DeformationFieldType;
// Choose the similarity metric
typedef itk::AvantsMutualInformationRegistrationFunction<FixedImageType,MovingImageType,DeformationFieldType> MIMetricType;
typedef itk::CrossCorrelationRegistrationFunction<FixedImageType,MovingImageType,DeformationFieldType> CCMetricType;
//typedef itk::LandmarkCrossCorrelationRegistrationFunction<FixedImageType,MovingImageType,DeformationFieldType> MetricType;
//typename
typename MIMetricType::Pointer mimet=MIMetricType::New();
typename CCMetricType::Pointer ccmet=CCMetricType::New();
// int nbins=32;
typename CCMetricType::RadiusType hradius;
typename CCMetricType::RadiusType ccradius;
ccradius.Fill(2);
typename MIMetricType::RadiusType miradius;
miradius.Fill(0);
// mimet->SetDeformationField(field);
mimet->SetFixedImage(image1);
mimet->SetMovingImage(image2);
mimet->SetRadius(miradius);
mimet->SetGradientStep(1.e2);
mimet->SetNormalizeGradient(false);
// ccmet->SetDeformationField(field);
ccmet->SetFixedImage(image1);
ccmet->SetMovingImage(image2);
ccmet->SetRadius(ccradius);
ccmet->SetGradientStep(1.e2);
ccmet->SetNormalizeGradient(false);
double metricvalue=0;
std::string metricname="";
if (whichmetric == 0)
{
hradius=miradius;
unsigned long ct = 0;
for( iter.GoToBegin(); !iter.IsAtEnd(); ++iter )
{
IndexType index=iter.GetIndex();
double fval=image1->GetPixel(index);
double mval=image2->GetPixel(index);
metricvalue+=fabs(fval-mval);
metricimg->SetPixel(index,fabs(fval-mval));
ct++;
}
metricvalue/=(float)ct;
metricname="MSQ ";
}
else if (whichmetric == 1 ) // imagedifference
{
hradius=ccradius;
metricname="CC ";
std::cout << metricname << std::endl;
ccmet->InitializeIteration();
metricvalue=ccmet->ComputeCrossCorrelation()*(1.0);
}
else
{
hradius=miradius;
mimet->InitializeIteration();
metricvalue=mimet->ComputeMutualInformation();
metricname="MI ";
}
std::cout << fn1 << " : " << fn2 << " => " << metricname << metricvalue << std::endl;
if (logfilename.length() > 3 ){
std::ofstream logfile;
logfile.open(logfilename.c_str(), std::ofstream::app);
if (logfile.good())
{
logfile << fn1 << " : " << fn2 << " => " << metricname << metricvalue << std::endl;
}
else std::cout << " cant open file ";
logfile.close();
}
if (imgfilename.length() > 3 ){
std::cout << "Only Implemented for MSQ " << std::endl;
typedef itk::ImageFileWriter<ImageType> writertype;
typename writertype::Pointer w= writertype::New();
w->SetInput(metricimg);
w->SetFileName(imgfilename.c_str());
w->Write(); // met->WriteImages();
/*
typename MetricType::NeighborhoodType asamIt( hradius, field,field->GetLargestPossibleRegion());
unsigned long ct = 0;
double totval = 0;
for( vfIter2.GoToBegin(); !vfIter2.IsAtEnd(); ++vfIter2 )
{
IndexType index=vfIter2.GetIndex();
double val=0;
asamIt.SetLocation(index);
// met->ComputeUpdate( asamIt, gd);
met->ComputeMetricAtPairB(index, zero);
metricimg->SetPixel(index, val);
//if (ct % 10000 == 0)
// std::cout << val << " index " << index << std::endl;
// asamIt.SetLocation(index);
// totval+=met->localProbabilistic;
ct++;
}
std::cout << " AvantsMI : " << totval/(double)ct << " E " << met->GetEnergy() << std::endl;
std::cout << " write begin " << std::endl;
std::cout << " write end " << std::endl;
*/
}
double diff = ((double)metricvalue - (double) targetvalue);
std::cout << " targetvalue " << targetvalue << " metricvalue " << metricvalue << " diff " << diff << " toler " << epsilontolerance << std::endl;
if ( diff < epsilontolerance) return EXIT_SUCCESS;
else return EXIT_FAILURE;
}
int main(int argc, char *argv[])
{
if ( argc < 3 )
{ std::cout << "Basic useage ex: " << std::endl;
std::cout << argv[0] << " ImageDimension whichmetric image1.ext image2.ext {logfile} {outimage.ext} {target-value} {epsilon-tolerance}" << std::endl;
std::cout << " outimage (Not Implemented) and logfile are optional " << std::endl;
std::cout <<" target-value and epsilon-tolerance set goals for the metric value -- if the metric value is within epsilon-tolerance of the target-value, then the test succeeds " << std::endl;
std::cout << " Metric 0 - MeanSquareDifference, 1 - Cross-Correlation, 2-Mutual Information " << std::endl;
return 1;
}
int metricsuccess=EXIT_FAILURE;
// Get the image dimension
switch( atoi(argv[1]))
{
case 2:
metricsuccess=MeasureImageSimilarity<2>(argc,argv);
break;
case 3:
metricsuccess=MeasureImageSimilarity<3>(argc,argv);
break;
default:
std::cerr << "Unsupported dimension" << std::endl;
exit( EXIT_FAILURE );
}
std::cout << " Failure? " << metricsuccess << std::endl;
return metricsuccess;
}
<|endoftext|>
|
<commit_before>/*
This file is part of the MinSG library extension LoaderCOLLADA.
Copyright (C) 2013 Benjamin Eikel <benjamin@eikel.org>
Copyright (C) 2012 Lukas Kopecki
This library is subject to the terms of the Mozilla Public License, v. 2.0.
You should have received a copy of the MPL along with this library; see the
file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#ifdef MINSG_EXT_LOADERCOLLADA
#include "LoaderCOLLADA.h"
#include "Writer.h"
#include "../../SceneManagement/SceneDescription.h"
#include <Util/IO/FileName.h>
COMPILER_WARN_PUSH
COMPILER_WARN_OFF_GCC(-Wold-style-cast)
COMPILER_WARN_OFF_GCC(-Wzero-as-null-pointer-constant)
COMPILER_WARN_OFF_GCC(-Wswitch-default)
COMPILER_WARN_OFF_CLANG(-W#warnings)
#include <COLLADASaxFWLIError.h>
#include <COLLADASaxFWLIErrorHandler.h>
#include <COLLADASaxFWLLoader.h>
#include <COLLADASaxFWLPrerequisites.h>
#include <COLLADAFWRoot.h>
COMPILER_WARN_POP
#include <string>
#include <functional>
#include <Util/Macros.h>
#include <Util/Timer.h>
namespace MinSG {
namespace LoaderCOLLADA {
class ErrorHandler : public COLLADASaxFWL::IErrorHandler {
private:
std::ostream & out;
public:
ErrorHandler(std::ostream & outStream) :
out(outStream) {
}
virtual ~ErrorHandler() {
}
bool handleError(const COLLADASaxFWL::IError * error) override {
switch(error->getSeverity()) {
case COLLADASaxFWL::IError::SEVERITY_CRITICAL:
out << "Critical";
break;
case COLLADASaxFWL::IError::SEVERITY_ERROR_NONCRITICAL:
out << "Non-critical";
break;
default:
break;
}
out << ' ';
switch(error->getErrorClass()) {
case COLLADASaxFWL::IError::ERROR_SAXPARSER:
out << "SaxParser";
break;
case COLLADASaxFWL::IError::ERROR_SAXFWL:
out << "SaxFWL";
break;
default:
out << "Unknown";
break;
}
out << error->getFullErrorMessage() << '\n';
// Continue loading.
return true;
}
};
static std::string getVersionString(const COLLADASaxFWL::COLLADAVersion & version) {
switch(version) {
case COLLADASaxFWL::COLLADAVersion::COLLADA_14:
return "1.4";
case COLLADASaxFWL::COLLADAVersion::COLLADA_15:
return "1.5";
case COLLADASaxFWL::COLLADAVersion::COLLADA_UNKNOWN:
default:
break;
}
return "Unknown";
}
const SceneManagement::DescriptionMap * loadScene(const Util::FileName & fileName, bool invertTransparency) {
Util::Timer timer;
timer.reset();
ErrorHandler errorHandler(std::cerr);
COLLADASaxFWL::Loader loader(&errorHandler);
Writer & writer = Writer::instance();
writer.beginLoadingProcess();
writer.setInvertTransparency(invertTransparency);
COLLADAFW::Root root(&loader, &writer);
const bool success = root.loadDocument(fileName.getPath());
if(!success) {
return nullptr;
}
timer.stop();
std::cout << "Loaded COLLADA " << getVersionString(loader.getCOLLADAVersion()) << " document in " << timer.getSeconds() << " seconds." << std::endl;
auto scene = writer.releaseSceneDescription();
writer.endLoadingProcess();
return scene;
}
}
}
#endif /* MINSG_EXT_LOADERCOLLADA */
<commit_msg>compile fix<commit_after>/*
This file is part of the MinSG library extension LoaderCOLLADA.
Copyright (C) 2013 Benjamin Eikel <benjamin@eikel.org>
Copyright (C) 2012 Lukas Kopecki
This library is subject to the terms of the Mozilla Public License, v. 2.0.
You should have received a copy of the MPL along with this library; see the
file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#ifdef MINSG_EXT_LOADERCOLLADA
#include <iostream>
#include "LoaderCOLLADA.h"
#include "Writer.h"
#include "../../SceneManagement/SceneDescription.h"
#include <Util/IO/FileName.h>
COMPILER_WARN_PUSH
COMPILER_WARN_OFF_GCC(-Wold-style-cast)
COMPILER_WARN_OFF_GCC(-Wzero-as-null-pointer-constant)
COMPILER_WARN_OFF_GCC(-Wswitch-default)
COMPILER_WARN_OFF_CLANG(-W#warnings)
#include <COLLADASaxFWLIError.h>
#include <COLLADASaxFWLIErrorHandler.h>
#include <COLLADASaxFWLLoader.h>
#include <COLLADASaxFWLPrerequisites.h>
#include <COLLADAFWRoot.h>
COMPILER_WARN_POP
#include <string>
#include <functional>
#include <Util/Macros.h>
#include <Util/Timer.h>
namespace MinSG {
namespace LoaderCOLLADA {
class ErrorHandler : public COLLADASaxFWL::IErrorHandler {
private:
std::ostream & out;
public:
ErrorHandler(std::ostream & outStream) :
out(outStream) {
}
virtual ~ErrorHandler() {
}
bool handleError(const COLLADASaxFWL::IError * error) override {
switch(error->getSeverity()) {
case COLLADASaxFWL::IError::SEVERITY_CRITICAL:
out << "Critical";
break;
case COLLADASaxFWL::IError::SEVERITY_ERROR_NONCRITICAL:
out << "Non-critical";
break;
default:
break;
}
out << ' ';
switch(error->getErrorClass()) {
case COLLADASaxFWL::IError::ERROR_SAXPARSER:
out << "SaxParser";
break;
case COLLADASaxFWL::IError::ERROR_SAXFWL:
out << "SaxFWL";
break;
default:
out << "Unknown";
break;
}
out << error->getFullErrorMessage() << '\n';
// Continue loading.
return true;
}
};
static std::string getVersionString(const COLLADASaxFWL::COLLADAVersion & version) {
switch(version) {
case COLLADASaxFWL::COLLADAVersion::COLLADA_14:
return "1.4";
case COLLADASaxFWL::COLLADAVersion::COLLADA_15:
return "1.5";
case COLLADASaxFWL::COLLADAVersion::COLLADA_UNKNOWN:
default:
break;
}
return "Unknown";
}
const SceneManagement::DescriptionMap * loadScene(const Util::FileName & fileName, bool invertTransparency) {
Util::Timer timer;
timer.reset();
ErrorHandler errorHandler(std::cerr);
COLLADASaxFWL::Loader loader(&errorHandler);
Writer & writer = Writer::instance();
writer.beginLoadingProcess();
writer.setInvertTransparency(invertTransparency);
COLLADAFW::Root root(&loader, &writer);
const bool success = root.loadDocument(fileName.getPath());
if(!success) {
return nullptr;
}
timer.stop();
std::cout << "Loaded COLLADA " << getVersionString(loader.getCOLLADAVersion()) << " document in " << timer.getSeconds() << " seconds." << std::endl;
auto scene = writer.releaseSceneDescription();
writer.endLoadingProcess();
return scene;
}
}
}
#endif /* MINSG_EXT_LOADERCOLLADA */
<|endoftext|>
|
<commit_before>/*!
* @file CurvatureFlow.cpp
* @brief Implementation of a curvature flow algorithm
*/
#include "CurvatureFlow.h"
namespace psalm
{
/*!
* Given an input mesh, calculates the curvature operator matrix for this
* mesh. The matrix will be a _sparse_ matrix, hence the need for handling
* it via boost.
*
* @param input_mesh Mesh to be processed
* @return Sparse matrix describing the curvature operator
*/
boost::numeric::ublas::mapped_matrix<double> CurvatureFlow::calc_curvature_operator(mesh& input_mesh)
{
using namespace boost::numeric::ublas;
mapped_matrix<double> K(input_mesh.num_vertices(), input_mesh.num_vertices()); // K as in "Kurvature"...
// We iterate over all faces and calculate the contributions of each
// vertex of the face to the corresponding entry of the matrix
for(size_t i = 0; i < input_mesh.num_faces(); i++)
{
face* f = input_mesh.get_face(i);
for(size_t j = 0; j < f->num_vertices(); j++)
{
vertex* v = f->get_vertex(j);
std::vector<const vertex*> neighbours = v->get_neighbours();
// FIXME: Used to update the correct matrix entries
// below. This assumes that the IDs have been allocated
// sequentially.
size_t cur_id = v->get_id();
// Find "opposing angles" for all neighbours; these are
// the $\alpha_{ij}$ and $\beta_{ij}$ values used for
// calculating the discrete curvature
for(size_t k = 0; k < neighbours.size(); k++)
{
std::pair<double, double> angles = v->find_opposite_angles(neighbours[k]);
if(angles.first >= 0.0 && angles.second >= 0.0)
{
// calculate contribution to matrix entries
double contribution = 1.0/tan(angles.first) + 1.0/tan(angles.second);
K(cur_id, cur_id) += contribution;
K(cur_id, neighbours[k]->get_id()) -= contribution;
}
}
}
}
// Scale the ith row of the matrix by the Voronoi area around the ith vertex
for(size_t i = 0; i < input_mesh.num_vertices(); i++)
{
double area = input_mesh.get_vertex(i)->calc_voronoi_area();
if(area < 2*std::numeric_limits<double>::epsilon())
{
// skip on error or upon encountering a Voronoi area
// that is too small
continue;
}
for(size_t j = 0; j < input_mesh.num_vertices(); j++)
{
if(K(i,j) != 0)
K(i,j) *= area;
}
}
return(K);
}
} // end of namespace "psalm"
<commit_msg>Added preliminary version of `CurvatureFlow`<commit_after>/*!
* @file CurvatureFlow.cpp
* @brief Implementation of a curvature flow algorithm
*/
#include "CurvatureFlow.h"
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/io.hpp>
namespace psalm
{
/*!
* Applies the curvature flow algorithm to the vertices of a given mesh.
* The size of timesteps needs to be set before. The input mesh is
* irreversibly changed by this operation.
*
* @param input_mesh Mesh on which the algorithm works.
* @return false if an error occurred, else true
*/
bool CurvatureFlow::apply_to(mesh& input_mesh)
{
using namespace boost::numeric::ublas;
size_t n = input_mesh.num_vertices();
if(n == 0)
return(true); // silently ignore empty meshes
// Stores x,y,z components of the vertices in the mesh
vector<double> X(n);
vector<double> Y(n);
vector<double> Z(n);
// Fill vector with position data
for(size_t i = 0; i < n; i++)
{
const v3ctor& pos = input_mesh.get_vertex(i)->get_position();
X[i] = pos[0];
Y[i] = pos[1];
Z[i] = pos[2];
}
// Prepare for "solving" the linear system (for now, this is something
// akin to the explicit Euler method)
mapped_matrix<double> M(n, n); // transformed matrix for the solving
// process, i.e. id - dt*K, where K is
// the matrix of the curvature operator
// FIXME: Should be user-configurable
double dt = 0.01;
M = identity_matrix<double>(n, n) - dt*calc_curvature_operator(input_mesh);
// Solve x,y,z components independently. This is _hellishly_ slow, but
// sufficient for small meshes.
vector<double> new_X = prod(M, X);
vector<double> new_Y = prod(M, Y);
vector<double> new_Z = prod(M, Z);
for(size_t i = 0; i < n; i++)
input_mesh.get_vertex(i)->set_position(new_X[i], new_Y[i], new_Z[i]);
return(true);
}
/*!
* Given an input mesh, calculates the curvature operator matrix for this
* mesh. The matrix will be a _sparse_ matrix, hence the need for handling
* it via boost.
*
* @param input_mesh Mesh to be processed
* @return Sparse matrix describing the curvature operator
*/
boost::numeric::ublas::mapped_matrix<double> CurvatureFlow::calc_curvature_operator(mesh& input_mesh)
{
using namespace boost::numeric::ublas;
mapped_matrix<double> K(input_mesh.num_vertices(), input_mesh.num_vertices()); // K as in "Kurvature"...
// We iterate over all faces and calculate the contributions of each
// vertex of the face to the corresponding entry of the matrix
for(size_t i = 0; i < input_mesh.num_faces(); i++)
{
face* f = input_mesh.get_face(i);
for(size_t j = 0; j < f->num_vertices(); j++)
{
vertex* v = f->get_vertex(j);
std::vector<const vertex*> neighbours = v->get_neighbours();
// FIXME: Used to update the correct matrix entries
// below. This assumes that the IDs have been allocated
// sequentially.
size_t cur_id = v->get_id();
// Find "opposing angles" for all neighbours; these are
// the $\alpha_{ij}$ and $\beta_{ij}$ values used for
// calculating the discrete curvature
for(size_t k = 0; k < neighbours.size(); k++)
{
std::pair<double, double> angles = v->find_opposite_angles(neighbours[k]);
if(angles.first >= 0.0 && angles.second >= 0.0)
{
// calculate contribution to matrix entries
double contribution = 1.0/tan(angles.first) + 1.0/tan(angles.second);
K(cur_id, cur_id) += contribution;
K(cur_id, neighbours[k]->get_id()) -= contribution;
}
}
}
}
// Scale the ith row of the matrix by the Voronoi area around the ith vertex
for(size_t i = 0; i < input_mesh.num_vertices(); i++)
{
double area = input_mesh.get_vertex(i)->calc_voronoi_area();
if(area < 2*std::numeric_limits<double>::epsilon())
{
// skip on error or upon encountering a Voronoi area
// that is too small
continue;
}
for(size_t j = 0; j < input_mesh.num_vertices(); j++)
{
if(K(i,j) != 0)
K(i,j) *= area;
}
}
return(K);
}
} // end of namespace "psalm"
<|endoftext|>
|
<commit_before>#include <arpa/inet.h>
#include <assert.h>
#include <map>
#include <openssl/sha.h>
#include <stdarg.h>
#include <stdio.h>
#include <string>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <zlib.h>
using namespace std;
namespace {
static const string NUL = string(1, '\0');
static const string SP = " ";
static const string LF = "\n";
__attribute__((noreturn)) void perror_abort(const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
perror("");
abort();
}
string compress(const string &in) {
string out(compressBound(in.size()), ' ');
size_t destLen = out.size();
int status = compress2((Bytef*)&out[0], &destLen, (const Bytef*)&in[0],
in.size(), 9);
if (status == Z_OK) {
out.erase(destLen);
} else {
fprintf(stderr, "zlib error: %d (%s)\n", status, zError(status));
abort();
}
return out;
}
string read_file(const string &name) {
struct stat buf;
if (stat(name.c_str(), &buf) < 0) {
perror_abort("stat: \"%s\"", name.c_str());
}
const size_t size = buf.st_size;
string res(size, ' ');
FILE *fp = fopen(name.c_str(), "rb");
size_t pos = 0;
while (pos < size) {
ssize_t n = fread(&res[pos], 1, size - pos, fp);
if (n < 0) {
perror_abort("fread");
}
pos += n;
}
assert(res.size() == size);
fclose(fp);
return res;
}
enum GitType {
OBJ_COMMIT = 1,
OBJ_TREE = 2,
OBJ_BLOB = 3,
};
string hex(const string& bin) {
string res;
for (unsigned char c : bin) {
char buf[3];
snprintf(buf, sizeof(buf), "%02x", c);
res += buf;
}
return res;
}
string sha1(const string& header, const string& data) {
SHA_CTX sha;
SHA1_Init(&sha);
SHA1_Update(&sha, header.data(), header.size());
SHA1_Update(&sha, data.data(), data.size());
unsigned char temp[SHA_DIGEST_LENGTH];
SHA1_Final(temp, &sha);
return string((const char *)temp, sizeof(temp));
}
const char *gittype_name(GitType type) {
switch (type) {
case OBJ_COMMIT:
return "commit";
case OBJ_TREE:
return "tree";
case OBJ_BLOB:
return "blob";
}
abort();
}
string git_header(GitType type, size_t length) {
char buf[32];
snprintf(buf, sizeof(buf), "%s %zu", gittype_name(type), length);
// Trailing NUL is included as a separator
return string(buf, strlen(buf) + 1);
}
struct Object {
GitType type;
const string* data;
};
void xfwrite(FILE *fp, const void *p_, size_t size) {
const char *p = (const char *)p_;
while (size) {
ssize_t n = fwrite(p, 1, size, fp);
if (n < 0) perror_abort("fwrite");
size -= n;
p += n;
}
}
void xfwrite(FILE *fp, const string& data) {
xfwrite(fp, data.data(), data.size());
}
struct Pack {
map<string, Object> objects;
SHA_CTX sha;
void add(const string& hash, const Object& obj) {
if (objects.find(hash) == objects.end()) {
objects[hash] = obj;
}
}
string hash_add(const Object& obj) {
string hash = sha1(git_header(obj.type, obj.data->size()), *obj.data);
add(hash, obj);
return hash;
}
void write_vint(FILE *fp, size_t x) {
assert(x);
while (x) {
char c = x & 0x7f;
if (x >>= 7) c |= 0x80;
writec(fp, c);
}
}
void writec(FILE *fp, char c) {
fputc(c, fp);
SHA1_Update(&sha, &c, 1);
}
void write(FILE *fp, const string& data) {
write(fp, data.data(), data.size());
}
void write(FILE *fp, const void *p, size_t size) {
SHA1_Update(&sha, p, size);
xfwrite(fp, p, size);
}
void print(FILE *fp) {
SHA1_Init(&sha);
char header[] = "PACK\0\0\0\2\0\0\0";
((uint32_t*)header)[2] = htonl(objects.size());
write(fp, header, sizeof(header));
for (const auto& i: objects) {
// first byte: low 4 bits is size, high bit is "size cont'd",
// middle three bits are type
//const string& hash = i.first;
const Object& obj = i.second;
assert(obj.type);
size_t size = obj.data->size();
long file_pos = ftell(fp);
write_vint(fp, ((size >> 4) << 7) | (obj.type << 4) | (size & 15));
long file_pos2 = ftell(fp);
const string compressed = compress(*obj.data);
write(fp, compressed);
if (0 && file_pos > 0) {
// SHA-1 type size size-in-packfile offset-in-packfile
fprintf(stderr, "%s %-6s %zu %zu %ld\n",
hex(i.first).c_str(),
gittype_name(obj.type),
size,
compressed.size() + (file_pos2 - file_pos),
file_pos);
}
}
unsigned char md[SHA_DIGEST_LENGTH];
SHA1_Final(md, &sha);
write(fp, md, sizeof(md));
}
};
string branch, author, commitmessage, parent;
Pack pack;
struct Tree {
string path_;
string data_;
string hash_;
struct stat stat_;
map<string, Tree> files_;
Tree(const string& path): path_(path) {
::stat(path.c_str(), &stat_);
}
void addpath(const string& path, const size_t pos = 0) {
size_t end = path.find('/', pos);
Tree& sub = addfile(path.substr(pos, end), path.substr(0, end));
if (end != string::npos) {
sub.addpath(path, end + 1);
}
}
Tree& addfile(const string& name, const string& path) {
auto it = files_.find(name);
if (it == files_.end()) {
return files_.insert(make_pair(name, Tree(path))).first->second;
} else {
return it->second;
}
}
const struct stat& stat() {
return stat_;
}
const string& data() {
if (data_.size() == 0) {
if (S_ISDIR(stat().st_mode)) {
for (auto& it: files_) {
string hash = it.second.hash();
char buf[12];
snprintf(buf, sizeof(buf), "%o ", it.second.git_mode());
const string entry = buf + it.first + NUL + hash;
data_ += entry;
// fprintf(stderr, "%s: %s %s\n", path_.c_str(), entry.c_str(), hex(hash).c_str());
}
} else if (S_ISREG(stat().st_mode)) {
data_ = read_file(path_);
} else {
fprintf(stderr, "Unhandled file type (mode %o) for %s\n",
stat().st_mode, path_.c_str());
abort();
}
}
return data_;
}
string header() {
return git_header(gittype(), data().size());
}
const string& hash() {
if (hash_.empty()) {
hash_ = sha1(header(), data());
// fprintf(stderr, "%s: %s\n", path_.c_str(), hex(hash_).c_str());
pack.add(hash_, object());
}
return hash_;
}
GitType gittype() {
return S_ISDIR(stat().st_mode) ? OBJ_TREE : OBJ_BLOB;
}
int git_mode() {
int m = stat().st_mode;
// file types recognized by git
const int type_mask = S_IFDIR | S_IFREG | S_IFLNK;
const int exec_mask = 0111;
if ((m & S_IFMT) != (m & type_mask))
{
fprintf(stderr, "Unknown file type (mode %o) for %s\n",
m, path_.c_str());
abort();
}
return (m & type_mask) | 0644 | (m & exec_mask ? exec_mask : 0);
}
Object object() {
return Object { gittype(), &data() };
}
};
Tree root(".");
// output: safe_name <safe_email> git_date
string make_author() {
char buf[256];
snprintf(buf, sizeof(buf), "%s %ld +0000", author.c_str(), time(nullptr));
return buf;
}
string make_commit(const string& tree, const string& commitmessage) {
const string author = make_author();
return "tree " + tree +
"\nparent " + parent +
"\nauthor " + author +
"\ncommitter " + author +
"\n\n" + commitmessage;
}
void pktline(const string& payload) {
if (payload.size() > 65516) {
fprintf(stderr, "FATAL: payload too large for pktline format\n");
abort();
}
printf("%04zx", payload.size() + 4);
xfwrite(stdout, payload);
}
}
// fgt-make-commit-pack BRANCH COMMITMSGFILE PARENT
int main(int argc, const char *argv[]) {
assert(argc >= 5);
branch = argv[1];
author = argv[2];
commitmessage = read_file(argv[3]);
parent = argv[4];
assert(parent.size() == 40);
char *line = nullptr;
size_t n = 0;
while (getdelim(&line, &n, '\0', stdin) >= 0)
{
if (string(line) == "./tmp.pack" || string(line) == "./tmp.idx")
continue;
const char *path = strchr(line, '/');
if (path)
root.addpath(path + 1);
}
string tree = root.hash();
string commitobj = make_commit(hex(tree), commitmessage);
string commithash = pack.hash_add(Object { OBJ_COMMIT, &commitobj });
fprintf(stderr, "%s\n", commitobj.c_str());
pktline(parent + SP + hex(commithash) + SP + branch + LF);
printf("0000");
pack.print(stdout);
FILE *fp = fopen("tmp.pack", "wb");
pack.print(fp);
fclose(fp);
}
<commit_msg>Add capabilities so that pushing works with github<commit_after>#include <arpa/inet.h>
#include <assert.h>
#include <map>
#include <openssl/sha.h>
#include <stdarg.h>
#include <stdio.h>
#include <string>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <zlib.h>
using namespace std;
namespace {
static const string NUL = string(1, '\0');
static const string SP = " ";
static const string LF = "\n";
__attribute__((noreturn)) void perror_abort(const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
perror("");
abort();
}
string compress(const string &in) {
string out(compressBound(in.size()), ' ');
size_t destLen = out.size();
int status = compress2((Bytef*)&out[0], &destLen, (const Bytef*)&in[0],
in.size(), 9);
if (status == Z_OK) {
out.erase(destLen);
} else {
fprintf(stderr, "zlib error: %d (%s)\n", status, zError(status));
abort();
}
return out;
}
string read_file(const string &name) {
struct stat buf;
if (stat(name.c_str(), &buf) < 0) {
perror_abort("stat: \"%s\"", name.c_str());
}
const size_t size = buf.st_size;
string res(size, ' ');
FILE *fp = fopen(name.c_str(), "rb");
size_t pos = 0;
while (pos < size) {
ssize_t n = fread(&res[pos], 1, size - pos, fp);
if (n < 0) {
perror_abort("fread");
}
pos += n;
}
assert(res.size() == size);
fclose(fp);
return res;
}
enum GitType {
OBJ_COMMIT = 1,
OBJ_TREE = 2,
OBJ_BLOB = 3,
};
string hex(const string& bin) {
string res;
for (unsigned char c : bin) {
char buf[3];
snprintf(buf, sizeof(buf), "%02x", c);
res += buf;
}
return res;
}
string sha1(const string& header, const string& data) {
SHA_CTX sha;
SHA1_Init(&sha);
SHA1_Update(&sha, header.data(), header.size());
SHA1_Update(&sha, data.data(), data.size());
unsigned char temp[SHA_DIGEST_LENGTH];
SHA1_Final(temp, &sha);
return string((const char *)temp, sizeof(temp));
}
const char *gittype_name(GitType type) {
switch (type) {
case OBJ_COMMIT:
return "commit";
case OBJ_TREE:
return "tree";
case OBJ_BLOB:
return "blob";
}
abort();
}
string git_header(GitType type, size_t length) {
char buf[32];
snprintf(buf, sizeof(buf), "%s %zu", gittype_name(type), length);
// Trailing NUL is included as a separator
return string(buf, strlen(buf) + 1);
}
struct Object {
GitType type;
const string* data;
};
void xfwrite(FILE *fp, const void *p_, size_t size) {
const char *p = (const char *)p_;
while (size) {
ssize_t n = fwrite(p, 1, size, fp);
if (n < 0) perror_abort("fwrite");
size -= n;
p += n;
}
}
void xfwrite(FILE *fp, const string& data) {
xfwrite(fp, data.data(), data.size());
}
struct Pack {
map<string, Object> objects;
SHA_CTX sha;
void add(const string& hash, const Object& obj) {
if (objects.find(hash) == objects.end()) {
objects[hash] = obj;
}
}
string hash_add(const Object& obj) {
string hash = sha1(git_header(obj.type, obj.data->size()), *obj.data);
add(hash, obj);
return hash;
}
void write_vint(FILE *fp, size_t x) {
assert(x);
while (x) {
char c = x & 0x7f;
if (x >>= 7) c |= 0x80;
writec(fp, c);
}
}
void writec(FILE *fp, char c) {
fputc(c, fp);
SHA1_Update(&sha, &c, 1);
}
void write(FILE *fp, const string& data) {
write(fp, data.data(), data.size());
}
void write(FILE *fp, const void *p, size_t size) {
SHA1_Update(&sha, p, size);
xfwrite(fp, p, size);
}
void print(FILE *fp) {
SHA1_Init(&sha);
char header[] = "PACK\0\0\0\2\0\0\0";
((uint32_t*)header)[2] = htonl(objects.size());
write(fp, header, sizeof(header));
for (const auto& i: objects) {
// first byte: low 4 bits is size, high bit is "size cont'd",
// middle three bits are type
//const string& hash = i.first;
const Object& obj = i.second;
assert(obj.type);
size_t size = obj.data->size();
long file_pos = ftell(fp);
write_vint(fp, ((size >> 4) << 7) | (obj.type << 4) | (size & 15));
long file_pos2 = ftell(fp);
const string compressed = compress(*obj.data);
write(fp, compressed);
if (0 && file_pos > 0) {
// SHA-1 type size size-in-packfile offset-in-packfile
fprintf(stderr, "%s %-6s %zu %zu %ld\n",
hex(i.first).c_str(),
gittype_name(obj.type),
size,
compressed.size() + (file_pos2 - file_pos),
file_pos);
}
}
unsigned char md[SHA_DIGEST_LENGTH];
SHA1_Final(md, &sha);
write(fp, md, sizeof(md));
}
};
string branch, author, commitmessage, parent;
Pack pack;
struct Tree {
string path_;
string data_;
string hash_;
struct stat stat_;
map<string, Tree> files_;
Tree(const string& path): path_(path) {
::stat(path.c_str(), &stat_);
}
void addpath(const string& path, const size_t pos = 0) {
size_t end = path.find('/', pos);
Tree& sub = addfile(path.substr(pos, end), path.substr(0, end));
if (end != string::npos) {
sub.addpath(path, end + 1);
}
}
Tree& addfile(const string& name, const string& path) {
auto it = files_.find(name);
if (it == files_.end()) {
return files_.insert(make_pair(name, Tree(path))).first->second;
} else {
return it->second;
}
}
const struct stat& stat() {
return stat_;
}
const string& data() {
if (data_.size() == 0) {
if (S_ISDIR(stat().st_mode)) {
for (auto& it: files_) {
string hash = it.second.hash();
char buf[12];
snprintf(buf, sizeof(buf), "%o ", it.second.git_mode());
const string entry = buf + it.first + NUL + hash;
data_ += entry;
// fprintf(stderr, "%s: %s %s\n", path_.c_str(), entry.c_str(), hex(hash).c_str());
}
} else if (S_ISREG(stat().st_mode)) {
data_ = read_file(path_);
} else {
fprintf(stderr, "Unhandled file type (mode %o) for %s\n",
stat().st_mode, path_.c_str());
abort();
}
}
return data_;
}
string header() {
return git_header(gittype(), data().size());
}
const string& hash() {
if (hash_.empty()) {
hash_ = sha1(header(), data());
// fprintf(stderr, "%s: %s\n", path_.c_str(), hex(hash_).c_str());
pack.add(hash_, object());
}
return hash_;
}
GitType gittype() {
return S_ISDIR(stat().st_mode) ? OBJ_TREE : OBJ_BLOB;
}
int git_mode() {
int m = stat().st_mode;
// file types recognized by git
const int type_mask = S_IFDIR | S_IFREG | S_IFLNK;
const int exec_mask = 0111;
if ((m & S_IFMT) != (m & type_mask))
{
fprintf(stderr, "Unknown file type (mode %o) for %s\n",
m, path_.c_str());
abort();
}
return (m & type_mask) | 0644 | (m & exec_mask ? exec_mask : 0);
}
Object object() {
return Object { gittype(), &data() };
}
};
Tree root(".");
// output: safe_name <safe_email> git_date
string make_author() {
char buf[256];
snprintf(buf, sizeof(buf), "%s %ld +0000", author.c_str(), time(nullptr));
return buf;
}
string make_commit(const string& tree, const string& commitmessage) {
const string author = make_author();
return "tree " + tree +
"\nparent " + parent +
"\nauthor " + author +
"\ncommitter " + author +
"\n\n" + commitmessage;
}
void pktline(const string& payload) {
if (payload.size() > 65516) {
fprintf(stderr, "FATAL: payload too large for pktline format\n");
abort();
}
printf("%04zx", payload.size() + 4);
xfwrite(stdout, payload);
}
}
// fgt-make-commit-pack BRANCH COMMITMSGFILE PARENT
int main(int argc, const char *argv[]) {
assert(argc >= 5);
branch = argv[1];
author = argv[2];
commitmessage = read_file(argv[3]);
parent = argv[4];
assert(parent.size() == 40);
char *line = nullptr;
size_t n = 0;
while (getdelim(&line, &n, '\0', stdin) >= 0)
{
if (string(line) == "./tmp.pack" || string(line) == "./tmp.idx")
continue;
const char *path = strchr(line, '/');
if (path)
root.addpath(path + 1);
}
string tree = root.hash();
string commitobj = make_commit(hex(tree), commitmessage);
string commithash = pack.hash_add(Object { OBJ_COMMIT, &commitobj });
fprintf(stderr, "%s\n", commitobj.c_str());
const string capabilities = "report-status";
pktline(parent + SP + hex(commithash) + SP + branch +
NUL + capabilities + LF);
printf("0000");
pack.print(stdout);
FILE *fp = fopen("tmp.pack", "wb");
pack.print(fp);
fclose(fp);
}
<|endoftext|>
|
<commit_before>#include "motors_old.h"
#define MINREQSPEED 5
#define POLARITY -1 // direction of forward / connection to motor
Motors_Old::Motors_Old()
{
//ctor
fdMotor = -1;
dVelocityScale = 1;
_max_speed_=50;
//SetupSerial();
}
Motors_Old::~Motors_Old()
{
//dtor
ShutdownSerial();
}
int Motors_Old::SetupSerial()
{
/* Open serial port with the specified flags
* O_RDWR - for reading and writing
* O_NOCTTY - don't act as the controlling terminal for the port
* O_DSYNC | O_RSYNC - complete i/o operiations as definded by synchronized i/o data
* integrity completion (i.e. waits for the data but not meta-data to be written
* to the file before continuing execution) - this doesn't seem to work
* O_NDELAY - don't wait for the DCD line to go to the space voltage
*/
if ((fdMotor = open(DEFAULT_PORT, O_RDWR | O_NOCTTY | O_DSYNC | O_RSYNC | O_NDELAY)) < 0)
{
printf("SetupSerial(): could not open port %s, %s\n", DEFAULT_PORT, strerror(errno));
return(-1);
}
/* Set the port back to blocking (waiting) behavior for calls to read() */
//fcntl(fdMotor, F_SETFL, 0);
/*no! => go nonblocking!*/
fcntl(fdMotor, F_SETFL, O_NONBLOCK);
/* Get the current options for the port */
struct termios options;
if (tcgetattr(fdMotor, &options) < 0)
{
printf("SetupSerial(): could not get the serial port options, %s\n", strerror(errno));
ShutdownSerial();
return(-1);
}
/* Configure the port options */
options.c_cflag |= (CREAD | CLOCAL); /* Enable the receiver and set local mode */
cfsetispeed(&options, B115200); /* Set 115200 baud rate */
cfsetospeed(&options, B115200);
options.c_cflag &= ~PARENB; /* Set no parity */
options.c_cflag &= ~CSTOPB; /* Set 1 stop bit */
options.c_cflag &= ~CSIZE; /* Set 8 data bits */
options.c_cflag |= CS8;
options.c_cc[VMIN] = 0; /* Set .2 sec timeout */
options.c_cc[VTIME] = 2;
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); /* Set raw input and output */
options.c_oflag &= ~OPOST;
/* Flush input and output buffers and then set the new options for the port */
if (tcsetattr(fdMotor, TCSAFLUSH, &options) < 0 )
{
printf("SetupSerial(): could not set the serial port options, %s\n", strerror(errno));
ShutdownSerial();
return(-1);
}
return(0);
}
int Motors_Old::ShutdownSerial()
{
if (close(fdMotor) < 0)
{
printf("ShutdownSerial(): could not close the serial port, %s\n", strerror(errno));
fdMotor = -1;
return(-1);
}
fdMotor = -1;
return(0);
}
int Motors_Old::Shutdown()
{
return(ShutdownSerial());
}
/* NOTE:
* When you raise the DTR line, if the motor controller is in AUTONOMOUS_MODE,
* it reads in any data in its uart buffer (4 bytes at most). Then, in all modes,
* it sends back its current motor states, control mode, and any errors it had
* with the transmission.
*/
int Motors_Old::set_motors(int iLeftVelocity, int iRightVelocity)
{
/* Scale the motor velocities, limit them to vaild values, and store them in the
* correct form to transmit to the motor controller.
* Alternate Title: fun with the ? operator
*/
int iScaledLeftVel = POLARITY * (int)(dVelocityScale * iLeftVelocity);
int iScaledRightVel = POLARITY * (int)(dVelocityScale * iRightVelocity);
unsigned char data[3] =
{
(unsigned char)( (((iScaledLeftVel < 0) ? REVERSE : FORWARD) << LEFT_DIR_OFFSET) | (((iScaledRightVel < 0) ? REVERSE : FORWARD) << RIGHT_DIR_OFFSET) ),
(unsigned char)( min(abs(iScaledLeftVel), 255) ),
(unsigned char)( min(abs(iScaledRightVel), 255) )
};
/* Send the motor states to the motor controller */
if ( write(fdMotor, data, 3) != 3 )
{
printf("set_motors(): could not write to serial port, %s\n", strerror(errno));
return(-1);
}
/* Make sure the data has finished being written - this can be removed if the option can be made work in open() */
tcdrain(fdMotor);
/* Get the current motor states from the motor controller */
return( get_motor_states() );
}
int Motors_Old::get_motor_states(void)
{
/* Flush any old data in the read buffer */
tcflush(fdMotor, TCIFLUSH);
/* Set the DTR line high to intterupt the motor controller */
int status;
if (ioctl(fdMotor, TIOCMGET, &status))
{
printf("get_motor_states(): could not get serial port status, %s\n", strerror(errno));
return(-1);
}
status |= TIOCM_DTR;
if (ioctl(fdMotor, TIOCMSET, &status))
{
printf("get_motor_states(): could not set RTS high, %s\n", strerror(errno));
return(-1);
}
/*
* If the DTR line can be raised and lowered in less than a full clock cycle
* of the controller, there should be a delay here to make sure the motor
* controller interrupts.
*/
/* Set the DTR line back to low
* If there are problems, you might need to get the motor status again with
* ioctl(fdMotor, TIOCMGET, &status) before doing this.
*/
status &= ~TIOCM_DTR;
if (ioctl(fdMotor, TIOCMSET, &status))
{
printf("get_motor_states(): could not set RTS low, %s\n", strerror(errno));
return(-1);
}
/* Read each byte sent from the controller */
unsigned char u8Buff[3];
int bytesRead;
if ((bytesRead = read(fdMotor, u8Buff, 3)) != 3)
{
printf("get_motor_states(): the motor controller did not respond or only partial responded, \n%s, %d bytes read\n", strerror(errno), bytesRead);
//return(-1);
}
//Test
printf("%d bytes read\n", bytesRead);
for (int i = 0; i < bytesRead; i++)
{
printf("%d ", u8Buff[i]);
}
printf("\n");
/* Report any errors the motor controller had with the transmission */
int iError = (u8Buff[0] & ERROR_MASK) >> ERROR_OFFSET;
if ( iError & (FRAME_ERROR|DATA_OVERRUN_ERROR|PARITY_ERROR|TIMEOUT_ERROR) )
{
printf("get_motor_states(): the motor controller could not process comand, Error %d\n", iError);
return(-1);
}
/* Store the current control mode */
controlMode = ( u8Buff[0] & CONTROL_MODE_MASK ) >> CONTROL_MODE_OFFSET;
/* Store the current motor velocities */
_iLeftVelocity = ((((u8Buff[0] & LEFT_DIR_MASK) >> LEFT_DIR_OFFSET)==FORWARD) ? 1 : -1) * (int)u8Buff[1];
_iRightVelocity = ((((u8Buff[0] & RIGHT_DIR_MASK) >> RIGHT_DIR_OFFSET)==FORWARD)? 1 : -1) * (int)u8Buff[2];
return(0);
}
/* Set motors based on given velocity:
* Fwd range [0,255]
* Rot range [-128,127]
*/
int Motors_Old::set_heading(int iFwdVelocity, int iRotation)
{
// XXX: hack!
//printf("irotation %d",iRotation);
iRotation *= 1.15;
//printf("\tirotation %d\n",iRotation);
// convert
int left = iFwdVelocity + iRotation ;
int right = iFwdVelocity - iRotation ;
if (1)
{
// scale speed
left = ( left * _max_speed_ / 255 ) ;
right = ( right * _max_speed_ / 255 ) ;
}
else
{
// cap speed
if (left > _max_speed_) left = _max_speed_ ;
if (right > _max_speed_) right = _max_speed_ ;
}
// don't go backwards
if (right < 0) right = 0 ;
if (left < 0) left = 0 ;
// motors don't respond until certain output is reached
if (right != 0) right += MINREQSPEED ;
if (left != 0) left += MINREQSPEED ;
// show
printf("Motors: L=%d R=%d \n",left,right);
// do it!
return this->set_motors( left , right );
}
void Motors_Old::set_max_speed(int maxspeed)
{
/* 0-255 */
_max_speed_ = maxspeed;
}
<commit_msg>...forgot the motors file on previous commit<commit_after>#include "motors_old.h"
#define MINREQSPEED 5
#define POLARITY -1 // direction of forward / connection to motor
Motors_Old::Motors_Old()
{
//ctor
fdMotor = -1;
dVelocityScale = 1;
_max_speed_=50;
//SetupSerial();
}
Motors_Old::~Motors_Old()
{
//dtor
ShutdownSerial();
}
int Motors_Old::SetupSerial()
{
/* Open serial port with the specified flags
* O_RDWR - for reading and writing
* O_NOCTTY - don't act as the controlling terminal for the port
* O_DSYNC | O_RSYNC - complete i/o operiations as definded by synchronized i/o data
* integrity completion (i.e. waits for the data but not meta-data to be written
* to the file before continuing execution) - this doesn't seem to work
* O_NDELAY - don't wait for the DCD line to go to the space voltage
*/
if ((fdMotor = open(DEFAULT_PORT, O_RDWR | O_NOCTTY | O_DSYNC | O_RSYNC | O_NDELAY)) < 0)
{
printf("SetupSerial(): could not open port %s, %s\n", DEFAULT_PORT, strerror(errno));
return(-1);
}
/* Set the port back to blocking (waiting) behavior for calls to read() */
//fcntl(fdMotor, F_SETFL, 0);
/*no! => go nonblocking!*/
fcntl(fdMotor, F_SETFL, O_NONBLOCK);
/* Get the current options for the port */
struct termios options;
if (tcgetattr(fdMotor, &options) < 0)
{
printf("SetupSerial(): could not get the serial port options, %s\n", strerror(errno));
ShutdownSerial();
return(-1);
}
/* Configure the port options */
options.c_cflag |= (CREAD | CLOCAL); /* Enable the receiver and set local mode */
cfsetispeed(&options, B115200); /* Set 115200 baud rate */
cfsetospeed(&options, B115200);
options.c_cflag &= ~PARENB; /* Set no parity */
options.c_cflag &= ~CSTOPB; /* Set 1 stop bit */
options.c_cflag &= ~CSIZE; /* Set 8 data bits */
options.c_cflag |= CS8;
options.c_cc[VMIN] = 0; /* Set .2 sec timeout */
options.c_cc[VTIME] = 2;
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); /* Set raw input and output */
options.c_oflag &= ~OPOST;
/* Flush input and output buffers and then set the new options for the port */
if (tcsetattr(fdMotor, TCSAFLUSH, &options) < 0 )
{
printf("SetupSerial(): could not set the serial port options, %s\n", strerror(errno));
ShutdownSerial();
return(-1);
}
return(0);
}
int Motors_Old::ShutdownSerial()
{
if (close(fdMotor) < 0)
{
printf("ShutdownSerial(): could not close the serial port, %s\n", strerror(errno));
fdMotor = -1;
return(-1);
}
fdMotor = -1;
return(0);
}
int Motors_Old::Shutdown()
{
return(ShutdownSerial());
}
/* NOTE:
* When you raise the DTR line, if the motor controller is in AUTONOMOUS_MODE,
* it reads in any data in its uart buffer (4 bytes at most). Then, in all modes,
* it sends back its current motor states, control mode, and any errors it had
* with the transmission.
*/
int Motors_Old::set_motors(int iLeftVelocity, int iRightVelocity)
{
/* Scale the motor velocities, limit them to vaild values, and store them in the
* correct form to transmit to the motor controller.
* Alternate Title: fun with the ? operator
*/
int iScaledLeftVel = POLARITY * (int)(dVelocityScale * iLeftVelocity);
int iScaledRightVel = POLARITY * (int)(dVelocityScale * iRightVelocity);
unsigned char data[3] =
{
(unsigned char)( (((iScaledLeftVel < 0) ? REVERSE : FORWARD) << LEFT_DIR_OFFSET) | (((iScaledRightVel < 0) ? REVERSE : FORWARD) << RIGHT_DIR_OFFSET) ),
(unsigned char)( min(abs(iScaledLeftVel), 255) ),
(unsigned char)( min(abs(iScaledRightVel), 255) )
};
/* Send the motor states to the motor controller */
if ( write(fdMotor, data, 3) != 3 )
{
printf("set_motors(): could not write to serial port, %s\n", strerror(errno));
return(-1);
}
/* Make sure the data has finished being written - this can be removed if the option can be made work in open() */
tcdrain(fdMotor);
/* Get the current motor states from the motor controller */
return( get_motor_states() );
}
int Motors_Old::get_motor_states(void)
{
/* Flush any old data in the read buffer */
tcflush(fdMotor, TCIFLUSH);
/* Set the DTR line high to intterupt the motor controller */
int status;
if (ioctl(fdMotor, TIOCMGET, &status))
{
printf("get_motor_states(): could not get serial port status, %s\n", strerror(errno));
return(-1);
}
status |= TIOCM_DTR;
if (ioctl(fdMotor, TIOCMSET, &status))
{
printf("get_motor_states(): could not set RTS high, %s\n", strerror(errno));
return(-1);
}
/*
* If the DTR line can be raised and lowered in less than a full clock cycle
* of the controller, there should be a delay here to make sure the motor
* controller interrupts.
*/
/* Set the DTR line back to low
* If there are problems, you might need to get the motor status again with
* ioctl(fdMotor, TIOCMGET, &status) before doing this.
*/
status &= ~TIOCM_DTR;
if (ioctl(fdMotor, TIOCMSET, &status))
{
printf("get_motor_states(): could not set RTS low, %s\n", strerror(errno));
return(-1);
}
/* Read each byte sent from the controller */
unsigned char u8Buff[3];
int bytesRead;
if ((bytesRead = read(fdMotor, u8Buff, 3)) != 3)
{
printf("get_motor_states(): the motor controller did not respond or only partial responded, \n%s, %d bytes read\n", strerror(errno), bytesRead);
//return(-1);
}
//Test
printf("%d bytes read\n", bytesRead);
for (int i = 0; i < bytesRead; i++)
{
printf("%d ", u8Buff[i]);
}
printf("\n");
/* Report any errors the motor controller had with the transmission */
int iError = (u8Buff[0] & ERROR_MASK) >> ERROR_OFFSET;
if ( iError & (FRAME_ERROR|DATA_OVERRUN_ERROR|PARITY_ERROR|TIMEOUT_ERROR) )
{
printf("get_motor_states(): the motor controller could not process comand, Error %d\n", iError);
return(-1);
}
/* Store the current control mode */
controlMode = ( u8Buff[0] & CONTROL_MODE_MASK ) >> CONTROL_MODE_OFFSET;
/* Store the current motor velocities */
_iLeftVelocity = ((((u8Buff[0] & LEFT_DIR_MASK) >> LEFT_DIR_OFFSET)==FORWARD) ? 1 : -1) * (int)u8Buff[1];
_iRightVelocity = ((((u8Buff[0] & RIGHT_DIR_MASK) >> RIGHT_DIR_OFFSET)==FORWARD)? 1 : -1) * (int)u8Buff[2];
return(0);
}
/* Set motors based on given velocity:
* Fwd range [0,255]
* Rot range [-128,127]
*/
int Motors_Old::set_heading(int iFwdVelocity, int iRotation)
{
// XXX: hack!
//printf("irotation %d",iRotation);
//iRotation *= 1.1;
//printf("\tirotation %d\n",iRotation);
// convert
int left = iFwdVelocity + iRotation ;
int right = iFwdVelocity - iRotation ;
if (1)
{
// scale speed
left = ( left * _max_speed_ / 255 ) ;
right = ( right * _max_speed_ / 255 ) ;
}
else
{
// cap speed
if (left > _max_speed_) left = _max_speed_ ;
if (right > _max_speed_) right = _max_speed_ ;
}
// don't go backwards
if (right < 0) right = 0 ;
if (left < 0) left = 0 ;
// motors don't respond until certain output is reached
if (right != 0) right += MINREQSPEED ;
if (left != 0) left += MINREQSPEED ;
// show
printf("Motors: L=%d R=%d \n",left,right);
// do it!
return this->set_motors( left , right );
}
void Motors_Old::set_max_speed(int maxspeed)
{
/* 0-255 */
_max_speed_ = maxspeed;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: languageoptions.cxx,v $
*
* $Revision: 1.14 $
*
* last change: $Author: rt $ $Date: 2005-09-05 13:37:12 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifdef SVL_DLLIMPLEMENTATION
#undef SVL_DLLIMPLEMENTATION
#endif
#define SVT_DLLIMPLEMENTATION
#include "languageoptions.hxx"
#ifndef _SVTOOLS_CJKOPTIONS_HXX
#include <cjkoptions.hxx>
#endif
#ifndef _SVTOOLS_CTLOPTIONS_HXX
#include <ctloptions.hxx>
#endif
#ifndef _LANG_HXX
#include <tools/lang.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef INCLUDED_RTL_INSTANCE_HXX
#include <rtl/instance.hxx>
#endif
// global ----------------------------------------------------------------------
namespace { struct ALMutex : public rtl::Static< ::osl::Mutex, ALMutex > {}; }
// class SvtLanguageOptions ----------------------------------------------------
SvtLanguageOptions::SvtLanguageOptions( sal_Bool _bDontLoad )
{
// Global access, must be guarded (multithreading)
::osl::MutexGuard aGuard( ALMutex::get() );
m_pCJKOptions = new SvtCJKOptions( _bDontLoad );
m_pCTLOptions = new SvtCTLOptions( _bDontLoad );
StartListening(*m_pCTLOptions);
}
//------------------------------------------------------------------------------
SvtLanguageOptions::~SvtLanguageOptions()
{
// Global access, must be guarded (multithreading)
::osl::MutexGuard aGuard( ALMutex::get() );
delete m_pCJKOptions;
delete m_pCTLOptions;
}
//------------------------------------------------------------------------------
// CJK options -----------------------------------------------------------------
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsCJKFontEnabled() const
{
return m_pCJKOptions->IsCJKFontEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsVerticalTextEnabled() const
{
return m_pCJKOptions->IsVerticalTextEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsAsianTypographyEnabled() const
{
return m_pCJKOptions->IsAsianTypographyEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsJapaneseFindEnabled() const
{
return m_pCJKOptions->IsJapaneseFindEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsRubyEnabled() const
{
return m_pCJKOptions->IsRubyEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsChangeCaseMapEnabled() const
{
return m_pCJKOptions->IsChangeCaseMapEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsDoubleLinesEnabled() const
{
return m_pCJKOptions->IsDoubleLinesEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsEmphasisMarksEnabled() const
{
return m_pCJKOptions->IsEmphasisMarksEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsVerticalCallOutEnabled() const
{
return m_pCJKOptions->IsVerticalCallOutEnabled();
}
//------------------------------------------------------------------------------
void SvtLanguageOptions::SetAll( sal_Bool _bSet )
{
m_pCJKOptions->SetAll( _bSet );
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsAnyEnabled() const
{
return m_pCJKOptions->IsAnyEnabled();
}
//------------------------------------------------------------------------------
// CTL options -----------------------------------------------------------------
//------------------------------------------------------------------------------
void SvtLanguageOptions::SetCTLFontEnabled( sal_Bool _bEnabled )
{
m_pCTLOptions->SetCTLFontEnabled( _bEnabled );
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsCTLFontEnabled() const
{
return m_pCTLOptions->IsCTLFontEnabled();
}
//------------------------------------------------------------------------------
void SvtLanguageOptions::SetCTLSequenceChecking( sal_Bool _bEnabled )
{
m_pCTLOptions->SetCTLSequenceChecking( _bEnabled );
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsCTLSequenceChecking() const
{
return m_pCTLOptions->IsCTLSequenceChecking();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsReadOnly(SvtLanguageOptions::EOption eOption) const
{
sal_Bool bReadOnly = sal_False;
switch(eOption)
{
// cjk options
case SvtLanguageOptions::E_CJKFONT : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_CJKFONT ); break;
case SvtLanguageOptions::E_VERTICALTEXT : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_VERTICALTEXT ); break;
case SvtLanguageOptions::E_ASIANTYPOGRAPHY : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_ASIANTYPOGRAPHY); break;
case SvtLanguageOptions::E_JAPANESEFIND : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_JAPANESEFIND ); break;
case SvtLanguageOptions::E_RUBY : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_RUBY ); break;
case SvtLanguageOptions::E_CHANGECASEMAP : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_CHANGECASEMAP ); break;
case SvtLanguageOptions::E_DOUBLELINES : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_DOUBLELINES ); break;
case SvtLanguageOptions::E_EMPHASISMARKS : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_EMPHASISMARKS ); break;
case SvtLanguageOptions::E_VERTICALCALLOUT : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_VERTICALCALLOUT); break;
case SvtLanguageOptions::E_ALLCJK : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_ALL ); break;
// ctl options
case SvtLanguageOptions::E_CTLFONT : bReadOnly = m_pCTLOptions->IsReadOnly(SvtCTLOptions::E_CTLFONT ); break;
case SvtLanguageOptions::E_CTLSEQUENCECHECKING : bReadOnly = m_pCTLOptions->IsReadOnly(SvtCTLOptions::E_CTLSEQUENCECHECKING); break;
case SvtLanguageOptions::E_CTLCURSORMOVEMENT : bReadOnly = m_pCTLOptions->IsReadOnly(SvtCTLOptions::E_CTLCURSORMOVEMENT ); break;
case SvtLanguageOptions::E_CTLTEXTNUMERALS : bReadOnly = m_pCTLOptions->IsReadOnly(SvtCTLOptions::E_CTLTEXTNUMERALS ); break;
}
return bReadOnly;
}
/* -----------------30.04.2003 11:03-----------------
--------------------------------------------------*/
void SvtLanguageOptions::Notify( SfxBroadcaster& rBC, const SfxHint& rHint )
{
vos::OGuard aVclGuard( Application::GetSolarMutex() );
Broadcast( rHint );
}
// -----------------------------------------------------------------------------
// returns for a language the scripttype
sal_uInt16 SvtLanguageOptions::GetScriptTypeOfLanguage( sal_uInt16 nLang )
{
if( LANGUAGE_DONTKNOW == nLang )
nLang = LANGUAGE_ENGLISH_US;
else if( LANGUAGE_SYSTEM == nLang )
nLang = Application::GetSettings().GetLanguage();
USHORT nScript;
switch( nLang )
{
// CJK
case LANGUAGE_CHINESE:
case LANGUAGE_CHINESE_TRADITIONAL:
case LANGUAGE_CHINESE_SIMPLIFIED:
case LANGUAGE_CHINESE_HONGKONG:
case LANGUAGE_CHINESE_SINGAPORE:
case LANGUAGE_CHINESE_MACAU:
case LANGUAGE_JAPANESE:
case LANGUAGE_KOREAN:
case LANGUAGE_KOREAN_JOHAB:
case LANGUAGE_USER_KOREAN_NORTH:
nScript = SCRIPTTYPE_ASIAN;
break;
// CTL
case LANGUAGE_ARABIC:
case LANGUAGE_ARABIC_SAUDI_ARABIA:
case LANGUAGE_ARABIC_IRAQ:
case LANGUAGE_ARABIC_EGYPT:
case LANGUAGE_ARABIC_LIBYA:
case LANGUAGE_ARABIC_ALGERIA:
case LANGUAGE_ARABIC_MOROCCO:
case LANGUAGE_ARABIC_TUNISIA:
case LANGUAGE_ARABIC_OMAN:
case LANGUAGE_ARABIC_YEMEN:
case LANGUAGE_ARABIC_SYRIA:
case LANGUAGE_ARABIC_JORDAN:
case LANGUAGE_ARABIC_LEBANON:
case LANGUAGE_ARABIC_KUWAIT:
case LANGUAGE_ARABIC_UAE:
case LANGUAGE_ARABIC_BAHRAIN:
case LANGUAGE_ARABIC_QATAR:
case LANGUAGE_ASSAMESE:
case LANGUAGE_BENGALI:
case LANGUAGE_BENGALI_BANGLADESH:
case LANGUAGE_FARSI:
case LANGUAGE_HEBREW:
case LANGUAGE_MARATHI:
case LANGUAGE_PUNJABI:
case LANGUAGE_GUJARATI:
case LANGUAGE_HINDI:
case LANGUAGE_KANNADA:
case LANGUAGE_KASHMIRI:
case LANGUAGE_KASHMIRI_INDIA:
case LANGUAGE_KHMER:
case LANGUAGE_LAO:
case LANGUAGE_MALAYALAM:
case LANGUAGE_MANIPURI:
case LANGUAGE_MONGOLIAN_MONGOLIAN:
case LANGUAGE_NEPALI:
case LANGUAGE_NEPALI_INDIA:
case LANGUAGE_ORIYA:
case LANGUAGE_SANSKRIT:
case LANGUAGE_SINDHI:
case LANGUAGE_SINDHI_PAKISTAN:
case LANGUAGE_SINHALESE_SRI_LANKA:
case LANGUAGE_SYRIAC:
case LANGUAGE_TAMIL:
case LANGUAGE_TELUGU:
case LANGUAGE_THAI:
case LANGUAGE_TIBETAN:
case LANGUAGE_DZONGKHA:
case LANGUAGE_URDU:
case LANGUAGE_URDU_PAKISTAN:
case LANGUAGE_URDU_INDIA:
case LANGUAGE_USER_KURDISH_IRAQ:
case LANGUAGE_USER_KURDISH_IRAN:
case LANGUAGE_VIETNAMESE:
nScript = SCRIPTTYPE_COMPLEX;
break;
// currently not knowing scripttype - defaultet to LATIN:
/*
#define LANGUAGE_ARMENIAN 0x042B
#define LANGUAGE_INDONESIAN 0x0421
#define LANGUAGE_KAZAK 0x043F
#define LANGUAGE_KONKANI 0x0457
#define LANGUAGE_MACEDONIAN 0x042F
#define LANGUAGE_TATAR 0x0444
*/
default:
switch ( nLang & LANGUAGE_MASK_PRIMARY )
{
// CJK catcher
case LANGUAGE_CHINESE & LANGUAGE_MASK_PRIMARY:
nScript = SCRIPTTYPE_ASIAN;
break;
// CTL catcher
case LANGUAGE_ARABIC & LANGUAGE_MASK_PRIMARY:
nScript = SCRIPTTYPE_COMPLEX;
break;
// Western (actually not necessarily Latin but also Cyrillic, for example)
default:
nScript = SCRIPTTYPE_LATIN;
}
break;
}
return nScript;
}
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS ooo19126 (1.13.2); FILE MERGED 2005/09/05 14:52:05 rt 1.13.2.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: languageoptions.cxx,v $
*
* $Revision: 1.15 $
*
* last change: $Author: rt $ $Date: 2005-09-08 14:41:55 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifdef SVL_DLLIMPLEMENTATION
#undef SVL_DLLIMPLEMENTATION
#endif
#define SVT_DLLIMPLEMENTATION
#include "languageoptions.hxx"
#ifndef _SVTOOLS_CJKOPTIONS_HXX
#include <cjkoptions.hxx>
#endif
#ifndef _SVTOOLS_CTLOPTIONS_HXX
#include <ctloptions.hxx>
#endif
#ifndef _LANG_HXX
#include <tools/lang.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef INCLUDED_RTL_INSTANCE_HXX
#include <rtl/instance.hxx>
#endif
// global ----------------------------------------------------------------------
namespace { struct ALMutex : public rtl::Static< ::osl::Mutex, ALMutex > {}; }
// class SvtLanguageOptions ----------------------------------------------------
SvtLanguageOptions::SvtLanguageOptions( sal_Bool _bDontLoad )
{
// Global access, must be guarded (multithreading)
::osl::MutexGuard aGuard( ALMutex::get() );
m_pCJKOptions = new SvtCJKOptions( _bDontLoad );
m_pCTLOptions = new SvtCTLOptions( _bDontLoad );
StartListening(*m_pCTLOptions);
}
//------------------------------------------------------------------------------
SvtLanguageOptions::~SvtLanguageOptions()
{
// Global access, must be guarded (multithreading)
::osl::MutexGuard aGuard( ALMutex::get() );
delete m_pCJKOptions;
delete m_pCTLOptions;
}
//------------------------------------------------------------------------------
// CJK options -----------------------------------------------------------------
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsCJKFontEnabled() const
{
return m_pCJKOptions->IsCJKFontEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsVerticalTextEnabled() const
{
return m_pCJKOptions->IsVerticalTextEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsAsianTypographyEnabled() const
{
return m_pCJKOptions->IsAsianTypographyEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsJapaneseFindEnabled() const
{
return m_pCJKOptions->IsJapaneseFindEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsRubyEnabled() const
{
return m_pCJKOptions->IsRubyEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsChangeCaseMapEnabled() const
{
return m_pCJKOptions->IsChangeCaseMapEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsDoubleLinesEnabled() const
{
return m_pCJKOptions->IsDoubleLinesEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsEmphasisMarksEnabled() const
{
return m_pCJKOptions->IsEmphasisMarksEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsVerticalCallOutEnabled() const
{
return m_pCJKOptions->IsVerticalCallOutEnabled();
}
//------------------------------------------------------------------------------
void SvtLanguageOptions::SetAll( sal_Bool _bSet )
{
m_pCJKOptions->SetAll( _bSet );
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsAnyEnabled() const
{
return m_pCJKOptions->IsAnyEnabled();
}
//------------------------------------------------------------------------------
// CTL options -----------------------------------------------------------------
//------------------------------------------------------------------------------
void SvtLanguageOptions::SetCTLFontEnabled( sal_Bool _bEnabled )
{
m_pCTLOptions->SetCTLFontEnabled( _bEnabled );
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsCTLFontEnabled() const
{
return m_pCTLOptions->IsCTLFontEnabled();
}
//------------------------------------------------------------------------------
void SvtLanguageOptions::SetCTLSequenceChecking( sal_Bool _bEnabled )
{
m_pCTLOptions->SetCTLSequenceChecking( _bEnabled );
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsCTLSequenceChecking() const
{
return m_pCTLOptions->IsCTLSequenceChecking();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsReadOnly(SvtLanguageOptions::EOption eOption) const
{
sal_Bool bReadOnly = sal_False;
switch(eOption)
{
// cjk options
case SvtLanguageOptions::E_CJKFONT : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_CJKFONT ); break;
case SvtLanguageOptions::E_VERTICALTEXT : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_VERTICALTEXT ); break;
case SvtLanguageOptions::E_ASIANTYPOGRAPHY : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_ASIANTYPOGRAPHY); break;
case SvtLanguageOptions::E_JAPANESEFIND : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_JAPANESEFIND ); break;
case SvtLanguageOptions::E_RUBY : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_RUBY ); break;
case SvtLanguageOptions::E_CHANGECASEMAP : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_CHANGECASEMAP ); break;
case SvtLanguageOptions::E_DOUBLELINES : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_DOUBLELINES ); break;
case SvtLanguageOptions::E_EMPHASISMARKS : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_EMPHASISMARKS ); break;
case SvtLanguageOptions::E_VERTICALCALLOUT : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_VERTICALCALLOUT); break;
case SvtLanguageOptions::E_ALLCJK : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_ALL ); break;
// ctl options
case SvtLanguageOptions::E_CTLFONT : bReadOnly = m_pCTLOptions->IsReadOnly(SvtCTLOptions::E_CTLFONT ); break;
case SvtLanguageOptions::E_CTLSEQUENCECHECKING : bReadOnly = m_pCTLOptions->IsReadOnly(SvtCTLOptions::E_CTLSEQUENCECHECKING); break;
case SvtLanguageOptions::E_CTLCURSORMOVEMENT : bReadOnly = m_pCTLOptions->IsReadOnly(SvtCTLOptions::E_CTLCURSORMOVEMENT ); break;
case SvtLanguageOptions::E_CTLTEXTNUMERALS : bReadOnly = m_pCTLOptions->IsReadOnly(SvtCTLOptions::E_CTLTEXTNUMERALS ); break;
}
return bReadOnly;
}
/* -----------------30.04.2003 11:03-----------------
--------------------------------------------------*/
void SvtLanguageOptions::Notify( SfxBroadcaster& rBC, const SfxHint& rHint )
{
vos::OGuard aVclGuard( Application::GetSolarMutex() );
Broadcast( rHint );
}
// -----------------------------------------------------------------------------
// returns for a language the scripttype
sal_uInt16 SvtLanguageOptions::GetScriptTypeOfLanguage( sal_uInt16 nLang )
{
if( LANGUAGE_DONTKNOW == nLang )
nLang = LANGUAGE_ENGLISH_US;
else if( LANGUAGE_SYSTEM == nLang )
nLang = Application::GetSettings().GetLanguage();
USHORT nScript;
switch( nLang )
{
// CJK
case LANGUAGE_CHINESE:
case LANGUAGE_CHINESE_TRADITIONAL:
case LANGUAGE_CHINESE_SIMPLIFIED:
case LANGUAGE_CHINESE_HONGKONG:
case LANGUAGE_CHINESE_SINGAPORE:
case LANGUAGE_CHINESE_MACAU:
case LANGUAGE_JAPANESE:
case LANGUAGE_KOREAN:
case LANGUAGE_KOREAN_JOHAB:
case LANGUAGE_USER_KOREAN_NORTH:
nScript = SCRIPTTYPE_ASIAN;
break;
// CTL
case LANGUAGE_ARABIC:
case LANGUAGE_ARABIC_SAUDI_ARABIA:
case LANGUAGE_ARABIC_IRAQ:
case LANGUAGE_ARABIC_EGYPT:
case LANGUAGE_ARABIC_LIBYA:
case LANGUAGE_ARABIC_ALGERIA:
case LANGUAGE_ARABIC_MOROCCO:
case LANGUAGE_ARABIC_TUNISIA:
case LANGUAGE_ARABIC_OMAN:
case LANGUAGE_ARABIC_YEMEN:
case LANGUAGE_ARABIC_SYRIA:
case LANGUAGE_ARABIC_JORDAN:
case LANGUAGE_ARABIC_LEBANON:
case LANGUAGE_ARABIC_KUWAIT:
case LANGUAGE_ARABIC_UAE:
case LANGUAGE_ARABIC_BAHRAIN:
case LANGUAGE_ARABIC_QATAR:
case LANGUAGE_ASSAMESE:
case LANGUAGE_BENGALI:
case LANGUAGE_BENGALI_BANGLADESH:
case LANGUAGE_FARSI:
case LANGUAGE_HEBREW:
case LANGUAGE_MARATHI:
case LANGUAGE_PUNJABI:
case LANGUAGE_GUJARATI:
case LANGUAGE_HINDI:
case LANGUAGE_KANNADA:
case LANGUAGE_KASHMIRI:
case LANGUAGE_KASHMIRI_INDIA:
case LANGUAGE_KHMER:
case LANGUAGE_LAO:
case LANGUAGE_MALAYALAM:
case LANGUAGE_MANIPURI:
case LANGUAGE_MONGOLIAN_MONGOLIAN:
case LANGUAGE_NEPALI:
case LANGUAGE_NEPALI_INDIA:
case LANGUAGE_ORIYA:
case LANGUAGE_SANSKRIT:
case LANGUAGE_SINDHI:
case LANGUAGE_SINDHI_PAKISTAN:
case LANGUAGE_SINHALESE_SRI_LANKA:
case LANGUAGE_SYRIAC:
case LANGUAGE_TAMIL:
case LANGUAGE_TELUGU:
case LANGUAGE_THAI:
case LANGUAGE_TIBETAN:
case LANGUAGE_DZONGKHA:
case LANGUAGE_URDU:
case LANGUAGE_URDU_PAKISTAN:
case LANGUAGE_URDU_INDIA:
case LANGUAGE_USER_KURDISH_IRAQ:
case LANGUAGE_USER_KURDISH_IRAN:
case LANGUAGE_VIETNAMESE:
nScript = SCRIPTTYPE_COMPLEX;
break;
// currently not knowing scripttype - defaultet to LATIN:
/*
#define LANGUAGE_ARMENIAN 0x042B
#define LANGUAGE_INDONESIAN 0x0421
#define LANGUAGE_KAZAK 0x043F
#define LANGUAGE_KONKANI 0x0457
#define LANGUAGE_MACEDONIAN 0x042F
#define LANGUAGE_TATAR 0x0444
*/
default:
switch ( nLang & LANGUAGE_MASK_PRIMARY )
{
// CJK catcher
case LANGUAGE_CHINESE & LANGUAGE_MASK_PRIMARY:
nScript = SCRIPTTYPE_ASIAN;
break;
// CTL catcher
case LANGUAGE_ARABIC & LANGUAGE_MASK_PRIMARY:
nScript = SCRIPTTYPE_COMPLEX;
break;
// Western (actually not necessarily Latin but also Cyrillic, for example)
default:
nScript = SCRIPTTYPE_LATIN;
}
break;
}
return nScript;
}
// -----------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>/*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
#include <limits>
#define FLATC_VERSION "1.3.0 (" __DATE__ ")"
static void Error(const std::string &err, bool usage = false,
bool show_exe_name = true);
// This struct allows us to create a table of all possible output generators
// for the various programming languages and formats we support.
struct Generator {
bool (*generate)(const flatbuffers::Parser &parser,
const std::string &path,
const std::string &file_name);
const char *generator_opt_short;
const char *generator_opt_long;
const char *lang_name;
flatbuffers::IDLOptions::Language lang;
const char *generator_help;
std::string (*make_rule)(const flatbuffers::Parser &parser,
const std::string &path,
const std::string &file_name);
};
const Generator generators[] = {
{ flatbuffers::GenerateBinary, "-b", "--binary", "binary",
flatbuffers::IDLOptions::kMAX,
"Generate wire format binaries for any data definitions",
flatbuffers::BinaryMakeRule },
{ flatbuffers::GenerateTextFile, "-t", "--json", "text",
flatbuffers::IDLOptions::kMAX,
"Generate text output for any data definitions",
flatbuffers::TextMakeRule },
{ flatbuffers::GenerateCPP, "-c", "--cpp", "C++",
flatbuffers::IDLOptions::kMAX,
"Generate C++ headers for tables/structs",
flatbuffers::CPPMakeRule },
{ flatbuffers::GenerateGo, "-g", "--go", "Go",
flatbuffers::IDLOptions::kGo,
"Generate Go files for tables/structs",
flatbuffers::GeneralMakeRule },
{ flatbuffers::GenerateGeneral, "-j", "--java", "Java",
flatbuffers::IDLOptions::kJava,
"Generate Java classes for tables/structs",
flatbuffers::GeneralMakeRule },
{ flatbuffers::GenerateJS, "-s", "--js", "JavaScript",
flatbuffers::IDLOptions::kMAX,
"Generate JavaScript code for tables/structs",
flatbuffers::JSMakeRule },
{ flatbuffers::GenerateGeneral, "-n", "--csharp", "C#",
flatbuffers::IDLOptions::kCSharp,
"Generate C# classes for tables/structs",
flatbuffers::GeneralMakeRule },
{ flatbuffers::GeneratePython, "-p", "--python", "Python",
flatbuffers::IDLOptions::kMAX,
"Generate Python files for tables/structs",
flatbuffers::GeneralMakeRule },
{ flatbuffers::GeneratePhp, nullptr, "--php", "PHP",
flatbuffers::IDLOptions::kMAX,
"Generate PHP files for tables/structs",
flatbuffers::GeneralMakeRule },
{ flatbuffers::GenerateGRPC, nullptr, "--grpc", "GRPC",
flatbuffers::IDLOptions::kMAX,
"Generate GRPC interfaces",
flatbuffers::CPPMakeRule },
};
const char *program_name = nullptr;
flatbuffers::Parser *parser = nullptr;
static void Error(const std::string &err, bool usage, bool show_exe_name) {
if (show_exe_name) printf("%s: ", program_name);
printf("%s\n", err.c_str());
if (usage) {
printf("usage: %s [OPTION]... FILE... [-- FILE...]\n", program_name);
for (size_t i = 0; i < sizeof(generators) / sizeof(generators[0]); ++i)
printf(" %-12s %s %s.\n",
generators[i].generator_opt_long,
generators[i].generator_opt_short
? generators[i].generator_opt_short
: " ",
generators[i].generator_help);
printf(
" -o PATH Prefix PATH to all generated files.\n"
" -I PATH Search for includes in the specified path.\n"
" -M Print make rules for generated files.\n"
" --version Print the version number of flatc and exit.\n"
" --strict-json Strict JSON: field names must be / will be quoted,\n"
" no trailing commas in tables/vectors.\n"
" --defaults-json Output fields whose value is the default when\n"
" writing JSON\n"
" --unknown-json Allow fields in JSON that are not defined in the\n"
" schema. These fields will be discared when generating\n"
" binaries.\n"
" --no-prefix Don\'t prefix enum values with the enum type in C++.\n"
" --scoped-enums Use C++11 style scoped and strongly typed enums.\n"
" also implies --no-prefix.\n"
" --gen-includes (deprecated), this is the default behavior.\n"
" If the original behavior is required (no include\n"
" statements) use --no-includes.\n"
" --no-includes Don\'t generate include statements for included\n"
" schemas the generated file depends on (C++).\n"
" --gen-mutable Generate accessors that can mutate buffers in-place.\n"
" --gen-onefile Generate single output file for C#.\n"
" --gen-name-strings Generate type name functions for C++.\n"
" --escape-proto-identifiers Disable appending '_' in namespaces names.\n"
" --raw-binary Allow binaries without file_indentifier to be read.\n"
" This may crash flatc given a mismatched schema.\n"
" --proto Input is a .proto, translate to .fbs.\n"
" --schema Serialize schemas instead of JSON (use with -b)\n"
"FILEs may be schemas, or JSON files (conforming to preceding schema)\n"
"FILEs after the -- must be binary flatbuffer format files.\n"
"Output files are named using the base file name of the input,\n"
"and written to the current directory or the path given by -o.\n"
"example: %s -c -b schema1.fbs schema2.fbs data.json\n",
program_name);
}
if (parser) delete parser;
exit(1);
}
int main(int argc, const char *argv[]) {
program_name = argv[0];
flatbuffers::IDLOptions opts;
std::string output_path;
const size_t num_generators = sizeof(generators) / sizeof(generators[0]);
bool generator_enabled[num_generators] = { false };
bool any_generator = false;
bool print_make_rules = false;
bool raw_binary = false;
bool schema_binary = false;
std::vector<std::string> filenames;
std::vector<const char *> include_directories;
size_t binary_files_from = std::numeric_limits<size_t>::max();
for (int argi = 1; argi < argc; argi++) {
std::string arg = argv[argi];
if (arg[0] == '-') {
if (filenames.size() && arg[1] != '-')
Error("invalid option location: " + arg, true);
if (arg == "-o") {
if (++argi >= argc) Error("missing path following: " + arg, true);
output_path = flatbuffers::ConCatPathFileName(argv[argi], "");
} else if(arg == "-I") {
if (++argi >= argc) Error("missing path following" + arg, true);
include_directories.push_back(argv[argi]);
} else if(arg == "--strict-json") {
opts.strict_json = true;
} else if(arg == "--no-js-exports") {
opts.skip_js_exports = true;
} else if(arg == "--defaults-json") {
opts.output_default_scalars_in_json = true;
} else if (arg == "--unknown-json") {
opts.skip_unexpected_fields_in_json = true;
} else if(arg == "--no-prefix") {
opts.prefixed_enums = false;
} else if(arg == "--scoped-enums") {
opts.prefixed_enums = false;
opts.scoped_enums = true;
} else if(arg == "--gen-mutable") {
opts.mutable_buffer = true;
} else if(arg == "--gen-name-strings") {
opts.generate_name_strings = true;
} else if(arg == "--gen-all") {
opts.generate_all = true;
opts.include_dependence_headers = false;
} else if(arg == "--gen-includes") {
// Deprecated, remove this option some time in the future.
printf("warning: --gen-includes is deprecated (it is now default)\n");
} else if(arg == "--no-includes") {
opts.include_dependence_headers = false;
} else if (arg == "--gen-onefile") {
opts.one_file = true;
} else if (arg == "--raw-binary") {
raw_binary = true;
} else if(arg == "--") { // Separator between text and binary inputs.
binary_files_from = filenames.size();
} else if(arg == "--proto") {
opts.proto_mode = true;
} else if (arg == "--escape-proto-identifiers") {
opts.escape_proto_identifiers = true;
} else if (arg == "--schema") {
schema_binary = true;
} else if(arg == "-M") {
print_make_rules = true;
} else if(arg == "--version") {
printf("flatc version %s\n", FLATC_VERSION);
exit(0);
} else {
for (size_t i = 0; i < num_generators; ++i) {
if (arg == generators[i].generator_opt_long ||
(generators[i].generator_opt_short &&
arg == generators[i].generator_opt_short)) {
generator_enabled[i] = true;
any_generator = true;
goto found;
}
}
Error("unknown commandline argument" + arg, true);
found:;
}
} else {
filenames.push_back(argv[argi]);
}
}
if (!filenames.size()) Error("missing input files", false, true);
if (opts.proto_mode) {
if (any_generator)
Error("cannot generate code directly from .proto files", true);
} else if (!any_generator) {
Error("no options: specify at least one generator.", true);
}
// Now process the files:
parser = new flatbuffers::Parser(opts);
for (auto file_it = filenames.begin();
file_it != filenames.end();
++file_it) {
std::string contents;
if (!flatbuffers::LoadFile(file_it->c_str(), true, &contents))
Error("unable to load file: " + *file_it);
bool is_binary = static_cast<size_t>(file_it - filenames.begin()) >=
binary_files_from;
if (is_binary) {
parser->builder_.Clear();
parser->builder_.PushFlatBuffer(
reinterpret_cast<const uint8_t *>(contents.c_str()),
contents.length());
if (!raw_binary) {
// Generally reading binaries that do not correspond to the schema
// will crash, and sadly there's no way around that when the binary
// does not contain a file identifier.
// We'd expect that typically any binary used as a file would have
// such an identifier, so by default we require them to match.
if (!parser->file_identifier_.length()) {
Error("current schema has no file_identifier: cannot test if \"" +
*file_it +
"\" matches the schema, use --raw-binary to read this file"
" anyway.");
} else if (!flatbuffers::BufferHasIdentifier(contents.c_str(),
parser->file_identifier_.c_str())) {
Error("binary \"" +
*file_it +
"\" does not have expected file_identifier \"" +
parser->file_identifier_ +
"\", use --raw-binary to read this file anyway.");
}
}
} else {
// Check if file contains 0 bytes.
if (contents.length() != strlen(contents.c_str())) {
Error("input file appears to be binary: " + *file_it, true);
}
if (flatbuffers::GetExtension(*file_it) == "fbs") {
// If we're processing multiple schemas, make sure to start each
// one from scratch. If it depends on previous schemas it must do
// so explicitly using an include.
delete parser;
parser = new flatbuffers::Parser(opts);
}
auto local_include_directory = flatbuffers::StripFileName(*file_it);
include_directories.push_back(local_include_directory.c_str());
include_directories.push_back(nullptr);
if (!parser->Parse(contents.c_str(), &include_directories[0],
file_it->c_str()))
Error(parser->error_, false, false);
if (schema_binary) {
parser->Serialize();
parser->file_extension_ = reflection::SchemaExtension();
}
include_directories.pop_back();
include_directories.pop_back();
}
std::string filebase = flatbuffers::StripPath(
flatbuffers::StripExtension(*file_it));
for (size_t i = 0; i < num_generators; ++i) {
parser->opts.lang = generators[i].lang;
if (generator_enabled[i]) {
if (!print_make_rules) {
flatbuffers::EnsureDirExists(output_path);
if (!generators[i].generate(*parser, output_path, filebase)) {
Error(std::string("Unable to generate ") +
generators[i].lang_name +
" for " +
filebase);
}
} else {
std::string make_rule = generators[i].make_rule(
*parser, output_path, *file_it);
if (!make_rule.empty())
printf("%s\n", flatbuffers::WordWrap(
make_rule, 80, " ", " \\").c_str());
}
}
}
if (opts.proto_mode) GenerateFBS(*parser, output_path, filebase, opts.escape_proto_identifiers)
// We do not want to generate code for the definitions in this file
// in any files coming up next.
parser->MarkGenerated();
}
delete parser;
return 0;
}
<commit_msg>Update flatc.cpp<commit_after>/*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
#include <limits>
#define FLATC_VERSION "1.3.0 (" __DATE__ ")"
static void Error(const std::string &err, bool usage = false,
bool show_exe_name = true);
// This struct allows us to create a table of all possible output generators
// for the various programming languages and formats we support.
struct Generator {
bool (*generate)(const flatbuffers::Parser &parser,
const std::string &path,
const std::string &file_name);
const char *generator_opt_short;
const char *generator_opt_long;
const char *lang_name;
flatbuffers::IDLOptions::Language lang;
const char *generator_help;
std::string (*make_rule)(const flatbuffers::Parser &parser,
const std::string &path,
const std::string &file_name);
};
const Generator generators[] = {
{ flatbuffers::GenerateBinary, "-b", "--binary", "binary",
flatbuffers::IDLOptions::kMAX,
"Generate wire format binaries for any data definitions",
flatbuffers::BinaryMakeRule },
{ flatbuffers::GenerateTextFile, "-t", "--json", "text",
flatbuffers::IDLOptions::kMAX,
"Generate text output for any data definitions",
flatbuffers::TextMakeRule },
{ flatbuffers::GenerateCPP, "-c", "--cpp", "C++",
flatbuffers::IDLOptions::kMAX,
"Generate C++ headers for tables/structs",
flatbuffers::CPPMakeRule },
{ flatbuffers::GenerateGo, "-g", "--go", "Go",
flatbuffers::IDLOptions::kGo,
"Generate Go files for tables/structs",
flatbuffers::GeneralMakeRule },
{ flatbuffers::GenerateGeneral, "-j", "--java", "Java",
flatbuffers::IDLOptions::kJava,
"Generate Java classes for tables/structs",
flatbuffers::GeneralMakeRule },
{ flatbuffers::GenerateJS, "-s", "--js", "JavaScript",
flatbuffers::IDLOptions::kMAX,
"Generate JavaScript code for tables/structs",
flatbuffers::JSMakeRule },
{ flatbuffers::GenerateGeneral, "-n", "--csharp", "C#",
flatbuffers::IDLOptions::kCSharp,
"Generate C# classes for tables/structs",
flatbuffers::GeneralMakeRule },
{ flatbuffers::GeneratePython, "-p", "--python", "Python",
flatbuffers::IDLOptions::kMAX,
"Generate Python files for tables/structs",
flatbuffers::GeneralMakeRule },
{ flatbuffers::GeneratePhp, nullptr, "--php", "PHP",
flatbuffers::IDLOptions::kMAX,
"Generate PHP files for tables/structs",
flatbuffers::GeneralMakeRule },
{ flatbuffers::GenerateGRPC, nullptr, "--grpc", "GRPC",
flatbuffers::IDLOptions::kMAX,
"Generate GRPC interfaces",
flatbuffers::CPPMakeRule },
};
const char *program_name = nullptr;
flatbuffers::Parser *parser = nullptr;
static void Error(const std::string &err, bool usage, bool show_exe_name) {
if (show_exe_name) printf("%s: ", program_name);
printf("%s\n", err.c_str());
if (usage) {
printf("usage: %s [OPTION]... FILE... [-- FILE...]\n", program_name);
for (size_t i = 0; i < sizeof(generators) / sizeof(generators[0]); ++i)
printf(" %-12s %s %s.\n",
generators[i].generator_opt_long,
generators[i].generator_opt_short
? generators[i].generator_opt_short
: " ",
generators[i].generator_help);
printf(
" -o PATH Prefix PATH to all generated files.\n"
" -I PATH Search for includes in the specified path.\n"
" -M Print make rules for generated files.\n"
" --version Print the version number of flatc and exit.\n"
" --strict-json Strict JSON: field names must be / will be quoted,\n"
" no trailing commas in tables/vectors.\n"
" --defaults-json Output fields whose value is the default when\n"
" writing JSON\n"
" --unknown-json Allow fields in JSON that are not defined in the\n"
" schema. These fields will be discared when generating\n"
" binaries.\n"
" --no-prefix Don\'t prefix enum values with the enum type in C++.\n"
" --scoped-enums Use C++11 style scoped and strongly typed enums.\n"
" also implies --no-prefix.\n"
" --gen-includes (deprecated), this is the default behavior.\n"
" If the original behavior is required (no include\n"
" statements) use --no-includes.\n"
" --no-includes Don\'t generate include statements for included\n"
" schemas the generated file depends on (C++).\n"
" --gen-mutable Generate accessors that can mutate buffers in-place.\n"
" --gen-onefile Generate single output file for C#.\n"
" --gen-name-strings Generate type name functions for C++.\n"
" --escape-proto-identifiers Disable appending '_' in namespaces names.\n"
" --raw-binary Allow binaries without file_indentifier to be read.\n"
" This may crash flatc given a mismatched schema.\n"
" --proto Input is a .proto, translate to .fbs.\n"
" --schema Serialize schemas instead of JSON (use with -b)\n"
"FILEs may be schemas, or JSON files (conforming to preceding schema)\n"
"FILEs after the -- must be binary flatbuffer format files.\n"
"Output files are named using the base file name of the input,\n"
"and written to the current directory or the path given by -o.\n"
"example: %s -c -b schema1.fbs schema2.fbs data.json\n",
program_name);
}
if (parser) delete parser;
exit(1);
}
int main(int argc, const char *argv[]) {
program_name = argv[0];
flatbuffers::IDLOptions opts;
std::string output_path;
const size_t num_generators = sizeof(generators) / sizeof(generators[0]);
bool generator_enabled[num_generators] = { false };
bool any_generator = false;
bool print_make_rules = false;
bool raw_binary = false;
bool schema_binary = false;
std::vector<std::string> filenames;
std::vector<const char *> include_directories;
size_t binary_files_from = std::numeric_limits<size_t>::max();
for (int argi = 1; argi < argc; argi++) {
std::string arg = argv[argi];
if (arg[0] == '-') {
if (filenames.size() && arg[1] != '-')
Error("invalid option location: " + arg, true);
if (arg == "-o") {
if (++argi >= argc) Error("missing path following: " + arg, true);
output_path = flatbuffers::ConCatPathFileName(argv[argi], "");
} else if(arg == "-I") {
if (++argi >= argc) Error("missing path following" + arg, true);
include_directories.push_back(argv[argi]);
} else if(arg == "--strict-json") {
opts.strict_json = true;
} else if(arg == "--no-js-exports") {
opts.skip_js_exports = true;
} else if(arg == "--defaults-json") {
opts.output_default_scalars_in_json = true;
} else if (arg == "--unknown-json") {
opts.skip_unexpected_fields_in_json = true;
} else if(arg == "--no-prefix") {
opts.prefixed_enums = false;
} else if(arg == "--scoped-enums") {
opts.prefixed_enums = false;
opts.scoped_enums = true;
} else if(arg == "--gen-mutable") {
opts.mutable_buffer = true;
} else if(arg == "--gen-name-strings") {
opts.generate_name_strings = true;
} else if(arg == "--gen-all") {
opts.generate_all = true;
opts.include_dependence_headers = false;
} else if(arg == "--gen-includes") {
// Deprecated, remove this option some time in the future.
printf("warning: --gen-includes is deprecated (it is now default)\n");
} else if(arg == "--no-includes") {
opts.include_dependence_headers = false;
} else if (arg == "--gen-onefile") {
opts.one_file = true;
} else if (arg == "--raw-binary") {
raw_binary = true;
} else if(arg == "--") { // Separator between text and binary inputs.
binary_files_from = filenames.size();
} else if(arg == "--proto") {
opts.proto_mode = true;
} else if (arg == "--escape-proto-identifiers") {
opts.escape_proto_identifiers = true;
} else if (arg == "--schema") {
schema_binary = true;
} else if(arg == "-M") {
print_make_rules = true;
} else if(arg == "--version") {
printf("flatc version %s\n", FLATC_VERSION);
exit(0);
} else {
for (size_t i = 0; i < num_generators; ++i) {
if (arg == generators[i].generator_opt_long ||
(generators[i].generator_opt_short &&
arg == generators[i].generator_opt_short)) {
generator_enabled[i] = true;
any_generator = true;
goto found;
}
}
Error("unknown commandline argument" + arg, true);
found:;
}
} else {
filenames.push_back(argv[argi]);
}
}
if (!filenames.size()) Error("missing input files", false, true);
if (opts.proto_mode) {
if (any_generator)
Error("cannot generate code directly from .proto files", true);
} else if (!any_generator) {
Error("no options: specify at least one generator.", true);
}
// Now process the files:
parser = new flatbuffers::Parser(opts);
for (auto file_it = filenames.begin();
file_it != filenames.end();
++file_it) {
std::string contents;
if (!flatbuffers::LoadFile(file_it->c_str(), true, &contents))
Error("unable to load file: " + *file_it);
bool is_binary = static_cast<size_t>(file_it - filenames.begin()) >=
binary_files_from;
if (is_binary) {
parser->builder_.Clear();
parser->builder_.PushFlatBuffer(
reinterpret_cast<const uint8_t *>(contents.c_str()),
contents.length());
if (!raw_binary) {
// Generally reading binaries that do not correspond to the schema
// will crash, and sadly there's no way around that when the binary
// does not contain a file identifier.
// We'd expect that typically any binary used as a file would have
// such an identifier, so by default we require them to match.
if (!parser->file_identifier_.length()) {
Error("current schema has no file_identifier: cannot test if \"" +
*file_it +
"\" matches the schema, use --raw-binary to read this file"
" anyway.");
} else if (!flatbuffers::BufferHasIdentifier(contents.c_str(),
parser->file_identifier_.c_str())) {
Error("binary \"" +
*file_it +
"\" does not have expected file_identifier \"" +
parser->file_identifier_ +
"\", use --raw-binary to read this file anyway.");
}
}
} else {
// Check if file contains 0 bytes.
if (contents.length() != strlen(contents.c_str())) {
Error("input file appears to be binary: " + *file_it, true);
}
if (flatbuffers::GetExtension(*file_it) == "fbs") {
// If we're processing multiple schemas, make sure to start each
// one from scratch. If it depends on previous schemas it must do
// so explicitly using an include.
delete parser;
parser = new flatbuffers::Parser(opts);
}
auto local_include_directory = flatbuffers::StripFileName(*file_it);
include_directories.push_back(local_include_directory.c_str());
include_directories.push_back(nullptr);
if (!parser->Parse(contents.c_str(), &include_directories[0],
file_it->c_str()))
Error(parser->error_, false, false);
if (schema_binary) {
parser->Serialize();
parser->file_extension_ = reflection::SchemaExtension();
}
include_directories.pop_back();
include_directories.pop_back();
}
std::string filebase = flatbuffers::StripPath(
flatbuffers::StripExtension(*file_it));
for (size_t i = 0; i < num_generators; ++i) {
parser->opts.lang = generators[i].lang;
if (generator_enabled[i]) {
if (!print_make_rules) {
flatbuffers::EnsureDirExists(output_path);
if (!generators[i].generate(*parser, output_path, filebase)) {
Error(std::string("Unable to generate ") +
generators[i].lang_name +
" for " +
filebase);
}
} else {
std::string make_rule = generators[i].make_rule(
*parser, output_path, *file_it);
if (!make_rule.empty())
printf("%s\n", flatbuffers::WordWrap(
make_rule, 80, " ", " \\").c_str());
}
}
}
if (opts.proto_mode) GenerateFBS(*parser, output_path, filebase, opts.escape_proto_identifiers);
// We do not want to generate code for the definitions in this file
// in any files coming up next.
parser->MarkGenerated();
}
delete parser;
return 0;
}
<|endoftext|>
|
<commit_before>
/*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#if SK_SUPPORT_GPU
#include "GrFragmentProcessor.h"
#include "GrCoordTransform.h"
#include "gl/GrGLProcessor.h"
#include "gl/builders/GrGLProgramBuilder.h"
#include "Resources.h"
#include "SkShader.h"
#include "SkStream.h"
#include "SkTypeface.h"
namespace skiagm {
///////////////////////////////////////////////////////////////////////////////
class DCShader : public SkShader {
public:
DCShader(const SkMatrix& matrix) : fDeviceMatrix(matrix) {}
// This is a custom shader, so we don't need to make it
// flattenable. Since this class is not part of the skia library,
// it wouldn't deserialize without linking this library anyway.
SK_DECLARE_NOT_FLATTENABLE_PROCS(DCShader)
bool asFragmentProcessor(GrContext*, const SkPaint& paint, const SkMatrix& viewM,
const SkMatrix* localMatrix, GrColor* color,
GrFragmentProcessor** fp) const SK_OVERRIDE;
private:
const SkMatrix fDeviceMatrix;
};
class DCFP : public GrFragmentProcessor {
public:
DCFP(const SkMatrix& m) : fDeviceTransform(kDevice_GrCoordSet, m) {
this->addCoordTransform(&fDeviceTransform);
this->initClassID<DCFP>();
}
void getGLProcessorKey(const GrGLCaps& caps,
GrProcessorKeyBuilder* b) const SK_OVERRIDE {}
GrGLFragmentProcessor* createGLInstance() const SK_OVERRIDE {
class DCGLFP : public GrGLFragmentProcessor {
void emitCode(GrGLFPBuilder* builder,
const GrFragmentProcessor& fp,
const char* outputColor,
const char* inputColor,
const TransformedCoordsArray& coords,
const TextureSamplerArray& samplers) {
GrGLFPFragmentBuilder* fpb = builder->getFragmentShaderBuilder();
fpb->codeAppendf("vec2 c = %s;", fpb->ensureFSCoords2D(coords, 0).c_str());
fpb->codeAppend("vec2 r = mod(c, vec2(20.0));");
fpb->codeAppend("vec4 color = vec4(0.5*sin(c.x / 15.0) + 0.5,"
"0.5*cos((c.x + c.y) / 15.0) + 0.5,"
"(r.x + r.y) / 20.0,"
"distance(r, vec2(15.0)) / 20.0 + 0.2);");
fpb->codeAppendf("color.rgb *= color.a;"
"%s = color * %s;",
outputColor, GrGLSLExpr4(inputColor).c_str());
}
void setData(const GrGLProgramDataManager&, const GrProcessor&) SK_OVERRIDE {}
};
return SkNEW(DCGLFP);
}
const char* name() const SK_OVERRIDE { return "DCFP"; }
void onComputeInvariantOutput(GrInvariantOutput* inout) const SK_OVERRIDE {
inout->mulByUnknownFourComponents();
}
private:
bool onIsEqual(const GrFragmentProcessor&) const SK_OVERRIDE { return true; }
GrCoordTransform fDeviceTransform;
};
bool DCShader::asFragmentProcessor(GrContext*, const SkPaint& paint, const SkMatrix& viewM,
const SkMatrix* localMatrix, GrColor* color,
GrFragmentProcessor** fp) const {
*fp = SkNEW_ARGS(DCFP, (fDeviceMatrix));
*color = GrColorPackA4(paint.getAlpha());
return true;
}
class DCShaderGM : public GM {
public:
DCShaderGM() {
this->setBGColor(0xFFAABBCC);
}
~DCShaderGM() SK_OVERRIDE {
for (int i = 0; i < fPrims.count(); ++i) {
SkDELETE(fPrims[i]);
}
}
protected:
uint32_t onGetFlags() const SK_OVERRIDE {
return kGPUOnly_Flag;
}
SkString onShortName() SK_OVERRIDE {
return SkString("dcshader");
}
SkISize onISize() SK_OVERRIDE { return SkISize::Make(1000, 900); }
void onOnceBeforeDraw() SK_OVERRIDE {
struct Rect : public Prim {
SkRect draw(SkCanvas* canvas, const SkPaint& paint) SK_OVERRIDE {
SkRect rect = SkRect::MakeXYWH(0, 0, 50, 50);
canvas->drawRect(rect, paint);
return rect;
}
};
struct Circle : public Prim {
SkRect draw(SkCanvas* canvas, const SkPaint& paint) SK_OVERRIDE {
static const SkScalar radius = 25;
canvas->drawCircle(radius, radius, radius, paint);
return SkRect::MakeXYWH(0, 0, 2 * radius, 2 * radius);
}
};
struct RRect : public Prim {
SkRect draw(SkCanvas* canvas, const SkPaint& paint) SK_OVERRIDE {
SkRRect rrect;
rrect.setRectXY(SkRect::MakeXYWH(0, 0, 50, 50), 10, 10);
canvas->drawRRect(rrect, paint);
return rrect.getBounds();
}
};
struct DRRect : public Prim {
SkRect draw(SkCanvas* canvas, const SkPaint& paint) SK_OVERRIDE {
SkRRect outerRRect;
outerRRect.setRectXY(SkRect::MakeXYWH(0, 0, 50, 50), 5, 5);
SkRRect innerRRect;
innerRRect.setRectXY(SkRect::MakeXYWH(5, 8, 35, 30), 8, 3);
canvas->drawDRRect(outerRRect, innerRRect, paint);
return outerRRect.getBounds();
}
};
struct Path : public Prim {
SkRect draw(SkCanvas* canvas, const SkPaint& paint) SK_OVERRIDE {
SkPath path;
path.addCircle(15, 15, 10);
path.addOval(SkRect::MakeXYWH(2, 2, 22, 37));
path.setFillType(SkPath::kEvenOdd_FillType);
canvas->drawPath(path, paint);
return path.getBounds();
}
};
struct Points : public Prim {
Points(SkCanvas::PointMode mode) : fMode(mode) {}
SkRect draw(SkCanvas* canvas, const SkPaint& paint) SK_OVERRIDE {
SkRandom random;
SkPoint points[500];
SkRect bounds = SkRect::MakeWH(50, 50);
int count = SkToInt(SK_ARRAY_COUNT(points));
if (SkCanvas::kPoints_PointMode != fMode) {
count = SkTMin(count, 10);
}
for (int p = 0; p < count; ++p) {
points[p].fX = random.nextUScalar1() * bounds.width();
points[p].fY = random.nextUScalar1() * bounds.width();
}
canvas->drawPoints(fMode, count, points, paint);
return bounds;
}
SkCanvas::PointMode fMode;
};
struct Text : public Prim {
SkRect draw(SkCanvas* canvas, const SkPaint& origPaint) SK_OVERRIDE {
SkPaint paint = origPaint;
paint.setTextSize(30.f);
this->setFont(&paint);
const char* text = this->text();
static const SkVector offset = SkVector::Make(10, 10);
canvas->drawText(text, strlen(text), offset.fX, offset.fY, paint);
SkRect bounds;
paint.measureText(text, strlen(text), &bounds);
bounds.offset(offset);
return bounds;
}
virtual void setFont(SkPaint* paint) {
sk_tool_utils::set_portable_typeface(paint);
}
virtual const char* text() const { return "Hello, Skia!"; }
};
struct BmpText : public Text {
void setFont(SkPaint* paint) SK_OVERRIDE {
if (!fTypeface) {
SkString filename = GetResourcePath("/Funkster.ttf");
SkAutoTUnref<SkFILEStream> stream(new SkFILEStream(filename.c_str()));
if (!stream->isValid()) {
SkDebugf("Could not find Funkster.ttf, please set --resourcePath "
"correctly.\n");
return;
}
fTypeface.reset(SkTypeface::CreateFromStream(stream));
}
paint->setTypeface(fTypeface);
}
const char* text() const SK_OVERRIDE { return "Hi, Skia!"; }
SkAutoTUnref<SkTypeface> fTypeface;
};
fPrims.push_back(SkNEW(Rect));
fPrims.push_back(SkNEW(Circle));
fPrims.push_back(SkNEW(RRect));
fPrims.push_back(SkNEW(DRRect));
fPrims.push_back(SkNEW(Path));
fPrims.push_back(SkNEW(Points(SkCanvas::kPoints_PointMode)));
fPrims.push_back(SkNEW(Points(SkCanvas::kLines_PointMode)));
fPrims.push_back(SkNEW(Points(SkCanvas::kPolygon_PointMode)));
fPrims.push_back(SkNEW(Text));
fPrims.push_back(SkNEW(BmpText));
}
void onDraw(SkCanvas* canvas) SK_OVERRIDE {
SkPaint paint;
SkTArray<SkMatrix> devMats;
devMats.push_back().reset();
devMats.push_back().setRotate(45, 500, 500);
devMats.push_back().setRotate(-30, 200, 200);
devMats.back().setPerspX(-SkScalarToPersp(SK_Scalar1 / 2000));
devMats.back().setPerspY(SkScalarToPersp(SK_Scalar1 / 1000));
SkTArray<SkMatrix> viewMats;
viewMats.push_back().setScale(0.75f, 0.75f);
viewMats.push_back().setRotate(45, 50, 50);
viewMats.back().postScale(0.5f, 1.1f);
canvas->translate(10, 20);
canvas->save();
SkScalar tx = 0, maxTy = 0;
static const SkScalar kW = 900;
for (int aa = 0; aa < 2; ++aa) {
for (int i = 0; i < fPrims.count(); ++i) {
for (int j = 0; j < devMats.count(); ++j) {
for (int k = 0; k < viewMats.count(); ++k) {
paint.setShader(SkNEW_ARGS(DCShader, (devMats[j])))->unref();
paint.setAntiAlias(SkToBool(aa));
canvas->save();
canvas->concat(viewMats[k]);
SkRect bounds = fPrims[i]->draw(canvas, paint);
canvas->restore();
viewMats[k].mapRect(&bounds);
// add margins
bounds.fRight += 20;
bounds.fBottom += 20;
canvas->translate(bounds.fRight, 0);
tx += bounds.fRight;
maxTy = SkTMax(bounds.fBottom, maxTy);
if (tx > kW) {
tx = 0;
canvas->restore();
canvas->translate(0, maxTy);
canvas->save();
maxTy = 0;
}
}
}
}
}
canvas->restore();
}
private:
struct Prim {
virtual ~Prim() {}
virtual SkRect draw(SkCanvas*, const SkPaint&) = 0;
};
SkTArray<Prim*> fPrims;
typedef GM INHERITED;
};
DEF_GM( return SkNEW(DCShaderGM); )
}
#endif
<commit_msg>Make DCShader serializable.<commit_after>
/*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#if SK_SUPPORT_GPU
#include "GrFragmentProcessor.h"
#include "GrCoordTransform.h"
#include "gl/GrGLProcessor.h"
#include "gl/builders/GrGLProgramBuilder.h"
#include "Resources.h"
#include "SkReadBuffer.h"
#include "SkShader.h"
#include "SkStream.h"
#include "SkTypeface.h"
#include "SkWriteBuffer.h"
namespace skiagm {
///////////////////////////////////////////////////////////////////////////////
class DCShader : public SkShader {
public:
DCShader(const SkMatrix& matrix) : fDeviceMatrix(matrix) {}
SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(DCShader);
void flatten(SkWriteBuffer& buf) const SK_OVERRIDE {
buf.writeMatrix(fDeviceMatrix);
}
bool asFragmentProcessor(GrContext*, const SkPaint& paint, const SkMatrix& viewM,
const SkMatrix* localMatrix, GrColor* color,
GrFragmentProcessor** fp) const SK_OVERRIDE;
private:
const SkMatrix fDeviceMatrix;
};
SkFlattenable* DCShader::CreateProc(SkReadBuffer& buf) {
SkMatrix matrix;
buf.readMatrix(&matrix);
return SkNEW_ARGS(DCShader, (matrix));
}
class DCFP : public GrFragmentProcessor {
public:
DCFP(const SkMatrix& m) : fDeviceTransform(kDevice_GrCoordSet, m) {
this->addCoordTransform(&fDeviceTransform);
this->initClassID<DCFP>();
}
void getGLProcessorKey(const GrGLCaps& caps,
GrProcessorKeyBuilder* b) const SK_OVERRIDE {}
GrGLFragmentProcessor* createGLInstance() const SK_OVERRIDE {
class DCGLFP : public GrGLFragmentProcessor {
void emitCode(GrGLFPBuilder* builder,
const GrFragmentProcessor& fp,
const char* outputColor,
const char* inputColor,
const TransformedCoordsArray& coords,
const TextureSamplerArray& samplers) {
GrGLFPFragmentBuilder* fpb = builder->getFragmentShaderBuilder();
fpb->codeAppendf("vec2 c = %s;", fpb->ensureFSCoords2D(coords, 0).c_str());
fpb->codeAppend("vec2 r = mod(c, vec2(20.0));");
fpb->codeAppend("vec4 color = vec4(0.5*sin(c.x / 15.0) + 0.5,"
"0.5*cos((c.x + c.y) / 15.0) + 0.5,"
"(r.x + r.y) / 20.0,"
"distance(r, vec2(15.0)) / 20.0 + 0.2);");
fpb->codeAppendf("color.rgb *= color.a;"
"%s = color * %s;",
outputColor, GrGLSLExpr4(inputColor).c_str());
}
void setData(const GrGLProgramDataManager&, const GrProcessor&) SK_OVERRIDE {}
};
return SkNEW(DCGLFP);
}
const char* name() const SK_OVERRIDE { return "DCFP"; }
void onComputeInvariantOutput(GrInvariantOutput* inout) const SK_OVERRIDE {
inout->mulByUnknownFourComponents();
}
private:
bool onIsEqual(const GrFragmentProcessor&) const SK_OVERRIDE { return true; }
GrCoordTransform fDeviceTransform;
};
bool DCShader::asFragmentProcessor(GrContext*, const SkPaint& paint, const SkMatrix& viewM,
const SkMatrix* localMatrix, GrColor* color,
GrFragmentProcessor** fp) const {
*fp = SkNEW_ARGS(DCFP, (fDeviceMatrix));
*color = GrColorPackA4(paint.getAlpha());
return true;
}
class DCShaderGM : public GM {
public:
DCShaderGM() {
this->setBGColor(0xFFAABBCC);
}
~DCShaderGM() SK_OVERRIDE {
for (int i = 0; i < fPrims.count(); ++i) {
SkDELETE(fPrims[i]);
}
}
protected:
uint32_t onGetFlags() const SK_OVERRIDE {
return kGPUOnly_Flag;
}
SkString onShortName() SK_OVERRIDE {
return SkString("dcshader");
}
SkISize onISize() SK_OVERRIDE { return SkISize::Make(1000, 900); }
void onOnceBeforeDraw() SK_OVERRIDE {
struct Rect : public Prim {
SkRect draw(SkCanvas* canvas, const SkPaint& paint) SK_OVERRIDE {
SkRect rect = SkRect::MakeXYWH(0, 0, 50, 50);
canvas->drawRect(rect, paint);
return rect;
}
};
struct Circle : public Prim {
SkRect draw(SkCanvas* canvas, const SkPaint& paint) SK_OVERRIDE {
static const SkScalar radius = 25;
canvas->drawCircle(radius, radius, radius, paint);
return SkRect::MakeXYWH(0, 0, 2 * radius, 2 * radius);
}
};
struct RRect : public Prim {
SkRect draw(SkCanvas* canvas, const SkPaint& paint) SK_OVERRIDE {
SkRRect rrect;
rrect.setRectXY(SkRect::MakeXYWH(0, 0, 50, 50), 10, 10);
canvas->drawRRect(rrect, paint);
return rrect.getBounds();
}
};
struct DRRect : public Prim {
SkRect draw(SkCanvas* canvas, const SkPaint& paint) SK_OVERRIDE {
SkRRect outerRRect;
outerRRect.setRectXY(SkRect::MakeXYWH(0, 0, 50, 50), 5, 5);
SkRRect innerRRect;
innerRRect.setRectXY(SkRect::MakeXYWH(5, 8, 35, 30), 8, 3);
canvas->drawDRRect(outerRRect, innerRRect, paint);
return outerRRect.getBounds();
}
};
struct Path : public Prim {
SkRect draw(SkCanvas* canvas, const SkPaint& paint) SK_OVERRIDE {
SkPath path;
path.addCircle(15, 15, 10);
path.addOval(SkRect::MakeXYWH(2, 2, 22, 37));
path.setFillType(SkPath::kEvenOdd_FillType);
canvas->drawPath(path, paint);
return path.getBounds();
}
};
struct Points : public Prim {
Points(SkCanvas::PointMode mode) : fMode(mode) {}
SkRect draw(SkCanvas* canvas, const SkPaint& paint) SK_OVERRIDE {
SkRandom random;
SkPoint points[500];
SkRect bounds = SkRect::MakeWH(50, 50);
int count = SkToInt(SK_ARRAY_COUNT(points));
if (SkCanvas::kPoints_PointMode != fMode) {
count = SkTMin(count, 10);
}
for (int p = 0; p < count; ++p) {
points[p].fX = random.nextUScalar1() * bounds.width();
points[p].fY = random.nextUScalar1() * bounds.width();
}
canvas->drawPoints(fMode, count, points, paint);
return bounds;
}
SkCanvas::PointMode fMode;
};
struct Text : public Prim {
SkRect draw(SkCanvas* canvas, const SkPaint& origPaint) SK_OVERRIDE {
SkPaint paint = origPaint;
paint.setTextSize(30.f);
this->setFont(&paint);
const char* text = this->text();
static const SkVector offset = SkVector::Make(10, 10);
canvas->drawText(text, strlen(text), offset.fX, offset.fY, paint);
SkRect bounds;
paint.measureText(text, strlen(text), &bounds);
bounds.offset(offset);
return bounds;
}
virtual void setFont(SkPaint* paint) {
sk_tool_utils::set_portable_typeface(paint);
}
virtual const char* text() const { return "Hello, Skia!"; }
};
struct BmpText : public Text {
void setFont(SkPaint* paint) SK_OVERRIDE {
if (!fTypeface) {
SkString filename = GetResourcePath("/Funkster.ttf");
SkAutoTUnref<SkFILEStream> stream(new SkFILEStream(filename.c_str()));
if (!stream->isValid()) {
SkDebugf("Could not find Funkster.ttf, please set --resourcePath "
"correctly.\n");
return;
}
fTypeface.reset(SkTypeface::CreateFromStream(stream));
}
paint->setTypeface(fTypeface);
}
const char* text() const SK_OVERRIDE { return "Hi, Skia!"; }
SkAutoTUnref<SkTypeface> fTypeface;
};
fPrims.push_back(SkNEW(Rect));
fPrims.push_back(SkNEW(Circle));
fPrims.push_back(SkNEW(RRect));
fPrims.push_back(SkNEW(DRRect));
fPrims.push_back(SkNEW(Path));
fPrims.push_back(SkNEW(Points(SkCanvas::kPoints_PointMode)));
fPrims.push_back(SkNEW(Points(SkCanvas::kLines_PointMode)));
fPrims.push_back(SkNEW(Points(SkCanvas::kPolygon_PointMode)));
fPrims.push_back(SkNEW(Text));
fPrims.push_back(SkNEW(BmpText));
}
void onDraw(SkCanvas* canvas) SK_OVERRIDE {
SkPaint paint;
SkTArray<SkMatrix> devMats;
devMats.push_back().reset();
devMats.push_back().setRotate(45, 500, 500);
devMats.push_back().setRotate(-30, 200, 200);
devMats.back().setPerspX(-SkScalarToPersp(SK_Scalar1 / 2000));
devMats.back().setPerspY(SkScalarToPersp(SK_Scalar1 / 1000));
SkTArray<SkMatrix> viewMats;
viewMats.push_back().setScale(0.75f, 0.75f);
viewMats.push_back().setRotate(45, 50, 50);
viewMats.back().postScale(0.5f, 1.1f);
canvas->translate(10, 20);
canvas->save();
SkScalar tx = 0, maxTy = 0;
static const SkScalar kW = 900;
for (int aa = 0; aa < 2; ++aa) {
for (int i = 0; i < fPrims.count(); ++i) {
for (int j = 0; j < devMats.count(); ++j) {
for (int k = 0; k < viewMats.count(); ++k) {
paint.setShader(SkNEW_ARGS(DCShader, (devMats[j])))->unref();
paint.setAntiAlias(SkToBool(aa));
canvas->save();
canvas->concat(viewMats[k]);
SkRect bounds = fPrims[i]->draw(canvas, paint);
canvas->restore();
viewMats[k].mapRect(&bounds);
// add margins
bounds.fRight += 20;
bounds.fBottom += 20;
canvas->translate(bounds.fRight, 0);
tx += bounds.fRight;
maxTy = SkTMax(bounds.fBottom, maxTy);
if (tx > kW) {
tx = 0;
canvas->restore();
canvas->translate(0, maxTy);
canvas->save();
maxTy = 0;
}
}
}
}
}
canvas->restore();
}
private:
struct Prim {
virtual ~Prim() {}
virtual SkRect draw(SkCanvas*, const SkPaint&) = 0;
};
SkTArray<Prim*> fPrims;
typedef GM INHERITED;
};
DEF_GM( return SkNEW(DCShaderGM); )
}
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: hatchwindowfactory.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: kz $ $Date: 2004-10-04 19:46:51 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _XHATCHWINDOWFACTORY_HXX_
#define _XHATCHWINDOWFACTORY_HXX_
#ifndef _COM_SUN_STAR_EMBED_XHATCHWINDOWFACTORY_HPP_
#include <com/sun/star/embed/XHatchWindowFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE5_HXX_
#include <cppuhelper/implbase2.hxx>
#endif
class OHatchWindowFactory : public ::cppu::WeakImplHelper2<
::com::sun::star::embed::XHatchWindowFactory,
::com::sun::star::lang::XServiceInfo >
{
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xFactory;
public:
OHatchWindowFactory(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory )
: m_xFactory( xFactory )
{
OSL_ENSURE( xFactory.is(), "No service manager is provided!\n" );
}
static ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL impl_staticGetSupportedServiceNames();
static ::rtl::OUString SAL_CALL impl_staticGetImplementationName();
static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL
impl_staticCreateSelfInstance(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager );
// XHatchWindowFactory
virtual ::com::sun::star::uno::Reference< ::com::sun::star::embed::XHatchWindow > SAL_CALL createHatchWindowInstance( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer >& xParent, const ::com::sun::star::awt::Rectangle& aBounds, const ::com::sun::star::awt::Size& aSize ) throw (::com::sun::star::uno::RuntimeException);
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName() throw (::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw (::com::sun::star::uno::RuntimeException);
};
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.380); FILE MERGED 2005/09/05 14:53:16 rt 1.2.380.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: hatchwindowfactory.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 15:54:23 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _XHATCHWINDOWFACTORY_HXX_
#define _XHATCHWINDOWFACTORY_HXX_
#ifndef _COM_SUN_STAR_EMBED_XHATCHWINDOWFACTORY_HPP_
#include <com/sun/star/embed/XHatchWindowFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE5_HXX_
#include <cppuhelper/implbase2.hxx>
#endif
class OHatchWindowFactory : public ::cppu::WeakImplHelper2<
::com::sun::star::embed::XHatchWindowFactory,
::com::sun::star::lang::XServiceInfo >
{
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xFactory;
public:
OHatchWindowFactory(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory )
: m_xFactory( xFactory )
{
OSL_ENSURE( xFactory.is(), "No service manager is provided!\n" );
}
static ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL impl_staticGetSupportedServiceNames();
static ::rtl::OUString SAL_CALL impl_staticGetImplementationName();
static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL
impl_staticCreateSelfInstance(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager );
// XHatchWindowFactory
virtual ::com::sun::star::uno::Reference< ::com::sun::star::embed::XHatchWindow > SAL_CALL createHatchWindowInstance( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer >& xParent, const ::com::sun::star::awt::Rectangle& aBounds, const ::com::sun::star::awt::Size& aSize ) throw (::com::sun::star::uno::RuntimeException);
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName() throw (::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw (::com::sun::star::uno::RuntimeException);
};
#endif
<|endoftext|>
|
<commit_before>#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;
#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
const ll M = 1000000007;
typedef tuple<ll, int, int> key; // bit, backback, back
vector<ll> connected[60][60];
map<key, ll> dp;
int N;
vector<int> V[60];
void make_connected(int x, int y) {
bool visited[60];
fill(visited, visited+60, false);
visited[x] = true;
visited[y] = true;
for (auto i = 0; i < N; ++i) {
if (visited[i]) continue;
ll ans = 0;
stack<int> S;
S.push(i);
while (!S.empty()) {
int now = S.top();
S.pop();
if (!visited[now]) {
visited[now] = true;
ans += 1ll << now;
for (auto e : V[now]) {
if (!visited[e]) {
S.push(e);
}
}
}
}
connected[x][y].push_back(ans);
}
connected[y][x] = connected[x][y];
}
inline bool all_or_nothing(const ll& bit, const ll& con) {
if ((bit & con) == con) return true;
// ll hanten = ((1ll << 55) - 1) ^ bit;
return (((((1ll << 55) - 1) ^ bit) & con) == con);
}
inline bool valid(key k) {
const ll& bit = get<0>(k);
const int& a = get<1>(k);
const int& b = get<2>(k);
for (auto& x : connected[a][b]) {
if (!(all_or_nothing(bit, x))) return false;
}
return true;
}
inline int cnt_one(ll bit) {
int cnt = 0;
while (bit > 0) {
if ((bit & 1ll) == 1) ++cnt;
bit = (bit >> 1);
}
return cnt;
}
ll value(key k) {
ll bit = get<0>(k);
int c = cnt_one(bit);
// if (c == 1) return 1;
if (!valid(k)) return 0;
if (c == 2) return 1;
auto it = dp.find(k);
if (it != dp.end()) return (*it).second;
ll ans = 0;
const int& a = get<1>(k);
const int& b = get<2>(k);
bit -= (1ll << b);
for (auto i = 0; i < N; ++i) {
if (i == a) continue;
if ((bit & (1ll << i)) == 0) continue;
ans += value(key(bit, i, a));
ans %= M;
}
dp[k] = ans;
return ans;
}
int main () {
cin >> N;
for (auto i = 0; i < N-1; ++i) {
int a, b;
cin >> a >> b;
--a;
--b;
}
if (N == 1) {
cout << 1 << endl;
return 0;
} else if (N == 2) {
cout << 2 << endl;
return 0;
}
for (auto i = 0; i < N; ++i) {
if (V[i].size() > 4) {
cout << 0 << endl;
return 0;
}
}
for (auto i = 0; i < N; ++i) {
for (auto j = i+1; j < N; ++j) {
make_connected(i, j);
}
}
ll ans = 0;
for (auto i = 0; i < N; ++i) {
for (auto j = 0; j < N; ++j) {
if (i == j) continue;
cerr << "i = " << i << ", j = " << j << ", val = "
<< value(key(((1ll << N) - 1), i, j)) << endl;
ans += value(key(((1ll << N) - 1), i, j));
ans %= M;
}
}
cout << ans << endl;
}
<commit_msg>tried D.cpp to 'D'<commit_after>#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;
#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
const ll M = 1000000007;
typedef tuple<ll, int, int> key; // bit, backback, back
vector<ll> connected[60][60];
map<key, ll> dp;
int N;
vector<int> V[60];
void make_connected(int x, int y) {
bool visited[60];
fill(visited, visited+60, false);
visited[x] = true;
visited[y] = true;
for (auto i = 0; i < N; ++i) {
if (visited[i]) continue;
ll ans = 0;
stack<int> S;
S.push(i);
while (!S.empty()) {
int now = S.top();
S.pop();
if (!visited[now]) {
visited[now] = true;
ans += 1ll << now;
for (auto e : V[now]) {
if (!visited[e]) {
S.push(e);
}
}
}
}
connected[x][y].push_back(ans);
}
connected[y][x] = connected[x][y];
}
inline bool all_or_nothing(const ll& bit, const ll& con) {
ll hanten = ((1ll << N) - 1) ^ bit;
cerr << "bit = " << bit << ", con = " << con
<< ", hanten = " << hanten << endl;
if ((bit & con) == con) {
return true;
}
return (((((1ll << N) - 1) ^ bit) & con) == con);
}
inline bool valid(key k) {
const ll& bit = get<0>(k);
const int& a = get<1>(k);
const int& b = get<2>(k);
for (auto& x : connected[a][b]) {
if (!(all_or_nothing(bit, x))) return false;
}
return true;
}
inline int cnt_one(ll bit) {
int cnt = 0;
while (bit > 0) {
if ((bit & 1ll) == 1) ++cnt;
bit = (bit >> 1);
}
return cnt;
}
ll value(key k) {
ll bit = get<0>(k);
int c = cnt_one(bit);
// if (c == 1) return 1;
if (!valid(k)) return 0;
if (c == 2) return 1;
auto it = dp.find(k);
if (it != dp.end()) return (*it).second;
ll ans = 0;
const int& a = get<1>(k);
const int& b = get<2>(k);
bit -= (1ll << b);
for (auto i = 0; i < N; ++i) {
if (i == a) continue;
if ((bit & (1ll << i)) == 0) continue;
ans += value(key(bit, i, a));
ans %= M;
}
dp[k] = ans;
return ans;
}
int main () {
cin >> N;
for (auto i = 0; i < N-1; ++i) {
int a, b;
cin >> a >> b;
--a;
--b;
}
if (N == 1) {
cout << 1 << endl;
return 0;
} else if (N == 2) {
cout << 2 << endl;
return 0;
}
for (auto i = 0; i < N; ++i) {
if (V[i].size() > 4) {
cout << 0 << endl;
return 0;
}
}
for (auto i = 0; i < N; ++i) {
for (auto j = i+1; j < N; ++j) {
make_connected(i, j);
}
}
ll ans = 0;
for (auto i = 0; i < N; ++i) {
for (auto j = 0; j < N; ++j) {
if (i == j) continue;
cerr << "i = " << i << ", j = " << j << ", val = "
<< value(key(((1ll << N) - 1), i, j)) << endl;
ans += value(key(((1ll << N) - 1), i, j));
ans %= M;
}
}
cout << ans << endl;
}
<|endoftext|>
|
<commit_before>// Game_Music_Emu https://bitbucket.org/mpyne/game-music-emu/
#include "Spc_Emu.h"
#include "blargg_endian.h"
#include <stdlib.h>
#include <string.h>
/* Copyright (C) 2004-2006 Shay Green. This module 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
module 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 module; if not, write to the Free Software Foundation,
Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */
#include "blargg_source.h"
// TODO: support Spc_Filter's bass
Spc_Emu::Spc_Emu()
{
set_type( gme_spc_type );
static const char* const names [Snes_Spc::voice_count] = {
"DSP 1", "DSP 2", "DSP 3", "DSP 4", "DSP 5", "DSP 6", "DSP 7", "DSP 8"
};
set_voice_names( names );
set_gain( 1.4 );
}
Spc_Emu::~Spc_Emu() { }
// Track info
long const trailer_offset = 0x10200;
byte const* Spc_Emu::trailer() const { return &file_data [min( file_size, trailer_offset )]; }
long Spc_Emu::trailer_size() const { return max( 0L, file_size - trailer_offset ); }
static void get_spc_xid6( byte const* begin, long size, track_info_t* out )
{
// header
byte const* end = begin + size;
if ( size < 8 || memcmp( begin, "xid6", 4 ) )
{
check( false );
return;
}
long info_size = get_le32( begin + 4 );
byte const* in = begin + 8;
if ( end - in > info_size )
{
debug_printf( "Extra data after SPC xid6 info\n" );
end = in + info_size;
}
int year = 0;
char copyright [256 + 5];
int copyright_len = 0;
int const year_len = 5;
while ( end - in >= 4 )
{
// header
int id = in [0];
int data = in [3] * 0x100 + in [2];
int type = in [1];
int len = type ? data : 0;
in += 4;
if ( len > end - in )
{
check( false );
break; // block goes past end of data
}
// handle specific block types
char* field = 0;
switch ( id )
{
case 0x01: field = out->song; break;
case 0x02: field = out->game; break;
case 0x03: field = out->author; break;
case 0x04: field = out->dumper; break;
case 0x07: field = out->comment; break;
case 0x14: year = data; break;
//case 0x30: // intro length
// Many SPCs have intro length set wrong for looped tracks, making it useless
/*
case 0x30:
check( len == 4 );
if ( len >= 4 )
{
out->intro_length = get_le32( in ) / 64;
if ( out->length > 0 )
{
long loop = out->length - out->intro_length;
if ( loop >= 2000 )
out->loop_length = loop;
}
}
break;
*/
case 0x13:
copyright_len = min( len, (int) sizeof copyright - year_len );
memcpy( ©right [year_len], in, copyright_len );
break;
default:
if ( id < 0x01 || (id > 0x07 && id < 0x10) ||
(id > 0x14 && id < 0x30) || id > 0x36 )
debug_printf( "Unknown SPC xid6 block: %X\n", (int) id );
break;
}
if ( field )
{
check( type == 1 );
Gme_File::copy_field_( field, (char const*) in, len );
}
// skip to next block
in += len;
// blocks are supposed to be 4-byte aligned with zero-padding...
byte const* unaligned = in;
while ( (in - begin) & 3 && in < end )
{
if ( *in++ != 0 )
{
// ...but some files have no padding
in = unaligned;
debug_printf( "SPC info tag wasn't properly padded to align\n" );
break;
}
}
}
char* p = ©right [year_len];
if ( year )
{
*--p = ' ';
for ( int n = 4; n--; )
{
*--p = char (year % 10 + '0');
year /= 10;
}
copyright_len += year_len;
}
if ( copyright_len )
Gme_File::copy_field_( out->copyright, p, copyright_len );
check( in == end );
}
static void get_spc_info( Spc_Emu::header_t const& h, byte const* xid6, long xid6_size,
track_info_t* out )
{
// decode length (can be in text or binary format, sometimes ambiguous ugh)
long len_secs = 0;
for ( int i = 0; i < 3; i++ )
{
unsigned n = h.len_secs [i] - '0';
if ( n > 9 )
{
// ignore single-digit text lengths
// (except if author field is present and begins at offset 1, ugh)
if ( i == 1 && (h.author [0] || !h.author [1]) )
len_secs = 0;
break;
}
len_secs *= 10;
len_secs += n;
}
if ( !len_secs || len_secs > 0x1FFF )
len_secs = get_le16( h.len_secs );
if ( len_secs < 0x1FFF )
out->length = len_secs * 1000;
int offset = (h.author [0] < ' ' || unsigned (h.author [0] - '0') <= 9);
Gme_File::copy_field_( out->author, &h.author [offset], sizeof h.author - offset );
GME_COPY_FIELD( h, out, song );
GME_COPY_FIELD( h, out, game );
GME_COPY_FIELD( h, out, dumper );
GME_COPY_FIELD( h, out, comment );
if ( xid6_size )
get_spc_xid6( xid6, xid6_size, out );
}
blargg_err_t Spc_Emu::track_info_( track_info_t* out, int ) const
{
get_spc_info( header(), trailer(), trailer_size(), out );
return 0;
}
static blargg_err_t check_spc_header( void const* header )
{
if ( memcmp( header, "SNES-SPC700 Sound File Data", 27 ) )
return gme_wrong_file_type;
return 0;
}
struct Spc_File : Gme_Info_
{
Spc_Emu::header_t header;
blargg_vector<byte> xid6;
Spc_File() { set_type( gme_spc_type ); }
blargg_err_t load_( Data_Reader& in )
{
long file_size = in.remain();
if ( file_size < Snes_Spc::spc_min_file_size )
return gme_wrong_file_type;
RETURN_ERR( in.read( &header, Spc_Emu::header_size ) );
RETURN_ERR( check_spc_header( header.tag ) );
long const xid6_offset = 0x10200;
long xid6_size = file_size - xid6_offset;
if ( xid6_size > 0 )
{
RETURN_ERR( xid6.resize( xid6_size ) );
RETURN_ERR( in.skip( xid6_offset - Spc_Emu::header_size ) );
RETURN_ERR( in.read( xid6.begin(), xid6.size() ) );
}
return 0;
}
blargg_err_t track_info_( track_info_t* out, int ) const
{
get_spc_info( header, xid6.begin(), xid6.size(), out );
return 0;
}
};
static Music_Emu* new_spc_emu () { return BLARGG_NEW Spc_Emu ; }
static Music_Emu* new_spc_file() { return BLARGG_NEW Spc_File; }
static gme_type_t_ const gme_spc_type_ = { "Super Nintendo", 1, &new_spc_emu, &new_spc_file, "SPC", 0 };
BLARGG_EXPORT extern gme_type_t const gme_spc_type = &gme_spc_type_;
// Setup
blargg_err_t Spc_Emu::set_sample_rate_( long sample_rate )
{
RETURN_ERR( apu.init() );
enable_accuracy( false );
if ( sample_rate != native_sample_rate )
{
RETURN_ERR( resampler.buffer_size( native_sample_rate / 20 * 2 ) );
resampler.time_ratio( (double) native_sample_rate / sample_rate, 0.9965 );
}
return 0;
}
void Spc_Emu::enable_accuracy_( bool b )
{
Music_Emu::enable_accuracy_( b );
filter.enable( b );
}
void Spc_Emu::mute_voices_( int m )
{
Music_Emu::mute_voices_( m );
apu.mute_voices( m );
}
blargg_err_t Spc_Emu::load_mem_( byte const* in, long size )
{
assert( offsetof (header_t,unused2 [46]) == header_size );
file_data = in;
file_size = size;
set_voice_count( Snes_Spc::voice_count );
if ( size < Snes_Spc::spc_min_file_size )
return gme_wrong_file_type;
return check_spc_header( in );
}
// Emulation
void Spc_Emu::set_tempo_( double t )
{
apu.set_tempo( (int) (t * apu.tempo_unit) );
}
blargg_err_t Spc_Emu::start_track_( int track )
{
RETURN_ERR( Music_Emu::start_track_( track ) );
resampler.clear();
filter.clear();
RETURN_ERR( apu.load_spc( file_data, file_size ) );
filter.set_gain( (int) (gain() * SPC_Filter::gain_unit) );
apu.clear_echo();
return 0;
}
blargg_err_t Spc_Emu::play_and_filter( long count, sample_t out [] )
{
RETURN_ERR( apu.play( count, out ) );
filter.run( out, count );
return 0;
}
blargg_err_t Spc_Emu::skip_( long count )
{
if ( sample_rate() != native_sample_rate )
{
count = long (count * resampler.ratio()) & ~1;
count -= resampler.skip_input( count );
}
// TODO: shouldn't skip be adjusted for the 64 samples read afterwards?
if ( count > 0 )
{
RETURN_ERR( apu.skip( count ) );
filter.clear();
}
// eliminate pop due to resampler
const int resampler_latency = 64;
sample_t buf [resampler_latency];
return play_( resampler_latency, buf );
}
blargg_err_t Spc_Emu::play_( long count, sample_t* out )
{
if ( sample_rate() == native_sample_rate )
return play_and_filter( count, out );
long remain = count;
while ( remain > 0 )
{
remain -= resampler.read( &out [count - remain], remain );
if ( remain > 0 )
{
long n = resampler.max_write();
RETURN_ERR( play_and_filter( n, resampler.buffer() ) );
resampler.write( n );
}
}
check( remain == 0 );
return 0;
}
<commit_msg>spc: Set a playback length by default if set in header.<commit_after>// Game_Music_Emu https://bitbucket.org/mpyne/game-music-emu/
#include "Spc_Emu.h"
#include "blargg_endian.h"
#include <stdlib.h>
#include <string.h>
/* Copyright (C) 2004-2006 Shay Green. This module 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
module 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 module; if not, write to the Free Software Foundation,
Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */
#include "blargg_source.h"
// TODO: support Spc_Filter's bass
Spc_Emu::Spc_Emu()
{
set_type( gme_spc_type );
static const char* const names [Snes_Spc::voice_count] = {
"DSP 1", "DSP 2", "DSP 3", "DSP 4", "DSP 5", "DSP 6", "DSP 7", "DSP 8"
};
set_voice_names( names );
set_gain( 1.4 );
}
Spc_Emu::~Spc_Emu() { }
// Track info
long const trailer_offset = 0x10200;
byte const* Spc_Emu::trailer() const { return &file_data [min( file_size, trailer_offset )]; }
long Spc_Emu::trailer_size() const { return max( 0L, file_size - trailer_offset ); }
static void get_spc_xid6( byte const* begin, long size, track_info_t* out )
{
// header
byte const* end = begin + size;
if ( size < 8 || memcmp( begin, "xid6", 4 ) )
{
check( false );
return;
}
long info_size = get_le32( begin + 4 );
byte const* in = begin + 8;
if ( end - in > info_size )
{
debug_printf( "Extra data after SPC xid6 info\n" );
end = in + info_size;
}
int year = 0;
char copyright [256 + 5];
int copyright_len = 0;
int const year_len = 5;
while ( end - in >= 4 )
{
// header
int id = in [0];
int data = in [3] * 0x100 + in [2];
int type = in [1];
int len = type ? data : 0;
in += 4;
if ( len > end - in )
{
check( false );
break; // block goes past end of data
}
// handle specific block types
char* field = 0;
switch ( id )
{
case 0x01: field = out->song; break;
case 0x02: field = out->game; break;
case 0x03: field = out->author; break;
case 0x04: field = out->dumper; break;
case 0x07: field = out->comment; break;
case 0x14: year = data; break;
//case 0x30: // intro length
// Many SPCs have intro length set wrong for looped tracks, making it useless
/*
case 0x30:
check( len == 4 );
if ( len >= 4 )
{
out->intro_length = get_le32( in ) / 64;
if ( out->length > 0 )
{
long loop = out->length - out->intro_length;
if ( loop >= 2000 )
out->loop_length = loop;
}
}
break;
*/
case 0x13:
copyright_len = min( len, (int) sizeof copyright - year_len );
memcpy( ©right [year_len], in, copyright_len );
break;
default:
if ( id < 0x01 || (id > 0x07 && id < 0x10) ||
(id > 0x14 && id < 0x30) || id > 0x36 )
debug_printf( "Unknown SPC xid6 block: %X\n", (int) id );
break;
}
if ( field )
{
check( type == 1 );
Gme_File::copy_field_( field, (char const*) in, len );
}
// skip to next block
in += len;
// blocks are supposed to be 4-byte aligned with zero-padding...
byte const* unaligned = in;
while ( (in - begin) & 3 && in < end )
{
if ( *in++ != 0 )
{
// ...but some files have no padding
in = unaligned;
debug_printf( "SPC info tag wasn't properly padded to align\n" );
break;
}
}
}
char* p = ©right [year_len];
if ( year )
{
*--p = ' ';
for ( int n = 4; n--; )
{
*--p = char (year % 10 + '0');
year /= 10;
}
copyright_len += year_len;
}
if ( copyright_len )
Gme_File::copy_field_( out->copyright, p, copyright_len );
check( in == end );
}
static void get_spc_info( Spc_Emu::header_t const& h, byte const* xid6, long xid6_size,
track_info_t* out )
{
// decode length (can be in text or binary format, sometimes ambiguous ugh)
long len_secs = 0;
for ( int i = 0; i < 3; i++ )
{
unsigned n = h.len_secs [i] - '0';
if ( n > 9 )
{
// ignore single-digit text lengths
// (except if author field is present and begins at offset 1, ugh)
if ( i == 1 && (h.author [0] || !h.author [1]) )
len_secs = 0;
break;
}
len_secs *= 10;
len_secs += n;
}
if ( !len_secs || len_secs > 0x1FFF )
len_secs = get_le16( h.len_secs );
if ( len_secs < 0x1FFF )
out->length = len_secs * 1000;
int offset = (h.author [0] < ' ' || unsigned (h.author [0] - '0') <= 9);
Gme_File::copy_field_( out->author, &h.author [offset], sizeof h.author - offset );
GME_COPY_FIELD( h, out, song );
GME_COPY_FIELD( h, out, game );
GME_COPY_FIELD( h, out, dumper );
GME_COPY_FIELD( h, out, comment );
if ( xid6_size )
get_spc_xid6( xid6, xid6_size, out );
}
blargg_err_t Spc_Emu::track_info_( track_info_t* out, int ) const
{
get_spc_info( header(), trailer(), trailer_size(), out );
return 0;
}
static blargg_err_t check_spc_header( void const* header )
{
if ( memcmp( header, "SNES-SPC700 Sound File Data", 27 ) )
return gme_wrong_file_type;
return 0;
}
struct Spc_File : Gme_Info_
{
Spc_Emu::header_t header;
blargg_vector<byte> xid6;
Spc_File() { set_type( gme_spc_type ); }
blargg_err_t load_( Data_Reader& in )
{
long file_size = in.remain();
if ( file_size < Snes_Spc::spc_min_file_size )
return gme_wrong_file_type;
RETURN_ERR( in.read( &header, Spc_Emu::header_size ) );
RETURN_ERR( check_spc_header( header.tag ) );
long const xid6_offset = 0x10200;
long xid6_size = file_size - xid6_offset;
if ( xid6_size > 0 )
{
RETURN_ERR( xid6.resize( xid6_size ) );
RETURN_ERR( in.skip( xid6_offset - Spc_Emu::header_size ) );
RETURN_ERR( in.read( xid6.begin(), xid6.size() ) );
}
return 0;
}
blargg_err_t track_info_( track_info_t* out, int ) const
{
get_spc_info( header, xid6.begin(), xid6.size(), out );
return 0;
}
};
static Music_Emu* new_spc_emu () { return BLARGG_NEW Spc_Emu ; }
static Music_Emu* new_spc_file() { return BLARGG_NEW Spc_File; }
static gme_type_t_ const gme_spc_type_ = { "Super Nintendo", 1, &new_spc_emu, &new_spc_file, "SPC", 0 };
BLARGG_EXPORT extern gme_type_t const gme_spc_type = &gme_spc_type_;
// Setup
blargg_err_t Spc_Emu::set_sample_rate_( long sample_rate )
{
RETURN_ERR( apu.init() );
enable_accuracy( false );
if ( sample_rate != native_sample_rate )
{
RETURN_ERR( resampler.buffer_size( native_sample_rate / 20 * 2 ) );
resampler.time_ratio( (double) native_sample_rate / sample_rate, 0.9965 );
}
return 0;
}
void Spc_Emu::enable_accuracy_( bool b )
{
Music_Emu::enable_accuracy_( b );
filter.enable( b );
}
void Spc_Emu::mute_voices_( int m )
{
Music_Emu::mute_voices_( m );
apu.mute_voices( m );
}
blargg_err_t Spc_Emu::load_mem_( byte const* in, long size )
{
assert( offsetof (header_t,unused2 [46]) == header_size );
file_data = in;
file_size = size;
set_voice_count( Snes_Spc::voice_count );
if ( size < Snes_Spc::spc_min_file_size )
return gme_wrong_file_type;
return check_spc_header( in );
}
// Emulation
void Spc_Emu::set_tempo_( double t )
{
apu.set_tempo( (int) (t * apu.tempo_unit) );
}
blargg_err_t Spc_Emu::start_track_( int track )
{
RETURN_ERR( Music_Emu::start_track_( track ) );
resampler.clear();
filter.clear();
RETURN_ERR( apu.load_spc( file_data, file_size ) );
filter.set_gain( (int) (gain() * SPC_Filter::gain_unit) );
apu.clear_echo();
track_info_t spc_info;
RETURN_ERR( track_info_( &spc_info, track ) );
// Set a default track length, need a non-zero fadeout
if ( spc_info.length > 0 )
set_fade ( spc_info.length, 50 );
return 0;
}
blargg_err_t Spc_Emu::play_and_filter( long count, sample_t out [] )
{
RETURN_ERR( apu.play( count, out ) );
filter.run( out, count );
return 0;
}
blargg_err_t Spc_Emu::skip_( long count )
{
if ( sample_rate() != native_sample_rate )
{
count = long (count * resampler.ratio()) & ~1;
count -= resampler.skip_input( count );
}
// TODO: shouldn't skip be adjusted for the 64 samples read afterwards?
if ( count > 0 )
{
RETURN_ERR( apu.skip( count ) );
filter.clear();
}
// eliminate pop due to resampler
const int resampler_latency = 64;
sample_t buf [resampler_latency];
return play_( resampler_latency, buf );
}
blargg_err_t Spc_Emu::play_( long count, sample_t* out )
{
if ( sample_rate() == native_sample_rate )
return play_and_filter( count, out );
long remain = count;
while ( remain > 0 )
{
remain -= resampler.read( &out [count - remain], remain );
if ( remain > 0 )
{
long n = resampler.max_write();
RETURN_ERR( play_and_filter( n, resampler.buffer() ) );
resampler.write( n );
}
}
check( remain == 0 );
return 0;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <chrono>
#include <thread>
#include <numeric>
#include <libdariadb/timeutil.h>
#include <libdariadb/engine.h>
#include <libdariadb/meas.h>
#include <libdariadb/utils/logger.h>
#include <libdariadb/utils/locker.h>
#include <libclient/client.h>
#include <libserver/server.h>
#include <boost/program_options.hpp>
using namespace dariadb;
using namespace dariadb::storage;
namespace po = boost::program_options;
std::string storage_path = "dariadb_storage";
unsigned short server_port = 2001;
std::string server_host = "127.0.0.1";
bool run_server_flag = true;
size_t server_threads_count = dariadb::net::SERVER_IO_THREADS_DEFAULT;
STRATEGY strategy = STRATEGY::FAST_WRITE;
Time cap_store_period = 0;
size_t clients_count = 5;
bool dont_clean=false;
Engine* engine = nullptr;
dariadb::net::Server*server_instance = nullptr;
void run_server() {
bool is_exists = false;
if (dariadb::utils::fs::path_exists(storage_path)) {
if(!dont_clean){
std::cout<<"remove old storage..."<<std::endl;
dariadb::utils::fs::rm(storage_path);
}else{
is_exists = true;
}
}
if (is_exists) {
Options::start(storage_path);
}
else {
Options::start();
}
Options::instance()->cap_store_period = cap_store_period;
Options::instance()->strategy = strategy;
Options::instance()->path = storage_path;
Options::instance()->aof_max_size = Options::instance()->measurements_count();
engine = new Engine();
if (!is_exists) {
Options::instance()->save();
}
dariadb::net::Server::Param server_param(server_port, server_threads_count);
server_instance=new dariadb::net::Server(server_param);
server_instance->set_storage(engine);
server_instance->start();
while (!server_instance->is_runned()) {
}
}
const size_t MEASES_SIZE = 2000;
const size_t SEND_COUNT = 200;
std::vector<float> elapsed;
std::vector<std::thread> threads;
std::vector<dariadb::net::client::Client_Ptr> clients;
void write_thread(dariadb::net::client::Client_Ptr client, size_t thread_num) {
dariadb::MeasArray ma;
ma.resize(MEASES_SIZE);
for (size_t i = 0; i < MEASES_SIZE; ++i) {
ma[i].id = dariadb::Id(i);
ma[i].value = dariadb::Value(i);
ma[i].time = i;
}
auto start = clock();
for(size_t i=0;i<SEND_COUNT;++i){
client->append(ma);
}
auto el = (((float)clock() - start) / CLOCKS_PER_SEC);
elapsed[thread_num]=el;
}
int main(int argc,char**argv){
po::options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
("storage-path", po::value<std::string>(&storage_path)->default_value(storage_path), "path to storage.")
("port", po::value<unsigned short>(&server_port)->default_value(server_port), "server port.")
("server-host", po::value<std::string>(&server_host)->default_value(server_host), "server host.")
("io-threads", po::value<size_t>(&server_threads_count)->default_value(server_threads_count), "server threads for query processing.")
("strategy", po::value<STRATEGY>(&strategy)->default_value(strategy),"write strategy.")
("store-period",po::value<Time>(&cap_store_period)->default_value(cap_store_period), "store period in CAP level.")
("clients-count", po::value<size_t>(&clients_count)->default_value(clients_count), "clients count.")
("dont-clean", po::value<bool>(&dont_clean)->default_value(dont_clean), "dont clean folder with storage if exists.")
("extern-server", "dont run server.");
po::variables_map vm;
try {
po::store(po::parse_command_line(argc, argv, desc), vm);
}
catch (std::exception &ex) {
dariadb::logger("Error: ", ex.what());
exit(1);
}
po::notify(vm);
if (vm.count("help")) {
std::cout << desc << std::endl;
std::exit(0);
}
if (vm.count("extern-server")) {
run_server_flag = false;
}
elapsed.resize(clients_count);
threads.resize(clients_count);
clients.resize(clients_count);
if (run_server_flag) {
run_server();
}
dariadb::net::client::Client::Param p(server_host, server_port);
for (size_t i = 0; i < clients_count; ++i) {
clients[i]=dariadb::net::client::Client_Ptr{ new dariadb::net::client::Client(p) };
clients[i]->connect();
}
auto start = clock();
for (size_t i = 0; i < clients_count; ++i) {
auto t=std::thread{ write_thread, clients[i], i };
threads[i] = std::move(t);
}
for (size_t i = 0; i < clients_count; ++i) {
threads[i].join();
clients[i]->disconnect();
while (clients[i]->state() != dariadb::net::ClientState::DISCONNECTED) {
std::this_thread::yield();
}
}
auto total_elapsed = (((float)clock() - start) / CLOCKS_PER_SEC);
if(run_server_flag){
server_instance->stop();
while (server_instance->is_runned()) {
std::this_thread::yield();
}
delete engine;
}
auto count_per_thread=MEASES_SIZE*SEND_COUNT;
auto total_writed = count_per_thread*clients_count;
std::cout << "writed: " << total_writed << std::endl;
std::cout << "total write time: " << total_elapsed << std::endl;
std::cout << "total speed: " << total_writed /total_elapsed<<" per sec." << std::endl;
auto average_time=std::accumulate(elapsed.begin(),elapsed.end(),0.0)/clients_count;
std::cout << "average time: " << average_time<<" sec." << std::endl;
std::cout << "average speed: " << count_per_thread/(float)(average_time)<<" per sec." << std::endl;
}
<commit_msg>net_bench: refact.<commit_after>#include <iostream>
#include <chrono>
#include <thread>
#include <numeric>
#include <libdariadb/timeutil.h>
#include <libdariadb/engine.h>
#include <libdariadb/meas.h>
#include <libdariadb/utils/logger.h>
#include <libdariadb/utils/locker.h>
#include <libclient/client.h>
#include <libserver/server.h>
#include <boost/program_options.hpp>
using namespace dariadb;
using namespace dariadb::storage;
namespace po = boost::program_options;
std::string storage_path = "dariadb_storage";
unsigned short server_port = 2001;
std::string server_host = "127.0.0.1";
bool run_server_flag = true;
size_t server_threads_count = dariadb::net::SERVER_IO_THREADS_DEFAULT;
STRATEGY strategy = STRATEGY::FAST_WRITE;
Time cap_store_period = 0;
size_t clients_count = 5;
bool dont_clean=false;
Engine* engine = nullptr;
dariadb::net::Server*server_instance = nullptr;
void run_server() {
bool is_exists = false;
if (dariadb::utils::fs::path_exists(storage_path)) {
if(!dont_clean){
std::cout<<"remove old storage..."<<std::endl;
dariadb::utils::fs::rm(storage_path);
}else{
is_exists = true;
}
}
if (is_exists) {
Options::start(storage_path);
}
else {
Options::start();
}
Options::instance()->cap_store_period = cap_store_period;
Options::instance()->strategy = strategy;
Options::instance()->path = storage_path;
Options::instance()->aof_max_size = Options::instance()->measurements_count();
engine = new Engine();
if (!is_exists) {
Options::instance()->save();
}
dariadb::net::Server::Param server_param(server_port, server_threads_count);
server_instance=new dariadb::net::Server(server_param);
server_instance->set_storage(engine);
server_instance->start();
while (!server_instance->is_runned()) {
}
}
const size_t MEASES_SIZE = 2000;
const size_t SEND_COUNT = 200;
std::vector<float> elapsed;
std::vector<std::thread> threads;
std::vector<dariadb::net::client::Client_Ptr> clients;
void write_thread(dariadb::net::client::Client_Ptr client, size_t thread_num) {
dariadb::MeasArray ma;
ma.resize(MEASES_SIZE);
for (size_t i = 0; i < MEASES_SIZE; ++i) {
ma[i].id = dariadb::Id(thread_num);
ma[i].value = dariadb::Value(i);
ma[i].time = i;
}
auto start = clock();
for(size_t i=0;i<SEND_COUNT;++i){
client->append(ma);
}
auto el = (((float)clock() - start) / CLOCKS_PER_SEC);
elapsed[thread_num]=el;
}
int main(int argc,char**argv){
po::options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
("storage-path", po::value<std::string>(&storage_path)->default_value(storage_path), "path to storage.")
("port", po::value<unsigned short>(&server_port)->default_value(server_port), "server port.")
("server-host", po::value<std::string>(&server_host)->default_value(server_host), "server host.")
("io-threads", po::value<size_t>(&server_threads_count)->default_value(server_threads_count), "server threads for query processing.")
("strategy", po::value<STRATEGY>(&strategy)->default_value(strategy),"write strategy.")
("store-period",po::value<Time>(&cap_store_period)->default_value(cap_store_period), "store period in CAP level.")
("clients-count", po::value<size_t>(&clients_count)->default_value(clients_count), "clients count.")
("dont-clean", po::value<bool>(&dont_clean)->default_value(dont_clean), "dont clean folder with storage if exists.")
("extern-server", "dont run server.");
po::variables_map vm;
try {
po::store(po::parse_command_line(argc, argv, desc), vm);
}
catch (std::exception &ex) {
dariadb::logger("Error: ", ex.what());
exit(1);
}
po::notify(vm);
if (vm.count("help")) {
std::cout << desc << std::endl;
std::exit(0);
}
if (vm.count("extern-server")) {
run_server_flag = false;
}
elapsed.resize(clients_count);
threads.resize(clients_count);
clients.resize(clients_count);
if (run_server_flag) {
run_server();
}
dariadb::net::client::Client::Param p(server_host, server_port);
for (size_t i = 0; i < clients_count; ++i) {
clients[i]=dariadb::net::client::Client_Ptr{ new dariadb::net::client::Client(p) };
clients[i]->connect();
}
for (size_t i = 0; i < clients_count; ++i) {
auto t=std::thread{ write_thread, clients[i], i };
threads[i] = std::move(t);
}
for (size_t i = 0; i < clients_count; ++i) {
threads[i].join();
clients[i]->disconnect();
while (clients[i]->state() != dariadb::net::ClientState::DISCONNECTED) {
std::this_thread::yield();
}
}
dariadb::net::client::Client_Ptr c{ new dariadb::net::client::Client(p) };
c->connect();
dariadb::storage::QueryInterval ri(dariadb::IdArray{0},0,0,MEASES_SIZE);
auto result=c->readInterval(ri);
if(run_server_flag){
server_instance->stop();
while (server_instance->is_runned()) {
std::this_thread::yield();
}
delete engine;
}
auto count_per_thread=MEASES_SIZE*SEND_COUNT;
auto total_writed = count_per_thread*clients_count;
std::cout << "writed: " << total_writed << std::endl;
auto average_time=std::accumulate(elapsed.begin(),elapsed.end(),0.0)/clients_count;
std::cout << "average time: " << average_time<<" sec." << std::endl;
std::cout << "average speed: " << count_per_thread/(float)(average_time)<<" per sec." << std::endl;
std::cout<<"result:"<<result.size();
if(result.size()!=MEASES_SIZE*SEND_COUNT ){
THROW_EXCEPTION("result.size()!=MEASES_SIZE*SEND_COUNT: ", result.size());
}
}
<|endoftext|>
|
<commit_before>// HandleLeak.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "HandleLeak.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// The one and only application object
CWinApp theApp;
using namespace std;
void TestHandleLeak()
{
cout << __FUNCTION__ << endl;
SHELLEXECUTEINFO ShExecInfo = {0};
ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
ShExecInfo.hwnd = NULL;
ShExecInfo.lpVerb = _T("open");
ShExecInfo.lpFile = _T("cmd");
ShExecInfo.lpParameters = _T("/c echo 111");
ShExecInfo.lpDirectory = NULL;
ShExecInfo.nShow = SW_HIDE;
ShExecInfo.hInstApp = NULL;
ShellExecuteEx(&ShExecInfo);
WaitForSingleObject(ShExecInfo.hProcess,INFINITE);
return;
}
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;
HMODULE hModule = ::GetModuleHandle(NULL);
if (hModule != NULL)
{
// initialize MFC and print and error on failure
if (!AfxWinInit(hModule, NULL, ::GetCommandLine(), 0))
{
// TODO: change error code to suit your needs
_tprintf(_T("Fatal Error: MFC initialization failed\n"));
nRetCode = 1;
}
else
{
// TODO: code your application's behavior here.
int i = 0;
while (i < 10000)
{
TestHandleLeak();
Sleep(10);
}
}
}
else
{
// TODO: change error code to suit your needs
_tprintf(_T("Fatal Error: GetModuleHandle failed\n"));
nRetCode = 1;
}
return nRetCode;
}
<commit_msg>close handle<commit_after>// HandleLeak.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "HandleLeak.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// The one and only application object
CWinApp theApp;
using namespace std;
void TestHandleLeak()
{
cout << __FUNCTION__ << endl;
SHELLEXECUTEINFO ShExecInfo = {0};
ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
ShExecInfo.hwnd = NULL;
ShExecInfo.lpVerb = _T("open");
ShExecInfo.lpFile = _T("cmd");
ShExecInfo.lpParameters = _T("/c echo 111");
ShExecInfo.lpDirectory = NULL;
ShExecInfo.nShow = SW_HIDE;
ShExecInfo.hInstApp = NULL;
ShellExecuteEx(&ShExecInfo);
WaitForSingleObject(ShExecInfo.hProcess,INFINITE);
CloseHandle(ShExecInfo.hProcess);
return;
}
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;
HMODULE hModule = ::GetModuleHandle(NULL);
if (hModule != NULL)
{
// initialize MFC and print and error on failure
if (!AfxWinInit(hModule, NULL, ::GetCommandLine(), 0))
{
// TODO: change error code to suit your needs
_tprintf(_T("Fatal Error: MFC initialization failed\n"));
nRetCode = 1;
}
else
{
// TODO: code your application's behavior here.
int i = 0;
while (i < 10000)
{
TestHandleLeak();
}
}
}
else
{
// TODO: change error code to suit your needs
_tprintf(_T("Fatal Error: GetModuleHandle failed\n"));
nRetCode = 1;
}
return nRetCode;
}
<|endoftext|>
|
<commit_before>
#include "FlareSpacecraftDockingSystem.h"
#include "../../Flare.h"
#include "../FlareStationDock.h"
#include "../FlareStationConnector.h"
#include "../FlareSpacecraft.h"
#include "../../Game/FlareGame.h"
#include "../../Quests/FlareQuestManager.h"
DECLARE_CYCLE_STAT(TEXT("FlareDockingSystem Tick"), STAT_FlareDockingSystem_Tick, STATGROUP_Flare);
#define LOCTEXT_NAMESPACE "FlareDockingSystem"
/*----------------------------------------------------
Constructor
----------------------------------------------------*/
UFlareSpacecraftDockingSystem::UFlareSpacecraftDockingSystem(const class FObjectInitializer& PCIP)
: Super(PCIP)
, Spacecraft(NULL)
{
SCOPE_CYCLE_COUNTER(STAT_FlareDockingSystem_Tick);
}
/*----------------------------------------------------
Gameplay events
----------------------------------------------------*/
void UFlareSpacecraftDockingSystem::TickSystem(float DeltaSeconds)
{
}
void UFlareSpacecraftDockingSystem::Initialize(AFlareSpacecraft* OwnerSpacecraft, FFlareSpacecraftSave* OwnerData)
{
Spacecraft = OwnerSpacecraft;
Components = Spacecraft->GetComponentsByClass(UFlareSpacecraftComponent::StaticClass());
Description = Spacecraft->GetParent()->GetDescription();
Data = OwnerData;
}
void UFlareSpacecraftDockingSystem::Start()
{
// Dock data
int32 DockCount = 0;
int32 ConnectorCount = 0;
TArray<UActorComponent*> ActorComponents;
Spacecraft->GetComponents(ActorComponents);
for (TArray<UActorComponent*>::TIterator ComponentIt(ActorComponents); ComponentIt; ++ComponentIt)
{
FVector DockLocation;
FRotator DockRotation;
UFlareStationDock* DockComponent = Cast<UFlareStationDock>(*ComponentIt);
UFlareStationConnector* ConnectorComponent = Cast<UFlareStationConnector>(*ComponentIt);
// Fill dock slots
if (DockComponent)
{
DockComponent->GetSocketWorldLocationAndRotation(FName("dock"), DockLocation, DockRotation);
// Fill info
FFlareDockingInfo Info;
Info.Ship = NULL;
Info.LocalAxis = Spacecraft->Airframe->GetComponentToWorld().Inverse().GetRotation().RotateVector(DockRotation.RotateVector(FVector(1,0,0)));
Info.LocalTopAxis = Spacecraft->Airframe->GetComponentToWorld().Inverse().GetRotation().RotateVector(DockRotation.RotateVector(FVector(0,1,0)));
Info.LocalLocation = Spacecraft->Airframe->GetComponentToWorld().Inverse().TransformPosition(DockLocation);
Info.DockId = DockCount;
Info.DockSize = DockComponent->DockSize;
Info.Station = Spacecraft;
Info.Granted = false;
Info.Occupied = false;
// Push this slot
DockingSlots.Add(Info);
DockCount++;
}
// Fill connector data to the parent
if (ConnectorComponent)
{
FCHECK(ConnectorCount < Spacecraft->GetDescription()->StationConnectorCount);
FCHECK(ConnectorCount < Spacecraft->GetParent()->GetStationConnectors().Num());
// Fetch connector data
FFlareDockingInfo* StationConnection = Spacecraft->GetParent()->GetStationConnector(ConnectorComponent->SlotIdentifier);
FCHECK(StationConnection != NULL);
// Fill info
if (StationConnection)
{
ConnectorComponent->GetSocketWorldLocationAndRotation(FName("dock"), DockLocation, DockRotation);
StationConnection->Ship = NULL;
StationConnection->Station = Spacecraft;
StationConnection->LocalAxis = Spacecraft->Airframe->GetComponentToWorld().Inverse().GetRotation().RotateVector(DockRotation.RotateVector(FVector(1, 0, 0)));
StationConnection->LocalTopAxis = Spacecraft->Airframe->GetComponentToWorld().Inverse().GetRotation().RotateVector(DockRotation.RotateVector(FVector(0, 1, 0)));
StationConnection->LocalLocation = Spacecraft->Airframe->GetComponentToWorld().Inverse().TransformPosition(DockLocation);
StationConnection->Occupied = true;
}
else
{
FLOGV("UFlareSpacecraftDockingSystem::Start : couldn't find station connector '%s' in parent", *ConnectorComponent->SlotIdentifier.ToString());
}
ConnectorCount++;
}
}
}
bool UFlareSpacecraftDockingSystem::HasCompatibleDock(AFlareSpacecraft* Ship) const
{
for (int32 i = 0; i < DockingSlots.Num(); i++)
{
if (DockingSlots[i].DockSize == Ship->GetSize())
{
return true;
}
}
return false;
}
FFlareDockingInfo UFlareSpacecraftDockingSystem::RequestDock(AFlareSpacecraft* Ship, FVector PreferredLocation)
{
int32 BestIndex = -1;
float BestDistance = 0;
// Player docking data
FText PlayerDockInfo;
AFlareSpacecraft* PlayerDockSpacecraft;
FFlareDockingParameters PlayerDockingParameters;
AFlareSpacecraft* PlayerShip = Ship->GetGame()->GetPC()->GetShipPawn();
// Deny all docking requests if the player is docking
if (PlayerShip)
{
bool DockingInProgress = PlayerShip->GetManualDockingProgress(PlayerDockSpacecraft, PlayerDockingParameters, PlayerDockInfo);
if (DockingInProgress && PlayerDockSpacecraft == Spacecraft && PlayerShip != Ship)
{
FLOG("UFlareSpacecraftDockingSystem::RequestDock : denied, player is docking");
FFlareDockingInfo Info;
Info.Granted = false;
Info.Station = Spacecraft;
return Info;
}
}
// Looking for nearest available slot
for (int32 i = 0; i < DockingSlots.Num(); i++)
{
if (!DockingSlots[i].Granted && DockingSlots[i].DockSize == Ship->GetSize())
{
float DockDistance = (Spacecraft->Airframe->GetComponentToWorld().TransformPosition(DockingSlots[i].LocalLocation) - PreferredLocation).Size();
if (BestIndex < 0 || DockDistance < BestDistance)
{
BestDistance = DockDistance;
BestIndex = i;
}
}
}
// Granted
if (BestIndex >= 0)
{
DockingSlots[BestIndex].Granted = true;
DockingSlots[BestIndex].Ship = Ship;
return DockingSlots[BestIndex];
}
// Denied, but player ship, so undock an AI ship
else if (Ship->IsPlayerShip())
{
BestIndex = 0;
// Look again without constraint
for (int32 i = 0; i < DockingSlots.Num(); i++)
{
if (DockingSlots[i].DockSize == Ship->GetSize())
{
float DockDistance = (Spacecraft->Airframe->GetComponentToWorld().TransformPosition(DockingSlots[i].LocalLocation) - PreferredLocation).Size();
if (BestIndex < 0 || DockDistance < BestDistance)
{
BestDistance = DockDistance;
BestIndex = i;
}
}
}
// Undock previous owner
if ((DockingSlots[BestIndex].Granted || DockingSlots[BestIndex].Occupied) && DockingSlots[BestIndex].Ship && DockingSlots[BestIndex].Ship->IsValidLowLevel())
{
if (DockingSlots[BestIndex].Ship->GetNavigationSystem()->IsDocked())
{
DockingSlots[BestIndex].Ship->GetNavigationSystem()->Undock();
}
else
{
DockingSlots[BestIndex].Ship->GetNavigationSystem()->AbortAllCommands();
}
}
// Grant dock
DockingSlots[BestIndex].Granted = true;
DockingSlots[BestIndex].Ship = Ship;
return DockingSlots[BestIndex];
}
// Denied
else
{
FFlareDockingInfo Info;
Info.Granted = false;
Info.Station = Spacecraft;
return Info;
}
}
void UFlareSpacecraftDockingSystem::ReleaseDock(AFlareSpacecraft* Ship, int32 DockId)
{
FLOGV("UFlareSpacecraftDockingSystem::ReleaseDock %d ('%s')", DockId, *Ship->GetParent()->GetImmatriculation().ToString());
DockingSlots[DockId].Granted = false;
DockingSlots[DockId].Occupied = false;
DockingSlots[DockId].Ship = NULL;
}
void UFlareSpacecraftDockingSystem::Dock(AFlareSpacecraft* Ship, int32 DockId)
{
FLOGV("UFlareSpacecraftDockingSystem::Dock %d ('%s')", DockId, *Ship->GetParent()->GetImmatriculation().ToString());
DockingSlots[DockId].Granted = true;
DockingSlots[DockId].Occupied = true;
DockingSlots[DockId].Ship = Ship;
Spacecraft->GetGame()->GetQuestManager()->OnShipDocked(Spacecraft->GetParent(), Ship->GetParent());
}
TArray<AFlareSpacecraft*> UFlareSpacecraftDockingSystem::GetDockedShips()
{
TArray<AFlareSpacecraft*> Result;
for (int32 i = 0; i < DockingSlots.Num(); i++)
{
if (DockingSlots[i].Granted && DockingSlots[i].Occupied)
{
//FLOGV("UFlareSpacecraftDockingSystem::GetDockedShips : found valid dock %d", i);
Result.AddUnique(DockingSlots[i].Ship);
}
}
return Result;
}
bool UFlareSpacecraftDockingSystem::HasAvailableDock(AFlareSpacecraft* Ship) const
{
// Looking for slot
for (int32 i = 0; i < DockingSlots.Num(); i++)
{
if (DockingSlots[i].DockSize != Ship->GetSize())
{
continue;
}
if (!DockingSlots[i].Granted)
{
return true;
}
}
return false;
}
int UFlareSpacecraftDockingSystem::GetDockCount() const
{
return DockingSlots.Num();
}
FFlareDockingInfo UFlareSpacecraftDockingSystem::GetDockInfo(int32 DockId)
{
return DockingSlots[DockId];
}
bool UFlareSpacecraftDockingSystem::IsGrantedShip(AFlareSpacecraft* ShipCanditate) const
{
for (int32 i = 0; i < DockingSlots.Num(); i++)
{
if (DockingSlots[i].Granted && DockingSlots[i].Ship == ShipCanditate)
{
return true;
}
}
return false;
}
bool UFlareSpacecraftDockingSystem::IsDockedShip(AFlareSpacecraft* ShipCanditate) const
{
for (int32 i = 0; i < DockingSlots.Num(); i++)
{
if (DockingSlots[i].Occupied && DockingSlots[i].Ship == ShipCanditate)
{
return true;
}
}
return false;
}
#undef LOCTEXT_NAMESPACE
<commit_msg>#1035 Fix complex guest orientation<commit_after>
#include "FlareSpacecraftDockingSystem.h"
#include "../../Flare.h"
#include "../FlareStationDock.h"
#include "../FlareStationConnector.h"
#include "../FlareSpacecraft.h"
#include "../../Game/FlareGame.h"
#include "../../Quests/FlareQuestManager.h"
DECLARE_CYCLE_STAT(TEXT("FlareDockingSystem Tick"), STAT_FlareDockingSystem_Tick, STATGROUP_Flare);
#define LOCTEXT_NAMESPACE "FlareDockingSystem"
/*----------------------------------------------------
Constructor
----------------------------------------------------*/
UFlareSpacecraftDockingSystem::UFlareSpacecraftDockingSystem(const class FObjectInitializer& PCIP)
: Super(PCIP)
, Spacecraft(NULL)
{
SCOPE_CYCLE_COUNTER(STAT_FlareDockingSystem_Tick);
}
/*----------------------------------------------------
Gameplay events
----------------------------------------------------*/
void UFlareSpacecraftDockingSystem::TickSystem(float DeltaSeconds)
{
}
void UFlareSpacecraftDockingSystem::Initialize(AFlareSpacecraft* OwnerSpacecraft, FFlareSpacecraftSave* OwnerData)
{
Spacecraft = OwnerSpacecraft;
Components = Spacecraft->GetComponentsByClass(UFlareSpacecraftComponent::StaticClass());
Description = Spacecraft->GetParent()->GetDescription();
Data = OwnerData;
}
void UFlareSpacecraftDockingSystem::Start()
{
// Dock data
int32 DockCount = 0;
int32 ConnectorCount = 0;
TArray<UActorComponent*> ActorComponents;
Spacecraft->GetComponents(ActorComponents);
for (TArray<UActorComponent*>::TIterator ComponentIt(ActorComponents); ComponentIt; ++ComponentIt)
{
FVector DockLocation;
FRotator DockRotation;
UFlareStationDock* DockComponent = Cast<UFlareStationDock>(*ComponentIt);
UFlareStationConnector* ConnectorComponent = Cast<UFlareStationConnector>(*ComponentIt);
// Fill dock slots
if (DockComponent)
{
DockComponent->GetSocketWorldLocationAndRotation(FName("dock"), DockLocation, DockRotation);
// Fill info
FFlareDockingInfo Info;
Info.Ship = NULL;
Info.LocalAxis = Spacecraft->Airframe->GetComponentToWorld().Inverse().GetRotation().RotateVector(DockRotation.RotateVector(FVector(1,0,0)));
Info.LocalTopAxis = Spacecraft->Airframe->GetComponentToWorld().Inverse().GetRotation().RotateVector(DockRotation.RotateVector(FVector(0,1,0)));
Info.LocalLocation = Spacecraft->Airframe->GetComponentToWorld().Inverse().TransformPosition(DockLocation);
Info.DockId = DockCount;
Info.DockSize = DockComponent->DockSize;
Info.Station = Spacecraft;
Info.Granted = false;
Info.Occupied = false;
// Push this slot
DockingSlots.Add(Info);
DockCount++;
}
// Fill connector data to the parent
if (ConnectorComponent)
{
FCHECK(ConnectorCount < Spacecraft->GetDescription()->StationConnectorCount);
FCHECK(ConnectorCount < Spacecraft->GetParent()->GetStationConnectors().Num());
// Fetch connector data
FFlareDockingInfo* StationConnection = Spacecraft->GetParent()->GetStationConnector(ConnectorComponent->SlotIdentifier);
FCHECK(StationConnection != NULL);
// Fill info
if (StationConnection)
{
ConnectorComponent->GetSocketWorldLocationAndRotation(FName("dock"), DockLocation, DockRotation);
StationConnection->Ship = NULL;
StationConnection->Station = Spacecraft;
StationConnection->LocalAxis = Spacecraft->Airframe->GetComponentToWorld().Inverse().GetRotation().RotateVector(DockRotation.RotateVector(FVector(0, 0, 1)));
StationConnection->LocalTopAxis = Spacecraft->Airframe->GetComponentToWorld().Inverse().GetRotation().RotateVector(DockRotation.RotateVector(FVector(0, 1, 0)));
StationConnection->LocalLocation = Spacecraft->Airframe->GetComponentToWorld().Inverse().TransformPosition(DockLocation);
StationConnection->Occupied = true;
}
else
{
FLOGV("UFlareSpacecraftDockingSystem::Start : couldn't find station connector '%s' in parent", *ConnectorComponent->SlotIdentifier.ToString());
}
ConnectorCount++;
}
}
}
bool UFlareSpacecraftDockingSystem::HasCompatibleDock(AFlareSpacecraft* Ship) const
{
for (int32 i = 0; i < DockingSlots.Num(); i++)
{
if (DockingSlots[i].DockSize == Ship->GetSize())
{
return true;
}
}
return false;
}
FFlareDockingInfo UFlareSpacecraftDockingSystem::RequestDock(AFlareSpacecraft* Ship, FVector PreferredLocation)
{
int32 BestIndex = -1;
float BestDistance = 0;
// Player docking data
FText PlayerDockInfo;
AFlareSpacecraft* PlayerDockSpacecraft;
FFlareDockingParameters PlayerDockingParameters;
AFlareSpacecraft* PlayerShip = Ship->GetGame()->GetPC()->GetShipPawn();
// Deny all docking requests if the player is docking
if (PlayerShip)
{
bool DockingInProgress = PlayerShip->GetManualDockingProgress(PlayerDockSpacecraft, PlayerDockingParameters, PlayerDockInfo);
if (DockingInProgress && PlayerDockSpacecraft == Spacecraft && PlayerShip != Ship)
{
FLOG("UFlareSpacecraftDockingSystem::RequestDock : denied, player is docking");
FFlareDockingInfo Info;
Info.Granted = false;
Info.Station = Spacecraft;
return Info;
}
}
// Looking for nearest available slot
for (int32 i = 0; i < DockingSlots.Num(); i++)
{
if (!DockingSlots[i].Granted && DockingSlots[i].DockSize == Ship->GetSize())
{
float DockDistance = (Spacecraft->Airframe->GetComponentToWorld().TransformPosition(DockingSlots[i].LocalLocation) - PreferredLocation).Size();
if (BestIndex < 0 || DockDistance < BestDistance)
{
BestDistance = DockDistance;
BestIndex = i;
}
}
}
// Granted
if (BestIndex >= 0)
{
DockingSlots[BestIndex].Granted = true;
DockingSlots[BestIndex].Ship = Ship;
return DockingSlots[BestIndex];
}
// Denied, but player ship, so undock an AI ship
else if (Ship->IsPlayerShip())
{
BestIndex = 0;
// Look again without constraint
for (int32 i = 0; i < DockingSlots.Num(); i++)
{
if (DockingSlots[i].DockSize == Ship->GetSize())
{
float DockDistance = (Spacecraft->Airframe->GetComponentToWorld().TransformPosition(DockingSlots[i].LocalLocation) - PreferredLocation).Size();
if (BestIndex < 0 || DockDistance < BestDistance)
{
BestDistance = DockDistance;
BestIndex = i;
}
}
}
// Undock previous owner
if ((DockingSlots[BestIndex].Granted || DockingSlots[BestIndex].Occupied) && DockingSlots[BestIndex].Ship && DockingSlots[BestIndex].Ship->IsValidLowLevel())
{
if (DockingSlots[BestIndex].Ship->GetNavigationSystem()->IsDocked())
{
DockingSlots[BestIndex].Ship->GetNavigationSystem()->Undock();
}
else
{
DockingSlots[BestIndex].Ship->GetNavigationSystem()->AbortAllCommands();
}
}
// Grant dock
DockingSlots[BestIndex].Granted = true;
DockingSlots[BestIndex].Ship = Ship;
return DockingSlots[BestIndex];
}
// Denied
else
{
FFlareDockingInfo Info;
Info.Granted = false;
Info.Station = Spacecraft;
return Info;
}
}
void UFlareSpacecraftDockingSystem::ReleaseDock(AFlareSpacecraft* Ship, int32 DockId)
{
FLOGV("UFlareSpacecraftDockingSystem::ReleaseDock %d ('%s')", DockId, *Ship->GetParent()->GetImmatriculation().ToString());
DockingSlots[DockId].Granted = false;
DockingSlots[DockId].Occupied = false;
DockingSlots[DockId].Ship = NULL;
}
void UFlareSpacecraftDockingSystem::Dock(AFlareSpacecraft* Ship, int32 DockId)
{
FLOGV("UFlareSpacecraftDockingSystem::Dock %d ('%s')", DockId, *Ship->GetParent()->GetImmatriculation().ToString());
DockingSlots[DockId].Granted = true;
DockingSlots[DockId].Occupied = true;
DockingSlots[DockId].Ship = Ship;
Spacecraft->GetGame()->GetQuestManager()->OnShipDocked(Spacecraft->GetParent(), Ship->GetParent());
}
TArray<AFlareSpacecraft*> UFlareSpacecraftDockingSystem::GetDockedShips()
{
TArray<AFlareSpacecraft*> Result;
for (int32 i = 0; i < DockingSlots.Num(); i++)
{
if (DockingSlots[i].Granted && DockingSlots[i].Occupied)
{
//FLOGV("UFlareSpacecraftDockingSystem::GetDockedShips : found valid dock %d", i);
Result.AddUnique(DockingSlots[i].Ship);
}
}
return Result;
}
bool UFlareSpacecraftDockingSystem::HasAvailableDock(AFlareSpacecraft* Ship) const
{
// Looking for slot
for (int32 i = 0; i < DockingSlots.Num(); i++)
{
if (DockingSlots[i].DockSize != Ship->GetSize())
{
continue;
}
if (!DockingSlots[i].Granted)
{
return true;
}
}
return false;
}
int UFlareSpacecraftDockingSystem::GetDockCount() const
{
return DockingSlots.Num();
}
FFlareDockingInfo UFlareSpacecraftDockingSystem::GetDockInfo(int32 DockId)
{
return DockingSlots[DockId];
}
bool UFlareSpacecraftDockingSystem::IsGrantedShip(AFlareSpacecraft* ShipCanditate) const
{
for (int32 i = 0; i < DockingSlots.Num(); i++)
{
if (DockingSlots[i].Granted && DockingSlots[i].Ship == ShipCanditate)
{
return true;
}
}
return false;
}
bool UFlareSpacecraftDockingSystem::IsDockedShip(AFlareSpacecraft* ShipCanditate) const
{
for (int32 i = 0; i < DockingSlots.Num(); i++)
{
if (DockingSlots[i].Occupied && DockingSlots[i].Ship == ShipCanditate)
{
return true;
}
}
return false;
}
#undef LOCTEXT_NAMESPACE
<|endoftext|>
|
<commit_before>#include "binary_message.h"
#include "../core/exceptions.hpp"
#include <functional>
namespace nng {
namespace messaging {
binary_message::binary_message()
: message_base()
, _header()
, _body() {
}
binary_message::binary_message(::nng_msg* msgp)
: message_base(msgp)
, _header(msgp)
, _body(msgp) {
}
binary_message::~binary_message() {
free();
}
binary_message::operator std::string() {
std::string s;
const auto buf = body()->get();
for (auto it = buf.begin(); it != buf.end(); it++) {
s.push_back(((std::string::value_type*)*it)[0]);
}
return s;
}
binary_message_header* const binary_message::header() {
return &_header;
}
binary_message_body* const binary_message::body() {
return &_body;
}
message_base::size_type binary_message::get_size() const {
// Should be both (Header.Size + Body.Size).
return _header.get_size() + _body.get_size();
}
void binary_message::clear() {
_header.clear();
_body.clear();
}
void binary_message::set_msgp(::nng_msg* msgp) {
// Frees any previously existing internal message beforehand.
message_base::set_msgp(msgp);
_header.set_msgp(msgp);
_body.set_msgp(msgp);
}
void binary_message::allocate(size_type sz) {
if (has_message()) { return; }
::nng_msg* msgp;
const auto errnum = ::nng_msg_alloc(&msgp, sz);
THROW_NNG_EXCEPTION_EC(errnum);
binary_message::set_msgp(msgp);
}
void binary_message::free() {
if (!has_message()) { return; }
::nng_msg_free(get_msgp());
binary_message::set_msgp(nullptr);
}
}
}
<commit_msg>allocating allows for re-allocation<commit_after>#include "binary_message.h"
#include "../core/exceptions.hpp"
#include <functional>
namespace nng {
namespace messaging {
binary_message::binary_message()
: message_base()
, _header()
, _body() {
}
binary_message::binary_message(::nng_msg* msgp)
: message_base(msgp)
, _header(msgp)
, _body(msgp) {
}
binary_message::~binary_message() {
free();
}
binary_message::operator std::string() {
std::string s;
const auto buf = body()->get();
for (auto it = buf.begin(); it != buf.end(); it++) {
s.push_back(((std::string::value_type*)*it)[0]);
}
return s;
}
binary_message_header* const binary_message::header() {
return &_header;
}
binary_message_body* const binary_message::body() {
return &_body;
}
message_base::size_type binary_message::get_size() const {
// Should be both (Header.Size + Body.Size).
return _header.get_size() + _body.get_size();
}
void binary_message::clear() {
_header.clear();
_body.clear();
}
void binary_message::set_msgp(::nng_msg* msgp) {
// Frees any previously existing internal message beforehand.
message_base::set_msgp(msgp);
_header.set_msgp(msgp);
_body.set_msgp(msgp);
}
void binary_message::allocate(size_type sz) {
if (has_message()) { free(); }
::nng_msg* msgp;
const auto errnum = ::nng_msg_alloc(&msgp, sz);
THROW_NNG_EXCEPTION_EC(errnum);
binary_message::set_msgp(msgp);
}
void binary_message::free() {
if (!has_message()) { return; }
::nng_msg_free(get_msgp());
binary_message::set_msgp(nullptr);
}
}
}
<|endoftext|>
|
<commit_before>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named LICENSE that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
// Provide BZFS with a list server connection
/* class header */
#include "ListServerConnection.h"
/* system implementation headers */
#include <string.h>
#include <string>
#include <math.h>
#include <errno.h>
/* common implementation headers */
#include "bzfio.h"
#include "version.h"
#include "TextUtils.h"
#include "Protocol.h"
extern Address serverAddress;
extern PingPacket getTeamCounts();
ListServerLink::ListServerLink(std::string listServerURL, std::string publicizedAddress, std::string publicizedTitle)
{
// parse url
std::string protocol, hostname, pathname;
int port = 80;
bool useDefault = false;
// use default if it can't be parsed
if (!BzfNetwork::parseURL(listServerURL, protocol, hostname, port, pathname))
useDefault = true;
// use default if wrong protocol or invalid port
if ((protocol != "http") || (port < 1) || (port > 65535))
useDefault = true;
// use default if bad address
Address address = Address::getHostAddress(hostname);
if (address.isAny())
useDefault = true;
// parse default list server URL if we need to; assume default works
if (useDefault) {
BzfNetwork::parseURL(DefaultListServerURL, protocol, hostname, port, pathname);
DEBUG1("Provided list server URL (%s) is invalid. Using default of %s.\n", listServerURL.c_str(), DefaultListServerURL);
}
// add to list
this->address = address;
this->port = port;
this->pathname = pathname;
this->hostname = hostname;
this->linkSocket = NotConnected;
this->publicizeAddress = publicizedAddress;
this->publicizeDescription = publicizedTitle;
this->publicizeServer = true; //if this c'tor is called, it's safe to publicize
// schedule initial ADD message
queueMessage(ListServerLink::ADD);
}
ListServerLink::ListServerLink()
{
// does not create a usable link, so checks should be placed
// in all public member functions to ensure that nothing tries
// to happen if publicizeServer is false
this->linkSocket = NotConnected;
this->publicizeServer = false;
}
ListServerLink::~ListServerLink()
{
// now tell the list server that we're going away. this can
// take some time but we don't want to wait too long. we do
// our own multiplexing loop and wait for a maximum of 3 seconds
// total.
// if we aren't supposed to be publicizing, skip the whole thing
// and don't waste 3 seconds.
if (!publicizeServer)
return;
queueMessage(ListServerLink::REMOVE);
TimeKeeper start = TimeKeeper::getCurrent();
do {
// compute timeout
float waitTime = 3.0f - (TimeKeeper::getCurrent() - start);
if (waitTime <= 0.0f)
break;
if (!isConnected()) //queueMessage should have connected us
break;
// check for list server socket connection
int fdMax = -1;
fd_set write_set;
fd_set read_set;
FD_ZERO(&write_set);
FD_ZERO(&read_set);
if (phase == ListServerLink::CONNECTING)
_FD_SET(linkSocket, &write_set);
else
_FD_SET(linkSocket, &read_set);
fdMax = linkSocket;
// wait for socket to connect or timeout
struct timeval timeout;
timeout.tv_sec = long(floorf(waitTime));
timeout.tv_usec = long(1.0e+6f * (waitTime - floorf(waitTime)));
int nfound = select(fdMax + 1, (fd_set*)&read_set, (fd_set*)&write_set,
0, &timeout);
if (nfound == 0)
// Time has gone, close and go
break;
// check for connection to list server
if (FD_ISSET(linkSocket, &write_set))
sendQueuedMessages();
else if (FD_ISSET(linkSocket, &read_set))
read();
} while (true);
// stop list server communication
closeLink();
}
void ListServerLink::closeLink()
{
if (isConnected()) {
close(linkSocket);
DEBUG4("Closing List Server\n");
linkSocket = NotConnected;
}
}
void ListServerLink::read()
{
if (isConnected()) {
char buf[256];
recv(linkSocket, buf, sizeof(buf), 0);
closeLink();
if (nextMessageType != ListServerLink::NONE)
// There was a pending request arrived after we write:
// we should redo all the stuff
openLink();
}
}
void ListServerLink::openLink()
{
// start opening connection if not already doing so
if (!isConnected()) {
linkSocket = socket(AF_INET, SOCK_STREAM, 0);
DEBUG4("Opening List Server\n");
if (!isConnected()) {
return;
}
// set to non-blocking for connect
if (BzfNetwork::setNonBlocking(linkSocket) < 0) {
closeLink();
return;
}
// Make our connection come from our serverAddress in case we have
// multiple/masked IPs so the list server can verify us.
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr = serverAddress;
// assign the address to the socket
if (bind(linkSocket, (CNCTType*)&addr, sizeof(addr)) < 0) {
closeLink();
return;
}
// connect. this should fail with EINPROGRESS but check for
// success just in case.
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr = address;
if (connect(linkSocket, (CNCTType*)&addr, sizeof(addr)) < 0) {
#if defined(_WIN32)
#undef EINPROGRESS
#define EINPROGRESS EWOULDBLOCK
#endif
if (getErrno() != EINPROGRESS) {
nerror("connecting to list server");
// try to lookup dns name again in case it moved
this->address = Address::getHostAddress(this->hostname);
closeLink();
} else {
phase = CONNECTING;
}
} else {
// shouldn't arrive here. Just in case, clean
closeLink();
}
}
}
void ListServerLink::queueMessage(MessageType type)
{
// ignore if the server is not public
if (!publicizeServer) return;
// Open network connection only if closed
if (!isConnected()) openLink();
// record next message to send.
nextMessageType = type;
}
void ListServerLink::sendQueuedMessages()
{
if (!isConnected())
return;
if (nextMessageType == ListServerLink::ADD) {
DEBUG3("Queuing ADD message to list server\n");
addMe(getTeamCounts(), publicizeAddress, TextUtils::url_encode(publicizeDescription));
lastAddTime = TimeKeeper::getCurrent();
} else if (nextMessageType == ListServerLink::REMOVE) {
DEBUG3("Queuing REMOVE message to list server\n");
removeMe(publicizeAddress);
}
}
void ListServerLink::addMe(PingPacket pingInfo,
std::string publicizedAddress,
std::string publicizedTitle)
{
std::string msg;
// encode ping reply as ascii hex digits plus NULL
char gameInfo[PingPacketHexPackedSize + 1];
pingInfo.packHex(gameInfo);
// send ADD message (must send blank line)
msg = TextUtils::format("GET %s?action=ADD&nameport=%s&version=%s&gameinfo=%s&build=%s&title=%s HTTP/1.1\r\n"
"Host: %s\r\nCache-Control: no-cache\r\n\r\n",
pathname.c_str(), publicizedAddress.c_str(),
getServerVersion(), gameInfo,
getAppVersion(),
publicizedTitle.c_str(),
hostname.c_str());
sendMessage(msg);
}
void ListServerLink::removeMe(std::string publicizedAddress)
{
std::string msg;
// send REMOVE (must send blank line)
msg = TextUtils::format("GET %s?action=REMOVE&nameport=%s HTTP/1.1\r\n"
"Host: %s\r\nCache-Control: no-cache\r\n\r\n",
pathname.c_str(),
publicizedAddress.c_str(),
hostname.c_str());
sendMessage(msg);
}
void ListServerLink::sendMessage(std::string message)
{
const int bufsize = 4096;
char msg[bufsize];
strncpy(msg, message.c_str(), bufsize);
msg[bufsize - 1] = 0;
if (strlen(msg) > 0) {
DEBUG3("%s\n", msg);
if (send(linkSocket, msg, strlen(msg), 0) == -1) {
perror("List server send failed");
DEBUG3("Unable to send to the list server!\n");
closeLink();
} else {
nextMessageType = ListServerLink::NONE;
phase = ListServerLink::WRITTEN;
}
} else {
closeLink();
}
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>comments on next steps for authentication<commit_after>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named LICENSE that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
// Provide BZFS with a list server connection
/* class header */
#include "ListServerConnection.h"
/* system implementation headers */
#include <string.h>
#include <string>
#include <math.h>
#include <errno.h>
/* common implementation headers */
#include "bzfio.h"
#include "version.h"
#include "TextUtils.h"
#include "Protocol.h"
extern Address serverAddress;
extern PingPacket getTeamCounts();
ListServerLink::ListServerLink(std::string listServerURL, std::string publicizedAddress, std::string publicizedTitle)
{
// parse url
std::string protocol, hostname, pathname;
int port = 80;
bool useDefault = false;
// use default if it can't be parsed
if (!BzfNetwork::parseURL(listServerURL, protocol, hostname, port, pathname))
useDefault = true;
// use default if wrong protocol or invalid port
if ((protocol != "http") || (port < 1) || (port > 65535))
useDefault = true;
// use default if bad address
Address address = Address::getHostAddress(hostname);
if (address.isAny())
useDefault = true;
// parse default list server URL if we need to; assume default works
if (useDefault) {
BzfNetwork::parseURL(DefaultListServerURL, protocol, hostname, port, pathname);
DEBUG1("Provided list server URL (%s) is invalid. Using default of %s.\n", listServerURL.c_str(), DefaultListServerURL);
}
// add to list
this->address = address;
this->port = port;
this->pathname = pathname;
this->hostname = hostname;
this->linkSocket = NotConnected;
this->publicizeAddress = publicizedAddress;
this->publicizeDescription = publicizedTitle;
this->publicizeServer = true; //if this c'tor is called, it's safe to publicize
// schedule initial ADD message
queueMessage(ListServerLink::ADD);
}
ListServerLink::ListServerLink()
{
// does not create a usable link, so checks should be placed
// in all public member functions to ensure that nothing tries
// to happen if publicizeServer is false
this->linkSocket = NotConnected;
this->publicizeServer = false;
}
ListServerLink::~ListServerLink()
{
// now tell the list server that we're going away. this can
// take some time but we don't want to wait too long. we do
// our own multiplexing loop and wait for a maximum of 3 seconds
// total.
// if we aren't supposed to be publicizing, skip the whole thing
// and don't waste 3 seconds.
if (!publicizeServer)
return;
queueMessage(ListServerLink::REMOVE);
TimeKeeper start = TimeKeeper::getCurrent();
do {
// compute timeout
float waitTime = 3.0f - (TimeKeeper::getCurrent() - start);
if (waitTime <= 0.0f)
break;
if (!isConnected()) //queueMessage should have connected us
break;
// check for list server socket connection
int fdMax = -1;
fd_set write_set;
fd_set read_set;
FD_ZERO(&write_set);
FD_ZERO(&read_set);
if (phase == ListServerLink::CONNECTING)
_FD_SET(linkSocket, &write_set);
else
_FD_SET(linkSocket, &read_set);
fdMax = linkSocket;
// wait for socket to connect or timeout
struct timeval timeout;
timeout.tv_sec = long(floorf(waitTime));
timeout.tv_usec = long(1.0e+6f * (waitTime - floorf(waitTime)));
int nfound = select(fdMax + 1, (fd_set*)&read_set, (fd_set*)&write_set,
0, &timeout);
if (nfound == 0)
// Time has gone, close and go
break;
// check for connection to list server
if (FD_ISSET(linkSocket, &write_set))
sendQueuedMessages();
else if (FD_ISSET(linkSocket, &read_set))
read();
} while (true);
// stop list server communication
closeLink();
}
void ListServerLink::closeLink()
{
if (isConnected()) {
close(linkSocket);
DEBUG4("Closing List Server\n");
linkSocket = NotConnected;
}
}
void ListServerLink::read()
{
if (isConnected()) {
char buf[256];
recv(linkSocket, buf, sizeof(buf), 0);
closeLink();
if (nextMessageType != ListServerLink::NONE)
// There was a pending request arrived after we write:
// we should redo all the stuff
openLink();
}
}
void ListServerLink::openLink()
{
// start opening connection if not already doing so
if (!isConnected()) {
linkSocket = socket(AF_INET, SOCK_STREAM, 0);
DEBUG4("Opening List Server\n");
if (!isConnected()) {
return;
}
// set to non-blocking for connect
if (BzfNetwork::setNonBlocking(linkSocket) < 0) {
closeLink();
return;
}
// Make our connection come from our serverAddress in case we have
// multiple/masked IPs so the list server can verify us.
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr = serverAddress;
// assign the address to the socket
if (bind(linkSocket, (CNCTType*)&addr, sizeof(addr)) < 0) {
closeLink();
return;
}
// connect. this should fail with EINPROGRESS but check for
// success just in case.
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr = address;
if (connect(linkSocket, (CNCTType*)&addr, sizeof(addr)) < 0) {
#if defined(_WIN32)
#undef EINPROGRESS
#define EINPROGRESS EWOULDBLOCK
#endif
if (getErrno() != EINPROGRESS) {
nerror("connecting to list server");
// try to lookup dns name again in case it moved
this->address = Address::getHostAddress(this->hostname);
closeLink();
} else {
phase = CONNECTING;
}
} else {
// shouldn't arrive here. Just in case, clean
closeLink();
}
}
}
void ListServerLink::queueMessage(MessageType type)
{
// ignore if the server is not public
if (!publicizeServer) return;
// Open network connection only if closed
if (!isConnected()) openLink();
// record next message to send.
nextMessageType = type;
}
void ListServerLink::sendQueuedMessages()
{
if (!isConnected())
return;
if (nextMessageType == ListServerLink::ADD) {
DEBUG3("Queuing ADD message to list server\n");
addMe(getTeamCounts(), publicizeAddress, TextUtils::url_encode(publicizeDescription));
lastAddTime = TimeKeeper::getCurrent();
} else if (nextMessageType == ListServerLink::REMOVE) {
DEBUG3("Queuing REMOVE message to list server\n");
removeMe(publicizeAddress);
}
}
void ListServerLink::addMe(PingPacket pingInfo,
std::string publicizedAddress,
std::string publicizedTitle)
{
std::string msg;
// encode ping reply as ascii hex digits plus NULL
char gameInfo[PingPacketHexPackedSize + 1];
pingInfo.packHex(gameInfo);
// TODO loop through and send any player tokens that need approval
// TODO loop through groups we are interested and request those too
// TODO we probably should convert to a POST instead. List server now allows either
// send ADD message (must send blank line)
msg = TextUtils::format("GET %s?action=ADD&nameport=%s&version=%s&gameinfo=%s&build=%s&title=%s HTTP/1.1\r\n"
"Host: %s\r\nCache-Control: no-cache\r\n\r\n",
pathname.c_str(), publicizedAddress.c_str(),
getServerVersion(), gameInfo,
getAppVersion(),
publicizedTitle.c_str(),
hostname.c_str());
// TODO need to listen for user info replies and setup callsign for isAllowedToEnter()
sendMessage(msg);
}
void ListServerLink::removeMe(std::string publicizedAddress)
{
std::string msg;
// send REMOVE (must send blank line)
msg = TextUtils::format("GET %s?action=REMOVE&nameport=%s HTTP/1.1\r\n"
"Host: %s\r\nCache-Control: no-cache\r\n\r\n",
pathname.c_str(),
publicizedAddress.c_str(),
hostname.c_str());
sendMessage(msg);
}
void ListServerLink::sendMessage(std::string message)
{
const int bufsize = 4096;
char msg[bufsize];
strncpy(msg, message.c_str(), bufsize);
msg[bufsize - 1] = 0;
if (strlen(msg) > 0) {
DEBUG3("%s\n", msg);
if (send(linkSocket, msg, strlen(msg), 0) == -1) {
perror("List server send failed");
DEBUG3("Unable to send to the list server!\n");
closeLink();
} else {
nextMessageType = ListServerLink::NONE;
phase = ListServerLink::WRITTEN;
}
} else {
closeLink();
}
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>
|
<commit_before>/**
* Copyright (C) 2003-2006 Funambol
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
#include "base/fscapi.h"
#include "base/Log.h"
#include "base/util/XMLProcessor.h"
#include "syncml/formatter/Formatter.h"
#include "spds/EmailData.h"
#define EMAIL_READ T("read")
#define EMAIL_FORW T("forwarded")
#define EMAIL_REPL T("replied")
#define EMAIL_TREC T("received")
#define EMAIL_TCRE T("created")
#define EMAIL_TMOD T("modified")
#define EMAIL_DELE T("deleted")
#define EMAIL_FLAG T("flagged")
#define EMAIL_ITEM T("emailitem")
static inline bool checkFlag(const char *xml, const char *field)
{
size_t start = 0, end = 0;
bool ret = false;
if( XMLProcessor::getEscapedElementContent(xml, field, NULL, &start, &end) ) {
ret = ( bstrncmp(xml+start, T("true"), end-start) == 0 ) ;
}
return ret;
}
EmailData::EmailData()
{
read = false;
forwarded = false;
replied = false;
deleted = false;
flagged = false;
}
int EmailData::parse(const BCHAR *msg, size_t len)
{
int ret = 0;
size_t start, end;
// Get attributes
read = checkFlag(msg, EMAIL_READ);
forwarded = checkFlag(msg, EMAIL_FORW);
replied = checkFlag(msg, EMAIL_REPL);
deleted = checkFlag(msg, EMAIL_DELE);
flagged = checkFlag(msg, EMAIL_FLAG);
if( XMLProcessor::getEscapedElementContent (msg, EMAIL_TREC, NULL, &start, &end) ) {
received = StringBuffer(msg+start, end-start);
}
else received = T("");
if( XMLProcessor::getEscapedElementContent (msg, EMAIL_TCRE, NULL, &start, &end) ) {
created = StringBuffer(msg+start, end-start);
}
else created = T("");
if( XMLProcessor::getEscapedElementContent (msg, EMAIL_TMOD, NULL, &start, &end) ) {
modified = StringBuffer(msg+start, end-start);
}
else modified = T("");
// Get content
if( XMLProcessor::getEscapedElementContent (msg, EMAIL_ITEM, NULL, &start, &end) ) {
StringBuffer item(msg+start, end-start);
if(XMLProcessor::getEscapedElementContent(item, T("CDATA"), NULL, &start, &end) == 0) {
LOG.error(T("EMailData: can't find inner CDATA section."));
return -1;
}
ret=emailItem.parse( item.c_str()+start, end-start );
}
else {
LOG.info(T("EMailData: no <emailitem> tag."));
// It is not an error, just log it for info.
}
return ret;
}
BCHAR *EmailData::format() {
StringBuffer out;
out.reserve(150);
out = T("<![CDATA[\n<Email>\n");
out += XMLProcessor::makeElement(EMAIL_READ, read);
out += XMLProcessor::makeElement(EMAIL_FORW, forwarded);
out += XMLProcessor::makeElement(EMAIL_REPL, replied);
out += XMLProcessor::makeElement(EMAIL_TREC, received);
out += XMLProcessor::makeElement(EMAIL_TCRE, created);
out += XMLProcessor::makeElement(EMAIL_TMOD, modified);
out += XMLProcessor::makeElement(EMAIL_DELE, deleted);
out += XMLProcessor::makeElement(EMAIL_FLAG, flagged);
out += T("<emailitem>\n<![CDATA[");
BCHAR *item = emailItem.format();
if ( item ) {
out += item;
delete [] item;
}
out += T("]]>\n</emailitem>\n</Email>\n]]>\n");
return stringdup(out.c_str());
}
<commit_msg>Parsing of qp encoded emailitem<commit_after>/**
* Copyright (C) 2003-2006 Funambol
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
#include "base/fscapi.h"
#include "base/Log.h"
#include "base/util/XMLProcessor.h"
#include "base/quoted-printable.h"
#include "syncml/formatter/Formatter.h"
#include "spds/EmailData.h"
#define EMAIL_READ T("read")
#define EMAIL_FORW T("forwarded")
#define EMAIL_REPL T("replied")
#define EMAIL_TREC T("received")
#define EMAIL_TCRE T("created")
#define EMAIL_TMOD T("modified")
#define EMAIL_DELE T("deleted")
#define EMAIL_FLAG T("flagged")
#define EMAIL_ITEM T("emailitem")
static inline bool checkFlag(const char *xml, const char *field)
{
size_t start = 0, end = 0;
bool ret = false;
if( XMLProcessor::getEscapedElementContent(xml, field, NULL, &start, &end) ) {
ret = ( bstrncmp(xml+start, T("true"), end-start) == 0 ) ;
}
return ret;
}
EmailData::EmailData()
{
read = false;
forwarded = false;
replied = false;
deleted = false;
flagged = false;
}
int EmailData::parse(const BCHAR *msg, size_t len)
{
int ret = 0;
size_t start, end;
// Get attributes
read = checkFlag(msg, EMAIL_READ);
forwarded = checkFlag(msg, EMAIL_FORW);
replied = checkFlag(msg, EMAIL_REPL);
deleted = checkFlag(msg, EMAIL_DELE);
flagged = checkFlag(msg, EMAIL_FLAG);
if( XMLProcessor::getEscapedElementContent (msg, EMAIL_TREC, NULL, &start, &end) ) {
received = StringBuffer(msg+start, end-start);
}
else received = T("");
if( XMLProcessor::getEscapedElementContent (msg, EMAIL_TCRE, NULL, &start, &end) ) {
created = StringBuffer(msg+start, end-start);
}
else created = T("");
if( XMLProcessor::getEscapedElementContent (msg, EMAIL_TMOD, NULL, &start, &end) ) {
modified = StringBuffer(msg+start, end-start);
}
else modified = T("");
// Get content
if( XMLProcessor::getEscapedElementContent(msg, EMAIL_ITEM, NULL, &start, &end) ) {
StringBuffer item(msg+start, end-start);
item.replaceAll("<", "<");
item.replaceAll(">", ">");
unsigned int startAttr=0, endAttr=0;
size_t itemlen = end-start;
if(XMLProcessor::getElementAttributes(msg, EMAIL_ITEM, &startAttr, &endAttr, true)){
if(bstrstr(msg+startAttr, "quoted-printable")) {
char *decoded = qp_decode(item);
item = decoded;
delete [] decoded;
}
}
// item must start with CDATA
size_t item_start = item.find("![CDATA");
if(item_start > 10){
LOG.error(T("EMailData: can't find inner CDATA section."));
return -1;
}
size_t item_end = item.rfind("]]>");
// If not found, try also the old case
if(item.length() - item_end > 10){
item_end = item.rfind("]]&gt;");
if(item.length() - item_end > 10){
LOG.error(T("EMailData: can't find CDATA end tag."));
return -1;
}
}
// okay, move the start pointer to the end of
item_start += bstrlen("![CDATA");
ret=emailItem.parse( item.c_str()+item_start, item_end - item_start );
}
else {
LOG.info(T("EMailData: no <emailitem> tag."));
// It is not an error, just log it for info.
}
return ret;
}
BCHAR *EmailData::format() {
StringBuffer out;
out.reserve(150);
out = T("<![CDATA[\n<Email>\n");
out += XMLProcessor::makeElement(EMAIL_READ, read);
out += XMLProcessor::makeElement(EMAIL_FORW, forwarded);
out += XMLProcessor::makeElement(EMAIL_REPL, replied);
out += XMLProcessor::makeElement(EMAIL_TREC, received);
out += XMLProcessor::makeElement(EMAIL_TCRE, created);
out += XMLProcessor::makeElement(EMAIL_TMOD, modified);
out += XMLProcessor::makeElement(EMAIL_DELE, deleted);
out += XMLProcessor::makeElement(EMAIL_FLAG, flagged);
out += T("<emailitem>\n<![CDATA[");
BCHAR *item = emailItem.format();
if ( item ) {
out += item;
delete [] item;
}
out += T("]]>\n</emailitem>\n</Email>\n]]>\n");
return stringdup(out.c_str());
}
<|endoftext|>
|
<commit_before>#ifndef MECHANICROTSHAFT_HPP_INCLUDED
#define MECHANICROTSHAFT_HPP_INCLUDED
#include <iostream>
#include "ComponentEssentials.h"
#include "ComponentUtilities.h"
#include "math.h"
//!
//! @file MechanicRotShaft.hpp
//! @author Petter Krus <petter.krus@liu.se>
//! @date Thu 28 Jun 2012 09:14:24
//! @brief Rotational shaft with torsional spring
//! @ingroup MechanicComponents
//!
//This component is generated by COMPGEN for HOPSAN-NG simulation
//from
/*{, C:, Documents and Settings, petkr14, My Documents, \
CompgenNG}/Mechanic1DNG.nb*/
using namespace hopsan;
class MechanicRotShaft : public ComponentC
{
private:
double mKs;
double malpha;
Port *mpPmr1;
Port *mpPmr2;
int mNstep;
//Port Pmr1 variable
double tormr1;
double thetamr1;
double wmr1;
double cmr1;
double Zcmr1;
double eqInertiamr1;
//Port Pmr2 variable
double tormr2;
double thetamr2;
double wmr2;
double cmr2;
double Zcmr2;
double eqInertiamr2;
//inputVariables
//outputVariables
//LocalExpressions variables
double cmr10;
double cmr20;
//Expressions variables
double cmr1f;
double cmr2f;
//Port Pmr1 pointer
double *mpND_tormr1;
double *mpND_thetamr1;
double *mpND_wmr1;
double *mpND_cmr1;
double *mpND_Zcmr1;
double *mpND_eqInertiamr1;
//Port Pmr2 pointer
double *mpND_tormr2;
double *mpND_thetamr2;
double *mpND_wmr2;
double *mpND_cmr2;
double *mpND_Zcmr2;
double *mpND_eqInertiamr2;
//Delay declarations
//inputVariables pointers
//outputVariables pointers
EquationSystemSolver *mpSolver;
public:
static Component *Creator()
{
return new MechanicRotShaft();
}
void configure()
{
const double Ks = 1000.;
const double alpha = 0.9;
mNstep=9;
mKs = Ks;
malpha = alpha;
//Add ports to the component
mpPmr1=addPowerPort("Pmr1","NodeMechanicRotational");
mpPmr2=addPowerPort("Pmr2","NodeMechanicRotational");
//Add inputVariables ports to the component
//Add outputVariables ports to the component
//Register changable parameters to the HOPSAN++ core
registerParameter("Ks", "Spring constant", "Nm/rad", mKs);
registerParameter("alpha", "damping factor", "", malpha);
}
void initialize()
{
//Read port variable pointers from nodes
//Port Pmr1
mpND_tormr1=getSafeNodeDataPtr(mpPmr1, \
NodeMechanicRotational::Torque);
mpND_thetamr1=getSafeNodeDataPtr(mpPmr1, \
NodeMechanicRotational::Angle);
mpND_wmr1=getSafeNodeDataPtr(mpPmr1, \
NodeMechanicRotational::AngularVelocity);
mpND_cmr1=getSafeNodeDataPtr(mpPmr1, \
NodeMechanicRotational::WaveVariable);
mpND_Zcmr1=getSafeNodeDataPtr(mpPmr1, \
NodeMechanicRotational::CharImpedance);
mpND_eqInertiamr1=getSafeNodeDataPtr(mpPmr1, \
NodeMechanicRotational::EquivalentInertia);
//Port Pmr2
mpND_tormr2=getSafeNodeDataPtr(mpPmr2, \
NodeMechanicRotational::Torque);
mpND_thetamr2=getSafeNodeDataPtr(mpPmr2, \
NodeMechanicRotational::Angle);
mpND_wmr2=getSafeNodeDataPtr(mpPmr2, \
NodeMechanicRotational::AngularVelocity);
mpND_cmr2=getSafeNodeDataPtr(mpPmr2, \
NodeMechanicRotational::WaveVariable);
mpND_Zcmr2=getSafeNodeDataPtr(mpPmr2, \
NodeMechanicRotational::CharImpedance);
mpND_eqInertiamr2=getSafeNodeDataPtr(mpPmr2, \
NodeMechanicRotational::EquivalentInertia);
//Read inputVariables pointers from nodes
//Read outputVariable pointers from nodes
//Read variables from nodes
//Port Pmr1
tormr1 = (*mpND_tormr1);
thetamr1 = (*mpND_thetamr1);
wmr1 = (*mpND_wmr1);
cmr1 = (*mpND_cmr1);
Zcmr1 = (*mpND_Zcmr1);
eqInertiamr1 = (*mpND_eqInertiamr1);
//Port Pmr2
tormr2 = (*mpND_tormr2);
thetamr2 = (*mpND_thetamr2);
wmr2 = (*mpND_wmr2);
cmr2 = (*mpND_cmr2);
Zcmr2 = (*mpND_Zcmr2);
eqInertiamr2 = (*mpND_eqInertiamr2);
//Read inputVariables from nodes
//Read outputVariables from nodes
//InitialExpressions
cmr1 = tormr1 - (mKs*mTimestep*wmr1)/(1 - malpha);
cmr2 = tormr2 - (mKs*mTimestep*wmr2)/(1 - malpha);
cmr1f = tormr1;
cmr2f = tormr2;
//LocalExpressions
cmr10 = cmr2 + (2*mKs*mTimestep*wmr2)/(1 - malpha);
cmr20 = cmr1 + (2*mKs*mTimestep*wmr1)/(1 - malpha);
//Initialize delays
}
void simulateOneTimestep()
{
//Read variables from nodes
//Port Pmr1
tormr1 = (*mpND_tormr1);
thetamr1 = (*mpND_thetamr1);
wmr1 = (*mpND_wmr1);
eqInertiamr1 = (*mpND_eqInertiamr1);
//Port Pmr2
tormr2 = (*mpND_tormr2);
thetamr2 = (*mpND_thetamr2);
wmr2 = (*mpND_wmr2);
eqInertiamr2 = (*mpND_eqInertiamr2);
//Read inputVariables from nodes
//LocalExpressions
cmr10 = cmr2 + (2*mKs*mTimestep*wmr2)/(1 - malpha);
cmr20 = cmr1 + (2*mKs*mTimestep*wmr1)/(1 - malpha);
//Expressions
cmr1 = cmr1f;
cmr2 = cmr2f;
cmr1f = cmr10*(1 - malpha) + cmr1f*malpha;
cmr2f = cmr20*(1 - malpha) + cmr2f*malpha;
Zcmr1 = (mKs*mTimestep)/(1 - malpha);
Zcmr2 = (mKs*mTimestep)/(1 - malpha);
//Calculate the delayed parts
//Write new values to nodes
//Port Pmr1
(*mpND_cmr1)=cmr1;
(*mpND_Zcmr1)=Zcmr1;
//Port Pmr2
(*mpND_cmr2)=cmr2;
(*mpND_Zcmr2)=Zcmr2;
//outputVariables
//Update the delayed variabels
}
};
#endif // MECHANICROTSHAFT_HPP_INCLUDED
<commit_msg>revised parameters<commit_after>#ifndef MECHANICROTSHAFT_HPP_INCLUDED
#define MECHANICROTSHAFT_HPP_INCLUDED
#include <iostream>
#include "ComponentEssentials.h"
#include "ComponentUtilities.h"
#include "math.h"
//!
//! @file MechanicRotShaft.hpp
//! @author Petter Krus <petter.krus@liu.se>
//! @date Tue 30 Apr 2013 14:45:54
//! @brief Rotational shaft with torsional spring
//! @ingroup MechanicComponents
//!
//==This code has been autogenerated using Compgen==
//from
/*{, C:, HopsanTrunk, HOPSAN++, CompgenModels}/Mechanic1dComponents.nb*/
using namespace hopsan;
class MechanicRotShaft : public ComponentC
{
private:
double Ks;
double alpha;
Port *mpPmr1;
Port *mpPmr2;
int mNstep;
//Port Pmr1 variable
double tormr1;
double thetamr1;
double wmr1;
double cmr1;
double Zcmr1;
double eqInertiamr1;
//Port Pmr2 variable
double tormr2;
double thetamr2;
double wmr2;
double cmr2;
double Zcmr2;
double eqInertiamr2;
//==This code has been autogenerated using Compgen==
//inputVariables
//outputVariables
//InitialExpressions variables
double cmr1f;
double cmr2f;
//LocalExpressions variables
double cmr10;
double cmr20;
//Expressions variables
//Port Pmr1 pointer
double *mpND_tormr1;
double *mpND_thetamr1;
double *mpND_wmr1;
double *mpND_cmr1;
double *mpND_Zcmr1;
double *mpND_eqInertiamr1;
//Port Pmr2 pointer
double *mpND_tormr2;
double *mpND_thetamr2;
double *mpND_wmr2;
double *mpND_cmr2;
double *mpND_Zcmr2;
double *mpND_eqInertiamr2;
//Delay declarations
//==This code has been autogenerated using Compgen==
//inputVariables pointers
//outputVariables pointers
EquationSystemSolver *mpSolver;
public:
static Component *Creator()
{
return new MechanicRotShaft();
}
void configure()
{
//==This code has been autogenerated using Compgen==
mNstep=9;
//Add ports to the component
mpPmr1=addPowerPort("Pmr1","NodeMechanicRotational");
mpPmr2=addPowerPort("Pmr2","NodeMechanicRotational");
//Add inputVariables to the component
//Add outputVariables to the component
//==This code has been autogenerated using Compgen==
//Add constants/parameters
addConstant("Ks", "Spring constant", "Nm/rad", 1000.,Ks);
addConstant("alpha", "damping factor", "", 0.9,alpha);
}
void initialize()
{
//Read port variable pointers from nodes
//Port Pmr1
mpND_tormr1=getSafeNodeDataPtr(mpPmr1, \
NodeMechanicRotational::Torque);
mpND_thetamr1=getSafeNodeDataPtr(mpPmr1, \
NodeMechanicRotational::Angle);
mpND_wmr1=getSafeNodeDataPtr(mpPmr1, \
NodeMechanicRotational::AngularVelocity);
mpND_cmr1=getSafeNodeDataPtr(mpPmr1, \
NodeMechanicRotational::WaveVariable);
mpND_Zcmr1=getSafeNodeDataPtr(mpPmr1, \
NodeMechanicRotational::CharImpedance);
mpND_eqInertiamr1=getSafeNodeDataPtr(mpPmr1, \
NodeMechanicRotational::EquivalentInertia);
//Port Pmr2
mpND_tormr2=getSafeNodeDataPtr(mpPmr2, \
NodeMechanicRotational::Torque);
mpND_thetamr2=getSafeNodeDataPtr(mpPmr2, \
NodeMechanicRotational::Angle);
mpND_wmr2=getSafeNodeDataPtr(mpPmr2, \
NodeMechanicRotational::AngularVelocity);
mpND_cmr2=getSafeNodeDataPtr(mpPmr2, \
NodeMechanicRotational::WaveVariable);
mpND_Zcmr2=getSafeNodeDataPtr(mpPmr2, \
NodeMechanicRotational::CharImpedance);
mpND_eqInertiamr2=getSafeNodeDataPtr(mpPmr2, \
NodeMechanicRotational::EquivalentInertia);
//Read variables from nodes
//Port Pmr1
tormr1 = (*mpND_tormr1);
thetamr1 = (*mpND_thetamr1);
wmr1 = (*mpND_wmr1);
cmr1 = (*mpND_cmr1);
Zcmr1 = (*mpND_Zcmr1);
eqInertiamr1 = (*mpND_eqInertiamr1);
//Port Pmr2
tormr2 = (*mpND_tormr2);
thetamr2 = (*mpND_thetamr2);
wmr2 = (*mpND_wmr2);
cmr2 = (*mpND_cmr2);
Zcmr2 = (*mpND_Zcmr2);
eqInertiamr2 = (*mpND_eqInertiamr2);
//Read inputVariables from nodes
//Read outputVariables from nodes
//==This code has been autogenerated using Compgen==
//InitialExpressions
cmr1 = tormr1 - (Ks*mTimestep*wmr1)/(1 - alpha);
cmr2 = tormr2 - (Ks*mTimestep*wmr2)/(1 - alpha);
cmr1f = tormr1;
cmr2f = tormr2;
//LocalExpressions
cmr10 = cmr2 + (2*Ks*mTimestep*wmr2)/(1 - alpha);
cmr20 = cmr1 + (2*Ks*mTimestep*wmr1)/(1 - alpha);
//Initialize delays
}
void simulateOneTimestep()
{
//Read variables from nodes
//Port Pmr1
tormr1 = (*mpND_tormr1);
thetamr1 = (*mpND_thetamr1);
wmr1 = (*mpND_wmr1);
eqInertiamr1 = (*mpND_eqInertiamr1);
//Port Pmr2
tormr2 = (*mpND_tormr2);
thetamr2 = (*mpND_thetamr2);
wmr2 = (*mpND_wmr2);
eqInertiamr2 = (*mpND_eqInertiamr2);
//Read inputVariables from nodes
//LocalExpressions
cmr10 = cmr2 + (2*Ks*mTimestep*wmr2)/(1 - alpha);
cmr20 = cmr1 + (2*Ks*mTimestep*wmr1)/(1 - alpha);
//Expressions
cmr1 = cmr1f;
cmr2 = cmr2f;
cmr1f = (1 - alpha)*cmr10 + alpha*cmr1f;
cmr2f = (1 - alpha)*cmr20 + alpha*cmr2f;
Zcmr1 = (Ks*mTimestep)/(1 - alpha);
Zcmr2 = (Ks*mTimestep)/(1 - alpha);
//Calculate the delayed parts
//Write new values to nodes
//Port Pmr1
(*mpND_cmr1)=cmr1;
(*mpND_Zcmr1)=Zcmr1;
//Port Pmr2
(*mpND_cmr2)=cmr2;
(*mpND_Zcmr2)=Zcmr2;
//outputVariables
//Update the delayed variabels
}
void deconfigure()
{
delete mpSolver;
}
};
#endif // MECHANICROTSHAFT_HPP_INCLUDED
<|endoftext|>
|
<commit_before>// Barst.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "cpl defs.h"
#include "named pipes.h"
#include "Log buffer.h"
#include "mem pool.h"
#include "ftdi device.h"
#include "rtv device.h"
#include "serial device.h"
#include "mcdaq_device.h"
#include "misc tools.h"
CMainManager::CMainManager() : CDevice(_T("Main"))
{
m_pcComm= NULL;
m_pcMemPool= new CMemPool; // main program buffer pool
m_hClose= CreateEvent(NULL, TRUE, FALSE, NULL);
m_bError= false;
if (!m_hClose)
m_bError= true;
}
// when shutting down, first the pipe is disconnected.
CMainManager::~CMainManager()
{
if (m_pcComm)
m_pcComm->Close();
for (size_t i= 0; i<m_acManagers.size(); ++i)
delete m_acManagers[i];
CloseHandle(m_hClose);
delete m_pcComm;
delete m_pcMemPool;
}
// only one thread ever calls this since there's only thread in this communicator
void CMainManager::ProcessData(const void *pHead, DWORD dwSize, __int64 llId)
{
if (m_bError)
return;
SData sData;
sData.pDevice= this;
sData.dwSize= sizeof(SBaseIn);
SBaseIn sBase;
memset(&sBase, 0, sizeof(SBaseIn));
sBase.dwSize= sizeof(SBaseIn);
sBase.nChan= -1;
bool bRes= true;
if (!pHead || dwSize < sizeof(SBaseIn) || dwSize != ((SBaseIn*)pHead)->dwSize) // incorrect size read
{
sBase.nError= SIZE_MISSMATCH;
} else if (((SBaseIn*)pHead)->eType == eVersion && ((SBaseIn*)pHead)->dwSize == sizeof(SBaseIn) &&
((SBaseIn*)pHead)->nChan == -1) // send lib version
{
sBase.dwInfo= BARST_VERSION;
sBase.eType= eVersion;
} else if (((SBaseIn*)pHead)->eType == eDelete && ((SBaseIn*)pHead)->dwSize == sizeof(SBaseIn)) // close manager
{
if (((SBaseIn*)pHead)->nChan == -1) // close main program
SetEvent(m_hClose);
else if (((SBaseIn*)pHead)->nChan >= 0 && ((SBaseIn*)pHead)->nChan < m_acManagers.size() &&
m_acManagers[((SBaseIn*)pHead)->nChan]) // close other manager
{
delete m_acManagers[((SBaseIn*)pHead)->nChan];
m_acManagers[((SBaseIn*)pHead)->nChan]= NULL;
}
else
sBase.nError= INVALID_CHANN;
sBase.nChan= ((SBaseIn*)pHead)->nChan;
sBase.eType= eDelete;
} else if (((SBaseIn*)pHead)->eType == eSet && ((SBaseIn*)pHead)->dwSize == sizeof(SBaseIn)) // add a manager
{
// prepare array element for manager
size_t t= 0;
for (; t < m_acManagers.size() && m_acManagers[t]; ++t);
if (t == m_acManagers.size())
m_acManagers.push_back(NULL);
sBase.eType= eSet;
switch (((SBaseIn*)pHead)->eType2) // the device to open
{
case eFTDIMan:
{
int nPos= -1;
for (size_t i= 0; i < m_acManagers.size() && nPos == -1; ++i) // make sure it isn't open already
if (m_acManagers[i] && _tcscmp(FTDI_MAN_STR, m_acManagers[i]->m_csName.c_str()) == 0)
nPos= (int)i;
if (nPos != -1) // found
{
sBase.nError= ALREADY_OPEN;
sBase.nChan= nPos;
break;
}
CManagerFTDI* pMan= new CManagerFTDI(m_pcComm, m_csPipe.c_str(), (int)t, sBase.nError);
if (!sBase.nError)
{
sBase.nChan= (int)t;
m_acManagers[t]= pMan;
} else
delete pMan;
break;
}
case eRTVMan:
{
int nPos= -1;
for (size_t i= 0; i < m_acManagers.size() && nPos == -1; ++i) // make sure it isn't open already
if (m_acManagers[i] && _tcscmp(RTV_MAN_STR, m_acManagers[i]->m_csName.c_str()) == 0)
nPos= (int)i;
if (nPos != -1) // found
{
sBase.nError= ALREADY_OPEN;
sBase.nChan= nPos;
break;
}
CManagerRTV* pMan= new CManagerRTV(m_pcComm, m_csPipe.c_str(), (int)t, sBase.nError);
if (!sBase.nError)
{
sBase.nChan= (int)t;
m_acManagers[t]= pMan;
} else
delete pMan;
break;
}
case eSerialMan:
{
int nPos= -1;
for (size_t i= 0; i < m_acManagers.size() && nPos == -1; ++i) // make sure it isn't open already
if (m_acManagers[i] && _tcscmp(SERIAL_MAN_STR, m_acManagers[i]->m_csName.c_str()) == 0)
nPos= (int)i;
if (nPos != -1) // found
{
sBase.nError= ALREADY_OPEN;
sBase.nChan= nPos;
break;
}
CManagerSerial* pMan= new CManagerSerial(m_pcComm, m_csPipe.c_str(), (int)t, sBase.nError);
if (!sBase.nError)
{
sBase.nChan= (int)t;
m_acManagers[t]= pMan;
} else
delete pMan;
break;
}
case eMCDAQMan:
{
int nPos= -1;
for (size_t i= 0; i < m_acManagers.size() && nPos == -1; ++i) // make sure it isn't open already
if (m_acManagers[i] && _tcscmp(MCDAQ_MAN_STR, m_acManagers[i]->m_csName.c_str()) == 0)
nPos= (int)i;
if (nPos != -1) // found
{
sBase.nError= ALREADY_OPEN;
sBase.nChan= nPos;
break;
}
CManagerMCDAQ* pMan= new CManagerMCDAQ(m_pcComm, m_csPipe.c_str(), (int)t, sBase.nError);
if (!sBase.nError)
{
sBase.nChan= (int)t;
m_acManagers[t]= pMan;
} else
delete pMan;
break;
}
default:
sBase.nError= INVALID_MAN;
break;
}
} else if (((SBaseIn*)pHead)->nChan == -1 && ((SBaseIn*)pHead)->eType == eQuery)
{
sData.dwSize = sizeof(SBaseIn) + sizeof(SBase) + sizeof(SPerfTime);
void *pHead = sData.pHead = m_pcMemPool->PoolAcquire(sData.dwSize);
if (pHead)
{
((SBaseIn*)pHead)->dwSize= sizeof(SBaseIn) + sizeof(SBase) + sizeof(SPerfTime);
((SBaseIn*)pHead)->eType= eQuery;
((SBaseIn*)pHead)->nChan= -1;
((SBaseIn*)pHead)->nError= 0;
pHead = (char*)pHead + sizeof(SBaseIn);
((SBase *)pHead)->dwSize = sizeof(SPerfTime) + sizeof(SBase);
((SBase *)pHead)->eType = eServerTime;
pHead= (char *)pHead + sizeof(SBase);
FILETIME sTime;
ULARGE_INTEGER ulTime;
((SPerfTime *)pHead)->dRelativeTime = g_cTimer.Seconds();
GetSystemTimeAsFileTime(&sTime);
ulTime.HighPart = sTime.dwHighDateTime;
ulTime.LowPart = sTime.dwLowDateTime;
((SPerfTime *)pHead)->dUTCTime = ulTime.QuadPart / 10000000.0;
m_pcComm->SendData(&sData, llId);
}
} else if (((SBaseIn*)pHead)->nChan < 0 || ((SBaseIn*)pHead)->nChan >= m_acManagers.size() ||
!m_acManagers[((SBaseIn*)pHead)->nChan]) // verify manager exists
{
sBase.nError= INVALID_CHANN;
sBase.eType= ((SBaseIn*)pHead)->eType;
} else if (((SBaseIn*)pHead)->eType == eQuery && ((SBaseIn*)pHead)->dwSize == sizeof(SBaseIn)) // send info on this manager
{
bRes= false;
DWORD dwResSize= m_acManagers[((SBaseIn*)pHead)->nChan]->GetInfo(NULL, 0); // size of response
sData.pHead= m_pcMemPool->PoolAcquire(dwResSize);
if (sData.pHead)
{
m_acManagers[((SBaseIn*)pHead)->nChan]->GetInfo(sData.pHead, dwResSize); // get response
sData.dwSize= dwResSize;
m_pcComm->SendData(&sData, llId);
}
} else if (((SBaseIn*)pHead)->eType == ePassOn) // pass following data to manager
{
bRes= false;
m_acManagers[((SBaseIn*)pHead)->nChan]->ProcessData((char*)pHead + sizeof(SBaseIn), dwSize-sizeof(SBaseIn), llId);
} else
sBase.nError= INVALID_COMMAND;
if (bRes) // respond
{
sData.pHead= m_pcMemPool->PoolAcquire(sData.dwSize);
if (sData.pHead)
{
memcpy(sData.pHead, &sBase, sizeof(SBaseIn));
m_pcComm->SendData(&sData, llId);
}
}
}
int CMainManager::Run(int argc, TCHAR* argv[])
{
if (argc != 4 && argc != 5)
return BAD_INPUT_PARAMS;
DWORD dwBuffSizeIn, dwBuffSizeOut; // size of pipe buffers
std::tstringstream in(argv[2]), out(argv[3]);
g_llMaxQueueBytes = -1;
if (argc == 5)
{
std::tstringstream ssMaxBytes(argv[4]);
ssMaxBytes >> g_llMaxQueueBytes; // queue limit, -1 means
}
in >> dwBuffSizeIn; // user writing to pipe size
out >> dwBuffSizeOut; // user reading from pipe
m_csPipe= argv[1]; // pipe name to use
if (in.fail() || out.fail() || _tcschr(argv[2], _T('-'))
|| _tcschr(argv[3], _T('-'))) // cannot be negative #
return BAD_INPUT_PARAMS;
// check if it exists already
HANDLE hPipe= CreateFile(argv[1], GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (hPipe != INVALID_HANDLE_VALUE || GetLastError() == ERROR_PIPE_BUSY)
return ALREADY_OPEN;
CloseHandle(hPipe);
m_pcComm= new CPipeServer(); // main program pipe
int nRes;
// only use one thread to ensure thread safety
if (nRes= static_cast<CPipeServer*>(m_pcComm)->Init(argv[1], 1, dwBuffSizeIn, dwBuffSizeOut, this, NULL))
return nRes;
if (WAIT_OBJECT_0 != WaitForSingleObject(m_hClose, INFINITE)) // wait here until closing
return WIN_ERROR(GetLastError(), nRes);
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
InitializeQueueLimit();
g_cTimer.ResetTimer();
ShowWindow(GetConsoleWindow(), SW_HIDE);
CMainManager* pMainManager= new CMainManager;
int nRes= pMainManager->Run(argc, argv); // program sits here until stopped
delete pMainManager;
return nRes;
}
// WM_COPYDATA http://www.cplusplus.com/forum/windows/23232/
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms633573%28v=vs.85%29.aspx
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms632593%28v=vs.85%29.aspx
<commit_msg>Don't hide window in debug mode.<commit_after>// Barst.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "cpl defs.h"
#include "named pipes.h"
#include "Log buffer.h"
#include "mem pool.h"
#include "ftdi device.h"
#include "rtv device.h"
#include "serial device.h"
#include "mcdaq_device.h"
#include "misc tools.h"
CMainManager::CMainManager() : CDevice(_T("Main"))
{
m_pcComm= NULL;
m_pcMemPool= new CMemPool; // main program buffer pool
m_hClose= CreateEvent(NULL, TRUE, FALSE, NULL);
m_bError= false;
if (!m_hClose)
m_bError= true;
}
// when shutting down, first the pipe is disconnected.
CMainManager::~CMainManager()
{
if (m_pcComm)
m_pcComm->Close();
for (size_t i= 0; i<m_acManagers.size(); ++i)
delete m_acManagers[i];
CloseHandle(m_hClose);
delete m_pcComm;
delete m_pcMemPool;
}
// only one thread ever calls this since there's only thread in this communicator
void CMainManager::ProcessData(const void *pHead, DWORD dwSize, __int64 llId)
{
if (m_bError)
return;
SData sData;
sData.pDevice= this;
sData.dwSize= sizeof(SBaseIn);
SBaseIn sBase;
memset(&sBase, 0, sizeof(SBaseIn));
sBase.dwSize= sizeof(SBaseIn);
sBase.nChan= -1;
bool bRes= true;
if (!pHead || dwSize < sizeof(SBaseIn) || dwSize != ((SBaseIn*)pHead)->dwSize) // incorrect size read
{
sBase.nError= SIZE_MISSMATCH;
} else if (((SBaseIn*)pHead)->eType == eVersion && ((SBaseIn*)pHead)->dwSize == sizeof(SBaseIn) &&
((SBaseIn*)pHead)->nChan == -1) // send lib version
{
sBase.dwInfo= BARST_VERSION;
sBase.eType= eVersion;
} else if (((SBaseIn*)pHead)->eType == eDelete && ((SBaseIn*)pHead)->dwSize == sizeof(SBaseIn)) // close manager
{
if (((SBaseIn*)pHead)->nChan == -1) // close main program
SetEvent(m_hClose);
else if (((SBaseIn*)pHead)->nChan >= 0 && ((SBaseIn*)pHead)->nChan < m_acManagers.size() &&
m_acManagers[((SBaseIn*)pHead)->nChan]) // close other manager
{
delete m_acManagers[((SBaseIn*)pHead)->nChan];
m_acManagers[((SBaseIn*)pHead)->nChan]= NULL;
}
else
sBase.nError= INVALID_CHANN;
sBase.nChan= ((SBaseIn*)pHead)->nChan;
sBase.eType= eDelete;
} else if (((SBaseIn*)pHead)->eType == eSet && ((SBaseIn*)pHead)->dwSize == sizeof(SBaseIn)) // add a manager
{
// prepare array element for manager
size_t t= 0;
for (; t < m_acManagers.size() && m_acManagers[t]; ++t);
if (t == m_acManagers.size())
m_acManagers.push_back(NULL);
sBase.eType= eSet;
switch (((SBaseIn*)pHead)->eType2) // the device to open
{
case eFTDIMan:
{
int nPos= -1;
for (size_t i= 0; i < m_acManagers.size() && nPos == -1; ++i) // make sure it isn't open already
if (m_acManagers[i] && _tcscmp(FTDI_MAN_STR, m_acManagers[i]->m_csName.c_str()) == 0)
nPos= (int)i;
if (nPos != -1) // found
{
sBase.nError= ALREADY_OPEN;
sBase.nChan= nPos;
break;
}
CManagerFTDI* pMan= new CManagerFTDI(m_pcComm, m_csPipe.c_str(), (int)t, sBase.nError);
if (!sBase.nError)
{
sBase.nChan= (int)t;
m_acManagers[t]= pMan;
} else
delete pMan;
break;
}
case eRTVMan:
{
int nPos= -1;
for (size_t i= 0; i < m_acManagers.size() && nPos == -1; ++i) // make sure it isn't open already
if (m_acManagers[i] && _tcscmp(RTV_MAN_STR, m_acManagers[i]->m_csName.c_str()) == 0)
nPos= (int)i;
if (nPos != -1) // found
{
sBase.nError= ALREADY_OPEN;
sBase.nChan= nPos;
break;
}
CManagerRTV* pMan= new CManagerRTV(m_pcComm, m_csPipe.c_str(), (int)t, sBase.nError);
if (!sBase.nError)
{
sBase.nChan= (int)t;
m_acManagers[t]= pMan;
} else
delete pMan;
break;
}
case eSerialMan:
{
int nPos= -1;
for (size_t i= 0; i < m_acManagers.size() && nPos == -1; ++i) // make sure it isn't open already
if (m_acManagers[i] && _tcscmp(SERIAL_MAN_STR, m_acManagers[i]->m_csName.c_str()) == 0)
nPos= (int)i;
if (nPos != -1) // found
{
sBase.nError= ALREADY_OPEN;
sBase.nChan= nPos;
break;
}
CManagerSerial* pMan= new CManagerSerial(m_pcComm, m_csPipe.c_str(), (int)t, sBase.nError);
if (!sBase.nError)
{
sBase.nChan= (int)t;
m_acManagers[t]= pMan;
} else
delete pMan;
break;
}
case eMCDAQMan:
{
int nPos= -1;
for (size_t i= 0; i < m_acManagers.size() && nPos == -1; ++i) // make sure it isn't open already
if (m_acManagers[i] && _tcscmp(MCDAQ_MAN_STR, m_acManagers[i]->m_csName.c_str()) == 0)
nPos= (int)i;
if (nPos != -1) // found
{
sBase.nError= ALREADY_OPEN;
sBase.nChan= nPos;
break;
}
CManagerMCDAQ* pMan= new CManagerMCDAQ(m_pcComm, m_csPipe.c_str(), (int)t, sBase.nError);
if (!sBase.nError)
{
sBase.nChan= (int)t;
m_acManagers[t]= pMan;
} else
delete pMan;
break;
}
default:
sBase.nError= INVALID_MAN;
break;
}
} else if (((SBaseIn*)pHead)->nChan == -1 && ((SBaseIn*)pHead)->eType == eQuery)
{
sData.dwSize = sizeof(SBaseIn) + sizeof(SBase) + sizeof(SPerfTime);
void *pHead = sData.pHead = m_pcMemPool->PoolAcquire(sData.dwSize);
if (pHead)
{
((SBaseIn*)pHead)->dwSize= sizeof(SBaseIn) + sizeof(SBase) + sizeof(SPerfTime);
((SBaseIn*)pHead)->eType= eQuery;
((SBaseIn*)pHead)->nChan= -1;
((SBaseIn*)pHead)->nError= 0;
pHead = (char*)pHead + sizeof(SBaseIn);
((SBase *)pHead)->dwSize = sizeof(SPerfTime) + sizeof(SBase);
((SBase *)pHead)->eType = eServerTime;
pHead= (char *)pHead + sizeof(SBase);
FILETIME sTime;
ULARGE_INTEGER ulTime;
((SPerfTime *)pHead)->dRelativeTime = g_cTimer.Seconds();
GetSystemTimeAsFileTime(&sTime);
ulTime.HighPart = sTime.dwHighDateTime;
ulTime.LowPart = sTime.dwLowDateTime;
((SPerfTime *)pHead)->dUTCTime = ulTime.QuadPart / 10000000.0;
m_pcComm->SendData(&sData, llId);
}
} else if (((SBaseIn*)pHead)->nChan < 0 || ((SBaseIn*)pHead)->nChan >= m_acManagers.size() ||
!m_acManagers[((SBaseIn*)pHead)->nChan]) // verify manager exists
{
sBase.nError= INVALID_CHANN;
sBase.eType= ((SBaseIn*)pHead)->eType;
} else if (((SBaseIn*)pHead)->eType == eQuery && ((SBaseIn*)pHead)->dwSize == sizeof(SBaseIn)) // send info on this manager
{
bRes= false;
DWORD dwResSize= m_acManagers[((SBaseIn*)pHead)->nChan]->GetInfo(NULL, 0); // size of response
sData.pHead= m_pcMemPool->PoolAcquire(dwResSize);
if (sData.pHead)
{
m_acManagers[((SBaseIn*)pHead)->nChan]->GetInfo(sData.pHead, dwResSize); // get response
sData.dwSize= dwResSize;
m_pcComm->SendData(&sData, llId);
}
} else if (((SBaseIn*)pHead)->eType == ePassOn) // pass following data to manager
{
bRes= false;
m_acManagers[((SBaseIn*)pHead)->nChan]->ProcessData((char*)pHead + sizeof(SBaseIn), dwSize-sizeof(SBaseIn), llId);
} else
sBase.nError= INVALID_COMMAND;
if (bRes) // respond
{
sData.pHead= m_pcMemPool->PoolAcquire(sData.dwSize);
if (sData.pHead)
{
memcpy(sData.pHead, &sBase, sizeof(SBaseIn));
m_pcComm->SendData(&sData, llId);
}
}
}
int CMainManager::Run(int argc, TCHAR* argv[])
{
if (argc != 4 && argc != 5)
return BAD_INPUT_PARAMS;
DWORD dwBuffSizeIn, dwBuffSizeOut; // size of pipe buffers
std::tstringstream in(argv[2]), out(argv[3]);
g_llMaxQueueBytes = -1;
if (argc == 5)
{
std::tstringstream ssMaxBytes(argv[4]);
ssMaxBytes >> g_llMaxQueueBytes; // queue limit, -1 means
}
in >> dwBuffSizeIn; // user writing to pipe size
out >> dwBuffSizeOut; // user reading from pipe
m_csPipe= argv[1]; // pipe name to use
if (in.fail() || out.fail() || _tcschr(argv[2], _T('-'))
|| _tcschr(argv[3], _T('-'))) // cannot be negative #
return BAD_INPUT_PARAMS;
// check if it exists already
HANDLE hPipe= CreateFile(argv[1], GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (hPipe != INVALID_HANDLE_VALUE || GetLastError() == ERROR_PIPE_BUSY)
return ALREADY_OPEN;
CloseHandle(hPipe);
m_pcComm= new CPipeServer(); // main program pipe
int nRes;
// only use one thread to ensure thread safety
if (nRes= static_cast<CPipeServer*>(m_pcComm)->Init(argv[1], 1, dwBuffSizeIn, dwBuffSizeOut, this, NULL))
return nRes;
if (WAIT_OBJECT_0 != WaitForSingleObject(m_hClose, INFINITE)) // wait here until closing
return WIN_ERROR(GetLastError(), nRes);
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
InitializeQueueLimit();
g_cTimer.ResetTimer();
#ifndef _DEBUG
ShowWindow(GetConsoleWindow(), SW_HIDE);
#endif
CMainManager* pMainManager= new CMainManager;
int nRes= pMainManager->Run(argc, argv); // program sits here until stopped
delete pMainManager;
return nRes;
}
// WM_COPYDATA http://www.cplusplus.com/forum/windows/23232/
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms633573%28v=vs.85%29.aspx
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms632593%28v=vs.85%29.aspx
<|endoftext|>
|
<commit_before>#include "layouterCSS.h"
#include <vector>
#include <string>
#include <memory>
#include <algorithm>
static uint8_t hex2num(char c)
{
switch (c)
{
case '0': return 0;
case '1': return 1;
case '2': return 2;
case '3': return 3;
case '4': return 4;
case '5': return 5;
case '6': return 6;
case '7': return 7;
case '8': return 8;
case '9': return 9;
case 'a':
case 'A': return 10;
case 'b':
case 'B': return 11;
case 'c':
case 'C': return 12;
case 'd':
case 'D': return 13;
case 'e':
case 'E': return 14;
case 'f':
case 'F': return 15;
default: return 0;
}
}
static uint8_t hex2byte(char c1, char c2)
{
return hex2num(c1)* 16 + hex2num(c2);
}
void evalColor(const std::string & col, uint8_t & r, uint8_t & g, uint8_t &b)
{
if (col[0] == '#' && col.length() >= 7)
{
r = hex2byte(col[1], col[2]);
g = hex2byte(col[3], col[4]);
b = hex2byte(col[5], col[6]);
}
}
double evalSize(const std::string & sz)
{
// right now we accept only pixel sizes
size_t l = sz.length();
if (sz[l-2] == 'p' && sz[l-1] == 'x')
{
return atof(sz.c_str());
}
// TODO exception
return 0;
}
static bool ruleFits(const std::string & sel, const pugi::xml_node & node)
{
if (sel == "*") return true;
if (sel == node.name()) return true;
return false;
}
static uint16_t rulePrio(const std::string & sel)
{
if (sel == "*") return 0;
return 1;
}
const std::string & textStyleSheet_c::getValue(const pugi::xml_node & node, const std::string & attribute) const
{
static std::string defaultValue("");
// go through all rules, check only the ones that give a value to the requested attribute
// evaluate rule by priority (look at the CSS priority rules
// choose the highest priority
int16_t bestPrio = -1;
std::string & res = defaultValue;
for (auto & r : rules)
{
if (ruleFits(r.selector, node) && r.attribute == attribute && rulePrio(r.selector) > bestPrio)
{
res = r.value;
bestPrio = rulePrio(r.selector);
}
}
return res;
}
void textStyleSheet_c::font(const std::string& family, const std::string& file, const std::string& style, const std::string& variant, const std::string& weight, const std::string& stretch)
{
if (families.size())
{
font(families.begin()->second->getCache(), family, file, style, variant, weight, stretch);
}
else
{
font(std::make_shared<fontCache_c>(), family, file, style, variant, weight, stretch);
}
}
void textStyleSheet_c::font(std::shared_ptr<fontCache_c> fc, const std::string& family, const std::string& file, const std::string& style, const std::string& variant, const std::string& weight, const std::string& stretch)
{
auto i = families.find(family);
if (i == families.end())
{
i = families.insert(std::make_pair(family, std::make_shared<fontFamily_c>(fc))).first;
}
i->second->addFont(file, style, variant, weight, stretch);
}
<commit_msg>implement class selector in CSS<commit_after>#include "layouterCSS.h"
#include <vector>
#include <string>
#include <memory>
#include <algorithm>
static uint8_t hex2num(char c)
{
switch (c)
{
case '0': return 0;
case '1': return 1;
case '2': return 2;
case '3': return 3;
case '4': return 4;
case '5': return 5;
case '6': return 6;
case '7': return 7;
case '8': return 8;
case '9': return 9;
case 'a':
case 'A': return 10;
case 'b':
case 'B': return 11;
case 'c':
case 'C': return 12;
case 'd':
case 'D': return 13;
case 'e':
case 'E': return 14;
case 'f':
case 'F': return 15;
default: return 0;
}
}
static uint8_t hex2byte(char c1, char c2)
{
return hex2num(c1)* 16 + hex2num(c2);
}
void evalColor(const std::string & col, uint8_t & r, uint8_t & g, uint8_t &b)
{
if (col[0] == '#' && col.length() >= 7)
{
r = hex2byte(col[1], col[2]);
g = hex2byte(col[3], col[4]);
b = hex2byte(col[5], col[6]);
}
}
double evalSize(const std::string & sz)
{
// right now we accept only pixel sizes
size_t l = sz.length();
if (sz[l-2] == 'p' && sz[l-1] == 'x')
{
return atof(sz.c_str());
}
// TODO exception
return 0;
}
static bool ruleFits(const std::string & sel, const pugi::xml_node & node)
{
if (sel == "*") return true;
if (sel == node.name()) return true;
if (sel[0] == '.')
{
auto attr = node.attribute("class");
if (!attr.empty())
{
if (attr.value() == sel.substr(1))
{
return true;
}
}
}
return false;
}
static uint16_t rulePrio(const std::string & sel)
{
if (sel == "*") return 0;
if (sel[0] == '.') return 1;
return 2;
}
const std::string & textStyleSheet_c::getValue(const pugi::xml_node & node, const std::string & attribute) const
{
static std::string defaultValue("");
// go through all rules, check only the ones that give a value to the requested attribute
// evaluate rule by priority (look at the CSS priority rules
// choose the highest priority
int16_t bestPrio = -1;
std::string & res = defaultValue;
for (auto & r : rules)
{
if (ruleFits(r.selector, node) && r.attribute == attribute && rulePrio(r.selector) > bestPrio)
{
res = r.value;
bestPrio = rulePrio(r.selector);
}
}
return res;
}
void textStyleSheet_c::font(const std::string& family, const std::string& file, const std::string& style, const std::string& variant, const std::string& weight, const std::string& stretch)
{
if (families.size())
{
font(families.begin()->second->getCache(), family, file, style, variant, weight, stretch);
}
else
{
font(std::make_shared<fontCache_c>(), family, file, style, variant, weight, stretch);
}
}
void textStyleSheet_c::font(std::shared_ptr<fontCache_c> fc, const std::string& family, const std::string& file, const std::string& style, const std::string& variant, const std::string& weight, const std::string& stretch)
{
auto i = families.find(family);
if (i == families.end())
{
i = families.insert(std::make_pair(family, std::make_shared<fontFamily_c>(fc))).first;
}
i->second->addFont(file, style, variant, weight, stretch);
}
<|endoftext|>
|
<commit_before>// $Id$
// Main authors: Matevz Tadel & Alja Mrak-Tadel: 2006, 2007
/**************************************************************************
* Copyright(c) 1998-2008, ALICE Experiment at CERN, all rights reserved. *
* See http://aliceinfo.cern.ch/Offline/AliRoot/License.html for *
* full copyright notice. *
**************************************************************************/
#if !defined(__CINT__) || defined(__MAKECINT__)
#include <TGeoManager.h>
#include <TGeoNode.h>
#include <TEveManager.h>
#include <TEveGeoNode.h>
#include <AliEveEventManager.h>
#endif
void geom_emcal()
{
AliEveEventManager::GetMaster()->AssertGeometry();
TGeoNode* node = gGeoManager->GetTopVolume()->FindNode("XEN1_1");
if (!node) {
Warning("geom_emcal()", "Node XEN1_1 not found.");
return;
}
TEveGeoTopNode* emcal_re = new TEveGeoTopNode(gGeoManager, node);
emcal_re->SetVisLevel(1);
gEve->AddGlobalElement(emcal_re);
gEve->Redraw3D();
}
<commit_msg>EMCal's geom added to RPhi projection.<commit_after>// $Id$
// Main authors: Matevz Tadel & Alja Mrak-Tadel: 2006, 2007
/**************************************************************************
* Copyright(c) 1998-2008, ALICE Experiment at CERN, all rights reserved. *
* See http://aliceinfo.cern.ch/Offline/AliRoot/License.html for *
* full copyright notice. *
**************************************************************************/
#if !defined(__CINT__) || defined(__MAKECINT__)
#include <TGeoManager.h>
#include <TGeoNode.h>
#include <TEveManager.h>
#include <TEveGeoNode.h>
#include <AliEveEventManager.h>
#include <AliEveMultiView.h>
#endif
void geom_emcal()
{
AliEveEventManager::GetMaster()->AssertGeometry();
AliEveMultiView *mv = AliEveMultiView::Instance();
TGeoNode* node = gGeoManager->GetTopVolume()->FindNode("XEN1_1");
if (!node) {
Warning("geom_emcal()", "Node XEN1_1 not found.");
return;
}
TEveGeoTopNode* emcal_re = new TEveGeoTopNode(gGeoManager, node);
emcal_re->SetVisLevel(1);
emcal_re->SetMainTransparency(70);
// 3D view:
gEve->AddGlobalElement(emcal_re);
// RPhi
mv->ImportGeomRPhi(emcal_re);
emcal_re->ProjectAllChildren();
emcal_re->PropagateRnrStateToProjecteds();
g_proj = gEve->SpawnNewScene("emcal proj", "emcal proj");
AliEveMultiView::Instance()->GetRPhiView()->AddScene(g_proj);
g_proj->SetElementName("EMCal geom RPhi");
g_proj->AddElement(emcal_re);
gSystem->ProcessEvents();
gEve->Redraw3D();
}
<|endoftext|>
|
<commit_before>#include "myHeader.h"
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
void printStringArr(const string a[], int n, ostream &os) {
for (int i = 0; i < n; i++)
os << "\n" << a[i];
}
int getIntInRange(int start, int end) {
int x = getInt();
while (x < start || x > end) {
cout
<< "\a\tYour number must be "
<< (x < start ? "greater" : "less")
<< " than or equal to "
<< (x < start ? start : end)
<< ". \n\tTry again: ";
x = getInt();
}
return x;
}
int getInt() {
double x = getNum();
while (int(x) != x) {
cout << "\a\tYour number is not an integer! \n\tTry Again: ";
x = getNum();
}
return int(x);
}
double getNum() {
double x;
while (!(cin >> x)) {
cin.clear(); cin.ignore(30, '\n');
cout << "\a\tPlease no inapropriate characters! \n\tTry again: ";
}
cin.ignore(80, '\n');
return x;
}
void loadStringArrayFromFile(string a[], int n, ifstream &ifs, bool &isLoaded) {
for (int i = 0; i < n; i++)
getline(ifs, a[i]);
isLoaded = true;
}
void loadStats(int &gamesPlayed, int whoWon[], double whoWonPercent[], double numMoves[], int n, ifstream &ifs, bool &isLoaded) {
while (ifs.peek() < '0' || ifs.peek() > '9')
ifs.ignore();
ifs >> gamesPlayed;
while (ifs.peek() < '0' || ifs.peek() > '9')
ifs.ignore();
for (int i = 0; i < n; i++)
ifs >> whoWon[i];
while (ifs.peek() < '0' || ifs.peek() > '9')
ifs.ignore();
for (int i = 0; i < n; i++) {
ifs >> whoWonPercent[i];
ifs.ignore(); // for discarding '%'
}
while (ifs.peek() < '0' || ifs.peek() > '9')
ifs.ignore();
for (int i = 0; i < n; i++)
ifs >> numMoves[i];
isLoaded = true;
}
void printStats(int gamesPld, const int whoWon[], const double winPct[], const double numMvs[], int n, ostream &os) {
os
<< fixed << setprecision(1)
<< "\nHunt the Wumpus Game Statistics"
<< "\n\n\tGames Played: " << gamesPld
<< "\n\n\tWho Won:"
<< "\n\tPlayer\tWumpus\tPit\n";
for (int i = 0; i < n; i++)
os << "\t" << whoWon[i];
os
<< "\n\n\tWin Rate:"
<< "\n\tPlayer\tWumpus\tPit\n";
for (int i = 0; i < n; i++)
os << "\t" << winPct[i] << "%";
os
<< "\n\n\tMoves per Game:"
<< "\n\tLeast\tMost\tAverage\n"
<< "\t" << int(numMvs[0])
<< "\t" << int(numMvs[1])
<< "\t" << numMvs[2];
}
void load2DArr(int map[][SIZE_EXITS], int const n, int const m) {
int tempMap[21][3] = {
{ 0, 0, 0 }, // room not actually used
{ 2, 4, 19 },
{ 1, 3, 6 },
{ 2, 8, 20 },
{ 1, 5, 9 },
{ 4, 6, 11 },
{ 2, 5, 7 },
{ 6, 8, 12 },
{ 3, 7, 13 },
{ 4, 10, 16 },
{ 9, 11, 14 },
{ 5, 10, 12 },
{ 7, 11, 15 },
{ 8, 15, 18 },
{ 10, 15, 17 },
{ 12, 13, 14 },
{ 9, 17, 19 },
{ 14, 16, 18 },
{ 13, 17, 20 },
{ 1, 16, 20 },
{ 3, 18, 19 }
};
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
map[i][j] = tempMap[i][j];
}
void print2DArr(int map[][3], int n, int m, ostream &os) {
cout << "\n";
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
cout << "\t" << map[i][j] << (j % m == m - 1 ? "\n" : ", ");
}
int startHunt(int const map[][3], int player, int wumpus, int bat1, int bat2, int pit1, int pit2, int &count) {
count = 0;
while (true) {
if (player == wumpus) {
cout << "\n\tYou awakened the Wumpus. He eats you. \n\tYou lose.";
return -1;
}
else if (player == pit1 || player == pit2) {
cout << "\n\tYou fell into a bottomless pit. \n\tYou lose... eventually...";
return 0;
}
/*if (isWumpusNear(player, wumpus))
cout << "\n\tYou smell the unmistakable stench of a Wumpus";
if (isPitNear(player, pit1, pit2))
cout << "\n\tYou smell the unmistakable stench of a Wumpus";
if (isBatNear(player, wumpus))
cout << "\n\tYou smell the unmistakable stench of a Wumpus";
cout << "You "*/
}
}<commit_msg>finished messaging for hazards<commit_after>#include "myHeader.h"
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
void printStringArr(const string a[], int n, ostream &os) {
for (int i = 0; i < n; i++)
os << "\n" << a[i];
}
int getIntInRange(int start, int end) {
int x = getInt();
while (x < start || x > end) {
cout
<< "\a\tYour number must be "
<< (x < start ? "greater" : "less")
<< " than or equal to "
<< (x < start ? start : end)
<< ". \n\tTry again: ";
x = getInt();
}
return x;
}
int getInt() {
double x = getNum();
while (int(x) != x) {
cout << "\a\tYour number is not an integer! \n\tTry Again: ";
x = getNum();
}
return int(x);
}
double getNum() {
double x;
while (!(cin >> x)) {
cin.clear(); cin.ignore(30, '\n');
cout << "\a\tPlease no inapropriate characters! \n\tTry again: ";
}
cin.ignore(80, '\n');
return x;
}
void loadStringArrayFromFile(string a[], int n, ifstream &ifs, bool &isLoaded) {
for (int i = 0; i < n; i++)
getline(ifs, a[i]);
isLoaded = true;
}
void loadStats(int &gamesPlayed, int whoWon[], double whoWonPercent[], double numMoves[], int n, ifstream &ifs, bool &isLoaded) {
while (ifs.peek() < '0' || ifs.peek() > '9')
ifs.ignore();
ifs >> gamesPlayed;
while (ifs.peek() < '0' || ifs.peek() > '9')
ifs.ignore();
for (int i = 0; i < n; i++)
ifs >> whoWon[i];
while (ifs.peek() < '0' || ifs.peek() > '9')
ifs.ignore();
for (int i = 0; i < n; i++) {
ifs >> whoWonPercent[i];
ifs.ignore(); // for discarding '%'
}
while (ifs.peek() < '0' || ifs.peek() > '9')
ifs.ignore();
for (int i = 0; i < n; i++)
ifs >> numMoves[i];
isLoaded = true;
}
void printStats(int gamesPld, const int whoWon[], const double winPct[], const double numMvs[], int n, ostream &os) {
os
<< fixed << setprecision(1)
<< "\nHunt the Wumpus Game Statistics"
<< "\n\n\tGames Played: " << gamesPld
<< "\n\n\tWho Won:"
<< "\n\tPlayer\tWumpus\tPit\n";
for (int i = 0; i < n; i++)
os << "\t" << whoWon[i];
os
<< "\n\n\tWin Rate:"
<< "\n\tPlayer\tWumpus\tPit\n";
for (int i = 0; i < n; i++)
os << "\t" << winPct[i] << "%";
os
<< "\n\n\tMoves per Game:"
<< "\n\tLeast\tMost\tAverage\n"
<< "\t" << int(numMvs[0])
<< "\t" << int(numMvs[1])
<< "\t" << numMvs[2];
}
void load2DArr(int map[][SIZE_EXITS], int const n, int const m) {
int tempMap[21][3] = {
{ 0, 0, 0 }, // room not actually used
{ 2, 4, 19 },
{ 1, 3, 6 },
{ 2, 8, 20 },
{ 1, 5, 9 },
{ 4, 6, 11 },
{ 2, 5, 7 },
{ 6, 8, 12 },
{ 3, 7, 13 },
{ 4, 10, 16 },
{ 9, 11, 14 },
{ 5, 10, 12 },
{ 7, 11, 15 },
{ 8, 15, 18 },
{ 10, 15, 17 },
{ 12, 13, 14 },
{ 9, 17, 19 },
{ 14, 16, 18 },
{ 13, 17, 20 },
{ 1, 16, 20 },
{ 3, 18, 19 }
};
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
map[i][j] = tempMap[i][j];
}
void print2DArr(int map[][3], int n, int m, ostream &os) {
cout << "\n";
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
cout << "\t" << map[i][j] << (j % m == m - 1 ? "\n" : ", ");
}
int startHunt(int const map[][3], int player, int wumpus, int bat1, int bat2, int pit1, int pit2, int &count) {
count = 0;
while (true) {
if (player == wumpus) {
cout << "\n\n\tYou awakened the Wumpus. He eats you. \n\tYou lose.";
return -1;
}
else if (player == pit1 || player == pit2) {
cout << "\n\n\tYou fell into a bottomless pit. \n\tYou lose... eventually...";
return 0;
}
if (isWumpusNear(player, wumpus))
cout << "\n\n\tYou smell the unmistakable stench of a Wumpus";
if (isBatNear(player, bat1, bat2))
cout << "\n\n\tYou hear the flapping of large wings";
if (isPitNear(player, pit1, pit2))
cout << "\n\n\tYou feel an ominous breeze";
cout << "\n\nYou are in room " << player;
}
}<|endoftext|>
|
<commit_before><commit_msg>label position and bounds rounding<commit_after><|endoftext|>
|
<commit_before>/*
* ______ __ __ __
* /\ _ \ __ /\ \/\ \ /\ \__
* \ \ \L\ \ __ __ /\_\ \_\ \ \ \____ ___\ \ ,_\ ____
* \ \ __ \/\ \/\ \\/\ \ /'_` \ \ '__`\ / __`\ \ \/ /',__\
* \ \ \/\ \ \ \_/ |\ \ \/\ \L\ \ \ \L\ \/\ \L\ \ \ \_/\__, `\
* \ \_\ \_\ \___/ \ \_\ \___,_\ \_,__/\ \____/\ \__\/\____/
* \/_/\/_/\/__/ \/_/\/__,_ /\/___/ \/___/ \/__/\/___/
* @copyright Copyright 2017 Avidbots Corp.
* @name flatland_server_ndoe.cpp
* @brief Load params and run the ros node for flatland_server
* @author Joseph Duchesne
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2017, Avidbots Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Avidbots Corp. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <ros/ros.h>
#include <signal.h>
#include <string>
#include "flatland_server/simulation_manager.h"
/** Global variables */
flatland_server::SimulationManager *simulation_manager;
/**
* @name SigintHandler
* @brief Interrupt handler - sends shutdown signal to simulation_manager
* @param[in] sig: signal itself
*/
void SigintHandler(int sig) {
ROS_WARN_NAMED("Node", "*** Shutting down... ***");
if (simulation_manager != nullptr) {
simulation_manager->Shutdown();
delete simulation_manager;
simulation_manager = nullptr;
}
ROS_INFO_STREAM_NAMED("Node", "Beginning ros shutdown");
ros::shutdown();
}
/**
* @name main
* @brief Entrypoint for Flatland Server ros node
*/
int main(int argc, char **argv) {
ros::init(argc, argv, "Node", ros::init_options::NoSigintHandler);
ros::NodeHandle node_handle("~");
// Load parameters
float initial_rate = 60.0; // The physics update rate (Hz)
std::string world_path;
if (node_handle.getParam("initial_rate", initial_rate)) {
ROS_INFO_STREAM_NAMED("Node", "initial rate: " << initial_rate);
} else {
ROS_INFO_STREAM_NAMED("Node", "assuming initial rate: " << initial_rate);
}
if (node_handle.getParam("world_path", world_path)) {
ROS_INFO_STREAM_NAMED("Node", "world path: " << world_path);
} else {
ROS_FATAL_NAMED("Node", "No world_path parameter given!");
ros::shutdown();
return 1;
}
// Create simulation manager object
simulation_manager =
new flatland_server::SimulationManager(world_path, initial_rate);
// Register sigint shutdown handler
signal(SIGINT, SigintHandler);
ROS_INFO_STREAM_NAMED("Node", "Initialized");
simulation_manager->Main();
ROS_INFO_STREAM_NAMED("Node", "Returned from simulation manager main");
delete simulation_manager;
simulation_manager = nullptr;
return 0;
}
<commit_msg>added another comment<commit_after>/*
* ______ __ __ __
* /\ _ \ __ /\ \/\ \ /\ \__
* \ \ \L\ \ __ __ /\_\ \_\ \ \ \____ ___\ \ ,_\ ____
* \ \ __ \/\ \/\ \\/\ \ /'_` \ \ '__`\ / __`\ \ \/ /',__\
* \ \ \/\ \ \ \_/ |\ \ \/\ \L\ \ \ \L\ \/\ \L\ \ \ \_/\__, `\
* \ \_\ \_\ \___/ \ \_\ \___,_\ \_,__/\ \____/\ \__\/\____/
* \/_/\/_/\/__/ \/_/\/__,_ /\/___/ \/___/ \/__/\/___/
* @copyright Copyright 2017 Avidbots Corp.
* @name flatland_server_ndoe.cpp
* @brief Load params and run the ros node for flatland_server
* @author Joseph Duchesne
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2017, Avidbots Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Avidbots Corp. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <ros/ros.h>
#include <signal.h>
#include <string>
#include "flatland_server/simulation_manager.h"
/** Global variables */
flatland_server::SimulationManager *simulation_manager;
/**
* @name SigintHandler
* @brief Interrupt handler - sends shutdown signal to simulation_manager
* @param[in] sig: signal itself
*/
void SigintHandler(int sig) {
ROS_WARN_NAMED("Node", "*** Shutting down... ***");
if (simulation_manager != nullptr) {
simulation_manager->Shutdown();
delete simulation_manager;
simulation_manager = nullptr;
}
ROS_INFO_STREAM_NAMED("Node", "Beginning ros shutdown");
ros::shutdown();
}
/**
* @name main
* @brief Entrypoint for Flatland Server ros node
*/
int main(int argc, char **argv) {
ros::init(argc, argv, "Node", ros::init_options::NoSigintHandler);
ros::NodeHandle node_handle("~");
// Load parameters
float initial_rate = 60.0; // The physics update rate (Hz)
std::string world_path; // The file path to the world.yaml file
if (node_handle.getParam("initial_rate", initial_rate)) {
ROS_INFO_STREAM_NAMED("Node", "initial rate: " << initial_rate);
} else {
ROS_INFO_STREAM_NAMED("Node", "assuming initial rate: " << initial_rate);
}
if (node_handle.getParam("world_path", world_path)) {
ROS_INFO_STREAM_NAMED("Node", "world path: " << world_path);
} else {
ROS_FATAL_NAMED("Node", "No world_path parameter given!");
ros::shutdown();
return 1;
}
// Create simulation manager object
simulation_manager =
new flatland_server::SimulationManager(world_path, initial_rate);
// Register sigint shutdown handler
signal(SIGINT, SigintHandler);
ROS_INFO_STREAM_NAMED("Node", "Initialized");
simulation_manager->Main();
ROS_INFO_STREAM_NAMED("Node", "Returned from simulation manager main");
delete simulation_manager;
simulation_manager = nullptr;
return 0;
}
<|endoftext|>
|
<commit_before>/*
* The MIT License (MIT)
*
* Copyright (c) 2016 Julian Ganz
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef CMOH_STRING_VIEW_HPP__
#define CMOH_STRING_VIEW_HPP__
// We try to detect whether a standard `string_view` is available, but only for
// post-C++14 (we don't expect a C++14 STL to ship it). We don't consider the
// `experimental/string_view` header, since at least one implementation (the one
// shipped with GCC), lacks `constexpr` in critical places.
#if __cplusplus > 201402L
# if __has_include(<string_view>)
# define has_string_view 1
# endif
#endif
// local includes
#include <cmoh/char_traits.hpp>
// use one of the `string_view` implementations
#ifdef has_string_view
#include <string_view>
namespace cmoh {
template <
typename CharT,
typename Traits = char_traits<CharT>
>
using basic_string_view = std::basic_string_view<CharT, Traits>;
}
#else
// std includes
#include <algorithm>
#include <cstddef>
#include <limits>
#include <ostream>
#include <stdexcept>
namespace cmoh {
/**
* Predefinition of the C++17 std::basic_string_view type
*
* This template provides an optional type which is modeled after the
* std::basic_string_view which is part of the C++17 standard proposal. Note
* that only a subset of the interface is provided. Also note that the Traits
* defaults to a custom `char_traits`, which has some additional compile
* capabilities but is somewhat slow at run time.
*
* For documentation, refer to the C++17 proposal or your favorite STL
* documentation site.
*/
template <
typename CharT,
typename Traits = char_traits<CharT>
>
class basic_string_view {
public:
typedef Traits traits_type;
// value types
typedef CharT value_type;
typedef CharT* pointer;
typedef CharT const* const_pointer;
typedef CharT& reference;
typedef CharT const& const_reference;
// TODO: iterator types
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
constexpr basic_string_view() noexcept : _data(nullptr), _count(0) {}
constexpr basic_string_view(const basic_string_view& other) noexcept =
default;
constexpr basic_string_view(const CharT* data, size_type count) noexcept :
_data(data), _count(count) {}
constexpr basic_string_view(const CharT* data) :
_data(data), _count(traits_type::length(data)) {}
basic_string_view& operator=( const basic_string_view& view ) = default;
// TODO: iterators
constexpr const_reference operator[](size_type pos) const {
return _data[pos];
}
constexpr const_reference at(size_type pos) const {
if (pos >= size())
throw std::out_of_range("Access out-of-bounds element.");
return _data[pos];
}
constexpr const_reference front() const {
return _data[0];
}
constexpr const_reference back() const {
return _data[size() - 1];
}
constexpr const_pointer data() const noexcept {
return _data;
}
constexpr size_type size() const noexcept {
return _count;
}
constexpr size_type length() const noexcept {
return size();
}
constexpr size_type max_size() const noexcept {
return std::numeric_limits<size_type>::max();
}
constexpr bool empty() const noexcept {
return size() == 0;
}
constexpr void remove_prefix(size_type n) {
_data+=n;
_count-=n;
}
constexpr void remove_suffix(size_type n) {
_count-=n;
}
constexpr void swap(basic_string_view& v) {
const_pointer* data = v._data;
size_type count = v._count;
v._data = _data;
v._count = _count;
_data = data;
_count = count;
}
size_type copy(CharT* dest, size_type count, size_type pos = 0) const {
if (pos >= size())
throw std::out_of_range("Access out-of-bounds element.");
count = std::min(count, size() - pos);
traits_type::copy(
dest,
&_data[pos],
count*sizeof(value_type)/sizeof(char)
);
return count;
}
constexpr basic_string_view
substr(size_type pos = 0, size_type count = npos) const {
if (pos >= size())
throw std::out_of_range("Access out-of-bounds element.");
return basic_string_view(_data + pos, std::min(count, size() - pos));
}
constexpr int compare(basic_string_view v) const noexcept {
auto retval = traits_type::compare(
data(),
v.data(),
std::min(size(), v.size())
);
if (retval != 0)
return retval;
if (size() == v.size())
return 0;
return size() < v.size() ? -1 : 1;
}
constexpr int
compare(size_type pos1, size_type count1, basic_string_view v) const {
return substr(pos1, count1).compare(v);
}
constexpr int
compare(
size_type pos1,
size_type count1,
basic_string_view v,
size_type pos2,
size_type count2
) const {
return substr(pos1, count1).compare(v.substr(pos2, count2));
}
constexpr int compare(const_pointer s) const {
return compare(basic_string_view(s));
}
constexpr int
compare(size_type pos1, size_type count1, const_pointer s) const {
return substr(pos1, count1).compare(s);
}
constexpr int
compare(
size_type pos1,
size_type count1,
const_pointer s,
size_type count2
) const {
return substr(pos1, count1).compare(basic_string_view(s, count2));
}
// TODO: find, rfind, ...
static constexpr size_type npos = size_type(-1);
private:
value_type const* _data;
size_type _count;
};
}
template<
class CharT,
class Traits
>
constexpr bool operator == (
cmoh::basic_string_view<CharT,Traits> lhs,
cmoh::basic_string_view<CharT,Traits> rhs
) noexcept {
return lhs.compare(rhs) == 0;
}
template<
class CharT,
class Traits
>
constexpr bool operator != (
cmoh::basic_string_view<CharT,Traits> lhs,
cmoh::basic_string_view<CharT,Traits> rhs
) noexcept {
return lhs.compare(rhs) != 0;
}
template<
class CharT,
class Traits
>
constexpr bool operator < (
cmoh::basic_string_view<CharT,Traits> lhs,
cmoh::basic_string_view<CharT,Traits> rhs
) noexcept {
return lhs.compare(rhs) < 0;
}
template<
class CharT,
class Traits
>
constexpr bool operator <= (
cmoh::basic_string_view<CharT,Traits> lhs,
cmoh::basic_string_view<CharT,Traits> rhs
) noexcept {
return lhs.compare(rhs) <= 0;
}
template<
class CharT,
class Traits
>
constexpr bool operator > (
cmoh::basic_string_view<CharT,Traits> lhs,
cmoh::basic_string_view<CharT,Traits> rhs
) noexcept {
return lhs.compare(rhs) > 0;
}
template<
class CharT,
class Traits
>
constexpr bool operator >= (
cmoh::basic_string_view<CharT,Traits> lhs,
cmoh::basic_string_view<CharT,Traits> rhs
) noexcept {
return lhs.compare(rhs) >= 0;
}
template <
class CharT,
class Traits
>
std::basic_ostream<CharT, Traits>&
operator << (
std::basic_ostream<CharT, Traits>& stream,
cmoh::basic_string_view<CharT, Traits> view
) {
auto len = view.size();
auto pos = view.data();
while (len > 0) {
stream.put(*pos);
++pos;
--len;
}
return stream;
}
// TODO: hash
#endif
namespace cmoh {
typedef basic_string_view<char> string_view;
typedef basic_string_view<wchar_t> wstring_view;
typedef basic_string_view<char16_t> u16string_view;
typedef basic_string_view<char32_t> u32string_view;
/**
* Create a string view with the standard char traits
*/
template <
typename CharT,
typename Traits
>
constexpr
basic_string_view<CharT, std::char_traits<CharT>>
std_traits_using(
basic_string_view<CharT, Traits> const& view
) {
return basic_string_view<CharT, std::char_traits<CharT>>(
view.data(),
view.size()
);
}
/**
* Create a string view with the cmoh char traits
*/
template <
typename CharT,
typename Traits
>
constexpr
basic_string_view<CharT>
cmoh_traits_using(
basic_string_view<CharT, Traits> const& view
) {
return basic_string_view<CharT>(view.data(), view.size());
}
}
// workaround to interface our custom char traits with the outside world
template <
class CharT
>
std::basic_ostream<CharT, std::char_traits<CharT>>&
operator << (
std::basic_ostream<CharT>& stream,
cmoh::basic_string_view<CharT> view
) {
return stream << std_traits_using(view);
}
#endif
<commit_msg>Add more workaround operators to interface traits<commit_after>/*
* The MIT License (MIT)
*
* Copyright (c) 2016 Julian Ganz
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef CMOH_STRING_VIEW_HPP__
#define CMOH_STRING_VIEW_HPP__
// We try to detect whether a standard `string_view` is available, but only for
// post-C++14 (we don't expect a C++14 STL to ship it). We don't consider the
// `experimental/string_view` header, since at least one implementation (the one
// shipped with GCC), lacks `constexpr` in critical places.
#if __cplusplus > 201402L
# if __has_include(<string_view>)
# define has_string_view 1
# endif
#endif
// local includes
#include <cmoh/char_traits.hpp>
// use one of the `string_view` implementations
#ifdef has_string_view
#include <string_view>
namespace cmoh {
template <
typename CharT,
typename Traits = char_traits<CharT>
>
using basic_string_view = std::basic_string_view<CharT, Traits>;
}
#else
// std includes
#include <algorithm>
#include <cstddef>
#include <limits>
#include <ostream>
#include <stdexcept>
namespace cmoh {
/**
* Predefinition of the C++17 std::basic_string_view type
*
* This template provides an optional type which is modeled after the
* std::basic_string_view which is part of the C++17 standard proposal. Note
* that only a subset of the interface is provided. Also note that the Traits
* defaults to a custom `char_traits`, which has some additional compile
* capabilities but is somewhat slow at run time.
*
* For documentation, refer to the C++17 proposal or your favorite STL
* documentation site.
*/
template <
typename CharT,
typename Traits = char_traits<CharT>
>
class basic_string_view {
public:
typedef Traits traits_type;
// value types
typedef CharT value_type;
typedef CharT* pointer;
typedef CharT const* const_pointer;
typedef CharT& reference;
typedef CharT const& const_reference;
// TODO: iterator types
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
constexpr basic_string_view() noexcept : _data(nullptr), _count(0) {}
constexpr basic_string_view(const basic_string_view& other) noexcept =
default;
constexpr basic_string_view(const CharT* data, size_type count) noexcept :
_data(data), _count(count) {}
constexpr basic_string_view(const CharT* data) :
_data(data), _count(traits_type::length(data)) {}
basic_string_view& operator=( const basic_string_view& view ) = default;
// TODO: iterators
constexpr const_reference operator[](size_type pos) const {
return _data[pos];
}
constexpr const_reference at(size_type pos) const {
if (pos >= size())
throw std::out_of_range("Access out-of-bounds element.");
return _data[pos];
}
constexpr const_reference front() const {
return _data[0];
}
constexpr const_reference back() const {
return _data[size() - 1];
}
constexpr const_pointer data() const noexcept {
return _data;
}
constexpr size_type size() const noexcept {
return _count;
}
constexpr size_type length() const noexcept {
return size();
}
constexpr size_type max_size() const noexcept {
return std::numeric_limits<size_type>::max();
}
constexpr bool empty() const noexcept {
return size() == 0;
}
constexpr void remove_prefix(size_type n) {
_data+=n;
_count-=n;
}
constexpr void remove_suffix(size_type n) {
_count-=n;
}
constexpr void swap(basic_string_view& v) {
const_pointer* data = v._data;
size_type count = v._count;
v._data = _data;
v._count = _count;
_data = data;
_count = count;
}
size_type copy(CharT* dest, size_type count, size_type pos = 0) const {
if (pos >= size())
throw std::out_of_range("Access out-of-bounds element.");
count = std::min(count, size() - pos);
traits_type::copy(
dest,
&_data[pos],
count*sizeof(value_type)/sizeof(char)
);
return count;
}
constexpr basic_string_view
substr(size_type pos = 0, size_type count = npos) const {
if (pos >= size())
throw std::out_of_range("Access out-of-bounds element.");
return basic_string_view(_data + pos, std::min(count, size() - pos));
}
constexpr int compare(basic_string_view v) const noexcept {
auto retval = traits_type::compare(
data(),
v.data(),
std::min(size(), v.size())
);
if (retval != 0)
return retval;
if (size() == v.size())
return 0;
return size() < v.size() ? -1 : 1;
}
constexpr int
compare(size_type pos1, size_type count1, basic_string_view v) const {
return substr(pos1, count1).compare(v);
}
constexpr int
compare(
size_type pos1,
size_type count1,
basic_string_view v,
size_type pos2,
size_type count2
) const {
return substr(pos1, count1).compare(v.substr(pos2, count2));
}
constexpr int compare(const_pointer s) const {
return compare(basic_string_view(s));
}
constexpr int
compare(size_type pos1, size_type count1, const_pointer s) const {
return substr(pos1, count1).compare(s);
}
constexpr int
compare(
size_type pos1,
size_type count1,
const_pointer s,
size_type count2
) const {
return substr(pos1, count1).compare(basic_string_view(s, count2));
}
// TODO: find, rfind, ...
static constexpr size_type npos = size_type(-1);
private:
value_type const* _data;
size_type _count;
};
}
template<
class CharT,
class Traits
>
constexpr bool operator == (
cmoh::basic_string_view<CharT,Traits> lhs,
cmoh::basic_string_view<CharT,Traits> rhs
) noexcept {
return lhs.compare(rhs) == 0;
}
template<
class CharT,
class Traits
>
constexpr bool operator != (
cmoh::basic_string_view<CharT,Traits> lhs,
cmoh::basic_string_view<CharT,Traits> rhs
) noexcept {
return lhs.compare(rhs) != 0;
}
template<
class CharT,
class Traits
>
constexpr bool operator < (
cmoh::basic_string_view<CharT,Traits> lhs,
cmoh::basic_string_view<CharT,Traits> rhs
) noexcept {
return lhs.compare(rhs) < 0;
}
template<
class CharT,
class Traits
>
constexpr bool operator <= (
cmoh::basic_string_view<CharT,Traits> lhs,
cmoh::basic_string_view<CharT,Traits> rhs
) noexcept {
return lhs.compare(rhs) <= 0;
}
template<
class CharT,
class Traits
>
constexpr bool operator > (
cmoh::basic_string_view<CharT,Traits> lhs,
cmoh::basic_string_view<CharT,Traits> rhs
) noexcept {
return lhs.compare(rhs) > 0;
}
template<
class CharT,
class Traits
>
constexpr bool operator >= (
cmoh::basic_string_view<CharT,Traits> lhs,
cmoh::basic_string_view<CharT,Traits> rhs
) noexcept {
return lhs.compare(rhs) >= 0;
}
template <
class CharT,
class Traits
>
std::basic_ostream<CharT, Traits>&
operator << (
std::basic_ostream<CharT, Traits>& stream,
cmoh::basic_string_view<CharT, Traits> view
) {
auto len = view.size();
auto pos = view.data();
while (len > 0) {
stream.put(*pos);
++pos;
--len;
}
return stream;
}
// TODO: hash
#endif
namespace cmoh {
typedef basic_string_view<char> string_view;
typedef basic_string_view<wchar_t> wstring_view;
typedef basic_string_view<char16_t> u16string_view;
typedef basic_string_view<char32_t> u32string_view;
/**
* Create a string view with the standard char traits
*/
template <
typename CharT,
typename Traits
>
constexpr
basic_string_view<CharT, std::char_traits<CharT>>
std_traits_using(
basic_string_view<CharT, Traits> const& view
) {
return basic_string_view<CharT, std::char_traits<CharT>>(
view.data(),
view.size()
);
}
/**
* Create a string view with the cmoh char traits
*/
template <
typename CharT,
typename Traits
>
constexpr
basic_string_view<CharT>
cmoh_traits_using(
basic_string_view<CharT, Traits> const& view
) {
return basic_string_view<CharT>(view.data(), view.size());
}
}
// workarounds to interface our custom char traits with the outside world
template<
class CharT
>
constexpr bool operator == (
cmoh::basic_string_view<CharT, cmoh::char_traits<CharT>> lhs,
cmoh::basic_string_view<CharT, std::char_traits<CharT>> rhs
) noexcept {
return lhs == cmoh_traits_using(rhs);
}
template<
class CharT
>
constexpr bool operator == (
cmoh::basic_string_view<CharT, std::char_traits<CharT>> lhs,
cmoh::basic_string_view<CharT, cmoh::char_traits<CharT>> rhs
) noexcept {
return cmoh_traits_using(lhs) == rhs;
}
template<
class CharT,
class Traits
>
constexpr bool operator != (
cmoh::basic_string_view<CharT, cmoh::char_traits<CharT>> lhs,
cmoh::basic_string_view<CharT, std::char_traits<CharT>> rhs
) noexcept {
return lhs != cmoh_traits_using(rhs);
}
template<
class CharT
>
constexpr bool operator != (
cmoh::basic_string_view<CharT, std::char_traits<CharT>> lhs,
cmoh::basic_string_view<CharT, cmoh::char_traits<CharT>> rhs
) noexcept {
return cmoh_traits_using(lhs) != rhs;
}
template<
class CharT,
class Traits
>
constexpr bool operator < (
cmoh::basic_string_view<CharT, cmoh::char_traits<CharT>> lhs,
cmoh::basic_string_view<CharT, std::char_traits<CharT>> rhs
) noexcept {
return lhs < cmoh_traits_using(rhs);
}
template<
class CharT
>
constexpr bool operator < (
cmoh::basic_string_view<CharT, std::char_traits<CharT>> lhs,
cmoh::basic_string_view<CharT, cmoh::char_traits<CharT>> rhs
) noexcept {
return cmoh_traits_using(lhs) < rhs;
}
template<
class CharT,
class Traits
>
constexpr bool operator <= (
cmoh::basic_string_view<CharT, cmoh::char_traits<CharT>> lhs,
cmoh::basic_string_view<CharT, std::char_traits<CharT>> rhs
) noexcept {
return lhs <= cmoh_traits_using(rhs);
}
template<
class CharT
>
constexpr bool operator <= (
cmoh::basic_string_view<CharT, std::char_traits<CharT>> lhs,
cmoh::basic_string_view<CharT, cmoh::char_traits<CharT>> rhs
) noexcept {
return cmoh_traits_using(lhs) <= rhs;
}
template<
class CharT,
class Traits
>
constexpr bool operator > (
cmoh::basic_string_view<CharT, cmoh::char_traits<CharT>> lhs,
cmoh::basic_string_view<CharT, std::char_traits<CharT>> rhs
) noexcept {
return lhs > cmoh_traits_using(rhs);
}
template<
class CharT
>
constexpr bool operator > (
cmoh::basic_string_view<CharT, std::char_traits<CharT>> lhs,
cmoh::basic_string_view<CharT, cmoh::char_traits<CharT>> rhs
) noexcept {
return cmoh_traits_using(lhs) > rhs;
}
template<
class CharT,
class Traits
>
constexpr bool operator >= (
cmoh::basic_string_view<CharT, cmoh::char_traits<CharT>> lhs,
cmoh::basic_string_view<CharT, std::char_traits<CharT>> rhs
) noexcept {
return lhs >= cmoh_traits_using(rhs);
}
template<
class CharT
>
constexpr bool operator >= (
cmoh::basic_string_view<CharT, std::char_traits<CharT>> lhs,
cmoh::basic_string_view<CharT, cmoh::char_traits<CharT>> rhs
) noexcept {
return cmoh_traits_using(lhs) >= rhs;
}
template <
class CharT
>
std::basic_ostream<CharT, std::char_traits<CharT>>&
operator << (
std::basic_ostream<CharT>& stream,
cmoh::basic_string_view<CharT> view
) {
return stream << std_traits_using(view);
}
#endif
<|endoftext|>
|
<commit_before>#pragma once
#include <future>
#include <chrono>
#include <string>
#include <cstdint>
#include <curlpp/cURLpp.hpp>
#include <curlpp/Easy.hpp>
#include <curlpp/Options.hpp>
namespace wonder_rabbit_project
{
namespace wonderland
{
namespace loader
{
using buffer_t = std::vector<std::uint8_t>;
using future_t = std::future<buffer_t>;
// main feature: load data from url with async/future
template < class T = void >
auto load(const std::string& url)
-> future_t
{
return std::async
( std::launch::async
, [ url ]
{
// temporary buffer
buffer_t buffer;
cURLpp::Cleanup cleaner;
cURLpp::Easy request;
request.setOpt( new cURLpp::Options::Url(url) );
request.setOpt
( new cURLpp::Options::WriteFunction
( cURLpp::Types::WriteFunctionFunctor
( [ &buffer ] (char* p, std::size_t size, std::size_t blocks)
{
const auto total_size = size * blocks;
std::copy( p, p + total_size, std::back_inserter(buffer) );
return total_size;
}
)
)
);
// it is blocking proccess!
request.perform();
return buffer;
}
);
}
}
}
}
<commit_msg>実装を libcurl&libcurlpp から libPoco へ変更<commit_after>#pragma once
#include <future>
#include <chrono>
#include <string>
#include <cstdint>
#include <Poco/Net/HTTPClientSession.h>
#include <Poco/Net/HTTPRequest.h>
#include <Poco/Net/HTTPResponse.h>
#include <Poco/URI.h>
#include <Poco/Exception.h>
namespace wonder_rabbit_project
{
namespace wonderland
{
namespace loader
{
using buffer_t = std::vector<std::uint8_t>;
using future_t = std::future<buffer_t>;
// main feature: load data from url with async/future
template < class T = void >
auto load(const std::string& url)
-> future_t
{
return std::async
( std::launch::async
, [ url ]
{
// temporary buffer
buffer_t buffer;
try
{
Poco::URI uri( url );
Poco::Net::HTTPClientSession session( uri.getHost(), uri.getPort() );
const auto path = uri.getPathAndQuery();
Poco::Net::HTTPRequest request( Poco::Net::HTTPRequest::HTTP_GET, path.empty() ? "/" : path, Poco::Net::HTTPMessage::HTTP_1_1 );
session.sendRequest( request );
Poco::Net::HTTPResponse response;
if ( response.getStatus() != Poco::Net::HTTPResponse::HTTPStatus::HTTP_OK )
return buffer;
auto& bin = session.receiveResponse( response );
std::copy( std::istreambuf_iterator< char >( bin ), std::istreambuf_iterator< char >(), std::back_inserter( buffer ) );
}
catch( const Poco::Exception& e )
{
std::cerr << "== Poco Exception ==> " << e.what();
throw e;
}
return buffer;
}
);
}
}
}
}
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2006 - 2014, Paul Beckingham, Federico Hernandez.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////
#include <cmake.h>
#include <iostream>
#include <Context.h>
#include <Filter.h>
#include <text.h>
#include <util.h>
#include <i18n.h>
#include <main.h>
#include <CmdDuplicate.h>
extern Context context;
////////////////////////////////////////////////////////////////////////////////
CmdDuplicate::CmdDuplicate ()
{
_keyword = "duplicate";
_usage = "task <filter> duplicate <mods>";
_description = STRING_CMD_DUPLICATE_USAGE;
_read_only = false;
_displays_id = false;
}
////////////////////////////////////////////////////////////////////////////////
int CmdDuplicate::execute (std::string& output)
{
int rc = 0;
int count = 0;
// Apply filter.
Filter filter;
std::vector <Task> filtered;
filter.subset (filtered);
if (filtered.size () == 0)
{
context.footnote (STRING_FEEDBACK_NO_TASKS_SP);
return 1;
}
// Apply the command line modifications to the new task.
A3 modifications = context.a3.extract_modifications ();
// Accumulated project change notifications.
std::map <std::string, std::string> projectChanges;
std::vector <Task>::iterator task;
for (task = filtered.begin (); task != filtered.end (); ++task)
{
// Duplicate the specified task.
Task dup (*task);
dup.set ("uuid", uuid ()); // Needs a new UUID.
dup.remove ("start"); // Does not inherit start date.
dup.remove ("end"); // Does not inherit end date.
dup.remove ("entry"); // Does not inherit entry date.
// When duplicating a child task, downgrade it to a plain task.
if (dup.has ("parent"))
{
dup.remove ("parent");
dup.remove ("recur");
dup.remove ("until");
dup.remove ("imask");
std::cout << format (STRING_CMD_DUPLICATE_NON_REC, task->id)
<< "\n";
}
// When duplicating a parent task, create a new parent task.
else if (dup.getStatus () == Task::recurring)
{
dup.remove ("mask");
std::cout << format (STRING_CMD_DUPLICATE_REC, task->id)
<< "\n";
}
dup.setStatus (Task::pending); // Does not inherit status.
// Must occur after Task::recurring check.
modify_task_annotate (dup, modifications);
if (permission (dup,
format (STRING_CMD_DUPLICATE_CONFIRM,
task->id,
task->get ("description")),
filtered.size ()))
{
context.tdb2.add (dup);
++count;
feedback_affected (STRING_CMD_DUPLICATE_TASK, *task);
if (context.verbose ("new-id"))
std::cout << format (STRING_CMD_ADD_FEEDBACK, context.tdb2.next_id ()) + "\n";
if (context.verbose ("project"))
projectChanges[task->get ("project")] = onProjectChange (*task);
}
else
{
std::cout << STRING_CMD_DUPLICATE_NO << "\n";
rc = 1;
if (_permission_quit)
break;
}
}
// Now list the project changes.
std::map <std::string, std::string>::iterator i;
for (i = projectChanges.begin (); i != projectChanges.end (); ++i)
if (i->first != "")
context.footnote (i->second);
context.tdb2.commit ();
feedback_affected (count == 1 ? STRING_CMD_DUPLICATE_1 : STRING_CMD_DUPLICATE_N, count);
return rc;
}
////////////////////////////////////////////////////////////////////////////////
<commit_msg>CmdDuplicate<commit_after>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2006 - 2014, Paul Beckingham, Federico Hernandez.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////
#include <cmake.h>
#include <iostream>
#include <Context.h>
#include <Filter.h>
#include <text.h>
#include <util.h>
#include <i18n.h>
#include <main.h>
#include <CmdDuplicate.h>
extern Context context;
////////////////////////////////////////////////////////////////////////////////
CmdDuplicate::CmdDuplicate ()
{
_keyword = "duplicate";
_usage = "task <filter> duplicate <mods>";
_description = STRING_CMD_DUPLICATE_USAGE;
_read_only = false;
_displays_id = false;
}
////////////////////////////////////////////////////////////////////////////////
int CmdDuplicate::execute (std::string& output)
{
int rc = 0;
int count = 0;
// Apply filter.
Filter filter;
std::vector <Task> filtered;
filter.subset (filtered);
if (filtered.size () == 0)
{
context.footnote (STRING_FEEDBACK_NO_TASKS_SP);
return 1;
}
// Accumulated project change notifications.
std::map <std::string, std::string> projectChanges;
std::vector <Task>::iterator task;
for (task = filtered.begin (); task != filtered.end (); ++task)
{
// Duplicate the specified task.
Task dup (*task);
dup.set ("uuid", uuid ()); // Needs a new UUID.
dup.remove ("start"); // Does not inherit start date.
dup.remove ("end"); // Does not inherit end date.
dup.remove ("entry"); // Does not inherit entry date.
// When duplicating a child task, downgrade it to a plain task.
if (dup.has ("parent"))
{
dup.remove ("parent");
dup.remove ("recur");
dup.remove ("until");
dup.remove ("imask");
std::cout << format (STRING_CMD_DUPLICATE_NON_REC, task->id)
<< "\n";
}
// When duplicating a parent task, create a new parent task.
else if (dup.getStatus () == Task::recurring)
{
dup.remove ("mask");
std::cout << format (STRING_CMD_DUPLICATE_REC, task->id)
<< "\n";
}
dup.setStatus (Task::pending); // Does not inherit status.
// Must occur after Task::recurring check.
dup.modify (Task::modAnnotate);
if (permission (dup,
format (STRING_CMD_DUPLICATE_CONFIRM,
task->id,
task->get ("description")),
filtered.size ()))
{
context.tdb2.add (dup);
++count;
feedback_affected (STRING_CMD_DUPLICATE_TASK, *task);
if (context.verbose ("new-id"))
std::cout << format (STRING_CMD_ADD_FEEDBACK, context.tdb2.next_id ()) + "\n";
if (context.verbose ("project"))
projectChanges[task->get ("project")] = onProjectChange (*task);
}
else
{
std::cout << STRING_CMD_DUPLICATE_NO << "\n";
rc = 1;
if (_permission_quit)
break;
}
}
// Now list the project changes.
std::map <std::string, std::string>::iterator i;
for (i = projectChanges.begin (); i != projectChanges.end (); ++i)
if (i->first != "")
context.footnote (i->second);
context.tdb2.commit ();
feedback_affected (count == 1 ? STRING_CMD_DUPLICATE_1 : STRING_CMD_DUPLICATE_N, count);
return rc;
}
////////////////////////////////////////////////////////////////////////////////
<|endoftext|>
|
<commit_before>#pragma once
/**
@file
@brief bit vector
@author MITSUNARI Shigeo(@herumi)
@license modified new BSD license
http://opensource.org/licenses/BSD-3-Clause
*/
#include <cybozu/exception.hpp>
#include <algorithm>
#include <vector>
#include <assert.h>
namespace cybozu {
template<class T>
size_t RoundupBit(size_t bitLen)
{
const size_t unitSize = sizeof(T) * 8;
return (bitLen + unitSize - 1) / unitSize;
}
template<class T>
T GetMaskBit(size_t bitLen)
{
assert(bitLen < sizeof(T) * 8);
return (T(1) << bitLen) - 1;
}
template<class T>
void SetBlockBit(T *buf, size_t bitLen)
{
const size_t unitSize = sizeof(T) * 8;
const size_t q = bitLen / unitSize;
const size_t r = bitLen % unitSize;
buf[q] |= T(1) << r;
}
template<class T>
void ResetBlockBit(T *buf, size_t bitLen)
{
const size_t unitSize = sizeof(T) * 8;
const size_t q = bitLen / unitSize;
const size_t r = bitLen % unitSize;
buf[q] &= ~(T(1) << r);
}
template<class T>
bool GetBlockBit(const T *buf, size_t bitLen)
{
const size_t unitSize = sizeof(T) * 8;
const size_t q = bitLen / unitSize;
const size_t r = bitLen % unitSize;
return (buf[q] & (T(1) << r)) != 0;
}
template<class T>
void CopyBit(T* dst, const T* src, size_t bitLen)
{
const size_t unitSize = sizeof(T) * 8;
const size_t q = bitLen / unitSize;
const size_t r = bitLen % unitSize;
for (size_t i = 0; i < q; i++) dst[i] = src[i];
if (r == 0) return;
dst[q] = src[q] & GetMaskBit<T>(r);
}
/*
dst[] = (src[] << shift) | ext
@param dst [out] dst[0..bitLen)
@param src [in] src[0..bitLen)
@param bitLen [in] length of src, dst
@param shift [in] 0 <= shift < unitSize
@param ext [in] or bit
*/
template<class T>
T ShiftLeftBit(T* dst, const T* src, size_t bitLen, size_t shift, T ext = 0)
{
if (bitLen == 0) return 0;
const size_t unitSize = sizeof(T) * 8;
if (shift >= unitSize) {
throw cybozu::Exception("ShiftLeftBit:large shift") << shift;
}
const size_t n = RoundupBit<T>(bitLen); // n >= 1 because bitLen > 0
const size_t r = bitLen % unitSize;
const T mask = r > 0 ? GetMaskBit<T>(r) : T(-1);
if (shift == 0) {
if (n == 1) {
dst[0] = (src[0] & mask) | ext;
} else {
dst[n - 1] = src[n - 1] & mask;
for (size_t i = n - 2; i > 0; i--) {
dst[i] = src[i];
}
dst[0] = src[0] | ext;
}
return 0;
}
const size_t revShift = unitSize - shift;
T prev = src[n - 1] & mask;
const T ret = prev >> revShift;
for (size_t i = n - 1; i > 0; i--) {
T v = src[i - 1];
dst[i] = (prev << shift) | (v >> revShift);
prev = v;
}
dst[0] = (prev << shift) | ext;
return ret;
}
namespace bitvector_local {
/*
dst[] = src[] << shift
dst[0..shift) does not change
@param dst [out] dst[shift..bitLen + shift)
@param src [in] src[0..bitLen)
@param bitLen [in] read bit size
@param shift [in] 0 <= shift < unitSize
*/
template<class T>
void shiftLeftBit(T* dst, const T* src, size_t bitLen, size_t shift)
{
const size_t unitSize = sizeof(T) * 8;
assert(bitLen);
assert(0 < shift && shift < unitSize);
const size_t dstN = RoundupBit<T>(bitLen + shift);
const size_t srcN = RoundupBit<T>(bitLen);
const size_t r = bitLen % unitSize;
const T mask = r ? GetMaskBit<T>(r) : T(-1);
const size_t revShift = unitSize - shift;
T prev = src[srcN - 1] & mask;
if (dstN > srcN) {
dst[dstN - 1] = prev >> revShift;
}
for (size_t i = srcN - 1; i > 0; i--) {
T v = src[i - 1];
dst[i] = (prev << shift) | (v >> revShift);
prev = v;
}
T ext = dst[0] & GetMaskBit<T>(shift);
dst[0] = (prev << shift) | ext;
}
/*
dst[] = src[] >> shift
@param dst [out] dst[0..bitLen)
@param src [in] src[shift..bitLen + shift)
@param bitLen [in] write bit size
@param shift [in] 0 <= shift < unitSize
@note src[bitLen + shift - 1] is accessable
*/
template<class T>
void shiftRightBit(T* dst, const T* src, size_t bitLen, size_t shift)
{
const size_t unitSize = sizeof(T) * 8;
assert(bitLen);
assert(0 < shift && shift < unitSize);
const size_t dstN = RoundupBit<T>(bitLen);
const size_t srcN = RoundupBit<T>(bitLen + shift);// srcN = dstN, dstN + 1
const size_t r = (bitLen + shift) % unitSize;
const T mask = r ? GetMaskBit<T>(r) : T(-1);
if (srcN == 1) {
dst[0] = (src[0] & mask) >> shift;
return;
}
const size_t revShift = unitSize - shift;
T prev = src[0];
for (size_t i = 0; i < srcN - 2; i++) {
T v = src[i + 1];
dst[i] = (prev >> shift) | (v << revShift);
prev = v;
}
// i = srcN - 1
T v = src[srcN - 1] & mask;
dst[srcN - 2] = (prev >> shift) | (v << revShift);
if (srcN == dstN) {
dst[srcN - 1] = v >> shift;
}
}
} // cybozu::bitvector_local
template<class T>
class BitVectorT {
static const size_t unitSize = sizeof(T) * 8;
size_t bitLen_;
std::vector<T> v_;
public:
BitVectorT() : bitLen_(0) {}
BitVectorT(const T *buf, size_t bitLen)
{
init(buf, bitLen);
}
void init(const T *buf, size_t bitLen)
{
resize(bitLen);
std::copy(buf, buf + v_.size(), &v_[0]);
}
void resize(size_t bitLen)
{
bitLen_ = bitLen;
const size_t n = RoundupBit<T>(bitLen);
const size_t r = bitLen % unitSize;
v_.resize(n);
if (r) {
v_[n - 1] &= GetMaskBit<T>(r);
}
}
void reserve(size_t bitLen)
{
v_.reserve(RoundupBit<T>(bitLen));
}
bool get(size_t idx) const
{
if (idx >= bitLen_) throw cybozu::Exception("BitVectorT:get:bad idx") << idx;
return GetBlockBit(v_.data(), idx);
}
void clear()
{
bitLen_ = 0;
v_.clear();
}
void set(size_t idx, bool b)
{
if (b) {
set(idx);
} else {
reset(idx);
}
}
// set(idx, true);
void set(size_t idx)
{
if (idx >= bitLen_) throw cybozu::Exception("BitVectorT:set:bad idx") << idx;
SetBlockBit(v_.data(), idx);
}
// set(idx, false);
void reset(size_t idx)
{
if (idx >= bitLen_) throw cybozu::Exception("BitVectorT:reset:bad idx") << idx;
ResetBlockBit(v_.data(), idx);
}
size_t size() const { return bitLen_; }
const T *getBlock() const { return &v_[0]; }
T *getBlock() { return &v_[0]; }
size_t getBlockSize() const { return v_.size(); }
/*
append src[0, bitLen)
*/
void append(const T* src, size_t bitLen)
{
if (bitLen == 0) return;
const size_t q = bitLen_ / unitSize;
const size_t r = bitLen_ % unitSize;
resize(bitLen_ + bitLen);
if (r == 0) {
CopyBit<T>(&v_[q], src, bitLen);
return;
}
bitvector_local::shiftLeftBit<T>(&v_[q], src, bitLen, r);
}
/*
append src & mask(bitLen)
*/
void append(uint64_t src, size_t bitLen)
{
if (bitLen == 0) return;
if (bitLen > unitSize) {
throw cybozu::Exception("BitVectorT:append:bad bitLen") << bitLen;
}
if (bitLen < unitSize) {
src &= GetMaskBit<T>(bitLen);
}
const size_t q = bitLen_ / unitSize;
const size_t r = bitLen_ % unitSize;
resize(bitLen_ + bitLen);
if (r == 0) {
v_[q] = T(src);
return;
}
v_[q] |= T(src << r);
if (r + bitLen > unitSize) {
v_[q + 1] = T(src >> (unitSize - r));
}
}
/*
append bitVector
*/
void append(const BitVectorT<T>& v)
{
append(v.getBlock(), v.size());
}
/*
dst[0, bitLen) = vec[pos, pos + bitLen)
*/
void extract(T* dst, size_t pos, size_t bitLen) const
{
if (bitLen == 0) return;
if (pos + bitLen > bitLen_) {
throw cybozu::Exception("BitVectorT:extract:bad range") << bitLen << pos << bitLen_;
}
const size_t q = pos / unitSize;
const size_t r = pos % unitSize;
if (r == 0) {
CopyBit<T>(dst, &v_[q], bitLen);
return;
}
bitvector_local::shiftRightBit<T>(dst, &v_[q], bitLen, r);
}
/*
dst = vec[pos, pos + bitLen)
*/
void extract(BitVectorT<T>& dst, size_t pos, size_t bitLen) const
{
dst.resize(bitLen);
extract(dst.getBlock(), pos, bitLen);
}
/*
return vec[pos, pos + bitLen)
*/
T extract(size_t pos, size_t bitLen) const
{
if (bitLen == 0) return 0;
if (bitLen > unitSize || pos + bitLen > bitLen_) {
throw cybozu::Exception("BitVectorT:extract:bad range") << bitLen << pos << bitLen_;
}
const size_t q = pos / unitSize;
const size_t r = pos % unitSize;
T v;
if (r == 0) {
v = v_[q];
} else if (q == v_.size() - 1) {
v = v_[q] >> r;
} else {
v = (v_[q] >> r) | v_[q + 1] << (unitSize - r);
}
if (bitLen < unitSize) {
v &= GetMaskBit<T>(bitLen);
}
return v;
}
bool operator==(const BitVectorT<T>& rhs) const { return v_ == rhs.v_; }
bool operator!=(const BitVectorT<T>& rhs) const { return v_ != rhs.v_; }
};
typedef BitVectorT<size_t> BitVector;
} // cybozu
<commit_msg>rename unitSize to unitBitSize<commit_after>#pragma once
/**
@file
@brief bit vector
@author MITSUNARI Shigeo(@herumi)
@license modified new BSD license
http://opensource.org/licenses/BSD-3-Clause
*/
#include <cybozu/exception.hpp>
#include <algorithm>
#include <vector>
#include <assert.h>
namespace cybozu {
template<class T>
size_t RoundupBit(size_t bitLen)
{
const size_t unitBitSize = sizeof(T) * 8;
return (bitLen + unitBitSize - 1) / unitBitSize;
}
template<class T>
T GetMaskBit(size_t bitLen)
{
assert(bitLen < sizeof(T) * 8);
return (T(1) << bitLen) - 1;
}
template<class T>
void SetBlockBit(T *buf, size_t bitLen)
{
const size_t unitBitSize = sizeof(T) * 8;
const size_t q = bitLen / unitBitSize;
const size_t r = bitLen % unitBitSize;
buf[q] |= T(1) << r;
}
template<class T>
void ResetBlockBit(T *buf, size_t bitLen)
{
const size_t unitBitSize = sizeof(T) * 8;
const size_t q = bitLen / unitBitSize;
const size_t r = bitLen % unitBitSize;
buf[q] &= ~(T(1) << r);
}
template<class T>
bool GetBlockBit(const T *buf, size_t bitLen)
{
const size_t unitBitSize = sizeof(T) * 8;
const size_t q = bitLen / unitBitSize;
const size_t r = bitLen % unitBitSize;
return (buf[q] & (T(1) << r)) != 0;
}
template<class T>
void CopyBit(T* dst, const T* src, size_t bitLen)
{
const size_t unitBitSize = sizeof(T) * 8;
const size_t q = bitLen / unitBitSize;
const size_t r = bitLen % unitBitSize;
for (size_t i = 0; i < q; i++) dst[i] = src[i];
if (r == 0) return;
dst[q] = src[q] & GetMaskBit<T>(r);
}
/*
dst[] = (src[] << shift) | ext
@param dst [out] dst[0..bitLen)
@param src [in] src[0..bitLen)
@param bitLen [in] length of src, dst
@param shift [in] 0 <= shift < unitBitSize
@param ext [in] or bit
*/
template<class T>
T ShiftLeftBit(T* dst, const T* src, size_t bitLen, size_t shift, T ext = 0)
{
if (bitLen == 0) return 0;
const size_t unitBitSize = sizeof(T) * 8;
if (shift >= unitBitSize) {
throw cybozu::Exception("ShiftLeftBit:large shift") << shift;
}
const size_t n = RoundupBit<T>(bitLen); // n >= 1 because bitLen > 0
const size_t r = bitLen % unitBitSize;
const T mask = r > 0 ? GetMaskBit<T>(r) : T(-1);
if (shift == 0) {
if (n == 1) {
dst[0] = (src[0] & mask) | ext;
} else {
dst[n - 1] = src[n - 1] & mask;
for (size_t i = n - 2; i > 0; i--) {
dst[i] = src[i];
}
dst[0] = src[0] | ext;
}
return 0;
}
const size_t revShift = unitBitSize - shift;
T prev = src[n - 1] & mask;
const T ret = prev >> revShift;
for (size_t i = n - 1; i > 0; i--) {
T v = src[i - 1];
dst[i] = (prev << shift) | (v >> revShift);
prev = v;
}
dst[0] = (prev << shift) | ext;
return ret;
}
namespace bitvector_local {
/*
dst[] = src[] << shift
dst[0..shift) does not change
@param dst [out] dst[shift..bitLen + shift)
@param src [in] src[0..bitLen)
@param bitLen [in] read bit size
@param shift [in] 0 <= shift < unitBitSize
*/
template<class T>
void shiftLeftBit(T* dst, const T* src, size_t bitLen, size_t shift)
{
const size_t unitBitSize = sizeof(T) * 8;
assert(bitLen);
assert(0 < shift && shift < unitBitSize);
const size_t dstN = RoundupBit<T>(bitLen + shift);
const size_t srcN = RoundupBit<T>(bitLen);
const size_t r = bitLen % unitBitSize;
const T mask = r ? GetMaskBit<T>(r) : T(-1);
const size_t revShift = unitBitSize - shift;
T prev = src[srcN - 1] & mask;
if (dstN > srcN) {
dst[dstN - 1] = prev >> revShift;
}
for (size_t i = srcN - 1; i > 0; i--) {
T v = src[i - 1];
dst[i] = (prev << shift) | (v >> revShift);
prev = v;
}
T ext = dst[0] & GetMaskBit<T>(shift);
dst[0] = (prev << shift) | ext;
}
/*
dst[] = src[] >> shift
@param dst [out] dst[0..bitLen)
@param src [in] src[shift..bitLen + shift)
@param bitLen [in] write bit size
@param shift [in] 0 <= shift < unitBitSize
@note src[bitLen + shift - 1] is accessable
*/
template<class T>
void shiftRightBit(T* dst, const T* src, size_t bitLen, size_t shift)
{
const size_t unitBitSize = sizeof(T) * 8;
assert(bitLen);
assert(0 < shift && shift < unitBitSize);
const size_t dstN = RoundupBit<T>(bitLen);
const size_t srcN = RoundupBit<T>(bitLen + shift);// srcN = dstN, dstN + 1
const size_t r = (bitLen + shift) % unitBitSize;
const T mask = r ? GetMaskBit<T>(r) : T(-1);
if (srcN == 1) {
dst[0] = (src[0] & mask) >> shift;
return;
}
const size_t revShift = unitBitSize - shift;
T prev = src[0];
for (size_t i = 0; i < srcN - 2; i++) {
T v = src[i + 1];
dst[i] = (prev >> shift) | (v << revShift);
prev = v;
}
// i = srcN - 1
T v = src[srcN - 1] & mask;
dst[srcN - 2] = (prev >> shift) | (v << revShift);
if (srcN == dstN) {
dst[srcN - 1] = v >> shift;
}
}
} // cybozu::bitvector_local
template<class T>
class BitVectorT {
static const size_t unitBitSize = sizeof(T) * 8;
size_t bitLen_;
std::vector<T> v_;
public:
typedef T value_type;
BitVectorT() : bitLen_(0) {}
BitVectorT(const T *buf, size_t bitLen)
{
init(buf, bitLen);
}
void init(const T *buf, size_t bitLen)
{
resize(bitLen);
std::copy(buf, buf + v_.size(), &v_[0]);
}
void resize(size_t bitLen)
{
bitLen_ = bitLen;
const size_t n = RoundupBit<T>(bitLen);
const size_t r = bitLen % unitBitSize;
v_.resize(n);
if (r) {
v_[n - 1] &= GetMaskBit<T>(r);
}
}
void reserve(size_t bitLen)
{
v_.reserve(RoundupBit<T>(bitLen));
}
bool get(size_t idx) const
{
if (idx >= bitLen_) throw cybozu::Exception("BitVectorT:get:bad idx") << idx;
return GetBlockBit(v_.data(), idx);
}
void clear()
{
bitLen_ = 0;
v_.clear();
}
void set(size_t idx, bool b)
{
if (b) {
set(idx);
} else {
reset(idx);
}
}
// set(idx, true);
void set(size_t idx)
{
if (idx >= bitLen_) throw cybozu::Exception("BitVectorT:set:bad idx") << idx;
SetBlockBit(v_.data(), idx);
}
// set(idx, false);
void reset(size_t idx)
{
if (idx >= bitLen_) throw cybozu::Exception("BitVectorT:reset:bad idx") << idx;
ResetBlockBit(v_.data(), idx);
}
size_t size() const { return bitLen_; }
const T *getBlock() const { return &v_[0]; }
T *getBlock() { return &v_[0]; }
size_t getBlockSize() const { return v_.size(); }
/*
append src[0, bitLen)
*/
void append(const T* src, size_t bitLen)
{
if (bitLen == 0) return;
const size_t q = bitLen_ / unitBitSize;
const size_t r = bitLen_ % unitBitSize;
resize(bitLen_ + bitLen);
if (r == 0) {
CopyBit<T>(&v_[q], src, bitLen);
return;
}
bitvector_local::shiftLeftBit<T>(&v_[q], src, bitLen, r);
}
/*
append src & mask(bitLen)
*/
void append(uint64_t src, size_t bitLen)
{
if (bitLen == 0) return;
if (bitLen > unitBitSize) {
throw cybozu::Exception("BitVectorT:append:bad bitLen") << bitLen;
}
if (bitLen < unitBitSize) {
src &= GetMaskBit<T>(bitLen);
}
const size_t q = bitLen_ / unitBitSize;
const size_t r = bitLen_ % unitBitSize;
resize(bitLen_ + bitLen);
if (r == 0) {
v_[q] = T(src);
return;
}
v_[q] |= T(src << r);
if (r + bitLen > unitBitSize) {
v_[q + 1] = T(src >> (unitBitSize - r));
}
}
/*
append bitVector
*/
void append(const BitVectorT<T>& v)
{
append(v.getBlock(), v.size());
}
/*
dst[0, bitLen) = vec[pos, pos + bitLen)
*/
void extract(T* dst, size_t pos, size_t bitLen) const
{
if (bitLen == 0) return;
if (pos + bitLen > bitLen_) {
throw cybozu::Exception("BitVectorT:extract:bad range") << bitLen << pos << bitLen_;
}
const size_t q = pos / unitBitSize;
const size_t r = pos % unitBitSize;
if (r == 0) {
CopyBit<T>(dst, &v_[q], bitLen);
return;
}
bitvector_local::shiftRightBit<T>(dst, &v_[q], bitLen, r);
}
/*
dst = vec[pos, pos + bitLen)
*/
void extract(BitVectorT<T>& dst, size_t pos, size_t bitLen) const
{
dst.resize(bitLen);
extract(dst.getBlock(), pos, bitLen);
}
/*
return vec[pos, pos + bitLen)
*/
T extract(size_t pos, size_t bitLen) const
{
if (bitLen == 0) return 0;
if (bitLen > unitBitSize || pos + bitLen > bitLen_) {
throw cybozu::Exception("BitVectorT:extract:bad range") << bitLen << pos << bitLen_;
}
const size_t q = pos / unitBitSize;
const size_t r = pos % unitBitSize;
T v;
if (r == 0) {
v = v_[q];
} else if (q == v_.size() - 1) {
v = v_[q] >> r;
} else {
v = (v_[q] >> r) | v_[q + 1] << (unitBitSize - r);
}
if (bitLen < unitBitSize) {
v &= GetMaskBit<T>(bitLen);
}
return v;
}
bool operator==(const BitVectorT<T>& rhs) const { return v_ == rhs.v_; }
bool operator!=(const BitVectorT<T>& rhs) const { return v_ != rhs.v_; }
};
typedef BitVectorT<size_t> BitVector;
} // cybozu
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2016 Marcin Kościelnicki <koriakin@0x04.net>
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include "pgraph.h"
#include "pgraph_mthd.h"
#include "pgraph_class.h"
#include "nva.h"
namespace hwtest {
namespace pgraph {
std::vector<SingleMthdTest *> EmuCelsius::mthds() {
std::vector<SingleMthdTest *> res = {
new MthdNop(opt, rnd(), "nop", -1, cls, 0x100),
new MthdNotify(opt, rnd(), "notify", -1, cls, 0x104),
new MthdWarning(opt, rnd(), "warning", -1, cls, 0x108),
new MthdState(opt, rnd(), "state", -1, cls, 0x10c),
new MthdSync(opt, rnd(), "sync", -1, cls, 0x110),
new MthdPmTrigger(opt, rnd(), "pm_trigger", -1, cls, 0x140),
new MthdDmaNotify(opt, rnd(), "dma_notify", -1, cls, 0x180),
new UntestedMthd(opt, rnd(), "dma_tex_a", -1, cls, 0x184), // XXX
new UntestedMthd(opt, rnd(), "dma_tex_b", -1, cls, 0x188), // XXX
new UntestedMthd(opt, rnd(), "dma_vtx", -1, cls, 0x18c), // XXX
new UntestedMthd(opt, rnd(), "dma_state", -1, cls, 0x190), // XXX
new MthdDmaSurf(opt, rnd(), "dma_surf_color", -1, cls, 0x194, 2, SURF_NV10),
new MthdDmaSurf(opt, rnd(), "dma_surf_zeta", -1, cls, 0x198, 3, SURF_NV10),
new UntestedMthd(opt, rnd(), "clip_h", -1, cls, 0x200), // XXX
new UntestedMthd(opt, rnd(), "clip_v", -1, cls, 0x204), // XXX
new MthdSurf3DFormat(opt, rnd(), "surf_format", -1, cls, 0x208, true),
new MthdSurfPitch2(opt, rnd(), "surf_pitch_2", -1, cls, 0x20c, 2, 3, SURF_NV10),
new MthdSurfOffset(opt, rnd(), "color_offset", -1, cls, 0x210, 2, SURF_NV10),
new MthdSurfOffset(opt, rnd(), "zeta_offset", -1, cls, 0x214, 3, SURF_NV10),
new UntestedMthd(opt, rnd(), "meh", -1, cls, 0x218, 2), // XXX
new UntestedMthd(opt, rnd(), "meh", -1, cls, 0x220, 8), // XXX
new UntestedMthd(opt, rnd(), "meh", -1, cls, 0x240, 0x10), // XXX
new UntestedMthd(opt, rnd(), "meh", -1, cls, 0x280, 0x20), // XXX
new UntestedMthd(opt, rnd(), "meh", -1, cls, 0x300, 0x40), // XXX
new UntestedMthd(opt, rnd(), "meh", -1, cls, 0x400, 0x100), // XXX
new UntestedMthd(opt, rnd(), "meh", -1, cls, 0x800, 0x200), // XXX
new UntestedMthd(opt, rnd(), "meh", -1, cls, 0x1000, 0x400), // XXX
};
if (cls == 0x56) {
} else {
res.insert(res.end(), {
new UntestedMthd(opt, rnd(), "unk114", -1, cls, 0x114), // XXX
new MthdFlipSet(opt, rnd(), "flip_write", -1, cls, 0x120, 1, 1),
new MthdFlipSet(opt, rnd(), "flip_read", -1, cls, 0x124, 1, 0),
new MthdFlipSet(opt, rnd(), "flip_modulo", -1, cls, 0x128, 1, 2),
new MthdFlipBumpWrite(opt, rnd(), "flip_bump_write", -1, cls, 0x12c, 1),
new UntestedMthd(opt, rnd(), "flip_unk130", -1, cls, 0x130),
});
}
return res;
}
std::vector<SingleMthdTest *> Kelvin::mthds() {
std::vector<SingleMthdTest *> res = {
new MthdNop(opt, rnd(), "nop", -1, cls, 0x100),
new MthdNotify(opt, rnd(), "notify", -1, cls, 0x104),
new MthdWarning(opt, rnd(), "warning", -1, cls, 0x108),
new MthdState(opt, rnd(), "state", -1, cls, 0x10c),
new MthdSync(opt, rnd(), "sync", -1, cls, 0x110),
new MthdFlipSet(opt, rnd(), "flip_write", -1, cls, 0x120, 1, 1),
new MthdFlipSet(opt, rnd(), "flip_read", -1, cls, 0x124, 1, 0),
new MthdFlipSet(opt, rnd(), "flip_modulo", -1, cls, 0x128, 1, 2),
new MthdFlipBumpWrite(opt, rnd(), "flip_bump_write", -1, cls, 0x12c, 1),
new UntestedMthd(opt, rnd(), "flip_unk130", -1, cls, 0x130),
new MthdPmTrigger(opt, rnd(), "pm_trigger", -1, cls, 0x140),
new MthdDmaNotify(opt, rnd(), "dma_notify", -1, cls, 0x180),
new UntestedMthd(opt, rnd(), "dma_tex_a", -1, cls, 0x184), // XXX
new UntestedMthd(opt, rnd(), "dma_tex_b", -1, cls, 0x188), // XXX
new UntestedMthd(opt, rnd(), "dma_state", -1, cls, 0x190), // XXX
new MthdDmaSurf(opt, rnd(), "dma_surf_color", -1, cls, 0x194, 2, SURF_NV10),
new MthdDmaSurf(opt, rnd(), "dma_surf_zeta", -1, cls, 0x198, 3, SURF_NV10),
new UntestedMthd(opt, rnd(), "dma_vtx_a", -1, cls, 0x19c), // XXX
new UntestedMthd(opt, rnd(), "dma_vtx_b", -1, cls, 0x1a0), // XXX
new UntestedMthd(opt, rnd(), "dma_fence", -1, cls, 0x1a4), // XXX
new UntestedMthd(opt, rnd(), "dma_query", -1, cls, 0x1a8), // XXX
new UntestedMthd(opt, rnd(), "clip_h", -1, cls, 0x200), // XXX
new UntestedMthd(opt, rnd(), "clip_v", -1, cls, 0x204), // XXX
new MthdSurf3DFormat(opt, rnd(), "surf_format", -1, cls, 0x208, true),
new MthdSurfPitch2(opt, rnd(), "surf_pitch_2", -1, cls, 0x20c, 2, 3, SURF_NV10),
new MthdSurfOffset(opt, rnd(), "color_offset", -1, cls, 0x210, 2, SURF_NV10),
new MthdSurfOffset(opt, rnd(), "zeta_offset", -1, cls, 0x214, 3, SURF_NV10),
new UntestedMthd(opt, rnd(), "meh", -1, cls, 0x218, 2), // XXX
new UntestedMthd(opt, rnd(), "meh", -1, cls, 0x220, 8), // XXX
new UntestedMthd(opt, rnd(), "meh", -1, cls, 0x240, 0x10), // XXX
new UntestedMthd(opt, rnd(), "meh", -1, cls, 0x280, 0x20), // XXX
new UntestedMthd(opt, rnd(), "meh", -1, cls, 0x300, 0x40), // XXX
new UntestedMthd(opt, rnd(), "meh", -1, cls, 0x400, 0x100), // XXX
new UntestedMthd(opt, rnd(), "meh", -1, cls, 0x800, 0x200), // XXX
new UntestedMthd(opt, rnd(), "meh", -1, cls, 0x1000, 0x400), // XXX
};
if (cls == 0x597) {
res.insert(res.end(), {
new UntestedMthd(opt, rnd(), "dma_clipid", -1, cls, 0x1ac),
new UntestedMthd(opt, rnd(), "dma_zcull", -1, cls, 0x1b0),
});
}
return res;
}
}
}
<commit_msg>hwtest/pgraph: Bring back trapbits to EmuCelsius.<commit_after>/*
* Copyright (C) 2016 Marcin Kościelnicki <koriakin@0x04.net>
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include "pgraph.h"
#include "pgraph_mthd.h"
#include "pgraph_class.h"
#include "nva.h"
namespace hwtest {
namespace pgraph {
std::vector<SingleMthdTest *> EmuCelsius::mthds() {
std::vector<SingleMthdTest *> res = {
new MthdNop(opt, rnd(), "nop", -1, cls, 0x100),
new MthdNotify(opt, rnd(), "notify", 0, cls, 0x104),
new MthdWarning(opt, rnd(), "warning", 2, cls, 0x108),
new MthdState(opt, rnd(), "state", -1, cls, 0x10c),
new MthdSync(opt, rnd(), "sync", 1, cls, 0x110),
new MthdPmTrigger(opt, rnd(), "pm_trigger", -1, cls, 0x140),
new MthdDmaNotify(opt, rnd(), "dma_notify", 3, cls, 0x180),
new UntestedMthd(opt, rnd(), "dma_tex_a", 4, cls, 0x184), // XXX
new UntestedMthd(opt, rnd(), "dma_tex_b", 5, cls, 0x188), // XXX
new UntestedMthd(opt, rnd(), "dma_vtx", 6, cls, 0x18c), // XXX
new UntestedMthd(opt, rnd(), "dma_state", 7, cls, 0x190), // XXX
new MthdDmaSurf(opt, rnd(), "dma_surf_color", 8, cls, 0x194, 2, SURF_NV10),
new MthdDmaSurf(opt, rnd(), "dma_surf_zeta", 9, cls, 0x198, 3, SURF_NV10),
new UntestedMthd(opt, rnd(), "clip_h", 10, cls, 0x200), // XXX
new UntestedMthd(opt, rnd(), "clip_v", 10, cls, 0x204), // XXX
new MthdSurf3DFormat(opt, rnd(), "surf_format", 11, cls, 0x208, true),
new MthdSurfPitch2(opt, rnd(), "surf_pitch_2", 12, cls, 0x20c, 2, 3, SURF_NV10),
new MthdSurfOffset(opt, rnd(), "color_offset", 13, cls, 0x210, 2, SURF_NV10),
new MthdSurfOffset(opt, rnd(), "zeta_offset", 14, cls, 0x214, 3, SURF_NV10),
new UntestedMthd(opt, rnd(), "meh", -1, cls, 0x218, 2), // XXX
new UntestedMthd(opt, rnd(), "meh", -1, cls, 0x220, 8), // XXX
new UntestedMthd(opt, rnd(), "meh", -1, cls, 0x240, 0x10), // XXX
new UntestedMthd(opt, rnd(), "meh", -1, cls, 0x280, 0x20), // XXX
new UntestedMthd(opt, rnd(), "meh", -1, cls, 0x300, 0x40), // XXX
new UntestedMthd(opt, rnd(), "meh", -1, cls, 0x400, 0x100), // XXX
new UntestedMthd(opt, rnd(), "meh", -1, cls, 0x800, 0x200), // XXX
new UntestedMthd(opt, rnd(), "meh", -1, cls, 0x1000, 0x400), // XXX
};
if (cls == 0x56) {
} else {
res.insert(res.end(), {
new UntestedMthd(opt, rnd(), "unk114", -1, cls, 0x114), // XXX
new MthdFlipSet(opt, rnd(), "flip_write", -1, cls, 0x120, 1, 1),
new MthdFlipSet(opt, rnd(), "flip_read", -1, cls, 0x124, 1, 0),
new MthdFlipSet(opt, rnd(), "flip_modulo", -1, cls, 0x128, 1, 2),
new MthdFlipBumpWrite(opt, rnd(), "flip_bump_write", -1, cls, 0x12c, 1),
new UntestedMthd(opt, rnd(), "flip_unk130", -1, cls, 0x130),
});
}
return res;
}
std::vector<SingleMthdTest *> Kelvin::mthds() {
std::vector<SingleMthdTest *> res = {
new MthdNop(opt, rnd(), "nop", -1, cls, 0x100),
new MthdNotify(opt, rnd(), "notify", -1, cls, 0x104),
new MthdWarning(opt, rnd(), "warning", -1, cls, 0x108),
new MthdState(opt, rnd(), "state", -1, cls, 0x10c),
new MthdSync(opt, rnd(), "sync", -1, cls, 0x110),
new MthdFlipSet(opt, rnd(), "flip_write", -1, cls, 0x120, 1, 1),
new MthdFlipSet(opt, rnd(), "flip_read", -1, cls, 0x124, 1, 0),
new MthdFlipSet(opt, rnd(), "flip_modulo", -1, cls, 0x128, 1, 2),
new MthdFlipBumpWrite(opt, rnd(), "flip_bump_write", -1, cls, 0x12c, 1),
new UntestedMthd(opt, rnd(), "flip_unk130", -1, cls, 0x130),
new MthdPmTrigger(opt, rnd(), "pm_trigger", -1, cls, 0x140),
new MthdDmaNotify(opt, rnd(), "dma_notify", -1, cls, 0x180),
new UntestedMthd(opt, rnd(), "dma_tex_a", -1, cls, 0x184), // XXX
new UntestedMthd(opt, rnd(), "dma_tex_b", -1, cls, 0x188), // XXX
new UntestedMthd(opt, rnd(), "dma_state", -1, cls, 0x190), // XXX
new MthdDmaSurf(opt, rnd(), "dma_surf_color", -1, cls, 0x194, 2, SURF_NV10),
new MthdDmaSurf(opt, rnd(), "dma_surf_zeta", -1, cls, 0x198, 3, SURF_NV10),
new UntestedMthd(opt, rnd(), "dma_vtx_a", -1, cls, 0x19c), // XXX
new UntestedMthd(opt, rnd(), "dma_vtx_b", -1, cls, 0x1a0), // XXX
new UntestedMthd(opt, rnd(), "dma_fence", -1, cls, 0x1a4), // XXX
new UntestedMthd(opt, rnd(), "dma_query", -1, cls, 0x1a8), // XXX
new UntestedMthd(opt, rnd(), "clip_h", -1, cls, 0x200), // XXX
new UntestedMthd(opt, rnd(), "clip_v", -1, cls, 0x204), // XXX
new MthdSurf3DFormat(opt, rnd(), "surf_format", -1, cls, 0x208, true),
new MthdSurfPitch2(opt, rnd(), "surf_pitch_2", -1, cls, 0x20c, 2, 3, SURF_NV10),
new MthdSurfOffset(opt, rnd(), "color_offset", -1, cls, 0x210, 2, SURF_NV10),
new MthdSurfOffset(opt, rnd(), "zeta_offset", -1, cls, 0x214, 3, SURF_NV10),
new UntestedMthd(opt, rnd(), "meh", -1, cls, 0x218, 2), // XXX
new UntestedMthd(opt, rnd(), "meh", -1, cls, 0x220, 8), // XXX
new UntestedMthd(opt, rnd(), "meh", -1, cls, 0x240, 0x10), // XXX
new UntestedMthd(opt, rnd(), "meh", -1, cls, 0x280, 0x20), // XXX
new UntestedMthd(opt, rnd(), "meh", -1, cls, 0x300, 0x40), // XXX
new UntestedMthd(opt, rnd(), "meh", -1, cls, 0x400, 0x100), // XXX
new UntestedMthd(opt, rnd(), "meh", -1, cls, 0x800, 0x200), // XXX
new UntestedMthd(opt, rnd(), "meh", -1, cls, 0x1000, 0x400), // XXX
};
if (cls == 0x597) {
res.insert(res.end(), {
new UntestedMthd(opt, rnd(), "dma_clipid", -1, cls, 0x1ac),
new UntestedMthd(opt, rnd(), "dma_zcull", -1, cls, 0x1b0),
});
}
return res;
}
}
}
<|endoftext|>
|
<commit_before>/**
* Copyright (C) 2018 3D Repo Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "boost/filesystem.hpp"
#include "OdPlatformSettings.h"
#include "vectorise_device_rvt.h"
#include "vectorise_view_rvt.h"
#include "helper_functions.h"
using namespace repo::manipulator::modelconvertor::odaHelper;
const char* RVT_TEXTURES_ENV_VARIABLE = "RVT_TEXTURES";
std::string getElementName(OdBmElementPtr element, uint64_t id)
{
std::string elName(convertToStdString(element->getElementName()));
if (!elName.empty())
elName.append("_");
elName.append(std::to_string(id));
return elName;
}
bool isFileExist(const std::string& inputPath)
{
if (boost::filesystem::exists(inputPath))
if (boost::filesystem::is_regular_file(inputPath))
return true;
return false;
}
std::string extractValidTexturePath(const std::string& inputPath)
{
std::string outputFilePath = inputPath;
//..try to extract one valid paths if multiple paths are provided
outputFilePath = outputFilePath.substr(0, outputFilePath.find("|", 0));
if (isFileExist(outputFilePath))
return outputFilePath;
//..try to apply absolute path
char* env = std::getenv(RVT_TEXTURES_ENV_VARIABLE);
if (env == nullptr)
return std::string();
auto absolutePath = boost::filesystem::absolute(outputFilePath, env);
outputFilePath = absolutePath.generic_string();
if (isFileExist(outputFilePath))
return outputFilePath;
return std::string();
}
std::string variantToString(const OdTfVariant& val, OdBmLabelUtilsPEPtr labelUtils, OdBmParamDefPtr paramDef, OdBmDatabase* database, OdBm::BuiltInParameterDefinition::Enum param)
{
std::string strOut;
switch (val.type()) {
case OdTfVariant::kString:
strOut = convertToStdString(val.getString());
break;
case OdTfVariant::kBool:
strOut = std::to_string(val.getBool());
break;
case OdTfVariant::kInt8:
strOut = std::to_string(val.getInt8());
break;
case OdTfVariant::kInt16:
strOut = std::to_string(val.getInt16());
break;
case OdTfVariant::kInt32:
if (paramDef->getParameterType() == OdBm::ParameterType::YesNo)
(val.getInt32()) ? strOut = "Yes" : strOut = "No";
else
strOut = std::to_string(val.getInt32());
break;
case OdTfVariant::kInt64:
strOut = std::to_string(val.getInt64());
break;
case OdTfVariant::kDouble:
strOut = convertToStdString(labelUtils->format(*database->getUnits(), paramDef->getUnitType(), val.getDouble(), false));
break;
case OdTfVariant::kDbStubPtr:
OdDbStub* stub = val.getDbStubPtr();
if (stub)
{
OdBmObjectId rawValue = OdBmObjectId(stub);
if (param == OdBm::BuiltInParameter::ELEM_CATEGORY_PARAM || param == OdBm::BuiltInParameter::ELEM_CATEGORY_PARAM_MT)
{
OdDbHandle hdl = rawValue.getHandle();
if (OdBmObjectId::isRegularHandle(hdl))
{
strOut = std::to_string((OdUInt64)hdl);
}
else
{
OdBm::BuiltInCategory::Enum builtInValue = static_cast<OdBm::BuiltInCategory::Enum>((OdUInt64)rawValue.getHandle());
strOut = convertToStdString(OdBm::BuiltInCategory(builtInValue).toString());
}
}
else
{
OdBmElementPtr elem = database->getObjectId(rawValue.getHandle()).safeOpenObject();
strOut = (elem->getElementName() == OdString::kEmpty) ? std::to_string((OdUInt64)rawValue.getHandle()) : convertToStdString(elem->getElementName());
}
}
}
return strOut;
}
OdGsViewPtr VectorizeView::createObject(GeometryCollector* geoColl)
{
auto ptr = OdRxObjectImpl<VectorizeView, OdGsView>::createObject();
static_cast<VectorizeView*>(ptr.get())->collector = geoColl;
return ptr;
}
VectorizeView::VectorizeView()
{
meshesCount = 0;
}
void VectorizeView::draw(const OdGiDrawable* pDrawable)
{
fillMeshData(pDrawable);
OdGsBaseMaterialView::draw(pDrawable);
}
VectoriseDeviceRvt* VectorizeView::device()
{
return (VectoriseDeviceRvt*)OdGsBaseVectorizeView::device();
}
void VectorizeView::OnFillMaterialCache(
OdGiMaterialItemPtr prevCache,
OdDbStub* materialId,
const OdGiMaterialTraitsData & materialData,
const MaterialColors& matColors,
repo_material_t& material)
{
bool missingTexture = false;
fillMaterial(matColors, material);
fillTexture(materialId, material, missingTexture);
collector->setCurrentMaterial(material, missingTexture);
collector->stopMeshEntry();
collector->startMeshEntry();
}
void VectorizeView::OnTriangleOut(const std::vector<repo::lib::RepoVector3D64>& vertices)
{
const int numVertices = 3;
if (vertices.size() != numVertices)
return;
OdGiMapperItemEntry::MapInputTriangle trg;
for (int i = 0; i < vertices.size(); ++i)
{
trg.inPt[i].x = vertices[i].x;
trg.inPt[i].y = vertices[i].y;
trg.inPt[i].z = vertices[i].z;
}
OdGiMapperItemEntry::MapOutputCoords outTex;
auto currentMap = currentMapper();
if (!currentMap.isNull())
{
auto diffuseMap = currentMap->diffuseMapper();
if (!diffuseMap.isNull())
diffuseMap->mapCoords(trg, outTex);
}
std::vector<repo::lib::RepoVector2D> uvc;
for (int i = 0; i < numVertices; ++i)
uvc.push_back({ (float)outTex.outCoord[i].x, (float)outTex.outCoord[i].y });
collector->addFace(vertices, uvc);
}
std::string VectorizeView::getLevel(OdBmElementPtr element, const std::string& name)
{
auto levelId = element->getAssocLevelId();
if (levelId.isValid())
{
auto levelObject = levelId.safeOpenObject();
if (!levelObject.isNull())
{
OdBmLevelPtr lptr = OdBmLevel::cast(levelObject);
if (!lptr.isNull())
return std::string(convertToStdString(lptr->getElementName()));
}
}
auto owner = element->getOwningElementId();
if (owner.isValid())
{
auto object = owner.openObject();
if (!object.isNull())
{
auto parentElement = OdBmElement::cast(object);
if (!parentElement.isNull())
return getLevel(parentElement, name);
}
}
return name;
}
void VectorizeView::fillMeshData(const OdGiDrawable* pDrawable)
{
OdBmElementPtr element = OdBmElement::cast(pDrawable);
if (element.isNull())
return;
if (!element->isDBRO())
return;
std::string elementName = getElementName(element, meshesCount);
collector->setNextMeshName(elementName);
collector->setMeshGroup(elementName);
try
{
collector->setCurrentMeta(fillMetadata(element));
}
catch(OdError& er)
{
//..Hotfix: handle nullPtr exception (need to check updated library)
}
meshesCount++;
std::string layerName = getLevel(element, "Layer Default");
collector->setLayer(layerName);
}
std::pair<std::vector<std::string>, std::vector<std::string>> VectorizeView::fillMetadata(OdBmElementPtr element)
{
std::pair<std::vector<std::string>, std::vector<std::string>> metadata;
OdBuiltInParamArray aParams;
element->getListParams(aParams);
OdBmLabelUtilsPEPtr labelUtils = OdBmObject::desc()->getX(OdBmLabelUtilsPE::desc());
if (labelUtils.isNull())
return metadata;
for (OdBuiltInParamArray::iterator it = aParams.begin(); it != aParams.end(); it++)
{
std::string builtInName = convertToStdString(OdBm::BuiltInParameter(*it).toString());
//..Hotfix: handle access violation exception (need to check updated library)
if (builtInName == std::string("ROOF_SLOPE"))
continue;
std::string paramName;
if (!labelUtils->getLabelFor(*it).isEmpty())
paramName = convertToStdString(labelUtils->getLabelFor(*it));
else
paramName = builtInName;
OdTfVariant value;
OdResult res = element->getParam(*it, value);
if (res == eOk)
{
OdBmParamElemPtr pParamElem = element->database()->getObjectId(*it).safeOpenObject();
OdBmParamDefPtr pDescParam = pParamElem->getParamDef();
std::string variantValue = variantToString(value, labelUtils, pDescParam, element->getDatabase(), *it);
if (!variantValue.empty())
{
metadata.first.push_back(convertToStdString(pDescParam->getCaption()));
metadata.second.push_back(variantValue);
}
}
}
return metadata;
}
void VectorizeView::fillMaterial(const MaterialColors& matColors, repo_material_t& material)
{
const float norm = 255.f;
material.diffuse = { ODGETRED(matColors.colorDiffuse) / norm, ODGETGREEN(matColors.colorDiffuse) / norm, ODGETBLUE(matColors.colorDiffuse) / norm, 1.0f };
material.specular = { ODGETRED(matColors.colorSpecular) / norm, ODGETGREEN(matColors.colorSpecular) / norm, ODGETBLUE(matColors.colorSpecular) / norm, 1.0f };
material.ambient = { ODGETRED(matColors.colorAmbient) / norm, ODGETGREEN(matColors.colorAmbient) / norm, ODGETBLUE(matColors.colorAmbient) / norm, 1.0f };
material.emissive = { ODGETRED(matColors.colorEmissive) / norm, ODGETGREEN(matColors.colorEmissive) / norm, ODGETBLUE(matColors.colorEmissive) / norm, 1.0f };
}
void VectorizeView::fillTexture(OdDbStub* materialId, repo_material_t& material, bool& missingTexture)
{
missingTexture = false;
OdBmObjectId matId(materialId);
if (!matId.isValid())
return;
OdBmObjectPtr materialPtr = matId.safeOpenObject(OdBm::kForRead);
OdBmMaterialElemPtr materialElem = (OdBmMaterialElem*)(materialPtr.get());
OdBmMaterialPtr matPtr = materialElem->getMaterial();
OdBmAssetPtr textureAsset = matPtr->getAsset();
if (textureAsset.isNull())
return;
OdBmAssetPtr bitmapAsset;
OdString textureFileName;
OdResult es = OdBmAppearanceAssetHelper::getTextureAsset(textureAsset, bitmapAsset);
if ((es != OdResult::eOk) || (bitmapAsset.isNull()))
return;
OdBmUnifiedBitmapSchemaHelper textureHelper(bitmapAsset);
es = textureHelper.getTextureFileName(textureFileName);
if (es != OdResult::eOk)
return;
std::string textureName(convertToStdString(textureFileName));
std::string validTextureName = extractValidTexturePath(textureName);
if (validTextureName.empty() && !textureName.empty())
missingTexture = true;
material.texturePath = validTextureName;
}<commit_msg>ISSUE #291 - disable shininess and shininessStrength<commit_after>/**
* Copyright (C) 2018 3D Repo Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "boost/filesystem.hpp"
#include "OdPlatformSettings.h"
#include "vectorise_device_rvt.h"
#include "vectorise_view_rvt.h"
#include "helper_functions.h"
using namespace repo::manipulator::modelconvertor::odaHelper;
const char* RVT_TEXTURES_ENV_VARIABLE = "RVT_TEXTURES";
std::string getElementName(OdBmElementPtr element, uint64_t id)
{
std::string elName(convertToStdString(element->getElementName()));
if (!elName.empty())
elName.append("_");
elName.append(std::to_string(id));
return elName;
}
bool isFileExist(const std::string& inputPath)
{
if (boost::filesystem::exists(inputPath))
if (boost::filesystem::is_regular_file(inputPath))
return true;
return false;
}
std::string extractValidTexturePath(const std::string& inputPath)
{
std::string outputFilePath = inputPath;
//..try to extract one valid paths if multiple paths are provided
outputFilePath = outputFilePath.substr(0, outputFilePath.find("|", 0));
if (isFileExist(outputFilePath))
return outputFilePath;
//..try to apply absolute path
char* env = std::getenv(RVT_TEXTURES_ENV_VARIABLE);
if (env == nullptr)
return std::string();
auto absolutePath = boost::filesystem::absolute(outputFilePath, env);
outputFilePath = absolutePath.generic_string();
if (isFileExist(outputFilePath))
return outputFilePath;
return std::string();
}
std::string variantToString(const OdTfVariant& val, OdBmLabelUtilsPEPtr labelUtils, OdBmParamDefPtr paramDef, OdBmDatabase* database, OdBm::BuiltInParameterDefinition::Enum param)
{
std::string strOut;
switch (val.type()) {
case OdTfVariant::kString:
strOut = convertToStdString(val.getString());
break;
case OdTfVariant::kBool:
strOut = std::to_string(val.getBool());
break;
case OdTfVariant::kInt8:
strOut = std::to_string(val.getInt8());
break;
case OdTfVariant::kInt16:
strOut = std::to_string(val.getInt16());
break;
case OdTfVariant::kInt32:
if (paramDef->getParameterType() == OdBm::ParameterType::YesNo)
(val.getInt32()) ? strOut = "Yes" : strOut = "No";
else
strOut = std::to_string(val.getInt32());
break;
case OdTfVariant::kInt64:
strOut = std::to_string(val.getInt64());
break;
case OdTfVariant::kDouble:
strOut = convertToStdString(labelUtils->format(*database->getUnits(), paramDef->getUnitType(), val.getDouble(), false));
break;
case OdTfVariant::kDbStubPtr:
OdDbStub* stub = val.getDbStubPtr();
if (stub)
{
OdBmObjectId rawValue = OdBmObjectId(stub);
if (param == OdBm::BuiltInParameter::ELEM_CATEGORY_PARAM || param == OdBm::BuiltInParameter::ELEM_CATEGORY_PARAM_MT)
{
OdDbHandle hdl = rawValue.getHandle();
if (OdBmObjectId::isRegularHandle(hdl))
{
strOut = std::to_string((OdUInt64)hdl);
}
else
{
OdBm::BuiltInCategory::Enum builtInValue = static_cast<OdBm::BuiltInCategory::Enum>((OdUInt64)rawValue.getHandle());
strOut = convertToStdString(OdBm::BuiltInCategory(builtInValue).toString());
}
}
else
{
OdBmElementPtr elem = database->getObjectId(rawValue.getHandle()).safeOpenObject();
strOut = (elem->getElementName() == OdString::kEmpty) ? std::to_string((OdUInt64)rawValue.getHandle()) : convertToStdString(elem->getElementName());
}
}
}
return strOut;
}
OdGsViewPtr VectorizeView::createObject(GeometryCollector* geoColl)
{
auto ptr = OdRxObjectImpl<VectorizeView, OdGsView>::createObject();
static_cast<VectorizeView*>(ptr.get())->collector = geoColl;
return ptr;
}
VectorizeView::VectorizeView()
{
meshesCount = 0;
}
void VectorizeView::draw(const OdGiDrawable* pDrawable)
{
fillMeshData(pDrawable);
OdGsBaseMaterialView::draw(pDrawable);
}
VectoriseDeviceRvt* VectorizeView::device()
{
return (VectoriseDeviceRvt*)OdGsBaseVectorizeView::device();
}
void VectorizeView::OnFillMaterialCache(
OdGiMaterialItemPtr prevCache,
OdDbStub* materialId,
const OdGiMaterialTraitsData & materialData,
const MaterialColors& matColors,
repo_material_t& material)
{
bool missingTexture = false;
fillMaterial(matColors, material);
fillTexture(materialId, material, missingTexture);
collector->setCurrentMaterial(material, missingTexture);
collector->stopMeshEntry();
collector->startMeshEntry();
}
void VectorizeView::OnTriangleOut(const std::vector<repo::lib::RepoVector3D64>& vertices)
{
const int numVertices = 3;
if (vertices.size() != numVertices)
return;
OdGiMapperItemEntry::MapInputTriangle trg;
for (int i = 0; i < vertices.size(); ++i)
{
trg.inPt[i].x = vertices[i].x;
trg.inPt[i].y = vertices[i].y;
trg.inPt[i].z = vertices[i].z;
}
OdGiMapperItemEntry::MapOutputCoords outTex;
auto currentMap = currentMapper();
if (!currentMap.isNull())
{
auto diffuseMap = currentMap->diffuseMapper();
if (!diffuseMap.isNull())
diffuseMap->mapCoords(trg, outTex);
}
std::vector<repo::lib::RepoVector2D> uvc;
for (int i = 0; i < numVertices; ++i)
uvc.push_back({ (float)outTex.outCoord[i].x, (float)outTex.outCoord[i].y });
collector->addFace(vertices, uvc);
}
std::string VectorizeView::getLevel(OdBmElementPtr element, const std::string& name)
{
auto levelId = element->getAssocLevelId();
if (levelId.isValid())
{
auto levelObject = levelId.safeOpenObject();
if (!levelObject.isNull())
{
OdBmLevelPtr lptr = OdBmLevel::cast(levelObject);
if (!lptr.isNull())
return std::string(convertToStdString(lptr->getElementName()));
}
}
auto owner = element->getOwningElementId();
if (owner.isValid())
{
auto object = owner.openObject();
if (!object.isNull())
{
auto parentElement = OdBmElement::cast(object);
if (!parentElement.isNull())
return getLevel(parentElement, name);
}
}
return name;
}
void VectorizeView::fillMeshData(const OdGiDrawable* pDrawable)
{
OdBmElementPtr element = OdBmElement::cast(pDrawable);
if (element.isNull())
return;
if (!element->isDBRO())
return;
std::string elementName = getElementName(element, meshesCount);
collector->setNextMeshName(elementName);
collector->setMeshGroup(elementName);
try
{
collector->setCurrentMeta(fillMetadata(element));
}
catch(OdError& er)
{
//..Hotfix: handle nullPtr exception (need to check updated library)
}
meshesCount++;
std::string layerName = getLevel(element, "Layer Default");
collector->setLayer(layerName);
}
std::pair<std::vector<std::string>, std::vector<std::string>> VectorizeView::fillMetadata(OdBmElementPtr element)
{
std::pair<std::vector<std::string>, std::vector<std::string>> metadata;
OdBuiltInParamArray aParams;
element->getListParams(aParams);
OdBmLabelUtilsPEPtr labelUtils = OdBmObject::desc()->getX(OdBmLabelUtilsPE::desc());
if (labelUtils.isNull())
return metadata;
for (OdBuiltInParamArray::iterator it = aParams.begin(); it != aParams.end(); it++)
{
std::string builtInName = convertToStdString(OdBm::BuiltInParameter(*it).toString());
//..Hotfix: handle access violation exception (need to check updated library)
if (builtInName == std::string("ROOF_SLOPE"))
continue;
std::string paramName;
if (!labelUtils->getLabelFor(*it).isEmpty())
paramName = convertToStdString(labelUtils->getLabelFor(*it));
else
paramName = builtInName;
OdTfVariant value;
OdResult res = element->getParam(*it, value);
if (res == eOk)
{
OdBmParamElemPtr pParamElem = element->database()->getObjectId(*it).safeOpenObject();
OdBmParamDefPtr pDescParam = pParamElem->getParamDef();
std::string variantValue = variantToString(value, labelUtils, pDescParam, element->getDatabase(), *it);
if (!variantValue.empty())
{
metadata.first.push_back(convertToStdString(pDescParam->getCaption()));
metadata.second.push_back(variantValue);
}
}
}
return metadata;
}
void VectorizeView::fillMaterial(const MaterialColors& matColors, repo_material_t& material)
{
const float norm = 255.f;
material.shininess = 0.f;
material.shininessStrength = 0.f;
material.diffuse = { ODGETRED(matColors.colorDiffuse) / norm, ODGETGREEN(matColors.colorDiffuse) / norm, ODGETBLUE(matColors.colorDiffuse) / norm, 1.0f };
material.specular = { ODGETRED(matColors.colorSpecular) / norm, ODGETGREEN(matColors.colorSpecular) / norm, ODGETBLUE(matColors.colorSpecular) / norm, 1.0f };
material.ambient = { ODGETRED(matColors.colorAmbient) / norm, ODGETGREEN(matColors.colorAmbient) / norm, ODGETBLUE(matColors.colorAmbient) / norm, 1.0f };
material.emissive = { ODGETRED(matColors.colorEmissive) / norm, ODGETGREEN(matColors.colorEmissive) / norm, ODGETBLUE(matColors.colorEmissive) / norm, 1.0f };
}
void VectorizeView::fillTexture(OdDbStub* materialId, repo_material_t& material, bool& missingTexture)
{
missingTexture = false;
OdBmObjectId matId(materialId);
if (!matId.isValid())
return;
OdBmObjectPtr materialPtr = matId.safeOpenObject(OdBm::kForRead);
OdBmMaterialElemPtr materialElem = (OdBmMaterialElem*)(materialPtr.get());
OdBmMaterialPtr matPtr = materialElem->getMaterial();
OdBmAssetPtr textureAsset = matPtr->getAsset();
if (textureAsset.isNull())
return;
OdBmAssetPtr bitmapAsset;
OdString textureFileName;
OdResult es = OdBmAppearanceAssetHelper::getTextureAsset(textureAsset, bitmapAsset);
if ((es != OdResult::eOk) || (bitmapAsset.isNull()))
return;
OdBmUnifiedBitmapSchemaHelper textureHelper(bitmapAsset);
es = textureHelper.getTextureFileName(textureFileName);
if (es != OdResult::eOk)
return;
std::string textureName(convertToStdString(textureFileName));
std::string validTextureName = extractValidTexturePath(textureName);
if (validTextureName.empty() && !textureName.empty())
missingTexture = true;
material.texturePath = validTextureName;
}<|endoftext|>
|
<commit_before>// Copyright (c) 2017 The Khronos Group Inc.
// Copyright (c) 2017 Valve Corporation
// Copyright (c) 2017 LunarG, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: Mark Young <marky@lunarg.com>
//
#pragma once
#include "xr_dependencies.h"
#if defined(XR_OS_LINUX)
#include <unistd.h>
#include <fcntl.h>
#include <iostream>
#endif
// Structure used to track the global runtime file information
struct GlobalRuntimeFile {
bool valid;
bool locked;
std::string file_name;
std::string runtime_name;
#if defined(XR_OS_LINUX)
int32_t file_descriptor;
#elif defined(XR_OS_APPLE)
// TBD
#elif defined(XR_OS_WINDOWS)
HANDLE file_handle;
#else
// TBD
#endif
};
// This is a CMake generated file with #defines for any functions/includes
// that it found present. This is currently necessary to properly determine
// if secure_getenv or __secure_getenv are present
#if !defined(OPENXR_NON_CMAKE_BUILD)
#include "common_cmake_config.h"
#endif // !defined(OPENXR_NON_CMAKE_BUILD)
// Environment variables
#if defined(XR_OS_LINUX)
static inline char* PlatformUtilsGetEnv(const char* name) { return getenv(name); }
static inline char* PlatformUtilsGetSecureEnv(const char* name) {
#ifdef HAVE_SECURE_GETENV
return secure_getenv(name);
#elif defined(HAVE___SECURE_GETENV)
return __secure_getenv(name);
#else
#pragma message( \
"Warning: Falling back to non-secure getenv for environmental" \
"lookups! Consider updating to a different libc.")
return PlatformUtilsGetEnv(name);
#endif
}
static inline void PlatformUtilsFreeEnv(char* val) {
// No freeing of memory necessary for Linux, but we should at least touch
// the val and inst pointers to get rid of compiler warnings.
(void)val;
}
// Prefix for the Linux/Apple global runtime JSON file name
static const std::string rt_dir_prefix = "/usr/local/share/openxr/";
static const std::string rt_filename = "/active_runtime.json";
static inline bool PlatformGetGlobalRuntimeFileName(uint16_t major_version, std::string& file_name) {
file_name = rt_dir_prefix;
file_name += std::to_string(major_version);
file_name += rt_filename;
return true;
}
static inline bool PlatformLockGlobalRuntimeFile(uint16_t major_version, GlobalRuntimeFile& global_rt_file) {
bool success = false;
try {
global_rt_file = {};
// Get the filename
if (PlatformGetGlobalRuntimeFileName(major_version, global_rt_file.file_name)) {
// Initialize the global runtime file info
// Open a file descriptor to the file.
global_rt_file.file_descriptor = open(global_rt_file.file_name.c_str(), O_RDWR);
if (0 <= global_rt_file.file_descriptor) {
flock fcntl_lock = {};
global_rt_file.valid = true;
// Test to see if a lock's already present
fcntl_lock.l_type = F_WRLCK;
fcntl_lock.l_whence = SEEK_SET;
fcntl_lock.l_start = 0;
fcntl_lock.l_len = 0;
if (-1 == fcntl(global_rt_file.file_descriptor, F_OFD_GETLK, &fcntl_lock)) {
std::string error_msg = "fcntl(querylock | ";
error_msg += global_rt_file.file_name;
error_msg += ", FD: ";
error_msg += std::to_string(global_rt_file.file_descriptor);
error_msg += ", ErrorNo: ";
error_msg += std::to_string(errno);
error_msg += ")";
perror(error_msg.c_str());
} else if (fcntl_lock.l_type == F_RDLCK || fcntl_lock.l_type == F_WRLCK) {
std::cerr << "Process " << std::to_string(fcntl_lock.l_pid) << " has a lock on " << global_rt_file.file_name
<< " already!" << std::endl;
} else {
// Lock the entire file for writing
fcntl_lock.l_type = F_WRLCK;
fcntl_lock.l_whence = SEEK_SET;
fcntl_lock.l_start = 0;
fcntl_lock.l_len = 0;
if (-1 == fcntl(global_rt_file.file_descriptor, F_OFD_SETLK, &fcntl_lock)) {
std::string error_msg = "fcntl(lock | ";
error_msg += global_rt_file.file_name;
error_msg += ", FD: ";
error_msg += std::to_string(global_rt_file.file_descriptor);
error_msg += ", ErrorNo: ";
error_msg += std::to_string(errno);
error_msg += ")";
perror(error_msg.c_str());
} else {
global_rt_file.locked = true;
success = true;
}
}
// Get the name of the runtime from the JSON (just crudely)
if (success) {
char buffer[4096];
std::string contents = "";
while (read(global_rt_file.file_descriptor, &buffer, 4095) > 0) {
contents += buffer;
}
std::size_t name_index = contents.find("\"name\"");
if (std::string::npos != name_index) {
std::size_t begin_quote_index = contents.find("\"", name_index + 6);
std::size_t end_quote_index = contents.find("\"", begin_quote_index + 1);
if (std::string::npos != begin_quote_index && std::string::npos != end_quote_index) {
global_rt_file.runtime_name =
contents.substr(begin_quote_index + 1, end_quote_index - begin_quote_index - 1);
}
}
}
} else {
std::string error_msg = "open(";
error_msg += global_rt_file.file_name;
error_msg += ")";
perror(error_msg.c_str());
}
}
} catch (...) {
}
// Cleanup on failure
if (!success) {
if (global_rt_file.valid) {
close(global_rt_file.file_descriptor);
global_rt_file.valid = false;
global_rt_file.file_name = "";
}
}
return success;
}
static inline bool PlatformUnlockGlobalRuntimeFile(GlobalRuntimeFile& global_rt_file) {
bool success = false;
try {
if (global_rt_file.valid && global_rt_file.locked) {
flock fcntl_lock = {};
// Unlock the entire file for writing
fcntl_lock.l_type = F_UNLCK;
fcntl_lock.l_whence = SEEK_SET;
fcntl_lock.l_start = 0;
fcntl_lock.l_len = 0;
if (-1 == fcntl(global_rt_file.file_descriptor, F_OFD_SETLK, &fcntl_lock)) {
std::string error_msg = "fcntl(unlock | ";
error_msg += global_rt_file.file_name;
error_msg += ", FD: ";
error_msg += std::to_string(global_rt_file.file_descriptor);
error_msg += ", ErrorNo: ";
error_msg += std::to_string(errno);
error_msg += ")";
perror(error_msg.c_str());
} else {
global_rt_file.locked = false;
success = true;
}
if (-1 == close(global_rt_file.file_descriptor)) {
std::string error_msg = "close(";
error_msg += global_rt_file.file_name;
error_msg += ", FD: ";
error_msg += std::to_string(global_rt_file.file_descriptor);
error_msg += ", ErrorNo: ";
error_msg += std::to_string(errno);
error_msg += ")";
perror(error_msg.c_str());
success = false;
} else {
global_rt_file.file_descriptor = -1;
global_rt_file.valid = false;
global_rt_file.file_name = "";
}
}
} catch (...) {
}
return success;
}
#elif defined(XR_OS_APPLE)
static inline char *PlatformUtilsGetEnv(const char *name) { return getenv(name); }
static inline char *PlatformUtilsGetSecureEnv(const char *name) {
#ifdef HAVE_SECURE_GETENV
return secure_getenv(name);
#elif defined(HAVE___SECURE_GETENV)
return __secure_getenv(name);
#else
#pragma message( \
"Warning: Falling back to non-secure getenv for environmental" \
"lookups! Consider updating to a different libc.")
return PlatformUtilsGetEnv(name);
#endif
}
static inline void PlatformUtilsFreeEnv(char *val) {
// No freeing of memory necessary for Linux, but we should at least touch
// the val and inst pointers to get rid of compiler warnings.
(void)val;
}
// Prefix for the Linux/Apple global runtime JSON file name
static const std::string rt_dir_prefix = "/usr/local/share/openxr/";
static const std::string rt_filename = "/active_runtime.json";
static inline bool PlatformGetGlobalRuntimeFileName(uint16_t major_version, std::string &file_name) {
file_name = rt_dir_prefix;
file_name += std::to_string(major_version);
file_name += rt_filename;
return true;
}
static inline bool PlatformLockGlobalRuntimeFile(uint16_t major_version, GlobalRuntimeFile &global_rt_file) {
// Stub func
(void)major_version;
(void)global_rt_file;
return false;
}
static inline bool PlatformUnlockGlobalRuntimeFile(GlobalRuntimeFile &global_rt_file) {
// Stub func
(void)global_rt_file;
return false;
}
#elif defined(XR_OS_WINDOWS)
static inline char *PlatformUtilsGetEnv(const char *name) {
char *retVal;
DWORD valSize;
valSize = GetEnvironmentVariableA(name, nullptr, 0);
// valSize DOES include the null terminator, so for any set variable
// will always be at least 1. If it's 0, the variable wasn't set.
if (valSize == 0) {
return nullptr;
}
// Allocate the space necessary for the registry entry
retVal = new char[valSize + 1];
GetEnvironmentVariableA(name, retVal, valSize);
return retVal;
}
static inline char *PlatformUtilsGetSecureEnv(const char *name) {
// No secure version for Windows as far as I know
return PlatformUtilsGetEnv(name);
}
static inline void PlatformUtilsFreeEnv(char *val) {
if (nullptr != val) {
delete[] val;
val = nullptr;
}
}
// Prefix for the Windows global runtime JSON file name
static const std::string rt_file_folder = "\\ProgramData\\Khronos\\OpenXR\\";
static const std::string rt_file_prefix = "\\openxr_runtime_";
static inline bool PlatformGetGlobalRuntimeFileName(uint16_t major_version, std::string &file_name) {
bool ret_value = false;
try {
char *sys_drive = PlatformUtilsGetSecureEnv("SystemDrive");
if (nullptr != sys_drive) {
file_name = sys_drive;
PlatformUtilsFreeEnv(sys_drive);
file_name += rt_file_folder;
if (sizeof(void *) == 8) {
file_name += "64";
} else {
file_name += "32";
}
file_name += rt_file_prefix;
file_name += std::to_string(major_version);
file_name += ".json";
ret_value = true;
}
} catch (...) {
}
return ret_value;
}
static inline bool PlatformLockGlobalRuntimeFile(uint16_t major_version, GlobalRuntimeFile &global_rt_file) {
bool ret_value = false;
std::string rt_filename;
if (PlatformGetGlobalRuntimeFileName(major_version, rt_filename)) {
HANDLE file_handle = CreateFileA(rt_filename.c_str(), (GENERIC_READ | GENERIC_WRITE), FILE_SHARE_READ, nullptr,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (file_handle != INVALID_HANDLE_VALUE) {
global_rt_file.valid = true;
global_rt_file.locked = true;
global_rt_file.file_handle = file_handle;
ret_value = true;
}
// Get the name of the runtime from the JSON (just crudely)
if (ret_value) {
char buffer[4096];
DWORD num_bytes_read = 0;
std::string contents = "";
while (FALSE != ReadFile(file_handle, buffer, 4095, &num_bytes_read, nullptr)) {
if (num_bytes_read == 0) {
break;
}
contents += buffer;
}
std::size_t name_index = contents.find("\"name\"");
if (std::string::npos != name_index) {
std::size_t begin_quote_index = contents.find("\"", name_index + 6);
std::size_t end_quote_index = contents.find("\"", begin_quote_index + 1);
if (std::string::npos != begin_quote_index && std::string::npos != end_quote_index) {
global_rt_file.runtime_name = contents.substr(begin_quote_index + 1, end_quote_index - begin_quote_index - 1);
}
}
}
}
return ret_value;
}
static inline bool PlatformUnlockGlobalRuntimeFile(GlobalRuntimeFile &global_rt_file) {
if (global_rt_file.valid && global_rt_file.locked && CloseHandle(global_rt_file.file_handle)) {
global_rt_file.valid = false;
global_rt_file.locked = false;
global_rt_file.file_handle = nullptr;
return true;
}
return false;
}
#else // Not Linux or Windows
static inline char *PlatformUtilsGetEnv(const char *name) {
// Stub func
(void)name;
return nullptr;
}
static inline char *PlatformUtilsGetSecureEnv(const char *name) {
// Stub func
(void)name;
return nullptr;
}
static inline void PlatformUtilsFreeEnv(char *val) {
// Stub func
(void)val;
}
static inline bool PlatformGetGlobalRuntimeFileName(uint16_t major_version, std::string &file_name) {
// Stub func
(void)major_version;
(void)file_name;
return false;
}
static inline bool PlatformLockGlobalRuntimeFile(uint16_t major_version, GlobalRuntimeFile &global_rt_file) {
// Stub func
(void)major_version;
(void)global_rt_file;
return false;
}
static inline bool PlatformUnlockGlobalRuntimeFile(GlobalRuntimeFile &global_rt_file) {
// Stub func
(void)global_rt_file;
return false;
}
#endif
<commit_msg>Remove dead code<commit_after>// Copyright (c) 2017 The Khronos Group Inc.
// Copyright (c) 2017 Valve Corporation
// Copyright (c) 2017 LunarG, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: Mark Young <marky@lunarg.com>
//
#pragma once
#include "xr_dependencies.h"
#if defined(XR_OS_LINUX)
#include <unistd.h>
#include <fcntl.h>
#include <iostream>
#endif
// This is a CMake generated file with #defines for any functions/includes
// that it found present. This is currently necessary to properly determine
// if secure_getenv or __secure_getenv are present
#if !defined(OPENXR_NON_CMAKE_BUILD)
#include "common_cmake_config.h"
#endif // !defined(OPENXR_NON_CMAKE_BUILD)
// Environment variables
#if defined(XR_OS_LINUX)
static inline char* PlatformUtilsGetEnv(const char* name) { return getenv(name); }
static inline char* PlatformUtilsGetSecureEnv(const char* name) {
#ifdef HAVE_SECURE_GETENV
return secure_getenv(name);
#elif defined(HAVE___SECURE_GETENV)
return __secure_getenv(name);
#else
#pragma message( \
"Warning: Falling back to non-secure getenv for environmental" \
"lookups! Consider updating to a different libc.")
return PlatformUtilsGetEnv(name);
#endif
}
static inline void PlatformUtilsFreeEnv(char* val) {
// No freeing of memory necessary for Linux, but we should at least touch
// the val and inst pointers to get rid of compiler warnings.
(void)val;
}
// Prefix for the Linux/Apple global runtime JSON file name
static const std::string rt_dir_prefix = "/usr/local/share/openxr/";
static const std::string rt_filename = "/active_runtime.json";
static inline bool PlatformGetGlobalRuntimeFileName(uint16_t major_version, std::string& file_name) {
file_name = rt_dir_prefix;
file_name += std::to_string(major_version);
file_name += rt_filename;
return true;
}
#elif defined(XR_OS_APPLE)
static inline char *PlatformUtilsGetEnv(const char *name) { return getenv(name); }
static inline char *PlatformUtilsGetSecureEnv(const char *name) {
#ifdef HAVE_SECURE_GETENV
return secure_getenv(name);
#elif defined(HAVE___SECURE_GETENV)
return __secure_getenv(name);
#else
#pragma message( \
"Warning: Falling back to non-secure getenv for environmental" \
"lookups! Consider updating to a different libc.")
return PlatformUtilsGetEnv(name);
#endif
}
static inline void PlatformUtilsFreeEnv(char *val) {
// No freeing of memory necessary for Linux, but we should at least touch
// the val and inst pointers to get rid of compiler warnings.
(void)val;
}
// Prefix for the Linux/Apple global runtime JSON file name
static const std::string rt_dir_prefix = "/usr/local/share/openxr/";
static const std::string rt_filename = "/active_runtime.json";
static inline bool PlatformGetGlobalRuntimeFileName(uint16_t major_version, std::string &file_name) {
file_name = rt_dir_prefix;
file_name += std::to_string(major_version);
file_name += rt_filename;
return true;
}
#elif defined(XR_OS_WINDOWS)
static inline char *PlatformUtilsGetEnv(const char *name) {
char *retVal;
DWORD valSize;
valSize = GetEnvironmentVariableA(name, nullptr, 0);
// valSize DOES include the null terminator, so for any set variable
// will always be at least 1. If it's 0, the variable wasn't set.
if (valSize == 0) {
return nullptr;
}
// Allocate the space necessary for the registry entry
retVal = new char[valSize + 1];
GetEnvironmentVariableA(name, retVal, valSize);
return retVal;
}
static inline char *PlatformUtilsGetSecureEnv(const char *name) {
// No secure version for Windows as far as I know
return PlatformUtilsGetEnv(name);
}
static inline void PlatformUtilsFreeEnv(char *val) {
if (nullptr != val) {
delete[] val;
val = nullptr;
}
}
// Prefix for the Windows global runtime JSON file name
static const std::string rt_file_folder = "\\ProgramData\\Khronos\\OpenXR\\";
static const std::string rt_file_prefix = "\\openxr_runtime_";
static inline bool PlatformGetGlobalRuntimeFileName(uint16_t major_version, std::string &file_name) {
bool ret_value = false;
try {
char *sys_drive = PlatformUtilsGetSecureEnv("SystemDrive");
if (nullptr != sys_drive) {
file_name = sys_drive;
PlatformUtilsFreeEnv(sys_drive);
file_name += rt_file_folder;
if (sizeof(void *) == 8) {
file_name += "64";
} else {
file_name += "32";
}
file_name += rt_file_prefix;
file_name += std::to_string(major_version);
file_name += ".json";
ret_value = true;
}
} catch (...) {
}
return ret_value;
}
#else // Not Linux or Windows
static inline char *PlatformUtilsGetEnv(const char *name) {
// Stub func
(void)name;
return nullptr;
}
static inline char *PlatformUtilsGetSecureEnv(const char *name) {
// Stub func
(void)name;
return nullptr;
}
static inline void PlatformUtilsFreeEnv(char *val) {
// Stub func
(void)val;
}
static inline bool PlatformGetGlobalRuntimeFileName(uint16_t major_version, std::string &file_name) {
// Stub func
(void)major_version;
(void)file_name;
return false;
}
#endif
<|endoftext|>
|
<commit_before>/* $Id$ */
/*
* Copyright (c) 2013 Roland van Rijswijk-Deij
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*****************************************************************************
silvia_keygen.cpp
Issuer key generation utility
*****************************************************************************/
#include "config.h"
#include "silvia_issuer_keygen.h"
#include "silvia_parameters.h"
#include "silvia_macros.h"
#include <string>
#include <unistd.h>
// Default modulus size for new keys
#define DEFAULT_BITSIZE 2048
void version(void)
{
printf("The Simple Library for Verifying and Issuing Attributes (silvia)\n");
printf("\n");
printf("Issuer key generation utility version %s\n", VERSION);
printf("\n");
printf("Copyright (c) 2013 Roland van Rijswijk-Deij\n\n");
printf("Use, modification and redistribution of this software is subject to the terms\n");
printf("of the license agreement. This software is licensed under a 2-clause BSD-style\n");
printf("license a copy of which is included as the file LICENSE in the distribution.\n");
}
void usage(void)
{
printf("Silvia issuer key generation utility %s\n\n", VERSION);
printf("Usage:\n");
printf("\tsilvia_keygen -a <#-attribs> [-n <bits>] [-p <file>] [-P <file>]\n");
printf("\tsilvia_keygen -h\n");
printf("\tsilvia_keygen -v\n");
printf("\n");
printf("\t-a <#-attribs> Generate a key-pair supporting credentials with at most\n");
printf("\t <#-attribs> attributes per credentials\n");
printf("\t-n <bits> Generate a key-pair with a <bits>-bit modulus (defaults\n");
printf("\t to %d)\n", DEFAULT_BITSIZE);
printf("\t-p <file> Output the public key to <file> (defaults to stdout)\n");
printf("\t-P <file> Output the private key to <file> (defaults to stdout)\n");
printf("\n");
printf("\t-h Print this help message\n");
printf("\n");
printf("\t-v Print the version number\n");
}
int generate_key_pair(FILE* pub_key_file, FILE* priv_key_file, size_t num_attribs, size_t bit_size)
{
printf("Generating %zd-bit issuer key pair for %zd attributes ... ", bit_size, num_attribs); fflush(stdout);
// Set key size
silvia_system_parameters::i()->set_l_n(bit_size);
// Generate key-pair
silvia_pub_key* pub_key;
silvia_priv_key* priv_key;
silvia_issuer_keyfactory::i()->generate_keypair(num_attribs + 1, &pub_key, &priv_key);
printf("OK\n");
// Output the public key
fprintf(pub_key_file, "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n");
fprintf(pub_key_file, "<IssuerPublicKey xmlns=\"http://www.zurich.ibm.com/security/idemix\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.zurich.ibm.com/security/idemix IssuerPublicKey.xsd\">\n");
fprintf(pub_key_file, " <References>\n");
fprintf(pub_key_file, " <GroupParameters>http://www.zurich.ibm.com/security/idmx/v2/gp.xml</GroupParameters>\n");
fprintf(pub_key_file, " </References>\n");
fprintf(pub_key_file, " <Elements>\n");
fprintf(pub_key_file, " <S>"); fprintmpzdec(pub_key_file, pub_key->get_S()); fprintf(pub_key_file, "</S>\n");
fprintf(pub_key_file, " <Z>"); fprintmpzdec(pub_key_file, pub_key->get_Z()); fprintf(pub_key_file, "</Z>\n");
fprintf(pub_key_file, " <n>"); fprintmpzdec(pub_key_file, pub_key->get_n()); fprintf(pub_key_file, "</n>\n");
fprintf(pub_key_file, " <Bases num=\"%zd\">\n", num_attribs);
for (size_t i = 0; i < num_attribs; i++)
{
fprintf(pub_key_file, " <Base_%zd>", i); fprintmpzdec(pub_key_file, pub_key->get_R()[i]); fprintf(pub_key_file, "</Base_%zd>\n", i);
}
fprintf(pub_key_file, " </Bases>\n");
fprintf(pub_key_file, " </Elements>\n");
fprintf(pub_key_file, " <Features>\n");
fprintf(pub_key_file, " <Epoch length=\"432000\"/>\n");
fprintf(pub_key_file, " </Features>\n");
fprintf(pub_key_file, "</IssuerPublicKey>\n");
// Output the private key
fprintf(priv_key_file, "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n");
fprintf(priv_key_file, "<IssuerPrivateKey xmlns=\"http://www.zurich.ibm.com/security/idemix\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.zurich.ibm.com/security/idemix IssuerPrivateKey.xsd\">\n");
fprintf(priv_key_file, " <References>\n");
fprintf(priv_key_file, " <IssuerPublicKey>http://www.issuer.com/ipk.xml</IssuerPublicKey>\n");
fprintf(priv_key_file, " </References>\n");
fprintf(priv_key_file, " <Elements>\n");
fprintf(priv_key_file, " <n>"); fprintmpzdec(priv_key_file, pub_key->get_n()); fprintf(priv_key_file, "</n>\n");
fprintf(priv_key_file, " <p>"); fprintmpzdec(priv_key_file, priv_key->get_p()); fprintf(priv_key_file, "</p>\n");
fprintf(priv_key_file, " <pPrime>"); fprintmpzdec(priv_key_file, priv_key->get_p_prime()); fprintf(priv_key_file, "</pPrime>\n");
fprintf(priv_key_file, " <q>"); fprintmpzdec(priv_key_file, priv_key->get_q()); fprintf(priv_key_file, "</q>\n");
fprintf(priv_key_file, " <qPrime>"); fprintmpzdec(priv_key_file, priv_key->get_q_prime()); fprintf(priv_key_file, "</qPrime>\n");
fprintf(priv_key_file, " </Elements>\n");
fprintf(priv_key_file, "</IssuerPrivateKey>\n");
delete pub_key;
delete priv_key;
return 1;
}
int main(int argc, char* argv[])
{
// Program parameters
size_t bit_size = DEFAULT_BITSIZE;
size_t num_attribs = 0;
std::string pub_key_filename;
std::string priv_key_filename;
int c = 0;
while ((c = getopt(argc, argv, "a:n:p:P:hv")) != -1)
{
switch (c)
{
case 'h':
usage();
return 0;
case 'v':
version();
return 0;
case 'a':
num_attribs = atoi(optarg);
break;
case 'n':
bit_size = atoi(optarg);
break;
case 'p':
pub_key_filename = std::string(optarg);
break;
case 'P':
priv_key_filename = std::string(optarg);
break;
}
}
if (num_attribs <= 0)
{
fprintf(stderr, "Missing argument -a; please specify a number of attributes\n");
return -1;
}
FILE* pub_key_file = stdout;
FILE* priv_key_file = stdout;
if (!pub_key_filename.empty())
{
pub_key_file = fopen(pub_key_filename.c_str(), "w");
if (pub_key_file == NULL)
{
fprintf(stderr, "Failed to open %s for writing\n", pub_key_filename.c_str());
return -1;
}
printf("Writing public key to %s\n", pub_key_filename.c_str());
}
if (!priv_key_filename.empty())
{
priv_key_file = fopen(priv_key_filename.c_str(), "w");
if (priv_key_file == NULL)
{
fprintf(stderr, "Failed to open %s for writing\n", priv_key_filename.c_str());
return -1;
}
printf("Writing private key to %s\n", priv_key_filename.c_str());
}
generate_key_pair(pub_key_file, priv_key_file, num_attribs, bit_size);
if (!pub_key_filename.empty()) fclose(pub_key_file);
if (!priv_key_filename.empty()) fclose(priv_key_file);
return 0;
}
<commit_msg>Fixed off-by-one-error, now prints all genertaed bases<commit_after>/* $Id$ */
/*
* Copyright (c) 2013 Roland van Rijswijk-Deij
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*****************************************************************************
silvia_keygen.cpp
Issuer key generation utility
*****************************************************************************/
#include "config.h"
#include "silvia_issuer_keygen.h"
#include "silvia_parameters.h"
#include "silvia_macros.h"
#include <string>
#include <unistd.h>
// Default modulus size for new keys
#define DEFAULT_BITSIZE 2048
void version(void)
{
printf("The Simple Library for Verifying and Issuing Attributes (silvia)\n");
printf("\n");
printf("Issuer key generation utility version %s\n", VERSION);
printf("\n");
printf("Copyright (c) 2013 Roland van Rijswijk-Deij\n\n");
printf("Use, modification and redistribution of this software is subject to the terms\n");
printf("of the license agreement. This software is licensed under a 2-clause BSD-style\n");
printf("license a copy of which is included as the file LICENSE in the distribution.\n");
}
void usage(void)
{
printf("Silvia issuer key generation utility %s\n\n", VERSION);
printf("Usage:\n");
printf("\tsilvia_keygen -a <#-attribs> [-n <bits>] [-p <file>] [-P <file>]\n");
printf("\tsilvia_keygen -h\n");
printf("\tsilvia_keygen -v\n");
printf("\n");
printf("\t-a <#-attribs> Generate a key-pair supporting credentials with at most\n");
printf("\t <#-attribs> attributes per credentials\n");
printf("\t-n <bits> Generate a key-pair with a <bits>-bit modulus (defaults\n");
printf("\t to %d)\n", DEFAULT_BITSIZE);
printf("\t-p <file> Output the public key to <file> (defaults to stdout)\n");
printf("\t-P <file> Output the private key to <file> (defaults to stdout)\n");
printf("\n");
printf("\t-h Print this help message\n");
printf("\n");
printf("\t-v Print the version number\n");
}
int generate_key_pair(FILE* pub_key_file, FILE* priv_key_file, size_t num_attribs, size_t bit_size)
{
printf("Generating %zd-bit issuer key pair for %zd attributes ... ", bit_size, num_attribs); fflush(stdout);
// Set key size
silvia_system_parameters::i()->set_l_n(bit_size);
// Generate key-pair
silvia_pub_key* pub_key;
silvia_priv_key* priv_key;
silvia_issuer_keyfactory::i()->generate_keypair(num_attribs + 1, &pub_key, &priv_key);
printf("OK\n");
// Output the public key
fprintf(pub_key_file, "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n");
fprintf(pub_key_file, "<IssuerPublicKey xmlns=\"http://www.zurich.ibm.com/security/idemix\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.zurich.ibm.com/security/idemix IssuerPublicKey.xsd\">\n");
fprintf(pub_key_file, " <References>\n");
fprintf(pub_key_file, " <GroupParameters>http://www.zurich.ibm.com/security/idmx/v2/gp.xml</GroupParameters>\n");
fprintf(pub_key_file, " </References>\n");
fprintf(pub_key_file, " <Elements>\n");
fprintf(pub_key_file, " <S>"); fprintmpzdec(pub_key_file, pub_key->get_S()); fprintf(pub_key_file, "</S>\n");
fprintf(pub_key_file, " <Z>"); fprintmpzdec(pub_key_file, pub_key->get_Z()); fprintf(pub_key_file, "</Z>\n");
fprintf(pub_key_file, " <n>"); fprintmpzdec(pub_key_file, pub_key->get_n()); fprintf(pub_key_file, "</n>\n");
fprintf(pub_key_file, " <Bases num=\"%zd\">\n", num_attribs);
for (size_t i = 0; i < num_attribs + 1; i++)
{
fprintf(pub_key_file, " <Base_%zd>", i); fprintmpzdec(pub_key_file, pub_key->get_R()[i]); fprintf(pub_key_file, "</Base_%zd>\n", i);
}
fprintf(pub_key_file, " </Bases>\n");
fprintf(pub_key_file, " </Elements>\n");
fprintf(pub_key_file, " <Features>\n");
fprintf(pub_key_file, " <Epoch length=\"432000\"/>\n");
fprintf(pub_key_file, " </Features>\n");
fprintf(pub_key_file, "</IssuerPublicKey>\n");
// Output the private key
fprintf(priv_key_file, "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n");
fprintf(priv_key_file, "<IssuerPrivateKey xmlns=\"http://www.zurich.ibm.com/security/idemix\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.zurich.ibm.com/security/idemix IssuerPrivateKey.xsd\">\n");
fprintf(priv_key_file, " <References>\n");
fprintf(priv_key_file, " <IssuerPublicKey>http://www.issuer.com/ipk.xml</IssuerPublicKey>\n");
fprintf(priv_key_file, " </References>\n");
fprintf(priv_key_file, " <Elements>\n");
fprintf(priv_key_file, " <n>"); fprintmpzdec(priv_key_file, pub_key->get_n()); fprintf(priv_key_file, "</n>\n");
fprintf(priv_key_file, " <p>"); fprintmpzdec(priv_key_file, priv_key->get_p()); fprintf(priv_key_file, "</p>\n");
fprintf(priv_key_file, " <pPrime>"); fprintmpzdec(priv_key_file, priv_key->get_p_prime()); fprintf(priv_key_file, "</pPrime>\n");
fprintf(priv_key_file, " <q>"); fprintmpzdec(priv_key_file, priv_key->get_q()); fprintf(priv_key_file, "</q>\n");
fprintf(priv_key_file, " <qPrime>"); fprintmpzdec(priv_key_file, priv_key->get_q_prime()); fprintf(priv_key_file, "</qPrime>\n");
fprintf(priv_key_file, " </Elements>\n");
fprintf(priv_key_file, "</IssuerPrivateKey>\n");
delete pub_key;
delete priv_key;
return 1;
}
int main(int argc, char* argv[])
{
// Program parameters
size_t bit_size = DEFAULT_BITSIZE;
size_t num_attribs = 0;
std::string pub_key_filename;
std::string priv_key_filename;
int c = 0;
while ((c = getopt(argc, argv, "a:n:p:P:hv")) != -1)
{
switch (c)
{
case 'h':
usage();
return 0;
case 'v':
version();
return 0;
case 'a':
num_attribs = atoi(optarg);
break;
case 'n':
bit_size = atoi(optarg);
break;
case 'p':
pub_key_filename = std::string(optarg);
break;
case 'P':
priv_key_filename = std::string(optarg);
break;
}
}
if (num_attribs <= 0)
{
fprintf(stderr, "Missing argument -a; please specify a number of attributes\n");
return -1;
}
FILE* pub_key_file = stdout;
FILE* priv_key_file = stdout;
if (!pub_key_filename.empty())
{
pub_key_file = fopen(pub_key_filename.c_str(), "w");
if (pub_key_file == NULL)
{
fprintf(stderr, "Failed to open %s for writing\n", pub_key_filename.c_str());
return -1;
}
printf("Writing public key to %s\n", pub_key_filename.c_str());
}
if (!priv_key_filename.empty())
{
priv_key_file = fopen(priv_key_filename.c_str(), "w");
if (priv_key_file == NULL)
{
fprintf(stderr, "Failed to open %s for writing\n", priv_key_filename.c_str());
return -1;
}
printf("Writing private key to %s\n", priv_key_filename.c_str());
}
generate_key_pair(pub_key_file, priv_key_file, num_attribs, bit_size);
if (!pub_key_filename.empty()) fclose(pub_key_file);
if (!priv_key_filename.empty()) fclose(priv_key_file);
return 0;
}
<|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2016 Artem Pavlenko
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_FACE_HPP
#define MAPNIK_FACE_HPP
//mapnik
#include <mapnik/config.hpp>
#include <mapnik/text/glyph_info.hpp>
#include <mapnik/util/noncopyable.hpp>
#pragma GCC diagnostic push
#include <mapnik/warning_ignore.hpp>
extern "C"
{
#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_STROKER_H
}
#pragma GCC diagnostic pop
//stl
#include <memory>
#include <string>
#include <vector>
namespace mapnik
{
class MAPNIK_DECL font_face : util::noncopyable
{
public:
font_face(FT_Face face);
std::string family_name() const
{
return std::string(face_->family_name);
}
std::string style_name() const
{
return std::string(face_->style_name);
}
FT_Face get_face() const
{
return face_;
}
bool set_character_sizes(double size);
bool set_unscaled_character_sizes();
bool glyph_dimensions(glyph_info &glyph) const;
~font_face();
private:
FT_Face face_;
};
using face_ptr = std::shared_ptr<font_face>;
class MAPNIK_DECL font_face_set : private util::noncopyable
{
public:
using iterator = std::vector<face_ptr>::iterator;
font_face_set(void) : faces_(){}
void add(face_ptr face);
void set_character_sizes(double size);
void set_unscaled_character_sizes();
std::size_t size() const { return faces_.size(); }
iterator begin() { return faces_.begin(); }
iterator end() { return faces_.end(); }
private:
std::vector<face_ptr> faces_;
};
using face_set_ptr = std::unique_ptr<font_face_set>;
// FT_Stroker wrapper
class stroker : util::noncopyable
{
public:
explicit stroker(FT_Stroker s)
: s_(s) {}
~stroker();
void init(double radius);
FT_Stroker const& get() const { return s_; }
private:
FT_Stroker s_;
};
} //ns mapnik
#endif // FACE_HPP
<commit_msg>add color_font_ member<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2016 Artem Pavlenko
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_FACE_HPP
#define MAPNIK_FACE_HPP
//mapnik
#include <mapnik/config.hpp>
#include <mapnik/text/glyph_info.hpp>
#include <mapnik/util/noncopyable.hpp>
#pragma GCC diagnostic push
#include <mapnik/warning_ignore.hpp>
extern "C"
{
#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_STROKER_H
}
#pragma GCC diagnostic pop
//stl
#include <memory>
#include <string>
#include <vector>
namespace mapnik
{
class MAPNIK_DECL font_face : util::noncopyable
{
public:
font_face(FT_Face face);
std::string family_name() const
{
return std::string(face_->family_name);
}
std::string style_name() const
{
return std::string(face_->style_name);
}
FT_Face get_face() const
{
return face_;
}
bool set_character_sizes(double size);
bool set_unscaled_character_sizes();
bool glyph_dimensions(glyph_info &glyph) const;
inline bool is_color() const { return color_font_;}
~font_face();
private:
FT_Face face_;
bool color_font_ = false;
};
using face_ptr = std::shared_ptr<font_face>;
class MAPNIK_DECL font_face_set : private util::noncopyable
{
public:
using iterator = std::vector<face_ptr>::iterator;
font_face_set(void) : faces_(){}
void add(face_ptr face);
void set_character_sizes(double size);
void set_unscaled_character_sizes();
std::size_t size() const { return faces_.size(); }
iterator begin() { return faces_.begin(); }
iterator end() { return faces_.end(); }
private:
std::vector<face_ptr> faces_;
};
using face_set_ptr = std::unique_ptr<font_face_set>;
// FT_Stroker wrapper
class stroker : util::noncopyable
{
public:
explicit stroker(FT_Stroker s)
: s_(s) {}
~stroker();
void init(double radius);
FT_Stroker const& get() const { return s_; }
private:
FT_Stroker s_;
};
} //ns mapnik
#endif // FACE_HPP
<|endoftext|>
|
<commit_before>//============================================================================
// MCKL/include/mckl/random/seed.hpp
//----------------------------------------------------------------------------
// MCKL: Monte Carlo Kernel Library
//----------------------------------------------------------------------------
// Copyright (c) 2013-2016, Yan Zhou
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//============================================================================
#ifndef MCKL_RANDOM_SEED_HPP
#define MCKL_RANDOM_SEED_HPP
#include <mckl/random/internal/common.hpp>
#include <mckl/random/counter.hpp>
/// \brief Default result type of Seed
/// \ingroup Config
#ifndef MCKL_SEED_RESULT_TYPE
#define MCKL_SEED_RESULT_TYPE unsigned
#endif
namespace mckl
{
/// \brief Seed generator
/// \ingroup Random
///
/// \details
/// The sequence of seeds are belongs to the equivalent class \f$s \mod D
/// \equiv R\f$ where \f$D > 0\f$, \f$R \ge 0\f$. The defaults are \f$1\f$ and
/// \f$0\f$ respectively. Each time `get()` is called, a new seed is returned.
///
/// The method `operator()(RNGType &rng)` is equivalent to
/// `rng.seed(static_cast<typename RNGType::result_type>(get()))`.
template <typename ID, typename ResultType = MCKL_SEED_RESULT_TYPE>
class SeedGenerator
{
static_assert(std::is_unsigned<ResultType>::value,
"**SeedGenerator** USED WITH ResultType OTHER THAN UNSIGEND INTEGER "
"TYPES");
public:
using result_type = ResultType;
SeedGenerator(const SeedGenerator<ID, ResultType> &) = delete;
SeedGenerator<ID, ResultType> &operator=(
const SeedGenerator<ID, ResultType> &) = delete;
static SeedGenerator<ID, ResultType> &instance()
{
static SeedGenerator<ID, ResultType> seed;
return seed;
}
/// \brief Seed a single RNG
template <typename RNGType>
void operator()(RNGType &rng)
{
rng.seed(static_cast<typename RNGType::result_type>(get()));
}
/// \brief Seed a sequence of RNGs
template <typename OutputIter>
OutputIter operator()(std::size_t n, OutputIter first)
{
using RNGType = typename std::iterator_traits<OutputIter>::value_type;
for (std::size_t i = 0; i != n; ++i, ++first)
first->seed(static_cast<typename RNGType::result_type>(get()));
return first;
}
/// \brief Set the seed to `s % max() * divisor() + remainder()`
void set(result_type s) { seed_ = s % max_; }
/// \brief Get a seed
result_type get()
{
result_type s = seed_.fetch_add(1);
return (s % max_ + 1) * divisor_ + remainder_;
}
/// \brief The maximum of the seed
result_type max() const { return max_; }
/// \brief The divisor of the output seed
result_type divisor() const { return divisor_; }
/// \brief The remainder of the output seed
result_type remainder() const { return remainder_; }
/// \brief Set the divisor and the remainder
void modulo(result_type divisor, result_type remainder)
{
runtime_assert(divisor > remainder,
"**SeedGenerator::modulo** the "
"remainder is not smaller than "
"the divisor");
result_type maxs = std::numeric_limits<result_type>::max() / divisor;
runtime_assert(maxs > 1,
"**SeedGenerator::modulo** the maximum of "
"the internal seed will be no larger than 1");
divisor_ = divisor;
remainder_ = remainder;
max_ = maxs;
set(seed_);
}
template <typename CharT, typename Traits>
friend std::basic_ostream<CharT, Traits> &operator<<(
std::basic_ostream<CharT, Traits> &os,
const SeedGenerator<ID, ResultType> &sg)
{
if (!os)
return os;
os << sg.seed_ << ' ';
os << sg.max_ << ' ';
os << sg.divisor_ << ' ';
os << sg.remainder_ << ' ';
return os;
}
template <typename CharT, typename Traits>
friend std::basic_istream<CharT, Traits> &operator>>(
std::basic_istream<CharT, Traits> &is,
SeedGenerator<ID, ResultType> &sg)
{
if (!is)
return is;
result_type seed;
result_type max;
result_type divisor;
result_type remainder;
is >> std::ws >> seed;
is >> std::ws >> max;
is >> std::ws >> divisor;
is >> std::ws >> remainder;
if (is) {
sg.seed_ = seed;
sg.max_ = max;
sg.divisor_ = divisor;
sg.remainder_ = remainder;
}
return is;
}
private:
std::atomic<result_type> seed_;
result_type max_;
result_type divisor_;
result_type remainder_;
SeedGenerator() : seed_(0), max_(0), divisor_(1), remainder_(0)
{
modulo(divisor_, remainder_);
}
}; // class SeedGenerator
/// \brief The default Seed type
/// \ingroup Random
using Seed = SeedGenerator<NullType>;
} // namespace mckl
#endif // MCKL_RANDOM_SEED_HPP
<commit_msg>fix seed maximum case<commit_after>//============================================================================
// MCKL/include/mckl/random/seed.hpp
//----------------------------------------------------------------------------
// MCKL: Monte Carlo Kernel Library
//----------------------------------------------------------------------------
// Copyright (c) 2013-2016, Yan Zhou
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//============================================================================
#ifndef MCKL_RANDOM_SEED_HPP
#define MCKL_RANDOM_SEED_HPP
#include <mckl/random/internal/common.hpp>
#include <mckl/random/counter.hpp>
/// \brief Default result type of Seed
/// \ingroup Config
#ifndef MCKL_SEED_RESULT_TYPE
#define MCKL_SEED_RESULT_TYPE unsigned
#endif
namespace mckl
{
/// \brief Seed generator
/// \ingroup Random
///
/// \details
/// The sequence of seeds are belongs to the equivalent class \f$s \mod D
/// \equiv R\f$ where \f$D > 0\f$, \f$R \ge 0\f$. The defaults are \f$D = 1\f$
/// and \f$R = 0\f$. Each time `get()` is called, a new seed is returned.
///
/// The method `operator()(RNGType &rng)` is equivalent to
/// `rng.seed(static_cast<typename RNGType::result_type>(get()))`.
///
/// \note
/// If \f$D = 1\f$ (and \f$R = 0\f$), then there will be exactly two seeds
/// equal
/// to `1` in any sequence of length \f$2^N\f$, where \f$N\f$ is the number of
/// digits in the unsigned integer type. They are either one at the beginning
/// and one at the end, or consecutive.
template <typename ID, typename ResultType = MCKL_SEED_RESULT_TYPE>
class SeedGenerator
{
static_assert(std::is_unsigned<ResultType>::value,
"**SeedGenerator** used with ResultType other than unsigned integer "
"types");
public:
using result_type = ResultType;
SeedGenerator(const SeedGenerator<ID, ResultType> &) = delete;
SeedGenerator<ID, ResultType> &operator=(
const SeedGenerator<ID, ResultType> &) = delete;
static SeedGenerator<ID, ResultType> &instance()
{
static SeedGenerator<ID, ResultType> seed;
return seed;
}
/// \brief Seed a single RNG
template <typename RNGType>
void operator()(RNGType &rng)
{
rng.seed(static_cast<typename RNGType::result_type>(get()));
}
/// \brief Seed a sequence of RNGs
template <typename OutputIter>
OutputIter operator()(std::size_t n, OutputIter first)
{
using RNGType = typename std::iterator_traits<OutputIter>::value_type;
for (std::size_t i = 0; i != n; ++i, ++first)
first->seed(static_cast<typename RNGType::result_type>(get()));
return first;
}
/// \brief Set the seed to `s % max() * divisor() + remainder()`
void set(result_type s) { seed_ = s % max_; }
/// \brief Get a seed
result_type get()
{
result_type s = seed_.fetch_add(1);
return (s % max_ + 1) * divisor_ + remainder_;
}
/// \brief The maximum of the seed
result_type max() const { return max_; }
/// \brief The divisor of the output seed
result_type divisor() const { return divisor_; }
/// \brief The remainder of the output seed
result_type remainder() const { return remainder_; }
/// \brief Set the divisor and the remainder
void modulo(result_type divisor, result_type remainder)
{
runtime_assert(divisor > remainder,
"**SeedGenerator::modulo** the remainder is not smaller than the "
"divisor");
result_type maxs =
(std::numeric_limits<result_type>::max() - remainder) / divisor;
runtime_assert(maxs > 1,
"**SeedGenerator::modulo** the maximum of the internal seed will "
"be no larger than 1");
divisor_ = divisor;
remainder_ = remainder;
max_ = maxs;
set(seed_);
}
template <typename CharT, typename Traits>
friend std::basic_ostream<CharT, Traits> &operator<<(
std::basic_ostream<CharT, Traits> &os,
const SeedGenerator<ID, ResultType> &sg)
{
if (!os)
return os;
os << sg.seed_ << ' ';
os << sg.max_ << ' ';
os << sg.divisor_ << ' ';
os << sg.remainder_ << ' ';
return os;
}
template <typename CharT, typename Traits>
friend std::basic_istream<CharT, Traits> &operator>>(
std::basic_istream<CharT, Traits> &is,
SeedGenerator<ID, ResultType> &sg)
{
if (!is)
return is;
result_type seed;
result_type max;
result_type divisor;
result_type remainder;
is >> std::ws >> seed;
is >> std::ws >> max;
is >> std::ws >> divisor;
is >> std::ws >> remainder;
if (is) {
sg.seed_ = seed;
sg.max_ = max;
sg.divisor_ = divisor;
sg.remainder_ = remainder;
}
return is;
}
private:
std::atomic<result_type> seed_;
result_type max_;
result_type divisor_;
result_type remainder_;
SeedGenerator() : seed_(0), max_(0), divisor_(1), remainder_(0)
{
modulo(divisor_, remainder_);
}
}; // class SeedGenerator
/// \brief The default Seed type
/// \ingroup Random
using Seed = SeedGenerator<NullType>;
} // namespace mckl
#endif // MCKL_RANDOM_SEED_HPP
<|endoftext|>
|
<commit_before>///
/// @file pmath.hpp
/// @brief Auxiliary math functions for primesieve.
///
/// Copyright (C) 2018 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef PMATH_HPP
#define PMATH_HPP
#include <stdint.h>
#include <algorithm>
#include <cmath>
#include <cstddef>
#include <limits>
#include <type_traits>
namespace primesieve {
template <typename X, typename Y>
inline X ceilDiv(X x, Y y)
{
return (X) ((x + y - 1) / y);
}
template <typename T>
inline bool isPow2(T x)
{
return x != 0 && (x & (x - 1)) == 0;
}
template <typename T>
inline T numberOfBits(T)
{
return (T) std::numeric_limits<
typename std::make_unsigned<T>::type
>::digits;
}
template <typename T>
inline T floorPow2(T x)
{
for (T i = 1; i < numberOfBits(x); i += i)
x |= (x >> i);
return x - (x >> 1);
}
template <typename T>
inline T ilog2(T x)
{
T bits = numberOfBits(x);
T one = 1;
T log2 = 0;
for (T i = bits / 2; i > 0; i /= 2)
{
if (x >= (one << i))
{
x >>= i;
log2 += i;
}
}
return log2;
}
#if __cplusplus >= 201402L
/// C++14 compile time square root using binary search
template <typename T>
constexpr T ctSqrt(T x, T lo, T hi)
{
if (lo == hi)
return lo;
const T mid = (lo + hi + 1) / 2;
if (x / mid < mid)
return ctSqrt<T>(x, lo, mid - 1);
else
return ctSqrt(x, mid, hi);
}
#else
#define MID ((lo + hi + 1) / 2)
/// C++11 compile time square root using binary search
template <typename T>
constexpr T ctSqrt(T x, T lo, T hi)
{
return lo == hi ? lo : ((x / MID < MID)
? ctSqrt<T>(x, lo, MID - 1) : ctSqrt<T>(x, MID, hi));
}
#endif
template <typename T>
constexpr T ctSqrt(T x)
{
return ctSqrt<T>(x, 0, x / 2 + 1);
}
template <typename T>
inline T isqrt(T x)
{
T r = (T) std::sqrt((double) x);
constexpr T maxSqrt = ctSqrt(std::numeric_limits<T>::max());
r = std::min(r, maxSqrt);
while (r * r > x)
r--;
while (x - r * r > r * 2)
r++;
return r;
}
/// Returns 2^64-1 if (x + y) > 2^64-1
inline uint64_t checkedAdd(uint64_t x, uint64_t y)
{
if (x >= std::numeric_limits<uint64_t>::max() - y)
return std::numeric_limits<uint64_t>::max();
else
return x + y;
}
/// Returns 0 if (x - y) < 0
inline uint64_t checkedSub(uint64_t x, uint64_t y)
{
if (x > y)
return x - y;
else
return 0;
}
template <typename A, typename B, typename C>
inline B inBetween(A min, B x, C max)
{
using T = typename std::common_type<A, B, C>::type;
if ((T) x < (T) min)
return (B) min;
if ((T) x > (T) max)
return (B) max;
return x;
}
/// primeCountApprox(x) >= pi(x)
inline std::size_t primeCountApprox(uint64_t start, uint64_t stop)
{
if (start > stop)
return 0;
if (stop <= 10)
return 4;
// pi(x) <= x / (log(x) - 1.1) + 5, for x >= 4
double x = (double) stop;
double logx = std::log(x);
double div = logx - 1.1;
double pix = (stop - start) / div + 5;
return (std::size_t) pix;
}
inline std::size_t primeCountApprox(uint64_t stop)
{
return primeCountApprox(0, stop);
}
/// Approximation of the maximum prime gap near n
template <typename T>
inline T maxPrimeGap(T n)
{
double x = (double) n;
x = std::max(8.0, x);
double logx = std::log(x);
double prime_gap = logx * logx;
return (T) prime_gap;
}
} // namespace
#endif
<commit_msg>constexpr numberOfBits()<commit_after>///
/// @file pmath.hpp
/// @brief Auxiliary math functions for primesieve.
///
/// Copyright (C) 2018 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef PMATH_HPP
#define PMATH_HPP
#include <stdint.h>
#include <algorithm>
#include <cmath>
#include <cstddef>
#include <limits>
#include <type_traits>
namespace primesieve {
template <typename X, typename Y>
inline X ceilDiv(X x, Y y)
{
return (X) ((x + y - 1) / y);
}
template <typename T>
inline bool isPow2(T x)
{
return x != 0 && (x & (x - 1)) == 0;
}
template <typename T>
constexpr T numberOfBits(T)
{
return (T) std::numeric_limits<
typename std::make_unsigned<T>::type
>::digits;
}
template <typename T>
inline T floorPow2(T x)
{
for (T i = 1; i < numberOfBits(x); i += i)
x |= (x >> i);
return x - (x >> 1);
}
template <typename T>
inline T ilog2(T x)
{
T bits = numberOfBits(x);
T one = 1;
T log2 = 0;
for (T i = bits / 2; i > 0; i /= 2)
{
if (x >= (one << i))
{
x >>= i;
log2 += i;
}
}
return log2;
}
#if __cplusplus >= 201402L
/// C++14 compile time square root using binary search
template <typename T>
constexpr T ctSqrt(T x, T lo, T hi)
{
if (lo == hi)
return lo;
const T mid = (lo + hi + 1) / 2;
if (x / mid < mid)
return ctSqrt<T>(x, lo, mid - 1);
else
return ctSqrt(x, mid, hi);
}
#else
#define MID ((lo + hi + 1) / 2)
/// C++11 compile time square root using binary search
template <typename T>
constexpr T ctSqrt(T x, T lo, T hi)
{
return lo == hi ? lo : ((x / MID < MID)
? ctSqrt<T>(x, lo, MID - 1) : ctSqrt<T>(x, MID, hi));
}
#endif
template <typename T>
constexpr T ctSqrt(T x)
{
return ctSqrt<T>(x, 0, x / 2 + 1);
}
template <typename T>
inline T isqrt(T x)
{
T r = (T) std::sqrt((double) x);
constexpr T maxSqrt = ctSqrt(std::numeric_limits<T>::max());
r = std::min(r, maxSqrt);
while (r * r > x)
r--;
while (x - r * r > r * 2)
r++;
return r;
}
/// Returns 2^64-1 if (x + y) > 2^64-1
inline uint64_t checkedAdd(uint64_t x, uint64_t y)
{
if (x >= std::numeric_limits<uint64_t>::max() - y)
return std::numeric_limits<uint64_t>::max();
else
return x + y;
}
/// Returns 0 if (x - y) < 0
inline uint64_t checkedSub(uint64_t x, uint64_t y)
{
if (x > y)
return x - y;
else
return 0;
}
template <typename A, typename B, typename C>
inline B inBetween(A min, B x, C max)
{
using T = typename std::common_type<A, B, C>::type;
if ((T) x < (T) min)
return (B) min;
if ((T) x > (T) max)
return (B) max;
return x;
}
/// primeCountApprox(x) >= pi(x)
inline std::size_t primeCountApprox(uint64_t start, uint64_t stop)
{
if (start > stop)
return 0;
if (stop <= 10)
return 4;
// pi(x) <= x / (log(x) - 1.1) + 5, for x >= 4
double x = (double) stop;
double logx = std::log(x);
double div = logx - 1.1;
double pix = (stop - start) / div + 5;
return (std::size_t) pix;
}
inline std::size_t primeCountApprox(uint64_t stop)
{
return primeCountApprox(0, stop);
}
/// Approximation of the maximum prime gap near n
template <typename T>
inline T maxPrimeGap(T n)
{
double x = (double) n;
x = std::max(8.0, x);
double logx = std::log(x);
double prime_gap = logx * logx;
return (T) prime_gap;
}
} // namespace
#endif
<|endoftext|>
|
<commit_before>// Copyright 2010-2012 RethinkDB, all rights reserved.
#include "concurrency/watchable.hpp"
#include <functional>
#include "errors.hpp"
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include "arch/timing.hpp"
#include "concurrency/cond_var.hpp"
#include "concurrency/wait_any.hpp"
template <class result_type, class outer_type, class callable_type>
class subview_watchable_t : public watchable_t<result_type> {
public:
subview_watchable_t(const callable_type &l, watchable_t<outer_type> *p) :
cache(new lensed_value_cache_t(l, p)) { }
subview_watchable_t *clone() const {
return new subview_watchable_t(cache);
}
result_type get() {
return *cache->get();
}
virtual void apply_read(const std::function<void(const result_type*)> &read) {
ASSERT_NO_CORO_WAITING;
read(cache->get());
}
publisher_t<boost::function<void()> > *get_publisher() {
return cache->get_publisher();
}
rwi_lock_assertion_t *get_rwi_lock_assertion() {
return cache->parent->get_rwi_lock_assertion();
}
private:
// lensed_value_cache_t is a cache for the result of a lens applied to
// a given parent watchable. It is implemented for incremental lenses only.
// (`non_incremental_lens_wrapper_t` can be used to apply it to non-incremental
// lenses as well).
// The cached value is recomputed only after the parent has published a new
// value.
class lensed_value_cache_t : public home_thread_mixin_t {
public:
lensed_value_cache_t(const callable_type &l, watchable_t<outer_type> *p) :
parent(p->clone()),
lens(l),
parent_subscription(boost::bind(
&subview_watchable_t<result_type, outer_type, callable_type>::lensed_value_cache_t::on_parent_changed,
this)) {
typename watchable_t<outer_type>::freeze_t freeze(parent);
ASSERT_FINITE_CORO_WAITING;
compute_value();
parent_subscription.reset(parent, &freeze);
}
~lensed_value_cache_t() {
assert_thread();
}
const result_type *get() {
assert_thread();
return &cached_value;
}
publisher_t<boost::function<void()> > *get_publisher() {
assert_thread();
return publisher_controller.get_publisher();
}
clone_ptr_t<watchable_t<outer_type> > parent;
private:
bool compute_value() {
// The closure is to avoid copying the whole value from the parent.
bool value_changed = false;
struct op_closure_t {
static void apply(callable_type *_lens,
bool *_value_changed,
result_type *_cached_value,
const outer_type *val) {
*_value_changed = (*_lens)(*val, _cached_value);
}
};
parent->apply_read(std::bind(&op_closure_t::apply,
&lens,
&value_changed,
&cached_value,
std::placeholders::_1));
return value_changed;
}
void on_parent_changed() {
assert_thread();
const bool value_changed = compute_value();
if (value_changed) {
publisher_controller.publish(&call_function);
}
}
callable_type lens;
result_type cached_value;
publisher_controller_t<boost::function<void()> > publisher_controller;
typename watchable_t<outer_type>::subscription_t parent_subscription;
};
explicit subview_watchable_t(const boost::shared_ptr<lensed_value_cache_t> &_cache) :
cache(_cache) { }
// If you clone a subview_watchable_t, all clones share the same cache.
// As a consequence, the lens is only applied once for the whole family
// of clones, not once per instance of subview_watchable_t. This should save
// some CPU and memory as well.
boost::shared_ptr<lensed_value_cache_t> cache;
};
/* Given a non-incremental lens with the type signature
* `result_type(input_type)`, `non_incremental_lens_wrapper_t` converts
* it into an incremental lens with type signature
* `bool(const input_type &, result_type *)` and otherwise equivalent semantics
* (as much as possible). */
template<class outer_type, class callable_type>
class non_incremental_lens_wrapper_t {
public:
typedef typename boost::result_of<callable_type(outer_type)>::type result_type;
explicit non_incremental_lens_wrapper_t(const callable_type &_inner) :
inner(_inner) {
}
bool operator()(const outer_type &input, result_type *current_out) {
guarantee(current_out != NULL);
result_type old_value = *current_out;
*current_out = inner(input);
return old_value != *current_out;
}
private:
callable_type inner;
};
template<class value_type>
template<class callable_type>
clone_ptr_t<watchable_t<typename callable_type::result_type> > watchable_t<value_type>::incremental_subview(const callable_type &lens) {
assert_thread();
return clone_ptr_t<watchable_t<typename callable_type::result_type> >(
new subview_watchable_t<typename callable_type::result_type, value_type, callable_type>(lens, this));
}
template<class value_type>
template<class result_type, class callable_type>
clone_ptr_t<watchable_t<result_type> > watchable_t<value_type>::incremental_subview(const callable_type &lens) {
assert_thread();
return clone_ptr_t<watchable_t<result_type> >(
new subview_watchable_t<result_type, value_type, callable_type>(lens, this));
}
template<class value_type>
template<class callable_type>
clone_ptr_t<watchable_t<typename boost::result_of<callable_type(value_type)>::type> > watchable_t<value_type>::subview(const callable_type &lens) {
assert_thread();
typedef non_incremental_lens_wrapper_t<value_type, callable_type> wrapped_callable_type;
wrapped_callable_type wrapped_lens(lens);
return clone_ptr_t<watchable_t<typename wrapped_callable_type::result_type> >(
new subview_watchable_t<typename wrapped_callable_type::result_type, value_type, wrapped_callable_type>(wrapped_lens, this));
}
// These are helper functions for `run_until_satisfied()` and `run_until_satisfied_2()`
// that can be passed into a watchable's `apply_read()`. They simply apply the
// provided function `_fun` to the current value of the watchable(s) and pass out
// its boolean return value.
template<class value_type, class callable_type>
void run_until_satisfied_apply(const callable_type &_fun, const value_type *val,
bool *is_done_out) {
*is_done_out = _fun(*val);
}
template<class a_type, class b_type, class callable_type>
void run_until_satisfied_2_apply_inner(const callable_type &_fun,
const a_type *a_val, const b_type *b_val, bool *is_done_out) {
*is_done_out = _fun(*a_val, *b_val);
}
template<class a_type, class b_type, class callable_type>
void run_until_satisfied_2_apply_outer(const callable_type &_fun,
const clone_ptr_t<watchable_t<b_type> > &_b, const a_type *a_val,
bool *is_done_out) {
_b->apply_read(std::bind(
&run_until_satisfied_2_apply_inner<a_type, b_type, callable_type>, _fun, a_val,
std::placeholders::_1, is_done_out));
}
template<class value_type>
template<class callable_type>
void watchable_t<value_type>::run_until_satisfied(const callable_type &fun,
signal_t *interruptor, int64_t nap_before_retry_ms) THROWS_ONLY(interrupted_exc_t) {
assert_thread();
bool is_done = false;
auto op = std::bind(&run_until_satisfied_apply<value_type, callable_type>,
fun,
std::placeholders::_1,
&is_done);
clone_ptr_t<watchable_t<value_type> > clone_this(this->clone());
while (true) {
cond_t changed;
typename watchable_t<value_type>::subscription_t subs(boost::bind(&cond_t::pulse_if_not_already_pulsed, &changed));
{
typename watchable_t<value_type>::freeze_t freeze(clone_this);
ASSERT_FINITE_CORO_WAITING;
clone_this->apply_read(op);
if (is_done) {
return;
}
subs.reset(clone_this, &freeze);
}
// Nap a little so changes to the watchables can accumulate.
// This is purely a performance optimization to save CPU cycles,
// in case that applying `fun` is expensive.
nap(nap_before_retry_ms, interruptor);
wait_interruptible(&changed, interruptor);
}
}
template<class a_type, class b_type, class callable_type>
void run_until_satisfied_2(
const clone_ptr_t<watchable_t<a_type> > &a,
const clone_ptr_t<watchable_t<b_type> > &b,
const callable_type &fun,
signal_t *interruptor,
int64_t nap_before_retry_ms) THROWS_ONLY(interrupted_exc_t) {
a->assert_thread();
b->assert_thread();
bool is_done = false;
auto op = std::bind(&run_until_satisfied_2_apply_outer<a_type, b_type, callable_type>,
fun,
b,
std::placeholders::_1,
&is_done);
while (true) {
cond_t changed;
typename watchable_t<a_type>::subscription_t a_subs(boost::bind(&cond_t::pulse_if_not_already_pulsed, &changed));
typename watchable_t<b_type>::subscription_t b_subs(boost::bind(&cond_t::pulse_if_not_already_pulsed, &changed));
{
typename watchable_t<a_type>::freeze_t a_freeze(a);
typename watchable_t<b_type>::freeze_t b_freeze(b);
ASSERT_FINITE_CORO_WAITING;
a->apply_read(op);
if (is_done) {
return;
}
a_subs.reset(a, &a_freeze);
b_subs.reset(b, &b_freeze);
}
// Nap a little so changes to the watchables can accumulate.
// This is purely a performance optimization to save CPU cycles,
// in case that applying `fun` is expensive (which it is in our
// applications in the reactors as of 12/10/2013).
nap(nap_before_retry_ms, interruptor);
wait_interruptible(&changed, interruptor);
}
}
<commit_msg>Don't nap if nap time is 0.<commit_after>// Copyright 2010-2012 RethinkDB, all rights reserved.
#include "concurrency/watchable.hpp"
#include <functional>
#include "errors.hpp"
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include "arch/timing.hpp"
#include "concurrency/cond_var.hpp"
#include "concurrency/wait_any.hpp"
template <class result_type, class outer_type, class callable_type>
class subview_watchable_t : public watchable_t<result_type> {
public:
subview_watchable_t(const callable_type &l, watchable_t<outer_type> *p) :
cache(new lensed_value_cache_t(l, p)) { }
subview_watchable_t *clone() const {
return new subview_watchable_t(cache);
}
result_type get() {
return *cache->get();
}
virtual void apply_read(const std::function<void(const result_type*)> &read) {
ASSERT_NO_CORO_WAITING;
read(cache->get());
}
publisher_t<boost::function<void()> > *get_publisher() {
return cache->get_publisher();
}
rwi_lock_assertion_t *get_rwi_lock_assertion() {
return cache->parent->get_rwi_lock_assertion();
}
private:
// lensed_value_cache_t is a cache for the result of a lens applied to
// a given parent watchable. It is implemented for incremental lenses only.
// (`non_incremental_lens_wrapper_t` can be used to apply it to non-incremental
// lenses as well).
// The cached value is recomputed only after the parent has published a new
// value.
class lensed_value_cache_t : public home_thread_mixin_t {
public:
lensed_value_cache_t(const callable_type &l, watchable_t<outer_type> *p) :
parent(p->clone()),
lens(l),
parent_subscription(boost::bind(
&subview_watchable_t<result_type, outer_type, callable_type>::lensed_value_cache_t::on_parent_changed,
this)) {
typename watchable_t<outer_type>::freeze_t freeze(parent);
ASSERT_FINITE_CORO_WAITING;
compute_value();
parent_subscription.reset(parent, &freeze);
}
~lensed_value_cache_t() {
assert_thread();
}
const result_type *get() {
assert_thread();
return &cached_value;
}
publisher_t<boost::function<void()> > *get_publisher() {
assert_thread();
return publisher_controller.get_publisher();
}
clone_ptr_t<watchable_t<outer_type> > parent;
private:
bool compute_value() {
// The closure is to avoid copying the whole value from the parent.
bool value_changed = false;
struct op_closure_t {
static void apply(callable_type *_lens,
bool *_value_changed,
result_type *_cached_value,
const outer_type *val) {
*_value_changed = (*_lens)(*val, _cached_value);
}
};
parent->apply_read(std::bind(&op_closure_t::apply,
&lens,
&value_changed,
&cached_value,
std::placeholders::_1));
return value_changed;
}
void on_parent_changed() {
assert_thread();
const bool value_changed = compute_value();
if (value_changed) {
publisher_controller.publish(&call_function);
}
}
callable_type lens;
result_type cached_value;
publisher_controller_t<boost::function<void()> > publisher_controller;
typename watchable_t<outer_type>::subscription_t parent_subscription;
};
explicit subview_watchable_t(const boost::shared_ptr<lensed_value_cache_t> &_cache) :
cache(_cache) { }
// If you clone a subview_watchable_t, all clones share the same cache.
// As a consequence, the lens is only applied once for the whole family
// of clones, not once per instance of subview_watchable_t. This should save
// some CPU and memory as well.
boost::shared_ptr<lensed_value_cache_t> cache;
};
/* Given a non-incremental lens with the type signature
* `result_type(input_type)`, `non_incremental_lens_wrapper_t` converts
* it into an incremental lens with type signature
* `bool(const input_type &, result_type *)` and otherwise equivalent semantics
* (as much as possible). */
template<class outer_type, class callable_type>
class non_incremental_lens_wrapper_t {
public:
typedef typename boost::result_of<callable_type(outer_type)>::type result_type;
explicit non_incremental_lens_wrapper_t(const callable_type &_inner) :
inner(_inner) {
}
bool operator()(const outer_type &input, result_type *current_out) {
guarantee(current_out != NULL);
result_type old_value = *current_out;
*current_out = inner(input);
return old_value != *current_out;
}
private:
callable_type inner;
};
template<class value_type>
template<class callable_type>
clone_ptr_t<watchable_t<typename callable_type::result_type> > watchable_t<value_type>::incremental_subview(const callable_type &lens) {
assert_thread();
return clone_ptr_t<watchable_t<typename callable_type::result_type> >(
new subview_watchable_t<typename callable_type::result_type, value_type, callable_type>(lens, this));
}
template<class value_type>
template<class result_type, class callable_type>
clone_ptr_t<watchable_t<result_type> > watchable_t<value_type>::incremental_subview(const callable_type &lens) {
assert_thread();
return clone_ptr_t<watchable_t<result_type> >(
new subview_watchable_t<result_type, value_type, callable_type>(lens, this));
}
template<class value_type>
template<class callable_type>
clone_ptr_t<watchable_t<typename boost::result_of<callable_type(value_type)>::type> > watchable_t<value_type>::subview(const callable_type &lens) {
assert_thread();
typedef non_incremental_lens_wrapper_t<value_type, callable_type> wrapped_callable_type;
wrapped_callable_type wrapped_lens(lens);
return clone_ptr_t<watchable_t<typename wrapped_callable_type::result_type> >(
new subview_watchable_t<typename wrapped_callable_type::result_type, value_type, wrapped_callable_type>(wrapped_lens, this));
}
// These are helper functions for `run_until_satisfied()` and `run_until_satisfied_2()`
// that can be passed into a watchable's `apply_read()`. They simply apply the
// provided function `_fun` to the current value of the watchable(s) and pass out
// its boolean return value.
template<class value_type, class callable_type>
void run_until_satisfied_apply(const callable_type &_fun, const value_type *val,
bool *is_done_out) {
*is_done_out = _fun(*val);
}
template<class a_type, class b_type, class callable_type>
void run_until_satisfied_2_apply_inner(const callable_type &_fun,
const a_type *a_val, const b_type *b_val, bool *is_done_out) {
*is_done_out = _fun(*a_val, *b_val);
}
template<class a_type, class b_type, class callable_type>
void run_until_satisfied_2_apply_outer(const callable_type &_fun,
const clone_ptr_t<watchable_t<b_type> > &_b, const a_type *a_val,
bool *is_done_out) {
_b->apply_read(std::bind(
&run_until_satisfied_2_apply_inner<a_type, b_type, callable_type>, _fun, a_val,
std::placeholders::_1, is_done_out));
}
template<class value_type>
template<class callable_type>
void watchable_t<value_type>::run_until_satisfied(const callable_type &fun,
signal_t *interruptor, int64_t nap_before_retry_ms) THROWS_ONLY(interrupted_exc_t) {
assert_thread();
bool is_done = false;
auto op = std::bind(&run_until_satisfied_apply<value_type, callable_type>,
fun,
std::placeholders::_1,
&is_done);
clone_ptr_t<watchable_t<value_type> > clone_this(this->clone());
while (true) {
cond_t changed;
typename watchable_t<value_type>::subscription_t subs(boost::bind(&cond_t::pulse_if_not_already_pulsed, &changed));
{
typename watchable_t<value_type>::freeze_t freeze(clone_this);
ASSERT_FINITE_CORO_WAITING;
clone_this->apply_read(op);
if (is_done) {
return;
}
subs.reset(clone_this, &freeze);
}
// Nap a little so changes to the watchables can accumulate.
// This is purely a performance optimization to save CPU cycles,
// in case that applying `fun` is expensive.
if (nap_before_retry_ms > 0) {
nap(nap_before_retry_ms, interruptor);
}
wait_interruptible(&changed, interruptor);
}
}
template<class a_type, class b_type, class callable_type>
void run_until_satisfied_2(
const clone_ptr_t<watchable_t<a_type> > &a,
const clone_ptr_t<watchable_t<b_type> > &b,
const callable_type &fun,
signal_t *interruptor,
int64_t nap_before_retry_ms) THROWS_ONLY(interrupted_exc_t) {
a->assert_thread();
b->assert_thread();
bool is_done = false;
auto op = std::bind(&run_until_satisfied_2_apply_outer<a_type, b_type, callable_type>,
fun,
b,
std::placeholders::_1,
&is_done);
while (true) {
cond_t changed;
typename watchable_t<a_type>::subscription_t a_subs(boost::bind(&cond_t::pulse_if_not_already_pulsed, &changed));
typename watchable_t<b_type>::subscription_t b_subs(boost::bind(&cond_t::pulse_if_not_already_pulsed, &changed));
{
typename watchable_t<a_type>::freeze_t a_freeze(a);
typename watchable_t<b_type>::freeze_t b_freeze(b);
ASSERT_FINITE_CORO_WAITING;
a->apply_read(op);
if (is_done) {
return;
}
a_subs.reset(a, &a_freeze);
b_subs.reset(b, &b_freeze);
}
// Nap a little so changes to the watchables can accumulate.
// This is purely a performance optimization to save CPU cycles,
// in case that applying `fun` is expensive (which it is in our
// applications in the reactors as of 12/10/2013).
if (nap_before_retry_ms > 0) {
nap(nap_before_retry_ms, interruptor);
}
wait_interruptible(&changed, interruptor);
}
}
<|endoftext|>
|
<commit_before>#include "condor_common.h"
#include "condor_config.h"
#include "condor_api.h"
#include "status_types.h"
#include "totals.h"
// global variables
AttrListPrintMask pm;
char *pool = NULL;
AdTypes type = (AdTypes) -1;
ppOption ppStyle = PP_NOTSET;
int wantTotals = 0;
int summarySize = -1;
Mode mode = MODE_NOTSET;
int diagnose = 0;
CondorQuery *query;
char buffer[1024];
ClassAdList result;
Totals totals;
char *myName;
// function declarations
void usage ();
void firstPass (int, char *[]);
void secondPass (int, char *[]);
void prettyPrint(ClassAdList &);
int matchPrefix(char *, char *);
extern "C" int SetSyscalls (int) {return 0;}
extern void setPPstyle (ppOption, int, char *);
extern void setType (char *, int, char *);
extern void setMode (Mode, int, char *);
int
main (int argc, char *argv[])
{
// initialize to read from config file
myName = argv[0];
config ((ClassAd*)NULL);
// The arguments take two passes to process --- the first pass
// figures out the mode, after which we can instantiate the required
// query object. We add implied constraints from the command line in
// the second pass.
firstPass (argc, argv);
// if the mode has not been set, it is NORMAL
if (mode == MODE_NOTSET) {
setMode (MODE_NORMAL, 0, "<default>");
}
// instantiate query object
if (!(query = new CondorQuery (type))) {
fprintf (stderr, "Error: Out of memory\n");
exit (1);
}
// set the constraint implied by the mode
switch (mode) {
case MODE_NORMAL:
case MODE_CUSTOM:
break;
case MODE_AVAIL:
// **** Remeber to change to evaluating Requirements ****
if (diagnose) {
printf ("Adding constraint [%s]\n", "TARGET.START == True");
}
query->addConstraint ("TARGET.START == True");
break;
case MODE_SUBMITTORS:
sprintf (buffer,"TARGET.%s > 0 || TARGET.%s > 0", ATTR_IDLE_JOBS,
ATTR_RUNNING_JOBS);
if (diagnose) {
printf ("Adding constraint [%s]\n", buffer);
}
query->addConstraint (buffer);
break;
case MODE_RUN:
sprintf (buffer, "TARGET.%s != \"NoJob\"", ATTR_STATE);
if (diagnose) {
printf ("Adding constraint [%s]\n", buffer);
}
query->addConstraint (buffer);
break;
}
// second pass: add regular parameters and constraints
if (diagnose) {
printf ("----------\n");
}
secondPass (argc, argv);
// initialize the totals object
if (wantTotals && summarySize == -1) {
fprintf (stderr,"Error: Want totals, but no total support for mode\n");
exit (1);
}
totals.setSummarySize (summarySize);
// fetch the query
QueryResult q;
// if diagnose was requested, just print the query ad
if (diagnose) {
ClassAd queryAd;
// print diagnostic information about inferred internal state
setMode ((Mode) 0, 0, NULL);
setType (NULL, 0, NULL);
setPPstyle ((ppOption) 0, 0, NULL);
printf ("----------\n");
q = query->getQueryAd (queryAd);
queryAd.fPrint (stdout);
printf ("----------\n");
fprintf (stderr, "Result of making query ad was: %d\n", q);
exit (1);
}
if ((q = query->fetchAds (result, pool)) != Q_OK) {
fprintf (stderr, "Error: Could not fetch ads --- error %d\n", q);
exit (1);
}
// output result
prettyPrint (result);
// be nice ...
delete query;
return 0;
}
void
usage ()
{
fprintf (stderr,"Usage: %s [options]\n"
" where [options] are zero or more of\n"
"\t[-avail]\t\tPrint information about available resources\n"
"\t[-constraint <const>]\tAdd constraint on classads\n"
"\t[-diagnose]\t\tPrint out query ad without performing query\n"
"\t[-entity <type>]\tForce query on specified entity\n"
"\t[-format <fmt> <attr>]\tRegister display format and attribute\n"
"\t[-help]\t\t\tThis screen\n"
"\t[-long]\t\t\tDisplay entire classads\n"
"\t[-pool <poolname>]\tGet information from <poolname>\n"
"\t[-run]\t\t\tPrint information about employed resources\n"
"\t[-server]\t\tDisplay important attributes of resources\n"
"\t[-submittors]\t\tObtain information about submittors\n"
"\t[-total]\t\tDisplay totals only\n"
"\t[-verbose]\t\tSame as -long\n",
myName);
}
void
firstPass (int argc, char *argv[])
{
// Process arguments: there are dependencies between them
// o -l/v and -serv are mutually exclusive
// o -sub, -avail and -run are mutually exclusive
// o -pool and -entity may be used at most once
// o since -c can be processed only after the query has been instantiated,
// constraints are added on the second pass
for (int i = 1; i < argc; i++) {
if (matchPrefix (argv[i], "-avail")) {
setMode (MODE_AVAIL, i, argv[i]);
} else
if (matchPrefix (argv[i], "-pool")) {
if (pool == NULL) {
pool = argv[++i];
} else {
fprintf (stderr, "At most one -pool argument may be used\n");
exit (1);
}
} else
if (matchPrefix (argv[i], "-format")) {
setPPstyle (PP_CUSTOM, i, argv[i]);
pm.registerFormat (argv[i+1], argv[i+2]);
if (diagnose) {
printf ("Arg %d --- register format [%s] for [%s]\n",
i, argv[i+1], argv[i+2]);
}
i += 2;
} else
if (matchPrefix (argv[i], "-constraint")) {
// can add constraints on second pass only
i++;
} else
if (matchPrefix (argv[i], "-diagnose")) {
diagnose = 1;
} else
if (matchPrefix (argv[i], "-help")) {
usage ();
exit (1);
} else
if (matchPrefix (argv[i],"-long") || matchPrefix (argv[i],"-verbose")) {
setPPstyle (PP_VERBOSE, i, argv[i]);
} else
if (matchPrefix (argv[i], "-run")) {
setMode (MODE_RUN, i, argv[i]);
} else
if (matchPrefix (argv[i], "-server")) {
setPPstyle (PP_SERVER, i, argv[i]);
} else
if (matchPrefix (argv[i], "-submittors")) {
setMode (MODE_SUBMITTORS, i, argv[i]);
} else
if (matchPrefix (argv[i], "-total")) {
wantTotals = 1;
} else
if (matchPrefix (argv[i], "-entity")) {
setMode (MODE_CUSTOM, i, argv[i]);
setType (argv[i+1], i, argv[i]);
} else
if (*argv[i] == '-') {
fprintf (stderr, "Error: Unknown option %s\n", argv[i]);
usage ();
exit (1);
}
}
}
void
secondPass (int argc, char *argv[])
{
for (int i = 1; i < argc; i++) {
// omit parameters which qualify switches
if (matchPrefix (argv[i], "-pool")) {
i++;
continue;
}
if (matchPrefix (argv[i], "-entity")) {
i++;
continue;
}
if (matchPrefix (argv[i], "-format")) {
i += 2;
continue;
}
// figure out what the other parameters should do
if (*argv[i] != '-') {
// display extra information for diagnosis
if (diagnose) {
printf ("Arg %d (%s) --- adding constraint", i, argv[i]);
}
switch (mode) {
case MODE_NORMAL:
case MODE_AVAIL:
case MODE_SUBMITTORS:
sprintf (buffer, "TARGET.%s == \"%s\"", ATTR_NAME, argv[i]);
if (diagnose) {
printf ("[%s]\n", buffer);
}
query->addConstraint (buffer);
break;
case MODE_RUN:
sprintf (buffer,"TARGET.%s == \"%s\"",ATTR_REMOTE_USER,argv[i]);
if (diagnose) {
printf ("[%s]\n", buffer);
}
query->addConstraint (buffer);
break;
case MODE_CUSTOM:
if (diagnose) {
printf ("[%s]\n", buffer);
}
query->addConstraint (argv[i]);
break;
default:
fprintf(stderr,"Error: Don't know how to process %s\n",argv[i]);
}
} else
if (matchPrefix (argv[i], "-constraint")) {
if (diagnose) {
printf ("[%s]\n", argv[i+1]);
}
query->addConstraint (argv[i+1]);
i++;
}
}
}
int
matchPrefix (char *s1, char *s2)
{
int lenS1 = strlen (s1);
int lenS2 = strlen (s2);
int len = (lenS1 < lenS2) ? lenS1 : lenS2;
return (strncmp (s1, s2, len) == 0);
}
<commit_msg>Added a better error message on query failure. Also fixed bug with -pool option, which previously used the string "-pool" as the target collector instead of the option which followed it.<commit_after>#include "condor_common.h"
#include "condor_config.h"
#include "condor_api.h"
#include "status_types.h"
#include "totals.h"
// global variables
AttrListPrintMask pm;
char *pool = NULL;
AdTypes type = (AdTypes) -1;
ppOption ppStyle = PP_NOTSET;
int wantTotals = 0;
int summarySize = -1;
Mode mode = MODE_NOTSET;
int diagnose = 0;
CondorQuery *query;
char buffer[1024];
ClassAdList result;
Totals totals;
char *myName;
// function declarations
void usage ();
void firstPass (int, char *[]);
void secondPass (int, char *[]);
void prettyPrint(ClassAdList &);
int matchPrefix(char *, char *);
extern "C" int SetSyscalls (int) {return 0;}
extern void setPPstyle (ppOption, int, char *);
extern void setType (char *, int, char *);
extern void setMode (Mode, int, char *);
int
main (int argc, char *argv[])
{
// initialize to read from config file
myName = argv[0];
config ((ClassAd*)NULL);
// The arguments take two passes to process --- the first pass
// figures out the mode, after which we can instantiate the required
// query object. We add implied constraints from the command line in
// the second pass.
firstPass (argc, argv);
// if the mode has not been set, it is NORMAL
if (mode == MODE_NOTSET) {
setMode (MODE_NORMAL, 0, "<default>");
}
// instantiate query object
if (!(query = new CondorQuery (type))) {
fprintf (stderr, "Error: Out of memory\n");
exit (1);
}
// set the constraint implied by the mode
switch (mode) {
case MODE_NORMAL:
case MODE_CUSTOM:
break;
case MODE_AVAIL:
// **** Remeber to change to evaluating Requirements ****
if (diagnose) {
printf ("Adding constraint [%s]\n", "TARGET.START == True");
}
query->addConstraint ("TARGET.START == True");
break;
case MODE_SUBMITTORS:
sprintf (buffer,"TARGET.%s > 0 || TARGET.%s > 0", ATTR_IDLE_JOBS,
ATTR_RUNNING_JOBS);
if (diagnose) {
printf ("Adding constraint [%s]\n", buffer);
}
query->addConstraint (buffer);
break;
case MODE_RUN:
sprintf (buffer, "TARGET.%s != \"NoJob\"", ATTR_STATE);
if (diagnose) {
printf ("Adding constraint [%s]\n", buffer);
}
query->addConstraint (buffer);
break;
}
// second pass: add regular parameters and constraints
if (diagnose) {
printf ("----------\n");
}
secondPass (argc, argv);
// initialize the totals object
if (wantTotals && summarySize == -1) {
fprintf (stderr,"Error: Want totals, but no total support for mode\n");
exit (1);
}
totals.setSummarySize (summarySize);
// fetch the query
QueryResult q;
// if diagnose was requested, just print the query ad
if (diagnose) {
ClassAd queryAd;
// print diagnostic information about inferred internal state
setMode ((Mode) 0, 0, NULL);
setType (NULL, 0, NULL);
setPPstyle ((ppOption) 0, 0, NULL);
printf ("----------\n");
q = query->getQueryAd (queryAd);
queryAd.fPrint (stdout);
printf ("----------\n");
fprintf (stderr, "Result of making query ad was: %d\n", q);
exit (1);
}
if ((q = query->fetchAds (result, pool)) != Q_OK) {
fprintf (stderr, "Error: Could not fetch ads --- error %s\n",
StrQueryResult[q]);
exit (1);
}
// output result
prettyPrint (result);
// be nice ...
delete query;
return 0;
}
void
usage ()
{
fprintf (stderr,"Usage: %s [options]\n"
" where [options] are zero or more of\n"
"\t[-avail]\t\tPrint information about available resources\n"
"\t[-constraint <const>]\tAdd constraint on classads\n"
"\t[-diagnose]\t\tPrint out query ad without performing query\n"
"\t[-entity <type>]\tForce query on specified entity\n"
"\t[-format <fmt> <attr>]\tRegister display format and attribute\n"
"\t[-help]\t\t\tThis screen\n"
"\t[-long]\t\t\tDisplay entire classads\n"
"\t[-pool <poolname>]\tGet information from <poolname>\n"
"\t[-run]\t\t\tPrint information about employed resources\n"
"\t[-server]\t\tDisplay important attributes of resources\n"
"\t[-submittors]\t\tObtain information about submittors\n"
"\t[-total]\t\tDisplay totals only\n"
"\t[-verbose]\t\tSame as -long\n",
myName);
}
void
firstPass (int argc, char *argv[])
{
// Process arguments: there are dependencies between them
// o -l/v and -serv are mutually exclusive
// o -sub, -avail and -run are mutually exclusive
// o -pool and -entity may be used at most once
// o since -c can be processed only after the query has been instantiated,
// constraints are added on the second pass
for (int i = 1; i < argc; i++) {
if (matchPrefix (argv[i], "-avail")) {
setMode (MODE_AVAIL, i, argv[i]);
} else
if (matchPrefix (argv[i], "-pool")) {
if (pool == NULL) {
pool = argv[++i];
} else {
fprintf (stderr, "At most one -pool argument may be used\n");
exit (1);
}
} else
if (matchPrefix (argv[i], "-format")) {
setPPstyle (PP_CUSTOM, i, argv[i]);
pm.registerFormat (argv[i+1], argv[i+2]);
if (diagnose) {
printf ("Arg %d --- register format [%s] for [%s]\n",
i, argv[i+1], argv[i+2]);
}
i += 2;
} else
if (matchPrefix (argv[i], "-constraint")) {
// can add constraints on second pass only
i++;
} else
if (matchPrefix (argv[i], "-diagnose")) {
diagnose = 1;
} else
if (matchPrefix (argv[i], "-help")) {
usage ();
exit (1);
} else
if (matchPrefix (argv[i],"-long") || matchPrefix (argv[i],"-verbose")) {
setPPstyle (PP_VERBOSE, i, argv[i]);
} else
if (matchPrefix (argv[i], "-run")) {
setMode (MODE_RUN, i, argv[i]);
} else
if (matchPrefix (argv[i], "-server")) {
setPPstyle (PP_SERVER, i, argv[i]);
} else
if (matchPrefix (argv[i], "-submittors")) {
setMode (MODE_SUBMITTORS, i, argv[i]);
} else
if (matchPrefix (argv[i], "-total")) {
wantTotals = 1;
} else
if (matchPrefix (argv[i], "-entity")) {
setMode (MODE_CUSTOM, i, argv[i]);
setType (argv[i+1], i, argv[i]);
} else
if (*argv[i] == '-') {
fprintf (stderr, "Error: Unknown option %s\n", argv[i]);
usage ();
exit (1);
}
}
}
void
secondPass (int argc, char *argv[])
{
for (int i = 1; i < argc; i++) {
// omit parameters which qualify switches
if (matchPrefix (argv[i], "-pool")) {
i++;
continue;
}
if (matchPrefix (argv[i], "-entity")) {
i++;
continue;
}
if (matchPrefix (argv[i], "-format")) {
i += 2;
continue;
}
// figure out what the other parameters should do
if (*argv[i] != '-') {
// display extra information for diagnosis
if (diagnose) {
printf ("Arg %d (%s) --- adding constraint", i, argv[i]);
}
switch (mode) {
case MODE_NORMAL:
case MODE_AVAIL:
case MODE_SUBMITTORS:
sprintf (buffer, "TARGET.%s == \"%s\"", ATTR_NAME, argv[i]);
if (diagnose) {
printf ("[%s]\n", buffer);
}
query->addConstraint (buffer);
break;
case MODE_RUN:
sprintf (buffer,"TARGET.%s == \"%s\"",ATTR_REMOTE_USER,argv[i]);
if (diagnose) {
printf ("[%s]\n", buffer);
}
query->addConstraint (buffer);
break;
case MODE_CUSTOM:
if (diagnose) {
printf ("[%s]\n", buffer);
}
query->addConstraint (argv[i]);
break;
default:
fprintf(stderr,"Error: Don't know how to process %s\n",argv[i]);
}
} else
if (matchPrefix (argv[i], "-constraint")) {
if (diagnose) {
printf ("[%s]\n", argv[i+1]);
}
query->addConstraint (argv[i+1]);
i++;
}
}
}
int
matchPrefix (char *s1, char *s2)
{
int lenS1 = strlen (s1);
int lenS2 = strlen (s2);
int len = (lenS1 < lenS2) ? lenS1 : lenS2;
return (strncmp (s1, s2, len) == 0);
}
<|endoftext|>
|
<commit_before><commit_msg>Create 1190 - Right Area.cpp<commit_after><|endoftext|>
|
<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "flusspferd/io/io.hpp"
#include "flusspferd/io/file_class.hpp"
#include "flusspferd/io/blob_stream.hpp"
#include "flusspferd/local_root_scope.hpp"
#include "flusspferd/class.hpp"
#include <iostream>
using namespace flusspferd;
using namespace flusspferd::io;
object flusspferd::io::load_io(object container) {
local_root_scope scope;
value previous = container.get_property("IO");
if (previous.is_object())
return previous.to_object();
object IO = get_current_context().get_constructor("IO");
if (!IO.is_valid()) {
IO = flusspferd::create_object();
load_class<stream_base>(IO);
load_class<file_class>(IO);
load_class<blob_stream>(IO);
IO.define_property(
"stdout",
create_native_object<stream_base>(object(), std::cout.rdbuf()));
IO.define_property(
"stderr",
create_native_object<stream_base>(object(), std::cerr.rdbuf()));
IO.define_property(
"stdin",
create_native_object<stream_base>(object(), std::cin.rdbuf()));
get_current_context().add_constructor("IO", IO);
}
container.define_property(
"IO",
IO,
object::read_only_property | object::dont_enumerate);
return IO;
}
<commit_msg>IO: make IO a real plugin<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "flusspferd/io/io.hpp"
#include "flusspferd/io/file_class.hpp"
#include "flusspferd/io/blob_stream.hpp"
#include "flusspferd/local_root_scope.hpp"
#include "flusspferd/class.hpp"
#include <iostream>
using namespace flusspferd;
using namespace flusspferd::io;
extern "C" value flusspferd_load(object container)
{
return load_io(container);
}
object flusspferd::io::load_io(object container) {
local_root_scope scope;
value previous = container.get_property("IO");
if (previous.is_object())
return previous.to_object();
object IO = get_current_context().get_constructor("IO");
if (!IO.is_valid()) {
IO = flusspferd::create_object();
load_class<stream_base>(IO);
load_class<file_class>(IO);
load_class<blob_stream>(IO);
IO.define_property(
"stdout",
create_native_object<stream_base>(object(), std::cout.rdbuf()));
IO.define_property(
"stderr",
create_native_object<stream_base>(object(), std::cerr.rdbuf()));
IO.define_property(
"stdin",
create_native_object<stream_base>(object(), std::cin.rdbuf()));
get_current_context().add_constructor("IO", IO);
}
container.define_property(
"IO",
IO,
object::read_only_property | object::dont_enumerate);
return IO;
}
<|endoftext|>
|
<commit_before>#pragma once
#include <unordered_map>
#include "common.hpp"
#include "components/logger.hpp"
#include "errors.hpp"
#include "utils/env.hpp"
#include "utils/string.hpp"
#include "x11/xresources.hpp"
POLYBAR_NS
#define GET_CONFIG_VALUE(section, var, name) var = m_conf.get<decltype(var)>(section, name, var)
#define REQ_CONFIG_VALUE(section, var, name) var = m_conf.get<decltype(var)>(section, name)
#define DEPR_CONFIG_VALUE(section, var, old, name) var = m_conf.deprecated<decltype(var)>(section, old, name, var)
DEFINE_ERROR(value_error);
DEFINE_ERROR(key_error);
class config {
public:
using valuemap_t = std::unordered_map<string, string>;
using sectionmap_t = std::unordered_map<string, valuemap_t>;
using make_type = const config&;
static make_type make(string path = "", string bar = "");
explicit config(const logger& logger, const xresource_manager& xrm, string&& path = "", string&& bar = "");
string filepath() const;
string section() const;
void warn_deprecated(const string& section, const string& key, string replacement) const;
/**
* Returns true if a given parameter exists
*/
bool has(const string& section, const string& key) const {
auto it = m_sections.find(section);
return it != m_sections.end() && it->second.find(key) != it->second.end();
}
/**
* Get parameter for the current bar by name
*/
template <typename T>
T get(const string& key) const {
return get<T>(section(), key);
}
/**
* Get value of a variable by section and parameter name
*/
template <typename T>
T get(const string& section, const string& key) const {
auto it = m_sections.find(section);
if (it == m_sections.end() || it->second.find(key) == it->second.end()) {
throw key_error("Missing parameter [" + section + "." + key + "]");
}
return dereference<T>(section, key, it->second.at(key), convert<T>(string{it->second.at(key)}));
}
/**
* Get value of a variable by section and parameter name
* with a default value in case the parameter isn't defined
*/
template <typename T>
T get(const string& section, const string& key, const T& default_value) const {
try {
T result{get<T>(section, key)};
string string_value{get<string>(section, key)};
return dereference<T>(move(section), move(key), move(string_value), move(result));
} catch (const key_error& err) {
return default_value;
}
}
/**
* Get list of values for the current bar by name
*/
template <typename T>
vector<T> get_list(const string& key) const {
return get_list<T>(section(), key);
}
/**
* Get list of values by section and parameter name
*/
template <typename T>
vector<T> get_list(const string& section, const string& key) const {
vector<T> results;
while (true) {
try {
string string_value{get<string>(section, key + "-" + to_string(results.size()))};
T value{get<T>(section, key + "-" + to_string(results.size()))};
if (!string_value.empty()) {
results.emplace_back(dereference<T>(section, key, move(string_value), move(value)));
} else {
results.emplace_back(move(value));
}
} catch (const key_error& err) {
break;
}
}
if (results.empty()) {
throw key_error("Missing parameter [" + section + "." + key + "-0]");
}
return results;
}
/**
* Get list of values by section and parameter name
* with a default list in case the list isn't defined
*/
template <typename T>
vector<T> get_list(const string& section, const string& key, const vector<T>& default_value) const {
vector<T> results;
while (true) {
try {
string string_value{get<string>(section, key + "-" + to_string(results.size()))};
T value{get<T>(section, key + "-" + to_string(results.size()))};
if (!string_value.empty()) {
results.emplace_back(dereference<T>(section, key, move(string_value), move(value)));
} else {
results.emplace_back(move(value));
}
} catch (const key_error& err) {
break;
}
}
if (!results.empty()) {
return results;
;
}
return default_value;
}
/**
* Attempt to load value using the deprecated key name. If successful show a
* warning message. If it fails load the value using the new key and given
* fallback value
*/
template <typename T>
T deprecated(const string& section, const string& old, const string& newkey, const T& fallback) const {
try {
T value{get<T>(section, old)};
warn_deprecated(section, old, newkey);
return value;
} catch (const key_error& err) {
return get<T>(section, newkey, fallback);
}
}
/**
* @see deprecated<T>
*/
template <typename T>
T deprecated_list(const string& section, const string& old, const string& newkey, const vector<T>& fallback) const {
try {
vector<T> value{get_list<T>(section, old)};
warn_deprecated(section, old, newkey);
return value;
} catch (const key_error& err) {
return get_list<T>(section, newkey, fallback);
}
}
protected:
void parse_file();
void copy_inherited();
template <typename T>
T convert(string&& value) const;
/**
* Dereference value reference
*/
template <typename T>
T dereference(const string& section, const string& key, const string& var, const T& fallback) const {
if (var.substr(0, 2) != "${" || var.substr(var.length() - 1) != "}") {
return fallback;
}
auto path = var.substr(2, var.length() - 3);
size_t pos;
if (path.compare(0, 4, "env:") == 0) {
return dereference_env<T>(path.substr(4), fallback);
} else if (path.compare(0, 5, "xrdb:") == 0) {
return dereference_xrdb<T>(path.substr(5), fallback);
} else if ((pos = path.find(".")) != string::npos) {
return dereference_local<T>(path.substr(0, pos), path.substr(pos + 1), section);
} else {
throw value_error("Invalid reference defined at [" + section + "." + key + "]");
}
}
/**
* Dereference local value reference defined using:
* ${root.key}
* ${self.key}
* ${section.key}
*/
template <typename T>
T dereference_local(string section, const string& key, const string& current_section) const {
if (section == "BAR") {
m_log.warn("${BAR.key} is deprecated. Use ${root.key} instead");
}
section = string_util::replace(section, "BAR", this->section(), 0, 3);
section = string_util::replace(section, "root", this->section(), 0, 4);
section = string_util::replace(section, "self", current_section, 0, 4);
try {
T result{get<T>(section, key)};
return dereference<T>(string(section), move(key), get<string>(section, key), move(result));
} catch (const key_error& err) {
throw value_error("Unexisting reference defined [" + section + "." + key + "]");
}
}
/**
* Dereference environment variable reference defined using:
* ${env:key}
* ${env:key:fallback value}
*/
template <typename T>
T dereference_env(string var, const T&) const {
size_t pos;
string env_default{""};
if ((pos = var.find(":")) != string::npos) {
env_default = var.substr(pos + 1);
var.erase(pos);
}
if (env_util::has(var.c_str())) {
string env_value{env_util::get(var.c_str())};
m_log.info("Found matching environment variable ${" + var + "} with the value \"" + env_value + "\"");
return convert<T>(move(env_value));
} else if (!env_default.empty()) {
m_log.info("The environment variable ${" + var + "} is undefined or empty, using defined fallback value \"" +
env_default + "\"");
} else {
m_log.info("The environment variable ${" + var + "} is undefined or empty");
}
return convert<T>(move(env_default));
}
/**
* Dereference X resource db value defined using:
* ${xrdb:key}
* ${xrdb:key:fallback value}
*/
template <typename T>
T dereference_xrdb(string var, const T& fallback) const {
size_t pos;
if ((pos = var.find(":")) != string::npos) {
return convert<T>(m_xrm.get_string(var.substr(0, pos), var.substr(pos + 1)));
}
string str{m_xrm.get_string(var, "")};
return str.empty() ? fallback : convert<T>(move(str));
}
private:
static constexpr const char* KEY_INHERIT{"inherit"};
const logger& m_log;
const xresource_manager& m_xrm;
string m_file;
string m_barname;
sectionmap_t m_sections{};
};
POLYBAR_NS_END
<commit_msg>fix(config): Avoid double value lookup<commit_after>#pragma once
#include <unordered_map>
#include "common.hpp"
#include "components/logger.hpp"
#include "errors.hpp"
#include "utils/env.hpp"
#include "utils/string.hpp"
#include "x11/xresources.hpp"
POLYBAR_NS
#define GET_CONFIG_VALUE(section, var, name) var = m_conf.get<decltype(var)>(section, name, var)
#define REQ_CONFIG_VALUE(section, var, name) var = m_conf.get<decltype(var)>(section, name)
#define DEPR_CONFIG_VALUE(section, var, old, name) var = m_conf.deprecated<decltype(var)>(section, old, name, var)
DEFINE_ERROR(value_error);
DEFINE_ERROR(key_error);
class config {
public:
using valuemap_t = std::unordered_map<string, string>;
using sectionmap_t = std::unordered_map<string, valuemap_t>;
using make_type = const config&;
static make_type make(string path = "", string bar = "");
explicit config(const logger& logger, const xresource_manager& xrm, string&& path = "", string&& bar = "");
string filepath() const;
string section() const;
void warn_deprecated(const string& section, const string& key, string replacement) const;
/**
* Returns true if a given parameter exists
*/
bool has(const string& section, const string& key) const {
auto it = m_sections.find(section);
return it != m_sections.end() && it->second.find(key) != it->second.end();
}
/**
* Get parameter for the current bar by name
*/
template <typename T>
T get(const string& key) const {
return get<T>(section(), key);
}
/**
* Get value of a variable by section and parameter name
*/
template <typename T>
T get(const string& section, const string& key) const {
auto it = m_sections.find(section);
if (it == m_sections.end() || it->second.find(key) == it->second.end()) {
throw key_error("Missing parameter [" + section + "." + key + "]");
}
return dereference<T>(section, key, it->second.at(key), convert<T>(string{it->second.at(key)}));
}
/**
* Get value of a variable by section and parameter name
* with a default value in case the parameter isn't defined
*/
template <typename T>
T get(const string& section, const string& key, const T& default_value) const {
try {
string string_value{get<string>(section, key)};
T result{convert<T>(string{string_value})};
return dereference<T>(move(section), move(key), move(string_value), move(result));
} catch (const key_error& err) {
return default_value;
}
}
/**
* Get list of values for the current bar by name
*/
template <typename T>
vector<T> get_list(const string& key) const {
return get_list<T>(section(), key);
}
/**
* Get list of values by section and parameter name
*/
template <typename T>
vector<T> get_list(const string& section, const string& key) const {
vector<T> results;
while (true) {
try {
string string_value{get<string>(section, key + "-" + to_string(results.size()))};
T value{convert<T>(string{string_value})};
if (!string_value.empty()) {
results.emplace_back(dereference<T>(section, key, move(string_value), move(value)));
} else {
results.emplace_back(move(value));
}
} catch (const key_error& err) {
break;
}
}
if (results.empty()) {
throw key_error("Missing parameter [" + section + "." + key + "-0]");
}
return results;
}
/**
* Get list of values by section and parameter name
* with a default list in case the list isn't defined
*/
template <typename T>
vector<T> get_list(const string& section, const string& key, const vector<T>& default_value) const {
vector<T> results;
while (true) {
try {
string string_value{get<string>(section, key + "-" + to_string(results.size()))};
T value{convert<T>(string{string_value})};
if (!string_value.empty()) {
results.emplace_back(dereference<T>(section, key, move(string_value), move(value)));
} else {
results.emplace_back(move(value));
}
} catch (const key_error& err) {
break;
}
}
if (!results.empty()) {
return results;
;
}
return default_value;
}
/**
* Attempt to load value using the deprecated key name. If successful show a
* warning message. If it fails load the value using the new key and given
* fallback value
*/
template <typename T>
T deprecated(const string& section, const string& old, const string& newkey, const T& fallback) const {
try {
T value{get<T>(section, old)};
warn_deprecated(section, old, newkey);
return value;
} catch (const key_error& err) {
return get<T>(section, newkey, fallback);
}
}
/**
* @see deprecated<T>
*/
template <typename T>
T deprecated_list(const string& section, const string& old, const string& newkey, const vector<T>& fallback) const {
try {
vector<T> value{get_list<T>(section, old)};
warn_deprecated(section, old, newkey);
return value;
} catch (const key_error& err) {
return get_list<T>(section, newkey, fallback);
}
}
protected:
void parse_file();
void copy_inherited();
template <typename T>
T convert(string&& value) const;
/**
* Dereference value reference
*/
template <typename T>
T dereference(const string& section, const string& key, const string& var, const T& fallback) const {
if (var.substr(0, 2) != "${" || var.substr(var.length() - 1) != "}") {
return fallback;
}
auto path = var.substr(2, var.length() - 3);
size_t pos;
if (path.compare(0, 4, "env:") == 0) {
return dereference_env<T>(path.substr(4), fallback);
} else if (path.compare(0, 5, "xrdb:") == 0) {
return dereference_xrdb<T>(path.substr(5), fallback);
} else if ((pos = path.find(".")) != string::npos) {
return dereference_local<T>(path.substr(0, pos), path.substr(pos + 1), section);
} else {
throw value_error("Invalid reference defined at [" + section + "." + key + "]");
}
}
/**
* Dereference local value reference defined using:
* ${root.key}
* ${self.key}
* ${section.key}
*/
template <typename T>
T dereference_local(string section, const string& key, const string& current_section) const {
if (section == "BAR") {
m_log.warn("${BAR.key} is deprecated. Use ${root.key} instead");
}
section = string_util::replace(section, "BAR", this->section(), 0, 3);
section = string_util::replace(section, "root", this->section(), 0, 4);
section = string_util::replace(section, "self", current_section, 0, 4);
try {
string string_value{get<string>(section, key)};
T result{convert<T>(string{string_value})};
return dereference<T>(string(section), move(key), move(string_value), move(result));
} catch (const key_error& err) {
throw value_error("Unexisting reference defined [" + section + "." + key + "]");
}
}
/**
* Dereference environment variable reference defined using:
* ${env:key}
* ${env:key:fallback value}
*/
template <typename T>
T dereference_env(string var, const T&) const {
size_t pos;
string env_default{""};
if ((pos = var.find(":")) != string::npos) {
env_default = var.substr(pos + 1);
var.erase(pos);
}
if (env_util::has(var.c_str())) {
string env_value{env_util::get(var.c_str())};
m_log.info("Found matching environment variable ${" + var + "} with the value \"" + env_value + "\"");
return convert<T>(move(env_value));
} else if (!env_default.empty()) {
m_log.info("The environment variable ${" + var + "} is undefined or empty, using defined fallback value \"" +
env_default + "\"");
} else {
m_log.info("The environment variable ${" + var + "} is undefined or empty");
}
return convert<T>(move(env_default));
}
/**
* Dereference X resource db value defined using:
* ${xrdb:key}
* ${xrdb:key:fallback value}
*/
template <typename T>
T dereference_xrdb(string var, const T& fallback) const {
size_t pos;
if ((pos = var.find(":")) != string::npos) {
return convert<T>(m_xrm.get_string(var.substr(0, pos), var.substr(pos + 1)));
}
string str{m_xrm.get_string(var, "")};
return str.empty() ? fallback : convert<T>(move(str));
}
private:
static constexpr const char* KEY_INHERIT{"inherit"};
const logger& m_log;
const xresource_manager& m_xrm;
string m_file;
string m_barname;
sectionmap_t m_sections{};
};
POLYBAR_NS_END
<|endoftext|>
|
<commit_before>// Time: O(n + p)
// Space: O(p)
class Solution {
public:
bool areSentencesSimilarTwo(vector<string>& words1, vector<string>& words2, vector<pair<string, string>> pairs) {
if (words1.size() != words2.size()) {
return false;
}
unordered_map<string, int> lookup;
UnionFind union_find(2 * pairs.size());
for (const auto& pair : pairs) {
if (!lookup.count(pair.first)) {
lookup[pair.first] = lookup.size() - 1;
}
if (!lookup.count(pair.second)) {
lookup[pair.second] = lookup.size() - 1;
}
union_find.union_set(lookup[pair.first], lookup[pair.second]);
}
for (int i = 0; i < words1.size(); ++i) {
if (words1[i] != words2[i] &&
(!lookup.count(words1[i]) || !lookup.count(words2[i]) ||
union_find.find_set(lookup[words1[i]]) !=
union_find.find_set(lookup[words2[i]]))) {
return false;
}
}
return true;
}
private:
class UnionFind {
public:
UnionFind(const int n) : set_(n) {
iota(set_.begin(), set_.end(), 0);
}
int find_set(const int x) {
if (set_[x] != x) {
set_[x] = find_set(set_[x]); // Path compression.
}
return set_[x];
}
bool union_set(const int x, const int y) {
int x_root = find_set(x), y_root = find_set(y);
if (x_root == y_root) {
return false;
}
set_[min(x_root, y_root)] = max(x_root, y_root);
return true;
}
private:
vector<int> set_;
};
};
<commit_msg>Update sentence-similarity-ii.cpp<commit_after>// Time: O(n + p)
// Space: O(p)
class Solution {
public:
bool areSentencesSimilarTwo(vector<string>& words1, vector<string>& words2, vector<pair<string, string>> pairs) {
if (words1.size() != words2.size()) {
return false;
}
unordered_map<string, int> lookup;
UnionFind union_find(2 * pairs.size());
for (const auto& pair : pairs) {
if (!lookup.count(pair.first)) {
lookup.emplace(pair.first, lookup.size());
}
if (!lookup.count(pair.second)) {
lookup.emplace(pair.second, lookup.size());
}
union_find.union_set(lookup[pair.first], lookup[pair.second]);
}
for (int i = 0; i < words1.size(); ++i) {
if (words1[i] != words2[i] &&
(!lookup.count(words1[i]) || !lookup.count(words2[i]) ||
union_find.find_set(lookup[words1[i]]) !=
union_find.find_set(lookup[words2[i]]))) {
return false;
}
}
return true;
}
private:
class UnionFind {
public:
UnionFind(const int n) : set_(n) {
iota(set_.begin(), set_.end(), 0);
}
int find_set(const int x) {
if (set_[x] != x) {
set_[x] = find_set(set_[x]); // Path compression.
}
return set_[x];
}
bool union_set(const int x, const int y) {
int x_root = find_set(x), y_root = find_set(y);
if (x_root == y_root) {
return false;
}
set_[min(x_root, y_root)] = max(x_root, y_root);
return true;
}
private:
vector<int> set_;
};
};
<|endoftext|>
|
<commit_before>#include "Networking.hpp"
#include <time.h>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <stdio.h>
#include <chrono>
#include <thread>
#include <mutex>
std::mutex coutMutex;
std::string serializeMapSize(const hlt::Map & map) {
std::string returnString = "";
std::ostringstream oss;
oss << map.map_width << ' ' << map.map_height << ' ';
returnString = oss.str();
return returnString;
}
std::string serializeProductions(const hlt::Map & map) {
std::string returnString = "";
std::ostringstream oss;
for(auto a = map.contents.begin(); a != map.contents.end(); a++) {
for(auto b = a->begin(); b != a->end(); b++) {
oss << (unsigned short)(b->production) << ' ';
}
}
returnString = oss.str();
return returnString;
}
std::string Networking::serializeMap(const hlt::Map & map) {
std::string returnString = "";
std::ostringstream oss;
//Run-length encode of owners
unsigned short currentOwner = map.contents[0][0].owner;
unsigned short counter = 0;
for(int a = 0; a < map.contents.size(); ++a) {
for(int b = 0; b < map.contents[a].size(); ++b) {
if (map.contents[a][b].owner == currentOwner) {
counter++;
}
else {
oss << (unsigned short)counter << ' ' << (unsigned short)currentOwner << ' ';
counter = 1;
currentOwner = map.contents[a][b].owner;
}
}
}
//Place the last run into the string
oss << (unsigned short)counter << ' ' << (unsigned short)currentOwner << ' ';
//Encoding of ages
for(int a = 0; a < map.contents.size(); ++a) {
for(int b = 0; b < map.contents[a].size(); ++b) {
oss << (unsigned short)map.contents[a][b].strength << ' ';
}
}
returnString = oss.str();
return returnString;
}
std::set<hlt::Move> Networking::deserializeMoveSet(std::string & inputString) {
std::set<hlt::Move> moves = std::set<hlt::Move>();
std::stringstream iss(inputString);
hlt::Location l;
int d;
while (iss >> l.x >> l.y >> d) moves.insert({ l, (unsigned char)d });
return moves;
}
void Networking::sendString(unsigned char playerTag, std::string &sendString) {
//End message with newline character
sendString += '\n';
#ifdef _WIN32
WinConnection connection = connections[playerTag - 1];
DWORD charsWritten;
bool success;
success = WriteFile(connection.write, sendString.c_str(), sendString.length(), &charsWritten, NULL);
if (!success || charsWritten == 0) {
if(!program_output_style) std::cout << "Problem writing to pipe\n";
throw 1;
}
#else
UniConnection connection = connections[playerTag - 1];
ssize_t charsWritten = write(connection.write, sendString.c_str(), sendString.length());
if(charsWritten < sendString.length()) {
if(!program_output_style) std::cout << "Problem writing to pipe\n";
throw 1;
}
#endif
}
std::string Networking::getString(unsigned char playerTag, unsigned int timeoutMillis) {
srand(time(NULL));
std::string newString;
#ifdef _WIN32
WinConnection connection = connections[playerTag - 1];
DWORD charsRead;
bool success;
char buffer;
//Keep reading char by char until a newline
while (true) {
//Check to see that there are bytes in the pipe before reading
//Throw error if no bytes in alloted time
//Check for bytes before sampling clock, because reduces latency (vast majority the pipe is alread full)
DWORD bytesAvailable = 0;
PeekNamedPipe(connection.read, NULL, 0, NULL, &bytesAvailable, NULL);
if (bytesAvailable < 1) {
clock_t initialTime = clock();
while (bytesAvailable < 1) {
if (((clock() - initialTime) * 1000 / CLOCKS_PER_SEC) > timeoutMillis) throw 1;
PeekNamedPipe(connection.read, NULL, 0, NULL, &bytesAvailable, NULL);
}
}
success = ReadFile(connection.read, &buffer, 1, &charsRead, NULL);
if (!success || charsRead < 1) {
if(!program_output_style) std::cout << "Pipe probably timed out\n";
throw 1;
}
if (buffer == '\n') break;
else newString += buffer;
}
#else
UniConnection connection = connections[playerTag - 1];
fd_set set;
FD_ZERO(&set); /* clear the set */
FD_SET(connection.read, &set); /* add our file descriptor to the set */
struct timeval timeout;
timeout.tv_sec = timeoutMillis / 1000.0;
timeout.tv_usec = (timeoutMillis % 1000)*1000;
char buffer;
//Keep reading char by char until a newline
while(true) {
//Check if there are bytes in the pipe
int selectionResult = select(connection.read+1, &set, NULL, NULL, &timeout);
if(selectionResult > 0) {
read(connection.read, &buffer, 1);
if (buffer == '\n') break;
else newString += buffer;
} else {
if(!program_output_style) {
// Buffer error message output
// If a bunch of bots fail at onces, we dont want to be writing to cout at the same time
// That looks really weird
std::string errorMessage = "";
errorMessage += std::string("Unix bot timeout or error ") + std::to_string(selectionResult) + std::string("\n");
playerLogs[playerTag-1].push_back(newString);
errorMessage += "#---------ALL OF THE OUTPUT OF THE BOT THAT TIMED OUT----------#\n";
for(auto stringIter = playerLogs[playerTag-1].begin(); stringIter != playerLogs[playerTag-1].end(); stringIter++) {
while(stringIter->size() < 60) stringIter->push_back(' ');
errorMessage += "# " + *stringIter + " #\n";
}
errorMessage += "#--------------------------------------------------------------#\n";
std::lock_guard<std::mutex> guard(coutMutex);
std::cout << errorMessage;
}
throw 1;
}
}
#endif
//Python turns \n into \r\n
if (newString.at(newString.size() - 1) == '\r') newString.pop_back();
playerLogs[playerTag-1].push_back(newString);
return newString;
}
void Networking::startAndConnectBot(std::string command) {
#ifdef _WIN32
command = "/C " + command;
WinConnection parentConnection, childConnection;
SECURITY_ATTRIBUTES saAttr;
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
//Child stdout pipe
if (!CreatePipe(&parentConnection.read, &childConnection.write, &saAttr, 0)) {
if(!program_output_style) std::cout << "Could not create pipe\n";
throw 1;
}
if (!SetHandleInformation(parentConnection.read, HANDLE_FLAG_INHERIT, 0)) throw 1;
//Child stdin pipe
if (!CreatePipe(&childConnection.read, &parentConnection.write, &saAttr, 0)) {
if(!program_output_style) std::cout << "Could not create pipe\n";
throw 1;
}
if (!SetHandleInformation(parentConnection.write, HANDLE_FLAG_INHERIT, 0)) throw 1;
//MAKE SURE THIS MEMORY IS ERASED
PROCESS_INFORMATION piProcInfo;
ZeroMemory(&piProcInfo, sizeof(PROCESS_INFORMATION));
STARTUPINFO siStartInfo;
ZeroMemory(&siStartInfo, sizeof(STARTUPINFO));
siStartInfo.cb = sizeof(STARTUPINFO);
siStartInfo.hStdError = childConnection.write;
siStartInfo.hStdOutput = childConnection.write;
siStartInfo.hStdInput = childConnection.read;
siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
//C:/xampp/htdocs/Halite/Halite/Debug/ExampleBot.exe
//C:/Users/Michael/Anaconda3/python.exe
//C:/Program Files/Java/jre7/bin/java.exe -cp C:/xampp/htdocs/Halite/AIResources/Java MyBot
bool success = CreateProcess(
"C:\\windows\\system32\\cmd.exe",
LPSTR(command.c_str()), //command line
NULL, //process security attributes
NULL, //primary thread security attributes
TRUE, //handles are inherited
0, //creation flags
NULL, //use parent's environment
NULL, //use parent's current directory
&siStartInfo, //STARTUPINFO pointer
&piProcInfo
); //receives PROCESS_INFORMATION
if(!success) {
if(!program_output_style) std::cout << "Could not start process\n";
throw 1;
}
else {
CloseHandle(piProcInfo.hProcess);
CloseHandle(piProcInfo.hThread);
processes.push_back(piProcInfo.hProcess);
connections.push_back(parentConnection);
}
#else
if(!program_output_style) std::cout << command << "\n";
pid_t pid = NULL;
int writePipe[2];
int readPipe[2];
if(pipe(writePipe)) {
if(!program_output_style) std::cout << "Error creating pipe\n";
throw 1;
}
if(pipe(readPipe)) {
if(!program_output_style) std::cout << "Error creating pipe\n";
throw 1;
}
//Fork a child process
pid = fork();
if(pid == 0) { //This is the child
dup2(writePipe[0], STDIN_FILENO);
dup2(readPipe[1], STDOUT_FILENO);
dup2(readPipe[1], STDERR_FILENO);
execl("/bin/sh", "sh", "-c", command.c_str(), (char*) NULL);
//Nothing past the execl should be run
exit(1);
} else if(pid < 0) {
if(!program_output_style) std::cout << "Fork failed\n";
throw 1;
}
UniConnection connection;
connection.read = readPipe[0];
connection.write = writePipe[1];
connections.push_back(connection);
processes.push_back(pid);
#endif
playerLogs.push_back(std::vector<std::string>(0));
}
bool Networking::handleInitNetworking(unsigned int timeoutMillis, unsigned char playerTag, const hlt::Map & m, std::string * playerName) {
try{
std::string playerTagString = std::to_string(playerTag), mapSizeString = serializeMapSize(m), mapString = serializeMap(m), prodString = serializeProductions(m);
sendString(playerTag, playerTagString);
sendString(playerTag, mapSizeString);
sendString(playerTag, prodString);
sendString(playerTag, mapString);
std::string outMessage = "Init Message sent to player " + std::to_string(int(playerTag)) + ".\n";
if(!program_output_style) std::cout << outMessage;
*playerName = getString(playerTag, timeoutMillis);
std::string inMessage = "Init Message received from player " + std::to_string(int(playerTag)) + ", " + *playerName + ".\n";
if(!program_output_style) std::cout << inMessage;
return true;
}
catch (int e) {
return false;
}
}
unsigned int Networking::handleFrameNetworking(unsigned int timeoutMillis, unsigned char playerTag, const hlt::Map & m, std::set<hlt::Move> * moves) {
try{
if (isProcessDead(playerTag)) return false;
//Send this bot the game map and the messages addressed to this bot
std::string mapString = serializeMap(m);
sendString(playerTag, mapString);
moves->clear();
clock_t initialTime = clock();
std::string movesString = getString(playerTag, timeoutMillis);
unsigned millisTaken = ((clock() - initialTime) * 1000 / CLOCKS_PER_SEC);
*moves = deserializeMoveSet(movesString);
return millisTaken;
}
catch (int e) {
return timeoutMillis+1;
}
}
void Networking::killPlayer(unsigned char playerTag) {
if (isProcessDead(playerTag)) return;
#ifdef _WIN32
HANDLE process = processes[playerTag - 1];
TerminateProcess(process, 0);
processes[playerTag - 1] = NULL;
connections[playerTag - 1].read = NULL;
connections[playerTag - 1].write = NULL;
if(!program_output_style) std::cout << "Player " << int(playerTag) << " is dead\n";
#else
kill(processes[playerTag - 1], SIGKILL);
processes[playerTag - 1] = -1;
connections[playerTag - 1].read = -1;
connections[playerTag - 1].write = -1;
#endif
}
bool Networking::isProcessDead(unsigned char playerTag) {
#ifdef _WIN32
return processes[playerTag - 1] == NULL;
#else
return processes[playerTag - 1] == -1;
#endif
}
int Networking::numberOfPlayers() {
#ifdef _WIN32
return connections.size();
#else
return connections.size();
#endif
}
<commit_msg>Fix killing of bot processes<commit_after>#include "Networking.hpp"
#include <time.h>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <stdio.h>
#include <chrono>
#include <thread>
#include <mutex>
std::mutex coutMutex;
std::string serializeMapSize(const hlt::Map & map) {
std::string returnString = "";
std::ostringstream oss;
oss << map.map_width << ' ' << map.map_height << ' ';
returnString = oss.str();
return returnString;
}
std::string serializeProductions(const hlt::Map & map) {
std::string returnString = "";
std::ostringstream oss;
for(auto a = map.contents.begin(); a != map.contents.end(); a++) {
for(auto b = a->begin(); b != a->end(); b++) {
oss << (unsigned short)(b->production) << ' ';
}
}
returnString = oss.str();
return returnString;
}
std::string Networking::serializeMap(const hlt::Map & map) {
std::string returnString = "";
std::ostringstream oss;
//Run-length encode of owners
unsigned short currentOwner = map.contents[0][0].owner;
unsigned short counter = 0;
for(int a = 0; a < map.contents.size(); ++a) {
for(int b = 0; b < map.contents[a].size(); ++b) {
if (map.contents[a][b].owner == currentOwner) {
counter++;
}
else {
oss << (unsigned short)counter << ' ' << (unsigned short)currentOwner << ' ';
counter = 1;
currentOwner = map.contents[a][b].owner;
}
}
}
//Place the last run into the string
oss << (unsigned short)counter << ' ' << (unsigned short)currentOwner << ' ';
//Encoding of ages
for(int a = 0; a < map.contents.size(); ++a) {
for(int b = 0; b < map.contents[a].size(); ++b) {
oss << (unsigned short)map.contents[a][b].strength << ' ';
}
}
returnString = oss.str();
return returnString;
}
std::set<hlt::Move> Networking::deserializeMoveSet(std::string & inputString) {
std::set<hlt::Move> moves = std::set<hlt::Move>();
std::stringstream iss(inputString);
hlt::Location l;
int d;
while (iss >> l.x >> l.y >> d) moves.insert({ l, (unsigned char)d });
return moves;
}
void Networking::sendString(unsigned char playerTag, std::string &sendString) {
//End message with newline character
sendString += '\n';
#ifdef _WIN32
WinConnection connection = connections[playerTag - 1];
DWORD charsWritten;
bool success;
success = WriteFile(connection.write, sendString.c_str(), sendString.length(), &charsWritten, NULL);
if (!success || charsWritten == 0) {
if(!program_output_style) std::cout << "Problem writing to pipe\n";
throw 1;
}
#else
UniConnection connection = connections[playerTag - 1];
ssize_t charsWritten = write(connection.write, sendString.c_str(), sendString.length());
if(charsWritten < sendString.length()) {
if(!program_output_style) std::cout << "Problem writing to pipe\n";
throw 1;
}
#endif
}
std::string Networking::getString(unsigned char playerTag, unsigned int timeoutMillis) {
srand(time(NULL));
std::string newString;
#ifdef _WIN32
WinConnection connection = connections[playerTag - 1];
DWORD charsRead;
bool success;
char buffer;
//Keep reading char by char until a newline
while (true) {
//Check to see that there are bytes in the pipe before reading
//Throw error if no bytes in alloted time
//Check for bytes before sampling clock, because reduces latency (vast majority the pipe is alread full)
DWORD bytesAvailable = 0;
PeekNamedPipe(connection.read, NULL, 0, NULL, &bytesAvailable, NULL);
if (bytesAvailable < 1) {
clock_t initialTime = clock();
while (bytesAvailable < 1) {
if (((clock() - initialTime) * 1000 / CLOCKS_PER_SEC) > timeoutMillis) throw 1;
PeekNamedPipe(connection.read, NULL, 0, NULL, &bytesAvailable, NULL);
}
}
success = ReadFile(connection.read, &buffer, 1, &charsRead, NULL);
if (!success || charsRead < 1) {
if(!program_output_style) std::cout << "Pipe probably timed out\n";
throw 1;
}
if (buffer == '\n') break;
else newString += buffer;
}
#else
UniConnection connection = connections[playerTag - 1];
fd_set set;
FD_ZERO(&set); /* clear the set */
FD_SET(connection.read, &set); /* add our file descriptor to the set */
struct timeval timeout;
timeout.tv_sec = timeoutMillis / 1000.0;
timeout.tv_usec = (timeoutMillis % 1000)*1000;
char buffer;
//Keep reading char by char until a newline
while(true) {
//Check if there are bytes in the pipe
int selectionResult = select(connection.read+1, &set, NULL, NULL, &timeout);
if(selectionResult > 0) {
read(connection.read, &buffer, 1);
if (buffer == '\n') break;
else newString += buffer;
} else {
if(!program_output_style) {
// Buffer error message output
// If a bunch of bots fail at onces, we dont want to be writing to cout at the same time
// That looks really weird
std::string errorMessage = "";
errorMessage += std::string("Unix bot timeout or error ") + std::to_string(selectionResult) + std::string("\n");
playerLogs[playerTag-1].push_back(newString);
errorMessage += "#---------ALL OF THE OUTPUT OF THE BOT THAT TIMED OUT----------#\n";
for(auto stringIter = playerLogs[playerTag-1].begin(); stringIter != playerLogs[playerTag-1].end(); stringIter++) {
while(stringIter->size() < 60) stringIter->push_back(' ');
errorMessage += "# " + *stringIter + " #\n";
}
errorMessage += "#--------------------------------------------------------------#\n";
std::lock_guard<std::mutex> guard(coutMutex);
std::cout << errorMessage;
}
throw 1;
}
}
#endif
//Python turns \n into \r\n
if (newString.at(newString.size() - 1) == '\r') newString.pop_back();
playerLogs[playerTag-1].push_back(newString);
return newString;
}
void Networking::startAndConnectBot(std::string command) {
#ifdef _WIN32
command = "/C " + command;
WinConnection parentConnection, childConnection;
SECURITY_ATTRIBUTES saAttr;
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
//Child stdout pipe
if (!CreatePipe(&parentConnection.read, &childConnection.write, &saAttr, 0)) {
if(!program_output_style) std::cout << "Could not create pipe\n";
throw 1;
}
if (!SetHandleInformation(parentConnection.read, HANDLE_FLAG_INHERIT, 0)) throw 1;
//Child stdin pipe
if (!CreatePipe(&childConnection.read, &parentConnection.write, &saAttr, 0)) {
if(!program_output_style) std::cout << "Could not create pipe\n";
throw 1;
}
if (!SetHandleInformation(parentConnection.write, HANDLE_FLAG_INHERIT, 0)) throw 1;
//MAKE SURE THIS MEMORY IS ERASED
PROCESS_INFORMATION piProcInfo;
ZeroMemory(&piProcInfo, sizeof(PROCESS_INFORMATION));
STARTUPINFO siStartInfo;
ZeroMemory(&siStartInfo, sizeof(STARTUPINFO));
siStartInfo.cb = sizeof(STARTUPINFO);
siStartInfo.hStdError = childConnection.write;
siStartInfo.hStdOutput = childConnection.write;
siStartInfo.hStdInput = childConnection.read;
siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
//C:/xampp/htdocs/Halite/Halite/Debug/ExampleBot.exe
//C:/Users/Michael/Anaconda3/python.exe
//C:/Program Files/Java/jre7/bin/java.exe -cp C:/xampp/htdocs/Halite/AIResources/Java MyBot
bool success = CreateProcess(
"C:\\windows\\system32\\cmd.exe",
LPSTR(command.c_str()), //command line
NULL, //process security attributes
NULL, //primary thread security attributes
TRUE, //handles are inherited
0, //creation flags
NULL, //use parent's environment
NULL, //use parent's current directory
&siStartInfo, //STARTUPINFO pointer
&piProcInfo
); //receives PROCESS_INFORMATION
if(!success) {
if(!program_output_style) std::cout << "Could not start process\n";
throw 1;
}
else {
CloseHandle(piProcInfo.hProcess);
CloseHandle(piProcInfo.hThread);
processes.push_back(piProcInfo.hProcess);
connections.push_back(parentConnection);
}
#else
if(!program_output_style) std::cout << command << "\n";
pid_t pid = NULL;
int writePipe[2];
int readPipe[2];
if(pipe(writePipe)) {
if(!program_output_style) std::cout << "Error creating pipe\n";
throw 1;
}
if(pipe(readPipe)) {
if(!program_output_style) std::cout << "Error creating pipe\n";
throw 1;
}
//Fork a child process
pid = fork();
if(pid == 0) { //This is the child
setpgid(getpid(), getpid());
dup2(writePipe[0], STDIN_FILENO);
dup2(readPipe[1], STDOUT_FILENO);
dup2(readPipe[1], STDERR_FILENO);
execl("/bin/sh", "sh", "-c", command.c_str(), (char*) NULL);
//Nothing past the execl should be run
exit(1);
} else if(pid < 0) {
if(!program_output_style) std::cout << "Fork failed\n";
throw 1;
}
UniConnection connection;
connection.read = readPipe[0];
connection.write = writePipe[1];
connections.push_back(connection);
processes.push_back(pid);
#endif
playerLogs.push_back(std::vector<std::string>(0));
}
bool Networking::handleInitNetworking(unsigned int timeoutMillis, unsigned char playerTag, const hlt::Map & m, std::string * playerName) {
try{
std::string playerTagString = std::to_string(playerTag), mapSizeString = serializeMapSize(m), mapString = serializeMap(m), prodString = serializeProductions(m);
sendString(playerTag, playerTagString);
sendString(playerTag, mapSizeString);
sendString(playerTag, prodString);
sendString(playerTag, mapString);
std::string outMessage = "Init Message sent to player " + std::to_string(int(playerTag)) + ".\n";
if(!program_output_style) std::cout << outMessage;
*playerName = getString(playerTag, timeoutMillis);
std::string inMessage = "Init Message received from player " + std::to_string(int(playerTag)) + ", " + *playerName + ".\n";
if(!program_output_style) std::cout << inMessage;
return true;
}
catch (int e) {
return false;
}
}
unsigned int Networking::handleFrameNetworking(unsigned int timeoutMillis, unsigned char playerTag, const hlt::Map & m, std::set<hlt::Move> * moves) {
try{
if (isProcessDead(playerTag)) return false;
//Send this bot the game map and the messages addressed to this bot
std::string mapString = serializeMap(m);
sendString(playerTag, mapString);
moves->clear();
clock_t initialTime = clock();
std::string movesString = getString(playerTag, timeoutMillis);
unsigned millisTaken = ((clock() - initialTime) * 1000 / CLOCKS_PER_SEC);
*moves = deserializeMoveSet(movesString);
return millisTaken;
}
catch (int e) {
return timeoutMillis+1;
}
}
void Networking::killPlayer(unsigned char playerTag) {
if (isProcessDead(playerTag)) return;
#ifdef _WIN32
HANDLE process = processes[playerTag - 1];
TerminateProcess(process, 0);
processes[playerTag - 1] = NULL;
connections[playerTag - 1].read = NULL;
connections[playerTag - 1].write = NULL;
if(!program_output_style) std::cout << "Player " << int(playerTag) << " is dead\n";
#else
kill(-processes[playerTag - 1], SIGKILL);
processes[playerTag - 1] = -1;
connections[playerTag - 1].read = -1;
connections[playerTag - 1].write = -1;
#endif
}
bool Networking::isProcessDead(unsigned char playerTag) {
#ifdef _WIN32
return processes[playerTag - 1] == NULL;
#else
return processes[playerTag - 1] == -1;
#endif
}
int Networking::numberOfPlayers() {
#ifdef _WIN32
return connections.size();
#else
return connections.size();
#endif
}
<|endoftext|>
|
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved
*/
#include "../StroikaPreComp.h"
#include <exception>
#include <malloc.h>
#include "../Memory/Common.h"
#include "MallocGuard.h"
using namespace Stroika::Foundation;
using Memory::Byte;
#if qStroika_Foundation_Debug_MallocGuard
namespace {
using GuradBytes_ = Byte[16];
constexpr GuradBytes_ kMallocGuardHeader_ = { 0xf3, 0xfa, 0x0b, 0x93, 0x48, 0x50, 0x46, 0xe6, 0x22, 0xf1, 0xfa, 0xc0, 0x9a, 0x0b, 0xeb, 0x23, };
constexpr GuradBytes_ kMallocGuardFooter_ = { 0x07, 0x41, 0xa4, 0x2b, 0xba, 0x97, 0xcb, 0x38, 0x46, 0x1e, 0x3c, 0x42, 0x3c, 0x5f, 0x0c, 0x80, };
// need header with size, so we can ....
struct alignas(alignof(long double)) HeaderOrFooter_ {
GuradBytes_ fGuard;
size_t fRequestedBlockSize;
};
void OhShit_ ()
{
const char kMsg_[] = "Fatal Error detected in Stroika Malloc Guard\n";
::write (2, kMsg_, NEltsOf (kMsg_));
std::terminate ();
}
void* ExposedPtrToBackendPtr_ (void* p)
{
if (p == nullptr) {
OhShit_ ();
}
return reinterpret_cast<HeaderOrFooter_*> (p) - 1;
}
void* BackendPtrToExposedPtr_ (void* p)
{
if (p == nullptr) {
OhShit_ ();
}
return reinterpret_cast<HeaderOrFooter_*> (p) + 1;
}
size_t AdjustMallocSize_ (size_t s)
{
return s + 2 * sizeof (HeaderOrFooter_);
}
void Validate_ (const HeaderOrFooter_& header, const HeaderOrFooter_& footer)
{
if (::memcmp (&header.fGuard, &kMallocGuardHeader_, sizeof (kMallocGuardHeader_)) != 0) {
OhShit_ ();
}
if (::memcmp (&footer.fGuard, &kMallocGuardFooter_, sizeof (kMallocGuardFooter_)) != 0) {
OhShit_ ();
}
if (header.fRequestedBlockSize != footer.fRequestedBlockSize) {
OhShit_ ();
}
// OK
}
void ValidateBackendPtr_ (const void* p)
{
const HeaderOrFooter_* hp = reinterpret_cast<const HeaderOrFooter_*> (p);
const HeaderOrFooter_* fp = reinterpret_cast<const HeaderOrFooter_*> (reinterpret_cast<const Byte*> (hp + 1) + hp->fRequestedBlockSize);
HeaderOrFooter_ footer;
(void)::memcpy (&footer, fp, sizeof (footer)); // align access
Validate_ (*hp, footer);
}
void PatchNewPointer_ (void* p, size_t requestedSize)
{
HeaderOrFooter_* hp = reinterpret_cast< HeaderOrFooter_*> (p);
(void)::memcpy (begin (hp->fGuard), begin (kMallocGuardHeader_), NEltsOf (kMallocGuardHeader_));
hp->fRequestedBlockSize = requestedSize;
HeaderOrFooter_* fp = reinterpret_cast< HeaderOrFooter_*> (reinterpret_cast<Byte*> (hp + 1) + hp->fRequestedBlockSize);
(void)::memcpy (begin (fp->fGuard), begin (kMallocGuardFooter_), NEltsOf (kMallocGuardFooter_));
fp->fRequestedBlockSize = requestedSize;
}
}
#endif
#if qStroika_Foundation_Debug_MallocGuard
extern "C" void __libc_free (void* __ptr);
extern "C" void* __libc_malloc (size_t __size);
extern "C" void* __libc_realloc (void* __ptr, size_t __size);
extern "C" void* __libc_calloc (size_t __nmemb, size_t __size);
extern "C" void __libc_free (void* __ptr);
extern "C" void* __libc_memalign (size_t __alignment, size_t __size);
#if 0
weak_alias (__malloc_info, malloc_info)
5256
5257
5258 strong_alias (__libc_calloc, __calloc) weak_alias (__libc_calloc, calloc)
5259 strong_alias (__libc_free, __cfree) weak_alias (__libc_free, cfree)
5260 strong_alias (__libc_free, __free) strong_alias (__libc_free, free)
5261 strong_alias (__libc_malloc, __malloc) strong_alias (__libc_malloc, malloc)
5262 strong_alias (__libc_memalign, __memalign)
5263 weak_alias (__libc_memalign, memalign)
5264 strong_alias (__libc_realloc, __realloc) strong_alias (__libc_realloc, realloc)
5265 strong_alias (__libc_valloc, __valloc) weak_alias (__libc_valloc, valloc)
5266 strong_alias (__libc_pvalloc, __pvalloc) weak_alias (__libc_pvalloc, pvalloc)
5267 strong_alias (__libc_mallinfo, __mallinfo)
5268 weak_alias (__libc_mallinfo, mallinfo)
5269 strong_alias (__libc_mallopt, __mallopt) weak_alias (__libc_mallopt, mallopt)
5270
5271 weak_alias (__malloc_stats, malloc_stats)
5272 weak_alias (__malloc_usable_size, malloc_usable_size)
5273 weak_alias (__malloc_trim, malloc_trim)
5274 weak_alias (__malloc_get_state, malloc_get_state)
5275 weak_alias (__malloc_set_state, malloc_set_state)
#endif
extern "C" void* calloc (size_t __nmemb, size_t __size)
{
size_t n = __nmemb * __size;
void* p = malloc (n);
(void)::memset (p, 0, n);
return p;
}
extern "C" void cfree (void* __ptr)
{
free (__ptr);
}
extern "C" void free (void* __ptr)
{
if (__ptr == nullptr) {
// according to http://linux.die.net/man/3/free
// "if ptr is NULL, no operation is performed." - and glibc does call this internally
return;
}
void* p = ExposedPtrToBackendPtr_ (__ptr);
ValidateBackendPtr_ (p);
__libc_free (p);
}
extern "C" void* malloc (size_t __size)
{
void* p = __libc_malloc (AdjustMallocSize_ (__size));
PatchNewPointer_ (p, __size);
ValidateBackendPtr_ (p);
if (p != nullptr) {
p = BackendPtrToExposedPtr_ (p);
}
return p;
}
extern "C" void* realloc (void* __ptr, size_t __size)
{
void* p = ExposedPtrToBackendPtr_ (__ptr);
ValidateBackendPtr_ (p);
size_t n = AdjustMallocSize_ (__size);
p = __libc_realloc (p, n);
if (p != nullptr) {
PatchNewPointer_ (p, __size);
ValidateBackendPtr_ (p);
p = BackendPtrToExposedPtr_ (p);
}
return p;
}
extern "C" void* valloc (size_t __size)
{
OhShit_ ();
return nullptr;
}
extern "C" void* pvalloc (size_t __size)
{
OhShit_ ();
return nullptr;
}
extern "C" void* memalign (size_t __alignment, size_t __size)
{
OhShit_ ();
return nullptr;
}
extern "C" size_t malloc_usable_size (void* ptr)
{
if (ptr == nullptr) {
return 0;
}
void* p = ExposedPtrToBackendPtr_ (ptr);
ValidateBackendPtr_ (p);
const HeaderOrFooter_* hp = reinterpret_cast<const HeaderOrFooter_*> (p);
return hp->fRequestedBlockSize;
}
#endif
<commit_msg>MallocGuard fix<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved
*/
#include "../StroikaPreComp.h"
#include <exception>
#include <malloc.h>
#include <cstdlib>
#include "../Memory/Common.h"
#include "MallocGuard.h"
using namespace Stroika::Foundation;
using Memory::Byte;
#if qStroika_Foundation_Debug_MallocGuard
namespace {
using GuradBytes_ = Byte[16];
constexpr GuradBytes_ kMallocGuardHeader_ = { 0xf3, 0xfa, 0x0b, 0x93, 0x48, 0x50, 0x46, 0xe6, 0x22, 0xf1, 0xfa, 0xc0, 0x9a, 0x0b, 0xeb, 0x23, };
constexpr GuradBytes_ kMallocGuardFooter_ = { 0x07, 0x41, 0xa4, 0x2b, 0xba, 0x97, 0xcb, 0x38, 0x46, 0x1e, 0x3c, 0x42, 0x3c, 0x5f, 0x0c, 0x80, };
// need header with size, so we can ....
struct alignas(alignof(long double)) HeaderOrFooter_ {
GuradBytes_ fGuard;
size_t fRequestedBlockSize;
};
void OhShit_ ()
{
const char kMsg_[] = "Fatal Error detected in Stroika Malloc Guard\n";
::write (2, kMsg_, NEltsOf (kMsg_));
std::terminate ();
}
void* ExposedPtrToBackendPtr_ (void* p)
{
if (p == nullptr) {
OhShit_ ();
}
return reinterpret_cast<HeaderOrFooter_*> (p) - 1;
}
void* BackendPtrToExposedPtr_ (void* p)
{
if (p == nullptr) {
OhShit_ ();
}
return reinterpret_cast<HeaderOrFooter_*> (p) + 1;
}
size_t AdjustMallocSize_ (size_t s)
{
return s + 2 * sizeof (HeaderOrFooter_);
}
void Validate_ (const HeaderOrFooter_& header, const HeaderOrFooter_& footer)
{
if (::memcmp (&header.fGuard, &kMallocGuardHeader_, sizeof (kMallocGuardHeader_)) != 0) {
OhShit_ ();
}
if (::memcmp (&footer.fGuard, &kMallocGuardFooter_, sizeof (kMallocGuardFooter_)) != 0) {
OhShit_ ();
}
if (header.fRequestedBlockSize != footer.fRequestedBlockSize) {
OhShit_ ();
}
// OK
}
void ValidateBackendPtr_ (const void* p)
{
const HeaderOrFooter_* hp = reinterpret_cast<const HeaderOrFooter_*> (p);
const HeaderOrFooter_* fp = reinterpret_cast<const HeaderOrFooter_*> (reinterpret_cast<const Byte*> (hp + 1) + hp->fRequestedBlockSize);
HeaderOrFooter_ footer;
(void)::memcpy (&footer, fp, sizeof (footer)); // align access
Validate_ (*hp, footer);
}
void PatchNewPointer_ (void* p, size_t requestedSize)
{
HeaderOrFooter_* hp = reinterpret_cast< HeaderOrFooter_*> (p);
(void)::memcpy (begin (hp->fGuard), begin (kMallocGuardHeader_), NEltsOf (kMallocGuardHeader_));
hp->fRequestedBlockSize = requestedSize;
HeaderOrFooter_* fp = reinterpret_cast< HeaderOrFooter_*> (reinterpret_cast<Byte*> (hp + 1) + hp->fRequestedBlockSize);
(void)::memcpy (begin (fp->fGuard), begin (kMallocGuardFooter_), NEltsOf (kMallocGuardFooter_));
fp->fRequestedBlockSize = requestedSize;
}
}
#endif
#if qStroika_Foundation_Debug_MallocGuard
extern "C" void __libc_free (void* __ptr);
extern "C" void* __libc_malloc (size_t __size);
extern "C" void* __libc_realloc (void* __ptr, size_t __size);
extern "C" void* __libc_calloc (size_t __nmemb, size_t __size);
extern "C" void __libc_free (void* __ptr);
extern "C" void* __libc_memalign (size_t __alignment, size_t __size);
#if 0
weak_alias (__malloc_info, malloc_info)
5256
5257
5258 strong_alias (__libc_calloc, __calloc) weak_alias (__libc_calloc, calloc)
5259 strong_alias (__libc_free, __cfree) weak_alias (__libc_free, cfree)
5260 strong_alias (__libc_free, __free) strong_alias (__libc_free, free)
5261 strong_alias (__libc_malloc, __malloc) strong_alias (__libc_malloc, malloc)
5262 strong_alias (__libc_memalign, __memalign)
5263 weak_alias (__libc_memalign, memalign)
5264 strong_alias (__libc_realloc, __realloc) strong_alias (__libc_realloc, realloc)
5265 strong_alias (__libc_valloc, __valloc) weak_alias (__libc_valloc, valloc)
5266 strong_alias (__libc_pvalloc, __pvalloc) weak_alias (__libc_pvalloc, pvalloc)
5267 strong_alias (__libc_mallinfo, __mallinfo)
5268 weak_alias (__libc_mallinfo, mallinfo)
5269 strong_alias (__libc_mallopt, __mallopt) weak_alias (__libc_mallopt, mallopt)
5270
5271 weak_alias (__malloc_stats, malloc_stats)
5272 weak_alias (__malloc_usable_size, malloc_usable_size)
5273 weak_alias (__malloc_trim, malloc_trim)
5274 weak_alias (__malloc_get_state, malloc_get_state)
5275 weak_alias (__malloc_set_state, malloc_set_state)
#endif
extern "C" void* calloc (size_t __nmemb, size_t __size)
{
size_t n = __nmemb * __size;
void* p = malloc (n);
(void)::memset (p, 0, n);
return p;
}
extern "C" void cfree (void* __ptr)
{
free (__ptr);
}
extern "C" void free (void* __ptr)
{
if (__ptr == nullptr) {
// according to http://linux.die.net/man/3/free
// "if ptr is NULL, no operation is performed." - and glibc does call this internally
return;
}
void* p = ExposedPtrToBackendPtr_ (__ptr);
ValidateBackendPtr_ (p);
__libc_free (p);
}
extern "C" void* malloc (size_t __size)
{
void* p = __libc_malloc (AdjustMallocSize_ (__size));
PatchNewPointer_ (p, __size);
ValidateBackendPtr_ (p);
if (p != nullptr) {
p = BackendPtrToExposedPtr_ (p);
}
return p;
}
extern "C" void* realloc (void* __ptr, size_t __size)
{
void* p = ExposedPtrToBackendPtr_ (__ptr);
ValidateBackendPtr_ (p);
size_t n = AdjustMallocSize_ (__size);
p = __libc_realloc (p, n);
if (p != nullptr) {
PatchNewPointer_ (p, __size);
ValidateBackendPtr_ (p);
p = BackendPtrToExposedPtr_ (p);
}
return p;
}
extern "C" void* valloc (size_t __size)
{
OhShit_ ();
return nullptr;
}
extern "C" void* pvalloc (size_t __size)
{
OhShit_ ();
return nullptr;
}
extern "C" void* memalign (size_t __alignment, size_t __size)
{
OhShit_ ();
return nullptr;
}
extern "C" size_t malloc_usable_size (void* ptr)
{
if (ptr == nullptr) {
return 0;
}
void* p = ExposedPtrToBackendPtr_ (ptr);
ValidateBackendPtr_ (p);
const HeaderOrFooter_* hp = reinterpret_cast<const HeaderOrFooter_*> (p);
return hp->fRequestedBlockSize;
}
#endif
<|endoftext|>
|
<commit_before>
#include "FrameBuffer.h"
#include "utility.h"
#include "globals.h"
#include "Interrupt.h"
#include "Segmentation.h"
#include "Keyboard.h"
#include "Paging.h"
#include "HardDrive.h"
#include "PhysicalMemoryAllocator.h"
#include "FAT.h"
#include "dirtyMalloc.h"
#include <stdarg.h>
#include <memory>
#include "CommandLine.h"
#include <functional>
using namespace std;
typedef void(*funcp)();
extern "C" {
extern funcp __init_array_start;
extern funcp __init_array_end;
}
extern "C" void* kernel_code_end;
void init(){
funcp *beg = & __init_array_start, *end = & __init_array_end;
for (funcp*p = beg; p < end; ++p){
(*p)();
}
}
void* getCR2(){
void* res;
asm("mov %%cr2,%0" :
"=r"(res)
:
:
);
return res;
}
void doublefault(InterruptParamsErr par){
bsod("Double fault at %p !! It may be an uncaught interruption.",par.eip);
//should not return eip is UB.
}
void gpfault(InterruptParamsErr par){
bsod("General Protection fault at %p with code %x!!",par.eip,par.errorCode);
}
void pagefault(InterruptParamsErr par){
printf("Page fault at %p with code %x accesing %p\n",par.eip,par.errorCode,getCR2());
while(true) asm volatile("cli;hlt");
//bsod("Page fault! (aka. segmentation fault)");
}
void printer (InterruptParams par){
fb.printf ("a is : %d, b is %d\n",par.eax,par.ebx);
}
void keyboard(InterruptParams) {
kbd.handleScanCode(inb(0x60));
pic.endOfInterrupt(1);
}
void div0 (InterruptParams par){
bsod(" 1/0 is not infinity at %p !",par.eip);
}
uint32 sum (InterruptParams par){
return par.eax + par.ebx;
}
extern "C" void kmain(multibootInfo* multibootinfo) {
multiboot = *multibootinfo;
PDE[0].present = false;
cli;
init(); //C++ global contructors should not change machine state.
initkmalloc();
gdt.init();
idt.init();
idt.addInt(0,div0);
idt.addInt(8,doublefault);
idt.addInt(14,pagefault);
idt.addInt(13,gpfault);
sti;
#define BLA -1
#if BLA == -1
volatile int i = ((int*)(nullptr))[42];
return;
#elif BLA == 0
char* p1 = (char*)malloc(13);
char* p2 = (char*)malloc(19);
char* p3 = (char*)malloc(23);
char* p4 = (char*)malloc(27);
fb.printf("%x %x %x %x\n", p1, p2, p3, p4);
free(p2);
char* p5 = (char*)malloc(21);
fb.printf("%x\n", p5);
while(1) asm volatile ("cli;hlt");
#elif BLA == 1
HDD first(1,true);
first.init();
//first.writeaddr(0xf0095,"random data !",13);
/*char text [15] = {};
first.readaddr (0xf0095,text,13);
printf("Read text %s \n",text);*/
PartitionTableEntry part1 = first[1];
fb.printf ("Partition 1 from %8x to %8x \n",part1.begLBA,part1.endLBA);
Partition pa1 (&first,part1);
/*uchar buffer[512];
pa1.readlba(0,buffer,1);
for(int i = 0 ; i < 512 ; ++ i){
printf("%x ",buffer[i]);
}
printf("\n");*/
fat::FS fs (&pa1);
fat::Directory* root = fs.getRootFat();
root->load();
Directory * boot = (*root)["boot"]->dir();
assert(boot);
//printf("%p\n",boot);
Directory* grub = (*boot)["grub"]->dir();
assert(grub);
auto v = grub->getFilesName();
printf("Filenames : \n");
for(auto s : v){
printf("-%s;\n",s.c_str());
}
fb.printf("\n");
while(true){
for(int i = 0 ; i < 1000000 ; ++i);
first.getStatus().printStatus();
fb.printf("\r");
}
#elif BLA == 2
volatile lint i = 42000000000000;
volatile lint j = 10000000000;
int res = i/j; // testing libgcc
fb.printf ("val :%d ",res);
#elif BLA == 3
idt.addInt(0x21,keyboard);
pic.activate(Pic::KEYBOARD);
kbd.setKeymap(&azertyKeymap);
HDD first(1,true);
first.init();
PartitionTableEntry part1 = first[1];
Partition pa1 (&first,part1);
fat::FS fs (&pa1);
CommandLine cl;
cl.pwd = fs.getRootFat();
// proof of concept for command
cl.add("test",[](CommandLine*,const vector<string>&){
fb.printf("test Command in kmain\n");
});
//running command line
cl.run();
#elif BLA == 5
int j = 5;
std::function<int(int)> func = [&j](int i){return i +j;};
j = 38;
printf("%d", func(4));
#else
//[insert here useful kernel code]
#endif
}
extern "C" void __cxa_pure_virtual (){}
void * __dso_handle=0;
//extern "C" void __cxa_atexit(){}
<commit_msg>Fix typo<commit_after>
#include "FrameBuffer.h"
#include "utility.h"
#include "globals.h"
#include "Interrupt.h"
#include "Segmentation.h"
#include "Keyboard.h"
#include "Paging.h"
#include "HardDrive.h"
#include "PhysicalMemoryAllocator.h"
#include "FAT.h"
#include "dirtyMalloc.h"
#include <stdarg.h>
#include <memory>
#include "CommandLine.h"
#include <functional>
using namespace std;
typedef void(*funcp)();
extern "C" {
extern funcp __init_array_start;
extern funcp __init_array_end;
}
extern "C" void* kernel_code_end;
void init(){
funcp *beg = & __init_array_start, *end = & __init_array_end;
for (funcp*p = beg; p < end; ++p){
(*p)();
}
}
void* getCR2(){
void* res;
asm("mov %%cr2,%0" :
"=r"(res)
:
:
);
return res;
}
void doublefault(InterruptParamsErr par){
bsod("Double fault at %p !! It may be an uncaught interruption.",par.eip);
//should not return eip is UB.
}
void gpfault(InterruptParamsErr par){
bsod("General Protection fault at %p with code %x!!",par.eip,par.errorCode);
}
void pagefault(InterruptParamsErr par){
printf("Page fault at %p with code %x accessing %p\n",par.eip,par.errorCode,getCR2());
while(true) asm volatile("cli;hlt");
//bsod("Page fault! (aka. segmentation fault)");
}
void printer (InterruptParams par){
fb.printf ("a is : %d, b is %d\n",par.eax,par.ebx);
}
void keyboard(InterruptParams) {
kbd.handleScanCode(inb(0x60));
pic.endOfInterrupt(1);
}
void div0 (InterruptParams par){
bsod(" 1/0 is not infinity at %p !",par.eip);
}
uint32 sum (InterruptParams par){
return par.eax + par.ebx;
}
extern "C" void kmain(multibootInfo* multibootinfo) {
multiboot = *multibootinfo;
PDE[0].present = false;
cli;
init(); //C++ global contructors should not change machine state.
initkmalloc();
gdt.init();
idt.init();
idt.addInt(0,div0);
idt.addInt(8,doublefault);
idt.addInt(14,pagefault);
idt.addInt(13,gpfault);
sti;
#define BLA -1
#if BLA == -1
volatile int i = ((int*)(nullptr))[42];
return;
#elif BLA == 0
char* p1 = (char*)malloc(13);
char* p2 = (char*)malloc(19);
char* p3 = (char*)malloc(23);
char* p4 = (char*)malloc(27);
fb.printf("%x %x %x %x\n", p1, p2, p3, p4);
free(p2);
char* p5 = (char*)malloc(21);
fb.printf("%x\n", p5);
while(1) asm volatile ("cli;hlt");
#elif BLA == 1
HDD first(1,true);
first.init();
//first.writeaddr(0xf0095,"random data !",13);
/*char text [15] = {};
first.readaddr (0xf0095,text,13);
printf("Read text %s \n",text);*/
PartitionTableEntry part1 = first[1];
fb.printf ("Partition 1 from %8x to %8x \n",part1.begLBA,part1.endLBA);
Partition pa1 (&first,part1);
/*uchar buffer[512];
pa1.readlba(0,buffer,1);
for(int i = 0 ; i < 512 ; ++ i){
printf("%x ",buffer[i]);
}
printf("\n");*/
fat::FS fs (&pa1);
fat::Directory* root = fs.getRootFat();
root->load();
Directory * boot = (*root)["boot"]->dir();
assert(boot);
//printf("%p\n",boot);
Directory* grub = (*boot)["grub"]->dir();
assert(grub);
auto v = grub->getFilesName();
printf("Filenames : \n");
for(auto s : v){
printf("-%s;\n",s.c_str());
}
fb.printf("\n");
while(true){
for(int i = 0 ; i < 1000000 ; ++i);
first.getStatus().printStatus();
fb.printf("\r");
}
#elif BLA == 2
volatile lint i = 42000000000000;
volatile lint j = 10000000000;
int res = i/j; // testing libgcc
fb.printf ("val :%d ",res);
#elif BLA == 3
idt.addInt(0x21,keyboard);
pic.activate(Pic::KEYBOARD);
kbd.setKeymap(&azertyKeymap);
HDD first(1,true);
first.init();
PartitionTableEntry part1 = first[1];
Partition pa1 (&first,part1);
fat::FS fs (&pa1);
CommandLine cl;
cl.pwd = fs.getRootFat();
// proof of concept for command
cl.add("test",[](CommandLine*,const vector<string>&){
fb.printf("test Command in kmain\n");
});
//running command line
cl.run();
#elif BLA == 5
int j = 5;
std::function<int(int)> func = [&j](int i){return i +j;};
j = 38;
printf("%d", func(4));
#else
//[insert here useful kernel code]
#endif
}
extern "C" void __cxa_pure_virtual (){}
void * __dso_handle=0;
//extern "C" void __cxa_atexit(){}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2011
* Alessio Sclocco <a.sclocco@vu.nl>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#define __CL_ENABLE_EXCEPTIONS
#include <CL/cl.hpp>
#include <string>
#include <utility>
using std::string;
using std::make_pair;
#include <kernels/Kernel.hpp>
#include <GPUData.hpp>
#include <Exceptions.hpp>
#include <utils.hpp>
using isa::OpenCL::Kernel;
using isa::OpenCL::GPUData;
using isa::Exceptions::OpenCLError;
using isa::utils::giga;
#ifndef VECTOR_ADD_HPP
#define VECTOR_ADD_HPP
namespace isa {
namespace OpenCL {
template < typename T > class VectorAdd : public Kernel< T > {
public:
VectorAdd(string dataType);
void generateCode() throw (OpenCLError);
void operator()(GPUData< T > *a, GPUData< T > *b, GPUData< T > *c) throw (OpenCLError);
inline void setNrThreadsPerBlock(unsigned int threads);
inline void setNrThreads(unsigned int threads);
inline void setNrRows(unsigned int rows);
private:
unsigned int nrThreadsPerBlock;
unsigned int nrThreads;
unsigned int nrRows;
};
// Implementation
template< typename T > VectorAdd< T >::VectorAdd(string dataType) : Kernel< T >("VectorAdd", dataType), nrThreadsPerBlock(0), nrThreads(0), nrRows(0) {}
template< typename T > void VectorAdd< T >::generateCode() throw (OpenCLError) {
long long unsigned int ops = static_cast< long long unsigned int >(nrThreads);
long long unsigned int memOps = ops * 12;
this->arInt = ops / static_cast< double >(memOps);
this->gflop = giga(ops);
this->gb = giga(memOps);
if ( this->code != 0 ) {
delete this->code;
}
this->code = new string();
*(this->code) = "__kernel void " + this->name + "(__global " + this->dataType + " *A, __global " + this->dataType + " *B, __global " + this->dataType + " *C) {\n"
"unsigned int id = (get_group_id(1) * get_num_groups(0) * get_local_size(0)) + (get_group_id(0) * get_local_size(0)) + get_local_id(0);\n"
"C[id] = A[id] + B[id];\n"
"}";
this->compile();
}
template< typename T > void VectorAdd< T >::operator()(GPUData< T > *a, GPUData< T > *b, GPUData< T > *c) throw (OpenCLError) {
cl::NDRange globalSize(nrThreads / nrRows, nrRows);
cl::NDRange localSize(nrThreadsPerBlock, 1);
this->setArgument(0, *(a->getDeviceData()));
this->setArgument(1, *(b->getDeviceData()));
this->setArgument(2, *(c->getDeviceData()));
this->run(globalSize, localSize);
}
template< typename T > inline void VectorAdd< T >::setNrThreadsPerBlock(unsigned int threads) {
nrThreadsPerBlock = threads;
}
template< typename T > inline void VectorAdd< T >::setNrThreads(unsigned int threads) {
nrThreads = threads;
}
template< typename T > inline void VectorAdd< T >::setNrRows(unsigned int rows) {
nrRows = rows;
}
} // OpenCL
} // isa
#endif // VECTOR_ADD_HPP
<commit_msg>Still working on the vector4 (I know, I should save the files before commit).<commit_after>/*
* Copyright (C) 2011
* Alessio Sclocco <a.sclocco@vu.nl>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#define __CL_ENABLE_EXCEPTIONS
#include <CL/cl.hpp>
#include <string>
#include <utility>
using std::string;
using std::make_pair;
#include <kernels/Kernel.hpp>
#include <GPUData.hpp>
#include <Exceptions.hpp>
#include <utils.hpp>
using isa::OpenCL::Kernel;
using isa::OpenCL::GPUData;
using isa::Exceptions::OpenCLError;
using isa::utils::giga;
#ifndef VECTOR_ADD_HPP
#define VECTOR_ADD_HPP
namespace isa {
namespace OpenCL {
template < typename T > class VectorAdd : public Kernel< T > {
public:
VectorAdd(string dataType);
void generateCode() throw (OpenCLError);
void operator()(GPUData< T > *a, GPUData< T > *b, GPUData< T > *c) throw (OpenCLError);
inline void setNrThreadsPerBlock(unsigned int threads);
inline void setNrThreads(unsigned int threads);
inline void setNrRows(unsigned int rows);
inline void setVector4(bool vec);
private:
unsigned int nrThreadsPerBlock;
unsigned int nrThreads;
unsigned int nrRows;
bool vector4;
};
// Implementation
template< typename T > VectorAdd< T >::VectorAdd(string dataType) : Kernel< T >("VectorAdd", dataType), nrThreadsPerBlock(0), nrThreads(0), nrRows(0), vector4(false) {}
template< typename T > void VectorAdd< T >::generateCode() throw (OpenCLError) {
long long unsigned int ops = static_cast< long long unsigned int >(nrThreads);
long long unsigned int memOps = ops * 12;
this->arInt = ops / static_cast< double >(memOps);
this->gflop = giga(ops);
this->gb = giga(memOps);
if ( this->code != 0 ) {
delete this->code;
}
this->code = new string();
if ( vector4 ) {
*(this->code) = "__kernel void " + this->name + "(__global " + this->dataType + "4 *A, __global " + this->dataType + "4 *B, __global " + this->dataType + "4 *C) {\n"
"unsigned int id = (get_group_id(1) * get_num_groups(0) * get_local_size(0)) + (get_group_id(0) * get_local_size(0)) + get_local_id(0);\n"
"C[id] = A[id] + B[id];\n"
"}";
}
else {
*(this->code) = "__kernel void " + this->name + "(__global " + this->dataType + " *A, __global " + this->dataType + " *B, __global " + this->dataType + " *C) {\n"
"unsigned int id = (get_group_id(1) * get_num_groups(0) * get_local_size(0)) + (get_group_id(0) * get_local_size(0)) + get_local_id(0);\n"
"C[id] = A[id] + B[id];\n"
"}";
}
this->compile();
}
template< typename T > void VectorAdd< T >::operator()(GPUData< T > *a, GPUData< T > *b, GPUData< T > *c) throw (OpenCLError) {
cl::NDRange globalSize(nrThreads / nrRows, nrRows);
cl::NDRange localSize(nrThreadsPerBlock, 1);
this->setArgument(0, *(a->getDeviceData()));
this->setArgument(1, *(b->getDeviceData()));
this->setArgument(2, *(c->getDeviceData()));
this->run(globalSize, localSize);
}
template< typename T > inline void VectorAdd< T >::setNrThreadsPerBlock(unsigned int threads) {
nrThreadsPerBlock = threads;
}
template< typename T > inline void VectorAdd< T >::setNrThreads(unsigned int threads) {
nrThreads = threads;
}
template< typename T > inline void VectorAdd< T >::setNrRows(unsigned int rows) {
nrRows = rows;
}
template< typename T > inline void VectorAdd< T >::setVector4(bool vec) {
vector4 = vec;
}
} // OpenCL
} // isa
#endif // VECTOR_ADD_HPP
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2008, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_ALLOCA
#include "libtorrent/config.hpp"
#ifdef TORRENT_WINDOWS
#include <malloc.h>
#define TORRENT_ALLOCA(t, n) static_cast<t*>(_alloca(sizeof(t) * (n)))
#else
#include <alloca.h>
#define TORRENT_ALLOCA(t, n) static_cast<t*>(alloca(sizeof(t) * (n)))
#endif
#endif
<commit_msg>another FreeBSD fix<commit_after>/*
Copyright (c) 2008, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_ALLOCA
#include "libtorrent/config.hpp"
#if defined TORRENT_WINDOWS
#include <malloc.h>
#define TORRENT_ALLOCA(t, n) static_cast<t*>(_alloca(sizeof(t) * (n)))
#elif defined TORRENT_BSD
#include <stdlib.h>
#define TORRENT_ALLOCA(t, n) static_cast<t*>(alloca(sizeof(t) * (n)))
#else
#include <alloca.h>
#define TORRENT_ALLOCA(t, n) static_cast<t*>(alloca(sizeof(t) * (n)))
#endif
#endif
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of Rasterbar Software nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef LIBTORRENT_BUFFER_HPP
#define LIBTORRENT_BUFFER_HPP
#include <memory>
#include <cstring>
#include "libtorrent/invariant_check.hpp"
#include "libtorrent/assert.hpp"
namespace libtorrent {
class buffer
{
public:
struct interval
{
interval()
: begin(0)
, end(0)
{}
interval(char* begin, char* end)
: begin(begin)
, end(end)
{}
char operator[](int index) const
{
TORRENT_ASSERT(begin + index < end);
return begin[index];
}
int left() const { TORRENT_ASSERT(end >= begin); return end - begin; }
char* begin;
char* end;
};
struct const_interval
{
const_interval(interval const& i)
: begin(i.begin)
, end(i.end)
{}
const_interval(char const* begin, char const* end)
: begin(begin)
, end(end)
{}
char operator[](int index) const
{
TORRENT_ASSERT(begin + index < end);
return begin[index];
}
bool operator==(const const_interval& p_interval)
{
return (begin == p_interval.begin
&& end == p_interval.end);
}
int left() const { TORRENT_ASSERT(end >= begin); return end - begin; }
char const* begin;
char const* end;
};
buffer(std::size_t n = 0)
: m_begin(0)
, m_end(0)
, m_last(0)
{
if (n) resize(n);
}
buffer(buffer const& b)
: m_begin(0)
, m_end(0)
, m_last(0)
{
if (b.size() == 0) return;
resize(b.size());
std::memcpy(m_begin, b.begin(), b.size());
}
buffer& operator=(buffer const& b)
{
resize(b.size());
std::memcpy(m_begin, b.begin(), b.size());
return *this;
}
~buffer()
{
::operator delete (m_begin);
}
buffer::interval data() { return interval(m_begin, m_end); }
buffer::const_interval data() const { return const_interval(m_begin, m_end); }
void resize(std::size_t n)
{
reserve(n);
m_end = m_begin + n;
}
void insert(char* point, char const* first, char const* last)
{
std::size_t p = point - m_begin;
if (point == m_end)
{
resize(size() + last - first);
std::memcpy(m_begin + p, first, last - first);
return;
}
resize(size() + last - first);
std::memmove(m_begin + p + (last - first), m_begin + p, last - first);
std::memcpy(m_begin + p, first, last - first);
}
void erase(char* begin, char* end)
{
TORRENT_ASSERT(end <= m_end);
TORRENT_ASSERT(begin >= m_begin);
TORRENT_ASSERT(begin <= end);
if (end == m_end)
{
resize(begin - m_begin);
return;
}
std::memmove(begin, end, m_end - end);
m_end = begin + (m_end - end);
}
void clear() { m_end = m_begin; }
std::size_t size() const { return m_end - m_begin; }
std::size_t capacity() const { return m_last - m_begin; }
void reserve(std::size_t n)
{
if (n <= capacity()) return;
TORRENT_ASSERT(n > 0);
char* buf = (char*)::operator new(n);
std::size_t s = size();
std::memcpy(buf, m_begin, s);
::operator delete (m_begin);
m_begin = buf;
m_end = buf + s;
m_last = m_begin + n;
}
bool empty() const { return m_begin == m_end; }
char& operator[](std::size_t i) { TORRENT_ASSERT(i < size()); return m_begin[i]; }
char const& operator[](std::size_t i) const { TORRENT_ASSERT(i < size()); return m_begin[i]; }
char* begin() { return m_begin; }
char const* begin() const { return m_begin; }
char* end() { return m_end; }
char const* end() const { return m_end; }
void swap(buffer& b)
{
using std::swap;
swap(m_begin, b.m_begin);
swap(m_end, b.m_end);
swap(m_last, b.m_last);
}
private:
char* m_begin; // first
char* m_end; // one passed end of size
char* m_last; // one passed end of allocation
};
}
#endif // LIBTORRENT_BUFFER_HPP
<commit_msg>switched over buffer to use realloc/free<commit_after>/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of Rasterbar Software nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef LIBTORRENT_BUFFER_HPP
#define LIBTORRENT_BUFFER_HPP
#include <memory>
#include <cstring>
#include "libtorrent/invariant_check.hpp"
#include "libtorrent/assert.hpp"
namespace libtorrent {
class buffer
{
public:
struct interval
{
interval()
: begin(0)
, end(0)
{}
interval(char* begin, char* end)
: begin(begin)
, end(end)
{}
char operator[](int index) const
{
TORRENT_ASSERT(begin + index < end);
return begin[index];
}
int left() const { TORRENT_ASSERT(end >= begin); return end - begin; }
char* begin;
char* end;
};
struct const_interval
{
const_interval(interval const& i)
: begin(i.begin)
, end(i.end)
{}
const_interval(char const* begin, char const* end)
: begin(begin)
, end(end)
{}
char operator[](int index) const
{
TORRENT_ASSERT(begin + index < end);
return begin[index];
}
bool operator==(const const_interval& p_interval)
{
return (begin == p_interval.begin
&& end == p_interval.end);
}
int left() const { TORRENT_ASSERT(end >= begin); return end - begin; }
char const* begin;
char const* end;
};
buffer(std::size_t n = 0)
: m_begin(0)
, m_end(0)
, m_last(0)
{
if (n) resize(n);
}
buffer(buffer const& b)
: m_begin(0)
, m_end(0)
, m_last(0)
{
if (b.size() == 0) return;
resize(b.size());
std::memcpy(m_begin, b.begin(), b.size());
}
buffer& operator=(buffer const& b)
{
if (&b == this) return *this;
resize(b.size());
std::memcpy(m_begin, b.begin(), b.size());
return *this;
}
~buffer()
{
std::free(m_begin);
}
buffer::interval data() { return interval(m_begin, m_end); }
buffer::const_interval data() const { return const_interval(m_begin, m_end); }
void resize(std::size_t n)
{
reserve(n);
m_end = m_begin + n;
}
void insert(char* point, char const* first, char const* last)
{
std::size_t p = point - m_begin;
if (point == m_end)
{
resize(size() + last - first);
std::memcpy(m_begin + p, first, last - first);
return;
}
resize(size() + last - first);
std::memmove(m_begin + p + (last - first), m_begin + p, last - first);
std::memcpy(m_begin + p, first, last - first);
}
void erase(char* begin, char* end)
{
TORRENT_ASSERT(end <= m_end);
TORRENT_ASSERT(begin >= m_begin);
TORRENT_ASSERT(begin <= end);
if (end == m_end)
{
resize(begin - m_begin);
return;
}
std::memmove(begin, end, m_end - end);
m_end = begin + (m_end - end);
}
void clear() { m_end = m_begin; }
std::size_t size() const { return m_end - m_begin; }
std::size_t capacity() const { return m_last - m_begin; }
void reserve(std::size_t n)
{
if (n <= capacity()) return;
TORRENT_ASSERT(n > 0);
std::size_t s = size();
m_begin = (char*)std::realloc(m_begin, n);
m_end = m_begin + s;
m_last = m_begin + n;
}
bool empty() const { return m_begin == m_end; }
char& operator[](std::size_t i) { TORRENT_ASSERT(i < size()); return m_begin[i]; }
char const& operator[](std::size_t i) const { TORRENT_ASSERT(i < size()); return m_begin[i]; }
char* begin() { return m_begin; }
char const* begin() const { return m_begin; }
char* end() { return m_end; }
char const* end() const { return m_end; }
void swap(buffer& b)
{
using std::swap;
swap(m_begin, b.m_begin);
swap(m_end, b.m_end);
swap(m_last, b.m_last);
}
private:
char* m_begin; // first
char* m_end; // one passed end of size
char* m_last; // one passed end of allocation
};
}
#endif // LIBTORRENT_BUFFER_HPP
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2005, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_CONFIG_HPP_INCLUDED
#define TORRENT_CONFIG_HPP_INCLUDED
#include <boost/config.hpp>
#include <boost/version.hpp>
#if defined(__GNUC__) && __GNUC__ >= 4
#define TORRENT_DEPRECATED __attribute__ ((deprecated))
# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __attribute__ ((visibility("default")))
# else
# define TORRENT_EXPORT
# endif
#elif defined(__GNUC__)
# define TORRENT_EXPORT
#elif defined(BOOST_MSVC)
# if defined(TORRENT_BUILDING_SHARED)
# define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __declspec(dllimport)
# else
# define TORRENT_EXPORT
# endif
#else
# define TORRENT_EXPORT
#endif
#ifndef TORRENT_DEPRECATED
#define TORRENT_DEPRECATED
#endif
// set up defines for target environments
#if (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \
|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \
|| defined __FreeBSD_kernel__
#define TORRENT_BSD
#elif defined __linux__
#define TORRENT_LINUX
#elif defined WIN32
#define TORRENT_WINDOWS
#else
#warning unkown OS, assuming BSD
#define TORRENT_BSD
#endif
// should wpath or path be used?
#if defined UNICODE && !defined BOOST_FILESYSTEM_NARROW_ONLY && BOOST_VERSION >= 103400
#define TORRENT_USE_WPATH 1
#else
#define TORRENT_USE_WPATH 0
#endif
#endif // TORRENT_CONFIG_HPP_INCLUDED
<commit_msg>only use wpath on windows<commit_after>/*
Copyright (c) 2005, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_CONFIG_HPP_INCLUDED
#define TORRENT_CONFIG_HPP_INCLUDED
#include <boost/config.hpp>
#include <boost/version.hpp>
#if defined(__GNUC__) && __GNUC__ >= 4
#define TORRENT_DEPRECATED __attribute__ ((deprecated))
# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __attribute__ ((visibility("default")))
# else
# define TORRENT_EXPORT
# endif
#elif defined(__GNUC__)
# define TORRENT_EXPORT
#elif defined(BOOST_MSVC)
# if defined(TORRENT_BUILDING_SHARED)
# define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __declspec(dllimport)
# else
# define TORRENT_EXPORT
# endif
#else
# define TORRENT_EXPORT
#endif
#ifndef TORRENT_DEPRECATED
#define TORRENT_DEPRECATED
#endif
// set up defines for target environments
#if (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \
|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \
|| defined __FreeBSD_kernel__
#define TORRENT_BSD
#elif defined __linux__
#define TORRENT_LINUX
#elif defined WIN32
#define TORRENT_WINDOWS
#else
#warning unkown OS, assuming BSD
#define TORRENT_BSD
#endif
// should wpath or path be used?
#if defined UNICODE && !defined BOOST_FILESYSTEM_NARROW_ONLY \
&& BOOST_VERSION >= 103400 && defined WIN32
#define TORRENT_USE_WPATH 1
#else
#define TORRENT_USE_WPATH 0
#endif
#endif // TORRENT_CONFIG_HPP_INCLUDED
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2005, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_CONFIG_HPP_INCLUDED
#define TORRENT_CONFIG_HPP_INCLUDED
#include <boost/config.hpp>
#include <boost/version.hpp>
#include <stdio.h> // for snprintf
#ifndef WIN32
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#endif
#ifndef PRId64
#ifdef _WIN32
#define PRId64 "I64d"
#else
#define PRId64 "lld"
#endif
#endif
#if defined(__GNUC__) && __GNUC__ >= 4
#define TORRENT_DEPRECATED __attribute__ ((deprecated))
# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __attribute__ ((visibility("default")))
# else
# define TORRENT_EXPORT
# endif
#elif defined(__GNUC__)
# define TORRENT_EXPORT
#elif defined(BOOST_MSVC)
#pragma warning(disable: 4258)
#pragma warning(disable: 4251)
# if defined(TORRENT_BUILDING_SHARED)
# define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __declspec(dllimport)
# else
# define TORRENT_EXPORT
# endif
#else
# define TORRENT_EXPORT
#endif
#ifndef TORRENT_DEPRECATED
#define TORRENT_DEPRECATED
#endif
// set up defines for target environments
#if (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \
|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \
|| defined __FreeBSD_kernel__
#define TORRENT_BSD
#elif defined __linux__
#define TORRENT_LINUX
#elif defined __MINGW32__
#define TORRENT_MINGW
#elif defined WIN32
#define TORRENT_WINDOWS
#elif defined sun || defined __sun
#define TORRENT_SOLARIS
#else
#warning unkown OS, assuming BSD
#define TORRENT_BSD
#endif
#define TORRENT_USE_IPV6 1
#define TORRENT_USE_MLOCK 1
#define TORRENT_USE_READV 1
#define TORRENT_USE_WRITEV 1
#define TORRENT_USE_IOSTREAM 1
// should wpath or path be used?
#if defined UNICODE && !defined BOOST_FILESYSTEM_NARROW_ONLY \
&& BOOST_VERSION >= 103400 && !defined __APPLE__
#define TORRENT_USE_WPATH 1
#else
#define TORRENT_USE_WPATH 0
#endif
#ifdef TORRENT_WINDOWS
#include <stdarg.h>
// this is the maximum number of characters in a
// path element / filename on windows
#define NAME_MAX 255
inline int snprintf(char* buf, int len, char const* fmt, ...)
{
va_list lp;
va_start(lp, fmt);
return vsnprintf_s(buf, len, _TRUNCATE, fmt, lp);
}
#define strtoll _strtoi64
#else
#include <limits.h>
#endif
#if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) && !defined (TORRENT_UPNP_LOGGING)
#define TORRENT_UPNP_LOGGING
#endif
#if !TORRENT_USE_WPATH && defined TORRENT_LINUX
// libiconv presnce, not implemented yet
#define TORRENT_USE_LOCALE_FILENAMES 1
#else
#define TORRENT_USE_LOCALE_FILENAMES 0
#endif
#if !defined(TORRENT_READ_HANDLER_MAX_SIZE)
# define TORRENT_READ_HANDLER_MAX_SIZE 256
#endif
#if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE)
# define TORRENT_WRITE_HANDLER_MAX_SIZE 256
#endif
// determine what timer implementation we can use
#if defined(__MACH__)
#define TORRENT_USE_ABSOLUTE_TIME 1
#elif defined(_WIN32)
#define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1
#elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0
#define TORRENT_USE_CLOCK_GETTIME 1
#else
#define TORRENT_USE_BOOST_DATE_TIME 1
#endif
#endif // TORRENT_CONFIG_HPP_INCLUDED
<commit_msg>attempt to make it build on windows<commit_after>/*
Copyright (c) 2005, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_CONFIG_HPP_INCLUDED
#define TORRENT_CONFIG_HPP_INCLUDED
#include <boost/config.hpp>
#include <boost/version.hpp>
#include <stdio.h> // for snprintf
#include <stdlib.h> // for _TRUNCATE (windows)
#include <stdarg.h>
#ifndef WIN32
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#endif
#ifndef PRId64
#ifdef _WIN32
#define PRId64 "I64d"
#else
#define PRId64 "lld"
#endif
#endif
#if defined(__GNUC__) && __GNUC__ >= 4
#define TORRENT_DEPRECATED __attribute__ ((deprecated))
# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __attribute__ ((visibility("default")))
# else
# define TORRENT_EXPORT
# endif
#elif defined(__GNUC__)
# define TORRENT_EXPORT
#elif defined(BOOST_MSVC)
#pragma warning(disable: 4258)
#pragma warning(disable: 4251)
# if defined(TORRENT_BUILDING_SHARED)
# define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __declspec(dllimport)
# else
# define TORRENT_EXPORT
# endif
#else
# define TORRENT_EXPORT
#endif
#ifndef TORRENT_DEPRECATED
#define TORRENT_DEPRECATED
#endif
// set up defines for target environments
#if (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \
|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \
|| defined __FreeBSD_kernel__
#define TORRENT_BSD
#elif defined __linux__
#define TORRENT_LINUX
#elif defined __MINGW32__
#define TORRENT_MINGW
#elif defined WIN32
#define TORRENT_WINDOWS
#elif defined sun || defined __sun
#define TORRENT_SOLARIS
#else
#warning unkown OS, assuming BSD
#define TORRENT_BSD
#endif
#define TORRENT_USE_IPV6 1
#define TORRENT_USE_MLOCK 1
#define TORRENT_USE_READV 1
#define TORRENT_USE_WRITEV 1
#define TORRENT_USE_IOSTREAM 1
// should wpath or path be used?
#if defined UNICODE && !defined BOOST_FILESYSTEM_NARROW_ONLY \
&& BOOST_VERSION >= 103400 && !defined __APPLE__
#define TORRENT_USE_WPATH 1
#else
#define TORRENT_USE_WPATH 0
#endif
#ifdef TORRENT_WINDOWS
#include <stdarg.h>
// this is the maximum number of characters in a
// path element / filename on windows
#define NAME_MAX 255
inline int snprintf(char* buf, int len, char const* fmt, ...)
{
va_list lp;
va_start(lp, fmt);
return vsnprintf_s(buf, len, _TRUNCATE, fmt, lp);
}
#define strtoll _strtoi64
#else
#include <limits.h>
#endif
#if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) && !defined (TORRENT_UPNP_LOGGING)
#define TORRENT_UPNP_LOGGING
#endif
#if !TORRENT_USE_WPATH && defined TORRENT_LINUX
// libiconv presnce, not implemented yet
#define TORRENT_USE_LOCALE_FILENAMES 1
#else
#define TORRENT_USE_LOCALE_FILENAMES 0
#endif
#if !defined(TORRENT_READ_HANDLER_MAX_SIZE)
# define TORRENT_READ_HANDLER_MAX_SIZE 256
#endif
#if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE)
# define TORRENT_WRITE_HANDLER_MAX_SIZE 256
#endif
// determine what timer implementation we can use
#if defined(__MACH__)
#define TORRENT_USE_ABSOLUTE_TIME 1
#elif defined(_WIN32)
#define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1
#elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0
#define TORRENT_USE_CLOCK_GETTIME 1
#else
#define TORRENT_USE_BOOST_DATE_TIME 1
#endif
#endif // TORRENT_CONFIG_HPP_INCLUDED
<|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2015 Artem Pavlenko
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_VALUE_HASH_HPP
#define MAPNIK_VALUE_HASH_HPP
// mapnik
#include <mapnik/util/variant.hpp>
#include <mapnik/value_types.hpp>
// stl
#include <functional>
#include <cassert>
// icu
#include <unicode/unistr.h>
namespace mapnik { namespace detail {
template <class T>
inline void hash_combine(std::size_t & seed, T const& v)
{
std::hash<T> hasher;
seed ^= hasher(v) + 0x9e3779b9 + (seed<<6) + (seed>>2);
}
struct value_hasher
{
std::size_t operator() (value_null val) const
{
return hash_value(val);
}
std::size_t operator() (value_unicode_string const& val) const
{
assert(val.hashCode() > 0);
return static_cast<std::size_t>(val.hashCode());
}
template <class T>
std::size_t operator()(T const& val) const
{
std::hash<T> hasher;
return hasher(val);
}
};
} // namespace detail
template <typename T>
std::size_t mapnik_hash_value(T const& val)
{
std::size_t seed = util::apply_visitor(detail::value_hasher(), val);
detail::hash_combine(seed, val.get_type_index());
return seed;
}
} // namespace mapnik
#endif // MAPNIK_VALUE_HASH_HPP
<commit_msg>add std::hash specialization for mapnik::value<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2015 Artem Pavlenko
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_VALUE_HASH_HPP
#define MAPNIK_VALUE_HASH_HPP
// mapnik
#include <mapnik/util/variant.hpp>
#include <mapnik/value_types.hpp>
// stl
#include <functional>
#include <cassert>
// icu
#include <unicode/unistr.h>
namespace mapnik { namespace detail {
template <class T>
inline void hash_combine(std::size_t & seed, T const& v)
{
std::hash<T> hasher;
seed ^= hasher(v) + 0x9e3779b9 + (seed<<6) + (seed>>2);
}
struct value_hasher
{
std::size_t operator() (value_null val) const
{
return hash_value(val);
}
std::size_t operator() (value_unicode_string const& val) const
{
assert(val.hashCode() > 0);
return static_cast<std::size_t>(val.hashCode());
}
template <class T>
std::size_t operator()(T const& val) const
{
std::hash<T> hasher;
return hasher(val);
}
};
} // namespace detail
template <typename T>
std::size_t mapnik_hash_value(T const& val)
{
std::size_t seed = util::apply_visitor(detail::value_hasher(), val);
detail::hash_combine(seed, val.get_type_index());
return seed;
}
} // namespace mapnik
// support for std::unordered containers
namespace std
{
template <>
struct hash<mapnik::value>
{
size_t operator()(const mapnik::value& val) const
{
return mapnik::mapnik_hash_value(val);
}
};
#endif // MAPNIK_VALUE_HASH_HPP
<|endoftext|>
|
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id: $ */
//_________________________________________________________________________
// Analysis task that executes the analysis classes
// that depend on the PartCorr frame, frame for Particle identification and correlations.
// Specially designed for calorimeters but also can be used for charged tracks
// Input of this task is a configuration file that contains all the settings of the analyis
//
// -- Author: Gustavo Conesa (INFN-LNF)
// root
#include <TROOT.h>
#include <TInterpreter.h>
//#include <Riostream.h>
// analysis
#include "AliAnalysisTaskParticleCorrelation.h"
#include "AliAnaPartCorrMaker.h"
#include "AliCaloTrackReader.h"
#include "AliPDG.h"
ClassImp(AliAnalysisTaskParticleCorrelation)
////////////////////////////////////////////////////////////////////////
AliAnalysisTaskParticleCorrelation::AliAnalysisTaskParticleCorrelation():
AliAnalysisTaskSE(),
fAna(0x0),
fOutputContainer(0x0),
fConfigName(0)
{
// Default constructor
}
//_____________________________________________________
AliAnalysisTaskParticleCorrelation::AliAnalysisTaskParticleCorrelation(const char* name):
AliAnalysisTaskSE(name),
fAna(0x0),
fOutputContainer(0x0),
fConfigName("")
{
// Default constructor
DefineOutput(1, TList::Class());
}
//_____________________________________________________
AliAnalysisTaskParticleCorrelation::~AliAnalysisTaskParticleCorrelation()
{
// Remove all pointers
if(fOutputContainer){
fOutputContainer->Clear() ;
delete fOutputContainer ;
}
}
//_____________________________________________________
void AliAnalysisTaskParticleCorrelation::UserCreateOutputObjects()
{
// Create the output container
if (fDebug > 1) printf("AliAnalysisTaskParticleCorrelation::CreateOutputData() - Begin \n");
//Get list of aod arrays, add each aod array to analysis frame
TClonesArray * array = 0;
TList * list = fAna->GetAODBranchList();
for(Int_t iaod = 0; iaod < list->GetEntries(); iaod++){
array = (TClonesArray*) list->At(iaod);
AddAODBranch("TClonesArray", &array);
}
//Histograms container
OpenFile(1);
fOutputContainer = fAna->GetOutputContainer();
if (fDebug > 1) printf("AliAnalysisTaskParticleCorrelation::CreateOutputData() - End \n");
}
//_____________________________________________________
void AliAnalysisTaskParticleCorrelation::Init()
{
// Initialization
if (fDebug > 1) printf("AliAnalysisTaskParticleCorrelation::Init() - Begin \n");
// Call configuration file if specified
if (fConfigName.Length()) {
printf("AliAnalysisTaskParticleCorrelation::Init() - ### Configuration file is %s.C ###", fConfigName.Data());
gROOT->LoadMacro(fConfigName+".C");
fAna = (AliAnaPartCorrMaker*) gInterpreter->ProcessLine("ConfigAnalysis()");
}
if(!fAna){
printf("AliAnalysisTaskParticleCorrelation::Init() Analysis maker pointer not initialized, no analysis specified, abort analysis!\n");
abort();
}
// Add different generator particles to PDG Data Base
// to avoid problems when reading MC generator particles
AliPDG::AddParticlesToPdgDataBase();
// Initialise analysis
fAna->Init();
if (fDebug > 1) printf("AliAnalysisTaskParticleCorrelation::Init() - End \n");
}
//_____________________________________________________
void AliAnalysisTaskParticleCorrelation::UserExec(Option_t */*option*/)
{
// Execute analysis for current event
//
if (fDebug > 1) printf("AliAnalysisTaskParticleCorrelation::Exec() - Begin \n");
//Get the type of data, check if type is correct
Int_t datatype = fAna->GetReader()->GetDataType();
if(datatype != AliCaloTrackReader::kESD && datatype != AliCaloTrackReader::kAOD &&
datatype != AliCaloTrackReader::kMC){
printf("AliAnalysisTaskParticleCorrelation::Exec() - Wrong type of data\n");
return ;
}
fAna->GetReader()->SetInputOutputMCEvent(InputEvent(), AODEvent(), MCEvent());
//Process event
fAna->ProcessEvent((Int_t) Entry());
if (fDebug > 1) printf("AliAnalysisTaskParticleCorrelation::Exec() - End \n");
PostData(1, fOutputContainer);
}
//_____________________________________________________
void AliAnalysisTaskParticleCorrelation::Terminate(Option_t */*option*/)
{
// Terminate analysis
// Do some plots
//
fAna->Terminate();
}
<commit_msg>Include cstdlib to declare abort()<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id: $ */
//_________________________________________________________________________
// Analysis task that executes the analysis classes
// that depend on the PartCorr frame, frame for Particle identification and correlations.
// Specially designed for calorimeters but also can be used for charged tracks
// Input of this task is a configuration file that contains all the settings of the analyis
//
// -- Author: Gustavo Conesa (INFN-LNF)
#include <cstdlib>
// root
#include <TROOT.h>
#include <TInterpreter.h>
//#include <Riostream.h>
// analysis
#include "AliAnalysisTaskParticleCorrelation.h"
#include "AliAnaPartCorrMaker.h"
#include "AliCaloTrackReader.h"
#include "AliPDG.h"
ClassImp(AliAnalysisTaskParticleCorrelation)
////////////////////////////////////////////////////////////////////////
AliAnalysisTaskParticleCorrelation::AliAnalysisTaskParticleCorrelation():
AliAnalysisTaskSE(),
fAna(0x0),
fOutputContainer(0x0),
fConfigName(0)
{
// Default constructor
}
//_____________________________________________________
AliAnalysisTaskParticleCorrelation::AliAnalysisTaskParticleCorrelation(const char* name):
AliAnalysisTaskSE(name),
fAna(0x0),
fOutputContainer(0x0),
fConfigName("")
{
// Default constructor
DefineOutput(1, TList::Class());
}
//_____________________________________________________
AliAnalysisTaskParticleCorrelation::~AliAnalysisTaskParticleCorrelation()
{
// Remove all pointers
if(fOutputContainer){
fOutputContainer->Clear() ;
delete fOutputContainer ;
}
}
//_____________________________________________________
void AliAnalysisTaskParticleCorrelation::UserCreateOutputObjects()
{
// Create the output container
if (fDebug > 1) printf("AliAnalysisTaskParticleCorrelation::CreateOutputData() - Begin \n");
//Get list of aod arrays, add each aod array to analysis frame
TClonesArray * array = 0;
TList * list = fAna->GetAODBranchList();
for(Int_t iaod = 0; iaod < list->GetEntries(); iaod++){
array = (TClonesArray*) list->At(iaod);
AddAODBranch("TClonesArray", &array);
}
//Histograms container
OpenFile(1);
fOutputContainer = fAna->GetOutputContainer();
if (fDebug > 1) printf("AliAnalysisTaskParticleCorrelation::CreateOutputData() - End \n");
}
//_____________________________________________________
void AliAnalysisTaskParticleCorrelation::Init()
{
// Initialization
if (fDebug > 1) printf("AliAnalysisTaskParticleCorrelation::Init() - Begin \n");
// Call configuration file if specified
if (fConfigName.Length()) {
printf("AliAnalysisTaskParticleCorrelation::Init() - ### Configuration file is %s.C ###", fConfigName.Data());
gROOT->LoadMacro(fConfigName+".C");
fAna = (AliAnaPartCorrMaker*) gInterpreter->ProcessLine("ConfigAnalysis()");
}
if(!fAna){
printf("AliAnalysisTaskParticleCorrelation::Init() Analysis maker pointer not initialized, no analysis specified, abort analysis!\n");
abort();
}
// Add different generator particles to PDG Data Base
// to avoid problems when reading MC generator particles
AliPDG::AddParticlesToPdgDataBase();
// Initialise analysis
fAna->Init();
if (fDebug > 1) printf("AliAnalysisTaskParticleCorrelation::Init() - End \n");
}
//_____________________________________________________
void AliAnalysisTaskParticleCorrelation::UserExec(Option_t */*option*/)
{
// Execute analysis for current event
//
if (fDebug > 1) printf("AliAnalysisTaskParticleCorrelation::Exec() - Begin \n");
//Get the type of data, check if type is correct
Int_t datatype = fAna->GetReader()->GetDataType();
if(datatype != AliCaloTrackReader::kESD && datatype != AliCaloTrackReader::kAOD &&
datatype != AliCaloTrackReader::kMC){
printf("AliAnalysisTaskParticleCorrelation::Exec() - Wrong type of data\n");
return ;
}
fAna->GetReader()->SetInputOutputMCEvent(InputEvent(), AODEvent(), MCEvent());
//Process event
fAna->ProcessEvent((Int_t) Entry());
if (fDebug > 1) printf("AliAnalysisTaskParticleCorrelation::Exec() - End \n");
PostData(1, fOutputContainer);
}
//_____________________________________________________
void AliAnalysisTaskParticleCorrelation::Terminate(Option_t */*option*/)
{
// Terminate analysis
// Do some plots
//
fAna->Terminate();
}
<|endoftext|>
|
<commit_before>//=============================================================================
//
// *** AddTaskFemtoAzimtuhalHBT.C ***
//
// This macro initialize a complete AnalysisTask object for femtoscopy.
//
//=============================================================================
AliAnalysisTaskFemto *AddTaskFemtoAzimtuhalHBT(TString configMacroName, const char *containerName="femtolist", const char *configMacroParameters="" )
{
// Creates a proton analysis task and adds it to the analysis manager.
// A. Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
Error("AddTaskFemtoAzimtuhalHBT", "No analysis manager to connect to.");
return NULL;
}
TString inputDataType = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
Bool_t useEtaGap=kFALSE;
Float_t etaGap=0.;
Bool_t posTPCAOD=kFALSE;
TString containername = "EPStat_ttd";
// B. Check the analysis type using the event handlers connected to the analysis
// manager. The availability of MC handler cann also be checked here.
//==============================================================================
if (!mgr->GetInputEventHandler()) {
::Error("AddTaskFemtoAzimtuhalHBT", "This task requires an input event handler");
return NULL;
}
TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
// cout << "Found " <<type << " event handler" << endl;
//gROOT->LoadMacro("AliEPSelectionTask3.cxx+g");
//gROOT->LoadMacro("AddTaskEventplane.C");
//AliEPSelectionTask3* epsel = AddTaskEventplane();
AliEPSelectionTask *eventplaneTask = new AliEPSelectionTask("EventplaneSelection4");
eventplaneTask->SelectCollisionCandidates(AliVEvent::kMB | AliVEvent::kSemiCentral | AliVEvent::kCentral);
if (inputDataType == "AOD"){
eventplaneTask->SetInput("AOD");
}
eventplaneTask->SetTrackType("TPC");
eventplaneTask->SetUsePtWeight();
eventplaneTask->SetUsePhiWeight();
eventplaneTask->SetSaveTrackContribution();
if(useEtaGap){
eventplaneTask->SetSubeventsSplitMethod(AliEPSelectionTask3::kEta);
eventplaneTask->SetEtaGap(etaGap);
}
if(posTPCAOD){
eventplaneTask->SetPersonalAODtrackCuts(128,0.,0.8,0.15,20.);
eventplaneTask->SetSubeventsSplitMethod(AliEPSelectionTask3::kRandom);
}
mgr->AddTask(eventplaneTask);
// C. Create the task, add it to manager.
//===========================================================================
// gSystem->SetIncludePath("-I$ROOTSYS/include -I./PWG2AOD/AOD -I./PWG2femtoscopy/FEMTOSCOPY/AliFemto -I./PWG2femtoscopyUser/FEMTOSCOPY/AliFemtoUser -I$ALICE_ROOT/include");
if (TProofMgr::GetListOfManagers()->GetEntries()) {
// if (dynamic_cast<TProofLite *> gProof) {
// char *macrocommand[10000];
// sprintf(macrocommand, ".L %s", configMacroName);
// gProof->Exec(macrocommand);
// }
// else
gProof->Load(configMacroName);
}
// gROOT->LoadMacro("ConfigFemtoAnalysis.C++");
AliAnalysisTaskFemto *taskfemto = new AliAnalysisTaskFemto("TaskFemto","$ALICE_ROOT/"+configMacroName,configMacroParameters);
//taskfemto->SelectCollisionCandidates(AliVEvent::kMB | AliVEvent::kCentral | AliVEvent::kSemiCentral) ;
mgr->AddTask(taskfemto);
// D. Configure the analysis task. Extra parameters can be used via optional
// arguments of the AddTaskXXX() function.
//===========================================================================
// E. Create ONLY the output containers for the data produced by the task.
// Get and connect other common input/output containers via the manager as below
//==============================================================================
TString outputfile = AliAnalysisManager::GetCommonFileName();
// outputfile += ":PWG2FEMTO";
AliAnalysisDataContainer *cout_femto = mgr->CreateContainer(containerName, TList::Class(),
AliAnalysisManager::kOutputContainer,outputfile);
mgr->ConnectInput(taskfemto, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(taskfemto, 0, cout_femto);
AliAnalysisDataContainer *cinput0 = mgr->GetCommonInputContainer();
AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(containername,
TList::Class(), AliAnalysisManager::kOutputContainer,
"EventStat_temp.root");
mgr->ConnectInput(eventplaneTask, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(eventplaneTask,1,coutput1);
// Return task pointer at the end
return taskfemto;
}
<commit_msg>All outputs in one file for Azimuthal HBT<commit_after>//=============================================================================
//
// *** AddTaskFemtoAzimtuhalHBT.C ***
//
// This macro initialize a complete AnalysisTask object for femtoscopy.
//
//=============================================================================
AliAnalysisTaskFemto *AddTaskFemtoAzimtuhalHBT(TString configMacroName, const char *containerName="femtolist", const char *configMacroParameters="" )
{
// Creates a proton analysis task and adds it to the analysis manager.
// A. Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
Error("AddTaskFemtoAzimtuhalHBT", "No analysis manager to connect to.");
return NULL;
}
TString inputDataType = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
Bool_t useEtaGap=kFALSE;
Float_t etaGap=0.;
Bool_t posTPCAOD=kFALSE;
TString containername = "EPStat_ttd";
// B. Check the analysis type using the event handlers connected to the analysis
// manager. The availability of MC handler cann also be checked here.
//==============================================================================
if (!mgr->GetInputEventHandler()) {
::Error("AddTaskFemtoAzimtuhalHBT", "This task requires an input event handler");
return NULL;
}
TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
// cout << "Found " <<type << " event handler" << endl;
//gROOT->LoadMacro("AliEPSelectionTask3.cxx+g");
//gROOT->LoadMacro("AddTaskEventplane.C");
//AliEPSelectionTask3* epsel = AddTaskEventplane();
AliEPSelectionTask *eventplaneTask = new AliEPSelectionTask("EventplaneSelection4");
eventplaneTask->SelectCollisionCandidates(AliVEvent::kMB | AliVEvent::kSemiCentral | AliVEvent::kCentral);
if (inputDataType == "AOD"){
eventplaneTask->SetInput("AOD");
}
eventplaneTask->SetTrackType("TPC");
eventplaneTask->SetUsePtWeight();
eventplaneTask->SetUsePhiWeight();
eventplaneTask->SetSaveTrackContribution();
if(useEtaGap){
eventplaneTask->SetSubeventsSplitMethod(AliEPSelectionTask3::kEta);
eventplaneTask->SetEtaGap(etaGap);
}
if(posTPCAOD){
eventplaneTask->SetPersonalAODtrackCuts(128,0.,0.8,0.15,20.);
eventplaneTask->SetSubeventsSplitMethod(AliEPSelectionTask3::kRandom);
}
mgr->AddTask(eventplaneTask);
// C. Create the task, add it to manager.
//===========================================================================
// gSystem->SetIncludePath("-I$ROOTSYS/include -I./PWG2AOD/AOD -I./PWG2femtoscopy/FEMTOSCOPY/AliFemto -I./PWG2femtoscopyUser/FEMTOSCOPY/AliFemtoUser -I$ALICE_ROOT/include");
if (TProofMgr::GetListOfManagers()->GetEntries()) {
// if (dynamic_cast<TProofLite *> gProof) {
// char *macrocommand[10000];
// sprintf(macrocommand, ".L %s", configMacroName);
// gProof->Exec(macrocommand);
// }
// else
gProof->Load(configMacroName);
}
// gROOT->LoadMacro("ConfigFemtoAnalysis.C++");
AliAnalysisTaskFemto *taskfemto = new AliAnalysisTaskFemto("TaskFemto","$ALICE_ROOT/"+configMacroName,configMacroParameters,kFALSE);
//taskfemto->SelectCollisionCandidates(AliVEvent::kMB | AliVEvent::kCentral | AliVEvent::kSemiCentral) ;
mgr->AddTask(taskfemto);
// D. Configure the analysis task. Extra parameters can be used via optional
// arguments of the AddTaskXXX() function.
//===========================================================================
// E. Create ONLY the output containers for the data produced by the task.
// Get and connect other common input/output containers via the manager as below
//==============================================================================
TString outputfile = AliAnalysisManager::GetCommonFileName();
// outputfile += ":PWG2FEMTO";
AliAnalysisDataContainer *cout_femto = mgr->CreateContainer(containerName, TList::Class(),
AliAnalysisManager::kOutputContainer,outputfile);
mgr->ConnectInput(taskfemto, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(taskfemto, 0, cout_femto);
AliAnalysisDataContainer *cinput0 = mgr->GetCommonInputContainer();
AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(containername, TList::Class(), AliAnalysisManager::kOutputContainer,outputfile);
mgr->ConnectInput(eventplaneTask, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(eventplaneTask,1,coutput1);
// Return task pointer at the end
return taskfemto;
}
<|endoftext|>
|
<commit_before>/* Representation for raw, binary data.
*
* DO NOT INCLUDE THIS FILE DIRECTLY; include pqxx/binarystring instead.
*
* Copyright (c) 2000-2020, Jeroen T. Vermeulen.
*
* See COPYING for copyright license. If you did not receive a file called
* COPYING with this source code, please notify the distributor of this
* mistake, or contact the author.
*/
#ifndef PQXX_H_BINARYSTRING
#define PQXX_H_BINARYSTRING
#include "pqxx/compiler-public.hxx"
#include "pqxx/internal/compiler-internal-pre.hxx"
#include <memory>
#include <string>
#include <string_view>
#include "pqxx/result.hxx"
#include "pqxx/strconv.hxx"
namespace pqxx
{
class binarystring;
template<> struct string_traits<binarystring>;
/// Binary data corresponding to PostgreSQL's "BYTEA" binary-string type.
/** @ingroup escaping-functions
*
* This class represents a binary string as stored in a field of type @c bytea.
*
* Internally a binarystring is zero-terminated, but it may also contain null
* bytes, they're just like any other byte value. So don't assume that it's
* safe to treat the contents as a C-style string.
*
* The binarystring retains its value even if the result it was obtained from
* is destroyed, but it cannot be copied or assigned.
*
* \relatesalso transaction_base::quote_raw
*
* To include a @c binarystring value in an SQL query, escape and quote it
* using the transaction's @c quote_raw function.
*
* @warning This class is implemented as a reference-counting smart pointer.
* Copying, swapping, and destroying binarystring objects that refer to the
* same underlying data block is <em>not thread-safe</em>. If you wish to pass
* binarystrings around between threads, make sure that each of these
* operations is protected against concurrency with similar operations on the
* same object, or other objects pointing to the same data block.
*/
class PQXX_LIBEXPORT binarystring
{
public:
using char_type = unsigned char;
using value_type = std::char_traits<char_type>::char_type;
using size_type = std::size_t;
using difference_type = long;
using const_reference = value_type const &;
using const_pointer = value_type const *;
using const_iterator = const_pointer;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
binarystring(binarystring const &) = default;
/// Read and unescape bytea field.
/** The field will be zero-terminated, even if the original bytea field
* isn't.
* @param F the field to read; must be a bytea field
*/
explicit binarystring(field const &);
/// Copy binary data from std::string_view on binary data.
/** This is inefficient in that it copies the data to a buffer allocated on
* the heap.
*/
explicit binarystring(std::string_view);
/// Copy binary data of given length straight out of memory.
binarystring(void const *, std::size_t);
/// Efficiently wrap a buffer of binary data in a @c binarystring.
binarystring(std::shared_ptr<value_type> ptr, size_type size) :
m_buf{std::move(ptr)}, m_size{size}
{}
/// Size of converted string in bytes.
[[nodiscard]] size_type size() const noexcept { return m_size; }
/// Size of converted string in bytes.
[[nodiscard]] size_type length() const noexcept { return size(); }
[[nodiscard]] bool empty() const noexcept { return size() == 0; }
[[nodiscard]] const_iterator begin() const noexcept { return data(); }
[[nodiscard]] const_iterator cbegin() const noexcept { return begin(); }
[[nodiscard]] const_iterator end() const noexcept { return data() + m_size; }
[[nodiscard]] const_iterator cend() const noexcept { return end(); }
[[nodiscard]] const_reference front() const noexcept { return *begin(); }
[[nodiscard]] const_reference back() const noexcept
{
return *(data() + m_size - 1);
}
[[nodiscard]] const_reverse_iterator rbegin() const
{
return const_reverse_iterator{end()};
}
[[nodiscard]] const_reverse_iterator crbegin() const { return rbegin(); }
[[nodiscard]] const_reverse_iterator rend() const
{
return const_reverse_iterator{begin()};
}
[[nodiscard]] const_reverse_iterator crend() const { return rend(); }
/// Unescaped field contents.
[[nodiscard]] value_type const *data() const noexcept { return m_buf.get(); }
[[nodiscard]] const_reference operator[](size_type i) const noexcept
{
return data()[i];
}
[[nodiscard]] PQXX_PURE bool operator==(binarystring const &) const noexcept;
[[nodiscard]] bool operator!=(binarystring const &rhs) const noexcept
{
return not operator==(rhs);
}
binarystring &operator=(binarystring const &);
/// Index contained string, checking for valid index.
const_reference at(size_type) const;
/// Swap contents with other binarystring.
void swap(binarystring &);
/// Raw character buffer (no terminating zero is added).
/** @warning No terminating zero is added! If the binary data did not end in
* a null character, you will not find one here.
*/
[[nodiscard]] char const *get() const noexcept
{
return reinterpret_cast<char const *>(m_buf.get());
}
/// Read contents as a std::string_view.
[[nodiscard]] std::string_view view() const noexcept
{
return std::string_view(get(), size());
}
/// Read as regular C++ string (may include null characters).
/** This creates and returns a new string object. Don't call this
* repeatedly; retrieve your string once and keep it in a local variable.
* Also, do not expect to be able to compare the string's address to that of
* an earlier invocation.
*/
[[nodiscard]] std::string str() const;
private:
std::shared_ptr<value_type> m_buf;
size_type m_size{0};
};
// TODO: Should binarystring have a default-constructed null value?
template<> struct nullness<binarystring> : no_null<binarystring>
{};
/// String conversion traits for @c binarystring.
/** Defines the conversions between a @c binarystring and its PostgreSQL
* textual format, for communication with the database.
*
* These conversions rely on the "hex" format which was introduced in
* PostgreSQL 9.0. Both your libpq and the server must be recent enough to
* speak this format.
*/
template<> struct string_traits<binarystring>
{
static std::size_t size_buffer(binarystring const &value) noexcept
{
return internal::size_esc_bin(value.size());
}
static zview to_buf(char *begin, char *end, binarystring const &value)
{
auto const value_end{into_buf(begin, end, value)};
return zview{begin, value_end - begin - 1};
}
static char *into_buf(char *begin, char *end, binarystring const &value)
{
auto const budget{size_buffer(value)};
if (static_cast<std::size_t>(end - begin) < budget)
throw conversion_overrun{
"Not enough buffer space to escape binary data."};
internal::esc_bin(value.view(), begin);
return begin + budget;
}
static binarystring from_string(std::string_view text)
{
auto const size{pqxx::internal::size_unesc_bin(text.size())};
std::shared_ptr<unsigned char> buf{
new unsigned char[size], [](unsigned char const *x) { delete[] x; }};
pqxx::internal::unesc_bin(text, reinterpret_cast<std::byte *>(buf.get()));
return binarystring{std::move(buf), size};
}
};
} // namespace pqxx
#include "pqxx/internal/compiler-internal-post.hxx"
#endif
<commit_msg>Deprecate `binarystring`.<commit_after>/* Representation for raw, binary data.
*
* DO NOT INCLUDE THIS FILE DIRECTLY; include pqxx/binarystring instead.
*
* Copyright (c) 2000-2020, Jeroen T. Vermeulen.
*
* See COPYING for copyright license. If you did not receive a file called
* COPYING with this source code, please notify the distributor of this
* mistake, or contact the author.
*/
#ifndef PQXX_H_BINARYSTRING
#define PQXX_H_BINARYSTRING
#include "pqxx/compiler-public.hxx"
#include "pqxx/internal/compiler-internal-pre.hxx"
#include <memory>
#include <string>
#include <string_view>
#include "pqxx/result.hxx"
#include "pqxx/strconv.hxx"
namespace pqxx
{
class binarystring;
template<> struct string_traits<binarystring>;
/// Binary data corresponding to PostgreSQL's "BYTEA" binary-string type.
/** @ingroup escaping-functions
* @deprecated Use @c std::basic_string<std::byte> and
* @c std::basic_string_view<std::byte> for binary data.
*
* This class represents a binary string as stored in a field of type @c bytea.
*
* Internally a binarystring is zero-terminated, but it may also contain null
* bytes, they're just like any other byte value. So don't assume that it's
* safe to treat the contents as a C-style string.
*
* The binarystring retains its value even if the result it was obtained from
* is destroyed, but it cannot be copied or assigned.
*
* \relatesalso transaction_base::quote_raw
*
* To include a @c binarystring value in an SQL query, escape and quote it
* using the transaction's @c quote_raw function.
*
* @warning This class is implemented as a reference-counting smart pointer.
* Copying, swapping, and destroying binarystring objects that refer to the
* same underlying data block is <em>not thread-safe</em>. If you wish to pass
* binarystrings around between threads, make sure that each of these
* operations is protected against concurrency with similar operations on the
* same object, or other objects pointing to the same data block.
*/
class PQXX_LIBEXPORT binarystring
{
public:
using char_type = unsigned char;
using value_type = std::char_traits<char_type>::char_type;
using size_type = std::size_t;
using difference_type = long;
using const_reference = value_type const &;
using const_pointer = value_type const *;
using const_iterator = const_pointer;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
binarystring(binarystring const &) = default;
/// Read and unescape bytea field.
/** The field will be zero-terminated, even if the original bytea field
* isn't.
* @param F the field to read; must be a bytea field
*/
explicit binarystring(field const &);
/// Copy binary data from std::string_view on binary data.
/** This is inefficient in that it copies the data to a buffer allocated on
* the heap.
*/
explicit binarystring(std::string_view);
/// Copy binary data of given length straight out of memory.
binarystring(void const *, std::size_t);
/// Efficiently wrap a buffer of binary data in a @c binarystring.
binarystring(std::shared_ptr<value_type> ptr, size_type size) :
m_buf{std::move(ptr)}, m_size{size}
{}
/// Size of converted string in bytes.
[[nodiscard]] size_type size() const noexcept { return m_size; }
/// Size of converted string in bytes.
[[nodiscard]] size_type length() const noexcept { return size(); }
[[nodiscard]] bool empty() const noexcept { return size() == 0; }
[[nodiscard]] const_iterator begin() const noexcept { return data(); }
[[nodiscard]] const_iterator cbegin() const noexcept { return begin(); }
[[nodiscard]] const_iterator end() const noexcept { return data() + m_size; }
[[nodiscard]] const_iterator cend() const noexcept { return end(); }
[[nodiscard]] const_reference front() const noexcept { return *begin(); }
[[nodiscard]] const_reference back() const noexcept
{
return *(data() + m_size - 1);
}
[[nodiscard]] const_reverse_iterator rbegin() const
{
return const_reverse_iterator{end()};
}
[[nodiscard]] const_reverse_iterator crbegin() const { return rbegin(); }
[[nodiscard]] const_reverse_iterator rend() const
{
return const_reverse_iterator{begin()};
}
[[nodiscard]] const_reverse_iterator crend() const { return rend(); }
/// Unescaped field contents.
[[nodiscard]] value_type const *data() const noexcept { return m_buf.get(); }
[[nodiscard]] const_reference operator[](size_type i) const noexcept
{
return data()[i];
}
[[nodiscard]] PQXX_PURE bool operator==(binarystring const &) const noexcept;
[[nodiscard]] bool operator!=(binarystring const &rhs) const noexcept
{
return not operator==(rhs);
}
binarystring &operator=(binarystring const &);
/// Index contained string, checking for valid index.
const_reference at(size_type) const;
/// Swap contents with other binarystring.
void swap(binarystring &);
/// Raw character buffer (no terminating zero is added).
/** @warning No terminating zero is added! If the binary data did not end in
* a null character, you will not find one here.
*/
[[nodiscard]] char const *get() const noexcept
{
return reinterpret_cast<char const *>(m_buf.get());
}
/// Read contents as a std::string_view.
[[nodiscard]] std::string_view view() const noexcept
{
return std::string_view(get(), size());
}
/// Read as regular C++ string (may include null characters).
/** This creates and returns a new string object. Don't call this
* repeatedly; retrieve your string once and keep it in a local variable.
* Also, do not expect to be able to compare the string's address to that of
* an earlier invocation.
*/
[[nodiscard]] std::string str() const;
private:
std::shared_ptr<value_type> m_buf;
size_type m_size{0};
};
// TODO: Should binarystring have a default-constructed null value?
template<> struct nullness<binarystring> : no_null<binarystring>
{};
/// String conversion traits for @c binarystring.
/** Defines the conversions between a @c binarystring and its PostgreSQL
* textual format, for communication with the database.
*
* These conversions rely on the "hex" format which was introduced in
* PostgreSQL 9.0. Both your libpq and the server must be recent enough to
* speak this format.
*/
template<> struct string_traits<binarystring>
{
static std::size_t size_buffer(binarystring const &value) noexcept
{
return internal::size_esc_bin(value.size());
}
static zview to_buf(char *begin, char *end, binarystring const &value)
{
auto const value_end{into_buf(begin, end, value)};
return zview{begin, value_end - begin - 1};
}
static char *into_buf(char *begin, char *end, binarystring const &value)
{
auto const budget{size_buffer(value)};
if (static_cast<std::size_t>(end - begin) < budget)
throw conversion_overrun{
"Not enough buffer space to escape binary data."};
internal::esc_bin(value.view(), begin);
return begin + budget;
}
static binarystring from_string(std::string_view text)
{
auto const size{pqxx::internal::size_unesc_bin(text.size())};
std::shared_ptr<unsigned char> buf{
new unsigned char[size], [](unsigned char const *x) { delete[] x; }};
pqxx::internal::unesc_bin(text, reinterpret_cast<std::byte *>(buf.get()));
return binarystring{std::move(buf), size};
}
};
} // namespace pqxx
#include "pqxx/internal/compiler-internal-post.hxx"
#endif
<|endoftext|>
|
<commit_before>///
/// @file config.hpp
/// @brief primesieve compile time constants.
///
/// Copyright (C) 2021 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef CONFIG_HPP
#define CONFIG_HPP
#include <stdint.h>
namespace {
namespace config {
/// Fallback L1 data cache size per core (in bytes) that will
/// be used if the CpuInfo class is unable to detect the CPU's
/// L1 data cache size at runtime.
///
constexpr uint64_t L1D_CACHE_BYTES = 32 << 10;
/// Fallback sieve array size (in bytes) that will be used if
/// the CpuInfo class is unable to detect the CPU's cache sizes
/// at runtime and the user has not set the sieve size.
/// @see get_sieve_size() in api.cpp.
///
/// The best performance is usually achieved using a sieve
/// size that matches the CPU's L1 data cache size per core or
/// that is slightly larger than the CPU's L1 data cache size
/// but smaller than the L2 cache size per core.
///
constexpr uint64_t SIEVE_BYTES = L1D_CACHE_BYTES * 8;
/// Number of sieving primes per Bucket in EratSmall, EratMedium
/// and EratBig objects, affects performance by about 3%.
/// @pre BUCKET_BYTES must be a power of 2.
///
/// - For x86-64 CPUs after 2010 use 8192
/// - For x86-64 CPUs before 2010 use 4096
/// - For PowerPC G4 CPUs 2003 use 2048
///
constexpr uint64_t BUCKET_BYTES = 8 << 10;
/// The MemoryPool allocates at most MAX_ALLOC_BYTES of new
/// memory when it runs out of buckets.
///
constexpr uint64_t MAX_ALLOC_BYTES = 16 << 20;
/// iterator::prev_prime() caches at least MIN_CACHE_ITERATOR
/// bytes of primes. Larger is usually faster but also
/// requires more memory.
///
constexpr uint64_t MIN_CACHE_ITERATOR = 8 << 20;
/// iterator::prev_prime() maximum cache size in bytes, used
/// if pi(sqrt(n)) * 8 bytes > MAX_CACHE_ITERATOR.
///
constexpr uint64_t MAX_CACHE_ITERATOR = 1 << 30;
/// Each thread sieves at least a distance of MIN_THREAD_DISTANCE
/// in order to reduce the initialization overhead.
/// @pre MIN_THREAD_DISTANCE >= 100
///
constexpr uint64_t MIN_THREAD_DISTANCE = (uint64_t) 1e7;
/// Sieving primes <= (L1D_CACHE_BYTES * FACTOR_ERATSMALL)
/// are processed in EratSmall. The ideal value for
/// FACTOR_ERATSMALL has been determined experimentally by
/// running benchmarks near 10^10.
/// @pre FACTOR_ERATSMALL >= 0 && <= 4.5
///
constexpr double FACTOR_ERATSMALL = 0.2;
/// Sieving primes > (sieveSize in bytes * FACTOR_ERATSMALL)
/// and <= (sieveSize in bytes * FACTOR_ERATMEDIUM)
/// are processed in EratMedium.
///
/// When FACTOR_ERATMEDIUM is small fewer sieving primes are
/// processed in EratMedium.cpp and more sieving primes are
/// processed in EratBig.cpp. Generally a larger FACTOR_ERATMEDIUM
/// decreases the number of executed instructions, but increases
/// the number of branch mispredictions. On newer CPUs it is more
/// important to reduce the number of branch mispredictions than to
/// aim for the fewest number of executed instructions.
///
/// @pre FACTOR_ERATMEDIUM >= 0 && <= 4.5
/// FACTOR_ERATMEDIUM * max(sieveSize) / 30 * 6 + 6 <= max(multipleIndex)
/// FACTOR_ERATMEDIUM * 2^23 / 30 * 6 + 6 <= 2^23 - 1
/// FACTOR_ERATMEDIUM <= ((2^23 - 7) * 30) / (2^23 * 6)
/// FACTOR_ERATMEDIUM <= 4.99999582
///
constexpr double FACTOR_ERATMEDIUM = 1.75;
} // namespace config
} // namespace
#endif
<commit_msg>Tune MIN_CACHE_ITERATOR<commit_after>///
/// @file config.hpp
/// @brief primesieve compile time constants.
///
/// Copyright (C) 2022 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef CONFIG_HPP
#define CONFIG_HPP
#include <stdint.h>
namespace {
namespace config {
/// Fallback L1 data cache size per core (in bytes) that will
/// be used if the CpuInfo class is unable to detect the CPU's
/// L1 data cache size at runtime.
///
constexpr uint64_t L1D_CACHE_BYTES = 32 << 10;
/// Fallback sieve array size (in bytes) that will be used if
/// the CpuInfo class is unable to detect the CPU's cache sizes
/// at runtime and the user has not set the sieve size.
/// @see get_sieve_size() in api.cpp.
///
/// The best performance is usually achieved using a sieve
/// size that matches the CPU's L1 data cache size per core or
/// that is slightly larger than the CPU's L1 data cache size
/// but smaller than the L2 cache size per core.
///
constexpr uint64_t SIEVE_BYTES = L1D_CACHE_BYTES * 8;
/// Number of sieving primes per Bucket in EratSmall, EratMedium
/// and EratBig objects, affects performance by about 3%.
/// @pre BUCKET_BYTES must be a power of 2.
///
/// - For x86-64 CPUs after 2010 use 8192
/// - For x86-64 CPUs before 2010 use 4096
/// - For PowerPC G4 CPUs 2003 use 2048
///
constexpr uint64_t BUCKET_BYTES = 8 << 10;
/// The MemoryPool allocates at most MAX_ALLOC_BYTES of new
/// memory when it runs out of buckets.
///
constexpr uint64_t MAX_ALLOC_BYTES = 16 << 20;
/// iterator::prev_prime() caches at least MIN_CACHE_ITERATOR
/// bytes of primes. Larger is usually faster but also
/// requires more memory.
///
constexpr uint64_t MIN_CACHE_ITERATOR = 4 << 20;
/// iterator::prev_prime() maximum cache size in bytes, used
/// if pi(sqrt(n)) * 8 bytes > MAX_CACHE_ITERATOR.
///
constexpr uint64_t MAX_CACHE_ITERATOR = 1 << 30;
/// Each thread sieves at least a distance of MIN_THREAD_DISTANCE
/// in order to reduce the initialization overhead.
/// @pre MIN_THREAD_DISTANCE >= 100
///
constexpr uint64_t MIN_THREAD_DISTANCE = (uint64_t) 1e7;
/// Sieving primes <= (L1D_CACHE_BYTES * FACTOR_ERATSMALL)
/// are processed in EratSmall. The ideal value for
/// FACTOR_ERATSMALL has been determined experimentally by
/// running benchmarks near 10^10.
/// @pre FACTOR_ERATSMALL >= 0 && <= 4.5
///
constexpr double FACTOR_ERATSMALL = 0.2;
/// Sieving primes > (sieveSize in bytes * FACTOR_ERATSMALL)
/// and <= (sieveSize in bytes * FACTOR_ERATMEDIUM)
/// are processed in EratMedium.
///
/// When FACTOR_ERATMEDIUM is small fewer sieving primes are
/// processed in EratMedium.cpp and more sieving primes are
/// processed in EratBig.cpp. Generally a larger FACTOR_ERATMEDIUM
/// decreases the number of executed instructions, but increases
/// the number of branch mispredictions. On newer CPUs it is more
/// important to reduce the number of branch mispredictions than to
/// aim for the fewest number of executed instructions.
///
/// @pre FACTOR_ERATMEDIUM >= 0 && <= 4.5
/// FACTOR_ERATMEDIUM * max(sieveSize) / 30 * 6 + 6 <= max(multipleIndex)
/// FACTOR_ERATMEDIUM * 2^23 / 30 * 6 + 6 <= 2^23 - 1
/// FACTOR_ERATMEDIUM <= ((2^23 - 7) * 30) / (2^23 * 6)
/// FACTOR_ERATMEDIUM <= 4.99999582
///
constexpr double FACTOR_ERATMEDIUM = 1.75;
} // namespace config
} // namespace
#endif
<|endoftext|>
|
<commit_before>#include "SimpleMemory.hh"
SimpleMemory::SimpleMemory(AstraNetworkAPI *NI,double access_latency,double npu_access_bw_GB,double nic_access_bw_GB){
this->last_request_serviced=0;
this->NI=NI;
this->access_latency=access_latency;
this->npu_access_bw_GB=npu_access_bw_GB;
this->nic_access_bw_GB=nic_access_bw_GB;
}
void SimpleMemory::set_network_api(AstraNetworkAPI *astraNetworkApi){
this->NI=astraNetworkApi;
}
uint64_t SimpleMemory::npu_mem_read(uint64_t size){
timespec_t time=NI->sim_get_time();
double time_ns=time.time_val;
double delay=access_latency+(size/npu_access_bw_GB);
double max=last_request_serviced;
if(max<time_ns){
max=time_ns;
}
double offset=(max+delay)-time_ns;
this->last_request_serviced=max+delay;
return (uint64_t)(offset);
}
uint64_t SimpleMemory::SimpleMemory::npu_mem_write(uint64_t size){
timespec_t time=NI->sim_get_time();
double time_ns=time.time_val;
double delay=access_latency+(size/npu_access_bw_GB);
double max=last_request_serviced;
if(max<time_ns){
max=time_ns;
}
double offset=(max+delay)-time_ns;
this->last_request_serviced=max+delay;
return (uint64_t)(offset);
}
uint64_t SimpleMemory::nic_mem_read(uint64_t size){
timespec_t time=NI->sim_get_time();
double time_ns=time.time_val;
double delay=access_latency+(size/nic_access_bw_GB);
double max=last_request_serviced;
if(max<time_ns){
max=time_ns;
}
double offset=(max+delay)-time_ns;
this->last_request_serviced=max+delay;
return (uint64_t)(offset);
}
uint64_t SimpleMemory::nic_mem_write(uint64_t size){
timespec_t time=NI->sim_get_time();
double time_ns=time.time_val;
double delay=access_latency+(size/nic_access_bw_GB);
double max=last_request_serviced;
if(max<time_ns){
max=time_ns;
}
double offset=(max+delay)-time_ns;
this->last_request_serviced=max+delay;
return (uint64_t)(offset);
}
uint64_t SimpleMemory::mem_read(uint64_t size){
return nic_mem_read(size);
}
uint64_t SimpleMemory::mem_write(uint64_t size){
return nic_mem_write(size);
}<commit_msg>updated<commit_after>#include "SimpleMemory.hh"
SimpleMemory::SimpleMemory(AstraNetworkAPI *NI,double access_latency,double npu_access_bw_GB,double nic_access_bw_GB){
this->last_request_serviced=0;
this->NI=NI;
this->access_latency=access_latency;
this->npu_access_bw_GB=npu_access_bw_GB;
this->nic_access_bw_GB=nic_access_bw_GB;
}
void SimpleMemory::set_network_api(AstraNetworkAPI *astraNetworkApi){
this->NI=astraNetworkApi;
}
uint64_t SimpleMemory::npu_mem_read(uint64_t size){
timespec_t time=NI->sim_get_time();
double time_ns=time.time_val;
double delay=access_latency+(size/npu_access_bw_GB);
double max=last_request_serviced;
if(max<time_ns){
max=time_ns;
}
double offset=(max+delay)-time_ns;
this->last_request_serviced=max+delay;
return (uint64_t)(offset);
}
uint64_t SimpleMemory::SimpleMemory::npu_mem_write(uint64_t size){
timespec_t time=NI->sim_get_time();
double time_ns=time.time_val;
double delay=access_latency+(size/npu_access_bw_GB);
double max=last_request_serviced;
if(max<time_ns){
max=time_ns;
}
double offset=(max+delay)-time_ns;
this->last_request_serviced=max+delay;
return (uint64_t)(offset);
}
uint64_t SimpleMemory::nic_mem_read(uint64_t size){
std::cout<<"1";
timespec_t time=NI->sim_get_time();
std::cout<<"2";
double time_ns=time.time_val;
double delay=access_latency+(size/nic_access_bw_GB);
double max=last_request_serviced;
if(max<time_ns){
max=time_ns;
}
double offset=(max+delay)-time_ns;
this->last_request_serviced=max+delay;
return (uint64_t)(offset);
}
uint64_t SimpleMemory::nic_mem_write(uint64_t size){
timespec_t time=NI->sim_get_time();
double time_ns=time.time_val;
double delay=access_latency+(size/nic_access_bw_GB);
double max=last_request_serviced;
if(max<time_ns){
max=time_ns;
}
double offset=(max+delay)-time_ns;
this->last_request_serviced=max+delay;
return (uint64_t)(offset);
}
uint64_t SimpleMemory::mem_read(uint64_t size){
return nic_mem_read(size);
}
uint64_t SimpleMemory::mem_write(uint64_t size){
return nic_mem_write(size);
}<|endoftext|>
|
<commit_before>#ifndef MESSAGES_HPP_
#define MESSAGES_HPP_
#include <cstdint>
namespace protocol {
namespace message {
struct heartbeat_message_t {
enum { ID = 0x00 };
std::uint8_t seq;
} __attribute__((packed));
struct log_message_t {
enum { ID = 0x01 };
char data[255];
} __attribute__((packed));
struct attitude_message_t {
enum { ID = 0x02 };
float roll;
float pitch;
float yaw;
} __attribute__((packed));
struct set_control_mode_message_t {
enum { ID = 0x03 };
enum class ControlMode {
MANUAL,
OFFBOARD
};
ControlMode mode;
} __attribute__((packed));
struct offboard_attitude_control_message_t {
enum { ID = 0x04 };
float roll;
float pitch;
float yaw;
float throttle;
} __attribute__((packed));
inline std::uint16_t length(int id) {
// TODO(kyle): sizeof(empty struct) is 1 in C++...
switch(id) {
case heartbeat_message_t::ID:
return sizeof(heartbeat_message_t);
case log_message_t::ID:
return sizeof(log_message_t);
case attitude_message_t::ID:
return sizeof(attitude_message_t);
case set_control_mode_message_t::ID:
return sizeof(set_control_mode_message_t);
case offboard_attitude_control_message_t::ID:
return sizeof(offboard_attitude_control_message_t);
}
return 0; // TODO(kyle): Return something more meaningful?
}
}
}
#endif // MESSAGES_HPP_
<commit_msg>Add set_arm_state message.<commit_after>#ifndef MESSAGES_HPP_
#define MESSAGES_HPP_
#include <cstdint>
namespace protocol {
namespace message {
struct heartbeat_message_t {
enum { ID = 0x00 };
std::uint8_t seq;
} __attribute__((packed));
struct log_message_t {
enum { ID = 0x01 };
char data[255];
} __attribute__((packed));
struct attitude_message_t {
enum { ID = 0x02 };
float roll;
float pitch;
float yaw;
} __attribute__((packed));
struct set_arm_state_message_t {
enum { ID = 0x03 };
bool armed;
} __attribute__((packed));
struct set_control_mode_message_t {
enum { ID = 0x04 };
enum class ControlMode {
MANUAL,
OFFBOARD
};
ControlMode mode;
} __attribute__((packed));
struct offboard_attitude_control_message_t {
enum { ID = 0x05 };
float roll;
float pitch;
float yaw;
float throttle;
} __attribute__((packed));
inline std::uint16_t length(int id) {
// TODO(kyle): sizeof(empty struct) is 1 in C++...
switch(id) {
case heartbeat_message_t::ID:
return sizeof(heartbeat_message_t);
case log_message_t::ID:
return sizeof(log_message_t);
case attitude_message_t::ID:
return sizeof(attitude_message_t);
case set_arm_state_message_t::ID:
return sizeof(set_arm_state_message_t);
case set_control_mode_message_t::ID:
return sizeof(set_control_mode_message_t);
case offboard_attitude_control_message_t::ID:
return sizeof(offboard_attitude_control_message_t);
}
return 0; // TODO(kyle): Return something more meaningful?
}
}
}
#endif // MESSAGES_HPP_
<|endoftext|>
|
<commit_before>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium 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 3
of the License, or (at your option) any later version.
Bohrium is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the
GNU Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <bh.h>
#include <bh_dag.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <boost/foreach.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/topological_sort.hpp>
#include <vector>
#include <map>
#include <iterator>
using namespace std;
using namespace boost;
typedef adjacency_list<setS, vecS, bidirectionalS, bh_ir_kernel> Graph;
typedef graph_traits<Graph>::vertex_descriptor Vertex;
typedef graph_traits<Graph>::edge_descriptor Edge;
bool fuse_mask(const Graph &dag, const vector<Edge> edges2explore,
const vector<bool> mask, Graph &new_dag)
{
vector<Edge> edges2merge;
unsigned int i=0;
BOOST_FOREACH(const Edge &e, edges2explore)
{
if(mask[i++])
{
edges2merge.push_back(e);
}
}
try
{
bh_dag_merge_vertices(dag, edges2merge, new_dag, true);
}
catch (const runtime_error &e)
{
return false;
}
if(bh_dag_cycles(new_dag))
return false;
return true;
}
int fuser_count=0;
void fuser(bh_ir &bhir)
{
Graph dag;
bh_dag_from_bhir(bhir, dag);
bh_dag_transitive_reduction(dag);
bh_dag_fuse_gentle(dag);
//The list of edges that we should try to merge
vector<Edge> edges2explore;
BOOST_FOREACH(const Edge &e, edges(dag))
{
if(dag[target(e,dag)].fusible(dag[source(e,dag)]))
edges2explore.push_back(e);
}
uint64_t best_cost = numeric_limits<uint64_t>().max();
Graph best_dag;
vector<bool> mask(edges2explore.size(), false);
if(mask.size() == 0)
return;
if(mask.size() > 20)
{
cout << "FUSER-OPTIMAL: ABORT the size of the search space is too large: 2^";
cout << mask.size() << "!" << endl;
return;
}
else if(mask.size() > 10)
{
cout << "FUSER-OPTIMAL: the size of the search space is 2^" << mask.size() << "!" << endl;
}
bool not_finished = true;
while(not_finished)
{
Graph new_dag;
if(fuse_mask(dag, edges2explore, mask, new_dag))
{
const uint64_t c = bh_dag_cost(new_dag);
if(best_cost > c)
{
best_cost = c;
best_dag = new_dag;
#ifdef VERBOSE
std::stringstream ss;
ss << "new_dag-" << fuser_count << "-" << bh_dag_cost(new_dag);
/*
ss << "-";
for(unsigned int i=0; i<mask.size(); ++i)
{
if(mask[i])
ss << "1";
else
ss << "0";
}
*/
ss << ".dot";
printf("write file: %s\n", ss.str().c_str());
bh_dag_pprint(new_dag, ss.str().c_str());
#endif
}
}
for(unsigned int i=mask.size()-1; i >= 0; --i)
{
if(mask[i])
{
if(i == 0)
{
not_finished = false;
break;
}
mask[i] = false;
}
else
{
mask[i] = true;
break;
}
}
}
if(best_cost < numeric_limits<uint64_t>().max())
{
bh_ir b;
vector<Vertex> topological_order;
topological_sort(best_dag, back_inserter(topological_order));
BOOST_REVERSE_FOREACH(const Vertex &v, topological_order)
{
b.kernel_list.push_back(best_dag[v]);
}
b.instr_list = bhir.instr_list;
bhir = b;
}
}
<commit_msg>optimal-fuser: now calling recursive<commit_after>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium 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 3
of the License, or (at your option) any later version.
Bohrium is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the
GNU Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <bh.h>
#include <bh_dag.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <boost/foreach.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/topological_sort.hpp>
#include <vector>
#include <map>
#include <iterator>
using namespace std;
using namespace boost;
typedef adjacency_list<setS, vecS, bidirectionalS, bh_ir_kernel> Graph;
typedef graph_traits<Graph>::vertex_descriptor Vertex;
typedef graph_traits<Graph>::edge_descriptor Edge;
void dag2kernel_list(const Graph &dag, vector<bh_ir_kernel> &kernel_list)
{
vector<Vertex> topological_order;
topological_sort(dag, back_inserter(topological_order));
BOOST_REVERSE_FOREACH(const Vertex &v, topological_order)
{
kernel_list.push_back(dag[v]);
}
}
bool fuse_mask(const Graph &dag, const vector<Edge> &edges2explore,
const vector<bool> &mask, Graph &new_dag)
{
vector<Edge> edges2merge;
unsigned int i=0;
BOOST_FOREACH(const Edge &e, edges2explore)
{
if(mask[i++])
{
edges2merge.push_back(e);
}
}
try
{
bh_dag_merge_vertices(dag, edges2merge, new_dag, true);
}
catch (const runtime_error &e)
{
return false;
}
if(bh_dag_cycles(new_dag))
return false;
return true;
}
int fuser_count=0;
uint64_t best_cost = numeric_limits<uint64_t>().max();
Graph best_dag;
void fuse(const Graph &dag, const vector<Edge> &edges2explore,
vector<bool> mask, unsigned int offset, bool merge_next)
{
if(not merge_next)
{
Graph new_dag;
mask[offset] = merge_next;
if(fuse_mask(dag, edges2explore, mask, new_dag))
{
const uint64_t c = bh_dag_cost(new_dag);
if(best_cost > c)
{
best_cost = c;
best_dag = new_dag;
#ifdef VERBOSE
std::stringstream ss;
ss << "new_best_dag-" << fuser_count << "-" << bh_dag_cost(new_dag) << ".dot";
printf("write file: %s\n", ss.str().c_str());
bh_dag_pprint(new_dag, ss.str().c_str());
#endif
}
}
}
if(offset+1 < mask.size())
{
fuse(dag, edges2explore, mask, offset+1, true);
fuse(dag, edges2explore, mask, offset+1, false);
}
}
void fuser(bh_ir &bhir)
{
Graph dag;
bh_dag_from_bhir(bhir, dag);
bh_dag_transitive_reduction(dag);
bh_dag_fuse_gentle(dag);
//The list of edges that we should try to merge
vector<Edge> edges2explore;
BOOST_FOREACH(const Edge &e, edges(dag))
{
if(dag[target(e,dag)].fusible(dag[source(e,dag)]))
edges2explore.push_back(e);
}
vector<bool> mask(edges2explore.size(), true);
if(mask.size() == 0)
return;
//First we check the trivial case where all kernels are merged
{
Graph new_dag;
if(fuse_mask(dag, edges2explore, mask, new_dag))
{
dag2kernel_list(new_dag, bhir.kernel_list);
return;
}
}
if(mask.size() > 20)
{
cout << "FUSER-OPTIMAL: ABORT the size of the search space is too large: 2^";
cout << mask.size() << "!" << endl;
return;
}
else if(mask.size() > 10)
{
cout << "FUSER-OPTIMAL: the size of the search space is 2^" << mask.size() << "!" << endl;
}
fuse(dag, edges2explore, mask, 0, true);
fuse(dag, edges2explore, mask, 0, false);
if(best_cost < numeric_limits<uint64_t>().max())
{
dag2kernel_list(best_dag, bhir.kernel_list);
}
}
<|endoftext|>
|
<commit_before>#ifndef MESSAGES_HPP_
#define MESSAGES_HPP_
#include <cstdint>
namespace protocol {
namespace message {
struct heartbeat_message_t {
enum { ID = 0x00 };
std::uint8_t seq;
} __attribute__((packed));
struct log_message_t {
enum { ID = 0x01 };
char data[255];
} __attribute__((packed));
struct attitude_message_t {
enum { ID = 0x02 };
float roll;
float pitch;
float yaw;
} __attribute__((packed));
struct set_control_mode_message_t {
enum { ID = 0x03 };
enum class ControlMode {
MANUAL,
OFFBOARD
};
ControlMode mode;
} __attribute__((packed));
inline std::uint16_t length(int id) {
// TODO(kyle): sizeof(empty struct) is 1 in C++...
switch(id) {
case heartbeat_message_t::ID:
return sizeof(heartbeat_message_t);
case log_message_t::ID:
return sizeof(log_message_t);
case attitude_message_t::ID:
return sizeof(attitude_message_t);
case set_control_mode_message_t::ID:
return sizeof(set_control_mode_message_t);
}
return 0; // TODO(kyle): Return something more meaningful?
}
}
}
#endif // MESSAGES_HPP_
<commit_msg>Add offboard control message.<commit_after>#ifndef MESSAGES_HPP_
#define MESSAGES_HPP_
#include <cstdint>
namespace protocol {
namespace message {
struct heartbeat_message_t {
enum { ID = 0x00 };
std::uint8_t seq;
} __attribute__((packed));
struct log_message_t {
enum { ID = 0x01 };
char data[255];
} __attribute__((packed));
struct attitude_message_t {
enum { ID = 0x02 };
float roll;
float pitch;
float yaw;
} __attribute__((packed));
struct set_control_mode_message_t {
enum { ID = 0x03 };
enum class ControlMode {
MANUAL,
OFFBOARD
};
ControlMode mode;
} __attribute__((packed));
struct offboard_attitutde_control_message_t {
enum { ID = 0x04 };
float roll;
float pitch;
float yaw;
float throttle;
} __attribute__((packed));
inline std::uint16_t length(int id) {
// TODO(kyle): sizeof(empty struct) is 1 in C++...
switch(id) {
case heartbeat_message_t::ID:
return sizeof(heartbeat_message_t);
case log_message_t::ID:
return sizeof(log_message_t);
case attitude_message_t::ID:
return sizeof(attitude_message_t);
case set_control_mode_message_t::ID:
return sizeof(set_control_mode_message_t);
case offboard_attitutde_control_message_t::ID:
return sizeof(offboard_attitutde_control_message_t);
}
return 0; // TODO(kyle): Return something more meaningful?
}
}
}
#endif // MESSAGES_HPP_
<|endoftext|>
|
<commit_before>/**
* @author Koen Wolters <koen.wolters@cern.ch>
* @author Daniel Hynds <daniel.hynds@cern.ch>
*/
#include "ModuleFactory.hpp"
#include <dlfcn.h>
#include <utility>
using namespace allpix;
// Constructor and destructor
ModuleFactory::ModuleFactory() : config_(), messenger_(), geometry_manager_() {}
ModuleFactory::~ModuleFactory() = default;
void ModuleFactory::setConfiguration(Configuration conf) {
config_ = std::move(conf);
}
Configuration& ModuleFactory::getConfiguration() {
return config_;
}
void ModuleFactory::setMessenger(Messenger* messenger) {
messenger_ = messenger;
}
Messenger* ModuleFactory::getMessenger() {
return messenger_;
}
void ModuleFactory::setGeometryManager(GeometryManager* geo_manager) {
geometry_manager_ = geo_manager;
}
GeometryManager* ModuleFactory::getGeometryManager() {
return geometry_manager_;
}
// Function to create modules from the dynamic library passed from the Module Manager
std::vector<std::pair<ModuleIdentifier, Module*>> ModuleFactory::createModules(std::string name, void* library) {
// Make the vector to return
std::vector<std::pair<ModuleIdentifier, Module*>> moduleList;
// Load an instance of the module from the library
ModuleIdentifier identifier(name, "", 0);
Module* module = NULL;
void* generator = dlsym(library, "generator");
char* err;
if((err = dlerror()) != NULL) {
// handle error, the symbol wasn't found
throw allpix::DynamicLibraryError(name);
} else {
module = reinterpret_cast<Module* (*)(Configuration, Messenger*, GeometryManager*)>(generator)(
getConfiguration(), getMessenger(), getGeometryManager());
}
moduleList.emplace_back(identifier, module);
return moduleList;
}
<commit_msg>clean up of module loading errors<commit_after>/**
* @author Koen Wolters <koen.wolters@cern.ch>
* @author Daniel Hynds <daniel.hynds@cern.ch>
*/
#include "ModuleFactory.hpp"
#include <dlfcn.h>
#include <utility>
using namespace allpix;
// Constructor and destructor
ModuleFactory::ModuleFactory() : config_(), messenger_(), geometry_manager_() {}
ModuleFactory::~ModuleFactory() = default;
void ModuleFactory::setConfiguration(Configuration conf) {
config_ = std::move(conf);
}
Configuration& ModuleFactory::getConfiguration() {
return config_;
}
void ModuleFactory::setMessenger(Messenger* messenger) {
messenger_ = messenger;
}
Messenger* ModuleFactory::getMessenger() {
return messenger_;
}
void ModuleFactory::setGeometryManager(GeometryManager* geo_manager) {
geometry_manager_ = geo_manager;
}
GeometryManager* ModuleFactory::getGeometryManager() {
return geometry_manager_;
}
// Function to create modules from the dynamic library passed from the Module Manager
std::vector<std::pair<ModuleIdentifier, Module*>> ModuleFactory::createModules(std::string name, void* library) {
// Make the vector to return
std::vector<std::pair<ModuleIdentifier, Module*>> moduleList;
// Load an instance of the module from the library
ModuleIdentifier identifier(name, "", 0);
Module* module = NULL;
// Get the generator function for this module
void* generator = dlsym(library, "generator");
char* err = dlerror();
// If the generator function was not found, throw an error
if(err != NULL) {
throw allpix::DynamicLibraryError(name);
} else {
// Otherwise initialise the module
module = reinterpret_cast<Module* (*)(Configuration, Messenger*, GeometryManager*)>(generator)(
getConfiguration(), getMessenger(), getGeometryManager());
}
// Store the module and return it to the Module Manager
moduleList.emplace_back(identifier, module);
return moduleList;
}
<|endoftext|>
|
<commit_before>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#pragma once
#include <seastar/core/circular_buffer.hh>
#include <seastar/core/future.hh>
#include <queue>
#include <seastar/util/std-compat.hh>
namespace seastar {
/// Asynchronous single-producer single-consumer queue with limited capacity.
/// There can be at most one producer-side and at most one consumer-side operation active at any time.
/// Operations returning a future are considered to be active until the future resolves.
///
/// Note: queue requires the data type T to be nothrow move constructible as it's
/// returned as future<T> by \ref pop_eventually and seastar futurized data type
/// are required to be nothrow move-constructible.
template <typename T>
SEASTAR_CONCEPT(requires std::is_nothrow_move_constructible_v<T>)
class queue {
std::queue<T, circular_buffer<T>> _q;
size_t _max;
std::optional<promise<>> _not_empty;
std::optional<promise<>> _not_full;
std::exception_ptr _ex = nullptr;
private:
void notify_not_empty() noexcept;
void notify_not_full() noexcept;
public:
explicit queue(size_t size);
/// \brief Push an item.
///
/// Returns false if the queue was full and the item was not pushed.
bool push(T&& a);
/// \brief Pop an item.
///
/// Popping from an empty queue will result in undefined behavior.
T pop() noexcept;
/// \brief access the front element in the queue
///
/// Accessing the front of an empty or aborted queue will result in undefined
/// behaviour.
T& front() noexcept;
/// Consumes items from the queue, passing them to \c func, until \c func
/// returns false or the queue it empty
///
/// Returns false if func returned false.
template <typename Func>
bool consume(Func&& func);
/// Returns true when the queue is empty.
bool empty() const noexcept;
/// Returns true when the queue is full.
bool full() const noexcept;
/// Returns a future<> that becomes available when pop() or consume()
/// can be called.
/// A consumer-side operation. Cannot be called concurrently with other consumer-side operations.
future<> not_empty();
/// Returns a future<> that becomes available when push() can be called.
/// A producer-side operation. Cannot be called concurrently with other producer-side operations.
future<> not_full();
/// Pops element now or when there is some. Returns a future that becomes
/// available when some element is available.
/// If the queue is, or already was, abort()ed, the future resolves with
/// the exception provided to abort().
/// A consumer-side operation. Cannot be called concurrently with other consumer-side operations.
future<T> pop_eventually();
/// Pushes the element now or when there is room. Returns a future<> which
/// resolves when data was pushed.
/// If the queue is, or already was, abort()ed, the future resolves with
/// the exception provided to abort().
/// A producer-side operation. Cannot be called concurrently with other producer-side operations.
future<> push_eventually(T&& data);
/// Returns the number of items currently in the queue.
size_t size() const noexcept {
// std::queue::size() has no reason to throw
return _q.size();
}
/// Returns the size limit imposed on the queue during its construction
/// or by a call to set_max_size(). If the queue contains max_size()
/// items (or more), further items cannot be pushed until some are popped.
size_t max_size() const noexcept { return _max; }
/// Set the maximum size to a new value. If the queue's max size is reduced,
/// items already in the queue will not be expunged and the queue will be temporarily
/// bigger than its max_size.
void set_max_size(size_t max) noexcept {
_max = max;
if (!full()) {
notify_not_full();
}
}
/// Destroy any items in the queue, and pass the provided exception to any
/// waiting readers or writers - or to any later read or write attempts.
void abort(std::exception_ptr ex) noexcept {
// std::queue::empty() and pop() doesn't throw
// since it just calls seastar::circular_buffer::pop_front
// that is specified as noexcept.
while (!_q.empty()) {
_q.pop();
}
_ex = ex;
if (_not_full) {
_not_full->set_exception(ex);
_not_full= std::nullopt;
}
if (_not_empty) {
_not_empty->set_exception(std::move(ex));
_not_empty = std::nullopt;
}
}
/// \brief Check if there is an active consumer
///
/// Returns true if another fiber waits for an item to be pushed into the queue
bool has_blocked_consumer() const noexcept {
return bool(_not_empty);
}
};
template <typename T>
inline
queue<T>::queue(size_t size)
: _max(size) {
}
template <typename T>
inline
void queue<T>::notify_not_empty() noexcept {
if (_not_empty) {
_not_empty->set_value();
_not_empty = std::optional<promise<>>();
}
}
template <typename T>
inline
void queue<T>::notify_not_full() noexcept {
if (_not_full) {
_not_full->set_value();
_not_full = std::optional<promise<>>();
}
}
template <typename T>
inline
bool queue<T>::push(T&& data) {
if (_q.size() < _max) {
_q.push(std::move(data));
notify_not_empty();
return true;
} else {
return false;
}
}
template <typename T>
inline
T& queue<T>::front() noexcept {
// std::queue::front() has no reason to throw
return _q.front();
}
template <typename T>
inline
T queue<T>::pop() noexcept {
if (_q.size() == _max) {
notify_not_full();
}
// popping the front element must not throw
// as T is required to be nothrow_move_constructible
// and std::queue::pop won't throw since it uses
// seastar::circular_beffer::pop_front.
T data = std::move(_q.front());
_q.pop();
return data;
}
template <typename T>
inline
future<T> queue<T>::pop_eventually() {
// seastar allows only nothrow_move_constructible types
// to be returned as future<T>
static_assert(std::is_nothrow_move_constructible_v<T>,
"Queue element type must be no-throw move constructible");
if (_ex) {
return make_exception_future<T>(_ex);
}
if (empty()) {
return not_empty().then([this] {
if (_ex) {
return make_exception_future<T>(_ex);
} else {
return make_ready_future<T>(pop());
}
});
} else {
return make_ready_future<T>(pop());
}
}
template <typename T>
inline
future<> queue<T>::push_eventually(T&& data) {
if (_ex) {
return make_exception_future<>(_ex);
}
if (full()) {
return not_full().then([this, data = std::move(data)] () mutable {
_q.push(std::move(data));
notify_not_empty();
});
} else {
_q.push(std::move(data));
notify_not_empty();
return make_ready_future<>();
}
}
template <typename T>
template <typename Func>
inline
bool queue<T>::consume(Func&& func) {
if (_ex) {
std::rethrow_exception(_ex);
}
bool running = true;
while (!_q.empty() && running) {
running = func(std::move(_q.front()));
_q.pop();
}
if (!full()) {
notify_not_full();
}
return running;
}
template <typename T>
inline
bool queue<T>::empty() const noexcept {
// std::queue::empty() has no reason to throw
return _q.empty();
}
template <typename T>
inline
bool queue<T>::full() const noexcept {
// std::queue::size() has no reason to throw
return _q.size() >= _max;
}
template <typename T>
inline
future<> queue<T>::not_empty() {
if (_ex) {
return make_exception_future<>(_ex);
}
if (!empty()) {
return make_ready_future<>();
} else {
_not_empty = promise<>();
return _not_empty->get_future();
}
}
template <typename T>
inline
future<> queue<T>::not_full() {
if (_ex) {
return make_exception_future<>(_ex);
}
if (!full()) {
return make_ready_future<>();
} else {
_not_full = promise<>();
return _not_full->get_future();
}
}
}
<commit_msg>queue: mark not_empty and not_full noexcept<commit_after>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#pragma once
#include <seastar/core/circular_buffer.hh>
#include <seastar/core/future.hh>
#include <queue>
#include <seastar/util/std-compat.hh>
namespace seastar {
/// Asynchronous single-producer single-consumer queue with limited capacity.
/// There can be at most one producer-side and at most one consumer-side operation active at any time.
/// Operations returning a future are considered to be active until the future resolves.
///
/// Note: queue requires the data type T to be nothrow move constructible as it's
/// returned as future<T> by \ref pop_eventually and seastar futurized data type
/// are required to be nothrow move-constructible.
template <typename T>
SEASTAR_CONCEPT(requires std::is_nothrow_move_constructible_v<T>)
class queue {
std::queue<T, circular_buffer<T>> _q;
size_t _max;
std::optional<promise<>> _not_empty;
std::optional<promise<>> _not_full;
std::exception_ptr _ex = nullptr;
private:
void notify_not_empty() noexcept;
void notify_not_full() noexcept;
public:
explicit queue(size_t size);
/// \brief Push an item.
///
/// Returns false if the queue was full and the item was not pushed.
bool push(T&& a);
/// \brief Pop an item.
///
/// Popping from an empty queue will result in undefined behavior.
T pop() noexcept;
/// \brief access the front element in the queue
///
/// Accessing the front of an empty or aborted queue will result in undefined
/// behaviour.
T& front() noexcept;
/// Consumes items from the queue, passing them to \c func, until \c func
/// returns false or the queue it empty
///
/// Returns false if func returned false.
template <typename Func>
bool consume(Func&& func);
/// Returns true when the queue is empty.
bool empty() const noexcept;
/// Returns true when the queue is full.
bool full() const noexcept;
/// Returns a future<> that becomes available when pop() or consume()
/// can be called.
/// A consumer-side operation. Cannot be called concurrently with other consumer-side operations.
future<> not_empty() noexcept;
/// Returns a future<> that becomes available when push() can be called.
/// A producer-side operation. Cannot be called concurrently with other producer-side operations.
future<> not_full() noexcept;
/// Pops element now or when there is some. Returns a future that becomes
/// available when some element is available.
/// If the queue is, or already was, abort()ed, the future resolves with
/// the exception provided to abort().
/// A consumer-side operation. Cannot be called concurrently with other consumer-side operations.
future<T> pop_eventually();
/// Pushes the element now or when there is room. Returns a future<> which
/// resolves when data was pushed.
/// If the queue is, or already was, abort()ed, the future resolves with
/// the exception provided to abort().
/// A producer-side operation. Cannot be called concurrently with other producer-side operations.
future<> push_eventually(T&& data);
/// Returns the number of items currently in the queue.
size_t size() const noexcept {
// std::queue::size() has no reason to throw
return _q.size();
}
/// Returns the size limit imposed on the queue during its construction
/// or by a call to set_max_size(). If the queue contains max_size()
/// items (or more), further items cannot be pushed until some are popped.
size_t max_size() const noexcept { return _max; }
/// Set the maximum size to a new value. If the queue's max size is reduced,
/// items already in the queue will not be expunged and the queue will be temporarily
/// bigger than its max_size.
void set_max_size(size_t max) noexcept {
_max = max;
if (!full()) {
notify_not_full();
}
}
/// Destroy any items in the queue, and pass the provided exception to any
/// waiting readers or writers - or to any later read or write attempts.
void abort(std::exception_ptr ex) noexcept {
// std::queue::empty() and pop() doesn't throw
// since it just calls seastar::circular_buffer::pop_front
// that is specified as noexcept.
while (!_q.empty()) {
_q.pop();
}
_ex = ex;
if (_not_full) {
_not_full->set_exception(ex);
_not_full= std::nullopt;
}
if (_not_empty) {
_not_empty->set_exception(std::move(ex));
_not_empty = std::nullopt;
}
}
/// \brief Check if there is an active consumer
///
/// Returns true if another fiber waits for an item to be pushed into the queue
bool has_blocked_consumer() const noexcept {
return bool(_not_empty);
}
};
template <typename T>
inline
queue<T>::queue(size_t size)
: _max(size) {
}
template <typename T>
inline
void queue<T>::notify_not_empty() noexcept {
if (_not_empty) {
_not_empty->set_value();
_not_empty = std::optional<promise<>>();
}
}
template <typename T>
inline
void queue<T>::notify_not_full() noexcept {
if (_not_full) {
_not_full->set_value();
_not_full = std::optional<promise<>>();
}
}
template <typename T>
inline
bool queue<T>::push(T&& data) {
if (_q.size() < _max) {
_q.push(std::move(data));
notify_not_empty();
return true;
} else {
return false;
}
}
template <typename T>
inline
T& queue<T>::front() noexcept {
// std::queue::front() has no reason to throw
return _q.front();
}
template <typename T>
inline
T queue<T>::pop() noexcept {
if (_q.size() == _max) {
notify_not_full();
}
// popping the front element must not throw
// as T is required to be nothrow_move_constructible
// and std::queue::pop won't throw since it uses
// seastar::circular_beffer::pop_front.
T data = std::move(_q.front());
_q.pop();
return data;
}
template <typename T>
inline
future<T> queue<T>::pop_eventually() {
// seastar allows only nothrow_move_constructible types
// to be returned as future<T>
static_assert(std::is_nothrow_move_constructible_v<T>,
"Queue element type must be no-throw move constructible");
if (_ex) {
return make_exception_future<T>(_ex);
}
if (empty()) {
return not_empty().then([this] {
if (_ex) {
return make_exception_future<T>(_ex);
} else {
return make_ready_future<T>(pop());
}
});
} else {
return make_ready_future<T>(pop());
}
}
template <typename T>
inline
future<> queue<T>::push_eventually(T&& data) {
if (_ex) {
return make_exception_future<>(_ex);
}
if (full()) {
return not_full().then([this, data = std::move(data)] () mutable {
_q.push(std::move(data));
notify_not_empty();
});
} else {
_q.push(std::move(data));
notify_not_empty();
return make_ready_future<>();
}
}
template <typename T>
template <typename Func>
inline
bool queue<T>::consume(Func&& func) {
if (_ex) {
std::rethrow_exception(_ex);
}
bool running = true;
while (!_q.empty() && running) {
running = func(std::move(_q.front()));
_q.pop();
}
if (!full()) {
notify_not_full();
}
return running;
}
template <typename T>
inline
bool queue<T>::empty() const noexcept {
// std::queue::empty() has no reason to throw
return _q.empty();
}
template <typename T>
inline
bool queue<T>::full() const noexcept {
// std::queue::size() has no reason to throw
return _q.size() >= _max;
}
template <typename T>
inline
future<> queue<T>::not_empty() noexcept {
if (_ex) {
return make_exception_future<>(_ex);
}
if (!empty()) {
return make_ready_future<>();
} else {
_not_empty = promise<>();
return _not_empty->get_future();
}
}
template <typename T>
inline
future<> queue<T>::not_full() noexcept {
if (_ex) {
return make_exception_future<>(_ex);
}
if (!full()) {
return make_ready_future<>();
} else {
_not_full = promise<>();
return _not_full->get_future();
}
}
}
<|endoftext|>
|
<commit_before>#ifndef V_SMC_CORE_SAMPLER_HPP
#define V_SMC_CORE_SAMPLER_HPP
#include <vSMC/internal/common.hpp>
#include <iostream>
#include <map>
#include <set>
#include <string>
namespace vSMC {
/// \brief SMC Sampler
///
/// \tparam T State state type. Requiment:
/// \li Consturctor: T (IntType N)
/// \li Method: copy (IntType from, IntType to)
template <typename T>
class Sampler
{
public :
/// The type of initialization functor
typedef internal::function<unsigned (Particle<T> &, void *)>
initialize_type;
/// The type of move and mcmc functor
typedef internal::function<unsigned (unsigned, Particle<T> &)>
move_type;
/// The type of ESS history vector
typedef std::vector<double> ess_type;
/// The type of resampling history vector
typedef std::vector<bool> resampled_type;
/// The type of accept count history vector
typedef std::vector<unsigned> accept_type;
/// \brief Construct a sampler with given number of particles
///
/// \param N The number of particles
/// \param init The functor used to initialize the particles
/// \param move The functor used to move the particles and weights
/// \param scheme The resampling scheme. See ResampleScheme
/// \param threshold The threshold for performing resampling
/// \param seed The seed to the parallel RNG system
explicit Sampler (
typename Particle<T>::size_type N,
const initialize_type &init = NULL,
const move_type &move = NULL,
ResampleScheme scheme = STRATIFIED,
double threshold = 0.5,
typename Particle<T>::seed_type seed = V_SMC_CRNG_SEED) :
initialized_(false), init_(init), move_(move),
scheme_(scheme), threshold_(threshold),
particle_(N, seed), iter_num_(0) {}
/// \brief Size of the particle set
///
/// \return The number of particles
typename Particle<T>::size_type size () const
{
return particle_.size();
}
/// \brief The number of iterations recorded
///
/// \return The number of iterations recorded so far (including the
/// initialization)
unsigned iter_size () const
{
return ess_.size();
}
/// \brief The number of iterations
///
/// \return The number of iterations performed by iterate() so far (not
/// including the initialization)
unsigned iter_num () const
{
return iter_num_;
}
/// \brief Get the current resampling scheme
///
/// \return The current resampling scheme
ResampleScheme resample_scheme () const
{
return scheme_;
}
/// \brief Set new resampling scheme
///
/// \param scheme The new scheme for resampling
void resample_scheme (ResampleScheme scheme)
{
scheme_ = scheme;
}
/// \brief Get the current threshold
///
/// \return The current threshold for resmapling
double resample_threshold () const
{
return threshold_;
}
/// \brief Set new resampling threshold
///
/// \param threshold The new threshold for resampling
void resample_threshold (double threshold)
{
threshold_ = threshold;
}
/// \brief Reserve space for histories
///
/// \param num Expected iteration number
void reserve (unsigned num)
{
ess_.reserve(num);
resampled_.reserve(num);
accept_.reserve(num);
for (typename std::map<std::string, Monitor<T> >::iterator
imap = monitor_.begin(); imap != monitor_.end(); ++imap) {
if (!imap->second.empty())
imap->second.reserve(num);
}
if (!path_.empty())
path_.reserve(num);
}
/// \brief ESS history
///
/// \return A const reference to the history of ESS
const ess_type &ess () const
{
return ess_;
}
/// \brief Resampling history
///
/// \return A const reference to the history of resampling
const resampled_type &resampled () const
{
return resampled_;
}
/// \brief Accept count history
///
/// \return A const reference to the history of accept count
const accept_type &accept () const
{
return accept_;
}
/// \brief Read and write access to the particle set
///
/// \return A reference to the latest particle set
Particle<T> &particle ()
{
return particle_;
}
/// \brief Read only access to the particle set
///
/// \return A const reference to the latest particle set.
const Particle<T> &particle () const
{
return particle_;
}
/// \brief Replace initialization functor
///
/// \param new_init New Initialization functor
void init (const initialize_type &new_init)
{
init_ = new_init;
}
/// \brief Replace iteration functor
///
/// \param new_move New Move functor
void move (const move_type &new_move)
{
move_ = new_move;
}
/// \brief Replace iteration functor
///
/// \param new_mcmc New MCMC Move functor
void mcmc (const move_type &new_mcmc)
{
mcmc_.push_back(new_mcmc);
}
/// \brief Clear all MCMC moves
void clear_mcmc ()
{
mcmc_.clear();
}
/// \brief Initialize the particle set
///
/// \param param Additional parameters passed to the initialization
/// functor
void initialize (void *param = NULL)
{
assert(bool(init_));
ess_.clear();
resampled_.clear();
accept_.clear();
path_.clear();
for (typename std::map<std::string, Monitor<T> >::iterator
imap = monitor_.begin(); imap != monitor_.end(); ++imap)
imap->second.clear();
iter_num_ = 0;
accept_.push_back(init_(particle_, param));
post_move();
particle_.reset_zconst();
initialized_ = true;
}
/// \brief Perform iteration
void iterate ()
{
assert(initialized_);
assert(bool(move_));
++iter_num_;
if (bool(move_))
accept_.push_back(move_(iter_num_, particle_));
for (typename std::vector<move_type>::iterator miter = mcmc_.begin();
miter != mcmc_.end(); ++miter)
accept_.back() = (*miter)(iter_num_, particle_);
post_move();
}
/// \brief Perform iteration
///
/// \param n The number of iterations to be performed
void iterate (unsigned n)
{
for (unsigned i = 0; i != n; ++i)
iterate();
}
/// \brief Perform importance sampling integration
///
/// \param integral The functor used to compute the integrands
/// \param res The result, an array of length dim
template<typename MonitorType>
void integrate (const MonitorType &integral, double *res)
{
Monitor<T> m(integral.dim(), integral);
m.eval(iter_num_, particle_);
Eigen::Map<Eigen::VectorXd> r(res, m.dim());
r = m.record().back();
}
/// \brief Perform importance sampling integration
///
/// \param dim The dimension of the parameter
/// \param integral The functor used to compute the integrands
/// \param res The result, an array of length dim
void integrate (unsigned dim,
const typename Monitor<T>::integral_type &integral, double *res)
{
assert(bool(integral));
Monitor<T> m(dim, integral);
m.eval(iter_num_, particle_);
Eigen::Map<Eigen::VectorXd> r(res, m.dim());
r = m.record().back();
}
/// \brief Add a monitor, similar to \b monitor in \b BUGS
///
/// \param name The name of the monitor
/// \param integral The functor used to compute the integrands
template<typename MonitorType>
void monitor (const std::string &name, const MonitorType &integral)
{
monitor_.insert(std::make_pair(
name, Monitor<T>(integral.dim(), integral)));
monitor_name_.insert(name);
}
/// \brief Add a monitor, similar to \b monitor in \b BUGS
///
/// \param name The name of the monitor
/// \param dim The dimension of the monitor
/// \param integral The functor used to compute the integrands
void monitor (const std::string &name, unsigned dim,
const typename Monitor<T>::integral_type &integral)
{
monitor_.insert(std::make_pair(name, Monitor<T>(dim, integral)));
monitor_name_.insert(name);
}
/// \brief Read only access to a named monitor through iterator
///
/// \param name The name of the monitor
///
/// \return An const_iterator point to the monitor for the given name
typename std::map<std::string, Monitor<T> >::const_iterator
monitor (const std::string &name) const
{
return monitor_.find(name);
}
/// \brief Read only access to all monitors
///
/// \return A const reference to monitors
const std::map<std::string, Monitor<T> > &monitor () const
{
return monitor_;
}
/// \brief Erase a named monitor
///
/// \param name The name of the monitor
void clear_monitor (const std::string &name)
{
monitor_.erase(name);
monitor_name_.erase(name);
}
/// \brief Erase all monitors
void clear_monitor ()
{
monitor_.clear();
monitor_name_.clear();
}
/// \brief Read only access to the Path sampling monitor
///
/// \return A const reference to the Path sampling monitor
const Path<T> &path () const
{
return path_;
}
/// \brief Set the path sampling integral
///
/// \param integral The functor used to compute the integrands
void path_sampling (const typename Path<T>::integral_type &integral)
{
path_.integral(integral);
}
/// \brief Path sampling estimate of normalizing constant
///
/// \return The log ratio of normalizing constants
double path_sampling () const
{
return path_.zconst();
}
/// \brief SMC estimate of normalizing constant
///
/// \return The log of SMC normalizng constant estimate
double zconst () const
{
return particle_.zconst();
}
/// \brief Print the history of the sampler
///
/// \param os The ostream to which the contents are printed
/// \param print_header Print header if \b true
void print (std::ostream &os = std::cout, bool print_header = true) const
{
print(os, print_header, !path_.index().empty(), monitor_name_);
}
/// \brief Print the history of the sampler
///
/// \param os The ostream to which the contents are printed
/// \param print_path Print path sampling history if \b true
/// \param print_monitor A set of monitor names to be printed
/// \param print_header Print header if \b true
void print (std::ostream &os, bool print_header, bool print_path,
const std::set<std::string> &print_monitor) const
{
if (print_header) {
os << "iter\tESS\tresample\taccept\t";
if (print_path)
os << "path.integrand\tpath.width\tpath.grid\t";
}
typename Path<T>::index_type::const_iterator iter_path_index
= path_.index().begin();
typename Path<T>::integrand_type::const_iterator iter_path_integrand
= path_.integrand().begin();
typename Path<T>::width_type::const_iterator iter_path_width
= path_.width().begin();
typename Path<T>::grid_type::const_iterator iter_path_grid
= path_.grid().begin();
std::vector<bool> monitor_index_empty;
std::vector<unsigned> monitor_dim;
std::vector<typename Monitor<T>::index_type::const_iterator>
iter_monitor_index;
std::vector<typename Monitor<T>::record_type::const_iterator>
iter_monitor_record;
for (typename std::map<std::string, Monitor<T> >::const_iterator
imap = monitor_.begin(); imap != monitor_.end(); ++imap) {
if (print_monitor.count(imap->first)) {
monitor_index_empty.push_back(imap->second.index().empty());
monitor_dim.push_back(imap->second.dim());
iter_monitor_index.push_back(imap->second.index().begin());
iter_monitor_record.push_back(imap->second.record().begin());
if (print_header) {
if (monitor_dim.back() > 1) {
for (unsigned d = 0; d != monitor_dim.back(); ++d)
os << imap->first << d + 1 << '\t';
} else {
os << imap->first << '\t';
}
}
}
}
if (print_header)
os << '\n';
for (unsigned i = 0; i != iter_num_ + 1; ++i) {
os
<< i << '\t' << ess_[i] / size()
<< '\t' << resampled_[i]
<< '\t' << static_cast<double>(accept_[i]) / size();
if (print_path) {
if (!path_.index().empty() && *iter_path_index == i) {
os
<< '\t' << *iter_path_integrand++
<< '\t' << *iter_path_width++
<< '\t' << *iter_path_grid++;
++iter_path_index;
} else {
os << '\t' << '.' << '\t' << '.' << '\t' << '.';
}
}
for (unsigned m = 0; m != monitor_index_empty.size(); ++m) {
if (!monitor_index_empty[m] && *iter_monitor_index[m] == i) {
for (unsigned d = 0; d != monitor_dim[m]; ++d)
os << '\t' << (*iter_monitor_record[m])[d];
++iter_monitor_index[m];
++iter_monitor_record[m];
} else {
for (unsigned d = 0; d != monitor_dim[m]; ++d)
os << '\t' << '.';
}
}
os << '\n';
}
}
private :
/// Initialization indicator
bool initialized_;
/// Initialization and movement
initialize_type init_;
move_type move_;
std::vector<move_type> mcmc_;
/// Resampling
ResampleScheme scheme_;
double threshold_;
/// Particle sets
Particle<T> particle_;
unsigned iter_num_;
ess_type ess_;
resampled_type resampled_;
accept_type accept_;
/// Monte Carlo estimation by integration
std::map<std::string, Monitor<T> > monitor_;
std::set<std::string> monitor_name_;
/// Path sampling
Path<T> path_;
void post_move ()
{
bool do_resample = particle_.ess() < threshold_ * size();
if (do_resample)
particle_.resample(scheme_);
if (!path_.empty())
path_.eval(iter_num_, particle_);
for (typename std::map<std::string, Monitor<T> >::iterator
imap = monitor_.begin(); imap != monitor_.end(); ++imap) {
if (!imap->second.empty())
imap->second.eval(iter_num_, particle_);
}
ess_.push_back(particle_.ess());
resampled_.push_back(do_resample);
particle_.resampled(resampled_.back());
particle_.accept(accept_.back());
}
}; // class Sampler
} // namespace vSMC
namespace std {
/// \brief Print the sampler
///
/// \param os The ostream to which the contents are printed
/// \param sampler The sampler to be printed
///
/// \note This is the same as <tt>sampler.print(os)</tt>
template<typename T>
std::ostream & operator<< (std::ostream &os, const vSMC::Sampler<T> &sampler)
{
sampler.print(os);
return os;
}
} // namespace std
#endif // V_SMC_CORE_SAMPLER_HPP
<commit_msg>split accept count recording and accordingly new print<commit_after>#ifndef V_SMC_CORE_SAMPLER_HPP
#define V_SMC_CORE_SAMPLER_HPP
#include <vSMC/internal/common.hpp>
#include <iostream>
#include <map>
#include <set>
#include <string>
namespace vSMC {
/// \brief SMC Sampler
///
/// \tparam T State state type. Requiment:
/// \li Consturctor: T (IntType N)
/// \li Method: copy (IntType from, IntType to)
template <typename T>
class Sampler
{
public :
/// The type of initialization functor
typedef internal::function<unsigned (Particle<T> &, void *)>
initialize_type;
/// The type of move and mcmc functor
typedef internal::function<unsigned (unsigned, Particle<T> &)>
move_type;
/// The type of ESS history vector
typedef std::deque<double> ess_type;
/// The type of resampling history vector
typedef std::deque<bool> resampled_type;
/// The type of accept count history vector
typedef std::deque<std::deque<unsigned> > accept_type;
/// The type of Monitor map
typedef std::map<std::string, Monitor<T> > monitor_map;
/// \brief Construct a sampler with given number of particles
///
/// \param N The number of particles
/// \param init The functor used to initialize the particles
/// \param move The functor used to move the particles and weights
/// \param scheme The resampling scheme. See ResampleScheme
/// \param threshold The threshold for performing resampling
/// \param seed The seed to the parallel RNG system
explicit Sampler (
typename Particle<T>::size_type N,
const initialize_type &init = NULL,
const move_type &move = NULL,
ResampleScheme scheme = STRATIFIED,
double threshold = 0.5,
typename Particle<T>::seed_type seed = V_SMC_CRNG_SEED) :
initialized_(false), init_(init), move_(move),
scheme_(scheme), threshold_(threshold),
particle_(N, seed), iter_num_(0) {}
/// \brief Size of the particle set
///
/// \return The number of particles
typename Particle<T>::size_type size () const
{
return particle_.size();
}
/// \brief The number of iterations recorded
///
/// \return The number of iterations recorded so far (including the
/// initialization)
unsigned iter_size () const
{
return ess_.size();
}
/// \brief The number of iterations
///
/// \return The number of iterations performed by iterate() so far (not
/// including the initialization)
unsigned iter_num () const
{
return iter_num_;
}
/// \brief Get the current resampling scheme
///
/// \return The current resampling scheme
ResampleScheme resample_scheme () const
{
return scheme_;
}
/// \brief Set new resampling scheme
///
/// \param scheme The new scheme for resampling
void resample_scheme (ResampleScheme scheme)
{
scheme_ = scheme;
}
/// \brief Get the current threshold
///
/// \return The current threshold for resmapling
double resample_threshold () const
{
return threshold_;
}
/// \brief Set new resampling threshold
///
/// \param threshold The new threshold for resampling
void resample_threshold (double threshold)
{
threshold_ = threshold;
}
/// \brief ESS history
///
/// \return A const reference to the history of ESS
const ess_type &ess () const
{
return ess_;
}
/// \brief Resampling history
///
/// \return A const reference to the history of resampling
const resampled_type &resampled () const
{
return resampled_;
}
/// \brief Accept count history
///
/// \return A const reference to the history of accept count
const accept_type &accept () const
{
return accept_;
}
/// \brief Read and write access to the particle set
///
/// \return A reference to the latest particle set
Particle<T> &particle ()
{
return particle_;
}
/// \brief Read only access to the particle set
///
/// \return A const reference to the latest particle set.
const Particle<T> &particle () const
{
return particle_;
}
/// \brief Replace initialization functor
///
/// \param new_init New Initialization functor
void init (const initialize_type &new_init)
{
init_ = new_init;
}
/// \brief Replace iteration functor
///
/// \param new_move New Move functor
void move (const move_type &new_move)
{
move_ = new_move;
}
/// \brief Replace iteration functor
///
/// \param new_mcmc New MCMC Move functor
void mcmc (const move_type &new_mcmc)
{
mcmc_.push_back(new_mcmc);
}
/// \brief Clear all MCMC moves
void clear_mcmc ()
{
mcmc_.clear();
}
/// \brief Initialize the particle set
///
/// \param param Additional parameters passed to the initialization
/// functor
void initialize (void *param = NULL)
{
assert(bool(init_));
ess_.clear();
resampled_.clear();
accept_.clear();
path_.clear();
for (typename monitor_map::iterator miter = monitor_.begin();
miter != monitor_.end(); ++miter)
miter->second.clear();
iter_num_ = 0;
accept_.push_back(std::deque<unsigned>(1, init_(particle_, param)));
post_move();
particle_.reset_zconst();
initialized_ = true;
}
/// \brief Perform iteration
void iterate ()
{
++iter_num_;
std::deque<unsigned> acc;
if (bool(move_))
acc.push_back(move_(iter_num_, particle_));
for (typename std::deque<move_type>::iterator miter = mcmc_.begin();
miter != mcmc_.end(); ++miter)
acc.push_back((*miter)(iter_num_, particle_));
accept_.push_back(acc);
post_move();
}
/// \brief Perform iteration
///
/// \param n The number of iterations to be performed
void iterate (unsigned n)
{
for (unsigned i = 0; i != n; ++i)
iterate();
}
/// \brief Perform importance sampling integration
///
/// \param dim The dimension of the parameter
/// \param integral The functor used to compute the integrands
/// \param res The result, an array of length dim
void integrate (unsigned dim,
const typename Monitor<T>::integral_type &integral, double *res)
{
assert(bool(integral));
assert(dim > 0);
Monitor<T> m(dim, integral);
m.eval(iter_num_, particle_);
for (unsigned d = 0; d += dim; ++d)
res[d] = m.record()[d].back();
}
/// \brief Add a monitor, similar to \b monitor in \b BUGS
///
/// \param name The name of the monitor
/// \param integral The functor used to compute the integrands
template<typename MonitorIntegralType>
void monitor (const std::string &name, const MonitorIntegralType &integral)
{
monitor_.insert(std::make_pair(
name, Monitor<T>(integral.dim(), integral)));
monitor_name_.insert(name);
}
/// \brief Add a monitor, similar to \b monitor in \b BUGS
///
/// \param name The name of the monitor
/// \param dim The dimension of the monitor
/// \param integral The functor used to compute the integrands
void monitor (const std::string &name, unsigned dim,
const typename Monitor<T>::integral_type &integral)
{
monitor_.insert(std::make_pair(name, Monitor<T>(dim, integral)));
monitor_name_.insert(name);
}
/// \brief Read only access to a named monitor through iterator
///
/// \param name The name of the monitor
///
/// \return An const_iterator point to the monitor for the given name
typename monitor_map::const_iterator monitor (
const std::string &name) const
{
return monitor_.find(name);
}
/// \brief Read and write access to a named monitor through iterator
///
/// \param name The name of the monitor
///
/// \return An iterator point to the monitor for the given name
typename monitor_map::iterator monitor (const std::string &name)
{
return monitor_.find(name);
}
/// \brief Read only access to all monitors
///
/// \return A const reference to monitors
const monitor_map &monitor () const
{
return monitor_;
}
/// \brief Read and write access to all monitors
///
/// \return A reference to monitors
monitor_map &monitor ()
{
return monitor_;
}
/// \brief Erase a named monitor
///
/// \param name The name of the monitor
void clear_monitor (const std::string &name)
{
monitor_.erase(name);
monitor_name_.erase(name);
}
/// \brief Erase all monitors
void clear_monitor ()
{
monitor_.clear();
monitor_name_.clear();
}
/// \brief Read only access to the Path sampling monitor
///
/// \return A const reference to the Path sampling monitor
const Path<T> &path () const
{
return path_;
}
/// \brief Set the path sampling integral
///
/// \param integral The functor used to compute the integrands
void path_sampling (const typename Path<T>::integral_type &integral)
{
path_.integral(integral);
}
/// \brief Path sampling estimate of normalizing constant
///
/// \return The log ratio of normalizing constants
double path_sampling () const
{
return path_.zconst();
}
/// \brief SMC estimate of normalizing constant
///
/// \return The log of SMC normalizng constant estimate
double zconst () const
{
return particle_.zconst();
}
/// \brief Print the history of the sampler
///
/// \param os The ostream to which the contents are printed
/// \param print_header Print header if \b true
void print (std::ostream &os = std::cout, bool print_header = true) const
{
// Accept count
unsigned accept_dim = 0;
for (accept_type::const_iterator aiter = accept_.begin();
aiter != accept_.end(); ++aiter)
if (aiter->size() > accept_dim)
accept_dim = aiter->size();
Eigen::MatrixXd accept_data(iter_num_ + 1, accept_dim);
accept_data.setConstant(0);
double anorm = static_cast<double>(size());
for (unsigned r = 0; r != iter_num_ + 1; ++r)
for (unsigned c = 0; c != accept_[r].size(); ++c)
accept_data(r, c) = accept_[r][c] / anorm;
// Path sampling
Eigen::MatrixXd path_data(iter_num_ + 1, 3);
Eigen::Matrix<bool, Eigen::Dynamic, Eigen::Dynamic>
path_mask(iter_num_ + 1, 1);
path_mask.setConstant(false);
for (unsigned d = 0; d != path_.iter_size(); ++d) {
unsigned prow = path_.index()[d];
path_data(prow, 0) = path_.integrand()[d];
path_data(prow, 1) = path_.width()[d];
path_data(prow, 2) = path_.grid()[d];
path_mask(prow) = true;
}
// Monitors
unsigned monitor_dim = 0;
for (typename monitor_map::const_iterator miter = monitor_.begin();
miter != monitor_.end(); ++miter)
monitor_dim += miter->second.dim();
Eigen::MatrixXd monitor_data(iter_num_ + 1, monitor_dim);
Eigen::Matrix<bool, Eigen::Dynamic, Eigen::Dynamic>
monitor_mask(iter_num_ + 1, monitor_.size());
unsigned mcol = 0;
unsigned mmask = 0;
for (typename monitor_map::const_iterator miter = monitor_.begin();
miter != monitor_.end(); ++miter) {
unsigned mdim = miter->second.dim();
for (unsigned d = 0; d != miter->second.iter_size(); ++d) {
unsigned mrow = miter->second.index()[d];
for (unsigned c = 0; c != mdim; ++c) {
monitor_data(mrow, c + mcol) =
miter->second.record()[c][d];
}
monitor_mask(mrow, mmask) = true;
}
mcol += miter->second.dim();
++mmask;
}
// Print header
if (print_header) {
os << "iter\tESS\tresample\t";
if (accept_dim == 1) {
os << "accept\t";
}
else {
for (unsigned d = 0; d != accept_dim; ++d)
os << "accept" << d + 1 << '\t';
}
os << "path.integrand\tpath.width\tpath.grid\t";
for (typename monitor_map::const_iterator miter = monitor_.begin();
miter != monitor_.end(); ++miter) {
if (miter->second.dim() == 1) {
os << miter->first << '\t';
} else {
for (unsigned d = 0; d != miter->second.dim(); ++d)
os << miter->first << d + 1 << '\t';
}
}
os << '\n';
}
// Print data
for (unsigned iter = 0; iter != iter_num_ + 1; ++iter) {
os << iter << '\t';
os << ess_[iter] / size() << '\t';
os << resampled_[iter] << '\t';
os << accept_data.row(iter) << '\t';
if (path_mask(iter))
os << path_data.row(iter) << '\t';
else
os << ".\t.\t.\t";
unsigned mcol = 0;
unsigned mmask = 0;
for (typename monitor_map::const_iterator miter = monitor_.begin();
miter != monitor_.end(); ++miter) {
unsigned mdim = miter->second.dim();
if (monitor_mask(iter, mmask)) {
os << monitor_data.block(iter, mcol, 1, mdim) << '\t';
} else {
for (unsigned m = 0; m != mdim; ++m)
os << ".\t";
}
mcol += miter->second.dim();
++mmask;
}
os << '\n';
}
}
private :
/// Initialization indicator
bool initialized_;
/// Initialization and movement
initialize_type init_;
move_type move_;
std::deque<move_type> mcmc_;
/// Resampling
ResampleScheme scheme_;
double threshold_;
/// Particle sets
Particle<T> particle_;
unsigned iter_num_;
ess_type ess_;
resampled_type resampled_;
accept_type accept_;
/// Monte Carlo estimation by integration
monitor_map monitor_;
std::set<std::string> monitor_name_;
/// Path sampling
Path<T> path_;
void post_move ()
{
bool do_resample = particle_.ess() < threshold_ * size();
if (do_resample)
particle_.resample(scheme_);
if (!path_.empty())
path_.eval(iter_num_, particle_);
for (typename std::map<std::string, Monitor<T> >::iterator
imap = monitor_.begin(); imap != monitor_.end(); ++imap) {
if (!imap->second.empty())
imap->second.eval(iter_num_, particle_);
}
ess_.push_back(particle_.ess());
resampled_.push_back(do_resample);
particle_.resampled(resampled_.back());
particle_.accept(accept_.back().back());
}
}; // class Sampler
} // namespace vSMC
namespace std {
/// \brief Print the sampler
///
/// \param os The ostream to which the contents are printed
/// \param sampler The sampler to be printed
///
/// \note This is the same as <tt>sampler.print(os)</tt>
template<typename T>
std::ostream & operator<< (std::ostream &os, const vSMC::Sampler<T> &sampler)
{
sampler.print(os);
return os;
}
} // namespace std
#endif // V_SMC_CORE_SAMPLER_HPP
<|endoftext|>
|
<commit_before>#if defined(_MSC_VER)
#define _CRTDBG_MAP_ALLOC
#define _CRT_SECURE_NO_WARNINGS
#include <crtdbg.h>
#endif
#include "CoolPropDLL.h"
#include "CoolProp.h"
#include "HumidAirProp.h"
#include "DataStructures.h"
#include "Exceptions.h"
double convert_from_kSI_to_SI(long iInput, double value)
{
if (get_debug_level() > 8){
std::cout << format("%s:%d: convert_from_kSI_to_SI(i=%d,value=%g)\n",__FILE__,__LINE__,iInput,value).c_str();
}
switch (iInput)
{
case CoolProp::iP:
case CoolProp::iCpmass:
case CoolProp::iCp0mass:
case CoolProp::iSmass:
case CoolProp::iGmass:
case CoolProp::iCvmass:
case CoolProp::iHmass:
case CoolProp::iUmass:
case CoolProp::iconductivity:
return value*1000.0;
case CoolProp::iDmass:
case CoolProp::ispeed_sound:
case CoolProp::iQ:
case CoolProp::iviscosity:
case CoolProp::iT:
case CoolProp::iPrandtl:
case CoolProp::isurface_tension:
return value;
default:
throw CoolProp::ValueError(format("index [%d] is invalid in convert_from_kSI_to_SI",iInput).c_str());
break;
}
return _HUGE;
}
double convert_from_SI_to_kSI(long iInput, double value)
{
if (get_debug_level() > 8){
std::cout << format("%s:%d: convert_from_SI_to_kSI(%d,%g)\n",__FILE__,__LINE__,iInput,value).c_str();
}
switch (iInput)
{
case CoolProp::iP:
case CoolProp::iCpmass:
case CoolProp::iCp0mass:
case CoolProp::iSmass:
case CoolProp::iGmass:
case CoolProp::iCvmass:
case CoolProp::iHmass:
case CoolProp::iUmass:
case CoolProp::iconductivity:
return value/1000.0;
case CoolProp::iDmass:
case CoolProp::iQ:
case CoolProp::ispeed_sound:
case CoolProp::iviscosity:
case CoolProp::iT:
case CoolProp::isurface_tension:
return value;
default:
throw CoolProp::ValueError(format("index [%d] is invalid in convert_from_SI_to_kSI", iInput).c_str());
break;
}
return _HUGE;
}
EXPORT_CODE long CONVENTION redirect_stdout(const char* file){
freopen(file, "a+", stdout);
return 0;
}
//EXPORT_CODE int CONVENTION set_reference_stateS(const char *Ref, const char *reference_state)
//{
// return set_reference_stateS(std::string(Ref), std::string(reference_state));
//}
//EXPORT_CODE int CONVENTION set_reference_stateD(const char *Ref, double T, double rho, double h0, double s0)
//{
// return set_reference_stateD(std::string(Ref), T, rho, h0, s0);
//}
// All the function interfaces that point to the single-input Props function
EXPORT_CODE double CONVENTION Props1(const char *FluidName, const char *Output){
return PropsS(Output, "", 0, "", 0, FluidName);
}
EXPORT_CODE double CONVENTION PropsS(const char *Output, const char* Name1, double Prop1, const char* Name2, double Prop2, const char * Ref){
double val = Props(Output,Name1[0],Prop1,Name2[0],Prop2,Ref);
return val;
}
EXPORT_CODE double CONVENTION Props(const char *Output, char Name1, double Prop1, char Name2, double Prop2, const char * Ref)
{
try
{
// Get parameter indices
std::string sName1 = std::string(1, Name1), sName2 = std::string(1, Name2);
long iOutput = get_param_index(Output);
long iName1 = CoolProp::get_parameter_index(sName1);
long iName2 = CoolProp::get_parameter_index(sName2);
// Convert inputs to SI
Prop1 = convert_from_kSI_to_SI(iName1, Prop1);
Prop2 = convert_from_kSI_to_SI(iName2, Prop2);
// Call the SI function
double val = PropsSI(Output, sName1.c_str(), Prop1, sName2.c_str(), Prop2, Ref);
// Convert back to unit system
return convert_from_SI_to_kSI(iOutput, val);
}
catch(std::exception &e){CoolProp::set_error_string(e.what()); return _HUGE;}
catch(...){CoolProp::set_error_string("Undefined error"); return _HUGE;}
}
EXPORT_CODE double CONVENTION Props1SI(const char *FluidName, const char *Output)
{
std::string _Output = Output, _FluidName = FluidName;
return CoolProp::PropsSI(_Output, "", 0, "", 0, _FluidName);
}
EXPORT_CODE double CONVENTION PropsSI(const char *Output, const char *Name1, double Prop1, const char *Name2, double Prop2, const char * FluidName)
{
std::string _Output = Output, _Name1 = Name1, _Name2 = Name2, _FluidName = FluidName;
return CoolProp::PropsSI(_Output, _Name1, Prop1, _Name2, Prop2, _FluidName);
}
EXPORT_CODE double CONVENTION PropsSIZ(const char *Output, const char *Name1, double Prop1, const char *Name2, double Prop2, const char * FluidName, const double *z, int n)
{
std::string _Output = Output, _Name1 = Name1, _Name2 = Name2, _FluidName = FluidName;
return CoolProp::PropsSI(_Output, _Name1, Prop1, _Name2, Prop2, _FluidName, std::vector<double>(z, z+n));
}
EXPORT_CODE void CONVENTION F77PropsSI(const char *Output, const char *Name1, double *Prop1, const char *Name2, double *Prop2, const char * FluidName, double *output)
{
std::string _Output = Output, _Name1 = Name1, _Name2 = Name2, _FluidName = FluidName;
*output = CoolProp::PropsSI(_Output, _Name1, *Prop1, _Name2, *Prop2, _FluidName);
}
EXPORT_CODE double CONVENTION K2F(double T){
return T * 9 / 5 - 459.67;
}
EXPORT_CODE double CONVENTION F2K(double T_F){
return (T_F + 459.67) * 5 / 9;
}
EXPORT_CODE int CONVENTION get_debug_level(){
return CoolProp::get_debug_level();
}
EXPORT_CODE void CONVENTION set_debug_level(int level){
CoolProp::set_debug_level(level);
}
EXPORT_CODE long CONVENTION get_param_index(const char * param){
return CoolProp::get_parameter_index(param);
}
#ifndef SWIG
EXPORT_CODE long CONVENTION get_global_param_string(const char *param, char * Output)
{
strcpy(Output,CoolProp::get_global_param_string(param).c_str());
return 0;
}
//EXPORT_CODE long CONVENTION get_fluid_param_string(const char *fluid, const char *param, char * Output)
//{
// strcpy(Output, get_fluid_param_string(std::string(fluid), std::string(param)).c_str());
// return 0;
//}
#endif
EXPORT_CODE double CONVENTION HAPropsSI(const char *Output, const char *Name1, double Prop1, const char *Name2, double Prop2, const char * Name3, double Prop3)
{
return HumidAir::HAPropsSI(Output, Name1, Prop1, Name2, Prop2, Name3, Prop3);
}
EXPORT_CODE void CONVENTION F77HAPropsSI(const char *Output, const char *Name1, double *Prop1, const char *Name2, double *Prop2, const char * Name3, double * Prop3, double *output)
{
*output = HumidAir::HAPropsSI(Output, Name1, *Prop1, Name2, *Prop2, Name3, *Prop3);
}
<commit_msg>Added missing string.h header include<commit_after>#if defined(_MSC_VER)
#define _CRTDBG_MAP_ALLOC
#define _CRT_SECURE_NO_WARNINGS
#include <crtdbg.h>
#endif
#include "CoolPropDLL.h"
#include "CoolProp.h"
#include "HumidAirProp.h"
#include "DataStructures.h"
#include "Exceptions.h"
#include <string.h>
double convert_from_kSI_to_SI(long iInput, double value)
{
if (get_debug_level() > 8){
std::cout << format("%s:%d: convert_from_kSI_to_SI(i=%d,value=%g)\n",__FILE__,__LINE__,iInput,value).c_str();
}
switch (iInput)
{
case CoolProp::iP:
case CoolProp::iCpmass:
case CoolProp::iCp0mass:
case CoolProp::iSmass:
case CoolProp::iGmass:
case CoolProp::iCvmass:
case CoolProp::iHmass:
case CoolProp::iUmass:
case CoolProp::iconductivity:
return value*1000.0;
case CoolProp::iDmass:
case CoolProp::ispeed_sound:
case CoolProp::iQ:
case CoolProp::iviscosity:
case CoolProp::iT:
case CoolProp::iPrandtl:
case CoolProp::isurface_tension:
return value;
default:
throw CoolProp::ValueError(format("index [%d] is invalid in convert_from_kSI_to_SI",iInput).c_str());
break;
}
return _HUGE;
}
double convert_from_SI_to_kSI(long iInput, double value)
{
if (get_debug_level() > 8){
std::cout << format("%s:%d: convert_from_SI_to_kSI(%d,%g)\n",__FILE__,__LINE__,iInput,value).c_str();
}
switch (iInput)
{
case CoolProp::iP:
case CoolProp::iCpmass:
case CoolProp::iCp0mass:
case CoolProp::iSmass:
case CoolProp::iGmass:
case CoolProp::iCvmass:
case CoolProp::iHmass:
case CoolProp::iUmass:
case CoolProp::iconductivity:
return value/1000.0;
case CoolProp::iDmass:
case CoolProp::iQ:
case CoolProp::ispeed_sound:
case CoolProp::iviscosity:
case CoolProp::iT:
case CoolProp::isurface_tension:
return value;
default:
throw CoolProp::ValueError(format("index [%d] is invalid in convert_from_SI_to_kSI", iInput).c_str());
break;
}
return _HUGE;
}
EXPORT_CODE long CONVENTION redirect_stdout(const char* file){
freopen(file, "a+", stdout);
return 0;
}
//EXPORT_CODE int CONVENTION set_reference_stateS(const char *Ref, const char *reference_state)
//{
// return set_reference_stateS(std::string(Ref), std::string(reference_state));
//}
//EXPORT_CODE int CONVENTION set_reference_stateD(const char *Ref, double T, double rho, double h0, double s0)
//{
// return set_reference_stateD(std::string(Ref), T, rho, h0, s0);
//}
// All the function interfaces that point to the single-input Props function
EXPORT_CODE double CONVENTION Props1(const char *FluidName, const char *Output){
return PropsS(Output, "", 0, "", 0, FluidName);
}
EXPORT_CODE double CONVENTION PropsS(const char *Output, const char* Name1, double Prop1, const char* Name2, double Prop2, const char * Ref){
double val = Props(Output,Name1[0],Prop1,Name2[0],Prop2,Ref);
return val;
}
EXPORT_CODE double CONVENTION Props(const char *Output, char Name1, double Prop1, char Name2, double Prop2, const char * Ref)
{
try
{
// Get parameter indices
std::string sName1 = std::string(1, Name1), sName2 = std::string(1, Name2);
long iOutput = get_param_index(Output);
long iName1 = CoolProp::get_parameter_index(sName1);
long iName2 = CoolProp::get_parameter_index(sName2);
// Convert inputs to SI
Prop1 = convert_from_kSI_to_SI(iName1, Prop1);
Prop2 = convert_from_kSI_to_SI(iName2, Prop2);
// Call the SI function
double val = PropsSI(Output, sName1.c_str(), Prop1, sName2.c_str(), Prop2, Ref);
// Convert back to unit system
return convert_from_SI_to_kSI(iOutput, val);
}
catch(std::exception &e){CoolProp::set_error_string(e.what()); return _HUGE;}
catch(...){CoolProp::set_error_string("Undefined error"); return _HUGE;}
}
EXPORT_CODE double CONVENTION Props1SI(const char *FluidName, const char *Output)
{
std::string _Output = Output, _FluidName = FluidName;
return CoolProp::PropsSI(_Output, "", 0, "", 0, _FluidName);
}
EXPORT_CODE double CONVENTION PropsSI(const char *Output, const char *Name1, double Prop1, const char *Name2, double Prop2, const char * FluidName)
{
std::string _Output = Output, _Name1 = Name1, _Name2 = Name2, _FluidName = FluidName;
return CoolProp::PropsSI(_Output, _Name1, Prop1, _Name2, Prop2, _FluidName);
}
EXPORT_CODE double CONVENTION PropsSIZ(const char *Output, const char *Name1, double Prop1, const char *Name2, double Prop2, const char * FluidName, const double *z, int n)
{
std::string _Output = Output, _Name1 = Name1, _Name2 = Name2, _FluidName = FluidName;
return CoolProp::PropsSI(_Output, _Name1, Prop1, _Name2, Prop2, _FluidName, std::vector<double>(z, z+n));
}
EXPORT_CODE void CONVENTION F77PropsSI(const char *Output, const char *Name1, double *Prop1, const char *Name2, double *Prop2, const char * FluidName, double *output)
{
std::string _Output = Output, _Name1 = Name1, _Name2 = Name2, _FluidName = FluidName;
*output = CoolProp::PropsSI(_Output, _Name1, *Prop1, _Name2, *Prop2, _FluidName);
}
EXPORT_CODE double CONVENTION K2F(double T){
return T * 9 / 5 - 459.67;
}
EXPORT_CODE double CONVENTION F2K(double T_F){
return (T_F + 459.67) * 5 / 9;
}
EXPORT_CODE int CONVENTION get_debug_level(){
return CoolProp::get_debug_level();
}
EXPORT_CODE void CONVENTION set_debug_level(int level){
CoolProp::set_debug_level(level);
}
EXPORT_CODE long CONVENTION get_param_index(const char * param){
return CoolProp::get_parameter_index(param);
}
#ifndef SWIG
EXPORT_CODE long CONVENTION get_global_param_string(const char *param, char * Output)
{
strcpy(Output,CoolProp::get_global_param_string(param).c_str());
return 0;
}
//EXPORT_CODE long CONVENTION get_fluid_param_string(const char *fluid, const char *param, char * Output)
//{
// strcpy(Output, get_fluid_param_string(std::string(fluid), std::string(param)).c_str());
// return 0;
//}
#endif
EXPORT_CODE double CONVENTION HAPropsSI(const char *Output, const char *Name1, double Prop1, const char *Name2, double Prop2, const char * Name3, double Prop3)
{
return HumidAir::HAPropsSI(Output, Name1, Prop1, Name2, Prop2, Name3, Prop3);
}
EXPORT_CODE void CONVENTION F77HAPropsSI(const char *Output, const char *Name1, double *Prop1, const char *Name2, double *Prop2, const char * Name3, double * Prop3, double *output)
{
*output = HumidAir::HAPropsSI(Output, Name1, *Prop1, Name2, *Prop2, Name3, *Prop3);
}
<|endoftext|>
|
<commit_before>/* This file is part of Strigi Desktop Search
*
* Copyright (C) 2006 Flavio Castelli <flavio.castelli@gmail.com>
* Jos van den Oever <jos@vandenoever.info>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "daemonconfigurator.h"
#include "../strigilogging.h"
#include <algorithm>
#include <fstream>
#include <sstream>
#include <stdlib.h>
using namespace std;
using namespace Strigi;
class FindRepository {
private:
string m_repoName;
public:
FindRepository(string repoName) { m_repoName = repoName; }
bool operator()(Repository repo) {
if (repo.a_name.compare(m_repoName) == 0) {
return true;
}
return false;
}
};
DaemonConfigurator::DaemonConfigurator (const string& confFile)
: m_confFile (confFile) {
// find the strigi directory
string strigidir;
string::size_type slashpos = confFile.rfind('/');
if (slashpos != string::npos) {
strigidir = confFile.substr(0, slashpos);
} else {
strigidir = getenv("HOME") + string("/.strigi");
}
stringbuf xml;
ifstream f(confFile.c_str(), ios::binary);
f.get(xml, '\0');
f.close();
if (xml.str().length()) {
XMLStream stream(xml.str());
stream >> *this;
}
FindRepository findRepository("localhost");
list<Repository>::iterator match = find_if(e_repository.begin(),
e_repository.end(),
findRepository);
// entry for localhost repository doesn't exists
if (match == e_repository.end()) {
a_useDBus = true;
Repository r;
r.a_name = "localhost";
string home;
if (getenv("HOME")) {
home.assign(getenv("HOME"));
}
r.a_indexdir = strigidir + "/clucene";
r.a_writeable = true;
r.a_type = "clucene";
r.a_pollingInterval = DEFAULT_POLLING_INTERVAL;
Path p;
p.a_path = home; r.e_path.push_back(p);
p.a_path = home + "/.kde"; r.e_path.push_back(p);
p.a_path = home + "/.kde4"; r.e_path.push_back(p);
p.a_path = home + "/.gnome2"; r.e_path.push_back(p);
p.a_path = home + "/.evolution"; r.e_path.push_back(p);
p.a_path = home + "/.mozilla"; r.e_path.push_back(p);
p.a_path = home + "/.mozilla-thunderbird"; r.e_path.push_back(p);
e_repository.push_back(r);
// add pattern to ignore hidden directories and hidden files
Filter f;
f.a_include = true;
f.a_pattern = ".*.directory/"; // mail box directory
e_filters.e_filter.push_back(f);
f.a_include = false;
f.a_pattern = ".*/";
e_filters.e_filter.push_back(f);
f.a_pattern = ".*";
e_filters.e_filter.push_back(f);
STRIGI_LOG_WARNING ("DaemonConfigurator",
"created default config for indexed dirs");
}
save();
}
void
DaemonConfigurator::setIndexedDirectories ( set<string>& dirs,
const string& repositoryName,
bool merge) {
FindRepository findRepository (repositoryName);
list<Repository>::iterator match = find_if (e_repository.begin(),
e_repository.end(),
findRepository);
Repository* r;
if (match != e_repository.end()) {
r = &(*match);
} else {
// create a new repository
Repository repo;
repo.a_name = repositoryName;
e_repository.push_back(repo);
return setIndexedDirectories (dirs, repositoryName, merge);
}
// clear old path
if (!merge) {
r->e_path.clear();
}
for (set<string>::const_iterator iter = dirs.begin(); iter != dirs.end();
++iter) {
Path p;
p.a_path = *iter;
r->e_path.push_back(p);
}
}
set<string>
DaemonConfigurator::getIndexedDirectories(const string& repositoryName) {
set<string> dirs;
FindRepository findRepository (repositoryName);
list<Repository>::iterator match = find_if (e_repository.begin(),
e_repository.end(),
findRepository);
if (match == e_repository.end()) {
STRIGI_LOG_WARNING ("DaemonConfigurator.getIndexedDirs",
"cannot find repository name: |" + repositoryName + '|');
return dirs;
}
Repository* r = &(*match);
for (list<Path>::const_iterator iter = r->e_path.begin();
iter != r->e_path.end(); ++iter) {
dirs.insert (iter->a_path);
}
return dirs;
}
void
DaemonConfigurator::save(const char* file) {
ofstream f;
if (file == NULL) {
f.open(m_confFile.c_str(), ios::binary);
} else {
f.open(file, ios::binary);
}
f << *this;
f.close();
}
string
DaemonConfigurator::getWriteableIndexType() const {
return (e_repository.size()) ?e_repository.begin()->a_type : "";
}
string
DaemonConfigurator::getWriteableIndexDir() const {
return (e_repository.size()) ?e_repository.begin()->a_indexdir : "";
}
list<Repository>
DaemonConfigurator::getReadOnlyRepositories() const {
list<Repository> ro;
list<Repository>::const_iterator i;
for (i = e_repository.begin(); i != e_repository.end(); ++i) {
if (!i->a_writeable) {
ro.push_back(*i);
}
}
return ro;
}
void
DaemonConfigurator::setPollingInterval (unsigned int value,
const string& repositoryName) {
FindRepository findRepository (repositoryName);
list<Repository>::iterator match = find_if (e_repository.begin(),
e_repository.end(),
findRepository);
if (match != e_repository.end()) {
Repository* r = &(*match);
r->a_pollingInterval = value;
} else {
// create a new repository
Repository repo;
repo.a_name = repositoryName;
repo.a_pollingInterval = value;
e_repository.push_back(repo);
}
}
unsigned int
DaemonConfigurator::getPollingInterval(const string& repositoryName) {
FindRepository findRepository (repositoryName);
list<Repository>::iterator match = find_if (e_repository.begin(),
e_repository.end(),
findRepository);
Repository* r;
if (match != e_repository.end()) {
r = &(*match);
} else {
// create a new repository
Repository repo;
repo.a_name = repositoryName;
e_repository.push_back(repo);
r = &repo;
}
// check minimum polling interval
if (r->a_pollingInterval < DEFAULT_POLLING_INTERVAL)
{
r->a_pollingInterval = DEFAULT_POLLING_INTERVAL;
return DEFAULT_POLLING_INTERVAL;
} else {
return r->a_pollingInterval;
}
}
void
DaemonConfigurator::loadFilteringRules(AnalyzerConfiguration& config) {
vector<pair<bool,string> > filters;
list<Filter>::const_iterator i;
for (i = e_filters.e_filter.begin(); i != e_filters.e_filter.end(); ++i) {
filters.push_back(make_pair<bool,string>(i->a_include, i->a_pattern));
}
config.setFilters(filters);
}
void
DaemonConfigurator::saveFilteringRules(const vector<pair<bool,string> >& f) {
e_filters.e_filter.clear();
vector<pair<bool,string> >::const_iterator i;
for (i = f.begin(); i != f.end(); ++i) {
Filter f;
f.a_include = i->first;
f.a_pattern = i->second;
e_filters.e_filter.push_back(f);
}
}
<commit_msg>Lower minimum for intervals between polling.<commit_after>/* This file is part of Strigi Desktop Search
*
* Copyright (C) 2006 Flavio Castelli <flavio.castelli@gmail.com>
* Jos van den Oever <jos@vandenoever.info>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "daemonconfigurator.h"
#include "../strigilogging.h"
#include <algorithm>
#include <fstream>
#include <sstream>
#include <stdlib.h>
using namespace std;
using namespace Strigi;
class FindRepository {
private:
string m_repoName;
public:
FindRepository(string repoName) { m_repoName = repoName; }
bool operator()(Repository repo) {
if (repo.a_name.compare(m_repoName) == 0) {
return true;
}
return false;
}
};
DaemonConfigurator::DaemonConfigurator (const string& confFile)
: m_confFile (confFile) {
// find the strigi directory
string strigidir;
string::size_type slashpos = confFile.rfind('/');
if (slashpos != string::npos) {
strigidir = confFile.substr(0, slashpos);
} else {
strigidir = getenv("HOME") + string("/.strigi");
}
stringbuf xml;
ifstream f(confFile.c_str(), ios::binary);
f.get(xml, '\0');
f.close();
if (xml.str().length()) {
XMLStream stream(xml.str());
stream >> *this;
}
FindRepository findRepository("localhost");
list<Repository>::iterator match = find_if(e_repository.begin(),
e_repository.end(),
findRepository);
// entry for localhost repository doesn't exists
if (match == e_repository.end()) {
a_useDBus = true;
Repository r;
r.a_name = "localhost";
string home;
if (getenv("HOME")) {
home.assign(getenv("HOME"));
}
r.a_indexdir = strigidir + "/clucene";
r.a_writeable = true;
r.a_type = "clucene";
r.a_pollingInterval = DEFAULT_POLLING_INTERVAL;
Path p;
p.a_path = home; r.e_path.push_back(p);
p.a_path = home + "/.kde"; r.e_path.push_back(p);
p.a_path = home + "/.kde4"; r.e_path.push_back(p);
p.a_path = home + "/.gnome2"; r.e_path.push_back(p);
p.a_path = home + "/.evolution"; r.e_path.push_back(p);
p.a_path = home + "/.mozilla"; r.e_path.push_back(p);
p.a_path = home + "/.mozilla-thunderbird"; r.e_path.push_back(p);
e_repository.push_back(r);
// add pattern to ignore hidden directories and hidden files
Filter f;
f.a_include = true;
f.a_pattern = ".*.directory/"; // mail box directory
e_filters.e_filter.push_back(f);
f.a_include = false;
f.a_pattern = ".*/";
e_filters.e_filter.push_back(f);
f.a_pattern = ".*";
e_filters.e_filter.push_back(f);
STRIGI_LOG_WARNING ("DaemonConfigurator",
"created default config for indexed dirs");
}
save();
}
void
DaemonConfigurator::setIndexedDirectories ( set<string>& dirs,
const string& repositoryName,
bool merge) {
FindRepository findRepository (repositoryName);
list<Repository>::iterator match = find_if (e_repository.begin(),
e_repository.end(),
findRepository);
Repository* r;
if (match != e_repository.end()) {
r = &(*match);
} else {
// create a new repository
Repository repo;
repo.a_name = repositoryName;
e_repository.push_back(repo);
return setIndexedDirectories (dirs, repositoryName, merge);
}
// clear old path
if (!merge) {
r->e_path.clear();
}
for (set<string>::const_iterator iter = dirs.begin(); iter != dirs.end();
++iter) {
Path p;
p.a_path = *iter;
r->e_path.push_back(p);
}
}
set<string>
DaemonConfigurator::getIndexedDirectories(const string& repositoryName) {
set<string> dirs;
FindRepository findRepository (repositoryName);
list<Repository>::iterator match = find_if (e_repository.begin(),
e_repository.end(),
findRepository);
if (match == e_repository.end()) {
STRIGI_LOG_WARNING ("DaemonConfigurator.getIndexedDirs",
"cannot find repository name: |" + repositoryName + '|');
return dirs;
}
Repository* r = &(*match);
for (list<Path>::const_iterator iter = r->e_path.begin();
iter != r->e_path.end(); ++iter) {
dirs.insert (iter->a_path);
}
return dirs;
}
void
DaemonConfigurator::save(const char* file) {
ofstream f;
if (file == NULL) {
f.open(m_confFile.c_str(), ios::binary);
} else {
f.open(file, ios::binary);
}
f << *this;
f.close();
}
string
DaemonConfigurator::getWriteableIndexType() const {
return (e_repository.size()) ?e_repository.begin()->a_type : "";
}
string
DaemonConfigurator::getWriteableIndexDir() const {
return (e_repository.size()) ?e_repository.begin()->a_indexdir : "";
}
list<Repository>
DaemonConfigurator::getReadOnlyRepositories() const {
list<Repository> ro;
list<Repository>::const_iterator i;
for (i = e_repository.begin(); i != e_repository.end(); ++i) {
if (!i->a_writeable) {
ro.push_back(*i);
}
}
return ro;
}
void
DaemonConfigurator::setPollingInterval (unsigned int value,
const string& repositoryName) {
FindRepository findRepository (repositoryName);
list<Repository>::iterator match = find_if (e_repository.begin(),
e_repository.end(),
findRepository);
if (match != e_repository.end()) {
Repository* r = &(*match);
r->a_pollingInterval = value;
} else {
// create a new repository
Repository repo;
repo.a_name = repositoryName;
repo.a_pollingInterval = value;
e_repository.push_back(repo);
}
}
unsigned int
DaemonConfigurator::getPollingInterval(const string& repositoryName) {
FindRepository findRepository (repositoryName);
list<Repository>::iterator match = find_if (e_repository.begin(),
e_repository.end(),
findRepository);
Repository* r;
if (match != e_repository.end()) {
r = &(*match);
} else {
// create a new repository
Repository repo;
repo.a_name = repositoryName;
e_repository.push_back(repo);
r = &repo;
}
// check minimum polling interval
if (r->a_pollingInterval < 5)
{
r->a_pollingInterval = DEFAULT_POLLING_INTERVAL;
return DEFAULT_POLLING_INTERVAL;
} else {
return r->a_pollingInterval;
}
}
void
DaemonConfigurator::loadFilteringRules(AnalyzerConfiguration& config) {
vector<pair<bool,string> > filters;
list<Filter>::const_iterator i;
for (i = e_filters.e_filter.begin(); i != e_filters.e_filter.end(); ++i) {
filters.push_back(make_pair<bool,string>(i->a_include, i->a_pattern));
}
config.setFilters(filters);
}
void
DaemonConfigurator::saveFilteringRules(const vector<pair<bool,string> >& f) {
e_filters.e_filter.clear();
vector<pair<bool,string> >::const_iterator i;
for (i = f.begin(); i != f.end(); ++i) {
Filter f;
f.a_include = i->first;
f.a_pattern = i->second;
e_filters.e_filter.push_back(f);
}
}
<|endoftext|>
|
<commit_before>/**
* @file lldiriterator.cpp
* @brief Iterator through directory entries matching the search pattern.
*
* $LicenseInfo:firstyear=2010&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* 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;
* version 2.1 of the License only.
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "lldiriterator.h"
#include <boost/filesystem.hpp>
#include <boost/regex.hpp>
namespace fs = boost::filesystem;
static std::string glob_to_regex(const std::string& glob);
class LLDirIterator::Impl
{
public:
Impl(const std::string &dirname, const std::string &mask);
~Impl();
bool next(std::string &fname);
private:
boost::regex mFilterExp;
fs::directory_iterator mIter;
bool mIsValid;
};
LLDirIterator::Impl::Impl(const std::string &dirname, const std::string &mask)
: mIsValid(false)
{
fs::path dir_path(dirname);
// Check if path exists.
if (!fs::exists(dir_path))
{
llwarns << "Invalid path: \"" << dir_path.string() << "\"" << llendl;
return;
}
// Initialize the directory iterator for the given path.
try
{
mIter = fs::directory_iterator(dir_path);
}
catch (fs::basic_filesystem_error<fs::path>& e)
{
llerrs << e.what() << llendl;
return;
}
// Convert the glob mask to a regular expression
std::string exp = glob_to_regex(mask);
// Initialize boost::regex with the expression converted from
// the glob mask.
// An exception is thrown if the expression is not valid.
try
{
mFilterExp.assign(exp);
}
catch (boost::regex_error& e)
{
llerrs << "\"" << exp << "\" is not a valid regular expression: "
<< e.what() << llendl;
return;
}
mIsValid = true;
}
LLDirIterator::Impl::~Impl()
{
}
bool LLDirIterator::Impl::next(std::string &fname)
{
fname = "";
if (!mIsValid)
{
llwarns << "The iterator is not correctly initialized." << llendl;
return false;
}
fs::directory_iterator end_itr; // default construction yields past-the-end
bool found = false;
while (mIter != end_itr && !found)
{
boost::smatch match;
std::string name = mIter->path().filename();
if (found = boost::regex_match(name, match, mFilterExp))
{
fname = name;
}
++mIter;
}
return found;
}
/**
Converts the incoming glob into a regex. This involves
converting incoming glob expressions to regex equivilents and
at the same time, escaping any regex meaningful characters which
do not have glob meaning, i.e.
.()+|^$
in the input.
*/
std::string glob_to_regex(const std::string& glob)
{
std::string regex;
regex.reserve(glob.size()<<1);
S32 braces = 0;
bool escaped = false;
bool square_brace_open = false;
for (std::string::const_iterator i = glob.begin(); i != glob.end(); ++i)
{
char c = *i;
switch (c)
{
case '*':
if (glob.begin() == i)
{
regex+="[^.].*";
}
else
{
regex+= escaped ? "*" : ".*";
}
break;
case '?':
regex+= escaped ? '?' : '.';
break;
case '{':
braces++;
regex+='(';
break;
case '}':
if (!braces)
{
llerrs << "glob_to_regex: Closing brace without an equivalent opening brace: " << glob << llendl;
}
regex+=')';
braces--;
break;
case ',':
regex+= braces ? '|' : c;
break;
case '!':
regex+= square_brace_open ? '^' : c;
break;
case '.': // This collection have different regex meaning
case '^': // and so need escaping.
case '(':
case ')':
case '+':
case '|':
case '$':
regex += '\\';
default:
regex += c;
break;
}
escaped = ('\\' == c);
square_brace_open = ('[' == c);
}
if (braces)
{
llerrs << "glob_to_regex: Unterminated brace expression: " << glob << llendl;
}
return regex;
}
LLDirIterator::LLDirIterator(const std::string &dirname, const std::string &mask)
{
mImpl = new Impl(dirname, mask);
}
LLDirIterator::~LLDirIterator()
{
delete mImpl;
}
bool LLDirIterator::next(std::string &fname)
{
return mImpl->next(fname);
}
<commit_msg>STORM-1476 FIXED Replaced non-fatal errors in LLDirIterator constructor with warnings to avoid viewer crashes. Added exception handling case.<commit_after>/**
* @file lldiriterator.cpp
* @brief Iterator through directory entries matching the search pattern.
*
* $LicenseInfo:firstyear=2010&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* 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;
* version 2.1 of the License only.
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "lldiriterator.h"
#include <boost/filesystem.hpp>
#include <boost/regex.hpp>
namespace fs = boost::filesystem;
static std::string glob_to_regex(const std::string& glob);
class LLDirIterator::Impl
{
public:
Impl(const std::string &dirname, const std::string &mask);
~Impl();
bool next(std::string &fname);
private:
boost::regex mFilterExp;
fs::directory_iterator mIter;
bool mIsValid;
};
LLDirIterator::Impl::Impl(const std::string &dirname, const std::string &mask)
: mIsValid(false)
{
fs::path dir_path(dirname);
bool is_dir = false;
// Check if path is a directory.
try
{
is_dir = fs::is_directory(dir_path);
}
catch (fs::basic_filesystem_error<fs::path>& e)
{
llwarns << e.what() << llendl;
return;
}
if (!is_dir)
{
llwarns << "Invalid path: \"" << dir_path.string() << "\"" << llendl;
return;
}
// Initialize the directory iterator for the given path.
try
{
mIter = fs::directory_iterator(dir_path);
}
catch (fs::basic_filesystem_error<fs::path>& e)
{
llwarns << e.what() << llendl;
return;
}
// Convert the glob mask to a regular expression
std::string exp = glob_to_regex(mask);
// Initialize boost::regex with the expression converted from
// the glob mask.
// An exception is thrown if the expression is not valid.
try
{
mFilterExp.assign(exp);
}
catch (boost::regex_error& e)
{
llwarns << "\"" << exp << "\" is not a valid regular expression: "
<< e.what() << llendl;
return;
}
mIsValid = true;
}
LLDirIterator::Impl::~Impl()
{
}
bool LLDirIterator::Impl::next(std::string &fname)
{
fname = "";
if (!mIsValid)
{
llwarns << "The iterator is not correctly initialized." << llendl;
return false;
}
fs::directory_iterator end_itr; // default construction yields past-the-end
bool found = false;
while (mIter != end_itr && !found)
{
boost::smatch match;
std::string name = mIter->path().filename();
if (found = boost::regex_match(name, match, mFilterExp))
{
fname = name;
}
++mIter;
}
return found;
}
/**
Converts the incoming glob into a regex. This involves
converting incoming glob expressions to regex equivilents and
at the same time, escaping any regex meaningful characters which
do not have glob meaning, i.e.
.()+|^$
in the input.
*/
std::string glob_to_regex(const std::string& glob)
{
std::string regex;
regex.reserve(glob.size()<<1);
S32 braces = 0;
bool escaped = false;
bool square_brace_open = false;
for (std::string::const_iterator i = glob.begin(); i != glob.end(); ++i)
{
char c = *i;
switch (c)
{
case '*':
if (glob.begin() == i)
{
regex+="[^.].*";
}
else
{
regex+= escaped ? "*" : ".*";
}
break;
case '?':
regex+= escaped ? '?' : '.';
break;
case '{':
braces++;
regex+='(';
break;
case '}':
if (!braces)
{
llerrs << "glob_to_regex: Closing brace without an equivalent opening brace: " << glob << llendl;
}
regex+=')';
braces--;
break;
case ',':
regex+= braces ? '|' : c;
break;
case '!':
regex+= square_brace_open ? '^' : c;
break;
case '.': // This collection have different regex meaning
case '^': // and so need escaping.
case '(':
case ')':
case '+':
case '|':
case '$':
regex += '\\';
default:
regex += c;
break;
}
escaped = ('\\' == c);
square_brace_open = ('[' == c);
}
if (braces)
{
llerrs << "glob_to_regex: Unterminated brace expression: " << glob << llendl;
}
return regex;
}
LLDirIterator::LLDirIterator(const std::string &dirname, const std::string &mask)
{
mImpl = new Impl(dirname, mask);
}
LLDirIterator::~LLDirIterator()
{
delete mImpl;
}
bool LLDirIterator::next(std::string &fname)
{
return mImpl->next(fname);
}
<|endoftext|>
|
<commit_before>/*
qgvdial is a cross platform Google Voice Dialer
Copyright (C) 2010 Yuvraaj Kelkar
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Contact: yuvraaj@gmail.com
*/
#include "DialContext.h"
#include "Singletons.h"
DialContext::DialContext (const QString &strMy, const QString &strT,
QDeclarativeView *mV)
: QObject(mV)
, bDialOut (false)
, ci (NULL)
, strMyNumber (strMy)
, strTarget (strT)
, fallbackCi (NULL)
, mainView (mV)
{
QObject *pRoot = mainView->rootObject ();
bool rv = connect (pRoot, SIGNAL (sigMsgBoxDone(bool)),
this , SLOT (onSigMsgBoxDone(bool)));
Q_ASSERT(rv); Q_UNUSED(rv);
}//DialContext::DialContext
DialContext::~DialContext() {
hideMsgBox ();
}//DialContext::~DialContext
void
DialContext::showMsgBox ()
{
ObserverFactory &obsF = Singletons::getRef().getObserverFactory ();
obsF.startObservers (strMyNumber, this, SLOT (callStarted()));
QString strMessage = QString("Dialing\n%1").arg(strTarget);
QDeclarativeContext *ctx = mainView->rootContext();
bool bTemp = true;
ctx->setContextProperty ("g_bShowMsg", bTemp);
ctx->setContextProperty ("g_strMsgText", strMessage);
}//DialContext::showMsgBox
void
DialContext::hideMsgBox ()
{
QDeclarativeContext *ctx = mainView->rootContext();
bool bTemp = false;
ctx->setContextProperty ("g_bShowMsg", bTemp);
}//DialContext::hideMsgBox
void
DialContext::callStarted ()
{
onSigMsgBoxDone (true);
}//DialContext::callStarted
void
DialContext::onSigMsgBoxDone (bool ok)
{
ObserverFactory &obsF = Singletons::getRef().getObserverFactory ();
obsF.stopObservers ();
hideMsgBox ();
emit sigDialComplete (this, ok);
}//DialContext::onSigMsgBoxDone
<commit_msg>Dial context failed to get the correct pointer for the MainPage.<commit_after>/*
qgvdial is a cross platform Google Voice Dialer
Copyright (C) 2010 Yuvraaj Kelkar
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Contact: yuvraaj@gmail.com
*/
#include "DialContext.h"
#include "Singletons.h"
DialContext::DialContext (const QString &strMy, const QString &strT,
QDeclarativeView *mV)
: QObject(mV)
, bDialOut (false)
, ci (NULL)
, strMyNumber (strMy)
, strTarget (strT)
, fallbackCi (NULL)
, mainView (mV)
{
QObject *pMain = NULL;
do { // Begin cleanup block (not a loop)
QObject *pRoot = mainView->rootObject ();
if (NULL == pRoot) {
qWarning ("Couldn't get root object in QML for MainPage");
break;
}
if (pRoot->objectName() == "MainPage") {
pMain = pRoot;
break;
}
pMain = pRoot->findChild <QObject*> ("MainPage");
if (NULL == pMain) {
qWarning ("Could not get to MainPage");
break;
}
} while (0); // End cleanup block (not a loop)
bool rv = connect (pMain, SIGNAL (sigMsgBoxDone(bool)),
this , SLOT (onSigMsgBoxDone(bool)));
Q_ASSERT(rv); Q_UNUSED(rv);
}//DialContext::DialContext
DialContext::~DialContext() {
hideMsgBox ();
}//DialContext::~DialContext
void
DialContext::showMsgBox ()
{
ObserverFactory &obsF = Singletons::getRef().getObserverFactory ();
obsF.startObservers (strMyNumber, this, SLOT (callStarted()));
QString strMessage = QString("Dialing\n%1").arg(strTarget);
QDeclarativeContext *ctx = mainView->rootContext();
bool bTemp = true;
ctx->setContextProperty ("g_bShowMsg", bTemp);
ctx->setContextProperty ("g_strMsgText", strMessage);
}//DialContext::showMsgBox
void
DialContext::hideMsgBox ()
{
QDeclarativeContext *ctx = mainView->rootContext();
bool bTemp = false;
ctx->setContextProperty ("g_bShowMsg", bTemp);
}//DialContext::hideMsgBox
void
DialContext::callStarted ()
{
onSigMsgBoxDone (true);
}//DialContext::callStarted
void
DialContext::onSigMsgBoxDone (bool ok)
{
ObserverFactory &obsF = Singletons::getRef().getObserverFactory ();
obsF.stopObservers ();
hideMsgBox ();
emit sigDialComplete (this, ok);
}//DialContext::onSigMsgBoxDone
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.