<commit_before>/* This file is part of Ingen.
 * Copyright 2007-2011 David Robillard <http://drobilla.net>
 *
 * Ingen 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.
 *
 * Ingen 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 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 St, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include <cassert>
#include <sys/mman.h>
#include <unistd.h>
#include "raul/log.hpp"
#include "raul/Deletable.hpp"
#include "raul/Maid.hpp"
#include "raul/SharedPtr.hpp"
#include "lv2/lv2plug.in/ns/ext/uri-map/uri-map.h"
#include "ingen/EventType.hpp"
#include "events/CreatePatch.hpp"
#include "events/CreatePort.hpp"
#include "shared/World.hpp"
#include "shared/LV2Features.hpp"
#include "shared/LV2URIMap.hpp"
#include "shared/Store.hpp"
#include "BufferFactory.hpp"
#include "ClientBroadcaster.hpp"
#include "ControlBindings.hpp"
#include "Driver.hpp"
#include "Engine.hpp"
#include "EngineStore.hpp"
#include "Event.hpp"
#include "EventSource.hpp"
#include "MessageContext.hpp"
#include "NodeFactory.hpp"
#include "PatchImpl.hpp"
#include "PostProcessor.hpp"
#include "ProcessContext.hpp"
#include "QueuedEngineInterface.hpp"
#include "ThreadManager.hpp"

using namespace std;
using namespace Raul;

namespace Ingen {
namespace Server {

bool ThreadManager::single_threaded = true;

Engine::Engine(Ingen::Shared::World* a_world)
	: _world(a_world)
	, _broadcaster(new ClientBroadcaster())
	, _buffer_factory(new BufferFactory(*this, a_world->uris()))
	, _control_bindings(new ControlBindings(*this))
	, _maid(new Raul::Maid(event_queue_size()))
	, _message_context(new MessageContext(*this))
	, _node_factory(new NodeFactory(a_world))
	, _post_processor(new PostProcessor(*this, event_queue_size()))
{
	if (a_world->store()) {
		assert(PtrCast<EngineStore>(a_world->store()));
	} else {
		a_world->set_store(SharedPtr<Ingen::Shared::Store>(new EngineStore()));
	}
}

Engine::~Engine()
{
	deactivate();

	SharedPtr<EngineStore> store = engine_store();
	if (store)
		for (EngineStore::iterator i = store->begin(); i != store->end(); ++i)
			if ( ! PtrCast<GraphObjectImpl>(i->second)->parent() )
				i->second.reset();

	delete _maid;
	delete _post_processor;
	delete _node_factory;
	delete _broadcaster;

	munlockall();
}

SharedPtr<EngineStore>
Engine::engine_store() const
{
	 return PtrCast<EngineStore>(_world->store());
}

size_t
Engine::event_queue_size() const
{
	return world()->conf()->option("queue-size").get_int32();
}

void
Engine::quit()
{
	_quit_flag = true;
}

bool
Engine::main_iteration()
{
	_post_processor->process();
	_maid->cleanup();
	return !_quit_flag;
}

void
Engine::add_event_source(SharedPtr<EventSource> source)
{
	_event_sources.insert(source);
}

void
Engine::set_driver(SharedPtr<Driver> driver)
{
	_driver = driver;
}

static void
execute_and_delete_event(ProcessContext& context, QueuedEvent* ev)
{
	ev->pre_process();
	ev->execute(context);
	ev->post_process();
	delete ev;
}

bool
Engine::activate()
{
	assert(_driver);
	ThreadManager::single_threaded = true;

	_buffer_factory->set_block_length(_driver->block_length());

	_message_context->Thread::start();

	const Ingen::Shared::LV2URIMap& uris = *world()->uris().get();

	// Create root patch
	PatchImpl* root_patch = _driver->root_patch();
	if (!root_patch) {
		root_patch = new PatchImpl(*this, "root", 1, NULL, _driver->sample_rate(), 1);
		root_patch->set_property(uris.rdf_type,
		                         Resource::Property(uris.ingen_Patch, Resource::INTERNAL));
		root_patch->set_property(uris.ingen_polyphony,
		                         Resource::Property(Raul::Atom(int32_t(1)),
		                                            Resource::INTERNAL));
		root_patch->activate(*_buffer_factory);
		_world->store()->add(root_patch);
		root_patch->compiled_patch(root_patch->compile());
		_driver->set_root_patch(root_patch);

		ProcessContext context(*this);

		Resource::Properties control_properties;
		control_properties.insert(make_pair(uris.lv2_name, "Control"));
		control_properties.insert(make_pair(uris.rdf_type, uris.ev_EventPort));

		// Add control input
		Resource::Properties in_properties(control_properties);
		in_properties.insert(make_pair(uris.rdf_type, uris.lv2_InputPort));
		in_properties.insert(make_pair(uris.lv2_index, 0));
		in_properties.insert(make_pair(uris.ingenui_canvas_x,
		                               Resource::Property(32.0f, Resource::EXTERNAL)));
		in_properties.insert(make_pair(uris.ingenui_canvas_y,
		                               Resource::Property(32.0f, Resource::EXTERNAL)));

		execute_and_delete_event(context, new Events::CreatePort(
				*this, SharedPtr<Request>(), 0,
				"/control_in", uris.ev_EventPort, false, in_properties));

		// Add control out
		Resource::Properties out_properties(control_properties);
		out_properties.insert(make_pair(uris.rdf_type, uris.lv2_OutputPort));
		out_properties.insert(make_pair(uris.lv2_index, 1));
		out_properties.insert(make_pair(uris.ingenui_canvas_x,
		                                Resource::Property(128.0f, Resource::EXTERNAL)));
		out_properties.insert(make_pair(uris.ingenui_canvas_y,
		                                Resource::Property(32.0f, Resource::EXTERNAL)));

		execute_and_delete_event(context, new Events::CreatePort(
				*this, SharedPtr<Request>(), 0,
				"/control_out", uris.ev_EventPort, true, out_properties));
	}

	_driver->activate();
	root_patch->enable();

	ThreadManager::single_threaded = false;

	return true;
}

void
Engine::deactivate()
{
	_driver->deactivate();
	_driver->root_patch()->deactivate();

	ThreadManager::single_threaded = true;
}

void
Engine::process_events(ProcessContext& context)
{
	ThreadManager::assert_thread(THREAD_PROCESS);

	for (EventSources::iterator i = _event_sources.begin(); i != _event_sources.end(); ++i)
		(*i)->process(*_post_processor, context);
}

} // namespace Server
} // namespace Ingen
<commit_msg>Fix immediate quit due to uninitialised quit flag (fix ticket #677).<commit_after>/* This file is part of Ingen.
 * Copyright 2007-2011 David Robillard <http://drobilla.net>
 *
 * Ingen 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.
 *
 * Ingen 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 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 St, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include <cassert>
#include <sys/mman.h>
#include <unistd.h>
#include "raul/log.hpp"
#include "raul/Deletable.hpp"
#include "raul/Maid.hpp"
#include "raul/SharedPtr.hpp"
#include "lv2/lv2plug.in/ns/ext/uri-map/uri-map.h"
#include "ingen/EventType.hpp"
#include "events/CreatePatch.hpp"
#include "events/CreatePort.hpp"
#include "shared/World.hpp"
#include "shared/LV2Features.hpp"
#include "shared/LV2URIMap.hpp"
#include "shared/Store.hpp"
#include "BufferFactory.hpp"
#include "ClientBroadcaster.hpp"
#include "ControlBindings.hpp"
#include "Driver.hpp"
#include "Engine.hpp"
#include "EngineStore.hpp"
#include "Event.hpp"
#include "EventSource.hpp"
#include "MessageContext.hpp"
#include "NodeFactory.hpp"
#include "PatchImpl.hpp"
#include "PostProcessor.hpp"
#include "ProcessContext.hpp"
#include "QueuedEngineInterface.hpp"
#include "ThreadManager.hpp"

using namespace std;
using namespace Raul;

namespace Ingen {
namespace Server {

bool ThreadManager::single_threaded = true;

Engine::Engine(Ingen::Shared::World* a_world)
	: _world(a_world)
	, _broadcaster(new ClientBroadcaster())
	, _buffer_factory(new BufferFactory(*this, a_world->uris()))
	, _control_bindings(new ControlBindings(*this))
	, _maid(new Raul::Maid(event_queue_size()))
	, _message_context(new MessageContext(*this))
	, _node_factory(new NodeFactory(a_world))
	, _post_processor(new PostProcessor(*this, event_queue_size()))
	, _quit_flag(false)
{
	if (a_world->store()) {
		assert(PtrCast<EngineStore>(a_world->store()));
	} else {
		a_world->set_store(SharedPtr<Ingen::Shared::Store>(new EngineStore()));
	}
}

Engine::~Engine()
{
	deactivate();

	SharedPtr<EngineStore> store = engine_store();
	if (store)
		for (EngineStore::iterator i = store->begin(); i != store->end(); ++i)
			if ( ! PtrCast<GraphObjectImpl>(i->second)->parent() )
				i->second.reset();

	delete _maid;
	delete _post_processor;
	delete _node_factory;
	delete _broadcaster;

	munlockall();
}

SharedPtr<EngineStore>
Engine::engine_store() const
{
	 return PtrCast<EngineStore>(_world->store());
}

size_t
Engine::event_queue_size() const
{
	return world()->conf()->option("queue-size").get_int32();
}

void
Engine::quit()
{
	_quit_flag = true;
}

bool
Engine::main_iteration()
{
	_post_processor->process();
	_maid->cleanup();
	return !_quit_flag;
}

void
Engine::add_event_source(SharedPtr<EventSource> source)
{
	_event_sources.insert(source);
}

void
Engine::set_driver(SharedPtr<Driver> driver)
{
	_driver = driver;
}

static void
execute_and_delete_event(ProcessContext& context, QueuedEvent* ev)
{
	ev->pre_process();
	ev->execute(context);
	ev->post_process();
	delete ev;
}

bool
Engine::activate()
{
	assert(_driver);
	ThreadManager::single_threaded = true;

	_buffer_factory->set_block_length(_driver->block_length());

	_message_context->Thread::start();

	const Ingen::Shared::LV2URIMap& uris = *world()->uris().get();

	// Create root patch
	PatchImpl* root_patch = _driver->root_patch();
	if (!root_patch) {
		root_patch = new PatchImpl(*this, "root", 1, NULL, _driver->sample_rate(), 1);
		root_patch->set_property(uris.rdf_type,
		                         Resource::Property(uris.ingen_Patch, Resource::INTERNAL));
		root_patch->set_property(uris.ingen_polyphony,
		                         Resource::Property(Raul::Atom(int32_t(1)),
		                                            Resource::INTERNAL));
		root_patch->activate(*_buffer_factory);
		_world->store()->add(root_patch);
		root_patch->compiled_patch(root_patch->compile());
		_driver->set_root_patch(root_patch);

		ProcessContext context(*this);

		Resource::Properties control_properties;
		control_properties.insert(make_pair(uris.lv2_name, "Control"));
		control_properties.insert(make_pair(uris.rdf_type, uris.ev_EventPort));

		// Add control input
		Resource::Properties in_properties(control_properties);
		in_properties.insert(make_pair(uris.rdf_type, uris.lv2_InputPort));
		in_properties.insert(make_pair(uris.lv2_index, 0));
		in_properties.insert(make_pair(uris.ingenui_canvas_x,
		                               Resource::Property(32.0f, Resource::EXTERNAL)));
		in_properties.insert(make_pair(uris.ingenui_canvas_y,
		                               Resource::Property(32.0f, Resource::EXTERNAL)));

		execute_and_delete_event(context, new Events::CreatePort(
				*this, SharedPtr<Request>(), 0,
				"/control_in", uris.ev_EventPort, false, in_properties));

		// Add control out
		Resource::Properties out_properties(control_properties);
		out_properties.insert(make_pair(uris.rdf_type, uris.lv2_OutputPort));
		out_properties.insert(make_pair(uris.lv2_index, 1));
		out_properties.insert(make_pair(uris.ingenui_canvas_x,
		                                Resource::Property(128.0f, Resource::EXTERNAL)));
		out_properties.insert(make_pair(uris.ingenui_canvas_y,
		                                Resource::Property(32.0f, Resource::EXTERNAL)));

		execute_and_delete_event(context, new Events::CreatePort(
				*this, SharedPtr<Request>(), 0,
				"/control_out", uris.ev_EventPort, true, out_properties));
	}

	_driver->activate();
	root_patch->enable();

	ThreadManager::single_threaded = false;

	return true;
}

void
Engine::deactivate()
{
	_driver->deactivate();
	_driver->root_patch()->deactivate();

	ThreadManager::single_threaded = true;
}

void
Engine::process_events(ProcessContext& context)
{
	ThreadManager::assert_thread(THREAD_PROCESS);

	for (EventSources::iterator i = _event_sources.begin(); i != _event_sources.end(); ++i)
		(*i)->process(*_post_processor, context);
}

} // namespace Server
} // namespace Ingen
<|endoftext|>


<commit_before>#include "server/control.hpp"
#include "arch/spinlock.hpp"

#include "logger.hpp"
#include "errors.hpp"

control_map_t& get_control_map() {
    /* Getter function so that we can be sure that control_list is initialized before it is needed,
    as advised by the C++ FAQ. Otherwise, a control_t might be initialized before the control list
    was initialized. */

    static control_map_t control_map;
    return control_map;
}

