<commit_before>#include "KeyIDClient.h"
#include <cpprest/filestream.h>
#include <chrono>

using namespace std;
using namespace web;
using namespace web::http;
using namespace web::http::client;
using namespace concurrency::streams;

/// <summary>
/// KeyID services client.
/// </summary>
/// <param name="settings"> KeyID settings struct</param>
KeyIDClient::KeyIDClient(KeyIDSettings settings)
{
	this->settings = settings;
	this->service = make_shared<KeyIDService>(settings.url, settings.license, settings.timeout);
}

KeyIDClient::KeyIDClient()
{
	this->service = make_shared<KeyIDService>(settings.url, settings.license, settings.timeout);
}

/// <summary>
/// KeyID client destructor.
/// </summary>
KeyIDClient::~KeyIDClient()
{
}

const KeyIDSettings& KeyIDClient::GetSettings()
{
	return settings;
}

void KeyIDClient::SetSettings(KeyIDSettings settings)
{
	this->settings = settings;
}

/// <summary>
/// Saves a given KeyID profile entry.
/// </summary>
/// <param name="entityID">Profile name to save.</param>
/// <param name="tsData">Typing sample data to save.</param>
/// <param name="sessionID">Session identifier for logging purposes.</param>
/// <returns>JSON value (task)</returns>
pplx::task<web::json::value> KeyIDClient::SaveProfile(std::wstring entityID, std::wstring tsData, std::wstring sessionID)
{
	// try to save profile without a token
	return service->SaveProfile(entityID, tsData)
	.then([=](http_response response)
	{
		json::value data = ParseResponse(response);

		// token is required
		if (data[L"Error"].as_string() == L"New enrollment code required.")
		{
			// get a save token
			return service->SaveToken(entityID, tsData)
			.then([=](http_response response)
			{
				json::value data = ParseResponse(response);
				// try to save profile with a token
				return service->SaveProfile(entityID, tsData, data[L"Token"].as_string());
			})
			.then([=](http_response response)
			{
				json::value data = ParseResponse(response);
				//todo this isn't a task?
				return data;
			});
		}

		return pplx::task_from_result(data);
	});
}

/// <summary>
/// Removes a KeyID profile.
/// </summary>
/// <param name="entityID">Profile name to remove.</param>
/// <param name="tsData">Optional typing sample for removal authorization.</param>
/// <param name="sessionID">Session identifier for logging purposes.</param>
/// <returns>JSON value (task)</returns>
pplx::task<web::json::value> KeyIDClient::RemoveProfile(std::wstring entityID, std::wstring tsData, std::wstring sessionID)
{
	// get a removal token
	return service->RemoveToken(entityID, tsData)
	.then([=](http_response response)
	{
		json::value data = ParseResponse(response);

		// remove profile
		if (data.has_field(L"Token")) {
			return service->RemoveProfile(entityID, data[L"Token"].as_string())
				.then([=](http_response response)
			{
				json::value data = ParseResponse(response);
				return pplx::task_from_result(data);
			});
		}
		else
			return pplx::task_from_result(data);
	});
}

/// <summary>
/// Evaluates a KeyID profile.
/// </summary>
/// <param name="entityID">Profile name to evaluate.</param>
/// <param name="tsData">Typing sample to evaluate against profile.</param>
/// <param name="sessionID">Session identifier for logging purposes.</param>
/// <returns></returns>
pplx::task<web::json::value> KeyIDClient::EvaluateProfile(std::wstring entityID, std::wstring tsData, std::wstring sessionID)
{
	long long nonceTime = DotNetTicks();

	return service->Nonce(nonceTime)
	.then([=](http_response response)
	{
		return service->EvaluateSample(entityID, tsData, response.extract_string().get());
	})
	.then([=](http_response response)
	{
		json::value data = ParseResponse(response);

		// check for error before continuing
		// todo check "error" exists first?
		if (data[L"Error"].as_string() == L"")
		{
			// coerce string to boolean
			data[L"Match"] = json::value::boolean(AlphaToBool(data[L"Match"].as_string()));
			data[L"IsReady"] = json::value::boolean(AlphaToBool(data[L"IsReady"].as_string()));

			// set match to true and return early if using passive validation
			if (settings.passiveValidation)
			{
				data[L"Match"] = json::value::boolean(true);
				return data;
			}
			// evaluate match value using custom threshold if enabled
			else if (settings.customThreshold)
			{
				data[L"Match"] = json::value::boolean(EvalThreshold(data[L"Confidence"].as_double(), data[L"Fidelity"].as_double()));
			}
		}

		return data;
	});
}

/// <summary>
/// Evaluates a given profile and adds typing sample to profile.
/// </summary>
/// <param name="entityID">Profile to evaluate.</param>
/// <param name="tsData">Typing sample to evaluate and save.</param>
/// <param name="sessionID">Session identifier for logging purposes.</param>
/// <returns></returns>
pplx::task<web::json::value> KeyIDClient::LoginPassiveEnrollment(std::wstring entityID, std::wstring tsData, std::wstring sessionID)
{
	return EvaluateProfile(entityID, tsData, sessionID)
	.then([=](json::value data)
	{
		// in base case that no profile exists save profile async and return early
		if (data[L"Error"].as_string() == L"EntityID does not exist." ||
			data[L"Error"].as_string() == L"The profile has too little data for a valid evaluation." ||
			data[L"Error"].as_string() == L"The entry varied so much from the model, no evaluation is possible.")
		{
			return SaveProfile(entityID, tsData, sessionID)
			.then([=](json::value saveData)
			{
				json::value evalData = data;
				evalData[L"Match"] = json::value::boolean(true);
				evalData[L"IsReady"] = json::value::boolean(false);
				evalData[L"Confidence"] = json::value::number(100.0);
				evalData[L"Fidelity"] = json::value::number(100.0);
				return evalData;
			});
		}

		// if profile is not ready save profile async and return early
		if (data[L"Error"].as_string() == L"" && data[L"IsReady"].as_bool() == false)
		{
			return SaveProfile(entityID, tsData, sessionID)
			.then([=](json::value saveData)
			{
				json::value evalData = data;
				evalData[L"Match"] = json::value::boolean(true);
				return evalData;
			});
		}

		return pplx::task_from_result(data);
	});
}

/// <summary>
/// Returns profile information without modifying the profile.
/// </summary>
/// <param name="entityID">Profile to inspect.</param>
/// <returns></returns>
pplx::task<web::json::value> KeyIDClient::GetProfileInfo(std::wstring entityID)
{
	return service->GetProfileInfo(entityID)
	.then([=](http_response response)
	{
		json::value data = ParseGetProfileResponse(response);
		return pplx::task_from_result(data);
	});
}

/// <summary>
/// Compares a given confidence and fidelity against pre-determined thresholds.
/// </summary>
/// <param name="confidence">KeyID evaluation confidence.</param>
/// <param name="fidelity">KeyID evaluation fidelity.</param>
/// <returns>Whether confidence and fidelity meet thresholds.</returns>
bool KeyIDClient::EvalThreshold(double confidence, double fidelity)
{
	if (confidence >= settings.thresholdConfidence &&
		fidelity >= settings.thresholdFidelity)
	{
		return true;
	}
	else
	{
		return false;
	}
}

/// <summary>
/// Converts a string value like 'true' to a boolean object.
/// </summary>
/// <param name="input">String to convert to boolean.</param>
/// <returns>Boolean value.</returns>
bool KeyIDClient::AlphaToBool(std::wstring input)
{
	std::transform(input.begin(), input.end(), input.begin(), ::toupper);

	if (input == L"TRUE")
		return true;
	else
		return false;
}

/// <summary>
/// Converts current time to Microsoft .Net 'ticks'. A tick is 100 nanoseconds.
/// </summary>
/// <returns>Current time in 'ticks'.</returns>
long long KeyIDClient::DotNetTicks()
{
	const long long EPOCH_OFFSET = 621355968000000000;
	const long MS_PER_TICK = 10000;
	long long ms_since_epoch = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
	long long ticks = ((ms_since_epoch * MS_PER_TICK) + EPOCH_OFFSET);
	return ticks;
}

/// <summary>
/// Extracts a JSON value from a http_response
/// </summary>
/// <param name="response">HTTP response</param>
/// <returns>JSON value</returns>
web::json::value KeyIDClient::ParseResponse(const web::http::http_response& response)
{
	if (response.status_code() == status_codes::OK)
	{
		return response.extract_json().get();
	}
	else
	{
		throw http_exception(L"HTTP response not 200 OK.");
	}
}

/// <summary>
/// Extracts a JSON value from a http_response
/// </summary>
/// <param name="response">HTTP response</param>
/// <returns>JSON value</returns>
web::json::value KeyIDClient::ParseGetProfileResponse(const web::http::http_response& response)
{
	if (response.status_code() == status_codes::OK)
	{
		json::value data = response.extract_json().get();
		if (data.is_array())
			return data[0];
		else
			return data;
	}
	else
	{
		throw http_exception(L"HTTP response not 200 OK.");
	}
}<commit_msg>Add invalid license handling.<commit_after>#include "KeyIDClient.h"
#include <cpprest/filestream.h>
#include <chrono>

using namespace std;
using namespace web;
using namespace web::http;
using namespace web::http::client;
using namespace concurrency::streams;

/// <summary>
/// KeyID services client.
/// </summary>
/// <param name="settings"> KeyID settings struct</param>
KeyIDClient::KeyIDClient(KeyIDSettings settings)
{
	this->settings = settings;
	this->service = make_shared<KeyIDService>(settings.url, settings.license, settings.timeout);
}

KeyIDClient::KeyIDClient()
{
	this->service = make_shared<KeyIDService>(settings.url, settings.license, settings.timeout);
}

/// <summary>
/// KeyID client destructor.
/// </summary>
KeyIDClient::~KeyIDClient()
{
}

const KeyIDSettings& KeyIDClient::GetSettings()
{
	return settings;
}

void KeyIDClient::SetSettings(KeyIDSettings settings)
{
	this->settings = settings;
}

/// <summary>
/// Saves a given KeyID profile entry.
/// </summary>
/// <param name="entityID">Profile name to save.</param>
/// <param name="tsData">Typing sample data to save.</param>
/// <param name="sessionID">Session identifier for logging purposes.</param>
/// <returns>JSON value (task)</returns>
pplx::task<web::json::value> KeyIDClient::SaveProfile(std::wstring entityID, std::wstring tsData, std::wstring sessionID)
{
	// try to save profile without a token
	return service->SaveProfile(entityID, tsData)
	.then([=](http_response response)
	{
		json::value data = ParseResponse(response);

		if (data[L"Error"].as_string() == L"Invalid license key.")
			throw exception("Invalid license key.");

		// token is required
		if (data[L"Error"].as_string() == L"New enrollment code required.")
		{
			// get a save token
			return service->SaveToken(entityID, tsData)
			.then([=](http_response response)
			{
				json::value data = ParseResponse(response);
				// try to save profile with a token
				return service->SaveProfile(entityID, tsData, data[L"Token"].as_string());
			})
			.then([=](http_response response)
			{
				json::value data = ParseResponse(response);
				//todo this isn't a task?
				return data;
			});
		}

		return pplx::task_from_result(data);
	});
}

