<commit_before>// MathLib.cpp
// This file is part of the EScript programming language.
// See copyright notice in EScript.h
// ------------------------------------------------------
#include "MathLib.h"
#define _USE_MATH_DEFINES
#include <cmath>

#ifndef M_PI
#define M_PI		3.14159265358979323846
#define M_PI_2		1.57079632679489661923
#endif

#include "../EScript/EScript.h"
#include <ctime>
#include <random>

namespace EScript{
namespace MathLib{

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

//! EWrapper for C++ random number engine
class E_RandomNumberGenerator : public ReferenceObject<std::mt19937> {
	ES_PROVIDES_TYPE_NAME(RandomNumberGenerator)
	public:
		//! (static)
		static Type * getTypeObject() {
			static Type * typeObject = new Type(Object::getTypeObject());
			return typeObject;
		}
		static void init(EScript::Namespace & globals);

		//! (ctor)
		E_RandomNumberGenerator(uint32_t seed) :
			ReferenceObject_t(std::mt19937(seed), getTypeObject()) {
		}

		E_RandomNumberGenerator(const std::mt19937 & engine) :
			ReferenceObject_t(engine, getTypeObject()) {
		}

		//! (dtor)
		virtual ~E_RandomNumberGenerator() {
		}

		//! ---|> Object
		virtual E_RandomNumberGenerator * clone() const {
			return new E_RandomNumberGenerator(ref());
		}
};

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

//! (static) MathLib init
void init(EScript::Namespace * globals) {
	Namespace * lib=new Namespace();
	declareConstant(globals,"Math",lib);

	declareConstant(lib,"PI",Number::create(M_PI));
	declareConstant(lib,"PI_2",Number::create(M_PI_2));

	//! Number Math.atan2(a,b)
	ESF_DECLARE(lib, "atan2", 2, 2,
				Number::create(std::atan2(parameter[0].toDouble(), parameter[1].toDouble())))

	// init E_RandomNumberGenerator
	E_RandomNumberGenerator::init(*lib);

	// init global E_RandomNumberGenerator-Object
	declareConstant(globals, "Rand", new E_RandomNumberGenerator(static_cast<unsigned int>(std::time(nullptr))));

	// ------
}

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

//! (static) init members for E_RandomNumberGenerator
void E_RandomNumberGenerator::init(EScript::Namespace & lib) {
	// E_Rand ---|> [Object]
	Type * typeObject = getTypeObject();
	declareConstant(&lib, getClassName(), typeObject);

	//! [ESF] new RandomNumberGenerator( [seed] )
	ESF_DECLARE(typeObject, "_constructor", 0, 1,
				new E_RandomNumberGenerator(parameter[0].toInt(0)))

	//! [ESMF] [0, 1] RandomNumberGenerator.bernoulli(p)
	ESMF_DECLARE(typeObject, E_RandomNumberGenerator, "bernoulli", 1, 1,
				 Number::create(std::bernoulli_distribution(parameter[0].toDouble())(**self) ? 1 : 0))

	//! [ESMF] Number RandomNumberGenerator.binomial(n,p)
	ESMF_DECLARE(typeObject, E_RandomNumberGenerator, "binomial", 2, 2,
				 Number::create(std::binomial_distribution<int>(parameter[0].toInt(), parameter[1].toDouble())(**self)))

	//! [ESMF] Number RandomNumberGenerator.categorical(Array weights)
	ES_MFUNCTION_DECLARE(typeObject, E_RandomNumberGenerator, "categorical", 1, 1, {
		Array * array = assertType<EScript::Array>(runtime, parameter[0]);
		std::vector<double> weights;
		for(const auto & element : *array) {
			weights.push_back(element->toDouble());
		}
		return Number::create(std::discrete_distribution<int>(weights.begin(), weights.end())(**self));
	})

	//! [ESMF] Number RandomNumberGenerator.chisquare(n)
	ESMF_DECLARE(typeObject, E_RandomNumberGenerator, "chisquare", 1, 1,
				 Number::create(std::chi_squared_distribution<double>(parameter[0].toDouble())(**self)))

	//! [ESMF] Number RandomNumberGenerator.equilikely(a,b)
	ESMF_DECLARE(typeObject, E_RandomNumberGenerator, "equilikely", 2, 2,
				 Number::create(std::uniform_int_distribution<int>(parameter[0].toInt(), parameter[1].toInt())(**self)))

	//! [ESMF] Number RandomNumberGenerator.exponential(m)
	ESMF_DECLARE(typeObject, E_RandomNumberGenerator, "exponential", 1, 1,
				 Number::create(std::exponential_distribution<double>(parameter[0].toDouble())(**self)))

	//! [ESMF] Number RandomNumberGenerator.geometric(p)
	ESMF_DECLARE(typeObject, E_RandomNumberGenerator, "geometric", 1, 1,
				 Number::create(std::geometric_distribution<int>(parameter[0].toDouble())(**self)))

	//! [ESMF] Number RandomNumberGenerator.lognormal(a,b)
	ESMF_DECLARE(typeObject, E_RandomNumberGenerator, "lognormal", 2, 2,
				 Number::create(std::lognormal_distribution<double>(parameter[0].toDouble(), parameter[1].toDouble())(**self)))

	//! [ESMF] Number RandomNumberGenerator.normal(m,s)
	ESMF_DECLARE(typeObject, E_RandomNumberGenerator, "normal", 2, 2,
				 Number::create(std::normal_distribution<double>(parameter[0].toDouble(), parameter[1].toDouble())(**self)))

	//! [ESMF] Number RandomNumberGenerator.pascal(n,p)
	ESMF_DECLARE(typeObject, E_RandomNumberGenerator, "pascal", 2, 2,
				 Number::create(std::negative_binomial_distribution<int>(parameter[0].toInt(), parameter[1].toDouble())(**self)))

	//! [ESMF] Number RandomNumberGenerator.poisson(m)
	ESMF_DECLARE(typeObject, E_RandomNumberGenerator, "poisson", 1, 1,
				 Number::create(std::poisson_distribution<int>(parameter[0].toDouble())(**self)))

	//! [ESMF] self RandomNumberGenerator.setSeed(Number)
	ESMF_DECLARE(typeObject, E_RandomNumberGenerator, "setSeed", 1, 1,
				 ((**self).seed(parameter[0].toInt()), self))

	//! [ESMF] Number RandomNumberGenerator.student(n)
	ESMF_DECLARE(typeObject, E_RandomNumberGenerator, "student", 1, 1,
				 Number::create(std::student_t_distribution<double>(parameter[0].toDouble())(**self)))

	//! [ESMF] Number RandomNumberGenerator.uniform(a,b)
	ESMF_DECLARE(typeObject, E_RandomNumberGenerator, "uniform", 2, 2,
				 Number::create(std::uniform_real_distribution<double>(parameter[0].toDouble(), parameter[1].toDouble())(**self)))

	//! [ESMF] Number RandomNumberGenerator.weibull(shape, scale)
	ESMF_DECLARE(typeObject, E_RandomNumberGenerator, "weibull", 2, 2,
				 Number::create(std::weibull_distribution<double>(parameter[0].toDouble(), parameter[1].toDouble())(**self)))

}

}
}
<commit_msg>Add reserve call for std::vector<commit_after>// MathLib.cpp
// This file is part of the EScript programming language.
// See copyright notice in EScript.h
// ------------------------------------------------------
#include "MathLib.h"
#define _USE_MATH_DEFINES
#include <cmath>

#ifndef M_PI
#define M_PI		3.14159265358979323846
#define M_PI_2		1.57079632679489661923
#endif

#include "../EScript/EScript.h"
#include <ctime>
#include <random>

namespace EScript{
namespace MathLib{

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

//! EWrapper for C++ random number engine
class E_RandomNumberGenerator : public ReferenceObject<std::mt19937> {
	ES_PROVIDES_TYPE_NAME(RandomNumberGenerator)
	public:
		//! (static)
		static Type * getTypeObject() {
			static Type * typeObject = new Type(Object::getTypeObject());
			return typeObject;
		}
		static void init(EScript::Namespace & globals);

		//! (ctor)
		E_RandomNumberGenerator(uint32_t seed) :
			ReferenceObject_t(std::mt19937(seed), getTypeObject()) {
		}

		E_RandomNumberGenerator(const std::mt19937 & engine) :
			ReferenceObject_t(engine, getTypeObject()) {
		}

		//! (dtor)
		virtual ~E_RandomNumberGenerator() {
		}