spinlock_t& get_control_lock() {
    /* To avoid static initialization fiasco */

    static spinlock_t lock;
    return lock;
}

std::string control_t::exec(int argc, char **argv) {
    if (argc == 0) {
        return "You must provide a command name. Type \"rethinkdb help\" for a list of available "
            "commands.\r\n";
    }
    std::string command = argv[0];

    control_map_t::iterator it = get_control_map().find(command);
    if (it == get_control_map().end()) {
        return "There is no command called \"" + command + "\". Type \"rethinkdb help\" for a "
            "list of available commands.\r\n";
    } else {
        return (*it).second->call(argc, argv);
    }
}

control_t::control_t(const std::string& _key, const std::string& _help_string, bool _internal)
    : key(_key), help_string(_help_string), internal(_internal)
{
    rassert(key.size() > 0);
    spinlock_acq_t control_acq(&get_control_lock());
    rassert(get_control_map().find(key) == get_control_map().end());
    get_control_map()[key] = this;
}

control_t::~control_t() {
    spinlock_acq_t control_acq(&get_control_lock());
    control_map_t &map = get_control_map();
    control_map_t::iterator it = map.find(key);
    rassert(it != map.end());
    map.erase(it);
}

/* Control that displays a list of controls */
struct help_control_t : public control_t
{
    help_control_t() : control_t("help", "Display this help message (use \"rethinkdb help internal\" to show internal commands).") { }
    std::string call(int argc, char **argv) {

        bool show_internal = argc == 2 && argv[1] == std::string("internal");

        spinlock_acq_t control_acq(&get_control_lock());
        std::string res = "The following \"rethinkdb\" commands are available:\r\n";
        for (control_map_t::iterator it = get_control_map().begin(); it != get_control_map().end(); it++) {
            if (it->second->internal != show_internal) continue;
            res += it->first + ": " + it->second->help_string + "\r\n";
        }
        return res;
    }
} help_control;

/* Example of how to add a control */
struct hi_control_t : public control_t
{
private:
    int counter;
public:
    hi_control_t() :
        control_t("hi", "Say 'hi' to the server, and it will say 'hi' back.", true),
        counter(0)
        { }
    std::string call(UNUSED int argc, UNUSED char **argv) {
        counter++;
        if (counter < 3)
            return "Salutations, user.\r\n";
        else if (counter < 4)
            return "Say hi again, I dare you.\r\n";
        else
            return "Base QPS decreased by 100,000.\r\n";
    }
} hi_control;
<commit_msg>Friendlier help message.<commit_after>#include "server/control.hpp"
#include "arch/spinlock.hpp"

#include "utils2.hpp"
#include "logger.hpp"
#include "errors.hpp"

control_map_t& get_control_map() {
    /* Getter function so that we can be sure that control_list is initialized before it is needed,
    as advised by the C++ FAQ. Otherwise, a control_t might be initialized before the control list
    was initialized. */

    static control_map_t control_map;
    return control_map;
}

spinlock_t& get_control_lock() {
    /* To avoid static initialization fiasco */

    static spinlock_t lock;
    return lock;
}

std::string control_t::exec(int argc, char **argv) {
    if (argc == 0) {
        return "You must provide a command name. Type \"rethinkdb help\" for a list of available "
            "commands.\r\n";
    }
    std::string command = argv[0];

    control_map_t::iterator it = get_control_map().find(command);
    if (it == get_control_map().end()) {
        return "There is no command called \"" + command + "\". Type \"rethinkdb help\" for a "
            "list of available commands.\r\n";
    } else {
        return (*it).second->call(argc, argv);
    }
}

control_t::control_t(const std::string& _key, const std::string& _help_string, bool _internal)
    : key(_key), help_string(_help_string), internal(_internal)
{
    rassert(key.size() > 0);
    spinlock_acq_t control_acq(&get_control_lock());
    rassert(get_control_map().find(key) == get_control_map().end());
    get_control_map()[key] = this;
}

control_t::~control_t() {
    spinlock_acq_t control_acq(&get_control_lock());
    control_map_t &map = get_control_map();
    control_map_t::iterator it = map.find(key);
    rassert(it != map.end());
    map.erase(it);
}

/* Control that displays a list of controls */
struct help_control_t : public control_t
{
    help_control_t() : control_t("help", "Display this help message (use \"rethinkdb help internal\" to show internal commands).") { }
    std::string call(int argc, char **argv) {
        bool show_internal = argc == 2 && argv[1] == std::string("internal");

        spinlock_acq_t control_acq(&get_control_lock());
        std::string res = strprintf("The following %scommands are available:\r\n", show_internal ? "internal " : "");
        for (control_map_t::iterator it = get_control_map().begin(); it != get_control_map().end(); it++) {
            if (it->second->internal != show_internal) continue;
            res += "rethinkdb " + it->first + ": " + it->second->help_string + "\r\n";
        }
        return res;
    }
} help_control;

/* Example of how to add a control */
struct hi_control_t : public control_t
{
private:
    int counter;
public:
    hi_control_t() :
        control_t("hi", "Say 'hi' to the server, and it will say 'hi' back.", true),
        counter(0)
        { }
    std::string call(UNUSED int argc, UNUSED char **argv) {
        counter++;
        if (counter < 3)
            return "Salutations, user.\r\n";
        else if (counter < 4)
            return "Say hi again, I dare you.\r\n";
        else
            return "Base QPS decreased by 100,000.\r\n";
    }
} hi_control;
<|endoftext|>


<commit_before>#include "solver_factory.h"

#include "OsiClpSolverInterface.hpp"
#include "OsiCbcSolverInterface.hpp"

#include "error.h"

namespace cyclus {

// 10800 s = 3 hrs * 60 min/hr * 60 s/min
SolverFactory::SolverFactory() : t_("cbc"), tmax_(10800) { }
SolverFactory::SolverFactory(std::string t) : t_(t), tmax_(10800) { }
SolverFactory::SolverFactory(std::string t, double tmax)
    : t_(t),
      tmax_(tmax) { }

OsiSolverInterface* SolverFactory::get() {
  if (t_ == "clp") {
    OsiClpSolverInterface* s = new OsiClpSolverInterface();
    s->getModelPtr()->setMaximumSeconds(tmax_);
    return s;
  } else if (t_ == "cbc") {
    OsiCbcSolverInterface* s = new OsiCbcSolverInterface();
    s->setMaximumSeconds(tmax_);
    return s;
  } else {
    throw ValueError("invalid SolverFactory type '" + t_ + "'");
  }
}

void SolveProg(OsiSolverInterface* si) {
  si->initialSolve();
  if (HasInt(si)) {
    si->branchAndBound();
  }
}

bool HasInt(OsiSolverInterface* si) {
  int i = 0;
  for (i = 0; i != si->getNumCols(); i++) {
    if (si->isInteger(i)) {
      return true;
    }
  }
  return false;
}

}  // namespace cyclus
<commit_msg>now solve fully linear problems with the primal method<commit_after>#include "solver_factory.h"

#include "OsiClpSolverInterface.hpp"
#include "OsiCbcSolverInterface.hpp"

#include "error.h"

namespace cyclus {

// 10800 s = 3 hrs * 60 min/hr * 60 s/min
SolverFactory::SolverFactory() : t_("cbc"), tmax_(10800) { }
SolverFactory::SolverFactory(std::string t) : t_(t), tmax_(10800) { }
SolverFactory::SolverFactory(std::string t, double tmax)
    : t_(t),
      tmax_(tmax) { }

OsiSolverInterface* SolverFactory::get() {
  if (t_ == "clp") {
    OsiClpSolverInterface* s = new OsiClpSolverInterface();
    s->getModelPtr()->setMaximumSeconds(tmax_);
    return s;
  } else if (t_ == "cbc") {
    OsiCbcSolverInterface* s = new OsiCbcSolverInterface();
    s->setMaximumSeconds(tmax_);
    return s;
  } else {
    throw ValueError("invalid SolverFactory type '" + t_ + "'");
  }
}

void SolveProg(OsiSolverInterface* si) {
  si->initialSolve();
  if (HasInt(si)) {
    si->branchAndBound();
  } else {
    OsiClpSolverInterface* cast = dynamic_cast<OsiClpSolverInterface*>(si);
    if (cast) {
      cast->getModelPtr()->primal(); // solve problem with primal alg
    }
  }
}

bool HasInt(OsiSolverInterface* si) {
  int i = 0;
  for (i = 0; i != si->getNumCols(); i++) {
    if (si->isInteger(i)) {
      return true;
    }
  }
  return false;
}

}  // namespace cyclus
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: tolayoutanchoredobjectposition.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: hr $ $Date: 2004-03-08 14:02:28 $
 *
 *  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 _TOLAYOUTANCHOREDOBJECTPOSITION_HXX
#include <tolayoutanchoredobjectposition.hxx>
#endif

#ifndef _FRAME_HXX
#include <frame.hxx>
#endif
#ifndef _FLYFRMS_HXX
#include <flyfrms.hxx>
#endif
#ifndef _PAGEFRM_HXX
#include <pagefrm.hxx>
#endif
#ifndef _SVX_SVDOBJ_HXX
#include <svx/svdobj.hxx>
#endif
#ifndef _FRMFMT_HXX
#include <frmfmt.hxx>
#endif
#ifndef _FMTANCHR_HXX
#include <fmtanchr.hxx>
#endif
#ifndef _FMTORNT_HXX
#include <fmtornt.hxx>
#endif
#ifndef _FMTSRND_HXX
#include <fmtsrnd.hxx>
#endif
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _FRMATR_HXX
#include <frmatr.hxx>
#endif
#ifndef _SVX_LRSPITEM_HXX
#include <svx/lrspitem.hxx>
#endif
#ifndef _SVX_ULSPITEM_HXX
#include <svx/ulspitem.hxx>
#endif

using namespace objectpositioning;

SwToLayoutAnchoredObjectPosition::SwToLayoutAnchoredObjectPosition( SdrObject& _rDrawObj )
    : SwAnchoredObjectPosition( _rDrawObj ),
      maRelPos ( Point() )
{}