/// <summary>
/// Removes a KeyID profile.
/// </summary>
/// <param name="entityID">Profile name to remove.</param>
/// <param name="tsData">Optional typing sample for removal authorization.</param>
/// <param name="sessionID">Session identifier for logging purposes.</param>
/// <returns>JSON value (task)</returns>
pplx::task<web::json::value> KeyIDClient::RemoveProfile(std::wstring entityID, std::wstring tsData, std::wstring sessionID)
{
	// get a removal token
	return service->RemoveToken(entityID, tsData)
	.then([=](http_response response)
	{
		json::value data = ParseResponse(response);

		if (data[L"Error"].as_string() == L"Invalid license key.")
			throw exception("Invalid license key.");

		// remove profile
		if (data.has_field(L"Token")) {
			return service->RemoveProfile(entityID, data[L"Token"].as_string())
				.then([=](http_response response)
			{
				json::value data = ParseResponse(response);
				return pplx::task_from_result(data);
			});
		}
		else
			return pplx::task_from_result(data);
	});
}

/// <summary>
/// Evaluates a KeyID profile.
/// </summary>
/// <param name="entityID">Profile name to evaluate.</param>
/// <param name="tsData">Typing sample to evaluate against profile.</param>
/// <param name="sessionID">Session identifier for logging purposes.</param>
/// <returns></returns>
pplx::task<web::json::value> KeyIDClient::EvaluateProfile(std::wstring entityID, std::wstring tsData, std::wstring sessionID)
{
	long long nonceTime = DotNetTicks();

	return service->Nonce(nonceTime)
	.then([=](http_response response)
	{
		return service->EvaluateSample(entityID, tsData, response.extract_string().get());
	})
	.then([=](http_response response)
	{
		json::value data = ParseResponse(response);

		if (data[L"Error"].as_string() == L"Invalid license key.")
			throw exception("Invalid license key.");

		// check for error before continuing
		// todo check "error" exists first?
		if (data[L"Error"].as_string() == L"")
		{
			// coerce string to boolean
			data[L"Match"] = json::value::boolean(AlphaToBool(data[L"Match"].as_string()));
			data[L"IsReady"] = json::value::boolean(AlphaToBool(data[L"IsReady"].as_string()));

			// set match to true and return early if using passive validation
			if (settings.passiveValidation)
			{
				data[L"Match"] = json::value::boolean(true);
				return data;
			}
			// evaluate match value using custom threshold if enabled
			else if (settings.customThreshold)
			{
				data[L"Match"] = json::value::boolean(EvalThreshold(data[L"Confidence"].as_double(), data[L"Fidelity"].as_double()));
			}
		}

		return data;
	});
}

/// <summary>
/// Evaluates a given profile and adds typing sample to profile.
/// </summary>
/// <param name="entityID">Profile to evaluate.</param>
/// <param name="tsData">Typing sample to evaluate and save.</param>
/// <param name="sessionID">Session identifier for logging purposes.</param>
/// <returns></returns>
pplx::task<web::json::value> KeyIDClient::LoginPassiveEnrollment(std::wstring entityID, std::wstring tsData, std::wstring sessionID)
{
	return EvaluateProfile(entityID, tsData, sessionID)
	.then([=](json::value data)
	{
		// in base case that no profile exists save profile async and return early
		if (data[L"Error"].as_string() == L"EntityID does not exist." ||
			data[L"Error"].as_string() == L"The profile has too little data for a valid evaluation." ||
			data[L"Error"].as_string() == L"The entry varied so much from the model, no evaluation is possible.")
		{
			return SaveProfile(entityID, tsData, sessionID)
			.then([=](json::value saveData)
			{
				json::value evalData = data;
				evalData[L"Match"] = json::value::boolean(true);
				evalData[L"IsReady"] = json::value::boolean(false);
				evalData[L"Confidence"] = json::value::number(100.0);
				evalData[L"Fidelity"] = json::value::number(100.0);
				return evalData;
			});
		}

		// if profile is not ready save profile async and return early
		if (data[L"Error"].as_string() == L"" && data[L"IsReady"].as_bool() == false)
		{
			return SaveProfile(entityID, tsData, sessionID)
			.then([=](json::value saveData)
			{
				json::value evalData = data;
				evalData[L"Match"] = json::value::boolean(true);
				return evalData;
			});
		}

		return pplx::task_from_result(data);
	});
}

/// <summary>
/// Returns profile information without modifying the profile.
/// </summary>
/// <param name="entityID">Profile to inspect.</param>
/// <returns></returns>
pplx::task<web::json::value> KeyIDClient::GetProfileInfo(std::wstring entityID)
{
	return service->GetProfileInfo(entityID)
	.then([=](http_response response)
	{
		json::value data = ParseGetProfileResponse(response);
		return pplx::task_from_result(data);
	});
}

/// <summary>
/// Compares a given confidence and fidelity against pre-determined thresholds.
/// </summary>
/// <param name="confidence">KeyID evaluation confidence.</param>
/// <param name="fidelity">KeyID evaluation fidelity.</param>
/// <returns>Whether confidence and fidelity meet thresholds.</returns>
bool KeyIDClient::EvalThreshold(double confidence, double fidelity)
{
	if (confidence >= settings.thresholdConfidence &&
		fidelity >= settings.thresholdFidelity)
	{
		return true;
	}
	else
	{
		return false;
	}
}

/// <summary>
/// Converts a string value like 'true' to a boolean object.
/// </summary>
/// <param name="input">String to convert to boolean.</param>
/// <returns>Boolean value.</returns>
bool KeyIDClient::AlphaToBool(std::wstring input)
{
	std::transform(input.begin(), input.end(), input.begin(), ::toupper);

	if (input == L"TRUE")
		return true;
	else
		return false;
}

/// <summary>
/// Converts current time to Microsoft .Net 'ticks'. A tick is 100 nanoseconds.
/// </summary>
/// <returns>Current time in 'ticks'.</returns>
long long KeyIDClient::DotNetTicks()
{
	const long long EPOCH_OFFSET = 621355968000000000;
	const long MS_PER_TICK = 10000;
	long long ms_since_epoch = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
	long long ticks = ((ms_since_epoch * MS_PER_TICK) + EPOCH_OFFSET);
	return ticks;
}

/// <summary>
/// Extracts a JSON value from a http_response
/// </summary>
/// <param name="response">HTTP response</param>
/// <returns>JSON value</returns>
web::json::value KeyIDClient::ParseResponse(const web::http::http_response& response)
{
	if (response.status_code() == status_codes::OK)
	{
		return response.extract_json().get();
	}
	else
	{
		throw http_exception(L"HTTP response not 200 OK.");
	}
}

/// <summary>
/// Extracts a JSON value from a http_response
/// </summary>
/// <param name="response">HTTP response</param>
/// <returns>JSON value</returns>
web::json::value KeyIDClient::ParseGetProfileResponse(const web::http::http_response& response)
{
	if (response.status_code() == status_codes::OK)
	{
		json::value data = response.extract_json().get();
		if (data.is_array())
			return data[0];
		else
			return data;
	}
	else
	{
		throw http_exception(L"HTTP response not 200 OK.");
	}
}<|endoftext|>


<commit_before>// Vsevolod Ivanov

#include <array>
#include <iostream>
#include <memory>
#include <asio.hpp>

class Session
{
    public:
        Session(asio::ip::tcp::socket& socket): socket_(socket){}

        bool ready_read() const {
            return state_ == reading;
        }

        void read(std::error_code& ec){
            std::string response;
            if (asio::read(socket_, asio::dynamic_buffer(response), ec)){
                printf("%s", response.c_str());
            }
        }

        bool ready_write() const {
            return state_ == writing;
        }

        void write(std::string request, std::error_code& ec){
            printf("writting request\n");
            if (asio::write(socket_, asio::dynamic_buffer(request), ec)){
                state_ = write_buffer_.size() > 0 ? writing : reading;
            }
            printf("state_=%i\n", state_);
        }

    private:
        asio::ip::tcp::socket& socket_;
        enum { reading, writing } state_ = writing;
        std::string write_buffer_;
};

class Connection: public std::enable_shared_from_this<Connection>
{
    public:
        Connection(asio::ip::tcp::socket socket): socket_(std::move(socket)){}

        void start(asio::ip::tcp::resolver::iterator &r_iter){
            asio::connect(socket_, r_iter);
        }

        void request(const std::string req){
            auto self(shared_from_this());

            if (session_.ready_write() && !write_in_progress_){
                write_in_progress_ = true;
                socket_.async_wait(asio::ip::tcp::socket::wait_write,
                                  [this, req, self](std::error_code ec){
                    write_in_progress_ = false;
                    printf("%s\n", ec.message().c_str());
                    if (!ec)
                        session_.write(req, ec);
                });
            }
        }

        std::string response(){
            auto self(shared_from_this());
            std::string resp;

            if (session_.ready_read() && !read_in_progress_){
                read_in_progress_ = true;
                socket_.async_wait(asio::ip::tcp::socket::wait_read,
                                  [this, resp, self](std::error_code ec){
                    read_in_progress_ = false;
                    if (!ec)
                        /*resp =*/session_.read(ec);
                });
            }
            return resp;

        }

        void close(){
            socket_.close();
        }

    private:
        asio::ip::tcp::socket socket_;
        Session session_{socket_};
        bool read_in_progress_ = false;
        bool write_in_progress_ = false;
};

class Client
{
    public:
        Client(asio::io_context &io_context, std::string ip, std::uint16_t port):
                resolver_(io_context){
            addr_ = asio::ip::address::from_string(ip);
            port_ = port;
            resolve();
        }

        void send_request(std::shared_ptr<Connection> conn){
            std::stringstream req;
            req << "GET / HTTP/1.1\n" <<
                   "Host: 127.0.0.1:8080\n" <<
                   "User-Agent: curl/7.64.1\n" <<
                   "Accept: */*\n\r\n\r\n";
            printf("sending:\n%s\n", req.str().c_str());
            conn->request(req.str());
            //if (!resolve_in_progress_)
            //    connections_.begin()->get()->request(req.str());
            //else
            //    throw std::runtime_error("resolve is in progress");
        }

