<commit_before>/*
 * Copyright (c) 1999-2010 Stephen Williams (steve@icarus.com)
 *
 *    This source code is free software; you can redistribute it
 *    and/or modify it in source code form 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.
 */

# include "config.h"

/*
 * This functor scans the design looking for dangling objects and
 * excess local signals. These deletions are not necessarily required
 * for proper functioning of anything, but they can clean up the
 * appearance of design files that are generated.
 */
# include  "functor.h"
# include  "netlist.h"
# include  "compiler.h"

class nodangle_f  : public functor_t {
    public:
      void event(Design*des, NetEvent*ev);
      void signal(Design*des, NetNet*sig);

      unsigned iteration;
      unsigned stotal, etotal;
      bool scontinue, econtinue;
      bool scomplete, ecomplete;
};

void nodangle_f::event(Design*, NetEvent*ev)
{
      if (ecomplete) return;

	/* If there are no references to this event, then go right
	   ahead and delete it. There is no use looking further at
	   it. */
      if ((ev->nwait() + ev->ntrig() + ev->nexpr()) == 0) {
	    delete ev;
	    etotal += 1;
	    return;
      }

      if (iteration == 0) {
              /* Try to remove duplicate probes from the event. This
                 is done as a separate initial pass to ensure similar
                 events are detected as soon as possible in subsequent
                 iterations. */
            for (unsigned idx = 0 ;  idx < ev->nprobe() ;  idx += 1) {
                  unsigned jdx = idx + 1;
                  while (jdx < ev->nprobe()) {
                        NetEvProbe*ip = ev->probe(idx);
                        NetEvProbe*jp = ev->probe(jdx);

                        if (ip->edge() != jp->edge()) {
                              jdx += 1;
                              continue;
                        }

                        bool fully_connected = true;
                        for (unsigned jpin = 0; jpin < jp->pin_count(); jpin += 1) {
                              unsigned ipin = 0;
                              bool connected_flag = false;
                              for (ipin = 0 ; ipin < ip->pin_count(); ipin += 1)
                                    if (connected(ip->pin(ipin), jp->pin(jpin))) {
                                          connected_flag = true;
                                          break;
                                    }

                              if (!connected_flag) {
                                    fully_connected = false;
                                    break;
                              }
                        }

                        if (fully_connected) {
                              delete jp;
                        } else {
                              jdx += 1;
                        }
                  }
            }
            econtinue = true;
      } else {
              /* Postpone examining events in an automatic scope until the
                 third (optional) pass. This will mean similar events are
                 biased towards being stored in static scopes. */
            if (ev->scope()->is_auto()) {
                  if (iteration == 1) {
                        econtinue = true;
                        return;
                  }
            } else {
                  if (iteration == 2) {
                        return;
                  }
            }

              /* Try to find all the events that are similar to me, and
                 replace their references with references to me. */
            list<NetEvent*> match;
            ev->find_similar_event(match);
            for (list<NetEvent*>::iterator idx = match.begin()
                       ; idx != match.end() ; ++ idx ) {

                  NetEvent*tmp = *idx;
                  assert(tmp != ev);
		  tmp ->replace_event(ev);
            }
      }
}

static bool floating_net_tested(NetNet*sig)
{
      static set<NetNet*> tested_set;

      pair< set<NetNet*>::iterator, bool > cur = tested_set.insert(sig);
      return !cur.second;
}

static void check_is_floating(NetNet*sig)
{
      if (sig->type() == NetNet::SUPPLY0) return;
      if (sig->type() == NetNet::SUPPLY1) return;
      if (sig->type() == NetNet::TRI0) return;
      if (sig->type() == NetNet::TRI1) return;
      if (sig->type() == NetNet::IMPLICIT_REG) return;
      if (sig->type() == NetNet::REG) return ;

      if (sig->peek_lref() > 0) return;

      for (unsigned idx = 0 ; idx < sig->pin_count() ; idx += 1) {
	    if (sig->pin(idx).get_dir() == Link::OUTPUT)
		  continue;

	    if (sig->pin(idx).nexus()->drivers_present())
		  continue;

	    if (sig->port_type() == PortType::NOT_A_PORT && sig->pin_count()==1) {
		  cerr << sig->get_fileline() << ": warning: "
		       << "Signal " << scope_path(sig->scope())
		       << "." << sig->name()
		       << " has no drivers." << endl;
	    } else if (sig->port_type()==PortType::NOT_A_PORT) {
		  cerr << sig->get_fileline() << ": warning: "
		       << "Signal " << scope_path(sig->scope())
		       << "." << sig->name()
		       << "[" << idx << "]"
		       << " has no drivers." << endl;
	    } else {
		  cerr << sig->get_fileline() << ": warning: "
		       << "Port " << sig->name()
		       << " of " << scope_path(sig->scope())
		       << " has no drivers." << endl;
	    }
      }

}

void nodangle_f::signal(Design*, NetNet*sig)
{
      if (scomplete) return;

      if (warn_floating_nets && !floating_net_tested(sig)) {
	    check_is_floating(sig);
      }

	/* Cannot delete signals referenced in an expression
	   or an l-value. */
      if (sig->get_refs() > 0)
	    return;

	/* Cannot delete the ports of tasks, functions or modules. There
	   are too many places where they are referenced. */
      if ((sig->port_type() != NetNet::NOT_A_PORT) &&
	  ((sig->scope()->type() == NetScope::TASK) ||
	   (sig->scope()->type() == NetScope::FUNC) ||
	   (sig->scope()->type() == NetScope::MODULE)))
	    return;

	/* Can't delete ports of cells. */
      if ((sig->port_type() != NetNet::NOT_A_PORT)
	  && (sig->scope()->attribute(perm_string::literal("ivl_synthesis_cell")) != verinum()))
	    return;

	/* Don't delete signals that are marked with the
	   ivl_do_not_elide property. */
      if (!sig->local_flag()
	  && (sig->attribute(perm_string::literal("ivl_do_not_elide")) != verinum()))
	    return;

	/* Check to see if the signal is completely unconnected. If
	   all the bits are unlinked, then delete it. */
      if (! sig->is_linked()) {
	    delete sig;
	    stotal += 1;
	    return;
      }

	/* The remaining things can only be done to synthesized
	   signals, not ones that appear in the original Verilog. */
      if (! sig->local_flag())
	    return;

	/* Check to see if there is some significant signal connected
	   to every pin of this signal. */
      unsigned significant_flags = 0;
      for (unsigned idx = 0 ;  idx < sig->pin_count() ;  idx += 1) {
	    Nexus*nex = sig->pin(idx).nexus();

	    for (Link*cur = nex->first_nlink()
		       ; cur ;  cur = cur->next_nlink()) {

		  if (cur == &sig->pin(idx))
			continue;

		  NetNet*cursig = dynamic_cast<NetNet*>(cur->get_obj());
		  if (cursig == 0)
			continue;

		  if (cursig->local_flag())
			continue;

		  significant_flags += 1;
		  break;
	    }

	    if (significant_flags <= idx)
		  break;
      }

	/* If every pin is connected to another significant signal,
	   then I can delete this one. */
      if (significant_flags == sig->pin_count()) {
	    delete sig;
	    stotal += 1;
      }
}

void nodangle(Design*des)
{
      nodangle_f fun;
      fun.iteration = 0;
      fun.stotal = 0;
      fun.etotal = 0;
      fun.scomplete = false;
      fun.ecomplete = false;
      do {
	    if (verbose_flag) {
		  cout << " ... scan for dangling signal and event nodes. "
		       << "(scomplete=" << (fun.scomplete? "T" : "F")
		       << ", ecomplete=" << (fun.ecomplete? "T" : "F")
		       << ")" << endl << flush;
	    }

            fun.scontinue = false;
            fun.econtinue = false;
	    des->functor(&fun);
	    fun.iteration += 1;
            fun.scomplete = !fun.scontinue;
            fun.ecomplete = !fun.econtinue;

	    if (verbose_flag) {
		  cout << " ... " << fun.iteration << " iterations"
		       << " deleted " << fun.stotal << " dangling signals"
		       << " and " << fun.etotal << " events." << endl << flush;
	    }

      } while (fun.scontinue || fun.econtinue);

      if (verbose_flag) {
	    cout << " ... done" << endl << flush;
      }
}
<commit_msg>Don't warning about floating local/internal symbols.<commit_after>/*
 * Copyright (c) 1999-2010 Stephen Williams (steve@icarus.com)
 *
 *    This source code is free software; you can redistribute it
 *    and/or modify it in source code form 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.
 */

# include "config.h"

/*
 * This functor scans the design looking for dangling objects and
 * excess local signals. These deletions are not necessarily required
 * for proper functioning of anything, but they can clean up the
 * appearance of design files that are generated.
 */
# include  "functor.h"
# include  "netlist.h"
# include  "compiler.h"

class nodangle_f  : public functor_t {
    public:
      void event(Design*des, NetEvent*ev);
      void signal(Design*des, NetNet*sig);

      unsigned iteration;
      unsigned stotal, etotal;
      bool scontinue, econtinue;
      bool scomplete, ecomplete;
};

void nodangle_f::event(Design*, NetEvent*ev)
{
      if (ecomplete) return;

	/* If there are no references to this event, then go right
	   ahead and delete it. There is no use looking further at
	   it. */
      if ((ev->nwait() + ev->ntrig() + ev->nexpr()) == 0) {
	    delete ev;
	    etotal += 1;
	    return;
      }

      if (iteration == 0) {
              /* Try to remove duplicate probes from the event. This
                 is done as a separate initial pass to ensure similar
                 events are detected as soon as possible in subsequent
                 iterations. */
            for (unsigned idx = 0 ;  idx < ev->nprobe() ;  idx += 1) {
                  unsigned jdx = idx + 1;
                  while (jdx < ev->nprobe()) {
                        NetEvProbe*ip = ev->probe(idx);
                        NetEvProbe*jp = ev->probe(jdx);

                        if (ip->edge() != jp->edge()) {
                              jdx += 1;
                              continue;
                        }

                        bool fully_connected = true;
                        for (unsigned jpin = 0; jpin < jp->pin_count(); jpin += 1) {
                              unsigned ipin = 0;
                              bool connected_flag = false;
                              for (ipin = 0 ; ipin < ip->pin_count(); ipin += 1)
                                    if (connected(ip->pin(ipin), jp->pin(jpin))) {
                                          connected_flag = true;
                                          break;
                                    }

                              if (!connected_flag) {
                                    fully_connected = false;
                                    break;
                              }
                        }

                        if (fully_connected) {
                              delete jp;
                        } else {
                              jdx += 1;
                        }
                  }
            }
            econtinue = true;
      } else {
              /* Postpone examining events in an automatic scope until the
                 third (optional) pass. This will mean similar events are
                 biased towards being stored in static scopes. */
            if (ev->scope()->is_auto()) {
                  if (iteration == 1) {
                        econtinue = true;
                        return;
                  }
            } else {
                  if (iteration == 2) {
                        return;
                  }
            }

              /* Try to find all the events that are similar to me, and
                 replace their references with references to me. */
            list<NetEvent*> match;
            ev->find_similar_event(match);
            for (list<NetEvent*>::iterator idx = match.begin()
                       ; idx != match.end() ; ++ idx ) {

                  NetEvent*tmp = *idx;
                  assert(tmp != ev);
		  tmp ->replace_event(ev);
            }
      }
}