SwToLayoutAnchoredObjectPosition::~SwToLayoutAnchoredObjectPosition()
{}

SwFlyLayFrm* SwToLayoutAnchoredObjectPosition::GetFlyLayFrmOfObj() const
{
    ASSERT( !IsObjFly() || ( GetFrmOfObj() && GetFrmOfObj()->ISA(SwFlyLayFrm) ),
            "SwToLayoutAnchoredObjectPosition::GetFlyLayFrmOfObj() - missing frame for object or wrong frame type" );

    SwFlyLayFrm* pRetFlyLayFrm =
        const_cast<SwFlyLayFrm*>(static_cast<const SwFlyLayFrm*>(GetFrmOfObj()));
    return pRetFlyLayFrm;
}

/** calculate position for object position type TO_LAYOUT

    @author OD
*/
void SwToLayoutAnchoredObjectPosition::CalcPosition()
{
    const SwRect aObjBoundRect( GetObject().GetCurrentBoundRect() );

    SWRECTFN( (&GetAnchorFrm()) );

    const SwFrmFmt& rFrmFmt = GetFrmFmt();
    const SvxLRSpaceItem &rLR = rFrmFmt.GetLRSpace();
    const SvxULSpaceItem &rUL = rFrmFmt.GetULSpace();

    const bool bFlyAtFly = FLY_AT_FLY == rFrmFmt.GetAnchor().GetAnchorId();

    // determine position.
    // 'vertical' and 'horizontal' position are calculated separately
    Point aRelPos;

    // calculate 'vertical' position
    SwFmtVertOrient aVert( rFrmFmt.GetVertOrient() );
    bool bVertChgd = false;
    {
        // to-frame anchored objects are *only* vertical positioned centered or
        // bottom, if its wrap mode is 'throught' and its anchor frame has fixed
        // size. Otherwise, it's positioned top.
        SwVertOrient eVertOrient = aVert.GetVertOrient();
        if ( ( bFlyAtFly &&
               ( eVertOrient == VERT_CENTER ||
                 eVertOrient == VERT_BOTTOM ) &&
             SURROUND_THROUGHT != rFrmFmt.GetSurround().GetSurround() &&
             !GetAnchorFrm().HasFixSize() ) )
        {
            eVertOrient = VERT_TOP;
        }
        SwTwips nRelPosY =
                _GetVertRelPos( GetAnchorFrm(), GetAnchorFrm(), eVertOrient,
                                aVert.GetRelationOrient(), aVert.GetPos(), rLR, rUL );

        // ??? Why saving calculated relative position
        // keep the calculated relative vertical position
        if ( aVert.GetVertOrient() == VERT_NONE &&
             aVert.GetPos() != nRelPosY )
        {
            aVert.SetPos( nRelPosY );
            bVertChgd = true;
        }

        // determine absolute 'vertical' position, depending on layout-direction
        if( bVert )
        {
            ASSERT( !bRev, "<SwToLayoutAnchoredObjectPosition::CalcPosition()> - reverse layout set." );
            aRelPos.X() = -nRelPosY - aObjBoundRect.Width();
        }
        else
        {
            aRelPos.Y() = nRelPosY;
        }

        // if in online-layout the bottom of to-page anchored object is beyond
        // the page bottom, the page frame has to grow by growing its body frame.
        if ( !bFlyAtFly && GetAnchorFrm().IsPageFrm() &&
             rFrmFmt.GetDoc()->IsBrowseMode() )
        {
            const long nAnchorBottom = GetAnchorFrm().Frm().Bottom();
            const long nBottom = GetAnchorFrm().Frm().Top() +
                                 aRelPos.Y() + aObjBoundRect.Height();
            if ( nAnchorBottom < nBottom )
            {
                static_cast<SwPageFrm&>(GetAnchorFrm()).
                        FindBodyCont()->Grow( nBottom - nAnchorBottom );
            }
        }
    } // end of determination of vertical position

    // calculate 'horizontal' position
    SwFmtHoriOrient aHori( rFrmFmt.GetHoriOrient() );
    bool bHoriChgd = false;
    {
        // consider toggle of horizontal position for even pages.
        const bool bToggle = aHori.IsPosToggle() &&
                             !GetAnchorFrm().FindPageFrm()->OnRightPage();
        SwHoriOrient eHoriOrient = aHori.GetHoriOrient();
        SwRelationOrient eRelOrient = aHori.GetRelationOrient();
        // toggle orientation
        _ToggleHoriOrientAndAlign( bToggle, eHoriOrient, eRelOrient );

        // determine alignment values:
        // <nWidth>: 'width' of the alignment area
        // <nOffset>: offset of alignment area, relative to 'left' of anchor frame
        SwTwips nWidth, nOffset;
        {
            bool bDummy; // in this context irrelevant output parameter
            _GetHoriAlignmentValues( GetAnchorFrm(), GetAnchorFrm(),
                                     eRelOrient, false,
                                     nWidth, nOffset, bDummy );
        }

        SwTwips nObjWidth = (aObjBoundRect.*fnRect->fnGetWidth)();

        // determine relative horizontal position
        SwTwips nRelPosX;
        if ( HORI_NONE == eHoriOrient )
        {
            if( bToggle ||
                ( !aHori.IsPosToggle() && GetAnchorFrm().IsRightToLeft() ) )
            {
                nRelPosX = nWidth - nObjWidth - aHori.GetPos();
            }
            else
            {
                nRelPosX = aHori.GetPos();
            }
        }
        else if ( HORI_CENTER == eHoriOrient )
            nRelPosX = (nWidth / 2) - (nObjWidth / 2);
        else if ( HORI_RIGHT == eHoriOrient )
            nRelPosX = nWidth - ( nObjWidth +
                             ( bVert ? rUL.GetLower() : rLR.GetRight() ) );
        else
            nRelPosX = bVert ? rUL.GetUpper() : rLR.GetLeft();
        nRelPosX += nOffset;

        // no 'negative' relative horizontal position
        // OD 06.11.2003 #FollowTextFlowAtFrame# - negative positions allow for
        // to frame anchored objects.
        if ( !bFlyAtFly && nRelPosX < 0 )
        {
            nRelPosX = 0;
        }

        // determine absolute 'horizontal' position, depending on layout-direction
        if( bVert )
            aRelPos.Y() = nRelPosX;
        else
            aRelPos.X() = nRelPosX;

        // ??? Why saving calculated relative position
        // keep the calculated relative horizontal position
        if ( HORI_NONE != aHori.GetHoriOrient() &&
             aHori.GetPos() != nRelPosX )
        {
            aHori.SetPos( nRelPosX );
            bHoriChgd = true;
        }
    } // end of determination of horizontal position

    // keep calculate relative position
    maRelPos = aRelPos;

    // ??? Why saving calculated relative position
    // update attributes, if changed
    {
        const_cast<SwFrmFmt&>(rFrmFmt).LockModify();
        if ( bVertChgd )
            const_cast<SwFrmFmt&>(rFrmFmt).SetAttr( aVert );
        if ( bHoriChgd )
            const_cast<SwFrmFmt&>(rFrmFmt).SetAttr( aHori );
        const_cast<SwFrmFmt&>(rFrmFmt).UnlockModify();
    }
}

/** calculated relative position for object position

    @author OD
*/
Point SwToLayoutAnchoredObjectPosition::GetRelPos() const
{
    return maRelPos;
}
<commit_msg>INTEGRATION: CWS qwizards1 (1.2.80); FILE MERGED 2004/04/14 13:54:35 tv 1.2.80.1: Correction - ::CalcPosition() - save new vertical relative position, if vertical position is automatic (TOP, CENTER, BOTTOM) Submitted by: OD<commit_after>/*************************************************************************
 *
 *  $RCSfile: tolayoutanchoredobjectposition.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: kz $ $Date: 2004-05-19 13:35:35 $
 *
 *  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 _TOLAYOUTANCHOREDOBJECTPOSITION_HXX
#include <tolayoutanchoredobjectposition.hxx>
#endif

#ifndef _FRAME_HXX
#include <frame.hxx>
#endif
#ifndef _FLYFRMS_HXX
#include <flyfrms.hxx>
#endif
#ifndef _PAGEFRM_HXX
#include <pagefrm.hxx>
#endif
#ifndef _SVX_SVDOBJ_HXX
#include <svx/svdobj.hxx>
#endif
#ifndef _FRMFMT_HXX
#include <frmfmt.hxx>
#endif
#ifndef _FMTANCHR_HXX
#include <fmtanchr.hxx>
#endif
#ifndef _FMTORNT_HXX
#include <fmtornt.hxx>
#endif
#ifndef _FMTSRND_HXX
#include <fmtsrnd.hxx>
#endif
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _FRMATR_HXX
#include <frmatr.hxx>
#endif
#ifndef _SVX_LRSPITEM_HXX
#include <svx/lrspitem.hxx>
#endif
#ifndef _SVX_ULSPITEM_HXX
#include <svx/ulspitem.hxx>
#endif

using namespace objectpositioning;

SwToLayoutAnchoredObjectPosition::SwToLayoutAnchoredObjectPosition( SdrObject& _rDrawObj )
    : SwAnchoredObjectPosition( _rDrawObj ),
      maRelPos ( Point() )
{}

SwToLayoutAnchoredObjectPosition::~SwToLayoutAnchoredObjectPosition()
{}

SwFlyLayFrm* SwToLayoutAnchoredObjectPosition::GetFlyLayFrmOfObj() const
{
    ASSERT( !IsObjFly() || ( GetFrmOfObj() && GetFrmOfObj()->ISA(SwFlyLayFrm) ),
            "SwToLayoutAnchoredObjectPosition::GetFlyLayFrmOfObj() - missing frame for object or wrong frame type" );

    SwFlyLayFrm* pRetFlyLayFrm =
        const_cast<SwFlyLayFrm*>(static_cast<const SwFlyLayFrm*>(GetFrmOfObj()));
    return pRetFlyLayFrm;
}

/** calculate position for object position type TO_LAYOUT

    @author OD
*/
void SwToLayoutAnchoredObjectPosition::CalcPosition()
{
    const SwRect aObjBoundRect( GetObject().GetCurrentBoundRect() );

    SWRECTFN( (&GetAnchorFrm()) );

    const SwFrmFmt& rFrmFmt = GetFrmFmt();
    const SvxLRSpaceItem &rLR = rFrmFmt.GetLRSpace();
    const SvxULSpaceItem &rUL = rFrmFmt.GetULSpace();

    const bool bFlyAtFly = FLY_AT_FLY == rFrmFmt.GetAnchor().GetAnchorId();

    // determine position.
    // 'vertical' and 'horizontal' position are calculated separately
    Point aRelPos;

    // calculate 'vertical' position
    SwFmtVertOrient aVert( rFrmFmt.GetVertOrient() );
    bool bVertChgd = false;
    {
        // to-frame anchored objects are *only* vertical positioned centered or
        // bottom, if its wrap mode is 'throught' and its anchor frame has fixed
        // size. Otherwise, it's positioned top.
        SwVertOrient eVertOrient = aVert.GetVertOrient();
        if ( ( bFlyAtFly &&
               ( eVertOrient == VERT_CENTER ||
                 eVertOrient == VERT_BOTTOM ) &&
             SURROUND_THROUGHT != rFrmFmt.GetSurround().GetSurround() &&
             !GetAnchorFrm().HasFixSize() ) )
        {
            eVertOrient = VERT_TOP;
        }
        SwTwips nRelPosY =
                _GetVertRelPos( GetAnchorFrm(), GetAnchorFrm(), eVertOrient,
                                aVert.GetRelationOrient(), aVert.GetPos(), rLR, rUL );

        // ??? Why saving calculated relative position
        // keep the calculated relative vertical position
        if ( aVert.GetVertOrient() != VERT_NONE &&
             aVert.GetPos() != nRelPosY )
        {
            aVert.SetPos( nRelPosY );
            bVertChgd = true;
        }

        // determine absolute 'vertical' position, depending on layout-direction
        if( bVert )
        {
            ASSERT( !bRev, "<SwToLayoutAnchoredObjectPosition::CalcPosition()> - reverse layout set." );
            aRelPos.X() = -nRelPosY - aObjBoundRect.Width();
        }
        else
        {
            aRelPos.Y() = nRelPosY;
        }

        // if in online-layout the bottom of to-page anchored object is beyond
        // the page bottom, the page frame has to grow by growing its body frame.
        if ( !bFlyAtFly && GetAnchorFrm().IsPageFrm() &&
             rFrmFmt.GetDoc()->IsBrowseMode() )
        {
            const long nAnchorBottom = GetAnchorFrm().Frm().Bottom();
            const long nBottom = GetAnchorFrm().Frm().Top() +
                                 aRelPos.Y() + aObjBoundRect.Height();
            if ( nAnchorBottom < nBottom )
            {
                static_cast<SwPageFrm&>(GetAnchorFrm()).
                        FindBodyCont()->Grow( nBottom - nAnchorBottom );
            }
        }
    } // end of determination of vertical position

    // calculate 'horizontal' position
    SwFmtHoriOrient aHori( rFrmFmt.GetHoriOrient() );
    bool bHoriChgd = false;
    {
        // consider toggle of horizontal position for even pages.
        const bool bToggle = aHori.IsPosToggle() &&
                             !GetAnchorFrm().FindPageFrm()->OnRightPage();
        SwHoriOrient eHoriOrient = aHori.GetHoriOrient();
        SwRelationOrient eRelOrient = aHori.GetRelationOrient();
        // toggle orientation
        _ToggleHoriOrientAndAlign( bToggle, eHoriOrient, eRelOrient );

        // determine alignment values:
        // <nWidth>: 'width' of the alignment area
        // <nOffset>: offset of alignment area, relative to 'left' of anchor frame
        SwTwips nWidth, nOffset;
        {
            bool bDummy; // in this context irrelevant output parameter
            _GetHoriAlignmentValues( GetAnchorFrm(), GetAnchorFrm(),
                                     eRelOrient, false,
                                     nWidth, nOffset, bDummy );
        }

        SwTwips nObjWidth = (aObjBoundRect.*fnRect->fnGetWidth)();

        // determine relative horizontal position
        SwTwips nRelPosX;
        if ( HORI_NONE == eHoriOrient )
        {
            if( bToggle ||
                ( !aHori.IsPosToggle() && GetAnchorFrm().IsRightToLeft() ) )
            {
                nRelPosX = nWidth - nObjWidth - aHori.GetPos();
            }
            else
            {
                nRelPosX = aHori.GetPos();
            }
        }
        else if ( HORI_CENTER == eHoriOrient )
            nRelPosX = (nWidth / 2) - (nObjWidth / 2);
        else if ( HORI_RIGHT == eHoriOrient )
            nRelPosX = nWidth - ( nObjWidth +
                             ( bVert ? rUL.GetLower() : rLR.GetRight() ) );
        else
            nRelPosX = bVert ? rUL.GetUpper() : rLR.GetLeft();
        nRelPosX += nOffset;

        // no 'negative' relative horizontal position
        // OD 06.11.2003 #FollowTextFlowAtFrame# - negative positions allow for
        // to frame anchored objects.
        if ( !bFlyAtFly && nRelPosX < 0 )
        {
            nRelPosX = 0;
        }

        // determine absolute 'horizontal' position, depending on layout-direction
        if( bVert )
            aRelPos.Y() = nRelPosX;
        else
            aRelPos.X() = nRelPosX;

        // ??? Why saving calculated relative position
        // keep the calculated relative horizontal position
        if ( HORI_NONE != aHori.GetHoriOrient() &&
             aHori.GetPos() != nRelPosX )
        {
            aHori.SetPos( nRelPosX );
            bHoriChgd = true;
        }
    } // end of determination of horizontal position

    // keep calculate relative position
    maRelPos = aRelPos;

    // ??? Why saving calculated relative position
    // update attributes, if changed
    {
        const_cast<SwFrmFmt&>(rFrmFmt).LockModify();
        if ( bVertChgd )
            const_cast<SwFrmFmt&>(rFrmFmt).SetAttr( aVert );
        if ( bHoriChgd )
            const_cast<SwFrmFmt&>(rFrmFmt).SetAttr( aHori );
        const_cast<SwFrmFmt&>(rFrmFmt).UnlockModify();
    }
}