    private:
        void resolve(){
            //resolve_in_progress_ = true;
            auto addr_t = addr_.is_v4() ? asio::ip::tcp::v4() : asio::ip::tcp::v6();
            asio::ip::tcp::resolver::query query{addr_t, addr_.to_string(),
                                                 std::to_string(port_)};
            asio::ip::tcp::socket socket{resolver_.get_io_context()};
            auto conn = std::make_shared<Connection>(std::move(socket));
            connections_.push_back(conn);

            resolver_.async_resolve(query,[this, conn](std::error_code ec,
                                           asio::ip::tcp::resolver::results_type results){
                if (!ec and !results.empty()){
                    auto first = results.begin();
                    std::cout << "resolved " << first->host_name() <<
                                 ":" << first->service_name() << std::endl;
                    conn->start(first);
                    send_request(conn);
                }
            });
            resolve_in_progress_ = false;
        }

        asio::ip::address addr_;
        std::uint16_t port_;
        bool resolve_in_progress_ = false;
        asio::ip::tcp::resolver resolver_;
        std::vector<std::shared_ptr<Connection>> connections_;
};

int main(int argc, char* argv[]){
    try {
        if (argc != 3){
            std::cerr << "Usage: ./binary <ip> <port>\n";
            return 1;
        }
        asio::io_context io_context;
        Client client(io_context, argv[1], std::atoi(argv[2]));
        //client.send_request();
        io_context.run();
    }
    catch (std::exception& e){
        std::cerr << "Exception: " << e.what() << "\n";
    }
    return 0;
}
<commit_msg>cpp/async: finish nonblocking client<commit_after>// Vsevolod Ivanov

#include <array>
#include <iostream>
#include <memory>
#include <asio.hpp>

class Session
{
    public:
        Session(asio::ip::tcp::socket& socket): socket_(socket){}

        bool ready_read() const {
            return state_ == reading;
        }

        void read(std::error_code& ec){
            std::string response;
            if (asio::read(socket_, asio::dynamic_buffer(response), ec)){
                printf("%s", response.c_str());
            }
        }

        bool ready_write() const {
            return state_ == writing;
        }

        void write(std::string request, std::error_code& ec){
            if (asio::write(socket_, asio::dynamic_buffer(request), ec)){
                state_ = write_buffer_.size() > 0 ? writing : reading;
            }
        }

    private:
        asio::ip::tcp::socket& socket_;
        enum { reading, writing } state_ = writing;
        std::string write_buffer_;
};

class Connection: public std::enable_shared_from_this<Connection>
{
    public:
        Connection(asio::ip::tcp::socket socket): socket_(std::move(socket)){}

        void start(asio::ip::tcp::resolver::iterator &r_iter){
            asio::connect(socket_, r_iter);
        }

        void request(const std::string req){
            auto self(shared_from_this());

            if (session_.ready_write() && !write_in_progress_){
                write_in_progress_ = true;
                socket_.async_wait(asio::ip::tcp::socket::wait_write,
                                  [this, req, self](std::error_code ec){
                    write_in_progress_ = false;
                    printf("write: %s\n", ec.message().c_str());
                    if (!ec)
                        session_.write(req, ec);
                    response();
                });
            }
        }

        void response(){
            auto self(shared_from_this());
            std::string resp;

            if (session_.ready_read() && !read_in_progress_){
                read_in_progress_ = true;

                socket_.async_wait(asio::ip::tcp::socket::wait_read,
                                  [this, resp, self](std::error_code ec){
                    read_in_progress_ = false;
                    printf("read: %s\n", ec.message().c_str());
                    if (!ec)
                        session_.read(ec);
                });
            }
        }

        bool open(){
            return socket_.is_open();
        }

        void close(){
            socket_.close();
        }

    private:
        asio::ip::tcp::socket socket_;
        Session session_{socket_};
        bool read_in_progress_ = false;
        bool write_in_progress_ = false;
};

class Client
{
    public:
        Client(asio::io_context &io_context, std::string ip, std::uint16_t port):
                resolver_(io_context){
            addr_ = asio::ip::address::from_string(ip);
            port_ = port;
        }

        void send_request(std::string request){
            async_request(request);
        }

    private:

        void async_request(std::string r){
            auto addr_t = addr_.is_v4() ? asio::ip::tcp::v4() : asio::ip::tcp::v6();
            asio::ip::tcp::resolver::query query{addr_t, addr_.to_string(),
                                                 std::to_string(port_)};
            asio::ip::tcp::socket socket{resolver_.get_io_context()};
            auto conn = std::make_shared<Connection>(std::move(socket));
            connections_.push_back(conn);

            resolver_.async_resolve(query,[this, conn, r](std::error_code ec,
                                           asio::ip::tcp::resolver::results_type results){
                // ready for write
                if (!ec and !results.empty()){
                    auto da = results.begin();
                    std::cout << "resolved " << "host=" << da->host_name() <<
                                 " service=" << da->service_name() << std::endl;
                    conn->start(da);

                    if (conn->open()){
                        printf("sending:\n%s\n", r.c_str());
                        conn->request(r);
                    }
                    else
                        printf("error: connection closed\n");
                }
                else {
                    printf("resolving error: closing connection\n");
                    conn->close();
                }
            });
        }

        asio::ip::address addr_;
        std::uint16_t port_;
        asio::ip::tcp::resolver resolver_;
        std::vector<std::shared_ptr<Connection>> connections_;
};

int main(int argc, char* argv[]){
    try {
        if (argc != 3){
            std::cerr << "Usage: ./binary <ip> <port>\n";
            return 1;
        }
        std::stringstream req;
        req << "GET / HTTP/1.1\r\n" <<
               "Host: 127.0.0.1:8080\r\n" <<
               "Accept: */*\r\n" <<
               "Connection: keep-alive\r\n" <<
               "\r\n";

        asio::io_context io_context;
        Client client(io_context, argv[1], std::atoi(argv[2]));
        client.send_request(req.str());
        client.send_request(req.str());
        client.send_request(req.str());
        io_context.run();
        printf("finishing..\n");
    }
    catch (std::exception& e){
        std::cerr << "Exception: " << e.what() << "\n";
    }
    return 0;
}
<|endoftext|>


<commit_before><commit_msg>Create Lab_02_Question_01.cpp<commit_after><|endoftext|>


<commit_before><commit_msg>Create Lab_02_Question_12.cpp<commit_after><|endoftext|>


<commit_before>class CQB_spawn {
	title = "    Enemy - CQB Populator (Building %)";
	values[]= {0,0.5,1,2,3,4,5};
	texts[]= {"Off","5","10","20","30","40","50"};
	default = 1;
};

class CQBaicap {
	title = "    CQB AI Limit (per player)";
	values[]= {0,1,2,3,4,5};
	texts[]= {"Off","15","25","50","100","AUTO"};
	default = 0;
};<commit_msg>[ENEMY] Added optional CQB max groups parameter<commit_after>class CQB_spawn {
	title = "    CQB Populator (Building %)";
	values[]= {0,0.5,1,2,3,4,5};
	texts[]= {"Off","5","10","20","30","40","50"};
	default = 1;
};

class CQBaicap {
	title = "        CQB AI Limit (per player)";
	values[]= {0,1,2,3,4,5};
	texts[]= {"Off","15","25","50","100","AUTO"};
	default = 0;
};

class CQBmaxgrps {
	title = "        CQB Group limit";
	values[]= {144,10,25,50,75,100};
	texts[]= {"Off","10","25","50","75","100"};
	default = 144;
};

<|endoftext|>


<commit_before>// Project specific
#include <Manager/GraphicManager.hpp>
#include <EntityComponent/EntityHandler.hpp>
#include <EntityComponent/Components/RenderComponent.hpp>
#include <EntityComponent/Components/TransformComponent.hpp>
// Engine
#include <DoremiEngine/Graphic/Include/GraphicModule.hpp>
#include <DoremiEngine/Graphic/Include/Interface/Manager/MeshManager.hpp>
#include <DoremiEngine/Graphic/Include/Interface/Manager/DirectXManager.hpp>
#include <DoremiEngine/Graphic/Include/Interface/Manager/SubModuleManager.hpp>
#include <DoremiEngine/Graphic/Include/Interface/Manager/ShaderManager.hpp>
#include <DoremiEngine/Graphic/Include/Interface/Mesh/MeshInfo.hpp>
#include <DoremiEngine/Graphic/Include/Interface/Mesh/MaterialInfo.hpp>
#include <DoremiEngine/Graphic/Include/Interface/Shader/PixelShader.hpp>
#include <DoremiEngine/Graphic/Include/Interface/Shader/VertexShader.hpp>
#include <DoremiEngine/Graphic/Include/Interface/State/DepthStencilState.hpp>
#include <DoremiEngine/Graphic/Include/Interface/State/RasterizerState.hpp>
#include <dxgi.h>
#include <d3d11_1.h>

namespace Doremi
{
    namespace Core
    {
        GraphicManager::GraphicManager(const DoremiEngine::Core::SharedContext& p_sharedContext) : Manager(p_sharedContext, "GraphicManager")
        {
            // TODOKO Should not be here!! or should it? For standard shaders? Maybee in shadermanager
            // TODOLH Maybe shouldnt be here either. Moved it from shadermodulemanagerImplementation cos this guy needs to be able to switch shader
            // before drawing
            D3D11_INPUT_ELEMENT_DESC ied[] = {
                {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0},
                {"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0},
                {"NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0},
            };
            m_vertexShader = m_sharedContext.GetGraphicModule().GetSubModuleManager().GetShaderManager().BuildVertexShader("BasicVertexShader.hlsl",
                                                                                ied, ARRAYSIZE(ied));
            m_pixelShader = m_sharedContext.GetGraphicModule().GetSubModuleManager().GetShaderManager().BuildPixelShader("BasicPixelShader.hlsl");

            D3D11_RASTERIZER_DESC rastDesc;
            ZeroMemory(&rastDesc, sizeof(rastDesc));
            rastDesc.FillMode = D3D11_FILL_SOLID;
            rastDesc.CullMode = D3D11_CULL_NONE;
            rastDesc.FrontCounterClockwise = false;
            rastDesc.DepthBias = 0;
            rastDesc.DepthBiasClamp = 0.0f;
            rastDesc.SlopeScaledDepthBias = 0.0f;
            rastDesc.DepthClipEnable = false;
            rastDesc.ScissorEnable = false;
            rastDesc.MultisampleEnable = true;
            rastDesc.AntialiasedLineEnable = false;
            m_rasterizerState = m_sharedContext.GetGraphicModule().GetSubModuleManager().GetDirectXManager().CreateRasterizerState(rastDesc);
            D3D11_DEPTH_STENCIL_DESC depthStencilDesc;
            ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc));
            depthStencilDesc.DepthEnable = true;
            depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
            depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;
            m_depthStencilState = m_sharedContext.GetGraphicModule().GetSubModuleManager().GetDirectXManager().CreateDepthStencilState(depthStencilDesc);
        }