static bool floating_net_tested(NetNet*sig)
{
      static set<NetNet*> tested_set;

      pair< set<NetNet*>::iterator, bool > cur = tested_set.insert(sig);
      return !cur.second;
}

static void check_is_floating(NetNet*sig)
{
	// Some signal types are implicitly driven if nothing else.
      if (sig->type() == NetNet::SUPPLY0) return;
      if (sig->type() == NetNet::SUPPLY1) return;
      if (sig->type() == NetNet::TRI0) return;
      if (sig->type() == NetNet::TRI1) return;
      if (sig->type() == NetNet::IMPLICIT_REG) return;
      if (sig->type() == NetNet::REG) return ;

	// Asignments drive a signal.
      if (sig->peek_lref() > 0) return;

      for (unsigned idx = 0 ; idx < sig->pin_count() ; idx += 1) {
	    if (sig->pin(idx).get_dir() == Link::OUTPUT)
		  continue;

	    if (sig->pin(idx).nexus()->drivers_present())
		  continue;

	    if (sig->port_type() == PortType::NOT_A_PORT && sig->pin_count()==1) {
		  cerr << sig->get_fileline() << ": warning: "
		       << "Signal " << scope_path(sig->scope())
		       << "." << sig->name()
		       << " has no drivers." << endl;
	    } else if (sig->port_type()==PortType::NOT_A_PORT) {
		  cerr << sig->get_fileline() << ": warning: "
		       << "Signal " << scope_path(sig->scope())
		       << "." << sig->name()
		       << "[" << idx << "]"
		       << " has no drivers." << endl;
	    } else {
		  cerr << sig->get_fileline() << ": warning: "
		       << "Port " << sig->name()
		       << " of " << scope_path(sig->scope())
		       << " has no drivers." << endl;
	    }
      }

}

void nodangle_f::signal(Design*, NetNet*sig)
{
      if (scomplete) return;

      if (warn_floating_nets && !sig->local_flag() && !floating_net_tested(sig)) {
	    check_is_floating(sig);
      }

	/* Cannot delete signals referenced in an expression
	   or an l-value. */
      if (sig->get_refs() > 0)
	    return;

	/* Cannot delete the ports of tasks, functions or modules. There
	   are too many places where they are referenced. */
      if ((sig->port_type() != NetNet::NOT_A_PORT) &&
	  ((sig->scope()->type() == NetScope::TASK) ||
	   (sig->scope()->type() == NetScope::FUNC) ||
	   (sig->scope()->type() == NetScope::MODULE)))
	    return;

	/* Can't delete ports of cells. */
      if ((sig->port_type() != NetNet::NOT_A_PORT)
	  && (sig->scope()->attribute(perm_string::literal("ivl_synthesis_cell")) != verinum()))
	    return;

	/* Don't delete signals that are marked with the
	   ivl_do_not_elide property. */
      if (!sig->local_flag()
	  && (sig->attribute(perm_string::literal("ivl_do_not_elide")) != verinum()))
	    return;

	/* Check to see if the signal is completely unconnected. If
	   all the bits are unlinked, then delete it. */
      if (! sig->is_linked()) {
	    delete sig;
	    stotal += 1;
	    return;
      }

	/* The remaining things can only be done to synthesized
	   signals, not ones that appear in the original Verilog. */
      if (! sig->local_flag())
	    return;

	/* Check to see if there is some significant signal connected
	   to every pin of this signal. */
      unsigned significant_flags = 0;
      for (unsigned idx = 0 ;  idx < sig->pin_count() ;  idx += 1) {
	    Nexus*nex = sig->pin(idx).nexus();

	    for (Link*cur = nex->first_nlink()
		       ; cur ;  cur = cur->next_nlink()) {

		  if (cur == &sig->pin(idx))
			continue;

		  NetNet*cursig = dynamic_cast<NetNet*>(cur->get_obj());
		  if (cursig == 0)
			continue;

		  if (cursig->local_flag())
			continue;

		  significant_flags += 1;
		  break;
	    }

	    if (significant_flags <= idx)
		  break;
      }

	/* If every pin is connected to another significant signal,
	   then I can delete this one. */
      if (significant_flags == sig->pin_count()) {
	    delete sig;
	    stotal += 1;
      }
}

void nodangle(Design*des)
{
      nodangle_f fun;
      fun.iteration = 0;
      fun.stotal = 0;
      fun.etotal = 0;
      fun.scomplete = false;
      fun.ecomplete = false;
      do {
	    if (verbose_flag) {
		  cout << " ... scan for dangling signal and event nodes. "
		       << "(scomplete=" << (fun.scomplete? "T" : "F")
		       << ", ecomplete=" << (fun.ecomplete? "T" : "F")
		       << ")" << endl << flush;
	    }

            fun.scontinue = false;
            fun.econtinue = false;
	    des->functor(&fun);
	    fun.iteration += 1;
            fun.scomplete = !fun.scontinue;
            fun.ecomplete = !fun.econtinue;

	    if (verbose_flag) {
		  cout << " ... " << fun.iteration << " iterations"
		       << " deleted " << fun.stotal << " dangling signals"
		       << " and " << fun.etotal << " events." << endl << flush;
	    }

      } while (fun.scontinue || fun.econtinue);

      if (verbose_flag) {
	    cout << " ... done" << endl << flush;
      }
}
<|endoftext|>


<commit_before>#include <thread>
#include <vector>
#include <atomic>

#include "spdlog/spdlog.h"

#include <iostream>
using namespace std;

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

    int thread_count = 10;
    if(argc > 1)
        thread_count = atoi(argv[1]);

    int howmany = 1000000;

    namespace spd = spdlog;
    ///Create a file rotating logger with 5mb size max and 3 rotated files
    auto logger = spd::rotating_logger_mt("file_logger", "logs/spd-sample", 10 *1024 * 1024 , 5);

    logger->set_pattern("[%Y-%b-%d %T.%e]: %v");

    std::atomic<int > msg_counter {0};
    vector<thread> threads;

    for (int t = 0; t < thread_count; ++t)
    {
        threads.push_back(std::thread([&]()
        {
            while (true)
            {
                int counter = ++msg_counter;
                if (counter > howmany) break;
                logger->info() << "spdlog message #" << counter << ": This is some text for your pleasure";
            }
        }));
    }

    for(auto &t:threads)
    {
        t.join();
    };

    return 0;
}
<commit_msg>small fix in comment<commit_after>#include <thread>
#include <vector>
#include <atomic>

#include "spdlog/spdlog.h"

#include <iostream>
using namespace std;

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

    int thread_count = 10;
    if(argc > 1)
        thread_count = atoi(argv[1]);

    int howmany = 1000000;

    namespace spd = spdlog;
    ///Create a file rotating logger with 5mb size max and 5 rotated files
    auto logger = spd::rotating_logger_mt("file_logger", "logs/spd-sample", 10 *1024 * 1024 , 5);

    logger->set_pattern("[%Y-%b-%d %T.%e]: %v");

    std::atomic<int > msg_counter {0};
    vector<thread> threads;

    for (int t = 0; t < thread_count; ++t)
    {
        threads.push_back(std::thread([&]()
        {
            while (true)
            {
                int counter = ++msg_counter;
                if (counter > howmany) break;
                logger->info() << "spdlog message #" << counter << ": This is some text for your pleasure";
            }
        }));
    }

    for(auto &t:threads)
    {
        t.join();
    };

    return 0;
}
<|endoftext|>


<commit_before>#include "blendMap.h"
#include "HeightMap.h"
#include "PivotPoint.h"
#include "utility.h"

BlendMap::BlendMap()
{
	m_texBlendMap = NULL;
	m_srvBlendMap = NULL;
}
BlendMap::~BlendMap()
{
	SAFE_RELEASE(m_texBlendMap);
	SAFE_RELEASE(m_srvBlendMap);
}

void BlendMap::update(ID3D11DeviceContext* p_devcon,
					  PivotPoint* p_pivot,
					  HeightMap* p_heightMap,
					  ManagementMenu::ToolPropertyIds toolProperty)
{
	int col		 = p_heightMap->getCol(p_pivot->getPosition().x);
	int row		 = p_heightMap->getRow(p_pivot->getPosition().z);
	float radius = p_pivot->getSize();
	float speed  = p_pivot->getSpeed();

	for( int x=col-radius; x<col+radius; x++ )
	{
		for( int z=row-radius; z<row+radius; z++ )
		{

			if(insideCircle(radius, x, z, col, row))
			{
				int index = z*m_width + x;
				if(index >= 0 && index < m_numTexels)
				{
					if(toolProperty == ManagementMenu::ToolPropertyIds_PROPERTY_0)
						modifyRed(speed, index);
					else if(toolProperty == ManagementMenu::ToolPropertyIds_PROPERTY_1)
						modifyGreen(speed, index);
					else if(toolProperty == ManagementMenu::ToolPropertyIds_PROPERTY_2)
						modifyBlue(speed, index);
				}
			}
		}
	}
	updateTexture(p_devcon);
}

void BlendMap::setTexel(ID3D11DeviceContext* p_devcon, Texel p_texel, int p_x, int p_y)
{
	m_texels[p_x * m_width + p_y] = p_texel;
	updateTexture(p_devcon);
}
void BlendMap::setAllTexels(ID3D11DeviceContext* p_devcon, Texel p_texel)
{
	for(unsigned int i=0; i<m_texels.size(); i++)
		m_texels[i] = p_texel;

	updateTexture(p_devcon);
}

void BlendMap::psSetBlendMap(ID3D11DeviceContext* p_devcon, unsigned int startSlott)
{
	p_devcon->PSSetShaderResources(startSlott, 1, &m_srvBlendMap);
}

ID3D11Texture2D* BlendMap::getTexBlendMap() const
{
	return m_texBlendMap;
}
ID3D11ShaderResourceView* BlendMap::getSrvBlendMap() const
{
	return m_srvBlendMap;
}

HRESULT BlendMap::init(ID3D11Device* p_device, int p_width, int p_height)
{
	m_width		= p_width;
	m_height	= p_height;
	m_numTexels = m_width * m_height;
	m_texels.resize(p_width*p_height, Texel(0, 0, 0, 0));

	HRESULT hr = S_OK;
	hr = initTexBlendMap(p_device, p_width, p_height);
	if(SUCCEEDED(hr))
		hr = initSrvBlendMap(p_device);

	return hr;
}
HRESULT BlendMap::initTexBlendMap(ID3D11Device* p_device, int p_width, int p_height)
{
	HRESULT hr = S_OK;

	D3D11_TEXTURE2D_DESC texDesc;
	ZeroMemory(&texDesc, sizeof(texDesc));

	texDesc.Width				= p_width;
	texDesc.Height				= p_height;
	texDesc.MipLevels			= 1;
	texDesc.ArraySize			= 1;
	texDesc.Format				= DXGI_FORMAT_R8G8B8A8_UNORM;
	texDesc.SampleDesc.Count	= 1;
	texDesc.SampleDesc.Quality	= 0;
	texDesc.Usage				= D3D11_USAGE_DYNAMIC;
	texDesc.BindFlags			= D3D11_BIND_SHADER_RESOURCE;
	texDesc.CPUAccessFlags		= D3D11_CPU_ACCESS_WRITE;
	texDesc.MiscFlags			= 0;

	hr = p_device->CreateTexture2D(&texDesc, NULL, &m_texBlendMap);
	if(FAILED(hr))
		MessageBox(NULL, L"BlendMap::initTexBlendMap() | device->CreateTexture2D() | Failed", L"BlendMap", MB_OK | MB_ICONEXCLAMATION);

	return hr;
}
HRESULT BlendMap::initSrvBlendMap(ID3D11Device* p_device)
{
	HRESULT hr = S_OK;

	D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
	ZeroMemory(&srvDesc, sizeof(srvDesc));

	srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
	srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
	srvDesc.Texture2D.MostDetailedMip = 0;
	srvDesc.Texture2D.MipLevels = 1;

	hr = p_device->CreateShaderResourceView(m_texBlendMap, &srvDesc, &m_srvBlendMap);
	if(FAILED(hr))
		MessageBox(NULL, L"BlendMap::initSrvBlendMap() | device->CreateShaderResourceView() | Failed", L"BlendMap", MB_OK | MB_ICONEXCLAMATION);

	return hr;
}