/** calculated relative position for object position

    @author OD
*/
Point SwToLayoutAnchoredObjectPosition::GetRelPos() const
{
    return maRelPos;
}
<|endoftext|>


<commit_before>#include "consoleui.h"

using namespace std;

ConsoleUI::ConsoleUI()
{

}
void ConsoleUI::OnlyTakeOneInput()
{
    cin.clear();
    fflush(stdin);
}

void ConsoleUI::run()
{
    bool run = true;
    while (run)
    {
       cout << " ================================" << endl;
       cout << " Press 1 to list the scientists"   << endl;
       cout << " Press 2 to sort the scientists"   << endl;
       cout << " Press 3 to add a scientist"       << endl;
       cout << " Press 4 to search the list"       << endl;
       cout << " Press 5 to remove a scientist"    << endl;
       cout << " Press 6 to exit"                  << endl;
       cout << " ================================" << endl;

       char input = '0';
       cin >> input;
       OnlyTakeOneInput();
       int choice = input - '0';

            switch (choice)
            {
            case 1:
                showData();
                break;
            case 2:
                sortData();
                break;
            case 3:
                addData();
                break;
            case 4:
                searchData();
                break;
            case 5:
                deleteData();
                break;
            case 6:
                run = false;
                break;
            default:
                cout << "Error! Invalid Input" << endl;
            }
    }
}

void ConsoleUI::addData()
{

    string name;
    char gender;
    int birthYear;
    int deathYear;

    cout << "Enter name: ";
    cin >> ws;
    getline(cin,name);
    if(!isupper(name[0]))
    {
        name[0] = toupper(name[0]);
    }
    cout << "Enter gender (M/F): ";
    cin >> gender;
    OnlyTakeOneInput();
    if(genderCheck(gender) == false)
    {
        if(check() == false)
        {
            return;
        }
    }
    cout << "Enter birth year: ";
    cin >> birthYear;
    OnlyTakeOneInput();
    cout << "Enter death year (0 for living person): ";
    cin >> deathYear;
    OnlyTakeOneInput();
    if(birthChecks(birthYear, deathYear) == false)
    {
        check();    // Checks if you want to try to input again.
    }
    else
    {
        Persons newPerson(name, gender, birthYear, deathYear);
        serve.add(newPerson);
    }
}
bool ConsoleUI::genderCheck(char& gender)
{

   if(gender == 'm' || gender == 'M' || gender == 'f' || gender == 'F')
   {
        if(gender == 'm')
        {
            gender = 'M';
        }
        if(gender == 'f')
        {
            gender = 'F';
        }

       return true;
   }
   else
   {
       cout << "Wrong input for gender!" << endl;
       return false;
   }
}

bool ConsoleUI::check()
{
    char continuel;
    cout << "Do you want to try again? (Y for yes and N for No) " ;
    cin  >> continuel;
    if(continuel == 'Y' || continuel == 'y')
    {
        addData();
        return true;
    }
    else
    {
       return false;
    }
}

void ConsoleUI::deleteData()
{
    cout << "Enter name of scientist(s) you would like to delete: ";
    string n = " ";
    cin >> ws;
    getline(cin, n);
    bool d = false;
    while (!d) {
        cout << "Are you sure you would like to delete the following scientist(s)? (y/n)\n";
        vector<int> v = serve.searchByName(n);
        int s = v.size();
        for (int i = 0; i < s; i++) {
            cout << serve.list()[v[i]];
        }
        char a = ' ';
        cin >> a;
        if (a == 'y' || a == 'Y') {
        for (int i = s-1; i >= 0; i--) {
            serve.erase(v[i]);
        }
        cout << "Scientist(s) deleted\n";
         d = true;
        }
        else if (a == 'n' || a == 'N') {
            cout << "Delete cancelled\n";
            d = true;
        }
        else {
            cout << "Invalid input!\n";
        }
    }
}
bool ConsoleUI::birthChecks(int birthYear, int deathYear)
{
    if(!isdigit(birthYear) && !isdigit(deathYear) && deathYear != 0)
    {

        cout << "Please do not input letter" << endl;
        return false;
    }
    if(birthYear < 0 )
    {
        cout << "The scientist can not be born before the year zero." << endl;
        return false;

    }
    if(birthYear > 2016)
    {
        cout << "The scientist can not be born after the year 2016" << endl;

        return false;

    }
    if(deathYear < birthYear && deathYear != 0)
    {
        cout << "The scientist cannot die before they are born!" << endl;
        return false;

    }
    if(deathYear > 2016 )
    {

        cout << "The scientist is still alive.";
        return false;
    }
    if(deathYear - birthYear > 123)
    {
        cout << "That is to old, the oldest woman was 122 years old!" << endl;
        return false;

    }

    return true;
}

void ConsoleUI::showData()
{
    cout << endl;
    printLine();
    for(size_t i = 0; i < serve.list().size();i++)
    {
        cout << serve.list()[i];
    }
     cout << "_____________________________________________________" << endl;

}

void ConsoleUI::searchData()
{
    bool error = false;
    do
    {
        cout << "How would you like to search the data?" << endl;
        cout << " =====================================" << endl;
        cout << " Press 1 to search by name" << endl;
        cout << " Press 2 to search by birth year" << endl;
        cout << " Press 3 to search for gender" << endl;
        cout << " Press 4 to search by birth year range" << endl;
        cout << " Press 5 to cancel" << endl;
        cout << " ======================================"  << endl;

        char input = '0';
        cin >> input;
        int choice = input - '0';

        switch(choice)
        {
            case 1:
            {
                string n = " ";
                cout << "Enter name: ";
                cin >> ws;
                getline(cin, n);
                if(!isupper(n[0]))
                {
                    n[0] = toupper(n[0]);
                }
                vector<int> vN = serve.searchByName(n);
                if (vN.size() == 0) {
                    cout << "No results found\n";
                }
                else {
                    printLine();
                    for (unsigned int i = 0; i < vN.size(); i++)
                    {
                        cout << serve.list()[vN[i]];
                    }
                }
                error = false;
                break;
            }
            case 2:
            {
                int y = 0;
                cout << "Enter year: ";
                cin >> y;
                vector<int> vY = serve.searchByYear(y);
                if (vY.size() == 0) {
                    cout << "No results found\n";
                }
                else {
                    printLine();
                    for (unsigned int i = 0; i < vY.size(); i++)
                    {
                        cout << serve.list()[vY[i]];
                    }
                }
                error = false;
                break;
            }
            case 3:
            {
                char gender;
                cout << "Enter gender (M/F): ";
                cin >> gender;
                if(genderCheck(gender) == false)
                {
                    searchData();
                }
                vector<int> v_g = serve.searchByGender(gender);
                if (v_g.size() == 0)
                {
                    cout << "No results found" << endl;
                }
                else
                {
                    printLine();
                    for (unsigned int i = 0; i < v_g.size(); i++)
                    {
                        cout << serve.list()[v_g[i]];
                    }
                }
                break;
            }
            case 4:
            {
                int f = 0, l = 0;
                cout << "Enter first year in range: ";
                cin >> f;
                cout << "Enter last year in range: ";
                cin >> l;

                vector<int> v_r = serve.searchByRange(f,l);
                if (v_r.size() == 0)
                {
                    cout << "No results found" << endl;
                }
                else
                {
                    printLine();
                    for (unsigned int i = 0; i < v_r.size(); i++)
                    {
                        cout << serve.list()[v_r[i]];
                    }
                }
                break;
            }

            case 5:
                error = false;
                break;
            default:
            {
                cout << "Error! Invalid input" << endl;
                error = true;
            }
        }
    } while (error);
}