        GraphicManager::~GraphicManager() {}

        void GraphicManager::Update(double p_dt)
        {
            m_sharedContext.GetGraphicModule().GetSubModuleManager().GetShaderManager().SetActiveVertexShader(m_vertexShader);
            m_sharedContext.GetGraphicModule().GetSubModuleManager().GetShaderManager().SetActivePixelShader(m_pixelShader);

            const size_t length = EntityHandler::GetInstance().GetLastEntityIndex();
            int mask = (int)ComponentType::Render | (int)ComponentType::Transform;
            for(size_t i = 0; i < length; i++)
            {
                if(EntityHandler::GetInstance().HasComponents(i, mask))
                {
                    RenderComponent* renderComp = EntityHandler::GetInstance().GetComponentFromStorage<RenderComponent>(i);
                    TransformComponent* orientationComp = EntityHandler::GetInstance().GetComponentFromStorage<TransformComponent>(i);
                    DirectX::XMFLOAT4X4 transMat;
                    DirectX::XMVECTOR quaternion = DirectX::XMLoadFloat4(&orientationComp->rotation);
                    DirectX::XMMATRIX tempTransMat = DirectX::XMMatrixTranspose(
                        DirectX::XMMatrixScaling(orientationComp->scale.x, orientationComp->scale.y, orientationComp->scale.z) *
                        DirectX::XMMatrixRotationQuaternion(quaternion) *
                        DirectX::XMMatrixTranslation(orientationComp->position.x, orientationComp->position.y, orientationComp->position.z));
                    DirectX::XMStoreFloat4x4(&transMat, tempTransMat);
                    m_sharedContext.GetGraphicModule().GetSubModuleManager().GetMeshManager().AddToRenderList(*renderComp->mesh, *renderComp->material, transMat);
                }
            }
            m_rasterizerState->GetRasterizerState();
            m_depthStencilState->GetDepthStencilState();
            DoremiEngine::Graphic::DirectXManager& dxmanager = m_sharedContext.GetGraphicModule().GetSubModuleManager().GetDirectXManager();
            m_sharedContext.GetGraphicModule().GetSubModuleManager().GetDirectXManager().DrawCurrentRenderList(m_rasterizerState->GetRasterizerState(),
                                                                                m_depthStencilState->GetDepthStencilState());
        }

        void GraphicManager::OnEvent(Event* p_event) {}
    }
}<commit_msg>Reduced the call to engine in a loop<commit_after>// Project specific
#include <Manager/GraphicManager.hpp>
#include <EntityComponent/EntityHandler.hpp>
#include <EntityComponent/Components/RenderComponent.hpp>
#include <EntityComponent/Components/TransformComponent.hpp>
// Engine
#include <DoremiEngine/Graphic/Include/GraphicModule.hpp>
#include <DoremiEngine/Graphic/Include/Interface/Manager/MeshManager.hpp>
#include <DoremiEngine/Graphic/Include/Interface/Manager/DirectXManager.hpp>
#include <DoremiEngine/Graphic/Include/Interface/Manager/SubModuleManager.hpp>
#include <DoremiEngine/Graphic/Include/Interface/Manager/ShaderManager.hpp>
#include <DoremiEngine/Graphic/Include/Interface/Mesh/MeshInfo.hpp>
#include <DoremiEngine/Graphic/Include/Interface/Mesh/MaterialInfo.hpp>
#include <DoremiEngine/Graphic/Include/Interface/Shader/PixelShader.hpp>
#include <DoremiEngine/Graphic/Include/Interface/Shader/VertexShader.hpp>
#include <DoremiEngine/Graphic/Include/Interface/State/DepthStencilState.hpp>
#include <DoremiEngine/Graphic/Include/Interface/State/RasterizerState.hpp>
#include <dxgi.h>
#include <d3d11_1.h>

namespace Doremi
{
    namespace Core
    {
        GraphicManager::GraphicManager(const DoremiEngine::Core::SharedContext& p_sharedContext) : Manager(p_sharedContext, "GraphicManager")
        {
            // TODOKO Should not be here!! or should it? For standard shaders? Maybee in shadermanager
            // TODOLH Maybe shouldnt be here either. Moved it from shadermodulemanagerImplementation cos this guy needs to be able to switch shader
            // before drawing
            D3D11_INPUT_ELEMENT_DESC ied[] = {
                {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0},
                {"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0},
                {"NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0},
            };
            m_vertexShader = m_sharedContext.GetGraphicModule().GetSubModuleManager().GetShaderManager().BuildVertexShader("BasicVertexShader.hlsl",
                                                                                ied, ARRAYSIZE(ied));
            m_pixelShader = m_sharedContext.GetGraphicModule().GetSubModuleManager().GetShaderManager().BuildPixelShader("BasicPixelShader.hlsl");

            D3D11_RASTERIZER_DESC rastDesc;
            ZeroMemory(&rastDesc, sizeof(rastDesc));
            rastDesc.FillMode = D3D11_FILL_SOLID;
            rastDesc.CullMode = D3D11_CULL_NONE;
            rastDesc.FrontCounterClockwise = false;
            rastDesc.DepthBias = 0;
            rastDesc.DepthBiasClamp = 0.0f;
            rastDesc.SlopeScaledDepthBias = 0.0f;
            rastDesc.DepthClipEnable = false;
            rastDesc.ScissorEnable = false;
            rastDesc.MultisampleEnable = true;
            rastDesc.AntialiasedLineEnable = false;
            m_rasterizerState = m_sharedContext.GetGraphicModule().GetSubModuleManager().GetDirectXManager().CreateRasterizerState(rastDesc);
            D3D11_DEPTH_STENCIL_DESC depthStencilDesc;
            ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc));
            depthStencilDesc.DepthEnable = true;
            depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
            depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;
            m_depthStencilState = m_sharedContext.GetGraphicModule().GetSubModuleManager().GetDirectXManager().CreateDepthStencilState(depthStencilDesc);
        }

        GraphicManager::~GraphicManager() {}

        void GraphicManager::Update(double p_dt)
        {
            DoremiEngine::Graphic::SubModuleManager& submoduleManager = m_sharedContext.GetGraphicModule().GetSubModuleManager();
            submoduleManager.GetShaderManager().SetActiveVertexShader(m_vertexShader);
            submoduleManager.GetShaderManager().SetActivePixelShader(m_pixelShader);

            EntityHandler& entityHandler = EntityHandler::GetInstance();
            const size_t length = entityHandler.GetLastEntityIndex();
            int mask = (int)ComponentType::Render | (int)ComponentType::Transform;
            for(size_t i = 0; i < length; i++)
            {
                if(entityHandler.HasComponents(i, mask))
                {
                    RenderComponent* renderComp = entityHandler.GetComponentFromStorage<RenderComponent>(i);
                    TransformComponent* orientationComp = entityHandler.GetComponentFromStorage<TransformComponent>(i);
                    DirectX::XMFLOAT4X4 transMat;
                    DirectX::XMVECTOR quaternion = DirectX::XMLoadFloat4(&orientationComp->rotation);
                    DirectX::XMMATRIX tempTransMat = DirectX::XMMatrixTranspose(
                        DirectX::XMMatrixScaling(orientationComp->scale.x, orientationComp->scale.y, orientationComp->scale.z) *
                        DirectX::XMMatrixRotationQuaternion(quaternion) *
                        DirectX::XMMatrixTranslation(orientationComp->position.x, orientationComp->position.y, orientationComp->position.z));
                    DirectX::XMStoreFloat4x4(&transMat, tempTransMat);
                    submoduleManager.GetMeshManager().AddToRenderList(*renderComp->mesh, *renderComp->material, transMat);
                }
            }
            m_rasterizerState->GetRasterizerState();
            m_depthStencilState->GetDepthStencilState();
            submoduleManager.GetDirectXManager().DrawCurrentRenderList(m_rasterizerState->GetRasterizerState(), m_depthStencilState->GetDepthStencilState());
        }

        void GraphicManager::OnEvent(Event* p_event) {}
    }
}<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    FastMarchingLevelSet.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include <FastMarchingLevelSet.h>
#include <FL/fl_file_chooser.H>

/************************************
 *
 *  Constructor
 *
 ***********************************/
FastMarchingLevelSet
::FastMarchingLevelSet()
{
  // This image is only used for providing visual
  // feedback to the user. The actual structure
  // holding the seeds is in the base class.
  m_SeedImage = SeedImageType::New();

  m_InputImageViewer.SetLabel("Input Image");

  m_ThresholdedImageViewer.SetLabel("Thresholded Image");

  m_SegmentationImageViewer.SetLabel("Segmented Image");
  m_SegmentationImageViewer.SetOverlayOpacity( 0.5 );

  m_GradientMagnitudeImageViewer.SetLabel("Gradient Magnitude Image");

  m_EdgePotentialImageViewer.SetLabel("Edge Potential Image");

  m_InputImageViewer.ClickSelectCallBack( ClickSelectCallback, (void *)this);

  // Initialize ITK filter with GUI values
  m_ThresholdFilter->SetLowerThreshold(
      static_cast<InternalPixelType>( lowerThresholdValueInput->value() ) );

  m_ThresholdFilter->SetUpperThreshold(
      static_cast<InputPixelType>( upperThresholdValueInput->value() ) );

  m_DerivativeFilter->SetSigma( sigmaValueInput->value() );

  m_SigmoidFilter->SetAlpha( alphaValueInput->value() );
  m_SigmoidFilter->SetBeta(  betaValueInput->value()  );

  m_FastMarchingFilter->SetStoppingValue( stoppingValueInput->value() );

  m_VTKSegmentedImageViewer = VTKImageViewerType::New();
  m_VTKSegmentedImageViewer->SetImage( m_ThresholdFilter->GetOutput() );

  m_TimeCrossingMapViewer.SetLabel("Time Crossing Map");

  // Connect Observers in the GUI
  inputImageButton->Observe( m_ImageReader.GetPointer() );
  thresholdedImageButton->Observe( m_ThresholdFilter.GetPointer() );
  segmentedImageButton->Observe( m_ThresholdFilter.GetPointer() );
  thresholdedImageVTKButton->Observe( m_ThresholdFilter.GetPointer() );
  timeCrossingButton->Observe( m_FastMarchingFilter.GetPointer() );
  gradientMagnitudeButton->Observe( m_DerivativeFilter.GetPointer() );
  edgePotentialButton->Observe( m_SigmoidFilter.GetPointer() );

  progressSlider->Observe( m_CastImageFilter.GetPointer() );
  progressSlider->Observe( m_DerivativeFilter.GetPointer() );
  progressSlider->Observe( m_ThresholdFilter.GetPointer() );
  progressSlider->Observe( m_SigmoidFilter.GetPointer() );
  progressSlider->Observe( m_ImageReader.GetPointer() );
  progressSlider->Observe( m_FastMarchingFilter.GetPointer() );

  m_ThresholdFilter->SetLowerThreshold( lowerThresholdValueInput->value() );
  m_ThresholdFilter->SetUpperThreshold( upperThresholdValueInput->value() );

  m_IterationCounter = 0;

}