HRESULT BlendMap::updateTexture(ID3D11DeviceContext* p_devcon)
{
	D3D11_MAPPED_SUBRESOURCE resource;
	ZeroMemory(&resource, sizeof(resource));

	HRESULT hr = S_OK;
	hr = p_devcon->Map(m_texBlendMap, 0, D3D11_MAP_WRITE_DISCARD, 0, &resource);
	if(FAILED(hr))
		MessageBox(NULL, L"BlendMap::setPixel() | devcon->Map() | Failed", L"BlendMap", MB_OK | MB_ICONEXCLAMATION);

	memcpy( resource.pData,& m_texels[0], sizeof(m_texels[0])*m_texels.size() );

	p_devcon->Unmap(m_texBlendMap, 0);

	return hr;
}

void BlendMap::modifyRed(float p_value, int p_index)
{
	int newValue = m_texels[p_index].m_red;
	newValue += p_value;
	if(newValue > 254)
		newValue = 254;
	else if(newValue < 0)
		newValue = 0;

	m_texels[p_index].m_red = newValue;
}
void BlendMap::modifyGreen(float p_value, int p_index)
{
	int newValue = m_texels[p_index].m_green;
	newValue += p_value;
	if(newValue > 254)
		newValue = 254;
	else if(newValue < 0)
		newValue = 0;

	m_texels[p_index].m_green = newValue;
}
void BlendMap::modifyBlue(float p_value, int p_index)
{
	int newValue = m_texels[p_index].m_blue;
	newValue += p_value;
	if(newValue > 254)
		newValue = 254;
	else if(newValue < 0)
		newValue = 0;

	m_texels[p_index].m_blue = newValue;
}

bool BlendMap::insideCircle(float p_radius, int p_x, int p_z, int p_col, int p_row)
{
	float hyp = sqrt((p_col-p_x)*(p_col-p_x)+(p_row-p_z)*(p_row-p_z));

	return hyp < p_radius;
}<commit_msg>Removed a coule of warnings.<commit_after>#include "blendMap.h"
#include "HeightMap.h"
#include "PivotPoint.h"
#include "utility.h"

BlendMap::BlendMap()
{
	m_texBlendMap = NULL;
	m_srvBlendMap = NULL;
}
BlendMap::~BlendMap()
{
	SAFE_RELEASE(m_texBlendMap);
	SAFE_RELEASE(m_srvBlendMap);
}

void BlendMap::update(ID3D11DeviceContext* p_devcon,
					  PivotPoint* p_pivot,
					  HeightMap* p_heightMap,
					  ManagementMenu::ToolPropertyIds toolProperty)
{
	int col		 = p_heightMap->getCol(p_pivot->getPosition().x);
	int row		 = p_heightMap->getRow(p_pivot->getPosition().z);
	float radius = p_pivot->getSize();
	float speed  = p_pivot->getSpeed();

	int lowX  = col - static_cast<int>(radius);
	int highX = col + static_cast<int>(radius);
	int lowZ  = row - static_cast<int>(radius);
	int highZ = row + static_cast<int>(radius);

	for( int x=lowX; x<highX; x++ )
	{
		for( int z=lowZ; z<highZ; z++ )
		{

			if(insideCircle(radius, x, z, col, row))
			{
				int index = z*m_width + x;
				if(index >= 0 && index < m_numTexels)
				{
					if(toolProperty == ManagementMenu::ToolPropertyIds_PROPERTY_0)
						modifyRed(speed, index);
					else if(toolProperty == ManagementMenu::ToolPropertyIds_PROPERTY_1)
						modifyGreen(speed, index);
					else if(toolProperty == ManagementMenu::ToolPropertyIds_PROPERTY_2)
						modifyBlue(speed, index);
				}
			}
		}
	}
	updateTexture(p_devcon);
}

void BlendMap::setTexel(ID3D11DeviceContext* p_devcon, Texel p_texel, int p_x, int p_y)
{
	m_texels[p_x * m_width + p_y] = p_texel;
	updateTexture(p_devcon);
}
void BlendMap::setAllTexels(ID3D11DeviceContext* p_devcon, Texel p_texel)
{
	for(unsigned int i=0; i<m_texels.size(); i++)
		m_texels[i] = p_texel;

	updateTexture(p_devcon);
}

void BlendMap::psSetBlendMap(ID3D11DeviceContext* p_devcon, unsigned int startSlott)
{
	p_devcon->PSSetShaderResources(startSlott, 1, &m_srvBlendMap);
}

ID3D11Texture2D* BlendMap::getTexBlendMap() const
{
	return m_texBlendMap;
}
ID3D11ShaderResourceView* BlendMap::getSrvBlendMap() const
{
	return m_srvBlendMap;
}

HRESULT BlendMap::init(ID3D11Device* p_device, int p_width, int p_height)
{
	m_width		= p_width;
	m_height	= p_height;
	m_numTexels = m_width * m_height;
	m_texels.resize(p_width*p_height, Texel(0, 0, 0, 0));

	HRESULT hr = S_OK;
	hr = initTexBlendMap(p_device, p_width, p_height);
	if(SUCCEEDED(hr))
		hr = initSrvBlendMap(p_device);

	return hr;
}
HRESULT BlendMap::initTexBlendMap(ID3D11Device* p_device, int p_width, int p_height)
{
	HRESULT hr = S_OK;

	D3D11_TEXTURE2D_DESC texDesc;
	ZeroMemory(&texDesc, sizeof(texDesc));

	texDesc.Width				= p_width;
	texDesc.Height				= p_height;
	texDesc.MipLevels			= 1;
	texDesc.ArraySize			= 1;
	texDesc.Format				= DXGI_FORMAT_R8G8B8A8_UNORM;
	texDesc.SampleDesc.Count	= 1;
	texDesc.SampleDesc.Quality	= 0;
	texDesc.Usage				= D3D11_USAGE_DYNAMIC;
	texDesc.BindFlags			= D3D11_BIND_SHADER_RESOURCE;
	texDesc.CPUAccessFlags		= D3D11_CPU_ACCESS_WRITE;
	texDesc.MiscFlags			= 0;

	hr = p_device->CreateTexture2D(&texDesc, NULL, &m_texBlendMap);
	if(FAILED(hr))
		MessageBox(NULL, L"BlendMap::initTexBlendMap() | device->CreateTexture2D() | Failed", L"BlendMap", MB_OK | MB_ICONEXCLAMATION);

	return hr;
}
HRESULT BlendMap::initSrvBlendMap(ID3D11Device* p_device)
{
	HRESULT hr = S_OK;

	D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
	ZeroMemory(&srvDesc, sizeof(srvDesc));

	srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
	srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
	srvDesc.Texture2D.MostDetailedMip = 0;
	srvDesc.Texture2D.MipLevels = 1;

	hr = p_device->CreateShaderResourceView(m_texBlendMap, &srvDesc, &m_srvBlendMap);
	if(FAILED(hr))
		MessageBox(NULL, L"BlendMap::initSrvBlendMap() | device->CreateShaderResourceView() | Failed", L"BlendMap", MB_OK | MB_ICONEXCLAMATION);

	return hr;
}

HRESULT BlendMap::updateTexture(ID3D11DeviceContext* p_devcon)
{
	D3D11_MAPPED_SUBRESOURCE resource;
	ZeroMemory(&resource, sizeof(resource));

	HRESULT hr = S_OK;
	hr = p_devcon->Map(m_texBlendMap, 0, D3D11_MAP_WRITE_DISCARD, 0, &resource);
	if(FAILED(hr))
		MessageBox(NULL, L"BlendMap::setPixel() | devcon->Map() | Failed", L"BlendMap", MB_OK | MB_ICONEXCLAMATION);

	memcpy( resource.pData,& m_texels[0], sizeof(m_texels[0])*m_texels.size() );

	p_devcon->Unmap(m_texBlendMap, 0);

	return hr;
}

void BlendMap::modifyRed(float p_value, int p_index)
{
	int newValue = m_texels[p_index].m_red;
	newValue += static_cast<int>(p_value);
	if(newValue > 254)
		newValue = 254;
	else if(newValue < 0)
		newValue = 0;

	m_texels[p_index].m_red = newValue;
}
void BlendMap::modifyGreen(float p_value, int p_index)
{
	int newValue = m_texels[p_index].m_green;
	newValue += static_cast<int>(p_value);
	if(newValue > 254)
		newValue = 254;
	else if(newValue < 0)
		newValue = 0;

	m_texels[p_index].m_green = newValue;
}
void BlendMap::modifyBlue(float p_value, int p_index)
{
	int newValue = m_texels[p_index].m_blue;
	newValue += static_cast<int>(p_value);
	if(newValue > 254)
		newValue = 254;
	else if(newValue < 0)
		newValue = 0;

	m_texels[p_index].m_blue = newValue;
}

bool BlendMap::insideCircle(float p_radius, int p_x, int p_z, int p_col, int p_row)
{
	int temp = (p_col-p_x)*(p_col-p_x)+(p_row-p_z)*(p_row-p_z);
	float hyp = sqrtf(static_cast<float>(temp));

	return hyp < p_radius;
}<|endoftext|>


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

  Program:   The OpenIGTLink Library
  Language:  C++
  Web page:  http://openigtlink.org/

  Copyright (c) Insight Software Consortium. All rights reserved.

  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 "igtlUnit.h"
#include "igtl_unit.h"

// Disable warning C4996 (strncpy() may be unsafe) in Windows.
#define _CRT_SECURE_NO_WARNINGS

namespace igtl {

Unit::Unit():
  Object()
{
  Init();
}

Unit::~Unit()
{
}

void Unit::Init()
{
  this->m_Prefix = SI_PREFIX_NONE;
  this->m_NUnits = 0;

  for (int i = 0; i < 6; i ++)
    {
    this->m_Unit[i] = SI_BASE_NONE;
    this->m_Exp[i]  = 0;
    }
}

int Unit::SetPrefix(int prefix)
{
  if (prefix >= SI_PREFIX_NONE && prefix <= SI_PREFIX_FEMTO)
    {
    this->m_Prefix = prefix;
    return 1;
    }
  else
    {
    return 0;
    }
}

int Unit::Append(int unit, int exp)
{
  // Check number of units already appended
  if (this->m_NUnits >= 6)
    {
    return 0;
    }

  // Check range
  if (unit < SI_BASE_NONE || unit >= SI_NUM_UNIT_TYPES)
    {
    return 0;
    }
  if (exp < -7 || exp > 7)
    {
    return 0;
    }

  // Append
  this->m_Unit[this->m_NUnits] = (igtlUint8)unit;
  this->m_Exp[this->m_NUnits] =  (igtlInt8)exp;

  return 1;
}

igtlUnit Unit::Pack()
{
  igtl_unit_data data;

  igtl_unit_init(&data);

  data.prefix = this->m_Prefix;
  for (int i = 0; i < 6; i ++)
    {
    data.unit[i] = this->m_Unit[i];
    data.exp[i] = this->m_Exp[i];
    }

  return (igtlUnit) igtl_unit_pack(&data);
}

int Unit::Unpack(igtlUnit unit)
{
  igtl_unit_data data;

  if (igtl_unit_unpack((igtl_unit)unit, &data) == 0)
    {
    return 0;
    }

  Init();

  this->m_Prefix = data.prefix;
  for (int i = 0; i < 6; i ++)
    {
    this->m_Unit[i] = data.unit[i];
    this->m_Exp[i]  = data.exp[i];
    }

  return 1;

}

} // namespace igtl