void ConsoleUI::sortData()
{
    char input = '0';
    int choice = 0;
    int choice2 = 0;
    bool error = false;

    do
    {

        cout << "How would you like to sort the list?" << endl;
        cout << " ================================" << endl;
        cout << " Press 1 for Name" << endl;
        cout << " Press 2 for Birth Year" << endl;
        cout << " Press 3 for Death Year " << endl;
        cout << " Press 4 for Gender" << endl;
        cout << " Press 5 to Cancel" << endl;
        cout << " ================================" << endl;

        cin >> input;
        choice = input - '0';
        choice2 = 0;
        input = '1';

            switch (choice)
                 {
                 case 1:
                    do
                    {
                        if (input != '1' && input != '2' && input != '3')
                        {
                            cout << "Error! Invalid input" << endl;
                        }
                        cout << "Regular or Reversed sorting?" << endl;
                        cout << " ================================" << endl;
                        cout << "Press 1 for regular sorting" << endl;
                        cout << "Press 2 for reversed sorting" << endl;
                        cout << "Press 3 to cancel" << endl;
                        cout << " ================================" << endl;

                        cin >> input;
                    }
                    while (input != '1' && input != '2' && input != '3');
                    choice2 = input - '0';

                    if (choice2 == 1 || choice2 == 2)
                    {
                        serve.sorting(choice, choice2);
                        error = false;
                    }
                    else
                    {
                        error = true;
                    }
                    break;
                 case 2:
                    do
                    {
                        if (input != '1' && input != '2' && input != '3')
                        {
                            cout << "Error! Invalid input" << endl;
                        }
                        cout << "Regular or Reversed sorting?" << endl;
                        cout << " ================================" << endl;
                        cout << "Press 1 for regular sorting" << endl;
                        cout << "Press 2 for reversed sorting" << endl;
                        cout << "Press 3 to cancel" << endl;
                        cout << " ================================" << endl;

                        cin >> input;
                    }
                    while (input != '1' && input != '2' && input != '3');
                    choice2 = input - '0';

                    if (choice2 == 1 || choice2 == 2)
                    {
                        serve.sorting(choice, choice2);
                        error = false;
                    }
                    else
                    {
                        error = true;
                    }
                    break;
                 case 3:
                    do
                    {
                        if (input != '1' && input != '2' && input != '3')
                        {
                            cout << "Error! Invalid input" << endl;
                        }
                        cout << "Regular or Reversed sorting?" << endl;
                        cout << " ================================" << endl;
                        cout << "Press 1 for regular sorting" << endl;
                        cout << "Press 2 for reversed sorting" << endl;
                        cout << "Press 3 to cancel" << endl;
                        cout << " ================================" << endl;

                        cin >> input;
                    }
                    while (input != '1' && input != '2' && input != '3');
                    choice2 = input - '0';

                    if (choice2 == 1 || choice2 == 2)
                    {
                        serve.sorting(choice, choice2);
                        error = false;
                    }
                    else
                    {
                        error = true;
                    }
                    break;
                 case 4:
                    do
                    {
                        if (input != '1' && input != '2' && input != '3')
                        {
                            cout << "Error! Invalid input" << endl;
                        }
                        cout << "Sort by Males or Females?" << endl;
                        cout << " ================================" << endl;
                        cout << "Press 1 for sorting by females first" << endl;
                        cout << "Press 2 for sorting by males first" << endl;
                        cout << "Press 3 to cancel" << endl;
                        cout << " ================================" << endl;

                        cin >> input;
                    }
                    while (input != '1' && input != '2' && input != '3');
                    choice2 = input - '0';

                    if (choice2 == 1 || choice2 == 2)
                    {
                        serve.sorting(choice, choice2);
                        error = false;
                    }
                    else
                    {
                        error = true;
                    }
                    break;
                 case 5:
                    error = false;
                    break;
                 default:
                     cout << "Error! Invalid input!" << endl;
                     error = true;
                 }
    }
    while (error);

    if (choice != 5) //if you press cancel, you don't want to see the list, do you?
    {
        showData();
    }
}

void ConsoleUI::printLine()
{
    cout.width(16);
    cout << left << "Name";
    cout <<  "\tGender\tBorn\tDied" << endl;
    cout << "_____________________________________________________" << endl;
}
<commit_msg>laga aðeins texta i consoleui<commit_after>#include "consoleui.h"

using namespace std;

ConsoleUI::ConsoleUI()
{

}
void ConsoleUI::OnlyTakeOneInput()
{
    cin.clear();
    fflush(stdin);
}

void ConsoleUI::run()
{
    bool run = true;
    while (run)
    {
       cout << " ================================" << endl;
       cout << " Press 1 to list the scientists"   << endl;
       cout << " Press 2 to sort the scientists"   << endl;
       cout << " Press 3 to add a scientist"       << endl;
       cout << " Press 4 to search the list"       << endl;
       cout << " Press 5 to remove a scientist"    << endl;
       cout << " Press 6 to exit"                  << endl;
       cout << " ================================" << endl;

       char input = '0';
       cin >> input;
       OnlyTakeOneInput();
       int choice = input - '0';

            switch (choice)
            {
            case 1:
                showData();
                break;
            case 2:
                sortData();
                break;
            case 3:
                addData();
                break;
            case 4:
                searchData();
                break;
            case 5:
                deleteData();
                break;
            case 6:
                run = false;
                break;
            default:
                cout << "Error! Invalid Input" << endl;
            }
    }
}

void ConsoleUI::addData()
{

    string name;
    char gender;
    int birthYear;
    int deathYear;

    cout << "Enter name: ";
    cin >> ws;
    getline(cin,name);
    if(!isupper(name[0]))
    {
        name[0] = toupper(name[0]);
    }
    cout << "Enter gender (M/F): ";
    cin >> gender;
    OnlyTakeOneInput();
    if(genderCheck(gender) == false)
    {
        if(check() == false)
        {
            return;
        }
    }
    cout << "Enter birth year: ";
    cin >> birthYear;
    OnlyTakeOneInput();
    cout << "Enter death year (0 for living person): ";
    cin >> deathYear;
    OnlyTakeOneInput();
    if(birthChecks(birthYear, deathYear) == false)
    {
        check();    // Checks if you want to try to input again.
    }
    else
    {
        Persons newPerson(name, gender, birthYear, deathYear);
        serve.add(newPerson);
    }
}
bool ConsoleUI::genderCheck(char& gender)
{

   if(gender == 'm' || gender == 'M' || gender == 'f' || gender == 'F')
   {
        if(gender == 'm')
        {
            gender = 'M';
        }
        if(gender == 'f')
        {
            gender = 'F';
        }

       return true;
   }
   else
   {
       cout << "Wrong input for gender!" << endl;
       return false;
   }
}

bool ConsoleUI::check()
{
    char continuel;
    cout << "Do you want to try again? (Y for yes and N for No) " ;
    cin  >> continuel;
    if(continuel == 'Y' || continuel == 'y')
    {
        addData();
        return true;
    }
    else
    {
       return false;
    }
}

void ConsoleUI::deleteData()
{
    cout << "Enter name of scientist(s) you would like to delete: ";
    string n = " ";
    cin >> ws;
    getline(cin, n);
    bool d = false;
    while (!d) {
        cout << "Are you sure you would like to delete the following scientist(s)? (y/n)\n";
        vector<int> v = serve.searchByName(n);
        int s = v.size();
        for (int i = 0; i < s; i++) {
            cout << serve.list()[v[i]];
        }
        char a = ' ';
        cin >> a;
        if (a == 'y' || a == 'Y') {
        for (int i = s-1; i >= 0; i--) {
            serve.erase(v[i]);
        }
        cout << "Scientist(s) deleted\n";
         d = true;
        }
        else if (a == 'n' || a == 'N') {
            cout << "Delete cancelled\n";
            d = true;
        }
        else {
            cout << "Invalid input!\n";
        }
    }
}
bool ConsoleUI::birthChecks(int birthYear, int deathYear)
{
    if(!isdigit(birthYear) && !isdigit(deathYear) && deathYear != 0)
    {

        cout << "Please do not input letter" << endl;
        return false;
    }
    if(birthYear < 0 )
    {
        cout << "The scientist can not be born before the year zero." << endl;
        return false;

    }
    if(birthYear > 2016)
    {
        cout << "The scientist can not be born after the year 2016" << endl;

        return false;

    }
    if(deathYear < birthYear && deathYear != 0)
    {
        cout << "The scientist cannot die before they are born!" << endl;
        return false;

    }
    if(deathYear > 2016 )
    {

        cout << "The scientist is still alive.";
        return false;
    }
    if(deathYear - birthYear > 123)
    {
        cout << "That is to old, the oldest woman was 122 years old!" << endl;
        return false;

    }

    return true;
}

void ConsoleUI::showData()
{
    cout << endl;
    printLine();
    for(size_t i = 0; i < serve.list().size();i++)
    {
        cout << serve.list()[i];
    }
     cout << "_____________________________________________________" << endl;

}

void ConsoleUI::searchData()
{
    bool error = false;
    do
    {
        cout << "How would you like to search the data?" << endl;
        cout << " =====================================" << endl;
        cout << " Press 1 to search by name" << endl;
        cout << " Press 2 to search by birth year" << endl;
        cout << " Press 3 to search for gender" << endl;
        cout << " Press 4 to search by birth year range" << endl;
        cout << " Press 5 to cancel" << endl;
        cout << " ======================================"  << endl;

        char input = '0';
        cin >> input;
        int choice = input - '0';

        switch(choice)
        {
            case 1:
            {
                string n = " ";
                cout << "Enter name: ";
                cin >> ws;
                getline(cin, n);
                if(!isupper(n[0]))
                {
                    n[0] = toupper(n[0]);
                }
                vector<int> vN = serve.searchByName(n);
                if (vN.size() == 0) {
                    cout << "No results found\n";
                }
                else {
                    printLine();
                    for (unsigned int i = 0; i < vN.size(); i++)
                    {
                        cout << serve.list()[vN[i]];
                    }
                }
                error = false;
                break;
            }
            case 2:
            {
                int y = 0;
                cout << "Enter year: ";
                cin >> y;
                vector<int> vY = serve.searchByYear(y);
                if (vY.size() == 0) {
                    cout << "No results found\n";
                }
                else {
                    printLine();
                    for (unsigned int i = 0; i < vY.size(); i++)
                    {
                        cout << serve.list()[vY[i]];
                    }
                }
                error = false;
                break;
            }
            case 3:
            {
                char gender;
                cout << "Enter gender (M/F): ";
                cin >> gender;
                if(genderCheck(gender) == false)
                {
                    searchData();
                }
                vector<int> v_g = serve.searchByGender(gender);
                if (v_g.size() == 0)
                {
                    cout << "No results found" << endl;
                }
                else
                {
                    printLine();
                    for (unsigned int i = 0; i < v_g.size(); i++)
                    {
                        cout << serve.list()[v_g[i]];
                    }
                }
                break;
            }
            case 4:
            {
                int f = 0, l = 0;
                cout << "Enter first year in range: ";
                cin >> f;
                cout << "Enter last year in range: ";
                cin >> l;

                vector<int> v_r = serve.searchByRange(f,l);
                if (v_r.size() == 0)
                {
                    cout << "No results found" << endl;
                }
                else
                {
                    printLine();
                    for (unsigned int i = 0; i < v_r.size(); i++)
                    {
                        cout << serve.list()[v_r[i]];
                    }
                }
                break;
            }

            case 5:
                error = false;
                break;
            default:
            {
                cout << "Error! Invalid input" << endl;
                error = true;
            }
        }
    } while (error);
}