/************************************
 *
 *  Destructor
 *
 ***********************************/
FastMarchingLevelSet
::~FastMarchingLevelSet()
{

}

/************************************
 *
 * Show main console
 *
 ***********************************/
void
FastMarchingLevelSet
::ShowConsole(void)
{
  consoleWindow->show();
}

/********************************************
 *
 * Quit : requires to hide all fltk windows
 *
 *******************************************/
void
FastMarchingLevelSet
::Quit(void)
{
  m_InputImageViewer.Hide();
  m_ThresholdedImageViewer.Hide();
  m_SegmentationImageViewer.Hide();
  m_EdgePotentialImageViewer.Hide();
  m_GradientMagnitudeImageViewer.Hide();
  m_TimeCrossingMapViewer.Hide();

  m_VTKSegmentedImageViewer->Hide();

  consoleWindow->hide();
}

/************************************
 *
 *  Load Input Image
 *
 ***********************************/
void
FastMarchingLevelSet
::LoadInputImage( void )
{

  const char * filename = fl_file_chooser("Input Image filename","*.*","");
  if( !filename )
  {
    return;
  }

  this->ShowStatus("Loading input image file...");

  try
  {
    FastMarchingLevelSetBase::LoadInputImage( filename );
  }
  catch( ... )
  {
    this->ShowStatus("Problems reading file format");
    controlsGroup->deactivate();
    return;
  }

  // Allocate a image of seeds of the same size
  m_SeedImage->SetRegions( m_ImageReader->GetOutput()->GetBufferedRegion() );
  m_SeedImage->Allocate();
  m_SeedImage->FillBuffer( itk::NumericTraits<SeedImageType::PixelType>::Zero );

  this->ShowStatus("Input Image Loaded");

  controlsGroup->activate();

}

/************************************
 *
 *  Show Status
 *
 ***********************************/
void
FastMarchingLevelSet
::ShowStatus( const char * message )
{
  statusTextOutput->value( message );
  Fl::check();
}

/************************************
 *
 *  Clear Seeds
 *
 ***********************************/
void
FastMarchingLevelSet
::ClearSeeds( void )
{
  this->FastMarchingLevelSetBase::ClearSeeds();
  m_SeedImage->FillBuffer( itk::NumericTraits<SeedImageType::PixelType>::Zero );
}

/************************************
 *
 *  Show Input Image
 *
 ***********************************/
void
FastMarchingLevelSet
::ShowInputImage( void )
{

  if( !m_InputImageIsLoaded )
    {
    return;
    }

  m_CastImageFilter->Update();
  m_InputImageViewer.SetImage( m_CastImageFilter->GetOutput() );
  m_InputImageViewer.SetOverlay( m_SeedImage );
  m_InputImageViewer.Show();

}

/************************************
 *
 *  Show Time Crossing Map Image
 *
 ***********************************/
void
FastMarchingLevelSet
::ShowTimeCrossingMapImage( void )
{

  if( !m_InputImageIsLoaded )
    {
    return;
    }
  this->RunFastMarching();
  m_TimeCrossingMapViewer.SetImage( m_FastMarchingFilter->GetOutput() );
  m_TimeCrossingMapViewer.Show();

}

/************************************
 *
 *  Show Gradient Magnitude
 *
 ***********************************/
void
FastMarchingLevelSet
::ShowGradientMagnitudeImage( void )
{

  if( !m_InputImageIsLoaded )
    {
    return;
    }
  this->ComputeGradientMagnitude();
  m_GradientMagnitudeImageViewer.SetImage( m_DerivativeFilter->GetOutput() );
  m_GradientMagnitudeImageViewer.Show();

}

/************************************
 *
 *  Show The Edge Potential Map
 *
 ***********************************/
void
FastMarchingLevelSet
::ShowEdgePotentialImage( void )
{

  if( !m_InputImageIsLoaded )
    {
    return;
    }
  this->ComputeEdgePotential();
  m_EdgePotentialImageViewer.SetImage( m_SigmoidFilter->GetOutput() );
  m_EdgePotentialImageViewer.Show();

}

/************************************
 *
 *  Show Thresholded Image
 *
 ***********************************/
void
FastMarchingLevelSet
::ShowThresholdedImage( void )
{
  m_ThresholdFilter->Update();
  m_ThresholdedImageViewer.SetImage( m_ThresholdFilter->GetOutput() );
  m_ThresholdedImageViewer.SetOverlay( m_SeedImage );
  m_ThresholdedImageViewer.Show();

}

/************************************
 *
 *  Show Segmented Image
 *
 ***********************************/
void
FastMarchingLevelSet
::ShowSegmentedImage( void )
{
  m_ThresholdFilter->Update();
  m_SegmentationImageViewer.SetImage( m_CastImageFilter->GetOutput() );
  m_SegmentationImageViewer.SetOverlay( m_ThresholdFilter->GetOutput() );
  m_SegmentationImageViewer.Show();

}

/************************************
 *
 *  Show Homogeneous Image
 *
 ***********************************/
void
FastMarchingLevelSet
::ShowThresholdedImageWithVTK( void )
{
  m_VTKSegmentedImageViewer->Show();
}

/*****************************************
 *
 *  Callback for Selecting a seed point
 *
 *****************************************/
void
FastMarchingLevelSet
::ClickSelectCallback(float x, float y, float z, float value, void * args )
{

  FastMarchingLevelSet * self =
     static_cast<FastMarchingLevelSet *>( args );

  self->SelectSeedPoint( x, y, z );

}

/*****************************************
 *
 *  Callback for Selecting a seed point
 *
 *****************************************/
void
FastMarchingLevelSet
::SelectSeedPoint(float x, float y, float z)
{

  typedef SeedImageType::IndexType IndexType;
  IndexType seed;
  seed[0] = static_cast<IndexType::IndexValueType>( x );
  seed[1] = static_cast<IndexType::IndexValueType>( y );
  seed[2] = static_cast<IndexType::IndexValueType>( z );

  FastMarchingLevelSetBase::AddSeed( seed );

  m_SeedImage->SetPixel( seed, 1 );

  m_InputImageViewer.Update();

}

/*  Finaly the main() that will instantiate the application  */
int main()
{

  try
    {
    FastMarchingLevelSet * console = new FastMarchingLevelSet();
    console->ShowConsole();
    Fl::run();
    delete console;
    }
  catch( itk::ExceptionObject & e )
    {
    std::cerr << "ITK exception caught in main" << std::endl;
    std::cerr << e << std::endl;
    }
  catch( std::exception & e )
    {
    std::cerr << "STD exception caught in main" << std::endl;
    std::cerr << e.what() << std::endl;
    }
  catch( ... )
    {
    std::cerr << "unknown exception caught in main" << std::endl;
    }

  return 0;

}

<commit_msg>ENH: Set the overlay opacity to 0.5 by default.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    FastMarchingLevelSet.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include <FastMarchingLevelSet.h>
#include <FL/fl_file_chooser.H>

/************************************
 *
 *  Constructor
 *
 ***********************************/
FastMarchingLevelSet
::FastMarchingLevelSet()
{
  // This image is only used for providing visual
  // feedback to the user. The actual structure
  // holding the seeds is in the base class.
  m_SeedImage = SeedImageType::New();

  m_InputImageViewer.SetLabel("Input Image");

  m_ThresholdedImageViewer.SetLabel("Thresholded Image");

  m_SegmentationImageViewer.SetLabel("Segmented Image");
  m_SegmentationImageViewer.SetOverlayOpacity( 0.5 );

  m_GradientMagnitudeImageViewer.SetLabel("Gradient Magnitude Image");

  m_EdgePotentialImageViewer.SetLabel("Edge Potential Image");

  m_InputImageViewer.ClickSelectCallBack( ClickSelectCallback, (void *)this);

  // Initialize ITK filter with GUI values
  m_ThresholdFilter->SetLowerThreshold(
      static_cast<InternalPixelType>( lowerThresholdValueInput->value() ) );

  m_ThresholdFilter->SetUpperThreshold(
      static_cast<InputPixelType>( upperThresholdValueInput->value() ) );

  m_DerivativeFilter->SetSigma( sigmaValueInput->value() );

  m_SigmoidFilter->SetAlpha( alphaValueInput->value() );
  m_SigmoidFilter->SetBeta(  betaValueInput->value()  );

  m_FastMarchingFilter->SetStoppingValue( stoppingValueInput->value() );

  m_VTKSegmentedImageViewer = VTKImageViewerType::New();
  m_VTKSegmentedImageViewer->SetImage( m_ThresholdFilter->GetOutput() );

  m_TimeCrossingMapViewer.SetLabel("Time Crossing Map");

  // Connect Observers in the GUI
  inputImageButton->Observe( m_ImageReader.GetPointer() );
  thresholdedImageButton->Observe( m_ThresholdFilter.GetPointer() );
  segmentedImageButton->Observe( m_ThresholdFilter.GetPointer() );
  thresholdedImageVTKButton->Observe( m_ThresholdFilter.GetPointer() );
  timeCrossingButton->Observe( m_FastMarchingFilter.GetPointer() );
  gradientMagnitudeButton->Observe( m_DerivativeFilter.GetPointer() );
  edgePotentialButton->Observe( m_SigmoidFilter.GetPointer() );

  progressSlider->Observe( m_CastImageFilter.GetPointer() );
  progressSlider->Observe( m_DerivativeFilter.GetPointer() );
  progressSlider->Observe( m_ThresholdFilter.GetPointer() );
  progressSlider->Observe( m_SigmoidFilter.GetPointer() );
  progressSlider->Observe( m_ImageReader.GetPointer() );
  progressSlider->Observe( m_FastMarchingFilter.GetPointer() );

  m_ThresholdFilter->SetLowerThreshold( lowerThresholdValueInput->value() );
  m_ThresholdFilter->SetUpperThreshold( upperThresholdValueInput->value() );

  m_IterationCounter = 0;

}

/************************************
 *
 *  Destructor
 *
 ***********************************/
FastMarchingLevelSet
::~FastMarchingLevelSet()
{

}

/************************************
 *
 * Show main console
 *
 ***********************************/
void
FastMarchingLevelSet
::ShowConsole(void)
{
  consoleWindow->show();
}

/********************************************
 *
 * Quit : requires to hide all fltk windows
 *
 *******************************************/