<commit_msg>igtlUnit index incremented after one assignment<commit_after>/*=========================================================================

  Program:   The OpenIGTLink Library
  Language:  C++
  Web page:  http://openigtlink.org/

  Copyright (c) Insight Software Consortium. All rights reserved.

  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 "igtlUnit.h"
#include "igtl_unit.h"

// Disable warning C4996 (strncpy() may be unsafe) in Windows.
#define _CRT_SECURE_NO_WARNINGS

namespace igtl {

Unit::Unit():
  Object()
{
  Init();
}

Unit::~Unit()
{
}

void Unit::Init()
{
  this->m_Prefix = SI_PREFIX_NONE;
  this->m_NUnits = 0;

  for (int i = 0; i < 6; i ++)
    {
    this->m_Unit[i] = SI_BASE_NONE;
    this->m_Exp[i]  = 0;
    }
}

int Unit::SetPrefix(int prefix)
{
  if (prefix >= SI_PREFIX_NONE && prefix <= SI_PREFIX_FEMTO)
    {
    this->m_Prefix = prefix;
    return 1;
    }
  else
    {
    return 0;
    }
}

int Unit::Append(int unit, int exp)
{
  // Check number of units already appended
  if (this->m_NUnits >= 6)
    {
    return 0;
    }

  // Check range
  if (unit < SI_BASE_NONE || unit >= SI_NUM_UNIT_TYPES)
    {
    return 0;
    }
  if (exp < -7 || exp > 7)
    {
    return 0;
    }

  // Append
  this->m_Unit[this->m_NUnits] = (igtlUint8)unit;
  this->m_Exp[this->m_NUnits] =  (igtlInt8)exp;
  this->m_NUnits++;
  return 1;
}

igtlUnit Unit::Pack()
{
  igtl_unit_data data;

  igtl_unit_init(&data);

  data.prefix = this->m_Prefix;
  for (int i = 0; i < 6; i ++)
    {
    data.unit[i] = this->m_Unit[i];
    data.exp[i] = this->m_Exp[i];
    }

  return (igtlUnit) igtl_unit_pack(&data);
}

int Unit::Unpack(igtlUnit unit)
{
  igtl_unit_data data;

  if (igtl_unit_unpack((igtl_unit)unit, &data) == 0)
    {
    return 0;
    }

  Init();

  this->m_Prefix = data.prefix;
  for (int i = 0; i < 6; i ++)
    {
    this->m_Unit[i] = data.unit[i];
    this->m_Exp[i]  = data.exp[i];
    }

  return 1;

}

} // namespace igtl

<|endoftext|>


<commit_before>#include <Toolbox/catch.hpp>

#include "TestSink.h"
#include <Toolbox/Sink/ThreadSafeProxySink.h>
#include <thread>
#include <sstream>

using namespace Toolbox::Sink;

TEST_CASE ("ThreadSafeProxySink with lvalue Sink")
{
  std::string rc;
  Test::Sink sink (rc);
  ThreadSafeProxySink<Test::Sink> proxySink (std::move (sink));
  std::string message = "test";
  proxySink << message;

  REQUIRE (rc == message);
}

TEST_CASE ("ThreadSafeProxySink with rvalue Sink")
{
  std::string rc;
  ThreadSafeProxySink<Test::Sink> proxySink (Test::Sink {rc});
  std::string message = "test";
  proxySink << message;

  REQUIRE (rc == message);
}

TEST_CASE ("Instantiate ThreadSafeProxySink using make_thread_safe")
{
  std::string rc;
  auto proxySink = make_thread_safe<Test::Sink>(rc);
  std::string message = "test";
  proxySink << message;

  REQUIRE (rc == message);
}

TEST_CASE ("ThreadSafeSink")
{
  std::string rc;
  Test::SafeSink safeSink (rc);
  std::string message = "test";
  safeSink << message;

  REQUIRE (rc == message);
}<commit_msg>added make_unique_thread_safe test<commit_after>#include <Toolbox/catch.hpp>

#include "TestSink.h"
#include <Toolbox/Sink/ThreadSafeProxySink.h>
#include <thread>
#include <sstream>

using namespace Toolbox::Sink;

TEST_CASE ("ThreadSafeProxySink with lvalue Sink")
{
  std::string rc;
  Test::Sink sink (rc);
  ThreadSafeProxySink<Test::Sink> proxySink (std::move (sink));
  std::string message = "test";
  proxySink << message;

  REQUIRE (rc == message);
}

TEST_CASE ("ThreadSafeProxySink with rvalue Sink")
{
  std::string rc;
  ThreadSafeProxySink<Test::Sink> proxySink (Test::Sink {rc});
  std::string message = "test";
  proxySink << message;

  REQUIRE (rc == message);
}

TEST_CASE ("Instantiate ThreadSafeProxySink using make_thread_safe")
{
  std::string rc;
  auto proxySink = make_thread_safe<Test::Sink>(rc);
  std::string message = "test";
  proxySink << message;

  REQUIRE (rc == message);
}

TEST_CASE ("Instantiate a unique_ptr<ThreadSafeProxySink> using make_unique_thread_safe")
{
  std::string rc;
  auto proxySink = make_unique_thread_safe<Test::Sink>(rc);
  std::string message = "test";
  (*proxySink) << message;

  REQUIRE (rc == message);
}

TEST_CASE ("ThreadSafeSink")
{
  std::string rc;
  Test::SafeSink safeSink (rc);
  std::string message = "test";
  safeSink << message;

  REQUIRE (rc == message);
}<|endoftext|>


<commit_before>
#include "NNSound.h"
#include "NNApplication.h"

void GetFileExtenstion(const wchar_t * file_name, wchar_t * file_ext, size_t file_ext_size)
{
	_wsplitpath_s(file_name, NULL, 0, NULL, 0, NULL, 0, file_ext, file_ext_size);
	wprintf(L"%s\n", file_ext);

	/*wchar_t* _file_name = nullptr;
	_file_name = (wchar_t*)malloc(1024);
	wcscpy_s(_file_name, 256, file_name);
	int file_name_len = wcslen (_file_name);
	_file_name +=file_name_len ;

	wchar_t *file_ext = nullptr;
	for(int i = 0 ; i <file_name_len ; i ++)
	{
		if(* _file_name == '.' )
		{
			file_ext = _file_name +1 ;
			break;
		}
		_file_name --;
	}
	return file_ext ;*/
	//return file_ext;
}

NNSound::NNSound()
	: m_Playing(false)
{
}
NNSound::~NNSound()
{
	Destroy();
}

void NNSound::Create( std::wstring path )
{
	MCI_OPEN_PARMS mciOpen = {0};
	MCIERROR mciError = {0};
	wchar_t file_ext[10];

	GetFileExtenstion(path.c_str(), file_ext, sizeof(file_ext) / sizeof(wchar_t));

	if(wcscmp(file_ext, L".mp3") == 0 )
	{
		//mp3
		mciOpen.lpstrDeviceType = L"MPEGVideo";//(LPCWSTR)MCI_DEVTYPE_WAVEFORM_AUDIO;
	}
	else if(wcscmp(file_ext, L".wav") == 0 )
	{
		mciOpen.lpstrDeviceType = L"waveaudio";//(LPCWSTR)MCI_DEVTYPE_WAVEFORM_AUDIO;
	}
	mciOpen.lpstrElementName = path.c_str();

	mciError = mciSendCommand( NULL, MCI_OPEN, MCI_OPEN_ELEMENT|MCI_OPEN_TYPE, (DWORD)&mciOpen );
	if ( mciError )
	{
		return;
	}

	m_MciDevice = mciOpen.wDeviceID;
	m_Playing = false;
}

void NNSound::Destroy()
{
	if ( m_Playing )
	{
		Stop();
	}
	if ( m_MciDevice )
	{
		mciSendCommand( m_MciDevice, MCI_CLOSE, 0, 0 );
	}
}

void NNSound::Play()
{
	if ( !m_MciDevice )
	{
		return;
	}
	MCI_PLAY_PARMS mciPlay = {0};
	MCIERROR mciError = {0};

	mciPlay.dwCallback = (DWORD_PTR)NNApplication::GetInstance()->GetHWND();
	mciError = mciSendCommand( m_MciDevice, MCI_PLAY, MCI_FROM|MCI_NOTIFY, (DWORD)&mciPlay );
	if ( !mciError )
	{
		m_Playing = true;
	}
}
void NNSound::Pause()
{
	if ( !m_MciDevice )
	{
		return;
	}
	mciSendCommand( m_MciDevice, MCI_PAUSE, 0, 0 );
}
void NNSound::Resume()
{
	if ( !m_MciDevice )
	{
		return;
	}
	mciSendCommand( m_MciDevice, MCI_RESUME, 0, 0 );
}
void NNSound::Stop()
{
	if ( !m_MciDevice )
	{
		return;
	}
	mciSendCommand( m_MciDevice, MCI_STOP, 0, 0 );
	m_Playing = false;
}

<commit_msg>불필요한 함수 삭제 및 수정<commit_after>
#include "NNSound.h"
#include "NNApplication.h"

NNSound::NNSound()
	: m_Playing(false)
{
}
NNSound::~NNSound()
{
	Destroy();
}

void NNSound::Create( std::wstring path )
{
	MCI_OPEN_PARMS mciOpen = {0};
	MCIERROR mciError = {0};
	wchar_t file_ext[10];

	// Ȯ
	_wsplitpath_s(path.c_str(), NULL, 0, NULL, 0, NULL, 0, file_ext, sizeof(file_ext) / sizeof(wchar_t));

	if(wcscmp(file_ext, L".mp3") == 0 )
	{
		//mp3
		mciOpen.lpstrDeviceType = L"MPEGVideo";//(LPCWSTR)MCI_DEVTYPE_WAVEFORM_AUDIO;
	}
	else if(wcscmp(file_ext, L".wav") == 0 )
	{
		mciOpen.lpstrDeviceType = L"waveaudio";//(LPCWSTR)MCI_DEVTYPE_WAVEFORM_AUDIO;
	}
	mciOpen.lpstrElementName = path.c_str();

	mciError = mciSendCommand( NULL, MCI_OPEN, MCI_OPEN_ELEMENT|MCI_OPEN_TYPE, (DWORD)&mciOpen );
	if ( mciError )
	{
		return;
	}

	m_MciDevice = mciOpen.wDeviceID;
	m_Playing = false;
}

void NNSound::Destroy()
{
	if ( m_Playing )
	{
		Stop();
	}
	if ( m_MciDevice )
	{
		mciSendCommand( m_MciDevice, MCI_CLOSE, 0, 0 );
	}
}