void ConsoleUI::sortData()
{
    char input = '0';
    int choice = 0;
    int choice2 = 0;
    bool error = false;

    do
    {

        cout << "How would you like to sort the list?" << endl;
        cout << " ================================" << endl;
        cout << " Press 1 for Name" << endl;
        cout << " Press 2 for Birth Year" << endl;
        cout << " Press 3 for Death Year " << endl;
        cout << " Press 4 for Gender" << endl;
        cout << " Press 5 to Cancel" << endl;
        cout << " ================================" << endl;

        cin >> input;
        choice = input - '0';
        choice2 = 0;
        input = '1';

            switch (choice)
                 {
                 case 1:
                    do
                    {
                        if (input != '1' && input != '2' && input != '3')
                        {
                            cout << "Error! Invalid input" << endl;
                        }
                        cout << "Regular or Reversed sorting?" << endl;
                        cout << " ================================" << endl;
                        cout << "Press 1 for regular sorting" << endl;
                        cout << "Press 2 for reversed sorting" << endl;
                        cout << "Press 3 to cancel" << endl;
                        cout << " ================================" << endl;

                        cin >> input;
                    }
                    while (input != '1' && input != '2' && input != '3');
                    choice2 = input - '0';

                    if (choice2 == 1 || choice2 == 2)
                    {
                        serve.sorting(choice, choice2);
                        error = false;
                    }
                    else
                    {
                        error = true;
                    }
                    break;
                 case 2:
                    do
                    {
                        if (input != '1' && input != '2' && input != '3')
                        {
                            cout << "Error! Invalid input" << endl;
                        }
                        cout << "Ascended or Descended sorting?" << endl;
                        cout << " ================================" << endl;
                        cout << "Press 1 to sort by ascending order" << endl;
                        cout << "Press 2 to sort by descending order" << endl;
                        cout << "Press 3 to cancel" << endl;
                        cout << " ================================" << endl;

                        cin >> input;
                    }
                    while (input != '1' && input != '2' && input != '3');
                    choice2 = input - '0';

                    if (choice2 == 1 || choice2 == 2)
                    {
                        serve.sorting(choice, choice2);
                        error = false;
                    }
                    else
                    {
                        error = true;
                    }
                    break;
                 case 3:
                    do
                    {
                        if (input != '1' && input != '2' && input != '3')
                        {
                            cout << "Error! Invalid input" << endl;
                        }
                        cout << "Ascended or Descended sorting?" << endl;
                        cout << " ================================" << endl;
                        cout << "Press 1 to sort by ascending order" << endl;
                        cout << "Press 2 to sort by descending order" << endl;
                        cout << "Press 3 to cancel" << endl;
                        cout << " ================================" << endl;

                        cin >> input;
                    }
                    while (input != '1' && input != '2' && input != '3');
                    choice2 = input - '0';

                    if (choice2 == 1 || choice2 == 2)
                    {
                        serve.sorting(choice, choice2);
                        error = false;
                    }
                    else
                    {
                        error = true;
                    }
                    break;
                 case 4:
                    do
                    {
                        if (input != '1' && input != '2' && input != '3')
                        {
                            cout << "Error! Invalid input" << endl;
                        }
                        cout << "Sort by Males or Females?" << endl;
                        cout << " ================================" << endl;
                        cout << "Press 1 to sort by females first" << endl;
                        cout << "Press 2 to sort by males first" << endl;
                        cout << "Press 3 to cancel" << endl;
                        cout << " ================================" << endl;

                        cin >> input;
                    }
                    while (input != '1' && input != '2' && input != '3');
                    choice2 = input - '0';

                    if (choice2 == 1 || choice2 == 2)
                    {
                        serve.sorting(choice, choice2);
                        error = false;
                    }
                    else
                    {
                        error = true;
                    }
                    break;
                 case 5:
                    error = false;
                    break;
                 default:
                     cout << "Error! Invalid input!" << endl;
                     error = true;
                 }
    }
    while (error);

    if (choice != 5) //if you press cancel, you don't want to see the list, do you?
    {
        showData();
    }
}