		//! ---|> Object
		virtual E_RandomNumberGenerator * clone() const {
			return new E_RandomNumberGenerator(ref());
		}
};

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

//! (static) MathLib init
void init(EScript::Namespace * globals) {
	Namespace * lib=new Namespace();
	declareConstant(globals,"Math",lib);

	declareConstant(lib,"PI",Number::create(M_PI));
	declareConstant(lib,"PI_2",Number::create(M_PI_2));

	//! Number Math.atan2(a,b)
	ESF_DECLARE(lib, "atan2", 2, 2,
				Number::create(std::atan2(parameter[0].toDouble(), parameter[1].toDouble())))

	// init E_RandomNumberGenerator
	E_RandomNumberGenerator::init(*lib);

	// init global E_RandomNumberGenerator-Object
	declareConstant(globals, "Rand", new E_RandomNumberGenerator(static_cast<unsigned int>(std::time(nullptr))));

	// ------
}

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

//! (static) init members for E_RandomNumberGenerator
void E_RandomNumberGenerator::init(EScript::Namespace & lib) {
	// E_Rand ---|> [Object]
	Type * typeObject = getTypeObject();
	declareConstant(&lib, getClassName(), typeObject);

	//! [ESF] new RandomNumberGenerator( [seed] )
	ESF_DECLARE(typeObject, "_constructor", 0, 1,
				new E_RandomNumberGenerator(parameter[0].toInt(0)))

	//! [ESMF] [0, 1] RandomNumberGenerator.bernoulli(p)
	ESMF_DECLARE(typeObject, E_RandomNumberGenerator, "bernoulli", 1, 1,
				 Number::create(std::bernoulli_distribution(parameter[0].toDouble())(**self) ? 1 : 0))

	//! [ESMF] Number RandomNumberGenerator.binomial(n,p)
	ESMF_DECLARE(typeObject, E_RandomNumberGenerator, "binomial", 2, 2,
				 Number::create(std::binomial_distribution<int>(parameter[0].toInt(), parameter[1].toDouble())(**self)))

	//! [ESMF] Number RandomNumberGenerator.categorical(Array weights)
	ES_MFUNCTION_DECLARE(typeObject, E_RandomNumberGenerator, "categorical", 1, 1, {
		Array * array = assertType<EScript::Array>(runtime, parameter[0]);
		std::vector<double> weights;
		weights.reserve(array->size());
		for(const auto & element : *array) {
			weights.push_back(element->toDouble());
		}
		return Number::create(std::discrete_distribution<int>(weights.begin(), weights.end())(**self));
	})

	//! [ESMF] Number RandomNumberGenerator.chisquare(n)
	ESMF_DECLARE(typeObject, E_RandomNumberGenerator, "chisquare", 1, 1,
				 Number::create(std::chi_squared_distribution<double>(parameter[0].toDouble())(**self)))

	//! [ESMF] Number RandomNumberGenerator.equilikely(a,b)
	ESMF_DECLARE(typeObject, E_RandomNumberGenerator, "equilikely", 2, 2,
				 Number::create(std::uniform_int_distribution<int>(parameter[0].toInt(), parameter[1].toInt())(**self)))

	//! [ESMF] Number RandomNumberGenerator.exponential(m)
	ESMF_DECLARE(typeObject, E_RandomNumberGenerator, "exponential", 1, 1,
				 Number::create(std::exponential_distribution<double>(parameter[0].toDouble())(**self)))

	//! [ESMF] Number RandomNumberGenerator.geometric(p)
	ESMF_DECLARE(typeObject, E_RandomNumberGenerator, "geometric", 1, 1,
				 Number::create(std::geometric_distribution<int>(parameter[0].toDouble())(**self)))

	//! [ESMF] Number RandomNumberGenerator.lognormal(a,b)
	ESMF_DECLARE(typeObject, E_RandomNumberGenerator, "lognormal", 2, 2,
				 Number::create(std::lognormal_distribution<double>(parameter[0].toDouble(), parameter[1].toDouble())(**self)))

	//! [ESMF] Number RandomNumberGenerator.normal(m,s)
	ESMF_DECLARE(typeObject, E_RandomNumberGenerator, "normal", 2, 2,
				 Number::create(std::normal_distribution<double>(parameter[0].toDouble(), parameter[1].toDouble())(**self)))

	//! [ESMF] Number RandomNumberGenerator.pascal(n,p)
	ESMF_DECLARE(typeObject, E_RandomNumberGenerator, "pascal", 2, 2,
				 Number::create(std::negative_binomial_distribution<int>(parameter[0].toInt(), parameter[1].toDouble())(**self)))

	//! [ESMF] Number RandomNumberGenerator.poisson(m)
	ESMF_DECLARE(typeObject, E_RandomNumberGenerator, "poisson", 1, 1,
				 Number::create(std::poisson_distribution<int>(parameter[0].toDouble())(**self)))

	//! [ESMF] self RandomNumberGenerator.setSeed(Number)
	ESMF_DECLARE(typeObject, E_RandomNumberGenerator, "setSeed", 1, 1,
				 ((**self).seed(parameter[0].toInt()), self))

	//! [ESMF] Number RandomNumberGenerator.student(n)
	ESMF_DECLARE(typeObject, E_RandomNumberGenerator, "student", 1, 1,
				 Number::create(std::student_t_distribution<double>(parameter[0].toDouble())(**self)))

	//! [ESMF] Number RandomNumberGenerator.uniform(a,b)
	ESMF_DECLARE(typeObject, E_RandomNumberGenerator, "uniform", 2, 2,
				 Number::create(std::uniform_real_distribution<double>(parameter[0].toDouble(), parameter[1].toDouble())(**self)))

	//! [ESMF] Number RandomNumberGenerator.weibull(shape, scale)
	ESMF_DECLARE(typeObject, E_RandomNumberGenerator, "weibull", 2, 2,
				 Number::create(std::weibull_distribution<double>(parameter[0].toDouble(), parameter[1].toDouble())(**self)))

}

}
}
<|endoftext|>


<commit_before><commit_msg>Resolve TODO. Fix memory leak.<commit_after><|endoftext|>


<commit_before><commit_msg>Don't crash on startup.<commit_after><|endoftext|>


<commit_before><commit_msg>added documentation to boundSegmentNonLinear function<commit_after><|endoftext|>


<commit_before>#include <memory>
#include <vector>

#include <SDL2/SDL.h>
#include <SDL2/SDL_opengles2.h>

#include "engine/shader.hpp"
#include "engine/shader_program.hpp"
#include "engine/vertex_buffer.hpp"
#include "engine/window.hpp"
#include "modules/static_triangle.hpp"

namespace static_triangle {
    const std::string module_name("static_triangle");

    const char *vertex_shader_source = R"glsl(
#version 100

attribute vec4 position;
attribute vec4 color;

varying vec4 fragment_color;

void main() {
    fragment_color = color;
    gl_Position = position;
}
)glsl";

    const char *fragment_shader_source = R"glsl(
#version 100

precision mediump float;

varying vec4 fragment_color;

void main() {
   gl_FragColor = fragment_color;
}
)glsl";

    const int vertex_depth = 4;

    int run(int argc, char **argv) {
        window main_window;

        auto shaders = std::make_unique<std::vector<std::unique_ptr<shader>>>();
        shaders->push_back(std::make_unique<shader>(GL_VERTEX_SHADER, vertex_shader_source));
        shaders->push_back(std::make_unique<shader>(GL_FRAGMENT_SHADER, fragment_shader_source));
        shader_program main_program(std::move(shaders));

        auto triangle_vertex_vector = std::make_unique<std::vector<GLfloat>, std::initializer_list<GLfloat>>({
                0.0f, 0.5f, 0.0f, 1.0f,
                0.5f, -0.5f, 0.0f, 1.0f,
                -0.5f, -0.5f, 0.0f, 1.0f,
                1.0f, 0.0f, 0.0f, 1.0f,
                0.0f, 1.0f, 0.0f, 1.0f,
                0.0f, 0.0f, 1.0f, 1.0f});
        const int vertex_count = triangle_vertex_vector->size() / vertex_depth / 2;
        vertex_buffer triangle_vertices(std::move(triangle_vertex_vector));

        main_program.use();
        triangle_vertices.bind();
        GLuint position_attrib = main_program.get_attrib_location("position");
        glEnableVertexAttribArray(position_attrib);
        glVertexAttribPointer(position_attrib, vertex_depth, GL_FLOAT, GL_FALSE, 0, 0);
        GLuint color_attrib = main_program.get_attrib_location("color");
        glEnableVertexAttribArray(color_attrib);
        glVertexAttribPointer(
                color_attrib,
                vertex_depth,
                GL_FLOAT,
                GL_FALSE,
                0,
                (GLvoid*) (sizeof(GLfloat) * vertex_depth * vertex_count));

        SDL_Event event;
        bool done = false;
        while (!done) {
            glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
            glClear(GL_COLOR_BUFFER_BIT);

            glDrawArrays(GL_TRIANGLES, 0, vertex_count);

            main_window.swap();

            while (SDL_PollEvent(&event)) {
                if (event.type == SDL_QUIT) {
                    done = true;
                }
            }
        }

        return 0;
    }
}
<commit_msg>static_triangle: added engine var to call SDL_Init<commit_after>#include <memory>
#include <vector>

#include <SDL2/SDL.h>
#include <SDL2/SDL_opengles2.h>

#include "engine/engine.hpp"
#include "engine/shader.hpp"
#include "engine/shader_program.hpp"
#include "engine/vertex_buffer.hpp"
#include "engine/window.hpp"
#include "modules/static_triangle.hpp"

namespace static_triangle {
    const std::string module_name("static_triangle");

    const char *vertex_shader_source = R"glsl(
#version 100

attribute vec4 position;
attribute vec4 color;

varying vec4 fragment_color;

void main() {
    fragment_color = color;
    gl_Position = position;
}
)glsl";

    const char *fragment_shader_source = R"glsl(
#version 100

precision mediump float;

varying vec4 fragment_color;

void main() {
   gl_FragColor = fragment_color;
}
)glsl";

    const int vertex_depth = 4;

    int run(int argc, char **argv) {
        engine e;
        window main_window;

        auto shaders = std::make_unique<std::vector<std::unique_ptr<shader>>>();
        shaders->push_back(std::make_unique<shader>(GL_VERTEX_SHADER, vertex_shader_source));
        shaders->push_back(std::make_unique<shader>(GL_FRAGMENT_SHADER, fragment_shader_source));
        shader_program main_program(std::move(shaders));

        auto triangle_vertex_vector = std::make_unique<std::vector<GLfloat>, std::initializer_list<GLfloat>>({
                0.0f, 0.5f, 0.0f, 1.0f,
                0.5f, -0.5f, 0.0f, 1.0f,
                -0.5f, -0.5f, 0.0f, 1.0f,
                1.0f, 0.0f, 0.0f, 1.0f,
                0.0f, 1.0f, 0.0f, 1.0f,
                0.0f, 0.0f, 1.0f, 1.0f});
        const int vertex_count = triangle_vertex_vector->size() / vertex_depth / 2;
        vertex_buffer triangle_vertices(std::move(triangle_vertex_vector));

        main_program.use();
        triangle_vertices.bind();
        GLuint position_attrib = main_program.get_attrib_location("position");
        glEnableVertexAttribArray(position_attrib);
        glVertexAttribPointer(position_attrib, vertex_depth, GL_FLOAT, GL_FALSE, 0, 0);
        GLuint color_attrib = main_program.get_attrib_location("color");
        glEnableVertexAttribArray(color_attrib);
        glVertexAttribPointer(
                color_attrib,
                vertex_depth,
                GL_FLOAT,
                GL_FALSE,
                0,
                (GLvoid*) (sizeof(GLfloat) * vertex_depth * vertex_count));

        SDL_Event event;
        bool done = false;
        while (!done) {
            glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
            glClear(GL_COLOR_BUFFER_BIT);

            glDrawArrays(GL_TRIANGLES, 0, vertex_count);

            main_window.swap();

            while (SDL_PollEvent(&event)) {
                if (event.type == SDL_QUIT) {
                    done = true;
                }
            }
        }

        return 0;
    }
}
<|endoftext|>