void NNSound::Play()
{
	if ( !m_MciDevice )
	{
		return;
	}
	MCI_PLAY_PARMS mciPlay = {0};
	MCIERROR mciError = {0};

	mciPlay.dwCallback = (DWORD_PTR)NNApplication::GetInstance()->GetHWND();
	mciError = mciSendCommand( m_MciDevice, MCI_PLAY, MCI_FROM|MCI_NOTIFY, (DWORD)&mciPlay );
	if ( !mciError )
	{
		m_Playing = true;
	}
}
void NNSound::Pause()
{
	if ( !m_MciDevice )
	{
		return;
	}
	mciSendCommand( m_MciDevice, MCI_PAUSE, 0, 0 );
}
void NNSound::Resume()
{
	if ( !m_MciDevice )
	{
		return;
	}
	mciSendCommand( m_MciDevice, MCI_RESUME, 0, 0 );
}
void NNSound::Stop()
{
	if ( !m_MciDevice )
	{
		return;
	}
	mciSendCommand( m_MciDevice, MCI_STOP, 0, 0 );
	m_Playing = false;
}

<|endoftext|>


<commit_before>/*
	This file is part of the GUI library.
	Copyright (C) 2008-2012 Benjamin Eikel <benjamin@eikel.org>
	Copyright (C) 2008-2012 Claudius Jähn <claudius@uni-paderborn.de>
	Copyright (C) 2008-2012 Ralf Petring <ralf@petring.net>

	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/.
*/
#include "StdShapes.h"
#include "../Base/Draw.h"
#include "../Base/BasicColors.h"
#include "Colors.h"
#include <Geometry/Interpolation.h>
#include <Util/References.h>
#include <iostream>

using namespace Geometry;

namespace GUI {

//! OuterRectShadowShape ---|> AbstractShape
void OuterRectShadowShape::display(const Rect & rect,flag_t /*flag*/){
	Geometry::Rect rect2(rect.getMinX()-size_left,rect.getMinX()-size_top,rect.getWidth()+size_left+size_right,rect.getHeight()+size_top+size_bottom);
	Draw::dropShadow(rect,rect2,color);
}
//! RectShape ---|> AbstractShape
void RectShape::display(const Rect & rect,flag_t /*flag*/){
	Draw::drawFilledRect(rect,bgColor,blend);
	Draw::drawLineRect(rect,lineColor,blend);
}

//! Rect3dShape ---|> AbstractShape
void Rect3dShape::display(const Rect & rect,flag_t flags){
	Draw::draw3DRect(rect, (flags&ACTIVE)^invert , bgColor1, bgColor2);
}

//! ScrollableMarkerShape ---|> AbstractShape
void ScrollableMarkerShape::display(const Rect & rect,flag_t /*flag*/){
	if(!colorTop.isTransparent()){
		Draw::drawFilledRect(Rect(rect.getMinX(),rect.getMinY(),rect.getWidth(),width),
						colorTop,Colors::NO_COLOR,Colors::NO_COLOR,colorTop);
	}
	else if(!colorRight.isTransparent()){
		Draw::drawFilledRect(Rect(rect.getMaxX()-width,rect.getMinY(),width,rect.getHeight()),
						Colors::NO_COLOR,Colors::NO_COLOR,colorRight,colorRight);
	}
	else if(!colorBottom.isTransparent()){
		Draw::drawFilledRect(Rect(rect.getMinX(),rect.getMaxY()-width,rect.getWidth(),width),
						Colors::NO_COLOR,colorBottom,colorBottom,Colors::NO_COLOR);
	}
	else if(!colorLeft.isTransparent()){
		Draw::drawFilledRect(Rect(rect.getMinX(),rect.getMinY(),width,rect.getHeight()),
						colorLeft,colorLeft,Colors::NO_COLOR,Colors::NO_COLOR);
	}

}
//! ShadowedRectShape ---|> AbstractShape
void ShadowedRectShape::display(const Rect & rect,flag_t /*flag*/){
	Draw::drawFilledRect(rect,bgColor,blend);
	Draw::drawLineRect(rect,lineColor,blend);
	Draw::dropShadow(rect);
}

//! SliderMarkerShape ---|> AbstractShape
void SliderMarkerShape::display(const Rect & rect,flag_t flags){
	if (flags&ACTIVE)
		Draw::draw3DRect(rect,true,color1,color2);
	else
		Draw::draw3DRect(rect,false,color1,color2);
	Vec2 c=rect.getCenter();
	Draw::draw3DRect(Rect(c.x()-1 , c.y()-1 ,2,2),false,color1,color2);
}

//! TabHeaderShape ---|> AbstractShape
void TabHeaderShape::display(const Rect & rect,flag_t /*flags*/){
	Draw::drawTab(rect,color1,color2,color3);
}

//! Rounded3dRectShape ---|> AbstractShape
void Rounded3dRectShape::display(const Rect & rect,flag_t flags){
	const bool down=flags&ACTIVE;
	if (bgColor1 != Colors::NO_COLOR){
		std::vector<float> vertices;
		std::vector<uint32_t> colors;
		vertices.reserve(8*2);
		colors.reserve(8);

		colors.insert(colors.end(),4, (down ? bgColor2:bgColor1).getAsUInt());
		vertices.push_back(rect.getMaxX());				vertices.push_back(rect.getMinY()+roundnessTR);
		vertices.push_back(rect.getMaxX()-roundnessTR);	vertices.push_back(rect.getMinY());
		vertices.push_back(rect.getMinX()+roundnessTL);	vertices.push_back(rect.getMinY());
		vertices.push_back(rect.getMinX());				vertices.push_back(rect.getMinY()+roundnessTL);

		colors.insert(colors.end(),4,(down ? bgColor1:bgColor2).getAsUInt());
		vertices.push_back(rect.getMinX());				vertices.push_back(rect.getMaxY()-roundnessBL);
		vertices.push_back(rect.getMinX()+roundnessBL);	vertices.push_back(rect.getMaxY());
		vertices.push_back(rect.getMaxX()-roundnessBR);	vertices.push_back(rect.getMaxY());
		vertices.push_back(rect.getMaxX());				vertices.push_back(rect.getMaxY()-roundnessBR);

		Draw::drawTriangleFan(vertices,colors);
	}

	{	// draw border
		const Util::Color4ub c1 = down ? Colors::BRIGHT_COLOR : Colors::DARK_COLOR;
		const Util::Color4ub c2 = down ? Colors::DARK_COLOR   : Colors::BRIGHT_COLOR;

		std::vector<float> vertices;
		std::vector<uint32_t> colors;
		vertices.reserve(10*2);
		colors.reserve(10);

		const Geometry::Rect_i r2(rect);
		Geometry::Rect r3(r2);
		r3.moveRel(0.5f,0.5f);

		colors.insert(colors.end(),5,c1.getAsUInt());
		vertices.push_back(r3.getMinX());				vertices.push_back(r3.getMaxY()-roundnessBL);
		vertices.push_back(r3.getMinX()+roundnessBL);	vertices.push_back(r3.getMaxY());
		vertices.push_back(r3.getMaxX()-roundnessBR);	vertices.push_back(r3.getMaxY());
		vertices.push_back(r3.getMaxX());				vertices.push_back(r3.getMaxY()-roundnessBR);
		vertices.push_back(r3.getMaxX());				vertices.push_back(r3.getMinY()+roundnessTR);

		colors.insert(colors.end(),5,c2.getAsUInt());
		vertices.push_back(r3.getMaxX());				vertices.push_back(r3.getMinY()+roundnessTR);
		vertices.push_back(r3.getMaxX()-roundnessTR);	vertices.push_back(r3.getMinY());
		vertices.push_back(r3.getMinX()+roundnessTL);	vertices.push_back(r3.getMinY());
		vertices.push_back(r3.getMinX());				vertices.push_back(r3.getMinY()+roundnessTL);
		vertices.push_back(r3.getMinX());				vertices.push_back(r3.getMaxY()-roundnessBL);
		Draw::drawLine(vertices,colors,1.0);
	}
}
//
//! ResizerShape ---|> AbstractShape
void ResizerShape::display(const Rect & rect,flag_t /*flag*/){
	const float w=floorf(rect.getWidth()/4.0f);
	const float h=floorf(rect.getWidth()/4.0f);
	const float x=floorf(rect.getX());
	const float y=floorf(rect.getY());
	Draw::drawFilledRect(Rect(x + floorf(w*2.75f), y+ floorf(h*0.25f), w,h) ,color,blend);

	Draw::drawFilledRect(Rect(x + floorf(w*1.5f) , y+ floorf(h*1.5f), w,h) ,color,blend);
	Draw::drawFilledRect(Rect(x + floorf(w*2.75f), y+ floorf(h*1.5f), w,h) ,color,blend);

	Draw::drawFilledRect(Rect(x + floorf(w*0.25f), y+ floorf(h*2.75f), w,h) ,color,blend);
	Draw::drawFilledRect(Rect(x + floorf(w*1.5f) , y+ floorf(h*2.75f), w,h) ,color,blend);
	Draw::drawFilledRect(Rect(x + floorf(w*2.75f), y+ floorf(h*2.75f), w,h) ,color,blend);
}//

//! TriangleAtCornerShape ---|> AbstractShape
void TriangleAtCornerShape::display(const Rect & rect,flag_t/* flags*/){
	std::vector<float> vertices;
	std::vector<uint32_t> colors;
	vertices.reserve(3*2);
	colors.reserve(3);

	colors.insert(colors.end(),3, color.getAsUInt());

	const Geometry::Vec2 corner = rect.getCorner(CORNER_XY);
	vertices.push_back(corner.x());				vertices.push_back(corner.y());
	vertices.push_back(corner.x());				vertices.push_back(corner.y()-size);
	vertices.push_back(corner.x()-size);		vertices.push_back(corner.y());

	Draw::drawTriangleFan(vertices,colors);
}

//! TriangleSelectorShape ---|> AbstractShape
void TriangleSelectorShape::display(const Rect & rect,flag_t flags){
	std::vector<float> vertices;
	std::vector<uint32_t> colors;
	vertices.reserve(3*2);
	colors.reserve(3);

	colors.insert(colors.end(),3, color.getAsUInt());

	const float sideLength = std::min(rect.getWidth(),rect.getHeight());
	const float halfSideLength = sideLength*0.5;
	const float h = std::sqrt( sideLength*sideLength - halfSideLength*halfSideLength );
	const float halfH = h*0.5;
	const Geometry::Vec2 center = rect.getCenter();
	if(flags&ACTIVE){
		vertices.push_back(center.x()-halfSideLength);		vertices.push_back(center.y()-halfH);
		vertices.push_back(center.x());						vertices.push_back(center.y()+halfH);
		vertices.push_back(center.x()+halfSideLength);		vertices.push_back(center.y()-halfH);
	}else{
		vertices.push_back(center.x()-halfH);				vertices.push_back(center.y()-halfSideLength);
		vertices.push_back(center.x()-halfH);				vertices.push_back(center.y()+halfSideLength);
		vertices.push_back(center.x()+halfH);				vertices.push_back(center.y());
	}
	Draw::drawTriangleFan(vertices,colors);
}

//! GridShape ---|> AbstractShape
void GridShape::display(const Rect & rect,flag_t /*flag*/){
	std::vector<float> vertices;
	std::vector<uint32_t> colors;

	// horizontal lines
	if(hDistance>0){
		int count=0;
		for(float pos=0;pos<=rect.getHeight();pos+=hDistance){
			colors.insert(colors.end(),2,(((count++ % (hNumMinors+1)) ==0) ? majorColor : minorColor).getAsUInt());
			vertices.push_back(0);						vertices.push_back(pos);
			vertices.push_back(rect.getWidth());		vertices.push_back(pos);
		}
	}
	// vertical lines
	if(vDistance>0){
		int count=0;
		for(float pos=0;pos<=rect.getWidth();pos+=vDistance){
			colors.insert(colors.end(),2,(((count++ % (vNumMinors+1)) ==0) ? majorColor : minorColor).getAsUInt());
			vertices.push_back(pos);					vertices.push_back(0);
			vertices.push_back(pos);					vertices.push_back(rect.getHeight());
		}
	}
	Draw::drawLines(vertices,colors);
}

//! CrossShape ---|> AbstractShape
void CrossShape::display(const Rect & rect,flag_t flags){
	Draw::drawCross(rect,flags&ACTIVE ? color2 : color1,lineWidth);
}

//! StraightLineShape ---|> LineShape
void StraightLineShape::displayLine(const std::vector<Geometry::Vec2> & points,flag_t){
	std::vector<float> vertices;
	vertices.reserve(points.size()*2);
	for(auto & point : points){
		vertices.push_back(static_cast<int>(point.x())+0.5f);
		vertices.push_back(static_cast<int>(point.y())+0.5f);
	}

	std::vector<uint32_t> colors;
	colors.insert(colors.end(),vertices.size(),color.getAsUInt());
	Draw::drawLine(vertices,colors,lineWidth,true);
}

//! SmoothConnectorShape ---|> LineShape
void SmoothConnectorShape::displayLine(const std::vector<Geometry::Vec2> & points,flag_t){
	std::vector<float> vertices;
	for(size_t i=1;i<points.size();++i){
		const Geometry::Vec2 p0(points[i-1]); // startPoint
		const Geometry::Vec2 p3(points[i]); // endPoint
		const float d = std::min(p0.distance(p3)*0.4,100.0);
		const Geometry::Vec2 p1(p0+Geometry::Vec2(d,0));
		const Geometry::Vec2 p2(p3-Geometry::Vec2(d,0));

		vertices.push_back(p0.x());
		vertices.push_back(p0.y());
		for(float t=0.0;t<=1.00;t += t<0.5 ? ((t*t)+0.1)*0.1 : (( (1.0-t)*(1.0-t))+0.1)*0.1 ){
			const Geometry::Vec2 p_t = Interpolation::cubicBezier(p0, p1, p2, p3, t);
			vertices.push_back(p_t.x());
			vertices.push_back(p_t.y());
		}
	}
	std::vector<uint32_t> colors;
	colors.insert(colors.end(),vertices.size(),color.getAsUInt());
	Draw::drawLine(vertices,colors,lineWidth,true);
}

}
<commit_msg>Adapt to changes in Geometry<commit_after>/*
	This file is part of the GUI library.
	Copyright (C) 2008-2012 Benjamin Eikel <benjamin@eikel.org>
	Copyright (C) 2008-2012 Claudius Jähn <claudius@uni-paderborn.de>
	Copyright (C) 2008-2012 Ralf Petring <ralf@petring.net>

	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/.
*/
#include "StdShapes.h"
#include "../Base/Draw.h"
#include "../Base/BasicColors.h"
#include "Colors.h"
#include <Geometry/Interpolation.h>
#include <Util/References.h>
#include <iostream>