void
FastMarchingLevelSet
::Quit(void)
{
  m_InputImageViewer.Hide();
  m_ThresholdedImageViewer.Hide();
  m_SegmentationImageViewer.Hide();
  m_EdgePotentialImageViewer.Hide();
  m_GradientMagnitudeImageViewer.Hide();
  m_TimeCrossingMapViewer.Hide();

  m_VTKSegmentedImageViewer->Hide();

  consoleWindow->hide();
}

/************************************
 *
 *  Load Input Image
 *
 ***********************************/
void
FastMarchingLevelSet
::LoadInputImage( void )
{

  const char * filename = fl_file_chooser("Input Image filename","*.*","");
  if( !filename )
  {
    return;
  }

  this->ShowStatus("Loading input image file...");

  try
  {
    FastMarchingLevelSetBase::LoadInputImage( filename );
  }
  catch( ... )
  {
    this->ShowStatus("Problems reading file format");
    controlsGroup->deactivate();
    return;
  }

  // Allocate a image of seeds of the same size
  m_SeedImage->SetRegions( m_ImageReader->GetOutput()->GetBufferedRegion() );
  m_SeedImage->Allocate();
  m_SeedImage->FillBuffer( itk::NumericTraits<SeedImageType::PixelType>::Zero );

  this->ShowStatus("Input Image Loaded");

  controlsGroup->activate();

}

/************************************
 *
 *  Show Status
 *
 ***********************************/
void
FastMarchingLevelSet
::ShowStatus( const char * message )
{
  statusTextOutput->value( message );
  Fl::check();
}

/************************************
 *
 *  Clear Seeds
 *
 ***********************************/
void
FastMarchingLevelSet
::ClearSeeds( void )
{
  this->FastMarchingLevelSetBase::ClearSeeds();
  m_SeedImage->FillBuffer( itk::NumericTraits<SeedImageType::PixelType>::Zero );
}

/************************************
 *
 *  Show Input Image
 *
 ***********************************/
void
FastMarchingLevelSet
::ShowInputImage( void )
{

  if( !m_InputImageIsLoaded )
    {
    return;
    }

  m_CastImageFilter->Update();
  m_InputImageViewer.SetImage( m_CastImageFilter->GetOutput() );
  m_InputImageViewer.SetOverlay( m_SeedImage );
  m_InputImageViewer.Show();

}

/************************************
 *
 *  Show Time Crossing Map Image
 *
 ***********************************/
void
FastMarchingLevelSet
::ShowTimeCrossingMapImage( void )
{

  if( !m_InputImageIsLoaded )
    {
    return;
    }
  this->RunFastMarching();
  m_TimeCrossingMapViewer.SetImage( m_FastMarchingFilter->GetOutput() );
  m_TimeCrossingMapViewer.Show();

}

/************************************
 *
 *  Show Gradient Magnitude
 *
 ***********************************/
void
FastMarchingLevelSet
::ShowGradientMagnitudeImage( void )
{

  if( !m_InputImageIsLoaded )
    {
    return;
    }
  this->ComputeGradientMagnitude();
  m_GradientMagnitudeImageViewer.SetImage( m_DerivativeFilter->GetOutput() );
  m_GradientMagnitudeImageViewer.Show();

}

/************************************
 *
 *  Show The Edge Potential Map
 *
 ***********************************/
void
FastMarchingLevelSet
::ShowEdgePotentialImage( void )
{

  if( !m_InputImageIsLoaded )
    {
    return;
    }
  this->ComputeEdgePotential();
  m_EdgePotentialImageViewer.SetImage( m_SigmoidFilter->GetOutput() );
  m_EdgePotentialImageViewer.Show();

}

/************************************
 *
 *  Show Thresholded Image
 *
 ***********************************/
void
FastMarchingLevelSet
::ShowThresholdedImage( void )
{
  m_ThresholdFilter->Update();
  m_ThresholdedImageViewer.SetImage( m_ThresholdFilter->GetOutput() );
  m_ThresholdedImageViewer.SetOverlay( m_SeedImage );
  m_ThresholdedImageViewer.Show();

}

/************************************
 *
 *  Show Segmented Image
 *
 ***********************************/
void
FastMarchingLevelSet
::ShowSegmentedImage( void )
{
  m_ThresholdFilter->Update();
  m_SegmentationImageViewer.SetImage( m_CastImageFilter->GetOutput() );
  m_SegmentationImageViewer.SetOverlay( m_ThresholdFilter->GetOutput() );
  m_SegmentationImageViewer.Show();
  m_SegmentationImageViewer.SetOverlayOpacity( 0.5 );

}

/************************************
 *
 *  Show Homogeneous Image
 *
 ***********************************/
void
FastMarchingLevelSet
::ShowThresholdedImageWithVTK( void )
{
  m_VTKSegmentedImageViewer->Show();
}

/*****************************************
 *
 *  Callback for Selecting a seed point
 *
 *****************************************/
void
FastMarchingLevelSet
::ClickSelectCallback(float x, float y, float z, float value, void * args )
{

  FastMarchingLevelSet * self =
     static_cast<FastMarchingLevelSet *>( args );

  self->SelectSeedPoint( x, y, z );

}

/*****************************************
 *
 *  Callback for Selecting a seed point
 *
 *****************************************/
void
FastMarchingLevelSet
::SelectSeedPoint(float x, float y, float z)
{

  typedef SeedImageType::IndexType IndexType;
  IndexType seed;
  seed[0] = static_cast<IndexType::IndexValueType>( x );
  seed[1] = static_cast<IndexType::IndexValueType>( y );
  seed[2] = static_cast<IndexType::IndexValueType>( z );

  FastMarchingLevelSetBase::AddSeed( seed );

  m_SeedImage->SetPixel( seed, 1 );

  m_InputImageViewer.Update();

}

/*  Finaly the main() that will instantiate the application  */
int main()
{

  try
    {
    FastMarchingLevelSet * console = new FastMarchingLevelSet();
    console->ShowConsole();
    Fl::run();
    delete console;
    }
  catch( itk::ExceptionObject & e )
    {
    std::cerr << "ITK exception caught in main" << std::endl;
    std::cerr << e << std::endl;
    }
  catch( std::exception & e )
    {
    std::cerr << "STD exception caught in main" << std::endl;
    std::cerr << e.what() << std::endl;
    }
  catch( ... )
    {
    std::cerr << "unknown exception caught in main" << std::endl;
    }

  return 0;

}

<|endoftext|>


<commit_before>#include "segment.h"
#include "gtest/gtest.h"

namespace project {

TEST(SegmentTest, CreatesRandomCars) {
  Segment segment(10, NULL, 50, 5, 5);
  ASSERT_GE(segment.num_cars(), 1);
  ASSERT_LE(segment.num_cars(), Segment::kMaxCars);
  ASSERT_LE(segment.num_cars(), 10);
  ASSERT_EQ(segment.ready_cars().size(), 50 * segment.num_cars() / 100);
}

TEST(SegmentTest, EntersLessOrEqualToCapacity) {
  Segment prev_segment(10, NULL, 50, 100, 5);
  Segment segment(10, &prev_segment, 50, 100, 5);
  prev_segment.set_next(&segment);
  segment.Enter();
  ASSERT_LE(segment.num_cars(), 10);
}

TEST(SegmentTest, RemovesCarsFromFreeway) {
  Segment segment(10, NULL, 50, 100, 5);
  Junction junction;
  segment.set_exit(&junction);
  std::vector<Car*> ready_cars = segment.ready_cars();
  size_t num_before_exit = segment.num_cars();

  size_t ready_to_exit = 0;
  for (size_t i = 0; i < ready_cars.size(); ++i) {
    if (ready_cars[i]->exit() == segment.exit()->id()) {
      ++ready_to_exit;
    }
  }

  segment.Exit();
  ASSERT_EQ(segment.num_cars(), num_before_exit - ready_to_exit);
}

TEST(SegmentTest, Operates) {
  Segment prev_segment(10, NULL, 50, 100, 5);
  Segment segment(10, &prev_segment, 50, 100, 5);
  Junction junction;
  segment.set_exit(&junction);
  prev_segment.set_next(&segment);
  std::vector<Car*> prev_ready_cars = segment.ready_cars();
  segment.Operate();
  std::vector<Car*> ready_cars = segment.ready_cars();

  ASSERT_GE(ready_cars.size(), prev_ready_cars.size());
  ASSERT_EQ(ready_cars.size() - prev_ready_cars.size(),
            50 * segment.num_cars() / 100);
  const std::vector<Car*>& cars_after_operation = segment.cars();
  for (size_t i = 0; i < cars_after_operation.size(); ++i) {
    ASSERT_EQ(cars_after_operation[i]->segment(), &segment);
  }
}

TEST(SegmentTest, PassesReadyCars) {
  Segment segment(10, NULL, 50, 100, 5);
  Segment next_segment(10, NULL, 50, 100, 5);
  segment.set_next(&next_segment);

  std::vector<Car*> ready_cars = segment.ready_cars();
  size_t ready_to_pass = 0;
  for (size_t i = 0; i < ready_cars.size(); ++i) {
    if (ready_cars[i]->exit() != segment.exit()->id()) {
      ++ready_to_pass;
    }
  }

  size_t num_before_pass = segment.num_cars();
  segment.Pass(5);
  if (num_before_pass >= 5) {
    ASSERT_GE(segment.num_cars(), num_before_pass - 5);
  }
  ASSERT_GE(segment.num_cars(), num_before_pass - ready_to_pass);
  ASSERT_LE(next_segment.num_cars(), 10);
}

TEST(SegmentTest, CreatesCarsWithGreaterExit) {
  Segment segment(10, NULL, 50, 100, 5);
  Junction junction;
  segment.set_exit(&junction);
  const std::vector<Car*>& cars = segment.cars();
  for (size_t i = 0; i < cars.size(); ++i) {
    ASSERT_GE(cars[i]->exit(), segment.exit()->id());
  }
}

TEST(SegmentTest, ReturnsReadyCars) {
  Segment segment(10, NULL, 50, 100, 5);
  std::vector<Car*> ready_cars = segment.ready_cars();

  ASSERT_LE(ready_cars.size(), segment.num_cars());
  for (size_t i = 0; i < ready_cars.size(); ++i) {
    ASSERT_EQ(ready_cars[i]->ready(), true);
  }
}

TEST(SegmentTest, ReturnsCapacity) {
  Segment segment(10, NULL, 50, 100, 5);
  ASSERT_EQ(segment.capacity(), 10);
}

TEST(SegmentTest, ReturnsEntrance) {
  Segment segment0(10, NULL, 50, 100, 5);
  Segment segment1(10, NULL, 50, 100, 5);
  Segment segment2(10, NULL, 50, 100, 5);
  ASSERT_GE(segment0.entrance(), 0);
  ASSERT_EQ(segment1.entrance(), segment0.entrance() + 1);
  ASSERT_EQ(segment2.entrance(), segment0.entrance() + 2);
}

TEST(SegmentTest, SetsExit) {
  Segment prev_segment(10, NULL, 50, 100, 5);
  Segment segment(10, &prev_segment, 50, 100, 5);
  prev_segment.set_next(&segment);
  ASSERT_EQ(prev_segment.exit()->id(), segment.entrance());

  Junction junction;
  segment.set_exit(&junction);
  ASSERT_EQ(segment.exit()->id(), junction.id());
}

}  // namespace project
<commit_msg>Extended tests for Segment constructor<commit_after>#include "segment.h"
#include "gtest/gtest.h"