<commit_before>/******************************************************************************
 *                       ____    _    _____                                   *
 *                      / ___|  / \  |  ___|    C++                           *
 *                     | |     / _ \ | |_       Actor                         *
 *                     | |___ / ___ \|  _|      Framework                     *
 *                      \____/_/   \_|_|                                      *
 *                                                                            *
 * Copyright (C) 2011 - 2017                                                  *
 * Dominik Charousset <dominik.charousset (at) haw-hamburg.de>                *
 *                                                                            *
 * Distributed under the terms and conditions of the BSD 3-Clause License or  *
 * (at your option) under the terms and conditions of the Boost Software      *
 * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE.       *
 *                                                                            *
 * If you did not receive a copy of the license files, see                    *
 * http://opensource.org/licenses/BSD-3-Clause and                            *
 * http://www.boost.org/LICENSE_1_0.txt.                                      *
 ******************************************************************************/

#include <string>
#include <numeric>
#include <fstream>
#include <iostream>
#include <iterator>

#define CAF_SUITE io_remote_streams
#include "caf/test/io_dsl.hpp"

#include "caf/io/middleman.hpp"
#include "caf/io/basp_broker.hpp"
#include "caf/io/network/test_multiplexer.hpp"

using std::cout;
using std::endl;
using std::string;

using namespace caf;
using namespace caf::io;

namespace {

behavior drop_all(event_based_actor* self) {
  return {
    [=](stream<int>& in, std::string& fname) {
      CAF_CHECK_EQUAL(fname, "test.txt");
      return self->add_sink(
        // input stream
        in,
        // initialize state
        [](unit_t&) {
          // nop
        },
        // processing step
        [](unit_t&, int) {
          // nop
        },
        // cleanup and produce void "result"
        [](unit_t&) {
          CAF_LOG_INFO("drop_all done");
        }
      );
    }
  };
}

void streamer_without_result(event_based_actor* self, const actor& dest) {
  CAF_LOG_INFO("streamer_without_result initialized");
  using buf = std::deque<int>;
  self->new_stream(
    // destination of the stream
    dest,
    // "file name" for the next stage
    std::make_tuple("test.txt"),
    // initialize state
    [&](buf& xs) {
      xs = buf{1, 2, 3, 4, 5, 6, 7, 8, 9};
    },
    // get next element
    [=](buf& xs, downstream<int>& out, size_t num) {
      auto n = std::min(num, xs.size());
      for (size_t i = 0; i < n; ++i)
        out.push(xs[i]);
      xs.erase(xs.begin(), xs.begin() + static_cast<ptrdiff_t>(n));
    },
    // check whether we reached the end
    [=](const buf& xs) {
      return xs.empty();
    },
    // handle result of the stream
    [=](expected<void>) {
      // nop
    }
  );
}

class remoting_config : public actor_system_config {
public:
  remoting_config() {
    load<middleman, network::test_multiplexer>();
    add_message_type<stream<int>>("stream<int>");
    add_message_type<std::vector<int>>("vector<int>");
    middleman_detach_utility_actors = false;
  }
};

using sub_fixture = test_node_fixture_t<remoting_config>;

} // namespace <anonymous>

struct dsl_path_info {
  sub_fixture& host;
  actor receiver;
  dsl_path_info(sub_fixture& x, actor y)
      : host(x), receiver(std::move(y)) {
    // nop
  }
  dsl_path_info(sub_fixture& x, strong_actor_ptr y)
      : host(x), receiver(actor_cast<actor>(std::move(y))) {
    // nop
  }
};