using namespace Geometry;

namespace GUI {

//! OuterRectShadowShape ---|> AbstractShape
void OuterRectShadowShape::display(const Rect & rect,flag_t /*flag*/){
	Geometry::Rect rect2(rect.getMinX()-size_left,rect.getMinX()-size_top,rect.getWidth()+size_left+size_right,rect.getHeight()+size_top+size_bottom);
	Draw::dropShadow(rect,rect2,color);
}
//! RectShape ---|> AbstractShape
void RectShape::display(const Rect & rect,flag_t /*flag*/){
	Draw::drawFilledRect(rect,bgColor,blend);
	Draw::drawLineRect(rect,lineColor,blend);
}

//! Rect3dShape ---|> AbstractShape
void Rect3dShape::display(const Rect & rect,flag_t flags){
	Draw::draw3DRect(rect, (flags&ACTIVE)^invert , bgColor1, bgColor2);
}

//! ScrollableMarkerShape ---|> AbstractShape
void ScrollableMarkerShape::display(const Rect & rect,flag_t /*flag*/){
	if(!colorTop.isTransparent()){
		Draw::drawFilledRect(Rect(rect.getMinX(),rect.getMinY(),rect.getWidth(),width),
						colorTop,Colors::NO_COLOR,Colors::NO_COLOR,colorTop);
	}
	else if(!colorRight.isTransparent()){
		Draw::drawFilledRect(Rect(rect.getMaxX()-width,rect.getMinY(),width,rect.getHeight()),
						Colors::NO_COLOR,Colors::NO_COLOR,colorRight,colorRight);
	}
	else if(!colorBottom.isTransparent()){
		Draw::drawFilledRect(Rect(rect.getMinX(),rect.getMaxY()-width,rect.getWidth(),width),
						Colors::NO_COLOR,colorBottom,colorBottom,Colors::NO_COLOR);
	}
	else if(!colorLeft.isTransparent()){
		Draw::drawFilledRect(Rect(rect.getMinX(),rect.getMinY(),width,rect.getHeight()),
						colorLeft,colorLeft,Colors::NO_COLOR,Colors::NO_COLOR);
	}

}
//! ShadowedRectShape ---|> AbstractShape
void ShadowedRectShape::display(const Rect & rect,flag_t /*flag*/){
	Draw::drawFilledRect(rect,bgColor,blend);
	Draw::drawLineRect(rect,lineColor,blend);
	Draw::dropShadow(rect);
}

//! SliderMarkerShape ---|> AbstractShape
void SliderMarkerShape::display(const Rect & rect,flag_t flags){
	if (flags&ACTIVE)
		Draw::draw3DRect(rect,true,color1,color2);
	else
		Draw::draw3DRect(rect,false,color1,color2);
	Vec2 c=rect.getCenter();
	Draw::draw3DRect(Rect(c.x()-1 , c.y()-1 ,2,2),false,color1,color2);
}

//! TabHeaderShape ---|> AbstractShape
void TabHeaderShape::display(const Rect & rect,flag_t /*flags*/){
	Draw::drawTab(rect,color1,color2,color3);
}

//! Rounded3dRectShape ---|> AbstractShape
void Rounded3dRectShape::display(const Rect & rect,flag_t flags){
	const bool down=flags&ACTIVE;
	if (bgColor1 != Colors::NO_COLOR){
		std::vector<float> vertices;
		std::vector<uint32_t> colors;
		vertices.reserve(8*2);
		colors.reserve(8);

		colors.insert(colors.end(),4, (down ? bgColor2:bgColor1).getAsUInt());
		vertices.push_back(rect.getMaxX());				vertices.push_back(rect.getMinY()+roundnessTR);
		vertices.push_back(rect.getMaxX()-roundnessTR);	vertices.push_back(rect.getMinY());
		vertices.push_back(rect.getMinX()+roundnessTL);	vertices.push_back(rect.getMinY());
		vertices.push_back(rect.getMinX());				vertices.push_back(rect.getMinY()+roundnessTL);

		colors.insert(colors.end(),4,(down ? bgColor1:bgColor2).getAsUInt());
		vertices.push_back(rect.getMinX());				vertices.push_back(rect.getMaxY()-roundnessBL);
		vertices.push_back(rect.getMinX()+roundnessBL);	vertices.push_back(rect.getMaxY());
		vertices.push_back(rect.getMaxX()-roundnessBR);	vertices.push_back(rect.getMaxY());
		vertices.push_back(rect.getMaxX());				vertices.push_back(rect.getMaxY()-roundnessBR);

		Draw::drawTriangleFan(vertices,colors);
	}

	{	// draw border
		const Util::Color4ub c1 = down ? Colors::BRIGHT_COLOR : Colors::DARK_COLOR;
		const Util::Color4ub c2 = down ? Colors::DARK_COLOR   : Colors::BRIGHT_COLOR;

		std::vector<float> vertices;
		std::vector<uint32_t> colors;
		vertices.reserve(10*2);
		colors.reserve(10);

		const Geometry::Rect_i r2(rect);
		Geometry::Rect r3(r2);
		r3.moveRel(0.5f,0.5f);

		colors.insert(colors.end(),5,c1.getAsUInt());
		vertices.push_back(r3.getMinX());				vertices.push_back(r3.getMaxY()-roundnessBL);
		vertices.push_back(r3.getMinX()+roundnessBL);	vertices.push_back(r3.getMaxY());
		vertices.push_back(r3.getMaxX()-roundnessBR);	vertices.push_back(r3.getMaxY());
		vertices.push_back(r3.getMaxX());				vertices.push_back(r3.getMaxY()-roundnessBR);
		vertices.push_back(r3.getMaxX());				vertices.push_back(r3.getMinY()+roundnessTR);

		colors.insert(colors.end(),5,c2.getAsUInt());
		vertices.push_back(r3.getMaxX());				vertices.push_back(r3.getMinY()+roundnessTR);
		vertices.push_back(r3.getMaxX()-roundnessTR);	vertices.push_back(r3.getMinY());
		vertices.push_back(r3.getMinX()+roundnessTL);	vertices.push_back(r3.getMinY());
		vertices.push_back(r3.getMinX());				vertices.push_back(r3.getMinY()+roundnessTL);
		vertices.push_back(r3.getMinX());				vertices.push_back(r3.getMaxY()-roundnessBL);
		Draw::drawLine(vertices,colors,1.0);
	}
}
//
//! ResizerShape ---|> AbstractShape
void ResizerShape::display(const Rect & rect,flag_t /*flag*/){
	const float w=floorf(rect.getWidth()/4.0f);
	const float h=floorf(rect.getWidth()/4.0f);
	const float x=floorf(rect.getX());
	const float y=floorf(rect.getY());
	Draw::drawFilledRect(Rect(x + floorf(w*2.75f), y+ floorf(h*0.25f), w,h) ,color,blend);

	Draw::drawFilledRect(Rect(x + floorf(w*1.5f) , y+ floorf(h*1.5f), w,h) ,color,blend);
	Draw::drawFilledRect(Rect(x + floorf(w*2.75f), y+ floorf(h*1.5f), w,h) ,color,blend);

	Draw::drawFilledRect(Rect(x + floorf(w*0.25f), y+ floorf(h*2.75f), w,h) ,color,blend);
	Draw::drawFilledRect(Rect(x + floorf(w*1.5f) , y+ floorf(h*2.75f), w,h) ,color,blend);
	Draw::drawFilledRect(Rect(x + floorf(w*2.75f), y+ floorf(h*2.75f), w,h) ,color,blend);
}//

//! TriangleAtCornerShape ---|> AbstractShape
void TriangleAtCornerShape::display(const Rect & rect,flag_t/* flags*/){
	std::vector<float> vertices;
	std::vector<uint32_t> colors;
	vertices.reserve(3*2);
	colors.reserve(3);

	colors.insert(colors.end(),3, color.getAsUInt());

	const Geometry::Vec2 corner = rect.getCorner(Geometry::rectCorner_t::XY);
	vertices.push_back(corner.x());				vertices.push_back(corner.y());
	vertices.push_back(corner.x());				vertices.push_back(corner.y()-size);
	vertices.push_back(corner.x()-size);		vertices.push_back(corner.y());

	Draw::drawTriangleFan(vertices,colors);
}

//! TriangleSelectorShape ---|> AbstractShape
void TriangleSelectorShape::display(const Rect & rect,flag_t flags){
	std::vector<float> vertices;
	std::vector<uint32_t> colors;
	vertices.reserve(3*2);
	colors.reserve(3);

	colors.insert(colors.end(),3, color.getAsUInt());

	const float sideLength = std::min(rect.getWidth(),rect.getHeight());
	const float halfSideLength = sideLength*0.5;
	const float h = std::sqrt( sideLength*sideLength - halfSideLength*halfSideLength );
	const float halfH = h*0.5;
	const Geometry::Vec2 center = rect.getCenter();
	if(flags&ACTIVE){
		vertices.push_back(center.x()-halfSideLength);		vertices.push_back(center.y()-halfH);
		vertices.push_back(center.x());						vertices.push_back(center.y()+halfH);
		vertices.push_back(center.x()+halfSideLength);		vertices.push_back(center.y()-halfH);
	}else{
		vertices.push_back(center.x()-halfH);				vertices.push_back(center.y()-halfSideLength);
		vertices.push_back(center.x()-halfH);				vertices.push_back(center.y()+halfSideLength);
		vertices.push_back(center.x()+halfH);				vertices.push_back(center.y());
	}
	Draw::drawTriangleFan(vertices,colors);
}

//! GridShape ---|> AbstractShape
void GridShape::display(const Rect & rect,flag_t /*flag*/){
	std::vector<float> vertices;
	std::vector<uint32_t> colors;

	// horizontal lines
	if(hDistance>0){
		int count=0;
		for(float pos=0;pos<=rect.getHeight();pos+=hDistance){
			colors.insert(colors.end(),2,(((count++ % (hNumMinors+1)) ==0) ? majorColor : minorColor).getAsUInt());
			vertices.push_back(0);						vertices.push_back(pos);
			vertices.push_back(rect.getWidth());		vertices.push_back(pos);
		}
	}
	// vertical lines
	if(vDistance>0){
		int count=0;
		for(float pos=0;pos<=rect.getWidth();pos+=vDistance){
			colors.insert(colors.end(),2,(((count++ % (vNumMinors+1)) ==0) ? majorColor : minorColor).getAsUInt());
			vertices.push_back(pos);					vertices.push_back(0);
			vertices.push_back(pos);					vertices.push_back(rect.getHeight());
		}
	}
	Draw::drawLines(vertices,colors);
}

//! CrossShape ---|> AbstractShape
void CrossShape::display(const Rect & rect,flag_t flags){
	Draw::drawCross(rect,flags&ACTIVE ? color2 : color1,lineWidth);
}

//! StraightLineShape ---|> LineShape
void StraightLineShape::displayLine(const std::vector<Geometry::Vec2> & points,flag_t){
	std::vector<float> vertices;
	vertices.reserve(points.size()*2);
	for(auto & point : points){
		vertices.push_back(static_cast<int>(point.x())+0.5f);
		vertices.push_back(static_cast<int>(point.y())+0.5f);
	}

	std::vector<uint32_t> colors;
	colors.insert(colors.end(),vertices.size(),color.getAsUInt());
	Draw::drawLine(vertices,colors,lineWidth,true);
}

//! SmoothConnectorShape ---|> LineShape
void SmoothConnectorShape::displayLine(const std::vector<Geometry::Vec2> & points,flag_t){
	std::vector<float> vertices;
	for(size_t i=1;i<points.size();++i){
		const Geometry::Vec2 p0(points[i-1]); // startPoint
		const Geometry::Vec2 p3(points[i]); // endPoint
		const float d = std::min(p0.distance(p3)*0.4,100.0);
		const Geometry::Vec2 p1(p0+Geometry::Vec2(d,0));
		const Geometry::Vec2 p2(p3-Geometry::Vec2(d,0));

		vertices.push_back(p0.x());
		vertices.push_back(p0.y());
		for(float t=0.0;t<=1.00;t += t<0.5 ? ((t*t)+0.1)*0.1 : (( (1.0-t)*(1.0-t))+0.1)*0.1 ){
			const Geometry::Vec2 p_t = Interpolation::cubicBezier(p0, p1, p2, p3, t);
			vertices.push_back(p_t.x());
			vertices.push_back(p_t.y());
		}
	}
	std::vector<uint32_t> colors;
	colors.insert(colors.end(),vertices.size(),color.getAsUInt());
	Draw::drawLine(vertices,colors,lineWidth,true);
}

}
<|endoftext|>