namespace project {

TEST(SegmentTest, CreatesRandomCars) {
  Segment segment(10, NULL, 50, 5, 5);
  ASSERT_GE(segment.num_cars(), 1);
  ASSERT_LE(segment.num_cars(), Segment::kMaxCars);
  ASSERT_LE(segment.num_cars(), 10);
  ASSERT_EQ(segment.ready_cars().size(), 50 * segment.num_cars() / 100);
  const std::vector<Car*>& cars = segment.cars();
  for (size_t i = 0; i < cars.size(); ++i) {
    ASSERT_EQ(cars[i]->segment(), &segment);
  }
}

TEST(SegmentTest, EntersLessOrEqualToCapacity) {
  Segment prev_segment(10, NULL, 50, 100, 5);
  Segment segment(10, &prev_segment, 50, 100, 5);
  prev_segment.set_next(&segment);
  segment.Enter();
  ASSERT_LE(segment.num_cars(), 10);
}

TEST(SegmentTest, RemovesCarsFromFreeway) {
  Segment segment(10, NULL, 50, 100, 5);
  Junction junction;
  segment.set_exit(&junction);
  std::vector<Car*> ready_cars = segment.ready_cars();
  size_t num_before_exit = segment.num_cars();

  size_t ready_to_exit = 0;
  for (size_t i = 0; i < ready_cars.size(); ++i) {
    if (ready_cars[i]->exit() == segment.exit()->id()) {
      ++ready_to_exit;
    }
  }

  segment.Exit();
  ASSERT_EQ(segment.num_cars(), num_before_exit - ready_to_exit);
}

TEST(SegmentTest, Operates) {
  Segment prev_segment(10, NULL, 50, 100, 5);
  Segment segment(10, &prev_segment, 50, 100, 5);
  Junction junction;
  segment.set_exit(&junction);
  prev_segment.set_next(&segment);
  std::vector<Car*> prev_ready_cars = segment.ready_cars();
  segment.Operate();
  std::vector<Car*> ready_cars = segment.ready_cars();

  ASSERT_GE(ready_cars.size(), prev_ready_cars.size());
  ASSERT_EQ(ready_cars.size() - prev_ready_cars.size(),
            50 * segment.num_cars() / 100);
  const std::vector<Car*>& cars_after_operation = segment.cars();
  for (size_t i = 0; i < cars_after_operation.size(); ++i) {
    ASSERT_EQ(cars_after_operation[i]->segment(), &segment);
  }
}

TEST(SegmentTest, PassesReadyCars) {
  Segment segment(10, NULL, 50, 100, 5);
  Segment next_segment(10, NULL, 50, 100, 5);
  segment.set_next(&next_segment);

  std::vector<Car*> ready_cars = segment.ready_cars();
  size_t ready_to_pass = 0;
  for (size_t i = 0; i < ready_cars.size(); ++i) {
    if (ready_cars[i]->exit() != segment.exit()->id()) {
      ++ready_to_pass;
    }
  }

  size_t num_before_pass = segment.num_cars();
  segment.Pass(5);
  if (num_before_pass >= 5) {
    ASSERT_GE(segment.num_cars(), num_before_pass - 5);
  }
  ASSERT_GE(segment.num_cars(), num_before_pass - ready_to_pass);
  ASSERT_LE(next_segment.num_cars(), 10);
}

TEST(SegmentTest, CreatesCarsWithGreaterExit) {
  Segment segment(10, NULL, 50, 100, 5);
  Junction junction;
  segment.set_exit(&junction);
  const std::vector<Car*>& cars = segment.cars();
  for (size_t i = 0; i < cars.size(); ++i) {
    ASSERT_GE(cars[i]->exit(), segment.exit()->id());
  }
}

TEST(SegmentTest, ReturnsReadyCars) {
  Segment segment(10, NULL, 50, 100, 5);
  std::vector<Car*> ready_cars = segment.ready_cars();

  ASSERT_LE(ready_cars.size(), segment.num_cars());
  for (size_t i = 0; i < ready_cars.size(); ++i) {
    ASSERT_EQ(ready_cars[i]->ready(), true);
  }
}

TEST(SegmentTest, ReturnsCapacity) {
  Segment segment(10, NULL, 50, 100, 5);
  ASSERT_EQ(segment.capacity(), 10);
}

TEST(SegmentTest, ReturnsEntrance) {
  Segment segment0(10, NULL, 50, 100, 5);
  Segment segment1(10, NULL, 50, 100, 5);
  Segment segment2(10, NULL, 50, 100, 5);
  ASSERT_GE(segment0.entrance(), 0);
  ASSERT_EQ(segment1.entrance(), segment0.entrance() + 1);
  ASSERT_EQ(segment2.entrance(), segment0.entrance() + 2);
}

TEST(SegmentTest, SetsExit) {
  Segment prev_segment(10, NULL, 50, 100, 5);
  Segment segment(10, &prev_segment, 50, 100, 5);
  prev_segment.set_next(&segment);
  ASSERT_EQ(prev_segment.exit()->id(), segment.entrance());

  Junction junction;
  segment.set_exit(&junction);
  ASSERT_EQ(segment.exit()->id(), junction.id());
}

}  // namespace project
<|endoftext|>


<commit_before><commit_msg>Fix stable_norm unit test for complexes<commit_after><|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkLogoRepresentation.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkLogoRepresentation.h"
#include "vtkCallbackCommand.h"
#include "vtkObjectFactory.h"
#include "vtkPoints.h"
#include "vtkCellArray.h"
#include "vtkPolyData.h"
#include "vtkPolyDataMapper2D.h"
#include "vtkProperty2D.h"
#include "vtkTexturedActor2D.h"
#include "vtkPolyData.h"
#include "vtkTexture.h"
#include "vtkPolyDataMapper2D.h"
#include "vtkFloatArray.h"
#include "vtkPointData.h"
#include "vtkImageData.h"
#include "vtkPropCollection.h"
#include "vtkRenderer.h"
#include "vtkWindow.h"

vtkStandardNewMacro(vtkLogoRepresentation);

vtkCxxSetObjectMacro(vtkLogoRepresentation, Image, vtkImageData);
vtkCxxSetObjectMacro(vtkLogoRepresentation, ImageProperty, vtkProperty2D);

//-------------------------------------------------------------------------
vtkLogoRepresentation::vtkLogoRepresentation()
{
  // Initialize the data members
  this->Image = NULL;
  this->ImageProperty = vtkProperty2D::New();

  // Setup the pipeline
  this->Texture = vtkTexture::New();
  this->TexturePolyData = vtkPolyData::New();
  this->TexturePoints = vtkPoints::New();
  this->TexturePoints->SetNumberOfPoints(4);
  this->TexturePolyData->SetPoints(this->TexturePoints);
  vtkCellArray* polys = vtkCellArray::New();
  polys->InsertNextCell(4);
  polys->InsertCellPoint(0);
  polys->InsertCellPoint(1);
  polys->InsertCellPoint(2);
  polys->InsertCellPoint(3);
  this->TexturePolyData->SetPolys(polys);
  polys->Delete();
  vtkFloatArray* tc = vtkFloatArray::New();
  tc->SetNumberOfComponents(2);
  tc->SetNumberOfTuples(4);
  tc->InsertComponent(0,0, 0.0);  tc->InsertComponent(0,1, 0.0);
  tc->InsertComponent(1,0, 1.0);  tc->InsertComponent(1,1, 0.0);
  tc->InsertComponent(2,0, 1.0);  tc->InsertComponent(2,1, 1.0);
  tc->InsertComponent(3,0, 0.0);  tc->InsertComponent(3,1, 1.0);
  this->TexturePolyData->GetPointData()->SetTCoords(tc);
  tc->Delete();
  this->TextureMapper = vtkPolyDataMapper2D::New();
  this->TextureMapper->SetInputData(this->TexturePolyData);
  this->TextureActor = vtkTexturedActor2D::New();
  this->TextureActor->SetMapper(this->TextureMapper);
  this->TextureActor->SetTexture(this->Texture);
  this->ImageProperty->SetOpacity(0.25);
  this->TextureActor->SetProperty(this->ImageProperty);

  // Set up parameters from thw superclass
  double size[2];
  this->GetSize(size);
  this->Position2Coordinate->SetValue(0.04*size[0], 0.04*size[1]);
  this->ProportionalResize = 1;
  this->Moving = 1;
  this->SetShowBorder(vtkBorderRepresentation::BORDER_ACTIVE);
  this->PositionCoordinate->SetValue(0.9, 0.025);
  this->Position2Coordinate->SetValue(0.075, 0.075);
}

//-------------------------------------------------------------------------
vtkLogoRepresentation::~vtkLogoRepresentation()
{
  if ( this->Image )
    {
    this->Image->Delete();
    }
  this->ImageProperty->Delete();
  this->Texture->Delete();
  this->TexturePoints->Delete();
  this->TexturePolyData->Delete();
  this->TextureMapper->Delete();
  this->TextureActor->Delete();
}

//----------------------------------------------------------------------
inline void vtkLogoRepresentation::AdjustImageSize(double o[2],
                                                   double borderSize[2],
                                                   double imageSize[2])
{
  // Scale the image to fit with in the border.
  // Also update the origin so the image is centered.
  double r0 = borderSize[0]/imageSize[0];
  double r1 = borderSize[1]/imageSize[1];
  if ( r0 > r1 )
    {
    imageSize[0] *= r1;
    imageSize[1] *= r1;
    }
  else
    {
    imageSize[0] *= r0;
    imageSize[1] *= r0;
    }

  if ( imageSize[0] < borderSize[0] )
    {
    o[0] += (borderSize[0]-imageSize[0])/2.0;
    }
  if ( imageSize[1] < borderSize[1] )
    {
    o[1] += (borderSize[1]-imageSize[1])/2.0;
    }
}