#define expect_on_path(types, fields, ...)                                     \
  CAF_MESSAGE(">>> " << #types << " on path " << #__VA_ARGS__);                \
  {                                                                            \
    std::vector<dsl_path_info> path{{__VA_ARGS__}};                            \
    for (auto x : path) {                                                      \
      network_traffic();                                                       \
      expect_on(x.host, types, from(_).to(x.receiver).fields);                 \
    }                                                                          \
  }                                                                            \
  CAF_MESSAGE("<<< path done")

CAF_TEST_FIXTURE_SCOPE(netstreams, point_to_point_fixture_t<remoting_config>)

CAF_TEST(stream_crossing_the_wire) {
  // TODO: stream servers are currently disabled, because they break many
  // possible setups by hiding remote actor handles. They must be
  // re-implemented in a transparent fashion.
  CAF_CHECK(true);
}

/*
CAF_TEST(stream_crossing_the_wire) {
  CAF_MESSAGE("earth stream serv: " << to_string(earth.stream_serv));
  CAF_MESSAGE("mars stream serv: " << to_string(mars.stream_serv));
  // Connect the buffers of mars and earth to setup a pseudo-network.
  mars.peer = &earth;
  earth.peer = &mars;
  // Setup: earth (streamer_without_result) streams to mars (drop_all).
  CAF_MESSAGE("spawn drop_all sink on mars");
  auto sink = mars.sys.spawn(drop_all);
  // This test uses two fixtures for keeping state.
  earth.conn = connection_handle::from_int(1);
  mars.conn = connection_handle::from_int(2);
  mars.acc = accept_handle::from_int(3);
  // Run any initialization code.
  exec_all();
  // Prepare publish and remote_actor calls.
  CAF_MESSAGE("prepare connections on earth and mars");
  prepare_connection(mars, earth, "mars", 8080u);
  // Publish sink on mars.
  CAF_MESSAGE("publish sink on mars");
  mars.publish(sink, 8080);
  // Get a proxy on earth.
  CAF_MESSAGE("connect from earth to mars");
  auto proxy = earth.remote_actor("mars", 8080);
  CAF_MESSAGE("got proxy: " << to_string(proxy) << ", spawn streamer on earth");
  CAF_MESSAGE("establish remote stream paths");
  // Establish remote paths between the two stream servers. This step is
  // necessary to prevent a deadlock in `stream_serv::remote_stream_serv` due
  // to blocking communication with the BASP broker.
  anon_send(actor_cast<actor>(earth.stream_serv), connect_atom::value,
            mars.stream_serv->node());
  anon_send(actor_cast<actor>(mars.stream_serv), connect_atom::value,
            earth.stream_serv->node());
  exec_all();
  CAF_MESSAGE("start streaming");
  // Start streaming.
  auto source = earth.sys.spawn(streamer_without_result, proxy);
  earth.sched.run_once();
  // source ----('sys', stream_msg::open)----> earth.stream_serv
  expect_on(earth, (atom_value, stream_msg),
            from(source).to(earth.stream_serv).with(sys_atom::value, _));
  // --------------(stream_msg::open)-------------->
  //  earth.stream_serv -> mars.stream_serv -> sink
  expect_on_path(
    (stream_msg::open), with(_, _, _, _, _, false),
    {mars, mars.stream_serv}, {mars, sink});
  // mars.stream_serv --('sys', 'ok', 5)--> earth.stream_serv
  network_traffic();
  expect_on(earth, (atom_value, atom_value, int32_t),
            from(_).to(earth.stream_serv)
            .with(sys_atom::value, ok_atom::value, 5));
  // -----------------(stream_msg::ack_open)------------------>
  //  sink -> mars.stream_serv -> earth.stream_serv -> source
  expect_on_path(
    (stream_msg::ack_open), with(_, 5, _, false),
    {mars, mars.stream_serv}, {earth, earth.stream_serv}, {earth, source});
  // earth.stream_serv --('sys', 'ok', 5)--> mars.stream_serv
  network_traffic();
  expect_on(mars, (atom_value, atom_value, int32_t),
            from(_).to(mars.stream_serv)
            .with(sys_atom::value, ok_atom::value, 5));
  // -------------------(stream_msg::batch)------------------->
  //  source -> earth.stream_serv -> mars.stream_serv -> sink
  expect_on_path(
    (stream_msg::batch), with(5, std::vector<int>{1, 2, 3, 4, 5}, 0),
    {earth, earth.stream_serv},
    {mars, mars.stream_serv}, {mars, sink});
  // -----------------(stream_msg::ack_batch)------------------>
  //  sink -> mars.stream_serv -> earth.stream_serv -> source
  expect_on_path(
    (stream_msg::ack_batch), with(5, 0),
    {mars, mars.stream_serv}, {earth, earth.stream_serv}, {earth, source});
  // -------------------(stream_msg::batch)------------------->
  //  source -> earth.stream_serv -> mars.stream_serv -> sink
  expect_on_path(
    (stream_msg::batch), with(4, std::vector<int>{6, 7, 8, 9}, 1),
    {earth, earth.stream_serv},
    {mars, mars.stream_serv}, {mars, sink});
  // -----------------(stream_msg::ack_batch)------------------>
  //  sink -> mars.stream_serv -> earth.stream_serv -> source
  expect_on_path(
    (stream_msg::ack_batch), with(4, 1),
    {mars, mars.stream_serv}, {earth, earth.stream_serv}, {earth, source});
  // -------------------(stream_msg::close)------------------->
  //  source -> earth.stream_serv -> mars.stream_serv -> sink
  expect_on_path(
    (stream_msg::close), with(),
    {earth, earth.stream_serv},
    {mars, mars.stream_serv}, {mars, sink});
  // sink ----(result: <empty>)---> source
  network_traffic();
  expect_on(earth, (void), from(proxy).to(source).with());
  // sink --(void)--> source
  anon_send_exit(sink, exit_reason::user_shutdown);
  mars.sched.run();
  anon_send_exit(source, exit_reason::user_shutdown);
  earth.sched.run();
}
*/

CAF_TEST_FIXTURE_SCOPE_END()
<commit_msg>Remove dead code<commit_after>/******************************************************************************
 *                       ____    _    _____                                   *
 *                      / ___|  / \  |  ___|    C++                           *
 *                     | |     / _ \ | |_       Actor                         *
 *                     | |___ / ___ \|  _|      Framework                     *
 *                      \____/_/   \_|_|                                      *
 *                                                                            *
 * Copyright (C) 2011 - 2017                                                  *
 * Dominik Charousset <dominik.charousset (at) haw-hamburg.de>                *
 *                                                                            *
 * Distributed under the terms and conditions of the BSD 3-Clause License or  *
 * (at your option) under the terms and conditions of the Boost Software      *
 * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE.       *
 *                                                                            *
 * If you did not receive a copy of the license files, see                    *
 * http://opensource.org/licenses/BSD-3-Clause and                            *
 * http://www.boost.org/LICENSE_1_0.txt.                                      *
 ******************************************************************************/

#include <string>
#include <numeric>
#include <fstream>
#include <iostream>
#include <iterator>

#define CAF_SUITE io_remote_streams
#include "caf/test/io_dsl.hpp"

#include "caf/io/middleman.hpp"
#include "caf/io/basp_broker.hpp"
#include "caf/io/network/test_multiplexer.hpp"

using std::cout;
using std::endl;
using std::string;

using namespace caf;
using namespace caf::io;

namespace {

class remoting_config : public actor_system_config {
public:
  remoting_config() {
    load<middleman, network::test_multiplexer>();
    add_message_type<stream<int>>("stream<int>");
    add_message_type<std::vector<int>>("vector<int>");
    middleman_detach_utility_actors = false;
  }
};

using sub_fixture = test_node_fixture_t<remoting_config>;

} // namespace <anonymous>

struct dsl_path_info {
  sub_fixture& host;
  actor receiver;
  dsl_path_info(sub_fixture& x, actor y)
      : host(x), receiver(std::move(y)) {
    // nop
  }
  dsl_path_info(sub_fixture& x, strong_actor_ptr y)
      : host(x), receiver(actor_cast<actor>(std::move(y))) {
    // nop
  }
};

#define expect_on_path(types, fields, ...)                                     \
  CAF_MESSAGE(">>> " << #types << " on path " << #__VA_ARGS__);                \
  {                                                                            \
    std::vector<dsl_path_info> path{{__VA_ARGS__}};                            \
    for (auto x : path) {                                                      \
      network_traffic();                                                       \
      expect_on(x.host, types, from(_).to(x.receiver).fields);                 \
    }                                                                          \
  }                                                                            \
  CAF_MESSAGE("<<< path done")

CAF_TEST_FIXTURE_SCOPE(netstreams, point_to_point_fixture_t<remoting_config>)

CAF_TEST(stream_crossing_the_wire) {
  // TODO: stream servers are currently disabled, because they break many
  // possible setups by hiding remote actor handles. They must be
  // re-implemented in a transparent fashion.
  CAF_CHECK(true);
}

/*
CAF_TEST(stream_crossing_the_wire) {
  CAF_MESSAGE("earth stream serv: " << to_string(earth.stream_serv));
  CAF_MESSAGE("mars stream serv: " << to_string(mars.stream_serv));
  // Connect the buffers of mars and earth to setup a pseudo-network.
  mars.peer = &earth;
  earth.peer = &mars;
  // Setup: earth (streamer_without_result) streams to mars (drop_all).
  CAF_MESSAGE("spawn drop_all sink on mars");
  auto sink = mars.sys.spawn(drop_all);
  // This test uses two fixtures for keeping state.
  earth.conn = connection_handle::from_int(1);
  mars.conn = connection_handle::from_int(2);
  mars.acc = accept_handle::from_int(3);
  // Run any initialization code.
  exec_all();
  // Prepare publish and remote_actor calls.
  CAF_MESSAGE("prepare connections on earth and mars");
  prepare_connection(mars, earth, "mars", 8080u);
  // Publish sink on mars.
  CAF_MESSAGE("publish sink on mars");
  mars.publish(sink, 8080);
  // Get a proxy on earth.
  CAF_MESSAGE("connect from earth to mars");
  auto proxy = earth.remote_actor("mars", 8080);
  CAF_MESSAGE("got proxy: " << to_string(proxy) << ", spawn streamer on earth");
  CAF_MESSAGE("establish remote stream paths");
  // Establish remote paths between the two stream servers. This step is
  // necessary to prevent a deadlock in `stream_serv::remote_stream_serv` due
  // to blocking communication with the BASP broker.
  anon_send(actor_cast<actor>(earth.stream_serv), connect_atom::value,
            mars.stream_serv->node());
  anon_send(actor_cast<actor>(mars.stream_serv), connect_atom::value,
            earth.stream_serv->node());
  exec_all();
  CAF_MESSAGE("start streaming");
  // Start streaming.
  auto source = earth.sys.spawn(streamer_without_result, proxy);
  earth.sched.run_once();
  // source ----('sys', stream_msg::open)----> earth.stream_serv
  expect_on(earth, (atom_value, stream_msg),
            from(source).to(earth.stream_serv).with(sys_atom::value, _));
  // --------------(stream_msg::open)-------------->
  //  earth.stream_serv -> mars.stream_serv -> sink
  expect_on_path(
    (stream_msg::open), with(_, _, _, _, _, false),
    {mars, mars.stream_serv}, {mars, sink});
  // mars.stream_serv --('sys', 'ok', 5)--> earth.stream_serv
  network_traffic();
  expect_on(earth, (atom_value, atom_value, int32_t),
            from(_).to(earth.stream_serv)
            .with(sys_atom::value, ok_atom::value, 5));
  // -----------------(stream_msg::ack_open)------------------>
  //  sink -> mars.stream_serv -> earth.stream_serv -> source
  expect_on_path(
    (stream_msg::ack_open), with(_, 5, _, false),
    {mars, mars.stream_serv}, {earth, earth.stream_serv}, {earth, source});
  // earth.stream_serv --('sys', 'ok', 5)--> mars.stream_serv
  network_traffic();
  expect_on(mars, (atom_value, atom_value, int32_t),
            from(_).to(mars.stream_serv)
            .with(sys_atom::value, ok_atom::value, 5));
  // -------------------(stream_msg::batch)------------------->
  //  source -> earth.stream_serv -> mars.stream_serv -> sink
  expect_on_path(
    (stream_msg::batch), with(5, std::vector<int>{1, 2, 3, 4, 5}, 0),
    {earth, earth.stream_serv},
    {mars, mars.stream_serv}, {mars, sink});
  // -----------------(stream_msg::ack_batch)------------------>
  //  sink -> mars.stream_serv -> earth.stream_serv -> source
  expect_on_path(
    (stream_msg::ack_batch), with(5, 0),
    {mars, mars.stream_serv}, {earth, earth.stream_serv}, {earth, source});
  // -------------------(stream_msg::batch)------------------->
  //  source -> earth.stream_serv -> mars.stream_serv -> sink
  expect_on_path(
    (stream_msg::batch), with(4, std::vector<int>{6, 7, 8, 9}, 1),
    {earth, earth.stream_serv},
    {mars, mars.stream_serv}, {mars, sink});
  // -----------------(stream_msg::ack_batch)------------------>
  //  sink -> mars.stream_serv -> earth.stream_serv -> source
  expect_on_path(
    (stream_msg::ack_batch), with(4, 1),
    {mars, mars.stream_serv}, {earth, earth.stream_serv}, {earth, source});
  // -------------------(stream_msg::close)------------------->
  //  source -> earth.stream_serv -> mars.stream_serv -> sink
  expect_on_path(
    (stream_msg::close), with(),
    {earth, earth.stream_serv},
    {mars, mars.stream_serv}, {mars, sink});
  // sink ----(result: <empty>)---> source
  network_traffic();
  expect_on(earth, (void), from(proxy).to(source).with());
  // sink --(void)--> source
  anon_send_exit(sink, exit_reason::user_shutdown);
  mars.sched.run();
  anon_send_exit(source, exit_reason::user_shutdown);
  earth.sched.run();
}
*/

CAF_TEST_FIXTURE_SCOPE_END()
<|endoftext|>


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

 Module:       FGAerodynamics.cpp
 Author:       Jon S. Berndt
 Date started: 09/13/00
 Purpose:      Encapsulates the aerodynamic forces (gear and collision)

 ------------- Copyright (C) 2000  Jon S. Berndt (jsb@hal-pc.org) -------------

 This program is free software; you can redistribute it and/or modify it under
 the terms of the GNU General Public License as published by the Free Software
 Foundation; either version 2 of the License, or (at your option) any later
 version.

 This program is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 details.

 You should have received a copy of the GNU General Public License along with
 this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 Place - Suite 330, Boston, MA  02111-1307, USA.

 Further information about the GNU General Public License can also be found on
 the world wide web at http://www.gnu.org.

FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------

HISTORY
--------------------------------------------------------------------------------
09/13/00   JSB   Created
04/22/01   JSB   Moved code into here from FGAircraft

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/

#include "FGAerodynamics.h"
#include "FGPropagate.h"
#include "FGAircraft.h"
#include "FGState.h"
#include "FGMassBalance.h"
#include "FGFactorGroup.h"
#include "FGPropertyManager.h"

namespace JSBSim {

static const char *IdSrc = "$Id: FGAerodynamics.cpp,v 1.48 2004/04/17 21:13:20 jberndt Exp $";
static const char *IdHdr = ID_AERODYNAMICS;

const unsigned NAxes=6;
const char* AxisNames[] = { "drag", "side-force", "lift", "rolling-moment",
                            "pitching-moment","yawing-moment" };

/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/

FGAerodynamics::FGAerodynamics(FGFDMExec* FDMExec) : FGModel(FDMExec)
{
  Name = "FGAerodynamics";

  AxisIdx["DRAG"]  = 0;
  AxisIdx["SIDE"]  = 1;
  AxisIdx["LIFT"]  = 2;
  AxisIdx["ROLL"]  = 3;
  AxisIdx["PITCH"] = 4;
  AxisIdx["YAW"]   = 5;

  Coeff = new CoeffArray[6];

  impending_stall = stall_hyst = 0.0;
  alphaclmin = alphaclmax = 0.0;
  alphahystmin = alphahystmax = 0.0;
  clsq = lod = 0.0;
  alphaw = 0.0;
  bi2vel = ci2vel = 0.0;
  bind();

  Debug(0);
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

FGAerodynamics::~FGAerodynamics()
{
  unsigned int i,j;

  unbind();

  for (i=0; i<6; i++) {
    for (j=0; j<Coeff[i].size(); j++) {
      delete Coeff[i][j];
    }
  }
  delete[] Coeff;

  Debug(1);
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

bool FGAerodynamics::Run(void)
{
  unsigned int axis_ctr,ctr;
  double alpha, twovel;

  if (!FGModel::Run()) {

    twovel = 2*Auxiliary->GetVt();
    if (twovel != 0) {
      bi2vel = Aircraft->GetWingSpan() / twovel;
      ci2vel = Aircraft->Getcbar() / twovel;
    }

    alphaw = Auxiliary->Getalpha() + Aircraft->GetWingIncidence();

    alpha = Auxiliary->Getalpha();

    if (alphaclmax != 0) {
      if (alpha > 0.85*alphaclmax) {
        impending_stall = 10*(alpha/alphaclmax - 0.85);
      } else {
        impending_stall = 0;
      }
    }

    if (alphahystmax != 0.0 && alphahystmin != 0.0) {
      if (alpha > alphahystmax) {
         stall_hyst = 1;
      } else if (alpha < alphahystmin) {
         stall_hyst = 0;
      }
    }

    vLastFs = vFs;
    vFs.InitMatrix();

    for (axis_ctr = 0; axis_ctr < 3; axis_ctr++) {
      for (ctr=0; ctr < Coeff[axis_ctr].size(); ctr++) {
        vFs(axis_ctr+1) += Coeff[axis_ctr][ctr]->TotalValue();
      }
    }

    //correct signs of drag and lift to wind axes convention
    //positive forward, right, down
    if ( Auxiliary->Getqbar() > 0) {
      clsq = vFs(eLift) / (Aircraft->GetWingArea()*Auxiliary->Getqbar());
      clsq *= clsq;
    }
    if ( vFs(eDrag)  > 0) {
      lod = vFs(eLift) / vFs(eDrag);
    }

    //correct signs of drag and lift to wind axes convention
    //positive forward, right, down
    vFs(eDrag)*=-1; vFs(eLift)*=-1;

    vForces = State->GetTs2b()*vFs;

    vDXYZcg = MassBalance->StructuralToBody(Aircraft->GetXYZrp());

    vMoments = vDXYZcg*vForces; // M = r X F

    for (axis_ctr = 0; axis_ctr < 3; axis_ctr++) {
      for (ctr = 0; ctr < Coeff[axis_ctr+3].size(); ctr++) {
        vMoments(axis_ctr+1) += Coeff[axis_ctr+3][ctr]->TotalValue();
      }
    }

    return false;
  } else {
    return true;
  }
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

bool FGAerodynamics::Load(FGConfigFile* AC_cfg)
{
  string parameter, axis, scratch;

  AC_cfg->GetNextConfigLine();

  while ((parameter = AC_cfg->GetValue()) != string("/AERODYNAMICS")) {
    if (parameter == "AXIS") {
      CoeffArray ca;
      axis = AC_cfg->GetValue("NAME");
      AC_cfg->GetNextConfigLine();
      while ((parameter = AC_cfg->GetValue()) != string("/AXIS")) {
        if ( parameter == "COEFFICIENT" ) {
          ca.push_back( new FGCoefficient(FDMExec) );
          ca.back()->Load(AC_cfg);
        } else if ( parameter == "GROUP" ) {
          ca.push_back( new FGFactorGroup(FDMExec) );
          ca.back()->Load(AC_cfg);
        }
      }
      Coeff[AxisIdx[axis]] = ca;
      AC_cfg->GetNextConfigLine();
    } else if (parameter == "AC_ALPHALIMITS") {
      *AC_cfg >> scratch >> alphaclmin >> alphaclmax;
      if (debug_lvl > 0) cout << "    Maximum Alpha: " << alphaclmax
                              << "    Minimum Alpha: " << alphaclmin
                              << endl;
    } else if (parameter == "AC_HYSTLIMITS") {
      *AC_cfg >> scratch >> alphahystmin >> alphahystmax;
      if (debug_lvl > 0) cout << "    Hysteresis Start: " << alphahystmax
                              << "    Hysteresis End: " << alphahystmin
                              << endl;
    }
  }

  bindModel();

  return true;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

string FGAerodynamics::GetCoefficientStrings(void)
{
  string CoeffStrings = "";
  bool firstime = true;
  unsigned int axis, sd;

  for (axis = 0; axis < 6; axis++) {
    for (sd = 0; sd < Coeff[axis].size(); sd++) {
      if (firstime) {
        firstime = false;
      } else {
        CoeffStrings += ", ";
      }
      CoeffStrings += Coeff[axis][sd]->GetCoefficientName();
    }
  }
  return CoeffStrings;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

string FGAerodynamics::GetCoefficientValues(void)
{
  string SDValues = "";
  bool firstime = true;

  for (unsigned int axis = 0; axis < 6; axis++) {
    for (unsigned int sd = 0; sd < Coeff[axis].size(); sd++) {
      if (firstime) {
        firstime = false;
      } else {
        SDValues += ", ";
      }
      SDValues += Coeff[axis][sd]->GetSDstring();
    }
  }

  return SDValues;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

void FGAerodynamics::bind(void)
{
  typedef double (FGAerodynamics::*PMF)(int) const;

  PropertyManager->Tie("forces/fbx-aero-lbs", this,1,
                       (PMF)&FGAerodynamics::GetForces);
  PropertyManager->Tie("forces/fby-aero-lbs", this,2,
                       (PMF)&FGAerodynamics::GetForces);
  PropertyManager->Tie("forces/fbz-aero-lbs", this,3,
                       (PMF)&FGAerodynamics::GetForces);
  PropertyManager->Tie("moments/l-aero-lbsft", this,1,
                       (PMF)&FGAerodynamics::GetMoments);
  PropertyManager->Tie("moments/m-aero-lbsft", this,2,
                       (PMF)&FGAerodynamics::GetMoments);
  PropertyManager->Tie("moments/n-aero-lbsft", this,3,
                       (PMF)&FGAerodynamics::GetMoments);
  PropertyManager->Tie("forces/fwx-aero-lbs", this,1,
                       (PMF)&FGAerodynamics::GetvFs);
  PropertyManager->Tie("forces/fwy-aero-lbs", this,2,
                       (PMF)&FGAerodynamics::GetvFs);
  PropertyManager->Tie("forces/fwz-aero-lbs", this,3,
                       (PMF)&FGAerodynamics::GetvFs);
  PropertyManager->Tie("forces/lod-norm", this,
                       &FGAerodynamics::GetLoD);
  PropertyManager->Tie("aero/cl-squared-norm", this,
                       &FGAerodynamics::GetClSquared);
  PropertyManager->Tie("aero/alpha-max-deg", this,
                       &FGAerodynamics::GetAlphaCLMax,
                       &FGAerodynamics::SetAlphaCLMax,
                       true);
  PropertyManager->Tie("aero/alpha-min-deg", this,
                       &FGAerodynamics::GetAlphaCLMin,
                       &FGAerodynamics::SetAlphaCLMin,
                       true);
  PropertyManager->Tie("aero/bi2vel", this,
                       &FGAerodynamics::GetBI2Vel);
  PropertyManager->Tie("aero/ci2vel", this,
                       &FGAerodynamics::GetCI2Vel);
  PropertyManager->Tie("aero/alpha-wing-rad", this,
                       &FGAerodynamics::GetAlphaW);
  PropertyManager->Tie("systems/stall-warn-norm", this,
                        &FGAerodynamics::GetStallWarn);
  PropertyManager->Tie("aero/stall-hyst-norm", this,
                        &FGAerodynamics::GetHysteresisParm);
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

void FGAerodynamics::bindModel(void)
{
  unsigned i,j;
  FGPropertyManager* node;
  string axis_node_name;
  node = PropertyManager->GetNode("aero/buildup",true);
  for (i=0;i<NAxes;i++) {
     node = node->GetNode( string(AxisNames[i]),true );
     for (j=0; j < Coeff[i].size(); j++) {
       Coeff[i][j]->bind(node);
     }
     node = (FGPropertyManager*)node->getParent();
  }
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

void FGAerodynamics::unbind(void)
{
  unsigned i,j;

  PropertyManager->Untie("forces/fbx-aero-lbs");
  PropertyManager->Untie("forces/fby-aero-lbs");
  PropertyManager->Untie("forces/fbz-aero-lbs");
  PropertyManager->Untie("moments/l-aero-lbsft");
  PropertyManager->Untie("moments/m-aero-lbsft");
  PropertyManager->Untie("moments/n-aero-lbsft");
  PropertyManager->Untie("forces/fwx-aero-lbs");
  PropertyManager->Untie("forces/fwy-aero-lbs");
  PropertyManager->Untie("forces/fwz-aero-lbs");
  PropertyManager->Untie("forces/lod-norm");
  PropertyManager->Untie("aero/cl-squared-norm");
  PropertyManager->Untie("aero/alpha-max-deg");
  PropertyManager->Untie("aero/alpha-min-deg");
  PropertyManager->Untie("aero/bi2vel");
  PropertyManager->Untie("aero/ci2vel");
  PropertyManager->Untie("aero/alpha-wing-rad");
  PropertyManager->Untie("aero/stall-hyst-norm");
  PropertyManager->Untie("systems/stall-warn-norm");

  for ( i=0; i<NAxes; i++ ) {
     for ( j=0; j < Coeff[i].size(); j++ ) {
       Coeff[i][j]->unbind();

     }
  }
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//    The bitmasked value choices are as follows:
//    unset: In this case (the default) JSBSim would only print
//       out the normally expected messages, essentially echoing
//       the config files as they are read. If the environment
//       variable is not set, debug_lvl is set to 1 internally
//    0: This requests JSBSim not to output any messages
//       whatsoever.
//    1: This value explicity requests the normal JSBSim
//       startup messages
//    2: This value asks for a message to be printed out when
//       a class is instantiated
//    4: When this value is set, a message is displayed when a
//       FGModel object executes its Run() method
//    8: When this value is set, various runtime state variables
//       are printed out periodically
//    16: When set various parameters are sanity checked and
//       a message is printed out when they go out of bounds

void FGAerodynamics::Debug(int from)
{
  if (debug_lvl <= 0) return;

  if (debug_lvl & 1) { // Standard console startup message output
    if (from == 0) { // Constructor

    }
  }
  if (debug_lvl & 2 ) { // Instantiation/Destruction notification
    if (from == 0) cout << "Instantiated: FGAerodynamics" << endl;
    if (from == 1) cout << "Destroyed:    FGAerodynamics" << endl;
  }
  if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects
  }
  if (debug_lvl & 8 ) { // Runtime state variables
  }
  if (debug_lvl & 16) { // Sanity checking
  }
  if (debug_lvl & 64) {
    if (from == 0) { // Constructor
      cout << IdSrc << endl;
      cout << IdHdr << endl;
    }
  }
}

} // namespace JSBSim
<commit_msg>Condensed the three EOM classes into one, FGPropagate. Changed references in other classes to refer to this new class.<commit_after>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

 Module:       FGAerodynamics.cpp
 Author:       Jon S. Berndt
 Date started: 09/13/00
 Purpose:      Encapsulates the aerodynamic forces (gear and collision)

 ------------- Copyright (C) 2000  Jon S. Berndt (jsb@hal-pc.org) -------------

 This program is free software; you can redistribute it and/or modify it under
 the terms of the GNU General Public License as published by the Free Software
 Foundation; either version 2 of the License, or (at your option) any later
 version.

 This program is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 details.

 You should have received a copy of the GNU General Public License along with
 this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 Place - Suite 330, Boston, MA  02111-1307, USA.

 Further information about the GNU General Public License can also be found on
 the world wide web at http://www.gnu.org.

FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------

HISTORY
--------------------------------------------------------------------------------
09/13/00   JSB   Created
04/22/01   JSB   Moved code into here from FGAircraft

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/

#include "FGAerodynamics.h"
#include "FGPropagate.h"
#include "FGAircraft.h"
#include "FGState.h"
#include "FGMassBalance.h"
#include "FGFactorGroup.h"
#include "FGPropertyManager.h"

namespace JSBSim {

static const char *IdSrc = "$Id: FGAerodynamics.cpp,v 1.49 2004/04/17 21:16:19 jberndt Exp $";
static const char *IdHdr = ID_AERODYNAMICS;

const unsigned NAxes=6;
const char* AxisNames[] = { "drag", "side-force", "lift", "rolling-moment",
                            "pitching-moment","yawing-moment" };

/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/

FGAerodynamics::FGAerodynamics(FGFDMExec* FDMExec) : FGModel(FDMExec)
{
  Name = "FGAerodynamics";

  AxisIdx["DRAG"]  = 0;
  AxisIdx["SIDE"]  = 1;
  AxisIdx["LIFT"]  = 2;
  AxisIdx["ROLL"]  = 3;
  AxisIdx["PITCH"] = 4;
  AxisIdx["YAW"]   = 5;

  Coeff = new CoeffArray[6];

  impending_stall = stall_hyst = 0.0;
  alphaclmin = alphaclmax = 0.0;
  alphahystmin = alphahystmax = 0.0;
  clsq = lod = 0.0;
  alphaw = 0.0;
  bi2vel = ci2vel = 0.0;
  bind();

  Debug(0);
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

FGAerodynamics::~FGAerodynamics()
{
  unsigned int i,j;

  unbind();

  for (i=0; i<6; i++) {
    for (j=0; j<Coeff[i].size(); j++) {
      delete Coeff[i][j];
    }
  }
  delete[] Coeff;

  Debug(1);
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

bool FGAerodynamics::Run(void)
{
  unsigned int axis_ctr,ctr;
  double alpha, twovel;

  if (!FGModel::Run()) {

    twovel = 2*Auxiliary->GetVt();
    if (twovel != 0) {
      bi2vel = Aircraft->GetWingSpan() / twovel;
      ci2vel = Aircraft->Getcbar() / twovel;
    }

    alphaw = Auxiliary->Getalpha() + Aircraft->GetWingIncidence();

    alpha = Auxiliary->Getalpha();

    if (alphaclmax != 0) {
      if (alpha > 0.85*alphaclmax) {
        impending_stall = 10*(alpha/alphaclmax - 0.85);
      } else {
        impending_stall = 0;
      }
    }

    if (alphahystmax != 0.0 && alphahystmin != 0.0) {
      if (alpha > alphahystmax) {
         stall_hyst = 1;
      } else if (alpha < alphahystmin) {
         stall_hyst = 0;
      }
    }

    vLastFs = vFs;
    vFs.InitMatrix();

    for (axis_ctr = 0; axis_ctr < 3; axis_ctr++) {
      for (ctr=0; ctr < Coeff[axis_ctr].size(); ctr++) {
        vFs(axis_ctr+1) += Coeff[axis_ctr][ctr]->TotalValue();
      }
    }

    //correct signs of drag and lift to wind axes convention
    //positive forward, right, down
    if ( Auxiliary->Getqbar() > 0) {
      clsq = vFs(eLift) / (Aircraft->GetWingArea()*Auxiliary->Getqbar());
      clsq *= clsq;
    }
    if ( vFs(eDrag)  > 0) {
      lod = vFs(eLift) / vFs(eDrag);
    }

    //correct signs of drag and lift to wind axes convention
    //positive forward, right, down
    vFs(eDrag)*=-1; vFs(eLift)*=-1;

    vForces = State->GetTs2b()*vFs;

    vDXYZcg = MassBalance->StructuralToBody(Aircraft->GetXYZrp());

    vMoments = vDXYZcg*vForces; // M = r X F

    for (axis_ctr = 0; axis_ctr < 3; axis_ctr++) {
      for (ctr = 0; ctr < Coeff[axis_ctr+3].size(); ctr++) {
        vMoments(axis_ctr+1) += Coeff[axis_ctr+3][ctr]->TotalValue();
      }
    }

    return false;
  } else {
    return true;
  }
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

bool FGAerodynamics::Load(FGConfigFile* AC_cfg)
{
  string parameter, axis, scratch;

  AC_cfg->GetNextConfigLine();

  while ((parameter = AC_cfg->GetValue()) != string("/AERODYNAMICS")) {
    if (parameter == "AXIS") {
      CoeffArray ca;
      axis = AC_cfg->GetValue("NAME");
      AC_cfg->GetNextConfigLine();
      while ((parameter = AC_cfg->GetValue()) != string("/AXIS")) {
        if ( parameter == "COEFFICIENT" ) {
          ca.push_back( new FGCoefficient(FDMExec) );
          ca.back()->Load(AC_cfg);
        } else if ( parameter == "GROUP" ) {
          ca.push_back( new FGFactorGroup(FDMExec) );
          ca.back()->Load(AC_cfg);
        }
      }
      Coeff[AxisIdx[axis]] = ca;
      AC_cfg->GetNextConfigLine();
    } else if (parameter == "AC_ALPHALIMITS") {
      *AC_cfg >> scratch >> alphaclmin >> alphaclmax;
      if (debug_lvl > 0) cout << "    Maximum Alpha: " << alphaclmax
                              << "    Minimum Alpha: " << alphaclmin
                              << endl;
    } else if (parameter == "AC_HYSTLIMITS") {
      *AC_cfg >> scratch >> alphahystmin >> alphahystmax;
      if (debug_lvl > 0) cout << "    Hysteresis Start: " << alphahystmax
                              << "    Hysteresis End: " << alphahystmin
                              << endl;
    }
  }

  bindModel();

  return true;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

string FGAerodynamics::GetCoefficientStrings(void)
{
  string CoeffStrings = "";
  bool firstime = true;
  unsigned int axis, sd;

  for (axis = 0; axis < 6; axis++) {
    for (sd = 0; sd < Coeff[axis].size(); sd++) {
      if (firstime) {
        firstime = false;
      } else {
        CoeffStrings += ", ";
      }
      CoeffStrings += Coeff[axis][sd]->GetCoefficientName();
    }
  }
  return CoeffStrings;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

string FGAerodynamics::GetCoefficientValues(void)
{
  string SDValues = "";
  bool firstime = true;

  for (unsigned int axis = 0; axis < 6; axis++) {
    for (unsigned int sd = 0; sd < Coeff[axis].size(); sd++) {
      if (firstime) {
        firstime = false;
      } else {
        SDValues += ", ";
      }
      SDValues += Coeff[axis][sd]->GetSDstring();
    }
  }

  return SDValues;
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

void FGAerodynamics::bind(void)
{
  typedef double (FGAerodynamics::*PMF)(int) const;

  PropertyManager->Tie("forces/fbx-aero-lbs", this,1,
                       (PMF)&FGAerodynamics::GetForces);
  PropertyManager->Tie("forces/fby-aero-lbs", this,2,
                       (PMF)&FGAerodynamics::GetForces);
  PropertyManager->Tie("forces/fbz-aero-lbs", this,3,
                       (PMF)&FGAerodynamics::GetForces);
  PropertyManager->Tie("moments/l-aero-lbsft", this,1,
                       (PMF)&FGAerodynamics::GetMoments);
  PropertyManager->Tie("moments/m-aero-lbsft", this,2,
                       (PMF)&FGAerodynamics::GetMoments);
  PropertyManager->Tie("moments/n-aero-lbsft", this,3,
                       (PMF)&FGAerodynamics::GetMoments);
  PropertyManager->Tie("forces/fwx-aero-lbs", this,1,
                       (PMF)&FGAerodynamics::GetvFs);
  PropertyManager->Tie("forces/fwy-aero-lbs", this,2,
                       (PMF)&FGAerodynamics::GetvFs);
  PropertyManager->Tie("forces/fwz-aero-lbs", this,3,
                       (PMF)&FGAerodynamics::GetvFs);
  PropertyManager->Tie("forces/lod-norm", this,
                       &FGAerodynamics::GetLoD);
  PropertyManager->Tie("aero/cl-squared-norm", this,
                       &FGAerodynamics::GetClSquared);
  PropertyManager->Tie("aero/alpha-max-deg", this,
                       &FGAerodynamics::GetAlphaCLMax,
                       &FGAerodynamics::SetAlphaCLMax,
                       true);
  PropertyManager->Tie("aero/alpha-min-deg", this,
                       &FGAerodynamics::GetAlphaCLMin,
                       &FGAerodynamics::SetAlphaCLMin,
                       true);
  PropertyManager->Tie("aero/bi2vel", this,
                       &FGAerodynamics::GetBI2Vel);
  PropertyManager->Tie("aero/ci2vel", this,
                       &FGAerodynamics::GetCI2Vel);
  PropertyManager->Tie("aero/alpha-wing-rad", this,
                       &FGAerodynamics::GetAlphaW);
  PropertyManager->Tie("systems/stall-warn-norm", this,
                        &FGAerodynamics::GetStallWarn);
  PropertyManager->Tie("aero/stall-hyst-norm", this,
                        &FGAerodynamics::GetHysteresisParm);
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

void FGAerodynamics::bindModel(void)
{
  unsigned i,j;
  FGPropertyManager* node;
  string axis_node_name;
  node = PropertyManager->GetNode("aero/buildup",true);
  for (i=0;i<NAxes;i++) {
     node = node->GetNode( string(AxisNames[i]),true );
     for (j=0; j < Coeff[i].size(); j++) {
       Coeff[i][j]->bind(node);
     }
     node = (FGPropertyManager*)node->getParent();
  }
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

void FGAerodynamics::unbind(void)
{
  unsigned i,j;

  PropertyManager->Untie("forces/fbx-aero-lbs");
  PropertyManager->Untie("forces/fby-aero-lbs");
  PropertyManager->Untie("forces/fbz-aero-lbs");
  PropertyManager->Untie("moments/l-aero-lbsft");
  PropertyManager->Untie("moments/m-aero-lbsft");
  PropertyManager->Untie("moments/n-aero-lbsft");
  PropertyManager->Untie("forces/fwx-aero-lbs");
  PropertyManager->Untie("forces/fwy-aero-lbs");
  PropertyManager->Untie("forces/fwz-aero-lbs");
  PropertyManager->Untie("forces/lod-norm");
  PropertyManager->Untie("aero/cl-squared-norm");
  PropertyManager->Untie("aero/alpha-max-deg");
  PropertyManager->Untie("aero/alpha-min-deg");
  PropertyManager->Untie("aero/bi2vel");
  PropertyManager->Untie("aero/ci2vel");
  PropertyManager->Untie("aero/alpha-wing-rad");
  PropertyManager->Untie("aero/stall-hyst-norm");
  PropertyManager->Untie("systems/stall-warn-norm");

  for ( i=0; i<NAxes; i++ ) {
     for ( j=0; j < Coeff[i].size(); j++ ) {
       Coeff[i][j]->unbind();

     }
  }
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//    The bitmasked value choices are as follows:
//    unset: In this case (the default) JSBSim would only print
//       out the normally expected messages, essentially echoing
//       the config files as they are read. If the environment
//       variable is not set, debug_lvl is set to 1 internally
//    0: This requests JSBSim not to output any messages
//       whatsoever.
//    1: This value explicity requests the normal JSBSim
//       startup messages
//    2: This value asks for a message to be printed out when
//       a class is instantiated
//    4: When this value is set, a message is displayed when a
//       FGModel object executes its Run() method
//    8: When this value is set, various runtime state variables
//       are printed out periodically
//    16: When set various parameters are sanity checked and
//       a message is printed out when they go out of bounds

void FGAerodynamics::Debug(int from)
{
  if (debug_lvl <= 0) return;

  if (debug_lvl & 1) { // Standard console startup message output
    if (from == 0) { // Constructor

    }
  }
  if (debug_lvl & 2 ) { // Instantiation/Destruction notification
    if (from == 0) cout << "Instantiated: FGAerodynamics" << endl;
    if (from == 1) cout << "Destroyed:    FGAerodynamics" << endl;
  }
  if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects
  }
  if (debug_lvl & 8 ) { // Runtime state variables
  }
  if (debug_lvl & 16) { // Sanity checking
  }
  if (debug_lvl & 64) {
    if (from == 0) { // Constructor
      cout << IdSrc << endl;
      cout << IdHdr << endl;
    }
  }
}

} // namespace JSBSim
<|endoftext|>


<commit_before>#include <iostream>

#include <chirp/chirp.hpp>
#include <thread>
#include <iostream>

///
/// Main entry point
///
int main() {
	try {
		chirp::audio_platform platform;
		auto device = platform.default_output_device();
		auto audio = device.create_audio( {44100, chirp::sixteen_bits_little_endian_stereo} );

		audio.play_async(
			[]( chirp::duration_type play_time, chirp::sample_request const& request ) {
				play_time;
				request;
			});

		std::this_thread::sleep_for( std::chrono::milliseconds(1000) );
	}
	catch( std::exception& e ) {
		std::cerr << "Exception:\n"
		          << "\tType:   " << typeid(e).name() << "\n"
		          << "\tMessage:" << e.what() << std::endl;
	}
	return 0;
}<commit_msg>Implement the sinewave example<commit_after>#include <iostream>

#include <chirp/chirp.hpp>
#include <thread>
#include <iostream>
#include <limits>
#include <cmath>

/// Double PI (360 degrees in radians)
const float two_pi = 2.0f * 3.14159265358979f;
/// Default frequency, if none is specified on the command line
const int default_frequency = 440;
/// Default duration, if none is specified on the command line
const auto default_duration = std::chrono::milliseconds{3000};

/// Command line arguments
class arguments
{
	public:
		/// Parse command line
		arguments( int argc, char const* argv[] ) :
			m_frequency( default_frequency ),
			m_duration( default_duration )
		{
			if( argc > 1 ) {
				m_frequency = std::atoi( argv[1] );
			}
			if( argc > 2 ) {
				m_duration = std::chrono::milliseconds{ std::atoi( argv[2] ) };
			}
		}

		/// @returns Frequency
		int frequency() const {
			return m_frequency;
		}

		/// @returns Duration
		std::chrono::milliseconds duration() const {
			return m_duration;
		}

	private:
		/// Sine wave frequency (in hertz)
		int m_frequency;
		/// Duration to play the generated sine wave
		std::chrono::milliseconds m_duration;
};

/// Generate a sample of a sinewave
/// @param frequency   The frequency of the sinewave to generate (in hertz)
/// @param time        The samples location on the time axis of sinewave
std::int16_t sinewave_sample( int frequency, chirp::duration_type time )
{
	auto seconds = std::chrono::duration_cast< std::chrono::duration<float> >(time).count();
	auto value = std::sinf( frequency * two_pi * seconds );
	return static_cast<std::int16_t>( std::numeric_limits<std::int16_t>::max() * value );
}

///
/// Main entry point
///
int main( int argc, char const* argv[] ) {
	try {
		arguments args{ argc, argv };

		/// Let's create the autio platform, device and audio instance to use
		chirp::audio_platform platform;
		auto device = platform.default_output_device();
		auto audio = device.create_audio( {44100, chirp::sixteen_bits_little_endian_mono} );

		// Let's start playing (and generating) the audio
		audio.play_async(
			[&args]( chirp::duration_type play_time, chirp::sample_request const& request ) {
				auto* ptr = static_cast<std::int16_t*>(request.buffer_start());
				for( std::uint32_t i=0; i<request.frames(); ++i ) {
					*(ptr++) = sinewave_sample( args.frequency(), play_time + (i*request.format().duration_per_frame() ) );
				}
			});

		std::this_thread::sleep_for( args.duration() );
	}
	catch( std::exception& e ) {
		std::cerr << "Exception:\n"
		          << "\tType:   " << typeid(e).name() << "\n"
		          << "\tMessage:" << e.what() << std::endl;
	}
	return 0;
}<|endoftext|>


<commit_before>//
//  KinematicsSimulator.cpp
//  GPcode01_01_xcode
//
//  Created by young-min kang on 3/27/15.
//  Copyright (c) 2015 young-min kang. All rights reserved.
//

#include "KinematicsSimulator.h"

CKinematicSimulator::CKinematicSimulator() : CSimulator() {}

void CKinematicSimulator::init() {
	initialLoc.set(0,1,0);
	initialVel.set(0,3,0);
	gravity.set(0.0, -9.8, 0.0);
	currentLoc = initialLoc;
	particle.setPosition(currentLoc[0], currentLoc[1], currentLoc[2]);
	particle.setRadius(0.1);
}

void CKinematicSimulator::doBeforeSimulation(double dt, double currentTime) {

}

void CKinematicSimulator::doSimulation(double dt, double currentTime) {
    currentLoc = initialLoc
		+ currentTime*initialVel
		+ (0.5 * currentTime * currentTime)  * gravity ;
    particle.setPosition(currentLoc[0], currentLoc[1], currentLoc[2]);
    particle.drawWithGL();
}

void CKinematicSimulator::doAfterSimulation(double dt, double currentTime) {

}<commit_msg>Kinematics Run<commit_after>//
//  KinematicsSimulator.cpp
//  GPcode01_01_xcode
//
//  Created by young-min kang on 3/27/15.
//  Copyright (c) 2015 young-min kang. All rights reserved.
//

#include "KinematicsSimulator.h"

CKinematicSimulator::CKinematicSimulator() : CSimulator() {}

void CKinematicSimulator::init() {
	initialLoc.set(0,1,0);
	initialVel.set(0,3,0);
	gravity.set(0.0, -9.8, 0.0);
	currentLoc = initialLoc;
	particle.setPosition(currentLoc[0], currentLoc[1], currentLoc[2]);
	particle.setRadius(0.1);
}

void CKinematicSimulator::doBeforeSimulation(double dt, double currentTime) {

}

void CKinematicSimulator::doSimulation(double dt, double currentTime) {
    currentLoc = initialLoc
		+ currentTime*initialVel
		+ (0.5 * currentTime * currentTime)  * gravity ;

    particle.setPosition(currentLoc[0], currentLoc[1], currentLoc[2]);
    particle.drawWithGL();
}

void CKinematicSimulator::doAfterSimulation(double dt, double currentTime) {

}<|endoftext|>


<commit_before>#include <iostream>
#include <typeinfo>

#include <map>

using std::cout;
using std::endl;

#include "viennagrid/forwards.hpp"

#include "viennagrid/storage/view.hpp"
#include "viennagrid/storage/container_collection.hpp"
#include "viennagrid/storage/inserter.hpp"
#include "viennagrid/storage/id_generator.hpp"
#include "viennagrid/storage/hidden_key_map.hpp"
#include "viennagrid/storage/range.hpp"

#include "viennagrid/topology/vertex.hpp"
#include "viennagrid/topology/line.hpp"
#include "viennagrid/topology/simplex.hpp"
#include "viennagrid/topology/plc.hpp"

#include "viennagrid/element/element_key.hpp"
#include "viennagrid/element/element_orientation.hpp"
#include "viennagrid/element/element_view.hpp"

#include "viennagrid/point.hpp"

#include "viennagrid/config/element_config.hpp"
#include "viennagrid/config/mesh_config.hpp"
#include "viennagrid/config/default_configs.hpp"

#include "viennagrid/mesh/mesh.hpp"
#include "viennagrid/mesh/element_creation.hpp"

#include "viennagrid/io/tetgen_poly_reader.hpp"

int main()
{

  //
  // typedefing and instancing the mesh type
  //

  typedef viennagrid::plc_3d_mesh MeshType;
  MeshType mesh;

  //
  // typedefs for the element types
  //

  typedef viennagrid::result_of::point<MeshType>::type point_type;

  typedef viennagrid::result_of::element<MeshType, viennagrid::vertex_tag>::type vertex_type;
  typedef viennagrid::result_of::handle<MeshType, viennagrid::vertex_tag>::type vertex_handle_type;

  typedef viennagrid::result_of::element<MeshType, viennagrid::line_tag>::type line_type;
  typedef viennagrid::result_of::handle<MeshType, viennagrid::line_tag>::type line_handle_type;

  typedef viennagrid::result_of::element<MeshType, viennagrid::plc_tag>::type plc_type;
  typedef viennagrid::result_of::handle<MeshType, viennagrid::plc_tag>::type plc_handle_type;

  //
  // Reading the PLC mesh
  //

  viennagrid::io::tetgen_poly_reader reader;
  reader(mesh, "../data/test.poly");

  // querying the first PLC in the mesh
  plc_type & plc = viennagrid::elements<plc_type>(mesh)[0];

  // printing all vertices of the first PLC
  typedef viennagrid::result_of::element_range<plc_type, vertex_type>::type vertex_on_plc_range;
  typedef viennagrid::result_of::iterator<vertex_on_plc_range>::type vertex_on_plc_iterator;

  std::cout << "All vertices of the PLC" << std::endl;
  vertex_on_plc_range vertex_range = viennagrid::elements<vertex_type>( plc );
  for (vertex_on_plc_iterator it = vertex_range.begin(); it != vertex_range.end(); ++it)
      std::cout << *it << " " << viennagrid::point(mesh, *it) << std::endl;
  std::cout << std::endl;

  // printing all lines of the first PLC
  typedef viennagrid::result_of::element_range<plc_type, line_type>::type line_on_plc_range;
  typedef viennagrid::result_of::iterator<line_on_plc_range>::type line_on_plc_iterator;

  std::cout << "All lines of the PLC" << std::endl;
  line_on_plc_range line_range = viennagrid::elements<line_type>( plc );
  for (line_on_plc_iterator it = line_range.begin(); it != line_range.end(); ++it)
      std::cout << *it << std::endl;
  std::cout << std::endl;

  // printing all PLC of the mesh
  std::cout << "All PLCs of the mesh" << std::endl;
  typedef viennagrid::result_of::element_range< MeshType, plc_type >::type plc_range_type;
  plc_range_type plc_range = viennagrid::elements< plc_type >(mesh);
  for ( plc_range_type::iterator it = plc_range.begin(); it != plc_range.end(); ++it)
      std::cout << *it << std::endl;
  std::cout << std::endl;

  // printing all hole points of the first PLC
  std::cout << "All hole points of the plc" << std::endl;
  std::vector<point_type> & pts = plc.appendix();
  std::copy( pts.begin(), pts.end(), std::ostream_iterator<point_type>(std::cout, "\n") );

    return 0;
}
<commit_msg>Added license header to PLC tutorial.<commit_after>/* =======================================================================
   Copyright (c) 2011-2013, Institute for Microelectronics,
                            Institute for Analysis and Scientific Computing,
                            TU Wien.

                            -----------------
                     ViennaGrid - The Vienna Grid Library
                            -----------------

   License:      MIT (X11), see file LICENSE in the base directory
======================================================================= */

#include <iostream>
#include <typeinfo>

#include <map>

using std::cout;
using std::endl;

#include "viennagrid/forwards.hpp"

#include "viennagrid/storage/view.hpp"
#include "viennagrid/storage/container_collection.hpp"
#include "viennagrid/storage/inserter.hpp"
#include "viennagrid/storage/id_generator.hpp"
#include "viennagrid/storage/hidden_key_map.hpp"
#include "viennagrid/storage/range.hpp"

#include "viennagrid/topology/vertex.hpp"
#include "viennagrid/topology/line.hpp"
#include "viennagrid/topology/simplex.hpp"
#include "viennagrid/topology/plc.hpp"

#include "viennagrid/element/element_key.hpp"
#include "viennagrid/element/element_orientation.hpp"
#include "viennagrid/element/element_view.hpp"

#include "viennagrid/point.hpp"

#include "viennagrid/config/element_config.hpp"
#include "viennagrid/config/mesh_config.hpp"
#include "viennagrid/config/default_configs.hpp"

#include "viennagrid/mesh/mesh.hpp"
#include "viennagrid/mesh/element_creation.hpp"

#include "viennagrid/io/tetgen_poly_reader.hpp"

int main()
{

  //
  // typedefing and instancing the mesh type
  //

  typedef viennagrid::plc_3d_mesh MeshType;
  MeshType mesh;

  //
  // typedefs for the element types
  //

  typedef viennagrid::result_of::point<MeshType>::type point_type;

  typedef viennagrid::result_of::element<MeshType, viennagrid::vertex_tag>::type vertex_type;
  typedef viennagrid::result_of::handle<MeshType, viennagrid::vertex_tag>::type vertex_handle_type;

  typedef viennagrid::result_of::element<MeshType, viennagrid::line_tag>::type line_type;
  typedef viennagrid::result_of::handle<MeshType, viennagrid::line_tag>::type line_handle_type;

  typedef viennagrid::result_of::element<MeshType, viennagrid::plc_tag>::type plc_type;
  typedef viennagrid::result_of::handle<MeshType, viennagrid::plc_tag>::type plc_handle_type;

  //
  // Reading the PLC mesh
  //

  viennagrid::io::tetgen_poly_reader reader;
  reader(mesh, "../data/test.poly");

  // querying the first PLC in the mesh
  plc_type & plc = viennagrid::elements<plc_type>(mesh)[0];

  // printing all vertices of the first PLC
  typedef viennagrid::result_of::element_range<plc_type, vertex_type>::type vertex_on_plc_range;
  typedef viennagrid::result_of::iterator<vertex_on_plc_range>::type vertex_on_plc_iterator;

  std::cout << "All vertices of the PLC" << std::endl;
  vertex_on_plc_range vertex_range = viennagrid::elements<vertex_type>( plc );
  for (vertex_on_plc_iterator it = vertex_range.begin(); it != vertex_range.end(); ++it)
      std::cout << *it << " " << viennagrid::point(mesh, *it) << std::endl;
  std::cout << std::endl;

  // printing all lines of the first PLC
  typedef viennagrid::result_of::element_range<plc_type, line_type>::type line_on_plc_range;
  typedef viennagrid::result_of::iterator<line_on_plc_range>::type line_on_plc_iterator;

  std::cout << "All lines of the PLC" << std::endl;
  line_on_plc_range line_range = viennagrid::elements<line_type>( plc );
  for (line_on_plc_iterator it = line_range.begin(); it != line_range.end(); ++it)
      std::cout << *it << std::endl;
  std::cout << std::endl;

  // printing all PLC of the mesh
  std::cout << "All PLCs of the mesh" << std::endl;
  typedef viennagrid::result_of::element_range< MeshType, plc_type >::type plc_range_type;
  plc_range_type plc_range = viennagrid::elements< plc_type >(mesh);
  for ( plc_range_type::iterator it = plc_range.begin(); it != plc_range.end(); ++it)
      std::cout << *it << std::endl;
  std::cout << std::endl;

  // printing all hole points of the first PLC
  std::cout << "All hole points of the plc" << std::endl;
  std::vector<point_type> & pts = plc.appendix();
  std::copy( pts.begin(), pts.end(), std::ostream_iterator<point_type>(std::cout, "\n") );

    return 0;
}
<|endoftext|>