<commit_before>// Copyright (c) 2003 Daniel Wallin and Arvid Norberg

// 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 LUABIND_CONFIG_HPP_INCLUDED
#define LUABIND_CONFIG_HPP_INCLUDED

#include <boost/config.hpp>

#ifdef BOOST_MSVC
	#define LUABIND_ANONYMOUS_FIX static
#else
	#define LUABIND_ANONYMOUS_FIX
#endif

#if defined (BOOST_MSVC) && (BOOST_MSVC <= 1200)

#define for if (false) {} else for

#include <cstring>

namespace std
{
	using ::strlen;
	using ::strcmp;
	using ::type_info;
}

#endif

#if defined (BOOST_MSVC) && (BOOST_MSVC <= 1300)
	#define LUABIND_MSVC_TYPENAME
#else
	#define LUABIND_MSVC_TYPENAME typename
#endif

// the maximum number of arguments of functions that's
// registered. Must at least be 2
#ifndef LUABIND_MAX_ARITY
	#define LUABIND_MAX_ARITY 10
#elif LUABIND_MAX_ARITY <= 1
	#undef LUABIND_MAX_ARITY
	#define LUABIND_MAX_ARITY 2
#endif

// the maximum number of classes one class
// can derive from
// max bases must at least be 1
#ifndef LUABIND_MAX_BASES
	#define LUABIND_MAX_BASES 4
#elif LUABIND_MAX_BASES <= 0
	#undef LUABIND_MAX_BASES
	#define LUABIND_MAX_BASES 1
#endif

// LUABIND_NO_ERROR_CHECKING
// define this to remove all error checks
// this will improve performance and memory
// footprint.
// if it is defined matchers will only be called on
// overloaded functions, functions that's
// not overloaded will be called directly. The
// parameters on the lua stack are assumed
// to match those of the function.
// exceptions will still be catched when there's
// no error checking.

// LUABIND_NOT_THREADSAFE
// this define will make luabind non-thread safe. That is,
// it will rely on a static variable. You can still have
// multiple lua states and use coroutines, but only
// one of your real threads may run lua code.

// LUABIND_NO_EXCEPTIONS
// this define will disable all usage of try, catch and throw in
// luabind. This will in many cases disable runtime-errors, such
// as invalid casts, when calling lua-functions that fails or
// returns values that cannot be converted by the given policy.
// Luabind requires that no function called directly or indirectly
// by luabind throws an exception (throwing exceptions through
// C code has undefined behavior, lua is written in C).

#ifdef LUABIND_DYNAMIC_LINK
# ifdef BOOST_WINDOWS
#  ifdef LUABIND_BUILDING
#   define LUABIND_API __declspec(dllexport)
#  else
#   define LUABIND_API __declspec(dllimport)
#  endif
# else
#  if defined(_GNUC_) && _GNUC_ >=4
#   define LUABIND_API __attribute__ ((visibility("default")))
#  endif
# endif
#endif

#ifndef LUABIND_API
# define LUABIND_API
#endif

namespace luabind {

LUABIND_API void disable_super_deprecation();

} // namespace luabind

#endif // LUABIND_CONFIG_HPP_INCLUDED

<commit_msg>Don't homebrew our own import/export macro detection - let boost do it.<commit_after>// Copyright (c) 2003 Daniel Wallin and Arvid Norberg

// 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 LUABIND_CONFIG_HPP_INCLUDED
#define LUABIND_CONFIG_HPP_INCLUDED

#include <boost/config.hpp>

#ifdef BOOST_MSVC
	#define LUABIND_ANONYMOUS_FIX static
#else
	#define LUABIND_ANONYMOUS_FIX
#endif

#if defined (BOOST_MSVC) && (BOOST_MSVC <= 1200)

#define for if (false) {} else for

#include <cstring>

namespace std
{
	using ::strlen;
	using ::strcmp;
	using ::type_info;
}

#endif

#if defined (BOOST_MSVC) && (BOOST_MSVC <= 1300)
	#define LUABIND_MSVC_TYPENAME
#else
	#define LUABIND_MSVC_TYPENAME typename
#endif

// the maximum number of arguments of functions that's
// registered. Must at least be 2
#ifndef LUABIND_MAX_ARITY
	#define LUABIND_MAX_ARITY 10
#elif LUABIND_MAX_ARITY <= 1
	#undef LUABIND_MAX_ARITY
	#define LUABIND_MAX_ARITY 2
#endif

// the maximum number of classes one class
// can derive from
// max bases must at least be 1
#ifndef LUABIND_MAX_BASES
	#define LUABIND_MAX_BASES 4
#elif LUABIND_MAX_BASES <= 0
	#undef LUABIND_MAX_BASES
	#define LUABIND_MAX_BASES 1
#endif

// LUABIND_NO_ERROR_CHECKING
// define this to remove all error checks
// this will improve performance and memory
// footprint.
// if it is defined matchers will only be called on
// overloaded functions, functions that's
// not overloaded will be called directly. The
// parameters on the lua stack are assumed
// to match those of the function.
// exceptions will still be catched when there's
// no error checking.

// LUABIND_NOT_THREADSAFE
// this define will make luabind non-thread safe. That is,
// it will rely on a static variable. You can still have
// multiple lua states and use coroutines, but only
// one of your real threads may run lua code.

// LUABIND_NO_EXCEPTIONS
// this define will disable all usage of try, catch and throw in
// luabind. This will in many cases disable runtime-errors, such
// as invalid casts, when calling lua-functions that fails or
// returns values that cannot be converted by the given policy.
// Luabind requires that no function called directly or indirectly
// by luabind throws an exception (throwing exceptions through
// C code has undefined behavior, lua is written in C).

#ifdef LUABIND_DYNAMIC_LINK
# ifdef LUABIND_BUILDING
#  define LUABIND_API BOOST_SYMBOL_EXPORT
# else
#  define LUABIND_API BOOST_SYMBOL_IMPORT
# endif
#endif

#ifndef LUABIND_API
# define LUABIND_API
#endif

namespace luabind {

LUABIND_API void disable_super_deprecation();

} // namespace luabind

#endif // LUABIND_CONFIG_HPP_INCLUDED

<|endoftext|>


<commit_before>#include "opencv2/core/utility.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"

#include <iostream>

using namespace cv;
using namespace std;

const auto RED = cv::Scalar(0,0,255);
const auto PINK = cv::Scalar(230,130,255);
const auto BLUE = cv::Scalar(255,0,0);
const auto LIGHTBLUE = cv::Scalar(255,255,160);
const auto GREEN = cv::Scalar(0,255,0);
const auto IMAGE_SCALE = .25;

class MyData
{
public:
  const cv::Mat original_image;
  cv::Mat image;
  MyData( auto _image ) : original_image(_image)
  {
    original_image.copyTo(image);
  }
  void reset() { original_image.copyTo(image); };
  void update(auto _newImage) { _newImage.copyTo(image); };

};

class MyWindow
{
protected:
  const string winName;
  MyData d;

public:
  /* enum{ NOT_SET = 0, IN_PROCESS = 1, SET = 2 }; */
  MyWindow( auto _winName, auto _image ):
    winName( _winName ), d( _image )
  {
    cv::namedWindow( winName, WINDOW_AUTOSIZE );
  }
  virtual ~MyWindow();
  virtual void showImage();
  virtual void reset();
};