//-------------------------------------------------------------------------
void vtkLogoRepresentation::BuildRepresentation()
{
  if ( this->GetMTime() > this->BuildTime ||
       (this->Renderer && this->Renderer->GetVTKWindow() &&
        this->Renderer->GetVTKWindow()->GetMTime() > this->BuildTime) )
    {

    // Determine and adjust the size of the image
    if ( this->Image )
      {
      double imageSize[2], borderSize[2], o[2];
      imageSize[0] = 0.0;
      imageSize[1] = 0.0;
      //this->Image->Update();
      if ( this->Image->GetDataDimension() == 2 )
        {
        int dims[3];
        this->Image->GetDimensions(dims);
        imageSize[0] = static_cast<double>(dims[0]);
        imageSize[1] = static_cast<double>(dims[1]);
        }
      int *p1 = this->PositionCoordinate->
        GetComputedDisplayValue(this->Renderer);
      int *p2 = this->Position2Coordinate->
        GetComputedDisplayValue(this->Renderer);
      borderSize[0] = p2[0] - p1[0];
      borderSize[1] = p2[1] - p1[1];
      o[0] = static_cast<double>(p1[0]);
      o[1] = static_cast<double>(p1[1]);

      // this preserves the image aspect ratio. The image is
      // centered around the center of the bordered ragion.
      this->AdjustImageSize(o,borderSize,imageSize);

      // Update the points
      this->Texture->SetInputData(this->Image);
      this->TexturePoints->SetPoint(0, o[0],o[1],0.0);
      this->TexturePoints->SetPoint(1, o[0]+imageSize[0],o[1],0.0);
      this->TexturePoints->SetPoint(2, o[0]+imageSize[0],o[1]+imageSize[1],0.0);
      this->TexturePoints->SetPoint(3, o[0],o[1]+imageSize[1],0.0);
      }
    }

  // Note that the transform is updated by the superclass
  this->Superclass::BuildRepresentation();
}

//-------------------------------------------------------------------------
void vtkLogoRepresentation::GetActors2D(vtkPropCollection *pc)
{
  pc->AddItem(this->TextureActor);
  this->Superclass::GetActors2D(pc);
}

//-------------------------------------------------------------------------
void vtkLogoRepresentation::ReleaseGraphicsResources(vtkWindow *w)
{
  this->TextureActor->ReleaseGraphicsResources(w);
  this->Superclass::ReleaseGraphicsResources(w);
}

//-------------------------------------------------------------------------
int vtkLogoRepresentation::RenderOverlay(vtkViewport *v)
{
  int count = this->Superclass::RenderOverlay(v);
  vtkRenderer* ren = vtkRenderer::SafeDownCast(v);
  if (ren)
    {
    count += this->TextureActor->RenderOverlay(v);
    }
  return count;
}

//-------------------------------------------------------------------------
void vtkLogoRepresentation::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

  if ( this->Image )
    {
    os << indent << "Image:\n";
    this->Image->PrintSelf(os,indent.GetNextIndent());
    }
  else
    {
    os << indent << "Image: (none)\n";
    }

  if ( this->ImageProperty )
    {
    os << indent << "Image Property:\n";
    this->ImageProperty->PrintSelf(os,indent.GetNextIndent());
    }
  else
    {
    os << indent << "Image Property: (none)\n";
    }
}
<commit_msg>Displaying border on top of logo so it is not hidden<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkLogoRepresentation.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkLogoRepresentation.h"
#include "vtkCallbackCommand.h"
#include "vtkObjectFactory.h"
#include "vtkPoints.h"
#include "vtkCellArray.h"
#include "vtkPolyData.h"
#include "vtkPolyDataMapper2D.h"
#include "vtkProperty2D.h"
#include "vtkTexturedActor2D.h"
#include "vtkPolyData.h"
#include "vtkTexture.h"
#include "vtkPolyDataMapper2D.h"
#include "vtkFloatArray.h"
#include "vtkPointData.h"
#include "vtkImageData.h"
#include "vtkPropCollection.h"
#include "vtkRenderer.h"
#include "vtkWindow.h"

vtkStandardNewMacro(vtkLogoRepresentation);

vtkCxxSetObjectMacro(vtkLogoRepresentation, Image, vtkImageData);
vtkCxxSetObjectMacro(vtkLogoRepresentation, ImageProperty, vtkProperty2D);

//-------------------------------------------------------------------------
vtkLogoRepresentation::vtkLogoRepresentation()
{
  // Initialize the data members
  this->Image = NULL;
  this->ImageProperty = vtkProperty2D::New();

  // Setup the pipeline
  this->Texture = vtkTexture::New();
  this->TexturePolyData = vtkPolyData::New();
  this->TexturePoints = vtkPoints::New();
  this->TexturePoints->SetNumberOfPoints(4);
  this->TexturePolyData->SetPoints(this->TexturePoints);
  vtkCellArray* polys = vtkCellArray::New();
  polys->InsertNextCell(4);
  polys->InsertCellPoint(0);
  polys->InsertCellPoint(1);
  polys->InsertCellPoint(2);
  polys->InsertCellPoint(3);
  this->TexturePolyData->SetPolys(polys);
  polys->Delete();
  vtkFloatArray* tc = vtkFloatArray::New();
  tc->SetNumberOfComponents(2);
  tc->SetNumberOfTuples(4);
  tc->InsertComponent(0,0, 0.0);  tc->InsertComponent(0,1, 0.0);
  tc->InsertComponent(1,0, 1.0);  tc->InsertComponent(1,1, 0.0);
  tc->InsertComponent(2,0, 1.0);  tc->InsertComponent(2,1, 1.0);
  tc->InsertComponent(3,0, 0.0);  tc->InsertComponent(3,1, 1.0);
  this->TexturePolyData->GetPointData()->SetTCoords(tc);
  tc->Delete();
  this->TextureMapper = vtkPolyDataMapper2D::New();
  this->TextureMapper->SetInputData(this->TexturePolyData);
  this->TextureActor = vtkTexturedActor2D::New();
  this->TextureActor->SetMapper(this->TextureMapper);
  this->TextureActor->SetTexture(this->Texture);
  this->ImageProperty->SetOpacity(0.25);
  this->TextureActor->SetProperty(this->ImageProperty);

  // Set up parameters from thw superclass
  double size[2];
  this->GetSize(size);
  this->Position2Coordinate->SetValue(0.04*size[0], 0.04*size[1]);
  this->ProportionalResize = 1;
  this->Moving = 1;
  this->SetShowBorder(vtkBorderRepresentation::BORDER_ACTIVE);
  this->PositionCoordinate->SetValue(0.9, 0.025);
  this->Position2Coordinate->SetValue(0.075, 0.075);
}

//-------------------------------------------------------------------------
vtkLogoRepresentation::~vtkLogoRepresentation()
{
  if ( this->Image )
    {
    this->Image->Delete();
    }
  this->ImageProperty->Delete();
  this->Texture->Delete();
  this->TexturePoints->Delete();
  this->TexturePolyData->Delete();
  this->TextureMapper->Delete();
  this->TextureActor->Delete();
}

//----------------------------------------------------------------------
inline void vtkLogoRepresentation::AdjustImageSize(double o[2],
                                                   double borderSize[2],
                                                   double imageSize[2])
{
  // Scale the image to fit with in the border.
  // Also update the origin so the image is centered.
  double r0 = borderSize[0]/imageSize[0];
  double r1 = borderSize[1]/imageSize[1];
  if ( r0 > r1 )
    {
    imageSize[0] *= r1;
    imageSize[1] *= r1;
    }
  else
    {
    imageSize[0] *= r0;
    imageSize[1] *= r0;
    }

  if ( imageSize[0] < borderSize[0] )
    {
    o[0] += (borderSize[0]-imageSize[0])/2.0;
    }
  if ( imageSize[1] < borderSize[1] )
    {
    o[1] += (borderSize[1]-imageSize[1])/2.0;
    }
}

//-------------------------------------------------------------------------
void vtkLogoRepresentation::BuildRepresentation()
{
  if ( this->GetMTime() > this->BuildTime ||
       (this->Renderer && this->Renderer->GetVTKWindow() &&
        this->Renderer->GetVTKWindow()->GetMTime() > this->BuildTime) )
    {

    // Determine and adjust the size of the image
    if ( this->Image )
      {
      double imageSize[2], borderSize[2], o[2];
      imageSize[0] = 0.0;
      imageSize[1] = 0.0;
      //this->Image->Update();
      if ( this->Image->GetDataDimension() == 2 )
        {
        int dims[3];
        this->Image->GetDimensions(dims);
        imageSize[0] = static_cast<double>(dims[0]);
        imageSize[1] = static_cast<double>(dims[1]);
        }
      int *p1 = this->PositionCoordinate->
        GetComputedDisplayValue(this->Renderer);
      int *p2 = this->Position2Coordinate->
        GetComputedDisplayValue(this->Renderer);
      borderSize[0] = p2[0] - p1[0];
      borderSize[1] = p2[1] - p1[1];
      o[0] = static_cast<double>(p1[0]);
      o[1] = static_cast<double>(p1[1]);

      // this preserves the image aspect ratio. The image is
      // centered around the center of the bordered ragion.
      this->AdjustImageSize(o,borderSize,imageSize);

      // Update the points
      this->Texture->SetInputData(this->Image);
      this->TexturePoints->SetPoint(0, o[0],o[1],0.0);
      this->TexturePoints->SetPoint(1, o[0]+imageSize[0],o[1],0.0);
      this->TexturePoints->SetPoint(2, o[0]+imageSize[0],o[1]+imageSize[1],0.0);
      this->TexturePoints->SetPoint(3, o[0],o[1]+imageSize[1],0.0);
      }
    }

  // Note that the transform is updated by the superclass
  this->Superclass::BuildRepresentation();
}

//-------------------------------------------------------------------------
void vtkLogoRepresentation::GetActors2D(vtkPropCollection *pc)
{
  pc->AddItem(this->TextureActor);
  this->Superclass::GetActors2D(pc);
}

//-------------------------------------------------------------------------
void vtkLogoRepresentation::ReleaseGraphicsResources(vtkWindow *w)
{
  this->TextureActor->ReleaseGraphicsResources(w);
  this->Superclass::ReleaseGraphicsResources(w);
}

//-------------------------------------------------------------------------
int vtkLogoRepresentation::RenderOverlay(vtkViewport *v)
{
  int count = 0;
  vtkRenderer* ren = vtkRenderer::SafeDownCast(v);
  if (ren)
    {
    count += this->TextureActor->RenderOverlay(v);
    }
  // Display border on top of logo
  count += this->Superclass::RenderOverlay(v);
  return count;
}

//-------------------------------------------------------------------------
void vtkLogoRepresentation::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

  if ( this->Image )
    {
    os << indent << "Image:\n";
    this->Image->PrintSelf(os,indent.GetNextIndent());
    }
  else
    {
    os << indent << "Image: (none)\n";
    }

  if ( this->ImageProperty )
    {
    os << indent << "Image Property:\n";
    this->ImageProperty->PrintSelf(os,indent.GetNextIndent());
    }
  else
    {
    os << indent << "Image Property: (none)\n";
    }
}
<|endoftext|>