void ConsoleUI::printLine()
{
    cout.width(16);
    cout << left << "Name";
    cout <<  "\tGender\tBorn\tDied" << endl;
    cout << "_____________________________________________________" << endl;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include "consoleui.h"
#include "performer.h"

using namespace std;

ConsoleUI::ConsoleUI()
{

}

// Should not contain logic for individual commands, that should be in separate functions!
void ConsoleUI::run()
{
    cout << "Please enter one of the following commands:" << endl;
    cout << "list - This will list all performers in the system" << endl;
    cout << "add - This will add a new performer" << endl;
    cout << "delete - Removes an entry" << endl;
    cout << "update - Updates an entry" << endl;
    cout << "search - Searches for a given performer" << endl;

    string command;
    cin >> command;

    if (command == "list")
    {
        displayListOfPerformers();
    }
    else if (command == "add")
    {
        string name;
        int age;
        cin >> name;
        cin >> age;

        Performer newPerformer(name, age);

        // TODO:
        //_service.addPerformer(newPerformer);
    }
    else if (command == "search")
    {
        // TODO
    }
    else
    {

    }

}

void ConsoleUI::displayListOfPerformers()
{
    vector<Performer> performers = _service.getPerformers();

    cout << "Performer name:" << endl;
    cout << "===============" << endl;
    for (size_t i = 0; i< performers.size(); ++i)
    {
        cout << performers[i].getName() << endl;
    }
}

<commit_msg>Testing<commit_after>#include <iostream>
#include <string>
#include "consoleui.h"
#include "performer.h"

using namespace std;

ConsoleUI::ConsoleUI()
{

}

// Should not contain logic for individual commands, that should be in separate functions!
void ConsoleUI::run()
{
    cout << "Please enter one of the following commands:" << endl;
    cout << "list - This will list all performers in the system" << endl;
    cout << "add - This will add a new performer" << endl;
    cout << "delete - This removes an entry" << endl;
    cout << "update - Updates an entry" << endl;
    cout << "search - Searches for a given performer" << endl;

    string command;
    cin >> command;

    if (command == "list")
    {
        displayListOfPerformers();
    }
    else if (command == "add")
    {
        string name;
        int age;
        cin >> name;
        cin >> age;

        Performer newPerformer(name, age);

        // TODO:
        //_service.addPerformer(newPerformer);
    }
    else if (command == "search")
    {
        // TODO
    }
    else
    {

    }

}

void ConsoleUI::displayListOfPerformers()
{
    vector<Performer> performers = _service.getPerformers();

    cout << "Performer name:" << endl;
    cout << "===============" << endl;
    for (size_t i = 0; i< performers.size(); ++i)
    {
        cout << performers[i].getName() << endl;
    }
}

<|endoftext|>


<commit_before>#include "controller.h"

// Constructor
//   Allows for Verbose Debugging Mode
//   @param bool debug_flag, true will enable verbose debugging
//   @warn assert will end program prematurely
//   @note axis is rendered in debugging mode
Controller::Controller(const int window_width, const int window_height, const bool debug_flag) :
  // Object construction
  renderer_(Renderer(debug_flag)),
  shaders_(renderer_.shaders()),
  camera_(Camera(shaders_, window_width, window_height)),
  sun_(Sun(camera(), debug_flag)),
  light_controller_(new LightController()),
  collision_controller_(CollisionController()),
  terrain_(new Terrain(shaders_->LightMappedGeneric)),
  road_sign_(RoadSign(shaders_, terrain_)),
  car_(AddObject(shaders_->LightMappedGeneric, "models/Pick-up_Truck/pickup_wind_alpha.obj")),
  // State and var defaults
  game_state_(kAutoDrive), light_pos_(glm::vec4(0,0,0,0)),
  frames_past_(0), frames_count_(0), delta_time_(16), is_debugging_(debug_flag) {

    is_key_pressed_hash_.reserve(256);
    is_key_pressed_hash_.resize(256);
    playSound = 1;

    rain_ = new Rain(shaders_->RainGeneric, debug_flag);
    water_ = new Water(shaders_->WaterGeneric);
    skybox_ = new Skybox(shaders_->SkyboxGeneric);

  // Add starting models
  // AddModel(shaders_->LightMappedGeneric, "models/Pick-up_Truck/pickup.obj", true);
  // AddModel(shaders_->LightMappedGeneric, "models/Car/car-n.obj", true);
  // AddModel(shaders_->LightMappedGeneric, "models/Signs_OBJ/working/curve_left.obj");
  // AddModel(shaders_->LightMappedGeneric, "models/Signs_OBJ/working/curve_right.obj");
  // AddModel(shaders_->LightMappedGeneric, "models/Signs_OBJ/working/60.obj");

}

// Adds a model to the member vector
//   @param shader, a shader class holding shader to use and uniforms
//   @param model_filename, a string containing the path of the .obj file
//   @warn the model is created on the heap and memory must be freed afterwards
Object * Controller::AddObject(const Shader &shader, const std::string &model_filename) {
  Object * object = new Model(shader, model_filename,
      glm::vec3(1.12f, 0.55f, 35.0f),     // Translation  move behind first tile (i.e. start on 2nd tile)
      glm::vec3(0.0f, 20.0f, 0.0f),       // Rotation
      glm::vec3(0.4f,  0.4f*1.6f, 0.4f),  // Scale
      60, false); // starting speed and debugging mode

  return object;
}

// Renders all models in the vector member
//   Should be called in the render loop
void Controller::Draw() {
  // Draw to shadow buffer
  glBindFramebuffer(GL_FRAMEBUFFER, renderer_.fbo()->FrameBufferShadows);
  glClear(GL_DEPTH_BUFFER_BIT);
  glViewport(0, 0, renderer_.fbo()->textureX, renderer_.fbo()->textureY);

  // Car with physics
  renderer_.RenderDepthBuffer(car_, sun_);
  // Road-signs
  const std::vector<Object*> signs = road_sign_.signs();
  const std::vector<int> active_signs = road_sign_.active_signs();

  // Unfortunately this does not work
  // for (unsigned int x = 0; x < signs.size(); ++x) {
  //   // if (active_signs[x] >= 0) // no point
  //   renderer_.RenderDepthBuffer(signs[x], sun_);
  // }
  // Terrain
  renderer_.RenderDepthBuffer(terrain_, sun_);

  // Draw to screen
  glBindFramebuffer(GL_FRAMEBUFFER, 0);
  // Bind shadow map texture
  glBindTexture(GL_TEXTURE_2D, renderer_.fbo()->DepthTexture);
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  glViewport(0, 0, camera_.width(), camera_.height());

  // Ordering of renderering is very important due to transparency
  renderer_.RenderSkybox(skybox_, camera_);
  // Water
  renderer_.RenderWater(water_, car_, skybox_, camera_);
  // Terrain
  renderer_.Render(terrain_, camera_, sun_);
  // Road-signs
  for (unsigned int x = 0; x < signs.size(); ++x) {
    // if (active_signs[x] >= 0) // no point
    renderer_.Render(signs[x], camera_, sun_);
  }
  if (camera_.state() == Camera::kFirstPerson) {
    // Rain (particles)
    if (sun_.time_of_day() != 12)
      rain_->Render(camera_, car_, skybox_);
  // Car with physics
  renderer_.Render(car_, camera_, sun_);
  } else {
    // Car with physics
    renderer_.Render(car_, camera_, sun_);
    // Rain (particles)
    if (sun_.time_of_day() != 12)
      rain_->Render(camera_, car_, skybox_);
  }

  // Axis only renders in debugging mode
  renderer_.RenderAxis(camera_);
}

// Assumes SetupLighting() has been called, only updates essential light properties
void Controller::PositionLights() {
  glm::mat4 view_matrix = camera_.view_matrix();
  glm::mat4 car_mv_matrix = view_matrix * car_->model_matrix();
  // glm::mat3 norm_matrix = glm::mat3(view_matrix);

  DirectionalLight dirLight;

  dirLight.DiffuseIntensity = glm::vec3(1.00f, 1.00f, 1.00f);
  dirLight.AmbientIntensity = glm::vec3(0.50f, 0.50f, 0.50f);
  dirLight.SpecularIntensity = glm::vec3(0.35f, 0.35f, 0.40f);
  dirLight.DiffuseIntensity *= sun_.LightIntensityMultiplier();
  dirLight.AmbientIntensity *= sun_.LightIntensityMultiplier();
  // dirLight.SpecularIntensity *= 1.0f - sun_.LightIntensityMultiplier();
  // if (!sun_.IsDay()) {
  //   dirLight.SpecularIntensity.x *= 1.0f - sun_.LightIntensityMultiplier();
  //   dirLight.SpecularIntensity.y *= 1.0f - sun_.LightIntensityMultiplier();
  // }
  dirLight.Direction =  sun_.sun_direction();

  // Point lights
  std::vector<PointLight> pointLights;
  // Main car brake lights
  for (unsigned int i = 0; i < 2; i++) {
    glm::mat4 brakeLightTranslation = glm::translate(glm::mat4(1.0f), glm::vec3(-0.85f + i * 1.7f, 0.0f, -3.3f));

    PointLight brakeLight;
    brakeLight.DiffuseIntensity = glm::vec3(1.0f, 0.0f, 0.0f);
    brakeLight.Position = glm::vec3(car_mv_matrix * brakeLightTranslation * glm::vec4(0.0f, 0.0f, 0.0f, 1.0f));
    brakeLight.Attenuation.Constant = 0.001f;
    brakeLight.Attenuation.Linear = 2.0f;
    brakeLight.Attenuation.Exp = 3.0f;

    if (is_key_pressed_hash_.at('s')) {
      brakeLight.Attenuation.Constant = 0.00001f;
      brakeLight.Attenuation.Linear = 0.5f;
      brakeLight.Attenuation.Exp = 3.0f;
    }

    pointLights.push_back(brakeLight);
  }

  // Spot lights
  std::vector<SpotLight> spotLights;
  // Main car headlights
  for (unsigned int i = 0; i < 2; i++) {
    glm::mat4 headlightTranslation = glm::translate(glm::mat4(1.0f), glm::vec3(-0.5f + i * 1.0f, 0.0f, 1.45f));
    glm::mat3 headlightNormMatrix = glm::mat3(car_mv_matrix);

    SpotLight headlight;
    headlight.DiffuseIntensity = glm::vec3(1.0f, 1.0f, 1.0f);
    headlight.SpecularIntensity = glm::vec3(0.1f, 0.1f, 0.1f);
    headlight.Position = glm::vec3(car_mv_matrix * headlightTranslation * glm::vec4(0.0f, 0.0f, 0.0f, 1.0f));
    headlight.Direction = headlightNormMatrix * glm::vec3(0.0f, -0.3f, 1.0f);
    headlight.CosineCutoff = cos(DEG2RAD(30.0f));
    headlight.Attenuation.Constant = 0.3f;
    headlight.Attenuation.Linear = 0.01f;
    headlight.Attenuation.Exp = 0.01f;

    if (is_key_pressed_hash_.at('r')) {
      headlight.DiffuseIntensity = glm::vec3(0.0f, 0.0f, 0.0f);
      headlight.SpecularIntensity = glm::vec3(0.0f, 0.0f, 0.0f);
    }

    spotLights.push_back(headlight);
  }

  light_controller_->SetDirectionalLight(car_->shader()->Id, dirLight);
  light_controller_->SetSpotLights(water_->shader().Id, spotLights.size(), &spotLights[0]);
  light_controller_->SetDirectionalLight(water_->shader().Id, dirLight);

  light_controller_->SetPointLights(car_->shader()->Id, pointLights.size(), &pointLights[0]);
  light_controller_->SetSpotLights(car_->shader()->Id, spotLights.size(), &spotLights[0]);
}

// The main control tick
//   Controls everything: camera, inputs, physics, collisions
void Controller::UpdateGame() {
  // Lights need to be transformed with view/normal matrix
  PositionLights();
  // Update the position of the rain
  rain_->UpdatePosition();

  // FPS counter - also determine delta time
  long long current_frame = glutGet(GLUT_ELAPSED_TIME);
  frames_count_ += 1;
  if ((current_frame - frames_past_) > 1000) {
    const int fps = frames_count_ * 1000.0f / (current_frame - frames_past_);
      std::cout << "FPS: " << frames_count_ << std::endl;
    frames_count_ = 0;
    frames_past_ = current_frame;

    // Work out average miliseconds per tick
    const GLfloat delta_time = 1.0f/fps * 1000.0f;
    if (abs(delta_time_ - delta_time) < 5)
      delta_time_ = delta_time;
    // printf("dt = %f\n",delta_time_);
  }

  // Update Sun/Moon position
  sun_.Update();

  // Send time for water
  water_->SendTime(current_frame);
  terrain_->GenerationTick();

  // printf("mid = (%f,%f,%f)\n",left_lane_midpoint_.x,left_lane_midpoint_.y,left_lane_midpoint_.z);
  // printf("car = (%f,%f,%f)\n",car_->translation().x,car_->translation().y,car_->translation().z);
  if (!collision_controller_.is_collision()) {
    UpdatePhysics();
    game_state_ = collision_controller_.UpdateCollisions(car_, terrain_, &camera_, &road_sign_, game_state_);
  } else {
    // TODO add car off road shaking
  }
  car_->UpdateModelMatrix();

  UpdateCamera();

  if (game_state_ == kCrashingFall) {
    // delta_time_ /= 5; //slowmo
    if(playSound)
      system("aplay ./sounds/metal_crash.wav -q &");
    playSound = 0;
    game_state_ = collision_controller_.CrashAnimationFall(&camera_, terrain_, car_, delta_time_, is_key_pressed_hash_);
    return;
  }
  if (game_state_ == kCrashingCliff) {
    // delta_time_ /= 5; //slowmo
    if(playSound)
      system("aplay ./sounds/metal_crash.wav -q &");
    playSound = 0;
    game_state_ = collision_controller_.CrashAnimationCliff(&camera_, terrain_, car_, delta_time_, is_key_pressed_hash_);
    return;
  }

  if (is_key_pressed_hash_.at('w') || is_key_pressed_hash_.at('s')
      || is_key_pressed_hash_.at('a') || is_key_pressed_hash_.at('d')) {
    game_state_ = kStart;
    playSound = 1;
  }
}

// The controllers camera update tick
//   Uses car position (for chase and 1st person view)
//   and checks keypresses for freeview
//   @warn should be called before car movement
void Controller::UpdateCamera() {
  // CAMERA CONTROLS
  // Freeview movement
  camera_.Movement(delta_time_, is_key_pressed_hash_);
  // Point at car
  camera_.UpdateCarTick(car_);
  // Update camera lookAt
  camera_.UpdateCamera();

}

// The controllers physics update tick
//   Checks keypresses and calculates acceleration
void Controller::UpdatePhysics() {

  if (game_state_ == kStart) {
    // Sets variables required for camera
    //  i.e. camera has access to car in UpdateCarTick(car_)
    car_->ControllerMovementTick(delta_time_, is_key_pressed_hash_);
  }

  if (game_state_ == kAutoDrive) {
    collision_controller_.AutoDrive(car_, delta_time_);
  }

}
<commit_msg>tweaked car start pos<commit_after>#include "controller.h"

// Constructor
//   Allows for Verbose Debugging Mode
//   @param bool debug_flag, true will enable verbose debugging
//   @warn assert will end program prematurely
//   @note axis is rendered in debugging mode
Controller::Controller(const int window_width, const int window_height, const bool debug_flag) :
  // Object construction
  renderer_(Renderer(debug_flag)),
  shaders_(renderer_.shaders()),
  camera_(Camera(shaders_, window_width, window_height)),
  sun_(Sun(camera(), debug_flag)),
  light_controller_(new LightController()),
  collision_controller_(CollisionController()),
  terrain_(new Terrain(shaders_->LightMappedGeneric)),
  road_sign_(RoadSign(shaders_, terrain_)),
  car_(AddObject(shaders_->LightMappedGeneric, "models/Pick-up_Truck/pickup_wind_alpha.obj")),
  // State and var defaults
  game_state_(kAutoDrive), light_pos_(glm::vec4(0,0,0,0)),
  frames_past_(0), frames_count_(0), delta_time_(16), is_debugging_(debug_flag) {

    is_key_pressed_hash_.reserve(256);
    is_key_pressed_hash_.resize(256);
    playSound = 1;

    rain_ = new Rain(shaders_->RainGeneric, debug_flag);
    water_ = new Water(shaders_->WaterGeneric);
    skybox_ = new Skybox(shaders_->SkyboxGeneric);

  // Add starting models
  // AddModel(shaders_->LightMappedGeneric, "models/Pick-up_Truck/pickup.obj", true);
  // AddModel(shaders_->LightMappedGeneric, "models/Car/car-n.obj", true);
  // AddModel(shaders_->LightMappedGeneric, "models/Signs_OBJ/working/curve_left.obj");
  // AddModel(shaders_->LightMappedGeneric, "models/Signs_OBJ/working/curve_right.obj");
  // AddModel(shaders_->LightMappedGeneric, "models/Signs_OBJ/working/60.obj");

}

// Adds a model to the member vector
//   @param shader, a shader class holding shader to use and uniforms
//   @param model_filename, a string containing the path of the .obj file
//   @warn the model is created on the heap and memory must be freed afterwards
Object * Controller::AddObject(const Shader &shader, const std::string &model_filename) {
  Object * object = new Model(shader, model_filename,
      glm::vec3(0.95f, 0.55f, 35.0f),     // Translation  move behind first tile (i.e. start on 2nd tile)
      glm::vec3(0.0f, 20.0f, 0.0f),       // Rotation
      glm::vec3(0.4f,  0.4f*1.6f, 0.4f),  // Scale
      60, false); // starting speed and debugging mode

  return object;
}

// Renders all models in the vector member
//   Should be called in the render loop
void Controller::Draw() {
  // Draw to shadow buffer
  glBindFramebuffer(GL_FRAMEBUFFER, renderer_.fbo()->FrameBufferShadows);
  glClear(GL_DEPTH_BUFFER_BIT);
  glViewport(0, 0, renderer_.fbo()->textureX, renderer_.fbo()->textureY);

  // Car with physics
  renderer_.RenderDepthBuffer(car_, sun_);
  // Road-signs
  const std::vector<Object*> signs = road_sign_.signs();
  const std::vector<int> active_signs = road_sign_.active_signs();

  // Unfortunately this does not work
  // for (unsigned int x = 0; x < signs.size(); ++x) {
  //   // if (active_signs[x] >= 0) // no point
  //   renderer_.RenderDepthBuffer(signs[x], sun_);
  // }
  // Terrain
  renderer_.RenderDepthBuffer(terrain_, sun_);

  // Draw to screen
  glBindFramebuffer(GL_FRAMEBUFFER, 0);
  // Bind shadow map texture
  glBindTexture(GL_TEXTURE_2D, renderer_.fbo()->DepthTexture);
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  glViewport(0, 0, camera_.width(), camera_.height());

  // Ordering of renderering is very important due to transparency
  renderer_.RenderSkybox(skybox_, camera_);
  // Water
  renderer_.RenderWater(water_, car_, skybox_, camera_);
  // Terrain
  renderer_.Render(terrain_, camera_, sun_);
  // Road-signs
  for (unsigned int x = 0; x < signs.size(); ++x) {
    // if (active_signs[x] >= 0) // no point
    renderer_.Render(signs[x], camera_, sun_);
  }
  if (camera_.state() == Camera::kFirstPerson) {
    // Rain (particles)
    if (sun_.time_of_day() != 12)
      rain_->Render(camera_, car_, skybox_);
  // Car with physics
  renderer_.Render(car_, camera_, sun_);
  } else {
    // Car with physics
    renderer_.Render(car_, camera_, sun_);
    // Rain (particles)
    if (sun_.time_of_day() != 12)
      rain_->Render(camera_, car_, skybox_);
  }

  // Axis only renders in debugging mode
  renderer_.RenderAxis(camera_);
}

// Assumes SetupLighting() has been called, only updates essential light properties
void Controller::PositionLights() {
  glm::mat4 view_matrix = camera_.view_matrix();
  glm::mat4 car_mv_matrix = view_matrix * car_->model_matrix();
  // glm::mat3 norm_matrix = glm::mat3(view_matrix);

  DirectionalLight dirLight;

  dirLight.DiffuseIntensity = glm::vec3(1.00f, 1.00f, 1.00f);
  dirLight.AmbientIntensity = glm::vec3(0.50f, 0.50f, 0.50f);
  dirLight.SpecularIntensity = glm::vec3(0.35f, 0.35f, 0.40f);
  dirLight.DiffuseIntensity *= sun_.LightIntensityMultiplier();
  dirLight.AmbientIntensity *= sun_.LightIntensityMultiplier();
  // dirLight.SpecularIntensity *= 1.0f - sun_.LightIntensityMultiplier();
  // if (!sun_.IsDay()) {
  //   dirLight.SpecularIntensity.x *= 1.0f - sun_.LightIntensityMultiplier();
  //   dirLight.SpecularIntensity.y *= 1.0f - sun_.LightIntensityMultiplier();
  // }
  dirLight.Direction =  sun_.sun_direction();

  // Point lights
  std::vector<PointLight> pointLights;
  // Main car brake lights
  for (unsigned int i = 0; i < 2; i++) {
    glm::mat4 brakeLightTranslation = glm::translate(glm::mat4(1.0f), glm::vec3(-0.85f + i * 1.7f, 0.0f, -3.3f));

    PointLight brakeLight;
    brakeLight.DiffuseIntensity = glm::vec3(1.0f, 0.0f, 0.0f);
    brakeLight.Position = glm::vec3(car_mv_matrix * brakeLightTranslation * glm::vec4(0.0f, 0.0f, 0.0f, 1.0f));
    brakeLight.Attenuation.Constant = 0.001f;
    brakeLight.Attenuation.Linear = 2.0f;
    brakeLight.Attenuation.Exp = 3.0f;

    if (is_key_pressed_hash_.at('s')) {
      brakeLight.Attenuation.Constant = 0.00001f;
      brakeLight.Attenuation.Linear = 0.5f;
      brakeLight.Attenuation.Exp = 3.0f;
    }

    pointLights.push_back(brakeLight);
  }

  // Spot lights
  std::vector<SpotLight> spotLights;
  // Main car headlights
  for (unsigned int i = 0; i < 2; i++) {
    glm::mat4 headlightTranslation = glm::translate(glm::mat4(1.0f), glm::vec3(-0.5f + i * 1.0f, 0.0f, 1.45f));
    glm::mat3 headlightNormMatrix = glm::mat3(car_mv_matrix);

    SpotLight headlight;
    headlight.DiffuseIntensity = glm::vec3(1.0f, 1.0f, 1.0f);
    headlight.SpecularIntensity = glm::vec3(0.1f, 0.1f, 0.1f);
    headlight.Position = glm::vec3(car_mv_matrix * headlightTranslation * glm::vec4(0.0f, 0.0f, 0.0f, 1.0f));
    headlight.Direction = headlightNormMatrix * glm::vec3(0.0f, -0.3f, 1.0f);
    headlight.CosineCutoff = cos(DEG2RAD(30.0f));
    headlight.Attenuation.Constant = 0.3f;
    headlight.Attenuation.Linear = 0.01f;
    headlight.Attenuation.Exp = 0.01f;

    if (is_key_pressed_hash_.at('r')) {
      headlight.DiffuseIntensity = glm::vec3(0.0f, 0.0f, 0.0f);
      headlight.SpecularIntensity = glm::vec3(0.0f, 0.0f, 0.0f);
    }

    spotLights.push_back(headlight);
  }

  light_controller_->SetDirectionalLight(car_->shader()->Id, dirLight);
  light_controller_->SetSpotLights(water_->shader().Id, spotLights.size(), &spotLights[0]);
  light_controller_->SetDirectionalLight(water_->shader().Id, dirLight);

  light_controller_->SetPointLights(car_->shader()->Id, pointLights.size(), &pointLights[0]);
  light_controller_->SetSpotLights(car_->shader()->Id, spotLights.size(), &spotLights[0]);
}

// The main control tick
//   Controls everything: camera, inputs, physics, collisions
void Controller::UpdateGame() {
  // Lights need to be transformed with view/normal matrix
  PositionLights();
  // Update the position of the rain
  rain_->UpdatePosition();

  // FPS counter - also determine delta time
  long long current_frame = glutGet(GLUT_ELAPSED_TIME);
  frames_count_ += 1;
  if ((current_frame - frames_past_) > 1000) {
    const int fps = frames_count_ * 1000.0f / (current_frame - frames_past_);
      std::cout << "FPS: " << frames_count_ << std::endl;
    frames_count_ = 0;
    frames_past_ = current_frame;

    // Work out average miliseconds per tick
    const GLfloat delta_time = 1.0f/fps * 1000.0f;
    if (abs(delta_time_ - delta_time) < 5)
      delta_time_ = delta_time;
    // printf("dt = %f\n",delta_time_);
  }

  // Update Sun/Moon position
  sun_.Update();

  // Send time for water
  water_->SendTime(current_frame);
  terrain_->GenerationTick();

  // printf("mid = (%f,%f,%f)\n",left_lane_midpoint_.x,left_lane_midpoint_.y,left_lane_midpoint_.z);
  // printf("car = (%f,%f,%f)\n",car_->translation().x,car_->translation().y,car_->translation().z);
  if (!collision_controller_.is_collision()) {
    UpdatePhysics();
    game_state_ = collision_controller_.UpdateCollisions(car_, terrain_, &camera_, &road_sign_, game_state_);
  } else {
    // TODO add car off road shaking
  }
  car_->UpdateModelMatrix();

  UpdateCamera();

  if (game_state_ == kCrashingFall) {
    // delta_time_ /= 5; //slowmo
    if(playSound)
      system("aplay ./sounds/metal_crash.wav -q &");
    playSound = 0;
    game_state_ = collision_controller_.CrashAnimationFall(&camera_, terrain_, car_, delta_time_, is_key_pressed_hash_);
    return;
  }
  if (game_state_ == kCrashingCliff) {
    // delta_time_ /= 5; //slowmo
    if(playSound)
      system("aplay ./sounds/metal_crash.wav -q &");
    playSound = 0;
    game_state_ = collision_controller_.CrashAnimationCliff(&camera_, terrain_, car_, delta_time_, is_key_pressed_hash_);
    return;
  }

  if (is_key_pressed_hash_.at('w') || is_key_pressed_hash_.at('s')
      || is_key_pressed_hash_.at('a') || is_key_pressed_hash_.at('d')) {
    game_state_ = kStart;
    playSound = 1;
  }
}

// The controllers camera update tick
//   Uses car position (for chase and 1st person view)
//   and checks keypresses for freeview
//   @warn should be called before car movement
void Controller::UpdateCamera() {
  // CAMERA CONTROLS
  // Freeview movement
  camera_.Movement(delta_time_, is_key_pressed_hash_);
  // Point at car
  camera_.UpdateCarTick(car_);
  // Update camera lookAt
  camera_.UpdateCamera();

}

// The controllers physics update tick
//   Checks keypresses and calculates acceleration
void Controller::UpdatePhysics() {

  if (game_state_ == kStart) {
    // Sets variables required for camera
    //  i.e. camera has access to car in UpdateCarTick(car_)
    car_->ControllerMovementTick(delta_time_, is_key_pressed_hash_);
  }

  if (game_state_ == kAutoDrive) {
    collision_controller_.AutoDrive(car_, delta_time_);
  }

}
<|endoftext|>


<commit_before>#include "iconnconfigmain.h"

#include <QApplication>
#include <QCommandLineParser>
#include <QLibraryInfo>
#include <QLocale>
#include <QSettings>
#include <QTranslator>

int main(int argc, char *argv[]) {
	QApplication app(argc, argv);
	QCoreApplication::setOrganizationName("punkt-k");
	QCoreApplication::setOrganizationDomain("www.punkt-k.de");
	QCoreApplication::setApplicationName("iConnConfig");
	QCoreApplication::setApplicationVersion("0.1.5-alpha");

	QTranslator mioConfigTranslator;
	QTranslator qtTranslator;
	QString l = "iconnconfig_" + QLocale::system().name();
	if (mioConfigTranslator.load(QLocale(), QLatin1String("iconnconfig"),
								 QLatin1String("_"),
								 QLatin1String(":/translations/tr"))) {
		app.installTranslator(&mioConfigTranslator);

		qtTranslator.load(QLocale(), QLatin1String("qt"),
                          QLatin1String("_"),
                          QLibraryInfo::location(QLibraryInfo::TranslationsPath));
		app.installTranslator(&qtTranslator);
	}

	QCommandLineParser *parser = new QCommandLineParser();
	parser->setApplicationDescription("Mio Config");
	parser->addHelpOption();
	parser->addVersionOption();

	// A boolean option with multiple names (-f, --filename)
	QCommandLineOption filenameOption(
		QStringList() << "f"
					  << "filename",
		QCoreApplication::translate("main", "filename to read settings from."),
		"filename");
	parser->addOption(filenameOption);

	// Process the actual command line arguments given by the user
	parser->process(app);
	MioMain w(parser);
	w.show();
	return app.exec();
}
<commit_msg>Remove unused variable<commit_after>#include "iconnconfigmain.h"

#include <QApplication>
#include <QCommandLineParser>
#include <QLibraryInfo>
#include <QLocale>
#include <QSettings>
#include <QTranslator>

int main(int argc, char *argv[]) {
	QApplication app(argc, argv);
	QCoreApplication::setOrganizationName("punkt-k");
	QCoreApplication::setOrganizationDomain("www.punkt-k.de");
	QCoreApplication::setApplicationName("iConnConfig");
	QCoreApplication::setApplicationVersion("0.1.5-alpha");

	QTranslator mioConfigTranslator;
	QTranslator qtTranslator;
	if (mioConfigTranslator.load(QLocale(), QLatin1String("iconnconfig"),
								 QLatin1String("_"),
								 QLatin1String(":/translations/tr"))) {
		app.installTranslator(&mioConfigTranslator);

		qtTranslator.load(
			QLocale(), QLatin1String("qt"), QLatin1String("_"),
			QLibraryInfo::location(QLibraryInfo::TranslationsPath));
		app.installTranslator(&qtTranslator);
	}

	QCommandLineParser *parser = new QCommandLineParser();
	parser->setApplicationDescription("Mio Config");
	parser->addHelpOption();
	parser->addVersionOption();

	// A boolean option with multiple names (-f, --filename)
	QCommandLineOption filenameOption(
		QStringList() << "f"
					  << "filename",
		QCoreApplication::translate("main", "filename to read settings from."),
		"filename");
	parser->addOption(filenameOption);

	// Process the actual command line arguments given by the user
	parser->process(app);
	MioMain w(parser);
	w.show();
	return app.exec();
}
<|endoftext|>