MyWindow::~MyWindow()
{
  cv::destroyWindow( winName );
}

void MyWindow::reset()
{
  d.reset();
  showImage();
}

void MyWindow::showImage()
{
  cv::imshow( winName, d.image );
}

class MyOperationWindow : public MyWindow
{
protected:
  /* virtual void setControls(){}; */
  virtual string getDescription() {}
public:
  MyOperationWindow( auto _winName, auto _image) : MyWindow( _winName, _image ) {}
  void apply( MyData& _d, std::vector<string>& _process_pile )
  {
    _d.update(d.image);
    _process_pile.push_back(getDescription());
  }
};

class MyThreshold : public MyOperationWindow
{
  int th;
public:
  MyThreshold( auto _winName, auto _image)
    : MyOperationWindow( _winName, _image ), th(125) { setControls(); };
  MyThreshold( auto _winName, auto _image, auto _th )
    : MyOperationWindow( _winName, _image ), th(_th) { setControls(); };
  static void thresholdCallback( int _th, void* ptr);
private:
  string getDescription() override;
  void setControls(); //
  void thresholdImage();
  void _thresholdCallback( int _th );
};

void MyThreshold::setControls() //
{
  const std::string bar_name = winName + "_thBar";
  cv::createTrackbar( bar_name, winName, &th, 255, MyThreshold::thresholdCallback );
}

void MyThreshold::thresholdCallback( int _th, void* ptr)
{
  MyThreshold* that = (MyThreshold*) (ptr);
  that->_thresholdCallback(_th);
}

void MyThreshold::_thresholdCallback( int _th )
{
  th = _th;
  thresholdImage();
  showImage();
}

string MyThreshold::getDescription()
{
  return "th " + std::to_string(th);
}

void MyThreshold::thresholdImage()
{
  enum ThresholdType {BINARY, BINARY_INVERTED, THRESHOLD_TRUNCATED,
                      THRESHOLD_TO_ZERO, THRESHOLD_TO_ZERO_INVERTED };
  ThresholdType const threshold_type = BINARY;
  int const max_BINARY_value = 255;

  threshold( d.original_image, d.image, th, max_BINARY_value, threshold_type );
}

class MyApp : public MyWindow
{
  vector<string> process;
  // std::unique_ptr<MyOperationWindow> current_operation;
  // MyOperationWindow* current_operation;
  string* current_operation;
public:
  MyApp( auto _winName, auto _image);

  void showImage();
  char option(auto _option);
  ~MyApp();
};

MyApp::~MyApp()
{
  if (current_operation != nullptr)
    delete(current_operation);
  cv::destroyWindow( winName );
}

static void help()
{
  cout << "L (or a) - list image transformations\n"
       << "R (or s) - restore original image\n"
       << "t (or d) - activate threshold window\n"
       << "r (or f) - reset the operation window\n"
       << "(enter) (or g) - accept changes and kill the operation window\n"
       << "(backspace) (or h)- ignore changes and kill the operation window\n"
       << endl;
}

MyApp::MyApp(auto _winName,auto  _image) :
  MyWindow( _winName, _image ),
  current_operation(nullptr) {}

char MyApp::option( auto _option )
{
  switch(_option)
    {
    case 't': case 'd':
      /// create the threshold window
      if (current_operation == nullptr)
        current_operation = new string("Hi");
        //current_operation = new MyThreshold("theshold", d.image);
      break;
    case 'R': case 's':
      /// reset the whole application
      reset();
    case 'r': case 'f':
      /// reset the threshold window
      if (current_operation != nullptr)
        std::cout << "option r says ..." << current_operation << std::endl;
        // current_operation->reset();
      break;
     }
  return _option;
}

const char* keys =
{
  "{help h||}{@image|../../testdata/A/A05_38.bmp|input image file}"
};

int main( int argc, const char** argv )
{
  cv::CommandLineParser parser(argc, argv, keys);
  if (parser.has("help"))
    {
      help();
      return 0;
    }
  std::string inputImage = parser.get<string>(0);

  // Load the source image. HighGUI use.
  cv::Mat image = imread( inputImage, CV_LOAD_IMAGE_GRAYSCALE );
  if(image.empty())
    {
      std::cerr << "Cannot read image file: " << inputImage << std::endl;
      return -1;
    }

  // TODO: check size and reduce it only if needed
  cv::resize(image, image, cv::Size(), IMAGE_SCALE, IMAGE_SCALE);
  help();

  /// Create the GUI
  std::string winName = "main window";
  MyApp appHandle = MyApp(winName, image);

  /// Loop until the user kills the program
  const auto ESC_KEY = '\x1b';
  while ( appHandle.option((char) waitKey(0)) != ESC_KEY )
    {
      /* until ESC */
    }
  std::cout << "Exit" << std::endl;
  return 0;
}

<commit_msg>bug found virtual method was not implemented<commit_after>#include "opencv2/core/utility.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"

#include <iostream>

using namespace cv;
using namespace std;

const auto RED = cv::Scalar(0,0,255);
const auto PINK = cv::Scalar(230,130,255);
const auto BLUE = cv::Scalar(255,0,0);
const auto LIGHTBLUE = cv::Scalar(255,255,160);
const auto GREEN = cv::Scalar(0,255,0);
const auto IMAGE_SCALE = .25;

class MyData
{
public:
  const cv::Mat& original_image;
  cv::Mat image;
  MyData(const cv::Mat&  _image ) : original_image(_image)
  {
    original_image.copyTo(image);
  }
  void reset() { original_image.copyTo(image); };
  void update(auto _newImage) { _newImage.copyTo(image); };

};

class MyWindow
{
protected:
  const string winName;
  MyData d;

public:
  /* enum{ NOT_SET = 0, IN_PROCESS = 1, SET = 2 }; */
  MyWindow( const string&  _winName, const cv::Mat&  _image ):
    winName( _winName ), d( _image )
  {
    cv::namedWindow( winName, WINDOW_AUTOSIZE );
  }
  virtual ~MyWindow();
  virtual void showImage();
  virtual void reset();
};

MyWindow::~MyWindow()
{
  cv::destroyWindow( winName );
}

void MyWindow::reset()
{
  d.reset();
  showImage();
}

void MyWindow::showImage()
{
  cv::imshow( winName, d.image );
}

class MyOperationWindow : public MyWindow
{
protected:
  /* virtual void setControls(){}; */
  virtual string getDescription() {}
public:
  MyOperationWindow( auto _winName, auto _image) : MyWindow( _winName, _image ) {}
  void apply( MyData& _d, std::vector<string>& _process_pile )
  {
    _d.update(d.image);
    _process_pile.push_back(getDescription());
  }
};

class MyThreshold : public MyOperationWindow
{
  int th;
public:
  MyThreshold( auto _winName, auto _image)
    : MyOperationWindow( _winName, _image ), th(125) { setControls(); }
  MyThreshold( auto _winName, auto _image, auto _th )
    : MyOperationWindow( _winName, _image ), th(_th) { setControls(); }
  static void thresholdCallback( int _th, void* ptr);
private:
  string getDescription() override;
  void setControls(); //
  void thresholdImage();
  void _thresholdCallback( int _th );
};

void MyThreshold::setControls() //
{
  const std::string bar_name = winName + "_thBar";
  cv::createTrackbar( bar_name, winName, &th, 255, MyThreshold::thresholdCallback );
}

void MyThreshold::thresholdCallback( int _th, void* ptr)
{
  MyThreshold* that = (MyThreshold*) (ptr);
  that->_thresholdCallback(_th);
}

void MyThreshold::_thresholdCallback( int _th )
{
  th = _th;
  thresholdImage();
  showImage();
}

string MyThreshold::getDescription()
{
  return "th " + std::to_string(th);
}

void MyThreshold::thresholdImage()
{
  enum ThresholdType {BINARY, BINARY_INVERTED, THRESHOLD_TRUNCATED,
                      THRESHOLD_TO_ZERO, THRESHOLD_TO_ZERO_INVERTED };
  ThresholdType const threshold_type = BINARY;
  int const max_BINARY_value = 255;

  threshold( d.original_image, d.image, th, max_BINARY_value, threshold_type );
}

class MyApp : public MyWindow
{
  vector<string> process;
  // std::unique_ptr<MyOperationWindow> current_operation;
  // MyOperationWindow* current_operation;
  string* current_operation;
public:
  MyApp(const std::string& _winName, const cv::Mat&  _image);

  //void showImage() {}
  char option(char _option);
  ~MyApp();
};

MyApp::~MyApp()
{
  if (current_operation != nullptr)
    delete(current_operation);
  //cv::destroyWindow( winName );
}

MyApp::MyApp(const string &_winName, const Mat &_image) :
  MyWindow( _winName, _image ),
  current_operation(nullptr) {}

char MyApp::option( char _option )
{
  switch(_option)
    {
    case 't': case 'd':
      /// create the threshold window
      if (current_operation == nullptr)
        current_operation = new string("Hi");
        //current_operation = new MyThreshold("theshold", d.image);
      break;
    case 'R': case 's':
      /// reset the whole application
      //reset();
    case 'r': case 'f':
      /// reset the threshold window
      if (current_operation != nullptr)
        std::cout << "option r says ..." << current_operation << std::endl;
        // current_operation->reset();
      break;
     }
  return _option;
}

const char* keys =
{
  "{help h||}{@image|../../testdata/A/A05_38.bmp|input image file}"
};

static void help();

int main( int argc, const char** argv )
{
  cv::CommandLineParser parser(argc, argv, keys);
  if (parser.has("help"))
    {
      help();
      return 0;
    }
  std::string inputImage = parser.get<string>(0);

  // Load the source image. HighGUI use.
  cv::Mat image = imread( inputImage, CV_LOAD_IMAGE_GRAYSCALE );
  if(image.empty())
    {
      std::cerr << "Cannot read image file: " << inputImage << std::endl;
      return -1;
    }

  // TODO: check size and reduce it only if needed
  cv::resize(image, image, cv::Size(), IMAGE_SCALE, IMAGE_SCALE);
  help();

  /// Create the GUI
  std::string winName = "main window";
  MyApp appHandle = MyApp(winName, image);

  /// Loop until the user kills the program
  const auto ESC_KEY = '\x1b';
  while ( appHandle.option((char) waitKey(0)) != ESC_KEY )
    {
      /* until ESC */
    }
  std::cout << "Exit" << std::endl;
  return 0;
}

static void help()
{
  cout << "L (or a) - list image transformations\n"
       << "R (or s) - restore original image\n"
       << "t (or d) - activate threshold window\n"
       << "r (or f) - reset the operation window\n"
       << "(enter) (or g) - accept changes and kill the operation window\n"
       << "(backspace) (or h)- ignore changes and kill the operation window\n"
       << endl;
}
<|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS dba30 (1.18.6); FILE MERGED 2006/07/19 10:25:04 fs 1.18.6.4: RESYNC: (1.20-1.21); FILE MERGED 2006/04/18 13:10:17 oj 1.18.6.3: RESYNC: (1.19-1.20); FILE MERGED 2005/09/28 12:11:44 fs 1.18.6.2: RESYNC: (1.18-1.19); FILE MERGED 2005/04/06 07:10:24 fs 1.18.6.1: #i46768# some assertions on the type of connection properties<commit_after><|endoftext|>