text
stringlengths 5
1.04M
|
|---|
// dll-shenanigans.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
int main()
{
std::cout << "Hello World!\n";
}
// Run program: Ctrl + F5 or Debug > Start Without Debugging menu
// Debug program: F5 or Debug > Start Debugging menu
// Tips for Getting Started:
// 1. Use the Solution Explorer window to add/manage files
// 2. Use the Team Explorer window to connect to source control
// 3. Use the Output window to see build output and other messages
// 4. Use the Error List window to view errors
// 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
// 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
|
// STLport regression testsuite component.
// To compile as a separate example, please #define MAIN.
#include <algorithm>
#include <vector>
#include <iostream>
#include <iterator>
#include <functional>
#include <iterator>
#ifdef MAIN
#define replace1_test main
#endif
#if !defined (STLPORT) || defined(__STL_USE_NAMESPACES)
using namespace std;
#endif
int replace1_test(int, char**)
{
cout<<"Results of replace1_test:"<<endl;
vector <int> v1(10);
for(int i = 0; i < v1.size(); i++)
v1[i] = i % 5;
ostream_iterator <int> iter(cout, " ");
copy(v1.begin(), v1.end(), iter);
cout << endl;
replace(v1.begin(), v1.end(), 2, 42);
copy(v1.begin(), v1.end(), iter);
cout << endl;
return 0;
}
|
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int i = m - 1, j = n - 1, k = m + n - 1;
while (j >= 0)
{
nums1[k--] = (i >= 0 && nums1[i] > nums2[j]) ? nums1[i--] : nums2[j--];
}
}
};
|
// REQUIRES: asan-64-bits
// Regression test: __tls_get_addr interceptor must recognize static TLS.
//
// RUN: %clangxx_asan -DSHARED %s -shared -o %t-so.so -fPIC
// RUN: %clangxx_asan %s -ldl -pthread -o %t %t-so.so
// RUN: %env_asan_opts=verbosity=2 %run %t 2>&1 | FileCheck %s
// CHECK: before
// CHECK: __tls_get_addr: static tls
// CHECK: after
// XFAIL: powerpc64, aarch64
#ifndef SHARED
#include <stdio.h>
unsigned *f();
int main(int argc, char *argv[]) {
fprintf(stderr, "before\n");
f();
fprintf(stderr, "after\n");
return 0;
}
#else // SHARED
static __thread unsigned ThreadLocal;
unsigned *f() {
return &ThreadLocal;
}
#endif
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/history/android/android_provider_backend.h"
#include "base/i18n/case_conversion.h"
#include "chrome/browser/bookmarks/bookmark_service.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/favicon/favicon_changed_details.h"
#include "chrome/browser/history/android/android_time.h"
#include "chrome/browser/history/android/android_urls_sql_handler.h"
#include "chrome/browser/history/android/bookmark_model_sql_handler.h"
#include "chrome/browser/history/android/favicon_sql_handler.h"
#include "chrome/browser/history/android/urls_sql_handler.h"
#include "chrome/browser/history/android/visit_sql_handler.h"
#include "chrome/browser/history/history_backend.h"
#include "chrome/browser/history/history_database.h"
#include "chrome/browser/history/thumbnail_database.h"
#include "content/public/common/page_transition_types.h"
#include "sql/connection.h"
using base::Time;
using base::TimeDelta;
namespace history {
namespace {
const char* kVirtualHistoryAndBookmarkTable =
"SELECT android_urls.id AS _id, "
"android_cache_db.bookmark_cache.created_time AS created, "
"urls.title AS title, android_urls.raw_url AS url, "
"urls.visit_count AS visits, "
"android_cache_db.bookmark_cache.last_visit_time AS date, "
"android_cache_db.bookmark_cache.bookmark AS bookmark, "
"android_cache_db.bookmark_cache.favicon_id AS favicon, "
"urls.id AS url_id, urls.url AS urls_url, "
// TODO (michaelbai) : Remove folder column once we remove it from Android
// framework.
// Android framework assumes 'folder' column exist in the table, the row is
// the bookmark once folder is 0, though it is not part of public API, it
// has to be added and set as 0 when the row is bookmark.
"(CASE WHEN android_cache_db.bookmark_cache.bookmark IS 0 "
"THEN 1 ELSE 0 END) as folder "
"FROM (android_urls JOIN urls on (android_urls.url_id = urls.id) "
"LEFT JOIN android_cache_db.bookmark_cache "
"on (android_urls.url_id = android_cache_db.bookmark_cache.url_id))";
const char * kURLUpdateClause =
"SELECT urls.id, urls.last_visit_time, created_time, urls.url "
"FROM urls LEFT JOIN "
"(SELECT url as visit_url, min(visit_time) as created_time"
" FROM visits GROUP BY url) ON (visit_url = urls.id) ";
const char* kSearchTermUpdateClause =
"SELECT keyword_search_terms.term, max(urls.last_visit_time) "
"FROM keyword_search_terms JOIN urls ON "
"(keyword_search_terms.url_id = urls.id) "
"GROUP BY keyword_search_terms.term";
void BindStatement(const std::vector<string16>& selection_args,
sql::Statement* statement,
int* col_index) {
for (std::vector<string16>::const_iterator i = selection_args.begin();
i != selection_args.end(); ++i) {
// Using the same method as Android, binding all argument as String.
statement->BindString16(*col_index, *i);
(*col_index)++;
}
}
bool IsHistoryAndBookmarkRowValid(const HistoryAndBookmarkRow& row) {
// The caller should make sure both/neither Raw URL and/nor URL should be set.
DCHECK(row.is_value_set_explicitly(HistoryAndBookmarkRow::RAW_URL) ==
row.is_value_set_explicitly(HistoryAndBookmarkRow::URL));
// The following cases are checked:
// a. Last visit time or created time is large than now.
// b. Last visit time is less than created time.
// c. Created time and last visit time is different, but visit count is less
// than 2.
// d. The difference between created and last visit time is less than
// visit_count.
// e. Visit count is 0 or 1 and both last visit time and created time are set
// explicitly, but the time is different or created time is not UnixEpoch.
if (row.is_value_set_explicitly(HistoryAndBookmarkRow::LAST_VISIT_TIME) &&
row.last_visit_time() > Time::Now())
return false;
if (row.is_value_set_explicitly(HistoryAndBookmarkRow::CREATED) &&
row.created() > Time::Now())
return false;
if (row.is_value_set_explicitly(HistoryAndBookmarkRow::LAST_VISIT_TIME) &&
row.is_value_set_explicitly(HistoryAndBookmarkRow::CREATED)) {
if (row.created() > row.last_visit_time())
return false;
if (row.is_value_set_explicitly(HistoryAndBookmarkRow::VISIT_COUNT) &&
row.is_value_set_explicitly(HistoryAndBookmarkRow::CREATED) &&
row.is_value_set_explicitly(HistoryAndBookmarkRow::LAST_VISIT_TIME)) {
if (row.created() != row.last_visit_time() &&
row.created() != Time::UnixEpoch() &&
(row.visit_count() == 0 || row.visit_count() == 1))
return false;
if (row.last_visit_time().ToInternalValue() -
row.created().ToInternalValue() < row.visit_count())
return false;
}
}
return true;
}
} // namespace
AndroidProviderBackend::AndroidProviderBackend(
const base::FilePath& db_name,
HistoryDatabase* history_db,
ThumbnailDatabase* thumbnail_db,
BookmarkService* bookmark_service,
HistoryBackend::Delegate* delegate)
: android_cache_db_filename_(db_name),
db_(&history_db->GetDB()),
history_db_(history_db),
thumbnail_db_(thumbnail_db),
bookmark_service_(bookmark_service),
initialized_(false),
delegate_(delegate) {
DCHECK(delegate_);
}
AndroidProviderBackend::~AndroidProviderBackend() {
}
AndroidStatement* AndroidProviderBackend::QueryHistoryAndBookmarks(
const std::vector<HistoryAndBookmarkRow::ColumnID>& projections,
const std::string& selection,
const std::vector<string16>& selection_args,
const std::string& sort_order) {
if (projections.empty())
return NULL;
ScopedTransaction transaction(history_db_, thumbnail_db_);
if (!EnsureInitializedAndUpdated())
return NULL;
transaction.Commit();
return QueryHistoryAndBookmarksInternal(projections, selection,
selection_args, sort_order);
}
bool AndroidProviderBackend::UpdateHistoryAndBookmarks(
const HistoryAndBookmarkRow& row,
const std::string& selection,
const std::vector<string16>& selection_args,
int* updated_count) {
HistoryNotifications notifications;
ScopedTransaction transaction(history_db_, thumbnail_db_);
if (!UpdateHistoryAndBookmarks(row, selection, selection_args, updated_count,
¬ifications))
return false;
transaction.Commit();
BroadcastNotifications(notifications);
return true;
}
AndroidURLID AndroidProviderBackend::InsertHistoryAndBookmark(
const HistoryAndBookmarkRow& values) {
HistoryNotifications notifications;
ScopedTransaction transaction(history_db_, thumbnail_db_);
AndroidURLID id = InsertHistoryAndBookmark(values, ¬ifications, true);
if (id) {
transaction.Commit();
BroadcastNotifications(notifications);
return id;
}
return 0;
}
bool AndroidProviderBackend::DeleteHistoryAndBookmarks(
const std::string& selection,
const std::vector<string16>& selection_args,
int* deleted_count) {
HistoryNotifications notifications;
ScopedTransaction transaction(history_db_, thumbnail_db_);
if (!DeleteHistoryAndBookmarks(selection, selection_args, deleted_count,
¬ifications))
return false;
transaction.Commit();
BroadcastNotifications(notifications);
return true;
}
bool AndroidProviderBackend::DeleteHistory(
const std::string& selection,
const std::vector<string16>& selection_args,
int* deleted_count) {
HistoryNotifications notifications;
ScopedTransaction transaction(history_db_, thumbnail_db_);
if (!DeleteHistory(selection, selection_args, deleted_count,
¬ifications))
return false;
transaction.Commit();
BroadcastNotifications(notifications);
return true;
}
AndroidProviderBackend::HistoryNotification::HistoryNotification(
int type,
HistoryDetails* detail)
: type(type),
detail(detail) {
}
AndroidProviderBackend::HistoryNotification::~HistoryNotification() {
}
AndroidProviderBackend::ScopedTransaction::ScopedTransaction(
HistoryDatabase* history_db,
ThumbnailDatabase* thumbnail_db)
: history_db_(history_db),
thumbnail_db_(thumbnail_db),
committed_(false),
history_transaction_nesting_(history_db_->transaction_nesting()),
thumbnail_transaction_nesting_(
thumbnail_db_ ? thumbnail_db_->transaction_nesting() : 0) {
// Commit all existing transactions since the AndroidProviderBackend's
// transaction is very like to be rolled back when compared with the others.
// The existing transactions have been scheduled to commit by
// ScheduleCommit in HistoryBackend and the same number of transaction
// will be created after this scoped transaction ends, there should have no
// issue to directly commit all transactions here.
int count = history_transaction_nesting_;
while (count--)
history_db_->CommitTransaction();
history_db_->BeginTransaction();
if (thumbnail_db_) {
count = thumbnail_transaction_nesting_;
while (count--)
thumbnail_db_->CommitTransaction();
thumbnail_db_->BeginTransaction();
}
}
AndroidProviderBackend::ScopedTransaction::~ScopedTransaction() {
if (!committed_) {
history_db_->RollbackTransaction();
if (thumbnail_db_)
thumbnail_db_->RollbackTransaction();
}
// There is no transaction now.
DCHECK_EQ(0, history_db_->transaction_nesting());
DCHECK(!thumbnail_db_ || 0 == thumbnail_db_->transaction_nesting());
int count = history_transaction_nesting_;
while (count--)
history_db_->BeginTransaction();
if (thumbnail_db_) {
count = thumbnail_transaction_nesting_;
while (count--)
thumbnail_db_->BeginTransaction();
}
}
void AndroidProviderBackend::ScopedTransaction::Commit() {
DCHECK(!committed_);
history_db_->CommitTransaction();
if (thumbnail_db_)
thumbnail_db_->CommitTransaction();
committed_ = true;
}
bool AndroidProviderBackend::UpdateHistoryAndBookmarks(
const HistoryAndBookmarkRow& row,
const std::string& selection,
const std::vector<string16>& selection_args,
int* updated_count,
HistoryNotifications* notifications) {
if (!IsHistoryAndBookmarkRowValid(row))
return false;
if (row.is_value_set_explicitly(HistoryAndBookmarkRow::ID))
return false;
if (!EnsureInitializedAndUpdated())
return false;
TableIDRows ids_set;
if (!GetSelectedURLs(selection, selection_args, &ids_set))
return false;
if (ids_set.empty()) {
*updated_count = 0;
return true;
}
// URL can not be updated, we simulate the update.
if (row.is_value_set_explicitly(HistoryAndBookmarkRow::URL)) {
// Only one row's URL can be updated at a time as we can't have multiple
// rows have the same URL.
if (ids_set.size() != 1)
return false;
HistoryAndBookmarkRow new_row = row;
if (!SimulateUpdateURL(new_row, ids_set, notifications))
return false;
*updated_count = 1;
return true;
}
for (std::vector<SQLHandler*>::iterator i =
sql_handlers_.begin(); i != sql_handlers_.end(); ++i) {
if ((*i)->HasColumnIn(row)) {
if (!(*i)->Update(row, ids_set))
return false;
}
}
*updated_count = ids_set.size();
scoped_ptr<URLsModifiedDetails> modified(new URLsModifiedDetails);
scoped_ptr<FaviconChangedDetails> favicon(new FaviconChangedDetails);
for (TableIDRows::const_iterator i = ids_set.begin(); i != ids_set.end();
++i) {
if (row.is_value_set_explicitly(HistoryAndBookmarkRow::TITLE) ||
row.is_value_set_explicitly(HistoryAndBookmarkRow::VISIT_COUNT) ||
row.is_value_set_explicitly(HistoryAndBookmarkRow::LAST_VISIT_TIME)) {
URLRow url_row;
if (!history_db_->GetURLRow(i->url_id, &url_row))
return false;
modified->changed_urls.push_back(url_row);
}
if (thumbnail_db_ &&
row.is_value_set_explicitly(HistoryAndBookmarkRow::FAVICON))
favicon->urls.insert(i->url);
}
if (!modified->changed_urls.empty())
notifications->push_back(HistoryNotification(
chrome::NOTIFICATION_HISTORY_URLS_MODIFIED, modified.release()));
if (!favicon->urls.empty())
notifications->push_back(HistoryNotification(
chrome::NOTIFICATION_FAVICON_CHANGED, favicon.release()));
return true;
}
AndroidURLID AndroidProviderBackend::InsertHistoryAndBookmark(
const HistoryAndBookmarkRow& values,
HistoryNotifications* notifications,
bool ensure_initialized_and_updated) {
if (!IsHistoryAndBookmarkRowValid(values))
return false;
if (ensure_initialized_and_updated && !EnsureInitializedAndUpdated())
return 0;
DCHECK(values.is_value_set_explicitly(HistoryAndBookmarkRow::URL));
// Make a copy of values as we need change it during insert.
HistoryAndBookmarkRow row = values;
for (std::vector<SQLHandler*>::iterator i =
sql_handlers_.begin(); i != sql_handlers_.end(); ++i) {
if (!(*i)->Insert(&row))
return 0;
}
URLRow url_row;
if (!history_db_->GetURLRow(row.url_id(), &url_row))
return false;
scoped_ptr<URLsModifiedDetails> modified(new URLsModifiedDetails);
if (!modified.get())
return false;
modified->changed_urls.push_back(url_row);
scoped_ptr<FaviconChangedDetails> favicon;
// No favicon should be changed if the thumbnail_db_ is not available.
if (row.is_value_set_explicitly(HistoryAndBookmarkRow::FAVICON) &&
row.favicon_valid() && thumbnail_db_) {
favicon.reset(new FaviconChangedDetails);
if (!favicon.get())
return false;
favicon->urls.insert(url_row.url());
}
notifications->push_back(HistoryNotification(
chrome::NOTIFICATION_HISTORY_URLS_MODIFIED, modified.release()));
if (favicon.get())
notifications->push_back(HistoryNotification(
chrome::NOTIFICATION_FAVICON_CHANGED, favicon.release()));
return row.id();
}
bool AndroidProviderBackend::DeleteHistoryAndBookmarks(
const std::string& selection,
const std::vector<string16>& selection_args,
int * deleted_count,
HistoryNotifications* notifications) {
if (!EnsureInitializedAndUpdated())
return false;
TableIDRows ids_set;
if (!GetSelectedURLs(selection, selection_args, &ids_set))
return false;
if (ids_set.empty()) {
*deleted_count = 0;
return true;
}
if (!DeleteHistoryInternal(ids_set, true, notifications))
return false;
*deleted_count = ids_set.size();
return true;
}
bool AndroidProviderBackend::DeleteHistory(
const std::string& selection,
const std::vector<string16>& selection_args,
int* deleted_count,
HistoryNotifications* notifications) {
if (!EnsureInitializedAndUpdated())
return false;
TableIDRows ids_set;
if (!GetSelectedURLs(selection, selection_args, &ids_set))
return false;
if (ids_set.empty()) {
*deleted_count = 0;
return true;
}
*deleted_count = ids_set.size();
// Get the bookmarked rows.
std::vector<HistoryAndBookmarkRow> bookmarks;
for (TableIDRows::const_iterator i = ids_set.begin(); i != ids_set.end();
++i) {
if (i->bookmarked) {
AndroidURLRow android_url_row;
if (!history_db_->GetAndroidURLRow(i->url_id, &android_url_row))
return false;
HistoryAndBookmarkRow row;
row.set_raw_url(android_url_row.raw_url);
row.set_url(i->url);
// Set the visit time to the UnixEpoch since that's when the Android
// system time starts. The Android have a CTS testcase for this.
row.set_last_visit_time(Time::UnixEpoch());
row.set_visit_count(0);
// We don't want to change the bookmark model, so set_is_bookmark() is
// not called.
bookmarks.push_back(row);
}
}
// Don't delete the bookmark from bookmark model when deleting the history.
if (!DeleteHistoryInternal(ids_set, false, notifications))
return false;
for (std::vector<HistoryAndBookmarkRow>::const_iterator i = bookmarks.begin();
i != bookmarks.end(); ++i) {
// Don't update the tables, otherwise, the bookmarks will be added to
// database during UpdateBookmark(), then the insertion will fail.
// We can't rely on UpdateBookmark() to insert the bookmarks into history
// database as the raw_url will be lost.
if (!InsertHistoryAndBookmark(*i, notifications, false))
return false;
}
return true;
}
AndroidStatement* AndroidProviderBackend::QuerySearchTerms(
const std::vector<SearchRow::ColumnID>& projections,
const std::string& selection,
const std::vector<string16>& selection_args,
const std::string& sort_order) {
if (projections.empty())
return NULL;
if (!EnsureInitializedAndUpdated())
return NULL;
std::string sql;
sql.append("SELECT ");
AppendSearchResultColumn(projections, &sql);
sql.append(" FROM android_cache_db.search_terms ");
if (!selection.empty()) {
sql.append(" WHERE ");
sql.append(selection);
}
if (!sort_order.empty()) {
sql.append(" ORDER BY ");
sql.append(sort_order);
}
scoped_ptr<sql::Statement> statement(new sql::Statement(
db_->GetUniqueStatement(sql.c_str())));
int count = 0;
BindStatement(selection_args, statement.get(), &count);
if (!statement->is_valid()) {
LOG(ERROR) << db_->GetErrorMessage();
return NULL;
}
sql::Statement* result = statement.release();
return new AndroidStatement(result, -1);
}
bool AndroidProviderBackend::UpdateSearchTerms(
const SearchRow& row,
const std::string& selection,
const std::vector<string16>& selection_args,
int* update_count) {
if (!EnsureInitializedAndUpdated())
return false;
SearchTerms search_terms;
if (!GetSelectedSearchTerms(selection, selection_args, &search_terms))
return false;
// We can not update search term if multiple row selected.
if (row.is_value_set_explicitly(SearchRow::SEARCH_TERM) &&
search_terms.size() > 1)
return false;
*update_count = search_terms.size();
if (search_terms.empty())
return true;
if (row.is_value_set_explicitly(SearchRow::SEARCH_TERM)) {
SearchTermRow search_term_row;
SearchRow search_row = row;
if (!history_db_->GetSearchTerm(search_terms[0], &search_term_row))
return false;
search_term_row.term = search_row.search_term();
if (!search_row.is_value_set_explicitly(SearchRow::SEARCH_TIME))
search_row.set_search_time(search_term_row.last_visit_time);
else
search_term_row.last_visit_time = search_row.search_time();
// Delete the original search term.
if (!history_db_->DeleteKeywordSearchTerm(search_terms[0]))
return false;
// Add the new one.
if (!AddSearchTerm(search_row))
return false;
// Update the cache table so the id will not be changed.
if (!history_db_->UpdateSearchTerm(search_term_row.id, search_term_row))
return false;
return true;
}
for (SearchTerms::const_iterator i = search_terms.begin();
i != search_terms.end(); ++i) {
SearchTermRow search_term_row;
if (!history_db_->GetSearchTerm(*i, &search_term_row))
return false;
// Check whether the given search time less than the existing one.
if (search_term_row.last_visit_time > row.search_time())
return false;
std::vector<KeywordSearchTermRow> search_term_rows;
if (!history_db_->GetKeywordSearchTermRows(*i, &search_term_rows) ||
search_term_rows.empty())
return false;
// Actually only search_time update. As there might multiple URLs
// asocciated with the keyword, Just update the first one's last_visit_time.
URLRow url_row;
if (!history_db_->GetURLRow(search_term_rows[0].url_id, &url_row))
return false;
HistoryAndBookmarkRow bookmark_row;
bookmark_row.set_last_visit_time(row.search_time());
TableIDRow table_id_row;
table_id_row.url_id = url_row.id();
TableIDRows table_id_rows;
table_id_rows.push_back(table_id_row);
if (!urls_handler_->Update(bookmark_row, table_id_rows))
return false;
if (!visit_handler_->Update(bookmark_row, table_id_rows))
return false;
}
return true;
}
SearchTermID AndroidProviderBackend::InsertSearchTerm(
const SearchRow& values) {
if (!EnsureInitializedAndUpdated())
return 0;
if (!AddSearchTerm(values))
return 0;
SearchTermID id = history_db_->GetSearchTerm(values.search_term(), NULL);
if (!id)
// Note the passed in Time() will be changed in UpdateSearchTermTable().
id = history_db_->AddSearchTerm(values.search_term(), Time());
return id;
}
bool AndroidProviderBackend::DeleteSearchTerms(
const std::string& selection,
const std::vector<string16>& selection_args,
int * deleted_count) {
if (!EnsureInitializedAndUpdated())
return false;
SearchTerms rows;
if (!GetSelectedSearchTerms(selection, selection_args, &rows))
return false;
*deleted_count = rows.size();
if (rows.empty())
return true;
for (SearchTerms::const_iterator i = rows.begin(); i != rows.end(); ++i)
if (!history_db_->DeleteKeywordSearchTerm(*i))
return false;
// We don't delete the rows in search_terms table, as once the
// search_terms table is updated with keyword_search_terms, all
// keyword cache not found in the keyword_search_terms will be removed.
return true;
}
bool AndroidProviderBackend::EnsureInitializedAndUpdated() {
if (!initialized_) {
if (!Init())
return false;
}
return UpdateTables();
}
bool AndroidProviderBackend::Init() {
urls_handler_.reset(new UrlsSQLHandler(history_db_));
visit_handler_.reset(new VisitSQLHandler(history_db_));
android_urls_handler_.reset(new AndroidURLsSQLHandler(history_db_));
if (thumbnail_db_)
favicon_handler_.reset(new FaviconSQLHandler(thumbnail_db_));
bookmark_model_handler_.reset(new BookmarkModelSQLHandler(history_db_));
// The urls_handler must be pushed first, because the subsequent handlers
// depend on its output.
sql_handlers_.push_back(urls_handler_.get());
sql_handlers_.push_back(visit_handler_.get());
sql_handlers_.push_back(android_urls_handler_.get());
if (favicon_handler_.get())
sql_handlers_.push_back(favicon_handler_.get());
sql_handlers_.push_back(bookmark_model_handler_.get());
if (!history_db_->CreateAndroidURLsTable())
return false;
if (sql::INIT_OK != history_db_->InitAndroidCacheDatabase(
android_cache_db_filename_))
return false;
initialized_ = true;
return true;
}
bool AndroidProviderBackend::UpdateTables() {
if (!UpdateVisitedURLs()) {
LOG(ERROR) << "Update of the visisted URLS failed";
return false;
}
if (!UpdateRemovedURLs()) {
LOG(ERROR) << "Update of the removed URLS failed";
return false;
}
if (!UpdateBookmarks()) {
LOG(ERROR) << "Update of the bookmarks failed";
return false;
}
if (!UpdateFavicon()) {
LOG(ERROR) << "Update of the icons failed";
return false;
}
if (!UpdateSearchTermTable()) {
LOG(ERROR) << "Update of the search_terms failed";
return false;
}
return true;
}
bool AndroidProviderBackend::UpdateVisitedURLs() {
std::string sql(kURLUpdateClause);
sql.append("WHERE urls.id NOT IN (SELECT url_id FROM android_urls)");
sql::Statement urls_statement(db_->GetCachedStatement(SQL_FROM_HERE,
sql.c_str()));
if (!urls_statement.is_valid()) {
LOG(ERROR) << db_->GetErrorMessage();
return false;
}
while (urls_statement.Step()) {
if (history_db_->GetAndroidURLRow(urls_statement.ColumnInt64(0), NULL))
continue;
if (!history_db_->AddAndroidURLRow(urls_statement.ColumnString(3),
urls_statement.ColumnInt64(0)))
return false;
}
if (!history_db_->ClearAllBookmarkCache())
return false;
sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE,
kURLUpdateClause));
while (statement.Step()) {
// The last_visit_time and the created time should be same when the visit
// count is 0, this behavior is also required by the Android CTS.
// The created_time could be set to the last_visit_time only when the type
// of the 'created' column is NULL because the left join is used in query
// and there is no row in the visit table when the visit count is 0.
Time last_visit_time = Time::FromInternalValue(statement.ColumnInt64(1));
Time created_time = last_visit_time;
if (statement.ColumnType(2) != sql::COLUMN_TYPE_NULL)
created_time = Time::FromInternalValue(statement.ColumnInt64(2));
if (!history_db_->AddBookmarkCacheRow(created_time, last_visit_time,
statement.ColumnInt64(0)))
return false;
}
return true;
}
bool AndroidProviderBackend::UpdateRemovedURLs() {
return history_db_->DeleteUnusedAndroidURLs();
}
bool AndroidProviderBackend::UpdateBookmarks() {
if (bookmark_service_ == NULL) {
LOG(ERROR) << "Bookmark service is not available";
return false;
}
bookmark_service_->BlockTillLoaded();
std::vector<BookmarkService::URLAndTitle> bookmarks;
bookmark_service_->GetBookmarks(&bookmarks);
if (bookmarks.empty())
return true;
std::vector<URLID> url_ids;
for (std::vector<BookmarkService::URLAndTitle>::const_iterator i =
bookmarks.begin(); i != bookmarks.end(); ++i) {
URLID url_id = history_db_->GetRowForURL(i->url, NULL);
if (url_id == 0) {
URLRow url_row(i->url);
url_row.set_title(i->title);
// Set the visit time to the UnixEpoch since that's when the Android
// system time starts. The Android have a CTS testcase for this.
url_row.set_last_visit(Time::UnixEpoch());
url_row.set_hidden(true);
url_id = history_db_->AddURL(url_row);
if (url_id == 0) {
LOG(ERROR) << "Can not add url for the new bookmark";
return false;
}
if (!history_db_->AddAndroidURLRow(i->url.spec(), url_id))
return false;
if (!history_db_->AddBookmarkCacheRow(Time::UnixEpoch(),
Time::UnixEpoch(), url_id))
return false;
}
url_ids.push_back(url_id);
}
return history_db_->MarkURLsAsBookmarked(url_ids);
}
bool AndroidProviderBackend::UpdateFavicon() {
ThumbnailDatabase::IconMappingEnumerator enumerator;
// We want the AndroidProviderBackend run without thumbnail_db_
if (!thumbnail_db_)
return true;
if (!thumbnail_db_->InitIconMappingEnumerator(chrome::FAVICON, &enumerator))
return false;
IconMapping icon_mapping;
while (enumerator.GetNextIconMapping(&icon_mapping)) {
URLID url_id = history_db_->GetRowForURL(icon_mapping.page_url, NULL);
if (url_id == 0) {
LOG(ERROR) << "Can not find favicon's page url";
continue;
}
history_db_->SetFaviconID(url_id, icon_mapping.icon_id);
}
return true;
}
bool AndroidProviderBackend::UpdateSearchTermTable() {
sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE,
kSearchTermUpdateClause));
while (statement.Step()) {
string16 term = statement.ColumnString16(0);
Time last_visit_time = Time::FromInternalValue(statement.ColumnInt64(1));
SearchTermRow search_term_row;
if (history_db_->GetSearchTerm(term, &search_term_row)) {
if (search_term_row.last_visit_time != last_visit_time) {
search_term_row.last_visit_time = last_visit_time;
if (!history_db_->UpdateSearchTerm(search_term_row.id, search_term_row))
return false;
}
} else {
if (!history_db_->AddSearchTerm(term, last_visit_time))
return false;
}
}
if (!history_db_->DeleteUnusedSearchTerms())
return false;
return true;
}
int AndroidProviderBackend::AppendBookmarkResultColumn(
const std::vector<HistoryAndBookmarkRow::ColumnID>& projections,
std::string* result_column) {
int replaced_index = -1;
// Attach the projections
bool first = true;
int index = 0;
for (std::vector<HistoryAndBookmarkRow::ColumnID>::const_iterator i =
projections.begin(); i != projections.end(); ++i) {
if (first)
first = false;
else
result_column->append(", ");
if (*i == HistoryAndBookmarkRow::FAVICON)
replaced_index = index;
result_column->append(HistoryAndBookmarkRow::GetAndroidName(*i));
index++;
}
return replaced_index;
}
bool AndroidProviderBackend::GetSelectedURLs(
const std::string& selection,
const std::vector<string16>& selection_args,
TableIDRows* rows) {
std::string sql("SELECT url_id, urls_url, bookmark FROM (");
sql.append(kVirtualHistoryAndBookmarkTable);
sql.append(" )");
if (!selection.empty()) {
sql.append(" WHERE ");
sql.append(selection);
}
sql::Statement statement(db_->GetUniqueStatement(sql.c_str()));
int count = 0;
BindStatement(selection_args, &statement, &count);
if (!statement.is_valid()) {
LOG(ERROR) << db_->GetErrorMessage();
return false;
}
while (statement.Step()) {
TableIDRow row;
row.url_id = statement.ColumnInt64(0);
row.url = GURL(statement.ColumnString(1));
row.bookmarked = statement.ColumnBool(2);
rows->push_back(row);
}
return true;
}
bool AndroidProviderBackend::GetSelectedSearchTerms(
const std::string& selection,
const std::vector<string16>& selection_args,
SearchTerms* rows) {
std::string sql("SELECT search "
"FROM android_cache_db.search_terms ");
if (!selection.empty()) {
sql.append(" WHERE ");
sql.append(selection);
}
sql::Statement statement(db_->GetUniqueStatement(sql.c_str()));
int count = 0;
BindStatement(selection_args, &statement, &count);
if (!statement.is_valid()) {
LOG(ERROR) << db_->GetErrorMessage();
return false;
}
while (statement.Step()) {
rows->push_back(statement.ColumnString16(0));
}
return true;
}
void AndroidProviderBackend::AppendSearchResultColumn(
const std::vector<SearchRow::ColumnID>& projections,
std::string* result_column) {
bool first = true;
int index = 0;
for (std::vector<SearchRow::ColumnID>::const_iterator i =
projections.begin(); i != projections.end(); ++i) {
if (first)
first = false;
else
result_column->append(", ");
result_column->append(SearchRow::GetAndroidName(*i));
index++;
}
}
bool AndroidProviderBackend::SimulateUpdateURL(
const HistoryAndBookmarkRow& row,
const TableIDRows& ids,
HistoryNotifications* notifications) {
DCHECK(ids.size() == 1);
// URL can not be updated, we simulate the update by deleting the old URL
// and inserting the new one; We do update the android_urls table as the id
// need to keep same.
// Find all columns value of the current URL.
std::vector<HistoryAndBookmarkRow::ColumnID> projections;
projections.push_back(HistoryAndBookmarkRow::LAST_VISIT_TIME);
projections.push_back(HistoryAndBookmarkRow::CREATED);
projections.push_back(HistoryAndBookmarkRow::VISIT_COUNT);
projections.push_back(HistoryAndBookmarkRow::TITLE);
projections.push_back(HistoryAndBookmarkRow::FAVICON);
projections.push_back(HistoryAndBookmarkRow::BOOKMARK);
std::ostringstream oss;
oss << "url_id = " << ids[0].url_id;
scoped_ptr<AndroidStatement> statement;
statement.reset(QueryHistoryAndBookmarksInternal(projections, oss.str(),
std::vector<string16>(), std::string()));
if (!statement.get() || !statement->statement()->Step())
return false;
HistoryAndBookmarkRow new_row;
new_row.set_last_visit_time(FromDatabaseTime(
statement->statement()->ColumnInt64(0)));
new_row.set_created(FromDatabaseTime(
statement->statement()->ColumnInt64(1)));
new_row.set_visit_count(statement->statement()->ColumnInt(2));
new_row.set_title(statement->statement()->ColumnString16(3));
scoped_ptr<URLsDeletedDetails> deleted_details(new URLsDeletedDetails);
scoped_ptr<FaviconChangedDetails> favicon_details(new FaviconChangedDetails);
scoped_ptr<URLsModifiedDetails> modified(new URLsModifiedDetails);
URLRow old_url_row;
if (!history_db_->GetURLRow(ids[0].url_id, &old_url_row))
return false;
deleted_details->rows.push_back(old_url_row);
chrome::FaviconID favicon_id = statement->statement()->ColumnInt64(4);
if (favicon_id) {
std::vector<FaviconBitmap> favicon_bitmaps;
if (!thumbnail_db_ ||
!thumbnail_db_->GetFaviconBitmaps(favicon_id, &favicon_bitmaps))
return false;
scoped_refptr<base::RefCountedMemory> bitmap_data =
favicon_bitmaps[0].bitmap_data;
if (bitmap_data.get() && bitmap_data->size())
new_row.set_favicon(bitmap_data);
favicon_details->urls.insert(old_url_row.url());
favicon_details->urls.insert(row.url());
}
new_row.set_is_bookmark(statement->statement()->ColumnBool(5));
// The SQLHandler vector is not used here because the row in android_url
// shouldn't be deleted, we need keep the AndroidUIID unchanged, so it
// appears update to the client.
if (!urls_handler_->Delete(ids))
return false;
if (!visit_handler_->Delete(ids))
return false;
if (favicon_handler_ && !favicon_handler_->Delete(ids))
return false;
if (!bookmark_model_handler_->Delete(ids))
return false;
new_row.set_url(row.url());
new_row.set_raw_url(row.raw_url());
if (row.is_value_set_explicitly(HistoryAndBookmarkRow::LAST_VISIT_TIME))
new_row.set_last_visit_time(row.last_visit_time());
if (row.is_value_set_explicitly(HistoryAndBookmarkRow::CREATED))
new_row.set_created(row.created());
if (row.is_value_set_explicitly(HistoryAndBookmarkRow::VISIT_COUNT))
new_row.set_visit_count(row.visit_count());
if (row.is_value_set_explicitly(HistoryAndBookmarkRow::TITLE))
new_row.set_title(row.title());
if (row.is_value_set_explicitly(HistoryAndBookmarkRow::FAVICON)) {
new_row.set_favicon(row.favicon());
favicon_details->urls.insert(new_row.url());
}
if (row.is_value_set_explicitly(HistoryAndBookmarkRow::BOOKMARK))
new_row.set_is_bookmark(row.is_bookmark());
if (!urls_handler_->Insert(&new_row))
return false;
if (!visit_handler_->Insert(&new_row))
return false;
// Update the current row instead of inserting a new row in android urls
// table. We need keep the AndroidUIID unchanged, so it appears update
// to the client.
if (!android_urls_handler_->Update(new_row, ids))
return false;
if (favicon_handler_ && !favicon_handler_->Insert(&new_row))
return false;
if (!bookmark_model_handler_->Insert(&new_row))
return false;
URLRow new_url_row;
if (!history_db_->GetURLRow(new_row.url_id(), &new_url_row))
return false;
modified->changed_urls.push_back(new_url_row);
notifications->push_back(HistoryNotification(
chrome::NOTIFICATION_HISTORY_URLS_DELETED,
deleted_details.release()));
if (favicon_details.get() && !favicon_details->urls.empty())
notifications->push_back(HistoryNotification(
chrome::NOTIFICATION_FAVICON_CHANGED, favicon_details.release()));
notifications->push_back(HistoryNotification(
chrome::NOTIFICATION_HISTORY_URLS_MODIFIED, modified.release()));
return true;
}
AndroidStatement* AndroidProviderBackend::QueryHistoryAndBookmarksInternal(
const std::vector<HistoryAndBookmarkRow::ColumnID>& projections,
const std::string& selection,
const std::vector<string16>& selection_args,
const std::string& sort_order) {
std::string sql;
sql.append("SELECT ");
int replaced_index = AppendBookmarkResultColumn(projections, &sql);
sql.append(" FROM (");
sql.append(kVirtualHistoryAndBookmarkTable);
sql.append(")");
if (!selection.empty()) {
sql.append(" WHERE ");
sql.append(selection);
}
if (!sort_order.empty()) {
sql.append(" ORDER BY ");
sql.append(sort_order);
}
scoped_ptr<sql::Statement> statement(new sql::Statement(
db_->GetUniqueStatement(sql.c_str())));
int count = 0;
BindStatement(selection_args, statement.get(), &count);
if (!statement->is_valid()) {
LOG(ERROR) << db_->GetErrorMessage();
return NULL;
}
sql::Statement* result = statement.release();
return new AndroidStatement(result, replaced_index);
}
bool AndroidProviderBackend::DeleteHistoryInternal(
const TableIDRows& urls,
bool delete_bookmarks,
HistoryNotifications* notifications) {
scoped_ptr<URLsDeletedDetails> deleted_details(new URLsDeletedDetails);
scoped_ptr<FaviconChangedDetails> favicon(new FaviconChangedDetails);
for (TableIDRows::const_iterator i = urls.begin(); i != urls.end(); ++i) {
URLRow url_row;
if (!history_db_->GetURLRow(i->url_id, &url_row))
return false;
deleted_details->rows.push_back(url_row);
if (thumbnail_db_ &&
thumbnail_db_->GetIconMappingsForPageURL(url_row.url(), NULL))
favicon->urls.insert(url_row.url());
}
// Only invoke Delete on the BookmarkModelHandler if we need
// to delete bookmarks.
for (std::vector<SQLHandler*>::iterator i =
sql_handlers_.begin(); i != sql_handlers_.end(); ++i) {
if ((*i) != bookmark_model_handler_.get() || delete_bookmarks)
if (!(*i)->Delete(urls))
return false;
}
notifications->push_back(HistoryNotification(
chrome::NOTIFICATION_HISTORY_URLS_DELETED,
deleted_details.release()));
if (favicon.get() && !favicon->urls.empty())
notifications->push_back(HistoryNotification(
chrome::NOTIFICATION_FAVICON_CHANGED, favicon.release()));
return true;
}
void AndroidProviderBackend::BroadcastNotifications(
const HistoryNotifications& notifications) {
for (HistoryNotifications::const_iterator i = notifications.begin();
i != notifications.end(); ++i) {
delegate_->BroadcastNotifications(i->type, i->detail);
}
}
bool AndroidProviderBackend::AddSearchTerm(const SearchRow& values) {
DCHECK(values.is_value_set_explicitly(SearchRow::SEARCH_TERM));
DCHECK(values.is_value_set_explicitly(SearchRow::TEMPLATE_URL));
DCHECK(values.is_value_set_explicitly(SearchRow::URL));
URLRow url_row;
HistoryAndBookmarkRow bookmark_row;
// Android CTS test BrowserTest.testAccessSearches allows insert the same
// seach term multiple times, and just search time need updated.
if (history_db_->GetRowForURL(values.url(), &url_row)) {
// Already exist, Add a visit.
if (values.is_value_set_explicitly(SearchRow::SEARCH_TIME))
bookmark_row.set_last_visit_time(values.search_time());
else
bookmark_row.set_visit_count(url_row.visit_count() + 1);
TableIDRows table_id_rows;
TableIDRow table_id_row;
table_id_row.url = values.url();
table_id_row.url_id = url_row.id();
table_id_rows.push_back(table_id_row);
if (!urls_handler_->Update(bookmark_row, table_id_rows))
return false;
if (!visit_handler_->Update(bookmark_row, table_id_rows))
return false;
if (!history_db_->GetKeywordSearchTermRow(url_row.id(), NULL))
if (!history_db_->SetKeywordSearchTermsForURL(url_row.id(),
values.template_url_id(), values.search_term()))
return false;
} else {
bookmark_row.set_raw_url(values.url().spec());
bookmark_row.set_url(values.url());
if (values.is_value_set_explicitly(SearchRow::SEARCH_TIME))
bookmark_row.set_last_visit_time(values.search_time());
if (!urls_handler_->Insert(&bookmark_row))
return false;
if (!visit_handler_->Insert(&bookmark_row))
return false;
if (!android_urls_handler_->Insert(&bookmark_row))
return false;
if (!history_db_->SetKeywordSearchTermsForURL(bookmark_row.url_id(),
values.template_url_id(), values.search_term()))
return false;
}
return true;
}
} // namespace history
|
#ifndef _MANIPULATORCOORDINATIONSERVICEIOQUERYQUERYHANDLER_HH_
#define _MANIPULATORCOORDINATIONSERVICEIOQUERYQUERYHANDLER_HH_
#include "CommBasicObjects/CommIOValues.hh"
#include "CommBasicObjects/CommIOValues.hh"
#include <string>
class ManipulatorCoordinationServiceIoqueryQueryHandler
{
public:
ManipulatorCoordinationServiceIoqueryQueryHandler(){
}
CommBasicObjects::CommIOValues handleRequest(const std::string& inString);
std::string handleAnswer(const CommBasicObjects::CommIOValues& answer);
};
#endif
|
#include "stdafx.h"
#include "../../xrEngine/igame_persistent.h"
#include "../xrRender/FBasicVisual.h"
#include "../../xrEngine/customhud.h"
#include "../../xrEngine/xr_object.h"
#include "../xrRender/QueryHelper.h"
IC bool pred_sp_sort (ISpatial* _1, ISpatial* _2)
{
float d1 = _1->spatial.sphere.P.distance_to_sqr (Device.vCameraPosition);
float d2 = _2->spatial.sphere.P.distance_to_sqr (Device.vCameraPosition);
return d1<d2 ;
}
void CRender::render_main (Fmatrix& m_ViewProjection, bool _fportals)
{
PIX_EVENT(render_main);
// Msg ("---begin");
marker ++;
// Calculate sector(s) and their objects
if (pLastSector) {
//!!!
//!!! BECAUSE OF PARALLEL HOM RENDERING TRY TO DELAY ACCESS TO HOM AS MUCH AS POSSIBLE
//!!!
{
// Traverse object database
g_SpatialSpace->q_frustum
(
lstRenderables,
ISpatial_DB::O_ORDERED,
STYPE_RENDERABLE + STYPE_LIGHTSOURCE,
ViewBase
);
// (almost) Exact sorting order (front-to-back)
std::sort (lstRenderables.begin(),lstRenderables.end(),pred_sp_sort);
// Determine visibility for dynamic part of scene
set_Object (0);
u32 uID_LTRACK = 0xffffffff;
if (phase==PHASE_NORMAL) {
uLastLTRACK ++;
if (lstRenderables.size()) uID_LTRACK = uLastLTRACK%lstRenderables.size();
// update light-vis for current entity / actor
CObject* O = g_pGameLevel->CurrentViewEntity();
if (O) {
CROS_impl* R = (CROS_impl*) O->ROS();
if (R) R->update (O);
}
// update light-vis for selected entity
// track lighting environment
if (lstRenderables.size()) {
IRenderable* renderable = lstRenderables[uID_LTRACK]->dcast_Renderable ();
if (renderable) {
CROS_impl* T = (CROS_impl*)renderable->renderable_ROS ();
if (T) T->update (renderable);
}
}
}
}
// Traverse sector/portal structure
PortalTraverser.traverse
(
pLastSector,
ViewBase,
Device.vCameraPosition,
m_ViewProjection,
CPortalTraverser::VQ_HOM + CPortalTraverser::VQ_SSA + CPortalTraverser::VQ_FADE
//. disabled scissoring (HW.Caps.bScissor?CPortalTraverser::VQ_SCISSOR:0) // generate scissoring info
);
// Determine visibility for static geometry hierrarhy
for (u32 s_it=0; s_it<PortalTraverser.r_sectors.size(); s_it++)
{
CSector* sector = (CSector*)PortalTraverser.r_sectors[s_it];
dxRender_Visual* root = sector->root();
for (u32 v_it=0; v_it<sector->r_frustums.size(); v_it++) {
set_Frustum (&(sector->r_frustums[v_it]));
add_Geometry (root);
}
}
// Traverse frustums
for (u32 o_it=0; o_it<lstRenderables.size(); o_it++)
{
ISpatial* spatial = lstRenderables[o_it]; spatial->spatial_updatesector ();
CSector* sector = (CSector*)spatial->spatial.sector;
if (0==sector) continue; // disassociated from S/P structure
if (spatial->spatial.type & STYPE_LIGHTSOURCE) {
// lightsource
light* L = (light*) (spatial->dcast_Light());
VERIFY (L);
float lod = L->get_LOD ();
if (lod>EPS_L) {
vis_data& vis = L->get_homdata ( );
if (HOM.visible(vis)) Lights.add_light (L);
}
continue ;
}
if (PortalTraverser.i_marker != sector->r_marker) continue; // inactive (untouched) sector
for (u32 v_it=0; v_it<sector->r_frustums.size(); v_it++) {
CFrustum& view = sector->r_frustums[v_it];
if (!view.testSphere_dirty(spatial->spatial.sphere.P,spatial->spatial.sphere.R)) continue;
if (spatial->spatial.type & STYPE_RENDERABLE)
{
// renderable
IRenderable* renderable = spatial->dcast_Renderable ();
VERIFY (renderable);
// Occlusion
// casting is faster then using getVis method
vis_data& v_orig = ((dxRender_Visual*)renderable->renderable.visual)->vis;
vis_data v_copy = v_orig;
v_copy.box.xform (renderable->renderable.xform);
BOOL bVisible = HOM.visible(v_copy);
v_orig.marker = v_copy.marker;
v_orig.accept_frame = v_copy.accept_frame;
v_orig.hom_frame = v_copy.hom_frame;
v_orig.hom_tested = v_copy.hom_tested;
if (!bVisible) break; // exit loop on frustums
// Rendering
set_Object (renderable);
renderable->renderable_Render ();
set_Object (0);
}
break; // exit loop on frustums
}
}
if (g_pGameLevel && (phase==PHASE_NORMAL)) g_pGameLevel->pHUD->Render_Last(); // HUD
}
else
{
set_Object (0);
if (g_pGameLevel && (phase==PHASE_NORMAL)) g_pGameLevel->pHUD->Render_Last(); // HUD
}
}
void CRender::render_menu ()
{
PIX_EVENT(render_menu);
// Globals
RCache.set_CullMode (CULL_CCW);
RCache.set_Stencil (FALSE);
RCache.set_ColorWriteEnable ();
// Main Render
{
if( !RImplementation.o.dx10_msaa )
Target->u_setrt (Target->rt_Generic_0,0,0,HW.pBaseZB); // LDR RT
else
Target->u_setrt (Target->rt_Generic_0,0,0,RImplementation.Target->rt_MSAADepth->pZRT); // LDR RT
g_pGamePersistent->OnRenderPPUI_main() ; // PP-UI
}
// Distort
{
if( !RImplementation.o.dx10_msaa )
Target->u_setrt (Target->rt_Generic_1,0,0,HW.pBaseZB); // Now RT is a distortion mask
else
Target->u_setrt (Target->rt_Generic_1,0,0,RImplementation.Target->rt_MSAADepth->pZRT); // Now RT is a distortion mask
//CHK_DX(HW.pDevice->Clear ( 0L, NULL, D3DCLEAR_TARGET, color_rgba(127,127,0,127), 1.0f, 0L));
FLOAT ColorRGBA[4] = { 127.0f/255.0f, 127.0f/255.0f, 0.0f, 127.0f/255.0f};
HW.pDevice->ClearRenderTargetView(Target->rt_Generic_1->pRT, ColorRGBA);
g_pGamePersistent->OnRenderPPUI_PP () ; // PP-UI
}
// Actual Display
Target->u_setrt ( Device.dwWidth,Device.dwHeight,HW.pBaseRT,NULL,NULL,HW.pBaseZB);
RCache.set_Shader ( Target->s_menu );
RCache.set_Geometry ( Target->g_menu );
Fvector2 p0,p1;
u32 Offset;
u32 C = color_rgba (255,255,255,255);
float _w = float(Device.dwWidth);
float _h = float(Device.dwHeight);
float d_Z = EPS_S;
float d_W = 1.f;
p0.set (.5f/_w, .5f/_h);
p1.set ((_w+.5f)/_w, (_h+.5f)/_h );
FVF::TL* pv = (FVF::TL*) RCache.Vertex.Lock (4,Target->g_menu->vb_stride,Offset);
pv->set (EPS, float(_h+EPS), d_Z, d_W, C, p0.x, p1.y); pv++;
pv->set (EPS, EPS, d_Z, d_W, C, p0.x, p0.y); pv++;
pv->set (float(_w+EPS), float(_h+EPS), d_Z, d_W, C, p1.x, p1.y); pv++;
pv->set (float(_w+EPS), EPS, d_Z, d_W, C, p1.x, p0.y); pv++;
RCache.Vertex.Unlock (4,Target->g_menu->vb_stride);
RCache.Render (D3DPT_TRIANGLELIST,Offset,0,4,0,2);
}
extern u32 g_r;
void CRender::Render ()
{
PIX_EVENT(CRender_Render);
g_r = 1;
VERIFY (0==mapDistort.size());
rmNormal();
bool _menu_pp = g_pGamePersistent?g_pGamePersistent->OnRenderPPUI_query():false;
if (_menu_pp) {
render_menu () ;
return ;
};
IMainMenu* pMainMenu = g_pGamePersistent?g_pGamePersistent->m_pMainMenu:0;
bool bMenu = pMainMenu?pMainMenu->CanSkipSceneRendering():false;
if( !(g_pGameLevel && g_pGameLevel->pHUD)
|| bMenu)
{
Target->u_setrt ( Device.dwWidth,Device.dwHeight,HW.pBaseRT,NULL,NULL,HW.pBaseZB);
return;
}
//. VERIFY (g_pGameLevel && g_pGameLevel->pHUD);
// Configure
RImplementation.o.distortion = FALSE; // disable distorion
Fcolor sun_color = ((light*)Lights.sun_adapted._get())->color;
BOOL bSUN = ps_r2_ls_flags.test(R2FLAG_SUN) && (u_diffuse2s(sun_color.r,sun_color.g,sun_color.b)>EPS);
if (o.sunstatic) bSUN = FALSE;
// Msg ("sstatic: %s, sun: %s",o.sunstatic?;"true":"false", bSUN?"true":"false");
// HOM
ViewBase.CreateFromMatrix (Device.mFullTransform, FRUSTUM_P_LRTB + FRUSTUM_P_FAR);
View = 0;
if (!ps_r2_ls_flags.test(R2FLAG_EXP_MT_CALC)) {
HOM.Enable ();
HOM.Render (ViewBase);
}
//******* Z-prefill calc - DEFERRER RENDERER
if (ps_r2_ls_flags.test(R2FLAG_ZFILL))
{
PIX_EVENT(DEFER_Z_FILL);
Device.Statistic->RenderCALC.Begin ();
float z_distance = ps_r2_zfill ;
Fmatrix m_zfill, m_project ;
m_project.build_projection (
deg2rad(Device.fFOV/* *Device.fASPECT*/),
Device.fASPECT, VIEWPORT_NEAR,
z_distance * g_pGamePersistent->Environment().CurrentEnv->far_plane);
m_zfill.mul (m_project,Device.mView);
r_pmask (true,false); // enable priority "0"
set_Recorder (NULL) ;
phase = PHASE_SMAP;
render_main (m_zfill,false) ;
r_pmask (true,false); // disable priority "1"
Device.Statistic->RenderCALC.End ( ) ;
// flush
Target->phase_scene_prepare ();
RCache.set_ColorWriteEnable (FALSE);
r_dsgraph_render_graph (0);
RCache.set_ColorWriteEnable ( );
}
else
{
Target->phase_scene_prepare ();
}
//*******
// Sync point
Device.Statistic->RenderDUMP_Wait_S.Begin ();
if (1)
{
CTimer T; T.Start ();
BOOL result = FALSE;
HRESULT hr = S_FALSE;
//while ((hr=q_sync_point[q_sync_count]->GetData (&result,sizeof(result),D3DGETDATA_FLUSH))==S_FALSE) {
while ((hr=GetData (q_sync_point[q_sync_count], &result,sizeof(result)))==S_FALSE)
{
if (!SwitchToThread()) Sleep(ps_r2_wait_sleep);
if (T.GetElapsed_ms() > 500) {
result = FALSE;
break;
}
}
}
Device.Statistic->RenderDUMP_Wait_S.End ();
q_sync_count = (q_sync_count+1)%HW.Caps.iGPUNum;
//CHK_DX (q_sync_point[q_sync_count]->Issue(D3DISSUE_END));
CHK_DX (EndQuery(q_sync_point[q_sync_count]));
//******* Main calc - DEFERRER RENDERER
// Main calc
Device.Statistic->RenderCALC.Begin ();
r_pmask (true,false,true); // enable priority "0",+ capture wmarks
if (bSUN) set_Recorder (&main_coarse_structure);
else set_Recorder (NULL);
phase = PHASE_NORMAL;
render_main (Device.mFullTransform,true);
set_Recorder (NULL);
r_pmask (true,false); // disable priority "1"
Device.Statistic->RenderCALC.End ();
BOOL split_the_scene_to_minimize_wait = FALSE;
if (ps_r2_ls_flags.test(R2FLAG_EXP_SPLIT_SCENE)) split_the_scene_to_minimize_wait=TRUE;
//******* Main render :: PART-0 -- first
if (!split_the_scene_to_minimize_wait)
{
PIX_EVENT(DEFER_PART0_NO_SPLIT);
// level, DO NOT SPLIT
Target->phase_scene_begin ();
r_dsgraph_render_hud ();
r_dsgraph_render_graph (0);
r_dsgraph_render_lods (true,true);
if(Details) Details->Render ();
Target->phase_scene_end ();
}
else
{
PIX_EVENT(DEFER_PART0_SPLIT);
// level, SPLIT
Target->phase_scene_begin ();
r_dsgraph_render_graph (0);
Target->disable_aniso ();
}
//******* Occlusion testing of volume-limited light-sources
Target->phase_occq ();
LP_normal.clear ();
LP_pending.clear ();
if( RImplementation.o.dx10_msaa )
RCache.set_ZB( RImplementation.Target->rt_MSAADepth->pZRT );
{
PIX_EVENT(DEFER_TEST_LIGHT_VIS);
// perform tests
u32 count = 0;
light_Package& LP = Lights.package;
// stats
stats.l_shadowed = LP.v_shadowed.size();
stats.l_unshadowed = LP.v_point.size() + LP.v_spot.size();
stats.l_total = stats.l_shadowed + stats.l_unshadowed;
// perform tests
count = _max (count,LP.v_point.size());
count = _max (count,LP.v_spot.size());
count = _max (count,LP.v_shadowed.size());
for (u32 it=0; it<count; it++) {
if (it<LP.v_point.size()) {
light* L = LP.v_point [it];
L->vis_prepare ();
if (L->vis.pending) LP_pending.v_point.push_back (L);
else LP_normal.v_point.push_back (L);
}
if (it<LP.v_spot.size()) {
light* L = LP.v_spot [it];
L->vis_prepare ();
if (L->vis.pending) LP_pending.v_spot.push_back (L);
else LP_normal.v_spot.push_back (L);
}
if (it<LP.v_shadowed.size()) {
light* L = LP.v_shadowed [it];
L->vis_prepare ();
if (L->vis.pending) LP_pending.v_shadowed.push_back (L);
else LP_normal.v_shadowed.push_back (L);
}
}
}
LP_normal.sort ();
LP_pending.sort ();
//******* Main render :: PART-1 (second)
if (split_the_scene_to_minimize_wait)
{
PIX_EVENT(DEFER_PART1_SPLIT);
// skybox can be drawn here
if (0)
{
if( !RImplementation.o.dx10_msaa )
Target->u_setrt ( Target->rt_Generic_0, Target->rt_Generic_1,0,HW.pBaseZB );
else
Target->u_setrt ( Target->rt_Generic_0, Target->rt_Generic_1,0,RImplementation.Target->rt_MSAADepth->pZRT );
RCache.set_CullMode ( CULL_NONE );
RCache.set_Stencil ( FALSE );
// draw skybox
RCache.set_ColorWriteEnable ();
//CHK_DX(HW.pDevice->SetRenderState ( D3DRS_ZENABLE, FALSE ));
RCache.set_Z(FALSE);
g_pGamePersistent->Environment().RenderSky ();
//CHK_DX(HW.pDevice->SetRenderState ( D3DRS_ZENABLE, TRUE ));
RCache.set_Z(TRUE);
}
// level
Target->phase_scene_begin ();
r_dsgraph_render_hud ();
r_dsgraph_render_lods (true,true);
if(Details) Details->Render ();
Target->phase_scene_end ();
}
if (g_hud && g_hud->RenderActiveItemUIQuery())
{
Target->phase_wallmarks();
r_dsgraph_render_hud_ui();
}
// Wall marks
if(Wallmarks)
{
PIX_EVENT(DEFER_WALLMARKS);
Target->phase_wallmarks ();
g_r = 0;
Wallmarks->Render (); // wallmarks has priority as normal geometry
}
// Update incremental shadowmap-visibility solver
{
PIX_EVENT(DEFER_FLUSH_OCCLUSION);
u32 it=0;
for (it=0; it<Lights_LastFrame.size(); it++) {
if (0==Lights_LastFrame[it]) continue ;
try {
Lights_LastFrame[it]->svis.flushoccq() ;
} catch (...)
{
Msg ("! Failed to flush-OCCq on light [%d] %X",it,*(u32*)(&Lights_LastFrame[it]));
}
}
Lights_LastFrame.clear ();
}
// full screen pass to mark msaa-edge pixels in highest stencil bit
if( RImplementation.o.dx10_msaa )
{
PIX_EVENT( MARK_MSAA_EDGES );
Target->mark_msaa_edges();
}
// TODO: DX10: Implement DX10 rain.
if (ps_r2_ls_flags.test(R3FLAG_DYN_WET_SURF))
{
PIX_EVENT(DEFER_RAIN);
render_rain();
}
// Directional light - fucking sun
if (bSUN)
{
PIX_EVENT(DEFER_SUN);
RImplementation.stats.l_visible ++;
render_sun_near ();
render_sun ();
render_sun_filtered ();
Target->accum_direct_blend ();
}
{
PIX_EVENT(DEFER_SELF_ILLUM);
Target->phase_accumulator ();
// Render emissive geometry, stencil - write 0x0 at pixel pos
RCache.set_xform_project (Device.mProject);
RCache.set_xform_view (Device.mView);
// Stencil - write 0x1 at pixel pos -
if( !RImplementation.o.dx10_msaa )
RCache.set_Stencil ( TRUE,D3DCMP_ALWAYS,0x01,0xff,0xff,D3DSTENCILOP_KEEP,D3DSTENCILOP_REPLACE,D3DSTENCILOP_KEEP);
else
RCache.set_Stencil ( TRUE,D3DCMP_ALWAYS,0x01,0xff,0x7f,D3DSTENCILOP_KEEP,D3DSTENCILOP_REPLACE,D3DSTENCILOP_KEEP);
//RCache.set_Stencil (TRUE,D3DCMP_ALWAYS,0x00,0xff,0xff,D3DSTENCILOP_KEEP,D3DSTENCILOP_REPLACE,D3DSTENCILOP_KEEP);
RCache.set_CullMode (CULL_CCW);
RCache.set_ColorWriteEnable ();
RImplementation.r_dsgraph_render_emissive();
}
// Lighting, non dependant on OCCQ
{
PIX_EVENT(DEFER_LIGHT_NO_OCCQ);
Target->phase_accumulator ();
HOM.Disable ();
render_lights (LP_normal);
}
// Lighting, dependant on OCCQ
{
PIX_EVENT(DEFER_LIGHT_OCCQ);
render_lights (LP_pending);
}
// Postprocess
{
PIX_EVENT(DEFER_LIGHT_COMBINE);
Target->phase_combine ();
}
VERIFY (0==mapDistort.size());
}
void CRender::render_forward ()
{
VERIFY (0==mapDistort.size());
RImplementation.o.distortion = RImplementation.o.distortion_enabled; // enable distorion
//******* Main render - second order geometry (the one, that doesn't support deffering)
//.todo: should be done inside "combine" with estimation of of luminance, tone-mapping, etc.
{
// level
r_pmask (false,true); // enable priority "1"
phase = PHASE_NORMAL;
render_main (Device.mFullTransform,false);//
// Igor: we don't want to render old lods on next frame.
mapLOD.clear ();
r_dsgraph_render_graph (1) ; // normal level, secondary priority
PortalTraverser.fade_render () ; // faded-portals
r_dsgraph_render_sorted () ; // strict-sorted geoms
g_pGamePersistent->Environment().RenderLast() ; // rain/thunder-bolts
}
RImplementation.o.distortion = FALSE; // disable distorion
}
|
/**
* UGENE - Integrated Bioinformatics Tools.
* Copyright (C) 2008-2012 UniPro <ugene@unipro.ru>
* http://ugene.unipro.ru
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include "GTMouseDriver.h"
namespace U2 {
void GTMouseDriver::click(U2::U2OpStatus &os, Qt::MouseButton button)
{
press(os, button);
release(os, button);
GTGlobals::sleep(100);
}
#ifndef Q_OS_MAC
void GTMouseDriver::doubleClick(U2OpStatus &os)
{
click(os, Qt::LeftButton);
click(os, Qt::LeftButton);
}
#endif
} //namespace
|
/* Copyright (c) 2009-2013, Fortylines LLC
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of fortylines nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Fortylines LLC ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Fortylines LLC BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
#ifndef guardtodo
#define guardtodo
#include "document.hh"
#include "mail.hh"
#include <boost/uuid/uuid.hpp>
/** Pages related to todo items.
Primary Author(s): Sebastien Mirolo <smirolo@fortylines.com>
*/
namespace tero {
#if 0 // XXX deprecated
/** An adapter is used to associate identifiers and pathnames
*/
class todoAdapter : public adapter {
public:
article fetch( session& s, const boost::filesystem::path& pathname );
boost::filesystem::path asPath( const boost::uuids::uuid& id ) const;
};
#endif
class todoFilter : public passThruFilter {
public:
/** Pattern used to select directories containing todo items.
*/
static const boost::regex viewPat;
/** Directory where modifications to todo item are stored.
*/
const boost::filesystem::path modifs;
public:
explicit todoFilter( const boost::filesystem::path& m )
: modifs(m) {}
todoFilter( const boost::filesystem::path& m, postFilter* n )
: passThruFilter(n), modifs(m) {}
std::string asPath( const std::string& tag );
};
/** Creating an item or commenting on an already existing item
use very similar mechanism. This abstract class implements
such mechanism to append a post to an item. (*always*)
*/
class todoModifPost {
protected:
/** Directory where modifications to todo items are stored. */
const boost::filesystem::path modifs;
/** Input stream containing the modification post
formatted as an e-mail. */
std::istream *istr;
public:
explicit todoModifPost( const boost::filesystem::path& m )
: modifs(m), istr(NULL) {}
todoModifPost( const boost::filesystem::path& m, std::istream& is )
: modifs(m), istr(&is) {}
};
void todoModifPostFetch( session& s, const url& name );
/** Create a new item
Creating a new item involves computing a unique identifier,
write the post in a file whose name is based on that identifier
and finally commit the file into the repository.
*/
class todoCreate : public todoModifPost {
public:
todoCreate( const boost::filesystem::path& m, std::istream& is )
: todoModifPost(m,is) {}
};
void todoCreateFetch( session& s, const url& name );
/** Comment an item
Commmenting on a item involves finding the file matching the unique
identifier of that item, append the post at the end of that file
and finally commit the file back into the repository.
*/
class todoComment : public todoModifPost {
public:
todoComment( const boost::filesystem::path& m,
std::istream& is )
: todoModifPost(m,is) {}
};
void todoCommentFetch( session& s, const url& name );
/** Display an index of all items in a directory with one item per row
with the rows sorted in descending score order. (*always*)
*/
void todoIndexWriteHtmlFetch( session& s, const url& name );
/** Callback when the process of voting on an item has been abandonned
(*always*).
*/
void todoVoteAbandonFetch( session& s, const url& name );
/** Callback when a vote on an item has successed.
First the item's unique identifier is used to find the file
that need to be updated. The file is then searched for the matching
'Score:' pattern and that line is modified to reflect the vote.
Finally the file is committed back into the repository.
*/
class todoVoteSuccess : public todoModifPost {
protected:
const char *returnPath;
public:
todoVoteSuccess( const boost::filesystem::path& m,
const char *retPath )
: todoModifPost(m), returnPath(retPath) {}
};
void todoVoteSuccessFetch( session& s, const url& name );
void todoMeta( session& s, std::istream& in, const url& name );
/** Generate an HTML printout of an item
*/
void todoWriteHtmlFetch( session& s, const url& name );
}
#endif
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <ddk/debug.h>
#include <ddk/device.h>
#include <ddk/metadata.h>
#include <ddk/metadata/clock.h>
#include <ddk/platform-defs.h>
#include <ddk/protocol/platform/bus.h>
#include <soc/msm8x53/msm8x53-clock.h>
#include <soc/msm8x53/msm8x53-gpio.h>
#include <soc/msm8x53/msm8x53-hw.h>
#include "msm8x53.h"
namespace board_msm8x53 {
namespace {
constexpr pbus_mmio_t clock_mmios[] = {
{
.base = msm8x53::kCcBase,
.length = msm8x53::kCcSize,
},
};
constexpr clock_id_t clock_ids[] = {
// For PIL.
{msm8x53::kCryptoAhbClk},
{msm8x53::kCryptoAxiClk},
{msm8x53::kCryptoClk},
};
constexpr pbus_metadata_t clock_metadata[] = {
{
.type = DEVICE_METADATA_CLOCK_IDS,
.data_buffer = &clock_ids,
.data_size = sizeof(clock_ids),
},
};
constexpr pbus_dev_t clock_dev = []() {
pbus_dev_t result{};
result.name = "gcc-clock";
result.vid = PDEV_VID_QUALCOMM;
result.pid = PDEV_PID_QUALCOMM_MSM8X53;
result.did = PDEV_DID_QUALCOMM_CLOCK;
result.mmio_list = clock_mmios;
result.mmio_count = countof(clock_mmios);
result.metadata_list = clock_metadata;
result.metadata_count = countof(clock_metadata);
return result;
}();
} // namespace
zx_status_t Msm8x53::ClockInit() {
zx_status_t status = pbus_.DeviceAdd(&clock_dev);
if (status != ZX_OK) {
zxlogf(ERROR, "%s: DeviceAdd failed %d", __func__, status);
return status;
}
return ZX_OK;
}
} // namespace board_msm8x53
|
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "Potamos.h"
#include "SubmeshData.h"
SubmeshData::SubmeshData()
{
}
SubmeshData::~SubmeshData()
{
}
|
#include <iostream>
using namespace std;
int K, L, M, N, D;
int main(void) {
cin >> K >> L >> M >> N >> D;
int ct = 0;
for(int i = 1; i <= D; i++) {
if(i % K == 0 || i % L == 0 || i % M == 0 || i % N == 0) ct++;
}
cout << ct << endl;
return 0;
}
|
//
// scale_to_action.hpp
// rawket
//
// Created by Tom Albrecht on 25.12.15.
//
//
#ifndef ScaleToAction_hpp
#define ScaleToAction_hpp
#include <vector>
#include <iostream>
#include "action.hpp"
#include "sprite.hpp"
RKT_NAMESPACE_BEGIN
class scale_to_action;
rkt_create_shared_ptr(scale_to_action);
/**
* Scales the target Nodes by x in y duration
*/
class scale_to_action : public action {
vec2f m_scale = vec2f_make(1.0, 1.0);
public:
scale_to_action(double duration, double destScale);
static scale_to_action_ptr create(double duration, double destScale);
virtual void update();
virtual void start();
};
RKT_NAMESPACE_END
#endif /* ScaleToAction_hpp */
|
/*
* Copyright (C) 2011 Google Inc. All rights reserved.
* Copyright (C) 2011 Ericsson AB. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "LocalMediaStream.h"
#if ENABLE(MEDIA_STREAM)
#include "MediaStreamCenter.h"
#include "UUID.h"
namespace WebCore {
PassRefPtr<LocalMediaStream> LocalMediaStream::create(ScriptExecutionContext* context, const MediaStreamSourceVector& audioSources, const MediaStreamSourceVector& videoSources)
{
return adoptRef(new LocalMediaStream(context, MediaStreamDescriptor::create(createCanonicalUUIDString(), audioSources, videoSources)));
}
PassRefPtr<LocalMediaStream> LocalMediaStream::create(ScriptExecutionContext* context, PassRefPtr<MediaStreamDescriptor> streamDescriptor)
{
return adoptRef(new LocalMediaStream(context, streamDescriptor));
}
LocalMediaStream::LocalMediaStream(ScriptExecutionContext* context, PassRefPtr<MediaStreamDescriptor> streamDescriptor)
: MediaStream(context, streamDescriptor)
{
}
void LocalMediaStream::stop()
{
if (ended())
return;
MediaStreamCenter::instance().didStopLocalMediaStream(descriptor());
streamEnded();
}
LocalMediaStream::~LocalMediaStream()
{
}
const AtomicString& LocalMediaStream::interfaceName() const
{
return eventNames().interfaceForLocalMediaStream;
}
} // namespace WebCore
#endif // ENABLE(MEDIA_STREAM)
|
/* Example to demonstrate the working of virtual function in C++ programming. */
#include <iostream>
using namespace std;
class B
{
public:
virtual void display() /* Virtual function */
{ cout<<"Content of base class.\n"; }
};
class D1 : public B
{
public:
//virtual void display()
//{ cout<<"Content of first derived class.\n"; }
};
class D2 : public B
{
public:
void display()
{ cout<<"Content of second derived class.\n"; }
};
int main()
{
B *b;
D1 d1;
D2 d2;
B a;
/* b->display(); // You cannot use this code here because the function of base class is virtual. */
b=&a;
b->display();
b = &d1;
b->display(); /* calls display() of class derived D1 */
b = &d2;
b->display(); /* calls display() of class derived D2 */
return 0;
}
|
#include <vector>
#include <algorithm>
#include "algol/sequence/sequence.hpp"
#include "algol/sequence/generator/geometric_progression_generator.hpp"
#include "gtest/gtest.h"
using geometric_progression_infinite = algol::sequence::geometric_progression_infinite_seq<uint32_t>;
using geometric_progression_first_n = algol::sequence::geometric_progression_first_n_seq<uint32_t>;
class geometric_progression_fixture : public ::testing::Test {
protected:
geometric_progression_infinite inf_seq {2, 3};
geometric_progression_first_n first_n_seq {5, 2, 6};
};
TEST_F(geometric_progression_fixture, infinite)
{
std::vector<uint32_t> val;
EXPECT_NE(std::begin(inf_seq), std::end(inf_seq));
std::copy_n(std::begin(inf_seq), 5, std::back_inserter(val));
ASSERT_EQ(val.size(), 5u);
ASSERT_EQ(val, (std::vector<uint32_t>{2, 6, 18, 54, 162}));
}
TEST_F(geometric_progression_fixture, first_n)
{
std::vector<uint32_t> val;
EXPECT_NE(std::begin(first_n_seq), std::end(first_n_seq));
std::copy(std::begin(first_n_seq), std::end(first_n_seq), std::back_inserter(val));
ASSERT_EQ(val.size(), 6u);
ASSERT_EQ(val, (std::vector<uint32_t>{5, 10, 20, 40, 80, 160}));
}
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "rpcprotocol.h"
#include "util.h"
#include <stdint.h>
#include <boost/algorithm/string.hpp>
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/shared_ptr.hpp>
#include "json/json_spirit_writer_template.h"
using namespace std;
using namespace boost;
using namespace boost::asio;
using namespace json_spirit;
//
// HTTP protocol
//
// This ain't Apache. We're just using HTTP header for the length field
// and to be compatible with other JSON-RPC implementations.
//
string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders)
{
ostringstream s;
s << "POST / HTTP/1.1\r\n"
<< "User-Agent: TRIPcoin-json-rpc/" << FormatFullVersion() << "\r\n"
<< "Host: 127.0.0.1\r\n"
<< "Content-Type: application/json\r\n"
<< "Content-Length: " << strMsg.size() << "\r\n"
<< "Connection: close\r\n"
<< "Accept: application/json\r\n";
BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders)
s << item.first << ": " << item.second << "\r\n";
s << "\r\n" << strMsg;
return s.str();
}
static string rfc1123Time()
{
return DateTimeStrFormat("%a, %d %b %Y %H:%M:%S +0000", GetTime());
}
string HTTPReply(int nStatus, const string& strMsg, bool keepalive)
{
if (nStatus == HTTP_UNAUTHORIZED)
return strprintf("HTTP/1.0 401 Authorization Required\r\n"
"Date: %s\r\n"
"Server: TRIPcoin-json-rpc/%s\r\n"
"WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n"
"Content-Type: text/html\r\n"
"Content-Length: 296\r\n"
"\r\n"
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n"
"\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n"
"<HTML>\r\n"
"<HEAD>\r\n"
"<TITLE>Error</TITLE>\r\n"
"<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n"
"</HEAD>\r\n"
"<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"
"</HTML>\r\n", rfc1123Time(), FormatFullVersion());
const char *cStatus;
if (nStatus == HTTP_OK) cStatus = "OK";
else if (nStatus == HTTP_BAD_REQUEST) cStatus = "Bad Request";
else if (nStatus == HTTP_FORBIDDEN) cStatus = "Forbidden";
else if (nStatus == HTTP_NOT_FOUND) cStatus = "Not Found";
else if (nStatus == HTTP_INTERNAL_SERVER_ERROR) cStatus = "Internal Server Error";
else cStatus = "";
return strprintf(
"HTTP/1.1 %d %s\r\n"
"Date: %s\r\n"
"Connection: %s\r\n"
"Content-Length: %u\r\n"
"Content-Type: application/json\r\n"
"Server: TRIPcoin-json-rpc/%s\r\n"
"\r\n"
"%s",
nStatus,
cStatus,
rfc1123Time(),
keepalive ? "keep-alive" : "close",
strMsg.size(),
FormatFullVersion(),
strMsg);
}
bool ReadHTTPRequestLine(std::basic_istream<char>& stream, int &proto,
string& http_method, string& http_uri)
{
string str;
getline(stream, str);
// HTTP request line is space-delimited
vector<string> vWords;
boost::split(vWords, str, boost::is_any_of(" "));
if (vWords.size() < 2)
return false;
// HTTP methods permitted: GET, POST
http_method = vWords[0];
if (http_method != "GET" && http_method != "POST")
return false;
// HTTP URI must be an absolute path, relative to current host
http_uri = vWords[1];
if (http_uri.size() == 0 || http_uri[0] != '/')
return false;
// parse proto, if present
string strProto = "";
if (vWords.size() > 2)
strProto = vWords[2];
proto = 0;
const char *ver = strstr(strProto.c_str(), "HTTP/1.");
if (ver != NULL)
proto = atoi(ver+7);
return true;
}
int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto)
{
string str;
getline(stream, str);
vector<string> vWords;
boost::split(vWords, str, boost::is_any_of(" "));
if (vWords.size() < 2)
return HTTP_INTERNAL_SERVER_ERROR;
proto = 0;
const char *ver = strstr(str.c_str(), "HTTP/1.");
if (ver != NULL)
proto = atoi(ver+7);
return atoi(vWords[1].c_str());
}
int ReadHTTPHeaders(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet)
{
int nLen = 0;
while (true)
{
string str;
std::getline(stream, str);
if (str.empty() || str == "\r")
break;
string::size_type nColon = str.find(":");
if (nColon != string::npos)
{
string strHeader = str.substr(0, nColon);
boost::trim(strHeader);
boost::to_lower(strHeader);
string strValue = str.substr(nColon+1);
boost::trim(strValue);
mapHeadersRet[strHeader] = strValue;
if (strHeader == "content-length")
nLen = atoi(strValue.c_str());
}
}
return nLen;
}
int ReadHTTPMessage(std::basic_istream<char>& stream, map<string,
string>& mapHeadersRet, string& strMessageRet,
int nProto)
{
mapHeadersRet.clear();
strMessageRet = "";
// Read header
int nLen = ReadHTTPHeaders(stream, mapHeadersRet);
if (nLen < 0 || nLen > (int)MAX_SIZE)
return HTTP_INTERNAL_SERVER_ERROR;
// Read message
if (nLen > 0)
{
vector<char> vch(nLen);
stream.read(&vch[0], nLen);
strMessageRet = string(vch.begin(), vch.end());
}
string sConHdr = mapHeadersRet["connection"];
if ((sConHdr != "close") && (sConHdr != "keep-alive"))
{
if (nProto >= 1)
mapHeadersRet["connection"] = "keep-alive";
else
mapHeadersRet["connection"] = "close";
}
return HTTP_OK;
}
//
// JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility,
// but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
// unspecified (HTTP errors and contents of 'error').
//
// 1.0 spec: http://json-rpc.org/wiki/specification
// 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http
// http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx
//
string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)
{
Object request;
request.push_back(Pair("method", strMethod));
request.push_back(Pair("params", params));
request.push_back(Pair("id", id));
return write_string(Value(request), false) + "\n";
}
Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id)
{
Object reply;
if (error.type() != null_type)
reply.push_back(Pair("result", Value::null));
else
reply.push_back(Pair("result", result));
reply.push_back(Pair("error", error));
reply.push_back(Pair("id", id));
return reply;
}
string JSONRPCReply(const Value& result, const Value& error, const Value& id)
{
Object reply = JSONRPCReplyObj(result, error, id);
return write_string(Value(reply), false) + "\n";
}
Object JSONRPCError(int code, const string& message)
{
Object error;
error.push_back(Pair("code", code));
error.push_back(Pair("message", message));
return error;
}
|
/*
* Copyright (c) 2013, Alexander Fronkin
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <cstdio>
#include <cstring>
#include <iconv.h>
#include <string>
#include "marcrecord.h"
#include "marcxml_reader.h"
namespace marcrecord {
extern "C" {
// XML start element handler for expat library.
void XMLCALL marcXmlStartElement(void *userData, const XML_Char *name,
const XML_Char **atts);
// XML end element handler for expat library.
void XMLCALL marcXmlEndElement(void *userData, const XML_Char *name);
// XML character data handler for expat library.
void XMLCALL marcXmlCharacterData(void *userData, const XML_Char *s, int len);
// XML unknown encoding handler for expat library.
int XMLCALL marcXmlUnknownEncoding(void *data, const XML_Char *encoding,
XML_Encoding *info);
} // extern "C"
} // namespace marcrecord
using namespace marcrecord;
/*
* Constructor.
*/
MarcXmlReader::MarcXmlReader(FILE *inputFile, const char *inputEncoding)
: MarcReader()
{
if (inputFile) {
// Open input file and initialize parser.
open(inputFile, inputEncoding);
} else {
// Clear object state.
m_xmlParser = NULL;
close();
}
}
/*
* Destructor.
*/
MarcXmlReader::~MarcXmlReader()
{
// Close input file and finalize parser.
close();
}
/*
* Open input file and initialize parser.
*/
bool
MarcXmlReader::open(FILE *inputFile, const char *inputEncoding)
{
// Clear error code and message.
m_errorCode = OK;
m_errorMessage = "";
// Initialize input stream parameters.
m_inputFile = inputFile == NULL ? stdin : inputFile;
m_inputEncoding = inputEncoding == NULL ? "" : inputEncoding;
// Create XML parser.
m_xmlParser = XML_ParserCreate(inputEncoding);
XML_SetUserData(m_xmlParser, &m_parserState);
XML_SetElementHandler(m_xmlParser,
marcXmlStartElement, marcXmlEndElement);
XML_SetCharacterDataHandler(m_xmlParser, marcXmlCharacterData);
XML_SetUnknownEncodingHandler(m_xmlParser,
marcXmlUnknownEncoding, NULL);
// Initialize XML parser state.
m_parserState.xmlParser = m_xmlParser;
m_parserState.done = false;
m_parserState.paused = false;
m_parserState.parentTag = "";
m_parserState.record = NULL;
m_parserState.characterData.erase();
return true;
}
/*
* Close input file and finalize parser.
*/
void
MarcXmlReader::close(void)
{
// Free XML parser.
if (m_xmlParser) {
XML_ParserFree(m_xmlParser);
}
// Clear member variables.
m_errorCode = OK;
m_errorMessage = "";
m_inputFile = NULL;
m_inputEncoding = "";
m_autoCorrectionMode = false;
m_xmlParser = NULL;
// Clear XML parser state.
m_parserState.xmlParser = NULL;
m_parserState.done = false;
m_parserState.paused = false;
m_parserState.parentTag = "";
m_parserState.record = NULL;
m_parserState.characterData.erase();
}
/*
* Read next record from MARCXML file.
*/
bool
MarcXmlReader::next(MarcRecord &record)
{
enum XML_Status parserResult;
// Clear error code and message.
m_errorCode = OK;
m_errorMessage = "";
// Clear record and initialize record pointer.
record.clear();
m_parserState.record = &record;
// Parse MARCXML file.
do {
if (m_parserState.paused) {
// Resume stopped parser.
m_parserState.paused = false;
parserResult = XML_ResumeParser(m_xmlParser);
} else {
// Read and parse buffer from file.
size_t dataLength = (int) fread(m_buffer,
1, sizeof(m_buffer), m_inputFile);
m_parserState.done = dataLength < sizeof(m_buffer);
parserResult = XML_Parse(m_xmlParser,
m_buffer, dataLength, m_parserState.done);
}
// Handle parser errors.
if (parserResult == XML_STATUS_ERROR) {
record.clear();
m_parserState.parentTag = "";
m_errorCode = ERROR_XML_PARSER;
m_errorMessage =
XML_ErrorString(XML_GetErrorCode(m_xmlParser));
return false;
}
} while (!m_parserState.done && !m_parserState.paused);
/*
* Finish if parser wasn't paused
* (means there is no more tags 'record').
*/
if (!m_parserState.paused) {
m_errorCode = END_OF_FILE;
return false;
}
return true;
}
namespace marcrecord {
/*
* XML start element handler for expat library.
*/
void XMLCALL
marcXmlStartElement(void *userData, const XML_Char *name,
const XML_Char **atts)
{
MarcXmlReader::XmlParserState *parserState =
(MarcXmlReader::XmlParserState *) userData;
// Select MARCXML element.
if (strcmp(name, "record") == 0 && parserState->parentTag == "") {
// Set parent tag.
parserState->parentTag = name;
} else if (strcmp(name, "leader") == 0
&& parserState->parentTag == "record")
{
// Set parent tag.
parserState->parentTag = name;
} else if (strcmp(name, "controlfield") == 0
&& parserState->parentTag == "record")
{
// Get attribute 'tag' for control field.
char *tag = (char *) "";
for (int i = 0; atts[i]; i += 2) {
if (strcmp(atts[i], "tag") == 0) {
tag = (char *) atts[i + 1];
}
}
// Add control field to the record.
parserState->fieldIt =
parserState->record->addControlField(tag);
// Set parent tag.
parserState->parentTag = name;
} else if (strcmp(name, "datafield") == 0
&& parserState->parentTag == "record")
{
// Get attributes 'tag', 'ind1, 'ind2' for data field.
char *tag = (char *) "";
char ind1 = ' ', ind2 = ' ';
for (int i = 0; atts[i]; i += 2) {
if (strcmp(atts[i], "tag") == 0) {
tag = (char *) atts[i + 1];
} else if (strcmp(atts[i], "ind1") == 0) {
ind1 = atts[i + 1][0];
} else if (strcmp(atts[i], "ind2") == 0) {
ind2 = atts[i + 1][0];
}
}
// Add data field to the record.
parserState->fieldIt =
parserState->record->addDataField(tag, ind1, ind2);
// Set parent tag.
parserState->parentTag = name;
} else if (strcmp(name, "subfield") == 0
&& parserState->parentTag == "datafield")
{
// Get attribute 'code' for subfield.
char subfieldId = ' ';
for (int i = 0; atts[i]; i += 2) {
if (strcmp(atts[i], "code") == 0) {
subfieldId = atts[i + 1][0];
}
}
// Add subfield to the data field.
parserState->subfieldIt =
parserState->fieldIt->addSubfield(subfieldId);
// Set parent tag.
parserState->parentTag = name;
}
// Clear character data.
parserState->characterData.erase();
}
/*
* XML end element handler for expat library.
*/
void XMLCALL
marcXmlEndElement(void *userData, const XML_Char *name)
{
MarcXmlReader::XmlParserState *parserState =
(MarcXmlReader::XmlParserState *) userData;
// Check if start and end tags are equal.
if (parserState->parentTag != name) {
return;
}
// Select MARCXML element.
if (strcmp(name, "record") == 0) {
// Restore parent tag.
parserState->parentTag = "";
// Pause parser.
parserState->paused = true;
XML_StopParser(parserState->xmlParser, XML_TRUE);
} else if (strcmp(name, "leader") == 0) {
// Restore parent tag.
parserState->parentTag = "record";
// Set record leader.
parserState->record->setLeader(parserState->characterData);
} else if (strcmp(name, "controlfield") == 0) {
// Restore parent tag.
parserState->parentTag = "record";
// Set data of control field.
parserState->fieldIt->setData(parserState->characterData);
} else if (strcmp(name, "datafield") == 0) {
// Restore parent tag.
parserState->parentTag = "record";
} else if (strcmp(name, "subfield") == 0) {
// Restore parent tag.
parserState->parentTag = "datafield";
// Set data of subfield.
parserState->subfieldIt->setData(parserState->characterData);
}
}
/*
* XML character data handler for expat library.
*/
void XMLCALL
marcXmlCharacterData(void *userData, const XML_Char *s, int len)
{
MarcXmlReader::XmlParserState *parserState =
(MarcXmlReader::XmlParserState *) userData;
parserState->characterData.append(s, len);
}
/*
* XML unknown encoding handler for expat library.
*/
int XMLCALL
marcXmlUnknownEncoding(void *data, const XML_Char *encoding,
XML_Encoding *info)
{
(void) (data);
iconv_t iconvDesc = (iconv_t) -1;
unsigned char iconvBuf[8];
// Initialize iconv.
iconvDesc = iconv_open("UTF-16BE", encoding);
if (iconvDesc == (iconv_t) -1) {
return XML_STATUS_ERROR;
}
// Generate conversion table for unknown encoding.
unsigned char i = 0;
do {
#ifndef ICONV_CONST_CHAR
char *src = (char *) &i;
#else
const char *src = (const char *) &i;
#endif
char *dest = (char *) iconvBuf;
size_t srcLen = 1;
size_t destLen = sizeof(iconvBuf);
if (iconv(iconvDesc, &src, &srcLen, &dest, &destLen)
== (size_t) -1)
{
info->map[i] = -1;
} else {
int value = 0;
unsigned char *p;
for (p = iconvBuf; (char *) p != dest; p++) {
value = (value << 8) + *p;
}
info->map[i] = value;
}
} while (i++ < 255);
// Finalize iconv.
iconv_close(iconvDesc);
// Initialize rest of encoding information.
info->data = NULL;
info->convert = NULL;
info->release = NULL;
return XML_STATUS_OK;
}
} // namespace marcrecord
|
#include <cstdlib>
#include <ctime>
#include <random>
#include "checkers.hpp"
using namespace std;
int main(int argc, char* argv[]) {
const vector<string> board = {"_b_b_b_b", "b_b_b_b_", "_b_b_b_b",
"________", "________", "w_w_w_w_",
"_w_w_w_w", "w_w_w_w_"};
srand(time(NULL));
// Zobrist_HASH::init_table(64, 4);
int total_match = 256;
int minimax_win = 0;
int tied = 0;
#pragma omp parallel for reduction(+ : minimax_win, tied)
for (int i = 0; i < total_match; i++) {
checkers chk_minimax;
checkers chk_random;
auto pttw = make_shared<TRANS_TABLE_HASH_MAP>();
auto pttb = make_shared<TRANS_TABLE_HASH_MAP>();
chk_minimax.setptt(pttb, pttw);
chk_minimax.setplayer('b');
chk_random.setplayer('w');
chk_random.setboard(board);
chk_minimax.setboard(board);
int step = 0;
while (1) {
auto vp1 = chk_minimax.next_move_handling();
if (vp1.empty()) {
// cout << "random win at " << step << endl;
// chk_minimax.print_board();
break;
}
chk_minimax.move_from_vp(vp1, chk_minimax.getplayer());
chk_random.setboard(chk_minimax.getboard());
auto vp = chk_random.random_move();
if (vp.empty()) {
// cout << "minimax win at " << step << endl;
// chk_random.print_board();
minimax_win++;
break;
}
chk_random.move_from_vp(vp, chk_random.getplayer());
chk_minimax.setboard(chk_random.getboard());
step++;
if (step >= 100) {
// cout << "tied" << endl;
tied++;
break;
}
}
// size_t trans_table_size = pttw->size() + pttb->size();
// printf("transposition table size = %lu\n", trans_table_size);
}
printf("minimax win rate %f, tie rate %f\n",
(double)minimax_win / total_match, (double)tied / total_match);
}
int main2() {
/*
const string board = {
"_b_b___b______b_____________b_b______w__w___w____w_____ww_______"};
const string board =
"_b_b___b______b_______________b_________w___w_b__w_____ww_______";
*/
const string board =
"_b_b_b_b______b______w______b___________w___w____w___w_ww_______";
checkers chk;
chk.setboard(board);
chk.setplayer('b');
chk.print_board();
/*
const auto rets = chk.get_avail_move('w');
cout << (rets.second == chk.CAP ? "CAP" : "MOVE") << endl;
const auto& ret = rets.first;
for (const auto& vp : ret) {
for (const auto& pt : vp) printf("%d %d, ", pt.first, pt.second);
cout << endl;
}
chk.print_board();
*/
/*
vector<vector<POINT>> cap;
vector<POINT> cur_vec = {{6, 7}};
chk.get_next_cap({6, 7}, cap, cur_vec, 'w');
for (const auto& vp : cap) {
for (const auto& pt : vp) printf("%d %d, ", pt.first, pt.second);
cout << endl;
}
*/
auto vp = chk.next_move_handling();
for (const auto& pt : vp) printf("%d %d, ", pt.first, pt.second);
cout << endl;
return 0;
}
vector<POINT> checkers::random_move() {
const auto avail_moves = get_avail_move(WHOSTURN);
const auto& avail_move = avail_moves.first;
if (avail_move.empty()) return {};
int rn = rand() % avail_move.size();
return avail_move[rn];
}
|
/*
* Copyright (c) 2015 Cryptonomex, Inc., and contributors.
*
* The MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <graphene/market_history/market_history_plugin.hpp>
#include <graphene/chain/account_evaluator.hpp>
#include <graphene/chain/account_object.hpp>
#include <graphene/chain/config.hpp>
#include <graphene/chain/database.hpp>
#include <graphene/chain/evaluator.hpp>
#include <graphene/chain/operation_history_object.hpp>
#include <graphene/chain/transaction_evaluation_state.hpp>
#include <graphene/protocol/fee_schedule.hpp>
#include <fc/thread/thread.hpp>
namespace graphene { namespace market_history {
namespace detail
{
class market_history_plugin_impl
{
public:
market_history_plugin_impl(market_history_plugin& _plugin)
:_self( _plugin ) {}
virtual ~market_history_plugin_impl();
/** this method is called as a callback after a block is applied
* and will process/index all operations that were applied in the block.
*/
void update_market_histories( const signed_block& b );
/// process all operations related to liquidity pools
void update_liquidity_pool_histories( time_point_sec time, const operation_history_object& oho,
const liquidity_pool_ticker_meta_object*& lp_meta );
graphene::chain::database& database()
{
return _self.database();
}
market_history_plugin& _self;
flat_set<uint32_t> _tracked_buckets;
uint32_t _maximum_history_per_bucket_size = 1000;
uint32_t _max_order_his_records_per_market = 1000;
uint32_t _max_order_his_seconds_per_market = 259200;
};
struct operation_process_fill_order
{
market_history_plugin& _plugin;
fc::time_point_sec _now;
const market_ticker_meta_object*& _meta;
operation_process_fill_order( market_history_plugin& mhp, fc::time_point_sec n, const market_ticker_meta_object*& meta )
:_plugin(mhp),_now(n),_meta(meta) {}
typedef void result_type;
/** do nothing for other operation types */
template<typename T>
void operator()( const T& )const{}
void operator()( const fill_order_operation& o )const
{
//ilog( "processing ${o}", ("o",o) );
auto& db = _plugin.database();
const auto& order_his_idx = db.get_index_type<history_index>().indices();
const auto& history_idx = order_his_idx.get<by_key>();
const auto& his_time_idx = order_his_idx.get<by_market_time>();
// To save new filled order data
history_key hkey;
hkey.base = o.pays.asset_id;
hkey.quote = o.receives.asset_id;
if( hkey.base > hkey.quote )
std::swap( hkey.base, hkey.quote );
hkey.sequence = std::numeric_limits<int64_t>::min();
auto itr = history_idx.lower_bound( hkey );
if( itr != history_idx.end() && itr->key.base == hkey.base && itr->key.quote == hkey.quote )
hkey.sequence = itr->key.sequence - 1;
else
hkey.sequence = 0;
const auto& new_order_his_obj = db.create<order_history_object>( [&]( order_history_object& ho ) {
ho.key = hkey;
ho.time = _now;
ho.op = o;
});
// save a reference to market ticker meta object
if( _meta == nullptr )
{
const auto& meta_idx = db.get_index_type<simple_index<market_ticker_meta_object>>();
if( meta_idx.size() == 0 )
_meta = &db.create<market_ticker_meta_object>( [&]( market_ticker_meta_object& mtm ) {
mtm.rolling_min_order_his_id = new_order_his_obj.id;
mtm.skip_min_order_his_id = false;
});
else
_meta = &( *meta_idx.begin() );
}
// To remove old filled order data
const auto max_records = _plugin.max_order_his_records_per_market();
hkey.sequence += max_records;
itr = history_idx.lower_bound( hkey );
if( itr != history_idx.end() && itr->key.base == hkey.base && itr->key.quote == hkey.quote )
{
const auto max_seconds = _plugin.max_order_his_seconds_per_market();
fc::time_point_sec min_time;
if( min_time + max_seconds < _now )
min_time = _now - max_seconds;
auto time_itr = his_time_idx.lower_bound( std::make_tuple( hkey.base, hkey.quote, min_time ) );
if( time_itr != his_time_idx.end() && time_itr->key.base == hkey.base && time_itr->key.quote == hkey.quote )
{
if( itr->key.sequence >= time_itr->key.sequence )
{
while( itr != history_idx.end() && itr->key.base == hkey.base && itr->key.quote == hkey.quote )
{
auto old_itr = itr;
++itr;
db.remove( *old_itr );
}
}
else
{
while( time_itr != his_time_idx.end() && time_itr->key.base == hkey.base && time_itr->key.quote == hkey.quote )
{
auto old_itr = time_itr;
++time_itr;
db.remove( *old_itr );
}
}
}
}
// To update ticker data and buckets data, only update for maker orders
if( !o.is_maker )
return;
bucket_key key;
key.base = o.pays.asset_id;
key.quote = o.receives.asset_id;
price trade_price = o.pays / o.receives;
if( key.base > key.quote )
{
std::swap( key.base, key.quote );
trade_price = ~trade_price;
}
price fill_price = o.fill_price;
if( fill_price.base.asset_id > fill_price.quote.asset_id )
fill_price = ~fill_price;
// To update ticker data
const auto& ticker_idx = db.get_index_type<market_ticker_index>().indices().get<by_market>();
auto ticker_itr = ticker_idx.find( std::make_tuple( key.base, key.quote ) );
if( ticker_itr == ticker_idx.end() )
{
db.create<market_ticker_object>( [&]( market_ticker_object& mt ) {
mt.base = key.base;
mt.quote = key.quote;
mt.last_day_base = 0;
mt.last_day_quote = 0;
mt.latest_base = fill_price.base.amount;
mt.latest_quote = fill_price.quote.amount;
mt.base_volume = trade_price.base.amount.value;
mt.quote_volume = trade_price.quote.amount.value;
});
}
else
{
db.modify( *ticker_itr, [&]( market_ticker_object& mt ) {
mt.latest_base = fill_price.base.amount;
mt.latest_quote = fill_price.quote.amount;
mt.base_volume += trade_price.base.amount.value; // ignore overflow
mt.quote_volume += trade_price.quote.amount.value; // ignore overflow
});
}
// To update buckets data
const auto max_history = _plugin.max_history();
if( max_history == 0 ) return;
const auto& buckets = _plugin.tracked_buckets();
if( buckets.size() == 0 ) return;
const auto& bucket_idx = db.get_index_type<bucket_index>();
for( auto bucket : buckets )
{
auto bucket_num = _now.sec_since_epoch() / bucket;
fc::time_point_sec cutoff;
if( bucket_num > max_history )
cutoff = cutoff + ( bucket * ( bucket_num - max_history ) );
key.seconds = bucket;
key.open = fc::time_point_sec() + ( bucket_num * bucket );
const auto& by_key_idx = bucket_idx.indices().get<by_key>();
auto bucket_itr = by_key_idx.find( key );
if( bucket_itr == by_key_idx.end() )
{ // create new bucket
/* const auto& obj = */
db.create<bucket_object>( [&]( bucket_object& b ){
b.key = key;
b.base_volume = trade_price.base.amount;
b.quote_volume = trade_price.quote.amount;
b.open_base = fill_price.base.amount;
b.open_quote = fill_price.quote.amount;
b.close_base = fill_price.base.amount;
b.close_quote = fill_price.quote.amount;
b.high_base = b.close_base;
b.high_quote = b.close_quote;
b.low_base = b.close_base;
b.low_quote = b.close_quote;
});
//wlog( " creating bucket ${b}", ("b",obj) );
}
else
{ // update existing bucket
//wlog( " before updating bucket ${b}", ("b",*bucket_itr) );
db.modify( *bucket_itr, [&]( bucket_object& b ){
try {
b.base_volume += trade_price.base.amount;
} catch( fc::overflow_exception& ) {
b.base_volume = std::numeric_limits<int64_t>::max();
}
try {
b.quote_volume += trade_price.quote.amount;
} catch( fc::overflow_exception& ) {
b.quote_volume = std::numeric_limits<int64_t>::max();
}
b.close_base = fill_price.base.amount;
b.close_quote = fill_price.quote.amount;
if( b.high() < fill_price )
{
b.high_base = b.close_base;
b.high_quote = b.close_quote;
}
if( b.low() > fill_price )
{
b.low_base = b.close_base;
b.low_quote = b.close_quote;
}
});
//wlog( " after bucket bucket ${b}", ("b",*bucket_itr) );
}
{
key.open = fc::time_point_sec();
bucket_itr = by_key_idx.lower_bound( key );
while( bucket_itr != by_key_idx.end() &&
bucket_itr->key.base == key.base &&
bucket_itr->key.quote == key.quote &&
bucket_itr->key.seconds == bucket &&
bucket_itr->key.open < cutoff )
{
// elog( " removing old bucket ${b}", ("b", *bucket_itr) );
auto old_bucket_itr = bucket_itr;
++bucket_itr;
db.remove( *old_bucket_itr );
}
}
}
}
};
market_history_plugin_impl::~market_history_plugin_impl()
{}
void market_history_plugin_impl::update_market_histories( const signed_block& b )
{
graphene::chain::database& db = database();
const market_ticker_meta_object* _meta = nullptr;
const auto& meta_idx = db.get_index_type<simple_index<market_ticker_meta_object>>();
if( meta_idx.size() > 0 )
_meta = &( *meta_idx.begin() );
const liquidity_pool_ticker_meta_object* _lp_meta = nullptr;
const auto& lp_meta_idx = db.get_index_type<simple_index<liquidity_pool_ticker_meta_object>>();
if( lp_meta_idx.size() > 0 )
_lp_meta = &( *lp_meta_idx.begin() );
const vector<optional< operation_history_object > >& hist = db.get_applied_operations();
for( const optional< operation_history_object >& o_op : hist )
{
if( o_op.valid() )
{
// process market history
try
{
o_op->op.visit( operation_process_fill_order( _self, b.timestamp, _meta ) );
} FC_CAPTURE_AND_LOG( (o_op) )
// process liquidity pool history
update_liquidity_pool_histories( b.timestamp, *o_op, _lp_meta );
}
}
// roll out expired data from ticker
if( _meta != nullptr )
{
time_point_sec last_day = b.timestamp - 86400;
object_id_type last_min_his_id = _meta->rolling_min_order_his_id;
bool skip = _meta->skip_min_order_his_id;
const auto& ticker_idx = db.get_index_type<market_ticker_index>().indices().get<by_market>();
const auto& history_idx = db.get_index_type<history_index>().indices().get<by_id>();
auto history_itr = history_idx.lower_bound( _meta->rolling_min_order_his_id );
while( history_itr != history_idx.end() && history_itr->time < last_day )
{
const fill_order_operation& o = history_itr->op;
if( skip && history_itr->id == _meta->rolling_min_order_his_id )
skip = false;
else if( o.is_maker )
{
bucket_key key;
key.base = o.pays.asset_id;
key.quote = o.receives.asset_id;
price trade_price = o.pays / o.receives;
if( key.base > key.quote )
{
std::swap( key.base, key.quote );
trade_price = ~trade_price;
}
price fill_price = o.fill_price;
if( fill_price.base.asset_id > fill_price.quote.asset_id )
fill_price = ~fill_price;
auto ticker_itr = ticker_idx.find( std::make_tuple( key.base, key.quote ) );
if( ticker_itr != ticker_idx.end() ) // should always be true
{
db.modify( *ticker_itr, [&]( market_ticker_object& mt ) {
mt.last_day_base = fill_price.base.amount;
mt.last_day_quote = fill_price.quote.amount;
mt.base_volume -= trade_price.base.amount.value; // ignore underflow
mt.quote_volume -= trade_price.quote.amount.value; // ignore underflow
});
}
}
last_min_his_id = history_itr->id;
++history_itr;
}
// update meta
if( history_itr != history_idx.end() ) // if still has some data rolling
{
if( history_itr->id != _meta->rolling_min_order_his_id ) // if rolled out some
{
db.modify( *_meta, [&]( market_ticker_meta_object& mtm ) {
mtm.rolling_min_order_his_id = history_itr->id;
mtm.skip_min_order_his_id = false;
});
}
}
else // if all data are rolled out
{
if( !_meta->skip_min_order_his_id
|| last_min_his_id != _meta->rolling_min_order_his_id ) // if rolled out some
{
db.modify( *_meta, [&]( market_ticker_meta_object& mtm ) {
mtm.rolling_min_order_his_id = last_min_his_id;
mtm.skip_min_order_his_id = true;
});
}
}
}
// roll out expired data from LP ticker
if( _lp_meta != nullptr )
{
time_point_sec last_day = b.timestamp - 86400;
object_id_type last_min_his_id = _lp_meta->rolling_min_lp_his_id;
bool skip = _lp_meta->skip_min_lp_his_id;
const auto& history_idx = db.get_index_type<liquidity_pool_history_index>().indices().get<by_id>();
auto history_itr = history_idx.lower_bound( _lp_meta->rolling_min_lp_his_id );
while( history_itr != history_idx.end() && history_itr->time < last_day )
{
if( skip && history_itr->id == _lp_meta->rolling_min_lp_his_id )
skip = false;
else
{
liquidity_pool_ticker_id_type ticker_id( history_itr->pool.instance );
const liquidity_pool_ticker_object* ticker = db.find<liquidity_pool_ticker_object>( ticker_id );
if( ticker != nullptr ) // should always be true
{
const operation_history_object& oho = history_itr->op;
if( oho.op.is_type< liquidity_pool_deposit_operation >() )
{
auto& op = oho.op.get< liquidity_pool_deposit_operation >();
auto& result = oho.result.get< generic_exchange_operation_result >();
db.modify( *ticker, [&op,&result]( liquidity_pool_ticker_object& t ) {
t._24h_deposit_count -= 1;
t._24h_deposit_amount_a -= op.amount_a.amount.value;
t._24h_deposit_amount_b -= op.amount_b.amount.value;
t._24h_deposit_share_amount -= result.received.front().amount.value;
t._24h_balance_delta_a -= op.amount_a.amount.value;
t._24h_balance_delta_b -= op.amount_b.amount.value;
});
}
else if( oho.op.is_type< liquidity_pool_withdraw_operation >() )
{
auto& op = oho.op.get< liquidity_pool_withdraw_operation >();
auto& result = oho.result.get< generic_exchange_operation_result >();
db.modify( *ticker, [&op,&result]( liquidity_pool_ticker_object& t ) {
t._24h_withdrawal_count -= 1;
t._24h_withdrawal_amount_a -= result.received.front().amount.value;
t._24h_withdrawal_amount_b -= result.received.back().amount.value;
t._24h_withdrawal_share_amount -= op.share_amount.amount.value;
t._24h_withdrawal_fee_a -= result.fees.front().amount.value;
t._24h_withdrawal_fee_b -= result.fees.back().amount.value;
t._24h_balance_delta_a += result.received.front().amount.value;
t._24h_balance_delta_b += result.received.back().amount.value;
});
}
else if( oho.op.is_type< liquidity_pool_exchange_operation >() )
{
auto& op = oho.op.get< liquidity_pool_exchange_operation >();
auto& result = oho.result.get< generic_exchange_operation_result >();
db.modify( *ticker, [&op,&result]( liquidity_pool_ticker_object& t ) {
auto amount_in = op.amount_to_sell.amount - result.fees.front().amount;
auto amount_out = result.received.front().amount + result.fees.at(1).amount;
if( op.amount_to_sell.asset_id < op.min_to_receive.asset_id ) // pool got a, paid b
{
t._24h_exchange_a2b_count -= 1;
t._24h_exchange_a2b_amount_a -= amount_in.value;
t._24h_exchange_a2b_amount_b -= amount_out.value;
t._24h_exchange_fee_b -= result.fees.back().amount.value;
t._24h_balance_delta_a -= amount_in.value;
t._24h_balance_delta_b += amount_out.value;
}
else // pool got b, paid a
{
t._24h_exchange_b2a_count -= 1;
t._24h_exchange_b2a_amount_a -= amount_out.value;
t._24h_exchange_b2a_amount_b -= amount_in.value;
t._24h_exchange_fee_a -= result.fees.back().amount.value;
t._24h_balance_delta_a += amount_out.value;
t._24h_balance_delta_b -= amount_in.value;
}
});
}
}
}
last_min_his_id = history_itr->id;
++history_itr;
}
// update meta
if( history_itr != history_idx.end() ) // if still has some data rolling
{
if( history_itr->id != _lp_meta->rolling_min_lp_his_id ) // if rolled out some
{
db.modify( *_lp_meta, [history_itr]( liquidity_pool_ticker_meta_object& mtm ) {
mtm.rolling_min_lp_his_id = history_itr->id;
mtm.skip_min_lp_his_id = false;
});
}
}
else // if all data are rolled out
{
if( !_lp_meta->skip_min_lp_his_id
|| last_min_his_id != _lp_meta->rolling_min_lp_his_id ) // if rolled out some
{
db.modify( *_lp_meta, [last_min_his_id]( liquidity_pool_ticker_meta_object& mtm ) {
mtm.rolling_min_lp_his_id = last_min_his_id;
mtm.skip_min_lp_his_id = true;
});
}
}
}
}
struct get_liquidity_pool_id_visitor
{
typedef optional<liquidity_pool_id_type> result_type;
/** do nothing for other operation types */
template<typename T>
result_type operator()( const T& )const
{
return {};
}
result_type operator()( const liquidity_pool_delete_operation& o )const
{
return o.pool;
}
result_type operator()( const liquidity_pool_deposit_operation& o )const
{
return o.pool;
}
result_type operator()( const liquidity_pool_withdraw_operation& o )const
{
return o.pool;
}
result_type operator()( const liquidity_pool_exchange_operation& o )const
{
return o.pool;
}
};
void market_history_plugin_impl::update_liquidity_pool_histories(
time_point_sec time, const operation_history_object& oho,
const liquidity_pool_ticker_meta_object*& lp_meta )
{ try {
optional<liquidity_pool_id_type> pool;
uint64_t sequence = 0;
if( oho.op.is_type< liquidity_pool_create_operation >() )
{
pool = *oho.result.get<generic_operation_result>().new_objects.begin();
sequence = 1;
}
else
{
pool = oho.op.visit( get_liquidity_pool_id_visitor() );
}
if( pool.valid() )
{
auto& db = database();
const auto& his_index = db.get_index_type<liquidity_pool_history_index>().indices();
const auto& his_seq_idx = his_index.get<by_pool_seq>();
const auto& his_time_idx = his_index.get<by_pool_time>();
if( sequence == 0 )
{
auto itr = his_seq_idx.lower_bound( *pool );
if( itr != his_seq_idx.end() && itr->pool == *pool )
sequence = itr->sequence + 1;
else
sequence = 2;
}
// To save new data
const auto& new_his_obj = db.create<liquidity_pool_history_object>( [&pool,sequence,time,&oho](
liquidity_pool_history_object& ho ) {
ho.pool = *pool;
ho.sequence = sequence;
ho.time = time;
ho.op_type = oho.op.which();
ho.op = oho;
});
// save a reference to the ticker meta object
if( lp_meta == nullptr )
{
const auto& lp_meta_idx = db.get_index_type<simple_index<liquidity_pool_ticker_meta_object>>();
if( lp_meta_idx.size() == 0 )
lp_meta = &db.create<liquidity_pool_ticker_meta_object>( [&new_his_obj](
liquidity_pool_ticker_meta_object& lptm ) {
lptm.rolling_min_lp_his_id = new_his_obj.id;
lptm.skip_min_lp_his_id = false;
});
else
lp_meta = &( *lp_meta_idx.begin() );
}
// To remove old history data
if( sequence > _max_order_his_records_per_market )
{
const auto min_seq = sequence - _max_order_his_records_per_market;
auto itr = his_seq_idx.lower_bound( std::make_tuple( *pool, min_seq ) );
if( itr != his_seq_idx.end() && itr->pool == *pool )
{
fc::time_point_sec min_time;
if( min_time + _max_order_his_seconds_per_market < time )
min_time = time - _max_order_his_seconds_per_market;
auto time_itr = his_time_idx.lower_bound( std::make_tuple( *pool, min_time ) );
if( time_itr != his_time_idx.end() && time_itr->pool == *pool )
{
if( itr->sequence <= time_itr->sequence )
{
while( itr != his_seq_idx.end() && itr->pool == *pool )
{
auto old_itr = itr;
++itr;
db.remove( *old_itr );
}
}
else
{
while( time_itr != his_time_idx.end() && time_itr->pool == *pool )
{
auto old_itr = time_itr;
++time_itr;
db.remove( *old_itr );
}
}
}
}
}
// To update ticker data
if( sequence == 1 ) // create
{
const liquidity_pool_ticker_object* ticker = nullptr;
do {
ticker = &db.create<liquidity_pool_ticker_object>( []( liquidity_pool_ticker_object& lpt ) {
});
} while( ticker->id.instance() < pool->instance );
}
else
{
liquidity_pool_ticker_id_type ticker_id( pool->instance );
const liquidity_pool_ticker_object* ticker = db.find<liquidity_pool_ticker_object>( ticker_id );
if( ticker != nullptr )
{
if( oho.op.is_type< liquidity_pool_deposit_operation >() )
{
auto& op = oho.op.get< liquidity_pool_deposit_operation >();
auto& result = oho.result.get< generic_exchange_operation_result >();
db.modify( *ticker, [&op,&result]( liquidity_pool_ticker_object& t ) {
t._24h_deposit_count += 1;
t._24h_deposit_amount_a += op.amount_a.amount.value;
t._24h_deposit_amount_b += op.amount_b.amount.value;
t._24h_deposit_share_amount += result.received.front().amount.value;
t._24h_balance_delta_a += op.amount_a.amount.value;
t._24h_balance_delta_b += op.amount_b.amount.value;
t.total_deposit_count += 1;
t.total_deposit_amount_a += op.amount_a.amount.value;
t.total_deposit_amount_b += op.amount_b.amount.value;
t.total_deposit_share_amount += result.received.front().amount.value;
});
}
else if( oho.op.is_type< liquidity_pool_withdraw_operation >() )
{
auto& op = oho.op.get< liquidity_pool_withdraw_operation >();
auto& result = oho.result.get< generic_exchange_operation_result >();
db.modify( *ticker, [&op,&result]( liquidity_pool_ticker_object& t ) {
t._24h_withdrawal_count += 1;
t._24h_withdrawal_amount_a += result.received.front().amount.value;
t._24h_withdrawal_amount_b += result.received.back().amount.value;
t._24h_withdrawal_share_amount += op.share_amount.amount.value;
t._24h_withdrawal_fee_a += result.fees.front().amount.value;
t._24h_withdrawal_fee_b += result.fees.back().amount.value;
t._24h_balance_delta_a -= result.received.front().amount.value;
t._24h_balance_delta_b -= result.received.back().amount.value;
t.total_withdrawal_count += 1;
t.total_withdrawal_amount_a += result.received.front().amount.value;
t.total_withdrawal_amount_b += result.received.back().amount.value;
t.total_withdrawal_share_amount += op.share_amount.amount.value;
t.total_withdrawal_fee_a += result.fees.front().amount.value;
t.total_withdrawal_fee_b += result.fees.back().amount.value;
});
}
else if( oho.op.is_type< liquidity_pool_exchange_operation >() )
{
auto& op = oho.op.get< liquidity_pool_exchange_operation >();
auto& result = oho.result.get< generic_exchange_operation_result >();
db.modify( *ticker, [&op,&result]( liquidity_pool_ticker_object& t ) {
auto amount_in = op.amount_to_sell.amount - result.fees.front().amount;
auto amount_out = result.received.front().amount + result.fees.at(1).amount;
if( op.amount_to_sell.asset_id < op.min_to_receive.asset_id ) // pool got a, paid b
{
t._24h_exchange_a2b_count += 1;
t._24h_exchange_a2b_amount_a += amount_in.value;
t._24h_exchange_a2b_amount_b += amount_out.value;
t._24h_exchange_fee_b += result.fees.back().amount.value;
t._24h_balance_delta_a += amount_in.value;
t._24h_balance_delta_b -= amount_out.value;
t.total_exchange_a2b_count += 1;
t.total_exchange_a2b_amount_a += amount_in.value;
t.total_exchange_a2b_amount_b += amount_out.value;
t.total_exchange_fee_b += result.fees.back().amount.value;
}
else // pool got b, paid a
{
t._24h_exchange_b2a_count += 1;
t._24h_exchange_b2a_amount_a += amount_out.value;
t._24h_exchange_b2a_amount_b += amount_in.value;
t._24h_exchange_fee_a += result.fees.back().amount.value;
t._24h_balance_delta_a -= amount_out.value;
t._24h_balance_delta_b += amount_in.value;
t.total_exchange_b2a_count += 1;
t.total_exchange_b2a_amount_a += amount_out.value;
t.total_exchange_b2a_amount_b += amount_in.value;
t.total_exchange_fee_a += result.fees.back().amount.value;
}
});
}
}
}
}
} FC_CAPTURE_AND_LOG( (time)(oho) ) }
} // end namespace detail
market_history_plugin::market_history_plugin() :
my( new detail::market_history_plugin_impl(*this) )
{
}
market_history_plugin::~market_history_plugin()
{
}
std::string market_history_plugin::plugin_name()const
{
return "market_history";
}
void market_history_plugin::plugin_set_program_options(
boost::program_options::options_description& cli,
boost::program_options::options_description& cfg
)
{
cli.add_options()
("bucket-size", boost::program_options::value<string>()->default_value("[60,300,900,1800,3600,14400,86400]"),
"Track market history by grouping orders into buckets of equal size measured "
"in seconds specified as a JSON array of numbers")
("history-per-size", boost::program_options::value<uint32_t>()->default_value(1000),
"How far back in time to track history for each bucket size, "
"measured in the number of buckets (default: 1000)")
("max-order-his-records-per-market", boost::program_options::value<uint32_t>()->default_value(1000),
"Will only store this amount of matched orders for each market in order history for querying, "
"or those meet the other option, which has more data (default: 1000). "
"This parameter is reused for liquidity pools as maximum operations per pool in history.")
("max-order-his-seconds-per-market", boost::program_options::value<uint32_t>()->default_value(259200),
"Will only store matched orders in last X seconds for each market in order history for querying, "
"or those meet the other option, which has more data (default: 259200 (3 days)). "
"This parameter is reused for liquidity pools as operations in last X seconds per pool in history. "
"Note: this parameter need to be greater than 24 hours to be able to serve market ticker data correctly.")
;
cfg.add(cli);
}
void market_history_plugin::plugin_initialize(const boost::program_options::variables_map& options)
{ try {
database().applied_block.connect( [this]( const signed_block& b){ my->update_market_histories(b); } );
database().add_index< primary_index< bucket_index > >();
database().add_index< primary_index< history_index > >();
database().add_index< primary_index< market_ticker_index > >();
database().add_index< primary_index< simple_index< market_ticker_meta_object > > >();
database().add_index< primary_index< liquidity_pool_history_index > >();
database().add_index< primary_index< simple_index< liquidity_pool_ticker_meta_object > > >();
database().add_index< primary_index< liquidity_pool_ticker_index, 8 > >(); // 256 pools per chunk
if( options.count( "bucket-size" ) > 0 )
{
const std::string& buckets = options["bucket-size"].as<string>();
my->_tracked_buckets = fc::json::from_string(buckets).as<flat_set<uint32_t>>(2);
my->_tracked_buckets.erase( 0 );
}
if( options.count( "history-per-size" ) > 0 )
my->_maximum_history_per_bucket_size = options["history-per-size"].as<uint32_t>();
if( options.count( "max-order-his-records-per-market" ) > 0 )
my->_max_order_his_records_per_market = options["max-order-his-records-per-market"].as<uint32_t>();
if( options.count( "max-order-his-seconds-per-market" ) > 0 )
my->_max_order_his_seconds_per_market = options["max-order-his-seconds-per-market"].as<uint32_t>();
} FC_CAPTURE_AND_RETHROW() }
void market_history_plugin::plugin_startup()
{
}
const flat_set<uint32_t>& market_history_plugin::tracked_buckets() const
{
return my->_tracked_buckets;
}
uint32_t market_history_plugin::max_history()const
{
return my->_maximum_history_per_bucket_size;
}
uint32_t market_history_plugin::max_order_his_records_per_market()const
{
return my->_max_order_his_records_per_market;
}
uint32_t market_history_plugin::max_order_his_seconds_per_market()const
{
return my->_max_order_his_seconds_per_market;
}
} }
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "init.h"
#include "util.h"
#include "sync.h"
#include "ui_interface.h"
#include "base58.h"
#include "bitcoinrpc.h"
#include "db.h"
#include "alert.h"
#include "checkpoints.h"
#include <boost/asio.hpp>
#include <boost/asio/ip/v6_only.hpp>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/shared_ptr.hpp>
#include <list>
using namespace std;
using namespace boost;
using namespace boost::asio;
using namespace json_spirit;
// Key used by getwork/getblocktemplate miners.
// Allocated in StartRPCThreads, free'd in StopRPCThreads
CReserveKey* pMiningKey = NULL;
static std::string strRPCUserColonPass;
// These are created by StartRPCThreads, destroyed in StopRPCThreads
static asio::io_service* rpc_io_service = NULL;
static ssl::context* rpc_ssl_context = NULL;
static boost::thread_group* rpc_worker_group = NULL;
static inline unsigned short GetDefaultRPCPort()
{
return GetBoolArg("-testnet", false) ? 18776 : 38776;
}
Object JSONRPCError(int code, const string& message)
{
Object error;
error.push_back(Pair("code", code));
error.push_back(Pair("message", message));
return error;
}
void RPCTypeCheck(const Array& params,
const list<Value_type>& typesExpected,
bool fAllowNull)
{
unsigned int i = 0;
BOOST_FOREACH(Value_type t, typesExpected)
{
if (params.size() <= i)
break;
const Value& v = params[i];
if (!((v.type() == t) || (fAllowNull && (v.type() == null_type))))
{
string err = strprintf("Expected type %s, got %s",
Value_type_name[t], Value_type_name[v.type()]);
throw JSONRPCError(RPC_TYPE_ERROR, err);
}
i++;
}
}
void RPCTypeCheck(const Object& o,
const map<string, Value_type>& typesExpected,
bool fAllowNull)
{
BOOST_FOREACH(const PAIRTYPE(string, Value_type)& t, typesExpected)
{
const Value& v = find_value(o, t.first);
if (!fAllowNull && v.type() == null_type)
throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first.c_str()));
if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type))))
{
string err = strprintf("Expected type %s for %s, got %s",
Value_type_name[t.second], t.first.c_str(), Value_type_name[v.type()]);
throw JSONRPCError(RPC_TYPE_ERROR, err);
}
}
}
int64 AmountFromValue(const Value& value)
{
double dAmount = value.get_real();
if (dAmount <= 0.0 || dAmount > 21000000.0)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
int64 nAmount = roundint64(dAmount * COIN);
if (!MoneyRange(nAmount))
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
return nAmount;
}
Value ValueFromAmount(int64 amount)
{
return (double)amount / (double)COIN;
}
std::string HexBits(unsigned int nBits)
{
union {
int32_t nBits;
char cBits[4];
} uBits;
uBits.nBits = htonl((int32_t)nBits);
return HexStr(BEGIN(uBits.cBits), END(uBits.cBits));
}
///
/// Note: This interface may still be subject to change.
///
string CRPCTable::help(string strCommand) const
{
string strRet;
set<rpcfn_type> setDone;
for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi)
{
const CRPCCommand *pcmd = mi->second;
string strMethod = mi->first;
// We already filter duplicates, but these deprecated screw up the sort order
if (strMethod.find("label") != string::npos)
continue;
if (strCommand != "" && strMethod != strCommand)
continue;
try
{
Array params;
rpcfn_type pfn = pcmd->actor;
if (setDone.insert(pfn).second)
(*pfn)(params, true);
}
catch (std::exception& e)
{
// Help text is returned in an exception
string strHelp = string(e.what());
if (strCommand == "")
if (strHelp.find('\n') != string::npos)
strHelp = strHelp.substr(0, strHelp.find('\n'));
strRet += strHelp + "\n";
}
}
if (strRet == "")
strRet = strprintf("help: unknown command: %s\n", strCommand.c_str());
strRet = strRet.substr(0,strRet.size()-1);
return strRet;
}
Value help(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"help [command]\n"
"List commands, or get help for a command.");
string strCommand;
if (params.size() > 0)
strCommand = params[0].get_str();
return tableRPC.help(strCommand);
}
Value stop(const Array& params, bool fHelp)
{
// Accept the deprecated and ignored 'detach' boolean argument
if (fHelp || params.size() > 1)
throw runtime_error(
"stop\n"
"Stop UTCC server.");
// Shutdown will take long enough that the response should get back
StartShutdown();
return "UTCC server stopping";
}
// Send alert (first introduced in ppcoin)
// There is a known deadlock situation with ThreadMessageHandler
// ThreadMessageHandler: holds cs_vSend and acquiring cs_main in SendMessages()
// ThreadRPCServer: holds cs_main and acquiring cs_vSend in alert.RelayTo()/PushMessage()/BeginMessage()
Value sendalert(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 6)
throw runtime_error(
"sendalert <message> <privatekey> <minver> <maxver> <priority> <id> [cancelupto]\n"
"<message> is the alert text message\n"
"<privatekey> is base58 hex string of alert master private key\n"
"<minver> is the minimum applicable internal client version\n"
"<maxver> is the maximum applicable internal client version\n"
"<priority> is integer priority number\n"
"<id> is the alert id\n"
"[cancelupto] cancels all alert id's up to this number\n"
"Returns true or false.");
// Prepare the alert message
CAlert alert;
alert.strStatusBar = params[0].get_str();
alert.nMinVer = params[2].get_int();
alert.nMaxVer = params[3].get_int();
alert.nPriority = params[4].get_int();
alert.nID = params[5].get_int();
if (params.size() > 6)
alert.nCancel = params[6].get_int();
alert.nVersion = PROTOCOL_VERSION;
alert.nRelayUntil = GetAdjustedTime() + 365*24*60*60;
alert.nExpiration = GetAdjustedTime() + 365*24*60*60;
CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
sMsg << (CUnsignedAlert)alert;
alert.vchMsg = vector<unsigned char>(sMsg.begin(), sMsg.end());
// Prepare master key and sign alert message
CBitcoinSecret vchSecret;
if (!vchSecret.SetString(params[1].get_str()))
throw runtime_error("Invalid alert master key");
CKey key;
bool fCompressed;
CSecret secret = vchSecret.GetSecret(fCompressed);
key.SetSecret(secret, fCompressed); // if key is not correct openssl may crash
if (!key.Sign(Hash2(alert.vchMsg.begin(), alert.vchMsg.end()), alert.vchSig))
throw runtime_error(
"Unable to sign alert, check alert master key?\n");
// Process alert
if(!alert.ProcessAlert())
throw runtime_error(
"Failed to process alert.\n");
// Relay alert
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
alert.RelayTo(pnode);
}
Object result;
result.push_back(Pair("strStatusBar", alert.strStatusBar));
result.push_back(Pair("nVersion", alert.nVersion));
result.push_back(Pair("nMinVer", alert.nMinVer));
result.push_back(Pair("nMaxVer", alert.nMaxVer));
result.push_back(Pair("nPriority", alert.nPriority));
result.push_back(Pair("nID", alert.nID));
if (alert.nCancel > 0)
result.push_back(Pair("nCancel", alert.nCancel));
return result;
}
// RPC commands related to sync checkpoints
// get information of sync-checkpoint (first introduced in ppcoin)
Value getcheckpoint(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getcheckpoint\n"
"Show info of synchronized checkpoint.\n");
Object result;
CBlockIndex* pindexCheckpoint;
result.push_back(Pair("synccheckpoint", Checkpoints::hashSyncCheckpoint.ToString().c_str()));
if (mapBlockIndex.count(Checkpoints::hashSyncCheckpoint))
{
pindexCheckpoint = mapBlockIndex[Checkpoints::hashSyncCheckpoint];
result.push_back(Pair("height", pindexCheckpoint->nHeight));
result.push_back(Pair("timestamp", (boost::int64_t) pindexCheckpoint->GetBlockTime()));
}
result.push_back(Pair("subscribemode", Checkpoints::IsSyncCheckpointEnforced()? "enforce" : "advisory"));
if (mapArgs.count("-checkpointkey"))
result.push_back(Pair("checkpointmaster", true));
return result;
}
Value sendcheckpoint(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"sendcheckpoint <blockhash>\n"
"Send a synchronized checkpoint.\n");
if (!mapArgs.count("-checkpointkey") || CSyncCheckpoint::strMasterPrivKey.empty())
throw runtime_error("Not a checkpointmaster node, first set checkpointkey in configuration and restart client. ");
std::string strHash = params[0].get_str();
uint256 hash(strHash);
if (!Checkpoints::SendSyncCheckpoint(hash))
throw runtime_error("Failed to send checkpoint, check log. ");
Object result;
CBlockIndex* pindexCheckpoint;
result.push_back(Pair("synccheckpoint", Checkpoints::hashSyncCheckpoint.ToString().c_str()));
if (mapBlockIndex.count(Checkpoints::hashSyncCheckpoint))
{
pindexCheckpoint = mapBlockIndex[Checkpoints::hashSyncCheckpoint];
result.push_back(Pair("height", pindexCheckpoint->nHeight));
result.push_back(Pair("timestamp", (boost::int64_t) pindexCheckpoint->GetBlockTime()));
}
result.push_back(Pair("subscribemode", Checkpoints::IsSyncCheckpointEnforced()? "enforce" : "advisory"));
if (mapArgs.count("-checkpointkey"))
result.push_back(Pair("checkpointmaster", true));
return result;
}
Value enforcecheckpoint(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"enforcecheckpoint <enforce>\n"
"<enforce> is true or false to enable or disable enforcement of broadcasted checkpoints by developer.");
bool fEnforceCheckpoint = params[0].get_bool();
if (mapArgs.count("-checkpointkey") && !fEnforceCheckpoint)
throw runtime_error(
"checkpoint master node must enforce synchronized checkpoints.");
if (fEnforceCheckpoint)
Checkpoints::strCheckpointWarning = "";
mapArgs["-checkpointenforce"] = (fEnforceCheckpoint ? "1" : "0");
return Value::null;
}
//
// Call Table
//
static const CRPCCommand vRPCCommands[] =
{ // name actor (function) okSafeMode threadSafe
// ------------------------ ----------------------- ---------- ----------
{ "help", &help, true, true },
{ "stop", &stop, true, true },
{ "getblockcount", &getblockcount, true, false },
{ "getconnectioncount", &getconnectioncount, true, false },
{ "getpeerinfo", &getpeerinfo, true, false },
{ "addnode", &addnode, true, true },
{ "getaddednodeinfo", &getaddednodeinfo, true, true },
{ "getdifficulty", &getdifficulty, true, false },
{ "getgenerate", &getgenerate, true, false },
{ "setgenerate", &setgenerate, true, false },
{ "gethashespersec", &gethashespersec, true, false },
{ "getinfo", &getinfo, true, false },
{ "getmininginfo", &getmininginfo, true, false },
{ "getnewaddress", &getnewaddress, true, false },
{ "getaccountaddress", &getaccountaddress, true, false },
{ "setaccount", &setaccount, true, false },
{ "getaccount", &getaccount, false, false },
{ "getaddressesbyaccount", &getaddressesbyaccount, true, false },
{ "sendtoaddress", &sendtoaddress, false, false },
{ "getreceivedbyaddress", &getreceivedbyaddress, false, false },
{ "getreceivedbyaccount", &getreceivedbyaccount, false, false },
{ "listreceivedbyaddress", &listreceivedbyaddress, false, false },
{ "listreceivedbyaccount", &listreceivedbyaccount, false, false },
{ "backupwallet", &backupwallet, true, false },
{ "keypoolrefill", &keypoolrefill, true, false },
{ "walletpassphrase", &walletpassphrase, true, false },
{ "walletpassphrasechange", &walletpassphrasechange, false, false },
{ "walletlock", &walletlock, true, false },
{ "encryptwallet", &encryptwallet, false, false },
{ "validateaddress", &validateaddress, true, false },
{ "getbalance", &getbalance, false, false },
{ "move", &movecmd, false, false },
{ "sendfrom", &sendfrom, false, false },
{ "sendmany", &sendmany, false, false },
{ "addmultisigaddress", &addmultisigaddress, false, false },
{ "createmultisig", &createmultisig, true, true },
{ "getrawmempool", &getrawmempool, true, false },
{ "getblock", &getblock, false, false },
{ "getblockhash", &getblockhash, false, false },
{ "gettransaction", &gettransaction, false, false },
{ "listtransactions", &listtransactions, false, false },
{ "listaddressgroupings", &listaddressgroupings, false, false },
{ "signmessage", &signmessage, false, false },
{ "verifymessage", &verifymessage, false, false },
{ "getwork", &getwork, true, false },
{ "getwork2", &getwork2, true, false },
{ "listaccounts", &listaccounts, false, false },
{ "settxfee", &settxfee, false, false },
{ "getblocktemplate", &getblocktemplate, true, false },
{ "submitblock", &submitblock, false, false },
{ "listsinceblock", &listsinceblock, false, false },
{ "dumpprivkey", &dumpprivkey, true, false },
{ "importprivkey", &importprivkey, false, false },
{ "listunspent", &listunspent, false, false },
{ "getrawtransaction", &getrawtransaction, false, false },
{ "createrawtransaction", &createrawtransaction, false, false },
{ "decoderawtransaction", &decoderawtransaction, false, false },
{ "signrawtransaction", &signrawtransaction, false, false },
{ "sendrawtransaction", &sendrawtransaction, false, false },
{ "gettxoutsetinfo", &gettxoutsetinfo, true, false },
{ "gettxout", &gettxout, true, false },
{ "lockunspent", &lockunspent, false, false },
{ "listlockunspent", &listlockunspent, false, false },
{ "makekeypair", &makekeypair, false, false },
{ "sendalert", &sendalert, false, false },
{ "getcheckpoint", &getcheckpoint, false, false },
{ "sendcheckpoint", &sendcheckpoint, false, false },
{ "enforcecheckpoint", &enforcecheckpoint, false, false },
};
CRPCTable::CRPCTable()
{
unsigned int vcidx;
for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++)
{
const CRPCCommand *pcmd;
pcmd = &vRPCCommands[vcidx];
mapCommands[pcmd->name] = pcmd;
}
}
const CRPCCommand *CRPCTable::operator[](string name) const
{
map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name);
if (it == mapCommands.end())
return NULL;
return (*it).second;
}
//
// HTTP protocol
//
// This ain't Apache. We're just using HTTP header for the length field
// and to be compatible with other JSON-RPC implementations.
//
string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders)
{
ostringstream s;
s << "POST / HTTP/1.1\r\n"
<< "User-Agent: UTCC-json-rpc/" << FormatFullVersion() << "\r\n"
<< "Host: 127.0.0.1\r\n"
<< "Content-Type: application/json\r\n"
<< "Content-Length: " << strMsg.size() << "\r\n"
<< "Connection: close\r\n"
<< "Accept: application/json\r\n";
BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders)
s << item.first << ": " << item.second << "\r\n";
s << "\r\n" << strMsg;
return s.str();
}
string rfc1123Time()
{
char buffer[64];
time_t now;
time(&now);
struct tm* now_gmt = gmtime(&now);
string locale(setlocale(LC_TIME, NULL));
setlocale(LC_TIME, "C"); // we want POSIX (aka "C") weekday/month strings
strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt);
setlocale(LC_TIME, locale.c_str());
return string(buffer);
}
static string HTTPReply(int nStatus, const string& strMsg, bool keepalive)
{
if (nStatus == HTTP_UNAUTHORIZED)
return strprintf("HTTP/1.0 401 Authorization Required\r\n"
"Date: %s\r\n"
"Server: UTCC-json-rpc/%s\r\n"
"WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n"
"Content-Type: text/html\r\n"
"Content-Length: 296\r\n"
"\r\n"
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n"
"\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n"
"<HTML>\r\n"
"<HEAD>\r\n"
"<TITLE>Error</TITLE>\r\n"
"<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n"
"</HEAD>\r\n"
"<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"
"</HTML>\r\n", rfc1123Time().c_str(), FormatFullVersion().c_str());
const char *cStatus;
if (nStatus == HTTP_OK) cStatus = "OK";
else if (nStatus == HTTP_BAD_REQUEST) cStatus = "Bad Request";
else if (nStatus == HTTP_FORBIDDEN) cStatus = "Forbidden";
else if (nStatus == HTTP_NOT_FOUND) cStatus = "Not Found";
else if (nStatus == HTTP_INTERNAL_SERVER_ERROR) cStatus = "Internal Server Error";
else cStatus = "";
return strprintf(
"HTTP/1.1 %d %s\r\n"
"Date: %s\r\n"
"Connection: %s\r\n"
"Content-Length: %"PRIszu"\r\n"
"Content-Type: application/json\r\n"
"Server: UTCC-json-rpc/%s\r\n"
"\r\n"
"%s",
nStatus,
cStatus,
rfc1123Time().c_str(),
keepalive ? "keep-alive" : "close",
strMsg.size(),
FormatFullVersion().c_str(),
strMsg.c_str());
}
bool ReadHTTPRequestLine(std::basic_istream<char>& stream, int &proto,
string& http_method, string& http_uri)
{
string str;
getline(stream, str);
// HTTP request line is space-delimited
vector<string> vWords;
boost::split(vWords, str, boost::is_any_of(" "));
if (vWords.size() < 2)
return false;
// HTTP methods permitted: GET, POST
http_method = vWords[0];
if (http_method != "GET" && http_method != "POST")
return false;
// HTTP URI must be an absolute path, relative to current host
http_uri = vWords[1];
if (http_uri.size() == 0 || http_uri[0] != '/')
return false;
// parse proto, if present
string strProto = "";
if (vWords.size() > 2)
strProto = vWords[2];
proto = 0;
const char *ver = strstr(strProto.c_str(), "HTTP/1.");
if (ver != NULL)
proto = atoi(ver+7);
return true;
}
int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto)
{
string str;
getline(stream, str);
vector<string> vWords;
boost::split(vWords, str, boost::is_any_of(" "));
if (vWords.size() < 2)
return HTTP_INTERNAL_SERVER_ERROR;
proto = 0;
const char *ver = strstr(str.c_str(), "HTTP/1.");
if (ver != NULL)
proto = atoi(ver+7);
return atoi(vWords[1].c_str());
}
int ReadHTTPHeaders(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet)
{
int nLen = 0;
loop
{
string str;
std::getline(stream, str);
if (str.empty() || str == "\r")
break;
string::size_type nColon = str.find(":");
if (nColon != string::npos)
{
string strHeader = str.substr(0, nColon);
boost::trim(strHeader);
boost::to_lower(strHeader);
string strValue = str.substr(nColon+1);
boost::trim(strValue);
mapHeadersRet[strHeader] = strValue;
if (strHeader == "content-length")
nLen = atoi(strValue.c_str());
}
}
return nLen;
}
int ReadHTTPMessage(std::basic_istream<char>& stream, map<string,
string>& mapHeadersRet, string& strMessageRet,
int nProto)
{
mapHeadersRet.clear();
strMessageRet = "";
// Read header
int nLen = ReadHTTPHeaders(stream, mapHeadersRet);
if (nLen < 0 || nLen > (int)MAX_SIZE)
return HTTP_INTERNAL_SERVER_ERROR;
// Read message
if (nLen > 0)
{
vector<char> vch(nLen);
stream.read(&vch[0], nLen);
strMessageRet = string(vch.begin(), vch.end());
}
string sConHdr = mapHeadersRet["connection"];
if ((sConHdr != "close") && (sConHdr != "keep-alive"))
{
if (nProto >= 1)
mapHeadersRet["connection"] = "keep-alive";
else
mapHeadersRet["connection"] = "close";
}
return HTTP_OK;
}
bool HTTPAuthorized(map<string, string>& mapHeaders)
{
string strAuth = mapHeaders["authorization"];
if (strAuth.substr(0,6) != "Basic ")
return false;
string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);
string strUserPass = DecodeBase64(strUserPass64);
return strUserPass == strRPCUserColonPass;
}
//
// JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility,
// but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
// unspecified (HTTP errors and contents of 'error').
//
// 1.0 spec: http://json-rpc.org/wiki/specification
// 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http
// http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx
//
string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)
{
Object request;
request.push_back(Pair("method", strMethod));
request.push_back(Pair("params", params));
request.push_back(Pair("id", id));
return write_string(Value(request), false) + "\n";
}
Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id)
{
Object reply;
if (error.type() != null_type)
reply.push_back(Pair("result", Value::null));
else
reply.push_back(Pair("result", result));
reply.push_back(Pair("error", error));
reply.push_back(Pair("id", id));
return reply;
}
string JSONRPCReply(const Value& result, const Value& error, const Value& id)
{
Object reply = JSONRPCReplyObj(result, error, id);
return write_string(Value(reply), false) + "\n";
}
void ErrorReply(std::ostream& stream, const Object& objError, const Value& id)
{
// Send error reply from json-rpc error object
int nStatus = HTTP_INTERNAL_SERVER_ERROR;
int code = find_value(objError, "code").get_int();
if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST;
else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND;
string strReply = JSONRPCReply(Value::null, objError, id);
stream << HTTPReply(nStatus, strReply, false) << std::flush;
}
bool ClientAllowed(const boost::asio::ip::address& address)
{
// Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses
if (address.is_v6()
&& (address.to_v6().is_v4_compatible()
|| address.to_v6().is_v4_mapped()))
return ClientAllowed(address.to_v6().to_v4());
if (address == asio::ip::address_v4::loopback()
|| address == asio::ip::address_v6::loopback()
|| (address.is_v4()
// Check whether IPv4 addresses match 127.0.0.0/8 (loopback subnet)
&& (address.to_v4().to_ulong() & 0xff000000) == 0x7f000000))
return true;
const string strAddress = address.to_string();
const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
BOOST_FOREACH(string strAllow, vAllow)
if (WildcardMatch(strAddress, strAllow))
return true;
return false;
}
//
// IOStream device that speaks SSL but can also speak non-SSL
//
template <typename Protocol>
class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> {
public:
SSLIOStreamDevice(asio::ssl::stream<typename Protocol::socket> &streamIn, bool fUseSSLIn) : stream(streamIn)
{
fUseSSL = fUseSSLIn;
fNeedHandshake = fUseSSLIn;
}
void handshake(ssl::stream_base::handshake_type role)
{
if (!fNeedHandshake) return;
fNeedHandshake = false;
stream.handshake(role);
}
std::streamsize read(char* s, std::streamsize n)
{
handshake(ssl::stream_base::server); // HTTPS servers read first
if (fUseSSL) return stream.read_some(asio::buffer(s, n));
return stream.next_layer().read_some(asio::buffer(s, n));
}
std::streamsize write(const char* s, std::streamsize n)
{
handshake(ssl::stream_base::client); // HTTPS clients write first
if (fUseSSL) return asio::write(stream, asio::buffer(s, n));
return asio::write(stream.next_layer(), asio::buffer(s, n));
}
bool connect(const std::string& server, const std::string& port)
{
ip::tcp::resolver resolver(stream.get_io_service());
ip::tcp::resolver::query query(server.c_str(), port.c_str());
ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
ip::tcp::resolver::iterator end;
boost::system::error_code error = asio::error::host_not_found;
while (error && endpoint_iterator != end)
{
stream.lowest_layer().close();
stream.lowest_layer().connect(*endpoint_iterator++, error);
}
if (error)
return false;
return true;
}
private:
bool fNeedHandshake;
bool fUseSSL;
asio::ssl::stream<typename Protocol::socket>& stream;
};
class AcceptedConnection
{
public:
virtual ~AcceptedConnection() {}
virtual std::iostream& stream() = 0;
virtual std::string peer_address_to_string() const = 0;
virtual void close() = 0;
};
template <typename Protocol>
class AcceptedConnectionImpl : public AcceptedConnection
{
public:
AcceptedConnectionImpl(
asio::io_service& io_service,
ssl::context &context,
bool fUseSSL) :
sslStream(io_service, context),
_d(sslStream, fUseSSL),
_stream(_d)
{
}
virtual std::iostream& stream()
{
return _stream;
}
virtual std::string peer_address_to_string() const
{
return peer.address().to_string();
}
virtual void close()
{
_stream.close();
}
typename Protocol::endpoint peer;
asio::ssl::stream<typename Protocol::socket> sslStream;
private:
SSLIOStreamDevice<Protocol> _d;
iostreams::stream< SSLIOStreamDevice<Protocol> > _stream;
};
void ServiceConnection(AcceptedConnection *conn);
// Forward declaration required for RPCListen
template <typename Protocol, typename SocketAcceptorService>
static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
bool fUseSSL,
AcceptedConnection* conn,
const boost::system::error_code& error);
/**
* Sets up I/O resources to accept and handle a new connection.
*/
template <typename Protocol, typename SocketAcceptorService>
static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
const bool fUseSSL)
{
// Accept connection
AcceptedConnectionImpl<Protocol>* conn = new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL);
acceptor->async_accept(
conn->sslStream.lowest_layer(),
conn->peer,
boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>,
acceptor,
boost::ref(context),
fUseSSL,
conn,
boost::asio::placeholders::error));
}
/**
* Accept and handle incoming connection.
*/
template <typename Protocol, typename SocketAcceptorService>
static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
const bool fUseSSL,
AcceptedConnection* conn,
const boost::system::error_code& error)
{
// Immediately start accepting new connections, except when we're cancelled or our socket is closed.
if (error != asio::error::operation_aborted && acceptor->is_open())
RPCListen(acceptor, context, fUseSSL);
AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn);
// TODO: Actually handle errors
if (error)
{
delete conn;
}
// Restrict callers by IP. It is important to
// do this before starting client thread, to filter out
// certain DoS and misbehaving clients.
else if (tcp_conn && !ClientAllowed(tcp_conn->peer.address()))
{
// Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake.
if (!fUseSSL)
conn->stream() << HTTPReply(HTTP_FORBIDDEN, "", false) << std::flush;
delete conn;
}
else {
ServiceConnection(conn);
conn->close();
delete conn;
}
}
void StartRPCThreads()
{
// getwork/getblocktemplate mining rewards paid here:
pMiningKey = new CReserveKey(pwalletMain);
strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"];
if ((mapArgs["-rpcpassword"] == "") ||
(mapArgs["-rpcuser"] == mapArgs["-rpcpassword"]))
{
unsigned char rand_pwd[32];
RAND_bytes(rand_pwd, 32);
string strWhatAmI = "To use UTCCd";
if (mapArgs.count("-server"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
else if (mapArgs.count("-daemon"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\"");
uiInterface.ThreadSafeMessageBox(strprintf(
_("%s, you must set a rpcpassword in the configuration file:\n"
"%s\n"
"It is recommended you use the following random password:\n"
"rpcuser=UTCCrpc\n"
"rpcpassword=%s\n"
"(you do not need to remember this password)\n"
"The username and password MUST NOT be the same.\n"
"If the file does not exist, create it with owner-readable-only file permissions.\n"
"It is also recommended to set alertnotify so you are notified of problems;\n"
"for example: alertnotify=echo %%s | mail -s \"UTCC Alert\" admin@foo.com\n"),
strWhatAmI.c_str(),
GetConfigFile().string().c_str(),
EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32).c_str()),
"", CClientUIInterface::MSG_ERROR);
StartShutdown();
return;
}
assert(rpc_io_service == NULL);
rpc_io_service = new asio::io_service();
rpc_ssl_context = new ssl::context(*rpc_io_service, ssl::context::sslv23);
const bool fUseSSL = GetBoolArg("-rpcssl");
if (fUseSSL)
{
rpc_ssl_context->set_options(ssl::context::no_sslv2);
filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert"));
if (!pathCertFile.is_complete()) pathCertFile = filesystem::path(GetDataDir()) / pathCertFile;
if (filesystem::exists(pathCertFile)) rpc_ssl_context->use_certificate_chain_file(pathCertFile.string());
else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string().c_str());
filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem"));
if (!pathPKFile.is_complete()) pathPKFile = filesystem::path(GetDataDir()) / pathPKFile;
if (filesystem::exists(pathPKFile)) rpc_ssl_context->use_private_key_file(pathPKFile.string(), ssl::context::pem);
else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string().c_str());
string strCiphers = GetArg("-rpcsslciphers", "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH");
SSL_CTX_set_cipher_list(rpc_ssl_context->impl(), strCiphers.c_str());
}
// Try a dual IPv6/IPv4 socket, falling back to separate IPv4 and IPv6 sockets
const bool loopback = !mapArgs.count("-rpcallowip");
asio::ip::address bindAddress = loopback ? asio::ip::address_v6::loopback() : asio::ip::address_v6::any();
ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", GetDefaultRPCPort()));
boost::system::error_code v6_only_error;
boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(*rpc_io_service));
bool fListening = false;
std::string strerr;
try
{
acceptor->open(endpoint.protocol());
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
// Try making the socket dual IPv6/IPv4 (if listening on the "any" address)
acceptor->set_option(boost::asio::ip::v6_only(loopback), v6_only_error);
acceptor->bind(endpoint);
acceptor->listen(socket_base::max_connections);
RPCListen(acceptor, *rpc_ssl_context, fUseSSL);
fListening = true;
}
catch(boost::system::system_error &e)
{
strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s"), endpoint.port(), e.what());
}
try {
// If dual IPv6/IPv4 failed (or we're opening loopback interfaces only), open IPv4 separately
if (!fListening || loopback || v6_only_error)
{
bindAddress = loopback ? asio::ip::address_v4::loopback() : asio::ip::address_v4::any();
endpoint.address(bindAddress);
acceptor.reset(new ip::tcp::acceptor(*rpc_io_service));
acceptor->open(endpoint.protocol());
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
acceptor->bind(endpoint);
acceptor->listen(socket_base::max_connections);
RPCListen(acceptor, *rpc_ssl_context, fUseSSL);
fListening = true;
}
}
catch(boost::system::system_error &e)
{
strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv4: %s"), endpoint.port(), e.what());
}
if (!fListening) {
uiInterface.ThreadSafeMessageBox(strerr, "", CClientUIInterface::MSG_ERROR);
StartShutdown();
return;
}
rpc_worker_group = new boost::thread_group();
for (int i = 0; i < GetArg("-rpcthreads", 4); i++)
rpc_worker_group->create_thread(boost::bind(&asio::io_service::run, rpc_io_service));
}
void StopRPCThreads()
{
delete pMiningKey; pMiningKey = NULL;
if (rpc_io_service == NULL) return;
rpc_io_service->stop();
rpc_worker_group->join_all();
delete rpc_worker_group; rpc_worker_group = NULL;
delete rpc_ssl_context; rpc_ssl_context = NULL;
delete rpc_io_service; rpc_io_service = NULL;
}
class JSONRequest
{
public:
Value id;
string strMethod;
Array params;
JSONRequest() { id = Value::null; }
void parse(const Value& valRequest);
};
void JSONRequest::parse(const Value& valRequest)
{
// Parse request
if (valRequest.type() != obj_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
const Object& request = valRequest.get_obj();
// Parse id now so errors from here on will have the id
id = find_value(request, "id");
// Parse method
Value valMethod = find_value(request, "method");
if (valMethod.type() == null_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method");
if (valMethod.type() != str_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
strMethod = valMethod.get_str();
if (strMethod != "getwork" && strMethod != "getwork2" && strMethod != "getblocktemplate")
printf("ThreadRPCServer method=%s\n", strMethod.c_str());
// Parse params
Value valParams = find_value(request, "params");
if (valParams.type() == array_type)
params = valParams.get_array();
else if (valParams.type() == null_type)
params = Array();
else
throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array");
}
static Object JSONRPCExecOne(const Value& req)
{
Object rpc_result;
JSONRequest jreq;
try {
jreq.parse(req);
Value result = tableRPC.execute(jreq.strMethod, jreq.params);
rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id);
}
catch (Object& objError)
{
rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id);
}
catch (std::exception& e)
{
rpc_result = JSONRPCReplyObj(Value::null,
JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
}
return rpc_result;
}
static string JSONRPCExecBatch(const Array& vReq)
{
Array ret;
for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++)
ret.push_back(JSONRPCExecOne(vReq[reqIdx]));
return write_string(Value(ret), false) + "\n";
}
void ServiceConnection(AcceptedConnection *conn)
{
bool fRun = true;
while (fRun)
{
int nProto = 0;
map<string, string> mapHeaders;
string strRequest, strMethod, strURI;
// Read HTTP request line
if (!ReadHTTPRequestLine(conn->stream(), nProto, strMethod, strURI))
break;
// Read HTTP message headers and body
ReadHTTPMessage(conn->stream(), mapHeaders, strRequest, nProto);
if (strURI != "/") {
conn->stream() << HTTPReply(HTTP_NOT_FOUND, "", false) << std::flush;
break;
}
// Check authorization
if (mapHeaders.count("authorization") == 0)
{
conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
break;
}
if (!HTTPAuthorized(mapHeaders))
{
printf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string().c_str());
/* Deter brute-forcing short passwords.
If this results in a DOS the user really
shouldn't have their RPC port exposed.*/
if (mapArgs["-rpcpassword"].size() < 20)
MilliSleep(250);
conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
break;
}
if (mapHeaders["connection"] == "close")
fRun = false;
JSONRequest jreq;
try
{
// Parse request
Value valRequest;
if (!read_string(strRequest, valRequest))
throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
string strReply;
// singleton request
if (valRequest.type() == obj_type) {
jreq.parse(valRequest);
Value result = tableRPC.execute(jreq.strMethod, jreq.params);
// Send reply
strReply = JSONRPCReply(result, Value::null, jreq.id);
// array of requests
} else if (valRequest.type() == array_type)
strReply = JSONRPCExecBatch(valRequest.get_array());
else
throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
conn->stream() << HTTPReply(HTTP_OK, strReply, fRun) << std::flush;
}
catch (Object& objError)
{
ErrorReply(conn->stream(), objError, jreq.id);
break;
}
catch (std::exception& e)
{
ErrorReply(conn->stream(), JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
break;
}
}
}
json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array ¶ms) const
{
// Find method
const CRPCCommand *pcmd = tableRPC[strMethod];
if (!pcmd)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found");
// Observe safe mode
string strWarning = GetWarnings("rpc");
if (strWarning != "" && !GetBoolArg("-disablesafemode") &&
!pcmd->okSafeMode)
throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning);
try
{
// Execute
Value result;
{
if (pcmd->threadSafe)
result = pcmd->actor(params, false);
else {
LOCK2(cs_main, pwalletMain->cs_wallet);
result = pcmd->actor(params, false);
}
}
return result;
}
catch (std::exception& e)
{
throw JSONRPCError(RPC_MISC_ERROR, e.what());
}
}
Object CallRPC(const string& strMethod, const Array& params)
{
if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
throw runtime_error(strprintf(
_("You must set rpcpassword=<password> in the configuration file:\n%s\n"
"If the file does not exist, create it with owner-readable-only file permissions."),
GetConfigFile().string().c_str()));
// Connect to localhost
bool fUseSSL = GetBoolArg("-rpcssl");
asio::io_service io_service;
ssl::context context(io_service, ssl::context::sslv23);
context.set_options(ssl::context::no_sslv2);
asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context);
SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL);
iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d);
if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(GetDefaultRPCPort()))))
throw runtime_error("couldn't connect to server");
// HTTP basic authentication
string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
map<string, string> mapRequestHeaders;
mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;
// Send request
string strRequest = JSONRPCRequest(strMethod, params, 1);
string strPost = HTTPPost(strRequest, mapRequestHeaders);
stream << strPost << std::flush;
// Receive HTTP reply status
int nProto = 0;
int nStatus = ReadHTTPStatus(stream, nProto);
// Receive HTTP reply message headers and body
map<string, string> mapHeaders;
string strReply;
ReadHTTPMessage(stream, mapHeaders, strReply, nProto);
if (nStatus == HTTP_UNAUTHORIZED)
throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR)
throw runtime_error(strprintf("server returned HTTP error %d", nStatus));
else if (strReply.empty())
throw runtime_error("no response from server");
// Parse reply
Value valReply;
if (!read_string(strReply, valReply))
throw runtime_error("couldn't parse reply from server");
const Object& reply = valReply.get_obj();
if (reply.empty())
throw runtime_error("expected reply to have result, error and id properties");
return reply;
}
template<typename T>
void ConvertTo(Value& value, bool fAllowNull=false)
{
if (fAllowNull && value.type() == null_type)
return;
if (value.type() == str_type)
{
// reinterpret string as unquoted json value
Value value2;
string strJSON = value.get_str();
if (!read_string(strJSON, value2))
throw runtime_error(string("Error parsing JSON:")+strJSON);
ConvertTo<T>(value2, fAllowNull);
value = value2;
}
else
{
value = value.get_value<T>();
}
}
// Convert strings to command-specific RPC representation
Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams)
{
Array params;
BOOST_FOREACH(const std::string ¶m, strParams)
params.push_back(param);
int n = params.size();
//
// Special case non-string parameter types
//
if (strMethod == "stop" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "getaddednodeinfo" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "setgenerate" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "setgenerate" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]);
if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]);
if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "getbalance" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getblockhash" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]);
if (strMethod == "move" && n > 3) ConvertTo<boost::int64_t>(params[3]);
if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]);
if (strMethod == "sendfrom" && n > 3) ConvertTo<boost::int64_t>(params[3]);
if (strMethod == "listtransactions" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listtransactions" && n > 2) ConvertTo<boost::int64_t>(params[2]);
if (strMethod == "listaccounts" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "walletpassphrase" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getblocktemplate" && n > 0) ConvertTo<Object>(params[0]);
if (strMethod == "listsinceblock" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "sendmany" && n > 1) ConvertTo<Object>(params[1]);
if (strMethod == "sendmany" && n > 2) ConvertTo<boost::int64_t>(params[2]);
if (strMethod == "addmultisigaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "addmultisigaddress" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "createmultisig" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "createmultisig" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "listunspent" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listunspent" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listunspent" && n > 2) ConvertTo<Array>(params[2]);
if (strMethod == "getrawtransaction" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "createrawtransaction" && n > 0) ConvertTo<Array>(params[0]);
if (strMethod == "createrawtransaction" && n > 1) ConvertTo<Object>(params[1]);
if (strMethod == "signrawtransaction" && n > 1) ConvertTo<Array>(params[1], true);
if (strMethod == "signrawtransaction" && n > 2) ConvertTo<Array>(params[2], true);
if (strMethod == "gettxout" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "gettxout" && n > 2) ConvertTo<bool>(params[2]);
if (strMethod == "lockunspent" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "lockunspent" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "importprivkey" && n > 2) ConvertTo<bool>(params[2]);
if (strMethod == "sendalert" && n > 2) ConvertTo<boost::int64_t>(params[2]);
if (strMethod == "sendalert" && n > 3) ConvertTo<boost::int64_t>(params[3]);
if (strMethod == "sendalert" && n > 4) ConvertTo<boost::int64_t>(params[4]);
if (strMethod == "sendalert" && n > 5) ConvertTo<boost::int64_t>(params[5]);
if (strMethod == "sendalert" && n > 6) ConvertTo<boost::int64_t>(params[6]);
if (strMethod == "enforcecheckpoint" && n > 0) ConvertTo<bool>(params[0]);
return params;
}
int CommandLineRPC(int argc, char *argv[])
{
string strPrint;
int nRet = 0;
try
{
// Skip switches
while (argc > 1 && IsSwitchChar(argv[1][0]))
{
argc--;
argv++;
}
// Method
if (argc < 2)
throw runtime_error("too few parameters");
string strMethod = argv[1];
// Parameters default to strings
std::vector<std::string> strParams(&argv[2], &argv[argc]);
Array params = RPCConvertValues(strMethod, strParams);
// Execute
Object reply = CallRPC(strMethod, params);
// Parse reply
const Value& result = find_value(reply, "result");
const Value& error = find_value(reply, "error");
if (error.type() != null_type)
{
// Error
strPrint = "error: " + write_string(error, false);
int code = find_value(error.get_obj(), "code").get_int();
nRet = abs(code);
}
else
{
// Result
if (result.type() == null_type)
strPrint = "";
else if (result.type() == str_type)
strPrint = result.get_str();
else
strPrint = write_string(result, true);
}
}
catch (boost::thread_interrupted) {
throw;
}
catch (std::exception& e) {
strPrint = string("error: ") + e.what();
nRet = 87;
}
catch (...) {
PrintException(NULL, "CommandLineRPC()");
}
if (strPrint != "")
{
fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
}
return nRet;
}
#ifdef TEST
int main(int argc, char *argv[])
{
#ifdef _MSC_VER
// Turn off Microsoft heap dump noise
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
#endif
setbuf(stdin, NULL);
setbuf(stdout, NULL);
setbuf(stderr, NULL);
try
{
if (argc >= 2 && string(argv[1]) == "-server")
{
printf("server ready\n");
ThreadRPCServer(NULL);
}
else
{
return CommandLineRPC(argc, argv);
}
}
catch (boost::thread_interrupted) {
throw;
}
catch (std::exception& e) {
PrintException(&e, "main()");
} catch (...) {
PrintException(NULL, "main()");
}
return 0;
}
#endif
const CRPCTable tableRPC;
|
// Copyright (c) 2011-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "guiutil.h"
#include "bitcoinaddressvalidator.h"
#include "bitcoinunits.h"
#include "qvalidatedlineedit.h"
#include "walletmodel.h"
#include "primitives/transaction.h"
#include "cashaddr.h"
#include "config.h"
#include "dstencode.h"
#include "init.h"
#include "main.h" // For minRelayTxFee
#include "protocol.h"
#include "script/script.h"
#include "script/standard.h"
#include "util.h"
#include "utilstrencodings.h"
#ifdef WIN32
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include "shellapi.h"
#include "shlobj.h"
#include "shlwapi.h"
#endif
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#if BOOST_FILESYSTEM_VERSION >= 3
#include <boost/filesystem/detail/utf8_codecvt_facet.hpp>
#endif
#include <boost/scoped_array.hpp>
#include <QAbstractItemView>
#include <QApplication>
#include <QClipboard>
#include <QDateTime>
#include <QDesktopServices>
#include <QDesktopWidget>
#include <QDoubleValidator>
#include <QFileDialog>
#include <QFont>
#include <QLineEdit>
#include <QSettings>
#include <QTextDocument> // for Qt::mightBeRichText
#include <QThread>
#if QT_VERSION < 0x050000
#include <QUrl>
#else
#include <QUrlQuery>
#endif
#if QT_VERSION >= 0x50200
#include <QFontDatabase>
#endif
#if BOOST_FILESYSTEM_VERSION >= 3
static boost::filesystem::detail::utf8_codecvt_facet utf8;
#endif
#if defined(Q_OS_MAC)
#include <QProcess>
extern double NSAppKitVersionNumber;
#if !defined(NSAppKitVersionNumber10_8)
#define NSAppKitVersionNumber10_8 1187
#endif
#if !defined(NSAppKitVersionNumber10_9)
#define NSAppKitVersionNumber10_9 1265
#endif
void ForceActivation();
#endif
namespace GUIUtil {
QString dateTimeStr(const QDateTime &date)
{
return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm");
}
QString dateTimeStr(qint64 nTime)
{
return dateTimeStr(QDateTime::fromTime_t((qint32)nTime));
}
QFont fixedPitchFont()
{
#if QT_VERSION >= 0x50200
return QFontDatabase::systemFont(QFontDatabase::FixedFont);
#else
QFont font("Monospace");
#if QT_VERSION >= 0x040800
font.setStyleHint(QFont::Monospace);
#else
font.setStyleHint(QFont::TypeWriter);
#endif
return font;
#endif
}
static std::string MakeAddrInvalid(std::string addr)
{
if (addr.size() < 2)
{
return "";
}
// Checksum is at the end of the address. Swapping chars to make it invalid.
std::swap(addr[addr.size() - 1], addr[addr.size() - 2]);
if (!IsValidDestinationString(addr))
{
return addr;
}
return "";
}
std::string DummyAddress(const CChainParams ¶ms, const Config &cfg)
{
// Just some dummy data to generate an convincing random-looking (but
// consistent) address
static const std::vector<uint8_t> dummydata = {0xeb, 0x15, 0x23, 0x1d, 0xfc, 0xeb, 0x60, 0x92, 0x58, 0x86, 0xb6,
0x7d, 0x06, 0x52, 0x99, 0x92, 0x59, 0x15, 0xae, 0xb1};
const CTxDestination dstKey = CKeyID(uint160(dummydata));
return MakeAddrInvalid(EncodeDestination(dstKey, params, cfg));
}
void setupAddressWidget(QValidatedLineEdit *widget, QWidget *parent)
{
parent->setFocusProxy(widget);
widget->setFont(fixedPitchFont());
const CChainParams ¶ms = Params();
#if QT_VERSION >= 0x040700
// We don't want translators to use own addresses in translations
// and this is the only place, where this address is supplied.
widget->setPlaceholderText(QObject::tr("Enter a Bitcoin address (e.g. %1)")
.arg(QString::fromStdString(DummyAddress(params, GetConfig()))));
#endif
widget->setValidator(new BitcoinAddressEntryValidator(params.CashAddrPrefix(), parent));
widget->setCheckValidator(new BitcoinAddressCheckValidator(parent));
}
void setupAmountWidget(QLineEdit *widget, QWidget *parent)
{
QDoubleValidator *amountValidator = new QDoubleValidator(parent);
amountValidator->setDecimals(8);
amountValidator->setBottom(0.0);
widget->setValidator(amountValidator);
widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
}
QString bitcoinURIScheme(const CChainParams ¶ms, bool useCashAddr)
{
if (!useCashAddr)
{
return "igocoin";
}
return QString::fromStdString(params.CashAddrPrefix());
}
QString bitcoinURIScheme(const Config &cfg)
{
return bitcoinURIScheme(cfg.GetChainParams(), cfg.UseCashAddrEncoding());
}
static bool IsCashAddrEncoded(const QUrl &uri)
{
const std::string addr = (uri.scheme() + ":" + uri.path()).toStdString();
auto decoded = cashaddr::Decode(addr, "");
return !decoded.first.empty();
}
bool parseBitcoinURI(const QString &scheme, const QUrl &uri, SendCoinsRecipient *out)
{
// return if URI has wrong scheme.
if (!uri.isValid() || uri.scheme() != scheme)
{
return false;
}
SendCoinsRecipient rv;
if (IsCashAddrEncoded(uri))
{
rv.address = uri.scheme() + ":" + uri.path();
}
else
{
// strip out uri scheme for base58 encoded addresses
rv.address = uri.path();
}
// Trim any following forward slash which may have been added by the OS
if (rv.address.endsWith("/"))
{
rv.address.truncate(rv.address.length() - 1);
}
rv.amount = 0;
#if QT_VERSION < 0x050000
QList<QPair<QString, QString> > items = uri.queryItems();
#else
QUrlQuery uriQuery(uri);
QList<QPair<QString, QString> > items = uriQuery.queryItems();
#endif
for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++)
{
bool fShouldReturnFalse = false;
if (i->first.startsWith("req-"))
{
i->first.remove(0, 4);
fShouldReturnFalse = true;
}
if (i->first == "label")
{
rv.label = i->second;
fShouldReturnFalse = false;
}
if (i->first == "message")
{
rv.message = i->second;
fShouldReturnFalse = false;
}
else if (i->first == "amount")
{
if (!i->second.isEmpty())
{
if (!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount))
{
return false;
}
}
fShouldReturnFalse = false;
}
if (fShouldReturnFalse)
return false;
}
if (out)
{
*out = rv;
}
return true;
}
bool parseBitcoinURI(const QString &scheme, QString uri, SendCoinsRecipient *out)
{
//
// Cannot handle this later, because igocoin://
// will cause Qt to see the part after // as host,
// which will lower-case it (and thus invalidate the address).
if (uri.startsWith(scheme + "://", Qt::CaseInsensitive))
{
uri.replace(0, scheme.length() + 3, scheme + ":");
}
QUrl uriInstance(uri);
return parseBitcoinURI(scheme, uriInstance, out);
}
QString formatBitcoinURI(const Config &cfg, const SendCoinsRecipient &info)
{
QString ret = info.address;
if (!cfg.UseCashAddrEncoding())
{
// prefix address with uri scheme for base58 encoded addresses.
ret = (bitcoinURIScheme(cfg) + ":%1").arg(ret);
}
int paramCount = 0;
if (info.amount)
{
ret += QString("?amount=%1").arg(BitcoinUnits::format(BitcoinUnits::BTC, info.amount, false, BitcoinUnits::separatorNever));
paramCount++;
}
if (!info.label.isEmpty())
{
QString lbl(QUrl::toPercentEncoding(info.label));
ret += QString("%1label=%2").arg(paramCount == 0 ? "?" : "&").arg(lbl);
paramCount++;
}
if (!info.message.isEmpty())
{
QString msg(QUrl::toPercentEncoding(info.message));
ret += QString("%1message=%2").arg(paramCount == 0 ? "?" : "&").arg(msg);
paramCount++;
}
return ret;
}
bool isDust(const QString& address, const CAmount& amount)
{
CTxDestination dest = DecodeDestination(address.toStdString());
CScript script = GetScriptForDestination(dest);
CTxOut txOut(amount, script);
return txOut.IsDust(::minRelayTxFee);
}
QString HtmlEscape(const QString& str, bool fMultiLine)
{
#if QT_VERSION < 0x050000
QString escaped = Qt::escape(str);
#else
QString escaped = str.toHtmlEscaped();
#endif
if(fMultiLine)
{
escaped = escaped.replace("\n", "<br>\n");
}
return escaped;
}
QString HtmlEscape(const std::string& str, bool fMultiLine)
{
return HtmlEscape(QString::fromStdString(str), fMultiLine);
}
void copyEntryData(QAbstractItemView *view, int column, int role)
{
if(!view || !view->selectionModel())
return;
QModelIndexList selection = view->selectionModel()->selectedRows(column);
if(!selection.isEmpty())
{
// Copy first item
setClipboard(selection.at(0).data(role).toString());
}
}
QVariant getEntryData(QAbstractItemView *view, int column, int role)
{
if(!view || !view->selectionModel())
return QVariant();
QModelIndexList selection = view->selectionModel()->selectedRows(column);
if(!selection.isEmpty()) {
// Return first item
return (selection.at(0).data(role));
}
return QVariant();
}
QString getSaveFileName(QWidget *parent, const QString &caption, const QString &dir,
const QString &filter,
QString *selectedSuffixOut)
{
QString selectedFilter;
QString myDir;
if(dir.isEmpty()) // Default to user documents location
{
#if QT_VERSION < 0x050000
myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
#else
myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
#endif
}
else
{
myDir = dir;
}
/* Directly convert path to native OS path separators */
QString result = QDir::toNativeSeparators(QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter));
/* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
QString selectedSuffix;
if(filter_re.exactMatch(selectedFilter))
{
selectedSuffix = filter_re.cap(1);
}
/* Add suffix if needed */
QFileInfo info(result);
if(!result.isEmpty())
{
if(info.suffix().isEmpty() && !selectedSuffix.isEmpty())
{
/* No suffix specified, add selected suffix */
if(!result.endsWith("."))
result.append(".");
result.append(selectedSuffix);
}
}
/* Return selected suffix if asked to */
if(selectedSuffixOut)
{
*selectedSuffixOut = selectedSuffix;
}
return result;
}
QString getOpenFileName(QWidget *parent, const QString &caption, const QString &dir,
const QString &filter,
QString *selectedSuffixOut)
{
QString selectedFilter;
QString myDir;
if(dir.isEmpty()) // Default to user documents location
{
#if QT_VERSION < 0x050000
myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
#else
myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
#endif
}
else
{
myDir = dir;
}
/* Directly convert path to native OS path separators */
QString result = QDir::toNativeSeparators(QFileDialog::getOpenFileName(parent, caption, myDir, filter, &selectedFilter));
if(selectedSuffixOut)
{
/* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
QString selectedSuffix;
if(filter_re.exactMatch(selectedFilter))
{
selectedSuffix = filter_re.cap(1);
}
*selectedSuffixOut = selectedSuffix;
}
return result;
}
Qt::ConnectionType blockingGUIThreadConnection()
{
if(QThread::currentThread() != qApp->thread())
{
return Qt::BlockingQueuedConnection;
}
else
{
return Qt::DirectConnection;
}
}
bool checkPoint(const QPoint &p, const QWidget *w)
{
QWidget *atW = QApplication::widgetAt(w->mapToGlobal(p));
if (!atW) return false;
return atW->topLevelWidget() == w;
}
bool isObscured(QWidget *w)
{
return !(checkPoint(QPoint(0, 0), w)
&& checkPoint(QPoint(w->width() - 1, 0), w)
&& checkPoint(QPoint(0, w->height() - 1), w)
&& checkPoint(QPoint(w->width() - 1, w->height() - 1), w)
&& checkPoint(QPoint(w->width() / 2, w->height() / 2), w));
}
void openDebugLogfile()
{
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
/* Open debug.log with the associated application */
if (boost::filesystem::exists(pathDebug))
QDesktopServices::openUrl(QUrl::fromLocalFile(boostPathToQString(pathDebug)));
}
bool openBitcoinConf()
{
boost::filesystem::path pathConfig = GetConfigFile();
/* Create the file */
boost::filesystem::ofstream configFile(pathConfig, std::ios_base::app);
if (!configFile.good())
return false;
configFile.close();
/* Open bitcoin.conf with the associated application */
return QDesktopServices::openUrl(QUrl::fromLocalFile(boostPathToQString(pathConfig)));
}
void SubstituteFonts(const QString& language)
{
#if defined(Q_OS_MAC)
// Background:
// OSX's default font changed in 10.9 and Qt is unable to find it with its
// usual fallback methods when building against the 10.7 sdk or lower.
// The 10.8 SDK added a function to let it find the correct fallback font.
// If this fallback is not properly loaded, some characters may fail to
// render correctly.
//
// The same thing happened with 10.10. .Helvetica Neue DeskInterface is now default.
//
// Solution: If building with the 10.7 SDK or lower and the user's platform
// is 10.9 or higher at runtime, substitute the correct font. This needs to
// happen before the QApplication is created.
#if defined(MAC_OS_X_VERSION_MAX_ALLOWED) && MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_8
if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_8)
{
if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_9)
/* On a 10.9 - 10.9.x system */
QFont::insertSubstitution(".Lucida Grande UI", "Lucida Grande");
else
{
/* 10.10 or later system */
if (language == "zh_CN" || language == "zh_TW" || language == "zh_HK") // traditional or simplified Chinese
QFont::insertSubstitution(".Helvetica Neue DeskInterface", "Heiti SC");
else if (language == "ja") // Japanesee
QFont::insertSubstitution(".Helvetica Neue DeskInterface", "Songti SC");
else
QFont::insertSubstitution(".Helvetica Neue DeskInterface", "Lucida Grande");
}
}
#endif
#endif
}
ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) :
QObject(parent),
size_threshold(size_threshold)
{
}
bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt)
{
if(evt->type() == QEvent::ToolTipChange)
{
QWidget *widget = static_cast<QWidget*>(obj);
QString tooltip = widget->toolTip();
if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt") && !Qt::mightBeRichText(tooltip))
{
// Envelop with <qt></qt> to make sure Qt detects this as rich text
// Escape the current message as HTML and replace \n by <br>
tooltip = "<qt>" + HtmlEscape(tooltip, true) + "</qt>";
widget->setToolTip(tooltip);
return true;
}
}
return QObject::eventFilter(obj, evt);
}
void TableViewLastColumnResizingFixer::connectViewHeadersSignals()
{
connect(tableView->horizontalHeader(), SIGNAL(sectionResized(int,int,int)), this, SLOT(on_sectionResized(int,int,int)));
connect(tableView->horizontalHeader(), SIGNAL(geometriesChanged()), this, SLOT(on_geometriesChanged()));
}
// We need to disconnect these while handling the resize events, otherwise we can enter infinite loops.
void TableViewLastColumnResizingFixer::disconnectViewHeadersSignals()
{
disconnect(tableView->horizontalHeader(), SIGNAL(sectionResized(int,int,int)), this, SLOT(on_sectionResized(int,int,int)));
disconnect(tableView->horizontalHeader(), SIGNAL(geometriesChanged()), this, SLOT(on_geometriesChanged()));
}
// Setup the resize mode, handles compatibility for Qt5 and below as the method signatures changed.
// Refactored here for readability.
void TableViewLastColumnResizingFixer::setViewHeaderResizeMode(int logicalIndex, QHeaderView::ResizeMode resizeMode)
{
#if QT_VERSION < 0x050000
tableView->horizontalHeader()->setResizeMode(logicalIndex, resizeMode);
#else
tableView->horizontalHeader()->setSectionResizeMode(logicalIndex, resizeMode);
#endif
}
void TableViewLastColumnResizingFixer::resizeColumn(int nColumnIndex, int width)
{
tableView->setColumnWidth(nColumnIndex, width);
tableView->horizontalHeader()->resizeSection(nColumnIndex, width);
}
int TableViewLastColumnResizingFixer::getColumnsWidth()
{
int nColumnsWidthSum = 0;
for (int i = 0; i < columnCount; i++)
{
nColumnsWidthSum += tableView->horizontalHeader()->sectionSize(i);
}
return nColumnsWidthSum;
}
int TableViewLastColumnResizingFixer::getAvailableWidthForColumn(int column)
{
int nResult = lastColumnMinimumWidth;
int nTableWidth = tableView->horizontalHeader()->width();
if (nTableWidth > 0)
{
int nOtherColsWidth = getColumnsWidth() - tableView->horizontalHeader()->sectionSize(column);
nResult = std::max(nResult, nTableWidth - nOtherColsWidth);
}
return nResult;
}
// Make sure we don't make the columns wider than the tables viewport width.
void TableViewLastColumnResizingFixer::adjustTableColumnsWidth()
{
disconnectViewHeadersSignals();
resizeColumn(lastColumnIndex, getAvailableWidthForColumn(lastColumnIndex));
connectViewHeadersSignals();
int nTableWidth = tableView->horizontalHeader()->width();
int nColsWidth = getColumnsWidth();
if (nColsWidth > nTableWidth)
{
resizeColumn(secondToLastColumnIndex,getAvailableWidthForColumn(secondToLastColumnIndex));
}
}
// Make column use all the space available, useful during window resizing.
void TableViewLastColumnResizingFixer::stretchColumnWidth(int column)
{
disconnectViewHeadersSignals();
resizeColumn(column, getAvailableWidthForColumn(column));
connectViewHeadersSignals();
}
// When a section is resized this is a slot-proxy for ajustAmountColumnWidth().
void TableViewLastColumnResizingFixer::on_sectionResized(int logicalIndex, int oldSize, int newSize)
{
adjustTableColumnsWidth();
int remainingWidth = getAvailableWidthForColumn(logicalIndex);
if (newSize > remainingWidth)
{
resizeColumn(logicalIndex, remainingWidth);
}
}
// When the tabless geometry is ready, we manually perform the stretch of the "Message" column,
// as the "Stretch" resize mode does not allow for interactive resizing.
void TableViewLastColumnResizingFixer::on_geometriesChanged()
{
if ((getColumnsWidth() - this->tableView->horizontalHeader()->width()) != 0)
{
disconnectViewHeadersSignals();
resizeColumn(secondToLastColumnIndex, getAvailableWidthForColumn(secondToLastColumnIndex));
connectViewHeadersSignals();
}
}
/**
* Initializes all internal variables and prepares the
* the resize modes of the last 2 columns of the table and
*/
TableViewLastColumnResizingFixer::TableViewLastColumnResizingFixer(QTableView* table, int lastColMinimumWidth, int allColsMinimumWidth, QObject *parent) :
QObject(parent),
tableView(table),
lastColumnMinimumWidth(lastColMinimumWidth),
allColumnsMinimumWidth(allColsMinimumWidth)
{
columnCount = tableView->horizontalHeader()->count();
lastColumnIndex = columnCount - 1;
secondToLastColumnIndex = columnCount - 2;
tableView->horizontalHeader()->setMinimumSectionSize(allColumnsMinimumWidth);
setViewHeaderResizeMode(secondToLastColumnIndex, QHeaderView::Interactive);
setViewHeaderResizeMode(lastColumnIndex, QHeaderView::Interactive);
}
#ifdef WIN32
boost::filesystem::path static StartupShortcutPath()
{
std::string chain = ChainNameFromCommandLine();
if (chain == CBaseChainParams::MAIN)
return GetSpecialFolderPath(CSIDL_STARTUP) / "Bitcoin.lnk";
if (chain == CBaseChainParams::TESTNET) // Remove this special case when CBaseChainParams::TESTNET = "testnet4"
return GetSpecialFolderPath(CSIDL_STARTUP) / "Bitcoin (testnet).lnk";
return GetSpecialFolderPath(CSIDL_STARTUP) / strprintf("Bitcoin (%s).lnk", chain);
}
bool GetStartOnSystemStartup()
{
// check for Bitcoin*.lnk
return boost::filesystem::exists(StartupShortcutPath());
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
// If the shortcut exists already, remove it for updating
boost::filesystem::remove(StartupShortcutPath());
if (fAutoStart)
{
CoInitialize(NULL);
// Get a pointer to the IShellLink interface.
IShellLink* psl = NULL;
HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
CLSCTX_INPROC_SERVER, IID_IShellLink,
reinterpret_cast<void**>(&psl));
if (SUCCEEDED(hres))
{
// Get the current executable path
TCHAR pszExePath[MAX_PATH];
GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
// Start client minimized
QString strArgs = "-min";
// Set -testnet /-regtest options
strArgs += QString::fromStdString(strprintf(" -testnet=%d -regtest=%d", GetBoolArg("-testnet", false), GetBoolArg("-regtest", false)));
#ifdef UNICODE
boost::scoped_array<TCHAR> args(new TCHAR[strArgs.length() + 1]);
// Convert the QString to TCHAR*
strArgs.toWCharArray(args.get());
// Add missing '\0'-termination to string
args[strArgs.length()] = '\0';
#endif
// Set the path to the shortcut target
psl->SetPath(pszExePath);
PathRemoveFileSpec(pszExePath);
psl->SetWorkingDirectory(pszExePath);
psl->SetShowCmd(SW_SHOWMINNOACTIVE);
#ifndef UNICODE
psl->SetArguments(strArgs.toStdString().c_str());
#else
psl->SetArguments(args.get());
#endif
// Query IShellLink for the IPersistFile interface for
// saving the shortcut in persistent storage.
IPersistFile* ppf = NULL;
hres = psl->QueryInterface(IID_IPersistFile, reinterpret_cast<void**>(&ppf));
if (SUCCEEDED(hres))
{
WCHAR pwsz[MAX_PATH];
// Ensure that the string is ANSI.
MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH);
// Save the link by calling IPersistFile::Save.
hres = ppf->Save(pwsz, TRUE);
ppf->Release();
psl->Release();
CoUninitialize();
return true;
}
psl->Release();
}
CoUninitialize();
return false;
}
return true;
}
#elif defined(Q_OS_LINUX)
// Follow the Desktop Application Autostart Spec:
// http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
boost::filesystem::path static GetAutostartDir()
{
namespace fs = boost::filesystem;
char* pszConfigHome = getenv("XDG_CONFIG_HOME");
if (pszConfigHome) return fs::path(pszConfigHome) / "autostart";
char* pszHome = getenv("HOME");
if (pszHome) return fs::path(pszHome) / ".config" / "autostart";
return fs::path();
}
boost::filesystem::path static GetAutostartFilePath()
{
std::string chain = ChainNameFromCommandLine();
if (chain == CBaseChainParams::MAIN)
return GetAutostartDir() / "bitcoin.desktop";
return GetAutostartDir() / strprintf("bitcoin-%s.lnk", chain);
}
bool GetStartOnSystemStartup()
{
boost::filesystem::ifstream optionFile(GetAutostartFilePath());
if (!optionFile.good())
return false;
// Scan through file for "Hidden=true":
std::string line;
while (!optionFile.eof())
{
getline(optionFile, line);
if (line.find("Hidden") != std::string::npos &&
line.find("true") != std::string::npos)
return false;
}
optionFile.close();
return true;
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
if (!fAutoStart)
boost::filesystem::remove(GetAutostartFilePath());
else
{
char pszExePath[MAX_PATH+1];
memset(pszExePath, 0, sizeof(pszExePath));
if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
return false;
boost::filesystem::create_directories(GetAutostartDir());
boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc);
if (!optionFile.good())
return false;
std::string chain = ChainNameFromCommandLine();
// Write a bitcoin.desktop file to the autostart directory:
optionFile << "[Desktop Entry]\n";
optionFile << "Type=Application\n";
if (chain == CBaseChainParams::MAIN)
optionFile << "Name=Bitcoin\n";
else
optionFile << strprintf("Name=Bitcoin (%s)\n", chain);
optionFile << "Exec=" << pszExePath << strprintf(" -min -testnet=%d -regtest=%d\n", GetBoolArg("-testnet", false), GetBoolArg("-regtest", false));
optionFile << "Terminal=false\n";
optionFile << "Hidden=false\n";
optionFile.close();
}
return true;
}
#elif defined(Q_OS_MAC)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
// based on: https://github.com/Mozketo/LaunchAtLoginController/blob/master/LaunchAtLoginController.m
#include <CoreFoundation/CoreFoundation.h>
#include <CoreServices/CoreServices.h>
LSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef findUrl);
LSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef findUrl)
{
// loop through the list of startup items and try to find the bitcoin app
CFArrayRef listSnapshot = LSSharedFileListCopySnapshot(list, NULL);
if (listSnapshot == NULL) {
return nullptr;
}
// loop through the list of startup items and try to find the bitcoin app
for(int i = 0; i < CFArrayGetCount(listSnapshot); i++) {
LSSharedFileListItemRef item = (LSSharedFileListItemRef)CFArrayGetValueAtIndex(listSnapshot, i);
UInt32 resolutionFlags = kLSSharedFileListNoUserInteraction | kLSSharedFileListDoNotMountVolumes;
CFURLRef currentItemURL = NULL;
#if defined(MAC_OS_X_VERSION_MAX_ALLOWED) && MAC_OS_X_VERSION_MAX_ALLOWED >= 10100
if(&LSSharedFileListItemCopyResolvedURL)
currentItemURL = LSSharedFileListItemCopyResolvedURL(item, resolutionFlags, NULL);
#if defined(MAC_OS_X_VERSION_MIN_REQUIRED) && MAC_OS_X_VERSION_MIN_REQUIRED < 10100
else
LSSharedFileListItemResolve(item, resolutionFlags, ¤tItemURL, NULL);
#endif
#else
LSSharedFileListItemResolve(item, resolutionFlags, ¤tItemURL, NULL);
#endif
if(currentItemURL) {
if (CFEqual(currentItemURL, findUrl)) {
// found
CFRelease(listSnapshot);
CFRelease(currentItemURL);
return item;
}
CFRelease(currentItemURL);
}
}
CFRelease(listSnapshot);
return NULL;
}
bool GetStartOnSystemStartup()
{
CFURLRef bitcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle());
if (bitcoinAppUrl == nullptr) {
return false;
}
LSSharedFileListRef loginItems = LSSharedFileListCreate(nullptr, kLSSharedFileListSessionLoginItems, nullptr);
LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, bitcoinAppUrl);
CFRelease(bitcoinAppUrl);
return !!foundItem; // return boolified object
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
CFURLRef bitcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle());
if (bitcoinAppUrl == nullptr) {
return false;
}
LSSharedFileListRef loginItems = LSSharedFileListCreate(nullptr, kLSSharedFileListSessionLoginItems, nullptr);
LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, bitcoinAppUrl);
if(fAutoStart && !foundItem) {
// add bitcoin app to startup item list
LSSharedFileListInsertItemURL(loginItems, kLSSharedFileListItemBeforeFirst, NULL, NULL, bitcoinAppUrl, NULL, NULL);
}
else if(!fAutoStart && foundItem) {
// remove item
LSSharedFileListItemRemove(loginItems, foundItem);
}
CFRelease(bitcoinAppUrl);
return true;
}
#pragma GCC diagnostic pop
#else
bool GetStartOnSystemStartup() { return false; }
bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
#endif
void saveWindowGeometry(const QString& strSetting, QWidget *parent)
{
QSettings settings;
settings.setValue(strSetting + "Pos", parent->pos());
settings.setValue(strSetting + "Size", parent->size());
}
void restoreWindowGeometry(const QString& strSetting, const QSize& defaultSize, QWidget *parent)
{
QSettings settings;
QPoint pos = settings.value(strSetting + "Pos").toPoint();
QSize size = settings.value(strSetting + "Size", defaultSize).toSize();
parent->resize(size);
parent->move(pos);
if ((!pos.x() && !pos.y()) || (QApplication::desktop()->screenNumber(parent) == -1))
{
QRect screen = QApplication::desktop()->screenGeometry();
QPoint defaultPos((screen.width() - defaultSize.width()) / 2,
(screen.height() - defaultSize.height()) / 2);
parent->resize(defaultSize);
parent->move(defaultPos);
}
}
void setClipboard(const QString& str)
{
QApplication::clipboard()->setText(str, QClipboard::Clipboard);
QApplication::clipboard()->setText(str, QClipboard::Selection);
}
#if BOOST_FILESYSTEM_VERSION >= 3
boost::filesystem::path qstringToBoostPath(const QString &path)
{
return boost::filesystem::path(path.toStdString(), utf8);
}
QString boostPathToQString(const boost::filesystem::path &path)
{
return QString::fromStdString(path.string(utf8));
}
#else
#warning Conversion between boost path and QString can use invalid character encoding with boost_filesystem v2 and older
boost::filesystem::path qstringToBoostPath(const QString &path)
{
return boost::filesystem::path(path.toStdString());
}
QString boostPathToQString(const boost::filesystem::path &path)
{
return QString::fromStdString(path.string());
}
#endif
QString formatDurationStr(int secs)
{
QStringList strList;
int days = secs / 86400;
int hours = (secs % 86400) / 3600;
int mins = (secs % 3600) / 60;
int seconds = secs % 60;
if (days)
strList.append(QString(QObject::tr("%1 d")).arg(days));
if (hours)
strList.append(QString(QObject::tr("%1 h")).arg(hours));
if (mins)
strList.append(QString(QObject::tr("%1 m")).arg(mins));
if (seconds || (!days && !hours && !mins))
strList.append(QString(QObject::tr("%1 s")).arg(seconds));
return strList.join(" ");
}
QString formatServicesStr(quint64 mask)
{
QStringList strList;
// Just scan the last 8 bits for now.
for (int i = 0; i < 8; i++) {
uint64_t check = 1 << i;
if (mask & check)
{
switch (check)
{
case NODE_NETWORK:
strList.append("NETWORK");
break;
case NODE_GETUTXO:
strList.append("GETUTXO");
break;
case NODE_BLOOM:
strList.append("BLOOM");
break;
default:
strList.append(QString("%1[%2]").arg("UNKNOWN").arg(check));
}
}
}
if (strList.size())
return strList.join(" & ");
else
return QObject::tr("None");
}
QString formatPingTime(double dPingTime)
{
return dPingTime == 0 ? QObject::tr("N/A") : QString(QObject::tr("%1 ms")).arg(QString::number((int)(dPingTime * 1000), 10));
}
QString formatTimeOffset(int64_t nTimeOffset)
{
return QString(QObject::tr("%1 s")).arg(QString::number((int)nTimeOffset, 10));
}
QString formateNiceTimeOffset(qint64 secs)
{
// Represent time from last generated block in human readable text
QString timeBehindText;
const int HOUR_IN_SECONDS = 60*60;
const int DAY_IN_SECONDS = 24*60*60;
const int WEEK_IN_SECONDS = 7*24*60*60;
const int YEAR_IN_SECONDS = 31556952; // Average length of year in Gregorian calendar
if(secs < 60)
{
timeBehindText = QObject::tr("%n seconds(s)","",secs);
}
else if(secs < 2*HOUR_IN_SECONDS)
{
timeBehindText = QObject::tr("%n minutes(s)","",secs/60);
}
else if(secs < 2*DAY_IN_SECONDS)
{
timeBehindText = QObject::tr("%n hour(s)","",secs/HOUR_IN_SECONDS);
}
else if(secs < 2*WEEK_IN_SECONDS)
{
timeBehindText = QObject::tr("%n day(s)","",secs/DAY_IN_SECONDS);
}
else if(secs < YEAR_IN_SECONDS)
{
timeBehindText = QObject::tr("%n week(s)","",secs/WEEK_IN_SECONDS);
}
else
{
qint64 years = secs / YEAR_IN_SECONDS;
qint64 remainder = secs % YEAR_IN_SECONDS;
timeBehindText = QObject::tr("%1 and %2").arg(QObject::tr("%n year(s)", "", years)).arg(QObject::tr("%n week(s)","", remainder/WEEK_IN_SECONDS));
}
return timeBehindText;
}
} // namespace GUIUtil
|
/*******************************<GINKGO LICENSE>******************************
Copyright (c) 2017-2021, the Ginkgo authors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************<GINKGO LICENSE>*******************************/
#include <ginkgo/core/multigrid/amgx_pgm.hpp>
#include <fstream>
#include <random>
#include <string>
#include <gtest/gtest.h>
#include <ginkgo/core/base/exception.hpp>
#include <ginkgo/core/base/executor.hpp>
#include <ginkgo/core/matrix/dense.hpp>
#include <ginkgo/core/matrix/diagonal.hpp>
#include <ginkgo/core/stop/combined.hpp>
#include <ginkgo/core/stop/iteration.hpp>
#include <ginkgo/core/stop/residual_norm.hpp>
#include "core/multigrid/amgx_pgm_kernels.hpp"
#include "core/test/utils/matrix_generator.hpp"
#include "core/test/utils/unsort_matrix.hpp"
#include "hip/test/utils.hip.hpp"
namespace {
class AmgxPgm : public ::testing::Test {
protected:
using value_type = gko::default_precision;
using index_type = gko::int32;
using Mtx = gko::matrix::Dense<>;
using Csr = gko::matrix::Csr<value_type, index_type>;
using Diag = gko::matrix::Diagonal<value_type>;
AmgxPgm() : rand_engine(30) {}
void SetUp()
{
ASSERT_GT(gko::HipExecutor::get_num_devices(), 0);
ref = gko::ReferenceExecutor::create();
hip = gko::HipExecutor::create(0, ref);
}
void TearDown()
{
if (hip != nullptr) {
ASSERT_NO_THROW(hip->synchronize());
}
}
std::unique_ptr<Mtx> gen_mtx(int num_rows, int num_cols)
{
return gko::test::generate_random_matrix<Mtx>(
num_rows, num_cols,
std::uniform_int_distribution<>(num_cols, num_cols),
std::normal_distribution<>(-1.0, 1.0), rand_engine, ref);
}
gko::Array<index_type> gen_array(gko::size_type num, index_type min_val,
index_type max_val)
{
return gko::test::generate_random_array<index_type>(
num, std::uniform_int_distribution<>(min_val, max_val), rand_engine,
ref);
}
gko::Array<index_type> gen_agg_array(gko::size_type num,
gko::size_type num_agg)
{
auto agg_array = gen_array(num, 0, num_agg - 1);
auto agg_array_val = agg_array.get_data();
std::vector<index_type> select_agg(num);
std::iota(select_agg.begin(), select_agg.end(), 0);
// use the first num_agg item as the aggregated index.
std::shuffle(select_agg.begin(), select_agg.end(), rand_engine);
// the value of agg_array is the i-th of aggregate group
for (gko::size_type i = 0; i < num; i++) {
agg_array_val[i] = select_agg[agg_array_val[i]];
}
// the aggregated group must contain the identifier-th element
// agg_val[i] == i holds in the aggregated group whose identifier is i
for (gko::size_type i = 0; i < num_agg; i++) {
auto agg_idx = select_agg[i];
agg_array_val[agg_idx] = agg_idx;
}
return agg_array;
}
void initialize_data()
{
m = 597;
n = 300;
int nrhs = 3;
agg = gen_agg_array(m, n);
// only use 0 ~ n-2 and ensure the end isolated and not yet finished
unfinished_agg = gen_array(m, -1, n - 2);
unfinished_agg.get_data()[n - 1] = -1;
strongest_neighbor = gen_array(m, 0, n - 2);
strongest_neighbor.get_data()[n - 1] = n - 1;
coarse_vector = gen_mtx(n, nrhs);
fine_vector = gen_mtx(m, nrhs);
auto weight = gen_mtx(m, m);
make_weight(weight.get());
weight_csr = Csr::create(ref);
weight->convert_to(weight_csr.get());
weight_diag = weight_csr->extract_diagonal();
auto system_dense = gen_mtx(m, m);
gko::test::make_hpd(system_dense.get());
system_mtx = Csr::create(ref);
system_dense->convert_to(system_mtx.get());
d_agg = gko::Array<index_type>(hip, agg);
d_unfinished_agg = gko::Array<index_type>(hip, unfinished_agg);
d_strongest_neighbor = gko::Array<index_type>(hip, strongest_neighbor);
d_coarse_vector = gko::clone(hip, coarse_vector);
d_fine_vector = gko::clone(hip, fine_vector);
d_weight_csr = gko::clone(hip, weight_csr);
d_weight_diag = gko::clone(hip, weight_diag);
d_system_mtx = gko::clone(hip, system_mtx);
}
void make_weight(Mtx* mtx)
{
gko::test::make_symmetric(mtx);
// only works for real value cases
mtx->compute_absolute_inplace();
gko::test::make_diag_dominant(mtx);
}
std::shared_ptr<gko::ReferenceExecutor> ref;
std::shared_ptr<const gko::HipExecutor> hip;
std::ranlux48 rand_engine;
gko::Array<index_type> agg;
gko::Array<index_type> unfinished_agg;
gko::Array<index_type> strongest_neighbor;
gko::Array<index_type> d_agg;
gko::Array<index_type> d_unfinished_agg;
gko::Array<index_type> d_strongest_neighbor;
std::unique_ptr<Mtx> coarse_vector;
std::unique_ptr<Mtx> fine_vector;
std::unique_ptr<Diag> weight_diag;
std::unique_ptr<Csr> weight_csr;
std::shared_ptr<Csr> system_mtx;
std::unique_ptr<Mtx> d_coarse_vector;
std::unique_ptr<Mtx> d_fine_vector;
std::unique_ptr<Diag> d_weight_diag;
std::unique_ptr<Csr> d_weight_csr;
std::shared_ptr<Csr> d_system_mtx;
gko::size_type n;
gko::size_type m;
};
TEST_F(AmgxPgm, MatchEdgeIsEquivalentToRef)
{
initialize_data();
auto x = unfinished_agg;
auto d_x = d_unfinished_agg;
gko::kernels::reference::amgx_pgm::match_edge(ref, strongest_neighbor, x);
gko::kernels::hip::amgx_pgm::match_edge(hip, d_strongest_neighbor, d_x);
GKO_ASSERT_ARRAY_EQ(d_x, x);
}
TEST_F(AmgxPgm, CountUnaggIsEquivalentToRef)
{
initialize_data();
index_type num_unagg;
index_type d_num_unagg;
gko::kernels::reference::amgx_pgm::count_unagg(ref, unfinished_agg,
&num_unagg);
gko::kernels::hip::amgx_pgm::count_unagg(hip, d_unfinished_agg,
&d_num_unagg);
ASSERT_EQ(d_num_unagg, num_unagg);
}
TEST_F(AmgxPgm, RenumberIsEquivalentToRef)
{
initialize_data();
index_type num_agg;
index_type d_num_agg;
gko::kernels::reference::amgx_pgm::renumber(ref, agg, &num_agg);
gko::kernels::hip::amgx_pgm::renumber(hip, d_agg, &d_num_agg);
ASSERT_EQ(d_num_agg, num_agg);
GKO_ASSERT_ARRAY_EQ(d_agg, agg);
ASSERT_EQ(num_agg, n);
}
TEST_F(AmgxPgm, FindStrongestNeighborIsEquivalentToRef)
{
initialize_data();
auto snb = strongest_neighbor;
auto d_snb = d_strongest_neighbor;
gko::kernels::reference::amgx_pgm::find_strongest_neighbor(
ref, weight_csr.get(), weight_diag.get(), agg, snb);
gko::kernels::hip::amgx_pgm::find_strongest_neighbor(
hip, d_weight_csr.get(), d_weight_diag.get(), d_agg, d_snb);
GKO_ASSERT_ARRAY_EQ(d_snb, snb);
}
TEST_F(AmgxPgm, AssignToExistAggIsEquivalentToRef)
{
initialize_data();
auto x = unfinished_agg;
auto d_x = d_unfinished_agg;
auto intermediate_agg = x;
auto d_intermediate_agg = d_x;
gko::kernels::reference::amgx_pgm::assign_to_exist_agg(
ref, weight_csr.get(), weight_diag.get(), x, intermediate_agg);
gko::kernels::hip::amgx_pgm::assign_to_exist_agg(
hip, d_weight_csr.get(), d_weight_diag.get(), d_x, d_intermediate_agg);
GKO_ASSERT_ARRAY_EQ(d_x, x);
}
TEST_F(AmgxPgm, AssignToExistAggUnderteminsticIsEquivalentToRef)
{
initialize_data();
auto d_x = d_unfinished_agg;
auto d_intermediate_agg = gko::Array<index_type>(hip, 0);
index_type d_num_unagg;
gko::kernels::hip::amgx_pgm::assign_to_exist_agg(
hip, d_weight_csr.get(), d_weight_diag.get(), d_x, d_intermediate_agg);
gko::kernels::hip::amgx_pgm::count_unagg(hip, d_agg, &d_num_unagg);
// only test whether all elements are aggregated.
GKO_ASSERT_EQ(d_num_unagg, 0);
}
TEST_F(AmgxPgm, GenerateMgLevelIsEquivalentToRef)
{
initialize_data();
auto mg_level_factory = gko::multigrid::AmgxPgm<double, int>::build()
.with_deterministic(true)
.with_skip_sorting(true)
.on(ref);
auto d_mg_level_factory = gko::multigrid::AmgxPgm<double, int>::build()
.with_deterministic(true)
.with_skip_sorting(true)
.on(hip);
auto mg_level = mg_level_factory->generate(system_mtx);
auto d_mg_level = d_mg_level_factory->generate(d_system_mtx);
GKO_ASSERT_MTX_NEAR(gko::as<Csr>(d_mg_level->get_restrict_op()),
gko::as<Csr>(mg_level->get_restrict_op()), 1e-14);
GKO_ASSERT_MTX_NEAR(gko::as<Csr>(d_mg_level->get_coarse_op()),
gko::as<Csr>(mg_level->get_coarse_op()), 1e-14);
GKO_ASSERT_MTX_NEAR(gko::as<Csr>(d_mg_level->get_prolong_op()),
gko::as<Csr>(mg_level->get_prolong_op()), 1e-14);
}
TEST_F(AmgxPgm, GenerateMgLevelIsEquivalentToRefOnUnsortedMatrix)
{
initialize_data();
gko::test::unsort_matrix(gko::lend(system_mtx), rand_engine);
d_system_mtx = gko::clone(hip, system_mtx);
auto mg_level_factory = gko::multigrid::AmgxPgm<double, int>::build()
.with_deterministic(true)
.on(ref);
auto d_mg_level_factory = gko::multigrid::AmgxPgm<double, int>::build()
.with_deterministic(true)
.on(hip);
auto mg_level = mg_level_factory->generate(system_mtx);
auto d_mg_level = d_mg_level_factory->generate(d_system_mtx);
GKO_ASSERT_MTX_NEAR(gko::as<Csr>(d_mg_level->get_restrict_op()),
gko::as<Csr>(mg_level->get_restrict_op()), 1e-14);
GKO_ASSERT_MTX_NEAR(gko::as<Csr>(d_mg_level->get_coarse_op()),
gko::as<Csr>(mg_level->get_coarse_op()), 1e-14);
GKO_ASSERT_MTX_NEAR(gko::as<Csr>(d_mg_level->get_prolong_op()),
gko::as<Csr>(mg_level->get_prolong_op()), 1e-14);
}
} // namespace
|
// Module: Log4CPLUS
// File: filter.cxx
// Created: 5/2003
// Author: Tad E. Smith
//
//
// Copyright (C) Tad E. Smith All rights reserved.
//
// This software is published under the terms of the Apache Software
// License version 1.1, a copy of which has been included with this
// distribution in the LICENSE.APL file.
//
#include <log4cplus/spi/filter.h>
#include <log4cplus/helpers/loglog.h>
#include <log4cplus/helpers/stringhelper.h>
using namespace log4cplus;
using namespace log4cplus::spi;
using namespace log4cplus::helpers;
///////////////////////////////////////////////////////////////////////////////
// global methods
///////////////////////////////////////////////////////////////////////////////
FilterResult
log4cplus::spi::checkFilter(const Filter* filter,
const InternalLoggingEvent& event)
{
const Filter* currentFilter = filter;
while(currentFilter) {
FilterResult result = currentFilter->decide(event);
if(result != NEUTRAL) {
return result;
}
currentFilter = currentFilter->next.get();
}
return ACCEPT;
}
///////////////////////////////////////////////////////////////////////////////
// Filter implementation
///////////////////////////////////////////////////////////////////////////////
Filter::Filter()
{
}
Filter::~Filter()
{
}
void
Filter::appendFilter(FilterPtr filter)
{
if(next.get() == 0) {
next = filter;
}
else {
next->appendFilter(filter);
}
}
///////////////////////////////////////////////////////////////////////////////
// DenyAllFilter implementation
///////////////////////////////////////////////////////////////////////////////
FilterResult
DenyAllFilter::decide(const InternalLoggingEvent&) const
{
return DENY;
}
///////////////////////////////////////////////////////////////////////////////
// LogLevelMatchFilter implementation
///////////////////////////////////////////////////////////////////////////////
LogLevelMatchFilter::LogLevelMatchFilter()
{
init();
}
LogLevelMatchFilter::LogLevelMatchFilter(const Properties& properties)
{
init();
if(properties.exists( LOG4CPLUS_TEXT("AcceptOnMatch"))){
tstring tmp = properties.getProperty( LOG4CPLUS_TEXT("AcceptOnMatch") );
acceptOnMatch = (toLower(tmp) == LOG4CPLUS_TEXT("true"));
}
if(properties.exists( LOG4CPLUS_TEXT("LogLevelToMatch")) ){
tstring tmp = properties.getProperty( LOG4CPLUS_TEXT("LogLevelToMatch") );
logLevelToMatch = getLogLevelManager().fromString(tmp);
}
}
void
LogLevelMatchFilter::init()
{
acceptOnMatch = true;
logLevelToMatch = NOT_SET_LOG_LEVEL;
}
FilterResult
LogLevelMatchFilter::decide(const InternalLoggingEvent& event) const
{
if(logLevelToMatch == NOT_SET_LOG_LEVEL) {
return NEUTRAL;
}
bool matchOccured = (logLevelToMatch == event.getLogLevel());
if(matchOccured) {
return (acceptOnMatch ? ACCEPT : DENY);
}
else {
return NEUTRAL;
}
}
///////////////////////////////////////////////////////////////////////////////
// LogLevelRangeFilter implementation
///////////////////////////////////////////////////////////////////////////////
LogLevelRangeFilter::LogLevelRangeFilter()
{
init();
}
LogLevelRangeFilter::LogLevelRangeFilter(const Properties& properties)
{
init();
if(properties.exists( LOG4CPLUS_TEXT("AcceptOnMatch")) ){
tstring tmp = properties.getProperty( LOG4CPLUS_TEXT("AcceptOnMatch") );
acceptOnMatch = (toLower(tmp) == LOG4CPLUS_TEXT("true"));
}
if(properties.exists( LOG4CPLUS_TEXT("LogLevelMin") )){
tstring tmp = properties.getProperty( LOG4CPLUS_TEXT("LogLevelMin") );
logLevelMin = getLogLevelManager().fromString(tmp);
}
if(properties.exists( LOG4CPLUS_TEXT("LogLevelMax"))){
tstring tmp = properties.getProperty( LOG4CPLUS_TEXT("LogLevelMax") );
logLevelMax = getLogLevelManager().fromString(tmp);
}
}
void
LogLevelRangeFilter::init()
{
acceptOnMatch = true;
logLevelMin = NOT_SET_LOG_LEVEL;
logLevelMax = NOT_SET_LOG_LEVEL;
}
FilterResult
LogLevelRangeFilter::decide(const InternalLoggingEvent& event) const
{
if((logLevelMin != NOT_SET_LOG_LEVEL) && (event.getLogLevel() < logLevelMin)) {
// priority of event is less than minimum
return NEUTRAL;
}
if((logLevelMax != NOT_SET_LOG_LEVEL) && (event.getLogLevel() > logLevelMax)) {
// priority of event is greater than maximum
return NEUTRAL;
}
if(acceptOnMatch) {
// this filter set up to bypass later filters and always return
// accept if priority in range
return ACCEPT;
}
else {
// event is ok for this filter; allow later filters to have a look...
return DENY;
}
}
///////////////////////////////////////////////////////////////////////////////
// StringMatchFilter implementation
///////////////////////////////////////////////////////////////////////////////
StringMatchFilter::StringMatchFilter()
{
init();
}
StringMatchFilter::StringMatchFilter(const Properties& properties)
{
init();
tstring tmp = properties.getProperty( LOG4CPLUS_TEXT("AcceptOnMatch") );
acceptOnMatch = (toLower(tmp) == LOG4CPLUS_TEXT("true"));
stringToMatch = properties.getProperty( LOG4CPLUS_TEXT("StringToMatch") );
}
void
StringMatchFilter::init()
{
acceptOnMatch = true;
}
FilterResult
StringMatchFilter::decide(const InternalLoggingEvent& event) const
{
const tstring& message = event.getMessage();
if(stringToMatch.length() == 0 || message.length() == 0) {
return NEUTRAL;
}
if(message.find(stringToMatch) == tstring::npos) {
return NEUTRAL;
}
else { // we've got a match
return (acceptOnMatch ? ACCEPT : DENY);
}
}
|
// Copyright 2010-2018 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#if defined(USE_GLPK)
#include <cmath>
#include <cstddef>
#include <limits>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/memory/memory.h"
#include "absl/strings/str_format.h"
#include "ortools/base/commandlineflags.h"
#include "ortools/base/hash.h"
#include "ortools/base/integral_types.h"
#include "ortools/base/logging.h"
#include "ortools/base/timer.h"
#include "ortools/linear_solver/linear_solver.h"
extern "C" {
#include "glpk.h"
}
namespace operations_research {
// Class to store information gathered in the callback
class GLPKInformation {
public:
explicit GLPKInformation(bool maximize) : num_all_nodes_(0) {
ResetBestObjectiveBound(maximize);
}
void Reset(bool maximize) {
num_all_nodes_ = 0;
ResetBestObjectiveBound(maximize);
}
void ResetBestObjectiveBound(bool maximize) {
if (maximize) {
best_objective_bound_ = std::numeric_limits<double>::infinity();
} else {
best_objective_bound_ = -std::numeric_limits<double>::infinity();
}
}
int num_all_nodes_;
double best_objective_bound_;
};
// Function to be called in the GLPK callback
void GLPKGatherInformationCallback(glp_tree* tree, void* info) {
CHECK(tree != nullptr);
CHECK(info != nullptr);
GLPKInformation* glpk_info = reinterpret_cast<GLPKInformation*>(info);
switch (glp_ios_reason(tree)) {
// The best bound and the number of nodes change only when GLPK
// branches, generates cuts or finds an integer solution.
case GLP_ISELECT:
case GLP_IROWGEN:
case GLP_IBINGO: {
// Get total number of nodes
glp_ios_tree_size(tree, nullptr, nullptr, &glpk_info->num_all_nodes_);
// Get best bound
int node_id = glp_ios_best_node(tree);
if (node_id > 0) {
glpk_info->best_objective_bound_ = glp_ios_node_bound(tree, node_id);
}
break;
}
default:
break;
}
}
// ----- GLPK Solver -----
namespace {
// GLPK indexes its variables and constraints starting at 1.
int MPSolverIndexToGlpkIndex(int index) { return index + 1; }
} // namespace
class GLPKInterface : public MPSolverInterface {
public:
// Constructor that takes a name for the underlying glpk solver.
GLPKInterface(MPSolver* const solver, bool mip);
~GLPKInterface() override;
// Sets the optimization direction (min/max).
void SetOptimizationDirection(bool maximize) override;
// ----- Solve -----
// Solve the problem using the parameter values specified.
MPSolver::ResultStatus Solve(const MPSolverParameters& param) override;
// ----- Model modifications and extraction -----
// Resets extracted model
void Reset() override;
// Modify bounds.
void SetVariableBounds(int mpsolver_var_index, double lb, double ub) override;
void SetVariableInteger(int mpsolver_var_index, bool integer) override;
void SetConstraintBounds(int mpsolver_constraint_index, double lb,
double ub) override;
// Add Constraint incrementally.
void AddRowConstraint(MPConstraint* const ct) override;
// Add variable incrementally.
void AddVariable(MPVariable* const var) override;
// Change a coefficient in a constraint.
void SetCoefficient(MPConstraint* const constraint,
const MPVariable* const variable, double new_value,
double old_value) override;
// Clear a constraint from all its terms.
void ClearConstraint(MPConstraint* const constraint) override;
// Change a coefficient in the linear objective
void SetObjectiveCoefficient(const MPVariable* const variable,
double coefficient) override;
// Change the constant term in the linear objective.
void SetObjectiveOffset(double value) override;
// Clear the objective from all its terms.
void ClearObjective() override;
// ------ Query statistics on the solution and the solve ------
// Number of simplex iterations
int64 iterations() const override;
// Number of branch-and-bound nodes. Only available for discrete problems.
int64 nodes() const override;
// Best objective bound. Only available for discrete problems.
double best_objective_bound() const override;
// Returns the basis status of a row.
MPSolver::BasisStatus row_status(int constraint_index) const override;
// Returns the basis status of a column.
MPSolver::BasisStatus column_status(int variable_index) const override;
// Checks whether a feasible solution exists.
bool CheckSolutionExists() const override;
// Checks whether information on the best objective bound exists.
bool CheckBestObjectiveBoundExists() const override;
// ----- Misc -----
// Query problem type.
bool IsContinuous() const override { return IsLP(); }
bool IsLP() const override { return !mip_; }
bool IsMIP() const override { return mip_; }
void ExtractNewVariables() override;
void ExtractNewConstraints() override;
void ExtractObjective() override;
std::string SolverVersion() const override {
return absl::StrFormat("GLPK %s", glp_version());
}
void* underlying_solver() override { return reinterpret_cast<void*>(lp_); }
double ComputeExactConditionNumber() const override;
private:
// Configure the solver's parameters.
void ConfigureGLPKParameters(const MPSolverParameters& param);
// Set all parameters in the underlying solver.
void SetParameters(const MPSolverParameters& param) override;
// Set each parameter in the underlying solver.
void SetRelativeMipGap(double value) override;
void SetPrimalTolerance(double value) override;
void SetDualTolerance(double value) override;
void SetPresolveMode(int value) override;
void SetScalingMode(int value) override;
void SetLpAlgorithm(int value) override;
void SetMaximumSolutions(int value) override;
void ExtractOldConstraints();
void ExtractOneConstraint(MPConstraint* const constraint, int* const indices,
double* const coefs);
// Transforms basis status from GLPK integer code to MPSolver::BasisStatus.
MPSolver::BasisStatus TransformGLPKBasisStatus(int glpk_basis_status) const;
// Computes the L1-norm of the current scaled basis.
// The L1-norm |A| is defined as max_j sum_i |a_ij|
// This method is available only for continuous problems.
double ComputeScaledBasisL1Norm(int num_rows, int num_cols,
double* row_scaling_factor,
double* column_scaling_factor) const;
// Computes the L1-norm of the inverse of the current scaled
// basis.
// This method is available only for continuous problems.
double ComputeInverseScaledBasisL1Norm(int num_rows, int num_cols,
double* row_scaling_factor,
double* column_scaling_factor) const;
glp_prob* lp_;
bool mip_;
// Parameters
glp_smcp lp_param_;
glp_iocp mip_param_;
// For the callback
std::unique_ptr<GLPKInformation> mip_callback_info_;
};
// Creates a LP/MIP instance with the specified name and minimization objective.
GLPKInterface::GLPKInterface(MPSolver* const solver, bool mip)
: MPSolverInterface(solver), lp_(nullptr), mip_(mip) {
lp_ = glp_create_prob();
glp_set_prob_name(lp_, solver_->name_.c_str());
glp_set_obj_dir(lp_, GLP_MIN);
mip_callback_info_ = absl::make_unique<GLPKInformation>(maximize_);
}
// Frees the LP memory allocations.
GLPKInterface::~GLPKInterface() {
CHECK(lp_ != nullptr);
glp_delete_prob(lp_);
lp_ = nullptr;
}
void GLPKInterface::Reset() {
CHECK(lp_ != nullptr);
glp_delete_prob(lp_);
lp_ = glp_create_prob();
glp_set_prob_name(lp_, solver_->name_.c_str());
glp_set_obj_dir(lp_, maximize_ ? GLP_MAX : GLP_MIN);
ResetExtractionInformation();
}
// ------ Model modifications and extraction -----
// Not cached
void GLPKInterface::SetOptimizationDirection(bool maximize) {
InvalidateSolutionSynchronization();
glp_set_obj_dir(lp_, maximize ? GLP_MAX : GLP_MIN);
}
void GLPKInterface::SetVariableBounds(int mpsolver_var_index, double lb,
double ub) {
InvalidateSolutionSynchronization();
if (!variable_is_extracted(mpsolver_var_index)) {
sync_status_ = MUST_RELOAD;
return;
}
// Not cached if the variable has been extracted.
DCHECK(lp_ != nullptr);
const double infinity = solver_->infinity();
const int glpk_var_index = MPSolverIndexToGlpkIndex(mpsolver_var_index);
if (lb != -infinity) {
if (ub != infinity) {
if (lb == ub) {
glp_set_col_bnds(lp_, glpk_var_index, GLP_FX, lb, ub);
} else {
glp_set_col_bnds(lp_, glpk_var_index, GLP_DB, lb, ub);
}
} else {
glp_set_col_bnds(lp_, glpk_var_index, GLP_LO, lb, 0.0);
}
} else if (ub != infinity) {
glp_set_col_bnds(lp_, glpk_var_index, GLP_UP, 0.0, ub);
} else {
glp_set_col_bnds(lp_, glpk_var_index, GLP_FR, 0.0, 0.0);
}
}
void GLPKInterface::SetVariableInteger(int mpsolver_var_index, bool integer) {
InvalidateSolutionSynchronization();
if (mip_) {
if (variable_is_extracted(mpsolver_var_index)) {
// Not cached if the variable has been extracted.
glp_set_col_kind(lp_, MPSolverIndexToGlpkIndex(mpsolver_var_index),
integer ? GLP_IV : GLP_CV);
} else {
sync_status_ = MUST_RELOAD;
}
}
}
void GLPKInterface::SetConstraintBounds(int mpsolver_constraint_index,
double lb, double ub) {
InvalidateSolutionSynchronization();
if (!constraint_is_extracted(mpsolver_constraint_index)) {
sync_status_ = MUST_RELOAD;
return;
}
// Not cached if the row has been extracted
const int glpk_constraint_index =
MPSolverIndexToGlpkIndex(mpsolver_constraint_index);
DCHECK(lp_ != nullptr);
const double infinity = solver_->infinity();
if (lb != -infinity) {
if (ub != infinity) {
if (lb == ub) {
glp_set_row_bnds(lp_, glpk_constraint_index, GLP_FX, lb, ub);
} else {
glp_set_row_bnds(lp_, glpk_constraint_index, GLP_DB, lb, ub);
}
} else {
glp_set_row_bnds(lp_, glpk_constraint_index, GLP_LO, lb, 0.0);
}
} else if (ub != infinity) {
glp_set_row_bnds(lp_, glpk_constraint_index, GLP_UP, 0.0, ub);
} else {
glp_set_row_bnds(lp_, glpk_constraint_index, GLP_FR, 0.0, 0.0);
}
}
void GLPKInterface::SetCoefficient(MPConstraint* const constraint,
const MPVariable* const variable,
double new_value, double old_value) {
InvalidateSolutionSynchronization();
// GLPK does not allow to modify one coefficient at a time, so we
// extract the whole constraint again, if it has been extracted
// already and if it does not contain new variables. Otherwise, we
// cache the modification.
if (constraint_is_extracted(constraint->index()) &&
(sync_status_ == MODEL_SYNCHRONIZED ||
!constraint->ContainsNewVariables())) {
const int size = constraint->coefficients_.size();
std::unique_ptr<int[]> indices(new int[size + 1]);
std::unique_ptr<double[]> coefs(new double[size + 1]);
ExtractOneConstraint(constraint, indices.get(), coefs.get());
}
}
// Not cached
void GLPKInterface::ClearConstraint(MPConstraint* const constraint) {
InvalidateSolutionSynchronization();
// Constraint may have not been extracted yet.
if (constraint_is_extracted(constraint->index())) {
glp_set_mat_row(lp_, MPSolverIndexToGlpkIndex(constraint->index()), 0,
nullptr, nullptr);
}
}
// Cached
void GLPKInterface::SetObjectiveCoefficient(const MPVariable* const variable,
double coefficient) {
sync_status_ = MUST_RELOAD;
}
// Cached
void GLPKInterface::SetObjectiveOffset(double value) {
sync_status_ = MUST_RELOAD;
}
// Clear objective of all its terms (linear)
void GLPKInterface::ClearObjective() {
InvalidateSolutionSynchronization();
for (const auto& entry : solver_->objective_->coefficients_) {
const int mpsolver_var_index = entry.first->index();
// Variable may have not been extracted yet.
if (!variable_is_extracted(mpsolver_var_index)) {
DCHECK_NE(MODEL_SYNCHRONIZED, sync_status_);
} else {
glp_set_obj_coef(lp_, MPSolverIndexToGlpkIndex(mpsolver_var_index), 0.0);
}
}
// Constant term.
glp_set_obj_coef(lp_, 0, 0.0);
}
void GLPKInterface::AddRowConstraint(MPConstraint* const ct) {
sync_status_ = MUST_RELOAD;
}
void GLPKInterface::AddVariable(MPVariable* const var) {
sync_status_ = MUST_RELOAD;
}
// Define new variables and add them to existing constraints.
void GLPKInterface::ExtractNewVariables() {
int total_num_vars = solver_->variables_.size();
if (total_num_vars > last_variable_index_) {
glp_add_cols(lp_, total_num_vars - last_variable_index_);
for (int j = last_variable_index_; j < solver_->variables_.size(); ++j) {
MPVariable* const var = solver_->variables_[j];
set_variable_as_extracted(j, true);
if (!var->name().empty()) {
glp_set_col_name(lp_, MPSolverIndexToGlpkIndex(j), var->name().c_str());
}
SetVariableBounds(/*mpsolver_var_index=*/j, var->lb(), var->ub());
SetVariableInteger(/*mpsolver_var_index=*/j, var->integer());
// The true objective coefficient will be set later in ExtractObjective.
double tmp_obj_coef = 0.0;
glp_set_obj_coef(lp_, MPSolverIndexToGlpkIndex(j), tmp_obj_coef);
}
// Add new variables to the existing constraints.
ExtractOldConstraints();
}
}
// Extract again existing constraints if they contain new variables.
void GLPKInterface::ExtractOldConstraints() {
const int max_constraint_size =
solver_->ComputeMaxConstraintSize(0, last_constraint_index_);
// The first entry in the following arrays is dummy, to be
// consistent with glpk API.
std::unique_ptr<int[]> indices(new int[max_constraint_size + 1]);
std::unique_ptr<double[]> coefs(new double[max_constraint_size + 1]);
for (int i = 0; i < last_constraint_index_; ++i) {
MPConstraint* const ct = solver_->constraints_[i];
DCHECK(constraint_is_extracted(i));
const int size = ct->coefficients_.size();
if (size == 0) {
continue;
}
// Update the constraint's coefficients if it contains new variables.
if (ct->ContainsNewVariables()) {
ExtractOneConstraint(ct, indices.get(), coefs.get());
}
}
}
// Extract one constraint. Arrays indices and coefs must be
// preallocated to have enough space to contain the constraint's
// coefficients.
void GLPKInterface::ExtractOneConstraint(MPConstraint* const constraint,
int* const indices,
double* const coefs) {
// GLPK convention is to start indexing at 1.
int k = 1;
for (const auto& entry : constraint->coefficients_) {
DCHECK(variable_is_extracted(entry.first->index()));
indices[k] = MPSolverIndexToGlpkIndex(entry.first->index());
coefs[k] = entry.second;
++k;
}
glp_set_mat_row(lp_, MPSolverIndexToGlpkIndex(constraint->index()), k - 1,
indices, coefs);
}
// Define new constraints on old and new variables.
void GLPKInterface::ExtractNewConstraints() {
int total_num_rows = solver_->constraints_.size();
if (last_constraint_index_ < total_num_rows) {
// Define new constraints
glp_add_rows(lp_, total_num_rows - last_constraint_index_);
int num_coefs = 0;
for (int i = last_constraint_index_; i < total_num_rows; ++i) {
MPConstraint* ct = solver_->constraints_[i];
set_constraint_as_extracted(i, true);
if (ct->name().empty()) {
glp_set_row_name(lp_, MPSolverIndexToGlpkIndex(i),
absl::StrFormat("ct_%i", i).c_str());
} else {
glp_set_row_name(lp_, MPSolverIndexToGlpkIndex(i), ct->name().c_str());
}
// All constraints are set to be of the type <= limit_ .
SetConstraintBounds(/*mpsolver_constraint_index=*/i, ct->lb(), ct->ub());
num_coefs += ct->coefficients_.size();
}
// Fill new constraints with coefficients
if (last_variable_index_ == 0 && last_constraint_index_ == 0) {
// Faster extraction when nothing has been extracted yet: build
// and load whole matrix at once instead of constructing rows
// separately.
// The first entry in the following arrays is dummy, to be
// consistent with glpk API.
std::unique_ptr<int[]> variable_indices(new int[num_coefs + 1]);
std::unique_ptr<int[]> constraint_indices(new int[num_coefs + 1]);
std::unique_ptr<double[]> coefs(new double[num_coefs + 1]);
int k = 1;
for (int i = 0; i < solver_->constraints_.size(); ++i) {
MPConstraint* ct = solver_->constraints_[i];
for (const auto& entry : ct->coefficients_) {
DCHECK(variable_is_extracted(entry.first->index()));
constraint_indices[k] = MPSolverIndexToGlpkIndex(ct->index());
variable_indices[k] = MPSolverIndexToGlpkIndex(entry.first->index());
coefs[k] = entry.second;
++k;
}
}
CHECK_EQ(num_coefs + 1, k);
glp_load_matrix(lp_, num_coefs, constraint_indices.get(),
variable_indices.get(), coefs.get());
} else {
// Build each new row separately.
int max_constraint_size = solver_->ComputeMaxConstraintSize(
last_constraint_index_, total_num_rows);
// The first entry in the following arrays is dummy, to be
// consistent with glpk API.
std::unique_ptr<int[]> indices(new int[max_constraint_size + 1]);
std::unique_ptr<double[]> coefs(new double[max_constraint_size + 1]);
for (int i = last_constraint_index_; i < total_num_rows; i++) {
ExtractOneConstraint(solver_->constraints_[i], indices.get(),
coefs.get());
}
}
}
}
void GLPKInterface::ExtractObjective() {
// Linear objective: set objective coefficients for all variables
// (some might have been modified).
for (const auto& entry : solver_->objective_->coefficients_) {
glp_set_obj_coef(lp_, MPSolverIndexToGlpkIndex(entry.first->index()),
entry.second);
}
// Constant term.
glp_set_obj_coef(lp_, 0, solver_->Objective().offset());
}
// Solve the problem using the parameter values specified.
MPSolver::ResultStatus GLPKInterface::Solve(const MPSolverParameters& param) {
WallTimer timer;
timer.Start();
// Note that GLPK provides incrementality for LP but not for MIP.
if (param.GetIntegerParam(MPSolverParameters::INCREMENTALITY) ==
MPSolverParameters::INCREMENTALITY_OFF) {
Reset();
}
// Set log level.
if (quiet_) {
glp_term_out(GLP_OFF);
} else {
glp_term_out(GLP_ON);
}
ExtractModel();
VLOG(1) << absl::StrFormat("Model built in %.3f seconds.", timer.Get());
// Configure parameters at every solve, even when the model has not
// been changed, in case some of the parameters such as the time
// limit have been changed since the last solve.
ConfigureGLPKParameters(param);
// Solve
timer.Restart();
int solver_status = glp_simplex(lp_, &lp_param_);
if (mip_) {
// glp_intopt requires to solve the root LP separately.
// If the root LP was solved successfully, solve the MIP.
if (solver_status == 0) {
solver_status = glp_intopt(lp_, &mip_param_);
} else {
// Something abnormal occurred during the root LP solve. It is
// highly unlikely that an integer feasible solution is
// available at this point, so we don't put any effort in trying
// to recover it.
result_status_ = MPSolver::ABNORMAL;
if (solver_status == GLP_ETMLIM) {
result_status_ = MPSolver::NOT_SOLVED;
}
sync_status_ = SOLUTION_SYNCHRONIZED;
return result_status_;
}
}
VLOG(1) << absl::StrFormat("GLPK Status: %i (time spent: %.3f seconds).",
solver_status, timer.Get());
// Get the results.
if (mip_) {
objective_value_ = glp_mip_obj_val(lp_);
} else {
objective_value_ = glp_get_obj_val(lp_);
}
VLOG(1) << "objective=" << objective_value_;
for (int i = 0; i < solver_->variables_.size(); ++i) {
MPVariable* const var = solver_->variables_[i];
double val;
if (mip_) {
val = glp_mip_col_val(lp_, MPSolverIndexToGlpkIndex(i));
} else {
val = glp_get_col_prim(lp_, MPSolverIndexToGlpkIndex(i));
}
var->set_solution_value(val);
VLOG(3) << var->name() << ": value =" << val;
if (!mip_) {
double reduced_cost;
reduced_cost = glp_get_col_dual(lp_, MPSolverIndexToGlpkIndex(i));
var->set_reduced_cost(reduced_cost);
VLOG(4) << var->name() << ": reduced cost = " << reduced_cost;
}
}
for (int i = 0; i < solver_->constraints_.size(); ++i) {
MPConstraint* const ct = solver_->constraints_[i];
if (!mip_) {
const double dual_value =
glp_get_row_dual(lp_, MPSolverIndexToGlpkIndex(i));
ct->set_dual_value(dual_value);
VLOG(4) << "row " << MPSolverIndexToGlpkIndex(i)
<< ": dual value = " << dual_value;
}
}
// Check the status: optimal, infeasible, etc.
if (mip_) {
int tmp_status = glp_mip_status(lp_);
VLOG(1) << "GLPK result status: " << tmp_status;
if (tmp_status == GLP_OPT) {
result_status_ = MPSolver::OPTIMAL;
} else if (tmp_status == GLP_FEAS) {
result_status_ = MPSolver::FEASIBLE;
} else if (tmp_status == GLP_NOFEAS) {
// For infeasible problems, GLPK actually seems to return
// GLP_UNDEF. So this is never (?) reached. Return infeasible
// in case GLPK returns a correct status in future versions.
result_status_ = MPSolver::INFEASIBLE;
} else if (solver_status == GLP_ETMLIM) {
result_status_ = MPSolver::NOT_SOLVED;
} else {
result_status_ = MPSolver::ABNORMAL;
// GLPK does not have a status code for unbounded MIP models, so
// we return an abnormal status instead.
}
} else {
int tmp_status = glp_get_status(lp_);
VLOG(1) << "GLPK result status: " << tmp_status;
if (tmp_status == GLP_OPT) {
result_status_ = MPSolver::OPTIMAL;
} else if (tmp_status == GLP_FEAS) {
result_status_ = MPSolver::FEASIBLE;
} else if (tmp_status == GLP_NOFEAS || tmp_status == GLP_INFEAS) {
// For infeasible problems, GLPK actually seems to return
// GLP_UNDEF. So this is never (?) reached. Return infeasible
// in case GLPK returns a correct status in future versions.
result_status_ = MPSolver::INFEASIBLE;
} else if (tmp_status == GLP_UNBND) {
// For unbounded problems, GLPK actually seems to return
// GLP_UNDEF. So this is never (?) reached. Return unbounded
// in case GLPK returns a correct status in future versions.
result_status_ = MPSolver::UNBOUNDED;
} else if (solver_status == GLP_ETMLIM) {
result_status_ = MPSolver::NOT_SOLVED;
} else {
result_status_ = MPSolver::ABNORMAL;
}
}
sync_status_ = SOLUTION_SYNCHRONIZED;
return result_status_;
}
MPSolver::BasisStatus GLPKInterface::TransformGLPKBasisStatus(
int glpk_basis_status) const {
switch (glpk_basis_status) {
case GLP_BS:
return MPSolver::BASIC;
case GLP_NL:
return MPSolver::AT_LOWER_BOUND;
case GLP_NU:
return MPSolver::AT_UPPER_BOUND;
case GLP_NF:
return MPSolver::FREE;
case GLP_NS:
return MPSolver::FIXED_VALUE;
default:
LOG(FATAL) << "Unknown GLPK basis status";
return MPSolver::FREE;
}
}
// ------ Query statistics on the solution and the solve ------
int64 GLPKInterface::iterations() const {
#if GLP_MAJOR_VERSION == 4 && GLP_MINOR_VERSION < 49
if (!mip_ && CheckSolutionIsSynchronized()) {
return lpx_get_int_parm(lp_, LPX_K_ITCNT);
}
#elif GLP_MAJOR_VERSION == 4 && GLP_MINOR_VERSION >= 53
if (!mip_ && CheckSolutionIsSynchronized()) {
return glp_get_it_cnt(lp_);
}
#endif
LOG(WARNING) << "Total number of iterations is not available";
return kUnknownNumberOfIterations;
}
int64 GLPKInterface::nodes() const {
if (mip_) {
if (!CheckSolutionIsSynchronized()) return kUnknownNumberOfNodes;
return mip_callback_info_->num_all_nodes_;
} else {
LOG(DFATAL) << "Number of nodes only available for discrete problems";
return kUnknownNumberOfNodes;
}
}
double GLPKInterface::best_objective_bound() const {
if (mip_) {
if (!CheckSolutionIsSynchronized() || !CheckBestObjectiveBoundExists()) {
return trivial_worst_objective_bound();
}
if (solver_->variables_.empty() && solver_->constraints_.empty()) {
// Special case for empty model.
return solver_->Objective().offset();
} else {
return mip_callback_info_->best_objective_bound_;
}
} else {
LOG(DFATAL) << "Best objective bound only available for discrete problems";
return trivial_worst_objective_bound();
}
}
MPSolver::BasisStatus GLPKInterface::row_status(int constraint_index) const {
DCHECK_GE(constraint_index, 0);
DCHECK_LT(constraint_index, last_constraint_index_);
const int glpk_basis_status =
glp_get_row_stat(lp_, MPSolverIndexToGlpkIndex(constraint_index));
return TransformGLPKBasisStatus(glpk_basis_status);
}
MPSolver::BasisStatus GLPKInterface::column_status(int variable_index) const {
DCHECK_GE(variable_index, 0);
DCHECK_LT(variable_index, last_variable_index_);
const int glpk_basis_status =
glp_get_col_stat(lp_, MPSolverIndexToGlpkIndex(variable_index));
return TransformGLPKBasisStatus(glpk_basis_status);
}
bool GLPKInterface::CheckSolutionExists() const {
if (result_status_ == MPSolver::ABNORMAL) {
LOG(WARNING) << "Ignoring ABNORMAL status from GLPK: This status may or may"
<< " not indicate that a solution exists.";
return true;
} else {
// Call default implementation
return MPSolverInterface::CheckSolutionExists();
}
}
bool GLPKInterface::CheckBestObjectiveBoundExists() const {
if (result_status_ == MPSolver::ABNORMAL) {
LOG(WARNING) << "Ignoring ABNORMAL status from GLPK: This status may or may"
<< " not indicate that information is available on the best"
<< " objective bound.";
return true;
} else {
// Call default implementation
return MPSolverInterface::CheckBestObjectiveBoundExists();
}
}
double GLPKInterface::ComputeExactConditionNumber() const {
if (!IsContinuous()) {
// TODO(user): support MIP.
LOG(DFATAL) << "ComputeExactConditionNumber not implemented for"
<< " GLPK_MIXED_INTEGER_PROGRAMMING";
return 0.0;
}
if (!CheckSolutionIsSynchronized()) return 0.0;
// Simplex is the only LP algorithm supported in the wrapper for
// GLPK, so when a solution exists, a basis exists.
CheckSolutionExists();
const int num_rows = glp_get_num_rows(lp_);
const int num_cols = glp_get_num_cols(lp_);
// GLPK indexes everything starting from 1 instead of 0.
std::unique_ptr<double[]> row_scaling_factor(new double[num_rows + 1]);
std::unique_ptr<double[]> column_scaling_factor(new double[num_cols + 1]);
for (int row = 1; row <= num_rows; ++row) {
row_scaling_factor[row] = glp_get_rii(lp_, row);
}
for (int col = 1; col <= num_cols; ++col) {
column_scaling_factor[col] = glp_get_sjj(lp_, col);
}
return ComputeInverseScaledBasisL1Norm(num_rows, num_cols,
row_scaling_factor.get(),
column_scaling_factor.get()) *
ComputeScaledBasisL1Norm(num_rows, num_cols, row_scaling_factor.get(),
column_scaling_factor.get());
}
double GLPKInterface::ComputeScaledBasisL1Norm(
int num_rows, int num_cols, double* row_scaling_factor,
double* column_scaling_factor) const {
double norm = 0.0;
std::unique_ptr<double[]> values(new double[num_rows + 1]);
std::unique_ptr<int[]> indices(new int[num_rows + 1]);
for (int col = 1; col <= num_cols; ++col) {
const int glpk_basis_status = glp_get_col_stat(lp_, col);
// Take into account only basic columns.
if (glpk_basis_status == GLP_BS) {
// Compute L1-norm of column 'col': sum_row |a_row,col|.
const int num_nz = glp_get_mat_col(lp_, col, indices.get(), values.get());
double column_norm = 0.0;
for (int k = 1; k <= num_nz; k++) {
column_norm += fabs(values[k] * row_scaling_factor[indices[k]]);
}
column_norm *= fabs(column_scaling_factor[col]);
// Compute max_col column_norm
norm = std::max(norm, column_norm);
}
}
// Slack variables.
for (int row = 1; row <= num_rows; ++row) {
const int glpk_basis_status = glp_get_row_stat(lp_, row);
// Take into account only basic slack variables.
if (glpk_basis_status == GLP_BS) {
// Only one non-zero coefficient: +/- 1.0 in the corresponding
// row. The row has a scaling coefficient but the slack variable
// is never scaled on top of that.
const double column_norm = fabs(row_scaling_factor[row]);
// Compute max_col column_norm
norm = std::max(norm, column_norm);
}
}
return norm;
}
double GLPKInterface::ComputeInverseScaledBasisL1Norm(
int num_rows, int num_cols, double* row_scaling_factor,
double* column_scaling_factor) const {
// Compute the LU factorization if it doesn't exist yet.
if (!glp_bf_exists(lp_)) {
const int factorize_status = glp_factorize(lp_);
switch (factorize_status) {
case GLP_EBADB: {
LOG(FATAL) << "Not able to factorize: error GLP_EBADB.";
break;
}
case GLP_ESING: {
LOG(WARNING)
<< "Not able to factorize: "
<< "the basis matrix is singular within the working precision.";
return MPSolver::infinity();
}
case GLP_ECOND: {
LOG(WARNING)
<< "Not able to factorize: the basis matrix is ill-conditioned.";
return MPSolver::infinity();
}
default:
break;
}
}
std::unique_ptr<double[]> right_hand_side(new double[num_rows + 1]);
double norm = 0.0;
// Iteratively solve B x = e_k, where e_k is the kth unit vector.
// The result of this computation is the kth column of B^-1.
// glp_ftran works on original matrix. Scale input and result to
// obtain the norm of the kth column in the inverse scaled
// matrix. See glp_ftran documentation in glpapi12.c for how the
// scaling is done: inv(B'') = inv(SB) * inv(B) * inv(R) where:
// o B'' is the scaled basis
// o B is the original basis
// o R is the diagonal row scaling matrix
// o SB consists of the basic columns of the augmented column
// scaling matrix (auxiliary variables then structural variables):
// S~ = diag(inv(R) | S).
for (int k = 1; k <= num_rows; ++k) {
for (int row = 1; row <= num_rows; ++row) {
right_hand_side[row] = 0.0;
}
right_hand_side[k] = 1.0;
// Multiply input by inv(R).
for (int row = 1; row <= num_rows; ++row) {
right_hand_side[row] /= row_scaling_factor[row];
}
glp_ftran(lp_, right_hand_side.get());
// glp_ftran stores the result in the same vector where the right
// hand side was provided.
// Multiply result by inv(SB).
for (int row = 1; row <= num_rows; ++row) {
const int k = glp_get_bhead(lp_, row);
if (k <= num_rows) {
// Auxiliary variable.
right_hand_side[row] *= row_scaling_factor[k];
} else {
// Structural variable.
right_hand_side[row] /= column_scaling_factor[k - num_rows];
}
}
// Compute sum_row |vector_row|.
double column_norm = 0.0;
for (int row = 1; row <= num_rows; ++row) {
column_norm += fabs(right_hand_side[row]);
}
// Compute max_col column_norm
norm = std::max(norm, column_norm);
}
return norm;
}
// ------ Parameters ------
void GLPKInterface::ConfigureGLPKParameters(const MPSolverParameters& param) {
if (mip_) {
glp_init_iocp(&mip_param_);
// Time limit
if (solver_->time_limit()) {
VLOG(1) << "Setting time limit = " << solver_->time_limit() << " ms.";
mip_param_.tm_lim = solver_->time_limit();
}
// Initialize structures related to the callback.
mip_param_.cb_func = GLPKGatherInformationCallback;
mip_callback_info_->Reset(maximize_);
mip_param_.cb_info = mip_callback_info_.get();
// TODO(user): switch some cuts on? All cuts are off by default!?
}
// Configure LP parameters in all cases since they will be used to
// solve the root LP in the MIP case.
glp_init_smcp(&lp_param_);
// Time limit
if (solver_->time_limit()) {
VLOG(1) << "Setting time limit = " << solver_->time_limit() << " ms.";
lp_param_.tm_lim = solver_->time_limit();
}
// Should give a numerically better representation of the problem.
glp_scale_prob(lp_, GLP_SF_AUTO);
// Use advanced initial basis (options: standard / advanced / Bixby's).
glp_adv_basis(lp_, 0);
// Set parameters specified by the user.
SetParameters(param);
}
void GLPKInterface::SetParameters(const MPSolverParameters& param) {
SetCommonParameters(param);
if (mip_) {
SetMIPParameters(param);
}
}
void GLPKInterface::SetRelativeMipGap(double value) {
if (mip_) {
mip_param_.mip_gap = value;
} else {
LOG(WARNING) << "The relative MIP gap is only available "
<< "for discrete problems.";
}
}
void GLPKInterface::SetPrimalTolerance(double value) {
lp_param_.tol_bnd = value;
}
void GLPKInterface::SetDualTolerance(double value) { lp_param_.tol_dj = value; }
void GLPKInterface::SetPresolveMode(int value) {
switch (value) {
case MPSolverParameters::PRESOLVE_OFF: {
mip_param_.presolve = GLP_OFF;
lp_param_.presolve = GLP_OFF;
break;
}
case MPSolverParameters::PRESOLVE_ON: {
mip_param_.presolve = GLP_ON;
lp_param_.presolve = GLP_ON;
break;
}
default: {
SetIntegerParamToUnsupportedValue(MPSolverParameters::PRESOLVE, value);
}
}
}
void GLPKInterface::SetScalingMode(int value) {
SetUnsupportedIntegerParam(MPSolverParameters::SCALING);
}
void GLPKInterface::SetLpAlgorithm(int value) {
switch (value) {
case MPSolverParameters::DUAL: {
// Use dual, and if it fails, switch to primal.
lp_param_.meth = GLP_DUALP;
break;
}
case MPSolverParameters::PRIMAL: {
lp_param_.meth = GLP_PRIMAL;
break;
}
case MPSolverParameters::BARRIER:
default: {
SetIntegerParamToUnsupportedValue(MPSolverParameters::LP_ALGORITHM,
value);
}
}
}
void GLPKInterface::SetMaximumSolutions(int value) {
SetUnsupportedIntegerParam(MPSolverParameters::MAXIMUM_SOLUTIONS);
}
MPSolverInterface* BuildGLPKInterface(bool mip, MPSolver* const solver) {
return new GLPKInterface(solver, mip);
}
} // namespace operations_research
#endif // #if defined(USE_GLPK)
|
#include "Hub.h"
#include "HTTPSocket.h"
#include <openssl/sha.h>
namespace uWS {
char *Hub::inflate(char *data, size_t &length, size_t maxPayload) {
dynamicInflationBuffer.clear();
inflationStream.next_in = (Bytef *) data;
inflationStream.avail_in = length;
int err;
do {
inflationStream.next_out = (Bytef *) inflationBuffer;
inflationStream.avail_out = LARGE_BUFFER_SIZE;
err = ::inflate(&inflationStream, Z_FINISH);
if (!inflationStream.avail_in) {
break;
}
dynamicInflationBuffer.append(inflationBuffer, LARGE_BUFFER_SIZE - inflationStream.avail_out);
} while (err == Z_BUF_ERROR && dynamicInflationBuffer.length() <= maxPayload);
inflateReset(&inflationStream);
if ((err != Z_BUF_ERROR && err != Z_OK) || dynamicInflationBuffer.length() > maxPayload) {
length = 0;
return nullptr;
}
if (dynamicInflationBuffer.length()) {
dynamicInflationBuffer.append(inflationBuffer, LARGE_BUFFER_SIZE - inflationStream.avail_out);
length = dynamicInflationBuffer.length();
return (char *) dynamicInflationBuffer.data();
}
length = LARGE_BUFFER_SIZE - inflationStream.avail_out;
return inflationBuffer;
}
void Hub::onServerAccept(uS::Socket *s) {
HttpSocket<SERVER> *httpSocket = new HttpSocket<SERVER>(s);
delete s;
httpSocket->setState<HttpSocket<SERVER>>();
httpSocket->start(httpSocket->nodeData->loop, httpSocket, httpSocket->setPoll(UV_READABLE));
httpSocket->setNoDelay(true);
Group<SERVER>::from(httpSocket)->addHttpSocket(httpSocket);
Group<SERVER>::from(httpSocket)->httpConnectionHandler(httpSocket);
}
void Hub::onClientConnection(uS::Socket *s, bool error) {
HttpSocket<CLIENT> *httpSocket = (HttpSocket<CLIENT> *) s;
if (error) {
httpSocket->onEnd(httpSocket);
} else {
httpSocket->setState<HttpSocket<CLIENT>>();
httpSocket->change(httpSocket->nodeData->loop, httpSocket, httpSocket->setPoll(UV_READABLE));
httpSocket->setNoDelay(true);
httpSocket->upgrade(nullptr, nullptr, 0, nullptr, 0, nullptr);
}
}
bool Hub::listen(const char *host, int port, uS::TLS::Context sslContext, int options, Group<SERVER> *eh) {
if (!eh) {
eh = (Group<SERVER> *) this;
}
if (uS::Node::listen<onServerAccept>(host, port, sslContext, options, (uS::NodeData *) eh, nullptr)) {
eh->errorHandler(port);
return false;
}
return true;
}
bool Hub::listen(int port, uS::TLS::Context sslContext, int options, Group<SERVER> *eh) {
return listen(nullptr, port, sslContext, options, eh);
}
uS::Socket *allocateHttpSocket(uS::Socket *s) {
return (uS::Socket *) new HttpSocket<CLIENT>(s);
}
bool parseURI(std::string &uri, bool &secure, std::string &hostname, int &port, std::string &path) {
port = 80;
secure = false;
size_t offset = 5;
if (!uri.compare(0, 6, "wss://")) {
port = 443;
secure = true;
offset = 6;
} else if (uri.compare(0, 5, "ws://")) {
return false;
}
if (offset == uri.length()) {
return false;
}
if (uri[offset] == '[') {
if (++offset == uri.length()) {
return false;
}
size_t endBracket = uri.find(']', offset);
if (endBracket == std::string::npos) {
return false;
}
hostname = uri.substr(offset, endBracket - offset);
offset = endBracket + 1;
} else {
hostname = uri.substr(offset, uri.find_first_of(":/", offset) - offset);
offset += hostname.length();
}
if (offset == uri.length()) {
path.clear();
return true;
}
if (uri[offset] == ':') {
offset++;
std::string portStr = uri.substr(offset, uri.find('/', offset) - offset);
if (portStr.length()) {
try {
port = stoi(portStr);
} catch (...) {
return false;
}
} else {
return false;
}
offset += portStr.length();
}
if (offset == uri.length()) {
path.clear();
return true;
}
if (uri[offset] == '/') {
path = uri.substr(++offset);
}
return true;
}
void Hub::connect(std::string uri, void *user, std::map<std::string, std::string> extraHeaders, int timeoutMs, Group<CLIENT> *eh) {
if (!eh) {
eh = (Group<CLIENT> *) this;
}
int port;
bool secure;
std::string hostname, path;
if (!parseURI(uri, secure, hostname, port, path)) {
eh->errorHandler(user);
} else {
HttpSocket<CLIENT> *httpSocket = (HttpSocket<CLIENT> *) uS::Node::connect<allocateHttpSocket, onClientConnection>(hostname.c_str(), port, secure, eh);
if (httpSocket) {
// startTimeout occupies the user
httpSocket->startTimeout<HttpSocket<CLIENT>::onEnd>(timeoutMs);
httpSocket->httpUser = user;
std::string randomKey = "x3JJHMbDL1EzLkh9GBhXDw==";
// for (int i = 0; i < 22; i++) {
// randomKey[i] = rand() %
// }
httpSocket->httpBuffer = "GET /" + path + " HTTP/1.1\r\n"
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n"
"Sec-WebSocket-Key: " + randomKey + "\r\n"
"Host: " + hostname + "\r\n" +
"Sec-WebSocket-Version: 13\r\n";
for (std::pair<std::string, std::string> header : extraHeaders) {
httpSocket->httpBuffer += header.first + ": " + header.second + "\r\n";
}
httpSocket->httpBuffer += "\r\n";
} else {
eh->errorHandler(user);
}
}
}
void Hub::upgrade(uv_os_sock_t fd, const char *secKey, SSL *ssl, const char *extensions, size_t extensionsLength, const char *subprotocol, size_t subprotocolLength, Group<SERVER> *serverGroup) {
if (!serverGroup) {
serverGroup = &getDefaultGroup<SERVER>();
}
uS::Socket s((uS::NodeData *) serverGroup, serverGroup->loop, fd, ssl);
s.setNoDelay(true);
// todo: skip httpSocket -> it cannot fail anyways!
HttpSocket<SERVER> *httpSocket = new HttpSocket<SERVER>(&s);
httpSocket->setState<HttpSocket<SERVER>>();
httpSocket->change(httpSocket->nodeData->loop, httpSocket, httpSocket->setPoll(UV_READABLE));
bool perMessageDeflate;
httpSocket->upgrade(secKey, extensions, extensionsLength, subprotocol, subprotocolLength, &perMessageDeflate);
WebSocket<SERVER> *webSocket = new WebSocket<SERVER>(perMessageDeflate, httpSocket);
delete httpSocket;
webSocket->setState<WebSocket<SERVER>>();
webSocket->change(webSocket->nodeData->loop, webSocket, webSocket->setPoll(UV_READABLE));
serverGroup->addWebSocket(webSocket);
serverGroup->connectionHandler(webSocket, {});
}
}
|
/*
* Copyright (c) 2019-2021 Arm Limited.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#pragma once
#ifdef __aarch64__
#include "../std_transforms_fixed.hpp"
#include "../performance_parameters.hpp"
#define ARGLIST \
const int8_t *, const int8_t *, \
int32_t *, int, int, int
namespace arm_gemm
{
// Actual kernel implementations
void a64_interleaved_s8s32_mmla_8x12( ARGLIST );
class cls_a64_interleaved_s8s32_mmla_8x12
{
public:
typedef int8_t operand_type;
typedef int32_t result_type;
typedef void (*kern_type)( ARGLIST );
/* Kernel blocking parameters */
static constexpr unsigned int out_height()
{
return 8;
}
static unsigned int out_width()
{
return 12;
}
static unsigned int stripe_width()
{
return 4;
}
static constexpr unsigned int k_unroll()
{
return 8;
}
StdTransformsFixed<operand_type, result_type, 8, 12, 8> transforms = {};
StdTransformsFixed<operand_type, result_type, 8, 12, 8, true> transforms_quantized = {};
template<typename T>
static inline PerformanceParameters get_performance_parameters(const CPUInfo *ci)
{
if (std::is_same<T, int32_t>::value) {
switch (ci->get_cpu_model()) {
default:
return { 62.57, 4.08, 8.01 };
case CPUModel::A510:
return { 48.25, 3.53, 3.71 };
case CPUModel::V1:
return { 117.02, 4.98, 10.87 };
}
}
if (std::is_same<T, int8_t>::value) {
switch (ci->get_cpu_model()) {
default:
return { 62.53, 3.70, 0.50 };
case CPUModel::A510:
return { 48.22, 2.49, 0.29 };
case CPUModel::V1:
return { 116.76, 4.67, 0.60 };
}
}
return { 1.0 };
}
// Default to the generic kernel
kern_type kernel=a64_interleaved_s8s32_mmla_8x12;
cls_a64_interleaved_s8s32_mmla_8x12(const CPUInfo *)
{
}
};
} // namespace arm_gemm
#undef ARGLIST
#endif // __aarch64__
|
/*++
Copyright (C) 2019 3MF Consortium (Original Author)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Abstract: This is the class declaration of CBeamLattice
*/
#ifndef __LIB3MF_BEAMLATTICE
#define __LIB3MF_BEAMLATTICE
#include "lib3mf_interfaces.hpp"
#include "lib3mf_base.hpp"
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4250)
#endif
#include "Common/Mesh/NMR_Mesh.h"
#include "Model/Classes/NMR_ModelMeshBeamLatticeAttributes.h"
#include "Model/Classes/NMR_ModelMeshObject.h"
// Include custom headers here.
namespace Lib3MF {
namespace Impl {
/*************************************************************************************************************************
Class declaration of CBeamLattice
**************************************************************************************************************************/
class CBeamLattice : public virtual IBeamLattice, public virtual CBase {
private:
/**
* Put private members here.
*/
NMR::CMesh& m_mesh;
NMR::PModelMeshBeamLatticeAttributes m_pAttributes;
NMR::PModelMeshObject m_pMeshObject;
protected:
/**
* Put protected members here.
*/
public:
/**
* Put additional public members here. They will not be visible in the external API.
*/
CBeamLattice(NMR::PModelMeshObject pMeshObject, NMR::PModelMeshBeamLatticeAttributes pAttributes);
/**
* Public member functions to implement.
*/
Lib3MF_double GetMinLength ();
void SetMinLength (const Lib3MF_double dMinLength);
void GetClipping (eBeamLatticeClipMode & eClipMode, Lib3MF_uint32 & nResourceID);
void SetClipping (const eBeamLatticeClipMode eClipMode, const Lib3MF_uint32 nResourceID);
bool GetRepresentation(Lib3MF_uint32 & nResourceID);
void SetRepresentation(const Lib3MF_uint32 nResourceID);
Lib3MF_uint32 GetBeamCount ();
sLib3MFBeam GetBeam (const Lib3MF_uint32 nIndex);
Lib3MF_uint32 AddBeam (const sLib3MFBeam BeamInfo);
void SetBeam (const Lib3MF_uint32 nIndex, const sLib3MFBeam BeamInfo);
void SetBeams (const Lib3MF_uint64 nBeamInfoBufferSize, const sLib3MFBeam * pBeamInfoBuffer);
void GetBeams (Lib3MF_uint64 nBeamInfoBufferSize, Lib3MF_uint64* pBeamInfoNeededCount, sLib3MFBeam * pBeamInfoBuffer);
Lib3MF_uint32 GetBeamSetCount ();
IBeamSet * AddBeamSet ();
IBeamSet * GetBeamSet (const Lib3MF_uint32 nIndex);
};
} // namespace Impl
} // namespace Lib3MF
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#endif // __LIB3MF_BEAMLATTICE
|
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
//
// BinaryWriter.cpp : Defines the exported functions for the DLL application.
//
#include "stdafx.h"
#include "Basics.h"
#define DATAWRITER_EXPORTS // creating the exports here
#include "DataWriter.h"
#include "BinaryReader.h"
namespace Microsoft { namespace MSR { namespace CNTK {
// Destroy - cleanup and remove this class
// NOTE: this destroys the object, and it can't be used past this point
template <class ElemType>
void BinaryWriter<ElemType>::Destroy()
{
delete this;
}
// destructor - virtual so it gets called properly
template <class ElemType>
BinaryWriter<ElemType>::~BinaryWriter()
{
// clear the section references, they will be delted by the sectionFile destructors
m_sections.clear();
// delete all the sectionfiles
for (auto pair : m_secFiles)
{
delete pair.second;
}
m_secFiles.clear();
}
// Init - Writer Initialize for multiple data sets/sections
// config - [in] configuration parameters for the datawriter
// Sample format below for BinaryWriter:
//writer=[
// # writer to use, can implement both reader and writer
// writerType=BinaryWriter
// miniBatchMode=Partial
// randomize=None
// wfile=c:\speech\mnist\mnist_test.bin
// #wsize - inital size of the file in MB default to 256
// # has to be large enough for your dataset. the file will shrink to the actual size when closed.
// #wsize=256
// #wrecords - number of records we should allocate space for in the file
// # files cannot be expanded, so this should be large enough. If known modify this element in config before creating file
// wrecords=50000
// features=[
// dim=784
// start=1
// sectionType=data
// stats=[
// sectionType=stats
// elementSize=32
// compute={sum:count:mean:variance:stddev:max:min:range}
// ]
// ]
// labels=[
// dim=1
// # sizeof(unsigned) which is the label index type
// elementSize=4
// wref=features
// sectionType=labels
// mapping=[
// #redefine number of records for this section, since we don't need to save it for each data record
// wrecords=10
// #variable size so use an average string size
// elementSize=10
// sectionType=labelMapping
// ]
// category=[
// dim=10
// #elementSize=sizeof(ElemType) is default
// sectionType=categoryLabels
// ]
// labelType=Category
// ]
//
//]
template <class ElemType>
Section* BinaryWriter<ElemType>::CreateSection(const ScriptableObjects::IConfigRecord&, Section*, size_t, size_t)
{
InvalidArgument("BinaryWriter currently not implemented for BrainScript.");
// ...the reason being that the BinaryWriter needs the ConfigPath, which is also not available in BrainScript.
}
template <class ElemType>
Section* BinaryWriter<ElemType>::CreateSection(const ConfigParameters& config, Section* parentSection, size_t p_records, size_t p_windowSize)
{
// first check if we need to open a new section file
std::vector<std::wstring> sections;
// determine the element size, default to ElemType size
size_t elementSize = sizeof(ElemType);
if (config.ExistsCurrent(L"elementSize"))
{
elementSize = config(L"elementSize");
}
// get the number of records we should expect (max)
// if defined in previous levels same number will be used
size_t records = p_records;
if (config.ExistsCurrent(L"wrecords"))
{
records = config(L"wrecords");
}
if (records == 0)
{
InvalidArgument("Required config variable 'wrecords' missing from BinaryWriter configuration.");
}
size_t dim = 1; // default dimension (single item)
if (config.ExistsCurrent(L"dim"))
{
dim = config(L"dim");
}
// get the section type (used for caching)
SectionType sectionType = sectionTypeNull;
if (config.ExistsCurrent(L"sectionType"))
{
SectionType foundType = sectionTypeNull;
wstring type = config(L"sectionType");
for (int i = 0; i < sectionTypeMax; i++)
{
if (EqualCI(type, SectionTypeStrings[i]))
{
foundType = SectionType(i);
break;
}
}
// check to make sure it matched something
if (foundType == sectionTypeNull)
{
InvalidArgument("Invalid value for 'sectionType' in BinaryWriter configuration: %ls", type.c_str());
}
sectionType = foundType;
}
// calculate number of bytes = dim*elementSize*records
size_t dataOnlySize = records * elementSize * dim;
size_t dataSize = dataOnlySize + sectionHeaderMin;
// filename to use the one defined at this level, if there is none use the parent file
SectionFile* file = NULL;
if (config.ExistsCurrent(L"wfile"))
{
std::wstring wfile = config(L"wfile");
auto secFile = m_secFiles.find(wfile);
if (secFile != m_secFiles.end())
{
file = secFile->second;
}
else
{
// TODO: sanity check and use records as a clue of how big to make it
size_t initialSize = config(L"wsize", (size_t) 256); // default to 256MB if not provided
initialSize *= 1024 * 1024; // convert MB to bytes
if (initialSize < dataSize)
initialSize = dataSize * 5 / 4; // make the initalSize slightly larger than needed for data
file = new SectionFile(wfile, fileOptionsReadWrite, initialSize);
m_secFiles[wfile] = file;
parentSection = file->FileSection();
parentSection->SetElementCount(records);
parentSection->SetFileUniqueId(this->m_uniqueID);
}
}
else
{ // no file defined at this config level, use parent file
if (parentSection != NULL && parentSection->GetSectionFile() != NULL)
{
file = parentSection->GetSectionFile();
}
else if (sectionType != sectionTypeNull)
{
InvalidArgument("No filename (wfile) defined in BinaryWriter configuration.");
}
}
// determine file position if needed
size_t filePositionLast = 0;
size_t filePositionNext = 0;
if (file != NULL)
{
// get the next available position in the file (always on the end)
filePositionLast = file->GetFilePositionMax();
filePositionNext = file->RoundUp(filePositionLast);
// we have a gap, zero it out to keep the file clean
if (filePositionLast != filePositionNext)
{
size_t size = filePositionNext - filePositionLast;
size_t roundDown = file->RoundUp(filePositionLast - file->GetViewAlignment() - 1);
// need to get a veiw to zero out non-used bytes
void* view = file->GetView(roundDown, file->GetViewAlignment());
char* ptr = (char*) view + filePositionLast % file->GetViewAlignment();
memset(ptr, 0, size);
file->ReleaseView(view);
}
}
// get the new section name
std::string sectionName = config.ConfigName();
// get the window size, to see if we want to do separate element mapping
size_t windowSize = p_windowSize;
if (config.ExistsCurrent(L"windowSize"))
{
windowSize = config(L"windowSize");
}
MappingType mappingMain = windowSize ? mappingElementWindow : mappingParent;
MappingType mappingAux = windowSize ? mappingSection : mappingParent;
// now create the new section
Section* section = NULL;
switch (sectionType)
{
case sectionTypeNull:
// this happens for the original file header, nothing to do
// also used when multiple files are defined, but none at the base level
break;
case sectionTypeFile: // file header
// shouldn't occur, but same case as above
break;
case sectionTypeData: // data section
section = new Section(file, parentSection, filePositionNext, mappingMain, dataSize);
section->InitHeader(sectionTypeData, sectionName + ":Data Section", sectionDataFloat, sizeof(ElemType));
break;
case sectionTypeLabel: // label data
{
size_t elementSize = sizeof(LabelIdType);
dataSize = records * elementSize + sectionHeaderMin;
auto sectionLabel = new SectionLabel(file, parentSection, filePositionNext, mappingMain, dataSize);
SectionData dataType = sectionDataInt;
LabelKind labelKind = labelCategory; // default
if (config.Match(L"labelType", L"Regression"))
{
labelKind = labelRegression;
dataType = sectionDataFloat;
elementSize = sizeof(ElemType);
}
else if (config.Match(L"labelType", L"Category"))
{
// everything set already, default value
}
else
{
RuntimeError("Invalid type 'labelType' or missing in BinaryWriter configuration.");
}
// initialize the section header
sectionLabel->InitHeader(sectionTypeLabel, sectionName + ":Labels", dataType, (WORD) elementSize);
// initialize the special label header items
sectionLabel->SetLabelKind(labelKind);
sectionLabel->SetLabelDim(config(L"labelDim"));
section = sectionLabel;
break;
}
case sectionTypeLabelMapping: // label mapping table (array of strings)
section = new SectionString(file, parentSection, filePositionNext, mappingAux, dataSize);
section->InitHeader(sectionTypeLabelMapping, sectionName + ":Label Map", sectionDataStrings, 0); // declare variable length strings
section->SetFlags(flagAuxilarySection);
section->SetFlags(flagVariableSized);
break;
case sectionTypeStats: // data statistics
{
ConfigArray calcStats = config(L"compute");
records = calcStats.size();
elementSize = sizeof(NumericStatistics);
dataOnlySize = records * elementSize;
dataSize = dataOnlySize + sectionHeaderMin;
auto sectionStats = new SectionStats(file, parentSection, filePositionNext, mappingAux, dataSize);
sectionStats->InitHeader(sectionTypeStats, sectionName + ":Data Statistics", sectionDataStruct, sizeof(NumericStatistics)); // declare variable length strings
sectionStats->SetFlags(flagAuxilarySection);
section = sectionStats;
break;
}
case sectionTypeCategoryLabel:
section = new Section(file, parentSection, filePositionNext, mappingMain, dataSize);
section->InitHeader(sectionTypeCategoryLabel, sectionName + ":Category Labels", sectionDataFloat, sizeof(ElemType)); // declare variable length strings
break;
}
// set the rest of the header variables necessary
if (section == NULL)
{
// NULL or file section/already created
section = parentSection;
}
else
{
section->SetElementSize(elementSize);
section->SetElementsPerRecord(dim);
section->SetElementCount(records * dim);
section->SetSize(dataSize);
section->SetSizeAll(dataSize);
// windowSize is in records, convert to bytes
size_t dataWindowSize = windowSize ? windowSize * elementSize * dim : dataOnlySize;
// clamp it down to actual data size
dataWindowSize = min(dataOnlySize, dataWindowSize);
// now get the data pointer setup and allocate the view as necessary
bool auxSection = !!(section->GetFlags() & flagAuxilarySection);
section->EnsureElements(0, auxSection ? dataOnlySize : dataWindowSize);
// update the max file position for the next section
file->SetFilePositionMax(section->GetFilePosition() + dataSize);
// Add new section to parent
parentSection->AddSection(section);
}
// From here on down we have a fully usable section object
// now find the subsections and repeat
vector<std::wstring> subsections;
FindConfigNames(config, "sectionType", subsections);
// look for any children and create them as well
for (std::wstring subsection : subsections)
{
CreateSection(config(subsection), section, records, windowSize);
}
// wait until here so everything is mapped and valid in the object
if (sectionType == sectionTypeStats)
{
ConfigArray calcStats = config(L"compute");
((SectionStats*) section)->InitCompute(calcStats);
}
// add to section map
if (sectionType != sectionTypeFile && sectionType != sectionTypeNull)
{
std::wstring wsectionName = msra::strfun::utf16(sectionName);
// can't have identical names in a write configuration
if (m_sections.find(wsectionName) != m_sections.end())
{
RuntimeError("Identical section name appears twice:%s", sectionName.c_str());
}
m_sections[wsectionName] = section;
}
// validate the header (make sure it's sane)
if (section && file && !section->ValidateHeader(file->Writing()))
{
RuntimeError("Invalid header in file %ls, in header %ls\n", file->GetName().c_str(), section->GetName().c_str());
}
// return the now complete section
return section;
}
// Init - initialize the Binary writer
// config - the configuration for the binary writer
template <class ElemType>
template <class ConfigRecordType>
void BinaryWriter<ElemType>::InitFromConfig(const ConfigRecordType& config)
{
// initialize all the variables
m_recordCurrent = 0;
m_recordMax = config(L"wrecords", (size_t) 0);
m_traceLevel = config(L"traceLevel", 0);
m_uniqueID = (WORD) GetTickCount();
// get the configuration, this will recursively go down and create all subfiles/sections as well
CreateSection(config, NULL, m_recordMax);
}
// GetSections - Get the sections of the file
// sections - a map of section name to section. Data sepcifications from config file will be used to determine where and how to save data
template <class ElemType>
void BinaryWriter<ElemType>::GetSections(std::map<std::wstring, SectionType, nocase_compare>& sections)
{
for (auto pair : m_sections)
{
sections[pair.first] = pair.second->GetSectionType();
}
}
// SaveData - save data in the file/files
// recordStart - Starting record number, will be > datasetSize for multiple passes
// matricies - a map of section name (section:subsection) to data pointer. Data sepcifications from config file will be used to determine where and how to save data
// numRecords - number of records we are saving, can be zero if not applicable
// datasetSize - Size of the dataset
// byteVariableSized - for variable sized data, size of current block to be written, zero when not used, or ignored if not variable sized data
// returns: true if more data is desired, false if no more data is required (signal that file may be closed)
template <class ElemType>
bool BinaryWriter<ElemType>::SaveData(size_t recordStart, const std::map<std::wstring, void*, nocase_compare>& matrices, size_t numRecords, size_t datasetSize, size_t byteVariableSized)
{
// allow restarting a writing session. This is used primarily for writing entire sections at once
if (recordStart == 0)
{
m_recordCurrent = recordStart;
}
// make sure there are no gaps in the writing
if (m_recordCurrent != recordStart)
{
RuntimeError("Caching with binary writer, records skip from %ld to %ld", m_recordCurrent, recordStart);
}
bool written = false;
for (auto pair : m_sections)
{
Section* section = pair.second;
written = section->SaveData(recordStart, matrices, numRecords, datasetSize, byteVariableSized) || written;
}
// the current record we expect to write next
m_recordCurrent = recordStart + numRecords;
return written;
}
// SaveMapping - save a map into the file
// saveId - name of the section to save into
// labelMapping - map we are saving to the file
template <class ElemType>
void BinaryWriter<ElemType>::SaveMapping(std::wstring saveId, const std::map<typename BinaryWriter<ElemType>::LabelIdType, typename BinaryWriter<ElemType>::LabelType>& labelMapping)
{
Section* section = m_sections[saveId];
if (section->GetSectionType() == sectionTypeLabelMapping)
{
auto sectionString = (SectionString*) section;
sectionString->SetLabelMapping(labelMapping);
}
}
// instantiate all the combinations we expect to be used
template class BinaryWriter<double>;
template class BinaryWriter<float>;
} } }
|
/*
* Copyright (c) 2019 The Fuchsia Authors
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "src/connectivity/wlan/drivers/third_party/broadcom/brcmfmac/sim/sim_fw.h"
#include <arpa/inet.h>
#include <fuchsia/hardware/wlan/info/c/banjo.h>
#include <fuchsia/hardware/wlanif/c/banjo.h>
#include <fuchsia/wlan/common/c/banjo.h>
#include <fuchsia/wlan/ieee80211/cpp/fidl.h>
#include <fuchsia/wlan/internal/c/banjo.h>
#include <zircon/assert.h>
#include <zircon/compiler.h>
#include <cstddef>
#include <memory>
#include <optional>
#include <third_party/bcmdhd/crossdriver/dhd.h>
#include <third_party/bcmdhd/crossdriver/wlioctl.h>
#include <wlan/common/mac_frame.h>
#include "src/connectivity/wlan/drivers/third_party/broadcom/brcmfmac/bits.h"
#include "src/connectivity/wlan/drivers/third_party/broadcom/brcmfmac/brcm_hw_ids.h"
#include "src/connectivity/wlan/drivers/third_party/broadcom/brcmfmac/common.h"
#include "src/connectivity/wlan/drivers/third_party/broadcom/brcmfmac/debug.h"
#include "src/connectivity/wlan/drivers/third_party/broadcom/brcmfmac/fweh.h"
#include "src/connectivity/wlan/drivers/third_party/broadcom/brcmfmac/fwil.h"
#include "src/connectivity/wlan/drivers/third_party/broadcom/brcmfmac/sim/sim.h"
#include "third_party/bcmdhd/crossdriver/include/proto/802.11.h"
#include "zircon/errors.h"
namespace wlan::brcmfmac {
namespace wlan_ieee80211 = ::fuchsia::wlan::ieee80211;
#define SIM_FW_CHK_CMD_LEN(dcmd_len, exp_len) \
(((dcmd_len) < (exp_len)) ? ZX_ERR_INVALID_ARGS : ZX_OK)
#ifdef USE_MFG_FW
const char* kFirmwareVer =
"wl0: Oct 5 2018 04:50:34 version 7.45.96.34 (r783496 WLTEST) FWID 01-df2d9ead";
#else
const char* kFirmwareVer = "wl0: Sep 10 2018 16:37:38 version 7.35.79 (r487924) FWID 01-c76ab99a";
#endif
const char* kFirmwareCap =
"ap sta wme 802.11d 802.11h rm cqa cac dualband ampdu ampdu_tx ampdu_rx amsdurx tdls "
"radio_pwrsave btamp p2p proptxstatus mchan wds dwds p2po anqpo vht-prop-rates dfrts "
"txpwrcache stbc-tx stbc-rx-1ss epno pfnx wnm bsstrans mfp ndoe rssi_mon cptlv-4 extsae";
struct IovarMetadata {
std::string name_;
std::optional<size_t> value_len_;
IovarSetHandler set_handler_;
IovarGetHandler get_handler_;
// Set this field to the offset of the member in sim_iface_entry_t if using the generic
// IovarIfaceVarGet/IovarIfaceVarSet methods
std::optional<size_t> ifentry_offset = std::nullopt;
// Set this field to the address of the member variable if using the generic IovarGet/IovarSet
// methods
std::optional<void*> var_addr = std::nullopt;
};
/* Steps to add an iovar handler:
*
* 1. If the iovar corresponds to a member variable in SimFirmware, use the generic handlers,
* IovarSet(), IovarGet() and set the size and address of the variable OR
* if the iovar corresponds to a member in sim_iface_entry_t , use the generic handlers,
* IovarIfaceVarSet(), IovarIfaceVarGet() and set the size and offset of the variable.
* 2. Or else define the handler function as SimFirmware::Iovar<Name>{Set, Get} in sim-fw.{h, cc}.
* 3. If the iovar exists in kIovarInfoTable: modify the corresponding entry by replacing the
* nullptr with your new handler.
*/
zx_status_t SimFirmware::SetupIovarTable() {
// The table initialized with information of all iovars. Note: passing std::nullopt to the second
// field means that the size check is customized by handler functions, passing std::nullptr to the
// third or the fourth field means that the handler is not supported.
static const IovarMetadata kIovarInfoTable[] = {
{"allmulti", sizeof(sim_iface_entry_t::allmulti), &SimFirmware::IovarIfaceVarSet,
&SimFirmware::IovarIfaceVarGet, offsetof(sim_iface_entry_t, allmulti)},
{"ampdu_ba_wsize", sizeof(uint32_t), &SimFirmware::IovarSet, &SimFirmware::IovarGet,
std::nullopt, &du_ba_wsize_},
{"arp_ol", sizeof(uint32_t), &SimFirmware::IovarSet, &SimFirmware::IovarGet, std::nullopt,
&arp_ol_},
{"arpoe", sizeof(uint32_t), &SimFirmware::IovarSet, &SimFirmware::IovarGet, std::nullopt,
&arpoe_},
{"assoc_info", sizeof(brcmf_cfg80211_assoc_ielen_le), nullptr,
&SimFirmware::IovarAssocInfoGet},
{"assoc_mgr_cmd", sizeof(assoc_mgr_cmd_t), &SimFirmware::IovarAssocMgrCmdSet, nullptr},
{"assoc_resp_ies", std::nullopt, nullptr, &SimFirmware::IovarAssocRespIesGet},
{"assoc_retry_max", sizeof(assoc_max_retries_), &SimFirmware::IovarSet,
&SimFirmware::IovarGet, std::nullopt, &assoc_max_retries_},
{"auth", sizeof(sim_iface_entry_t::auth_type), &SimFirmware::IovarIfaceVarSet,
&SimFirmware::IovarIfaceVarGet, offsetof(sim_iface_entry_t, auth_type)},
{"bcn_timeout", sizeof(uint32_t), &SimFirmware::IovarSet, &SimFirmware::IovarGet,
std::nullopt, &beacon_timeout_},
{"bss", sizeof(brcmf_bss_ctrl), &SimFirmware::IovarBssSet, nullptr},
{"cap", strlen(kFirmwareCap) + 1, nullptr, &SimFirmware::IovarCapGet},
{"chanspec", sizeof(sim_iface_entry_t::chanspec), &SimFirmware::IovarChanspecSet,
&SimFirmware::IovarIfaceVarGet, offsetof(sim_iface_entry_t, chanspec)},
{"country", sizeof(brcmf_fil_country_le), &SimFirmware::IovarSet, &SimFirmware::IovarGet,
std::nullopt, &country_code_},
{"crash", sizeof(uint32_t), &SimFirmware::IovarCrashSet, nullptr},
{"cur_etheraddr", ETH_ALEN, &SimFirmware::IovarCurEtheraddrSet,
&SimFirmware::IovarCurEtheraddrGet},
{"escan", sizeof(brcmf_escan_params_le), &SimFirmware::IovarEscanSet, nullptr},
{"interface_remove", 0, &SimFirmware::IovarInterfaceRemoveSet, nullptr},
{"join", sizeof(brcmf_ext_join_params_le), &SimFirmware::IovarJoinSet, nullptr},
{"mchan", sizeof(mchan_), &SimFirmware::IovarSet, &SimFirmware::IovarGet, std::nullopt,
&mchan_},
{"mpc", sizeof(mpc_), &SimFirmware::IovarMpcSet, &SimFirmware::IovarGet, std::nullopt, &mpc_},
{"ndoe", sizeof(ndoe_), &SimFirmware::IovarSet, &SimFirmware::IovarGet, std::nullopt, &ndoe_},
{"nmode", sizeof(uint32_t), nullptr, &SimFirmware::IovarNmodeGet},
{"pfn_macaddr", ETH_ALEN, &SimFirmware::IovarPfnMacaddrSet, &SimFirmware::IovarPfnMacaddrGet},
{"rrm", sizeof(uint32_t), nullptr, &SimFirmware::IovarRrmGet},
{"rxchain", sizeof(uint32_t), nullptr, &SimFirmware::IovarRxchainGet},
{"snr", sizeof(int32_t), nullptr, &SimFirmware::IovarSnrGet},
{"ssid", sizeof(brcmf_ssid_le), &SimFirmware::IovarSsidSet, nullptr},
{"stbc_tx", sizeof(int32_t), &SimFirmware::IovarStbcTxSet, &SimFirmware::IovarStbcTxGet},
{"tlv", sizeof(sim_iface_entry_t::tlv), &SimFirmware::IovarIfaceVarSet,
&SimFirmware::IovarIfaceVarGet, offsetof(sim_iface_entry_t, tlv)},
{"txstreams", sizeof(txstreams_), &SimFirmware::IovarTxstreamsSet, &SimFirmware::IovarGet,
std::nullopt, &txstreams_},
{"ver", strlen(kFirmwareVer) + 1, nullptr, &SimFirmware::IovarVerGet},
{"vht_mode", sizeof(uint32_t), nullptr, &SimFirmware::IovarVhtModeGet},
{"wme_ac_sta", sizeof(edcf_acparam_t) * 4, nullptr, &SimFirmware::IovarWmeAcStaGet},
{"wme_apsd", sizeof(uint32_t), nullptr, &SimFirmware::IovarWmeApsdGet},
{"wnm", sizeof(wnm_), &SimFirmware::IovarSet, &SimFirmware::IovarGet, std::nullopt, &wnm_},
{"wpa_auth", sizeof(sim_iface_entry_t::wpa_auth), &SimFirmware::IovarIfaceVarSet,
&SimFirmware::IovarIfaceVarGet, offsetof(sim_iface_entry_t, wpa_auth)},
{"wsec", sizeof(sim_iface_entry_t::wsec), &SimFirmware::IovarIfaceVarSet,
&SimFirmware::IovarIfaceVarGet, offsetof(sim_iface_entry_t, wsec)},
{"wsec_key", sizeof(brcmf_wsec_key_le), &SimFirmware::IovarWsecKeySet,
&SimFirmware::IovarWsecKeyGet},
{"wstats_counters", sizeof(wl_wstats_cnt_t), nullptr, &SimFirmware::IovarWstatsCountersGet},
};
for (const auto& it : kIovarInfoTable) {
iovar_table_.insert({it.name_, SimIovar(it.value_len_, this, it.set_handler_, it.get_handler_,
it.ifentry_offset, it.var_addr)});
}
return ZX_OK;
}
SimFirmware::SimFirmware(brcmf_simdev* simdev) : simdev_(simdev), hw_(simdev->env) {
// Configure the chanspec encode/decoder
d11_inf_.io_type = kIoType;
brcmu_d11_attach(&d11_inf_);
// Configure the (simulated) hardware => (simulated) firmware callbacks
SimHardware::EventHandlers handlers = {
.rx_handler = std::bind(&SimFirmware::Rx, this, std::placeholders::_1, std::placeholders::_2),
};
hw_.SetCallbacks(handlers);
country_code_ = {};
// The real FW always creates the first interface
struct brcmf_mbss_ssid_le default_mbss = {};
if (HandleIfaceTblReq(true, &default_mbss, nullptr, 0) != ZX_OK) {
ZX_PANIC("Unable to create default interface");
}
if (SetupIovarTable() != ZX_OK) {
ZX_PANIC("Unable to setup Iovar Table");
}
}
SimFirmware::~SimFirmware() = default;
simulation::StationIfc* SimFirmware::GetHardwareIfc() { return &hw_; }
void SimFirmware::GetChipInfo(uint32_t* chip, uint32_t* chiprev) {
*chip = BRCM_CC_4356_CHIP_ID;
*chiprev = 2;
}
int32_t SimFirmware::GetPM() { return power_mode_; }
zx_status_t SimFirmware::BusPreinit() {
// Currently nothing to do
return ZX_OK;
}
void SimFirmware::BusStop() { BRCMF_ERR("%s unimplemented", __FUNCTION__); }
// Returns a buffer that can be used for BCDC-formatted communications, with the requested
// payload size and an initialized BCDC header. "data_offset" represents any signalling offset
// (in words) and "offset_out" represents the offset of the payload within the returned buffer.
std::unique_ptr<std::vector<uint8_t>> SimFirmware::CreateBcdcBuffer(int16_t ifidx,
size_t requested_size,
size_t* offset_out) {
size_t header_size = sizeof(brcmf_proto_bcdc_header);
size_t total_size = header_size + requested_size;
auto buf = std::make_unique<std::vector<uint8_t>>(total_size);
auto header = reinterpret_cast<brcmf_proto_bcdc_header*>(buf->data());
header->flags = (BCDC_PROTO_VER << BCDC_FLAG_VER_SHIFT) & BCDC_FLAG_VER_MASK;
header->priority = 0xff & BCDC_PRIORITY_MASK;
header->flags2 = 0;
BCDC_SET_IF_IDX(header, ifidx);
// Data immediately follows the header
header->data_offset = 0;
*offset_out = header_size;
return buf;
}
// Set or get the value of an iovar. The format of the message is a null-terminated string
// containing the iovar name, followed by the value to assign to that iovar.
zx_status_t SimFirmware::BcdcVarOp(uint16_t ifidx, brcmf_proto_bcdc_dcmd* dcmd, uint8_t* data,
size_t len, bool is_set) {
zx_status_t status = ZX_OK;
if (is_set) {
// The command consists of a NUL-terminated name, followed by a value.
const char* const name_begin = reinterpret_cast<char*>(data);
const char* const name_end = static_cast<const char*>(memchr(name_begin, '\0', dcmd->len));
if (name_end == nullptr) {
BRCMF_DBG(SIM, "SET_VAR: iovar name not null-terminated");
return ZX_ERR_INVALID_ARGS;
}
const char* const value_begin = name_end + 1;
const size_t value_size = dcmd->len - (value_begin - name_begin);
// Since we're passing the value as a buffer down to users that may expect to be able to cast
// directly into it, make a suitably aligned copy here.
static constexpr auto align_val = static_cast<std::align_val_t>(alignof(std::max_align_t));
const auto aligned_delete = [](char* buffer) { operator delete[](buffer, align_val); };
std::unique_ptr<char, decltype(aligned_delete)> value_buffer(
static_cast<char*>(operator new[](value_size, align_val)), aligned_delete);
std::memcpy(value_buffer.get(), value_begin, value_size);
// IovarsSet returns the input unchanged
status = IovarsSet(ifidx, name_begin, value_buffer.get(), value_size, &dcmd->status);
} else {
// IovarsGet modifies the buffer in-place
status = IovarsGet(ifidx, reinterpret_cast<const char*>(data), data, dcmd->len, &dcmd->status);
if (dcmd->status != BCME_OK) {
dcmd->flags |= BCDC_DCMD_ERROR;
}
BRCMF_DBG(SIM, "dcmd->status=%s dcmd->flags=0x%08x", brcmf_fil_get_errstr(dcmd->status),
dcmd->flags);
}
if (status == ZX_OK || status == ZX_ERR_IO_REFUSED) {
if (dcmd->status != BCME_OK)
dcmd->flags |= BCDC_DCMD_ERROR;
bcdc_response_.Set(reinterpret_cast<uint8_t*>(dcmd), len);
} else {
// Return empty message on failure
bcdc_response_.Clear();
}
return status;
}
// Process a TX CTL message. These have a BCDC header, followed by a payload that is determined
// by the type of command.
zx_status_t SimFirmware::BusTxCtl(unsigned char* msg, unsigned int len) {
brcmf_proto_bcdc_dcmd* dcmd;
constexpr size_t hdr_size = sizeof(struct brcmf_proto_bcdc_dcmd);
uint32_t value;
uint32_t ifidx;
if (len < hdr_size) {
BRCMF_DBG(SIM, "Message length (%u) smaller than BCDC header size (%zd)", len, hdr_size);
return ZX_ERR_INVALID_ARGS;
}
dcmd = reinterpret_cast<brcmf_proto_bcdc_dcmd*>(msg);
// The variable-length payload immediately follows the header
uint8_t* data = reinterpret_cast<uint8_t*>(dcmd) + hdr_size;
size_t data_len = len - hdr_size;
if (dcmd->len > data_len) {
BRCMF_DBG(SIM, "BCDC total message length (%zd) exceeds buffer size (%u)", dcmd->len + hdr_size,
len);
// The real firmware allows the true buffer size (dcmd->len) to exceed the length of the txctl
// itself (len - hdr_size). For an iovar get, we know this is allowed, so the sim firmware
// should let such a call through.
if (dcmd->cmd != BRCMF_C_GET_VAR) {
return ZX_ERR_INVALID_ARGS;
}
}
// Retrieve ifidx from the command and validate if the corresponding
// IF entry was previously allocated.
ifidx = BCDC_DCMD_IFIDX(dcmd->flags);
if (ifidx >= kMaxIfSupported || !iface_tbl_[ifidx].allocated) {
BRCMF_DBG(SIM, "IF idx: %d invalid or not allocated", ifidx);
return ZX_ERR_INVALID_ARGS;
}
zx_status_t status;
bcme_status_t fw_err;
if (err_inj_.CheckIfErrInjCmdEnabled(dcmd->cmd, &status, &fw_err, ifidx)) {
if (status == ZX_OK) {
// If the transmission status is ZX_OK, customize the firmware error code which will be
// sent back through bcdc response.
if (fw_err != BCME_OK) {
dcmd->flags |= BCDC_DCMD_ERROR;
}
dcmd->status = fw_err;
bcdc_response_.Set(msg, len);
}
// If the transmission status is not ZX_OK, return the error for this command transmission.
return status;
}
// If an err event has been injected for this command, then send event to driver and return.
brcmf_fweh_event_code ecode;
brcmf_fweh_event_status_t estatus;
status_code_t reason;
uint16_t flags;
if (err_inj_.CheckIfErrEventInjCmdEnabled(dcmd->cmd, ecode, estatus, reason, flags, ifidx)) {
SendEventToDriver(0, nullptr, ecode, estatus, ifidx, nullptr, flags, reason, kZeroMac,
kAssocEventDelay);
return ZX_OK;
}
status = ZX_OK;
switch (dcmd->cmd) {
// Get/Set a firmware IOVAR. This message is comprised of a NULL-terminated string
// for the variable name, followed by the value to assign to it.
case BRCMF_C_SET_VAR:
case BRCMF_C_GET_VAR:
return BcdcVarOp(ifidx, dcmd, data, len, dcmd->cmd == BRCMF_C_SET_VAR);
break;
case BRCMF_C_GET_BANDLIST: {
const uint32_t bandlist[] = {
2, // Number of bands
WLC_BAND_2G,
WLC_BAND_5G,
};
if ((status = SIM_FW_CHK_CMD_LEN(dcmd->len, sizeof(bandlist))) == ZX_OK) {
memcpy(data, bandlist, sizeof(bandlist));
}
break;
}
case BRCMF_C_GET_REVINFO: {
struct brcmf_rev_info_le rev_info;
hw_.GetRevInfo(&rev_info);
if ((status = SIM_FW_CHK_CMD_LEN(dcmd->len, sizeof(rev_info))) == ZX_OK) {
memcpy(data, &rev_info, sizeof(rev_info));
}
break;
}
case BRCMF_C_GET_VERSION: {
// GET_VERSION is a bit of a misnomer. It's really the 802.11 supported spec
// (e.g., n or ac).
if ((status = SIM_FW_CHK_CMD_LEN(dcmd->len, sizeof(kIoType))) == ZX_OK) {
std::memcpy(data, &kIoType, sizeof(kIoType));
}
break;
}
case BRCMF_C_GET_GET_PKTCNTS: {
if (!iface_tbl_[kClientIfidx].allocated) {
BRCMF_ERR("Client iface has not been allocated.");
return ZX_ERR_BAD_STATE;
}
// Fake packet counter arbitrary values.
const brcmf_pktcnt_le sim_pktcnt = {
.rx_good_pkt = 5,
.rx_bad_pkt = 4,
.tx_good_pkt = 3,
.tx_bad_pkt = 2,
.rx_ocast_good_pkt = 1,
};
if ((status = SIM_FW_CHK_CMD_LEN(dcmd->len, sizeof(brcmf_pktcnt_le))) == ZX_OK) {
std::memcpy(data, &sim_pktcnt, sizeof(brcmf_pktcnt_le));
}
break;
}
case BRCMF_C_SET_PASSIVE_SCAN: {
// Specify whether to use a passive scan by default (instead of an active scan)
if ((status = SIM_FW_CHK_CMD_LEN(dcmd->len, sizeof(uint32_t))) == ZX_OK) {
value = *(reinterpret_cast<uint32_t*>(data));
default_passive_scan_ = value > 0;
}
break;
}
case BRCMF_C_SET_PROMISC:
// Set promiscuous mode
if ((status = SIM_FW_CHK_CMD_LEN(dcmd->len, sizeof(uint32_t))) == ZX_OK) {
value = *(reinterpret_cast<uint32_t*>(data));
ZX_ASSERT_MSG(!value, "Promiscuous mode not supported in simulator");
}
break;
case BRCMF_C_SET_SCAN_PASSIVE_TIME:
if ((status = SIM_FW_CHK_CMD_LEN(dcmd->len, sizeof(default_passive_time_))) == ZX_OK) {
default_passive_time_ = *(reinterpret_cast<uint32_t*>(data));
}
break;
case BRCMF_C_SET_PM:
if ((status = SIM_FW_CHK_CMD_LEN(dcmd->len, sizeof(power_mode_))) == ZX_OK) {
power_mode_ = *(reinterpret_cast<int32_t*>(data));
}
break;
case BRCMF_C_GET_PM:
if ((status = SIM_FW_CHK_CMD_LEN(dcmd->len, sizeof(power_mode_))) == ZX_OK) {
std::memcpy(data, &power_mode_, sizeof(power_mode_));
}
break;
case BRCMF_C_SET_SCAN_CHANNEL_TIME:
case BRCMF_C_SET_SCAN_UNASSOC_TIME:
BRCMF_DBG(SIM, "Ignoring firmware message %d", dcmd->cmd);
break;
case BRCMF_C_DISASSOC: {
if ((status = SIM_FW_CHK_CMD_LEN(dcmd->len, sizeof(brcmf_scb_val_le))) == ZX_OK) {
if (iface_tbl_[kClientIfidx].allocated && kClientIfidx == ifidx) {
// Initiate Disassoc from AP
auto scb_val = reinterpret_cast<brcmf_scb_val_le*>(data);
auto req_bssid = reinterpret_cast<common::MacAddr*>(scb_val->ea);
if (!assoc_state_.opts) {
BRCMF_DBG(SIM, "BRCMF_C_DISASSOC issued without assoc - ignore");
break;
}
common::MacAddr bssid(assoc_state_.opts->bssid);
ZX_ASSERT(bssid == *req_bssid);
DisassocLocalClient(static_cast<wlan_ieee80211::ReasonCode>(scb_val->val));
} else if (softap_ifidx_ != std::nullopt && softap_ifidx_ == ifidx) {
BRCMF_ERR("This iovar is not expected to be used on softAP iface.");
return ZX_ERR_IO_REFUSED;
}
} else {
// Triggered by link down event in driver (no data)
if (assoc_state_.state == AssocState::ASSOCIATED) {
SetAssocState(AssocState::NOT_ASSOCIATED);
}
status = ZX_OK;
}
break;
}
case BRCMF_C_SCB_DEAUTHENTICATE_FOR_REASON: {
if ((status = SIM_FW_CHK_CMD_LEN(dcmd->len, sizeof(brcmf_scb_val_le))) == ZX_OK) {
status = ZX_ERR_IO;
if (softap_ifidx_ != std::nullopt && softap_ifidx_ == ifidx) {
auto scb_val = reinterpret_cast<brcmf_scb_val_le*>(data);
auto req_mac = reinterpret_cast<common::MacAddr*>(scb_val->ea);
auto client = FindClient(*req_mac);
if (client) {
// Deauthenticate also disassocs the client
SendEventToDriver(0, nullptr, BRCMF_E_DEAUTH, BRCMF_E_STATUS_SUCCESS,
softap_ifidx_.value(), nullptr, 0, 0, *req_mac);
SendEventToDriver(0, nullptr, BRCMF_E_DISASSOC, BRCMF_E_STATUS_SUCCESS,
softap_ifidx_.value(), nullptr, 0, 0, *req_mac);
iface_tbl_[softap_ifidx_.value()].ap_config.clients.remove(client);
status = ZX_OK;
}
}
}
break;
}
case BRCMF_C_SET_ROAM_TRIGGER:
case BRCMF_C_SET_ROAM_DELTA:
break;
case BRCMF_C_UP:
// The value in the IOVAR does not matter (according to Broadcom)
// TODO(karthikrish) Use dev_is_up_ to disable Tx, Rx, etc.
dev_is_up_ = true;
break;
case BRCMF_C_DOWN: {
// The value in the IOVAR does not matter (according to Broadcom)
// If any of the IFs are operational (i.e., client is associated or
// softap is started) disconnect as appropriate.
if (softap_ifidx_ != std::nullopt) {
StopSoftAP(softap_ifidx_.value());
}
DisassocLocalClient(wlan_ieee80211::ReasonCode::LEAVING_NETWORK_DISASSOC);
dev_is_up_ = false;
break;
}
case BRCMF_C_SET_INFRA:
if ((status = SIM_FW_CHK_CMD_LEN(dcmd->len, sizeof(uint32_t))) == ZX_OK) {
iface_tbl_[ifidx].ap_config.infra_mode = *(reinterpret_cast<uint32_t*>(data));
}
break;
case BRCMF_C_SET_AP:
if ((status = SIM_FW_CHK_CMD_LEN(dcmd->len, sizeof(uint32_t))) == ZX_OK) {
value = *(reinterpret_cast<uint32_t*>(data));
#ifdef USE_MFG_FW
// Manufacturer firmware does not allow turning off AP if it is already off
if (!value && !iface_tbl_[ifidx].ap_mode) {
status = ZX_ERR_IO_REFUSED;
break;
}
#endif
if (value) {
ZX_ASSERT_MSG(iface_tbl_[ifidx].ap_config.infra_mode, "Only Infra mode AP is supported");
iface_tbl_[ifidx].ap_mode = true;
} else
iface_tbl_[ifidx].ap_mode = false;
softap_ifidx_ = std::nullopt;
}
break;
case BRCMF_C_SET_BCNPRD:
if ((status = SIM_FW_CHK_CMD_LEN(dcmd->len, sizeof(uint32_t))) == ZX_OK) {
// Beacon period
iface_tbl_[ifidx].ap_config.beacon_period = *(reinterpret_cast<uint32_t*>(data));
}
break;
case BRCMF_C_SET_DTIMPRD:
if ((status = SIM_FW_CHK_CMD_LEN(dcmd->len, sizeof(uint32_t))) == ZX_OK) {
// DTIM
iface_tbl_[ifidx].ap_config.dtim_period = *(reinterpret_cast<uint32_t*>(data));
}
break;
case BRCMF_C_SET_FAKEFRAG:
if ((status = SIM_FW_CHK_CMD_LEN(dcmd->len, sizeof(uint32_t))) == ZX_OK) {
// fakefrag
fakefrag_ = *(reinterpret_cast<uint32_t*>(data));
}
break;
case BRCMF_C_GET_FAKEFRAG:
if ((status = SIM_FW_CHK_CMD_LEN(dcmd->len, sizeof(uint32_t))) == ZX_OK) {
// fakefrag
std::memcpy(data, &fakefrag_, sizeof(uint32_t));
}
break;
case BRCMF_C_SET_SSID: {
if ((status = SIM_FW_CHK_CMD_LEN(dcmd->len, sizeof(brcmf_join_params))) == ZX_OK) {
auto join_params = (reinterpret_cast<brcmf_join_params*>(data));
if (iface_tbl_[ifidx].ap_mode == true) {
iface_tbl_[ifidx].ap_config.ssid = join_params->ssid_le;
if (join_params->ssid_le.SSID_len) {
// non-zero SSID - assume AP start
ZX_ASSERT(iface_tbl_[ifidx].ap_config.ap_started == false);
// Schedule a Link Event to be sent to driver (simulating behviour
// in real HW).
ScheduleLinkEvent(kStartAPLinkEventDelay, ifidx);
iface_tbl_[ifidx].ap_config.ap_started = true;
softap_ifidx_ = ifidx;
// Set the channel to the value specified in "chanspec" iovar
wlan_channel_t channel;
chanspec_to_channel(&d11_inf_, iface_tbl_[ifidx].chanspec, &channel);
hw_.SetChannel(channel);
// Set the auth_type of softap to OPEN.
iface_tbl_[ifidx].auth_type = BRCMF_AUTH_MODE_OPEN;
// And Enable Rx
hw_.EnableRx();
// Send the AP_STARTED event after a delay
SendEventToDriver(0, nullptr, BRCMF_E_AP_STARTED, BRCMF_E_STATUS_SUCCESS,
softap_ifidx_.value(), nullptr, 0, 0, kZeroMac, kApStartedEventDelay);
} else {
// AP stop
// Note that SoftAP may have been only partially started (maybe one
// of the iovars in the sequence fails).
StopSoftAP(ifidx);
BRCMF_DBG(SIM, "AP Stop processed");
}
} else {
// When iface_tbl_[ifidx].ap_mode == false, start an association
ZX_ASSERT(join_params->params_le.chanspec_num == 1);
if (ifidx != kClientIfidx) {
BRCMF_ERR("Not starting an assoc on client iface.");
return ZX_ERR_INVALID_ARGS;
}
// This is a start point of authentication and association operation, make sure the client
// iface is allocated.
if (!iface_tbl_[kClientIfidx].allocated) {
BRCMF_ERR("client iface has not been allocated.");
return ZX_ERR_BAD_STATE;
}
if (scan_state_.state == ScanState::SCANNING) {
BRCMF_DBG(SIM, "Scan in progress, aborting scan.");
hw_.RequestCallback(
std::bind(&SimFirmware::ScanComplete, this, BRCMF_E_STATUS_NEWASSOC),
kAbortScanDelay);
}
auto assoc_opts = std::make_unique<AssocOpts>();
wlan_channel_t channel;
chanspec_to_channel(&d11_inf_, join_params->params_le.chanspec_list[0], &channel);
iface_tbl_[ifidx].chanspec = join_params->params_le.chanspec_list[0];
memcpy(assoc_opts->bssid.byte, join_params->params_le.bssid, ETH_ALEN);
assoc_opts->ssid.len = join_params->ssid_le.SSID_len;
memcpy(assoc_opts->ssid.data, join_params->ssid_le.SSID,
wlan_ieee80211::MAX_SSID_BYTE_LEN);
AssocInit(std::move(assoc_opts), channel);
BRCMF_DBG(SIM, "Auth start from C_SET_SSID");
// Schedule AuthStart to break the call chain for SAE authentication.
hw_.RequestCallback(std::bind(&SimFirmware::AuthStart, this), zx::msec(0));
}
}
break;
}
case BRCMF_C_GET_RSSI: {
if ((status = SIM_FW_CHK_CMD_LEN(dcmd->len, sizeof(int32_t))) == ZX_OK) {
int32_t rssi = -20;
std::memcpy(data, &rssi, sizeof(rssi));
}
break;
}
case BRCMF_C_SCAN: {
// For now this command is not used to start any kind of scan, the iovar "escan" is the entry
// of scan operation. This command is now only used to abort an escan when channel[0] in the
// parameter is -1.
auto scan_params = (reinterpret_cast<brcmf_scan_params_le*>(data));
ZX_ASSERT_MSG(scan_params->channel_list[0] == static_cast<uint16_t>(-1),
"BRCMF_C_SCAN should only be used for aborting an escan now.");
// Abort the scan. If there is no scan in progress, this becomes a nop.
if (scan_state_.state == ScanState::SCANNING) {
hw_.RequestCallback(std::bind(&SimFirmware::ScanComplete, this, BRCMF_E_STATUS_ABORT),
kAbortScanDelay);
}
break;
}
default:
BRCMF_DBG(SIM, "Unimplemented firmware message %d", dcmd->cmd);
return ZX_ERR_NOT_SUPPORTED;
}
if (status == ZX_OK) {
bcdc_response_.Set(msg, len);
}
return status;
}
zx_status_t SimFirmware::BusTxData(struct brcmf_netbuf* netbuf) {
if (netbuf->len < BCDC_HEADER_LEN + sizeof(ethhdr)) {
BRCMF_DBG(SIM, "Data netbuf (%u) smaller than BCDC + ethernet header %lu\n", netbuf->len,
BCDC_HEADER_LEN + sizeof(ethhdr));
return ZX_ERR_INVALID_ARGS;
}
// Get ifidx from bcdc header
brcmf_proto_bcdc_header* bcdc_header = (struct brcmf_proto_bcdc_header*)(netbuf);
uint16_t ifidx = BCDC_GET_IF_IDX(bcdc_header);
// For now we only support data transmission for client iface, another logic path should be added
// if we need to support data transmission for softap iface.
ZX_ASSERT_MSG(ifidx == kClientIfidx,
"Only data transmission for client iface is supported for now.");
// Ignore the BCDC Header
ethhdr* ethFrame = reinterpret_cast<ethhdr*>(netbuf->data + BCDC_HEADER_LEN);
// Build MAC frame
simulation::SimQosDataFrame dataFrame{};
// we can't send data frames if we aren't associated with anything
if (assoc_state_.opts == nullptr) {
return ZX_ERR_BAD_STATE;
}
// IEEE Std 802.11-2016, 9.4.1.4
switch (assoc_state_.opts->bss_type) {
case BSS_TYPE_INDEPENDENT:
// We don't support INDEPENDENT
ZX_ASSERT_MSG(false, "Non-infrastructure types not currently supported by sim-fw\n");
dataFrame.toDS_ = 0;
dataFrame.fromDS_ = 0;
dataFrame.addr1_ = common::MacAddr(ethFrame->h_dest);
dataFrame.addr2_ = common::MacAddr(ethFrame->h_source);
dataFrame.addr3_ = assoc_state_.opts->bssid;
break;
case BSS_TYPE_INFRASTRUCTURE:
dataFrame.toDS_ = 1;
dataFrame.fromDS_ = 0;
dataFrame.addr1_ = assoc_state_.opts->bssid;
dataFrame.addr2_ = common::MacAddr(ethFrame->h_source);
dataFrame.addr3_ = common::MacAddr(ethFrame->h_dest);
// Sim FW currently doesn't distinguish QoS from non-QoS association. If it does, this should
// only be set for a QoS association.
dataFrame.qosControl_ = netbuf->priority;
break;
default:
// TODO: support other bss types such as Mesh
ZX_ASSERT_MSG(false, "Non-infrastructure types not currently supported by sim-fw\n");
break;
}
// For now, since the LLC information would always be the same aside from the redundant ethernet
// type (Table M2 IEEE 802.11 2016). we will not append/parse LLC headers
uint32_t payload_size = netbuf->len - BCDC_HEADER_LEN - sizeof(ethhdr);
dataFrame.payload_.resize(payload_size);
memcpy(dataFrame.payload_.data(), netbuf->data + BCDC_HEADER_LEN + sizeof(ethhdr), payload_size);
hw_.Tx(dataFrame);
if (netbuf->ifc_netbuf) {
netbuf->ifc_netbuf->Return(ZX_OK);
}
brcmf_netbuf_free(netbuf);
return ZX_OK;
}
// Stop the SoftAP
void SimFirmware::StopSoftAP(uint16_t ifidx) {
// Disassoc and remove all the associated clients
for (auto client : iface_tbl_[ifidx].ap_config.clients) {
simulation::SimDisassocReqFrame disassoc_req_frame(
iface_tbl_[ifidx].mac_addr, client->mac_addr,
wlan_ieee80211::ReasonCode::UNSPECIFIED_REASON);
hw_.Tx(disassoc_req_frame);
}
iface_tbl_[ifidx].ap_config.clients.clear();
SendEventToDriver(0, nullptr, BRCMF_E_LINK, BRCMF_E_STATUS_SUCCESS, ifidx);
iface_tbl_[ifidx].ap_config.ap_started = false;
iface_tbl_[ifidx].chanspec = 0;
softap_ifidx_ = std::nullopt;
}
void SimFirmware::SendAPStartLinkEvent(uint16_t ifidx) {
SendEventToDriver(0, nullptr, BRCMF_E_LINK, BRCMF_E_STATUS_SUCCESS, ifidx, nullptr,
BRCMF_EVENT_MSG_LINK);
}
void SimFirmware::ScheduleLinkEvent(zx::duration when, uint16_t ifidx) {
hw_.RequestCallback(std::bind(&SimFirmware::SendAPStartLinkEvent, this, ifidx), when);
}
uint16_t SimFirmware::GetNumClients(uint16_t ifidx) {
if (softap_ifidx_ == std::nullopt) {
BRCMF_ERR("SoftAP iface has not been allocated or started.");
return 0;
}
if (ifidx != softap_ifidx_) {
BRCMF_ERR("Input iface is not SoftAP iface.");
return 0;
}
return iface_tbl_[softap_ifidx_.value()].ap_config.clients.size();
}
void SimFirmware::TriggerFirmwareDisassoc(::fuchsia::wlan::ieee80211::ReasonCode reason) {
DisassocLocalClient(reason);
}
// Process an RX CTL message. We simply pass back the results of the previous TX CTL
// operation, which has been stored in bcdc_response_. In real hardware, we may have to
// indicate that the TX CTL operation has not completed. In simulated hardware, we perform
// all operations synchronously.
//
// This function is a simplified version of brcmf_sdio_bus_rxctl. As much of the
// response `msg_` last stored by BcdcResponse::Set() is written to `data` as possible,
// and the actual size of `msg_` is returned in `len_out`.
zx_status_t SimFirmware::BusRxCtl(unsigned char* msg, uint len, int* rxlen_out) {
if (bcdc_response_.IsClear()) {
BRCMF_ERR("no response available");
return ZX_ERR_UNAVAILABLE;
}
zx_status_t status = bcdc_response_.Get(msg, len, rxlen_out);
// Responses are not re-sent on subsequent requests
bcdc_response_.Clear();
return status;
}
struct pktq* SimFirmware::BusGetTxQueue() {
BRCMF_ERR("%s unimplemented", __FUNCTION__);
return nullptr;
}
zx_status_t SimFirmware::BusFlushTxQueue(int /* ifidx */) {
// Sim firmware doesn't have a queue
return ZX_OK;
}
zx_status_t SimFirmware::BusGetBootloaderMacAddr(uint8_t* mac_addr) {
// Simulate a fixed MAC address.
static uint8_t fixed_random_macaddr[ETH_ALEN] = {};
static bool memoized = false;
zx_status_t status;
// Use a value provided by the error injector, if one has been set
auto bootloader_mac_addr = err_inj_.BootloaderMacAddr();
if (bootloader_mac_addr) {
memcpy(mac_addr, bootloader_mac_addr->byte, ETH_ALEN);
return ZX_OK;
}
if (!memoized) {
BRCMF_INFO(
"Bootloader MAC address not available to simulated firmware. Generating a random mac "
"address to simulate a fixed MAC address.");
status = brcmf_gen_random_mac_addr(fixed_random_macaddr);
if (status != ZX_OK) {
return status;
}
BRCMF_INFO("Generated random mac address: " FMT_MAC, FMT_MAC_ARGS(fixed_random_macaddr));
memoized = true;
}
memcpy(mac_addr, fixed_random_macaddr, sizeof(fixed_random_macaddr));
return ZX_OK;
}
void SimFirmware::BcdcResponse::Clear() { len_ = 0; }
zx_status_t SimFirmware::BcdcResponse::Get(uint8_t* msg, size_t len, int* rxlen_out) {
memcpy(msg, msg_, std::min(len, len_));
ZX_ASSERT_MSG(len_ <= INT_MAX, "Response length exceeds INT_MAX");
*rxlen_out = static_cast<int>(len_);
return ZX_OK;
}
bool SimFirmware::BcdcResponse::IsClear() { return len_ == 0; }
void SimFirmware::BcdcResponse::Set(uint8_t* data, size_t new_len) {
ZX_DEBUG_ASSERT(new_len <= sizeof(msg_));
len_ = new_len;
memcpy(msg_, data, new_len);
}
zx_status_t SimFirmware::HandleIfaceTblReq(const bool add_entry, const void* data,
uint8_t* iface_id, int32_t bsscfgidx) {
if (add_entry) {
// Allocate the first available entry
for (int i = 0; i < kMaxIfSupported; i++) {
if (!iface_tbl_[i].allocated) {
iface_tbl_[i].allocated = true;
iface_tbl_[i].iface_id = i;
iface_tbl_[i].bsscfgidx = bsscfgidx;
if (iface_id)
*iface_id = i;
return ZX_OK;
}
}
} else {
for (int i = 0; i < kMaxIfSupported; i++) {
if (iface_tbl_[i].allocated && iface_tbl_[i].bsscfgidx == bsscfgidx) {
if (iface_id)
*iface_id = iface_tbl_[i].iface_id;
// If AP is in started state, send disassoc req to all clients
if (iface_tbl_[i].ap_mode) {
if (iface_tbl_[i].ap_config.ap_started) {
BRCMF_DBG(SIM, "AP is still started...disassoc all clients");
for (auto client : iface_tbl_[i].ap_config.clients) {
simulation::SimDisassocReqFrame disassoc_req_frame(
iface_tbl_[i].mac_addr, client->mac_addr,
wlan_ieee80211::ReasonCode::UNSPECIFIED_REASON);
hw_.Tx(disassoc_req_frame);
}
}
// Clear out the clients
iface_tbl_[i].ap_config.clients.clear();
softap_ifidx_ = std::nullopt;
}
iface_tbl_[i] = {};
BRCMF_DBG(SIM, "Interface Delete ifidx: %d done", i);
return ZX_OK;
}
}
}
return ZX_ERR_IO;
}
zx_status_t SimFirmware::HandleIfaceRequest(const bool add_iface, const void* data,
const size_t len, int32_t bsscfgidx) {
uint8_t iface_id;
size_t payload_size = sizeof(brcmf_if_event);
auto buf = std::make_unique<std::vector<uint8_t>>(payload_size);
uint8_t* buffer_data = buf->data();
struct brcmf_if_event* ifevent = reinterpret_cast<brcmf_if_event*>(buffer_data);
ifevent->role = 1;
if (HandleIfaceTblReq(add_iface, data, &iface_id, bsscfgidx) == ZX_OK) {
if (add_iface) {
ifevent->action = BRCMF_E_IF_ADD;
ifevent->bsscfgidx = bsscfgidx;
} else {
ifevent->action = BRCMF_E_IF_DEL;
ifevent->bsscfgidx = bsscfgidx;
}
ifevent->ifidx = iface_id;
char ifname[IFNAMSIZ];
sprintf(ifname, "wl0.%d", iface_id);
SendEventToDriver(payload_size, std::move(buf), BRCMF_E_IF, BRCMF_E_STATUS_SUCCESS, iface_id,
ifname);
} else {
SendEventToDriver(payload_size, std::move(buf), BRCMF_E_IF, BRCMF_E_STATUS_ERROR, 0);
}
return ZX_OK;
}
// Handle association request from a client to the SoftAP interface
// ifidx is expected to be a valid index (allocated and configured as AP)
#define TWO_ZERO_LEN_TLVS_LEN (4)
void SimFirmware::HandleAssocReq(std::shared_ptr<const simulation::SimAssocReqFrame> frame) {
auto buf = std::make_unique<std::vector<uint8_t>>(TWO_ZERO_LEN_TLVS_LEN);
uint8_t* tlv_buf = buf->data();
// The driver expects ssid and rsne in TLV format, just fake it for now
*tlv_buf++ = WLAN_IE_TYPE_SSID;
*tlv_buf++ = 0;
*tlv_buf++ = WLAN_IE_TYPE_RSNE;
*tlv_buf++ = 0;
// Check client state
auto client = FindClient(frame->src_addr_);
if (client) {
if (client->state == Client::ASSOCIATED) {
// Client already associated, send a REASSOC_IND event to driver
SendEventToDriver(TWO_ZERO_LEN_TLVS_LEN, std::move(buf), BRCMF_E_REASSOC_IND,
BRCMF_E_STATUS_SUCCESS, softap_ifidx_.value(), nullptr, 0, 0,
frame->src_addr_);
} else if (client->state == Client::AUTHENTICATED) {
// Indicate Assoc success to driver - by sendind ASSOC_IND
SendEventToDriver(TWO_ZERO_LEN_TLVS_LEN, std::move(buf), BRCMF_E_ASSOC_IND,
BRCMF_E_STATUS_SUCCESS, softap_ifidx_.value(), nullptr, 0, 0,
frame->src_addr_);
client->state = Client::ASSOCIATED;
}
simulation::SimAssocRespFrame assoc_resp_frame(frame->bssid_, frame->src_addr_,
wlan_ieee80211::StatusCode::SUCCESS);
hw_.Tx(assoc_resp_frame);
BRCMF_DBG(SIM, "Assoc done Num Clients : %lu",
iface_tbl_[softap_ifidx_.value()].ap_config.clients.size());
} else {
// Client cannot start association before getting authenticated.
// IEEE 802.11-2016 11.3.6.3 specifies that the SME issues a NOT_AUTHENTICATED in the
// MLME-AUTHENTICATE.response message here. Unfortunately, NOT_AUTHENTICATED is in the
// ReasonCode namespace, and the generated MAC frame requires a StatusCode for the association
// response frame. This is a known fault in 802.11-2016, that may be fixed in the next
// revision. Fortunately for us, the NOT_AUTHENTICATED value of 9 in the ReasonCode namespace
// falls in a reserved-unused value in the StatusCode namespace, so we will just return the
// casted value as (presumably) existing APs may err in doing.
simulation::SimAssocRespFrame assoc_resp_frame(
frame->bssid_, frame->src_addr_,
static_cast<wlan_ieee80211::StatusCode>(wlan_ieee80211::ReasonCode::NOT_AUTHENTICATED));
hw_.Tx(assoc_resp_frame);
BRCMF_DBG(SIM, "Assoc fail, should be authenticated first.");
}
}
void SimFirmware::AssocInit(std::unique_ptr<AssocOpts> assoc_opts, wlan_channel_t& channel) {
SetAssocState(AssocState::ASSOCIATING);
assoc_state_.opts = std::move(assoc_opts);
assoc_state_.num_attempts = 0;
uint16_t chanspec = channel_to_chanspec(&d11_inf_, &channel);
SetIFChanspec(kClientIfidx, chanspec);
hw_.SetChannel(channel);
hw_.EnableRx();
}
void SimFirmware::AssocScanResultSeen(const ScanResult& scan_result) {
std::optional<cssid_t> scan_result_ssid;
for (const auto& ie : scan_result.ies) {
if (ie != nullptr && ie->IeType() == simulation::InformationElement::IE_TYPE_SSID) {
auto ssid_ie = std::static_pointer_cast<simulation::SsidInformationElement>(ie);
scan_result_ssid.emplace(ssid_ie->ssid_);
}
}
// Check ssid filter
if (scan_state_.opts->ssid && scan_result_ssid.has_value()) {
ZX_ASSERT(scan_state_.opts->ssid->len <= sizeof(scan_state_.opts->ssid->data));
if (scan_result_ssid->len != scan_state_.opts->ssid->len) {
return;
}
if (std::memcmp(scan_result_ssid->data, scan_state_.opts->ssid->data, scan_result_ssid->len) !=
0) {
return;
}
}
// Check bssid filter
if ((scan_state_.opts->bssid) && (scan_result.bssid != *scan_state_.opts->bssid)) {
return;
}
assoc_state_.scan_results.push_back(scan_result);
}
void SimFirmware::AssocScanDone(brcmf_fweh_event_status_t event_status) {
ZX_ASSERT(assoc_state_.state == AssocState::SCANNING);
// Operation fails if we don't have at least one scan result
if ((event_status == BRCMF_E_STATUS_SUCCESS) && (assoc_state_.scan_results.size() == 0)) {
event_status = BRCMF_E_STATUS_NO_NETWORKS;
}
if (event_status != BRCMF_E_STATUS_SUCCESS) {
SendEventToDriver(0, nullptr, BRCMF_E_SET_SSID, event_status, kClientIfidx);
SetAssocState(AssocState::NOT_ASSOCIATED);
return;
}
// For now, just pick the first AP. The real firmware can select based on signal strength and
// band, but since wlanstack makes its own decision, we won't bother to model that here for now.
ScanResult& ap = assoc_state_.scan_results.front();
auto assoc_opts = std::make_unique<AssocOpts>();
assoc_opts->bssid = ap.bssid;
if (scan_state_.opts->ssid)
assoc_opts->ssid = scan_state_.opts->ssid.value();
AssocInit(std::move(assoc_opts), ap.channel);
// Send an event of the first scan result to driver when assoc scan is done.
EscanResultSeen(ap);
BRCMF_DBG(SIM, "Auth start after assoc scan");
AuthStart();
}
void SimFirmware::AssocClearContext() {
hw_.CancelCallback(assoc_state_.assoc_timer_id);
AuthClearContext();
SetAssocState(AssocState::NOT_ASSOCIATED);
assoc_state_.opts = nullptr;
assoc_state_.scan_results.clear();
// Clear out the channel setting
iface_tbl_[kClientIfidx].chanspec = 0;
assoc_resp_ies_len_ = 0;
memset(assoc_resp_ies_, 0, ASSOC_IES_MAX_LEN);
}
void SimFirmware::AuthClearContext() {
hw_.CancelCallback(auth_state_.auth_timer_id);
auth_state_.state = AuthState::NOT_AUTHENTICATED;
auth_state_.sec_type = simulation::SEC_PROTO_TYPE_OPEN;
}
void SimFirmware::AssocHandleFailure(wlan_ieee80211::StatusCode status) {
if (assoc_state_.state == AssocState::NOT_ASSOCIATED) {
return;
}
if (assoc_state_.num_attempts >= assoc_max_retries_
// The firmware has been observed to not retry when there is an
// authentication challenge failure. Also when firmware is doing external supplicant SAE auth,
// it won't retry, because the retry is controlled by external supplicant.
|| assoc_state_.state == AssocState::AUTHENTICATION_CHALLENGE_FAILURE ||
auth_state_.sec_type == simulation::SEC_PROTO_TYPE_WPA3) {
BRCMF_DBG(SIM, "Assoc failed. Send E_SET_SSID with failure");
SendEventToDriver(0, nullptr, BRCMF_E_ASSOC, BRCMF_E_STATUS_FAIL, kClientIfidx, nullptr, 0,
static_cast<uint32_t>(status), assoc_state_.opts->bssid);
SendEventToDriver(0, nullptr, BRCMF_E_SET_SSID, BRCMF_E_STATUS_FAIL, kClientIfidx);
AssocClearContext();
} else {
assoc_state_.num_attempts++;
auth_state_.state = AuthState::NOT_AUTHENTICATED;
BRCMF_DBG(SIM, "Assoc failed. Try again..attempt: %d", assoc_state_.num_attempts);
AuthStart();
}
}
void SimFirmware::AuthStart() {
BRCMF_DBG(SIM, "Auth Start");
common::MacAddr srcAddr(GetMacAddr(kClientIfidx));
common::MacAddr bssid(assoc_state_.opts->bssid);
hw_.RequestCallback(std::bind(&SimFirmware::AssocHandleFailure, this,
wlan_ieee80211::StatusCode::REJECTED_SEQUENCE_TIMEOUT),
kAuthTimeout, &auth_state_.auth_timer_id);
ZX_ASSERT(auth_state_.state == AuthState::NOT_AUTHENTICATED);
simulation::SimAuthType auth_type = simulation::AUTH_TYPE_OPEN;
switch (iface_tbl_[kClientIfidx].auth_type) {
case BRCMF_AUTH_MODE_OPEN:
// Sequence number start from 0, end with at most 3.
auth_type = simulation::AUTH_TYPE_OPEN;
break;
case BRCMF_AUTH_MODE_AUTO:
auth_type = simulation::AUTH_TYPE_SHARED_KEY;
break;
case BRCMF_AUTH_MODE_SAE:
auth_type = simulation::AUTH_TYPE_SAE;
break;
default:
ZX_ASSERT_MSG(false, "Auth type not supported.");
}
simulation::SimAuthFrame auth_req_frame(srcAddr, bssid, 1, auth_type,
wlan_ieee80211::StatusCode::SUCCESS);
if (iface_tbl_[kClientIfidx].wsec == WEP_ENABLED) {
ZX_ASSERT(iface_tbl_[kClientIfidx].wpa_auth == WPA_AUTH_DISABLED);
auth_state_.sec_type = simulation::SEC_PROTO_TYPE_WEP;
}
switch (iface_tbl_[kClientIfidx].wpa_auth) {
case WPA_AUTH_PSK:
ZX_ASSERT((iface_tbl_[kClientIfidx].wsec & (uint32_t)WSEC_NONE) == 0U);
auth_state_.sec_type = simulation::SEC_PROTO_TYPE_WPA1;
break;
case WPA2_AUTH_PSK:
ZX_ASSERT((iface_tbl_[kClientIfidx].wsec & (uint32_t)WSEC_NONE) == 0U);
auth_state_.sec_type = simulation::SEC_PROTO_TYPE_WPA2;
break;
case WPA3_AUTH_SAE_PSK:
ZX_ASSERT((iface_tbl_[kClientIfidx].wsec & (uint32_t)WSEC_NONE) == 0U);
auth_state_.sec_type = simulation::SEC_PROTO_TYPE_WPA3;
break;
default:
ZX_ASSERT_MSG(auth_state_.sec_type == simulation::SEC_PROTO_TYPE_WEP ||
auth_state_.sec_type == simulation::SEC_PROTO_TYPE_OPEN,
"Upper layer auth type not supported.");
/* No action needed for WEP or OPEN*/
break;
}
if (auth_state_.sec_type == simulation::SEC_PROTO_TYPE_WPA3) {
auto buf = std::make_unique<std::vector<uint8_t>>(sizeof(brcmf_ext_auth));
auto ext_auth_data = reinterpret_cast<brcmf_ext_auth*>(buf->data());
// Set the data values, though driver only cares about the bssid.
ext_auth_data->ssid.SSID_len = assoc_state_.opts->ssid.len;
memcpy(ext_auth_data->ssid.SSID, assoc_state_.opts->ssid.data,
wlan_ieee80211::MAX_SSID_BYTE_LEN);
bssid.CopyTo(ext_auth_data->bssid);
ext_auth_data->key_mgmt_suite = WPA3_AUTH_SAE_PSK;
ext_auth_data->status = BRCMF_E_STATUS_SUCCESS;
auth_state_.state = AuthState::EXPECTING_EXTERNAL_COMMIT;
SendEventToDriver(sizeof(brcmf_ext_auth), std::move(buf), BRCMF_E_JOIN_START,
BRCMF_E_STATUS_SUCCESS, kClientIfidx);
} else {
auth_req_frame.sec_proto_type_ = auth_state_.sec_type;
auth_state_.state = AuthState::EXPECTING_SECOND;
hw_.Tx(auth_req_frame);
}
}
// The authentication frame might be an authentication response for client iface, or it could also
// be an authentication req from a potential client for softap iface.
void SimFirmware::RxAuthFrame(std::shared_ptr<const simulation::SimAuthFrame> frame) {
if (frame->sec_proto_type_ == simulation::SEC_PROTO_TYPE_WPA3) {
ZX_ASSERT(frame->auth_type_ == simulation::AUTH_TYPE_SAE);
RemoteUpdateExternalSaeStatus(frame->seq_num_, frame->status_, frame->payload_.data(),
frame->payload_.size());
} else {
if (frame->seq_num_ == 1) {
HandleAuthReq(frame);
} else {
HandleAuthResp(frame);
}
}
}
// Handling authentication request for potential client of softap iface.
void SimFirmware::HandleAuthReq(std::shared_ptr<const simulation::SimAuthFrame> frame) {
if (softap_ifidx_ == std::nullopt) {
BRCMF_DBG(SIM, "SoftAP iface has not been allocated or started.");
return;
}
ZX_ASSERT_MSG(iface_tbl_[softap_ifidx_.value()].auth_type == BRCMF_AUTH_MODE_OPEN,
"The only auth type we support now is BRCMF_AUTH_MODE_OPEN because softAP iface "
"only support OPEN and WPA2.");
// Refuse auth req with auth type other than AUTH_TYPE_OPEN.
if (frame->auth_type_ != simulation::AUTH_TYPE_OPEN) {
BRCMF_DBG(SIM, "SoftAP iface only support OPEN mode for authentication now.");
// Send authentication response back
simulation::SimAuthFrame auth_resp_frame(
iface_tbl_[softap_ifidx_.value()].mac_addr, frame->src_addr_, 2, frame->auth_type_,
wlan_ieee80211::StatusCode::REFUSED_REASON_UNSPECIFIED);
hw_.Tx(auth_resp_frame);
return;
}
auto client = std::make_shared<Client>(frame->src_addr_, Client::AUTHENTICATED);
// Add the client to the list
iface_tbl_[softap_ifidx_.value()].ap_config.clients.push_back(client);
// Send authentication response back
simulation::SimAuthFrame auth_resp_frame(iface_tbl_[softap_ifidx_.value()].mac_addr,
frame->src_addr_, 2, simulation::AUTH_TYPE_OPEN,
wlan_ieee80211::StatusCode::SUCCESS);
hw_.Tx(auth_resp_frame);
// AUTH_IND is a simple event with the source mac address included
SendEventToDriver(0, nullptr, BRCMF_E_AUTH_IND, BRCMF_E_STATUS_SUCCESS, softap_ifidx_.value(),
nullptr, 0, 0, frame->src_addr_);
}
void SimFirmware::HandleAuthResp(std::shared_ptr<const simulation::SimAuthFrame> frame) {
// If we are not expecting auth resp packets, ignore it,
if (auth_state_.state == AuthState::NOT_AUTHENTICATED ||
auth_state_.state == AuthState::AUTHENTICATED) {
return;
}
// Ignore if this is not intended for us
common::MacAddr mac_addr(GetMacAddr(kClientIfidx));
if (frame->dst_addr_ != mac_addr) {
return;
}
// Ignore if this is not from the bssid with which we were trying to authenticate
if (frame->src_addr_ != assoc_state_.opts->bssid) {
return;
}
// It should not be an auth req frame if its dst addr is a client
if (frame->seq_num_ != 2 && frame->seq_num_ != 4) {
return;
}
// Response received, cancel timer
hw_.CancelCallback(auth_state_.auth_timer_id);
if (iface_tbl_[kClientIfidx].auth_type == BRCMF_AUTH_MODE_OPEN) {
ZX_ASSERT(auth_state_.state == AuthState::EXPECTING_SECOND);
ZX_ASSERT(frame->seq_num_ == 2);
if (frame->status_ != wlan_ieee80211::StatusCode::SUCCESS) {
BRCMF_DBG(SIM, "Auth refused, Handle failure");
AssocHandleFailure(frame->status_);
return;
}
auth_state_.state = AuthState::AUTHENTICATED;
// Remember the last auth'd bssid
auth_state_.bssid = assoc_state_.opts->bssid;
BRCMF_DBG(SIM, "Assoc Start after auth");
AssocStart();
} else {
// When iface_tbl_[kClientIfidx].auth_type == BRCMF_AUTH_MODE_AUTO
if (auth_state_.state == AuthState::EXPECTING_SECOND && frame->seq_num_ == 2) {
// Retry with AUTH_TYPE_OPEN_SYSTEM when refused in AUTH_TYPE_SHARED_KEY mode
if (frame->status_ != wlan_ieee80211::StatusCode::SUCCESS) {
auth_state_.state = AuthState::NOT_AUTHENTICATED;
iface_tbl_[kClientIfidx].auth_type = BRCMF_AUTH_MODE_OPEN;
BRCMF_DBG(SIM, "Auth shared refused...try with OPEN");
AuthStart();
return;
}
// Challenge failure should not occur until the fourth frame.
ZX_ASSERT(frame->status_ != wlan_ieee80211::StatusCode::CHALLENGE_FAILURE);
// If we receive the second auth frame when we are expecting it, we send out the third one and
// set another timer for it.
hw_.RequestCallback(std::bind(&SimFirmware::AssocHandleFailure, this,
wlan_ieee80211::StatusCode::REJECTED_SEQUENCE_TIMEOUT),
kAuthTimeout, &auth_state_.auth_timer_id);
auth_state_.state = AuthState::EXPECTING_FOURTH;
common::MacAddr srcAddr(GetMacAddr(kClientIfidx));
common::MacAddr bssid(assoc_state_.opts->bssid);
simulation::SimAuthFrame auth_req_frame(srcAddr, bssid, frame->seq_num_ + 1,
simulation::AUTH_TYPE_SHARED_KEY,
wlan_ieee80211::StatusCode::SUCCESS);
auth_req_frame.sec_proto_type_ = auth_state_.sec_type;
hw_.Tx(auth_req_frame);
} else if (auth_state_.state == AuthState::EXPECTING_FOURTH && frame->seq_num_ == 4) {
if (frame->status_ == wlan_ieee80211::StatusCode::CHALLENGE_FAILURE) {
assoc_state_.state = AssocState::AUTHENTICATION_CHALLENGE_FAILURE;
auth_state_.state = AuthState::NOT_AUTHENTICATED;
BRCMF_DBG(SIM, "Auth shared challenge failure, Handle failure");
SendEventToDriver(0, nullptr, BRCMF_E_AUTH, BRCMF_E_STATUS_FAIL, kClientIfidx, nullptr,
0, // TODO: determine what the flags should be
static_cast<uint32_t>(frame->status_), frame->src_addr_);
AssocHandleFailure(frame->status_);
return;
}
// If we receive the fourth auth frame when we are expecting it, start association
auth_state_.state = AuthState::AUTHENTICATED;
// Remember the last auth'd bssid
auth_state_.bssid = assoc_state_.opts->bssid;
BRCMF_DBG(SIM, "Assoc Start after 4way handshake");
AssocStart();
}
}
}
zx_status_t SimFirmware::RemoteUpdateExternalSaeStatus(uint16_t seq_num,
wlan_ieee80211::StatusCode status_code,
const uint8_t* sae_payload,
size_t text_len) {
ZX_ASSERT(sae_payload != nullptr);
if (seq_num != 1 && seq_num != 2) {
BRCMF_ERR("Invalid sequence number in SAE auth frame.");
return ZX_ERR_INVALID_ARGS;
}
if (seq_num == 1 && auth_state_.state != AuthState::EXPECTING_AP_COMMIT) {
BRCMF_ERR("Unexpected COMMIT auth frame from AP.");
return ZX_ERR_BAD_STATE;
}
if (seq_num == 2 && auth_state_.state != AuthState::EXPECTING_AP_CONFIRM) {
BRCMF_ERR("Unexpected CONFIRM auth frame from AP.");
return ZX_ERR_BAD_STATE;
}
// Frame received from AP, cancel timer.
hw_.CancelCallback(auth_state_.auth_timer_id);
// construct auth frame and send up to external supplicant.
size_t buf_size = sizeof(wlan::Authentication) + text_len;
auto buf = std::make_unique<std::vector<uint8_t>>(buf_size);
auto pframe_hdr = reinterpret_cast<wlan::Authentication*>(buf->data());
pframe_hdr->auth_txn_seq_number = seq_num;
pframe_hdr->status_code = WLAN_AUTH_RESULT_SUCCESS;
pframe_hdr->auth_algorithm_number = BRCMF_AUTH_MODE_SAE;
memcpy(buf->data() + sizeof(wlan::Authentication), sae_payload, text_len);
hw_.RequestCallback(std::bind(&SimFirmware::AssocHandleFailure, this,
wlan_ieee80211::StatusCode::REJECTED_SEQUENCE_TIMEOUT),
kAuthTimeout, &auth_state_.auth_timer_id);
// Update state
if (seq_num == 1)
auth_state_.state = AuthState::EXPECTING_EXTERNAL_CONFIRM;
else
auth_state_.state = AuthState::EXPECTING_EXTERNAL_HANDSHAKE_RESP;
SendEventToDriver(buf_size, std::move(buf), BRCMF_E_AUTH, BRCMF_E_STATUS_SUCCESS, kClientIfidx);
return ZX_OK;
}
zx_status_t SimFirmware::LocalUpdateExternalSaeStatus(uint16_t seq_num,
wlan_ieee80211::StatusCode status_code,
const uint8_t* sae_payload, size_t text_len) {
ZX_ASSERT(sae_payload != nullptr);
if (seq_num != 1 && seq_num != 2) {
BRCMF_ERR("Invalid sequence number in SAE auth frame.");
return ZX_ERR_INVALID_ARGS;
}
common::MacAddr srcAddr(GetMacAddr(kClientIfidx));
common::MacAddr bssid(assoc_state_.opts->bssid);
// Create a template auth_req_frame, might be modified later.
simulation::SimAuthFrame auth_req_frame(srcAddr, bssid, 1, simulation::AUTH_TYPE_SAE,
wlan_ieee80211::StatusCode::SUCCESS);
if (seq_num == 1 && auth_state_.state != AuthState::EXPECTING_EXTERNAL_COMMIT) {
BRCMF_ERR("Unexpected COMMIT auth frame from external supplicant. seq_num: %u, state: %u",
seq_num, auth_state_.state);
return ZX_ERR_BAD_STATE;
}
if (seq_num == 2 && auth_state_.state != AuthState::EXPECTING_EXTERNAL_CONFIRM) {
BRCMF_ERR("Unexpected CONFIRM auth frame from external supplicant. seq_num: %u, state: %u",
seq_num, auth_state_.state);
return ZX_ERR_BAD_STATE;
}
// Frame received from external supplicant, cancel timer.
hw_.CancelCallback(auth_state_.auth_timer_id);
auth_req_frame.status_ = status_code;
auth_req_frame.seq_num_ = seq_num;
auth_req_frame.AddChallengeText(cpp20::span(sae_payload, text_len));
auth_req_frame.sec_proto_type_ = auth_state_.sec_type;
hw_.RequestCallback(std::bind(&SimFirmware::AssocHandleFailure, this,
wlan_ieee80211::StatusCode::REJECTED_SEQUENCE_TIMEOUT),
kAuthTimeout, &auth_state_.auth_timer_id);
hw_.Tx(auth_req_frame);
// Update state
if (seq_num == 1)
auth_state_.state = AuthState::EXPECTING_AP_COMMIT;
else
auth_state_.state = AuthState::EXPECTING_AP_CONFIRM;
return ZX_OK;
}
// Remove the client from the list. If found return true else false.
bool SimFirmware::FindAndRemoveClient(const common::MacAddr client_mac, bool motivation_deauth,
wlan_ieee80211::ReasonCode deauth_reason) {
if (softap_ifidx_ == std::nullopt) {
BRCMF_ERR("SoftAP iface has not been allocated or started.");
return false;
}
auto& clients = iface_tbl_[softap_ifidx_.value()].ap_config.clients;
for (auto client : clients) {
if (client->mac_addr == client_mac) {
if (motivation_deauth) {
// The removal is triggered by a deauth frame.
if (client->state == Client::AUTHENTICATED) {
// When this client is authenticated but not associated, only send up BRCMF_E_DEAUTH_IND
// to driver.
SendEventToDriver(0, nullptr, BRCMF_E_DEAUTH_IND, BRCMF_E_STATUS_SUCCESS,
softap_ifidx_.value(), nullptr, 0, static_cast<uint32_t>(deauth_reason),
client_mac);
} else if (client->state == Client::ASSOCIATED) {
// When this client is associated, send both BRCMF_E_DEAUTH_IND and BRCMF_E_DISASSOC_IND
// events up to driver.
SendEventToDriver(0, nullptr, BRCMF_E_DEAUTH_IND, BRCMF_E_STATUS_SUCCESS,
softap_ifidx_.value(), nullptr, 0, static_cast<uint32_t>(deauth_reason),
client_mac);
SendEventToDriver(
0, nullptr, BRCMF_E_DISASSOC_IND, BRCMF_E_STATUS_SUCCESS, softap_ifidx_.value(),
nullptr, BRCMF_EVENT_MSG_LINK,
static_cast<uint32_t>(wlan_ieee80211::ReasonCode::LEAVING_NETWORK_DISASSOC),
client_mac);
}
} else {
BRCMF_DBG(SIM, "deauth_reason is not used.");
// The removal is triggered by a disassoc frame.
SendEventToDriver(
0, nullptr, BRCMF_E_DISASSOC_IND, BRCMF_E_STATUS_SUCCESS, softap_ifidx_.value(),
nullptr, BRCMF_EVENT_MSG_LINK,
static_cast<uint32_t>(wlan_ieee80211::ReasonCode::LEAVING_NETWORK_DISASSOC),
client_mac);
}
clients.remove(client);
return true;
}
}
return false;
}
// Return true if client is in the assoc list else false
std::shared_ptr<SimFirmware::Client> SimFirmware::FindClient(const common::MacAddr client_mac) {
if (softap_ifidx_ == std::nullopt) {
BRCMF_ERR("SoftAP iface has not been allocated or started.");
return std::shared_ptr<SimFirmware::Client>(nullptr);
}
auto& clients = iface_tbl_[softap_ifidx_.value()].ap_config.clients;
for (auto& client : clients) {
if (client->mac_addr == client_mac) {
return client;
}
}
return std::shared_ptr<SimFirmware::Client>(nullptr);
}
std::vector<brcmf_wsec_key_le> SimFirmware::GetKeyList(uint16_t ifidx) {
return iface_tbl_[ifidx].wsec_key_list;
}
void SimFirmware::RxDeauthReq(std::shared_ptr<const simulation::SimDeauthFrame> frame) {
BRCMF_DBG(SIM, "Deauth from %s for %s reason: %d", MACSTR(frame->src_addr_),
MACSTR(frame->dst_addr_), static_cast<int>(frame->reason_));
// First check if this is a deauth meant for a client associated to our SoftAP
auto ifidx = GetIfidxByMac(frame->dst_addr_);
if (ifidx == -1) {
// Not meant for any of the valid IFs, ignore
return;
}
if (!iface_tbl_[ifidx].ap_mode) {
ZX_ASSERT_MSG(ifidx == kClientIfidx, "Not matching client iface.");
// Not meant for the SoftAP. Check if it is meant for the client interface
HandleDisconnectForClientIF(frame, auth_state_.bssid, frame->reason_);
return;
}
// Remove the client from the list (if found)
if (FindAndRemoveClient(frame->src_addr_, true, frame->reason_)) {
BRCMF_DBG(SIM, "Deauth done Num Clients: %lu", iface_tbl_[ifidx].ap_config.clients.size());
return;
}
BRCMF_DBG(SIM, "Deauth Client not found in List");
}
void SimFirmware::AssocStart() {
BRCMF_DBG(SIM, "Assoc Start");
common::MacAddr srcAddr(GetMacAddr(kClientIfidx));
hw_.RequestCallback(std::bind(&SimFirmware::AssocHandleFailure, this,
wlan_ieee80211::StatusCode::REFUSED_REASON_UNSPECIFIED),
kAssocTimeout, &assoc_state_.assoc_timer_id);
// We can't use assoc_state_.opts->bssid directly because it may get free'd during TxAssocReq
// handling if a response is sent.
common::MacAddr bssid(assoc_state_.opts->bssid);
simulation::SimAssocReqFrame assoc_req_frame(srcAddr, bssid, assoc_state_.opts->ssid);
hw_.Tx(assoc_req_frame);
}
// Get the index of the SoftAP IF based on Mac.
int16_t SimFirmware::GetIfidxByMac(const common::MacAddr& addr) {
for (uint8_t i = 0; i < kMaxIfSupported; i++) {
if (iface_tbl_[i].allocated && iface_tbl_[i].mac_addr == addr) {
return i;
}
}
return -1;
}
// Get channel of IF
wlan_channel_t SimFirmware::GetIfChannel(bool is_ap) {
wlan_channel_t channel;
// Get chanspec
ZX_ASSERT_MSG(iface_tbl_[kClientIfidx].allocated, "The client iface is not allocated!");
uint16_t chanspec = iface_tbl_[kClientIfidx].chanspec;
ZX_ASSERT_MSG(chanspec != 0, "No chanspec assigned to client.");
// convert to channel
chanspec_to_channel(&d11_inf_, chanspec, &channel);
return channel;
}
// This routine for now only handles Disassoc Request meant for the SoftAP IF.
void SimFirmware::RxDisassocReq(std::shared_ptr<const simulation::SimDisassocReqFrame> frame) {
BRCMF_DBG(SIM, "Disassoc from %s for %s reason: %d", MACSTR(frame->src_addr_),
MACSTR(frame->dst_addr_), static_cast<int>(frame->reason_));
// First check if this is a disassoc meant for a client associated to our SoftAP
auto ifidx = GetIfidxByMac(frame->dst_addr_);
if (ifidx == -1) {
// Not meant for any of the valid IFs, ignore
return;
}
if (!iface_tbl_[ifidx].ap_mode) {
ZX_ASSERT_MSG(ifidx == kClientIfidx, "Not matching client iface.");
// Not meant for the SoftAP. Check if it is meant for the client interface
HandleDisconnectForClientIF(frame, assoc_state_.opts->bssid, frame->reason_);
return;
}
// Remove the client from the list (if found)
if (FindAndRemoveClient(frame->src_addr_, false,
wlan_ieee80211::ReasonCode::UNSPECIFIED_REASON)) {
BRCMF_DBG(SIM, "Disassoc done Num Clients: %lu", iface_tbl_[ifidx].ap_config.clients.size());
return;
}
BRCMF_DBG(SIM, "Client not found in List");
}
void SimFirmware::RxAssocResp(std::shared_ptr<const simulation::SimAssocRespFrame> frame) {
// Ignore if we are not trying to associate
if (assoc_state_.state != AssocState::ASSOCIATING) {
return;
}
// Ignore if this is not intended for us
if (GetIfidxByMac(frame->dst_addr_) == -1) {
return;
}
// Ignore if this is not from the bssid with which we were trying to associate
if (frame->src_addr_ != assoc_state_.opts->bssid) {
return;
}
// Response received, cancel timer
hw_.CancelCallback(assoc_state_.assoc_timer_id);
if (frame->status_ == wlan_ieee80211::StatusCode::SUCCESS) {
// IEEE Std 802.11-2016, 9.4.1.4 to determine bss type
bool capIbss = frame->capability_info_.ibss();
bool capEss = frame->capability_info_.ess();
if (capIbss && !capEss) {
ZX_ASSERT_MSG(false, "Non-infrastructure types not currently supported by sim-fw\n");
assoc_state_.opts->bss_type = BSS_TYPE_INDEPENDENT;
} else if (!capIbss && capEss) {
assoc_state_.opts->bss_type = BSS_TYPE_INFRASTRUCTURE;
} else if (capIbss && capEss) {
ZX_ASSERT_MSG(false, "Non-infrastructure types not currently supported by sim-fw\n");
assoc_state_.opts->bss_type = BSS_TYPE_MESH;
} else {
BRCMF_WARN("Station with impossible capability not being an ess or ibss found\n");
}
// Set values that are returned for iovar "assoc_resp_ies"
ZX_ASSERT_MSG(frame->raw_ies_.size() <= ASSOC_IES_MAX_LEN,
"Assoc resp frame IEs longer than ASSOC_IES_MAX_LEN: %lu > %d",
frame->raw_ies_.size(), ASSOC_IES_MAX_LEN);
memcpy(assoc_resp_ies_, frame->raw_ies_.data(), frame->raw_ies_.size());
assoc_resp_ies_len_ = frame->raw_ies_.size();
BRCMF_DBG(SIM, "Assoc success, send events with a delay");
// Send the ASSOC event with a delay
SendEventToDriver(0, nullptr, BRCMF_E_ASSOC, BRCMF_E_STATUS_SUCCESS, kClientIfidx, nullptr, 0,
0, assoc_state_.opts->bssid, kAssocEventDelay);
// Send the LINK event with a delay
SendEventToDriver(0, nullptr, BRCMF_E_LINK, BRCMF_E_STATUS_SUCCESS, kClientIfidx, nullptr,
BRCMF_EVENT_MSG_LINK, 0, assoc_state_.opts->bssid, kLinkEventDelay);
// Send the SSID event after a delay
SendEventToDriver(0, nullptr, BRCMF_E_SET_SSID, BRCMF_E_STATUS_SUCCESS, kClientIfidx, nullptr,
0, 0, assoc_state_.opts->bssid, kSsidEventDelay);
// Set the Assoc state only after E_ASSOC is sent to the driver.
hw_.RequestCallback(std::bind(&SimFirmware::SetAssocState, this, AssocState::ASSOCIATED),
kAssocEventDelay);
if (softap_ifidx_ != std::nullopt) {
// Send the AP_STARTED event to the SoftAp IF after a delay. This event is sent to the
// SoftAP IF in case its channel changed (to sync up to the client's channel).
SendEventToDriver(0, nullptr, BRCMF_E_AP_STARTED, BRCMF_E_STATUS_SUCCESS,
softap_ifidx_.value(), nullptr, 0, 0, kZeroMac, kApStartedEventDelay);
}
} else {
BRCMF_DBG(SIM, "Assoc refused, Handle failure");
AssocHandleFailure(frame->status_);
}
}
void SimFirmware::SetAssocState(AssocState::AssocStateName state) {
if (state == AssocState::NOT_ASSOCIATED) {
auth_state_.state = AuthState::NOT_AUTHENTICATED;
}
assoc_state_.state = state;
}
// Disassociate the Local Client (request coming in from the driver)
void SimFirmware::DisassocLocalClient(wlan_ieee80211::ReasonCode reason) {
common::MacAddr srcAddr(GetMacAddr(kClientIfidx));
if (assoc_state_.state == AssocState::ASSOCIATED) {
common::MacAddr bssid(assoc_state_.opts->bssid);
// Transmit the disassoc req and since there is no response for it, indicate disassoc done to
// driver now
simulation::SimDisassocReqFrame disassoc_req_frame(srcAddr, bssid, reason);
hw_.Tx(disassoc_req_frame);
SetStateToDisassociated(reason, true);
} else if (auth_state_.state == AuthState::AUTHENTICATED) {
common::MacAddr bssid(assoc_state_.opts->bssid);
// Transmit the deauth frame clear AP state.
simulation::SimDeauthFrame deauth_req_frame(srcAddr, bssid, reason);
hw_.Tx(deauth_req_frame);
}
AuthClearContext();
AssocClearContext();
}
// Disassoc/deauth Request from FakeAP for the Client IF.
void SimFirmware::HandleDisconnectForClientIF(
std::shared_ptr<const simulation::SimManagementFrame> frame, const common::MacAddr& bssid,
wlan_ieee80211::ReasonCode reason) {
// Ignore if this is not intended for us
common::MacAddr mac_addr(iface_tbl_[kClientIfidx].mac_addr);
if (frame->dst_addr_ != mac_addr) {
return;
}
// Ignore if this is not from the bssid with which we are associated/authenticated
if (frame->src_addr_ != bssid) {
return;
}
if (frame->MgmtFrameType() == simulation::SimManagementFrame::FRAME_TYPE_DEAUTH) {
// The client could receive a deauth even after disassociation. Notify the driver always
SendEventToDriver(0, nullptr, BRCMF_E_DEAUTH_IND, BRCMF_E_STATUS_SUCCESS, kClientIfidx, 0, 0,
static_cast<uint32_t>(reason));
if (auth_state_.state == AuthState::AUTHENTICATED) {
AuthClearContext();
}
// DEAUTH implies disassoc, so continue
}
// disassoc
if (assoc_state_.state != AssocState::ASSOCIATED) {
// Already disassoc'd, nothing more to do.
return;
}
SetStateToDisassociated(reason, false);
AssocClearContext();
}
// precondition: was associated
void SimFirmware::SetStateToDisassociated(wlan_ieee80211::ReasonCode reason,
bool locally_initiated) {
// Disable beacon watchdog that triggers disconnect
DisableBeaconWatchdog();
// Send the appropriate event to driver.
SendEventToDriver(0, nullptr, locally_initiated ? BRCMF_E_DISASSOC : BRCMF_E_DISASSOC_IND,
BRCMF_E_STATUS_SUCCESS, kClientIfidx, nullptr, 0, static_cast<uint32_t>(reason),
assoc_state_.opts->bssid, kDisassocEventDelay);
SendEventToDriver(0, nullptr, BRCMF_E_LINK, BRCMF_E_STATUS_SUCCESS, kClientIfidx, nullptr, 0,
static_cast<uint32_t>(reason), assoc_state_.opts->bssid, kLinkEventDelay);
}
// Assoc Request from Client for the SoftAP IF
void SimFirmware::RxAssocReq(std::shared_ptr<const simulation::SimAssocReqFrame> frame) {
BRCMF_DBG(SIM, "Assoc from %s for %s", MACSTR(frame->src_addr_), MACSTR(frame->bssid_));
if (softap_ifidx_ == std::nullopt) {
BRCMF_DBG(SIM,
"Received an assoc request but the softap iface has not been allocated or started.");
return;
}
if (std::memcmp(iface_tbl_[softap_ifidx_.value()].mac_addr.byte, frame->bssid_.byte, ETH_ALEN) ==
0) {
// ASSOC_IND contains some TLVs
HandleAssocReq(frame);
}
}
zx_status_t SimFirmware::HandleJoinRequest(const void* value, size_t value_len) {
auto join_params = reinterpret_cast<const brcmf_ext_join_params_le*>(value);
// Verify that the channel count is consistent with the size of the structure
size_t max_channels =
(value_len - offsetof(brcmf_ext_join_params_le, assoc_le.chanspec_list)) / sizeof(uint16_t);
size_t num_channels = join_params->assoc_le.chanspec_num;
if (max_channels < num_channels) {
BRCMF_DBG(SIM, "Bad join request: message size (%zd) too short for %zd channels", value_len,
num_channels);
return ZX_ERR_INVALID_ARGS;
}
if (assoc_state_.state != AssocState::NOT_ASSOCIATED) {
ZX_ASSERT_MSG(assoc_state_.state != AssocState::ASSOCIATED,
"Need to add support for automatically disassociating");
BRCMF_DBG(SIM, "Attempt to associate while association already in progress");
return ZX_ERR_BAD_STATE;
}
if (scan_state_.state != ScanState::STOPPED) {
BRCMF_DBG(SIM, "Attempt to associate while scan already in progress");
}
auto scan_opts = std::make_unique<ScanOpts>();
// scan_opts->sync_id is unused, since we're not reporting our results back to the driver
switch (join_params->scan_le.scan_type) {
case BRCMF_SCANTYPE_DEFAULT:
// Use the default
scan_opts->is_active = !default_passive_scan_;
break;
case BRCMF_SCANTYPE_PASSIVE:
scan_opts->is_active = false;
break;
case BRCMF_SCANTYPE_ACTIVE:
// FIXME: this should be true, but this is the mode used by the firmware and active scans are
// not supported yet.
scan_opts->is_active = false;
break;
default:
return ZX_ERR_INVALID_ARGS;
}
// Specify the SSID filter, if applicable
const struct brcmf_ssid_le* req_ssid = &join_params->ssid_le;
ZX_ASSERT(wlan_ieee80211::MAX_SSID_BYTE_LEN == sizeof(scan_opts->ssid->data));
if (req_ssid->SSID_len != 0) {
cssid_t ssid;
ssid.len = req_ssid->SSID_len;
std::copy(&req_ssid->SSID[0], &req_ssid->SSID[wlan_ieee80211::MAX_SSID_BYTE_LEN], ssid.data);
scan_opts->ssid = ssid;
}
// Specify BSSID filter, if applicable
common::MacAddr bssid(join_params->assoc_le.bssid);
if (!bssid.IsZero()) {
scan_opts->bssid = bssid;
}
// Determine dwell time
if (scan_opts->is_active) {
if (join_params->scan_le.active_time == static_cast<uint32_t>(-1)) {
// If we hit this, we need to determine how to set the default active time
ZX_ASSERT("Attempt to use default active scan time, but we don't know how to set this");
}
if (join_params->scan_le.active_time == 0) {
return ZX_ERR_INVALID_ARGS;
}
int32_t nprobes = (int32_t)join_params->scan_le.nprobes;
scan_opts->active_scan_max_attempts = nprobes <= 0 ? 1 : nprobes;
// Dwell time is equally split across the # of attempts
scan_opts->dwell_time =
zx::msec(join_params->scan_le.active_time) / scan_opts->active_scan_max_attempts;
BRCMF_DBG(SIM, "Join req - active scan: act time: %u nprobes: %d dwell: %zu",
join_params->scan_le.active_time, join_params->scan_le.nprobes,
scan_opts->dwell_time.get());
} else if (join_params->scan_le.passive_time == static_cast<uint32_t>(-1)) {
// Use default passive time
if (default_passive_time_ == static_cast<uint32_t>(-1)) {
// If we hit this, we need to determine the default default passive time
ZX_ASSERT("Attempt to use default passive scan time, but it hasn't been set yet");
}
scan_opts->dwell_time = zx::msec(default_passive_time_);
} else {
scan_opts->dwell_time = zx::msec(join_params->scan_le.passive_time);
}
// Copy channels from request
scan_opts->channels.resize(num_channels);
const uint16_t* chanspecs = &join_params->assoc_le.chanspec_list[0];
std::copy(&chanspecs[0], &chanspecs[num_channels], scan_opts->channels.data());
scan_opts->on_result_fn =
std::bind(&SimFirmware::AssocScanResultSeen, this, std::placeholders::_1);
scan_opts->on_done_fn = std::bind(&SimFirmware::AssocScanDone, this, std::placeholders::_1);
// Reset assoc state
SetAssocState(AssocState::SCANNING);
assoc_state_.scan_results.clear();
zx_status_t status = ScanStart(std::move(scan_opts));
if (status != ZX_OK) {
BRCMF_DBG(SIM, "Failed to start scan: %s", zx_status_get_string(status));
SetAssocState(AssocState::NOT_ASSOCIATED);
}
return status;
}
zx_status_t SimFirmware::SetIFChanspec(uint16_t ifidx, uint16_t chanspec) {
if (ifidx < 0 || ifidx >= kMaxIfSupported || !iface_tbl_[ifidx].allocated) {
return ZX_ERR_INVALID_ARGS;
}
if (iface_tbl_[ifidx].ap_mode) {
// When it's set for softAP, and if there is a client with a chanspec
if (!iface_tbl_[kClientIfidx].allocated || iface_tbl_[kClientIfidx].chanspec == 0) {
// If no client is activated, just set the chanspec
iface_tbl_[ifidx].chanspec = chanspec;
return ZX_OK;
}
// When a new softAP iface is created, set the chanspec to client iface chanspec, ignore
// the input.
iface_tbl_[ifidx].chanspec = iface_tbl_[kClientIfidx].chanspec;
return ZX_OK;
} else {
// If it's set for clients, change all chanspecs of existing ifaces into the same one(the one we
// want to set).
for (uint16_t i = 0; i < kMaxIfSupported; i++) {
if (iface_tbl_[i].allocated) {
// TODO(zhiyichen): If this operation change the chanspec for softAP iface, send out CSA
// announcement when there is any client connecting to it.
iface_tbl_[i].chanspec = chanspec;
}
}
}
return ZX_OK;
}
// Get the index of IF with the given bsscfgidx
int16_t SimFirmware::GetIfidxByBsscfgidx(int32_t bsscfgidx) {
for (uint8_t i = 0; i < kMaxIfSupported; i++) {
if (iface_tbl_[i].allocated && (bsscfgidx == iface_tbl_[i].bsscfgidx)) {
return i;
}
}
return -1;
}
// Stop the specified bss
zx_status_t SimFirmware::StopInterface(const int32_t bsscfgidx) {
int16_t ifidx = GetIfidxByBsscfgidx(bsscfgidx);
if (ifidx == -1)
return ZX_ERR_IO;
if (iface_tbl_[ifidx].ap_mode) {
StopSoftAP(ifidx);
} else {
DisassocLocalClient(wlan_ieee80211::ReasonCode::LEAVING_NETWORK_DISASSOC);
}
return ZX_OK;
}
zx_status_t SimFirmware::IovarsSet(uint16_t ifidx, const char* name_buf, const void* value_buf,
size_t value_len, bcme_status_t* fw_err) {
uint8_t* value = (uint8_t*)value_buf;
int32_t bsscfgidx = 0;
char* name = (char*)name_buf;
// If it is a bsscfg iovar, handle it accordingly (strip the prefix and extract the
// bsscfgidx.
const size_t bsscfg_prefix_len = strlen(BRCMF_FWIL_BSSCFG_PREFIX);
if (!std::strncmp(name, BRCMF_FWIL_BSSCFG_PREFIX, bsscfg_prefix_len)) {
bsscfgidx = *(reinterpret_cast<const int32_t*>(value));
value += sizeof(bsscfgidx);
ZX_ASSERT(value_len >= sizeof(bsscfgidx));
value_len -= sizeof(bsscfgidx);
if (!value_len)
value = nullptr;
name += bsscfg_prefix_len;
}
// If Error Injection is enabled return with the appropriate status right away
zx_status_t status = ZX_OK;
if (err_inj_.CheckIfErrInjIovarEnabled(name, &status, fw_err, nullptr, ifidx)) {
return status;
}
auto iovar = iovar_table_.find(name);
if (iovar == iovar_table_.end()) {
BRCMF_ERR("Iovar -- %s is not found in iovar table.", name);
return ZX_OK;
}
auto& impl = iovar->second;
status = impl.Set(ifidx, bsscfgidx, value, value_len);
if (status == ZX_ERR_IO_REFUSED) {
*fw_err = BCME_BUFTOOSHORT;
}
return status;
}
zx_status_t SimFirmware::IovarsGet(uint16_t ifidx, const char* name, void* value_out,
size_t value_len, bcme_status_t* fw_err) {
zx_status_t status = ZX_OK;
if (fw_err == nullptr) {
BRCMF_ERR(
"fw_err cannot be nullptr for IovarsGet() calls. IovarsGet() should not be called directly "
"from firmware simulator tests.");
return ZX_ERR_INTERNAL;
} else {
*fw_err = BCME_OK;
}
const std::vector<uint8_t>* err_inj_alt_value;
if (err_inj_.CheckIfErrInjIovarEnabled(name, &status, fw_err, &err_inj_alt_value, ifidx)) {
if (err_inj_alt_value != nullptr) {
// Use provided replacement data
size_t alt_data_size = err_inj_alt_value->size();
memcpy(value_out, err_inj_alt_value->data(), std::min(alt_data_size, value_len));
if (alt_data_size < value_len) {
// Zero out any remaining bytes
uint8_t* bytes_out = reinterpret_cast<uint8_t*>(value_out);
memset(&bytes_out[alt_data_size], 0, value_len - alt_data_size);
}
} else {
memset(value_out, 0, value_len);
}
return status;
}
auto iovar = iovar_table_.find(name);
if (iovar == iovar_table_.end()) {
BRCMF_ERR("Iovar -- %s is not found in iovar table.", name);
memset(value_out, 0, value_len);
return ZX_OK;
}
auto& impl = iovar->second;
status = impl.Get(ifidx, value_out, value_len);
if (status == ZX_ERR_IO_REFUSED) {
// TODO(zhiyichen): If the buffer is too short, set return value to ZX_OK to return dcmd to
// driver. Driver will ignore dcmd if the return value is not ZX_OK. This logic needs to be
// fixed.
status = ZX_OK;
*fw_err = BCME_BUFTOOSHORT;
}
return status;
}
/* Iovar handler function definitions */
zx_status_t SimFirmware::IovarIfaceVarSet(SimIovarSetReq* req) {
ZX_ASSERT_MSG(req->iftbl_offset.has_value(), "offset in sim_iface_entry_t not set");
if (!iface_tbl_[req->ifidx].allocated) {
return ZX_ERR_BAD_STATE;
}
char* base = (char*)&iface_tbl_[req->ifidx];
memcpy(base + req->iftbl_offset.value(), req->value, req->value_len);
return ZX_OK;
}
zx_status_t SimFirmware::IovarIfaceVarGet(SimIovarGetReq* req) {
ZX_ASSERT_MSG(req->iftbl_offset.has_value(), "offset in sim_iface_entry_t not set");
if (!iface_tbl_[req->ifidx].allocated) {
return ZX_ERR_BAD_STATE;
}
char* base = (char*)&iface_tbl_[req->ifidx];
memcpy(req->value, base + req->iftbl_offset.value(), req->value_len);
return ZX_OK;
}
zx_status_t SimFirmware::IovarSet(SimIovarSetReq* req) {
ZX_ASSERT_MSG(req->var_addr.has_value(), "Variable address is not set");
memcpy(req->var_addr.value(), req->value, req->value_len);
return ZX_OK;
}
zx_status_t SimFirmware::IovarGet(SimIovarGetReq* req) {
ZX_ASSERT_MSG(req->var_addr.has_value(), "Variable address is not set");
memcpy(req->value, req->var_addr.value(), req->value_len);
return ZX_OK;
}
zx_status_t SimFirmware::IovarCurEtheraddrSet(SimIovarSetReq* req) {
if (req->value_len != ETH_ALEN) {
return ZX_ERR_INVALID_ARGS;
}
return SetMacAddr(req->ifidx, reinterpret_cast<const uint8_t*>(req->value));
}
zx_status_t SimFirmware::IovarCurEtheraddrGet(SimIovarGetReq* req) {
if (iface_tbl_[req->ifidx].mac_addr_set)
memcpy(req->value, iface_tbl_[req->ifidx].mac_addr.byte, ETH_ALEN);
else
memcpy(req->value, mac_addr_.data(), ETH_ALEN);
return ZX_OK;
}
zx_status_t SimFirmware::IovarPfnMacaddrSet(SimIovarSetReq* req) {
auto pfn_mac = reinterpret_cast<const brcmf_pno_macaddr_le*>(req->value);
memcpy(pfn_mac_addr_.byte, pfn_mac->mac, ETH_ALEN);
return ZX_OK;
}
zx_status_t SimFirmware::IovarPfnMacaddrGet(SimIovarGetReq* req) {
memcpy(req->value, pfn_mac_addr_.byte, ETH_ALEN);
return ZX_OK;
}
zx_status_t SimFirmware::IovarStbcTxSet(SimIovarSetReq* req) {
auto stbc_tx = reinterpret_cast<const int32_t*>(req->value);
if (*stbc_tx != -1 && *stbc_tx != 0 && *stbc_tx != 1) {
BRCMF_ERR("stbc_tx: %d has to be 0, 1 or -1", *stbc_tx);
return ZX_ERR_INVALID_ARGS;
}
if (txstreams_ == 1 && *stbc_tx == 1) {
BRCMF_ERR("stbc_tx cannot be set to 1 when txstreams is 1");
return ZX_ERR_INVALID_ARGS;
}
stbc_tx_ = *stbc_tx;
BRCMF_DBG(SIM, "set stbc tx value: %u", stbc_tx_);
return ZX_OK;
}
zx_status_t SimFirmware::IovarStbcTxGet(SimIovarGetReq* req) {
BRCMF_DBG(SIM, "get stbc_tx value: %u", stbc_tx_);
memcpy(req->value, &stbc_tx_, sizeof(stbc_tx_));
return ZX_OK;
}
zx_status_t SimFirmware::IovarTxstreamsSet(SimIovarSetReq* req) {
auto txstreams = reinterpret_cast<const uint32_t*>(req->value);
if (*txstreams >= 1) {
txstreams_ = *txstreams;
BRCMF_DBG(SIM, "set txstreams value: %u", *txstreams);
return ZX_OK;
}
BRCMF_ERR("txstreams: %d has to be atleast >= 1", *txstreams);
return ZX_ERR_INVALID_ARGS;
}
zx_status_t SimFirmware::IovarTxstreamsGet(SimIovarGetReq* req) {
BRCMF_DBG(SIM, "get txstreams value: %u", txstreams_);
memcpy(req->value, &txstreams_, sizeof(txstreams_));
return ZX_OK;
}
zx_status_t SimFirmware::IovarWsecKeySet(SimIovarSetReq* req) {
auto wk_req = reinterpret_cast<const brcmf_wsec_key_le*>(req->value);
// Ensure that Primary Key does not have a mac address (all zeros)
if (wk_req->flags == BRCMF_PRIMARY_KEY) {
ZX_ASSERT_MSG(std::memcmp(wk_req->ea, kZeroMac.byte, ETH_ALEN) == 0,
"Group Key Mac should be all zeros");
}
std::vector<brcmf_wsec_key_le>& key_list = iface_tbl_[req->ifidx].wsec_key_list;
auto key_iter = std::find_if(key_list.begin(), key_list.end(),
[=](brcmf_wsec_key_le& k) { return k.index == wk_req->index; });
// If the key with same index exists, override it, if not, add a new key.
if (key_iter != key_list.end()) {
*key_iter = *wk_req;
} else {
// Use the first key index as current key index, in real case it will only change by AP.
if (key_list.empty())
iface_tbl_[req->ifidx].cur_key_idx = wk_req->index;
key_list.push_back(*wk_req);
}
return ZX_OK;
}
zx_status_t SimFirmware::IovarWsecKeyGet(SimIovarGetReq* req) {
std::vector<brcmf_wsec_key_le>& key_list = iface_tbl_[req->ifidx].wsec_key_list;
auto key_iter = std::find_if(key_list.begin(), key_list.end(), [=](brcmf_wsec_key_le& k) {
return k.index == iface_tbl_[req->ifidx].cur_key_idx;
});
if (key_iter == key_list.end()) {
return ZX_ERR_NOT_FOUND;
}
memcpy(req->value, &(*key_iter), sizeof(brcmf_wsec_key_le));
return ZX_OK;
}
zx_status_t SimFirmware::IovarChanspecSet(SimIovarSetReq* req) {
auto chanspec = reinterpret_cast<const uint16_t*>(req->value);
// TODO(karthikrish) Add multi channel support in SIM Env. For now ensure all IFs use the same
// channel
return (SetIFChanspec(req->ifidx, *chanspec));
}
zx_status_t SimFirmware::IovarMpcSet(SimIovarSetReq* req) {
auto mpc = reinterpret_cast<const uint32_t*>(req->value);
// Ensure that mpc is never enabled when AP has been started
if (softap_ifidx_ != std::nullopt) {
// Ensure that mpc is 0 if the SoftAP has been started
ZX_ASSERT_MSG(*mpc == 0, "mpc should be 0 when SoftAP is active");
}
mpc_ = *mpc;
return ZX_OK;
}
zx_status_t SimFirmware::IovarInterfaceRemoveSet(SimIovarSetReq* req) {
return HandleIfaceRequest(false, req->value, req->value_len, req->bsscfgidx);
}
zx_status_t SimFirmware::IovarSsidSet(SimIovarSetReq* req) {
return HandleIfaceRequest(true, req->value, req->value_len, req->bsscfgidx);
}
zx_status_t SimFirmware::IovarEscanSet(SimIovarSetReq* req) {
// For now scanning on softAP iface is not supported yet.
if (req->ifidx != kClientIfidx) {
BRCMF_ERR("Not scanning with client iface.");
return ZX_ERR_INVALID_ARGS;
}
return HandleEscanRequest(reinterpret_cast<const brcmf_escan_params_le*>(req->value),
req->value_len);
}
zx_status_t SimFirmware::IovarJoinSet(SimIovarSetReq* req) {
if (req->ifidx != kClientIfidx) {
BRCMF_ERR("Not joining with client iface.");
return ZX_ERR_INVALID_ARGS;
}
// This is a start point of authentication and association operation, make sure the client
// iface is allocated.
if (!iface_tbl_[kClientIfidx].allocated) {
BRCMF_ERR("Client iface has not been allocated.");
return ZX_ERR_BAD_STATE;
}
// Don't cast yet because last element is variable length
return HandleJoinRequest(req->value, req->value_len);
}
zx_status_t SimFirmware::IovarBssSet(SimIovarSetReq* req) {
auto bss_info = reinterpret_cast<const brcmf_bss_ctrl*>(req->value);
// We do not know how non-zero value is handled in real FW.
ZX_ASSERT(bss_info->value == 0);
return StopInterface(bss_info->bsscfgidx);
}
zx_status_t SimFirmware::IovarAssocMgrCmdSet(SimIovarSetReq* req) {
BRCMF_DBG(SIM, "Receive assoc_mgr_cmd in sim-fw.");
ZX_ASSERT_MSG(req->ifidx == kClientIfidx, "SAE authentication only supported on client iface.");
auto cmd = reinterpret_cast<const assoc_mgr_cmd_t*>(req->value);
if (cmd->version != ASSOC_MGR_CURRENT_VERSION) {
BRCMF_INFO("Version number doesn't match the current one, but ignoring it in sim-fw for now.");
}
switch (cmd->cmd) {
case ASSOC_MGR_CMD_PAUSE_ON_EVT:
if (cmd->params == ASSOC_MGR_PARAMS_PAUSE_EVENT_AUTH_RESP) {
// When driver received JOIN_START event and successfully notified SME that the SAE
// authentication should start by sending up handshake indication, it will send a
// assoc_mgr_cmd with this parameter, telling firmware to expect the first authentication
// frame from external supplicant. Here we only check whether the auth_state is correct.
if (auth_state_.state != AuthState::EXPECTING_EXTERNAL_COMMIT) {
BRCMF_ERR(
"Incorrect state, START_AUTH event wasn't sent up to the driver, or the SAE "
"process has been started. Ignoring the command and return.");
return ZX_ERR_BAD_STATE;
}
} else if (cmd->params == ASSOC_MGR_PARAMS_EVENT_NONE) {
// Driver is trying to start association after finishing SAE authentication.
if (auth_state_.state != AuthState::EXPECTING_EXTERNAL_HANDSHAKE_RESP) {
BRCMF_ERR(
"Unexpected HANDSHAKE_RESP from external supplicant. Ignoring the command and "
"return.");
return ZX_ERR_BAD_STATE;
}
// Handshake resp received from external supplicant, cancel timer.
hw_.CancelCallback(auth_state_.auth_timer_id);
auth_state_.state = AuthState::AUTHENTICATED;
AssocStart();
return ZX_OK;
}
break;
case ASSOC_MGR_CMD_ABORT_ASSOC:
ZX_ASSERT_MSG(false, "Not supporting this command for assoc_mgr_cmd yet.");
break;
case ASSOC_MGR_CMD_SEND_AUTH: {
ZX_ASSERT_MSG(req->ifidx == kClientIfidx,
"SAE authentication only supported on client iface.");
auto sae_frame = reinterpret_cast<const brcmf_sae_auth_frame*>(&cmd->params);
if (memcmp(sae_frame->mac_hdr.addr1.byte, assoc_state_.opts->bssid.byte, ETH_ALEN) ||
memcmp(sae_frame->mac_hdr.addr3.byte, assoc_state_.opts->bssid.byte, ETH_ALEN)) {
BRCMF_ERR(
"Dest addr does not match in SAE frame from external supplicant. Ignoring frame.");
return ZX_ERR_INVALID_ARGS;
}
// Authentication algorithm field must be SAE.
if (sae_frame->auth_hdr.auth_algorithm_number != BRCMF_AUTH_MODE_SAE) {
BRCMF_ERR("Authentication algorithm number does not match SAE algorithm number");
return ZX_ERR_INVALID_ARGS;
}
size_t sae_payload_length = cmd->length - offsetof(struct brcmf_sae_auth_frame, sae_payload);
if (LocalUpdateExternalSaeStatus(
sae_frame->auth_hdr.auth_txn_seq_number,
static_cast<wlan_ieee80211::StatusCode>(sae_frame->auth_hdr.status_code),
sae_frame->sae_payload, sae_payload_length) != ZX_OK) {
BRCMF_ERR("Update SAE status failed with auth frame from external supllicant.");
return ZX_ERR_BAD_STATE;
}
break;
}
default:
ZX_ASSERT_MSG(false, "Command type %u is not currently supported for assoc_mgr_cmd.",
cmd->cmd);
break;
}
return ZX_OK;
}
zx_status_t SimFirmware::IovarCrashSet(SimIovarSetReq* req) {
// No need to check the value of 'crash' iovar.
ResetSimFirmware();
return ZX_OK;
}
zx_status_t SimFirmware::IovarVerGet(SimIovarGetReq* req) {
strlcpy(static_cast<char*>(req->value), kFirmwareVer, req->value_len);
return ZX_OK;
}
zx_status_t SimFirmware::IovarRxchainGet(SimIovarGetReq* req) {
if (!iface_tbl_[req->ifidx].allocated) {
return ZX_ERR_BAD_STATE;
}
// rxchain 1 indicates antenna index 0.
const uint32_t sim_rxchain = 1;
memcpy(req->value, &sim_rxchain, sizeof(uint32_t));
return ZX_OK;
}
zx_status_t SimFirmware::IovarSnrGet(SimIovarGetReq* req) {
if (!iface_tbl_[req->ifidx].allocated) {
return ZX_ERR_BAD_STATE;
}
int32_t sim_snr = 40;
memcpy(req->value, &sim_snr, sizeof(sim_snr));
return ZX_OK;
}
zx_status_t SimFirmware::IovarWstatsCountersGet(SimIovarGetReq* req) {
if (!iface_tbl_[req->ifidx].allocated) {
return ZX_ERR_BAD_STATE;
}
wl_wstats_cnt_t wstats_cnt = {
.version = WSTATS_CNT_T_VERSION,
};
// Manually populate a few histograms.
const uint16_t snr_db = 60;
const uint32_t snr_num_frames = 50;
wstats_cnt.rxsnr[snr_db] = snr_num_frames;
const uint32_t noiseflr_dbm_index = 170;
const uint32_t noiseflr_num_frames = 20;
wstats_cnt.rxnoiseflr[noiseflr_dbm_index] = noiseflr_num_frames;
const uint32_t rssi_dbm_index = 190;
const uint32_t rssi_num_frames = 40;
wstats_cnt.rxrssi[rssi_dbm_index] = rssi_num_frames;
const uint32_t rate_index = 7;
const uint32_t rate_num_frames = 80;
wstats_cnt.rx11g[rate_index] = rate_num_frames;
memcpy(req->value, &wstats_cnt, sizeof(wl_wstats_cnt_t));
return ZX_OK;
}
zx_status_t SimFirmware::IovarAssocInfoGet(SimIovarGetReq* req) {
auto result_ptr = static_cast<brcmf_cfg80211_assoc_ielen_le*>(req->value);
result_ptr->req_len = 0;
result_ptr->resp_len = assoc_resp_ies_len_;
return ZX_OK;
}
zx_status_t SimFirmware::IovarAssocRespIesGet(SimIovarGetReq* req) {
if (req->value_len < assoc_resp_ies_len_) {
BRCMF_ERR("Buffer length is too small for the prepared assoc response ies.");
return ZX_ERR_IO_REFUSED;
}
memcpy(req->value, assoc_resp_ies_, assoc_resp_ies_len_);
return ZX_OK;
}
zx_status_t SimFirmware::IovarCapGet(SimIovarGetReq* req) {
strlcpy(static_cast<char*>(req->value), kFirmwareCap, req->value_len);
return ZX_OK;
}
zx_status_t SimFirmware::IovarNmodeGet(SimIovarGetReq* req) {
// TODO: Provide means to simulate hardware without nmode.
uint32_t* result_ptr = static_cast<uint32_t*>(req->value);
*result_ptr = 1;
return ZX_OK;
}
zx_status_t SimFirmware::IovarVhtModeGet(SimIovarGetReq* req) {
// TODO: Provide means to simulate hardware without vhtmode.
uint32_t* result_ptr = static_cast<uint32_t*>(req->value);
*result_ptr = 1;
return ZX_OK;
}
zx_status_t SimFirmware::IovarRrmGet(SimIovarGetReq* req) {
// TODO: Provide means to simulate hardware without rrm.
uint32_t* result_ptr = static_cast<uint32_t*>(req->value);
*result_ptr = 1;
return ZX_OK;
}
zx_status_t SimFirmware::IovarWmeAcStaGet(SimIovarGetReq* req) {
// Note: the below mocked AC parameters are slightly different from default values
// because we set different values for each AC to make sure in the test that
// the right ACs are parsed.
edcf_acparam_t params[4];
// AC_BE
params[0].aci = 4; // aifsn
params[0].ecw = 5 + (10 << 4); // ecw_min + (ecw_max << 4)
params[0].txop = 0;
// AC_BK
params[1].aci = 7 + (1 << 5); // aifsn + (aci << 5)
params[1].ecw = 6 + (11 << 4); // ecw_min + (ecw_max << 4)
params[1].txop = 0;
// AC_VI
params[2].aci = 3 + (2 << 5); // aifsn + (aci << 5)
params[2].ecw = 4 + (5 << 4); // ecw_min + (ecw_max << 4)
params[2].txop = 94;
// AC_VO
params[3].aci = 2 + (1 << 4) + (3 << 5); // aifsn + (acm << 4) + (aci << 5)
params[3].ecw = 2 + (4 << 4); // ecw_min + (ecw_max << 4)
params[3].txop = 47;
memcpy(req->value, params, sizeof(params));
return ZX_OK;
}
zx_status_t SimFirmware::IovarWmeApsdGet(SimIovarGetReq* req) {
uint32_t* result_ptr = static_cast<uint32_t*>(req->value);
*result_ptr = 1;
return ZX_OK;
}
// If setting for the first time, save it as system mac address as well
zx_status_t SimFirmware::SetMacAddr(uint16_t ifidx, const uint8_t* mac_addr) {
if (mac_addr_set_ == false) {
BRCMF_DBG(SIM, "Setting system mac addr: " FMT_MAC, FMT_MAC_ARGS(mac_addr));
memcpy(mac_addr_.data(), mac_addr, ETH_ALEN);
memcpy(pfn_mac_addr_.byte, mac_addr, ETH_ALEN);
mac_addr_set_ = true;
}
memcpy(iface_tbl_[ifidx].mac_addr.byte, mac_addr, ETH_ALEN);
iface_tbl_[ifidx].mac_addr_set = true;
BRCMF_DBG(SIM, "Setting mac addr ifidx: %d: " FMT_MAC, ifidx, FMT_MAC_ARGS(mac_addr));
return ZX_OK;
}
common::MacAddr SimFirmware::GetMacAddr(uint16_t ifidx) {
if (ifidx < kMaxIfSupported && iface_tbl_[ifidx].allocated && iface_tbl_[ifidx].mac_addr_set) {
return iface_tbl_[ifidx].mac_addr;
}
ZX_ASSERT(mac_addr_set_);
return common::MacAddr(mac_addr_);
}
zx_status_t SimFirmware::ScanStart(std::unique_ptr<ScanOpts> opts) {
if (scan_state_.state != ScanState::STOPPED) {
// Can't start a scan while another is in progress
return ZX_ERR_NOT_SUPPORTED;
}
if (!iface_tbl_[kClientIfidx].allocated) {
BRCMF_ERR("client iface has not been allocated.");
return ZX_ERR_BAD_STATE;
}
// I believe in real firmware this will just search all channels. We need to define that set in
// order for this functionality to work.
ZX_ASSERT_MSG(opts->channels.size() >= 1,
"No channels provided to escan start request - unsupported");
// Configure state
scan_state_.state = ScanState::SCANNING;
scan_state_.opts = std::move(opts);
scan_state_.channel_index = 0;
// Start scan
uint16_t chanspec = scan_state_.opts->channels[scan_state_.channel_index++];
wlan_channel_t channel;
chanspec_to_channel(&d11_inf_, chanspec, &channel);
hw_.SetChannel(channel);
// Do an active scan using random mac
if (scan_state_.opts->is_active) {
scan_state_.active_scan_attempts = 1;
simulation::SimProbeReqFrame probe_req_frame(pfn_mac_addr_);
hw_.Tx(probe_req_frame);
}
hw_.EnableRx();
hw_.RequestCallback(std::bind(&SimFirmware::ScanContinue, this), scan_state_.opts->dwell_time);
return ZX_OK;
}
// Continue or stop scanning based on scan type.
// Active scan - continue with current channel until max attempts of probes sent
// or else switch to next channel
// Passive scan - switch to next channel
void SimFirmware::ScanContinue() {
switch (scan_state_.state) {
case ScanState::STOPPED:
// We may see this event if a scan was cancelled -- just ignore it
return;
case ScanState::HOME:
// We don't yet support intermittent scanning
return;
case ScanState::SCANNING:
// If active scan, check and resend probe request if max attempts not reached.
if (scan_state_.opts->is_active &&
scan_state_.active_scan_attempts < scan_state_.opts->active_scan_max_attempts) {
BRCMF_DBG(SIM, "active scan continue: %d att: %d max: %d", scan_state_.opts->is_active,
scan_state_.active_scan_attempts, scan_state_.opts->active_scan_max_attempts);
// Note that the channel remains the same
scan_state_.active_scan_attempts++;
simulation::SimProbeReqFrame probe_req_frame(pfn_mac_addr_);
hw_.Tx(probe_req_frame);
hw_.RequestCallback(std::bind(&SimFirmware::ScanContinue, this),
scan_state_.opts->dwell_time);
return;
}
if (scan_state_.channel_index >= scan_state_.opts->channels.size()) {
ScanComplete(BRCMF_E_STATUS_SUCCESS);
} else {
// Scan next channel
uint16_t chanspec = scan_state_.opts->channels[scan_state_.channel_index++];
wlan_channel_t channel;
chanspec_to_channel(&d11_inf_, chanspec, &channel);
hw_.SetChannel(channel);
BRCMF_DBG(SIM, "Continue scan - next chanspec: 0x%x", chanspec);
if (scan_state_.opts->is_active) {
scan_state_.active_scan_attempts = 1;
simulation::SimProbeReqFrame probe_req_frame(pfn_mac_addr_);
hw_.Tx(probe_req_frame);
}
hw_.RequestCallback(std::bind(&SimFirmware::ScanContinue, this),
scan_state_.opts->dwell_time);
}
}
}
// Clean up state after a scan request is finished
void SimFirmware::ScanComplete(brcmf_fweh_event_status_t status) {
if (scan_state_.opts->is_active) {
BRCMF_DBG(SIM, "Resetting pfn_mac_addr_ to system mac addr: " FMT_MAC,
FMT_MAC_ARGS(mac_addr_.data()));
memcpy(pfn_mac_addr_.byte, mac_addr_.data(), ETH_ALEN);
}
hw_.DisableRx();
scan_state_.state = ScanState::STOPPED;
// Restore the operating channel since Scan is done. This applies
// only if the scan was started when the IF is already associated
if (iface_tbl_[kClientIfidx].chanspec) {
wlan_channel_t channel;
chanspec_to_channel(&d11_inf_, iface_tbl_[kClientIfidx].chanspec, &channel);
hw_.SetChannel(channel);
}
scan_state_.opts->on_done_fn(status);
scan_state_.opts = nullptr;
}
// Send an event to the firmware notifying them that the scan has completed.
zx_status_t SimFirmware::HandleEscanRequest(const brcmf_escan_params_le* escan_params,
size_t params_len) {
if (escan_params->version != BRCMF_ESCAN_REQ_VERSION) {
BRCMF_DBG(SIM, "Mismatched escan version (expected %d, saw %d) - ignoring request",
BRCMF_ESCAN_REQ_VERSION, escan_params->version);
return ZX_ERR_NOT_SUPPORTED;
}
switch (escan_params->action) {
case WL_ESCAN_ACTION_START:
return EscanStart(escan_params->sync_id, &escan_params->params_le,
params_len - offsetof(brcmf_escan_params_le, params_le));
case WL_ESCAN_ACTION_CONTINUE:
ZX_ASSERT_MSG(0, "Unimplemented escan option WL_ESCAN_ACTION_CONTINUE");
return ZX_ERR_NOT_SUPPORTED;
case WL_ESCAN_ACTION_ABORT:
ZX_ASSERT_MSG(0, "Unimplemented escan option WL_ESCAN_ACTION_ABORT");
return ZX_ERR_NOT_SUPPORTED;
default:
ZX_ASSERT_MSG(0, "Unrecognized escan option %d", escan_params->action);
return ZX_ERR_NOT_SUPPORTED;
}
return ZX_OK;
}
// When asked to start an escan, we will listen on each of the specified channels for the requested
// duration (dwell time). We accomplish this by setting up a future event for the next channel,
// iterating until we have scanned all channels.
zx_status_t SimFirmware::EscanStart(uint16_t sync_id, const brcmf_scan_params_le* params,
size_t params_len) {
auto scan_opts = std::make_unique<ScanOpts>();
scan_opts->sync_id = sync_id;
switch (params->scan_type) {
case BRCMF_SCANTYPE_ACTIVE:
scan_opts->is_active = true;
if (params->active_time == static_cast<uint32_t>(-1)) {
BRCMF_ERR("No active scan time in parameter");
return ZX_ERR_INVALID_ARGS;
} else {
int32_t nprobes = (int32_t)params->nprobes;
scan_opts->active_scan_max_attempts = nprobes <= 0 ? 1 : nprobes;
// Dwell time is equally split across the # of attempts
scan_opts->dwell_time = zx::msec(params->active_time) / scan_opts->active_scan_max_attempts;
BRCMF_DBG(SIM, "Active scan req: act time: %u nprobes: %d act time: %d dwell: %zu",
params->active_time, params->nprobes, params->active_time,
scan_opts->dwell_time.get());
}
break;
case BRCMF_SCANTYPE_PASSIVE:
scan_opts->is_active = false;
// Determine dwell time. If specified in the request, use that value. Otherwise, if a default
// dwell time has been specified, use that value. Otherwise, fail.
if (params->passive_time == static_cast<uint32_t>(-1)) {
if (default_passive_time_ == static_cast<uint32_t>(-1)) {
BRCMF_ERR("Attempt to use default passive time, iovar hasn't been set yet");
return ZX_ERR_INVALID_ARGS;
}
scan_opts->dwell_time = zx::msec(default_passive_time_);
} else {
scan_opts->dwell_time = zx::msec(params->passive_time);
}
break;
default:
BRCMF_DBG(SIM, "Invalid scan type requested: %d", params->scan_type);
return ZX_ERR_INVALID_ARGS;
}
size_t num_channels = params->channel_num & BRCMF_SCAN_PARAMS_COUNT_MASK;
// Configure state
scan_opts->channels.resize(num_channels);
std::copy(¶ms->channel_list[0], ¶ms->channel_list[num_channels],
scan_opts->channels.data());
scan_opts->on_result_fn = std::bind(&SimFirmware::EscanResultSeen, this, std::placeholders::_1);
scan_opts->on_done_fn = std::bind(&SimFirmware::EscanComplete, this, std::placeholders::_1);
return ScanStart(std::move(scan_opts));
}
void SimFirmware::EscanComplete(brcmf_fweh_event_status_t event_status) {
// The last field in a brcmf_escan_result_le is variable-length (although it isn't defined that
// way). To generate a scan complete message, it has to have no BSS entries.
size_t buf_len = offsetof(brcmf_escan_result_le, bss_info_le);
auto buf = std::make_unique<std::vector<uint8_t>>(buf_len);
// Assemble the result buffer. As per above, we are making a pointer to the escan_result, but we
// MUST NOT reference the last field (bss_info_le), since it hasn't been allocated.
auto result = reinterpret_cast<brcmf_escan_result_le*>(buf->data());
result->buflen = buf_len;
result->version = BRCMF_BSS_INFO_VERSION;
result->sync_id = scan_state_.opts->sync_id;
result->bss_count = 0;
SendEventToDriver(buf_len, std::move(buf), BRCMF_E_ESCAN_RESULT, event_status, kClientIfidx);
}
void SimFirmware::Rx(std::shared_ptr<const simulation::SimFrame> frame,
std::shared_ptr<const simulation::WlanRxInfo> info) {
if (frame->FrameType() == simulation::SimFrame::FRAME_TYPE_MGMT) {
auto mgmt_frame = std::static_pointer_cast<const simulation::SimManagementFrame>(frame);
RxMgmtFrame(mgmt_frame, info);
} else if (frame->FrameType() == simulation::SimFrame::FRAME_TYPE_DATA) {
auto data_frame = std::static_pointer_cast<const simulation::SimDataFrame>(frame);
RxDataFrame(data_frame, info);
}
}
void SimFirmware::RxMgmtFrame(std::shared_ptr<const simulation::SimManagementFrame> mgmt_frame,
std::shared_ptr<const simulation::WlanRxInfo> info) {
switch (mgmt_frame->MgmtFrameType()) {
case simulation::SimManagementFrame::FRAME_TYPE_BEACON: {
auto beacon = std::static_pointer_cast<const simulation::SimBeaconFrame>(mgmt_frame);
RxBeacon(info->channel, beacon, info->signal_strength);
break;
}
case simulation::SimManagementFrame::FRAME_TYPE_PROBE_RESP: {
auto probe_resp = std::static_pointer_cast<const simulation::SimProbeRespFrame>(mgmt_frame);
RxProbeResp(info->channel, probe_resp, info->signal_strength);
break;
}
case simulation::SimManagementFrame::FRAME_TYPE_ASSOC_REQ: {
auto assoc_req = std::static_pointer_cast<const simulation::SimAssocReqFrame>(mgmt_frame);
RxAssocReq(assoc_req);
break;
}
case simulation::SimManagementFrame::FRAME_TYPE_ASSOC_RESP: {
auto assoc_resp = std::static_pointer_cast<const simulation::SimAssocRespFrame>(mgmt_frame);
RxAssocResp(assoc_resp);
break;
}
case simulation::SimManagementFrame::FRAME_TYPE_DISASSOC_REQ: {
auto disassoc_req =
std::static_pointer_cast<const simulation::SimDisassocReqFrame>(mgmt_frame);
RxDisassocReq(disassoc_req);
break;
}
case simulation::SimManagementFrame::FRAME_TYPE_AUTH: {
auto auth_resp = std::static_pointer_cast<const simulation::SimAuthFrame>(mgmt_frame);
RxAuthFrame(auth_resp);
break;
}
case simulation::SimManagementFrame::FRAME_TYPE_DEAUTH: {
auto deauth_req = std::static_pointer_cast<const simulation::SimDeauthFrame>(mgmt_frame);
RxDeauthReq(deauth_req);
break;
}
default:
break;
}
}
bool SimFirmware::OffloadArpFrame(int16_t ifidx,
std::shared_ptr<const simulation::SimDataFrame> data_frame) {
// Feature is disabled for this interface
if (arpoe_ == 0) {
return false;
}
if (data_frame->payload_.size() < (sizeof(ethhdr) + sizeof(ether_arp))) {
return false;
}
auto eth_hdr = reinterpret_cast<const ethhdr*>(data_frame->payload_.data());
if (ntohs(eth_hdr->h_proto) != ETH_P_ARP) {
return false;
}
auto arp_hdr = reinterpret_cast<const ether_arp*>(&data_frame->payload_.data()[sizeof(eth_hdr)]);
uint16_t ar_op = ntohs(arp_hdr->ea_hdr.ar_op);
if (ar_op == ARPOP_REQUEST) {
// TODO: Actually construct the ARP reply, which would require us to sniff for IP addresses.
// For now, not forwarding the packet to the host is enough.
return (arp_ol_ & BRCMF_ARP_OL_AGENT) && (arp_ol_ & BRCMF_ARP_OL_PEER_AUTO_REPLY);
}
// TODO: Add support for ARP offloading of other commands
ZX_ASSERT_MSG(0, "Support for ARP offloading (op = %d) unimplemented", ar_op);
return false;
}
void SimFirmware::RxDataFrame(std::shared_ptr<const simulation::SimDataFrame> data_frame,
std::shared_ptr<const simulation::WlanRxInfo> info) {
bool is_broadcast = (data_frame->addr1_ == common::kBcastMac);
for (uint8_t idx = 0; idx < kMaxIfSupported; idx++) {
if (!iface_tbl_[idx].allocated)
continue;
if (!(is_broadcast || (data_frame->addr1_ == iface_tbl_[idx].mac_addr)))
continue;
if (OffloadArpFrame(idx, data_frame))
continue;
if (idx == kClientIfidx && assoc_state_.state != AssocState::ASSOCIATED) {
// Receiving a unicast packet before client is associated. Send a deauth event
// to driver (in the real world we would have sent a deauth frame to the sender
BRCMF_DBG(SIM, "Sending E_DEAUTH to driver");
SendEventToDriver(0, nullptr, BRCMF_E_DEAUTH, BRCMF_E_STATUS_SUCCESS, idx, nullptr, 0,
BRCMF_E_REASON_UCAST_FROM_UNASSOC_STA);
continue;
}
SendFrameToDriver(idx, data_frame->payload_.size(), data_frame->payload_, info);
}
}
// Start or restart the beacon watchdog. This is a timeout event mirroring how the firmware can
// detect when a connection is lost from the lack of beacons received.
void SimFirmware::RestartBeaconWatchdog() {
DisableBeaconWatchdog();
assoc_state_.is_beacon_watchdog_active = true;
hw_.RequestCallback(std::bind(&SimFirmware::HandleBeaconTimeout, this), zx::sec(beacon_timeout_),
&assoc_state_.beacon_watchdog_id_);
}
void SimFirmware::DisableBeaconWatchdog() {
if (assoc_state_.is_beacon_watchdog_active) {
hw_.CancelCallback(assoc_state_.beacon_watchdog_id_);
}
}
void SimFirmware::HandleBeaconTimeout() {
// Ignore if we are not associated
if (assoc_state_.state != AssocState::ASSOCIATED) {
return;
}
assoc_state_.is_beacon_watchdog_active = false;
// Indicate to the driver that we're disassociating due to lost beacons
SendEventToDriver(0, nullptr, BRCMF_E_LINK, BRCMF_E_STATUS_SUCCESS, kClientIfidx, 0,
BRCMF_E_REASON_LOW_RSSI);
SendEventToDriver(0, nullptr, BRCMF_E_LINK, BRCMF_E_STATUS_SUCCESS, kClientIfidx, 0,
BRCMF_E_REASON_DEAUTH);
AssocClearContext();
}
void SimFirmware::ConductChannelSwitch(const wlan_channel_t& dst_channel, uint8_t mode) {
// Change fw and hw channel
uint16_t chanspec;
ZX_ASSERT_MSG(iface_tbl_[kClientIfidx].allocated, "No client found!");
hw_.SetChannel(dst_channel);
chanspec = channel_to_chanspec(&d11_inf_, &dst_channel);
SetIFChanspec(kClientIfidx, chanspec);
// Send up CSA event to driver
auto buf = std::make_unique<std::vector<uint8_t>>(sizeof(uint8_t));
*(buf->data()) = mode;
SendEventToDriver(sizeof(uint8_t), std::move(buf), BRCMF_E_CSA_COMPLETE_IND,
BRCMF_E_STATUS_SUCCESS, kClientIfidx);
// Clear state
channel_switch_state_.state = ChannelSwitchState::HOME;
}
// static
int8_t SimFirmware::RssiDbmFromSignalStrength(double signal_strength) {
// truncate signal strength to rssi unit
if (signal_strength > INT8_MAX) {
return INT8_MAX;
} else if (signal_strength < INT8_MIN) {
return INT8_MIN;
}
return signal_strength;
}
void SimFirmware::RxBeacon(const wlan_channel_t& channel,
std::shared_ptr<const simulation::SimBeaconFrame> frame,
double signal_strength) {
if (scan_state_.state == ScanState::SCANNING && !scan_state_.opts->is_active) {
int8_t rssi_dbm = RssiDbmFromSignalStrength(signal_strength);
ScanResult scan_result = {
.channel = channel, .bssid = frame->bssid_, .rssi_dbm = rssi_dbm, .ies = frame->IEs_};
scan_result.bss_capability.set_val(frame->capability_info_.val());
scan_state_.opts->on_result_fn(scan_result);
// TODO(fxbug.dev/49350): Channel switch during scanning need to be supported.
} else if (assoc_state_.state == AssocState::ASSOCIATED &&
frame->bssid_ == assoc_state_.opts->bssid) {
// if we're associated with this AP, start/restart the beacon watchdog
RestartBeaconWatchdog();
auto ie = frame->FindIe(simulation::InformationElement::IE_TYPE_CSA);
if (ie == nullptr) {
return;
}
// If CSA IE exists.
auto csa_ie = std::static_pointer_cast<simulation::CsaInformationElement>(ie);
// Get current chanspec of client ifidx and convert to channel.
wlan_channel_t channel = GetIfChannel(false);
zx::duration SwitchDelay = frame->interval_ * (int64_t)csa_ie->channel_switch_count_;
if (channel_switch_state_.state == ChannelSwitchState::HOME) {
// If the destination channel is the same as current channel, just ignore it.
if (csa_ie->new_channel_number_ == channel.primary) {
return;
}
channel.primary = csa_ie->new_channel_number_;
channel_switch_state_.new_channel = csa_ie->new_channel_number_;
channel_switch_state_.state = ChannelSwitchState::SWITCHING;
} else {
ZX_ASSERT(channel_switch_state_.state == ChannelSwitchState::SWITCHING);
if (csa_ie->new_channel_number_ == channel_switch_state_.new_channel) {
return;
}
// If the new channel is different from the previous dst channel, cancel callback.
hw_.CancelCallback(channel_switch_state_.switch_timer_id);
// If it's the same as current channel for this client before switching, just simply cancel
// the switch event and clear state.
if (csa_ie->new_channel_number_ == channel.primary) {
channel_switch_state_.state = ChannelSwitchState::HOME;
return;
}
// Schedule a new event when dst channel change.
channel.primary = csa_ie->new_channel_number_;
}
hw_.RequestCallback(
std::bind(&SimFirmware::ConductChannelSwitch, this, channel, csa_ie->channel_switch_mode_),
SwitchDelay, &channel_switch_state_.switch_timer_id);
}
}
void SimFirmware::RxProbeResp(const wlan_channel_t& channel,
std::shared_ptr<const simulation::SimProbeRespFrame> frame,
double signal_strength) {
if (scan_state_.state != ScanState::SCANNING || !scan_state_.opts->is_active) {
return;
}
int8_t rssi_dbm = SimFirmware::RssiDbmFromSignalStrength(signal_strength);
ScanResult scan_result = {
.channel = channel, .bssid = frame->src_addr_, .rssi_dbm = rssi_dbm, .ies = frame->IEs_};
scan_result.bss_capability.set_val(frame->capability_info_.val());
scan_state_.opts->on_result_fn(scan_result);
}
// Handle an Rx Beacon sent to us from the hardware, using it to fill in all of the fields in a
// brcmf_escan_result.
void SimFirmware::EscanResultSeen(const ScanResult& result_in) {
std::vector<uint8_t> ie_buf;
for (const auto& ie : result_in.ies) {
if (ie == nullptr) {
continue;
}
switch (ie->IeType()) {
case simulation::InformationElement::IE_TYPE_SSID: {
const auto ssid_ie = std::static_pointer_cast<simulation::SsidInformationElement>(ie);
std::vector<uint8_t> current_ie_buf = ssid_ie->ToRawIe();
ie_buf.insert(ie_buf.end(), current_ie_buf.begin(), current_ie_buf.end());
break;
}
case simulation::InformationElement::IE_TYPE_CSA: {
const auto csa_ie = std::static_pointer_cast<simulation::CsaInformationElement>(ie);
std::vector<uint8_t> current_ie_buf = csa_ie->ToRawIe();
ie_buf.insert(ie_buf.end(), current_ie_buf.begin(), current_ie_buf.end());
break;
}
case simulation::InformationElement::IE_TYPE_WPA1:
__FALLTHROUGH;
case simulation::InformationElement::IE_TYPE_WPA2:
__FALLTHROUGH;
default:
break;
}
}
// scan_result_size includes all BSS info structures (each including IEs). Like the firmware, we
// only send one result back at a time.
size_t scan_result_size = roundup(sizeof(brcmf_escan_result_le) + ie_buf.size(), 4);
auto buf = std::make_unique<std::vector<uint8_t>>(scan_result_size);
uint8_t* buffer_data = buf->data();
auto result_out = reinterpret_cast<brcmf_escan_result_le*>(buffer_data);
result_out->buflen = scan_result_size;
result_out->version = BRCMF_BSS_INFO_VERSION;
result_out->sync_id = scan_state_.opts->sync_id;
result_out->bss_count = 1;
struct brcmf_bss_info_le* bss_info = &result_out->bss_info_le;
bss_info->version = BRCMF_BSS_INFO_VERSION;
// length of this record (includes IEs)
bss_info->length = roundup(sizeof(brcmf_bss_info_le) + ie_buf.size(), 4);
// channel
bss_info->chanspec = channel_to_chanspec(&d11_inf_, &result_in.channel);
// capability
bss_info->capability = result_in.bss_capability.val();
// ssid
bss_info->SSID_len = 0; // SSID will go into an IE
// bssid
ZX_ASSERT(sizeof(bss_info->BSSID) == common::kMacAddrLen);
memcpy(bss_info->BSSID, result_in.bssid.byte, common::kMacAddrLen);
// RSSI
bss_info->RSSI = result_in.rssi_dbm;
// IEs
bss_info->ie_offset = sizeof(brcmf_bss_info_le);
size_t ie_offset = sizeof(brcmf_escan_result_le);
uint8_t* ie_data = &buffer_data[ie_offset];
std::memcpy(ie_data, ie_buf.data(), ie_buf.size());
bss_info->ie_length = ie_buf.size();
// Wrap this in an event and send it back to the driver
SendEventToDriver(scan_result_size, std::move(buf), BRCMF_E_ESCAN_RESULT, BRCMF_E_STATUS_PARTIAL,
kClientIfidx);
}
std::shared_ptr<std::vector<uint8_t>> SimFirmware::CreateEventBuffer(
size_t requested_size, brcmf_event_msg_be** msg_out_be, size_t* payload_offset_out) {
size_t total_size = sizeof(brcmf_event) + requested_size;
size_t event_data_offset;
// Note: events always encode the interface index into the event header and 0 into the BCDC
// header.
auto buf = CreateBcdcBuffer(0, total_size, &event_data_offset);
uint8_t* buffer_data = buf->data();
auto event = reinterpret_cast<brcmf_event*>(&buffer_data[event_data_offset]);
memcpy(event->eth.h_dest, mac_addr_.data(), ETH_ALEN);
memcpy(event->eth.h_source, mac_addr_.data(), ETH_ALEN);
// Disable local bit - we do this because, well, the real firmware does this.
event->eth.h_source[0] &= ~0x2;
event->eth.h_proto = htobe16(ETH_P_LINK_CTL);
auto hdr_be = &event->hdr;
// hdr_be->subtype unused
hdr_be->length = htobe16(total_size);
hdr_be->version = 0;
memcpy(&hdr_be->oui, BRCM_OUI, sizeof(hdr_be->oui));
hdr_be->usr_subtype = htobe16(BCMILCP_BCM_SUBTYPE_EVENT);
// Set the generic fields of the event msg
*msg_out_be = &event->msg;
(*msg_out_be)->version = htobe16(2);
(*msg_out_be)->datalen = htobe32(requested_size);
memcpy((*msg_out_be)->addr, mac_addr_.data(), ETH_ALEN);
memcpy((*msg_out_be)->ifname, kDefaultIfcName, strlen(kDefaultIfcName));
// Payload immediately follows the brcmf_event structure
if (payload_offset_out != nullptr) {
*payload_offset_out = event_data_offset + sizeof(brcmf_event);
}
return buf;
}
void SimFirmware::SendEventToDriver(size_t payload_size,
std::shared_ptr<std::vector<uint8_t>> buffer_in,
uint32_t event_type, uint32_t status, uint16_t ifidx,
char* ifname, uint16_t flags, uint32_t reason,
std::optional<common::MacAddr> addr,
std::optional<zx::duration> delay) {
BRCMF_DBG(SIM, "*****Sending Event: %d*****", event_type);
brcmf_event_msg_be* msg_be;
size_t payload_offset;
// Assert if ifidx is not valid
if (event_type != BRCMF_E_IF)
ZX_ASSERT(ifidx < kMaxIfSupported && iface_tbl_[ifidx].allocated);
auto buf = CreateEventBuffer(payload_size, &msg_be, &payload_offset);
msg_be->flags = htobe16(flags);
msg_be->event_type = htobe32(event_type);
msg_be->status = htobe32(status);
msg_be->reason = htobe32(reason);
msg_be->auth_type = htobe32(iface_tbl_[ifidx].auth_type);
msg_be->ifidx = ifidx;
msg_be->bsscfgidx = iface_tbl_[ifidx].bsscfgidx;
if (ifname)
memcpy(msg_be->ifname, ifname, IFNAMSIZ);
if (addr)
memcpy(msg_be->addr, addr->byte, ETH_ALEN);
if (payload_size != 0) {
ZX_ASSERT(buffer_in != nullptr);
uint8_t* buf_data = buf->data();
memcpy(&buf_data[payload_offset], buffer_in->data(), payload_size);
}
if (delay && delay->get() > 0) {
// Setup the callback and return.
hw_.RequestCallback(std::bind(&brcmf_sim_rx_event, simdev_, buf), delay.value());
return;
} else {
BRCMF_DBG(SIM, "Sending Event: %d", event_type);
brcmf_sim_rx_event(simdev_, std::move(buf));
}
}
void SimFirmware::SendFrameToDriver(uint16_t ifidx, size_t payload_size,
const std::vector<uint8_t>& buffer_in,
std::shared_ptr<const simulation::WlanRxInfo> info) {
size_t header_offset;
auto buf = CreateBcdcBuffer(ifidx, payload_size, &header_offset);
if (payload_size != 0) {
ZX_ASSERT(!buffer_in.empty());
uint8_t* buf_data = buf->data();
memcpy(&buf_data[header_offset], buffer_in.data(), payload_size);
}
brcmf_sim_rx_frame(simdev_, std::move(buf));
}
// This function schedules an event for brcmf_sim_reset() instead of directly calling this function,
// this is because this function will delete and recreated the sim-fw, so that sim-fw will release
// itself if this function is in the same call chain, which leads a segment fault.
void SimFirmware::ResetSimFirmware() {
// The crash happens immediately after 'crash' iovar is received from firmware.
hw_.RequestCallback(std::bind(&brcmf_sim_firmware_crash, simdev_), zx::sec(0));
}
void SimFirmware::convert_chanspec_to_channel(uint16_t chanspec, wlan_channel_t* channel) {
chanspec_to_channel(&d11_inf_, chanspec, channel);
}
uint16_t SimFirmware::convert_channel_to_chanspec(wlan_channel_t* channel) {
return channel_to_chanspec(&d11_inf_, channel);
}
} // namespace wlan::brcmfmac
|
/////////////////////////////////////////////////////////////////////////////////
//
// SourceFile: HTTPTime.cpp
//
// Marlin Server: Internet server/client
//
// Copyright (c) 2014-2021 ir. W.E. Huisman
// All rights reserved
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include "stdafx.h"
#include "HTTPTime.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
const char* weekday_short[7] =
{
"Sun","Mon","Tue","Wed","Thu","Fri","Sat"
};
const char* weekday_long[7] =
{
"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"
};
const char* month[12] =
{
"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
};
// Print HTTP time in RFC 1123 format (Preferred standard)
// as in "Tue, 8 Dec 2015 21:26:32 GMT"
bool
HTTPTimeFromSystemTime(const SYSTEMTIME* p_systemtime,CString& p_time)
{
// Check that we have a system time
if(!p_systemtime)
{
SetLastError(ERROR_INVALID_PARAMETER);
return false;
}
p_time.Format("%s, %02d %s %04d %2.2d:%2.2d:%2.2d GMT"
,weekday_short[p_systemtime->wDayOfWeek]
,p_systemtime->wDay
,month[p_systemtime->wMonth - 1]
,p_systemtime->wYear
,p_systemtime->wHour
,p_systemtime->wMinute
,p_systemtime->wSecond);
SetLastError(ERROR_SUCCESS);
return true;
}
// Check year loosely for RFC850/1036 implementations
static void
CheckYearImplementation(SYSTEMTIME* p_systemtime)
{
if(p_systemtime->wYear < 100 && p_systemtime->wYear >= 0)
{
if(p_systemtime->wYear < 50)
{
p_systemtime->wYear += 2000;
}
else
{
p_systemtime->wYear += 1900;
}
}
}
// Convert an loosely conforming RFC2616 time such as
// 'Sun, 04-Dec-2016 12:02:37 GMT' to the proper systemtime
// Excerpt from RFC 2616:
//
// HTTP applications have historically allowed three different formats
// for the representation of date / time stamps :
//
// Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822,updated by RFC 1123
// Sunday, 06 - Nov - 94 08:49:37 GMT ; RFC 850,obsoleted by RFC 1036
// Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
//
// The first format is preferred as an Internet standard and represents
// a fixed - length subset of that defined by RFC 1123[8](an update to
// RFC 822[9]).The second format is in common use,but is based on the
// obsolete RFC 850[12] date format and lacks a four - digit year.
// HTTP / 1.1 clients and servers that parse the date value MUST accept
// all three formats(for compatibility with HTTP / 1.0),though they MUST
// only generate the RFC 1123 format for representing HTTP - date values
// in header fields.See section 19.3 for further information
//
bool
HTTPTimeToSystemTime(const CString p_time,SYSTEMTIME* p_systemtime)
{
// const char *pointer = p_time.GetString();
unsigned index = 0;
unsigned length = p_time.GetLength();
bool ansic = false;
// Check if we have something to do
if(!p_time || !p_systemtime)
{
SetLastError(ERROR_INVALID_PARAMETER);
return false;
}
SetLastError(ERROR_SUCCESS);
// Reset systemtime
memset(p_systemtime,0,sizeof(SYSTEMTIME));
// Skip whitespace
while(index < length && isspace(p_time.GetAt(index)))
{
++index;
}
// If empty string, use default system time
// Various implementations e.g. MS-Windows do this strange behaviour
// by getting the current system time
if(index >= length)
{
GetSystemTime(p_systemtime);
return true;
}
// Default day is not-scanned
p_systemtime->wDayOfWeek = 7;
// Now scan for the day of the week
for(int ind = 0; ind < 7; ++ind)
{
if((p_time.Mid(index,3).CompareNoCase(weekday_short[ind]) == 0) ||
(p_time.Mid(index,(int)strlen(weekday_long[ind])).CompareNoCase(weekday_long[ind]) == 0))
{
p_systemtime->wDayOfWeek = (WORD) ind;
while(index < length && isalpha(p_time.GetAt(index))) ++index;
break;
}
}
// No weekday found
if(p_systemtime->wDayOfWeek > 6)
{
SetLastError(ERROR_INVALID_PARAMETER);
memset(p_systemtime,0,sizeof(SYSTEMTIME));
return false;
}
// Skip spaces and separators
while(index < length &&
!isdigit(p_time.GetAt(index)) &&
!isalpha(p_time.GetAt(index)))
{
++index;
}
if(isalpha(p_time.GetAt(index)))
{
// ANSI C month name first
ansic = true;
for(int ind = 0; ind < 12; ++ind)
{
if(p_time.Mid(index,3).CompareNoCase(month[ind]) == 0)
{
p_systemtime->wMonth = (WORD)(ind + 1);
while(index < length && isalpha(p_time.GetAt(index))) ++index;
// Skip spaces and separators
while(index < length &&
!isdigit(p_time.GetAt(index)) &&
!isalpha(p_time.GetAt(index)))
{
++index;
}
break;
}
}
}
// Scan day-of-the-month
p_systemtime->wDay = (WORD) atoi(&p_time.GetString()[index]);
while(index < length && isdigit(p_time.GetAt(index))) ++index;
// Skip spaces and separators
while(index < length &&
!isdigit(p_time.GetAt(index)) &&
!isalpha(p_time.GetAt(index)))
{
++index;
}
if(isalpha(p_time.GetAt(index)))
{
// Find the month name
for(int ind = 0; ind < 12; ++ind)
{
if(p_time.Mid(index,3).CompareNoCase(month[ind]) == 0)
{
p_systemtime->wMonth = (WORD) (ind + 1);
break;
}
}
}
// Check that we found a month name
if(p_systemtime->wMonth == 0)
{
SetLastError(ERROR_INVALID_PARAMETER);
memset(p_systemtime,0,sizeof(SYSTEMTIME));
return false;
}
if(!ansic)
{
// Skip to the year digit
while(index < length && !isdigit(p_time.GetAt(index))) ++index;
if(index >= length)
{
SetLastError(ERROR_INVALID_PARAMETER);
memset(p_systemtime,0,sizeof(SYSTEMTIME));
return false;
}
p_systemtime->wYear = (WORD) atoi(&p_time.GetString()[index]);
while(index < length && isdigit(p_time.GetAt(index))) ++index;
}
// After this point we have the year
// RFC's state to be robust. Missing hour or seconds are
// not leading to an error (Except for the ansic implementation)
// Hours
while(index < length && !isdigit(p_time.GetAt(index))) ++index;
if(index >= length)
{
CheckYearImplementation(p_systemtime);
return true;
}
p_systemtime->wHour = (WORD) atoi(&p_time.GetString()[index]);
while(index < length && isdigit(p_time.GetAt(index))) ++index;
// Minutes
while(index < length && !isdigit(p_time.GetAt(index))) ++index;
if(index >= length)
{
CheckYearImplementation(p_systemtime);
return true;
}
p_systemtime->wMinute = (WORD) atoi(&p_time.GetString()[index]);
while(index < length && isdigit(p_time.GetAt(index))) ++index;
// Seconds
while(index < length && !isdigit(p_time.GetAt(index))) ++index;
if(index >= length)
{
CheckYearImplementation(p_systemtime);
return true;
}
p_systemtime->wSecond = (WORD) atoi(&p_time.GetString()[index]);
while(index < length && isdigit(p_time.GetAt(index))) ++index;
// Still ANSI C Year to do?
if(ansic)
{
while(index < length && !isdigit(p_time.GetAt(index))) ++index;
if(index >= length)
{
SetLastError(ERROR_INVALID_PARAMETER);
memset(p_systemtime,0,sizeof(SYSTEMTIME));
return false;
}
p_systemtime->wYear = (WORD) atoi(&p_time.GetString()[index]);
}
CheckYearImplementation(p_systemtime);
return true;
}
// Print HTTP time in RFC 1123 format (Preferred standard)
// as in "Tue, 8 Dec 2015 21:26:32 GMT"
CString
HTTPGetSystemTime()
{
CString time;
SYSTEMTIME systemtime;
GetSystemTime(&systemtime);
time.Format("%s, %02d %s %04d %2.2d:%2.2d:%2.2d GMT"
,weekday_short[systemtime.wDayOfWeek]
,systemtime.wDay
,month[systemtime.wMonth - 1]
,systemtime.wYear
,systemtime.wHour
,systemtime.wMinute
,systemtime.wSecond);
return time;
}
|
//////////////////////////////////////////////////////////////////////////////
/// Copyright 2003 and onward LASMEA UMR 6602 CNRS/U.B.P Clermont-Ferrand
/// Copyright 2009 and onward LRI UMR 8623 CNRS/Univ Paris Sud XI
///
/// Distributed under the Boost Software License, Version 1.0
/// See accompanying file LICENSE.txt or copy at
/// http://www.boost.org/LICENSE_1_0.txt
//////////////////////////////////////////////////////////////////////////////
#ifndef NT2_TOOLBOX_BOOST_MATH_FUNCTION_SIMD_SSE_XOP_ELLINT3_3_HPP_INCLUDED
#define NT2_TOOLBOX_BOOST_MATH_FUNCTION_SIMD_SSE_XOP_ELLINT3_3_HPP_INCLUDED
#include <nt2/toolbox/boost_math/function/simd/sse/sse4a/ellint3_3.hpp>
#endif
|
/*
* Copyright 2006 by NVIDIA Corporation. All rights reserved. All
* information contained herein is proprietary and confidential to NVIDIA
* Corporation. Any use, reproduction, or disclosure without the written
* permission of NVIDIA Corporation is prohibited.
*/
#include <Cg/half.hpp>
#include <Cg/fixed.hpp>
#include <Cg/double.hpp>
#include <Cg/radians.hpp>
namespace Cg {
float radians(float v)
{
return radians<float,1>(v);
}
float1 radians(float1 v)
{
return radians<float,1>(v);
}
float2 radians(float2 v)
{
return radians<float,2>(v);
}
float3 radians(float3 v)
{
return radians<float,3>(v);
}
float4 radians(float4 v)
{
return radians<float,4>(v);
}
double radians(double v)
{
return radians<double,1>(v);
}
double1 radians(double1 v)
{
return radians<double,1>(v);
}
double2 radians(double2 v)
{
return radians<double,2>(v);
}
double3 radians(double3 v)
{
return radians<double,3>(v);
}
double4 radians(double4 v)
{
return radians<double,4>(v);
}
half radians(half v)
{
return radians<half,1>(v);
}
half1 radians(half1 v)
{
return radians<half,1>(v);
}
half2 radians(half2 v)
{
return radians<half,2>(v);
}
half3 radians(half3 v)
{
return radians<half,3>(v);
}
half4 radians(half4 v)
{
return radians<half,4>(v);
}
fixed radians(fixed v)
{
return radians<fixed,1>(v);
}
fixed1 radians(fixed1 v)
{
return radians<fixed,1>(v);
}
fixed2 radians(fixed2 v)
{
return radians<fixed,2>(v);
}
fixed3 radians(fixed3 v)
{
return radians<fixed,3>(v);
}
fixed4 radians(fixed4 v)
{
return radians<fixed,4>(v);
}
} // namespace Cg
|
/*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (c) 2019, Open AI Lab
* Author: zpluo@openailab.com
*/
#ifndef __RNN_PARAM_HPP__
#define __RNN_PARAM_HPP__
#include <vector>
#include "parameter.hpp"
namespace TEngine {
#define RNN_ACT_TANH 1
struct RNNParam : public NamedParam
{
float clip;
int output_len;
int sequence_len;
int input_size;
int hidden_size;
int has_clip;
int has_bias;
int has_init_state;
int activation;
DECLARE_PARSER_STRUCTURE(RNNParam)
{
DECLARE_PARSER_ENTRY(clip);
DECLARE_PARSER_ENTRY(output_len);
DECLARE_PARSER_ENTRY(sequence_len);
DECLARE_PARSER_ENTRY(input_size);
DECLARE_PARSER_ENTRY(hidden_size);
DECLARE_PARSER_ENTRY(has_clip);
DECLARE_PARSER_ENTRY(has_bias);
DECLARE_PARSER_ENTRY(has_init_state);
DECLARE_PARSER_ENTRY(activation);
};
};
} // namespace TEngine
#endif
|
/*
* PatternContainer.cpp
* --------------------
* Purpose: Container class for managing patterns.
* Notes : (currently none)
* Authors: OpenMPT Devs
* The OpenMPT source code is released under the BSD license. Read LICENSE for more details.
*/
#include "stdafx.h"
#include "patternContainer.h"
#include "Sndfile.h"
#include "mod_specifications.h"
#include "../common/serialization_utils.h"
#include "../common/version.h"
OPENMPT_NAMESPACE_BEGIN
void CPatternContainer::ClearPatterns()
{
DestroyPatterns();
m_Patterns.assign(m_Patterns.size(), CPattern(*this));
}
void CPatternContainer::DestroyPatterns()
{
for(PATTERNINDEX i = 0; i < m_Patterns.size(); i++)
{
Remove(i);
}
}
PATTERNINDEX CPatternContainer::Duplicate(PATTERNINDEX from, bool respectQtyLimits)
{
if(!IsValidPat(from))
{
return PATTERNINDEX_INVALID;
}
PATTERNINDEX newPatIndex = InsertAny(m_Patterns[from].GetNumRows(), respectQtyLimits);
if(newPatIndex != PATTERNINDEX_INVALID)
{
m_Patterns[newPatIndex] = m_Patterns[from];
}
return newPatIndex;
}
PATTERNINDEX CPatternContainer::InsertAny(const ROWINDEX rows, bool respectQtyLimits)
{
PATTERNINDEX i = 0;
for(i = 0; i < m_Patterns.size(); i++)
if(!m_Patterns[i].IsValid()) break;
if(respectQtyLimits && i >= m_rSndFile.GetModSpecifications().patternsMax)
return PATTERNINDEX_INVALID;
if(!Insert(i, rows))
return PATTERNINDEX_INVALID;
else return i;
}
bool CPatternContainer::Insert(const PATTERNINDEX index, const ROWINDEX rows)
{
if(rows > MAX_PATTERN_ROWS || rows == 0)
return false;
if(IsValidPat(index))
return false;
try
{
if(index >= m_Patterns.size())
{
m_Patterns.resize(index + 1, CPattern(*this));
}
m_Patterns[index].AllocatePattern(rows);
m_Patterns[index].RemoveSignature();
m_Patterns[index].SetName("");
} MPT_EXCEPTION_CATCH_OUT_OF_MEMORY(e)
{
MPT_EXCEPTION_DELETE_OUT_OF_MEMORY(e);
return false;
}
return m_Patterns[index].IsValid();
}
void CPatternContainer::Remove(const PATTERNINDEX ipat)
{
if(ipat < m_Patterns.size()) m_Patterns[ipat].Deallocate();
}
bool CPatternContainer::IsPatternEmpty(const PATTERNINDEX nPat) const
{
if(!IsValidPat(nPat))
return false;
for(const auto &m : m_Patterns[nPat].m_ModCommands)
{
if(!m.IsEmpty())
return false;
}
return true;
}
void CPatternContainer::ResizeArray(const PATTERNINDEX newSize)
{
if(Size() <= newSize)
{
m_Patterns.resize(newSize, CPattern(*this));
} else
{
for(PATTERNINDEX i = Size(); i > newSize; i--)
Remove(i - 1);
m_Patterns.resize(newSize, CPattern(*this));
}
}
void CPatternContainer::OnModTypeChanged(const MODTYPE /*oldtype*/)
{
const CModSpecifications specs = m_rSndFile.GetModSpecifications();
//if(specs.patternsMax < Size())
// ResizeArray(specs.patternsMax);
// remove pattern time signatures
if(!specs.hasPatternSignatures)
{
for(PATTERNINDEX nPat = 0; nPat < m_Patterns.size(); nPat++)
{
m_Patterns[nPat].RemoveSignature();
m_Patterns[nPat].RemoveTempoSwing();
}
}
}
PATTERNINDEX CPatternContainer::GetNumPatterns() const
{
for(PATTERNINDEX pat = Size(); pat > 0; pat--)
{
if(IsValidPat(pat - 1))
{
return pat;
}
}
return 0;
}
PATTERNINDEX CPatternContainer::GetNumNamedPatterns() const
{
if(Size() == 0)
{
return 0;
}
for(PATTERNINDEX nPat = Size(); nPat > 0; nPat--)
{
if(!m_Patterns[nPat - 1].GetName().empty())
{
return nPat;
}
}
return 0;
}
void WriteModPatterns(std::ostream& oStrm, const CPatternContainer& patc)
{
srlztn::SsbWrite ssb(oStrm);
ssb.BeginWrite(FileIdPatterns, Version::Current().GetRawVersion());
const PATTERNINDEX nPatterns = patc.Size();
uint16 nCount = 0;
for(uint16 i = 0; i < nPatterns; i++) if (patc[i].IsValid())
{
ssb.WriteItem(patc[i], srlztn::ID::FromInt<uint16>(i), &WriteModPattern);
nCount = i + 1;
}
ssb.WriteItem<uint16>(nCount, "num"); // Index of last pattern + 1.
ssb.FinishWrite();
}
void ReadModPatterns(std::istream& iStrm, CPatternContainer& patc, const size_t)
{
srlztn::SsbRead ssb(iStrm);
ssb.BeginRead(FileIdPatterns, Version::Current().GetRawVersion());
if ((ssb.GetStatus() & srlztn::SNT_FAILURE) != 0)
return;
PATTERNINDEX nPatterns = patc.Size();
uint16 nCount = uint16_max;
if (ssb.ReadItem(nCount, "num") != srlztn::SsbRead::EntryNotFound)
nPatterns = nCount;
LimitMax(nPatterns, ModSpecs::mptm.patternsMax);
if (nPatterns > patc.Size())
patc.ResizeArray(nPatterns);
for(uint16 i = 0; i < nPatterns; i++)
{
ssb.ReadItem(patc[i], srlztn::ID::FromInt<uint16>(i), &ReadModPattern);
}
}
OPENMPT_NAMESPACE_END
|
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "schemaconfigurer.h"
#include <vespa/config-attributes.h>
#include <vespa/config-imported-fields.h>
#include <vespa/config-indexschema.h>
#include <vespa/config-summary.h>
#include <vespa/searchcommon/common/schema.h>
#include <vespa/searchcommon/attribute/collectiontype.h>
#include <vespa/searchcommon/attribute/basictype.h>
#include <vespa/searchcommon/config/subscriptionproxyng.h>
#include <vespa/log/log.h>
LOG_SETUP(".index.schemaconfigurer");
using namespace config;
using namespace vespa::config::search;
namespace search::index {
using schema::DataType;
using schema::CollectionType;
namespace {
Schema::DataType
convertIndexDataType(const IndexschemaConfig::Indexfield::Datatype &type)
{
switch (type) {
case IndexschemaConfig::Indexfield::Datatype::STRING:
return DataType::STRING;
case IndexschemaConfig::Indexfield::Datatype::INT64:
return DataType::INT64;
}
return DataType::STRING;
}
Schema::CollectionType
convertIndexCollectionType(const IndexschemaConfig::Indexfield::Collectiontype &type)
{
switch (type) {
case IndexschemaConfig::Indexfield::Collectiontype::SINGLE:
return CollectionType::SINGLE;
case IndexschemaConfig::Indexfield::Collectiontype::ARRAY:
return CollectionType::ARRAY;
case IndexschemaConfig::Indexfield::Collectiontype::WEIGHTEDSET:
return CollectionType::WEIGHTEDSET;
}
return CollectionType::SINGLE;
}
template <typename ConfigType>
Schema::DataType
convertDataType(const ConfigType &type)
{
switch (type) {
case ConfigType::STRING:
return DataType::STRING;
case ConfigType::BOOL:
return DataType::BOOL;
case ConfigType::UINT2:
return DataType::UINT2;
case ConfigType::UINT4:
return DataType::UINT4;
case ConfigType::INT8:
return DataType::INT8;
case ConfigType::INT16:
return DataType::INT16;
case ConfigType::INT32:
return DataType::INT32;
case ConfigType::INT64:
return DataType::INT64;
case ConfigType::FLOAT:
return DataType::FLOAT;
case ConfigType::DOUBLE:
return DataType::DOUBLE;
case ConfigType::PREDICATE:
return DataType::BOOLEANTREE;
case ConfigType::TENSOR:
return DataType::TENSOR;
case ConfigType::REFERENCE:
return DataType::REFERENCE;
default:
break;
}
// TODO: exception?
return DataType::STRING;
}
template <typename ConfigType>
Schema::CollectionType
convertCollectionType(const ConfigType &type)
{
switch (type) {
case ConfigType::SINGLE:
return CollectionType::SINGLE;
case ConfigType::ARRAY:
return CollectionType::ARRAY;
case ConfigType::WEIGHTEDSET:
return CollectionType::WEIGHTEDSET;
}
return CollectionType::SINGLE;
}
Schema::DataType
convertSummaryType(const vespalib::string &type)
{
if (type == "byte") {
return DataType::INT8;
} else if (type == "short") {
return DataType::INT16;
} else if (type == "integer") {
return DataType::INT32;
} else if (type == "int64") {
return DataType::INT64;
} else if (type == "float") {
return DataType::FLOAT;
} else if (type == "double") {
return DataType::DOUBLE;
} else if (type == "string" ||
type == "longstring" ||
type == "xmlstring" ||
type == "featuredata" ||
type == "jsonstring")
{
return DataType::STRING;
} else if (type == "data" ||
type == "longdata")
{
return DataType::RAW;
}
return DataType::RAW;
}
}
void
SchemaBuilder::build(const IndexschemaConfig &cfg, Schema &schema)
{
for (size_t i = 0; i < cfg.indexfield.size(); ++i) {
const IndexschemaConfig::Indexfield & f = cfg.indexfield[i];
schema.addIndexField(Schema::IndexField(f.name, convertIndexDataType(f.datatype),
convertIndexCollectionType(f.collectiontype)).
setAvgElemLen(f.averageelementlen).
set_interleaved_features(f.interleavedfeatures));
}
for (size_t i = 0; i < cfg.fieldset.size(); ++i) {
const IndexschemaConfig::Fieldset &fs = cfg.fieldset[i];
Schema::FieldSet toAdd(fs.name);
for (size_t j = 0; j < fs.field.size(); ++j) {
toAdd.addField(fs.field[j].name);
}
schema.addFieldSet(toAdd);
}
}
void
SchemaBuilder::build(const AttributesConfig &cfg, Schema &schema)
{
for (const auto &attr : cfg.attribute) {
if (attr.imported) {
schema.addImportedAttributeField(Schema::ImportedAttributeField(attr.name,
convertDataType(attr.datatype),
convertCollectionType(attr.collectiontype)));
} else {
schema.addAttributeField(Schema::Field(attr.name,
convertDataType(attr.datatype),
convertCollectionType(attr.collectiontype)));
}
}
}
void
SchemaBuilder::build(const SummaryConfig &cfg, Schema &schema)
{
for (size_t i = 0; i < cfg.classes.size(); ++i) {
LOG(debug, "class with index %lu has id %d (default has id %d)",
i, cfg.classes[i].id, cfg.defaultsummaryid);
}
for (size_t i = 0; i < cfg.classes.size(); ++i) {
// use the default summary class that has all fields
if (cfg.classes[i].id == cfg.defaultsummaryid) {
for (size_t j = 0; j < cfg.classes[i].fields.size(); ++j) {
const SummaryConfig::Classes::Fields & f =
cfg.classes[i].fields[j];
schema.addSummaryField(Schema::Field(f.name,
convertSummaryType(f.type)));
}
return;
}
}
if (cfg.classes.empty()) {
LOG(debug,
"No summary class configured that match the default summary id %d",
cfg.defaultsummaryid);
} else {
LOG(warning,
"No summary class configured that match the default summary id %d",
cfg.defaultsummaryid);
}
}
void
SchemaConfigurer::configure(const IndexschemaConfig &cfg)
{
SchemaBuilder::build(cfg, _schema);
}
void
SchemaConfigurer::configure(const AttributesConfig &cfg)
{
SchemaBuilder::build(cfg, _schema);
}
void
SchemaConfigurer::configure(const SummaryConfig & cfg)
{
SchemaBuilder::build(cfg, _schema);
}
SchemaConfigurer::SchemaConfigurer(Schema &schema, const vespalib::string &configId)
: _schema(schema)
{
search::SubscriptionProxyNg<SchemaConfigurer, IndexschemaConfig>
indexSchemaSubscriber(*this, &SchemaConfigurer::configure);
search::SubscriptionProxyNg<SchemaConfigurer, AttributesConfig>
attributesSubscriber(*this, &SchemaConfigurer::configure);
search::SubscriptionProxyNg<SchemaConfigurer, SummaryConfig>
summarySubscriber(*this, &SchemaConfigurer::configure);
indexSchemaSubscriber.subscribe(configId.c_str());
attributesSubscriber.subscribe(configId.c_str());
summarySubscriber.subscribe(configId.c_str());
}
}
|
//
// DrawableUIComponent.cpp
// Chilli Source
// Created by Ian Copland on 28/11/2014.
//
// The MIT License (MIT)
//
// Copyright (c) 2014 Tag Games Limited
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include <ChilliSource/UI/Drawable/DrawableUIComponent.h>
#include <ChilliSource/Core/Delegate/MakeDelegate.h>
#include <ChilliSource/UI/Base/PropertyTypes.h>
#include <ChilliSource/UI/Drawable/UIDrawable.h>
#include <ChilliSource/UI/Drawable/UIDrawableDef.h>
namespace ChilliSource
{
namespace
{
const char k_drawableKey[] = "Drawable";
const std::vector<PropertyMap::PropertyDesc> k_propertyDescs =
{
{PropertyTypes::UIDrawableDef(), k_drawableKey},
};
}
CS_DEFINE_NAMEDTYPE(DrawableUIComponent);
//-------------------------------------------------------------------
//-------------------------------------------------------------------
const std::vector<PropertyMap::PropertyDesc>& DrawableUIComponent::GetPropertyDescs()
{
return k_propertyDescs;
}
//-------------------------------------------------------------------
//-------------------------------------------------------------------
DrawableUIComponent::DrawableUIComponent(const std::string& in_componentName, const PropertyMap& in_properties)
: UIComponent(in_componentName)
{
RegisterProperty<UIDrawableDefCSPtr>(PropertyTypes::UIDrawableDef(), k_drawableKey, MakeDelegate(this, &DrawableUIComponent::GetDrawableDef), MakeDelegate(this, &DrawableUIComponent::ApplyDrawableDef));
ApplyRegisteredProperties(in_properties);
}
//-------------------------------------------------------------------
//-------------------------------------------------------------------
bool DrawableUIComponent::IsA(InterfaceIDType in_interfaceId) const
{
return (UIComponent::InterfaceID == in_interfaceId || DrawableUIComponent::InterfaceID == in_interfaceId);
}
//-------------------------------------------------------------------
//-------------------------------------------------------------------
UIDrawable* DrawableUIComponent::GetDrawable()
{
return m_drawable.get();
}
//-------------------------------------------------------------------
//-------------------------------------------------------------------
const UIDrawable* DrawableUIComponent::GetDrawable() const
{
return m_drawable.get();
}
//-------------------------------------------------------------------
//-------------------------------------------------------------------
void DrawableUIComponent::ApplyDrawableDef(const UIDrawableDefCSPtr& in_drawableDef)
{
m_drawable.reset();
m_drawableDef = in_drawableDef;
if (m_drawableDef != nullptr)
{
m_drawable = m_drawableDef->CreateDrawable();
}
}
//-------------------------------------------------------------------
//-------------------------------------------------------------------
const UIDrawableDefCSPtr& DrawableUIComponent::GetDrawableDef() const
{
return m_drawableDef;
}
//----------------------------------------------------------------
//----------------------------------------------------------------
void DrawableUIComponent::OnDraw(CanvasRenderer* in_renderer, const Matrix3& in_transform, const Vector2& in_absSize, const Colour& in_absColour)
{
if (m_drawable != nullptr)
{
m_drawable->Draw(in_renderer, in_transform, in_absSize, in_absColour);
}
}
}
|
#pragma once
#include <torch/extension.h>
#include <deque>
#include <exception>
#include <memory>
#include <mutex>
#include <thread>
#include <vector>
#include <pybind11/chrono.h>
#include <c10d/ProcessGroup.hpp>
#include <c10d/Store.hpp>
#include <c10d/Types.hpp>
#include <c10d/Utils.hpp>
#include <ucp/api/ucp.h>
#include <api/xccl.h>
namespace c10d {
class ProcessGroupUCC : public ProcessGroup {
public:
class WorkUCP : public ProcessGroup::Work {
public:
WorkUCP(ucs_status_ptr_t request, ucp_worker_h ucp_worker):
req(request), worker(ucp_worker) {}
virtual ~WorkUCP();
bool isCompleted() override;
bool isSuccess() const override;
bool wait() override;
protected:
ucs_status_ptr_t req;
ucp_worker_h worker;
friend class ProcessGroupUCC;
};
class WorkUCC : public ProcessGroup::Work {
public:
WorkUCC(xccl_coll_req_h request): req(request){}
WorkUCC(){}
virtual ~WorkUCC();
bool isCompleted() override;
bool isSuccess() const override;
bool wait() override;
protected:
xccl_coll_req_h req;
xccl_coll_op_args_t args;
std::vector<uint32_t> scratch;
std::vector<at::Tensor> output_data_vec;
at::Tensor flat_tensor;
friend class ProcessGroupUCC;
};
explicit ProcessGroupUCC(const std::shared_ptr<Store>& store,
int rank = -1,
int size = -1);
virtual ~ProcessGroupUCC();
std::shared_ptr<ProcessGroup::Work> broadcast(std::vector<at::Tensor>& data,
const BroadcastOptions& opts = BroadcastOptions()) override;
std::shared_ptr<ProcessGroup::Work> allreduce(std::vector<at::Tensor>& tensors,
const AllreduceOptions& opts = AllreduceOptions()) override;
std::shared_ptr<ProcessGroup::Work> allreduce_coalesced(std::vector<at::Tensor>& tensors,
const AllreduceCoalescedOptions& opts = AllreduceCoalescedOptions()) override;
std::shared_ptr<ProcessGroup::Work> reduce(std::vector<at::Tensor>& tensors,
const ReduceOptions& opts = ReduceOptions()) override;
std::shared_ptr<ProcessGroup::Work> allgather(std::vector<std::vector<at::Tensor>>& outputTensors,
std::vector<at::Tensor>& inputTensors,
const AllgatherOptions& opts = AllgatherOptions()) override;
std::shared_ptr<ProcessGroup::Work> allgather_base(at::Tensor& outputBuffer,
at::Tensor& inputBuffer,
const AllgatherOptions& opts = AllgatherOptions()) override;
std::shared_ptr<ProcessGroup::Work> barrier(const BarrierOptions& opts = BarrierOptions()) override;
std::shared_ptr<ProcessGroup::Work> gather(std::vector<std::vector<at::Tensor>>& outputTensors,
std::vector<at::Tensor>& inputTensors,
const GatherOptions& opts = GatherOptions()) override;
std::shared_ptr<ProcessGroup::Work> scatter(std::vector<at::Tensor>& outputTensors,
std::vector<std::vector<at::Tensor>>& inputTensors,
const ScatterOptions& opts = ScatterOptions()) override;
std::shared_ptr<ProcessGroup::Work> reduce_scatter(std::vector<at::Tensor>& outputTensors,
std::vector<std::vector<at::Tensor>>& inputTensors,
const ReduceScatterOptions& opts = ReduceScatterOptions()) override;
std::shared_ptr<ProcessGroup::Work> alltoall_base(at::Tensor& outputTensor,
at::Tensor& inputTensor,
std::vector<int64_t>& outputSplitSizes,
std::vector<int64_t>& inputSplitSizes,
const AllToAllOptions& opts = AllToAllOptions()) override;
std::shared_ptr<ProcessGroup::Work> alltoall(std::vector<at::Tensor>& outputTensors,
std::vector<at::Tensor>& inputTensors,
const AllToAllOptions& opts = AllToAllOptions()) override;
std::shared_ptr<ProcessGroup::Work> send(std::vector<at::Tensor>& tensors,
int dstRank,
int tag);
std::shared_ptr<ProcessGroup::Work> recv(std::vector<at::Tensor>& tensors,
int srcRank,
int tag);
std::shared_ptr<ProcessGroup::Work> recvAnysource(std::vector<at::Tensor>& tensors,
int tag);
static std::shared_ptr<ProcessGroup> createProcessGroupUCC(
const std::shared_ptr<::c10d::Store>& store,
int rank,
int size,
const std::chrono::duration<float>& timeout);
static void ProcessGroupUCCConstructor() __attribute__((constructor)) {
py::object module = py::module::import("torch.distributed");
py::object register_backend = module.attr("Backend").attr("register_backend");
register_backend("ucc", py::cpp_function(createProcessGroupUCC));
}
protected:
std::shared_ptr<Store> store_;
ucp_context_h ucp_ctx;
ucp_worker_h ucp_worker;
std::vector<ucp_ep_h> ucp_eps;
xccl_lib_h xccl_lib;
xccl_context_h xccl_ctx;
xccl_team_h xccl_team;
private:
struct xccl_oob_allgather_req_t {
xccl_ep_range_t range;
void *sbuf;
void *rbuf;
void *oob_coll_ctx;
int my_rank;
size_t msglen;
int iter;
ucs_status_ptr_t reqs[2];
};
struct xccl_oob_coll_ctx_t {
int rank;
int size;
ucp_worker_h ucp_worker;
ucp_ep_h *ucp_eps;
} oob_coll_ctx;
void check_tensor(const std::vector<at::Tensor>& tensors);
xccl_coll_req_h launch_xccl_collective(xccl_collective_type_t coll,
const std::vector<at::Tensor>& tensors,
int root, xccl_op_t op);
static ucs_status_t ucp_test_all(ucp_worker_h worker, int n_reqs,
ucs_status_ptr_t *reqs, int *completed);
static xccl_status_t oob_allgather_test(void *req);
static xccl_status_t oob_allgather_free(void *req);
static int oob_allgather(void *sbuf, void *rbuf, size_t msglen,
int my_rank, xccl_ep_range_t range,
void *oob_coll_ctx, void **req);
void init_xccl();
};
} // namespace c10d
|
#include <mutex>
#include <thread>
#include <fstream>
#include <sys/stat.h>
#include "inc/list_processor.h"
#include "inc/u16fstream.h"
list_processor::list_processor()
:m_lock(), m_lists(), m_workingThread(), m_isWorking(true)
{
}
void list_processor::init()
{
syncFromFile();
m_workingThread = std::thread(&list_processor::workingThread, this);
}
void list_processor::shutdown()
{
m_isWorking = false;
m_workingThread.join();
syncToFile();
}
void list_processor::workingThread()
{
short counter = 0;
while(m_isWorking)
{
if (counter != 30)
{
std::this_thread::sleep_for(std::chrono::seconds(1));
counter++;
}
else
{
counter = 0;
syncToFile();
}
}
}
void list_processor::syncFromFile()
{
char dbFilename[] = "main.db";
struct stat st;
if (stat(dbFilename, &st) != 0) //database file doesn't exists
{
u16ofstream writer(dbFilename);
writer.close();
}
u16ifstream reader(dbFilename);
std::pair<unsigned char, std::u16string> item;
while(reader.readRecord(item))
{
if (item.first == 0)
{
m_lists.push_back(std::make_pair(item.second, std::vector<std::u16string>()));
}
else
{
m_lists[item.first - 1].second.push_back(item.second);
}
}
reader.close();
}
void list_processor::syncToFile()
{
m_lock.lock();
auto listCopy = m_lists;
m_lock.unlock();
u16ofstream writer("main.db");
if (writer)
{
for(size_t i = 0; i < listCopy.size(); ++i)
{
unsigned char listId = 0;
writer.writeRecord(std::make_pair(listId, listCopy[i].first));
for(const auto& itemName : listCopy[i].second)
{
listId = static_cast<unsigned char>(i + 1);
writer.writeRecord(std::make_pair(listId, itemName));
}
}
}
writer.close();
}
uchar_t list_processor::createList(const std::u16string& listName)
{
std::lock_guard<atomic_lock> lock(m_lock);
uchar_t ret = 0;
if (m_lists.size() < std::numeric_limits<uchar_t>::max())
{
bool isListExists = false;
for (const auto& pair : m_lists)
{
if (listName == pair.first)
{
isListExists = true;
break;
}
}
if (!isListExists)
{
m_lists.push_back(std::make_pair(listName, std::vector<std::u16string>()));
ret = static_cast<uchar_t>(m_lists.size());
}
}
return ret;
}
bool list_processor::deleteList(const std::u16string& listName)
{
bool ret = false;
std::lock_guard<atomic_lock> lock(m_lock);
for (auto iter = m_lists.begin(); iter != m_lists.end(); ++iter)
{
if (iter->first == listName)
{
m_lists.erase(iter);
ret = true;
break;
}
}
return ret;
}
bool list_processor::addListItem(const uchar_t& listID, const std::u16string& itemName)
{
bool bret = false;
std::lock_guard<atomic_lock> lock(m_lock);
auto& pair = m_lists[listID - 1];
bool isItemExists = false;
for(const auto& item : pair.second)
{
if (item == itemName)
{
isItemExists = true;
break;
}
}
if (!isItemExists)
{
pair.second.push_back(itemName);
bret = true;
}
return bret;
}
bool list_processor::deleteListItem(const uchar_t& listID, const std::u16string& listName)
{
bool bret = false;
std::lock_guard<atomic_lock> lock(m_lock);
auto& pair = m_lists[listID - 1];
for(auto iter = pair.second.begin(); iter != pair.second.end(); ++iter)
{
if (*iter == listName)
{
pair.second.erase(iter);
bret = true;
break;
}
}
return bret;
}
std::vector<std::u16string> list_processor::getList(const uchar_t& listID)
{
std::lock_guard<atomic_lock> lock(m_lock);
std::vector<std::u16string> list;
if (listID == 0)
{
for(const auto& pair : m_lists)
{
list.push_back(pair.first);
}
}
else
{
if (m_lists.size() >= listID)
{
const auto& pair = m_lists[listID - 1];
list = pair.second;
}
}
return list;
}
|
// bslmf_allocatorargt.t.cpp -*-C++-*-
#include <bslmf_allocatorargt.h>
#include <bsls_bsltestutil.h>
#include <stdio.h> // 'printf'
#include <stdlib.h> // 'atoi'
using namespace BloombergLP;
//=============================================================================
// TEST PLAN
//-----------------------------------------------------------------------------
// This component consists of an empty tag type and a constant object of that
// type. There is no functionality to test. Instead, we test that this tag
// can be used for its intended purpose, which is to disambiguate constructor
// and function calls. Thus, the entire test consists of a usage example.
//-----------------------------------------------------------------------------
// [1] struct bsl::allocator_arg_t
// [1] static const bsl::allocator_arg_t bsl::allocator_arg
//
// [1] USAGE EXAMPLE
// ============================================================================
// STANDARD BSL ASSERT TEST FUNCTION
// ----------------------------------------------------------------------------
namespace {
int testStatus = 0;
void aSsErT(bool condition, const char *message, int line)
{
if (condition) {
printf("Error " __FILE__ "(%d): %s (failed)\n", line, message);
if (0 <= testStatus && testStatus <= 100) {
++testStatus;
}
}
}
} // close unnamed namespace
// ============================================================================
// STANDARD BSL TEST DRIVER MACRO ABBREVIATIONS
// ----------------------------------------------------------------------------
#define ASSERT BSLS_BSLTESTUTIL_ASSERT
#define ASSERTV BSLS_BSLTESTUTIL_ASSERTV
#define LOOP_ASSERT BSLS_BSLTESTUTIL_LOOP_ASSERT
#define LOOP0_ASSERT BSLS_BSLTESTUTIL_LOOP0_ASSERT
#define LOOP1_ASSERT BSLS_BSLTESTUTIL_LOOP1_ASSERT
#define LOOP2_ASSERT BSLS_BSLTESTUTIL_LOOP2_ASSERT
#define LOOP3_ASSERT BSLS_BSLTESTUTIL_LOOP3_ASSERT
#define LOOP4_ASSERT BSLS_BSLTESTUTIL_LOOP4_ASSERT
#define LOOP5_ASSERT BSLS_BSLTESTUTIL_LOOP5_ASSERT
#define LOOP6_ASSERT BSLS_BSLTESTUTIL_LOOP6_ASSERT
#define Q BSLS_BSLTESTUTIL_Q // Quote identifier literally.
#define P BSLS_BSLTESTUTIL_P // Print identifier and value.
#define P_ BSLS_BSLTESTUTIL_P_ // P(X) without '\n'.
#define T_ BSLS_BSLTESTUTIL_T_ // Print a tab (w/o newline).
#define L_ BSLS_BSLTESTUTIL_L_ // current Line number
//=============================================================================
// GLOBAL TYPEDEFS/CONSTANTS FOR TESTING
//-----------------------------------------------------------------------------
//=============================================================================
// USAGE EXAMPLES
//-----------------------------------------------------------------------------
// BDE_VERIFY pragma: push // Usage examples relax rules for doc clarity
// BDE_VERIFY pragma: -AQJ02 // Headers are included where examples need them
// BDE_VERIFY pragma: -FABC01 // Functions ordered for expository purpose
// BDE_VERIFY pragma: -FD01 // Function contracts replaced by expository text
// BDE_VERIFY pragma: -FD03 // Function contracts replaced by expository text
///Usage
///-----
// In this section we show intended use of this component.
//
///Example 1: Disambiguate a constructor invocation
/// - - - - - - - - - - - - - - - - - - - - - - - -
// Suppose we want to define a nullable type that can be in the full state
// (holding an object) or the null state (not holding an object). When in the
// full state, memory is allocated for the held object using a memory
// allocator. For simplicity, this memory allocator is not automatically
// propagated to the held object.
//
// First, we define a simple allocator class hierarchy with an abstract
// 'xyzma::Allocator' base class and two derived classes:
// 'xyzma::NewDeleteAllocator' and 'xyzma::TestAllocator':
//..
#include <cstddef>
namespace xyzma {
class Allocator {
// Abstract allocator base class
public:
virtual ~Allocator() { }
virtual void *allocate(std::size_t nbytes) = 0;
virtual void deallocate(void *ptr) = 0;
};
class NewDeleteAllocator : public Allocator {
// Concrete allocator that uses operators 'new' and 'delete'
public:
static NewDeleteAllocator* singleton();
// Returns a singleton instance of this class
virtual void *allocate(std::size_t nbytes);
virtual void deallocate(void *ptr);
};
NewDeleteAllocator *NewDeleteAllocator::singleton() {
static NewDeleteAllocator s;
return &s;
}
void *NewDeleteAllocator::allocate(std::size_t nbytes) {
return ::operator new(nbytes);
}
void NewDeleteAllocator::deallocate(void *ptr) {
::operator delete(ptr);
}
class TestAllocator : public Allocator {
// Concrete allocator that keeps track of number of blocks allocated
// and deallocated.
std::size_t d_allocatedBlocks;
std::size_t d_deallocatedBlocks;
public:
TestAllocator() : d_allocatedBlocks(0), d_deallocatedBlocks(0) { }
virtual void *allocate(std::size_t nbytes);
virtual void deallocate(void *ptr);
// ACCESSORS
std::size_t allocatedBlocks() const { return d_allocatedBlocks; }
std::size_t deallocatedBlocks() const { return d_deallocatedBlocks; }
std::size_t outstandingBlocks() const {
return d_allocatedBlocks - d_deallocatedBlocks;
}
};
void *TestAllocator::allocate(std::size_t nbytes) {
++d_allocatedBlocks;
return ::operator new(nbytes);
}
void TestAllocator::deallocate(void *ptr) {
++d_deallocatedBlocks;
::operator delete(ptr);
}
} // close namespace xyzma
//..
// Next, we define our nullable class template, declaring two constructors: one
// that constructs the null object, and one that constructs a non-null object
// using the specified constructor argument. For flexibility, the second
// constructor is a template that takes any type and can therefore construct
// the object without necessarily invoking the copy constructor. (Ideally,
// this second constructor would be variadic, but that is not necessary for
// this example.):
//..
#include <new>
namespace xyzutl {
template <class TYPE>
class Nullable {
xyzma::Allocator *d_alloc_p;
TYPE *d_object_p;
public:
// CREATORS
Nullable();
// Construct a null object. Note: this is ctor A.
template <class ARG>
Nullable(const ARG& arg);
// Construct a non-null object using the specified 'arg' as the
// constructor argument for the 'TYPE' object. Note: this is ctor
// B.
//..
// Next, we want to add constructors that supply an allocator for use by the
// 'Nullable' object. Our first thought is to add two more constructors like
// the two above, but with an additional allocator argument at the end:
//..
// Nullable(xyzma::Allocator *alloc);
// ctor C
// template <class ARG>
// Nullable(const ARG& arg, xyzma::Allocator *alloc);
// ctor D
//..
// However, ctor C is difficult to invoke, because ctor B is almost always a
// better match. Nor can we use SFINAE to disqualify ctor B in cases where
// ARG is 'xyzma::Allocator*' because 'xyzma::Allocator*' is a perfectly valid
// constructor argument for many 'TYPE's.
//
// We solve this problem by using 'allocator_arg_t' to explicitly tag the
// constructor that takes an allocator argument:
//..
Nullable(bsl::allocator_arg_t, xyzma::Allocator *alloc);
// Construct a null object with the specified 'alloc' allocator.
// Note: this is ctor E
//..
// The 'allocator_arg_t' argument disambiguates the constructor.
//
// Next, to make things consistent (which is important for generic
// programming), we use the 'allocator_arg_t' tag in the other allocator-aware
// constructor, as well:
//..
template <class ARG>
Nullable(bsl::allocator_arg_t,
xyzma::Allocator *alloc,
const ARG& arg);
// Construct a non-null object using the specified 'arg' as the
// constructor argument for the 'TYPE' object, and the specified
// 'alloc' allocator. Note: this is ctor F.
//..
// Next, we finish the class interface and implementation:
//..
~Nullable();
// MANIPULATORS
Nullable& operator=(const Nullable& rhs);
// Copy assign this object from the specified 'rhs'.
Nullable& operator=(const TYPE& rhs);
// Construct a non-null object holding a copy of the specified
// 'rhs' object.
// ACCESSORS
const TYPE& value() const { return *d_object_p; }
// Return the object stored in this Nullable. The behavior is
// undefined if this is null.
bool isNull() const { return ! d_object_p; }
// Returns true if this object is not null.
xyzma::Allocator *allocator() const { return d_alloc_p; }
};
template <class TYPE>
Nullable<TYPE>::Nullable()
: d_alloc_p(xyzma::NewDeleteAllocator::singleton())
, d_object_p(0)
{
}
template <class TYPE>
template <class ARG>
Nullable<TYPE>::Nullable(const ARG& arg)
: d_alloc_p(xyzma::NewDeleteAllocator::singleton())
, d_object_p(static_cast<TYPE*>(d_alloc_p->allocate(sizeof(TYPE))))
{
::new(d_object_p) TYPE(arg);
}
template <class TYPE>
Nullable<TYPE>::Nullable(bsl::allocator_arg_t, xyzma::Allocator *alloc)
: d_alloc_p(alloc)
, d_object_p(0)
{
}
template <class TYPE>
template <class ARG>
Nullable<TYPE>::Nullable(bsl::allocator_arg_t,
xyzma::Allocator *alloc,
const ARG& arg)
: d_alloc_p(alloc)
, d_object_p(static_cast<TYPE*>(d_alloc_p->allocate(sizeof(TYPE))))
{
::new(d_object_p) TYPE(arg);
}
template <class TYPE>
Nullable<TYPE>::~Nullable() {
if (d_object_p) {
d_object_p->~TYPE();
d_alloc_p->deallocate(d_object_p);
}
}
template <class TYPE>
Nullable<TYPE>& Nullable<TYPE>::operator=(const Nullable& rhs) {
if (&rhs == this) return *this; // RETURN
if (!isNull() && !rhs.isNull()) {
*d_object_p = *rhs.d_object_p;
}
else if (!isNull() /* && rhs.isNull() */) {
// Make null
d_object_p->~TYPE();
d_alloc_p->deallocate(d_object_p);
d_object_p = 0;
}
else if (/* isNull() && */ !rhs.isNull()) {
// Allocate and copy from 'rhs'
d_object_p = static_cast<TYPE*>(d_alloc_p->allocate(sizeof(TYPE)));
::new(d_object_p) TYPE(*rhs.d_object_p);
}
// else both are null
return *this;
}
template <class TYPE>
Nullable<TYPE>& Nullable<TYPE>::operator=(const TYPE& rhs) {
if (isNull()) {
d_object_p = static_cast<TYPE*>(d_alloc_p->allocate(sizeof(TYPE)));
::new(d_object_p) TYPE(*rhs.d_object_p);
}
else {
*d_object_p = rhs;
}
return *this;
}
} // close namespace xyzutl
//..
// Now, for testing purposes, we define a class that takes an allocator
// constructor argument:
//..
class Obj {
xyzma::Allocator *d_alloc_p;
int d_count;
public:
explicit Obj(xyzma::Allocator *alloc = 0)
: d_alloc_p(alloc), d_count(0)
{
}
Obj(int count, xyzma::Allocator *alloc = 0) // IMPLICIT
: d_alloc_p(alloc), d_count(count)
{
}
int count() const { return d_count; }
xyzma::Allocator *allocator() const { return d_alloc_p; }
};
bool operator==(const Obj& a, const Obj& b) {
return a.count() == b.count();
}
bool operator!=(const Obj& a, const Obj& b) {
return a.count() != b.count();
}
//..
// Finally, we test that our nullable type can be constructed with and without
// an allocator pointer and that the allocator pointer can unambiguously be
// used for the object's allocator.
//..
int usageExample() {
using xyzutl::Nullable;
xyzma::TestAllocator ta;
Nullable<Obj> no1;
ASSERT( no1.isNull());
ASSERT(xyzma::NewDeleteAllocator::singleton() == no1.allocator());
Nullable<Obj> no2(2);
ASSERT(! no2.isNull());
ASSERT(xyzma::NewDeleteAllocator::singleton() == no2.allocator());
ASSERT(2 == no2.value());
ASSERT(0 == no2.value().allocator());
Nullable<Obj> no3(bsl::allocator_arg, &ta);
ASSERT( no3.isNull());
ASSERT(&ta == no3.allocator());
ASSERT(0 == ta.outstandingBlocks());
Nullable<Obj> no4(bsl::allocator_arg, &ta, 4);
ASSERT(! no4.isNull());
ASSERT(&ta == no4.allocator());
ASSERT(1 == ta.outstandingBlocks());
ASSERT(4 == no4.value());
ASSERT(0 == no4.value().allocator());
// '&ta' used by 'Obj', not by 'Nullable'.
Nullable<Obj> no5(&ta);
ASSERT(! no5.isNull());
ASSERT(xyzma::NewDeleteAllocator::singleton() == no5.allocator());
ASSERT(1 == ta.outstandingBlocks()); // No change
ASSERT(0 == no5.value());
ASSERT(&ta == no5.value().allocator());
// '&ta' used by both 'Nullable' and by 'Obj'
Nullable<Obj> no6(bsl::allocator_arg, &ta, &ta);
ASSERT(! no6.isNull());
ASSERT(&ta == no6.allocator());
ASSERT(2 == ta.outstandingBlocks());
ASSERT(0 == no6.value());
ASSERT(&ta == no6.value().allocator());
return 0;
}
//..
// BDE_VERIFY pragma: pop // end of usage example-example relaxed rules
//=============================================================================
// MAIN PROGRAM
//-----------------------------------------------------------------------------
int main(int argc, char *argv[])
{
int test = argc > 1 ? atoi(argv[1]) : 0;
bool verbose = argc > 2;
bool veryVerbose = argc > 3;
bool veryVeryVerbose = argc > 4;
bool veryVeryVeryVerbose = argc > 5;
(void) veryVerbose; // unused variable warning
(void) veryVeryVerbose; // unused variable warning
(void)veryVeryVeryVerbose; // unused variable warning
printf("TEST " __FILE__ " CASE %d\n", test);
switch (test) { case 0: // Zero is always the leading case.
case 1: {
// --------------------------------------------------------------------
// USAGE EXAMPLE
//
// Concerns:
//: 1 The usage example compiles and runs.
//: 2 'allocator_arg_t' can disambiguate constructors.
//
// Plan:
//: 1 For concern 1, copy the usage example from the header file.
//: 2 The usage example is designed to address concern 2.
//
// Testing:
// struct bsl::allocator_arg_t
// static const bsl::allocator_arg_t bsl::allocator_arg
// USAGE EXAMPLE
// --------------------------------------------------------------------
if (verbose) printf("\nUSAGE EXAMPLE"
"\n=============\n");
usageExample();
} break;
default: {
fprintf(stderr, "WARNING: CASE `%d' NOT FOUND.\n", test);
testStatus = -1;
}
}
if (testStatus > 0) {
fprintf(stderr, "Error, non-zero test status = %d.\n", testStatus);
}
return testStatus;
}
// ----------------------------------------------------------------------------
// Copyright 2015 Bloomberg Finance L.P.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------- END-OF-FILE ----------------------------------
|
//----------------------------------------------------------------------------//
// //
// ozz-animation is hosted at http://github.com/guillaumeblanc/ozz-animation //
// and distributed under the MIT License (MIT). //
// //
// Copyright (c) 2017 Guillaume Blanc //
// //
// Permission is hereby granted, free of charge, to any person obtaining a //
// copy of this software and associated documentation files (the "Software"), //
// to deal in the Software without restriction, including without limitation //
// the rights to use, copy, modify, merge, publish, distribute, sublicense, //
// and/or sell copies of the Software, and to permit persons to whom the //
// Software is furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL //
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING //
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER //
// DEALINGS IN THE SOFTWARE. //
// //
//----------------------------------------------------------------------------//
#include "ozz/animation/offline/track_optimizer.h"
#include <cassert>
#include <cstddef>
#include "ozz/base/maths/math_ex.h"
#include "ozz/animation/offline/raw_track.h"
// Needs runtime track to access TrackPolicy.
#include "ozz/animation/runtime/track.h"
namespace ozz {
namespace animation {
namespace offline {
// Setup default values (favoring quality).
TrackOptimizer::TrackOptimizer() : tolerance(1e-3f) { // 1 mm.
}
namespace {
bool Compare(float _left, float _right, float _tolerance) {
return fabs(_left - _right) <= _tolerance;
}
// Copy _src keys to _dest but except the ones that can be interpolated.
template <typename _Keyframes>
void Filter(const _Keyframes& _src, float _tolerance, _Keyframes* _dest) {
typedef typename _Keyframes::value_type Keyframe;
typedef typename Keyframe::ValueType ValueType;
_dest->reserve(_src.size());
// Only copies the key that cannot be interpolated from the others.
size_t last_src_pushed = 0; // Index (in src) of the last pushed key.
for (size_t i = 0; i < _src.size(); ++i) {
const Keyframe& current = _src[i];
// First and last keys are always pushed.
// RawTrackInterpolation::kStep keyframes aren't optimized, as steps can't
// be interpolated.
if (i == 0 || current.interpolation == RawTrackInterpolation::kStep) {
_dest->push_back(_src[i]);
last_src_pushed = i;
} else if (i == _src.size() - 1) {
// Don't push the last value if it's the same as last_src_pushed.
const Keyframe& left = _src[last_src_pushed];
if (!Compare(left.value, current.value, _tolerance)) {
_dest->push_back(current);
last_src_pushed = i;
}
} else {
// Only inserts i key if keys in range ]last_src_pushed,i] cannot be
// interpolated from keys last_src_pushed and i + 1.
const Keyframe& left = _src[last_src_pushed];
const Keyframe& right = _src[i + 1];
for (size_t j = last_src_pushed + 1; j <= i; ++j) {
const Keyframe& test = _src[j];
const float alpha =
(test.ratio - left.ratio) / (right.ratio - left.ratio);
assert(alpha >= 0.f && alpha <= 1.f);
const ValueType lerped =
animation::internal::TrackPolicy<ValueType>::Lerp(
left.value, right.value, alpha);
if (!Compare(lerped, test.value, _tolerance)) {
_dest->push_back(current);
last_src_pushed = i;
break;
}
}
}
}
assert(_dest->size() <= _src.size());
}
template <typename _Track>
bool Optimize(const TrackOptimizer& _optimizer, const _Track& _input,
_Track* _output) {
if (!_output) {
return false;
}
// Reset output animation to default.
*_output = _Track();
// Validate animation.
if (!_input.Validate()) {
return false;
}
// Copy name
_output->name = _input.name;
// Optimizes.
Filter(_input.keyframes, _optimizer.tolerance, &_output->keyframes);
// Output animation is always valid though.
return _output->Validate();
}
} // namespace
bool TrackOptimizer::operator()(const RawFloatTrack& _input,
RawFloatTrack* _output) const {
return Optimize(*this, _input, _output);
}
bool TrackOptimizer::operator()(const RawFloat2Track& _input,
RawFloat2Track* _output) const {
return Optimize(*this, _input, _output);
}
bool TrackOptimizer::operator()(const RawFloat3Track& _input,
RawFloat3Track* _output) const {
return Optimize(*this, _input, _output);
}
bool TrackOptimizer::operator()(const RawFloat4Track& _input,
RawFloat4Track* _output) const {
return Optimize(*this, _input, _output);
}
bool TrackOptimizer::operator()(const RawQuaternionTrack& _input,
RawQuaternionTrack* _output) const {
return Optimize(*this, _input, _output);
}
} // namespace offline
} // namespace animation
} // namespace ozz
|
// Copyright (c) UnnamedOrange. Licensed under the MIT Licence.
// See the LICENSE file in the repository root for full licence text.
#pragma once
#include <cctype>
#include <Windows.h>
#undef min
#undef max
#include "resource.h"
#include <utils/resource_loader.hpp>
#include <utils/multi_language.hpp>
class my_multi_language : public multi_language
{
public:
my_multi_language()
{
{
auto t = resource_loader::load(MAKEINTRESOURCEW(IDR_JSON_EN_US), L"JSON");
if (!load_language(std::string_view(reinterpret_cast<const char*>(t.data()))))
throw std::runtime_error("fail to load_language.");
}
{
auto t = resource_loader::load(MAKEINTRESOURCEW(IDR_JSON_ZH_CN), L"JSON");
load_language(std::string_view(reinterpret_cast<const char*>(t.data())));
}
}
public:
std::wstring operator[](std::string_view key) const
{
return code_conv<char8_t, wchar_t>::convert(multi_language::operator[](key));
}
void set_current_language_to_system_default()
{
wchar_t locale[LOCALE_NAME_MAX_LENGTH];
GetUserDefaultLocaleName(locale, LOCALE_NAME_MAX_LENGTH);
set_current_language(code_conv<wchar_t, char8_t>::convert(locale));
}
};
inline my_multi_language lang;
|
// Copyright (c) 2013-2019 The Arowanacoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/test/unit_test.hpp>
#include <clientversion.h>
#include <key.h>
#include <key_io.h>
#include <streams.h>
#include <util/system.h>
#include <util/strencodings.h>
#include <test/setup_common.h>
#include <string>
#include <vector>
struct TestDerivation {
std::string pub;
std::string prv;
unsigned int nChild;
};
struct TestVector {
std::string strHexMaster;
std::vector<TestDerivation> vDerive;
explicit TestVector(std::string strHexMasterIn) : strHexMaster(strHexMasterIn) {}
TestVector& operator()(std::string pub, std::string prv, unsigned int nChild) {
vDerive.push_back(TestDerivation());
TestDerivation &der = vDerive.back();
der.pub = pub;
der.prv = prv;
der.nChild = nChild;
return *this;
}
};
TestVector test1 =
TestVector("000102030405060708090a0b0c0d0e0f")
("xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8",
"xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi",
0x80000000)
("xpub68Gmy5EdvgibQVfPdqkBBCHxA5htiqg55crXYuXoQRKfDBFA1WEjWgP6LHhwBZeNK1VTsfTFUHCdrfp1bgwQ9xv5ski8PX9rL2dZXvgGDnw",
"xprv9uHRZZhk6KAJC1avXpDAp4MDc3sQKNxDiPvvkX8Br5ngLNv1TxvUxt4cV1rGL5hj6KCesnDYUhd7oWgT11eZG7XnxHrnYeSvkzY7d2bhkJ7",
1)
("xpub6ASuArnXKPbfEwhqN6e3mwBcDTgzisQN1wXN9BJcM47sSikHjJf3UFHKkNAWbWMiGj7Wf5uMash7SyYq527Hqck2AxYysAA7xmALppuCkwQ",
"xprv9wTYmMFdV23N2TdNG573QoEsfRrWKQgWeibmLntzniatZvR9BmLnvSxqu53Kw1UmYPxLgboyZQaXwTCg8MSY3H2EU4pWcQDnRnrVA1xe8fs",
0x80000002)
("xpub6D4BDPcP2GT577Vvch3R8wDkScZWzQzMMUm3PWbmWvVJrZwQY4VUNgqFJPMM3No2dFDFGTsxxpG5uJh7n7epu4trkrX7x7DogT5Uv6fcLW5",
"xprv9z4pot5VBttmtdRTWfWQmoH1taj2axGVzFqSb8C9xaxKymcFzXBDptWmT7FwuEzG3ryjH4ktypQSAewRiNMjANTtpgP4mLTj34bhnZX7UiM",
2)
("xpub6FHa3pjLCk84BayeJxFW2SP4XRrFd1JYnxeLeU8EqN3vDfZmbqBqaGJAyiLjTAwm6ZLRQUMv1ZACTj37sR62cfN7fe5JnJ7dh8zL4fiyLHV",
"xprvA2JDeKCSNNZky6uBCviVfJSKyQ1mDYahRjijr5idH2WwLsEd4Hsb2Tyh8RfQMuPh7f7RtyzTtdrbdqqsunu5Mm3wDvUAKRHSC34sJ7in334",
1000000000)
("xpub6H1LXWLaKsWFhvm6RVpEL9P4KfRZSW7abD2ttkWP3SSQvnyA8FSVqNTEcYFgJS2UaFcxupHiYkro49S8yGasTvXEYBVPamhGW6cFJodrTHy",
"xprvA41z7zogVVwxVSgdKUHDy1SKmdb533PjDz7J6N6mV6uS3ze1ai8FHa8kmHScGpWmj4WggLyQjgPie1rFSruoUihUZREPSL39UNdE3BBDu76",
0);
TestVector test2 =
TestVector("fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542")
("xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB",
"xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U",
0)
("xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH",
"xprv9vHkqa6EV4sPZHYqZznhT2NPtPCjKuDKGY38FBWLvgaDx45zo9WQRUT3dKYnjwih2yJD9mkrocEZXo1ex8G81dwSM1fwqWpWkeS3v86pgKt",
0xFFFFFFFF)
("xpub6ASAVgeehLbnwdqV6UKMHVzgqAG8Gr6riv3Fxxpj8ksbH9ebxaEyBLZ85ySDhKiLDBrQSARLq1uNRts8RuJiHjaDMBU4Zn9h8LZNnBC5y4a",
"xprv9wSp6B7kry3Vj9m1zSnLvN3xH8RdsPP1Mh7fAaR7aRLcQMKTR2vidYEeEg2mUCTAwCd6vnxVrcjfy2kRgVsFawNzmjuHc2YmYRmagcEPdU9",
1)
("xpub6DF8uhdarytz3FWdA8TvFSvvAh8dP3283MY7p2V4SeE2wyWmG5mg5EwVvmdMVCQcoNJxGoWaU9DCWh89LojfZ537wTfunKau47EL2dhHKon",
"xprv9zFnWC6h2cLgpmSA46vutJzBcfJ8yaJGg8cX1e5StJh45BBciYTRXSd25UEPVuesF9yog62tGAQtHjXajPPdbRCHuWS6T8XA2ECKADdw4Ef",
0xFFFFFFFE)
("xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL",
"xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc",
2)
("xpub6FnCn6nSzZAw5Tw7cgR9bi15UV96gLZhjDstkXXxvCLsUXBGXPdSnLFbdpq8p9HmGsApME5hQTZ3emM2rnY5agb9rXpVGyy3bdW6EEgAtqt",
"xprvA2nrNbFZABcdryreWet9Ea4LvTJcGsqrMzxHx98MMrotbir7yrKCEXw7nadnHM8Dq38EGfSh6dqA9QWTyefMLEcBYJUuekgW4BYPJcr9E7j",
0);
TestVector test3 =
TestVector("4b381541583be4423346c643850da4b320e46a87ae3d2a4e6da11eba819cd4acba45d239319ac14f863b8d5ab5a0d0c64d2e8a1e7d1457df2e5a3c51c73235be")
("xpub661MyMwAqRbcEZVB4dScxMAdx6d4nFc9nvyvH3v4gJL378CSRZiYmhRoP7mBy6gSPSCYk6SzXPTf3ND1cZAceL7SfJ1Z3GC8vBgp2epUt13",
"xprv9s21ZrQH143K25QhxbucbDDuQ4naNntJRi4KUfWT7xo4EKsHt2QJDu7KXp1A3u7Bi1j8ph3EGsZ9Xvz9dGuVrtHHs7pXeTzjuxBrCmmhgC6",
0x80000000)
("xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y",
"xprv9uPDJpEQgRQfDcW7BkF7eTya6RPxXeJCqCJGHuCJ4GiRVLzkTXBAJMu2qaMWPrS7AANYqdq6vcBcBUdJCVVFceUvJFjaPdGZ2y9WACViL4L",
0);
static void RunTest(const TestVector &test) {
std::vector<unsigned char> seed = ParseHex(test.strHexMaster);
CExtKey key;
CExtPubKey pubkey;
key.SetSeed(seed.data(), seed.size());
pubkey = key.Neuter();
for (const TestDerivation &derive : test.vDerive) {
unsigned char data[74];
key.Encode(data);
pubkey.Encode(data);
// Test private key
BOOST_CHECK(EncodeExtKey(key) == derive.prv);
BOOST_CHECK(DecodeExtKey(derive.prv) == key); //ensure a base58 decoded key also matches
// Test public key
BOOST_CHECK(EncodeExtPubKey(pubkey) == derive.pub);
BOOST_CHECK(DecodeExtPubKey(derive.pub) == pubkey); //ensure a base58 decoded pubkey also matches
// Derive new keys
CExtKey keyNew;
BOOST_CHECK(key.Derive(keyNew, derive.nChild));
CExtPubKey pubkeyNew = keyNew.Neuter();
if (!(derive.nChild & 0x80000000)) {
// Compare with public derivation
CExtPubKey pubkeyNew2;
BOOST_CHECK(pubkey.Derive(pubkeyNew2, derive.nChild));
BOOST_CHECK(pubkeyNew == pubkeyNew2);
}
key = keyNew;
pubkey = pubkeyNew;
CDataStream ssPub(SER_DISK, CLIENT_VERSION);
ssPub << pubkeyNew;
BOOST_CHECK(ssPub.size() == 75);
CDataStream ssPriv(SER_DISK, CLIENT_VERSION);
ssPriv << keyNew;
BOOST_CHECK(ssPriv.size() == 75);
CExtPubKey pubCheck;
CExtKey privCheck;
ssPub >> pubCheck;
ssPriv >> privCheck;
BOOST_CHECK(pubCheck == pubkeyNew);
BOOST_CHECK(privCheck == keyNew);
}
}
BOOST_FIXTURE_TEST_SUITE(bip32_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(bip32_test1) {
RunTest(test1);
}
BOOST_AUTO_TEST_CASE(bip32_test2) {
RunTest(test2);
}
BOOST_AUTO_TEST_CASE(bip32_test3) {
RunTest(test3);
}
BOOST_AUTO_TEST_SUITE_END()
|
#include <eosio/eosio.hpp>
// Message table
struct [[eosio::table("message"), eosio::contract("talk")]] message {
uint64_t id = {}; // Non-0
uint64_t reply_to = {}; // Non-0 if this is a reply
eosio::name user = {};
std::string content = {};
uint64_t primary_key() const { return id; }
uint64_t get_reply_to() const { return reply_to; }
};
using message_table = eosio::multi_index<
"message"_n, message, eosio::indexed_by<"by.reply.to"_n, eosio::const_mem_fun<message, uint64_t, &message::get_reply_to>>>;
// The contract
class talk : eosio::contract {
public:
// Use contract's constructor
using contract::contract;
// Post a message
[[eosio::action]] void post(uint64_t id, uint64_t reply_to, eosio::name user, const std::string& content) {
message_table table{get_self(), 0};
// Check user
require_auth(user);
// Check reply_to exists
if (reply_to)
table.get(reply_to);
// Create an ID if user didn't specify one
eosio::check(id < 1'000'000'000ull, "user-specified id is too large");
if (!id)
id = std::max(table.available_primary_key(), 1'000'000'000ull);
// Record the message
table.emplace(get_self(), [&](auto& message) {
message.id = id;
message.reply_to = reply_to;
message.user = user;
message.content = content;
});
}
};
|
// Copyright (c) 2018-2021 The Dash Core developers
// Copyright (c) 2021 The CREDD Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "evodb.h"
std::unique_ptr<CEvoDB> evoDb;
CEvoDBScopedCommitter::CEvoDBScopedCommitter(CEvoDB &_evoDB) :
evoDB(_evoDB)
{
}
CEvoDBScopedCommitter::~CEvoDBScopedCommitter()
{
if (!didCommitOrRollback)
Rollback();
}
void CEvoDBScopedCommitter::Commit()
{
assert(!didCommitOrRollback);
didCommitOrRollback = true;
evoDB.CommitCurTransaction();
}
void CEvoDBScopedCommitter::Rollback()
{
assert(!didCommitOrRollback);
didCommitOrRollback = true;
evoDB.RollbackCurTransaction();
}
CEvoDB::CEvoDB(size_t nCacheSize, bool fMemory, bool fWipe) :
db(fMemory ? "" : (GetDataDir() / "evodb"), nCacheSize, fMemory, fWipe),
rootBatch(),
rootDBTransaction(db, rootBatch),
curDBTransaction(rootDBTransaction, rootDBTransaction)
{
}
void CEvoDB::CommitCurTransaction()
{
LOCK(cs);
curDBTransaction.Commit();
}
void CEvoDB::RollbackCurTransaction()
{
LOCK(cs);
curDBTransaction.Clear();
}
bool CEvoDB::CommitRootTransaction()
{
assert(curDBTransaction.IsClean());
rootDBTransaction.Commit();
bool ret = db.WriteBatch(rootBatch);
rootBatch.Clear();
return ret;
}
bool CEvoDB::VerifyBestBlock(const uint256& hash)
{
uint256 hashBestBlock;
return Read(EVODB_BEST_BLOCK, hashBestBlock) && hashBestBlock == hash;
}
void CEvoDB::WriteBestBlock(const uint256& hash)
{
Write(EVODB_BEST_BLOCK, hash);
}
|
/* Delete Kth element from max heap */
#include<bits/stdc++.h>
using namespace std;
// Heapify the array
void max_heapify (int a[], int n, int i) {
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (n > left && a[left] > a[largest]) {
largest = left;
}
if (n > right && a[right] > a[largest]) {
largest = right;
}
if (largest != i) {
swap (a[largest], a[i]);
max_heapify (a, n, largest);
}
}
void build_heap (int a[], int n) {
for (int i = (n - 2) / 2; i >= 0; i--) {
max_heapify(a, n, i);
}
}
void delete_kth (int a[], int *n, int k) {
int r = a[k];
a[k] = a[*n-1];
(*n)--;
if (a[k] > a[(k - 1) / 2]) {
max_heapify (a, *n, (k - 1) / 2);
}
else{
max_heapify(a, *n, k);
}
}
int main() {
int n, k;
cout << "Enter size of the array : ";
cin >> n;
int a[n];
cout << "\nEnter elements of the array : ";
for (int i = 0; i < n; i++) {
cin >> a[i];
}
// Calling Function to create a max heap
build_heap(a, n);
cout << "\nMax heap : ";
// Print max heap
for (int i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout << "\nEnter the index of the element which you want to delete : ";
cin >> k;
// Calling function to delete kth element
delete_kth(a, &n, k);
cout << "\nAfter deleting " << k << "th index element ,new heap is : ";
for (int i = 0; i < n; i++) {
cout << a[i] << " ";
}
}
|
// Copyright (c) 2009-2013 The Bitcoin developers
// Copyright (c) 2015-2019 The PIVX developers
// Copyright (c) 2019 The ADSPLACE developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "crypter.h"
#include "script/script.h"
#include "script/standard.h"
#include "util.h"
#include "init.h"
#include "uint256.h"
#include <boost/foreach.hpp>
#include <openssl/aes.h>
#include <openssl/evp.h>
#include "wallet.h"
bool CCrypter::SetKeyFromPassphrase(const SecureString& strKeyData, const std::vector<unsigned char>& chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod)
{
if (nRounds < 1 || chSalt.size() != WALLET_CRYPTO_SALT_SIZE)
return false;
int i = 0;
if (nDerivationMethod == 0)
i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha512(), &chSalt[0],
(unsigned char*)&strKeyData[0], strKeyData.size(), nRounds, chKey, chIV);
if (i != (int)WALLET_CRYPTO_KEY_SIZE) {
OPENSSL_cleanse(chKey, sizeof(chKey));
OPENSSL_cleanse(chIV, sizeof(chIV));
return false;
}
fKeySet = true;
return true;
}
bool CCrypter::SetKey(const CKeyingMaterial& chNewKey, const std::vector<unsigned char>& chNewIV)
{
if (chNewKey.size() != WALLET_CRYPTO_KEY_SIZE || chNewIV.size() != WALLET_CRYPTO_KEY_SIZE)
return false;
memcpy(&chKey[0], &chNewKey[0], sizeof chKey);
memcpy(&chIV[0], &chNewIV[0], sizeof chIV);
fKeySet = true;
return true;
}
bool CCrypter::Encrypt(const CKeyingMaterial& vchPlaintext, std::vector<unsigned char>& vchCiphertext)
{
if (!fKeySet)
return false;
// max ciphertext len for a n bytes of plaintext is
// n + AES_BLOCK_SIZE - 1 bytes
int nLen = vchPlaintext.size();
int nCLen = nLen + AES_BLOCK_SIZE, nFLen = 0;
vchCiphertext = std::vector<unsigned char>(nCLen);
bool fOk = true;
EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
if (fOk) fOk = EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, chKey, chIV) != 0;
if (fOk) fOk = EVP_EncryptUpdate(ctx, &vchCiphertext[0], &nCLen, &vchPlaintext[0], nLen) != 0;
if (fOk) fOk = EVP_EncryptFinal_ex(ctx, (&vchCiphertext[0]) + nCLen, &nFLen) != 0;
EVP_CIPHER_CTX_free(ctx);
if (!fOk) return false;
vchCiphertext.resize(nCLen + nFLen);
return true;
}
bool CCrypter::Decrypt(const std::vector<unsigned char>& vchCiphertext, CKeyingMaterial& vchPlaintext)
{
if (!fKeySet)
return false;
// plaintext will always be equal to or lesser than length of ciphertext
int nLen = vchCiphertext.size();
int nPLen = nLen, nFLen = 0;
vchPlaintext = CKeyingMaterial(nPLen);
bool fOk = true;
EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
if (fOk) fOk = EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, chKey, chIV) != 0;
if (fOk) fOk = EVP_DecryptUpdate(ctx, &vchPlaintext[0], &nPLen, &vchCiphertext[0], nLen) != 0;
if (fOk) fOk = EVP_DecryptFinal_ex(ctx, (&vchPlaintext[0]) + nPLen, &nFLen) != 0;
EVP_CIPHER_CTX_free(ctx);
if (!fOk) return false;
vchPlaintext.resize(nPLen + nFLen);
return true;
}
bool EncryptSecret(const CKeyingMaterial& vMasterKey, const CKeyingMaterial& vchPlaintext, const uint256& nIV, std::vector<unsigned char>& vchCiphertext)
{
CCrypter cKeyCrypter;
std::vector<unsigned char> chIV(WALLET_CRYPTO_KEY_SIZE);
memcpy(&chIV[0], &nIV, WALLET_CRYPTO_KEY_SIZE);
if (!cKeyCrypter.SetKey(vMasterKey, chIV))
return false;
return cKeyCrypter.Encrypt(*((const CKeyingMaterial*)&vchPlaintext), vchCiphertext);
}
// General secure AES 256 CBC encryption routine
bool EncryptAES256(const SecureString& sKey, const SecureString& sPlaintext, const std::string& sIV, std::string& sCiphertext)
{
// max ciphertext len for a n bytes of plaintext is
// n + AES_BLOCK_SIZE - 1 bytes
int nLen = sPlaintext.size();
int nCLen = nLen + AES_BLOCK_SIZE;
int nFLen = 0;
// Verify key sizes
if (sKey.size() != 32 || sIV.size() != AES_BLOCK_SIZE) {
LogPrintf("crypter EncryptAES256 - Invalid key or block size: Key: %d sIV:%d\n", sKey.size(), sIV.size());
return false;
}
// Prepare output buffer
sCiphertext.resize(nCLen);
// Perform the encryption
EVP_CIPHER_CTX* ctx;
bool fOk = true;
ctx = EVP_CIPHER_CTX_new();
if (fOk) fOk = EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, (const unsigned char*)&sKey[0], (const unsigned char*)&sIV[0]);
if (fOk) fOk = EVP_EncryptUpdate(ctx, (unsigned char*)&sCiphertext[0], &nCLen, (const unsigned char*)&sPlaintext[0], nLen);
if (fOk) fOk = EVP_EncryptFinal_ex(ctx, (unsigned char*)(&sCiphertext[0]) + nCLen, &nFLen);
EVP_CIPHER_CTX_free(ctx);
if (!fOk) return false;
sCiphertext.resize(nCLen + nFLen);
return true;
}
bool DecryptSecret(const CKeyingMaterial& vMasterKey, const std::vector<unsigned char>& vchCiphertext, const uint256& nIV, CKeyingMaterial& vchPlaintext)
{
CCrypter cKeyCrypter;
std::vector<unsigned char> chIV(WALLET_CRYPTO_KEY_SIZE);
memcpy(&chIV[0], &nIV, WALLET_CRYPTO_KEY_SIZE);
if (!cKeyCrypter.SetKey(vMasterKey, chIV))
return false;
return cKeyCrypter.Decrypt(vchCiphertext, *((CKeyingMaterial*)&vchPlaintext));
}
bool DecryptAES256(const SecureString& sKey, const std::string& sCiphertext, const std::string& sIV, SecureString& sPlaintext)
{
// plaintext will always be equal to or lesser than length of ciphertext
int nLen = sCiphertext.size();
int nPLen = nLen, nFLen = 0;
// Verify key sizes
if (sKey.size() != 32 || sIV.size() != AES_BLOCK_SIZE) {
LogPrintf("crypter DecryptAES256 - Invalid key or block size\n");
return false;
}
sPlaintext.resize(nPLen);
EVP_CIPHER_CTX* ctx;
bool fOk = true;
ctx = EVP_CIPHER_CTX_new();
if (fOk) fOk = EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, (const unsigned char*)&sKey[0], (const unsigned char*)&sIV[0]);
if (fOk) fOk = EVP_DecryptUpdate(ctx, (unsigned char*)&sPlaintext[0], &nPLen, (const unsigned char*)&sCiphertext[0], nLen);
if (fOk) fOk = EVP_DecryptFinal_ex(ctx, (unsigned char*)(&sPlaintext[0]) + nPLen, &nFLen);
EVP_CIPHER_CTX_free(ctx);
if (!fOk) return false;
sPlaintext.resize(nPLen + nFLen);
return true;
}
bool CCryptoKeyStore::SetCrypted()
{
LOCK(cs_KeyStore);
if (fUseCrypto)
return true;
if (!mapKeys.empty())
return false;
fUseCrypto = true;
return true;
}
bool CCryptoKeyStore::Lock()
{
if (!SetCrypted())
return false;
{
LOCK(cs_KeyStore);
vMasterKey.clear();
pwalletMain->zwalletMain->Lock();
}
NotifyStatusChanged(this);
return true;
}
bool CCryptoKeyStore::Unlock(const CKeyingMaterial& vMasterKeyIn)
{
{
LOCK(cs_KeyStore);
if (!SetCrypted())
return false;
bool keyPass = false;
bool keyFail = false;
CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
for (; mi != mapCryptedKeys.end(); ++mi) {
const CPubKey& vchPubKey = (*mi).second.first;
const std::vector<unsigned char>& vchCryptedSecret = (*mi).second.second;
CKeyingMaterial vchSecret;
if (!DecryptSecret(vMasterKeyIn, vchCryptedSecret, vchPubKey.GetHash(), vchSecret)) {
keyFail = true;
break;
}
if (vchSecret.size() != 32) {
keyFail = true;
break;
}
CKey key;
key.Set(vchSecret.begin(), vchSecret.end(), vchPubKey.IsCompressed());
if (key.GetPubKey() != vchPubKey) {
keyFail = true;
break;
}
keyPass = true;
if (fDecryptionThoroughlyChecked)
break;
}
if (keyPass && keyFail) {
LogPrintf("The wallet is probably corrupted: Some keys decrypt but not all.");
assert(false);
}
if (keyFail || !keyPass)
return false;
vMasterKey = vMasterKeyIn;
fDecryptionThoroughlyChecked = true;
uint256 hashSeed;
if (CWalletDB(pwalletMain->strWalletFile).ReadCurrentSeedHash(hashSeed)) {
uint256 nSeed;
if (!GetDeterministicSeed(hashSeed, nSeed)) {
return error("Failed to read zADS seed from DB. Wallet is probably corrupt.");
}
pwalletMain->zwalletMain->SetMasterSeed(nSeed, false);
} else {
// First time this wallet has been unlocked with dzADS
// Borrow random generator from the key class so that we don't have to worry about randomness
CKey key;
key.MakeNewKey(true);
uint256 seed = key.GetPrivKey_256();
LogPrintf("%s: first run of zADS wallet detected, new seed generated. Seedhash=%s\n", __func__, Hash(seed.begin(), seed.end()).GetHex());
pwalletMain->zwalletMain->SetMasterSeed(seed, true);
pwalletMain->zwalletMain->GenerateMintPool();
}
}
NotifyStatusChanged(this);
return true;
}
bool CCryptoKeyStore::AddKeyPubKey(const CKey& key, const CPubKey& pubkey)
{
{
LOCK(cs_KeyStore);
if (!IsCrypted())
return CBasicKeyStore::AddKeyPubKey(key, pubkey);
if (IsLocked())
return false;
std::vector<unsigned char> vchCryptedSecret;
CKeyingMaterial vchSecret(key.begin(), key.end());
if (!EncryptSecret(vMasterKey, vchSecret, pubkey.GetHash(), vchCryptedSecret))
return false;
if (!AddCryptedKey(pubkey, vchCryptedSecret))
return false;
}
return true;
}
bool CCryptoKeyStore::AddCryptedKey(const CPubKey& vchPubKey, const std::vector<unsigned char>& vchCryptedSecret)
{
{
LOCK(cs_KeyStore);
if (!SetCrypted())
return false;
mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret);
}
return true;
}
bool CCryptoKeyStore::GetKey(const CKeyID& address, CKey& keyOut) const
{
{
LOCK(cs_KeyStore);
if (!IsCrypted())
return CBasicKeyStore::GetKey(address, keyOut);
CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
if (mi != mapCryptedKeys.end()) {
const CPubKey& vchPubKey = (*mi).second.first;
const std::vector<unsigned char>& vchCryptedSecret = (*mi).second.second;
CKeyingMaterial vchSecret;
if (!DecryptSecret(vMasterKey, vchCryptedSecret, vchPubKey.GetHash(), vchSecret))
return false;
if (vchSecret.size() != 32)
return false;
keyOut.Set(vchSecret.begin(), vchSecret.end(), vchPubKey.IsCompressed());
return true;
}
}
return false;
}
bool CCryptoKeyStore::GetPubKey(const CKeyID& address, CPubKey& vchPubKeyOut) const
{
{
LOCK(cs_KeyStore);
if (!IsCrypted())
return CKeyStore::GetPubKey(address, vchPubKeyOut);
CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
if (mi != mapCryptedKeys.end()) {
vchPubKeyOut = (*mi).second.first;
return true;
}
}
return false;
}
bool CCryptoKeyStore::EncryptKeys(CKeyingMaterial& vMasterKeyIn)
{
{
LOCK(cs_KeyStore);
if (!mapCryptedKeys.empty() || IsCrypted())
return false;
fUseCrypto = true;
BOOST_FOREACH (KeyMap::value_type& mKey, mapKeys) {
const CKey& key = mKey.second;
CPubKey vchPubKey = key.GetPubKey();
CKeyingMaterial vchSecret(key.begin(), key.end());
std::vector<unsigned char> vchCryptedSecret;
if (!EncryptSecret(vMasterKeyIn, vchSecret, vchPubKey.GetHash(), vchCryptedSecret))
return false;
if (!AddCryptedKey(vchPubKey, vchCryptedSecret))
return false;
}
mapKeys.clear();
}
return true;
}
bool CCryptoKeyStore::AddDeterministicSeed(const uint256& seed)
{
CWalletDB db(pwalletMain->strWalletFile);
string strErr;
uint256 hashSeed = Hash(seed.begin(), seed.end());
if(IsCrypted()) {
if (!IsLocked()) { //if we have password
CKeyingMaterial kmSeed(seed.begin(), seed.end());
vector<unsigned char> vchSeedSecret;
//attempt encrypt
if (EncryptSecret(vMasterKey, kmSeed, hashSeed, vchSeedSecret)) {
//write to wallet with hashSeed as unique key
if (db.WriteZADSSeed(hashSeed, vchSeedSecret)) {
return true;
}
}
strErr = "encrypt seed";
}
strErr = "save since wallet is locked";
} else { //wallet not encrypted
if (db.WriteZADSSeed(hashSeed, ToByteVector(seed))) {
return true;
}
strErr = "save zADSseed to wallet";
}
//the use case for this is no password set seed, mint dzADS,
return error("s%: Failed to %s\n", __func__, strErr);
}
bool CCryptoKeyStore::GetDeterministicSeed(const uint256& hashSeed, uint256& seedOut)
{
CWalletDB db(pwalletMain->strWalletFile);
string strErr;
if (IsCrypted()) {
if(!IsLocked()) { //if we have password
vector<unsigned char> vchCryptedSeed;
//read encrypted seed
if (db.ReadZADSSeed(hashSeed, vchCryptedSeed)) {
uint256 seedRetrieved = uint256(ReverseEndianString(HexStr(vchCryptedSeed)));
//this checks if the hash of the seed we just read matches the hash given, meaning it is not encrypted
//the use case for this is when not crypted, seed is set, then password set, the seed not yet crypted in memory
if(hashSeed == Hash(seedRetrieved.begin(), seedRetrieved.end())) {
seedOut = seedRetrieved;
return true;
}
CKeyingMaterial kmSeed;
//attempt decrypt
if (DecryptSecret(vMasterKey, vchCryptedSeed, hashSeed, kmSeed)) {
seedOut = uint256(ReverseEndianString(HexStr(kmSeed)));
return true;
}
strErr = "decrypt seed";
} else { strErr = "read seed from wallet"; }
} else { strErr = "read seed; wallet is locked"; }
} else {
vector<unsigned char> vchSeed;
// wallet not crypted
if (db.ReadZADSSeed(hashSeed, vchSeed)) {
seedOut = uint256(ReverseEndianString(HexStr(vchSeed)));
return true;
}
strErr = "read seed from wallet";
}
return error("%s: Failed to %s\n", __func__, strErr);
// return error("Failed to decrypt deterministic seed %s", IsLocked() ? "Wallet is locked!" : "");
}
|
/*
* Copyright (C) 2007 Apple Inc.
* Copyright (C) 2007 Alp Toker <alp@atoker.com>
* Copyright (C) 2008 Collabora Ltd.
* Copyright (C) 2008, 2009 Google Inc.
* Copyright (C) 2009 Kenneth Rohde Christiansen
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#include "config.h"
#include "core/layout/LayoutThemeDefault.h"
#include "core/CSSValueKeywords.h"
#include "core/layout/LayoutObject.h"
#include "core/layout/LayoutProgress.h"
#include "core/layout/LayoutThemeFontProvider.h"
#include "core/paint/MediaControlsPainter.h"
#include "platform/LayoutTestSupport.h"
#include "platform/PlatformResourceLoader.h"
#include "platform/graphics/Color.h"
#include "platform/scroll/ScrollbarTheme.h"
#include "public/platform/Platform.h"
#include "public/platform/WebThemeEngine.h"
namespace blink {
enum PaddingType {
TopPadding,
RightPadding,
BottomPadding,
LeftPadding
};
static const int styledMenuListInternalPadding[4] = { 1, 4, 1, 4 };
// These values all match Safari/Win.
static const float defaultControlFontPixelSize = 13;
static const float defaultCancelButtonSize = 9;
static const float minCancelButtonSize = 5;
static const float maxCancelButtonSize = 21;
static const float defaultSearchFieldResultsDecorationSize = 13;
static const float minSearchFieldResultsDecorationSize = 9;
static const float maxSearchFieldResultsDecorationSize = 30;
static bool useMockTheme()
{
return LayoutTestSupport::isRunningLayoutTest();
}
unsigned LayoutThemeDefault::m_activeSelectionBackgroundColor = 0xff1e90ff;
unsigned LayoutThemeDefault::m_activeSelectionForegroundColor = Color::black;
unsigned LayoutThemeDefault::m_inactiveSelectionBackgroundColor = 0xffc8c8c8;
unsigned LayoutThemeDefault::m_inactiveSelectionForegroundColor = 0xff323232;
double LayoutThemeDefault::m_caretBlinkInterval;
LayoutThemeDefault::LayoutThemeDefault()
{
m_caretBlinkInterval = LayoutTheme::caretBlinkInterval();
}
LayoutThemeDefault::~LayoutThemeDefault()
{
}
bool LayoutThemeDefault::supportsFocusRing(const ComputedStyle& style) const
{
if (useMockTheme()) {
// Don't use focus rings for buttons when mocking controls.
return style.appearance() == ButtonPart
|| style.appearance() == PushButtonPart
|| style.appearance() == SquareButtonPart;
}
// This causes Blink to draw the focus rings for us.
return false;
}
Color LayoutThemeDefault::systemColor(CSSValueID cssValueId) const
{
static const Color defaultButtonGrayColor(0xffdddddd);
static const Color defaultMenuColor(0xfff7f7f7);
if (cssValueId == CSSValueButtonface) {
if (useMockTheme())
return Color(0xc0, 0xc0, 0xc0);
return defaultButtonGrayColor;
}
if (cssValueId == CSSValueMenu)
return defaultMenuColor;
return LayoutTheme::systemColor(cssValueId);
}
// Use the Windows style sheets to match their metrics.
String LayoutThemeDefault::extraDefaultStyleSheet()
{
return LayoutTheme::extraDefaultStyleSheet()
+ loadResourceAsASCIIString("themeWin.css")
+ loadResourceAsASCIIString("themeChromiumSkia.css")
#if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
+ loadResourceAsASCIIString("themeInputMultipleFields.css")
#endif
+ loadResourceAsASCIIString("themeChromium.css");
}
String LayoutThemeDefault::extraQuirksStyleSheet()
{
return loadResourceAsASCIIString("themeWinQuirks.css");
}
Color LayoutThemeDefault::activeListBoxSelectionBackgroundColor() const
{
return Color(0x28, 0x28, 0x28);
}
Color LayoutThemeDefault::activeListBoxSelectionForegroundColor() const
{
return Color::black;
}
Color LayoutThemeDefault::inactiveListBoxSelectionBackgroundColor() const
{
return Color(0xc8, 0xc8, 0xc8);
}
Color LayoutThemeDefault::inactiveListBoxSelectionForegroundColor() const
{
return Color(0x32, 0x32, 0x32);
}
Color LayoutThemeDefault::platformActiveSelectionBackgroundColor() const
{
if (useMockTheme())
return Color(0x00, 0x00, 0xff); // Royal blue.
return m_activeSelectionBackgroundColor;
}
Color LayoutThemeDefault::platformInactiveSelectionBackgroundColor() const
{
if (useMockTheme())
return Color(0x99, 0x99, 0x99); // Medium gray.
return m_inactiveSelectionBackgroundColor;
}
Color LayoutThemeDefault::platformActiveSelectionForegroundColor() const
{
if (useMockTheme())
return Color(0xff, 0xff, 0xcc); // Pale yellow.
return m_activeSelectionForegroundColor;
}
Color LayoutThemeDefault::platformInactiveSelectionForegroundColor() const
{
if (useMockTheme())
return Color::white;
return m_inactiveSelectionForegroundColor;
}
IntSize LayoutThemeDefault::sliderTickSize() const
{
if (useMockTheme())
return IntSize(1, 3);
return IntSize(1, 6);
}
int LayoutThemeDefault::sliderTickOffsetFromTrackCenter() const
{
if (useMockTheme())
return 11;
return -16;
}
void LayoutThemeDefault::adjustSliderThumbSize(ComputedStyle& style, Element* element) const
{
IntSize size = Platform::current()->themeEngine()->getSize(WebThemeEngine::PartSliderThumb);
// FIXME: Mock theme doesn't handle zoomed sliders.
float zoomLevel = useMockTheme() ? 1 : style.effectiveZoom();
if (style.appearance() == SliderThumbHorizontalPart) {
style.setWidth(Length(size.width() * zoomLevel, Fixed));
style.setHeight(Length(size.height() * zoomLevel, Fixed));
} else if (style.appearance() == SliderThumbVerticalPart) {
style.setWidth(Length(size.height() * zoomLevel, Fixed));
style.setHeight(Length(size.width() * zoomLevel, Fixed));
} else {
MediaControlsPainter::adjustMediaSliderThumbSize(style);
}
}
void LayoutThemeDefault::setCaretBlinkInterval(double interval)
{
m_caretBlinkInterval = interval;
}
void LayoutThemeDefault::setSelectionColors(
unsigned activeBackgroundColor,
unsigned activeForegroundColor,
unsigned inactiveBackgroundColor,
unsigned inactiveForegroundColor)
{
m_activeSelectionBackgroundColor = activeBackgroundColor;
m_activeSelectionForegroundColor = activeForegroundColor;
m_inactiveSelectionBackgroundColor = inactiveBackgroundColor;
m_inactiveSelectionForegroundColor = inactiveForegroundColor;
}
void LayoutThemeDefault::setCheckboxSize(ComputedStyle& style) const
{
// If the width and height are both specified, then we have nothing to do.
if (!style.width().isIntrinsicOrAuto() && !style.height().isAuto())
return;
IntSize size = Platform::current()->themeEngine()->getSize(WebThemeEngine::PartCheckbox);
float zoomLevel = style.effectiveZoom();
size.setWidth(size.width() * zoomLevel);
size.setHeight(size.height() * zoomLevel);
setSizeIfAuto(style, size);
}
void LayoutThemeDefault::setRadioSize(ComputedStyle& style) const
{
// If the width and height are both specified, then we have nothing to do.
if (!style.width().isIntrinsicOrAuto() && !style.height().isAuto())
return;
IntSize size = Platform::current()->themeEngine()->getSize(WebThemeEngine::PartRadio);
float zoomLevel = style.effectiveZoom();
size.setWidth(size.width() * zoomLevel);
size.setHeight(size.height() * zoomLevel);
setSizeIfAuto(style, size);
}
void LayoutThemeDefault::adjustInnerSpinButtonStyle(ComputedStyle& style, Element*) const
{
IntSize size = Platform::current()->themeEngine()->getSize(WebThemeEngine::PartInnerSpinButton);
style.setWidth(Length(size.width(), Fixed));
style.setMinWidth(Length(size.width(), Fixed));
}
bool LayoutThemeDefault::shouldOpenPickerWithF4Key() const
{
return true;
}
bool LayoutThemeDefault::shouldUseFallbackTheme(const ComputedStyle& style) const
{
if (useMockTheme()) {
// The mock theme can't handle zoomed controls, so we fall back to the "fallback" theme.
ControlPart part = style.appearance();
if (part == CheckboxPart || part == RadioPart)
return style.effectiveZoom() != 1;
}
return LayoutTheme::shouldUseFallbackTheme(style);
}
bool LayoutThemeDefault::supportsHover(const ComputedStyle& style) const
{
return true;
}
Color LayoutThemeDefault::platformFocusRingColor() const
{
static Color focusRingColor(229, 151, 0, 255);
return focusRingColor;
}
double LayoutThemeDefault::caretBlinkInterval() const
{
// Disable the blinking caret in layout test mode, as it introduces
// a race condition for the pixel tests. http://b/1198440
if (LayoutTestSupport::isRunningLayoutTest())
return 0;
return m_caretBlinkInterval;
}
void LayoutThemeDefault::systemFont(CSSValueID systemFontID, FontStyle& fontStyle, FontWeight& fontWeight, float& fontSize, AtomicString& fontFamily) const
{
LayoutThemeFontProvider::systemFont(systemFontID, fontStyle, fontWeight, fontSize, fontFamily);
}
int LayoutThemeDefault::minimumMenuListSize(const ComputedStyle& style) const
{
return 0;
}
// Return a rectangle that has the same center point as |original|, but with a
// size capped at |width| by |height|.
IntRect center(const IntRect& original, int width, int height)
{
width = std::min(original.width(), width);
height = std::min(original.height(), height);
int x = original.x() + (original.width() - width) / 2;
int y = original.y() + (original.height() - height) / 2;
return IntRect(x, y, width, height);
}
void LayoutThemeDefault::adjustButtonStyle(ComputedStyle& style, Element*) const
{
if (style.appearance() == PushButtonPart) {
// Ignore line-height.
style.setLineHeight(ComputedStyle::initialLineHeight());
}
}
void LayoutThemeDefault::adjustSearchFieldStyle(ComputedStyle& style, Element*) const
{
// Ignore line-height.
style.setLineHeight(ComputedStyle::initialLineHeight());
}
void LayoutThemeDefault::adjustSearchFieldCancelButtonStyle(ComputedStyle& style, Element*) const
{
// Scale the button size based on the font size
float fontScale = style.fontSize() / defaultControlFontPixelSize;
int cancelButtonSize = lroundf(std::min(std::max(minCancelButtonSize, defaultCancelButtonSize * fontScale), maxCancelButtonSize));
style.setWidth(Length(cancelButtonSize, Fixed));
style.setHeight(Length(cancelButtonSize, Fixed));
}
void LayoutThemeDefault::adjustSearchFieldDecorationStyle(ComputedStyle& style, Element*) const
{
IntSize emptySize(1, 11);
style.setWidth(Length(emptySize.width(), Fixed));
style.setHeight(Length(emptySize.height(), Fixed));
}
void LayoutThemeDefault::adjustSearchFieldResultsDecorationStyle(ComputedStyle& style, Element*) const
{
// Scale the decoration size based on the font size
float fontScale = style.fontSize() / defaultControlFontPixelSize;
int magnifierSize = lroundf(std::min(std::max(minSearchFieldResultsDecorationSize, defaultSearchFieldResultsDecorationSize * fontScale),
maxSearchFieldResultsDecorationSize));
style.setWidth(Length(magnifierSize, Fixed));
style.setHeight(Length(magnifierSize, Fixed));
}
void LayoutThemeDefault::adjustMenuListStyle(ComputedStyle& style, Element*) const
{
// Height is locked to auto on all browsers.
style.setLineHeight(ComputedStyle::initialLineHeight());
}
void LayoutThemeDefault::adjustMenuListButtonStyle(ComputedStyle& style, Element* e) const
{
adjustMenuListStyle(style, e);
}
int LayoutThemeDefault::popupInternalPaddingLeft(const ComputedStyle& style) const
{
return menuListInternalPadding(style, LeftPadding);
}
int LayoutThemeDefault::popupInternalPaddingRight(const ComputedStyle& style) const
{
return menuListInternalPadding(style, RightPadding);
}
int LayoutThemeDefault::popupInternalPaddingTop(const ComputedStyle& style) const
{
return menuListInternalPadding(style, TopPadding);
}
int LayoutThemeDefault::popupInternalPaddingBottom(const ComputedStyle& style) const
{
return menuListInternalPadding(style, BottomPadding);
}
// static
void LayoutThemeDefault::setDefaultFontSize(int fontSize)
{
LayoutThemeFontProvider::setDefaultFontSize(fontSize);
}
int LayoutThemeDefault::menuListArrowPadding() const
{
return ScrollbarTheme::theme()->scrollbarThickness();
}
int LayoutThemeDefault::menuListInternalPadding(const ComputedStyle& style, int paddingType) const
{
// This internal padding is in addition to the user-supplied padding.
// Matches the FF behavior.
int padding = styledMenuListInternalPadding[paddingType];
// Reserve the space for right arrow here. The rest of the padding is
// set by adjustMenuListStyle, since PopMenuWin.cpp uses the padding from
// LayoutMenuList to lay out the individual items in the popup.
// If the MenuList actually has appearance "NoAppearance", then that means
// we don't draw a button, so don't reserve space for it.
const int barType = style.direction() == LTR ? RightPadding : LeftPadding;
if (paddingType == barType && style.appearance() != NoControlPart)
padding += menuListArrowPadding();
return padding;
}
bool LayoutThemeDefault::shouldShowPlaceholderWhenFocused() const
{
return true;
}
//
// Following values are come from default of GTK+
//
static const int progressAnimationFrames = 10;
static const double progressAnimationInterval = 0.125;
double LayoutThemeDefault::animationRepeatIntervalForProgressBar() const
{
return progressAnimationInterval;
}
double LayoutThemeDefault::animationDurationForProgressBar() const
{
return progressAnimationInterval * progressAnimationFrames * 2; // "2" for back and forth
}
} // namespace blink
|
/**
* @file concat_impl.hpp
* @author Marcus Edel
* @author Mehul Kumar Nirala
*
* Implementation of the Concat class, which acts as a concatenation contain.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_METHODS_ANN_LAYER_CONCAT_IMPL_HPP
#define MLPACK_METHODS_ANN_LAYER_CONCAT_IMPL_HPP
// In case it hasn't yet been included.
#include "concat.hpp"
#include "../visitor/forward_visitor.hpp"
#include "../visitor/backward_visitor.hpp"
#include "../visitor/gradient_visitor.hpp"
namespace mlpack {
namespace ann /** Artificial Neural Network. */ {
template<typename InputDataType, typename OutputDataType,
typename... CustomLayers>
Concat<InputDataType, OutputDataType, CustomLayers...>::Concat(
const bool model, const bool run) :
axis(0),
useAxis(false),
model(model),
run(run),
channels(1)
{
parameters.set_size(0, 0);
}
template<typename InputDataType, typename OutputDataType,
typename... CustomLayers>
Concat<InputDataType, OutputDataType, CustomLayers...>::Concat(
arma::Row<size_t>& inputSize,
const size_t axis,
const bool model,
const bool run) :
inputSize(inputSize),
axis(axis),
useAxis(true),
model(model),
run(run)
{
parameters.set_size(0, 0);
// Parameters to help calculate the number of channels.
size_t oldColSize = 1, newColSize = 1;
// Axis is specified and useAxis is true.
if (useAxis)
{
// Axis is specified without input dimension.
// Throw an error.
if (inputSize.n_elem > 0)
{
// Calculate rowSize, newColSize based on the axis
// of concatenation. Finally concat along cols and
// reshape to original format i.e. (input, batch_size).
size_t i = std::min(axis + 1, (size_t) inputSize.n_elem);
for (; i < inputSize.n_elem; ++i)
{
newColSize *= inputSize[i];
}
}
else
{
throw std::logic_error("Input dimensions not specified.");
}
}
else
{
channels = 1;
}
if (newColSize <= 0)
{
throw std::logic_error("Col size is zero.");
}
channels = newColSize / oldColSize;
inputSize.clear();
}
template<typename InputDataType, typename OutputDataType,
typename... CustomLayers>
Concat<InputDataType, OutputDataType, CustomLayers...>::~Concat()
{
// Clear memory.
std::for_each(network.begin(), network.end(),
boost::apply_visitor(deleteVisitor));
}
template<typename InputDataType, typename OutputDataType,
typename... CustomLayers>
template<typename eT>
void Concat<InputDataType, OutputDataType, CustomLayers...>::Forward(
const arma::Mat<eT>& input, arma::Mat<eT>& output)
{
if (run)
{
for (size_t i = 0; i < network.size(); ++i)
{
boost::apply_visitor(ForwardVisitor(input,
boost::apply_visitor(outputParameterVisitor, network[i])),
network[i]);
}
}
output = boost::apply_visitor(outputParameterVisitor, network.front());
// Reshape output to incorporate the channels.
output.reshape(output.n_rows / channels, output.n_cols * channels);
for (size_t i = 1; i < network.size(); ++i)
{
arma::Mat<eT> out = boost::apply_visitor(outputParameterVisitor,
network[i]);
out.reshape(out.n_rows / channels, out.n_cols * channels);
// Vertically concatentate output from each layer.
output = arma::join_cols(output, out);
}
// Reshape output to its original shape.
output.reshape(output.n_rows * channels, output.n_cols / channels);
}
template<typename InputDataType, typename OutputDataType,
typename... CustomLayers>
template<typename eT>
void Concat<InputDataType, OutputDataType, CustomLayers...>::Backward(
const arma::Mat<eT>& /* input */, const arma::Mat<eT>& gy, arma::Mat<eT>& g)
{
size_t rowCount = 0;
if (run)
{
arma::Mat<eT> delta;
arma::Mat<eT> gyTmp(((arma::Mat<eT>&) gy).memptr(), gy.n_rows / channels,
gy.n_cols * channels, false, false);
for (size_t i = 0; i < network.size(); ++i)
{
// Use rows from the error corresponding to the output from each layer.
size_t rows = boost::apply_visitor(
outputParameterVisitor, network[i]).n_rows;
// Extract from gy the parameters for the i-th network.
delta = gyTmp.rows(rowCount / channels, (rowCount + rows) / channels - 1);
delta.reshape(delta.n_rows * channels, delta.n_cols / channels);
boost::apply_visitor(BackwardVisitor(
boost::apply_visitor(outputParameterVisitor,
network[i]), delta,
boost::apply_visitor(deltaVisitor, network[i])), network[i]);
rowCount += rows;
}
g = boost::apply_visitor(deltaVisitor, network[0]);
for (size_t i = 1; i < network.size(); ++i)
{
g += boost::apply_visitor(deltaVisitor, network[i]);
}
}
else
{
g = gy;
}
}
template<typename InputDataType, typename OutputDataType,
typename... CustomLayers>
template<typename eT>
void Concat<InputDataType, OutputDataType, CustomLayers...>::Backward(
const arma::Mat<eT>& /* input */,
const arma::Mat<eT>& gy,
arma::Mat<eT>& g,
const size_t index)
{
size_t rowCount = 0, rows = 0;
for (size_t i = 0; i < index; ++i)
{
rowCount += boost::apply_visitor(
outputParameterVisitor, network[i]).n_rows;
}
rows = boost::apply_visitor(outputParameterVisitor, network[index]).n_rows;
// Reshape gy to extract the i-th layer gy.
arma::Mat<eT> gyTmp(((arma::Mat<eT>&) gy).memptr(), gy.n_rows / channels,
gy.n_cols * channels, false, false);
arma::Mat<eT> delta = gyTmp.rows(rowCount / channels, (rowCount + rows) /
channels - 1);
delta.reshape(delta.n_rows * channels, delta.n_cols / channels);
boost::apply_visitor(BackwardVisitor(boost::apply_visitor(
outputParameterVisitor, network[index]), delta,
boost::apply_visitor(deltaVisitor, network[index])), network[index]);
g = boost::apply_visitor(deltaVisitor, network[index]);
}
template<typename InputDataType, typename OutputDataType,
typename... CustomLayers>
template<typename eT>
void Concat<InputDataType, OutputDataType, CustomLayers...>::Gradient(
const arma::Mat<eT>& input,
const arma::Mat<eT>& error,
arma::Mat<eT>& /* gradient */)
{
if (run)
{
size_t rowCount = 0;
// Reshape error to extract the i-th layer error.
arma::Mat<eT> errorTmp(((arma::Mat<eT>&) error).memptr(),
error.n_rows / channels, error.n_cols * channels, false, false);
for (size_t i = 0; i < network.size(); ++i)
{
size_t rows = boost::apply_visitor(
outputParameterVisitor, network[i]).n_rows;
// Extract from error the parameters for the i-th network.
arma::Mat<eT> err = errorTmp.rows(rowCount / channels, (rowCount + rows) /
channels - 1);
err.reshape(err.n_rows * channels, err.n_cols / channels);
boost::apply_visitor(GradientVisitor(input, err), network[i]);
rowCount += rows;
}
}
}
template<typename InputDataType, typename OutputDataType,
typename... CustomLayers>
template<typename eT>
void Concat<InputDataType, OutputDataType, CustomLayers...>::Gradient(
const arma::Mat<eT>& input,
const arma::Mat<eT>& error,
arma::Mat<eT>& /* gradient */,
const size_t index)
{
size_t rowCount = 0;
for (size_t i = 0; i < index; ++i)
{
rowCount += boost::apply_visitor(outputParameterVisitor,
network[i]).n_rows;
}
size_t rows = boost::apply_visitor(
outputParameterVisitor, network[index]).n_rows;
arma::Mat<eT> errorTmp(((arma::Mat<eT>&) error).memptr(),
error.n_rows / channels, error.n_cols * channels, false, false);
arma::Mat<eT> err = errorTmp.rows(rowCount / channels, (rowCount + rows) /
channels - 1);
err.reshape(err.n_rows * channels, err.n_cols / channels);
boost::apply_visitor(GradientVisitor(input, err), network[index]);
}
template<typename InputDataType, typename OutputDataType,
typename... CustomLayers>
template<typename Archive>
void Concat<InputDataType, OutputDataType, CustomLayers...>::serialize(
Archive& ar, const unsigned int /* version */)
{
ar & BOOST_SERIALIZATION_NVP(model);
ar & BOOST_SERIALIZATION_NVP(run);
// Do we have to load or save a model?
if (model)
{
// Clear memory first, if needed.
if (Archive::is_loading::value)
{
std::for_each(network.begin(), network.end(),
boost::apply_visitor(deleteVisitor));
}
ar & BOOST_SERIALIZATION_NVP(network);
}
}
} // namespace ann
} // namespace mlpack
#endif
|
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The ADSPLACE developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/adsplace-config.h"
#endif
#include "util.h"
#include "uritests.h"
#ifdef ENABLE_WALLET
#include "paymentservertests.h"
#endif
#include <QCoreApplication>
#include <QObject>
#include <QTest>
#include <openssl/ssl.h>
#if defined(QT_STATICPLUGIN)
#include <QtPlugin>
#if defined(QT_QPA_PLATFORM_MINIMAL)
Q_IMPORT_PLUGIN(QMinimalIntegrationPlugin);
#endif
#if defined(QT_QPA_PLATFORM_XCB)
Q_IMPORT_PLUGIN(QXcbIntegrationPlugin);
#elif defined(QT_QPA_PLATFORM_WINDOWS)
Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin);
#elif defined(QT_QPA_PLATFORM_COCOA)
Q_IMPORT_PLUGIN(QCocoaIntegrationPlugin);
#endif
#endif
extern void noui_connect();
// This is all you need to run all the tests
int main(int argc, char *argv[])
{
SetupEnvironment();
bool fInvalid = false;
// Don't remove this, it's needed to access
// QCoreApplication:: in the tests
QCoreApplication app(argc, argv);
app.setApplicationName("Adsplace-Qt-test");
SSL_library_init();
URITests test1;
if (QTest::qExec(&test1) != 0)
fInvalid = true;
#ifdef ENABLE_WALLET
PaymentServerTests test2;
if (QTest::qExec(&test2) != 0)
fInvalid = true;
#endif
return fInvalid;
}
|
///////////////////////////////////////////////////////////////
// Copyright Christopher Kormanyos 2002 - 2011.
// Copyright 2011 John Maddock. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_
//
// This work is based on an earlier work:
// "Algorithm 910: A Portable C++ Multiple-Precision System for Special-Function Calculations",
// in ACM TOMS, {VOL 37, ISSUE 4, (February 2011)} (C) ACM, 2011. http://doi.acm.org/10.1145/1916461.1916469
#ifdef _MSC_VER
# define _SCL_SECURE_NO_WARNINGS
#endif
#include <boost/detail/lightweight_test.hpp>
#include <boost/array.hpp>
#include "test.hpp"
#if !defined(TEST_MPF_50) && !defined(TEST_MPF) && !defined(TEST_BACKEND) && !defined(TEST_CPP_DEC_FLOAT) && !defined(TEST_MPFR) && !defined(TEST_MPFR_50) && !defined(TEST_MPFI_50) && !defined(TEST_FLOAT128)
# define TEST_MPF_50
# define TEST_MPFR_50
# define TEST_MPFI_50
# define TEST_BACKEND
# define TEST_CPP_DEC_FLOAT
# define TEST_FLOAT128
#ifdef _MSC_VER
#pragma message("CAUTION!!: No backend type specified so testing everything.... this will take some time!!")
#endif
#ifdef __GNUC__
#pragma warning "CAUTION!!: No backend type specified so testing everything.... this will take some time!!"
#endif
#endif
#if defined(TEST_MPF_50)
#include <boost/multiprecision/gmp.hpp>
#endif
#if defined(TEST_MPFR_50)
#include <boost/multiprecision/mpfr.hpp>
#endif
#if defined(TEST_MPFI_50)
#include <boost/multiprecision/mpfi.hpp>
#endif
#ifdef TEST_BACKEND
#include <boost/multiprecision/concepts/mp_number_archetypes.hpp>
#endif
#ifdef TEST_CPP_DEC_FLOAT
#include <boost/multiprecision/cpp_dec_float.hpp>
#endif
#ifdef TEST_FLOAT128
#include <boost/multiprecision/float128.hpp>
#endif
template <class T>
void test()
{
std::cout << "Testing type: " << typeid(T).name() << std::endl;
static const boost::array<const char*, 51u> data =
{{
"0.33937643772780730649735035088117439284797964277099188367427256402032493952288848579083622213428182842627923924487560393743204013166230906610274533504451302298480596207257724471359936027198954417317381228420986152562253196896619001418292769103034561794393400788635610424360775622370491149170501475453034747306600304507650361914904138327962144190354572359428689767990353722392457982930942617983634601752",
"5.9746833446871871874685235810964396457491766537010251792063372398172074828151074989468673672535421045923659313715467371148678693662985453590831122722616951299822923837410906027605763677066945998696776562438704017846907508677186762421899376364636371743116519071733413775650991880222096045615827530741679305666041641331859757012015389431793705875600863391408448065773828563483223117178640044499399723744",
"383.32826140718915582837967448860824902040431804683461630967288341613741467095168380744762629948507973653220772087887989292128183196493611623766470283358542341824134250511562240487252437079958429586344329111208041197054162309164204144237855212391474938076935722386012246677813568519769393617755607372817372398764101401294149353978426057544810680225593132066193858006901125069663362991172745649465725272",
"180470.88334757918167934673473709881208559849920820465419382707969109187448281704429118605409224039018180517847684905660962429505828088398660499158213746722168139372781263849989865384042531846290813274318773753295025006473736660333640052386121946183935053629928496714560749082485275242374067168149435272169334475060524974384307351757201698786200303374802146857634893509516262245925287553380389076772488",
"6.2781497954189513207977998975338639259302378413658035459603622432839117790845430762753614618299222131433987986511235061633658516824123179660244932375967566163895461895213509376427850290780942550513918615228886566287592461085762554208269169000672149592375451149457664991726947185145469263932975075681560662428417041932848357447220175607720561540370653825438750168143857523868718856189519864027430308779e8",
"1.6137831147508521132232267071463247985636947830692243664921522457394294988129666666745854084767325882717254318322908201512400243137564101564235450151960593110176457803621675408660678871179456625850704076654060872094257085919134755925910859520026379969099492921728083639989029675808598278170215911879751320574053132699172028082102336989338403081942130794464992491330850160862146024982135931859868176809e13",
"3.065121004865094886953119667134247741359538615435533822684602797608029400610449009335078883525336625519599034934744634528257351124420564267197918749480389135525897886434344884370577475363556341414615470556433033106705280531443046669163916446454890662947185057748542735928453570069226294801221403438864013368364219717148075652123561545773399076318560221173734215703610924057158101731263882232550297741e18",
"4.3016893602106215864771434464025735547192956887049374680649926707919814241961779812200280749930256501997849507695395125441756421661413154730888574483309057229943886742437071251707738990393977398403536175642762242808350076543018009682725019125106175929448866428526984370017465117236484653179596869643117790492866002064306593104169410537341890174831622159415936125041593936992634719906123727028419057537e24",
"4.4608685929681360001024935791890661655506049487122331222491789265929503651540405036031990380918459104583255735620288691363060079360758406339887417913286769718423759522832754263499878135869223253358698774066131403822428286318351390574838877307934317251880890827523325360658275060099119902102399714992704146743744108968362755624325107486994088414126705458507082103811086372240878942983212662081104875997e31",
"3.4181315955816806472569357441100390029536003312981931954091744304974491527743599822230006760631204302243855667216955365986192324833652299336285826148922073950348547795494738267861098328516497599288314822606511466743212319770180141969147554023326883651348621187276823849839283609071336923316655316828855943689100621619083822127788284160652232283630351386798636794979234576432977468152969056493038423561e39",
"1.9352946282727908101414530212785249763640776919052480158881659190625166733449770912626442628329346416132299268886589920690636914906717492301836773331460154604580407945460359957380672599434023197425489039882987443681919056322268437224184910074985583829184831034293865504101338027818555871946080687710035062238789949143319550108801094190098446234092310048150477274502060870736716324117412815209633124145e48",
"8.0964449511890098565841496436016431651692307764702784234901741408135381374668439020986470675941110923614446905696410406066640351065195237123718468440597743167713019447544827353458477844468727834630038609140168354634397475741840053079910210908251252223665806813131724262334693137656218010287981601097259534068903471812189212459231851835393208367369054618963204727992168556204168791513644815218096463093e57",
"2.5028257092625174549175008952222569141816383637904981644379473858250736896174216539673733521627607209322019413420937570273676341726636306931304501320694017061891400181233108050930610234076339285157392030024769366663118692571469493256243952018705693924919037621083041696227375589264811876761430035546270312014570431860268644276406457398485042029556392894799022733858611415899182421526634018060028309384e68",
"5.7168370213792649967466315312864179662895170192695050789061362839510836418124645968032989149068311018994324517420345278843446068634292140996241291031113395887824145000873531937856827299256489358571593850210528248202703396455363364446996158929674989959483681393263782486430231288067231095140919741928337466492665857902913114664767450432510739209971738097074002526312039248809036478310948111740897528204e79",
"9.6487261169670031207955841899729386502708125098394777808615183927342163909284025992243201020435915122698808649711566042372911206942311277943247994427354130507790526857797833309691667375441761513692598664419973302444660838882173718713387158013802112502169254860961105745895124415352002289485483908952674562396552790441656755711709645516914188860464353624992313010889765422981069429049436524222321550149e91",
"1.2032977660238608232537005158851668311089986235965463249220377778638489972355974848209035082333822309902237165042868213438627625544096344578102199846440476859557339736747791529782018329078191477783605471526120462726353510147373798347292650122930289404816748193194907382572774906323766342758092979989633448828636445074016110331338699464788279882402189027828261039788079556739180915346692779065476431369e105",
"1.1088306081278288754492401130897590262404571813281460605683836139669281218442501421935533170636990866165181664561596333701204545493730707210930818738817252706131805203538144119244917164949716209095542194899833868499263375700313934257155600824601418042452138211549248837967344874095248283887929145923103153332810091693393888809653081365270947112297406471162377655179657693898463736926911943490619163092e119",
"7.5499880591625965663868042832675300901799245732418501707646792135512053284835138294796976048691668315442427834949618514094329533376442442492757936744857569785450769927581802961191319878260712808001736830227501518832554201816224207300614310712430470538022948957433004823102746037654096845266998518623332118892916505020627868405618942429551700207476696585635930562973459491424179233918050890206232214765e133",
"3.798536358006797624025033016530070695826982685154937173246022092345982280900791849578041210970037835270398289956157015064696375146357207576854029748413680946201805214954504282866534528711715039215051307866373994662368105368505465037259587291440042344663580680646178313958620437868058550744621854406871361710599007951099013146571208384054250556080476992977623024059268095813712424244902009427293468485e149",
"1.4121319341572581270215359848706630542776633675711529687593487346259283960708095601494823112486631023721124235640943167173029348028743563902367757599140008654691320430919753414890689949599421028277624880392344132646738394546195638261279687543208503932172926275294218429086816560213399180179494004109164546844899632385177835442946174653663068675983237955855108059376913611877439522917217336109804190399e166",
"3.8790307719997974510664339744260233373881096199933152202662556556779783775106563986911859526413282055258612522499767709123313205863879946518297779104337686883587019222829967005608205535314284003183828513113021722123872387036435113517356676447376715595408179555267871947671679098986651665719279348025058713817796876795915844151719103197410787508530261619841035613531487094949084263218956635085585632719e183",
"7.8733605373835840397434523264038598405672829925651165847065668324385430746087633348848905637835428739401439679896923081980364912472282573695612463537585283007941057172128277340402716645674443632827653710173742423648839359547777694778576675604645880219833375227941998426325886558435214355022240854563558864080627758653439429917072753785194675103766900514602432580639079224631229479607396935864512990879e201",
"1.1808262995038900942517891457926200063018079695348469762725520377876370005771518954251015338402886097689762895044056273430051256244413916763438966705458118354189107806216991150264176024521937328179762640422127608560103802431672144866013216405157197709788484197720057702118788168789816074560208078260433548283881535909071116553897893659656781376448427981358955547508806938614921874867135186509274509121e221",
"1.3085817499987842655130548827168955655838432140245228169691892267707778790498773914833199368916114043966197329562444577848635313938483757629541576533880917215885485474416704968999200090496252044959849927443732134176975867869986011315975625868009065373046224716063168977788103866885720471095547385342868632018951910603936835789387464412366605713487321530237148912677199033012777178113821791621549557963e241",
"1.0715308148006899161903881353829644069217121138682658034413051575604561649576261428568888094218620444635013220705511245290719605273316790249367622122178650529000528086055415007045458486410501636380119413632657994999412652188430063128470336817401482172580366374079331295129200936246446347832380606353293858222758687479612927181530236387227215663399410099251455256898414199913458340065553949424990477448e262",
"6.483319651006309502237640505955012384293570932602353784849377890534620180296272226076424490097577093511886503973590409376477611667988893542117173598716788837179265384921201772013611631892729250835822804494742316330406688475091973437669111728949960922002370308207819760146543720499389938855072810566961589413895110830251224194598788696990065693705615156654866578134664648091752361824241438921952031149e283",
"2.8985391304542768293172709775230767981477721528885408305355619530690119426207269563049756824939397157221877775531212262059946098575425050827283362457005503261796116156917077778477251551070762614233325253060283603452216492681531839154649232080928787066338399915850327381614672456102374248950210248266796072457623370079195574322846594267768883120374288952014885152055438195794090975578878933873824774214e306",
"9.57524433627083921372674145950563946532138741951042299439035158875449060589509856903496678820625880407684156184675763001790613289835869844325821965070261880894138207436003366195024403902162467929095155787852409710735775347490909311196315332711680552044467458169615366116872469435840608534489425322247278926672059747911266981024366989976214521515026692183039600169984107883592297128416659318858313127e329",
"2.3372734503362369375381009524197350830316472034721759761797536237738670471009423543542251572488229045699598160834162677357730620072441755506075897500940629883044875771104686291523502165266242030847074909362622098365719455332359938746138629161304717385265309980898079489959955157644566232440805137701071311495653330606071611331941246434767948905863368638163788562679785940566685500460815077065003612487e354",
"4.2155879126937199240969909448599186868484717887298729605150033299123534992857332918168135230843738695925698383815575417820480732378749635394939513838137876524333991937836847074991505476867647762082587225838063325020413513077128321581439429001485977751765798011101092072613053687422983352140468569171564773941232256057064161142341661775359191159220450305300322654184921617310753474842253496677498824723e379",
"5.6181811613375701248970224378256740494692066242437602652469740512738297599235414593999616891945156186827736326184687322137498447792007445397397290336810468925670064733464757082986791232916898141597610692740388799796632396708149027243436859752526805112778790645096555770227809873695589969805678601106157556386974221647669590827712353133603091803570183764883405340587430017053183637835511899658145649708e405",
"5.532511069282205350923830187073466127274584467195468607886763750877294392993663821432158885753563495238131394373865428654052604326264330104646257659760161386620716716703631608643312613245804625511813964275109451513736558514977338129201153666764317441936156609643185133981728847167450887861106642311329612564652645663234240748195490808151911497393974690166034839217817023634217121406163178148652748479e432",
"4.0256666306761331240653217136731531623017017695713942917027851762705346357330788586411431378972009980532310757689380174461664677676028378924382554201434975574729861177781849023768222381429947872325368088023224591306630434887529215459580760863075907686248521168590309636468448648513752893851767315693469638980874648457114335557202115472595647478331668869318302753802858726588719006447471192697846325955e460",
"2.1644237346681663424601781769159797919834245365230735589058796985974745594485988855971413936820871935714602237643458356241187573307428309041919648027960168541647193436225977495680484218384107820095589356463058222584008532497069179993678533431131233629312850771528970443634604290143149079209513868130585713006080733488491160321145735562062411305931183571279530201672366980412430529846635995189699318073e489",
"8.5987580981195983662047247216936066485731760315371506386077056691409579856014763032619539539935299716110411688793466397984311640631361934500807639285587334983206556915704635831992012926186843826981296831658998834850783404713050829093753126189556625095994621605300047199962332098857236359801681157419606676412198783092816364336047306243999363335004760439115355072350465422891365411868472688286678516314e518",
"2.5241673163187127276134610716954724162270290228773641734420864618245211926017624829840685860130579257772126398622324109858115624706486522844752512951837805396709793171502497523431473021570806024043139443284538862368635312799539108264084028032731295487282188616820261689634926427135060887942797635147693849950058672753458576476491733064455826768562371858057444914175251596852571637211466017938478085247e549",
"5.475067911823387661325942057081957044927796274441278042805014835144678321092623034147031518807063234976073102574257079170283458172046752719724152941316842521196069804425876507927418423409523739261726681120662097159943049401039490818332686968135012747332468921142470970507219403290422458185430415836291605355383658657658638112408092789126678938878667507151950931633694006471359998448912249374833586727e580",
"8.7750549689950256776639468724574158629603320014390275681028674550826357080136422399476213432791376656222763800628593282303459051561266270006921840049305819767639184391149913915312831894296821356222752594264134130151457242713539248421883837353442181724530706933220158507240760325182068001553294949268596178418634164323874971937997072367419479635154591248667559627811893588163238012665671798461211917208e612",
"1.0392000158337773273751156576416024664653679689973856373456304843339302977923254238376497044027728158058903302390909588333829463843362779584402914847447592731182614369968957680281500946805571235013941407979569788567794900810257154433592958167545186687137810101848000107335074486050959387974516414654638879740966175786016492797845169374594168995878543584318334800124941205910589727264397237600733483158e646",
"9.0936326753636727240574546678839170665019169110943878894933093211555976995701468041449327370073681898690638466136204694745206283652338526673125958055131610409923286526192661778126811265116493171283319361595267283588121098349703951929669281966675596890266483864217591555707552765565756842701056144290075867893520379419521775913047964393758374891516340929062076304350159966063972713118995033247759001609e679",
"5.8798281636930489964162009429009257867906792508058801627042121953599912951265315933723440185825519080102988056836911095299854840387008575164090793635997912930561430335216151607097220208013034399895832350235280120270626904356196935166701773768680311063264380891331021514518757839220818506905997847228783439015252768055166165941582030353226255576433910936297965207260585437762430381969160714956727596198e714",
"2.8091881292911108404345975896815558958477835260737794579417284512413473388968057587088555041266297486841923628702282019643659456724373332519583025947015025975126598748630623031951723754960589046233996595466021913942587558326660593063197905288573353559106884645285531497626940379800500474282446929237914568534665868703742731713632349090897884403966643055728471509474896855575286123275564417626861566706e750",
"9.917129372597671132067673866739246238179742417231064062960232866725337575281938597212073697168000155027158148165861617400080837699968785505107579831803685516054837447325150388867488754170677228096524224392410232206238263933144338637103531441623303187445874039234973380151391274490746625993568552049954630793219419614845431626975962881182662815760423226111647056071831411664335144052772436215105801395e786",
"2.5869027163543111121878679987081647715187872826677398475096738640583659800068967379551376322170347537454918190603891312949716382621902484616361664158953484778255247083652726854621059785392022847887382779010079407502679229021085320675903109573769331277413372272363218896397965662581357886739691376204316908974081821980432178065394228926767529685562155837452626029223937027004015040825450642409597700449e824",
"4.9861251931207080923785686798881789193813879610842675205361210155894774686328710893906543682447029206928934967525495260314937837003448878215156341411477636831113484416124080974502217578408248150338565305116223944900839866528622960352723938548713319425798453345402992146078868053263606234074443024155243450623634720912438841022969909473424559262711669905282193529250216454066716533180418518228387188393e862",
"7.1012569014339068241101751233953234216522840280342406520909288232012799547871960723719836516359548198842749536961644100550279020276709043358260853581760590386456213180291689322352732545965831405519844109680619067101311180959399339922706596098526969148981173519865139508665631317310424178378833370605922449094745510812618563813537347841030916512147874232760564378443782164868016244561788356251308121716e901",
"7.4730215360486642135431754747074885377840195683583018254892502245011973712084221116813364423492802080799768174534590613188275471080608467087354983850284805514875889145266688973752185071777341375422809910165581997555433091939959406569831183459872344778707098094941193489061532160249775856426569696127193453339548371679229676272663084782830276508737129506676031759345288056484158647796152349867328841634e941",
"5.8109375364209112227579654658730977030869454388607076903639465992296616832002964138000947668837140543325908222688655359602408511410663722770167244801973012245657865182739637159804595049180263175014778215232564251739259624759589953677661356104554831551073263668188283861123521688445132164147762321111597028523130093864153999974376790494383016372210442340324038686843345053322425194077414241243050491297e982",
"3.33875955701899627718146291382268063073604182131575843695486667154496711979350813988644889979275310892951143249901398447859083674739840084454465850475774696325142148671937407108540250845900941142800157345665761403930889797424808979569550325271558518404559007551625637761142662107757913763221912282957681784053564387104062317729788737215450574233690655931888608424916152893688106181220341997128198692e1024",
"1.4174672877823334709610117319768830739080734407353905145632612088824955720198734996604261250019291955883620333545750761619015467840567122066622229379056280064206319780047687015558007624774062399477328822231085767309831266032616053065858739373818651687128093335640388513396191118537181280334430292439188737524362269789272308905723812818882228503013875816702686587035844437102478263525616196832018321602e1067",
"4.4466189016791091516801723880812533528438597080549410911235655611382010503145789286158745555771483577943662768773465284793798720178177605712848440200402906836390133865748188969184005230383247111166918721449908133920663776952786683837038180436264738937354101153867171804315769471050303182129269442292354388037298125177941217926845803005587166270803697433886463469168814941555804311717400657004050157245e1110",
}};
T eg = static_cast<T>("5.77215664901532860606512090082402431042159335939923598805767234884867726777664670936947063291746749514631447249807082480960504014486542836224173997644923536253500333742937337737673942792595258247094916008735203948165670853233151776611528621199501507984793745085705740029921354786146694029604325421519e-1");
unsigned max_err = 0;
for(unsigned k = 0; k < data.size(); k++)
{
const T x = eg + k;
T val = boost::multiprecision::sinh(x * x);
T e = relative_error(val, T(data[k]));
unsigned err = e.template convert_to<unsigned>();
if(err > max_err)
max_err = err;
val = boost::multiprecision::sinh(-x * x);
e = relative_error(val, T(-T(data[k])));
err = e.template convert_to<unsigned>();
if(err > max_err)
max_err = err;
}
boost::array<const char*, 50> small_values =
{{
"8.223167319358299807036616344469138485821440027829633696917375433348917938654659351596020080036406671343718039863220496616e-01",
"2.526123168081683079141251505420579055197542874276608074880949653019810769068593790606537020961198741487692473633089323967e-01",
"8.342981744595282037256218647969712476322487890550784823763249893556153270975172951404094950587944959561849750490537201329e-02",
"2.778135016068299789938671680845480653984976507019542653788637161116587306168290886761259072846829249121589698206609261524e-02",
"9.259391565199916442789400306996794489540862711193761818262415211084389468754315525525896238827358889826875006042447587516e-03",
"3.086424653287772358219607529932097884435043040527155440187640095572710676452654803730003577747633690318001961509535020849e-03",
"1.028806765851002064810061084014826478832745077469708149635730407866217436751337520417458090265791086156438275231514030381e-03",
"3.429355348425226988441198390119109217716503769838753365112550442738406326637684639052252898314646892490045395290022292013e-04",
"1.143118429558603374406653541544292690548937361618336125287018361332072426474632105217297150810234138626767253281422813482e-04",
"3.810394757818873406266877296641684693312194735341898368873067089928172619067423751257049691985638480762032673977695116880e-05",
"1.270131585666421832817527834137477593266387525701388601975733237436369505733715799310429349744168792375082834509467436523e-05",
"4.233771952120219947940459634636576539101577724347428305072378100562649548884420218224692461748739725090626754420296122389e-06",
"1.411257317369659013704209000288436132710449162963127340562961271337242582661013580874165903770246169179192268836124421074e-06",
"4.704191057897475365825409916786898392364235667906752767514580467152163619657508910797742266406961516358439252434955007668e-07",
"1.568063685965773714045928492719360014894368531987759414833778466374819836545157375950693756664550256136222396871173634254e-07",
"5.226878953219226673524993193392503058475862017726848548717100658392470633650387274004511940515056405069137033934323251644e-08",
"1.742292984406408185991240874995689487745140228031202510923711784729440494088066989430128101759261047316736074663327672115e-08",
"5.807643281354693692124967044009687283114597355717062156493618245876910131607338183944830908381903728560328284173507220743e-09",
"1.935881093784897887701686451485601671131342930785061493703969418728524594573922282309665275558709040519461560600768780392e-09",
"6.452936979282992955422916851920785543106383715381924626175995859924351552325880931187614903984801793287071578640505194508e-10",
"2.150978993094330985008279519046512957825521218238790792201835497215534851989750722105234826300738623838446309250309905466e-10",
"7.169929976981103283311786261663531258230547972690500493476881079295129579131280734024784107219045379345460886663104148486e-11",
"2.389976658993701094435441884684454421835327948893136184573938864819002944442339456827931472237274353903634036758669394620e-11",
"7.966588863312336981450798799860506345287566898810744342680146925029151178981033890759916168189916177504592939240995619757e-12",
"2.655529621104112327150241298135440075805848488054800577703768668100658036999584228451100239039042920681377381394421710121e-12",
"8.851765403680374423834128412864530361591097252230621965426275532533242581680245794741067906285298655116802944992368126680e-13",
"2.950588467893458141278042461784956914687338675140497707333871358819185395356569206661450997145748756956497959702280685427e-13",
"9.835294892978193804260141412430145318398649753331401112621871794012928366988233744354238387090649589382104704221708773516e-14",
"3.278431630992731268086713799445120869198593899364655036314007566906378666339665297288092596796135684816883503781385164489e-14",
"1.092810543664243756028904599641030626636532928735904320784337625844108091213506619051042206148385975354700234586478575025e-14",
"3.642701812214145853429681998738987398752764686754626492252324567456938623579239392678142797020213493844816454129960310753e-15",
"1.214233937404715284476560666243942169089106312534317920490462975351305354471020532764015606315872085933262687299655265697e-15",
"4.047446458015717614921868887478923169619805517194433471908835726595116905187672132801369948377551282604828733616045843751e-16",
"1.349148819338572538307289629159608313551890152969010184597042496758528297346351553643241208769191557898925543369605617734e-16",
"4.497162731128575127690965430532015584807024576774799020494128293451281927637267192489558050090835454302448780391749096414e-17",
"1.499054243709525042563655143510671412452985626833998379862387948592418229228808284088934491020852037924756758483008288052e-17",
"4.996847479031750141878850478368904541825005460277179305602161748681654262243578435201096986093377131577325573917436618470e-18",
"1.665615826343916713959616826122968174447164290616980189746184851537351248309665330601503343215376981550822569162631313560e-18",
"5.552052754479722379865389420409893912541965834349657578615232567585047309856390957625702896178052275806406957076143469634e-19",
"1.850684251493240793288463140136631304096139902769381795814754672989850701401641374814254071564872119933498619234778448524e-19",
"6.168947504977469310961543800455437680289164351695283493312025632359317744715643192414807145394613572397590534364339391526e-20",
"2.056315834992489770320514600151812560095228784236601072113743484455321300338926430301421880927367590178440922006775473367e-20",
"6.854386116641632567735048667172708533650333231531203539518552950777817440179277823487619201513258000884052637516041835420e-21",
"2.284795372213877522578349555724236177883428507451482660054557452824460619777642844796449091646418601791047308814504431261e-21",
"7.615984574046258408594498519080787259611422468149787192854095139994568043598766360557598146279482678180281335390895949036e-22",
"2.538661524682086136198166173026929086537140604567639372655275057673980680372673609490963070062819520295998328327889923353e-22",
"8.462205082273620453993887243423096955123801934429554813185698344472203995997708879527322555715697860578416576045982358004e-23",
"2.820735027424540151331295747807698985041267308484077168753311108116374235508697904826049959781116012127075951788533527897e-23",
"9.402450091415133837770985826025663283470891027171945709804152456669015193736201020401750153196590359525341207466344738924e-24",
"3.134150030471711279256995275341887761156963675682933328476437810109959425395050019306074135780459168092270327572635795510e-24",
}};
max_err = 0;
T v = 0.75;
for(unsigned k = 0; k < small_values.size(); ++k)
{
T val = boost::multiprecision::sinh(v);
T e = relative_error(val, T(small_values[k]));
unsigned err = e.template convert_to<unsigned>();
if(err > max_err)
{
max_err = err;
}
val = boost::multiprecision::sinh(-v);
e = relative_error(val, T(-T(small_values[k])));
err = e.template convert_to<unsigned>();
if(err > max_err)
{
max_err = err;
}
v /= 3;
}
std::cout << "Max error was: " << max_err << std::endl;
BOOST_TEST(max_err < 2000);
}
int main()
{
#ifdef TEST_BACKEND
test<boost::multiprecision::number<boost::multiprecision::concepts::number_backend_float_architype> >();
#endif
#ifdef TEST_MPF_50
test<boost::multiprecision::mpf_float_50>();
test<boost::multiprecision::mpf_float_100>();
#endif
#ifdef TEST_MPFR_50
test<boost::multiprecision::mpfr_float_50>();
test<boost::multiprecision::mpfr_float_100>();
#endif
#ifdef TEST_MPFI_50
test<boost::multiprecision::mpfi_float_50>();
test<boost::multiprecision::mpfi_float_100>();
#endif
#ifdef TEST_CPP_DEC_FLOAT
test<boost::multiprecision::cpp_dec_float_50>();
test<boost::multiprecision::cpp_dec_float_100>();
#ifndef SLOW_COMPLER
// Some "peculiar" digit counts which stress our code:
test<boost::multiprecision::number<boost::multiprecision::cpp_dec_float<65> > >();
test<boost::multiprecision::number<boost::multiprecision::cpp_dec_float<64> > >();
test<boost::multiprecision::number<boost::multiprecision::cpp_dec_float<63> > >();
test<boost::multiprecision::number<boost::multiprecision::cpp_dec_float<62> > >();
test<boost::multiprecision::number<boost::multiprecision::cpp_dec_float<61, long long> > >();
test<boost::multiprecision::number<boost::multiprecision::cpp_dec_float<60, long long> > >();
test<boost::multiprecision::number<boost::multiprecision::cpp_dec_float<59, long long, std::allocator<void> > > >();
test<boost::multiprecision::number<boost::multiprecision::cpp_dec_float<58, long long, std::allocator<void> > > >();
// Check low multiprecision digit counts.
test<boost::multiprecision::number<boost::multiprecision::cpp_dec_float<9> > >();
test<boost::multiprecision::number<boost::multiprecision::cpp_dec_float<18> > >();
#endif
#endif
#ifdef TEST_FLOAT128
test<boost::multiprecision::float128>();
#endif
return boost::report_errors();
}
|
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2017 ArangoDB GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Christoph Uhde
/// @author Ewout Prangsma
/// @author Simon Grätzer
////////////////////////////////////////////////////////////////////////////////
#include <fuerte/fuerte.h>
#include <fuerte/helper.h>
#include <velocypack/Builder.h>
#include <velocypack/velocypack-aliases.h>
#include "ConnectionTest.h"
namespace fu = ::arangodb::fuerte;
TEST_P(ConnectionTestF, ApiVersionSync) {
for (size_t rep = 0; rep < repeat(); rep++) {
auto request = fu::createRequest(fu::RestVerb::Get, "/_api/version");
auto result = _connection->sendRequest(std::move(request));
ASSERT_EQ(result->statusCode(), fu::StatusOK);
auto slice = result->slices().front();
auto version = slice.get("version").copyString();
auto server = slice.get("server").copyString();
ASSERT_EQ(server, "arango");
ASSERT_EQ(version[0], _major_arango_version);
}
}
TEST_P(ConnectionTestF, ApiVersionASync) {
fu::WaitGroup wg;
auto cb = [&](fu::Error error, std::unique_ptr<fu::Request> req, std::unique_ptr<fu::Response> res) {
fu::WaitGroupDone done(wg);
if (error != fu::Error::NoError) {
ASSERT_TRUE(false) << fu::to_string(error);
} else {
ASSERT_EQ(res->statusCode(), fu::StatusOK);
auto slice = res->slices().front();
auto version = slice.get("version").copyString();
auto server = slice.get("server").copyString();
ASSERT_EQ(server, "arango");
ASSERT_EQ(version[0], _major_arango_version);
}
};
for (size_t rep = 0; rep < repeat(); rep++) {
auto request = fu::createRequest(fu::RestVerb::Get, "/_api/version");
wg.add();
_connection->sendRequest(std::move(request), cb);
if (wg.counter() >= 32) {
wg.wait();
}
}
wg.wait();
}
TEST_P(ConnectionTestF, SimpleCursorSync){
auto request = fu::createRequest(fu::RestVerb::Post, "/_api/cursor");
VPackBuilder builder;
builder.openObject();
builder.add("query", VPackValue("FOR x IN 1..5 RETURN x"));
builder.close();
request->addVPack(builder.slice());
auto response = _connection->sendRequest(std::move(request));
ASSERT_EQ(response->statusCode(), fu::StatusCreated);
auto slice = response->slices().front();
ASSERT_TRUE(slice.isObject());
auto result = slice.get("result");
ASSERT_TRUE(result.isArray());
ASSERT_TRUE(result.length() == 5);
}
TEST_P(ConnectionTestF, CreateDocumentSync){
dropCollection("test");
createCollection("test");
auto request = fu::createRequest(fu::RestVerb::Post, "/_api/document/test");
request->addVPack(VPackSlice::emptyObjectSlice());
auto response = _connection->sendRequest(std::move(request));
ASSERT_EQ(response->statusCode(), fu::StatusAccepted);
auto slice = response->slices().front();
ASSERT_TRUE(slice.get("_id").isString());
ASSERT_TRUE(slice.get("_key").isString());
ASSERT_TRUE(slice.get("_rev").isString());
dropCollection("test");
}
TEST_P(ConnectionTestF, ShortAndLongASync){
fu::WaitGroup wg;
fu::RequestCallback cb = [&](fu::Error error, std::unique_ptr<fu::Request> req, std::unique_ptr<fu::Response> res) {
fu::WaitGroupDone done(wg);
if (error != fu::Error::NoError) {
ASSERT_TRUE(false) << fu::to_string(error);
} else {
ASSERT_EQ(res->statusCode(), fu::StatusCreated);
auto slice = res->slices().front();
ASSERT_TRUE(slice.isObject());
ASSERT_TRUE(slice.get("code").isInteger());
//std::cout << "messageID: " << req->messageID << " " << slice.toJson() << std::endl;
}
};
auto requestShort = fu::createRequest(fu::RestVerb::Post, "/_api/cursor");
{
VPackBuilder builder;
builder.openObject();
builder.add("query", VPackValue("RETURN SLEEP(1)"));
builder.close();
requestShort->addVPack(builder.slice());
}
auto requestLong = fu::createRequest(fu::RestVerb::Post, "/_api/cursor");
{
VPackBuilder builder;
builder.openObject();
builder.add("query", VPackValue("RETURN SLEEP(2)"));
builder.close();
requestLong->addVPack(builder.slice());
}
wg.add();
_connection->sendRequest(std::move(requestLong), cb);
wg.add();
_connection->sendRequest(std::move(requestShort), cb);
wg.wait();
}
// threads parameter has no effect in this testsuite
static const ConnectionTestParams connectionTestBasicParams[] = {
{/*._protocol = */fu::ProtocolType::Http,/*._threads=*/1, /*._repeat=*/100},
{/*._protocol = */fu::ProtocolType::Http2,/*._threads=*/1, /*._repeat=*/100},
{/*._protocol = */fu::ProtocolType::Vst,/*._threads=*/1, /*._repeat=*/100},
{/*._protocol = */fu::ProtocolType::Http,/*._threads=*/1, /*._repeat=*/2500},
{/*._protocol = */fu::ProtocolType::Http2,/*._threads=*/1, /*._repeat=*/2500},
{/*._protocol = */fu::ProtocolType::Vst,/*._threads=*/1, /*._repeat=*/2500}
};
INSTANTIATE_TEST_CASE_P(BasicConnectionTests, ConnectionTestF,
::testing::ValuesIn(connectionTestBasicParams));
|
//https://en.wikipedia.org/wiki/Quicksort
#include <iostream>
using namespace std;
void swap(int &x,int &y){
int temp=x;
x=y;
y=temp;
}
int partition(int A[], int lo, int hi){
int i,j,p=A[lo];
for(i=lo,j=hi; i<j;){
for(; A[i]<p; i++);
for(; p<A[j]; j--);
swap(A[i],A[j]);
}return j;
}
void quicksort(int A[], int lo, int hi){
if(lo<hi){
int p=partition(A,lo,hi);
quicksort(A,lo,p);
quicksort(A,p+1,hi);
}
}
int main() {
int A[]={2,4,3,8,1,6,5,7,9,0};
quicksort(A,0,9);
for(int i=0;i<10;i++) cout<<A[i];
}
|
#pragma once
/// <summary>
/// Simple storage class that keeps the outlier score, core distance, and id (index) for a single point.
/// OutlierScores are sorted in ascending order by outlier score, with core distances used to break
/// outlier score ties, and ids used to break core distance ties.
/// </summary>
class outlierScore
{
private:
double coreDistance;
public:
double score;
int id;
/// <summary>
/// Creates a new OutlierScore for a given point.
/// </summary>
/// <param name="score">The outlier score of the point</param>
/// <param name="coreDistance">The point's core distance</param>
/// <param name="id">The id (index) of the point</param>
outlierScore(double score, double coreDistance, int id);
outlierScore();
/// <summary>
/// Method Overridden to compare two objects.
/// </summary>
bool operator<(const outlierScore& other) const;
};
|
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/delegates/gpu/cl/kernels/mean_stddev_normalization.h"
#include <string>
#include "tensorflow/lite/delegates/gpu/cl/cl_program.h"
#include "tensorflow/lite/delegates/gpu/cl/device_info.h"
#include "tensorflow/lite/delegates/gpu/cl/kernels/util.h"
#include "tensorflow/lite/delegates/gpu/cl/kernels/work_group_picking.h"
#include "tensorflow/lite/delegates/gpu/cl/precision.h"
namespace tflite {
namespace gpu {
namespace cl {
namespace {
std::string GetVectorReduceCode() {
return R"(static inline float reduce_vector(float4 v) {
return dot(v, (float4)(1.0f));
})";
}
std::string GetReduceCode() {
// If it is supported, use the built-in work_group_reduce_add function.
// Otherwise, implement a reduction using __local memory. Note this only works
// with power-of-two work group sizes.
return R"(
#if (__OPENCL_C_VERSION__ >= 200) && (__OPENCL_C_VERSION__ < 300) && \
!defined(__opencl_c_work_group_collective_functions)
#define __opencl_c_work_group_collective_functions 1
#endif
#ifdef __opencl_c_work_group_collective_functions
#define local_reduce(item, tmp) work_group_reduce_add(item)
#else // !defined(__opencl_c_work_group_collective_functions)
static inline float local_reduce(float item, __local float* tmp) {
const int local_id = get_local_id(0);
tmp[local_id] = item;
barrier(CLK_LOCAL_MEM_FENCE);
// The number of items still need to be summed
int reduction_size = get_local_size(0);
while (reduction_size > 1) {
// Reduction step: add upper half of the still-to-be-summed vector to the
// lower half, while taking care of odd sizes and rounding. E.g.:
// Number of items still to be summed before: 5
// Local memory before: [a, b, c, d, e];
// Local memory after: [a+d, b+e, c, d, e];
// Threads doing work: id < 2 = floor(5/2)
// Offset to the added items: 3 = ceil(5/2)
// Number of items still to be summed after: 3 = ceil(5/2)
const int active_thread_limit = reduction_size / 2;
const int offset = (reduction_size + 1) / 2;
if (local_id < active_thread_limit) {
tmp[local_id] += tmp[local_id + offset];
}
barrier(CLK_LOCAL_MEM_FENCE);
reduction_size = offset;
}
return tmp[0];
}
#endif // defined(__opencl_c_work_group_collective_functions)
)";
}
std::string GetFilterCode() {
return R"(
static inline float4 filter_outside_tensor(float4 x, int num_channels, int slice) {
return select(x, (float4)(0.0f), slice * 4 + (int4)(0, 1, 2, 3) >= num_channels);
}
)";
}
} // namespace
MeanStdDevNormalization::MeanStdDevNormalization(const OperationDef& definition,
const DeviceInfo& device_info,
const int tensor_slices)
: GPUOperation(definition) {
// The kernel code does not inherently need a fixed size, but in order to not
// hardcode the __local array's size for the reductions, we would need to pass
// that size to the kernel at runtime, and that is currently not supported.
// For now, fix workgroup size to the biggest supported by the device, but not
// larger than the number of tensor slices.
int desired_work_group_size =
std::min(tensor_slices, device_info.max_work_group_size_x);
if (device_info.IsMali() && desired_work_group_size > 64) {
// Don't use more than 64 work items per work group on ARM Mali. They
// implement local memory using the global memory, larger workgroups have
// severe performance penalty.
desired_work_group_size = 64;
}
work_group_size_.x = desired_work_group_size;
work_group_size_.y = 1; // Required
work_group_size_.z = 1; // Required
code_ = GetNormalizationCode();
if (device_info.cl_version >= OpenCLVersion::CL_3_0) {
compiler_options_.push_back(CompilerOptions::CL_3_0);
} else if (device_info.cl_version >= OpenCLVersion::CL_2_0) {
compiler_options_.push_back(CompilerOptions::CL_2_0);
}
}
std::string MeanStdDevNormalization::GetNormalizationCode() {
AddSrcTensor("src_tensor", definition_.src_tensors[0]);
AddDstTensor("dst_tensor", definition_.dst_tensors[0]);
std::string c = GetCommonDefines(definition_.precision);
c += GetVectorReduceCode();
c += GetReduceCode();
c += GetFilterCode();
c += "__attribute__((reqd_work_group_size(" +
std::to_string(work_group_size_.x) + ", 1, 1)))\n";
c += R"(__kernel void main_function($0) {
#ifndef __opencl_c_work_group_collective_functions
__local float tmp[)" +
std::to_string(work_group_size_.x) + R"(];
#endif
const int B = get_global_id(1);
// Calculate the total sum of the input tensor.
// First, get a local sum of input[local_id_x + N*local_size_x] for all N.
float4 private_sum4 = (float4)(0.0f);
for (int S = get_local_id(0); S < args.src_tensor.Slices(); S += get_local_size(0)) {
const float4 t = args.src_tensor.Read<float>(0, 0, S, B);
private_sum4 += filter_outside_tensor(t, args.src_tensor.Channels(), S);
}
// Reduce the vector to a single float and do a workgroup reduce.
const float private_sum = reduce_vector(private_sum4);
const float sum = local_reduce(private_sum, tmp);
// Calculate the mean
const float mean = sum / args.src_tensor.Channels();
// Calculate the squared sum of the difference from the mean.
float4 private_sum_diff_sq4 = (float4)(0.0f);
for (int S = get_local_id(0); S < args.src_tensor.Slices(); S += get_local_size(0)) {
const float4 t = args.src_tensor.Read<float>(0, 0, S, B);
const float4 diff = filter_outside_tensor(t - mean, args.src_tensor.Channels(), S);
// sum_diff_sq += diff²
private_sum_diff_sq4 = mad(diff, diff, private_sum_diff_sq4);
}
// Reduce
const float private_sum_diff_sq = reduce_vector(private_sum_diff_sq4);
const float sum_diff_sq = local_reduce(private_sum_diff_sq, tmp);
// Calculate 1/stddev (with the 'regulazing constant' as in tensor_utils.cc)
const float variance = sum_diff_sq / args.src_tensor.Channels();
const float stddev_inv = native_rsqrt(variance + 1.0e-8f);
// Calculate (t-mean)/stddev for each element
for (int S = get_local_id(0); S < args.src_tensor.Slices(); S += get_local_size(0)) {
const float4 t = args.src_tensor.Read<float>(0, 0, S, B);
FLT4 result = TO_FLT4((t - mean) * stddev_inv);
args.dst_tensor.Write(result, 0, 0, S, B);
}
})";
return c;
}
int3 MeanStdDevNormalization::GetGridSize() const {
// To avoid dealing with global reductions, we restrict the grid size to the
// work group size in the first dimension.
const int grid_x = work_group_size_.x;
const int grid_y = src_[0]->Batch();
const int grid_z = 1;
return int3(grid_x, grid_y, grid_z);
}
MeanStdDevNormalization CreateMeanStdDevNormalization(
const OperationDef& definition, const DeviceInfo& device_info,
const int tensor_slices) {
return MeanStdDevNormalization(definition, device_info, tensor_slices);
}
} // namespace cl
} // namespace gpu
} // namespace tflite
|
#include <components/PolygonalPrism.h>
#include <core/IndentWriter.h>
#include <core/Point2D.h>
#include <core/Polygon.h>
#include <iostream>
int main(int argc, char **argv)
{
IndentWriter writer;
Polygon<Point2D> base;
base.addPoint(Point2D(1.0, 2.0));
base.addPoint(Point2D(1.0, -2.0));
base.addPoint(Point2D(-1.0, -1.0));
base.addPoint(Point2D(-2.0, 1.0));
Component prism(PolygonalPrism(base, 5.0));
writer << prism;
std::cout << writer;
return 0;
}
|
// __BEGIN_LICENSE__
// Copyright (c) 2006-2013, United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration. All
// rights reserved.
//
// The NASA Vision Workbench is licensed under the Apache License,
// Version 2.0 (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// __END_LICENSE__
/// \file CameraRelation.cc
///
#include <vw/BundleAdjustment/CameraRelation.h>
#include <boost/foreach.hpp>
namespace vw {
namespace ba {
// Implementations for specific features
ControlMeasure
IPFeature::control_measure() const {
return ControlMeasure( m_ip.x, m_ip.y,
m_ip.scale, m_ip.scale,
m_camera_id );
}
ControlMeasure
JFeature::control_measure() const {
return ControlMeasure( m_location[0], m_location[1],
m_scale[0], m_scale[1],
m_camera_id );
}
std::ostream& operator<<( std::ostream& os, IPFeature const& feat ) {
os << "IPFeature( (" << feat.m_ip.x << "," << feat.m_ip.y << ")@"
<< feat.m_camera_id << " links "
<< feat.m_connections.size() << " )";
return os;
}
std::ostream& operator<<( std::ostream& os, JFeature const& feat ) {
os << "JFeature( " << feat.m_point_id << " " << feat.m_location
<< "@" << feat.m_camera_id << " links "
<< feat.m_connections.size() << " )";
return os;
}
// Camera Relation Network
template <class FeatureT>
void CameraRelationNetwork<FeatureT>::add_node( cnode const& node ) {
m_nodes.push_back( node );
}
template <class FeatureT>
void CameraRelationNetwork<FeatureT>::build_map() {
typedef boost::shared_ptr<FeatureT> f_ptr;
typedef boost::weak_ptr<FeatureT> w_ptr;
typedef typename std::list<f_ptr>::iterator list_it;
typedef typename std::list<f_ptr>::const_iterator list_cit;
typedef typename std::map<size_t,w_ptr>::const_iterator map_cit;
for ( size_t j = 0; j < m_nodes.size(); j++ ) {
// Building maps for all features
for ( list_it fiter = m_nodes[j].relations.begin();
fiter != m_nodes[j].relations.end(); fiter++ ) {
(**fiter).build_map();
}
// Finally building multimap
m_nodes[j].map.clear();
// Iterating through all features within this camera
for ( list_cit fiter = m_nodes[j].relations.begin();
fiter != m_nodes[j].relations.end(); fiter++ ) {
// Iterating through all features that our feature connects to
for ( map_cit miter = (**fiter).m_map.begin();
miter != (**fiter).m_map.end(); miter++ ) {
m_nodes[j].map.insert( std::make_pair( (*miter).first, *fiter ) );
}
} // end iterating through this camera's features
} // end iterating through cameras
}
template <class FeatureT>
void CameraRelationNetwork<FeatureT>::read_controlnetwork( ControlNetwork const& cnet ) {
typedef boost::shared_ptr<FeatureT> f_ptr;
typedef boost::weak_ptr<FeatureT> w_ptr;
m_nodes.clear();
for ( size_t cp_i = 0; cp_i < cnet.size(); cp_i++ ) {
std::vector<f_ptr> features_added;
// Building up features to be added and linking to camera nodes
BOOST_FOREACH( ControlMeasure const& cm, cnet[cp_i] ) {
// Seeing if a camera node exists for this measure
if ( cm.image_id() >= this->size() ) {
for ( size_t i = this->size();
i <= cm.image_id(); i++ ) {
this->add_node( CameraNode<FeatureT>( i, "" ) );
}
}
// Appending to list
features_added.push_back( f_ptr( new FeatureT(cm, cp_i) ) );
// Attaching to camera node
(*this)[cm.image_id()].relations.push_back( features_added.back() );
}
// Doubly Linking features together
typedef typename std::vector<f_ptr>::iterator fvi_ptr;
for ( fvi_ptr first = features_added.begin();
first < features_added.end() - 1; first++ ) {
for ( fvi_ptr second = first + 1;
second < features_added.end(); second++ ) {
(*first)->connection( w_ptr( *second ), false );
(*second)->connection( w_ptr( *first ), false );
}
}
} // end for through control points
// setting up maps
this->build_map();
}
template <class FeatureT>
void CameraRelationNetwork<FeatureT>::write_controlnetwork( ControlNetwork & cnet ) const {
if ( this->size() == 0 )
vw_throw( ArgumentErr() << "CameraRelation network is empty." );
cnet.clear();
// This process is destructive, making a copy of self.
CameraRelationNetwork<FeatureT> crn = (*this);
// On top of building the control network, we're also going filter
// out 'spiral' type errors. Features that managed to link to the
// image twice.
int spiral_error_count = 0;
{
TerminalProgressCallback progress("ba","Assembly: ");
progress.report_progress(0);
for ( size_t i = 0; i < crn.size() - 1; i++ ) {
progress.report_progress(float(i)/float(crn.size()-1));
typedef boost::weak_ptr<FeatureT> w_ptr;
typedef boost::shared_ptr<FeatureT> f_ptr;
typedef typename std::list<f_ptr>::iterator f_list_iter;
typedef typename std::list<w_ptr>::iterator w_list_iter;
// Iterating over matched relations inside a camera node and
// building control points for them.
for ( f_list_iter iter = crn[i].begin();
iter != crn[i].end(); iter++ ) {
// 1.) Building a listing of interest point for a control
// point
std::list<w_ptr> interestpts;
interestpts.push_back(*iter);
(*iter)->list_connections( interestpts );
ControlPoint cpoint( ControlPoint::TiePoint );
// 2.) Adding this location
cpoint.add_measure( (*iter)->control_measure() );
// 3.) Adding and Removing measures in all other locations
w_list_iter measure = interestpts.begin();
measure++;
for ( ; measure != interestpts.end(); measure++ ) {
crn[(*measure).lock()->m_camera_id].relations.remove((*measure).lock());
cpoint.add_measure( (*measure).lock()->control_measure() );
}
// 4.) Removing this location finally
iter = crn[i].relations.erase(iter);
iter--;
// 5.) Checking for spiral error
{
std::list<size_t> previous_camera;
bool match = false;
for ( w_list_iter interest = interestpts.begin();
interest != interestpts.end(); interest++ ) {
BOOST_FOREACH( size_t previous, previous_camera ) {
if ( previous == interest->lock()->m_camera_id ) {
match = true;
break;
}
}
previous_camera.push_back( (*interest).lock()->m_camera_id );
if ( match )
continue;
}
if ( match ) {
spiral_error_count++;
continue;
}
}
// 6.) Did you pass? Sweet you're in the gang!
// - CPoints with only a single measure are GCPs
if ( cpoint.size() > 0 )
cnet.add_control_point( cpoint );
} // end of iteration over relations
} // end of iteration over camera nodes
progress.report_finished();
if ( spiral_error_count != 0 )
vw_out(WarningMessage,"ba") << "\t"
<< spiral_error_count
<< " control points removed due to spiral errors.\n";
}
VW_ASSERT( cnet.size() != 0,
Aborted() << "Failed to load any points, Control Network empty\n" );
}
// Explicit template Instantiation
#define VW_INSTANTIATE_CAMERA_RELATION_TYPES(FEATURET) \
template class CameraRelationNetwork<FEATURET >; \
VW_INSTANTIATE_CAMERA_RELATION_TYPES(IPFeature)
VW_INSTANTIATE_CAMERA_RELATION_TYPES(JFeature)
}}
|
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wsign-compare"
#include <boost/test/unit_test.hpp>
#pragma GCC diagnostic pop
#include <boost/algorithm/string/predicate.hpp>
#include <fscio/testing/tester.hpp>
#include <fscio/chain/abi_serializer.hpp>
#include <payloadless/payloadless.wast.hpp>
#include <payloadless/payloadless.abi.hpp>
#include <Runtime/Runtime.h>
#include <fc/variant_object.hpp>
#include <fc/io/json.hpp>
#ifdef NON_VALIDATING_TEST
#define TESTER tester
#else
#define TESTER validating_tester
#endif
using namespace fscio;
using namespace fscio::chain;
using namespace fscio::testing;
using namespace fc;
class payloadless_tester : public TESTER {
};
BOOST_AUTO_TEST_SUITE(payloadless_tests)
BOOST_FIXTURE_TEST_CASE( test_doit, payloadless_tester ) {
create_accounts( {N(payloadless)} );
set_code( N(payloadless), payloadless_wast );
set_abi( N(payloadless), payloadless_abi );
auto trace = push_action(N(payloadless), N(doit), N(payloadless), mutable_variant_object());
auto msg = trace->action_traces.front().console;
BOOST_CHECK_EQUAL(msg == "Im a payloadless action", true);
}
// test GH#3916 - contract api action with no parameters fails when called from clfsc
// abi_serializer was failing when action data was empty.
BOOST_FIXTURE_TEST_CASE( test_abi_serializer, payloadless_tester ) {
create_accounts( {N(payloadless)} );
set_code( N(payloadless), payloadless_wast );
set_abi( N(payloadless), payloadless_abi );
variant pretty_trx = fc::mutable_variant_object()
("actions", fc::variants({
fc::mutable_variant_object()
("account", name(N(payloadless)))
("name", "doit")
("authorization", fc::variants({
fc::mutable_variant_object()
("actor", name(N(payloadless)))
("permission", name(config::active_name))
}))
("data", fc::mutable_variant_object()
)
})
);
signed_transaction trx;
// from_variant is key to this test as abi_serializer was explicitly not allowing empty "data"
abi_serializer::from_variant(pretty_trx, trx, get_resolver(), abi_serializer_max_time);
set_transaction_headers(trx);
trx.sign( get_private_key( N(payloadless), "active" ), control->get_chain_id() );
auto trace = push_transaction( trx );
auto msg = trace->action_traces.front().console;
BOOST_CHECK_EQUAL(msg == "Im a payloadless action", true);
}
BOOST_AUTO_TEST_SUITE_END()
|
/**Kattis - busnumbers2
* Kinda weird going back to easy questions after spending so much time in the 5-8 difficulty
* range with 100+ lines of code per question. We just find all sums of cubes of 2 distinct numbers
* under the upperbound. Then we get the largest. We can tell if a number can be represented in 2
* different ways by just using a hashmap to store the numbers that have already been represented
* at least once before.
*/
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,fma")
#pragma GCC optimize("unroll-loops")
#include <bits/stdc++.h>
using namespace std;
unordered_set<int> s;
int main() {
int ans = -1;
int ub;
cin >> ub;
for (int i = 1; i <= cbrt(ub); i++) {
for (int j = i; j <= cbrt(ub); j++) {
if (i * i * i + j * j * j > ub) break;
if (s.find(i * i * i + j * j * j) == s.end()) {
s.insert(i * i * i + j * j * j);
} else {
ans = max(ans, i * i * i + j * j * j);
}
}
}
cout << (ans == -1 ? "none" : to_string(ans)) << endl;
return 0;
}
|
// Listing 10.3 - usestock0.cpp -- the client program
// compile with stock00.cpp
#include <iostream>
#include "stock00.h"
int main()
{
Stock fluffy_the_cat;
fluffy_the_cat.acquire("NanoSmart", 20, 12.50);
fluffy_the_cat.show();
fluffy_the_cat.buy(15, 18.125);
fluffy_the_cat.show();
fluffy_the_cat.sell(400, 20.00);
fluffy_the_cat.show();
fluffy_the_cat.buy(300000, 40.125);
fluffy_the_cat.show();
fluffy_the_cat.sell(300000, 0.125);
fluffy_the_cat.show();
return 0;
}
|
// class template regex -*- C++ -*-
// Copyright (C) 2013-2016 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.
// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
// <http://www.gnu.org/licenses/>.
/**
* @file bits/regex_compiler.tcc
* This is an internal header file, included by other library headers.
* Do not attempt to use it directly. @headername{regex}
*/
// FIXME make comments doxygen format.
// This compiler refers to "Regular Expression Matching Can Be Simple And Fast"
// (http://swtch.com/~rsc/regexp/regexp1.html"),
// but doesn't strictly follow it.
//
// When compiling, states are *chained* instead of tree- or graph-constructed.
// It's more like structured programs: there's if statement and loop statement.
//
// For alternative structure (say "a|b"), aka "if statement", two branches
// should be constructed. However, these two shall merge to an "end_tag" at
// the end of this operator:
//
// branch1
// / \
// => begin_tag end_tag =>
// \ /
// branch2
//
// This is the difference between this implementation and that in Russ's
// article.
//
// That's why we introduced dummy node here ------ "end_tag" is a dummy node.
// All dummy node will be eliminated at the end of compiling process.
namespace std _GLIBCXX_VISIBILITY(default)
{
namespace __detail
{
_GLIBCXX_BEGIN_NAMESPACE_VERSION
template<typename _TraitsT>
_Compiler<_TraitsT>::
_Compiler(_IterT __b, _IterT __e,
const typename _TraitsT::locale_type& __loc, _FlagT __flags)
: _M_flags((__flags
& (regex_constants::ECMAScript
| regex_constants::basic
| regex_constants::extended
| regex_constants::grep
| regex_constants::egrep
| regex_constants::awk))
? __flags
: __flags | regex_constants::ECMAScript),
_M_scanner(__b, __e, _M_flags, __loc),
_M_nfa(make_shared<_RegexT>(__loc, _M_flags)),
_M_traits(_M_nfa->_M_traits),
_M_ctype(std::use_facet<_CtypeT>(__loc))
{
_StateSeqT __r(*_M_nfa, _M_nfa->_M_start());
__r._M_append(_M_nfa->_M_insert_subexpr_begin());
this->_M_disjunction();
if (!_M_match_token(_ScannerT::_S_token_eof))
__throw_regex_error(regex_constants::error_paren);
__r._M_append(_M_pop());
__glibcxx_assert(_M_stack.empty());
__r._M_append(_M_nfa->_M_insert_subexpr_end());
__r._M_append(_M_nfa->_M_insert_accept());
_M_nfa->_M_eliminate_dummy();
}
template<typename _TraitsT>
void
_Compiler<_TraitsT>::
_M_disjunction()
{
this->_M_alternative();
while (_M_match_token(_ScannerT::_S_token_or))
{
_StateSeqT __alt1 = _M_pop();
this->_M_alternative();
_StateSeqT __alt2 = _M_pop();
auto __end = _M_nfa->_M_insert_dummy();
__alt1._M_append(__end);
__alt2._M_append(__end);
// __alt2 is state._M_next, __alt1 is state._M_alt. The executor
// executes _M_alt before _M_next, as well as executing left
// alternative before right one.
_M_stack.push(_StateSeqT(*_M_nfa,
_M_nfa->_M_insert_alt(
__alt2._M_start, __alt1._M_start, false),
__end));
}
}
template<typename _TraitsT>
void
_Compiler<_TraitsT>::
_M_alternative()
{
if (this->_M_term())
{
_StateSeqT __re = _M_pop();
this->_M_alternative();
__re._M_append(_M_pop());
_M_stack.push(__re);
}
else
_M_stack.push(_StateSeqT(*_M_nfa, _M_nfa->_M_insert_dummy()));
}
template<typename _TraitsT>
bool
_Compiler<_TraitsT>::
_M_term()
{
if (this->_M_assertion())
return true;
if (this->_M_atom())
{
while (this->_M_quantifier());
return true;
}
return false;
}
template<typename _TraitsT>
bool
_Compiler<_TraitsT>::
_M_assertion()
{
if (_M_match_token(_ScannerT::_S_token_line_begin))
_M_stack.push(_StateSeqT(*_M_nfa, _M_nfa->_M_insert_line_begin()));
else if (_M_match_token(_ScannerT::_S_token_line_end))
_M_stack.push(_StateSeqT(*_M_nfa, _M_nfa->_M_insert_line_end()));
else if (_M_match_token(_ScannerT::_S_token_word_bound))
// _M_value[0] == 'n' means it's negative, say "not word boundary".
_M_stack.push(_StateSeqT(*_M_nfa, _M_nfa->
_M_insert_word_bound(_M_value[0] == 'n')));
else if (_M_match_token(_ScannerT::_S_token_subexpr_lookahead_begin))
{
auto __neg = _M_value[0] == 'n';
this->_M_disjunction();
if (!_M_match_token(_ScannerT::_S_token_subexpr_end))
__throw_regex_error(regex_constants::error_paren,
"Parenthesis is not closed.");
auto __tmp = _M_pop();
__tmp._M_append(_M_nfa->_M_insert_accept());
_M_stack.push(
_StateSeqT(
*_M_nfa,
_M_nfa->_M_insert_lookahead(__tmp._M_start, __neg)));
}
else
return false;
return true;
}
template<typename _TraitsT>
bool
_Compiler<_TraitsT>::
_M_quantifier()
{
bool __neg = (_M_flags & regex_constants::ECMAScript);
auto __init = [this, &__neg]()
{
if (_M_stack.empty())
__throw_regex_error(regex_constants::error_badrepeat,
"Nothing to repeat before a quantifier.");
__neg = __neg && _M_match_token(_ScannerT::_S_token_opt);
};
if (_M_match_token(_ScannerT::_S_token_closure0))
{
__init();
auto __e = _M_pop();
_StateSeqT __r(*_M_nfa,
_M_nfa->_M_insert_repeat(_S_invalid_state_id,
__e._M_start, __neg));
__e._M_append(__r);
_M_stack.push(__r);
}
else if (_M_match_token(_ScannerT::_S_token_closure1))
{
__init();
auto __e = _M_pop();
__e._M_append(_M_nfa->_M_insert_repeat(_S_invalid_state_id,
__e._M_start, __neg));
_M_stack.push(__e);
}
else if (_M_match_token(_ScannerT::_S_token_opt))
{
__init();
auto __e = _M_pop();
auto __end = _M_nfa->_M_insert_dummy();
_StateSeqT __r(*_M_nfa,
_M_nfa->_M_insert_repeat(_S_invalid_state_id,
__e._M_start, __neg));
__e._M_append(__end);
__r._M_append(__end);
_M_stack.push(__r);
}
else if (_M_match_token(_ScannerT::_S_token_interval_begin))
{
if (_M_stack.empty())
__throw_regex_error(regex_constants::error_badrepeat,
"Nothing to repeat before a quantifier.");
if (!_M_match_token(_ScannerT::_S_token_dup_count))
__throw_regex_error(regex_constants::error_badbrace,
"Unexpected token in brace expression.");
_StateSeqT __r(_M_pop());
_StateSeqT __e(*_M_nfa, _M_nfa->_M_insert_dummy());
long __min_rep = _M_cur_int_value(10);
bool __infi = false;
long __n;
// {3
if (_M_match_token(_ScannerT::_S_token_comma))
if (_M_match_token(_ScannerT::_S_token_dup_count)) // {3,7}
__n = _M_cur_int_value(10) - __min_rep;
else
__infi = true;
else
__n = 0;
if (!_M_match_token(_ScannerT::_S_token_interval_end))
__throw_regex_error(regex_constants::error_brace,
"Unexpected end of brace expression.");
__neg = __neg && _M_match_token(_ScannerT::_S_token_opt);
for (long __i = 0; __i < __min_rep; ++__i)
__e._M_append(__r._M_clone());
if (__infi)
{
auto __tmp = __r._M_clone();
_StateSeqT __s(*_M_nfa,
_M_nfa->_M_insert_repeat(_S_invalid_state_id,
__tmp._M_start, __neg));
__tmp._M_append(__s);
__e._M_append(__s);
}
else
{
if (__n < 0)
__throw_regex_error(regex_constants::error_badbrace,
"Invalid range in brace expression.");
auto __end = _M_nfa->_M_insert_dummy();
// _M_alt is the "match more" branch, and _M_next is the
// "match less" one. Switch _M_alt and _M_next of all created
// nodes. This is a hack but IMO works well.
std::stack<_StateIdT> __stack;
for (long __i = 0; __i < __n; ++__i)
{
auto __tmp = __r._M_clone();
auto __alt = _M_nfa->_M_insert_repeat(__tmp._M_start,
__end, __neg);
__stack.push(__alt);
__e._M_append(_StateSeqT(*_M_nfa, __alt, __tmp._M_end));
}
__e._M_append(__end);
while (!__stack.empty())
{
auto& __tmp = (*_M_nfa)[__stack.top()];
__stack.pop();
std::swap(__tmp._M_next, __tmp._M_alt);
}
}
_M_stack.push(__e);
}
else
return false;
return true;
}
#define __INSERT_REGEX_MATCHER(__func, args...)\
do\
if (!(_M_flags & regex_constants::icase))\
if (!(_M_flags & regex_constants::collate))\
__func<false, false>(args);\
else\
__func<false, true>(args);\
else\
if (!(_M_flags & regex_constants::collate))\
__func<true, false>(args);\
else\
__func<true, true>(args);\
while (false)
template<typename _TraitsT>
bool
_Compiler<_TraitsT>::
_M_atom()
{
if (_M_match_token(_ScannerT::_S_token_anychar))
{
if (!(_M_flags & regex_constants::ECMAScript))
__INSERT_REGEX_MATCHER(_M_insert_any_matcher_posix);
else
__INSERT_REGEX_MATCHER(_M_insert_any_matcher_ecma);
}
else if (_M_try_char())
__INSERT_REGEX_MATCHER(_M_insert_char_matcher);
else if (_M_match_token(_ScannerT::_S_token_backref))
_M_stack.push(_StateSeqT(*_M_nfa, _M_nfa->
_M_insert_backref(_M_cur_int_value(10))));
else if (_M_match_token(_ScannerT::_S_token_quoted_class))
__INSERT_REGEX_MATCHER(_M_insert_character_class_matcher);
else if (_M_match_token(_ScannerT::_S_token_subexpr_no_group_begin))
{
_StateSeqT __r(*_M_nfa, _M_nfa->_M_insert_dummy());
this->_M_disjunction();
if (!_M_match_token(_ScannerT::_S_token_subexpr_end))
__throw_regex_error(regex_constants::error_paren,
"Parenthesis is not closed.");
__r._M_append(_M_pop());
_M_stack.push(__r);
}
else if (_M_match_token(_ScannerT::_S_token_subexpr_begin))
{
_StateSeqT __r(*_M_nfa, _M_nfa->_M_insert_subexpr_begin());
this->_M_disjunction();
if (!_M_match_token(_ScannerT::_S_token_subexpr_end))
__throw_regex_error(regex_constants::error_paren,
"Parenthesis is not closed.");
__r._M_append(_M_pop());
__r._M_append(_M_nfa->_M_insert_subexpr_end());
_M_stack.push(__r);
}
else if (!_M_bracket_expression())
return false;
return true;
}
template<typename _TraitsT>
bool
_Compiler<_TraitsT>::
_M_bracket_expression()
{
bool __neg =
_M_match_token(_ScannerT::_S_token_bracket_neg_begin);
if (!(__neg || _M_match_token(_ScannerT::_S_token_bracket_begin)))
return false;
__INSERT_REGEX_MATCHER(_M_insert_bracket_matcher, __neg);
return true;
}
#undef __INSERT_REGEX_MATCHER
template<typename _TraitsT>
template<bool __icase, bool __collate>
void
_Compiler<_TraitsT>::
_M_insert_any_matcher_ecma()
{
_M_stack.push(_StateSeqT(*_M_nfa,
_M_nfa->_M_insert_matcher
(_AnyMatcher<_TraitsT, true, __icase, __collate>
(_M_traits))));
}
template<typename _TraitsT>
template<bool __icase, bool __collate>
void
_Compiler<_TraitsT>::
_M_insert_any_matcher_posix()
{
_M_stack.push(_StateSeqT(*_M_nfa,
_M_nfa->_M_insert_matcher
(_AnyMatcher<_TraitsT, false, __icase, __collate>
(_M_traits))));
}
template<typename _TraitsT>
template<bool __icase, bool __collate>
void
_Compiler<_TraitsT>::
_M_insert_char_matcher()
{
_M_stack.push(_StateSeqT(*_M_nfa,
_M_nfa->_M_insert_matcher
(_CharMatcher<_TraitsT, __icase, __collate>
(_M_value[0], _M_traits))));
}
template<typename _TraitsT>
template<bool __icase, bool __collate>
void
_Compiler<_TraitsT>::
_M_insert_character_class_matcher()
{
__glibcxx_assert(_M_value.size() == 1);
_BracketMatcher<_TraitsT, __icase, __collate> __matcher
(_M_ctype.is(_CtypeT::upper, _M_value[0]), _M_traits);
__matcher._M_add_character_class(_M_value, false);
__matcher._M_ready();
_M_stack.push(_StateSeqT(*_M_nfa,
_M_nfa->_M_insert_matcher(std::move(__matcher))));
}
template<typename _TraitsT>
template<bool __icase, bool __collate>
void
_Compiler<_TraitsT>::
_M_insert_bracket_matcher(bool __neg)
{
_BracketMatcher<_TraitsT, __icase, __collate> __matcher(__neg, _M_traits);
pair<bool, _CharT> __last_char; // Optional<_CharT>
__last_char.first = false;
if (!(_M_flags & regex_constants::ECMAScript))
if (_M_try_char())
{
__matcher._M_add_char(_M_value[0]);
__last_char.first = true;
__last_char.second = _M_value[0];
}
while (_M_expression_term(__last_char, __matcher));
__matcher._M_ready();
_M_stack.push(_StateSeqT(
*_M_nfa,
_M_nfa->_M_insert_matcher(std::move(__matcher))));
}
template<typename _TraitsT>
template<bool __icase, bool __collate>
bool
_Compiler<_TraitsT>::
_M_expression_term(pair<bool, _CharT>& __last_char,
_BracketMatcher<_TraitsT, __icase, __collate>& __matcher)
{
if (_M_match_token(_ScannerT::_S_token_bracket_end))
return false;
if (_M_match_token(_ScannerT::_S_token_collsymbol))
{
auto __symbol = __matcher._M_add_collate_element(_M_value);
if (__symbol.size() == 1)
{
__last_char.first = true;
__last_char.second = __symbol[0];
}
}
else if (_M_match_token(_ScannerT::_S_token_equiv_class_name))
__matcher._M_add_equivalence_class(_M_value);
else if (_M_match_token(_ScannerT::_S_token_char_class_name))
__matcher._M_add_character_class(_M_value, false);
// POSIX doesn't allow '-' as a start-range char (say [a-z--0]),
// except when the '-' is the first or last character in the bracket
// expression ([--0]). ECMAScript treats all '-' after a range as a
// normal character. Also see above, where _M_expression_term gets called.
//
// As a result, POSIX rejects [-----], but ECMAScript doesn't.
// Boost (1.57.0) always uses POSIX style even in its ECMAScript syntax.
// Clang (3.5) always uses ECMAScript style even in its POSIX syntax.
//
// It turns out that no one reads BNFs ;)
else if (_M_try_char())
{
if (!__last_char.first)
{
__matcher._M_add_char(_M_value[0]);
if (_M_value[0] == '-'
&& !(_M_flags & regex_constants::ECMAScript))
{
if (_M_match_token(_ScannerT::_S_token_bracket_end))
return false;
__throw_regex_error(
regex_constants::error_range,
"Unexpected dash in bracket expression. For POSIX syntax, "
"a dash is not treated literally only when it is at "
"beginning or end.");
}
__last_char.first = true;
__last_char.second = _M_value[0];
}
else
{
if (_M_value[0] == '-')
{
if (_M_try_char())
{
__matcher._M_make_range(__last_char.second , _M_value[0]);
__last_char.first = false;
}
else
{
if (_M_scanner._M_get_token()
!= _ScannerT::_S_token_bracket_end)
__throw_regex_error(
regex_constants::error_range,
"Unexpected end of bracket expression.");
__matcher._M_add_char(_M_value[0]);
}
}
else
{
__matcher._M_add_char(_M_value[0]);
__last_char.second = _M_value[0];
}
}
}
else if (_M_match_token(_ScannerT::_S_token_quoted_class))
__matcher._M_add_character_class(_M_value,
_M_ctype.is(_CtypeT::upper,
_M_value[0]));
else
__throw_regex_error(regex_constants::error_brack,
"Unexpected character in bracket expression.");
return true;
}
template<typename _TraitsT>
bool
_Compiler<_TraitsT>::
_M_try_char()
{
bool __is_char = false;
if (_M_match_token(_ScannerT::_S_token_oct_num))
{
__is_char = true;
_M_value.assign(1, _M_cur_int_value(8));
}
else if (_M_match_token(_ScannerT::_S_token_hex_num))
{
__is_char = true;
_M_value.assign(1, _M_cur_int_value(16));
}
else if (_M_match_token(_ScannerT::_S_token_ord_char))
__is_char = true;
return __is_char;
}
template<typename _TraitsT>
bool
_Compiler<_TraitsT>::
_M_match_token(_TokenT token)
{
if (token == _M_scanner._M_get_token())
{
_M_value = _M_scanner._M_get_value();
_M_scanner._M_advance();
return true;
}
return false;
}
template<typename _TraitsT>
int
_Compiler<_TraitsT>::
_M_cur_int_value(int __radix)
{
long __v = 0;
for (typename _StringT::size_type __i = 0;
__i < _M_value.length(); ++__i)
__v =__v * __radix + _M_traits.value(_M_value[__i], __radix);
return __v;
}
template<typename _TraitsT, bool __icase, bool __collate>
bool
_BracketMatcher<_TraitsT, __icase, __collate>::
_M_apply(_CharT __ch, false_type) const
{
bool __ret = std::binary_search(_M_char_set.begin(), _M_char_set.end(),
_M_translator._M_translate(__ch));
if (!__ret)
{
auto __s = _M_translator._M_transform(__ch);
for (auto& __it : _M_range_set)
if (__it.first <= __s && __s <= __it.second)
{
__ret = true;
break;
}
if (_M_traits.isctype(__ch, _M_class_set))
__ret = true;
else if (std::find(_M_equiv_set.begin(), _M_equiv_set.end(),
_M_traits.transform_primary(&__ch, &__ch+1))
!= _M_equiv_set.end())
__ret = true;
else
{
for (auto& __it : _M_neg_class_set)
if (!_M_traits.isctype(__ch, __it))
{
__ret = true;
break;
}
}
}
if (_M_is_non_matching)
return !__ret;
else
return __ret;
}
_GLIBCXX_END_NAMESPACE_VERSION
} // namespace __detail
} // namespace
|
//===--- Casting.cpp - Swift Language Dynamic Casting Support -------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Implementations of the dynamic cast runtime functions.
//
//===----------------------------------------------------------------------===//
#include "swift/Basic/LLVM.h"
#include "swift/Basic/Demangle.h"
#include "swift/Basic/Fallthrough.h"
#include "swift/Basic/Lazy.h"
#include "swift/Runtime/Config.h"
#include "swift/Runtime/Enum.h"
#include "swift/Runtime/HeapObject.h"
#include "swift/Runtime/Metadata.h"
#include "swift/Runtime/Mutex.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/PointerIntPair.h"
#include "swift/Runtime/Debug.h"
#include "ErrorObject.h"
#include "ExistentialMetadataImpl.h"
#include "Private.h"
#include "SwiftHashableSupport.h"
#include "../SwiftShims/RuntimeShims.h"
#include "stddef.h"
#if SWIFT_OBJC_INTEROP
#include "swift/Runtime/ObjCBridge.h"
#include "SwiftValue.h"
#endif
#include <cstring>
#include <type_traits>
using namespace swift;
using namespace swift::hashable_support;
using namespace metadataimpl;
#if SWIFT_OBJC_INTEROP
#include <objc/NSObject.h>
#include <objc/runtime.h>
#include <objc/message.h>
#include <objc/objc.h>
// Aliases for Objective-C runtime entry points.
static const char *class_getName(const ClassMetadata* type) {
return class_getName(
reinterpret_cast<Class>(const_cast<ClassMetadata*>(type)));
}
// Aliases for Swift runtime entry points for Objective-C types.
extern "C" const void *swift_dynamicCastObjCProtocolConditional(
const void *object,
size_t numProtocols,
const ProtocolDescriptor * const *protocols);
#endif
namespace {
enum class TypeSyntaxLevel {
/// Any type syntax is valid.
Type,
/// Function types must be parenthesized.
TypeSimple,
};
}
static void _buildNameForMetadata(const Metadata *type,
TypeSyntaxLevel level,
bool qualified,
std::string &result);
static void _buildNominalTypeName(const NominalTypeDescriptor *ntd,
const Metadata *type,
bool qualified,
std::string &result) {
auto options = Demangle::DemangleOptions();
options.DisplayDebuggerGeneratedModule = false;
options.QualifyEntities = qualified;
// Demangle the basic type name.
result += Demangle::demangleTypeAsString(ntd->Name,
strlen(ntd->Name),
options);
// If generic, demangle the type parameters.
if (ntd->GenericParams.NumPrimaryParams > 0) {
result += "<";
auto typeBytes = reinterpret_cast<const char *>(type);
auto genericParam = reinterpret_cast<const Metadata * const *>(
typeBytes + sizeof(void*) * ntd->GenericParams.Offset);
for (unsigned i = 0, e = ntd->GenericParams.NumPrimaryParams;
i < e; ++i, ++genericParam) {
if (i > 0)
result += ", ";
_buildNameForMetadata(*genericParam, TypeSyntaxLevel::Type, qualified,
result);
}
result += ">";
}
}
static const char *_getProtocolName(const ProtocolDescriptor *protocol) {
const char *name = protocol->Name;
// An Objective-C protocol's name is unmangled.
#if SWIFT_OBJC_INTEROP
if (!protocol->Flags.isSwift())
return name;
#endif
// Protocol names are emitted with the _Tt prefix so that ObjC can
// recognize them as mangled Swift names.
assert(name[0] == '_' && name[1] == 'T' && name[2] == 't');
return name + 3;
}
static void _buildExistentialTypeName(const ProtocolDescriptorList *protocols,
TypeSyntaxLevel level,
bool qualified,
std::string &result) {
auto options = Demangle::DemangleOptions();
options.QualifyEntities = qualified;
options.DisplayDebuggerGeneratedModule = false;
// If there's only one protocol, the existential type name is the protocol
// name. If there are 0 protocols it is 'Any'
auto descriptors = protocols->getProtocols();
auto numProtocols = protocols->NumProtocols;
if (numProtocols == 0) {
result += "Any";
} else {
// compositions of more than 1 protocol need parens in .Type contexts
bool needsParens = (level >= TypeSyntaxLevel::TypeSimple) && (numProtocols != 1);
if (needsParens) result += "(";
for (unsigned i = 0, e = numProtocols; i < e; ++i) {
if (i) result += " & ";
auto name = _getProtocolName(descriptors[i]);
result += Demangle::demangleTypeAsString(name,
strlen(name),
options);
}
if (needsParens) result += ")";
}
}
static void _buildFunctionTypeName(const FunctionTypeMetadata *func,
bool qualified,
std::string &result) {
result += "(";
for (size_t i = 0; i < func->getNumArguments(); ++i) {
auto arg = func->getArguments()[i].getPointer();
bool isInout = func->getArguments()[i].getFlag();
if (isInout)
result += "inout ";
_buildNameForMetadata(arg, TypeSyntaxLevel::TypeSimple,
qualified, result);
if (i < func->getNumArguments() - 1) {
result += ", ";
}
}
result += ")";
if (func->throws()) {
result += " throws";
}
result += " -> ";
_buildNameForMetadata(func->ResultType,
TypeSyntaxLevel::Type,
qualified,
result);
}
// Build a user-comprehensible name for a type.
static void _buildNameForMetadata(const Metadata *type,
TypeSyntaxLevel level,
bool qualified,
std::string &result) {
auto options = Demangle::DemangleOptions();
options.DisplayDebuggerGeneratedModule = false;
switch (type->getKind()) {
case MetadataKind::Class: {
auto classType = static_cast<const ClassMetadata *>(type);
#if SWIFT_OBJC_INTEROP
// Look through artificial subclasses.
while (classType->isTypeMetadata() && classType->isArtificialSubclass())
classType = classType->SuperClass;
// Ask the Objective-C runtime to name ObjC classes.
if (!classType->isTypeMetadata()) {
result += class_getName(classType);
return;
}
#endif
return _buildNominalTypeName(classType->getDescription(),
classType, qualified,
result);
}
case MetadataKind::Enum:
case MetadataKind::Optional:
case MetadataKind::Struct: {
auto structType = static_cast<const StructMetadata *>(type);
return _buildNominalTypeName(structType->Description,
type, qualified, result);
}
case MetadataKind::ObjCClassWrapper: {
#if SWIFT_OBJC_INTEROP
auto objcWrapper = static_cast<const ObjCClassWrapperMetadata *>(type);
result += class_getName(objcWrapper->Class);
#else
assert(false && "no ObjC interop");
#endif
return;
}
case MetadataKind::ForeignClass: {
auto foreign = static_cast<const ForeignClassMetadata *>(type);
const char *name = foreign->getName();
size_t len = strlen(name);
result += Demangle::demangleTypeAsString(name, len, options);
return;
}
case MetadataKind::Existential: {
auto exis = static_cast<const ExistentialTypeMetadata *>(type);
_buildExistentialTypeName(&exis->Protocols, level, qualified, result);
return;
}
case MetadataKind::ExistentialMetatype: {
auto metatype = static_cast<const ExistentialMetatypeMetadata *>(type);
_buildNameForMetadata(metatype->InstanceType, TypeSyntaxLevel::TypeSimple,
qualified,
result);
result += ".Type";
return;
}
case MetadataKind::Function: {
if (level >= TypeSyntaxLevel::TypeSimple)
result += "(";
auto func = static_cast<const FunctionTypeMetadata *>(type);
switch (func->getConvention()) {
case FunctionMetadataConvention::Swift:
break;
case FunctionMetadataConvention::Thin:
result += "@convention(thin) ";
break;
case FunctionMetadataConvention::Block:
result += "@convention(block) ";
break;
case FunctionMetadataConvention::CFunctionPointer:
result += "@convention(c) ";
break;
}
_buildFunctionTypeName(func, qualified, result);
if (level >= TypeSyntaxLevel::TypeSimple)
result += ")";
return;
}
case MetadataKind::Metatype: {
auto metatype = static_cast<const MetatypeMetadata *>(type);
_buildNameForMetadata(metatype->InstanceType, TypeSyntaxLevel::TypeSimple,
qualified, result);
if (metatype->InstanceType->isAnyExistentialType())
result += ".Protocol";
else
result += ".Type";
return;
}
case MetadataKind::Tuple: {
auto tuple = static_cast<const TupleTypeMetadata *>(type);
result += "(";
auto elts = tuple->getElements();
for (unsigned i = 0, e = tuple->NumElements; i < e; ++i) {
if (i > 0)
result += ", ";
_buildNameForMetadata(elts[i].Type, TypeSyntaxLevel::Type, qualified,
result);
}
result += ")";
return;
}
case MetadataKind::Opaque: {
// TODO
result += "<<<opaque type>>>";
return;
}
case MetadataKind::HeapLocalVariable:
case MetadataKind::HeapGenericLocalVariable:
case MetadataKind::ErrorObject:
break;
}
result += "<<<invalid type>>>";
}
/// Return a user-comprehensible name for the given type.
std::string swift::nameForMetadata(const Metadata *type,
bool qualified) {
std::string result;
_buildNameForMetadata(type, TypeSyntaxLevel::Type, qualified, result);
return result;
}
SWIFT_CC(swift) SWIFT_RUNTIME_EXPORT
TwoWordPair<const char *, uintptr_t>::Return
swift::swift_getTypeName(const Metadata *type, bool qualified) {
using Pair = TwoWordPair<const char *, uintptr_t>;
using Key = llvm::PointerIntPair<const Metadata *, 1, bool>;
static StaticReadWriteLock TypeNameCacheLock;
static Lazy<llvm::DenseMap<Key, std::pair<const char *, size_t>>>
TypeNameCache;
Key key(type, qualified);
auto &cache = TypeNameCache.get();
// Attempt read-only lookup of cache entry.
{
StaticScopedReadLock guard(TypeNameCacheLock);
auto found = cache.find(key);
if (found != cache.end()) {
auto result = found->second;
return Pair{result.first, result.second};
}
}
// Read-only lookup failed to find item, we may need to create it.
{
StaticScopedWriteLock guard(TypeNameCacheLock);
// Do lookup again just to make sure it wasn't created by another
// thread before we acquired the write lock.
auto found = cache.find(key);
if (found != cache.end()) {
auto result = found->second;
return Pair{result.first, result.second};
}
// Build the metadata name.
auto name = nameForMetadata(type, qualified);
// Copy it to memory we can reference forever.
auto size = name.size();
auto result = (char *)malloc(size + 1);
memcpy(result, name.data(), size);
result[size] = 0;
cache.insert({key, {result, size}});
return Pair{result, size};
}
}
/// Report a dynamic cast failure.
// This is noinline with asm("") to preserve this frame in stack traces.
// We want "dynamicCastFailure" to appear in crash logs even we crash
// during the diagnostic because some Metadata is invalid.
LLVM_ATTRIBUTE_NORETURN
LLVM_ATTRIBUTE_NOINLINE
void
swift::swift_dynamicCastFailure(const void *sourceType, const char *sourceName,
const void *targetType, const char *targetName,
const char *message) {
asm("");
swift::fatalError(/* flags = */ 0,
"Could not cast value of type '%s' (%p) to '%s' (%p)%s%s\n",
sourceName, sourceType,
targetName, targetType,
message ? ": " : ".",
message ? message : "");
}
LLVM_ATTRIBUTE_NORETURN
void
swift::swift_dynamicCastFailure(const Metadata *sourceType,
const Metadata *targetType,
const char *message) {
std::string sourceName = nameForMetadata(sourceType);
std::string targetName = nameForMetadata(targetType);
swift_dynamicCastFailure(sourceType, sourceName.c_str(),
targetType, targetName.c_str(), message);
}
#if SWIFT_OBJC_INTEROP
// Objective-C bridging helpers.
namespace {
struct _ObjectiveCBridgeableWitnessTable;
}
static const _ObjectiveCBridgeableWitnessTable *
findBridgeWitness(const Metadata *T);
static bool _dynamicCastValueToClassViaObjCBridgeable(
OpaqueValue *dest,
OpaqueValue *src,
const Metadata *srcType,
const Metadata *targetType,
const _ObjectiveCBridgeableWitnessTable *srcBridgeWitness,
DynamicCastFlags flags);
static bool _dynamicCastValueToClassExistentialViaObjCBridgeable(
OpaqueValue *dest,
OpaqueValue *src,
const Metadata *srcType,
const ExistentialTypeMetadata *targetType,
const _ObjectiveCBridgeableWitnessTable *srcBridgeWitness,
DynamicCastFlags flags);
static bool _dynamicCastClassToValueViaObjCBridgeable(
OpaqueValue *dest,
OpaqueValue *src,
const Metadata *srcType,
const Metadata *targetType,
const _ObjectiveCBridgeableWitnessTable *targetBridgeWitness,
DynamicCastFlags flags);
#endif
/// A convenient method for failing out of a dynamic cast.
static bool _fail(OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *targetType, DynamicCastFlags flags,
const Metadata *srcDynamicType = nullptr) {
if (flags & DynamicCastFlags::Unconditional) {
const Metadata *srcTypeToReport =
srcDynamicType ? srcDynamicType
: srcType;
swift_dynamicCastFailure(srcTypeToReport, targetType);
}
if (flags & DynamicCastFlags::DestroyOnFailure)
srcType->vw_destroy(srcValue);
return false;
}
/// A convenient method for succeeding at a dynamic cast.
static bool _succeed(OpaqueValue *dest, OpaqueValue *src,
const Metadata *srcType, DynamicCastFlags flags) {
if (flags & DynamicCastFlags::TakeOnSuccess) {
srcType->vw_initializeWithTake(dest, src);
} else {
srcType->vw_initializeWithCopy(dest, src);
}
return true;
}
/// Dynamically cast a class metatype to a Swift class metatype.
static const ClassMetadata *
_dynamicCastClassMetatype(const ClassMetadata *sourceType,
const ClassMetadata *targetType) {
do {
if (sourceType == targetType) {
return sourceType;
}
sourceType = _swift_getSuperclass(sourceType);
} while (sourceType);
return nullptr;
}
/// Dynamically cast a class instance to a Swift class type.
SWIFT_RT_ENTRY_VISIBILITY
const void *
swift::swift_dynamicCastClass(const void *object,
const ClassMetadata *targetType)
SWIFT_CC(RegisterPreservingCC_IMPL) {
#if SWIFT_OBJC_INTEROP
assert(!targetType->isPureObjC());
// Swift native classes never have a tagged-pointer representation.
if (isObjCTaggedPointerOrNull(object)) {
return nullptr;
}
#endif
auto isa = _swift_getClassOfAllocated(object);
if (_dynamicCastClassMetatype(isa, targetType))
return object;
return nullptr;
}
/// Dynamically cast a class object to a Swift class type.
const void *
swift::swift_dynamicCastClassUnconditional(const void *object,
const ClassMetadata *targetType) {
auto value = swift_dynamicCastClass(object, targetType);
if (value) return value;
swift_dynamicCastFailure(_swift_getClass(object), targetType);
}
#if SWIFT_OBJC_INTEROP
static bool _unknownClassConformsToObjCProtocol(const OpaqueValue *value,
const ProtocolDescriptor *protocol) {
const void *object
= *reinterpret_cast<const void * const *>(value);
return swift_dynamicCastObjCProtocolConditional(object, 1, &protocol);
}
#endif
/// Check whether a type conforms to a protocol.
///
/// \param value - can be null, in which case the question should
/// be answered abstractly if possible
/// \param conformance - if non-null, and the protocol requires a
/// witness table, and the type implements the protocol, the witness
/// table will be placed here
static bool _conformsToProtocol(const OpaqueValue *value,
const Metadata *type,
const ProtocolDescriptor *protocol,
const WitnessTable **conformance) {
// Handle AnyObject directly.
if (protocol->Flags.getSpecialProtocol() == SpecialProtocol::AnyObject) {
switch (type->getKind()) {
case MetadataKind::Class:
case MetadataKind::ObjCClassWrapper:
case MetadataKind::ForeignClass:
// Classes conform to AnyObject.
return true;
case MetadataKind::Existential: {
auto sourceExistential = cast<ExistentialTypeMetadata>(type);
// The existential conforms to AnyObject if it's class-constrained.
// FIXME: It also must not carry witness tables.
return sourceExistential->isClassBounded();
}
case MetadataKind::ExistentialMetatype:
case MetadataKind::Metatype:
case MetadataKind::Function:
case MetadataKind::HeapLocalVariable:
case MetadataKind::HeapGenericLocalVariable:
case MetadataKind::ErrorObject:
case MetadataKind::Enum:
case MetadataKind::Optional:
case MetadataKind::Opaque:
case MetadataKind::Struct:
case MetadataKind::Tuple:
return false;
}
_failCorruptType(type);
}
// Look up the witness table for protocols that need them.
if (protocol->Flags.needsWitnessTable()) {
auto witness = swift_conformsToProtocol(type, protocol);
if (!witness)
return false;
if (conformance)
*conformance = witness;
return true;
}
// For Objective-C protocols, check whether we have a class that
// conforms to the given protocol.
switch (type->getKind()) {
case MetadataKind::Class:
#if SWIFT_OBJC_INTEROP
if (value) {
return _unknownClassConformsToObjCProtocol(value, protocol);
} else {
return classConformsToObjCProtocol(type, protocol);
}
#endif
return false;
case MetadataKind::ObjCClassWrapper: {
#if SWIFT_OBJC_INTEROP
if (value) {
return _unknownClassConformsToObjCProtocol(value, protocol);
} else {
auto wrapper = cast<ObjCClassWrapperMetadata>(type);
return classConformsToObjCProtocol(wrapper->Class, protocol);
}
#endif
return false;
}
case MetadataKind::ForeignClass:
#if SWIFT_OBJC_INTEROP
if (value)
return _unknownClassConformsToObjCProtocol(value, protocol);
return false;
#else
_failCorruptType(type);
#endif
case MetadataKind::Existential: // FIXME
case MetadataKind::ExistentialMetatype: // FIXME
case MetadataKind::Function:
case MetadataKind::HeapLocalVariable:
case MetadataKind::HeapGenericLocalVariable:
case MetadataKind::ErrorObject:
case MetadataKind::Metatype:
case MetadataKind::Enum:
case MetadataKind::Optional:
case MetadataKind::Opaque:
case MetadataKind::Struct:
case MetadataKind::Tuple:
return false;
}
return false;
}
/// Check whether a type conforms to the given protocols, filling in a
/// list of conformances.
static bool _conformsToProtocols(const OpaqueValue *value,
const Metadata *type,
const ProtocolDescriptorList &protocols,
const WitnessTable **conformances) {
for (unsigned i = 0, n = protocols.NumProtocols; i != n; ++i) {
const ProtocolDescriptor *protocol = protocols[i];
if (!_conformsToProtocol(value, type, protocol, conformances))
return false;
if (protocol->Flags.needsWitnessTable()) {
assert(*conformances != nullptr);
++conformances;
}
}
return true;
}
static bool shouldDeallocateSource(bool castSucceeded, DynamicCastFlags flags) {
return (castSucceeded && (flags & DynamicCastFlags::TakeOnSuccess)) ||
(!castSucceeded && (flags & DynamicCastFlags::DestroyOnFailure));
}
/// Given that a cast operation is complete, maybe deallocate an
/// opaque existential value.
static void _maybeDeallocateOpaqueExistential(OpaqueValue *srcExistential,
bool castSucceeded,
DynamicCastFlags flags) {
if (shouldDeallocateSource(castSucceeded, flags)) {
auto container =
reinterpret_cast<OpaqueExistentialContainer *>(srcExistential);
container->Type->vw_deallocateBuffer(&container->Buffer);
}
}
static bool
isAnyObjectExistentialType(const ExistentialTypeMetadata *targetType) {
unsigned numProtos = targetType->Protocols.NumProtocols;
if (numProtos != 1)
return false;
const ProtocolDescriptor *protocol = targetType->Protocols[0];
bool isAnyObjectProtocol =
protocol->Flags.getSpecialProtocol() == SpecialProtocol::AnyObject;
// Assert that AnyObject does not need any witness tables. We rely on this.
assert(!isAnyObjectProtocol || !protocol->Flags.needsWitnessTable() &&
"AnyObject should not require witness tables");
return isAnyObjectProtocol;
}
/// Given a possibly-existential value, find its dynamic type and the
/// address of its storage.
static void
findDynamicValueAndType(OpaqueValue *value, const Metadata *type,
OpaqueValue *&outValue, const Metadata *&outType,
bool &inoutCanTake,
bool isTargetTypeAnyObject) {
switch (type->getKind()) {
case MetadataKind::Class:
case MetadataKind::ObjCClassWrapper:
case MetadataKind::ForeignClass: {
// TODO: avoid unnecessary repeat lookup of
// ObjCClassWrapper/ForeignClass when the type matches.
outValue = value;
outType = swift_getObjectType(*reinterpret_cast<HeapObject**>(value));
return;
}
case MetadataKind::Existential: {
auto existentialType = cast<ExistentialTypeMetadata>(type);
switch (existentialType->getRepresentation()) {
case ExistentialTypeRepresentation::Class: {
// Class existentials can't recursively contain existential containers,
// so we can fast-path by not bothering to recur.
auto existential =
reinterpret_cast<ClassExistentialContainer*>(value);
outValue = (OpaqueValue*) &existential->Value;
outType = swift_getObjectType((HeapObject*) existential->Value);
return;
}
case ExistentialTypeRepresentation::Opaque:
case ExistentialTypeRepresentation::Error: {
const Metadata *innerType = existentialType->getDynamicType(value);
// Short cut class in existential as AnyObject casts.
if (isTargetTypeAnyObject &&
innerType->getKind() == MetadataKind::Class) {
// inline value buffer storage.
outValue = value;
outType = 0;
inoutCanTake= true;
return;
}
OpaqueValue *innerValue
= existentialType->projectValue(value);
inoutCanTake &= existentialType->mayTakeValue(value);
return findDynamicValueAndType(innerValue, innerType,
outValue, outType, inoutCanTake, false);
}
}
}
case MetadataKind::Metatype:
case MetadataKind::ExistentialMetatype: {
auto storedType = *(const Metadata **) value;
outValue = value;
outType = swift_getMetatypeMetadata(storedType);
return;
}
// Non-polymorphic types.
case MetadataKind::Function:
case MetadataKind::HeapLocalVariable:
case MetadataKind::HeapGenericLocalVariable:
case MetadataKind::ErrorObject:
case MetadataKind::Enum:
case MetadataKind::Optional:
case MetadataKind::Opaque:
case MetadataKind::Struct:
case MetadataKind::Tuple:
outValue = value;
outType = type;
return;
}
_failCorruptType(type);
}
extern "C" const Metadata *
swift::swift_getDynamicType(OpaqueValue *value, const Metadata *self) {
OpaqueValue *outValue;
const Metadata *outType;
bool canTake = false;
findDynamicValueAndType(value, self, outValue, outType, canTake, false);
return outType;
}
/// Given a possibly-existential value, deallocate any buffer in its storage.
static void deallocateDynamicValue(OpaqueValue *value, const Metadata *type) {
switch (type->getKind()) {
case MetadataKind::Existential: {
auto existentialType = cast<ExistentialTypeMetadata>(type);
switch (existentialType->getRepresentation()) {
case ExistentialTypeRepresentation::Class:
// Nothing to clean up.
break;
case ExistentialTypeRepresentation::Error:
// TODO: We could clean up from a reclaimed uniquely-referenced error box.
break;
case ExistentialTypeRepresentation::Opaque:
auto existential =
reinterpret_cast<OpaqueExistentialContainer*>(value);
// Handle the possibility of nested existentials.
OpaqueValue *existentialValue =
existential->Type->vw_projectBuffer(&existential->Buffer);
deallocateDynamicValue(existentialValue, existential->Type);
// Deallocate the buffer.
existential->Type->vw_deallocateBuffer(&existential->Buffer);
break;
}
return;
}
// None of the rest of these require deallocation.
case MetadataKind::Class:
case MetadataKind::ForeignClass:
case MetadataKind::ObjCClassWrapper:
case MetadataKind::Metatype:
case MetadataKind::ExistentialMetatype:
case MetadataKind::Function:
case MetadataKind::HeapLocalVariable:
case MetadataKind::HeapGenericLocalVariable:
case MetadataKind::ErrorObject:
case MetadataKind::Enum:
case MetadataKind::Optional:
case MetadataKind::Opaque:
case MetadataKind::Struct:
case MetadataKind::Tuple:
return;
}
_failCorruptType(type);
}
#if SWIFT_OBJC_INTEROP
SWIFT_CC(c) SWIFT_RUNTIME_EXPORT
extern "C" id
swift_dynamicCastMetatypeToObjectConditional(const Metadata *metatype) {
switch (metatype->getKind()) {
case MetadataKind::Class:
// Swift classes are objects in and of themselves.
return (id)metatype;
case MetadataKind::ObjCClassWrapper: {
// Unwrap ObjC class objects.
auto wrapper = static_cast<const ObjCClassWrapperMetadata*>(metatype);
return (id)wrapper->getClassObject();
}
// Other kinds of metadata don't cast to AnyObject.
case MetadataKind::Struct:
case MetadataKind::Enum:
case MetadataKind::Optional:
case MetadataKind::Opaque:
case MetadataKind::Tuple:
case MetadataKind::Function:
case MetadataKind::Existential:
case MetadataKind::Metatype:
case MetadataKind::ExistentialMetatype:
case MetadataKind::ForeignClass:
case MetadataKind::HeapLocalVariable:
case MetadataKind::HeapGenericLocalVariable:
case MetadataKind::ErrorObject:
return nullptr;
}
}
SWIFT_CC(c) SWIFT_RUNTIME_EXPORT
extern "C" id
swift_dynamicCastMetatypeToObjectUnconditional(const Metadata *metatype) {
switch (metatype->getKind()) {
case MetadataKind::Class:
// Swift classes are objects in and of themselves.
return (id)metatype;
case MetadataKind::ObjCClassWrapper: {
// Unwrap ObjC class objects.
auto wrapper = static_cast<const ObjCClassWrapperMetadata*>(metatype);
return (id)wrapper->getClassObject();
}
// Other kinds of metadata don't cast to AnyObject.
case MetadataKind::Struct:
case MetadataKind::Enum:
case MetadataKind::Optional:
case MetadataKind::Opaque:
case MetadataKind::Tuple:
case MetadataKind::Function:
case MetadataKind::Existential:
case MetadataKind::Metatype:
case MetadataKind::ExistentialMetatype:
case MetadataKind::ForeignClass:
case MetadataKind::HeapLocalVariable:
case MetadataKind::HeapGenericLocalVariable:
case MetadataKind::ErrorObject: {
std::string sourceName = nameForMetadata(metatype);
swift_dynamicCastFailure(metatype, sourceName.c_str(),
nullptr, "AnyObject",
"only class metatypes can be converted to AnyObject");
}
}
}
// @_silgen_name("swift_stdlib_getErrorEmbeddedNSErrorIndirect")
// public func _stdlib_getErrorEmbeddedNSErrorIndirect<T : Error>(
/// _ x: UnsafePointer<T>) -> AnyObject?
SWIFT_CC(swift)
extern "C" id swift_stdlib_getErrorEmbeddedNSErrorIndirect(
const OpaqueValue *error,
const Metadata *T,
const WitnessTable *Error);
#endif
/******************************************************************************/
/******************************** AnyHashable *********************************/
/******************************************************************************/
/// Nominal type descriptor for Swift.AnyHashable.
extern "C" const NominalTypeDescriptor _TMnVs11AnyHashable;
/// Protocol descriptor for Swift.Hashable.
extern "C" const ProtocolDescriptor _TMps8Hashable;
static bool isAnyHashableType(const StructMetadata *type) {
return type->getDescription() == &_TMnVs11AnyHashable;
}
static bool isAnyHashableType(const Metadata *type) {
if (auto structType = dyn_cast<StructMetadata>(type)) {
return isAnyHashableType(structType);
}
return false;
}
/// Perform a dynamic cast from a nominal type to AnyHashable.
static bool _dynamicCastToAnyHashable(OpaqueValue *destination,
OpaqueValue *source,
const Metadata *sourceType,
const Metadata *targetType,
DynamicCastFlags flags) {
// Look for a conformance to Hashable.
auto hashableConformance = reinterpret_cast<const HashableWitnessTable *>(
swift_conformsToProtocol(sourceType, &_TMps8Hashable));
// If we don't find one, the cast fails.
if (!hashableConformance) {
return _fail(source, sourceType, targetType, flags);
}
// If we do find one, the cast succeeds.
// The intrinsic wants the value at +1, so we have to copy it into
// a temporary.
ValueBuffer buffer;
bool mustDeallocBuffer = false;
if (!(flags & DynamicCastFlags::TakeOnSuccess)) {
source = sourceType->vw_initializeBufferWithCopy(&buffer, source);
mustDeallocBuffer = true;
}
// Initialize the destination.
_swift_convertToAnyHashableIndirect(source, destination,
sourceType, hashableConformance);
// Deallocate the buffer if we used it.
if (mustDeallocBuffer) {
sourceType->vw_deallocateBuffer(&buffer);
}
// The cast succeeded.
return true;
}
/// Perform a dynamic cast to an arbitrary type from AnyHashable.
static bool _dynamicCastFromAnyHashable(OpaqueValue *destination,
OpaqueValue *source,
const Metadata *sourceType,
const Metadata *targetType,
DynamicCastFlags flags) {
// Perform a conditional, non-consuming cast into the destination.
if (_swift_anyHashableDownCastConditionalIndirect(source, destination,
targetType)) {
// If that succeeded, and we were supposed to claim the source,
// destroy it now.
if (flags & DynamicCastFlags::TakeOnSuccess) {
sourceType->vw_destroy(source);
}
return true;
}
return _fail(source, sourceType, targetType, flags);
}
/******************************************************************************/
/******************************** Existentials ********************************/
/******************************************************************************/
/// Perform a dynamic cast to an existential type.
static bool _dynamicCastToExistential(OpaqueValue *dest,
OpaqueValue *src,
const Metadata *srcType,
const ExistentialTypeMetadata *targetType,
DynamicCastFlags flags) {
#if SWIFT_OBJC_INTEROP
// This variable's lifetime needs to be for the whole function, but is
// only valid with Objective-C interop enabled.
id tmp;
#endif
// Find the actual type of the source.
OpaqueValue *srcDynamicValue;
const Metadata *srcDynamicType;
bool canConsumeDynamicValue = true;
// Are we casting to AnyObject? In this case we can fast-path casts from
// classes.
bool isTargetTypeAnyObject =
targetType->getKind() == MetadataKind::Existential &&
isAnyObjectExistentialType(targetType);
// We don't care what the target type of a cast from class to AnyObject is.
// srcDynamicType will be set to a nullptr in this case to save a lookup.
findDynamicValueAndType(src, srcType, srcDynamicValue, srcDynamicType,
canConsumeDynamicValue, isTargetTypeAnyObject);
// Recursive casts on the dynamic value should not destroy the source
// if findDynamicValueAndType doesn't allow it.
DynamicCastFlags dynamicFlags = flags;
if (!canConsumeDynamicValue) {
dynamicFlags = dynamicFlags - (DynamicCastFlags::TakeOnSuccess |
DynamicCastFlags::DestroyOnFailure);
}
// Given that we performed a cast on srcDynamicValue and obeyed
// dynamicFlags there, clean up after src.
auto maybeDeallocateSource = [&](bool success) {
// If the flags don't say to destroy src, we're done.
if (!shouldDeallocateSource(success, flags)) return;
// If findDynamicValueAndType didn't give us a consumable interior
// value, then src is still completely intact.
if (!canConsumeDynamicValue) {
srcType->vw_destroy(src);
// Otherwise, if we destroyed an interior value, we need to clean
// up any leftover buffers it may have been contained in.
} else if (src != srcDynamicValue) {
deallocateDynamicValue(src, srcType);
}
};
// A function to call if the dynamic type does not conform to the
// protocols. Typically fails, but if the source type is AnyHashable,
// tries to unwrap that.
auto fallbackForNonDirectConformance = [&] {
// As a fallback, if the source type is AnyHashable, perform a cast
// on its interior value.
if (isAnyHashableType(srcDynamicType)) {
bool success =
_dynamicCastFromAnyHashable(dest, srcDynamicValue, srcDynamicType,
targetType, dynamicFlags);
maybeDeallocateSource(success);
return success;
}
return _fail(src, srcType, targetType, flags, srcDynamicType);
};
// The representation of an existential is different for some protocols.
switch (targetType->getRepresentation()) {
case ExistentialTypeRepresentation::Class: {
auto destExistential =
reinterpret_cast<ClassExistentialContainer*>(dest);
MetadataKind kind =
srcDynamicType ? srcDynamicType->getKind() : MetadataKind::Class;
// A fallback to use if we don't have a more specialized approach
// for a non-class type.
auto fallbackForNonClass = [&] {
#if SWIFT_OBJC_INTEROP
// If the destination type is a set of protocols that SwiftValue
// implements, we're fine.
if (findSwiftValueConformances(targetType->Protocols,
destExistential->getWitnessTables())) {
bool consumeValue = dynamicFlags & DynamicCastFlags::TakeOnSuccess;
destExistential->Value =
bridgeAnythingToSwiftValueObject(srcDynamicValue, srcDynamicType,
consumeValue);
maybeDeallocateSource(true);
return true;
}
#endif
return _fail(src, srcType, targetType, flags);
};
// If the source type is a value type, it cannot possibly conform
// to a class-bounded protocol.
switch (kind) {
case MetadataKind::ExistentialMetatype:
case MetadataKind::Metatype: {
#if SWIFT_OBJC_INTEROP
// Class metadata can be used as an object when ObjC interop is available.
auto metatypePtr = reinterpret_cast<const Metadata **>(src);
auto metatype = *metatypePtr;
tmp = swift_dynamicCastMetatypeToObjectConditional(metatype);
// If the cast succeeded, use the result value as the class instance
// below.
if (tmp) {
srcDynamicValue = reinterpret_cast<OpaqueValue*>(&tmp);
srcDynamicType = reinterpret_cast<const Metadata*>(tmp);
break;
}
#endif
// Otherwise, metatypes aren't class objects.
return fallbackForNonClass();
}
case MetadataKind::Class:
case MetadataKind::ObjCClassWrapper:
case MetadataKind::ForeignClass:
case MetadataKind::Existential:
// Handle the class cases below. Note that opaque existentials
// shouldn't get here because we should have drilled into them above.
break;
case MetadataKind::Struct:
// If the source type is AnyHashable, cast from that.
if (isAnyHashableType(cast<StructMetadata>(srcDynamicType))) {
bool result =
_dynamicCastFromAnyHashable(dest, srcDynamicValue, srcDynamicType,
targetType, dynamicFlags);
maybeDeallocateSource(result);
return result;
}
SWIFT_FALLTHROUGH;
case MetadataKind::Enum:
case MetadataKind::Optional:
#if SWIFT_OBJC_INTEROP
// If the source type is bridged to Objective-C, try to bridge.
if (auto srcBridgeWitness = findBridgeWitness(srcDynamicType)) {
bool success = _dynamicCastValueToClassExistentialViaObjCBridgeable(
dest,
srcDynamicValue,
srcDynamicType,
targetType,
srcBridgeWitness,
dynamicFlags);
maybeDeallocateSource(success);
return success;
}
#endif
SWIFT_FALLTHROUGH;
case MetadataKind::Function:
case MetadataKind::HeapLocalVariable:
case MetadataKind::HeapGenericLocalVariable:
case MetadataKind::ErrorObject:
case MetadataKind::Opaque:
case MetadataKind::Tuple:
return fallbackForNonClass();
}
// Check for protocol conformances and fill in the witness tables. If
// srcDynamicType equals nullptr we have a cast from an existential
// container with a class instance to AnyObject. In this case no check is
// necessary.
if (srcDynamicType && !_conformsToProtocols(srcDynamicValue, srcDynamicType,
targetType->Protocols,
destExistential->getWitnessTables()))
return fallbackForNonDirectConformance();
auto object = *(reinterpret_cast<HeapObject**>(srcDynamicValue));
destExistential->Value = object;
if (!canConsumeDynamicValue || !(flags & DynamicCastFlags::TakeOnSuccess)) {
swift_retain(object);
}
maybeDeallocateSource(true);
return true;
}
case ExistentialTypeRepresentation::Opaque: {
auto destExistential =
reinterpret_cast<OpaqueExistentialContainer*>(dest);
// Check for protocol conformances and fill in the witness tables.
if (!_conformsToProtocols(srcDynamicValue, srcDynamicType,
targetType->Protocols,
destExistential->getWitnessTables()))
return fallbackForNonDirectConformance();
// Fill in the type and value.
destExistential->Type = srcDynamicType;
if (canConsumeDynamicValue && (flags & DynamicCastFlags::TakeOnSuccess)) {
srcDynamicType->vw_initializeBufferWithTake(&destExistential->Buffer,
srcDynamicValue);
} else {
srcDynamicType->vw_initializeBufferWithCopy(&destExistential->Buffer,
srcDynamicValue);
}
maybeDeallocateSource(true);
return true;
}
case ExistentialTypeRepresentation::Error: {
auto destBoxAddr =
reinterpret_cast<SwiftError**>(dest);
// Check for the Error protocol conformance, which should be the only
// one we need.
assert(targetType->Protocols.NumProtocols == 1);
const WitnessTable *errorWitness;
if (!_conformsToProtocols(srcDynamicValue, srcDynamicType,
targetType->Protocols,
&errorWitness))
return fallbackForNonDirectConformance();
#if SWIFT_OBJC_INTEROP
// Check whether there is an embedded NSError. If so, use that for our Error
// representation.
if (auto embedded =
swift_stdlib_getErrorEmbeddedNSErrorIndirect(srcDynamicValue,
srcDynamicType,
errorWitness)) {
*destBoxAddr = reinterpret_cast<SwiftError*>(embedded);
maybeDeallocateSource(true);
return true;
}
#endif
bool isTake =
(canConsumeDynamicValue && (flags & DynamicCastFlags::TakeOnSuccess));
BoxPair destBox = swift_allocError(srcDynamicType, errorWitness,
srcDynamicValue, isTake);
*destBoxAddr = reinterpret_cast<SwiftError*>(destBox.first);
maybeDeallocateSource(true);
return true;
}
}
}
/******************************************************************************/
/********************************** Classes ***********************************/
/******************************************************************************/
static const void *
_dynamicCastUnknownClassToExistential(const void *object,
const ExistentialTypeMetadata *targetType) {
for (unsigned i = 0, e = targetType->Protocols.NumProtocols; i < e; ++i) {
const ProtocolDescriptor *protocol = targetType->Protocols[i];
switch (protocol->Flags.getDispatchStrategy()) {
case ProtocolDispatchStrategy::Swift:
// If the target existential requires witness tables, we can't do this cast.
// The result type would not have a single-refcounted-pointer rep.
return nullptr;
case ProtocolDispatchStrategy::ObjC:
#if SWIFT_OBJC_INTEROP
// All classes conform to AnyObject.
if (protocol->Flags.getSpecialProtocol() == SpecialProtocol::AnyObject)
break;
if (!objectConformsToObjCProtocol(object, protocol))
return nullptr;
break;
#else
assert(false && "ObjC interop disabled?!");
return nullptr;
#endif
case ProtocolDispatchStrategy::Empty:
// The only non-@objc, non-witness-table-requiring protocol should be
// AnyObject for now.
assert(protocol->Flags.getSpecialProtocol() == SpecialProtocol::AnyObject
&& "swift protocols besides AnyObject should always require a "
"witness table");
break;
}
}
return object;
}
/// Perform a dynamic class of some sort of class instance to some
/// sort of class type.
const void *
swift::swift_dynamicCastUnknownClass(const void *object,
const Metadata *targetType) {
switch (targetType->getKind()) {
case MetadataKind::Class: {
auto targetClassType = static_cast<const ClassMetadata *>(targetType);
return swift_dynamicCastClass(object, targetClassType);
}
case MetadataKind::ObjCClassWrapper: {
#if SWIFT_OBJC_INTEROP
auto targetClassType
= static_cast<const ObjCClassWrapperMetadata *>(targetType)->Class;
return swift_dynamicCastObjCClass(object, targetClassType);
#else
_failCorruptType(targetType);
#endif
}
case MetadataKind::ForeignClass: {
#if SWIFT_OBJC_INTEROP
auto targetClassType = static_cast<const ForeignClassMetadata*>(targetType);
return swift_dynamicCastForeignClass(object, targetClassType);
#else
_failCorruptType(targetType);
#endif
}
case MetadataKind::Existential: {
return _dynamicCastUnknownClassToExistential(object,
static_cast<const ExistentialTypeMetadata *>(targetType));
}
case MetadataKind::ExistentialMetatype:
case MetadataKind::Function:
case MetadataKind::HeapLocalVariable:
case MetadataKind::HeapGenericLocalVariable:
case MetadataKind::ErrorObject:
case MetadataKind::Metatype:
case MetadataKind::Enum:
case MetadataKind::Optional:
case MetadataKind::Opaque:
case MetadataKind::Struct:
case MetadataKind::Tuple:
return nullptr;
}
_failCorruptType(targetType);
}
/// Perform a dynamic class of some sort of class instance to some
/// sort of class type.
const void *
swift::swift_dynamicCastUnknownClassUnconditional(const void *object,
const Metadata *targetType) {
switch (targetType->getKind()) {
case MetadataKind::Class: {
auto targetClassType = static_cast<const ClassMetadata *>(targetType);
return swift_dynamicCastClassUnconditional(object, targetClassType);
}
case MetadataKind::ObjCClassWrapper: {
#if SWIFT_OBJC_INTEROP
auto targetClassType
= static_cast<const ObjCClassWrapperMetadata *>(targetType)->Class;
return swift_dynamicCastObjCClassUnconditional(object, targetClassType);
#else
_failCorruptType(targetType);
#endif
}
case MetadataKind::ForeignClass: {
#if SWIFT_OBJC_INTEROP
auto targetClassType = static_cast<const ForeignClassMetadata*>(targetType);
return swift_dynamicCastForeignClassUnconditional(object, targetClassType);
#else
_failCorruptType(targetType);
#endif
}
case MetadataKind::Existential: {
// We can cast to ObjC existentials. Non-ObjC existentials don't have
// a single-refcounted-pointer representation.
if (auto result = _dynamicCastUnknownClassToExistential(object,
static_cast<const ExistentialTypeMetadata *>(targetType)))
return result;
swift_dynamicCastFailure(_swift_getClass(object), targetType);
}
case MetadataKind::ExistentialMetatype:
case MetadataKind::Function:
case MetadataKind::HeapLocalVariable:
case MetadataKind::HeapGenericLocalVariable:
case MetadataKind::ErrorObject:
case MetadataKind::Metatype:
case MetadataKind::Enum:
case MetadataKind::Optional:
case MetadataKind::Opaque:
case MetadataKind::Struct:
case MetadataKind::Tuple:
swift_dynamicCastFailure(_swift_getClass(object), targetType);
}
_failCorruptType(targetType);
}
/******************************************************************************/
/********************************* Metatypes **********************************/
/******************************************************************************/
const Metadata *
swift::swift_dynamicCastMetatype(const Metadata *sourceType,
const Metadata *targetType) {
auto origSourceType = sourceType;
switch (targetType->getKind()) {
case MetadataKind::ObjCClassWrapper:
// Get the actual class object.
targetType = static_cast<const ObjCClassWrapperMetadata*>(targetType)
->Class;
SWIFT_FALLTHROUGH;
case MetadataKind::Class:
// The source value must also be a class; otherwise the cast fails.
switch (sourceType->getKind()) {
case MetadataKind::ObjCClassWrapper:
// Get the actual class object.
sourceType = static_cast<const ObjCClassWrapperMetadata*>(sourceType)
->Class;
SWIFT_FALLTHROUGH;
case MetadataKind::Class: {
// Check if the source is a subclass of the target.
#if SWIFT_OBJC_INTEROP
// We go through ObjC lookup to deal with potential runtime magic in ObjC
// land.
if (swift_dynamicCastObjCClassMetatype((const ClassMetadata*)sourceType,
(const ClassMetadata*)targetType))
return origSourceType;
#else
if (_dynamicCastClassMetatype((const ClassMetadata*)sourceType,
(const ClassMetadata*)targetType))
return origSourceType;
#endif
return nullptr;
}
case MetadataKind::ForeignClass: {
// Check if the source is a subclass of the target.
if (swift_dynamicCastForeignClassMetatype(
(const ClassMetadata*)sourceType,
(const ClassMetadata*)targetType))
return origSourceType;
return nullptr;
}
case MetadataKind::Existential:
case MetadataKind::ExistentialMetatype:
case MetadataKind::Function:
case MetadataKind::HeapLocalVariable:
case MetadataKind::HeapGenericLocalVariable:
case MetadataKind::ErrorObject:
case MetadataKind::Metatype:
case MetadataKind::Enum:
case MetadataKind::Optional:
case MetadataKind::Opaque:
case MetadataKind::Struct:
case MetadataKind::Tuple:
return nullptr;
}
break;
case MetadataKind::ForeignClass:
switch (sourceType->getKind()) {
case MetadataKind::ObjCClassWrapper:
// Get the actual class object.
sourceType = static_cast<const ObjCClassWrapperMetadata*>(sourceType)
->Class;
SWIFT_FALLTHROUGH;
case MetadataKind::Class:
case MetadataKind::ForeignClass:
// Check if the source is a subclass of the target.
if (swift_dynamicCastForeignClassMetatype(
(const ClassMetadata*)sourceType,
(const ClassMetadata*)targetType))
return origSourceType;
return nullptr;
case MetadataKind::Existential:
case MetadataKind::ExistentialMetatype:
case MetadataKind::Function:
case MetadataKind::HeapLocalVariable:
case MetadataKind::HeapGenericLocalVariable:
case MetadataKind::ErrorObject:
case MetadataKind::Metatype:
case MetadataKind::Enum:
case MetadataKind::Optional:
case MetadataKind::Opaque:
case MetadataKind::Struct:
case MetadataKind::Tuple:
return nullptr;
}
break;
case MetadataKind::Existential:
case MetadataKind::ExistentialMetatype:
case MetadataKind::Function:
case MetadataKind::HeapLocalVariable:
case MetadataKind::HeapGenericLocalVariable:
case MetadataKind::ErrorObject:
case MetadataKind::Metatype:
case MetadataKind::Enum:
case MetadataKind::Optional:
case MetadataKind::Opaque:
case MetadataKind::Struct:
case MetadataKind::Tuple:
// The cast succeeds only if the metadata pointers are statically
// equivalent.
if (sourceType != targetType)
return nullptr;
return origSourceType;
}
}
const Metadata *
swift::swift_dynamicCastMetatypeUnconditional(const Metadata *sourceType,
const Metadata *targetType) {
auto origSourceType = sourceType;
switch (targetType->getKind()) {
case MetadataKind::ObjCClassWrapper:
// Get the actual class object.
targetType = static_cast<const ObjCClassWrapperMetadata*>(targetType)
->Class;
SWIFT_FALLTHROUGH;
case MetadataKind::Class:
// The source value must also be a class; otherwise the cast fails.
switch (sourceType->getKind()) {
case MetadataKind::ObjCClassWrapper:
// Get the actual class object.
sourceType = static_cast<const ObjCClassWrapperMetadata*>(sourceType)
->Class;
SWIFT_FALLTHROUGH;
case MetadataKind::Class: {
// Check if the source is a subclass of the target.
#if SWIFT_OBJC_INTEROP
// We go through ObjC lookup to deal with potential runtime magic in ObjC
// land.
swift_dynamicCastObjCClassMetatypeUnconditional(
(const ClassMetadata*)sourceType,
(const ClassMetadata*)targetType);
#else
if (!_dynamicCastClassMetatype((const ClassMetadata*)sourceType,
(const ClassMetadata*)targetType))
swift_dynamicCastFailure(sourceType, targetType);
#endif
// If we returned, then the cast succeeded.
return origSourceType;
}
case MetadataKind::ForeignClass: {
// Check if the source is a subclass of the target.
swift_dynamicCastForeignClassMetatypeUnconditional(
(const ClassMetadata*)sourceType,
(const ClassMetadata*)targetType);
// If we returned, then the cast succeeded.
return origSourceType;
}
case MetadataKind::Existential:
case MetadataKind::ExistentialMetatype:
case MetadataKind::Function:
case MetadataKind::HeapLocalVariable:
case MetadataKind::HeapGenericLocalVariable:
case MetadataKind::ErrorObject:
case MetadataKind::Metatype:
case MetadataKind::Enum:
case MetadataKind::Optional:
case MetadataKind::Opaque:
case MetadataKind::Struct:
case MetadataKind::Tuple:
swift_dynamicCastFailure(sourceType, targetType);
}
break;
case MetadataKind::ForeignClass:
// The source value must also be a class; otherwise the cast fails.
switch (sourceType->getKind()) {
case MetadataKind::ObjCClassWrapper:
// Get the actual class object.
sourceType = static_cast<const ObjCClassWrapperMetadata*>(sourceType)
->Class;
SWIFT_FALLTHROUGH;
case MetadataKind::Class:
case MetadataKind::ForeignClass:
// Check if the source is a subclass of the target.
swift_dynamicCastForeignClassMetatypeUnconditional(
(const ClassMetadata*)sourceType,
(const ClassMetadata*)targetType);
// If we returned, then the cast succeeded.
return origSourceType;
case MetadataKind::Existential:
case MetadataKind::ExistentialMetatype:
case MetadataKind::Function:
case MetadataKind::HeapLocalVariable:
case MetadataKind::HeapGenericLocalVariable:
case MetadataKind::ErrorObject:
case MetadataKind::Metatype:
case MetadataKind::Enum:
case MetadataKind::Optional:
case MetadataKind::Opaque:
case MetadataKind::Struct:
case MetadataKind::Tuple:
swift_dynamicCastFailure(sourceType, targetType);
}
break;
case MetadataKind::Existential:
case MetadataKind::ExistentialMetatype:
case MetadataKind::Function:
case MetadataKind::HeapLocalVariable:
case MetadataKind::HeapGenericLocalVariable:
case MetadataKind::ErrorObject:
case MetadataKind::Metatype:
case MetadataKind::Enum:
case MetadataKind::Optional:
case MetadataKind::Opaque:
case MetadataKind::Struct:
case MetadataKind::Tuple:
// The cast succeeds only if the metadata pointers are statically
// equivalent.
if (sourceType != targetType)
swift_dynamicCastFailure(sourceType, targetType);
return origSourceType;
}
}
/******************************************************************************/
/********************************** Classes ***********************************/
/******************************************************************************/
#if SWIFT_OBJC_INTEROP
/// Do a dynamic cast to the target class.
static void *_dynamicCastUnknownClass(void *object,
const Metadata *targetType,
bool unconditional) {
// The unconditional path avoids some failure logic.
if (unconditional) {
return const_cast<void*>(
swift_dynamicCastUnknownClassUnconditional(object, targetType));
}
return const_cast<void*>(swift_dynamicCastUnknownClass(object, targetType));
}
#endif
static bool _dynamicCastUnknownClassIndirect(OpaqueValue *dest,
void *object,
const Metadata *targetType,
DynamicCastFlags flags) {
void **destSlot = reinterpret_cast<void **>(dest);
// The unconditional path avoids some failure logic.
if (flags & DynamicCastFlags::Unconditional) {
void *result = const_cast<void*>(
swift_dynamicCastUnknownClassUnconditional(object, targetType));
*destSlot = result;
if (!(flags & DynamicCastFlags::TakeOnSuccess)) {
swift_unknownRetain(result);
}
return true;
}
// Okay, we're doing a conditional cast.
void *result =
const_cast<void*>(swift_dynamicCastUnknownClass(object, targetType));
assert(result == nullptr || object == result);
// If the cast failed, destroy the input and return false.
if (!result) {
if (flags & DynamicCastFlags::DestroyOnFailure) {
swift_unknownRelease(object);
}
return false;
}
// Otherwise, store to the destination and return true.
*destSlot = result;
if (!(flags & DynamicCastFlags::TakeOnSuccess)) {
swift_unknownRetain(result);
}
return true;
}
/******************************************************************************/
/******************************** Existentials ********************************/
/******************************************************************************/
#if SWIFT_OBJC_INTEROP
extern "C" const ProtocolDescriptor _TMps5Error;
static const WitnessTable *findErrorWitness(const Metadata *srcType) {
return swift_conformsToProtocol(srcType, &_TMps5Error);
}
#endif
/// Perform a dynamic cast from an existential type to some kind of
/// class type.
static bool _dynamicCastToUnknownClassFromExistential(OpaqueValue *dest,
OpaqueValue *src,
const ExistentialTypeMetadata *srcType,
const Metadata *targetType,
DynamicCastFlags flags) {
switch (srcType->getRepresentation()) {
case ExistentialTypeRepresentation::Class: {
auto classContainer =
reinterpret_cast<ClassExistentialContainer*>(src);
void *obj = classContainer->Value;
#if SWIFT_OBJC_INTEROP
// If we're casting to NSError, we may need a representation change,
// so fall into the general swift_dynamicCast path.
if (targetType == getNSErrorMetadata()) {
return swift_dynamicCast(dest, src, swift_getObjectType((HeapObject*)obj),
targetType, flags);
}
#endif
return _dynamicCastUnknownClassIndirect(dest, obj, targetType, flags);
}
case ExistentialTypeRepresentation::Opaque: {
auto opaqueContainer =
reinterpret_cast<OpaqueExistentialContainer*>(src);
auto srcCapturedType = opaqueContainer->Type;
OpaqueValue *srcValue =
srcCapturedType->vw_projectBuffer(&opaqueContainer->Buffer);
bool result = swift_dynamicCast(dest,
srcValue,
srcCapturedType,
targetType,
flags);
if (src != srcValue)
_maybeDeallocateOpaqueExistential(src, result, flags);
return result;
}
case ExistentialTypeRepresentation::Error: {
const SwiftError *errorBox =
*reinterpret_cast<const SwiftError * const *>(src);
auto srcCapturedType = errorBox->getType();
const OpaqueValue *srcValue;
// A bridged NSError is itself the value.
if (errorBox->isPureNSError())
srcValue = src;
else
srcValue = errorBox->getValue();
// We can't take or destroy the value out of the box since it might be
// shared.
auto subFlags = flags - (DynamicCastFlags::TakeOnSuccess
| DynamicCastFlags::DestroyOnFailure);
bool result = swift_dynamicCast(dest,
const_cast<OpaqueValue*>(srcValue),
srcCapturedType, targetType,
subFlags);
if (shouldDeallocateSource(result, flags))
srcType->vw_destroy(src);
return result;
}
}
}
static void unwrapExistential(OpaqueValue *src,
const ExistentialTypeMetadata *srcType,
OpaqueValue *&srcValue,
const Metadata *&srcCapturedType,
bool &isOutOfLine,
bool &canTake) {
switch (srcType->getRepresentation()) {
case ExistentialTypeRepresentation::Class: {
auto classContainer =
reinterpret_cast<const ClassExistentialContainer*>(src);
srcValue = (OpaqueValue*) &classContainer->Value;
void *obj = classContainer->Value;
srcCapturedType = swift_getObjectType(reinterpret_cast<HeapObject*>(obj));
isOutOfLine = false;
canTake = true;
break;
}
case ExistentialTypeRepresentation::Opaque: {
auto opaqueContainer = reinterpret_cast<OpaqueExistentialContainer*>(src);
srcCapturedType = opaqueContainer->Type;
srcValue = srcCapturedType->vw_projectBuffer(&opaqueContainer->Buffer);
isOutOfLine = (src != srcValue);
canTake = true;
break;
}
case ExistentialTypeRepresentation::Error: {
const SwiftError *errorBox
= *reinterpret_cast<const SwiftError * const *>(src);
srcCapturedType = errorBox->getType();
// A bridged NSError is itself the value.
if (errorBox->isPureNSError())
srcValue = src;
else
srcValue = const_cast<OpaqueValue*>(errorBox->getValue());
// The value is out-of-line, but we can't take it, since it may be shared.
isOutOfLine = true;
canTake = false;
break;
}
}
}
/// Perform a dynamic cast from an existential type to a
/// non-existential type.
static bool _dynamicCastFromExistential(OpaqueValue *dest,
OpaqueValue *src,
const ExistentialTypeMetadata *srcType,
const Metadata *targetType,
DynamicCastFlags flags) {
OpaqueValue *srcValue;
const Metadata *srcCapturedType;
bool isOutOfLine;
bool canTake;
unwrapExistential(src, srcType,
srcValue, srcCapturedType, isOutOfLine, canTake);
auto subFlags = flags;
if (!canTake)
subFlags = subFlags - (DynamicCastFlags::DestroyOnFailure
| DynamicCastFlags::TakeOnSuccess);
bool result = swift_dynamicCast(dest, srcValue, srcCapturedType,
targetType, subFlags);
if (!canTake) {
// swift_dynamicCast performed no memory management.
// Destroy the value if requested.
if (shouldDeallocateSource(result, flags))
srcType->vw_destroy(src);
} else {
// swift_dynamicCast took or destroyed the value as per the original request
// We may still have an opaque existential container to deallocate.
if (isOutOfLine) {
assert(srcType->getRepresentation()
== ExistentialTypeRepresentation::Opaque);
_maybeDeallocateOpaqueExistential(src, result, flags);
}
}
return result;
}
/******************************************************************************/
/********************************* Metatypes **********************************/
/******************************************************************************/
/// Perform a dynamic cast of a metatype to a metatype.
///
/// Note that the check is whether 'metatype' is an *instance of*
/// 'targetType', not a *subtype of it*.
static bool _dynamicCastMetatypeToMetatype(OpaqueValue *dest,
const Metadata *metatype,
const MetatypeMetadata *targetType,
DynamicCastFlags flags) {
const Metadata *result;
if (flags & DynamicCastFlags::Unconditional) {
result = swift_dynamicCastMetatypeUnconditional(metatype,
targetType->InstanceType);
} else {
result = swift_dynamicCastMetatype(metatype, targetType->InstanceType);
if (!result) return false;
}
*((const Metadata **) dest) = result;
return true;
}
/// Check whether an unknown class instance is actually a class object.
static const Metadata *_getUnknownClassAsMetatype(void *object) {
#if SWIFT_OBJC_INTEROP
// Objective-C class metadata are objects, so an AnyObject (or NSObject)
// may refer to a class object.
// Test whether the object's isa is a metaclass, which indicates that the
// object is a class.
Class isa = object_getClass((id)object);
if (class_isMetaClass(isa)) {
return swift_getObjCClassMetadata((const ClassMetadata *)object);
}
#endif
// Class values are currently never metatypes in the native runtime.
return nullptr;
}
/// Perform a dynamic cast of a class value to a metatype type.
static bool _dynamicCastUnknownClassToMetatype(OpaqueValue *dest,
void *object,
const MetatypeMetadata *targetType,
DynamicCastFlags flags) {
if (auto metatype = _getUnknownClassAsMetatype(object))
return _dynamicCastMetatypeToMetatype(dest, metatype, targetType, flags);
if (flags & DynamicCastFlags::Unconditional)
swift_dynamicCastFailure(_swift_getClass(object), targetType);
if (flags & DynamicCastFlags::DestroyOnFailure)
swift_unknownRelease((HeapObject*) object);
return false;
}
/// Perform a dynamic cast to a metatype type.
static bool _dynamicCastToMetatype(OpaqueValue *dest,
OpaqueValue *src,
const Metadata *srcType,
const MetatypeMetadata *targetType,
DynamicCastFlags flags) {
switch (srcType->getKind()) {
case MetadataKind::Metatype: {
const Metadata *srcMetatype = *(const Metadata * const *) src;
return _dynamicCastMetatypeToMetatype(dest, srcMetatype,
targetType, flags);
}
case MetadataKind::ExistentialMetatype: {
const Metadata *srcMetatype = *(const Metadata * const *) src;
return _dynamicCastMetatypeToMetatype(dest, srcMetatype,
targetType, flags);
}
case MetadataKind::Existential: {
auto srcExistentialType = cast<ExistentialTypeMetadata>(srcType);
switch (srcExistentialType->getRepresentation()) {
case ExistentialTypeRepresentation::Class: {
auto srcExistential = (ClassExistentialContainer*) src;
return _dynamicCastUnknownClassToMetatype(dest,
srcExistential->Value,
targetType, flags);
}
case ExistentialTypeRepresentation::Opaque: {
auto srcExistential = (OpaqueExistentialContainer*) src;
auto srcValueType = srcExistential->Type;
auto srcValue = srcValueType->vw_projectBuffer(&srcExistential->Buffer);
bool result = _dynamicCastToMetatype(dest, srcValue, srcValueType,
targetType, flags);
if (src != srcValue)
_maybeDeallocateOpaqueExistential(src, result, flags);
return result;
}
case ExistentialTypeRepresentation::Error: {
const SwiftError *srcBox
= *reinterpret_cast<const SwiftError * const *>(src);
auto srcValueType = srcBox->getType();
const OpaqueValue *srcValue;
if (srcBox->isPureNSError())
srcValue = src;
else
srcValue = srcBox->getValue();
// Can't take from a box since the value may be shared.
auto subFlags = flags - (DynamicCastFlags::TakeOnSuccess
| DynamicCastFlags::DestroyOnFailure);
bool result = _dynamicCastToMetatype(dest,
const_cast<OpaqueValue*>(srcValue),
srcValueType,
targetType, subFlags);
if (shouldDeallocateSource(result, flags))
srcType->vw_destroy(src);
return result;
}
}
}
case MetadataKind::Class:
case MetadataKind::ObjCClassWrapper:
case MetadataKind::ForeignClass: {
void *object = *reinterpret_cast<void**>(src);
return _dynamicCastUnknownClassToMetatype(dest, object, targetType, flags);
}
case MetadataKind::Function:
case MetadataKind::HeapLocalVariable:
case MetadataKind::HeapGenericLocalVariable:
case MetadataKind::ErrorObject:
case MetadataKind::Enum:
case MetadataKind::Optional:
case MetadataKind::Opaque:
case MetadataKind::Struct: // AnyHashable, if metatypes implement Hashable
case MetadataKind::Tuple:
return _fail(src, srcType, targetType, flags);
}
_failCorruptType(srcType);
}
/// Perform a dynamic cast of a metatype to an existential metatype type.
static bool _dynamicCastMetatypeToExistentialMetatype(OpaqueValue *dest,
const Metadata *srcMetatype,
const ExistentialMetatypeMetadata *targetType,
DynamicCastFlags flags,
bool writeDestMetatype = true) {
// The instance type of an existential metatype must be either an
// existential or an existential metatype.
auto destMetatype = reinterpret_cast<ExistentialMetatypeContainer*>(dest);
// If it's an existential, we need to check for conformances.
auto targetInstanceType = targetType->InstanceType;
if (auto targetInstanceTypeAsExistential =
dyn_cast<ExistentialTypeMetadata>(targetInstanceType)) {
// Check for conformance to all the protocols.
// TODO: collect the witness tables.
auto &protocols = targetInstanceTypeAsExistential->Protocols;
const WitnessTable **conformance
= writeDestMetatype ? destMetatype->getWitnessTables() : nullptr;
for (unsigned i = 0, n = protocols.NumProtocols; i != n; ++i) {
const ProtocolDescriptor *protocol = protocols[i];
if (!_conformsToProtocol(nullptr, srcMetatype, protocol, conformance)) {
if (flags & DynamicCastFlags::Unconditional)
swift_dynamicCastFailure(srcMetatype, targetType);
return false;
}
if (conformance && protocol->Flags.needsWitnessTable())
++conformance;
}
if (writeDestMetatype)
destMetatype->Value = srcMetatype;
return true;
}
// Otherwise, we're casting to SomeProtocol.Type.Type.
auto targetInstanceTypeAsMetatype =
cast<ExistentialMetatypeMetadata>(targetInstanceType);
// If the source type isn't a metatype, the cast fails.
auto srcMetatypeMetatype = dyn_cast<MetatypeMetadata>(srcMetatype);
if (!srcMetatypeMetatype) {
if (flags & DynamicCastFlags::Unconditional)
swift_dynamicCastFailure(srcMetatype, targetType);
return false;
}
// The representation of an existential metatype remains consistent
// arbitrarily deep: a metatype, followed by some protocols. The
// protocols are the same at every level, so we can just set the
// metatype correctly and then recurse, letting the recursive call
// fill in the conformance information correctly.
// Proactively set the destination metatype so that we can tail-recur,
// unless we've already done so. There's no harm in doing this even if
// the cast fails.
if (writeDestMetatype)
*((const Metadata **) dest) = srcMetatype;
// Recurse.
auto srcInstanceType = srcMetatypeMetatype->InstanceType;
return _dynamicCastMetatypeToExistentialMetatype(dest, srcInstanceType,
targetInstanceTypeAsMetatype,
flags,
/*overwrite*/ false);
}
/// Perform a dynamic cast of a class value to an existential metatype type.
static bool _dynamicCastUnknownClassToExistentialMetatype(OpaqueValue *dest,
void *object,
const ExistentialMetatypeMetadata *targetType,
DynamicCastFlags flags) {
if (auto metatype = _getUnknownClassAsMetatype(object))
return _dynamicCastMetatypeToExistentialMetatype(dest, metatype,
targetType, flags);
// Class values are currently never metatypes (?).
if (flags & DynamicCastFlags::Unconditional)
swift_dynamicCastFailure(_swift_getClass(object), targetType);
if (flags & DynamicCastFlags::DestroyOnFailure)
swift_unknownRelease((HeapObject*) object);
return false;
}
/// Perform a dynamic cast to an existential metatype type.
static bool _dynamicCastToExistentialMetatype(OpaqueValue *dest,
OpaqueValue *src,
const Metadata *srcType,
const ExistentialMetatypeMetadata *targetType,
DynamicCastFlags flags) {
switch (srcType->getKind()) {
case MetadataKind::Metatype: {
const Metadata *srcMetatype = *(const Metadata * const *) src;
return _dynamicCastMetatypeToExistentialMetatype(dest, srcMetatype,
targetType, flags);
}
// TODO: take advantage of protocol conformances already known.
case MetadataKind::ExistentialMetatype: {
const Metadata *srcMetatype = *(const Metadata * const *) src;
return _dynamicCastMetatypeToExistentialMetatype(dest, srcMetatype,
targetType, flags);
}
case MetadataKind::Existential: {
auto srcExistentialType = cast<ExistentialTypeMetadata>(srcType);
switch (srcExistentialType->getRepresentation()) {
case ExistentialTypeRepresentation::Class: {
auto srcExistential = (ClassExistentialContainer*) src;
return _dynamicCastUnknownClassToExistentialMetatype(dest,
srcExistential->Value,
targetType, flags);
}
case ExistentialTypeRepresentation::Opaque: {
auto srcExistential = (OpaqueExistentialContainer*) src;
auto srcValueType = srcExistential->Type;
auto srcValue = srcValueType->vw_projectBuffer(&srcExistential->Buffer);
bool result = _dynamicCastToExistentialMetatype(dest, srcValue, srcValueType,
targetType, flags);
if (src != srcValue)
_maybeDeallocateOpaqueExistential(src, result, flags);
return result;
}
case ExistentialTypeRepresentation::Error: {
const SwiftError *srcBox
= *reinterpret_cast<const SwiftError * const *>(src);
auto srcValueType = srcBox->getType();
const OpaqueValue *srcValue;
if (srcBox->isPureNSError())
srcValue = src;
else
srcValue = srcBox->getValue();
// Can't take from a box since the value may be shared.
auto subFlags = flags - (DynamicCastFlags::TakeOnSuccess
| DynamicCastFlags::DestroyOnFailure);
bool result = _dynamicCastToExistentialMetatype(dest,
const_cast<OpaqueValue*>(srcValue),
srcValueType,
targetType, subFlags);
if (shouldDeallocateSource(result, flags))
srcType->vw_destroy(src);
return result;
}
}
}
case MetadataKind::Class:
case MetadataKind::ObjCClassWrapper:
case MetadataKind::ForeignClass: {
void *object = *reinterpret_cast<void**>(src);
return _dynamicCastUnknownClassToExistentialMetatype(dest, object,
targetType, flags);
}
case MetadataKind::Function:
case MetadataKind::HeapLocalVariable:
case MetadataKind::HeapGenericLocalVariable:
case MetadataKind::ErrorObject:
case MetadataKind::Enum:
case MetadataKind::Optional:
case MetadataKind::Opaque:
case MetadataKind::Struct: // AnyHashable, if metatypes implement Hashable
case MetadataKind::Tuple:
return _fail(src, srcType, targetType, flags);
}
_failCorruptType(srcType);
}
/******************************************************************************/
/********************************* Functions **********************************/
/******************************************************************************/
static bool _dynamicCastToFunction(OpaqueValue *dest,
OpaqueValue *src,
const Metadata *srcType,
const FunctionTypeMetadata *targetType,
DynamicCastFlags flags) {
// Function casts succeed on exact matches, or if the target type is
// throwier than the source type.
//
// TODO: We could also allow ABI-compatible variance, such as casting
// a dynamic Base -> Derived to Derived -> Base. We wouldn't be able to
// perform a dynamic cast that required any ABI adjustment without a JIT
// though.
// Check for an exact type match first.
if (srcType == targetType) {
return _succeed(dest, src, srcType, flags);
}
switch (srcType->getKind()) {
case MetadataKind::Function: {
auto srcFn = static_cast<const FunctionTypeMetadata *>(srcType);
auto targetFn = static_cast<const FunctionTypeMetadata *>(targetType);
// Check that argument counts and convention match. "throws" can vary.
if (srcFn->Flags.withThrows(false) != targetFn->Flags.withThrows(false))
return _fail(src, srcType, targetType, flags);
// If the target type can't throw, neither can the source.
if (srcFn->throws() && !targetFn->throws())
return _fail(src, srcType, targetType, flags);
// The result and argument types must match.
if (srcFn->ResultType != targetFn->ResultType)
return _fail(src, srcType, targetType, flags);
if (srcFn->getNumArguments() != targetFn->getNumArguments())
return _fail(src, srcType, targetType, flags);
for (unsigned i = 0, e = srcFn->getNumArguments(); i < e; ++i)
if (srcFn->getArguments()[i] != targetFn->getArguments()[i])
return _fail(src, srcType, targetType, flags);
return _succeed(dest, src, srcType, flags);
}
case MetadataKind::Existential:
return _dynamicCastFromExistential(dest, src,
static_cast<const ExistentialTypeMetadata*>(srcType),
targetType, flags);
case MetadataKind::Class:
case MetadataKind::Struct:
case MetadataKind::Enum:
case MetadataKind::Optional:
case MetadataKind::ObjCClassWrapper:
case MetadataKind::ForeignClass:
case MetadataKind::ExistentialMetatype:
case MetadataKind::HeapLocalVariable:
case MetadataKind::HeapGenericLocalVariable:
case MetadataKind::ErrorObject:
case MetadataKind::Metatype:
case MetadataKind::Opaque:
case MetadataKind::Tuple:
return _fail(src, srcType, targetType, flags);
}
}
/******************************************************************************/
/****************************** Bridging NSError ******************************/
/******************************************************************************/
#if SWIFT_OBJC_INTEROP
static id dynamicCastValueToNSError(OpaqueValue *src,
const Metadata *srcType,
const WitnessTable *srcErrorWitness,
DynamicCastFlags flags) {
// Check whether there is an embedded NSError.
if (auto embedded =
swift_stdlib_getErrorEmbeddedNSErrorIndirect(src, srcType,
srcErrorWitness)) {
if (flags & DynamicCastFlags::TakeOnSuccess)
srcType->vw_destroy(src);
return embedded;
}
BoxPair errorBox = swift_allocError(srcType, srcErrorWitness, src,
/*isTake*/ flags & DynamicCastFlags::TakeOnSuccess);
return swift_bridgeErrorToNSError((SwiftError*)errorBox.first);
}
#endif
/******************************************************************************/
/********************************* Optionals **********************************/
/******************************************************************************/
namespace {
struct OptionalCastResult {
bool success;
const Metadata* payloadType;
};
}
/// Handle optional unwrapping of the cast source.
/// \returns {true, nullptr} if the cast succeeds without unwrapping.
/// \returns {false, nullptr} if the cast fails before unwrapping.
/// \returns {false, payloadType} if the cast should be attempted using an
/// equivalent payloadType.
static OptionalCastResult
checkDynamicCastFromOptional(OpaqueValue *dest,
OpaqueValue *src,
const Metadata *srcType,
const Metadata *targetType,
DynamicCastFlags flags) {
if (srcType->getKind() != MetadataKind::Optional)
return {false, srcType};
// Check if the target is an existential that Optional always conforms to.
if (targetType->getKind() == MetadataKind::Existential) {
// Attempt a conditional cast without destroying on failure.
DynamicCastFlags checkCastFlags
= flags - (DynamicCastFlags::Unconditional
| DynamicCastFlags::DestroyOnFailure);
assert((checkCastFlags - DynamicCastFlags::TakeOnSuccess)
== DynamicCastFlags::Default && "Unhandled DynamicCastFlag");
if (_dynamicCastToExistential(dest, src, srcType,
cast<ExistentialTypeMetadata>(targetType),
checkCastFlags)) {
return {true, nullptr};
}
}
const Metadata *payloadType =
cast<EnumMetadata>(srcType)->getGenericArgs()[0];
int enumCase =
swift_getEnumCaseSinglePayload(src, payloadType, 1 /*emptyCases=*/);
if (enumCase != -1) {
// Allow Optional<T>.none -> Optional<U>.none
if (targetType->getKind() != MetadataKind::Optional) {
_fail(src, srcType, targetType, flags);
return {false, nullptr};
}
// Get the destination payload type
const Metadata *targetPayloadType =
cast<EnumMetadata>(targetType)->getGenericArgs()[0];
// Inject the .none tag
swift_storeEnumTagSinglePayload(dest, targetPayloadType, enumCase,
1 /*emptyCases=*/);
// We don't have to destroy the source, because it was nil.
return {true, nullptr};
}
// .Some
// Single payload enums are guaranteed layout compatible with their
// payload. Only the source's payload needs to be taken or destroyed.
return {false, payloadType};
}
/******************************************************************************/
/**************************** Bridging _SwiftValue ****************************/
/******************************************************************************/
#if SWIFT_OBJC_INTEROP
/// Try to unbox a _SwiftValue box to perform a dynamic cast.
static bool tryDynamicCastBoxedSwiftValue(OpaqueValue *dest,
OpaqueValue *src,
const Metadata *srcType,
const Metadata *targetType,
DynamicCastFlags flags) {
// Swift type should be AnyObject or a class type.
if (!srcType->isAnyClass()) {
auto existential = dyn_cast<ExistentialTypeMetadata>(srcType);
if (!existential ||
existential->Flags.getSpecialProtocol()
!= SpecialProtocol::AnyObject)
return false;
}
id srcObject;
memcpy(&srcObject, src, sizeof(id));
// Do we have a _SwiftValue?
_SwiftValue *srcSwiftValue = getAsSwiftValue(srcObject);
if (!srcSwiftValue)
return false;
// If so, extract the boxed value and try to cast it.
const Metadata *boxedType;
const OpaqueValue *boxedValue;
std::tie(boxedType, boxedValue)
= getValueFromSwiftValue(srcSwiftValue);
// We can't touch the value from the box because it may be
// multiply-referenced.
// TODO: Check for uniqueness and consume if box is unique?
// Does the boxed type exactly match the target type we're looking for?
if (boxedType == targetType) {
targetType->vw_initializeWithCopy(dest,
const_cast<OpaqueValue*>(boxedValue));
// Release the box if we need to.
if (flags & DynamicCastFlags::TakeOnSuccess)
objc_release((id)srcSwiftValue);
return true;
}
// Maybe we can cast the boxed value to our destination type somehow.
auto innerFlags = flags - DynamicCastFlags::TakeOnSuccess
- DynamicCastFlags::DestroyOnFailure;
if (swift_dynamicCast(dest, const_cast<OpaqueValue*>(boxedValue),
boxedType, targetType, innerFlags)) {
// Release the box if we need to.
if (flags & DynamicCastFlags::TakeOnSuccess)
objc_release((id)srcSwiftValue);
return true;
}
return false;
}
#endif
/******************************************************************************/
/******************************** Collections *********************************/
/******************************************************************************/
/// Nominal type descriptor for Swift.Array.
extern "C" const NominalTypeDescriptor _TMnSa;
/// Nominal type descriptor for Swift.Dictionary.
extern "C" const NominalTypeDescriptor _TMnVs10Dictionary;
/// Nominal type descriptor for Swift.Set.
extern "C" const NominalTypeDescriptor _TMnVs3Set;
SWIFT_CC(swift)
extern "C"
void _swift_arrayDownCastIndirect(OpaqueValue *destination,
OpaqueValue *source,
const Metadata *sourceValueType,
const Metadata *targetValueType);
SWIFT_CC(swift)
extern "C"
bool _swift_arrayDownCastConditionalIndirect(OpaqueValue *destination,
OpaqueValue *source,
const Metadata *sourceValueType,
const Metadata *targetValueType);
SWIFT_CC(swift)
extern "C"
void _swift_setDownCastIndirect(OpaqueValue *destination,
OpaqueValue *source,
const Metadata *sourceValueType,
const Metadata *targetValueType);
SWIFT_CC(swift)
extern "C"
bool _swift_setDownCastConditionalIndirect(OpaqueValue *destination,
OpaqueValue *source,
const Metadata *sourceValueType,
const Metadata *targetValueType);
SWIFT_CC(swift)
extern "C"
void _swift_dictionaryDownCastIndirect(OpaqueValue *destination,
OpaqueValue *source,
const Metadata *sourceKeyType,
const Metadata *sourceValueType,
const Metadata *targetKeyType,
const Metadata *targetValueType);
SWIFT_CC(swift)
extern "C"
bool _swift_dictionaryDownCastConditionalIndirect(OpaqueValue *destination,
OpaqueValue *source,
const Metadata *sourceKeyType,
const Metadata *sourceValueType,
const Metadata *targetKeyType,
const Metadata *targetValueType);
static bool _dynamicCastStructToStruct(OpaqueValue *destination,
OpaqueValue *source,
const StructMetadata *sourceType,
const StructMetadata *targetType,
DynamicCastFlags flags) {
if (sourceType == targetType)
return _succeed(destination, source, sourceType, flags);
// The two types have to be instantiations of the same type.
auto descriptor = sourceType->Description.get();
auto targetDescriptor = targetType->Description.get();
if (descriptor != targetDescriptor) {
if (descriptor == &_TMnVs11AnyHashable) {
return _dynamicCastFromAnyHashable(destination, source,
sourceType, targetType, flags);
} else if (targetDescriptor == &_TMnVs11AnyHashable) {
return _dynamicCastToAnyHashable(destination, source,
sourceType, targetType, flags);
} else {
return _fail(source, sourceType, targetType, flags);
}
}
auto sourceArgs = sourceType->getGenericArgs();
auto targetArgs = targetType->getGenericArgs();
bool result;
// Arrays.
if (descriptor == &_TMnSa) {
if (flags & DynamicCastFlags::Unconditional) {
_swift_arrayDownCastIndirect(source, destination,
sourceArgs[0], targetArgs[0]);
result = true;
} else {
result =
_swift_arrayDownCastConditionalIndirect(source, destination,
sourceArgs[0], targetArgs[0]);
}
// Dictionaries.
} else if (descriptor == &_TMnVs10Dictionary) {
if (flags & DynamicCastFlags::Unconditional) {
_swift_dictionaryDownCastIndirect(source, destination,
sourceArgs[0], sourceArgs[1],
targetArgs[0], targetArgs[1]);
result = true;
} else {
result =
_swift_dictionaryDownCastConditionalIndirect(source, destination,
sourceArgs[0], sourceArgs[1],
targetArgs[0], targetArgs[1]);
}
// Sets.
} else if (descriptor == &_TMnVs3Set) {
if (flags & DynamicCastFlags::Unconditional) {
_swift_setDownCastIndirect(source, destination,
sourceArgs[0], targetArgs[0]);
result = true;
} else {
result =
_swift_setDownCastConditionalIndirect(source, destination,
sourceArgs[0], targetArgs[0]);
}
// Other struct types don't support dynamic covariance for now.
} else {
return _fail(source, sourceType, targetType, flags);
}
// The intrinsics above never consume the source value.
bool shouldDestroySource =
result ? flags & DynamicCastFlags::TakeOnSuccess
: flags & DynamicCastFlags::DestroyOnFailure;
if (shouldDestroySource) {
sourceType->vw_destroy(source);
}
return result;
}
/******************************************************************************/
/****************************** Main Entrypoint *******************************/
/******************************************************************************/
/// Perform a dynamic cast to an arbitrary type.
SWIFT_RT_ENTRY_VISIBILITY
bool swift::swift_dynamicCast(OpaqueValue *dest,
OpaqueValue *src,
const Metadata *srcType,
const Metadata *targetType,
DynamicCastFlags flags)
SWIFT_CC(RegisterPreservingCC_IMPL) {
auto unwrapResult = checkDynamicCastFromOptional(dest, src, srcType,
targetType, flags);
srcType = unwrapResult.payloadType;
if (!srcType)
return unwrapResult.success;
#if SWIFT_OBJC_INTEROP
// A class or AnyObject reference may point at a boxed _SwiftValue.
if (tryDynamicCastBoxedSwiftValue(dest, src, srcType,
targetType, flags)) {
return true;
}
#endif
switch (targetType->getKind()) {
// Handle wrapping an Optional target.
case MetadataKind::Optional: {
// If the source is an existential, attempt to cast it first without
// unwrapping the target. This handles an optional source wrapped within an
// existential that Optional conforms to (Any).
if (auto srcExistentialType = dyn_cast<ExistentialTypeMetadata>(srcType)) {
return _dynamicCastFromExistential(dest, src, srcExistentialType,
targetType, flags);
}
// Recursively cast into the layout compatible payload area.
const Metadata *payloadType =
cast<EnumMetadata>(targetType)->getGenericArgs()[0];
if (swift_dynamicCast(dest, src, srcType, payloadType, flags)) {
swift_storeEnumTagSinglePayload(dest, payloadType, -1 /*case*/,
1 /*emptyCases*/);
return true;
}
return false;
}
// Casts to class type.
case MetadataKind::Class:
case MetadataKind::ObjCClassWrapper:
#if SWIFT_OBJC_INTEROP
// If the destination type is an NSError, and the source type is an
// Error, then the cast can succeed by NSError bridging.
if (targetType == getNSErrorMetadata()) {
// Don't rebridge if the source is already some kind of NSError.
if (srcType->isAnyClass()
&& swift_dynamicCastObjCClass(*reinterpret_cast<id*>(src),
static_cast<const ObjCClassWrapperMetadata*>(targetType)->Class))
return _succeed(dest, src, srcType, flags);
if (auto srcErrorWitness = findErrorWitness(srcType)) {
auto error = dynamicCastValueToNSError(src, srcType,
srcErrorWitness, flags);
*reinterpret_cast<id *>(dest) = error;
return true;
}
}
SWIFT_FALLTHROUGH;
#endif
case MetadataKind::ForeignClass:
switch (srcType->getKind()) {
case MetadataKind::Class:
case MetadataKind::ObjCClassWrapper:
case MetadataKind::ForeignClass: {
// Do a dynamic cast on the instance pointer.
void *object = *reinterpret_cast<void * const *>(src);
return _dynamicCastUnknownClassIndirect(dest, object,
targetType, flags);
}
case MetadataKind::Existential: {
auto srcExistentialType = cast<ExistentialTypeMetadata>(srcType);
return _dynamicCastToUnknownClassFromExistential(dest, src,
srcExistentialType,
targetType, flags);
}
case MetadataKind::Struct:
// If the source type is AnyHashable, cast from that.
if (isAnyHashableType(cast<StructMetadata>(srcType))) {
return _dynamicCastFromAnyHashable(dest, src, srcType,
targetType, flags);
}
SWIFT_FALLTHROUGH;
case MetadataKind::Enum:
case MetadataKind::Optional: {
#if SWIFT_OBJC_INTEROP
// If the source type is bridged to Objective-C, try to bridge.
if (auto srcBridgeWitness = findBridgeWitness(srcType)) {
return _dynamicCastValueToClassViaObjCBridgeable(dest, src, srcType,
targetType,
srcBridgeWitness,
flags);
}
#endif
return _fail(src, srcType, targetType, flags);
}
case MetadataKind::ExistentialMetatype:
case MetadataKind::Function:
case MetadataKind::HeapLocalVariable:
case MetadataKind::HeapGenericLocalVariable:
case MetadataKind::ErrorObject:
case MetadataKind::Metatype:
case MetadataKind::Opaque:
case MetadataKind::Tuple:
return _fail(src, srcType, targetType, flags);
}
break;
case MetadataKind::Existential:
return _dynamicCastToExistential(dest, src, srcType,
cast<ExistentialTypeMetadata>(targetType),
flags);
case MetadataKind::Metatype:
return _dynamicCastToMetatype(dest, src, srcType,
cast<MetatypeMetadata>(targetType),
flags);
case MetadataKind::ExistentialMetatype:
return _dynamicCastToExistentialMetatype(dest, src, srcType,
cast<ExistentialMetatypeMetadata>(targetType),
flags);
// Function types.
case MetadataKind::Function: {
return _dynamicCastToFunction(dest, src, srcType,
cast<FunctionTypeMetadata>(targetType),
flags);
}
case MetadataKind::Struct:
case MetadataKind::Enum:
switch (srcType->getKind()) {
case MetadataKind::Class:
case MetadataKind::ObjCClassWrapper:
case MetadataKind::ForeignClass: {
// Casts to AnyHashable.
if (isAnyHashableType(targetType)) {
return _dynamicCastToAnyHashable(dest, src, srcType, targetType, flags);
}
#if SWIFT_OBJC_INTEROP
// If the target type is bridged to Objective-C, try to bridge.
if (auto targetBridgeWitness = findBridgeWitness(targetType)) {
return _dynamicCastClassToValueViaObjCBridgeable(dest, src, srcType,
targetType,
targetBridgeWitness,
flags);
}
// If the source is an NSError, and the target is a bridgeable
// Error, try to bridge.
if (tryDynamicCastNSErrorToValue(dest, src, srcType, targetType, flags)) {
return true;
}
#endif
break;
}
case MetadataKind::Struct:
// Collection and AnyHashable casts.
if (targetType->getKind() == MetadataKind::Struct) {
return _dynamicCastStructToStruct(dest, src,
cast<StructMetadata>(srcType),
cast<StructMetadata>(targetType),
flags);
}
break;
case MetadataKind::Optional:
case MetadataKind::Enum:
// Casts to AnyHashable.
if (isAnyHashableType(targetType)) {
return _dynamicCastToAnyHashable(dest, src, srcType, targetType, flags);
}
break;
case MetadataKind::Existential:
case MetadataKind::ExistentialMetatype:
case MetadataKind::Function:
case MetadataKind::HeapLocalVariable:
case MetadataKind::HeapGenericLocalVariable:
case MetadataKind::ErrorObject:
case MetadataKind::Metatype:
case MetadataKind::Opaque:
case MetadataKind::Tuple:
break;
}
SWIFT_FALLTHROUGH;
// The non-polymorphic types.
case MetadataKind::HeapLocalVariable:
case MetadataKind::HeapGenericLocalVariable:
case MetadataKind::ErrorObject:
case MetadataKind::Opaque:
case MetadataKind::Tuple:
// If there's an exact type match, we're done.
if (srcType == targetType)
return _succeed(dest, src, srcType, flags);
// If we have an existential, look at its dynamic type.
if (auto srcExistentialType = dyn_cast<ExistentialTypeMetadata>(srcType)) {
return _dynamicCastFromExistential(dest, src, srcExistentialType,
targetType, flags);
}
// Otherwise, we have a failure.
return _fail(src, srcType, targetType, flags);
}
_failCorruptType(srcType);
}
static inline bool swift_isClassOrObjCExistentialTypeImpl(const Metadata *T) {
auto kind = T->getKind();
// Classes.
if (Metadata::isAnyKindOfClass(kind))
return true;
#if SWIFT_OBJC_INTEROP
// ObjC existentials.
if (kind == MetadataKind::Existential &&
static_cast<const ExistentialTypeMetadata *>(T)->isObjC())
return true;
// Blocks are ObjC objects.
if (kind == MetadataKind::Function) {
auto fT = static_cast<const FunctionTypeMetadata *>(T);
return fT->getConvention() == FunctionMetadataConvention::Block;
}
#endif
return false;
}
/******************************************************************************/
/********************************** Bridging **********************************/
/******************************************************************************/
#if SWIFT_OBJC_INTEROP
//===----------------------------------------------------------------------===//
// Bridging to and from Objective-C
//===----------------------------------------------------------------------===//
namespace {
// protocol _ObjectiveCBridgeable {
struct _ObjectiveCBridgeableWitnessTable {
// associatedtype _ObjectiveCType : class
const Metadata * (*ObjectiveCType)(
const Metadata *parentMetadata,
const _ObjectiveCBridgeableWitnessTable *witnessTable);
// func _bridgeToObjectiveC() -> _ObjectiveCType
HeapObject *(*bridgeToObjectiveC)(
OpaqueValue *self, const Metadata *Self,
const _ObjectiveCBridgeableWitnessTable *witnessTable);
// class func _forceBridgeFromObjectiveC(x: _ObjectiveCType,
// inout result: Self?)
void (*forceBridgeFromObjectiveC)(
HeapObject *sourceValue,
OpaqueValue *result,
const Metadata *self,
const Metadata *selfType,
const _ObjectiveCBridgeableWitnessTable *witnessTable);
// class func _conditionallyBridgeFromObjectiveC(x: _ObjectiveCType,
// inout result: Self?) -> Bool
bool (*conditionallyBridgeFromObjectiveC)(
HeapObject *sourceValue,
OpaqueValue *result,
const Metadata *self,
const Metadata *selfType,
const _ObjectiveCBridgeableWitnessTable *witnessTable);
};
// }
} // unnamed namespace
extern "C" const ProtocolDescriptor _TMps21_ObjectiveCBridgeable;
/// Dynamic cast from a value type that conforms to the _ObjectiveCBridgeable
/// protocol to a class type, first by bridging the value to its Objective-C
/// object representation and then by dynamic casting that object to the
/// resulting target type.
static bool _dynamicCastValueToClassViaObjCBridgeable(
OpaqueValue *dest,
OpaqueValue *src,
const Metadata *srcType,
const Metadata *targetType,
const _ObjectiveCBridgeableWitnessTable *srcBridgeWitness,
DynamicCastFlags flags) {
// Bridge the source value to an object.
auto srcBridgedObject =
srcBridgeWitness->bridgeToObjectiveC(src, srcType, srcBridgeWitness);
// Dynamic cast the object to the resulting class type.
bool success;
if (auto cast = _dynamicCastUnknownClass(srcBridgedObject, targetType,
flags & DynamicCastFlags::Unconditional)) {
*reinterpret_cast<void **>(dest) = cast;
success = true;
} else {
// We don't need the object anymore.
swift_unknownRelease(srcBridgedObject);
success = false;
}
// Clean up the source if we're supposed to.
if (shouldDeallocateSource(success, flags)) {
srcType->vw_destroy(src);
}
// We're done.
return success;
}
/// Dynamic cast from a value type that conforms to the
/// _ObjectiveCBridgeable protocol to a class-bounded existential,
/// first by bridging the value to its Objective-C object
/// representation and then by dynamic-casting that object to the
/// resulting target type.
static bool _dynamicCastValueToClassExistentialViaObjCBridgeable(
OpaqueValue *dest,
OpaqueValue *src,
const Metadata *srcType,
const ExistentialTypeMetadata *targetType,
const _ObjectiveCBridgeableWitnessTable *srcBridgeWitness,
DynamicCastFlags flags) {
// Bridge the source value to an object.
auto srcBridgedObject =
srcBridgeWitness->bridgeToObjectiveC(src, srcType, srcBridgeWitness);
// Try to cast the object to the destination existential.
DynamicCastFlags subFlags = DynamicCastFlags::TakeOnSuccess
| DynamicCastFlags::DestroyOnFailure;
if (flags & DynamicCastFlags::Unconditional)
subFlags |= DynamicCastFlags::Unconditional;
bool success = _dynamicCastToExistential(
dest,
(OpaqueValue *)&srcBridgedObject,
swift_getObjectType(srcBridgedObject),
targetType,
subFlags);
// Clean up the source if we're supposed to.
if (shouldDeallocateSource(success, flags)) {
srcType->vw_destroy(src);
}
// We're done.
return success;
}
/// Dynamic cast from a class type to a value type that conforms to the
/// _ObjectiveCBridgeable, first by dynamic casting the object to the
/// Objective-C class to which the value type is bridged, and then bridging
/// from that object to the value type via the witness table.
static bool _dynamicCastClassToValueViaObjCBridgeable(
OpaqueValue *dest,
OpaqueValue *src,
const Metadata *srcType,
const Metadata *targetType,
const _ObjectiveCBridgeableWitnessTable *targetBridgeWitness,
DynamicCastFlags flags) {
// Determine the class type to which the target value type is bridged.
auto targetBridgedClass =
targetBridgeWitness->ObjectiveCType(targetType, targetBridgeWitness);
// Dynamic cast the source object to the class type to which the target value
// type is bridged. If we succeed, we can bridge from there; if we fail,
// there's nothing more to do.
void *srcObject = *reinterpret_cast<void * const *>(src);
if (!_dynamicCastUnknownClass(srcObject,
targetBridgedClass,
flags & DynamicCastFlags::Unconditional)) {
return _fail(src, srcType, targetType, flags);
}
// Unless we're always supposed to consume the input, retain the
// object because the witness takes it at +1.
bool alwaysConsumeSrc = (flags & DynamicCastFlags::TakeOnSuccess) &&
(flags & DynamicCastFlags::DestroyOnFailure);
if (!alwaysConsumeSrc) {
swift_unknownRetain(srcObject);
}
// The extra byte is for the tag.
auto targetSize = targetType->getValueWitnesses()->size + 1;
auto targetAlignMask = targetType->getValueWitnesses()->getAlignmentMask();
// Object that frees a buffer when it goes out of scope.
struct FreeBuffer {
void *Buffer = nullptr;
size_t size, alignMask;
FreeBuffer(size_t size, size_t alignMask) :
size(size), alignMask(alignMask) {}
~FreeBuffer() {
if (Buffer)
swift_slowDealloc(Buffer, size, alignMask);
}
} freeBuffer{targetSize, targetAlignMask};
// Allocate a buffer to store the T? returned by bridging.
// The extra byte is for the tag.
const std::size_t inlineValueSize = 3 * sizeof(void*);
alignas(std::max_align_t) char inlineBuffer[inlineValueSize + 1];
void *optDestBuffer;
if (targetType->getValueWitnesses()->getStride() <= inlineValueSize) {
// Use the inline buffer.
optDestBuffer = inlineBuffer;
} else {
// Allocate a buffer.
optDestBuffer = swift_slowAlloc(targetSize, targetAlignMask);
freeBuffer.Buffer = optDestBuffer;
}
// Initialize the buffer as an empty optional.
swift_storeEnumTagSinglePayload((OpaqueValue *)optDestBuffer, targetType,
0, 1);
// Perform the bridging operation.
bool success;
if (flags & DynamicCastFlags::Unconditional) {
// For an unconditional dynamic cast, use forceBridgeFromObjectiveC.
targetBridgeWitness->forceBridgeFromObjectiveC(
(HeapObject *)srcObject, (OpaqueValue *)optDestBuffer,
targetType, targetType, targetBridgeWitness);
success = true;
} else {
// For a conditional dynamic cast, use conditionallyBridgeFromObjectiveC.
success = targetBridgeWitness->conditionallyBridgeFromObjectiveC(
(HeapObject *)srcObject, (OpaqueValue *)optDestBuffer,
targetType, targetType, targetBridgeWitness);
}
// If we succeeded, take from the optional buffer into the
// destination buffer.
if (success) {
targetType->vw_initializeWithTake(dest, (OpaqueValue *)optDestBuffer);
}
// Unless we're always supposed to consume the input, release the
// input if we need to now.
if (!alwaysConsumeSrc && shouldDeallocateSource(success, flags)) {
swift_unknownRelease(srcObject);
}
return success;
}
static id bridgeAnythingNonVerbatimToObjectiveC(OpaqueValue *src,
const Metadata *srcType,
bool consume) {
// We can always bridge objects verbatim.
if (srcType->isAnyClass()) {
id result;
memcpy(&result, src, sizeof(id));
if (!consume)
swift_unknownRetain(result);
return result;
}
// Dig through existential types.
if (auto srcExistentialTy = dyn_cast<ExistentialTypeMetadata>(srcType)) {
OpaqueValue *srcInnerValue;
const Metadata *srcInnerType;
bool isOutOfLine;
bool canTake;
unwrapExistential(src, srcExistentialTy,
srcInnerValue, srcInnerType, isOutOfLine, canTake);
auto result = bridgeAnythingNonVerbatimToObjectiveC(srcInnerValue,
srcInnerType,
consume && canTake);
// Clean up the existential, or its remains after taking the value from
// it.
if (consume) {
if (canTake) {
if (isOutOfLine) {
// Should only be true of opaque existentials right now.
assert(srcExistentialTy->getRepresentation()
== ExistentialTypeRepresentation::Opaque);
auto container = reinterpret_cast<OpaqueExistentialContainer*>(src);
srcInnerType->vw_deallocateBuffer(&container->Buffer);
}
} else {
// We didn't take the value, so clean up the existential value.
srcType->vw_destroy(src);
}
}
return result;
}
// Handle metatypes.
if (isa<ExistentialMetatypeMetadata>(srcType)
|| isa<MetatypeMetadata>(srcType)) {
const Metadata *srcMetatypeValue;
memcpy(&srcMetatypeValue, src, sizeof(srcMetatypeValue));
// Class metatypes bridge to their class object.
if (isa<ClassMetadata>(srcMetatypeValue)
|| isa<ObjCClassWrapperMetadata>(srcMetatypeValue)) {
return (id)srcMetatypeValue->getClassObject();
// ObjC protocols bridge to their Protocol object.
} else if (auto existential
= dyn_cast<ExistentialTypeMetadata>(srcMetatypeValue)) {
if (existential->isObjC() && existential->Protocols.NumProtocols == 1) {
// Though they're statically-allocated globals, Protocol inherits
// NSObject's default refcounting behavior so must be retained.
auto protocolObj = (id)existential->Protocols[0];
return objc_retain(protocolObj);
}
}
} else if (auto srcBridgeWitness = findBridgeWitness(srcType)) {
// Bridge the source value to an object.
auto srcBridgedObject =
srcBridgeWitness->bridgeToObjectiveC(src, srcType, srcBridgeWitness);
// Consume if the source object was passed in +1.
if (consume)
srcType->vw_destroy(src);
return (id)srcBridgedObject;
}
// Fall back to boxing.
return (id)bridgeAnythingToSwiftValueObject(src, srcType, consume);
}
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERFACE
extern "C"
id _swift_bridgeAnythingNonVerbatimToObjectiveC(OpaqueValue *src,
const Metadata *srcType) {
return bridgeAnythingNonVerbatimToObjectiveC(src, srcType, /*consume*/ true);
}
//===--- Bridging helpers for the Swift stdlib ----------------------------===//
// Functions that must discover and possibly use an arbitrary type's
// conformance to a given protocol. See ../core/BridgeObjectiveC.swift for
// documentation.
//===----------------------------------------------------------------------===//
extern "C" const _ObjectiveCBridgeableWitnessTable
_TWPVs19_BridgeableMetatypes21_ObjectiveCBridgeables;
static const _ObjectiveCBridgeableWitnessTable *
findBridgeWitness(const Metadata *T) {
auto w = swift_conformsToProtocol(T, &_TMps21_ObjectiveCBridgeable);
if (LLVM_LIKELY(w))
return reinterpret_cast<const _ObjectiveCBridgeableWitnessTable *>(w);
// Class and ObjC existential metatypes can be bridged, but metatypes can't
// directly conform to protocols yet. Use a stand-in conformance for a type
// that looks like a metatype value if the metatype can be bridged.
switch (T->getKind()) {
case MetadataKind::Metatype: {
auto metaTy = static_cast<const MetatypeMetadata *>(T);
if (metaTy->InstanceType->isAnyClass())
return &_TWPVs19_BridgeableMetatypes21_ObjectiveCBridgeables;
break;
}
case MetadataKind::ExistentialMetatype: {
auto existentialMetaTy =
static_cast<const ExistentialMetatypeMetadata *>(T);
if (existentialMetaTy->isObjC())
return &_TWPVs19_BridgeableMetatypes21_ObjectiveCBridgeables;
break;
}
case MetadataKind::Class:
case MetadataKind::Struct:
case MetadataKind::Enum:
case MetadataKind::Optional:
case MetadataKind::Opaque:
case MetadataKind::Tuple:
case MetadataKind::Function:
case MetadataKind::Existential:
case MetadataKind::ObjCClassWrapper:
case MetadataKind::ForeignClass:
case MetadataKind::HeapLocalVariable:
case MetadataKind::HeapGenericLocalVariable:
case MetadataKind::ErrorObject:
break;
}
return nullptr;
}
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERFACE
extern "C" const Metadata *_swift_getBridgedNonVerbatimObjectiveCType(
const Metadata *value, const Metadata *T
) {
// Classes and Objective-C existentials bridge verbatim.
assert(!swift_isClassOrObjCExistentialTypeImpl(T));
// Check if the type conforms to _BridgedToObjectiveC, in which case
// we'll extract its associated type.
if (const auto *bridgeWitness = findBridgeWitness(T)) {
return bridgeWitness->ObjectiveCType(T, bridgeWitness);
}
return nullptr;
}
// @_silgen_name("_swift_bridgeNonVerbatimFromObjectiveCToAny")
// func _bridgeNonVerbatimFromObjectiveCToAny(
// x: AnyObject,
// inout result: Any?
// )
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERFACE
extern "C" void
_swift_bridgeNonVerbatimFromObjectiveCToAny(HeapObject *sourceValue,
OpaqueValue *destValue);
// @_silgen_name("_swift_bridgeNonVerbatimBoxedValue")
// func _bridgeNonVerbatimBoxedValue<NativeType>(
// x: UnsafePointer<NativeType>,
// inout result: NativeType?
// )
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERFACE
extern "C" void
_swift_bridgeNonVerbatimBoxedValue(const OpaqueValue *sourceValue,
OpaqueValue *destValue,
const Metadata *nativeType);
// Try bridging by conversion to Any or boxing if applicable.
static bool tryBridgeNonVerbatimFromObjectiveCUniversal(
HeapObject *sourceValue,
const Metadata *nativeType,
OpaqueValue *destValue
) {
// If the type is the Any type, we can bridge by "upcasting" the object
// to Any.
if (auto nativeExistential = dyn_cast<ExistentialTypeMetadata>(nativeType)) {
if (nativeExistential->Protocols.NumProtocols == 0) {
_swift_bridgeNonVerbatimFromObjectiveCToAny(sourceValue,
destValue);
return true;
}
}
// Check if the value is a box containing a value of the desired type.
if (auto srcBox = getAsSwiftValue((id)sourceValue)) {
const Metadata *sourceType;
const OpaqueValue *sourceBoxedValue;
std::tie(sourceType, sourceBoxedValue) = getValueFromSwiftValue(srcBox);
if (sourceType == nativeType) {
_swift_bridgeNonVerbatimBoxedValue(sourceBoxedValue,
destValue,
nativeType);
return true;
}
}
return false;
}
// @_silgen_name("_swift_bridgeNonVerbatimFromObjectiveC")
// func _bridgeNonVerbatimFromObjectiveC<NativeType>(
// x: AnyObject,
// nativeType: NativeType.Type
// inout result: T?
// )
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERFACE
extern "C" void
_swift_bridgeNonVerbatimFromObjectiveC(
HeapObject *sourceValue,
const Metadata *nativeType,
OpaqueValue *destValue,
const Metadata *nativeType_
) {
if (tryBridgeNonVerbatimFromObjectiveCUniversal(sourceValue, nativeType,
destValue))
return;
// Check if the type conforms to _BridgedToObjectiveC.
if (const auto *bridgeWitness = findBridgeWitness(nativeType)) {
// Check if sourceValue has the _ObjectiveCType type required by the
// protocol.
const Metadata *objectiveCType =
bridgeWitness->ObjectiveCType(nativeType, bridgeWitness);
auto sourceValueAsObjectiveCType =
const_cast<void*>(swift_dynamicCastUnknownClass(sourceValue,
objectiveCType));
if (sourceValueAsObjectiveCType) {
// The type matches. _forceBridgeFromObjectiveC returns `Self`, so
// we can just return it directly.
bridgeWitness->forceBridgeFromObjectiveC(
static_cast<HeapObject*>(sourceValueAsObjectiveCType),
destValue, nativeType, nativeType, bridgeWitness);
return;
}
}
// Fail.
swift::crash("value type is not bridged to Objective-C");
}
// @_silgen_name("_swift_bridgeNonVerbatimFromObjectiveCConditional")
// func _bridgeNonVerbatimFromObjectiveCConditional<NativeType>(
// x: AnyObject,
// nativeType: T.Type,
// inout result: T?
// ) -> Bool
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERFACE
extern "C" bool
_swift_bridgeNonVerbatimFromObjectiveCConditional(
HeapObject *sourceValue,
const Metadata *nativeType,
OpaqueValue *destValue,
const Metadata *nativeType_
) {
if (tryBridgeNonVerbatimFromObjectiveCUniversal(sourceValue, nativeType,
destValue))
return true;
// Local function that releases the source and returns false.
auto fail = [&] () -> bool {
swift_unknownRelease(sourceValue);
return false;
};
// Check if the type conforms to _BridgedToObjectiveC.
const auto *bridgeWitness = findBridgeWitness(nativeType);
if (!bridgeWitness)
return fail();
// Dig out the Objective-C class type through which the native type
// is bridged.
const Metadata *objectiveCType =
bridgeWitness->ObjectiveCType(nativeType, bridgeWitness);
// Check whether we can downcast the source value to the Objective-C
// type.
auto sourceValueAsObjectiveCType =
const_cast<void*>(swift_dynamicCastUnknownClass(sourceValue,
objectiveCType));
if (!sourceValueAsObjectiveCType)
return fail();
// If the type also conforms to _ConditionallyBridgedToObjectiveC,
// use conditional bridging.
return bridgeWitness->conditionallyBridgeFromObjectiveC(
static_cast<HeapObject*>(sourceValueAsObjectiveCType),
destValue, nativeType, nativeType, bridgeWitness);
}
// func _isBridgedNonVerbatimToObjectiveC<T>(x: T.Type) -> Bool
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERFACE
extern "C" bool _swift_isBridgedNonVerbatimToObjectiveC(
const Metadata *value, const Metadata *T
) {
assert(!swift_isClassOrObjCExistentialTypeImpl(T));
auto bridgeWitness = findBridgeWitness(T);
return (bool)bridgeWitness;
}
#endif
// func _isClassOrObjCExistential<T>(x: T.Type) -> Bool
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERFACE
extern "C" bool _swift_isClassOrObjCExistentialType(const Metadata *value,
const Metadata *T) {
return swift_isClassOrObjCExistentialTypeImpl(T);
}
const Metadata *swift::_swift_class_getSuperclass(const Metadata *theClass) {
if (const ClassMetadata *classType = theClass->getClassObject())
if (classHasSuperclass(classType))
return swift_getObjCClassMetadata(classType->SuperClass);
return nullptr;
}
SWIFT_CC(c) SWIFT_RUNTIME_EXPORT
extern "C" bool swift_isClassType(const Metadata *type) {
return Metadata::isAnyKindOfClass(type->getKind());
}
SWIFT_CC(c) SWIFT_RUNTIME_EXPORT
extern "C" bool swift_isOptionalType(const Metadata *type) {
return type->getKind() == MetadataKind::Optional;
}
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2013-2018 Regents of the University of California.
*
* This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
*
* ndn-cxx library is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later version.
*
* ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with ndn-cxx, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of ndn-cxx authors and contributors.
*
* @author Yingdi Yu <http://irl.cs.ucla.edu/~yingdi/>
*/
#include "ndn-cxx/util/regex/regex-backref-manager.hpp"
namespace ndn {
size_t
RegexBackrefManager::pushRef(const shared_ptr<RegexMatcher>& matcher)
{
auto last = m_backrefs.size();
m_backrefs.emplace_back(matcher);
return last;
}
shared_ptr<RegexMatcher>
RegexBackrefManager::getBackref(size_t i) const
{
auto backref = m_backrefs[i].lock();
BOOST_ASSERT(backref != nullptr);
return backref;
}
} // namespace ndn
|
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <cstdarg>
#include <cstring>
#include <type_traits>
#include <typeinfo>
typedef std::string string;
// should support all compilers(todo)
// #if __GNUC__ || __clang__
// typedef __int128 int128;
// #else
// typedef __int128_t int128;
// #endif
typedef long long int64;
typedef unsigned long long uint64;
typedef unsigned int uint;
typedef unsigned long long uint64;
typedef short int16;
typedef unsigned short uint16;
typedef unsigned char uint8;
typedef char int8;
void error(string err_msg){
std::cerr << err_msg << std::endl ;
}
void panic(string err_msg){
error(err_msg);
exit(1);
}
string ReadStr(){
string res;
std::cin >> res;
return res;
}
string ReadStr(string p){
std::cout << p;
string res;
std::cin >> res;
return res;
}
char ReadChar(){
char res;
std::cin >> res;
return res;
}
char ReadChar(string p){
std::cout << p;
char res;
std::cin >> res;
return res;
}
bool ReadBool(){
string tmp = ReadStr();
if(tmp == "0" || tmp == "true")
return true;
return false;
}
bool ReadBool(string p){
string tmp = ReadStr(p);
if(tmp == "0" || tmp == "true")
return true;
return false;
}
int ReadInt(){
int res;
std::cin >> res;
return res;
}
int ReadInt(string p){
std::cout << p;
int res;
std::cin >> res;
return res;
}
float ReadFloat(){
float res;
std::cin >> res;
return res;
}
float ReadFloat(string p){
std::cout << p;
float res;
std::cin >> res;
return res;
}
template<typename Test, template<typename...> class Ref>
struct is_specialization : std::false_type {};
template<template<typename...> class Ref, typename... Args>
struct is_specialization<Ref<Args...>, Ref>: std::true_type {};
// this function is used to get length of a vector
template <typename T>
int len(std::vector<T> v){
return v.size();
}
// this function is used to get length of a string
int len(string s){
return s.length();
}
// this function is used to append a value to a vector
template <typename T>
void append(std::vector<T>& v, T val){
v.push_back(val);
}
string input(){
return ReadStr();
}
string input(string text){
return ReadStr(text);
}
std::vector<std::string> split(std::string str,std::string sep){
char* cstr=const_cast<char*>(str.c_str());
char* current;
std::vector<std::string> arr;
current=strtok(cstr,sep.c_str());
while(current!=NULL){
arr.push_back(current);
current=strtok(NULL,sep.c_str());
}
return arr;
}
// format function -> e.g : format("Hi, {}",name)
template <typename T, typename ... ARGS>
string format(T text,ARGS... args){
string res;
std::vector<string> fmt_list = { args... };
std::vector<string> points = split(text,"{}");
int fmt_size = fmt_list.size();
int points_size = points.size();
for(int i,j=0;i<=points_size-1 && j<=fmt_size;j++,i++){
res += points[i] + fmt_list[j];
}
return res;
}
template <typename T>
T* mem_new(T val){
T* res = new T(val);
return res;
}
template <typename T>
T* mem_realloc(T* ptr, T val){
delete ptr;
T* res = new T(val);
return res;
}
template <typename T>
void mem_delete(T* ptr){
delete ptr;
}
template <typename T>
std::vector<T>* mem_new(){
auto res = new std::vector<T>();
return res;
}
template <typename T>
std::vector<T>* mem_renew(std::vector<T>* ptr,std::vector<T> val){
delete ptr;
auto res = new std::vector<T>(val);
return res;
}
template <typename T>
void mem_delete(std::vector<T>* ptr){
delete ptr;
}
// exit()
#include <cctype>
#include <cctype>
bool is_alpha(char c){
return std::isalpha(c);
}
bool is_alphanum(char c){
return std::isalpha(c) || std::isdigit(c);
}
bool is_space(char c){
return std::isspace(c);
}
bool is_number(char c){
return std::isdigit(c);
}
string to_lower(string str){
string temp;
for (char c : str)
{
temp += std::tolower(c);
}
return temp;
}
string to_upper(string str){
string temp;
for (char c : str)
{
temp += std::toupper(c);
}
return temp;
}
struct token{
string kind ;
string value ;
};
std::vector<token> tokenizer( string input) {
input = input + std::string("\n");auto current = 0;
std::vector<token> tokens;
while(current < len(input)){
auto ch = to_char(input[current]);
if(ch == '('){
append(tokens, {std::string("paren"),std::string("(")});
current = current + 1;continue;
}
if(ch == ')'){
append(tokens, {std::string("paren"),std::string(")")});
current = current + 1;continue;
}
if(ch == ' '){
current = current + 1;continue;
}
if(is_number(ch)){
auto value = std::string("");
while(is_number(ch) == true){
value = value + to_string(ch);current = current + 1;ch = to_char(input[current]);
}
append(tokens, {std::string("number"),value});
continue;
}
if(is_number(ch) == true){
auto value = std::string("");
while(is_number(ch) == true){
value = value + to_string(ch);current = current + 1;ch = to_char(input[current]);
}
append(tokens, {std::string("name"),value});
continue;
}
break;
}
return tokens;
}
struct node_t{
};
struct node{
string kind ;
string value ;
string name ;
node* callee ;
node* expression ;
std::vector<node> body;
std::vector<node> params;
node* arguments ;
node* context ;
};
struct ast : node{
};
int pc ;
std::vector<token> pt;
node walk() {
token tok = pt[pc];
if(tok.kind == std::string("number")){
pc = pc + 1;return node{std::string("NumberLiteral"), tok.value};
}
if(tok.kind == std::string("paren") && tok.value == std::string("(")){
pc = pc + 1;tok = pt[pc];node n = node{std::string("CallExpression"), tok.value};
pc = pc + 1;tok = pt[pc];while(tok.kind != std::string("paren") && (tok.kind == std::string("paren") && tok.value != std::string(")"))){
append(n.params, walk());
tok = pt[pc];
}
pc = pc + 1;return n;
}
error(std::string("Unexpected token"));
return node{};
}
ast parser( std::vector<token> tokens) {
pc = 0;pt = tokens;auto result_ast = ast{std::string("Program")};
while(pc < len(pt)){
append(result_ast.body, walk());
}
return result_ast;
}
int main(int argc,char** args) {
std::vector<std::string> argv;for(int i=0;i<argc;i++){argv.push_back(args[i]);}
return 0;
}
|
#ifndef _SEQUENCERHLCOORDINATIONSERVERHLCOMMANDSERVEREVENTHANDLER_HH_
#define _SEQUENCERHLCOORDINATIONSERVERHLCOMMANDSERVEREVENTHANDLER_HH_
#include "aceSmartSoft.hh"
#include <string>
#include <iostream>
#include "CommBasicObjects/CommSkillMsg.hh"
#include "CommBasicObjects/CommSkillMsg.hh"
class SequencerHLCoordinationServerHLCommandServerEventHandler
{
public:
std::string handleEvent(const CommBasicObjects::CommSkillMsg &r) throw();
CommBasicObjects::CommSkillMsg activateEventParam(const std::string& parameterString);
};
#endif
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <proxygen/lib/http/RFC2616.h>
#include <stdlib.h>
#include <folly/String.h>
#include <folly/ThreadLocal.h>
#include <proxygen/lib/http/HTTPHeaders.h>
namespace {
/* Wapper around strtoul(3) */
bool strtoulWrapper(const char*& curs, const char* end, unsigned long& val) {
char* endptr = nullptr;
unsigned long v = strtoul(curs, &endptr, 10);
if (endptr == curs) {
return false;
}
if (endptr > end) {
return false;
}
curs = endptr;
val = v;
return true;
}
bool equalsIgnoreCase(folly::StringPiece s1, folly::StringPiece s2) {
if (s1.size() != s2.size()) {
return false;
}
return std::equal(
s1.begin(), s1.end(), s2.begin(), folly::AsciiCaseInsensitive());
}
} // namespace
namespace proxygen { namespace RFC2616 {
BodyAllowed isRequestBodyAllowed(folly::Optional<HTTPMethod> method) {
if (method == HTTPMethod::TRACE) {
return BodyAllowed::NOT_ALLOWED;
}
if (method == HTTPMethod::OPTIONS || method == HTTPMethod::POST ||
method == HTTPMethod::PUT) {
return BodyAllowed::DEFINED;
}
return BodyAllowed::NOT_DEFINED;
}
bool responseBodyMustBeEmpty(unsigned status) {
return (status == 304 || status == 204 || (100 <= status && status < 200));
}
bool bodyImplied(const HTTPHeaders& headers) {
return headers.exists(HTTP_HEADER_TRANSFER_ENCODING) ||
headers.exists(HTTP_HEADER_CONTENT_LENGTH);
}
double parseQvalue(const EncodingParams& params) {
double qvalue = 1.0;
for (const auto& paramPair : params) {
if (paramPair.first == "q") {
qvalue = folly::to<double>(paramPair.second);
}
}
return qvalue;
}
bool parseQvalues(folly::StringPiece value, TokenPairVec& output) {
bool success = true;
try {
auto encodings = parseEncoding(value);
for (const auto& pair : encodings) {
double qvalue = 1.0;
try {
qvalue = parseQvalue(pair.second);
} catch (const std::range_error&) {
// q=<some garbage>
success = false;
}
output.emplace_back(pair.first, qvalue);
}
} catch (const std::exception& /*ex*/) {
success = false;
}
return success;
}
bool parseByteRangeSpec(folly::StringPiece value,
unsigned long& outFirstByte,
unsigned long& outLastByte,
unsigned long& outInstanceLength) {
// We should start with "bytes "
if (!value.startsWith("bytes ")) {
return false;
}
const char* curs = value.begin() + 6 /* strlen("bytes ") */;
const char* end = value.end();
unsigned long firstByte = ULONG_MAX;
unsigned long lastByte = ULONG_MAX;
unsigned long instanceLength = ULONG_MAX;
if (!strtoulWrapper(curs, end, firstByte)) {
if (*curs != '*') {
return false;
}
firstByte = 0;
lastByte = ULONG_MAX;
++curs;
} else {
if (*curs != '-') {
return false;
}
++curs;
if (!strtoulWrapper(curs, end, lastByte)) {
return false;
}
}
if (*curs != '/') {
return false;
}
++curs;
if (*curs != '*') {
if (!strtoulWrapper(curs, end, instanceLength)) {
return false;
}
} else {
++curs;
}
if (curs < end && *curs != '\0') {
return false;
}
if (lastByte < firstByte) {
return false;
}
if ((lastByte - firstByte + 1) > instanceLength) {
return false;
}
outFirstByte = firstByte;
outLastByte = lastByte;
outInstanceLength = instanceLength;
return true;
}
EncodingList parseEncoding(const folly::StringPiece header) {
EncodingList result;
std::vector<folly::StringPiece> topLevelTokens;
folly::split(',', header, topLevelTokens, true /*ignore empty*/);
if (topLevelTokens.empty()) {
throw std::runtime_error("Header value mustn't be empty.");
}
for (auto topLevelToken : topLevelTokens) {
std::vector<folly::StringPiece> secondLevelTokens;
folly::split(';', topLevelToken, secondLevelTokens, true /*ignore empty*/);
if (secondLevelTokens.empty()) {
throw std::runtime_error("Encoding must have name.");
}
auto encoding = folly::trimWhitespace(secondLevelTokens.front());
if (encoding.empty()) {
throw std::runtime_error("Empty encoding!");
}
EncodingParams params;
params.reserve(secondLevelTokens.size() - 1);
auto it = secondLevelTokens.begin();
while (++it != secondLevelTokens.end()) {
auto val = *it;
auto key = val.split_step('=');
key = folly::trimWhitespace(key);
val = folly::trimWhitespace(val);
if (key.empty()) {
throw std::runtime_error("Param key must not be empty!");
}
params.emplace_back(key, val);
}
result.emplace_back(encoding, std::move(params));
}
return result;
}
bool acceptsEncoding(const folly::StringPiece header,
const folly::StringPiece encoding) {
try {
auto encodings = parseEncoding(header);
return acceptsEncoding(encodings, encoding);
} catch (const std::exception&) {
return false;
}
}
bool acceptsEncoding(const EncodingList& encodings,
const folly::StringPiece encoding) {
for (const auto& pair : encodings) {
if (equalsIgnoreCase(pair.first, encoding)) {
try {
auto qval = parseQvalue(pair.second);
return qval > 0;
} catch (const std::exception&) {
}
return true;
}
}
return false;
}
}} // namespace proxygen::RFC2616
|
//=================================================================================================
/*!
// \file src/mathtest/dmatsmatmult/SUDbSCa.cpp
// \brief Source file for the SUDbSCa dense matrix/sparse matrix multiplication math test
//
// Copyright (C) 2012-2018 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/CompressedMatrix.h>
#include <blaze/math/DynamicMatrix.h>
#include <blaze/math/StrictlyUpperMatrix.h>
#include <blaze/math/SymmetricMatrix.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/dmatsmatmult/OperationTest.h>
#include <blazetest/system/MathTest.h>
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'SUDbSCa'..." << std::endl;
using blazetest::mathtest::TypeA;
using blazetest::mathtest::TypeB;
try
{
// Matrix type definitions
typedef blaze::StrictlyUpperMatrix< blaze::DynamicMatrix<TypeB> > SUDb;
typedef blaze::SymmetricMatrix< blaze::CompressedMatrix<TypeA> > SCa;
// Creator type definitions
typedef blazetest::Creator<SUDb> CSUDb;
typedef blazetest::Creator<SCa> CSCa;
// Running tests with small matrices
for( size_t i=0UL; i<=6UL; ++i ) {
for( size_t j=0UL; j<=i*i; ++j ) {
RUN_DMATSMATMULT_OPERATION_TEST( CSUDb( i ), CSCa( i, j ) );
}
}
// Running tests with large matrices
RUN_DMATSMATMULT_OPERATION_TEST( CSUDb( 31UL ), CSCa( 31UL, 7UL ) );
RUN_DMATSMATMULT_OPERATION_TEST( CSUDb( 67UL ), CSCa( 67UL, 7UL ) );
RUN_DMATSMATMULT_OPERATION_TEST( CSUDb( 127UL ), CSCa( 127UL, 13UL ) );
RUN_DMATSMATMULT_OPERATION_TEST( CSUDb( 32UL ), CSCa( 32UL, 8UL ) );
RUN_DMATSMATMULT_OPERATION_TEST( CSUDb( 64UL ), CSCa( 64UL, 8UL ) );
RUN_DMATSMATMULT_OPERATION_TEST( CSUDb( 128UL ), CSCa( 128UL, 16UL ) );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during dense matrix/sparse matrix multiplication:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE23_Relative_Path_Traversal__wchar_t_connect_socket_fopen_02.cpp
Label Definition File: CWE23_Relative_Path_Traversal.label.xml
Template File: sources-sink-02.tmpl.cpp
*/
/*
* @description
* CWE: 23 Relative Path Traversal
* BadSource: connect_socket Read data using a connect socket (client side)
* GoodSource: Use a fixed file name
* Sink: fopen
* BadSink : Open the file named in data using fopen()
* Flow Variant: 02 Control flow: if(1) and if(0)
*
* */
#include "std_testcase.h"
#ifdef _WIN32
#define BASEPATH L"c:\\temp\\"
#else
#include <wchar.h>
#define BASEPATH L"/tmp/"
#endif
#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <direct.h>
#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */
#define CLOSE_SOCKET closesocket
#else /* NOT _WIN32 */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define CLOSE_SOCKET close
#define SOCKET int
#endif
#define TCP_PORT 27015
#define IP_ADDRESS "127.0.0.1"
#ifdef _WIN32
#define FOPEN _wfopen
#else
#define FOPEN fopen
#endif
namespace CWE23_Relative_Path_Traversal__wchar_t_connect_socket_fopen_02
{
#ifndef OMITBAD
void bad()
{
wchar_t * data;
wchar_t dataBuffer[FILENAME_MAX] = BASEPATH;
data = dataBuffer;
if(1)
{
{
#ifdef _WIN32
WSADATA wsaData;
int wsaDataInit = 0;
#endif
int recvResult;
struct sockaddr_in service;
wchar_t *replace;
SOCKET connectSocket = INVALID_SOCKET;
size_t dataLen = wcslen(data);
do
{
#ifdef _WIN32
if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
{
break;
}
wsaDataInit = 1;
#endif
/* POTENTIAL FLAW: Read data using a connect socket */
connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (connectSocket == INVALID_SOCKET)
{
break;
}
memset(&service, 0, sizeof(service));
service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr(IP_ADDRESS);
service.sin_port = htons(TCP_PORT);
if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
{
break;
}
/* Abort on error or the connection was closed, make sure to recv one
* less char than is in the recv_buf in order to append a terminator */
/* Abort on error or the connection was closed */
recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(wchar_t) * (FILENAME_MAX - dataLen - 1), 0);
if (recvResult == SOCKET_ERROR || recvResult == 0)
{
break;
}
/* Append null terminator */
data[dataLen + recvResult / sizeof(wchar_t)] = L'\0';
/* Eliminate CRLF */
replace = wcschr(data, L'\r');
if (replace)
{
*replace = L'\0';
}
replace = wcschr(data, L'\n');
if (replace)
{
*replace = L'\0';
}
}
while (0);
if (connectSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(connectSocket);
}
#ifdef _WIN32
if (wsaDataInit)
{
WSACleanup();
}
#endif
}
}
{
FILE *pFile = NULL;
/* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */
pFile = FOPEN(data, L"wb+");
if (pFile != NULL)
{
fclose(pFile);
}
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B1() - use goodsource and badsink by changing the 1 to 0 */
static void goodG2B1()
{
wchar_t * data;
wchar_t dataBuffer[FILENAME_MAX] = BASEPATH;
data = dataBuffer;
if(0)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
/* FIX: Use a fixed file name */
wcscat(data, L"file.txt");
}
{
FILE *pFile = NULL;
/* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */
pFile = FOPEN(data, L"wb+");
if (pFile != NULL)
{
fclose(pFile);
}
}
}
/* goodG2B2() - use goodsource and badsink by reversing the statements in the if */
static void goodG2B2()
{
wchar_t * data;
wchar_t dataBuffer[FILENAME_MAX] = BASEPATH;
data = dataBuffer;
if(1)
{
/* FIX: Use a fixed file name */
wcscat(data, L"file.txt");
}
{
FILE *pFile = NULL;
/* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */
pFile = FOPEN(data, L"wb+");
if (pFile != NULL)
{
fclose(pFile);
}
}
}
void good()
{
goodG2B1();
goodG2B2();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE23_Relative_Path_Traversal__wchar_t_connect_socket_fopen_02; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
/*
* Copyright (c) 2015 Cryptonomex, Inc., and contributors.
*
* The MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <graphene/chain/get_config.hpp>
#include <graphene/chain/config.hpp>
#include <graphene/chain/protocol/types.hpp>
namespace graphene { namespace chain {
fc::variant_object get_config()
{
fc::mutable_variant_object result;
result[ "GRAPHENE_SYMBOL" ] = GRAPHENE_SYMBOL;
result[ "GRAPHENE_ADDRESS_PREFIX" ] = GRAPHENE_ADDRESS_PREFIX;
result[ "GRAPHENE_MIN_ACCOUNT_NAME_LENGTH" ] = GRAPHENE_MIN_ACCOUNT_NAME_LENGTH;
result[ "GRAPHENE_MAX_ACCOUNT_NAME_LENGTH" ] = GRAPHENE_MAX_ACCOUNT_NAME_LENGTH;
result[ "GRAPHENE_MIN_ASSET_SYMBOL_LENGTH" ] = GRAPHENE_MIN_ASSET_SYMBOL_LENGTH;
result[ "GRAPHENE_MAX_ASSET_SYMBOL_LENGTH" ] = GRAPHENE_MAX_ASSET_SYMBOL_LENGTH;
result[ "GRAPHENE_MAX_SHARE_SUPPLY" ] = GRAPHENE_MAX_SHARE_SUPPLY;
result[ "GRAPHENE_MAX_PAY_RATE" ] = GRAPHENE_MAX_PAY_RATE;
result[ "GRAPHENE_MAX_SIG_CHECK_DEPTH" ] = GRAPHENE_MAX_SIG_CHECK_DEPTH;
result[ "GRAPHENE_MIN_TRANSACTION_SIZE_LIMIT" ] = GRAPHENE_MIN_TRANSACTION_SIZE_LIMIT;
result[ "GRAPHENE_MIN_BLOCK_INTERVAL" ] = GRAPHENE_MIN_BLOCK_INTERVAL;
result[ "GRAPHENE_MAX_BLOCK_INTERVAL" ] = GRAPHENE_MAX_BLOCK_INTERVAL;
result[ "GRAPHENE_DEFAULT_BLOCK_INTERVAL" ] = GRAPHENE_DEFAULT_BLOCK_INTERVAL;
result[ "GRAPHENE_DEFAULT_MAX_TRANSACTION_SIZE" ] = GRAPHENE_DEFAULT_MAX_TRANSACTION_SIZE;
result[ "GRAPHENE_DEFAULT_MAX_BLOCK_SIZE" ] = GRAPHENE_DEFAULT_MAX_BLOCK_SIZE;
result[ "GRAPHENE_DEFAULT_MAX_TIME_UNTIL_EXPIRATION" ] = GRAPHENE_DEFAULT_MAX_TIME_UNTIL_EXPIRATION;
result[ "GRAPHENE_DEFAULT_MAINTENANCE_INTERVAL" ] = GRAPHENE_DEFAULT_MAINTENANCE_INTERVAL;
result[ "GRAPHENE_DEFAULT_MAINTENANCE_SKIP_SLOTS" ] = GRAPHENE_DEFAULT_MAINTENANCE_SKIP_SLOTS;
result[ "GRAPHENE_MIN_UNDO_HISTORY" ] = GRAPHENE_MIN_UNDO_HISTORY;
result[ "GRAPHENE_MAX_UNDO_HISTORY" ] = GRAPHENE_MAX_UNDO_HISTORY;
result[ "GRAPHENE_MIN_BLOCK_SIZE_LIMIT" ] = GRAPHENE_MIN_BLOCK_SIZE_LIMIT;
result[ "GRAPHENE_MIN_TRANSACTION_EXPIRATION_LIMIT" ] = GRAPHENE_MIN_TRANSACTION_EXPIRATION_LIMIT;
result[ "GRAPHENE_BLOCKCHAIN_PRECISION" ] = GRAPHENE_BLOCKCHAIN_PRECISION;
result[ "GRAPHENE_BLOCKCHAIN_PRECISION_DIGITS" ] = GRAPHENE_BLOCKCHAIN_PRECISION_DIGITS;
result[ "GRAPHENE_DEFAULT_TRANSFER_FEE" ] = GRAPHENE_DEFAULT_TRANSFER_FEE;
result[ "GRAPHENE_MAX_INSTANCE_ID" ] = GRAPHENE_MAX_INSTANCE_ID;
result[ "GRAPHENE_100_PERCENT" ] = GRAPHENE_100_PERCENT;
result[ "GRAPHENE_1_PERCENT" ] = GRAPHENE_1_PERCENT;
result[ "GRAPHENE_MAX_MARKET_FEE_PERCENT" ] = GRAPHENE_MAX_MARKET_FEE_PERCENT;
result[ "GRAPHENE_DEFAULT_FORCE_SETTLEMENT_DELAY" ] = GRAPHENE_DEFAULT_FORCE_SETTLEMENT_DELAY;
result[ "GRAPHENE_DEFAULT_FORCE_SETTLEMENT_OFFSET" ] = GRAPHENE_DEFAULT_FORCE_SETTLEMENT_OFFSET;
result[ "GRAPHENE_DEFAULT_FORCE_SETTLEMENT_MAX_VOLUME" ] = GRAPHENE_DEFAULT_FORCE_SETTLEMENT_MAX_VOLUME;
result[ "GRAPHENE_DEFAULT_PRICE_FEED_LIFETIME" ] = GRAPHENE_DEFAULT_PRICE_FEED_LIFETIME;
result[ "GRAPHENE_MAX_FEED_PRODUCERS" ] = GRAPHENE_MAX_FEED_PRODUCERS;
result[ "GRAPHENE_DEFAULT_MAX_AUTHORITY_MEMBERSHIP" ] = GRAPHENE_DEFAULT_MAX_AUTHORITY_MEMBERSHIP;
result[ "GRAPHENE_DEFAULT_MAX_ASSET_WHITELIST_AUTHORITIES" ] = GRAPHENE_DEFAULT_MAX_ASSET_WHITELIST_AUTHORITIES;
result[ "GRAPHENE_DEFAULT_MAX_ASSET_FEED_PUBLISHERS" ] = GRAPHENE_DEFAULT_MAX_ASSET_FEED_PUBLISHERS;
result[ "GRAPHENE_COLLATERAL_RATIO_DENOM" ] = GRAPHENE_COLLATERAL_RATIO_DENOM;
result[ "GRAPHENE_MIN_COLLATERAL_RATIO" ] = GRAPHENE_MIN_COLLATERAL_RATIO;
result[ "GRAPHENE_MAX_COLLATERAL_RATIO" ] = GRAPHENE_MAX_COLLATERAL_RATIO;
result[ "GRAPHENE_DEFAULT_MAINTENANCE_COLLATERAL_RATIO" ] = GRAPHENE_DEFAULT_MAINTENANCE_COLLATERAL_RATIO;
result[ "GRAPHENE_DEFAULT_MAX_SHORT_SQUEEZE_RATIO" ] = GRAPHENE_DEFAULT_MAX_SHORT_SQUEEZE_RATIO;
result[ "GRAPHENE_DEFAULT_MARGIN_PERIOD_SEC" ] = GRAPHENE_DEFAULT_MARGIN_PERIOD_SEC;
result[ "GRAPHENE_DEFAULT_MAX_MINERS" ] = GRAPHENE_DEFAULT_MAX_MINERS;
result[ "GRAPHENE_DEFAULT_MAX_GUARDS" ] = GRAPHENE_DEFAULT_MAX_GUARDS;
result[ "GRAPHENE_DEFAULT_MAX_PROPOSAL_LIFETIME_SEC" ] = GRAPHENE_DEFAULT_MAX_PROPOSAL_LIFETIME_SEC;
result[ "GRAPHENE_DEFAULT_COMMITTEE_PROPOSAL_REVIEW_PERIOD_SEC" ] = GRAPHENE_DEFAULT_GUARD_PROPOSAL_REVIEW_PERIOD_SEC;
result[ "GRAPHENE_DEFAULT_NETWORK_PERCENT_OF_FEE" ] = GRAPHENE_DEFAULT_NETWORK_PERCENT_OF_FEE;
result[ "GRAPHENE_DEFAULT_LIFETIME_REFERRER_PERCENT_OF_FEE" ] = GRAPHENE_DEFAULT_LIFETIME_REFERRER_PERCENT_OF_FEE;
result[ "GRAPHENE_DEFAULT_MAX_BULK_DISCOUNT_PERCENT" ] = GRAPHENE_DEFAULT_MAX_BULK_DISCOUNT_PERCENT;
result[ "GRAPHENE_DEFAULT_BULK_DISCOUNT_THRESHOLD_MIN" ] = GRAPHENE_DEFAULT_BULK_DISCOUNT_THRESHOLD_MIN;
result[ "GRAPHENE_DEFAULT_BULK_DISCOUNT_THRESHOLD_MAX" ] = GRAPHENE_DEFAULT_BULK_DISCOUNT_THRESHOLD_MAX;
result[ "GRAPHENE_DEFAULT_CASHBACK_VESTING_PERIOD_SEC" ] = GRAPHENE_DEFAULT_CASHBACK_VESTING_PERIOD_SEC;
result[ "GRAPHENE_DEFAULT_CASHBACK_VESTING_THRESHOLD" ] = GRAPHENE_DEFAULT_CASHBACK_VESTING_THRESHOLD;
result[ "GRAPHENE_DEFAULT_BURN_PERCENT_OF_FEE" ] = GRAPHENE_DEFAULT_BURN_PERCENT_OF_FEE;
result[ "GRAPHENE_WITNESS_PAY_PERCENT_PRECISION" ] = GRAPHENE_WITNESS_PAY_PERCENT_PRECISION;
result[ "GRAPHENE_DEFAULT_MAX_ASSERT_OPCODE" ] = GRAPHENE_DEFAULT_MAX_ASSERT_OPCODE;
result[ "GRAPHENE_DEFAULT_FEE_LIQUIDATION_THRESHOLD" ] = GRAPHENE_DEFAULT_FEE_LIQUIDATION_THRESHOLD;
result[ "GRAPHENE_DEFAULT_ACCOUNTS_PER_FEE_SCALE" ] = GRAPHENE_DEFAULT_ACCOUNTS_PER_FEE_SCALE;
result[ "GRAPHENE_DEFAULT_ACCOUNT_FEE_SCALE_BITSHIFTS" ] = GRAPHENE_DEFAULT_ACCOUNT_FEE_SCALE_BITSHIFTS;
result[ "GRAPHENE_MAX_WORKER_NAME_LENGTH" ] = GRAPHENE_MAX_WORKER_NAME_LENGTH;
result[ "GRAPHENE_MAX_URL_LENGTH" ] = GRAPHENE_MAX_URL_LENGTH;
result[ "GRAPHENE_NEAR_SCHEDULE_CTR_IV" ] = GRAPHENE_NEAR_SCHEDULE_CTR_IV;
result[ "GRAPHENE_FAR_SCHEDULE_CTR_IV" ] = GRAPHENE_FAR_SCHEDULE_CTR_IV;
result[ "GRAPHENE_CORE_ASSET_CYCLE_RATE" ] = GRAPHENE_CORE_ASSET_CYCLE_RATE;
result[ "GRAPHENE_CORE_ASSET_CYCLE_RATE_BITS" ] = GRAPHENE_CORE_ASSET_CYCLE_RATE_BITS;
result[ "GRAPHENE_DEFAULT_WITNESS_PAY_PER_BLOCK" ] = GRAPHENE_DEFAULT_WITNESS_PAY_PER_BLOCK;
result[ "GRAPHENE_DEFAULT_miner_pay_vesting_seconds" ] = GRAPHENE_DEFAULT_miner_pay_vesting_seconds;
result[ "GRAPHENE_DEFAULT_WORKER_BUDGET_PER_DAY" ] = GRAPHENE_DEFAULT_WORKER_BUDGET_PER_DAY;
result[ "GRAPHENE_MAX_INTEREST_APR" ] = GRAPHENE_MAX_INTEREST_APR;
result[ "GRAPHENE_GUARD_ACCOUNT" ] = GRAPHENE_GUARD_ACCOUNT;
result[ "GRAPHENE_MINER_ACCOUNT" ] = GRAPHENE_MINER_ACCOUNT;
result[ "GRAPHENE_RELAXED_COMMITTEE_ACCOUNT" ] = GRAPHENE_RELAXED_COMMITTEE_ACCOUNT;
result[ "GRAPHENE_NULL_ACCOUNT" ] = GRAPHENE_NULL_ACCOUNT;
result[ "GRAPHENE_TEMP_ACCOUNT" ] = GRAPHENE_TEMP_ACCOUNT;
return result;
}
} } // graphene::chain
|
//
// Created by kazem on 4/23/17.
//
#include <atomic>
#include <fstream>
#include <iostream>
#include <sstream>
#include "Util.h"
namespace Sympiler {
namespace Internal {
namespace {
// We use 64K of memory to store unique counters for the purpose of
// making names unique. Using less memory increases the likelihood of
// hash collisions. This wouldn't break anything, but makes stmts
// slightly confusing to read because names that are actually unique
// will get suffixes that falsely hint that they are not.
const int num_unique_name_counters = (1 << 14);
std::atomic<int> unique_name_counters[num_unique_name_counters];
int unique_count(size_t h) {
h = h & (num_unique_name_counters - 1);
return unique_name_counters[h]++;
}
}
// There are three possible families of names returned by the methods below:
// 1) char pattern: (char that isn't '$') + number (e.g. v234)
// 2) string pattern: (string without '$') + '$' + number (e.g. fr#nk82$42)
// 3) a string that does not match the patterns above
// There are no collisions within each family, due to the unique_count
// done above, and there can be no collisions across families by
// construction.
std::string unique_name(char prefix) {
if (prefix == '$') prefix = '_';
return prefix + std::to_string(unique_count((size_t) (prefix)));
}
std::string unique_name(const std::string &prefix) {
std::string sanitized = prefix;
// Does the input string look like something returned from unique_name(char)?
bool matches_char_pattern = true;
// Does the input string look like something returned from unique_name(string)?
bool matches_string_pattern = true;
// Rewrite '$' to '_'. This is a many-to-one mapping, but that's
// OK, we're about to hash anyway. It just means that some names
// will share the same counter.
int num_dollars = 0;
for (size_t i = 0; i < sanitized.size(); i++) {
if (sanitized[i] == '$') {
num_dollars++;
sanitized[i] = '_';
}
if (i > 0 && !isdigit(sanitized[i])) {
// Found a non-digit after the first char
matches_char_pattern = false;
if (num_dollars) {
// Found a non-digit after a '$'
matches_string_pattern = false;
}
}
}
matches_string_pattern &= num_dollars == 1;
matches_char_pattern &= prefix.size() > 1;
// Then add a suffix that's globally unique relative to the hash
// of the sanitized name.
int count = unique_count(std::hash<std::string>()(sanitized));
if (count == 0) {
// We can return the name as-is if there's no risk of it
// looking like something unique_name has ever returned in the
// past or will ever return in the future.
if (!matches_char_pattern && !matches_string_pattern) {
return prefix;
}
}
return sanitized + "$" + std::to_string(count);
}
bool readCSCMatrixPattern(std::string fName, int &n, int& m, int &NNZ, int* &col,
int* &row){
/*This function reads the input matrix from "fName" file and
* allocate memory for matrix A, L and U.
* - The input file is a coordinate version and e
* ach row of the file shows (col, row, nnz)
* - The matrices are zero-indexed
*/
std::ifstream inFile;
inFile.open(fName);
std::string line,banner, mtx, crd, arith, sym;
/* File format:
* %%MatrixMarket matrix coordinate real general/symmetric/...
* % ...
* % (optional comments)
* % ...
* #rows #non-zero
* Triplet in the rest of lines: row col value
*/
std::getline(inFile,line);
for (unsigned i=0; i<line.length(); line[i]=tolower(line[i]),i++);
std::istringstream iss(line);
if (!(iss >> banner >> mtx >> crd >> arith >> sym)){
std::cout<<"Invalid header (first line does not contain 5 tokens)\n";
return false;
}
if(banner.compare("%%matrixmarket")) {
std::cout<<"Invalid header (first token is not \"%%%%MatrixMarket\")\n";
return false;
}
if(mtx.compare("matrix")) {
std::cout<<"Not a matrix; this driver cannot handle that.\"\n";
return false;
}
if(crd.compare("coordinate")) {
std::cout<<"Not in coordinate format; this driver cannot handle that.\"\n";
return false;
}
if(arith.compare("real") and arith.compare("integer")) {
if(!arith.compare("complex")) {
std::cout<<"Complex matrix; use zreadMM instead!\n";
return false;
}
else if(!arith.compare("pattern")) {
std::cout<<"Pattern matrix; values are needed!\n";
return false;
}
else {
std::cout<<"Unknown arithmetic\n";
return false;
}
}
while (!line.compare(0,1,"%"))
{
std::getline(inFile, line);
}
std::istringstream issDim(line);
if (!(issDim >> n >> n >> NNZ)){
std::cout<<"The matrix dimension is missing\n";
return false;
}
if(n <= 0 || NNZ <= 0)
return false;
col = new int[n + 1]();
// colL = new int[n + 1]; colU = new int[n + 1];
row = new int[NNZ];
// rowL = new int[factorSize]; rowU = new int[factorSize];
// valL = new double[factorSize]; valU = new double[factorSize];
if( !col || !row)
return false;
//Initializing the result vector
int y, x, colCnt=0, nnzCnt=0;
double value;
col[0]=0;
for (int i = 0; nnzCnt<NNZ; ) {//Reading from file row by row
inFile>>x;x--;
inFile>>y;y--;//zero indexing
inFile>>value;
if(y > n)
return false;
if(y==i){
row[nnzCnt]=x;
colCnt++; nnzCnt++;
}
else{//New col
col[i+1]=col[i]+colCnt;
i++;//next iteration
colCnt=1;
row[nnzCnt]=x;
nnzCnt++;
}
}
col[n]= col[n - 1] + colCnt;//last col
return true;
}
}
}
|
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/shelf/swipe_home_to_overview_controller.h"
#include "ash/app_list/app_list_controller_impl.h"
#include "ash/constants/ash_features.h"
#include "ash/public/cpp/app_list/app_list_config.h"
#include "ash/public/cpp/shelf_config.h"
#include "ash/session/session_controller_impl.h"
#include "ash/shelf/contextual_tooltip.h"
#include "ash/shelf/drag_window_from_shelf_controller.h"
#include "ash/shelf/shelf_metrics.h"
#include "ash/shell.h"
#include "ash/wm/overview/overview_controller.h"
#include "ash/wm/overview/overview_session.h"
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/cxx17_backports.h"
#include "base/metrics/histogram_macros.h"
#include "base/time/default_tick_clock.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/compositor/layer_animation_element.h"
#include "ui/compositor/scoped_layer_animation_settings.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"
#include "ui/gfx/animation/tween.h"
namespace ash {
namespace {
// The target/min home launcher view scale.
constexpr float kTargetHomeScale = 0.92f;
// The home UI will be scaled down towards center of the screen as drag location
// moves upwards. The target threshold for scaling is extended above the actual
// threshold for transition so the UI keeps changing even when the gesture goes
// over the threshold. This is the target home screen scaling threshold in terms
// of ratio of the display height.
constexpr float kHomeScalingThresholdDisplayHeightRatio = 0.5f;
// The amount of time the drag has to remain bellow velocity threshold before
// the transition to the overview starts.
constexpr base::TimeDelta kOverviewTransitionDelay = base::Milliseconds(150);
// The duration of transition from the home screen current scaled state to the
// initial (unscaled) state when the gesture is canceled.
constexpr base::TimeDelta kGestureCancelationDuration = base::Milliseconds(350);
// The duration of transition from the home screen current scaled state to the
// initial (unscaled) state when the gesture is canceled due to a back gesture.
constexpr base::TimeDelta kGestureCancelationForBackDuration =
base::Milliseconds(250);
void UpdateHomeAnimationForGestureCancel(
bool going_back,
ui::ScopedLayerAnimationSettings* settings) {
settings->SetTransitionDuration(going_back
? kGestureCancelationForBackDuration
: kGestureCancelationDuration);
settings->SetTweenType(gfx::Tween::FAST_OUT_SLOW_IN);
settings->SetPreemptionStrategy(
ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET);
}
} // namespace
SwipeHomeToOverviewController::SwipeHomeToOverviewController(int64_t display_id)
: SwipeHomeToOverviewController(display_id,
base::DefaultTickClock::GetInstance()) {}
SwipeHomeToOverviewController::SwipeHomeToOverviewController(
int64_t display_id,
const base::TickClock* tick_clock)
: display_id_(display_id), overview_transition_timer_(tick_clock) {}
SwipeHomeToOverviewController::~SwipeHomeToOverviewController() {
CancelDrag();
}
void SwipeHomeToOverviewController::Drag(const gfx::PointF& location_in_screen,
float scroll_x,
float scroll_y) {
if (state_ == State::kFinished)
return;
display::Display display;
if (!display::Screen::GetScreen()->GetDisplayWithDisplayId(display_id_,
&display)) {
CancelDrag();
return;
}
const int shelf_top =
display.bounds().bottom() - ShelfConfig::Get()->shelf_size();
if (state_ == State::kInitial) {
// Do not start drag until the drag goes above the shelf.
if (location_in_screen.y() > shelf_top)
return;
overview_transition_threshold_y_ =
shelf_top - kVerticalThresholdForOverviewTransition;
scaling_threshold_y_ =
display.bounds().y() +
display.bounds().height() * kHomeScalingThresholdDisplayHeightRatio;
state_ = State::kTrackingDrag;
home_screen_blur_disabler_ =
Shell::Get()->app_list_controller()->DisableHomeScreenBackgroundBlur();
} else {
if (location_in_screen.y() <= overview_transition_threshold_y_ &&
std::abs(scroll_x) + std::abs(scroll_y) <= kMovementVelocityThreshold) {
ScheduleFinalizeDragAndShowOverview();
} else {
overview_transition_timer_.Stop();
}
}
// Update the home screen scale to match progress during the drag.
// Use extended threshold as the projected final transition position - UI
// changing even after the user gets over the threshold should make the user
// more likely to keep dragging up when they get really close to the threshold
// for transition to overview (and reduce false negatives for detecting
// transition to overview).
const float distance = location_in_screen.y() - scaling_threshold_y_;
const float target_distance = overview_transition_threshold_y_ -
scaling_threshold_y_ +
kVerticalThresholdForOverviewTransition;
const float progress = gfx::Tween::CalculateValue(
gfx::Tween::FAST_OUT_SLOW_IN,
base::clamp(1.f - distance / target_distance, 0.0f, 1.0f));
float scale = gfx::Tween::FloatValueBetween(progress, 1.0f, kTargetHomeScale);
Shell::Get()->app_list_controller()->UpdateScaleAndOpacityForHomeLauncher(
scale, 1.0f /*opacity*/, absl::nullopt /*animation_info*/,
base::NullCallback());
}
void SwipeHomeToOverviewController::EndDrag(
const gfx::PointF& location_in_screen,
absl::optional<float> velocity_y) {
if (state_ != State::kTrackingDrag) {
state_ = State::kFinished;
return;
}
// Upward swipe should return to the home screen's initial state.
const bool go_back =
velocity_y &&
*velocity_y <
-DragWindowFromShelfController::kVelocityToHomeScreenThreshold;
// Overview is triggered by |overview_transition_timer_|. If EndDrag()
// is called before the timer fires, the result of the gesture should be
// staying on the home screen.
FinalizeDragAndStayOnHomeScreen(go_back);
}
void SwipeHomeToOverviewController::CancelDrag() {
if (state_ != State::kTrackingDrag) {
state_ = State::kFinished;
return;
}
FinalizeDragAndStayOnHomeScreen(/*go_back=*/false);
}
void SwipeHomeToOverviewController::ScheduleFinalizeDragAndShowOverview() {
if (overview_transition_timer_.IsRunning())
return;
overview_transition_timer_.Start(
FROM_HERE, kOverviewTransitionDelay,
base::BindOnce(
&SwipeHomeToOverviewController::FinalizeDragAndShowOverview,
base::Unretained(this)));
}
void SwipeHomeToOverviewController::FinalizeDragAndShowOverview() {
state_ = State::kFinished;
overview_transition_threshold_y_ = 0;
if (features::AreContextualNudgesEnabled()) {
contextual_tooltip::HandleGesturePerformed(
Shell::Get()->session_controller()->GetActivePrefService(),
contextual_tooltip::TooltipType::kHomeToOverview);
}
UMA_HISTOGRAM_ENUMERATION(kEnterOverviewHistogramName,
EnterOverviewFromHomeLauncher::kOverview);
// NOTE: No need to update the home launcher opacity and scale here - the
// AppListControllerImpl will update the home launcher state when it detects
// that the overview is starting.
Shell::Get()->overview_controller()->StartOverview(
OverviewStartAction::kExitHomeLauncher);
// No need to keep blur disabled for the drag - note that blur might remain
// disabled at this point due to the started overview transition (which
// triggers home screen scale animation).
home_screen_blur_disabler_.reset();
}
void SwipeHomeToOverviewController::FinalizeDragAndStayOnHomeScreen(
bool go_back) {
overview_transition_timer_.Stop();
overview_transition_threshold_y_ = 0;
state_ = State::kFinished;
if (go_back) {
Shell::Get()->app_list_controller()->Back();
UMA_HISTOGRAM_ENUMERATION(kEnterOverviewHistogramName,
EnterOverviewFromHomeLauncher::kBack);
} else {
UMA_HISTOGRAM_ENUMERATION(kEnterOverviewHistogramName,
EnterOverviewFromHomeLauncher::kCanceled);
}
// Make sure the home launcher scale and opacity return to the initial state.
// Note that this is needed even if the gesture ended up in a fling, as early
// gesture handling might have updated the launcher scale.
Shell::Get()->app_list_controller()->UpdateScaleAndOpacityForHomeLauncher(
1.0f /*scale*/, 1.0f /*opacity*/, absl::nullopt /*animation_info*/,
base::BindRepeating(&UpdateHomeAnimationForGestureCancel, go_back));
// No need to keep blur disabled for the drag - note that blur might remain
// disabled at this point due to the started home screen scale animation.
home_screen_blur_disabler_.reset();
}
} // namespace ash
|
#include <unistd.h>
#include "../simpleServer/abstractStream.h"
#include "../simpleServer/abstractService.h"
#include "../simpleServer/shared/stdLogOutput.h"
using namespace simpleServer;
int main(int argc, char **argv) {
return
ServiceControl::create(argc, argv,"exampleService",[](ServiceControl control, StrViewA name, ArgList args) {
std::cout << "Service running: " << name << std::endl;
control.dispatch();
return 0;
});
}
|
/*
* Copyright (c) 2020, the SerenityOS developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/QuickSort.h>
#include <LibGUI/RegularEditingEngine.h>
#include <LibGUI/TextEditor.h>
namespace GUI {
CursorWidth RegularEditingEngine::cursor_width() const
{
return CursorWidth::NARROW;
}
bool RegularEditingEngine::on_key(const KeyEvent& event)
{
if (EditingEngine::on_key(event))
return true;
if (event.key() == KeyCode::Key_Escape) {
if (m_editor->on_escape_pressed)
m_editor->on_escape_pressed();
return true;
}
if (event.alt() && event.shift() && event.key() == KeyCode::Key_S) {
sort_selected_lines();
return true;
}
return false;
}
static int strcmp_utf32(const u32* s1, const u32* s2, size_t n)
{
while (n-- > 0) {
if (*s1++ != *s2++)
return s1[-1] < s2[-1] ? -1 : 1;
}
return 0;
}
void RegularEditingEngine::sort_selected_lines()
{
if (!m_editor->is_editable())
return;
if (!m_editor->has_selection())
return;
size_t first_line;
size_t last_line;
get_selection_line_boundaries(first_line, last_line);
auto& lines = m_editor->document().lines();
auto start = lines.begin() + (int)first_line;
auto end = lines.begin() + (int)last_line + 1;
quick_sort(start, end, [](auto& a, auto& b) {
return strcmp_utf32(a.code_points(), b.code_points(), min(a.length(), b.length())) < 0;
});
m_editor->did_change();
m_editor->update();
}
}
|
#include "threading.hpp"
// Thread_wait
void forest::Thread_wait::inc(){
std::unique_lock<std::mutex> lock(m);
++count;
}
void forest::Thread_wait::dec(){
std::unique_lock<std::mutex> lock(m);
if(--count == 0){
cv.notify_all();
}
}
void forest::Thread_wait::wait(){
std::unique_lock<std::mutex> lock(m);
while (count > 0) {
cv.wait(lock);
}
}
// Thread_worker
forest::Thread_worker::Thread_worker(){
t = std::thread([this]{
while(true){
work_fn fn;
{
auto lock = get_lock();
while(q.empty()){
busy = false;
notify();
if(!active) return;
cv.wait(lock);
}
busy = true;
fn = q.front();
q.pop();
}
fn();
}
});
}
forest::Thread_worker::~Thread_worker(){
close();
t.join();
}
void forest::Thread_worker::close(){
auto lock = get_lock();
active = false;
notify();
}
void forest::Thread_worker::work(work_fn f){
auto lock = get_lock();
q.push(f);
notify();
}
void forest::Thread_worker::wait(){
auto lock = get_lock();
while(busy){
cv.wait(lock);
}
}
bool forest::Thread_worker::is_busy(){
return busy;
}
void forest::Thread_worker::notify(){
cv.notify_all();
}
forest::Thread_worker::lock_t forest::Thread_worker::get_lock(){
return lock_t(m);
}
|
/**
@file main.cpp
*/
#include <Arduino.h>
#include <Ticker.h>
#include "LedControlModule.h"
#include "ClockModule.h"
#include "WifiModule.h"
#include "Settings.h"
#include "AceButton.h"
#include "SimpleTime.h"
#include "ConfigModule.h"
#include "AmbientLightModule.h"
using namespace ace_button;
//-----------------------------------------------------
// Member Variables
//-----------------------------------------------------
NeoTopology<MyPanelLayout> topo(PANEL_WIDTH, PANEL_HEIGHT);
LedControlModule ledControlModule(topo);
NeoPixelBusType pixelStrip(PIXEL_COUNT);
ClockModule clockModule(Wire, LOCAL_TIMEZONE, NTP_SERVER_NAME);
WifiModule wifiModule(DEVICE_NAME);
ConfigModule configModule(CONFIG_FILE_PATH);
AmbientLightModule ambientLight(LIGHT_SENSOR_PIN, MAXIMUM_LIGHT_VALUE);
AceButton buttonOne(new ButtonConfig());
AceButton buttonTwo(new ButtonConfig());
AceButton buttonThree(new ButtonConfig());
AceButton buttonFour(new ButtonConfig());
unsigned long lastClockUpdate = 0;
unsigned long lastShowTime = 0;
unsigned long lastLightUpdate = 0;
bool showTimeDisabled = false;
int currentLedColorId = 0;
RgbwColor currentLedColor = LED_COLORS[currentLedColorId];
Config config;
//-----------------------------------------------------
// Function Declarations
//-----------------------------------------------------
void handleButtonOneEvent(AceButton*, uint8_t, uint8_t);
void handleButtonTwoEvent(AceButton*, uint8_t, uint8_t);
void handleButtonThreeEvent(AceButton*, uint8_t, uint8_t);
void handleButtonFourEvent(AceButton*, uint8_t, uint8_t);
void updateClock();
void updateLedColor();
void setButtonConfig(ButtonConfig* buttonConfig, ButtonConfig::EventHandler eventHandler);
void setupButtons();
void showTime();
void configModeCallback (WiFiManager *myWiFiManager);
void saveConfigCallback();
//-----------------------------------------------------
// Function Definitions
//-----------------------------------------------------
/**
* Setup all Modules
*/
void setup() {
Serial.begin(9600);
pinMode(BUILTIN_LED, OUTPUT);
Serial.println("Setup start.");
Serial.println("loadConfig:");
configModule.setup();
config = configModule.loadConfig();
currentLedColorId = config.setLedColor;
updateLedColor();
ledControlModule.setup(&pixelStrip);
setupButtons();
wifiModule.setup(configModeCallback, saveConfigCallback);
//wifiModule.reset();
wifiModule.connect();
clockModule.setup();
updateClock();
lastClockUpdate = millis();
showTime();
lastShowTime = millis();
Serial.println("Setup done.");
}
/**
* Setup Event Handlers of a Button
* @param buttonConfig
* @param eventHandler
*/
void setButtonConfig(ButtonConfig* buttonConfig, ButtonConfig::EventHandler eventHandler) {
buttonConfig->setEventHandler(eventHandler);
buttonConfig->setFeature(ButtonConfig::kFeatureClick);
buttonConfig->setFeature(ButtonConfig::kFeatureDoubleClick);
buttonConfig->setFeature(ButtonConfig::kFeatureLongPress);
// buttonConfig->setFeature(ButtonConfig::kFeatureRepeatPress);
}
/**
* Setup all four Buttons.
*/
void setupButtons() {
pinMode(BUTTON_ONE_PIN, INPUT);
buttonOne.init(BUTTON_ONE_PIN, LOW);
pinMode(BUTTON_TWO_PIN, INPUT);
buttonTwo.init(BUTTON_TWO_PIN, LOW);
pinMode(BUTTON_THREE_PIN, INPUT);
buttonThree.init(BUTTON_THREE_PIN, LOW);
pinMode(BUTTON_FOUR_PIN, INPUT);
buttonFour.init(BUTTON_FOUR_PIN, LOW);
setButtonConfig(buttonOne.getButtonConfig(), handleButtonOneEvent);
setButtonConfig(buttonTwo.getButtonConfig(), handleButtonTwoEvent);
setButtonConfig(buttonThree.getButtonConfig(), handleButtonThreeEvent);
setButtonConfig(buttonFour.getButtonConfig(), handleButtonFourEvent);
}
/**
* Main Loop
*/
void loop() {
if((millis() - lastClockUpdate) > (CLOCK_UPDATE_INTERVAL * 1000)) {
updateClock();
lastClockUpdate = millis();
}
if((millis() - lastShowTime) > (TIME_UPDATE_INTERVAL * 1000) && !showTimeDisabled) {
updateLedColor();
showTime();
lastShowTime = millis();
}
buttonOne.check();
buttonTwo.check();
buttonThree.check();
buttonFour.check();
}
/**
* Gets called when WiFiManager enters configuration mode
* @param myWiFiManager
*/
void configModeCallback (WiFiManager *myWiFiManager) {
Serial.println("Entered config mode");
showTimeDisabled = true;
ledControlModule.showConfigWifi();
}
/**
* Gets called when WifiManager when custom parameters have been set AND a connection has been established.
*/
void saveConfigCallback() {
Serial.println("Save callback.");
config.enableTime = wifiModule.getEnableTime();
config.disableTime = wifiModule.getDisableTime();
configModule.saveConfig(config);
showTimeDisabled = false;
showTime();
}
/**
* Get Time from RTC and update if it is not correct from NTP. Only show time if it is bound in enabled time range.
*/
void showTime() {
Serial.println("disableTime: " + config.disableTime.toString());
Serial.println("enableTime: " + config.enableTime.toString());
if(!clockModule.isDateTimeValid()) {
updateClock();
}
const SimpleTime st = clockModule.getLocalSimpleTime();
if(config.disableTime == config.enableTime ||
!(((config.disableTime > config.enableTime) && (config.disableTime <= st && config.enableTime < st)) ||
((config.disableTime < config.enableTime) && (config.disableTime <= st && config.enableTime > st)))) {
Serial.println("Show Time: " + st.toString());
ledControlModule.showTime(st, currentLedColor);
} else {
Serial.println("Show Time: LED DISABLED");
ledControlModule.disableLeds();
}
}
/**
* Connect to Wifi and update RTC over NTP.
*/
void updateClock() {
Serial.println("Connect to wifi and update clock.");
if (!wifiModule.isConnected()) {
wifiModule.connect();
}
clockModule.update();
}
/**
* Apply ambient light by dimming currentLedColor.
*/
void updateLedColor() {
currentLedColor = LED_COLORS[currentLedColorId];
int darken = 255 - ambientLight.getBrightness();
currentLedColor.Darken(darken);
}
/**
* Handle clicks of 1. button from left.
* @param button
* @param eventType
* @param buttonState
*/
void handleButtonOneEvent(AceButton* button, uint8_t eventType,
uint8_t buttonState) {
switch (eventType) {
case AceButton::kEventClicked:
Serial.println("Button One Clicked");
currentLedColorId = (currentLedColorId + 1) % LED_COLORS_SIZE;
config.setLedColor = currentLedColorId;
configModule.saveConfig(config);
updateLedColor();
showTime();
break;
case AceButton::kEventLongPressed:
Serial.println("Button One Long Press");
if(!showTimeDisabled) {
Serial.println("Disable LED");
ledControlModule.disableLeds();
showTimeDisabled = true;
} else {
Serial.println("Enable LED");
showTime();
showTimeDisabled = false;
}
break;
}
}
/**
* Handle clicks of 2. button from left.
* @param button
* @param eventType
* @param buttonState
*/
void handleButtonTwoEvent(AceButton* button, uint8_t eventType,
uint8_t buttonState) {
switch (eventType) {
case AceButton::kEventClicked:
Serial.println("Button Two Clicked");
if(ambientLight.getBrightnessCorrection() > -9){
ambientLight.setBrightnessCorrection(ambientLight.getBrightnessCorrection() - 1);
Serial.println("Brightness Correction: " + ambientLight.getBrightnessCorrection());
};
// Serial.println("Current Brightness (out of 255):");
// Serial.println(ambientLight.getBrightness());
// Serial.println("with User Brightness Correction [-9 9]:");
// Serial.println(ambientLight.getBrightnessCorrection());
updateLedColor();
showTime();
break;
case AceButton::kEventLongPressed:
Serial.println("Button Two Long Press");
ambientLight.setBrightnessCorrection(0);
// Serial.println("User Brightness Correction Reset");
// Serial.println("Current Brightness (out of 255):");
// Serial.println(ambientLight.getBrightness());
updateLedColor();
showTime();
break;
}
}
/**
* Handle clicks of 3. button from left.
* @param button
* @param eventType
* @param buttonState
*/
void handleButtonThreeEvent(AceButton* button, uint8_t eventType,
uint8_t buttonState) {
switch (eventType) {
case AceButton::kEventClicked:
Serial.println("Button Three Clicked");
if(ambientLight.getBrightnessCorrection() < 9){
ambientLight.setBrightnessCorrection(ambientLight.getBrightnessCorrection() + 1);
Serial.println("Brightness Correction: " + ambientLight.getBrightnessCorrection());
};
// Serial.println("Current Brightness (out of 255):");
// Serial.println(ambientLight.getBrightness());
// Serial.println("with User Brightness Correction [-9 9]:");
// Serial.println(ambientLight.getBrightnessCorrection());
updateLedColor();
showTime();
break;
case AceButton::kEventLongPressed:
Serial.println("Button Three Long Press");
break;
}
}
/**
* Handle clicks of 4. button from left.
* @param button
* @param eventType
* @param buttonState
*/
void handleButtonFourEvent(AceButton* button, uint8_t eventType,
uint8_t buttonState) {
switch (eventType) {
case AceButton::kEventClicked:
Serial.println("Button Four Clicked");
updateClock();
break;
case AceButton::kEventLongPressed:
Serial.println("Button Four Long Press");
wifiModule.reset();
delay(1000);
wifiModule.connect();
break;
}
}
|
/**
* Licensed to Green Energy Corp (www.greenenergycorp.com) under one or
* more contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright ownership.
* Green Energy Corp licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This project was forked on 01/01/2013 by Automatak, LLC and modifications
* may have been made to this file. Automatak, LLC licenses these modifications
* to you under the terms of the License.
*/
#include "SerialTypes.h"
namespace asiopal
{
ParityType GetParityFromInt(int parity)
{
switch(parity)
{
case (1): return ParityType::EVEN;
case (2) : return ParityType::ODD;
default: return ParityType::NONE;
}
}
FlowType GetFlowTypeFromInt(int flowControl)
{
switch(flowControl)
{
case (1) : return FlowType::HARDWARE;
case (2) : return FlowType::XONXOFF;
default: return FlowType::NONE;
}
}
}
|
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <map>
#include <string>
#include <google/protobuf/compiler/objectivec/objectivec_enum_field.h>
#include <google/protobuf/compiler/objectivec/objectivec_helpers.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/wire_format.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace objectivec {
namespace {
void SetEnumVariables(const FieldDescriptor* descriptor,
std::map<std::string, std::string>* variables) {
std::string type = EnumName(descriptor->enum_type());
(*variables)["storage_type"] = type;
// For non repeated fields, if it was defined in a different file, the
// property decls need to use "enum NAME" rather than just "NAME" to support
// the forward declaration of the enums.
if (!descriptor->is_repeated() &&
(descriptor->file() != descriptor->enum_type()->file())) {
(*variables)["property_type"] = "enum " + type;
}
(*variables)["enum_verifier"] = type + "_IsValidValue";
(*variables)["enum_desc_func"] = type + "_EnumDescriptor";
(*variables)["dataTypeSpecific_name"] = "enumDescFunc";
(*variables)["dataTypeSpecific_value"] = (*variables)["enum_desc_func"];
const Descriptor* msg_descriptor = descriptor->containing_type();
(*variables)["owning_message_class"] = ClassName(msg_descriptor);
}
} // namespace
EnumFieldGenerator::EnumFieldGenerator(const FieldDescriptor* descriptor,
const Options& options)
: SingleFieldGenerator(descriptor, options) {
SetEnumVariables(descriptor, &variables_);
}
EnumFieldGenerator::~EnumFieldGenerator() {}
void EnumFieldGenerator::GenerateCFunctionDeclarations(
io::Printer* printer) const {
if (!HasPreservingUnknownEnumSemantics(descriptor_->file())) {
return;
}
printer->Print(
variables_,
"/**\n"
" * Fetches the raw value of a @c $owning_message_class$'s @c $name$ property, even\n"
" * if the value was not defined by the enum at the time the code was generated.\n"
" **/\n"
"int32_t $owning_message_class$_$capitalized_name$_RawValue($owning_message_class$ *message);\n"
"/**\n"
" * Sets the raw value of an @c $owning_message_class$'s @c $name$ property, allowing\n"
" * it to be set to a value that was not defined by the enum at the time the code\n"
" * was generated.\n"
" **/\n"
"void Set$owning_message_class$_$capitalized_name$_RawValue($owning_message_class$ *message, int32_t value);\n"
"\n");
}
void EnumFieldGenerator::GenerateCFunctionImplementations(
io::Printer* printer) const {
if (!HasPreservingUnknownEnumSemantics(descriptor_->file())) return;
printer->Print(
variables_,
"int32_t $owning_message_class$_$capitalized_name$_RawValue($owning_message_class$ *message) {\n"
" GPBDescriptor *descriptor = [$owning_message_class$ descriptor];\n"
" GPBFieldDescriptor *field = [descriptor fieldWithNumber:$field_number_name$];\n"
" return GPBGetMessageRawEnumField(message, field);\n"
"}\n"
"\n"
"void Set$owning_message_class$_$capitalized_name$_RawValue($owning_message_class$ *message, int32_t value) {\n"
" GPBDescriptor *descriptor = [$owning_message_class$ descriptor];\n"
" GPBFieldDescriptor *field = [descriptor fieldWithNumber:$field_number_name$];\n"
" GPBSetMessageRawEnumField(message, field, value);\n"
"}\n"
"\n");
}
void EnumFieldGenerator::DetermineForwardDeclarations(
std::set<std::string>* fwd_decls) const {
SingleFieldGenerator::DetermineForwardDeclarations(fwd_decls);
// If it is an enum defined in a different file, then we'll need a forward
// declaration for it. When it is in our file, all the enums are output
// before the message, so it will be declared before it is needed.
if (descriptor_->file() != descriptor_->enum_type()->file()) {
// Enum name is already in "storage_type".
const std::string& name = variable("storage_type");
fwd_decls->insert("GPB_ENUM_FWD_DECLARE(" + name + ")");
}
}
RepeatedEnumFieldGenerator::RepeatedEnumFieldGenerator(
const FieldDescriptor* descriptor, const Options& options)
: RepeatedFieldGenerator(descriptor, options) {
SetEnumVariables(descriptor, &variables_);
variables_["array_storage_type"] = "GPBEnumArray";
}
RepeatedEnumFieldGenerator::~RepeatedEnumFieldGenerator() {}
void RepeatedEnumFieldGenerator::FinishInitialization(void) {
RepeatedFieldGenerator::FinishInitialization();
variables_["array_comment"] =
"// |" + variables_["name"] + "| contains |" + variables_["storage_type"] + "|\n";
}
} // namespace objectivec
} // namespace compiler
} // namespace protobuf
} // namespace google
|
// Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "ngraph/validation_util.hpp"
#include <algorithm>
#include <ngraph/ops.hpp>
#include <ngraph/rt_info.hpp>
#include <numeric>
#include "ngraph/evaluator.hpp"
#include "ngraph/op/concat.hpp"
#include "ngraph/op/convert.hpp"
#include "ngraph/op/gather.hpp"
#include "ngraph/op/min.hpp"
#include "ngraph/op/minimum.hpp"
#include "ngraph/op/reshape.hpp"
#include "ngraph/op/shape_of.hpp"
#include "ngraph/op/squeeze.hpp"
#include "ngraph/op/unsqueeze.hpp"
#include "ngraph/shape.hpp"
#include "ngraph/type/element_type_traits.hpp"
#include "ngraph/util.hpp"
NGRAPH_SUPPRESS_DEPRECATED_START
using namespace std;
using namespace ngraph;
Strides ngraph::conv_default_strides(const Node* /* node */,
const PartialShape& data_batch_shape,
const PartialShape& filters_shape) {
size_t rank;
if (data_batch_shape.rank().is_static() && data_batch_shape.rank().get_length() >= 2) {
rank = data_batch_shape.rank().get_length() - 2;
} else if (filters_shape.rank().is_static() && filters_shape.rank().get_length() >= 2) {
rank = filters_shape.rank().get_length() - 2;
} else {
rank = 0;
}
return Strides(rank, 1);
}
CoordinateDiff ngraph::conv_default_padding(const Node* /* node */,
const PartialShape& data_batch_shape,
const PartialShape& filters_shape) {
size_t rank;
if (data_batch_shape.rank().is_static() && data_batch_shape.rank().get_length() >= 2) {
rank = data_batch_shape.rank().get_length() - 2;
} else if (filters_shape.rank().is_static() && filters_shape.rank().get_length() >= 2) {
rank = filters_shape.rank().get_length() - 2;
} else {
rank = 0;
}
return CoordinateDiff(rank, 0);
}
//
// Infers the output shape of a windowed reduction operation, where the data may be dilated and/or
// padded, and the reduction window may be strided and/or dilated.
//
// TODO(amprocte): The messages here would be a bit friendlier if we didn't say "after
// padding/after dilation" for cases where there is actually no padding/dilation.
//
PartialShape ngraph::infer_windowed_reduction_output_shape(const Node* node,
const PartialShape& data_shape,
const Strides& data_dilation,
const CoordinateDiff& data_padding_below,
const CoordinateDiff& data_padding_above,
const PartialShape& window_shape,
const Strides& window_strides,
const Strides& window_dilation,
bool is_window_all_in_padding_allowed,
bool ceil_mode) {
PartialShape data_shape_merged{PartialShape::dynamic()};
NODE_VALIDATION_CHECK(
node,
data_shape_merged.merge_rank(data_shape.rank()) && data_shape_merged.merge_rank(data_dilation.size()) &&
data_shape_merged.merge_rank(data_padding_below.size()) &&
data_shape_merged.merge_rank(data_padding_above.size()) &&
data_shape_merged.merge_rank(window_shape.rank()) && data_shape_merged.merge_rank(window_strides.size()) &&
data_shape_merged.merge_rank(window_dilation.size()),
"Ranks for data shape (",
data_shape,
"), data dilation (",
data_dilation,
"), padding below (",
data_padding_below,
"), padding above (",
data_padding_above,
"), window shape (",
window_shape,
"), window strides (",
window_strides,
"), and window dilation (",
window_dilation,
") do not match.");
PartialShape output_shape = PartialShape::dynamic(data_shape_merged.rank());
if (output_shape.rank().is_static()) {
for (int64_t i = 0; i < output_shape.rank().get_length(); i++) {
NODE_VALIDATION_CHECK(node,
data_dilation[i] > 0,
"Data dilation (",
data_dilation,
") has zero dimension at axis ",
i,
".");
NODE_VALIDATION_CHECK(node,
window_strides[i] > 0,
"Window strides (",
window_strides,
") has zero dimension at axis ",
i,
".");
NODE_VALIDATION_CHECK(node,
window_dilation[i] > 0,
"Window dilation (",
window_dilation,
") has zero dimension at axis ",
i,
".");
bool data_dim_static = data_shape.rank().is_static() && data_shape[i].is_static();
bool window_dim_static = window_shape.rank().is_static() && window_shape[i].is_static();
ptrdiff_t data_padded_dilated_dim = -1;
if (data_dim_static) {
data_padded_dilated_dim = (static_cast<int64_t>(data_dilation[i]) * (data_shape[i].get_length() - 1)) +
1 + data_padding_below[i] + data_padding_above[i];
NODE_VALIDATION_CHECK(node,
data_padded_dilated_dim > 0,
"Data shape after padding and dilation has dimension less than 1 (dim: ",
data_padded_dilated_dim,
") at axis ",
i,
".");
}
ptrdiff_t window_dilated_dim = -1;
if (window_dim_static) {
window_dilated_dim = static_cast<int64_t>(window_dilation[i]) * (window_shape[i].get_length() - 1) + 1;
NODE_VALIDATION_CHECK(node,
window_dilated_dim > 0,
"Window after dilation has dimension less than 1 (dim: ",
window_dilated_dim,
") at axis ",
i,
".");
NODE_VALIDATION_CHECK(node,
is_window_all_in_padding_allowed || (window_dilated_dim > data_padding_below[i] &&
window_dilated_dim > data_padding_above[i]),
"Window after dilation is sometimes entirely in the padding area for axis ",
i,
" (dilated window dimension: ",
window_dilated_dim,
", padding below dimension: ",
data_padding_below[i],
", padding above dimension: ",
data_padding_above[i],
") and this is not ",
"allowed.");
}
if (data_dim_static && window_dim_static) {
NODE_VALIDATION_CHECK(node,
window_dilated_dim <= data_padded_dilated_dim,
"Window after dilation has dimension (dim: ",
window_dilated_dim,
") larger than the data shape after padding (dim: ",
data_padded_dilated_dim,
") at axis ",
i,
".");
if (ceil_mode) {
output_shape[i] =
ceil_div(static_cast<size_t>(data_padded_dilated_dim) - static_cast<size_t>(window_dilated_dim),
window_strides[i]) +
1;
} else {
output_shape[i] =
((static_cast<size_t>(data_padded_dilated_dim) - static_cast<size_t>(window_dilated_dim)) /
window_strides[i]) +
1;
}
}
}
}
return output_shape;
}
void ngraph::validate_conv_params_spatial_dimensions(const Node* node,
const size_t num_spatial_dims,
const op::PadType auto_pad,
Strides& strides,
Strides& dilations,
CoordinateDiff& pads_begin,
CoordinateDiff& pads_end) {
if (strides.size() == 0) {
strides = Strides(num_spatial_dims, 1);
}
if (dilations.size() == 0) {
dilations = Strides(num_spatial_dims, 1);
}
if (pads_begin.size() == 0 || auto_pad == op::PadType::VALID) {
pads_begin = CoordinateDiff(num_spatial_dims, 0);
}
if (pads_end.size() == 0 || auto_pad == op::PadType::VALID) {
pads_end = CoordinateDiff(num_spatial_dims, 0);
}
NODE_VALIDATION_CHECK(node,
strides.size() == num_spatial_dims,
"Strides should be defined for all and only spatial features.");
NODE_VALIDATION_CHECK(node,
dilations.size() == num_spatial_dims,
"Dilations should be defined for all and only spatial features.");
NODE_VALIDATION_CHECK(node,
pads_begin.size() == num_spatial_dims && pads_end.size() == num_spatial_dims,
"Pads should be defined for all and only spatial features.");
}
PartialShape ngraph::validate_and_infer_convolution_forward_output_shape(const Node* node,
const Rank& result_ps_rank,
const PartialShape& data_batch_pshape,
const PartialShape& filters_pshape,
const op::PadType auto_pad,
Strides& strides,
Strides& dilations,
CoordinateDiff& pads_begin,
CoordinateDiff& pads_end) {
PartialShape result_shape = PartialShape::dynamic();
if (result_ps_rank.is_static()) {
const auto num_spatial_dims = result_ps_rank.get_length() - 2;
validate_conv_params_spatial_dimensions(node,
num_spatial_dims,
auto_pad,
strides,
dilations,
pads_begin,
pads_end);
result_shape = PartialShape::dynamic(result_ps_rank);
if (data_batch_pshape.rank().is_static()) {
result_shape[0] = data_batch_pshape[0]; // batch size
}
if (filters_pshape.rank().is_static()) {
result_shape[1] = filters_pshape[0]; // filter channel size
}
if (auto_pad == op::PadType::SAME_UPPER || auto_pad == op::PadType::SAME_LOWER) {
bool auto_padding_applied = false;
if (filters_pshape.rank().is_static() && filters_pshape.rank().get_length() > 2) {
pads_begin.clear();
pads_end.clear();
const PartialShape filter_spatial_shape = [filters_pshape]() {
vector<Dimension> filter_dims{filters_pshape};
filter_dims.erase(filter_dims.begin(),
filter_dims.begin() + 2); // Remove {C_OUT, C_IN}
return PartialShape{filter_dims};
}();
if (filter_spatial_shape.is_static()) {
auto_padding_applied = try_apply_auto_padding(data_batch_pshape,
filter_spatial_shape.to_shape(),
strides,
dilations,
auto_pad,
pads_end,
pads_begin);
}
}
if (!auto_padding_applied) {
return result_shape;
}
}
result_shape = infer_convolution_forward(node,
data_batch_pshape,
Strides(num_spatial_dims, 1), // dummy data dilations
pads_begin,
pads_end,
filters_pshape,
strides,
dilations);
}
return result_shape;
}
//
// Infers the output batch shape and element type for convolution fprop.
//
PartialShape ngraph::infer_convolution_forward(const Node* node,
const PartialShape& data_batch_shape,
const Strides& data_dilation,
const CoordinateDiff& data_padding_below,
const CoordinateDiff& data_padding_above,
const PartialShape& filters_shape,
const Strides& filter_strides,
const Strides& filter_dilation) {
Rank data_batch_filters_rank{Rank::dynamic()};
NODE_VALIDATION_CHECK(node,
Rank::merge(data_batch_filters_rank, data_batch_shape.rank(), filters_shape.rank()),
"Data batch and filters rank do not match (data batch shape: ",
data_batch_shape,
", filters shape: ",
filters_shape,
").");
NODE_VALIDATION_CHECK(node,
data_batch_filters_rank.is_dynamic() || data_batch_filters_rank.get_length() >= 3,
"Data batch and filters must have rank of at least 3 (one batch axis, ",
"one input-channel axis, and at least one spatial dimension) ",
"(data batch shape: ",
data_batch_shape,
", filters shape: ",
filters_shape,
").");
Rank spatial_rank{Rank::dynamic()};
NODE_VALIDATION_CHECK(node,
Rank::merge(spatial_rank, spatial_rank, data_batch_filters_rank - 2) &&
Rank::merge(spatial_rank, spatial_rank, data_dilation.size()) &&
Rank::merge(spatial_rank, spatial_rank, data_padding_below.size()) &&
Rank::merge(spatial_rank, spatial_rank, data_padding_above.size()) &&
Rank::merge(spatial_rank, spatial_rank, filter_strides.size()) &&
Rank::merge(spatial_rank, spatial_rank, filter_dilation.size()),
"Ranks for data item shape/filters shape (data batch has shape ",
data_batch_shape,
", so data item rank is ",
(data_batch_shape.rank() - 2),
" and filters have shape ",
filters_shape,
", so filters spatial rank is ",
(filters_shape.rank() - 2),
"), data dilation (",
data_dilation,
"), padding below (",
data_padding_below,
"), padding above (",
data_padding_above,
"), filter strides (",
filter_strides,
"), and filter dilation (",
filter_dilation,
") do not match.");
Dimension batch_size = (data_batch_shape.rank().is_static() ? data_batch_shape[0] : Dimension::dynamic());
Dimension data_channel_count = (data_batch_shape.rank().is_static() ? data_batch_shape[1] : Dimension::dynamic());
PartialShape data_spatial_shape(PartialShape::dynamic(spatial_rank));
Dimension filter_output_channel_count =
(filters_shape.rank().is_static() ? filters_shape[0] : Dimension::dynamic());
Dimension filter_input_channel_count = (filters_shape.rank().is_static() ? filters_shape[1] : Dimension::dynamic());
PartialShape filter_spatial_shape(PartialShape::dynamic(spatial_rank));
//
// Note: spatial_rank is definitely static at this point.
//
for (int64_t i = 0; i < spatial_rank.get_length(); i++) {
if (data_batch_shape.rank().is_static()) {
data_spatial_shape[i] = data_batch_shape[i + 2];
}
if (filters_shape.rank().is_static()) {
filter_spatial_shape[i] = filters_shape[i + 2];
}
}
NODE_VALIDATION_CHECK(node, batch_size.is_dynamic() || batch_size.get_length() > 0, "Batch size is zero.");
Dimension merged_channel_count;
NODE_VALIDATION_CHECK(node,
Dimension::merge(merged_channel_count, data_channel_count, filter_input_channel_count),
"Data batch channel count (",
data_channel_count,
") does not match filter input ",
"channel count (",
filter_input_channel_count,
").");
NODE_VALIDATION_CHECK(node,
merged_channel_count.is_dynamic() || merged_channel_count.get_length() > 0,
"Data batch channel count and/or filter input channel count is zero.");
NODE_VALIDATION_CHECK(node,
filter_output_channel_count.is_dynamic() || filter_output_channel_count.get_length() > 0,
"Filter output channel count is zero.");
PartialShape data_output_shape = infer_windowed_reduction_output_shape(node,
data_spatial_shape,
data_dilation,
data_padding_below,
data_padding_above,
filter_spatial_shape,
filter_strides,
filter_dilation,
true);
PartialShape batch_output_shape(PartialShape::dynamic(spatial_rank + 2));
batch_output_shape[0] = batch_size;
batch_output_shape[1] = filter_output_channel_count;
for (int64_t i = 0; i < spatial_rank.get_length(); i++) {
batch_output_shape[i + 2] = data_output_shape[i];
}
return batch_output_shape;
}
//
// Infers the output batch shape and element type for batched pooling fprop.
//
PartialShape ngraph::infer_batched_pooling_forward(const Node* node,
const PartialShape& data_batch_shape,
const CoordinateDiff& data_padding_below,
const CoordinateDiff& data_padding_above,
const PartialShape& window_shape,
const Strides& window_strides,
bool is_window_all_in_padding_allowed,
bool ceil_mode,
const Strides& window_dilation) {
NODE_VALIDATION_CHECK(node,
data_batch_shape.rank().is_dynamic() ||
(data_batch_shape.rank().get_length() >= 3 && data_batch_shape.rank().get_length() <= 5),
"Data batch must have rank of at least 4 or 5 (one batch axis, ",
"one input-channel axis, and two or three spatial dimension) ",
"(data batch shape: ",
data_batch_shape,
").");
PartialShape data_spatial_shape{PartialShape::dynamic()};
NODE_VALIDATION_CHECK(node,
data_spatial_shape.merge_rank(data_batch_shape.rank() - 2) &&
data_spatial_shape.merge_rank(data_padding_below.size()) &&
data_spatial_shape.merge_rank(data_padding_above.size()) &&
data_spatial_shape.merge_rank(window_shape.rank()) &&
data_spatial_shape.merge_rank(window_strides.size()),
"Ranks for data item shape (data batch has shape ",
data_batch_shape,
", so data item rank is ",
(data_batch_shape.rank() - 2),
"), padding below (",
data_padding_below,
"), padding above (",
data_padding_above,
"), window shape (",
window_shape,
"), and window strides (",
window_strides,
") do not match.");
Dimension batch_size{Dimension::dynamic()};
Dimension channel_count{Dimension::dynamic()};
PartialShape data_output_spatial_shape{PartialShape::dynamic(data_spatial_shape.rank())};
if (data_batch_shape.rank().is_static()) {
batch_size = data_batch_shape[0];
channel_count = data_batch_shape[1];
for (int64_t i = 0; i < data_spatial_shape.rank().get_length(); i++) {
data_spatial_shape[i] = data_batch_shape[i + 2];
}
NODE_VALIDATION_CHECK(node, batch_size.is_dynamic() || batch_size.get_length() > 0, "Batch size is zero.");
NODE_VALIDATION_CHECK(node,
channel_count.is_dynamic() || channel_count.get_length() > 0,
"Channel count is zero.");
// For pooling ops we don't need dilation, so we fill in the identity value (all 1).
Strides data_dilation(data_spatial_shape.rank().get_length(), 1);
Strides dilations = window_dilation;
// if the window_dilation was not specified, generate the default value (no dilations)
if (window_dilation.empty()) {
// dilations equal to 1 for each spatial axis mean that the window is not dilated
dilations = Strides(data_spatial_shape.rank().get_length(), 1);
}
data_output_spatial_shape = infer_windowed_reduction_output_shape(node,
data_spatial_shape,
data_dilation,
data_padding_below,
data_padding_above,
window_shape,
window_strides,
dilations,
is_window_all_in_padding_allowed,
ceil_mode);
}
PartialShape data_batch_output_shape{PartialShape::dynamic(data_output_spatial_shape.rank() + 2)};
data_batch_output_shape[0] = batch_size;
data_batch_output_shape[1] = channel_count;
for (int64_t i = 0; i < data_spatial_shape.rank().get_length(); i++) {
data_batch_output_shape[i + 2] = data_output_spatial_shape[i];
}
return data_batch_output_shape;
}
struct ChannelShapedInputSpec {
element::Type m_element_type;
PartialShape m_shape;
std::string m_input_name;
};
static std::tuple<element::Type, PartialShape, PartialShape> infer_batch_norm_forward_helper(
const Node* node,
element::Type input_element_type,
const PartialShape& input_shape,
const std::vector<ChannelShapedInputSpec>& channel_shaped_inputs) {
// Built up a slash-separated string naming all the channel-shaped inputs, for use in error
// messages.
std::stringstream ss;
bool first = true;
for (const auto& inp : channel_shaped_inputs) {
if (!first) {
ss << "/";
}
ss << inp.m_input_name;
first = false;
}
std::string channel_input_names = ss.str();
// Infer output element type.
element::Type et_result{input_element_type};
for (const auto& inp : channel_shaped_inputs) {
NODE_VALIDATION_CHECK(node,
element::Type::merge(et_result, et_result, inp.m_element_type),
"Input element types do not match.");
}
NODE_VALIDATION_CHECK(node,
et_result.is_dynamic() || et_result.is_real(),
"Input element types must be floating-point. Got: ",
et_result);
// Extract channel dimension from input shape.
Dimension channel_dim{Dimension::dynamic()};
Rank input_rank = input_shape.rank();
if (input_rank.is_static()) {
NODE_VALIDATION_CHECK(node,
input_rank.get_length() >= 2,
"Input argument must have rank of at least 2 (input argument shape: ",
input_shape,
").");
channel_dim = input_shape[1];
}
// Infer gamma/beta/mu/sigma shape, which must be consistent with a vector of size
// "channel_dim".
PartialShape channel_shape{PartialShape::dynamic()};
for (const auto& inp : channel_shaped_inputs) {
NODE_VALIDATION_CHECK(node,
PartialShape::merge_into(channel_shape, inp.m_shape),
"Shapes for ",
channel_input_names,
" do not match.");
}
NODE_VALIDATION_CHECK(node,
channel_shape.merge_rank(1),
"Shape for ",
channel_input_names,
" (",
channel_shape,
") does not have rank 1.");
NODE_VALIDATION_CHECK(node,
Dimension::merge(channel_dim, channel_dim, channel_shape[0]),
"Input channel dimension (",
channel_dim,
") does not match shape for ",
channel_input_names,
" (",
channel_shape,
").");
NODE_VALIDATION_CHECK(node,
channel_dim.is_dynamic() || channel_dim.get_length() >= 1,
"Channel count must be at least 1.");
// Batch result shape is same as the input shape, except we may possibly have inferred more
// information from the channel count via gamma/beta/etc.
PartialShape batch_result_shape{input_shape};
if (batch_result_shape.rank().is_static()) {
batch_result_shape[1] = channel_dim;
}
return std::make_tuple(et_result, batch_result_shape, PartialShape{channel_dim});
}
std::tuple<element::Type, PartialShape, PartialShape> ngraph::infer_batch_norm_forward(
const Node* node,
element::Type input_element_type,
element::Type gamma_element_type,
element::Type beta_element_type,
element::Type mean_element_type,
element::Type variance_element_type,
const PartialShape& input_shape,
const PartialShape& gamma_shape,
const PartialShape& beta_shape,
const PartialShape& mean_shape,
const PartialShape& variance_shape) {
return infer_batch_norm_forward_helper(node,
input_element_type,
input_shape,
{{gamma_element_type, gamma_shape, "gamma"},
{beta_element_type, beta_shape, "beta"},
{mean_element_type, mean_shape, "mean"},
{variance_element_type, variance_shape, "variance"}});
}
std::tuple<element::Type, PartialShape, PartialShape> ngraph::infer_batch_norm_forward(const Node* node,
element::Type input_element_type,
element::Type gamma_element_type,
element::Type beta_element_type,
const PartialShape& input_shape,
const PartialShape& gamma_shape,
const PartialShape& beta_shape) {
return infer_batch_norm_forward_helper(
node,
input_element_type,
input_shape,
{{gamma_element_type, gamma_shape, "gamma"}, {beta_element_type, beta_shape, "beta"}});
}
void ngraph::infer_auto_padding(const Shape& image_shape,
const Shape& filter_shape,
const Strides& filter_strides,
const Strides& filter_dilations,
const op::PadType pad_type,
CoordinateDiff& padding_above,
CoordinateDiff& padding_below) {
const auto image_dims = std::vector<Dimension>(std::begin(image_shape), std::end(image_shape));
// because image_shape is fully known result of try_apply_infer_auto_padding is ignored
try_apply_auto_padding(image_dims,
filter_shape,
filter_strides,
filter_dilations,
pad_type,
padding_above,
padding_below);
}
bool ngraph::try_apply_auto_padding(const PartialShape& image_shape,
const Shape& filter_shape,
const Strides& filter_strides,
const Strides& filter_dilations,
const op::PadType pad_type,
CoordinateDiff& padding_above,
CoordinateDiff& padding_below) {
NGRAPH_CHECK(pad_type == op::PadType::SAME_UPPER || pad_type == op::PadType::SAME_LOWER);
if (image_shape.rank().is_dynamic()) {
return false;
}
const auto image_dims = static_cast<std::vector<Dimension>>(image_shape);
for (size_t i = 0; i < static_cast<size_t>(filter_shape.size()); i++) {
if (image_dims[i + 2].is_static()) {
int64_t image_size = static_cast<int64_t>(image_dims[i + 2].get_length());
int64_t filter_size = (static_cast<int64_t>(filter_shape[i]) - 1) * filter_dilations[i] + 1;
int64_t filter_stride = static_cast<int64_t>(filter_strides[i]);
auto output_size = (image_size + filter_stride - 1) / filter_stride;
auto padding_needed = std::max(int64_t(0), (output_size - 1) * filter_stride + filter_size - image_size);
auto padding_lhs = padding_needed / 2;
auto padding_rhs = padding_needed - padding_lhs;
padding_below.push_back(pad_type == op::PadType::SAME_UPPER ? padding_lhs : padding_rhs);
padding_above.push_back(pad_type == op::PadType::SAME_UPPER ? padding_rhs : padding_lhs);
} else {
padding_below.push_back(0);
padding_above.push_back(0);
}
}
return true;
}
PartialShape ngraph::infer_slice_shape(const Node* node,
const PartialShape& input_shape,
const std::vector<int64_t>& begin,
const std::vector<int64_t>& end,
const std::vector<int64_t>& strides,
const AxisSet& begin_mask,
const AxisSet& end_mask,
const AxisSet& new_axis_mask,
const AxisSet& shrink_axis_mask,
const AxisSet& ellipsis_mask) {
if (begin.size() && end.size()) {
NODE_VALIDATION_CHECK(node,
begin.size() == end.size(),
"Lower bounds and Upper bounds needs to have same number of values");
}
if (begin.size() && strides.size()) {
NODE_VALIDATION_CHECK(node,
begin.size() == strides.size(),
"Lower bounds and strides needs to have same number of values");
}
if (end.size() && strides.size()) {
NODE_VALIDATION_CHECK(node,
end.size() == strides.size(),
"Upper bounds and strides needs to have same number of values");
}
NODE_VALIDATION_CHECK(node, ellipsis_mask.size() <= 1, "At most one ellipsis is allowed.");
if (input_shape.rank().is_dynamic()) {
return PartialShape::dynamic();
}
NODE_VALIDATION_CHECK(node,
input_shape.rank().get_length() + new_axis_mask.size() >= begin.size(),
"Input rank plus number of new axis has to be at least the size of Lower "
"and Upper bounds vector.");
std::vector<Dimension> dim;
int64_t input_shape_idx = 0;
for (size_t axis = 0; axis < begin.size(); ++axis) {
// add all dimensions hidden under the ellipsis mask if ellipsis mask is set
if (ellipsis_mask.count(axis)) {
// only one bit in ellipsis mask is allowed
int num_new_axis_after_ellipses = 0;
int num_input_axis_before_ellipses = 0;
for (size_t i = 0; i < axis; ++i) {
if (!new_axis_mask.count(i)) {
num_input_axis_before_ellipses++;
}
}
for (size_t i = axis + 1; i < begin.size(); ++i) {
if (new_axis_mask.count(i)) {
num_new_axis_after_ellipses++;
}
}
int64_t num_input_axis_after_ellipses =
(begin.size() - axis - num_new_axis_after_ellipses - 1); // -1 because it's a position of ellipses
int64_t num_of_hidden_dims =
input_shape.rank().get_length() - num_input_axis_after_ellipses - num_input_axis_before_ellipses;
for (int64_t i = 0; i < num_of_hidden_dims; ++i) {
dim.emplace_back(input_shape[input_shape_idx]);
input_shape_idx++;
}
} else {
// add new single dimension if new_axis_mask is set
if (new_axis_mask.count(axis)) {
dim.emplace_back(1);
}
// skip this dimension if shrink_axis_mask is set
else if (shrink_axis_mask.count(axis)) {
input_shape_idx++;
}
// calculating dimension (begin, end, begin_mask, end_mask, stride)
else {
// check dynamic dimension
if (input_shape[input_shape_idx].is_dynamic()) {
input_shape_idx++;
dim.emplace_back(Dimension::dynamic());
continue;
}
int64_t lb = begin[axis];
int64_t ub = end[axis];
// set default value for stride or use given value
int64_t stride = 1;
if (strides.size() > axis) {
stride = strides[axis];
}
NODE_VALIDATION_CHECK(node, stride != 0, "Stride must be non-zero");
// convert negative indexes to positive
// take max for this case: if abs(lb) > input_shape[input_shape_idx],then after
// conversion lb < 0
// so according to tensorflow and numpy we just get 0
if (lb < 0) {
lb = std::max(input_shape[input_shape_idx].get_length() + lb, int64_t(0));
}
if (ub < 0) {
ub =
std::max(input_shape[input_shape_idx].get_length() + ub, stride > 0 ? int64_t(0) : int64_t(-1));
}
// apply restrictions when begin or end values more than max possible values.
lb = std::min(input_shape[input_shape_idx].get_length(), lb);
ub = std::min(input_shape[input_shape_idx].get_length(), ub);
int64_t dimension = 0;
if (stride < 0) {
// apply masks
if (begin_mask.count(axis)) {
lb = input_shape[input_shape_idx].get_length() - 1;
}
if (end_mask.count(axis)) {
ub = -1;
}
lb = std::min(lb, input_shape[input_shape_idx].get_length() - 1);
lb -= 1; // we always get 1st element, so we need decrease range
if (ub <= lb) {
dimension = (ub - lb) / stride + 1;
}
} else {
// apply masks
if (begin_mask.count(axis)) {
lb = 0;
}
if (end_mask.count(axis)) {
ub = input_shape[input_shape_idx].get_length();
}
lb += 1; // we always get 1st element, so we need decrease range
if (ub >= lb) {
dimension = (ub - lb) / stride + 1;
}
}
dim.emplace_back(dimension);
input_shape_idx++;
}
}
}
// get remaining values
for (; input_shape_idx < input_shape.rank().get_length(); ++input_shape_idx) {
dim.emplace_back(input_shape[input_shape_idx]);
}
return dim;
}
std::vector<size_t> ngraph::normalize_axes(const std::string& node_description,
const std::vector<int64_t>& axes,
const Rank& tensor_rank) {
std::vector<size_t> new_axes;
for (const auto& axis : axes) {
new_axes.push_back(normalize_axis(node_description, axis, tensor_rank));
}
return new_axes;
}
int64_t ngraph::normalize_axis(const Node* node, std::int64_t axis, const Rank& tensor_rank) {
return normalize_axis(node->description(), axis, tensor_rank);
}
int64_t ngraph::normalize_axis(const std::string& node_description, std::int64_t axis, const Rank& tensor_rank) {
if (axis < 0) {
// Handling negative axis requires static tensor rank
NGRAPH_CHECK(tensor_rank.is_static(),
node_description,
" Rank must be static in order to normalize negative axis=",
axis);
}
if (tensor_rank.is_dynamic()) {
return axis;
}
const auto tensor_rank_value = tensor_rank.get_length();
return normalize_axis(node_description,
axis,
tensor_rank_value,
-tensor_rank_value,
tensor_rank_value ? (tensor_rank_value - 1) : 0);
}
int64_t ngraph::normalize_axis(const Node* node,
std::int64_t axis,
std::uint64_t tensor_rank,
std::int64_t axis_range_min,
std::int64_t axis_range_max) {
return ngraph::normalize_axis(node->description(), axis, tensor_rank, axis_range_min, axis_range_max);
}
int64_t ngraph::normalize_axis(const std::string& node_description,
std::int64_t axis,
std::uint64_t tensor_rank,
std::int64_t axis_range_min,
std::int64_t axis_range_max) {
// Accepted range of value for axis is [axis_range_min, axis_range_max].
NGRAPH_CHECK(((axis >= axis_range_min) && (axis <= axis_range_max)),
node_description,
" Parameter axis ",
axis,
" out of the tensor rank range [",
axis_range_min,
", ",
axis_range_max,
"].");
if (axis < 0) {
axis = axis + tensor_rank;
}
return int64_t(axis);
}
void ngraph::opset1::infer_conv_backprop_auto_padding(const Shape& input_data_shape,
const Shape& filters_shape,
const Shape& output_shape,
const Strides& strides,
const Strides& dilations,
const op::PadType auto_pad_type,
const CoordinateDiff& output_padding,
CoordinateDiff& pads_begin,
CoordinateDiff& pads_end) {
NGRAPH_CHECK(auto_pad_type == op::PadType::SAME_UPPER || auto_pad_type == op::PadType::SAME_LOWER);
size_t num_spatial_dims = input_data_shape.size();
NGRAPH_CHECK(filters_shape.size() == num_spatial_dims && strides.size() == num_spatial_dims &&
dilations.size() == num_spatial_dims && pads_begin.size() == num_spatial_dims &&
pads_end.size() == num_spatial_dims && output_padding.size() == num_spatial_dims);
pads_begin = CoordinateDiff(num_spatial_dims);
pads_end = CoordinateDiff(num_spatial_dims);
for (uint64_t i = 0; i < num_spatial_dims; ++i) {
int total_padding =
std::max<int>(strides[i] * (input_data_shape[i] - 1) + dilations[i] * (filters_shape[i] - 1) + 1 -
output_shape[i] + output_padding[i],
0);
if (auto_pad_type != op::PadType::SAME_UPPER) {
pads_begin[i] = total_padding / 2;
pads_end[i] = total_padding - pads_begin[i];
} else {
pads_end[i] = total_padding / 2;
pads_begin[i] = total_padding - pads_end[i];
}
}
}
namespace {
/// \brief Scalar variant describes value of an Output, for use in max shape determination
///
/// For tensor values, we use the maximum value in the tensor
struct MaxValue {
/// \brief No information known about the output
MaxValue() {}
/// \brief uint64_t assoiated with the output
MaxValue(uint64_t value) : m_value(value) {}
MaxValue(const vector<uint64_t>& slices, int64_t slice_axis) : m_slices(slices), m_slice_axis(slice_axis) {
m_value = *max_element(m_slices.begin(), m_slices.end());
}
uint64_t m_value{numeric_limits<uint64_t>::max()};
vector<uint64_t> m_slices;
int64_t m_slice_axis{-1};
};
vector<MaxValue> exec_constant(Node* node, vector<MaxValue>& inputs) {
auto result = MaxValue();
auto op = ov::as_type<op::Constant>(node);
auto element_type = op->get_output_element_type(0);
if (element_type.is_integral()) {
uint64_t max_val = 0;
if (element_type.is_signed()) {
for (auto elt : op->cast_vector<int64_t>()) {
if (max_val < static_cast<uint64_t>(elt)) {
max_val = elt;
}
}
} else {
for (auto elt : op->cast_vector<uint64_t>()) {
if (max_val < elt) {
max_val = elt;
}
}
}
result = MaxValue(max_val);
}
return {result};
}
vector<MaxValue> exec_minimum(Node* node, vector<MaxValue>& inputs) {
uint64_t min_value = numeric_limits<uint64_t>::max();
switch (node->get_output_element_type(0)) {
case element::Type_t::i8:
min_value = numeric_limits<int8_t>::max();
break;
case element::Type_t::i16:
min_value = numeric_limits<int16_t>::max();
break;
case element::Type_t::i32:
min_value = numeric_limits<int32_t>::max();
break;
case element::Type_t::i64:
min_value = numeric_limits<int64_t>::max();
break;
case element::Type_t::u8:
min_value = numeric_limits<uint8_t>::max();
break;
case element::Type_t::u16:
min_value = numeric_limits<uint16_t>::max();
break;
case element::Type_t::u32:
min_value = numeric_limits<uint32_t>::max();
break;
case element::Type_t::u64:
min_value = numeric_limits<uint64_t>::max();
break;
default:
break;
}
min_value = min(min_value, inputs.at(0).m_value);
min_value = min(min_value, inputs.at(1).m_value);
return {MaxValue(min_value)};
}
vector<MaxValue> exec_concat(Node* node, vector<MaxValue>& inputs) {
auto op = ov::as_type<op::v0::Concat>(node);
vector<uint64_t> slice_maxen;
for (auto input : inputs) {
slice_maxen.push_back(input.m_value);
}
auto axis = op->get_concatenation_axis();
return {MaxValue(slice_maxen, axis)};
}
vector<MaxValue> exec_reduce_min(Node* node, vector<MaxValue>& inputs) {
auto data = inputs.at(0);
if (data.m_slice_axis >= 0 && data.m_slices.size() > 1) {
if (auto indices_const = ov::as_type<op::v0::Constant>(node->get_input_node_ptr(1))) {
if (indices_const->get_output_element_type(0).is_integral()) {
auto indices_shape = indices_const->get_output_shape(0);
if (indices_shape == Shape{1}) {
auto indices = indices_const->cast_vector<int64_t>();
auto axis = indices.at(0);
if (axis == data.m_slice_axis) {
return {MaxValue(*min_element(data.m_slices.begin(), data.m_slices.end()))};
}
}
}
}
}
// Noting we can do
return {MaxValue(data.m_value)};
}
vector<MaxValue> exec_shape_of(Node* node, vector<MaxValue>& inputs) {
const auto& inputPS = node->get_input_partial_shape(0);
std::vector<uint64_t> shapeDims;
for (int64_t i = 0; i < inputPS.rank().get_length(); i++) {
if (inputPS[i].is_static()) {
shapeDims.push_back(inputPS[i].get_length());
} else {
shapeDims.push_back(std::numeric_limits<uint64_t>::max());
}
}
return {MaxValue(shapeDims, 0)};
}
vector<MaxValue> exec_gather(Node* node, vector<MaxValue>& inputs) {
auto gather = ov::as_type<op::v1::Gather>(node);
const auto& indices = ov::as_type_ptr<op::v0::Constant>(node->input_value(1).get_node_shared_ptr());
const auto& axis = ov::as_type_ptr<op::v0::Constant>(node->input_value(2).get_node_shared_ptr());
if (!indices || !axis) {
return {MaxValue()};
}
if (gather->get_axis() != 0) {
return {MaxValue()};
}
const auto& indicesVec = indices->cast_vector<int64_t>();
if (indicesVec.size() != 1 || indicesVec[0] >= static_cast<int64_t>(inputs[0].m_slices.size())) {
return {MaxValue()};
}
return {MaxValue(inputs[0].m_slices[indicesVec[0]])};
}
vector<MaxValue> exec_nop(Node* node, vector<MaxValue>& inputs) {
return {inputs.at(0)};
}
} // namespace
pair<bool, uint64_t> ngraph::maximum_value(const Output<Node>& value) {
static Evaluator<MaxValue>::op_handler_map handlers = {{op::v0::Concat::type_info, exec_concat},
{op::v0::Constant::type_info, exec_constant},
{op::v0::Convert::type_info, exec_nop},
{op::v1::Gather::type_info, exec_gather},
{op::v1::Minimum::type_info, exec_minimum},
{op::v1::ReduceMin::type_info, exec_reduce_min},
{op::v1::Reshape::type_info, exec_nop},
{op::v3::ShapeOf::type_info, exec_shape_of},
{op::v0::Squeeze::type_info, exec_nop},
{op::v0::Unsqueeze::type_info, exec_nop}};
Evaluator<MaxValue>::value_map value_map;
Evaluator<MaxValue> evaluator(handlers, value_map);
auto val = evaluator.evaluate(value);
return pair<bool, uint64_t>(val.m_value < numeric_limits<uint64_t>::max(), val.m_value);
}
void ngraph::evaluate_nodes(std::map<RawNodeOutput, HostTensorPtr>& value_map,
std::map<RawNodeOutput, HostTensorPtr>& output_tensor_map,
const OutputVector& outputs,
const EvaluationContext& evaluation_context) {
Evaluator<HostTensorPtr> evaluator({}, value_map);
evaluator.set_univeral_handler(
[&output_tensor_map, &evaluation_context](Node* node,
const HostTensorVector& input_tensors) -> HostTensorVector {
HostTensorVector output_tensors;
for (const auto& v : node->outputs()) {
auto it = output_tensor_map.find(v);
if (it == output_tensor_map.end()) {
auto c = make_shared<HostTensor>(v);
output_tensors.push_back(c);
} else {
output_tensors.push_back(it->second);
}
}
if (node->evaluate(output_tensors, input_tensors, evaluation_context)) {
return output_tensors;
} else {
NGRAPH_CHECK(false, "Evaluation failed on ", node);
}
});
for (const auto& value : outputs) {
evaluator.evaluate(value);
}
}
bool ngraph::could_propagate(const Output<Node>& output, std::vector<Node*>& order) {
bool status = true;
std::deque<Node*> nodes_to_calculate = {output.get_node()};
order.push_back(output.get_node());
while (status && !nodes_to_calculate.empty()) {
auto current_node = nodes_to_calculate.front();
nodes_to_calculate.pop_front();
if (current_node->inputs().empty() && !is_type<op::Constant>(current_node))
status = false;
else if (!is_type<op::v0::ShapeOf>(current_node) && !is_type<op::v3::ShapeOf>(current_node)) {
// not a leaf, not a shape_of -- continue to search
for (const auto& input_value : current_node->input_values()) {
const auto& input_node = input_value.get_node();
order.push_back(input_node);
nodes_to_calculate.push_front(input_node);
}
}
}
return status;
}
void propagate_rt_info(Node* node, const Output<Node>& final_port) {
auto node_outputs = node->outputs();
bool same_outputs = std::all_of(node_outputs.begin(), node_outputs.end(), [](const Output<Node>& output) {
return output.get_tensor().has_and_set_bound();
});
if (same_outputs && op::is_constant(node)) // constant should not propagate it's rt_info
{
std::unordered_set<Node*> stop_nodes;
for (const auto& in : final_port.get_target_inputs())
stop_nodes.insert(in.get_node());
auto curr_node = node->shared_from_this();
for (const auto& output : node_outputs) {
if (output == final_port)
continue;
for (auto& in : output.get_target_inputs()) {
if (stop_nodes.count(in.get_node()))
continue;
auto consumer = in.get_node()->shared_from_this();
// FIXME: Here we have a WA in order to save some original fields
// if we have conflicts because Variant merge doesn't work.
// We can restore original fields because we don't change the operation
auto orig_rt_info = consumer->get_rt_info();
copy_runtime_info({curr_node, consumer}, consumer);
auto& rt_info = consumer->get_rt_info();
for (const auto& it : orig_rt_info) {
if (rt_info.find(it.first) == rt_info.end() && it.second->is_copyable())
rt_info[it.first] = it.second;
}
}
}
}
}
HostTensorPtr evaluate_bound(const Output<Node>& output, bool is_upper) {
// bound is already set in the tensor
if (is_upper && output.get_tensor().get_upper_value() != nullptr)
return output.get_tensor().get_upper_value();
if (!is_upper && output.get_tensor().get_lower_value() != nullptr)
return output.get_tensor().get_lower_value();
std::vector<Node*> order;
if (could_propagate(output, order)) {
reverse(order.begin(), order.end());
for (const auto& node : order) {
HostTensorVector outputs;
for (const auto& out : node->outputs())
outputs.push_back(std::make_shared<HostTensor>(out));
if (is_upper ? node->evaluate_upper(outputs) : node->evaluate_lower(outputs)) {
const auto& input_values = node->input_values();
bool same_inputs = std::all_of(input_values.begin(), input_values.end(), [](const Output<Node>& input) {
return input.get_tensor().has_and_set_bound();
});
for (size_t i = 0; i < outputs.size(); ++i) {
// TODO: should we skip setting value for tensors that have only one consumer?
if ((same_inputs || is_upper) && node->get_output_tensor(i).get_upper_value() == nullptr)
node->get_output_tensor(i).set_upper_value(outputs[i]);
if ((same_inputs || !is_upper) && node->get_output_tensor(i).get_lower_value() == nullptr)
node->get_output_tensor(i).set_lower_value(outputs[i]);
}
for (const auto& input : input_values)
if (input.get_target_inputs().size() == 1)
input.get_tensor().invalidate_values();
propagate_rt_info(node, output);
} else {
break;
}
}
}
if (is_upper)
return output.get_tensor().get_upper_value();
else
return output.get_tensor().get_lower_value();
}
HostTensorPtr ngraph::evaluate_lower_bound(const Output<Node>& output) {
return evaluate_bound(output, false);
}
HostTensorPtr ngraph::evaluate_upper_bound(const Output<Node>& output) {
return evaluate_bound(output, true);
}
pair<HostTensorPtr, HostTensorPtr> ngraph::evaluate_both_bounds(const Output<Node>& output) {
return {evaluate_lower_bound(output), evaluate_upper_bound(output)};
}
bool ngraph::evaluate_as_partial_shape(const Output<Node>& output, PartialShape& pshape) {
HostTensorPtr lb, ub;
std::tie(lb, ub) = evaluate_both_bounds(output);
bool shape_defined = false;
if (lb && ub) {
const auto lower_bound = std::make_shared<op::Constant>(lb)->cast_vector<int64_t>();
const auto upper_bound = std::make_shared<op::Constant>(ub)->cast_vector<int64_t>();
NGRAPH_CHECK(lower_bound.size() == upper_bound.size());
vector<Dimension> resulting_pshape(lower_bound.size());
for (size_t i = 0; i < lower_bound.size(); ++i) {
NGRAPH_CHECK(lower_bound[i] >= 0 && upper_bound[i] >= 0);
resulting_pshape[i] = {lower_bound[i], upper_bound[i]};
}
pshape = PartialShape(resulting_pshape);
shape_defined = true;
}
return shape_defined;
}
bool default_bound_evaluator(const Node* node, const HostTensorVector& output_values, bool is_upper) {
HostTensorVector input_tensors;
for (const auto& input : node->input_values()) {
if (auto bound = is_upper ? input.get_tensor().get_upper_value() : input.get_tensor().get_lower_value())
input_tensors.push_back(bound);
else
return false;
}
return node->evaluate(output_values, input_tensors);
}
bool ngraph::default_lower_bound_evaluator(const Node* node, const HostTensorVector& output_values) {
return default_bound_evaluator(node, output_values, false);
}
bool ngraph::default_upper_bound_evaluator(const Node* node, const HostTensorVector& output_values) {
return default_bound_evaluator(node, output_values, true);
}
shared_ptr<op::Constant> ngraph::get_constant_max_of_type(element::Type_t t) {
#define NGRAPH_TYPE_TO_MAX_CONST(t) \
case t: \
return op::Constant::create(t, {}, {std::numeric_limits<typename element_type_traits<t>::value_type>::max()}); \
break
switch (t) {
NGRAPH_TYPE_TO_MAX_CONST(element::boolean);
NGRAPH_TYPE_TO_MAX_CONST(element::bf16);
NGRAPH_TYPE_TO_MAX_CONST(element::f16);
NGRAPH_TYPE_TO_MAX_CONST(element::f32);
NGRAPH_TYPE_TO_MAX_CONST(element::f64);
NGRAPH_TYPE_TO_MAX_CONST(element::i8);
NGRAPH_TYPE_TO_MAX_CONST(element::i16);
NGRAPH_TYPE_TO_MAX_CONST(element::i32);
NGRAPH_TYPE_TO_MAX_CONST(element::i64);
NGRAPH_TYPE_TO_MAX_CONST(element::u1);
NGRAPH_TYPE_TO_MAX_CONST(element::u8);
NGRAPH_TYPE_TO_MAX_CONST(element::u16);
NGRAPH_TYPE_TO_MAX_CONST(element::u32);
NGRAPH_TYPE_TO_MAX_CONST(element::u64);
case element::undefined:
case element::dynamic:
default:
return nullptr;
}
}
shared_ptr<op::Constant> ngraph::get_constant_min_of_type(element::Type_t t) {
#define NGRAPH_TYPE_TO_MIN_CONST(t) \
case t: \
return op::Constant::create(t, {}, {std::numeric_limits<typename element_type_traits<t>::value_type>::min()}); \
break
switch (t) {
NGRAPH_TYPE_TO_MIN_CONST(element::boolean);
NGRAPH_TYPE_TO_MIN_CONST(element::bf16);
NGRAPH_TYPE_TO_MIN_CONST(element::f16);
NGRAPH_TYPE_TO_MIN_CONST(element::f32);
NGRAPH_TYPE_TO_MIN_CONST(element::f64);
NGRAPH_TYPE_TO_MIN_CONST(element::i8);
NGRAPH_TYPE_TO_MIN_CONST(element::i16);
NGRAPH_TYPE_TO_MIN_CONST(element::i32);
NGRAPH_TYPE_TO_MIN_CONST(element::i64);
NGRAPH_TYPE_TO_MIN_CONST(element::u1);
NGRAPH_TYPE_TO_MIN_CONST(element::u8);
NGRAPH_TYPE_TO_MIN_CONST(element::u16);
NGRAPH_TYPE_TO_MIN_CONST(element::u32);
NGRAPH_TYPE_TO_MIN_CONST(element::u64);
case element::undefined:
case element::dynamic:
default:
return nullptr;
}
}
HostTensorPtr equality_mask(const HostTensorPtr& tensor, const shared_ptr<op::Constant>& constant) {
auto mask = std::make_shared<HostTensor>(element::boolean, tensor->get_shape());
const auto& param = std::make_shared<op::Parameter>(tensor->get_element_type(), tensor->get_shape());
op::v1::Equal(param, constant, ngraph::op::AutoBroadcastSpec::NUMPY)
.evaluate({mask}, {tensor, std::make_shared<HostTensor>(constant)});
return mask;
}
HostTensorPtr or_tensor(const HostTensorPtr& lhs, const HostTensorPtr& rhs) {
auto result = std::make_shared<HostTensor>();
op::v1::LogicalOr(std::make_shared<op::Parameter>(lhs->get_element_type(), lhs->get_shape()),
std::make_shared<op::Parameter>(rhs->get_element_type(), rhs->get_shape()),
ngraph::op::AutoBroadcastSpec::NUMPY)
.evaluate({result}, {lhs, rhs});
return result;
}
bool ngraph::interval_bound_evaluator(const Node* node,
const HostTensorVector& lower_output_values,
const HostTensorVector& upper_output_values) {
// TODO: relax for n inputs ?
NGRAPH_CHECK(lower_output_values.size() == upper_output_values.size());
NGRAPH_CHECK(node->get_input_size() == 2);
const auto num_of_outputs = node->get_output_size();
std::shared_ptr<HostTensor> low_0 = evaluate_lower_bound(node->get_input_source_output(0));
std::shared_ptr<HostTensor> low_1 = evaluate_lower_bound(node->get_input_source_output(1));
std::shared_ptr<HostTensor> up_0 = evaluate_upper_bound(node->get_input_source_output(0));
std::shared_ptr<HostTensor> up_1 = evaluate_upper_bound(node->get_input_source_output(1));
std::set<HostTensorVector> input_variants = {{low_0, low_1}, {low_0, up_1}, {up_0, low_1}, {up_0, up_1}};
for (const auto& variant_of_input_vector : input_variants)
for (const auto& input_tensor : variant_of_input_vector)
if (input_tensor == nullptr)
return false;
if (input_variants.size() == 1)
return node->evaluate(upper_output_values, *input_variants.begin()) &&
node->evaluate(lower_output_values, *input_variants.begin());
auto zero = op::v0::Constant::create(element::i64, {1}, {0});
std::vector<HostTensorVector> unsqueezed_output_variants;
for (auto& input_variant : input_variants) {
HostTensorVector vector_of_output_variants;
for (const auto& output : lower_output_values)
vector_of_output_variants.push_back(
std::make_shared<HostTensor>(output->get_element_type(), output->get_partial_shape()));
node->evaluate(vector_of_output_variants, input_variant);
HostTensorVector vector_of_unsqueezed_output_variants;
for (const auto& output : vector_of_output_variants) {
if (!output)
return false;
auto unsqueezed_shape = output->get_shape();
unsqueezed_shape.insert(unsqueezed_shape.begin(), 1);
const auto unsqueezed = make_shared<HostTensor>(output->get_element_type(), unsqueezed_shape);
op::v0::Unsqueeze().evaluate({unsqueezed}, {output, make_shared<HostTensor>(zero)});
vector_of_unsqueezed_output_variants.push_back(unsqueezed);
}
unsqueezed_output_variants.push_back(vector_of_unsqueezed_output_variants);
}
auto input_0_maximum_value = get_constant_max_of_type(low_0->get_element_type());
auto input_1_maximum_value = get_constant_max_of_type(low_1->get_element_type());
if (input_0_maximum_value == nullptr || input_1_maximum_value == nullptr)
return false;
auto input_0_low_dyn_mask = equality_mask(low_0, input_0_maximum_value);
auto input_0_up_dyn_mask = equality_mask(up_0, input_0_maximum_value);
auto input_1_low_dyn_mask = equality_mask(low_1, input_1_maximum_value);
auto input_1_up_dyn_mask = equality_mask(up_1, input_1_maximum_value);
auto final_input_dyn_mask = or_tensor(or_tensor(input_0_low_dyn_mask, input_0_up_dyn_mask),
or_tensor(input_1_low_dyn_mask, input_1_up_dyn_mask));
bool fully_defined = true;
for (size_t i = 0; i < num_of_outputs; ++i) {
HostTensorVector all_variants_for_ith_output;
for (const auto& unsqueezed_output_variant : unsqueezed_output_variants)
all_variants_for_ith_output.push_back(unsqueezed_output_variant[i]);
auto concated_shape = all_variants_for_ith_output[0]->get_shape();
concated_shape[0] = all_variants_for_ith_output.size();
auto concated = make_shared<HostTensor>(all_variants_for_ith_output[0]->get_element_type(), concated_shape);
auto concat = op::Concat();
concat.set_axis(0);
concat.evaluate({concated}, all_variants_for_ith_output);
auto fake_param =
make_shared<op::Parameter>(all_variants_for_ith_output[0]->get_element_type(), concated_shape);
auto reduce_min_op = op::v1::ReduceMin(fake_param, zero, false);
reduce_min_op.evaluate({lower_output_values[i]}, {concated, make_shared<HostTensor>(zero)});
auto reduce_max_op = op::v1::ReduceMax(fake_param, zero, false);
reduce_max_op.evaluate({upper_output_values[i]}, {concated, make_shared<HostTensor>(zero)});
if (upper_output_values[i] == nullptr)
fully_defined = false;
else {
auto output_maximum_value = get_constant_max_of_type(upper_output_values[i]->get_element_type());
op::v1::Select().evaluate(
{upper_output_values[i]},
{final_input_dyn_mask, std::make_shared<HostTensor>(output_maximum_value), upper_output_values[i]});
node->get_output_tensor(i).set_upper_value(upper_output_values[i]);
}
if (lower_output_values[i] == nullptr)
fully_defined = false;
else {
auto output_minimum_value = op::Constant::create(lower_output_values[i]->get_element_type(), {}, {0});
// Can not set to get_constant_min_of_type(lower_output_values[i]->get_element_type())
// yet
op::v1::Select().evaluate(
{lower_output_values[i]},
{final_input_dyn_mask, std::make_shared<HostTensor>(output_minimum_value), lower_output_values[i]});
node->get_output_tensor(i).set_lower_value(lower_output_values[i]);
}
}
return fully_defined;
}
bool ngraph::host_tensor_is_positive(const HostTensorPtr& bound) {
const auto bound_constant = std::make_shared<op::Constant>(bound);
const auto zero_constant = op::Constant::create(bound->get_element_type(), {1}, {0});
OutputVector greater(1);
bool folded = std::make_shared<op::v1::Greater>(bound_constant, zero_constant)
->constant_fold(greater, {bound_constant, zero_constant});
NGRAPH_CHECK(folded);
auto axes_vector = std::vector<int64_t>(greater[0].get_shape().size());
std::iota(axes_vector.begin(), axes_vector.end(), 0);
const auto axes = op::Constant::create(element::i64, {axes_vector.size()}, axes_vector);
OutputVector all(1);
folded = std::make_shared<op::v1::ReduceLogicalAnd>(greater[0], axes)->constant_fold(all, {greater[0], axes});
NGRAPH_CHECK(folded && ov::is_type<op::Constant>(all[0].get_node_shared_ptr()));
const auto result = std::dynamic_pointer_cast<op::Constant>(all[0].get_node_shared_ptr())->cast_vector<bool>();
NGRAPH_CHECK(all[0].get_shape() == Shape{});
return result[0];
}
bool ngraph::has_and_set_equal_bounds(const Output<Node>& source) {
if (op::is_constant(source.get_node_shared_ptr()))
return true;
HostTensorPtr lb, ub;
std::tie(lb, ub) = evaluate_both_bounds(source);
return lb && lb == ub;
}
shared_ptr<op::Constant> ngraph::get_constant_from_source(const Output<Node>& source) {
if (!has_and_set_equal_bounds(source))
return nullptr;
if (const auto& c = ov::as_type_ptr<op::Constant>(source.get_node_shared_ptr()))
return c;
return std::make_shared<op::Constant>(source.get_tensor().get_upper_value());
}
bool ngraph::validate_host_tensor_vector(const HostTensorVector& tensor_vector, const size_t& size) {
if (tensor_vector.size() != size)
return false;
return std::all_of(tensor_vector.begin(), tensor_vector.end(), [](const HostTensorPtr& t) {
return t != nullptr;
});
}
|
// Copyright(c) 2021 Hansen Audio.
#include "detail/shuffle_note.h"
#include "ha/fx_collection/trance_gate.h"
#include "gtest/gtest.h"
using namespace ha::fx_collection;
namespace {
//-----------------------------------------------------------------------------
TEST(trance_gate_test, test_setting_mix)
{
auto trance_gate = TranceGateImpl::create();
TranceGateImpl::set_sample_rate(trance_gate, real(44100.));
TranceGateImpl::set_mix(trance_gate, 1.);
EXPECT_EQ(trance_gate.mix, 1.);
}
//-----------------------------------------------------------------------------
TEST(trance_gate_test, test_delay_active)
{
auto trance_gate = TranceGateImpl::create();
TranceGateImpl::set_sample_rate(trance_gate, real(44100.));
EXPECT_FALSE(trance_gate.is_delay_active);
TranceGateImpl::trigger(trance_gate, real(1. / 32.));
EXPECT_TRUE(trance_gate.is_delay_active);
}
//-----------------------------------------------------------------------------
TEST(trance_gate_test, test_fade_in_active)
{
auto trance_gate = TranceGateImpl::create();
TranceGateImpl::set_sample_rate(trance_gate, real(44100.));
EXPECT_FALSE(trance_gate.is_fade_in_active);
TranceGateImpl::trigger(trance_gate, real(0.), real(1. / 32.));
EXPECT_TRUE(trance_gate.is_fade_in_active);
}
//-----------------------------------------------------------------------------
TEST(trance_gate_test, test_processing)
{
constexpr i32 LEFT_CH = 0;
auto trance_gate = TranceGateImpl::create();
TranceGateImpl::set_sample_rate(trance_gate, real(44100.));
TranceGateImpl::set_step_count(trance_gate, 8);
TranceGateImpl::set_step(trance_gate, LEFT_CH, 0, real(1.));
TranceGateImpl::set_step(trance_gate, LEFT_CH, 1, real(0.));
TranceGateImpl::set_step(trance_gate, LEFT_CH, 2, real(1.));
TranceGateImpl::set_step(trance_gate, LEFT_CH, 3, real(0.));
TranceGateImpl::set_step(trance_gate, LEFT_CH, 4, real(1.));
TranceGateImpl::set_step(trance_gate, LEFT_CH, 5, real(1.));
TranceGateImpl::set_step(trance_gate, LEFT_CH, 6, real(1.));
TranceGateImpl::set_step(trance_gate, LEFT_CH, 7, real(0.));
TranceGateImpl::set_step_len(trance_gate, real(1. / 32.));
mut_i32 numSamples = 1024;
AudioFrame sum{real(0.), real(0.), real(0.), real(0.)};
while (numSamples-- > 0)
{
AudioFrame in{real(0.5), real(0.5), real(0.), real(0.)};
AudioFrame out{real(0.), real(0.), real(0.), real(0.)};
TranceGateImpl::process(trance_gate, in, out);
for (mut_i32 i = 0; i < sum.data.size(); ++i)
sum.data[i] += out.data[i];
}
EXPECT_TRUE(sum.data[0] > real(468.));
EXPECT_TRUE(sum.data[1] > real(468.));
EXPECT_TRUE(sum.data[0] < real(469.));
EXPECT_TRUE(sum.data[1] < real(469.));
}
//-----------------------------------------------------------------------------
TEST(trance_gate_test, test_is_shuffle_note_16)
{
mut_i32 step_index = 0;
constexpr real note_len = real(1. / 16.);
EXPECT_FALSE(detail::is_shuffle_note(step_index++, note_len));
EXPECT_TRUE(detail::is_shuffle_note(step_index++, note_len));
EXPECT_FALSE(detail::is_shuffle_note(step_index++, note_len));
EXPECT_TRUE(detail::is_shuffle_note(step_index++, note_len));
EXPECT_FALSE(detail::is_shuffle_note(step_index++, note_len));
EXPECT_TRUE(detail::is_shuffle_note(step_index++, note_len));
EXPECT_FALSE(detail::is_shuffle_note(step_index++, note_len));
EXPECT_TRUE(detail::is_shuffle_note(step_index, note_len));
}
//-----------------------------------------------------------------------------
TEST(trance_gate_test, test_is_shuffle_note_32)
{
mut_i32 step_index = 0;
constexpr real note_len = real(1. / 32.);
EXPECT_FALSE(detail::is_shuffle_note(step_index++, note_len));
EXPECT_FALSE(detail::is_shuffle_note(step_index++, note_len));
EXPECT_TRUE(detail::is_shuffle_note(step_index++, note_len));
EXPECT_FALSE(detail::is_shuffle_note(step_index++, note_len));
EXPECT_FALSE(detail::is_shuffle_note(step_index++, note_len));
EXPECT_FALSE(detail::is_shuffle_note(step_index++, note_len));
EXPECT_TRUE(detail::is_shuffle_note(step_index++, note_len));
EXPECT_FALSE(detail::is_shuffle_note(step_index++, note_len));
EXPECT_FALSE(detail::is_shuffle_note(step_index++, note_len));
EXPECT_FALSE(detail::is_shuffle_note(step_index++, note_len));
EXPECT_TRUE(detail::is_shuffle_note(step_index++, note_len));
}
//-----------------------------------------------------------------------------
} // namespace
|
/****************************************************************************
*
* Copyright (c) 2021 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file PublicationManager.cpp
*
* Manages the dynamic (run-time configurable) UAVCAN publications
*
* @author Peter van der Perk <peter.vanderperk@nxp.com>
* @author Jacob Crabill <jacob@flyvoly.com>
*/
#include "PublicationManager.hpp"
PublicationManager::~PublicationManager()
{
_dynpublishers.clear();
}
void PublicationManager::updateDynamicPublications()
{
for (auto &sub : _uavcan_pubs) {
bool found_publisher = false;
for (auto &dynpub : _dynpublishers) {
// Check if subscriber has already been created
const char *subj_name = dynpub->getSubjectName();
const uint8_t instance = dynpub->getInstance();
if (strcmp(subj_name, sub.subject_name) == 0 && instance == sub.instance) {
found_publisher = true;
break;
}
}
if (found_publisher) {
continue;
}
char uavcan_param[90];
snprintf(uavcan_param, sizeof(uavcan_param), "uavcan.pub.%s.%d.id", sub.subject_name, sub.instance);
uavcan_register_Value_1_0 value;
if (_param_manager.GetParamByName(uavcan_param, value)) {
uint16_t port_id = value.natural16.value.elements[0];
if (port_id <= CANARD_PORT_ID_MAX) { // PortID is set, create a subscriber
UavcanPublisher *dynpub = sub.create_pub(_canard_instance, _param_manager);
if (dynpub == nullptr) {
PX4_ERR("Out of memory");
return;
}
_dynpublishers.add(dynpub);
dynpub->updateParam();
}
} else {
PX4_ERR("Port ID param for publisher %s.%u not found", sub.subject_name, sub.instance);
return;
}
}
}
void PublicationManager::printInfo()
{
for (auto &dynpub : _dynpublishers) {
dynpub->printInfo();
}
}
void PublicationManager::updateParams()
{
for (auto &dynpub : _dynpublishers) {
dynpub->updateParam();
}
// Check for any newly-enabled publication
updateDynamicPublications();
}
void PublicationManager::update()
{
for (auto &dynpub : _dynpublishers) {
dynpub->update();
}
}
|
/*
* Catch v1.2.1
* Generated: 2015-06-30 18:23:27.961086
* ----------------------------------------------------------
* This file has been merged from multiple headers. Please don't edit it directly
* Copyright (c) 2012 Two Blue Cubes Ltd. All rights reserved.
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
#define TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
#define TWOBLUECUBES_CATCH_HPP_INCLUDED
#ifdef __clang__
# pragma clang system_header
#elif defined __GNUC__
# pragma GCC system_header
#endif
// #included from: internal/catch_suppress_warnings.h
#define TWOBLUECUBES_CATCH_SUPPRESS_WARNINGS_H_INCLUDED
#ifdef __clang__
# ifdef __ICC // icpc defines the __clang__ macro
# pragma warning(push)
# pragma warning(disable: 161 1682)
# else // __ICC
# pragma clang diagnostic ignored "-Wglobal-constructors"
# pragma clang diagnostic ignored "-Wvariadic-macros"
# pragma clang diagnostic ignored "-Wc99-extensions"
# pragma clang diagnostic ignored "-Wunused-variable"
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wpadded"
# pragma clang diagnostic ignored "-Wc++98-compat"
# pragma clang diagnostic ignored "-Wc++98-compat-pedantic"
# pragma clang diagnostic ignored "-Wswitch-enum"
# endif
#elif defined __GNUC__
# pragma GCC diagnostic ignored "-Wvariadic-macros"
# pragma GCC diagnostic ignored "-Wunused-variable"
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wpadded"
#endif
#if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER)
# define CATCH_IMPL
#endif
#ifdef CATCH_IMPL
# ifndef CLARA_CONFIG_MAIN
# define CLARA_CONFIG_MAIN_NOT_DEFINED
# define CLARA_CONFIG_MAIN
# endif
#endif
// #included from: internal/catch_notimplemented_exception.h
#define TWOBLUECUBES_CATCH_NOTIMPLEMENTED_EXCEPTION_H_INCLUDED
// #included from: catch_common.h
#define TWOBLUECUBES_CATCH_COMMON_H_INCLUDED
#define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
#define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
#define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
#define INTERNAL_CATCH_STRINGIFY2( expr ) #expr
#define INTERNAL_CATCH_STRINGIFY( expr ) INTERNAL_CATCH_STRINGIFY2( expr )
#include <sstream>
#include <stdexcept>
#include <algorithm>
// #included from: catch_compiler_capabilities.h
#define TWOBLUECUBES_CATCH_COMPILER_CAPABILITIES_HPP_INCLUDED
// Detect a number of compiler features - mostly C++11/14 conformance - by compiler
// The following features are defined:
//
// CATCH_CONFIG_CPP11_NULLPTR : is nullptr supported?
// CATCH_CONFIG_CPP11_NOEXCEPT : is noexcept supported?
// CATCH_CONFIG_CPP11_GENERATED_METHODS : The delete and default keywords for compiler generated methods
// CATCH_CONFIG_CPP11_IS_ENUM : std::is_enum is supported?
// CATCH_CONFIG_CPP11_TUPLE : std::tuple is supported
// CATCH_CONFIG_CPP11_OR_GREATER : Is C++11 supported?
// CATCH_CONFIG_VARIADIC_MACROS : are variadic macros supported?
// In general each macro has a _NO_<feature name> form
// (e.g. CATCH_CONFIG_CPP11_NO_NULLPTR) which disables the feature.
// Many features, at point of detection, define an _INTERNAL_ macro, so they
// can be combined, en-mass, with the _NO_ forms later.
// All the C++11 features can be disabled with CATCH_CONFIG_NO_CPP11
#ifdef __clang__
# if __has_feature(cxx_nullptr)
# define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR
# endif
# if __has_feature(cxx_noexcept)
# define CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT
# endif
#endif // __clang__
////////////////////////////////////////////////////////////////////////////////
// Borland
#ifdef __BORLANDC__
#endif // __BORLANDC__
////////////////////////////////////////////////////////////////////////////////
// EDG
#ifdef __EDG_VERSION__
#endif // __EDG_VERSION__
////////////////////////////////////////////////////////////////////////////////
// Digital Mars
#ifdef __DMC__
#endif // __DMC__
////////////////////////////////////////////////////////////////////////////////
// GCC
#ifdef __GNUC__
#if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6 && defined(__GXX_EXPERIMENTAL_CXX0X__) )
# define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR
#endif
#endif // __GNUC__
////////////////////////////////////////////////////////////////////////////////
// Visual C++
#ifdef _MSC_VER
#if (_MSC_VER >= 1600)
# define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR
#endif
#if (_MSC_VER >= 1900 ) // (VC++ 13 (VS2015))
#define CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT
#define CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS
#endif
#endif // _MSC_VER
// Use variadic macros if the compiler supports them
#if ( defined _MSC_VER && _MSC_VER > 1400 && !defined __EDGE__) || \
( defined __WAVE__ && __WAVE_HAS_VARIADICS ) || \
( defined __GNUC__ && __GNUC__ >= 3 ) || \
( !defined __cplusplus && __STDC_VERSION__ >= 199901L || __cplusplus >= 201103L )
#define CATCH_INTERNAL_CONFIG_VARIADIC_MACROS
#endif
////////////////////////////////////////////////////////////////////////////////
// C++ language feature support
// catch all support for C++11
#if (__cplusplus >= 201103L)
# define CATCH_CPP11_OR_GREATER
# if !defined(CATCH_INTERNAL_CONFIG_CPP11_NULLPTR)
# define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR
# endif
# ifndef CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT
# define CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT
# endif
# ifndef CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS
# define CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS
# endif
# ifndef CATCH_INTERNAL_CONFIG_CPP11_IS_ENUM
# define CATCH_INTERNAL_CONFIG_CPP11_IS_ENUM
# endif
# ifndef CATCH_INTERNAL_CONFIG_CPP11_TUPLE
# define CATCH_INTERNAL_CONFIG_CPP11_TUPLE
# endif
# ifndef CATCH_INTERNAL_CONFIG_VARIADIC_MACROS
# define CATCH_INTERNAL_CONFIG_VARIADIC_MACROS
# endif
#endif // __cplusplus >= 201103L
// Now set the actual defines based on the above + anything the user has configured
#if defined(CATCH_INTERNAL_CONFIG_CPP11_NULLPTR) && !defined(CATCH_CONFIG_CPP11_NO_NULLPTR) && !defined(CATCH_CONFIG_CPP11_NULLPTR) && !defined(CATCH_CONFIG_NO_CPP11)
# define CATCH_CONFIG_CPP11_NULLPTR
#endif
#if defined(CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT) && !defined(CATCH_CONFIG_CPP11_NO_NOEXCEPT) && !defined(CATCH_CONFIG_CPP11_NOEXCEPT) && !defined(CATCH_CONFIG_NO_CPP11)
# define CATCH_CONFIG_CPP11_NOEXCEPT
#endif
#if defined(CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS) && !defined(CATCH_CONFIG_CPP11_NO_GENERATED_METHODS) && !defined(CATCH_CONFIG_CPP11_GENERATED_METHODS) && !defined(CATCH_CONFIG_NO_CPP11)
# define CATCH_CONFIG_CPP11_GENERATED_METHODS
#endif
#if defined(CATCH_INTERNAL_CONFIG_CPP11_IS_ENUM) && !defined(CATCH_CONFIG_CPP11_NO_IS_ENUM) && !defined(CATCH_CONFIG_CPP11_IS_ENUM) && !defined(CATCH_CONFIG_NO_CPP11)
# define CATCH_CONFIG_CPP11_IS_ENUM
#endif
#if defined(CATCH_INTERNAL_CONFIG_CPP11_TUPLE) && !defined(CATCH_CONFIG_CPP11_NO_TUPLE) && !defined(CATCH_CONFIG_CPP11_TUPLE) && !defined(CATCH_CONFIG_NO_CPP11)
# define CATCH_CONFIG_CPP11_TUPLE
#endif
#if defined(CATCH_INTERNAL_CONFIG_VARIADIC_MACROS) && !defined(CATCH_CONFIG_NO_VARIADIC_MACROS) && !defined(CATCH_CONFIG_VARIADIC_MACROS)
#define CATCH_CONFIG_VARIADIC_MACROS
#endif
// noexcept support:
#if defined(CATCH_CONFIG_CPP11_NOEXCEPT) && !defined(CATCH_NOEXCEPT)
# define CATCH_NOEXCEPT noexcept
# define CATCH_NOEXCEPT_IS(x) noexcept(x)
#else
# define CATCH_NOEXCEPT throw()
# define CATCH_NOEXCEPT_IS(x)
#endif
namespace Catch {
class NonCopyable {
#ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS
NonCopyable( NonCopyable const& ) = delete;
NonCopyable( NonCopyable && ) = delete;
NonCopyable& operator = ( NonCopyable const& ) = delete;
NonCopyable& operator = ( NonCopyable && ) = delete;
#else
NonCopyable( NonCopyable const& info );
NonCopyable& operator = ( NonCopyable const& );
#endif
protected:
NonCopyable() {}
virtual ~NonCopyable();
};
class SafeBool {
public:
typedef void (SafeBool::*type)() const;
static type makeSafe( bool value ) {
return value ? &SafeBool::trueValue : 0;
}
private:
void trueValue() const {}
};
template<typename ContainerT>
inline void deleteAll( ContainerT& container ) {
typename ContainerT::const_iterator it = container.begin();
typename ContainerT::const_iterator itEnd = container.end();
for(; it != itEnd; ++it )
delete *it;
}
template<typename AssociativeContainerT>
inline void deleteAllValues( AssociativeContainerT& container ) {
typename AssociativeContainerT::const_iterator it = container.begin();
typename AssociativeContainerT::const_iterator itEnd = container.end();
for(; it != itEnd; ++it )
delete it->second;
}
bool startsWith( std::string const& s, std::string const& prefix );
bool endsWith( std::string const& s, std::string const& suffix );
bool contains( std::string const& s, std::string const& infix );
void toLowerInPlace( std::string& s );
std::string toLower( std::string const& s );
std::string trim( std::string const& str );
bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis );
struct pluralise {
pluralise( std::size_t count, std::string const& label );
friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser );
std::size_t m_count;
std::string m_label;
};
struct SourceLineInfo {
SourceLineInfo();
SourceLineInfo( char const* _file, std::size_t _line );
SourceLineInfo( SourceLineInfo const& other );
# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS
SourceLineInfo( SourceLineInfo && ) = default;
SourceLineInfo& operator = ( SourceLineInfo const& ) = default;
SourceLineInfo& operator = ( SourceLineInfo && ) = default;
# endif
bool empty() const;
bool operator == ( SourceLineInfo const& other ) const;
bool operator < ( SourceLineInfo const& other ) const;
std::string file;
std::size_t line;
};
std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info );
// This is just here to avoid compiler warnings with macro constants and boolean literals
inline bool isTrue( bool value ){ return value; }
inline bool alwaysTrue() { return true; }
inline bool alwaysFalse() { return false; }
void throwLogicError( std::string const& message, SourceLineInfo const& locationInfo );
// Use this in variadic streaming macros to allow
// >> +StreamEndStop
// as well as
// >> stuff +StreamEndStop
struct StreamEndStop {
std::string operator+() {
return std::string();
}
};
template<typename T>
T const& operator + ( T const& value, StreamEndStop ) {
return value;
}
}
#define CATCH_INTERNAL_LINEINFO ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
#define CATCH_INTERNAL_ERROR( msg ) ::Catch::throwLogicError( msg, CATCH_INTERNAL_LINEINFO );
#include <ostream>
namespace Catch {
class NotImplementedException : public std::exception
{
public:
NotImplementedException( SourceLineInfo const& lineInfo );
NotImplementedException( NotImplementedException const& ) {}
virtual ~NotImplementedException() CATCH_NOEXCEPT {}
virtual const char* what() const CATCH_NOEXCEPT;
private:
std::string m_what;
SourceLineInfo m_lineInfo;
};
} // end namespace Catch
///////////////////////////////////////////////////////////////////////////////
#define CATCH_NOT_IMPLEMENTED throw Catch::NotImplementedException( CATCH_INTERNAL_LINEINFO )
// #included from: internal/catch_context.h
#define TWOBLUECUBES_CATCH_CONTEXT_H_INCLUDED
// #included from: catch_interfaces_generators.h
#define TWOBLUECUBES_CATCH_INTERFACES_GENERATORS_H_INCLUDED
#include <string>
namespace Catch {
struct IGeneratorInfo {
virtual ~IGeneratorInfo();
virtual bool moveNext() = 0;
virtual std::size_t getCurrentIndex() const = 0;
};
struct IGeneratorsForTest {
virtual ~IGeneratorsForTest();
virtual IGeneratorInfo& getGeneratorInfo( std::string const& fileInfo, std::size_t size ) = 0;
virtual bool moveNext() = 0;
};
IGeneratorsForTest* createGeneratorsForTest();
} // end namespace Catch
// #included from: catch_ptr.hpp
#define TWOBLUECUBES_CATCH_PTR_HPP_INCLUDED
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpadded"
#endif
namespace Catch {
// An intrusive reference counting smart pointer.
// T must implement addRef() and release() methods
// typically implementing the IShared interface
template<typename T>
class Ptr {
public:
Ptr() : m_p( NULL ){}
Ptr( T* p ) : m_p( p ){
if( m_p )
m_p->addRef();
}
Ptr( Ptr const& other ) : m_p( other.m_p ){
if( m_p )
m_p->addRef();
}
~Ptr(){
if( m_p )
m_p->release();
}
void reset() {
if( m_p )
m_p->release();
m_p = NULL;
}
Ptr& operator = ( T* p ){
Ptr temp( p );
swap( temp );
return *this;
}
Ptr& operator = ( Ptr const& other ){
Ptr temp( other );
swap( temp );
return *this;
}
void swap( Ptr& other ) { std::swap( m_p, other.m_p ); }
T* get() { return m_p; }
const T* get() const{ return m_p; }
T& operator*() const { return *m_p; }
T* operator->() const { return m_p; }
bool operator !() const { return m_p == NULL; }
operator SafeBool::type() const { return SafeBool::makeSafe( m_p != NULL ); }
private:
T* m_p;
};
struct IShared : NonCopyable {
virtual ~IShared();
virtual void addRef() const = 0;
virtual void release() const = 0;
};
template<typename T = IShared>
struct SharedImpl : T {
SharedImpl() : m_rc( 0 ){}
virtual void addRef() const {
++m_rc;
}
virtual void release() const {
if( --m_rc == 0 )
delete this;
}
mutable unsigned int m_rc;
};
} // end namespace Catch
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#include <memory>
#include <vector>
#include <stdlib.h>
namespace Catch {
class TestCase;
class Stream;
struct IResultCapture;
struct IRunner;
struct IGeneratorsForTest;
struct IConfig;
struct IContext
{
virtual ~IContext();
virtual IResultCapture* getResultCapture() = 0;
virtual IRunner* getRunner() = 0;
virtual size_t getGeneratorIndex( std::string const& fileInfo, size_t totalSize ) = 0;
virtual bool advanceGeneratorsForCurrentTest() = 0;
virtual Ptr<IConfig const> getConfig() const = 0;
};
struct IMutableContext : IContext
{
virtual ~IMutableContext();
virtual void setResultCapture( IResultCapture* resultCapture ) = 0;
virtual void setRunner( IRunner* runner ) = 0;
virtual void setConfig( Ptr<IConfig const> const& config ) = 0;
};
IContext& getCurrentContext();
IMutableContext& getCurrentMutableContext();
void cleanUpContext();
Stream createStream( std::string const& streamName );
}
// #included from: internal/catch_test_registry.hpp
#define TWOBLUECUBES_CATCH_TEST_REGISTRY_HPP_INCLUDED
// #included from: catch_interfaces_testcase.h
#define TWOBLUECUBES_CATCH_INTERFACES_TESTCASE_H_INCLUDED
#include <vector>
namespace Catch {
class TestSpec;
struct ITestCase : IShared {
virtual void invoke () const = 0;
protected:
virtual ~ITestCase();
};
class TestCase;
struct IConfig;
struct ITestCaseRegistry {
virtual ~ITestCaseRegistry();
virtual std::vector<TestCase> const& getAllTests() const = 0;
virtual void getFilteredTests( TestSpec const& testSpec, IConfig const& config, std::vector<TestCase>& matchingTestCases, bool negated = false ) const = 0;
};
}
namespace Catch {
template<typename C>
class MethodTestCase : public SharedImpl<ITestCase> {
public:
MethodTestCase( void (C::*method)() ) : m_method( method ) {}
virtual void invoke() const {
C obj;
(obj.*m_method)();
}
private:
virtual ~MethodTestCase() {}
void (C::*m_method)();
};
typedef void(*TestFunction)();
struct NameAndDesc {
NameAndDesc( const char* _name = "", const char* _description= "" )
: name( _name ), description( _description )
{}
const char* name;
const char* description;
};
struct AutoReg {
AutoReg( TestFunction function,
SourceLineInfo const& lineInfo,
NameAndDesc const& nameAndDesc );
template<typename C>
AutoReg( void (C::*method)(),
char const* className,
NameAndDesc const& nameAndDesc,
SourceLineInfo const& lineInfo ) {
registerTestCase( new MethodTestCase<C>( method ),
className,
nameAndDesc,
lineInfo );
}
void registerTestCase( ITestCase* testCase,
char const* className,
NameAndDesc const& nameAndDesc,
SourceLineInfo const& lineInfo );
~AutoReg();
private:
AutoReg( AutoReg const& );
void operator= ( AutoReg const& );
};
} // end namespace Catch
#ifdef CATCH_CONFIG_VARIADIC_MACROS
///////////////////////////////////////////////////////////////////////////////
#define INTERNAL_CATCH_TESTCASE( ... ) \
static void INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )(); \
namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( __VA_ARGS__ ) ); }\
static void INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )()
///////////////////////////////////////////////////////////////////////////////
#define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \
namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &QualifiedMethod, "&" #QualifiedMethod, Catch::NameAndDesc( __VA_ARGS__ ), CATCH_INTERNAL_LINEINFO ); }
///////////////////////////////////////////////////////////////////////////////
#define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... )\
namespace{ \
struct INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) : ClassName{ \
void test(); \
}; \
Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( &INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )::test, #ClassName, Catch::NameAndDesc( __VA_ARGS__ ), CATCH_INTERNAL_LINEINFO ); \
} \
void INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )::test()
#else
///////////////////////////////////////////////////////////////////////////////
#define INTERNAL_CATCH_TESTCASE( Name, Desc ) \
static void INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )(); \
namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( Name, Desc ) ); }\
static void INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )()
///////////////////////////////////////////////////////////////////////////////
#define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, Name, Desc ) \
namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &QualifiedMethod, "&" #QualifiedMethod, Catch::NameAndDesc( Name, Desc ), CATCH_INTERNAL_LINEINFO ); }
///////////////////////////////////////////////////////////////////////////////
#define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, TestName, Desc )\
namespace{ \
struct INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) : ClassName{ \
void test(); \
}; \
Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( &INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )::test, #ClassName, Catch::NameAndDesc( TestName, Desc ), CATCH_INTERNAL_LINEINFO ); \
} \
void INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )::test()
#endif
// #included from: internal/catch_capture.hpp
#define TWOBLUECUBES_CATCH_CAPTURE_HPP_INCLUDED
// #included from: catch_result_builder.h
#define TWOBLUECUBES_CATCH_RESULT_BUILDER_H_INCLUDED
// #included from: catch_result_type.h
#define TWOBLUECUBES_CATCH_RESULT_TYPE_H_INCLUDED
namespace Catch {
// ResultWas::OfType enum
struct ResultWas { enum OfType {
Unknown = -1,
Ok = 0,
Info = 1,
Warning = 2,
FailureBit = 0x10,
ExpressionFailed = FailureBit | 1,
ExplicitFailure = FailureBit | 2,
Exception = 0x100 | FailureBit,
ThrewException = Exception | 1,
DidntThrowException = Exception | 2,
FatalErrorCondition = 0x200 | FailureBit
}; };
inline bool isOk( ResultWas::OfType resultType ) {
return ( resultType & ResultWas::FailureBit ) == 0;
}
inline bool isJustInfo( int flags ) {
return flags == ResultWas::Info;
}
// ResultDisposition::Flags enum
struct ResultDisposition { enum Flags {
Normal = 0x01,
ContinueOnFailure = 0x02, // Failures fail test, but execution continues
FalseTest = 0x04, // Prefix expression with !
SuppressFail = 0x08 // Failures are reported but do not fail the test
}; };
inline ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );
}
inline bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; }
inline bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; }
} // end namespace Catch
// #included from: catch_assertionresult.h
#define TWOBLUECUBES_CATCH_ASSERTIONRESULT_H_INCLUDED
#include <string>
namespace Catch {
struct AssertionInfo
{
AssertionInfo() {}
AssertionInfo( std::string const& _macroName,
SourceLineInfo const& _lineInfo,
std::string const& _capturedExpression,
ResultDisposition::Flags _resultDisposition );
std::string macroName;
SourceLineInfo lineInfo;
std::string capturedExpression;
ResultDisposition::Flags resultDisposition;
};
struct AssertionResultData
{
AssertionResultData() : resultType( ResultWas::Unknown ) {}
std::string reconstructedExpression;
std::string message;
ResultWas::OfType resultType;
};
class AssertionResult {
public:
AssertionResult();
AssertionResult( AssertionInfo const& info, AssertionResultData const& data );
~AssertionResult();
# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS
AssertionResult( AssertionResult const& ) = default;
AssertionResult( AssertionResult && ) = default;
AssertionResult& operator = ( AssertionResult const& ) = default;
AssertionResult& operator = ( AssertionResult && ) = default;
# endif
bool isOk() const;
bool succeeded() const;
ResultWas::OfType getResultType() const;
bool hasExpression() const;
bool hasMessage() const;
std::string getExpression() const;
std::string getExpressionInMacro() const;
bool hasExpandedExpression() const;
std::string getExpandedExpression() const;
std::string getMessage() const;
SourceLineInfo getSourceInfo() const;
std::string getTestMacroName() const;
protected:
AssertionInfo m_info;
AssertionResultData m_resultData;
};
} // end namespace Catch
namespace Catch {
struct TestFailureException{};
template<typename T> class ExpressionLhs;
struct STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison;
struct CopyableStream {
CopyableStream() {}
CopyableStream( CopyableStream const& other ) {
oss << other.oss.str();
}
CopyableStream& operator=( CopyableStream const& other ) {
oss.str("");
oss << other.oss.str();
return *this;
}
std::ostringstream oss;
};
class ResultBuilder {
public:
ResultBuilder( char const* macroName,
SourceLineInfo const& lineInfo,
char const* capturedExpression,
ResultDisposition::Flags resultDisposition );
template<typename T>
ExpressionLhs<T const&> operator <= ( T const& operand );
ExpressionLhs<bool> operator <= ( bool value );
template<typename T>
ResultBuilder& operator << ( T const& value ) {
m_stream.oss << value;
return *this;
}
template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator && ( RhsT const& );
template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator || ( RhsT const& );
ResultBuilder& setResultType( ResultWas::OfType result );
ResultBuilder& setResultType( bool result );
ResultBuilder& setLhs( std::string const& lhs );
ResultBuilder& setRhs( std::string const& rhs );
ResultBuilder& setOp( std::string const& op );
void endExpression();
std::string reconstructExpression() const;
AssertionResult build() const;
void useActiveException( ResultDisposition::Flags resultDisposition = ResultDisposition::Normal );
void captureResult( ResultWas::OfType resultType );
void captureExpression();
void react();
bool shouldDebugBreak() const;
bool allowThrows() const;
private:
AssertionInfo m_assertionInfo;
AssertionResultData m_data;
struct ExprComponents {
ExprComponents() : testFalse( false ) {}
bool testFalse;
std::string lhs, rhs, op;
} m_exprComponents;
CopyableStream m_stream;
bool m_shouldDebugBreak;
bool m_shouldThrow;
};
} // namespace Catch
// Include after due to circular dependency:
// #included from: catch_expression_lhs.hpp
#define TWOBLUECUBES_CATCH_EXPRESSION_LHS_HPP_INCLUDED
// #included from: catch_evaluate.hpp
#define TWOBLUECUBES_CATCH_EVALUATE_HPP_INCLUDED
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable:4389) // '==' : signed/unsigned mismatch
#endif
#include <cstddef>
namespace Catch {
namespace Internal {
enum Operator {
IsEqualTo,
IsNotEqualTo,
IsLessThan,
IsGreaterThan,
IsLessThanOrEqualTo,
IsGreaterThanOrEqualTo
};
template<Operator Op> struct OperatorTraits { static const char* getName(){ return "*error*"; } };
template<> struct OperatorTraits<IsEqualTo> { static const char* getName(){ return "=="; } };
template<> struct OperatorTraits<IsNotEqualTo> { static const char* getName(){ return "!="; } };
template<> struct OperatorTraits<IsLessThan> { static const char* getName(){ return "<"; } };
template<> struct OperatorTraits<IsGreaterThan> { static const char* getName(){ return ">"; } };
template<> struct OperatorTraits<IsLessThanOrEqualTo> { static const char* getName(){ return "<="; } };
template<> struct OperatorTraits<IsGreaterThanOrEqualTo>{ static const char* getName(){ return ">="; } };
template<typename T>
inline T& opCast(T const& t) { return const_cast<T&>(t); }
// nullptr_t support based on pull request #154 from Konstantin Baumann
#ifdef CATCH_CONFIG_CPP11_NULLPTR
inline std::nullptr_t opCast(std::nullptr_t) { return nullptr; }
#endif // CATCH_CONFIG_CPP11_NULLPTR
// So the compare overloads can be operator agnostic we convey the operator as a template
// enum, which is used to specialise an Evaluator for doing the comparison.
template<typename T1, typename T2, Operator Op>
class Evaluator{};
template<typename T1, typename T2>
struct Evaluator<T1, T2, IsEqualTo> {
static bool evaluate( T1 const& lhs, T2 const& rhs) {
return opCast( lhs ) == opCast( rhs );
}
};
template<typename T1, typename T2>
struct Evaluator<T1, T2, IsNotEqualTo> {
static bool evaluate( T1 const& lhs, T2 const& rhs ) {
return opCast( lhs ) != opCast( rhs );
}
};
template<typename T1, typename T2>
struct Evaluator<T1, T2, IsLessThan> {
static bool evaluate( T1 const& lhs, T2 const& rhs ) {
return opCast( lhs ) < opCast( rhs );
}
};
template<typename T1, typename T2>
struct Evaluator<T1, T2, IsGreaterThan> {
static bool evaluate( T1 const& lhs, T2 const& rhs ) {
return opCast( lhs ) > opCast( rhs );
}
};
template<typename T1, typename T2>
struct Evaluator<T1, T2, IsGreaterThanOrEqualTo> {
static bool evaluate( T1 const& lhs, T2 const& rhs ) {
return opCast( lhs ) >= opCast( rhs );
}
};
template<typename T1, typename T2>
struct Evaluator<T1, T2, IsLessThanOrEqualTo> {
static bool evaluate( T1 const& lhs, T2 const& rhs ) {
return opCast( lhs ) <= opCast( rhs );
}
};
template<Operator Op, typename T1, typename T2>
bool applyEvaluator( T1 const& lhs, T2 const& rhs ) {
return Evaluator<T1, T2, Op>::evaluate( lhs, rhs );
}
// This level of indirection allows us to specialise for integer types
// to avoid signed/ unsigned warnings
// "base" overload
template<Operator Op, typename T1, typename T2>
bool compare( T1 const& lhs, T2 const& rhs ) {
return Evaluator<T1, T2, Op>::evaluate( lhs, rhs );
}
// unsigned X to int
template<Operator Op> bool compare( unsigned int lhs, int rhs ) {
return applyEvaluator<Op>( lhs, static_cast<unsigned int>( rhs ) );
}
template<Operator Op> bool compare( unsigned long lhs, int rhs ) {
return applyEvaluator<Op>( lhs, static_cast<unsigned int>( rhs ) );
}
template<Operator Op> bool compare( unsigned char lhs, int rhs ) {
return applyEvaluator<Op>( lhs, static_cast<unsigned int>( rhs ) );
}
// unsigned X to long
template<Operator Op> bool compare( unsigned int lhs, long rhs ) {
return applyEvaluator<Op>( lhs, static_cast<unsigned long>( rhs ) );
}
template<Operator Op> bool compare( unsigned long lhs, long rhs ) {
return applyEvaluator<Op>( lhs, static_cast<unsigned long>( rhs ) );
}
template<Operator Op> bool compare( unsigned char lhs, long rhs ) {
return applyEvaluator<Op>( lhs, static_cast<unsigned long>( rhs ) );
}
// int to unsigned X
template<Operator Op> bool compare( int lhs, unsigned int rhs ) {
return applyEvaluator<Op>( static_cast<unsigned int>( lhs ), rhs );
}
template<Operator Op> bool compare( int lhs, unsigned long rhs ) {
return applyEvaluator<Op>( static_cast<unsigned int>( lhs ), rhs );
}
template<Operator Op> bool compare( int lhs, unsigned char rhs ) {
return applyEvaluator<Op>( static_cast<unsigned int>( lhs ), rhs );
}
// long to unsigned X
template<Operator Op> bool compare( long lhs, unsigned int rhs ) {
return applyEvaluator<Op>( static_cast<unsigned long>( lhs ), rhs );
}
template<Operator Op> bool compare( long lhs, unsigned long rhs ) {
return applyEvaluator<Op>( static_cast<unsigned long>( lhs ), rhs );
}
template<Operator Op> bool compare( long lhs, unsigned char rhs ) {
return applyEvaluator<Op>( static_cast<unsigned long>( lhs ), rhs );
}
// pointer to long (when comparing against NULL)
template<Operator Op, typename T> bool compare( long lhs, T* rhs ) {
return Evaluator<T*, T*, Op>::evaluate( reinterpret_cast<T*>( lhs ), rhs );
}
template<Operator Op, typename T> bool compare( T* lhs, long rhs ) {
return Evaluator<T*, T*, Op>::evaluate( lhs, reinterpret_cast<T*>( rhs ) );
}
// pointer to int (when comparing against NULL)
template<Operator Op, typename T> bool compare( int lhs, T* rhs ) {
return Evaluator<T*, T*, Op>::evaluate( reinterpret_cast<T*>( lhs ), rhs );
}
template<Operator Op, typename T> bool compare( T* lhs, int rhs ) {
return Evaluator<T*, T*, Op>::evaluate( lhs, reinterpret_cast<T*>( rhs ) );
}
#ifdef CATCH_CONFIG_CPP11_NULLPTR
// pointer to nullptr_t (when comparing against nullptr)
template<Operator Op, typename T> bool compare( std::nullptr_t, T* rhs ) {
return Evaluator<T*, T*, Op>::evaluate( NULL, rhs );
}
template<Operator Op, typename T> bool compare( T* lhs, std::nullptr_t ) {
return Evaluator<T*, T*, Op>::evaluate( lhs, NULL );
}
#endif // CATCH_CONFIG_CPP11_NULLPTR
} // end of namespace Internal
} // end of namespace Catch
#ifdef _MSC_VER
#pragma warning(pop)
#endif
// #included from: catch_to_string.h
#define TWOBLUECUBES_CATCH_TOSTRING_H_INCLUDED
#include <sstream>
#include <iomanip>
#include <limits>
#include <vector>
#include <cstddef>
#ifdef __OBJC__
// #included from: catch_objc_arc.hpp
#define TWOBLUECUBES_CATCH_OBJC_ARC_HPP_INCLUDED
#import <Foundation/Foundation.h>
#ifdef __has_feature
#define CATCH_ARC_ENABLED __has_feature(objc_arc)
#else
#define CATCH_ARC_ENABLED 0
#endif
void arcSafeRelease( NSObject* obj );
id performOptionalSelector( id obj, SEL sel );
#if !CATCH_ARC_ENABLED
inline void arcSafeRelease( NSObject* obj ) {
[obj release];
}
inline id performOptionalSelector( id obj, SEL sel ) {
if( [obj respondsToSelector: sel] )
return [obj performSelector: sel];
return nil;
}
#define CATCH_UNSAFE_UNRETAINED
#define CATCH_ARC_STRONG
#else
inline void arcSafeRelease( NSObject* ){}
inline id performOptionalSelector( id obj, SEL sel ) {
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
#endif
if( [obj respondsToSelector: sel] )
return [obj performSelector: sel];
#ifdef __clang__
#pragma clang diagnostic pop
#endif
return nil;
}
#define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
#define CATCH_ARC_STRONG __strong
#endif
#endif
#ifdef CATCH_CONFIG_CPP11_TUPLE
#include <tuple>
#endif
#ifdef CATCH_CONFIG_CPP11_IS_ENUM
#include <type_traits>
#endif
namespace Catch {
// Why we're here.
template<typename T>
std::string toString( T const& value );
// Built in overloads
std::string toString( std::string const& value );
std::string toString( std::wstring const& value );
std::string toString( const char* const value );
std::string toString( char* const value );
std::string toString( const wchar_t* const value );
std::string toString( wchar_t* const value );
std::string toString( int value );
std::string toString( unsigned long value );
std::string toString( unsigned int value );
std::string toString( const double value );
std::string toString( const float value );
std::string toString( bool value );
std::string toString( char value );
std::string toString( signed char value );
std::string toString( unsigned char value );
#ifdef CATCH_CONFIG_CPP11_NULLPTR
std::string toString( std::nullptr_t );
#endif
#ifdef __OBJC__
std::string toString( NSString const * const& nsstring );
std::string toString( NSString * CATCH_ARC_STRONG const& nsstring );
std::string toString( NSObject* const& nsObject );
#endif
namespace Detail {
extern std::string unprintableString;
struct BorgType {
template<typename T> BorgType( T const& );
};
struct TrueType { char sizer[1]; };
struct FalseType { char sizer[2]; };
TrueType& testStreamable( std::ostream& );
FalseType testStreamable( FalseType );
FalseType operator<<( std::ostream const&, BorgType const& );
template<typename T>
struct IsStreamInsertable {
static std::ostream &s;
static T const&t;
enum { value = sizeof( testStreamable(s << t) ) == sizeof( TrueType ) };
};
#if defined(CATCH_CONFIG_CPP11_IS_ENUM)
template<typename T,
bool IsEnum = std::is_enum<T>::value
>
struct EnumStringMaker
{
static std::string convert( T const& ) { return unprintableString; }
};
template<typename T>
struct EnumStringMaker<T,true>
{
static std::string convert( T const& v )
{
return ::Catch::toString(
static_cast<typename std::underlying_type<T>::type>(v)
);
}
};
#endif
template<bool C>
struct StringMakerBase {
#if defined(CATCH_CONFIG_CPP11_IS_ENUM)
template<typename T>
static std::string convert( T const& v )
{
return EnumStringMaker<T>::convert( v );
}
#else
template<typename T>
static std::string convert( T const& ) { return unprintableString; }
#endif
};
template<>
struct StringMakerBase<true> {
template<typename T>
static std::string convert( T const& _value ) {
std::ostringstream oss;
oss << _value;
return oss.str();
}
};
std::string rawMemoryToString( const void *object, std::size_t size );
template<typename T>
inline std::string rawMemoryToString( const T& object ) {
return rawMemoryToString( &object, sizeof(object) );
}
} // end namespace Detail
template<typename T>
struct StringMaker :
Detail::StringMakerBase<Detail::IsStreamInsertable<T>::value> {};
template<typename T>
struct StringMaker<T*> {
template<typename U>
static std::string convert( U* p ) {
if( !p )
return INTERNAL_CATCH_STRINGIFY( NULL );
else
return Detail::rawMemoryToString( p );
}
};
template<typename R, typename C>
struct StringMaker<R C::*> {
static std::string convert( R C::* p ) {
if( !p )
return INTERNAL_CATCH_STRINGIFY( NULL );
else
return Detail::rawMemoryToString( p );
}
};
namespace Detail {
template<typename InputIterator>
std::string rangeToString( InputIterator first, InputIterator last );
}
//template<typename T, typename Allocator>
//struct StringMaker<std::vector<T, Allocator> > {
// static std::string convert( std::vector<T,Allocator> const& v ) {
// return Detail::rangeToString( v.begin(), v.end() );
// }
//};
template<typename T, typename Allocator>
std::string toString( std::vector<T,Allocator> const& v ) {
return Detail::rangeToString( v.begin(), v.end() );
}
#ifdef CATCH_CONFIG_CPP11_TUPLE
// toString for tuples
namespace TupleDetail {
template<
typename Tuple,
std::size_t N = 0,
bool = (N < std::tuple_size<Tuple>::value)
>
struct ElementPrinter {
static void print( const Tuple& tuple, std::ostream& os )
{
os << ( N ? ", " : " " )
<< Catch::toString(std::get<N>(tuple));
ElementPrinter<Tuple,N+1>::print(tuple,os);
}
};
template<
typename Tuple,
std::size_t N
>
struct ElementPrinter<Tuple,N,false> {
static void print( const Tuple&, std::ostream& ) {}
};
}
template<typename ...Types>
struct StringMaker<std::tuple<Types...>> {
static std::string convert( const std::tuple<Types...>& tuple )
{
std::ostringstream os;
os << '{';
TupleDetail::ElementPrinter<std::tuple<Types...>>::print( tuple, os );
os << " }";
return os.str();
}
};
#endif // CATCH_CONFIG_CPP11_TUPLE
namespace Detail {
template<typename T>
std::string makeString( T const& value ) {
return StringMaker<T>::convert( value );
}
} // end namespace Detail
/// \brief converts any type to a string
///
/// The default template forwards on to ostringstream - except when an
/// ostringstream overload does not exist - in which case it attempts to detect
/// that and writes {?}.
/// Overload (not specialise) this template for custom typs that you don't want
/// to provide an ostream overload for.
template<typename T>
std::string toString( T const& value ) {
return StringMaker<T>::convert( value );
}
namespace Detail {
template<typename InputIterator>
std::string rangeToString( InputIterator first, InputIterator last ) {
std::ostringstream oss;
oss << "{ ";
if( first != last ) {
oss << Catch::toString( *first );
for( ++first ; first != last ; ++first )
oss << ", " << Catch::toString( *first );
}
oss << " }";
return oss.str();
}
}
} // end namespace Catch
namespace Catch {
// Wraps the LHS of an expression and captures the operator and RHS (if any) -
// wrapping them all in a ResultBuilder object
template<typename T>
class ExpressionLhs {
ExpressionLhs& operator = ( ExpressionLhs const& );
# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS
ExpressionLhs& operator = ( ExpressionLhs && ) = delete;
# endif
public:
ExpressionLhs( ResultBuilder& rb, T lhs ) : m_rb( rb ), m_lhs( lhs ) {}
# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS
ExpressionLhs( ExpressionLhs const& ) = default;
ExpressionLhs( ExpressionLhs && ) = default;
# endif
template<typename RhsT>
ResultBuilder& operator == ( RhsT const& rhs ) {
return captureExpression<Internal::IsEqualTo>( rhs );
}
template<typename RhsT>
ResultBuilder& operator != ( RhsT const& rhs ) {
return captureExpression<Internal::IsNotEqualTo>( rhs );
}
template<typename RhsT>
ResultBuilder& operator < ( RhsT const& rhs ) {
return captureExpression<Internal::IsLessThan>( rhs );
}
template<typename RhsT>
ResultBuilder& operator > ( RhsT const& rhs ) {
return captureExpression<Internal::IsGreaterThan>( rhs );
}
template<typename RhsT>
ResultBuilder& operator <= ( RhsT const& rhs ) {
return captureExpression<Internal::IsLessThanOrEqualTo>( rhs );
}
template<typename RhsT>
ResultBuilder& operator >= ( RhsT const& rhs ) {
return captureExpression<Internal::IsGreaterThanOrEqualTo>( rhs );
}
ResultBuilder& operator == ( bool rhs ) {
return captureExpression<Internal::IsEqualTo>( rhs );
}
ResultBuilder& operator != ( bool rhs ) {
return captureExpression<Internal::IsNotEqualTo>( rhs );
}
void endExpression() {
bool value = m_lhs ? true : false;
m_rb
.setLhs( Catch::toString( value ) )
.setResultType( value )
.endExpression();
}
// Only simple binary expressions are allowed on the LHS.
// If more complex compositions are required then place the sub expression in parentheses
template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator + ( RhsT const& );
template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator - ( RhsT const& );
template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator / ( RhsT const& );
template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator * ( RhsT const& );
template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator && ( RhsT const& );
template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator || ( RhsT const& );
private:
template<Internal::Operator Op, typename RhsT>
ResultBuilder& captureExpression( RhsT const& rhs ) {
return m_rb
.setResultType( Internal::compare<Op>( m_lhs, rhs ) )
.setLhs( Catch::toString( m_lhs ) )
.setRhs( Catch::toString( rhs ) )
.setOp( Internal::OperatorTraits<Op>::getName() );
}
private:
ResultBuilder& m_rb;
T m_lhs;
};
} // end namespace Catch
namespace Catch {
template<typename T>
inline ExpressionLhs<T const&> ResultBuilder::operator <= ( T const& operand ) {
return ExpressionLhs<T const&>( *this, operand );
}
inline ExpressionLhs<bool> ResultBuilder::operator <= ( bool value ) {
return ExpressionLhs<bool>( *this, value );
}
} // namespace Catch
// #included from: catch_msg.h
#define TWOBLUECUBES_CATCH_MSG_H_INCLUDED
#include <string>
namespace Catch {
struct MessageInfo {
MessageInfo( std::string const& _macroName,
SourceLineInfo const& _lineInfo,
ResultWas::OfType _type );
std::string macroName;
SourceLineInfo lineInfo;
ResultWas::OfType type;
std::string message;
unsigned int sequence;
bool operator == ( MessageInfo const& other ) const {
return sequence == other.sequence;
}
bool operator < ( MessageInfo const& other ) const {
return sequence < other.sequence;
}
private:
static unsigned int globalCount;
};
struct MessageBuilder {
MessageBuilder( std::string const& macroName,
SourceLineInfo const& lineInfo,
ResultWas::OfType type )
: m_info( macroName, lineInfo, type )
{}
template<typename T>
MessageBuilder& operator << ( T const& value ) {
m_stream << value;
return *this;
}
MessageInfo m_info;
std::ostringstream m_stream;
};
class ScopedMessage {
public:
ScopedMessage( MessageBuilder const& builder );
ScopedMessage( ScopedMessage const& other );
~ScopedMessage();
MessageInfo m_info;
};
} // end namespace Catch
// #included from: catch_interfaces_capture.h
#define TWOBLUECUBES_CATCH_INTERFACES_CAPTURE_H_INCLUDED
#include <string>
namespace Catch {
class TestCase;
class AssertionResult;
struct AssertionInfo;
struct SectionInfo;
struct MessageInfo;
class ScopedMessageBuilder;
struct Counts;
struct IResultCapture {
virtual ~IResultCapture();
virtual void assertionEnded( AssertionResult const& result ) = 0;
virtual bool sectionStarted( SectionInfo const& sectionInfo,
Counts& assertions ) = 0;
virtual void sectionEnded( SectionInfo const& name, Counts const& assertions, double _durationInSeconds ) = 0;
virtual void pushScopedMessage( MessageInfo const& message ) = 0;
virtual void popScopedMessage( MessageInfo const& message ) = 0;
virtual std::string getCurrentTestName() const = 0;
virtual const AssertionResult* getLastResult() const = 0;
virtual void handleFatalErrorCondition( std::string const& message ) = 0;
};
IResultCapture& getResultCapture();
}
// #included from: catch_debugger.h
#define TWOBLUECUBES_CATCH_DEBUGGER_H_INCLUDED
// #included from: catch_platform.h
#define TWOBLUECUBES_CATCH_PLATFORM_H_INCLUDED
#if defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
#define CATCH_PLATFORM_MAC
#elif defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
#define CATCH_PLATFORM_IPHONE
#elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER)
#define CATCH_PLATFORM_WINDOWS
#endif
#include <string>
namespace Catch{
bool isDebuggerActive();
void writeToDebugConsole( std::string const& text );
}
#ifdef CATCH_PLATFORM_MAC
// The following code snippet based on:
// http://cocoawithlove.com/2008/03/break-into-debugger.html
#ifdef DEBUG
#if defined(__ppc64__) || defined(__ppc__)
#define CATCH_BREAK_INTO_DEBUGGER() \
if( Catch::isDebuggerActive() ) { \
__asm__("li r0, 20\nsc\nnop\nli r0, 37\nli r4, 2\nsc\nnop\n" \
: : : "memory","r0","r3","r4" ); \
}
#else
#define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) {__asm__("int $3\n" : : );}
#endif
#endif
#elif defined(_MSC_VER)
#define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) { __debugbreak(); }
#elif defined(__MINGW32__)
extern "C" __declspec(dllimport) void __stdcall DebugBreak();
#define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) { DebugBreak(); }
#endif
#ifndef CATCH_BREAK_INTO_DEBUGGER
#define CATCH_BREAK_INTO_DEBUGGER() Catch::alwaysTrue();
#endif
// #included from: catch_interfaces_runner.h
#define TWOBLUECUBES_CATCH_INTERFACES_RUNNER_H_INCLUDED
namespace Catch {
class TestCase;
struct IRunner {
virtual ~IRunner();
virtual bool aborting() const = 0;
};
}
///////////////////////////////////////////////////////////////////////////////
// In the event of a failure works out if the debugger needs to be invoked
// and/or an exception thrown and takes appropriate action.
// This needs to be done as a macro so the debugger will stop in the user
// source code rather than in Catch library code
#define INTERNAL_CATCH_REACT( resultBuilder ) \
if( resultBuilder.shouldDebugBreak() ) CATCH_BREAK_INTO_DEBUGGER(); \
resultBuilder.react();
///////////////////////////////////////////////////////////////////////////////
#define INTERNAL_CATCH_TEST( expr, resultDisposition, macroName ) \
do { \
Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \
try { \
( __catchResult <= expr ).endExpression(); \
} \
catch( ... ) { \
__catchResult.useActiveException( Catch::ResultDisposition::Normal ); \
} \
INTERNAL_CATCH_REACT( __catchResult ) \
} while( Catch::isTrue( false && (expr) ) ) // expr here is never evaluated at runtime but it forces the compiler to give it a look
///////////////////////////////////////////////////////////////////////////////
#define INTERNAL_CATCH_IF( expr, resultDisposition, macroName ) \
INTERNAL_CATCH_TEST( expr, resultDisposition, macroName ); \
if( Catch::getResultCapture().getLastResult()->succeeded() )
///////////////////////////////////////////////////////////////////////////////
#define INTERNAL_CATCH_ELSE( expr, resultDisposition, macroName ) \
INTERNAL_CATCH_TEST( expr, resultDisposition, macroName ); \
if( !Catch::getResultCapture().getLastResult()->succeeded() )
///////////////////////////////////////////////////////////////////////////////
#define INTERNAL_CATCH_NO_THROW( expr, resultDisposition, macroName ) \
do { \
Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \
try { \
expr; \
__catchResult.captureResult( Catch::ResultWas::Ok ); \
} \
catch( ... ) { \
__catchResult.useActiveException( resultDisposition ); \
} \
INTERNAL_CATCH_REACT( __catchResult ) \
} while( Catch::alwaysFalse() )
///////////////////////////////////////////////////////////////////////////////
#define INTERNAL_CATCH_THROWS( expr, resultDisposition, macroName ) \
do { \
Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \
if( __catchResult.allowThrows() ) \
try { \
expr; \
__catchResult.captureResult( Catch::ResultWas::DidntThrowException ); \
} \
catch( ... ) { \
__catchResult.captureResult( Catch::ResultWas::Ok ); \
} \
else \
__catchResult.captureResult( Catch::ResultWas::Ok ); \
INTERNAL_CATCH_REACT( __catchResult ) \
} while( Catch::alwaysFalse() )
///////////////////////////////////////////////////////////////////////////////
#define INTERNAL_CATCH_THROWS_AS( expr, exceptionType, resultDisposition, macroName ) \
do { \
Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \
if( __catchResult.allowThrows() ) \
try { \
expr; \
__catchResult.captureResult( Catch::ResultWas::DidntThrowException ); \
} \
catch( exceptionType ) { \
__catchResult.captureResult( Catch::ResultWas::Ok ); \
} \
catch( ... ) { \
__catchResult.useActiveException( resultDisposition ); \
} \
else \
__catchResult.captureResult( Catch::ResultWas::Ok ); \
INTERNAL_CATCH_REACT( __catchResult ) \
} while( Catch::alwaysFalse() )
///////////////////////////////////////////////////////////////////////////////
#ifdef CATCH_CONFIG_VARIADIC_MACROS
#define INTERNAL_CATCH_MSG( messageType, resultDisposition, macroName, ... ) \
do { \
Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, "", resultDisposition ); \
__catchResult << __VA_ARGS__ + ::Catch::StreamEndStop(); \
__catchResult.captureResult( messageType ); \
INTERNAL_CATCH_REACT( __catchResult ) \
} while( Catch::alwaysFalse() )
#else
#define INTERNAL_CATCH_MSG( messageType, resultDisposition, macroName, log ) \
do { \
Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, "", resultDisposition ); \
__catchResult << log + ::Catch::StreamEndStop(); \
__catchResult.captureResult( messageType ); \
INTERNAL_CATCH_REACT( __catchResult ) \
} while( Catch::alwaysFalse() )
#endif
///////////////////////////////////////////////////////////////////////////////
#define INTERNAL_CATCH_INFO( log, macroName ) \
Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage ) = Catch::MessageBuilder( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log;
///////////////////////////////////////////////////////////////////////////////
#define INTERNAL_CHECK_THAT( arg, matcher, resultDisposition, macroName ) \
do { \
Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #arg " " #matcher, resultDisposition ); \
try { \
std::string matcherAsString = ::Catch::Matchers::matcher.toString(); \
__catchResult \
.setLhs( Catch::toString( arg ) ) \
.setRhs( matcherAsString == Catch::Detail::unprintableString ? #matcher : matcherAsString ) \
.setOp( "matches" ) \
.setResultType( ::Catch::Matchers::matcher.match( arg ) ); \
__catchResult.captureExpression(); \
} catch( ... ) { \
__catchResult.useActiveException( resultDisposition | Catch::ResultDisposition::ContinueOnFailure ); \
} \
INTERNAL_CATCH_REACT( __catchResult ) \
} while( Catch::alwaysFalse() )
// #included from: internal/catch_section.h
#define TWOBLUECUBES_CATCH_SECTION_H_INCLUDED
// #included from: catch_section_info.h
#define TWOBLUECUBES_CATCH_SECTION_INFO_H_INCLUDED
namespace Catch {
struct SectionInfo {
SectionInfo
( SourceLineInfo const& _lineInfo,
std::string const& _name,
std::string const& _description = std::string() );
std::string name;
std::string description;
SourceLineInfo lineInfo;
};
} // end namespace Catch
// #included from: catch_totals.hpp
#define TWOBLUECUBES_CATCH_TOTALS_HPP_INCLUDED
#include <cstddef>
namespace Catch {
struct Counts {
Counts() : passed( 0 ), failed( 0 ), failedButOk( 0 ) {}
Counts operator - ( Counts const& other ) const {
Counts diff;
diff.passed = passed - other.passed;
diff.failed = failed - other.failed;
diff.failedButOk = failedButOk - other.failedButOk;
return diff;
}
Counts& operator += ( Counts const& other ) {
passed += other.passed;
failed += other.failed;
failedButOk += other.failedButOk;
return *this;
}
std::size_t total() const {
return passed + failed + failedButOk;
}
bool allPassed() const {
return failed == 0 && failedButOk == 0;
}
bool allOk() const {
return failed == 0;
}
std::size_t passed;
std::size_t failed;
std::size_t failedButOk;
};
struct Totals {
Totals operator - ( Totals const& other ) const {
Totals diff;
diff.assertions = assertions - other.assertions;
diff.testCases = testCases - other.testCases;
return diff;
}
Totals delta( Totals const& prevTotals ) const {
Totals diff = *this - prevTotals;
if( diff.assertions.failed > 0 )
++diff.testCases.failed;
else if( diff.assertions.failedButOk > 0 )
++diff.testCases.failedButOk;
else
++diff.testCases.passed;
return diff;
}
Totals& operator += ( Totals const& other ) {
assertions += other.assertions;
testCases += other.testCases;
return *this;
}
Counts assertions;
Counts testCases;
};
}
// #included from: catch_timer.h
#define TWOBLUECUBES_CATCH_TIMER_H_INCLUDED
#ifdef CATCH_PLATFORM_WINDOWS
typedef unsigned long long uint64_t;
#else
#include <stdint.h>
#endif
namespace Catch {
class Timer {
public:
Timer() : m_ticks( 0 ) {}
void start();
unsigned int getElapsedMicroseconds() const;
unsigned int getElapsedMilliseconds() const;
double getElapsedSeconds() const;
private:
uint64_t m_ticks;
};
} // namespace Catch
#include <string>
namespace Catch {
class Section : NonCopyable {
public:
Section( SectionInfo const& info );
~Section();
// This indicates whether the section should be executed or not
operator bool() const;
private:
SectionInfo m_info;
std::string m_name;
Counts m_assertions;
bool m_sectionIncluded;
Timer m_timer;
};
} // end namespace Catch
#ifdef CATCH_CONFIG_VARIADIC_MACROS
#define INTERNAL_CATCH_SECTION( ... ) \
if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) )
#else
#define INTERNAL_CATCH_SECTION( name, desc ) \
if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, name, desc ) )
#endif
// #included from: internal/catch_generators.hpp
#define TWOBLUECUBES_CATCH_GENERATORS_HPP_INCLUDED
#include <iterator>
#include <vector>
#include <string>
#include <stdlib.h>
namespace Catch {
template<typename T>
struct IGenerator {
virtual ~IGenerator() {}
virtual T getValue( std::size_t index ) const = 0;
virtual std::size_t size () const = 0;
};
template<typename T>
class BetweenGenerator : public IGenerator<T> {
public:
BetweenGenerator( T from, T to ) : m_from( from ), m_to( to ){}
virtual T getValue( std::size_t index ) const {
return m_from+static_cast<int>( index );
}
virtual std::size_t size() const {
return static_cast<std::size_t>( 1+m_to-m_from );
}
private:
T m_from;
T m_to;
};
template<typename T>
class ValuesGenerator : public IGenerator<T> {
public:
ValuesGenerator(){}
void add( T value ) {
m_values.push_back( value );
}
virtual T getValue( std::size_t index ) const {
return m_values[index];
}
virtual std::size_t size() const {
return m_values.size();
}
private:
std::vector<T> m_values;
};
template<typename T>
class CompositeGenerator {
public:
CompositeGenerator() : m_totalSize( 0 ) {}
// *** Move semantics, similar to auto_ptr ***
CompositeGenerator( CompositeGenerator& other )
: m_fileInfo( other.m_fileInfo ),
m_totalSize( 0 )
{
move( other );
}
CompositeGenerator& setFileInfo( const char* fileInfo ) {
m_fileInfo = fileInfo;
return *this;
}
~CompositeGenerator() {
deleteAll( m_composed );
}
operator T () const {
size_t overallIndex = getCurrentContext().getGeneratorIndex( m_fileInfo, m_totalSize );
typename std::vector<const IGenerator<T>*>::const_iterator it = m_composed.begin();
typename std::vector<const IGenerator<T>*>::const_iterator itEnd = m_composed.end();
for( size_t index = 0; it != itEnd; ++it )
{
const IGenerator<T>* generator = *it;
if( overallIndex >= index && overallIndex < index + generator->size() )
{
return generator->getValue( overallIndex-index );
}
index += generator->size();
}
CATCH_INTERNAL_ERROR( "Indexed past end of generated range" );
return T(); // Suppress spurious "not all control paths return a value" warning in Visual Studio - if you know how to fix this please do so
}
void add( const IGenerator<T>* generator ) {
m_totalSize += generator->size();
m_composed.push_back( generator );
}
CompositeGenerator& then( CompositeGenerator& other ) {
move( other );
return *this;
}
CompositeGenerator& then( T value ) {
ValuesGenerator<T>* valuesGen = new ValuesGenerator<T>();
valuesGen->add( value );
add( valuesGen );
return *this;
}
private:
void move( CompositeGenerator& other ) {
std::copy( other.m_composed.begin(), other.m_composed.end(), std::back_inserter( m_composed ) );
m_totalSize += other.m_totalSize;
other.m_composed.clear();
}
std::vector<const IGenerator<T>*> m_composed;
std::string m_fileInfo;
size_t m_totalSize;
};
namespace Generators
{
template<typename T>
CompositeGenerator<T> between( T from, T to ) {
CompositeGenerator<T> generators;
generators.add( new BetweenGenerator<T>( from, to ) );
return generators;
}
template<typename T>
CompositeGenerator<T> values( T val1, T val2 ) {
CompositeGenerator<T> generators;
ValuesGenerator<T>* valuesGen = new ValuesGenerator<T>();
valuesGen->add( val1 );
valuesGen->add( val2 );
generators.add( valuesGen );
return generators;
}
template<typename T>
CompositeGenerator<T> values( T val1, T val2, T val3 ){
CompositeGenerator<T> generators;
ValuesGenerator<T>* valuesGen = new ValuesGenerator<T>();
valuesGen->add( val1 );
valuesGen->add( val2 );
valuesGen->add( val3 );
generators.add( valuesGen );
return generators;
}
template<typename T>
CompositeGenerator<T> values( T val1, T val2, T val3, T val4 ) {
CompositeGenerator<T> generators;
ValuesGenerator<T>* valuesGen = new ValuesGenerator<T>();
valuesGen->add( val1 );
valuesGen->add( val2 );
valuesGen->add( val3 );
valuesGen->add( val4 );
generators.add( valuesGen );
return generators;
}
} // end namespace Generators
using namespace Generators;
} // end namespace Catch
#define INTERNAL_CATCH_LINESTR2( line ) #line
#define INTERNAL_CATCH_LINESTR( line ) INTERNAL_CATCH_LINESTR2( line )
#define INTERNAL_CATCH_GENERATE( expr ) expr.setFileInfo( __FILE__ "(" INTERNAL_CATCH_LINESTR( __LINE__ ) ")" )
// #included from: internal/catch_interfaces_exception.h
#define TWOBLUECUBES_CATCH_INTERFACES_EXCEPTION_H_INCLUDED
#include <string>
// #included from: catch_interfaces_registry_hub.h
#define TWOBLUECUBES_CATCH_INTERFACES_REGISTRY_HUB_H_INCLUDED
#include <string>
namespace Catch {
class TestCase;
struct ITestCaseRegistry;
struct IExceptionTranslatorRegistry;
struct IExceptionTranslator;
struct IReporterRegistry;
struct IReporterFactory;
struct IRegistryHub {
virtual ~IRegistryHub();
virtual IReporterRegistry const& getReporterRegistry() const = 0;
virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0;
virtual IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() = 0;
};
struct IMutableRegistryHub {
virtual ~IMutableRegistryHub();
virtual void registerReporter( std::string const& name, IReporterFactory* factory ) = 0;
virtual void registerTest( TestCase const& testInfo ) = 0;
virtual void registerTranslator( const IExceptionTranslator* translator ) = 0;
};
IRegistryHub& getRegistryHub();
IMutableRegistryHub& getMutableRegistryHub();
void cleanUp();
std::string translateActiveException();
}
namespace Catch {
typedef std::string(*exceptionTranslateFunction)();
struct IExceptionTranslator {
virtual ~IExceptionTranslator();
virtual std::string translate() const = 0;
};
struct IExceptionTranslatorRegistry {
virtual ~IExceptionTranslatorRegistry();
virtual std::string translateActiveException() const = 0;
};
class ExceptionTranslatorRegistrar {
template<typename T>
class ExceptionTranslator : public IExceptionTranslator {
public:
ExceptionTranslator( std::string(*translateFunction)( T& ) )
: m_translateFunction( translateFunction )
{}
virtual std::string translate() const {
try {
throw;
}
catch( T& ex ) {
return m_translateFunction( ex );
}
}
protected:
std::string(*m_translateFunction)( T& );
};
public:
template<typename T>
ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) {
getMutableRegistryHub().registerTranslator
( new ExceptionTranslator<T>( translateFunction ) );
}
};
}
///////////////////////////////////////////////////////////////////////////////
#define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) \
static std::string INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator )( signature ); \
namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ) ); }\
static std::string INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator )( signature )
// #included from: internal/catch_approx.hpp
#define TWOBLUECUBES_CATCH_APPROX_HPP_INCLUDED
#include <cmath>
#include <limits>
namespace Catch {
namespace Detail {
class Approx {
public:
explicit Approx ( double value )
: m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
m_scale( 1.0 ),
m_value( value )
{}
Approx( Approx const& other )
: m_epsilon( other.m_epsilon ),
m_scale( other.m_scale ),
m_value( other.m_value )
{}
static Approx custom() {
return Approx( 0 );
}
Approx operator()( double value ) {
Approx approx( value );
approx.epsilon( m_epsilon );
approx.scale( m_scale );
return approx;
}
friend bool operator == ( double lhs, Approx const& rhs ) {
// Thanks to Richard Harris for his help refining this formula
return fabs( lhs - rhs.m_value ) < rhs.m_epsilon * (rhs.m_scale + (std::max)( fabs(lhs), fabs(rhs.m_value) ) );
}
friend bool operator == ( Approx const& lhs, double rhs ) {
return operator==( rhs, lhs );
}
friend bool operator != ( double lhs, Approx const& rhs ) {
return !operator==( lhs, rhs );
}
friend bool operator != ( Approx const& lhs, double rhs ) {
return !operator==( rhs, lhs );
}
Approx& epsilon( double newEpsilon ) {
m_epsilon = newEpsilon;
return *this;
}
Approx& scale( double newScale ) {
m_scale = newScale;
return *this;
}
std::string toString() const {
std::ostringstream oss;
oss << "Approx( " << Catch::toString( m_value ) << " )";
return oss.str();
}
private:
double m_epsilon;
double m_scale;
double m_value;
};
}
template<>
inline std::string toString<Detail::Approx>( Detail::Approx const& value ) {
return value.toString();
}
} // end namespace Catch
// #included from: internal/catch_matchers.hpp
#define TWOBLUECUBES_CATCH_MATCHERS_HPP_INCLUDED
namespace Catch {
namespace Matchers {
namespace Impl {
template<typename ExpressionT>
struct Matcher : SharedImpl<IShared>
{
typedef ExpressionT ExpressionType;
virtual ~Matcher() {}
virtual Ptr<Matcher> clone() const = 0;
virtual bool match( ExpressionT const& expr ) const = 0;
virtual std::string toString() const = 0;
};
template<typename DerivedT, typename ExpressionT>
struct MatcherImpl : Matcher<ExpressionT> {
virtual Ptr<Matcher<ExpressionT> > clone() const {
return Ptr<Matcher<ExpressionT> >( new DerivedT( static_cast<DerivedT const&>( *this ) ) );
}
};
namespace Generic {
template<typename ExpressionT>
class AllOf : public MatcherImpl<AllOf<ExpressionT>, ExpressionT> {
public:
AllOf() {}
AllOf( AllOf const& other ) : m_matchers( other.m_matchers ) {}
AllOf& add( Matcher<ExpressionT> const& matcher ) {
m_matchers.push_back( matcher.clone() );
return *this;
}
virtual bool match( ExpressionT const& expr ) const
{
for( std::size_t i = 0; i < m_matchers.size(); ++i )
if( !m_matchers[i]->match( expr ) )
return false;
return true;
}
virtual std::string toString() const {
std::ostringstream oss;
oss << "( ";
for( std::size_t i = 0; i < m_matchers.size(); ++i ) {
if( i != 0 )
oss << " and ";
oss << m_matchers[i]->toString();
}
oss << " )";
return oss.str();
}
private:
std::vector<Ptr<Matcher<ExpressionT> > > m_matchers;
};
template<typename ExpressionT>
class AnyOf : public MatcherImpl<AnyOf<ExpressionT>, ExpressionT> {
public:
AnyOf() {}
AnyOf( AnyOf const& other ) : m_matchers( other.m_matchers ) {}
AnyOf& add( Matcher<ExpressionT> const& matcher ) {
m_matchers.push_back( matcher.clone() );
return *this;
}
virtual bool match( ExpressionT const& expr ) const
{
for( std::size_t i = 0; i < m_matchers.size(); ++i )
if( m_matchers[i]->match( expr ) )
return true;
return false;
}
virtual std::string toString() const {
std::ostringstream oss;
oss << "( ";
for( std::size_t i = 0; i < m_matchers.size(); ++i ) {
if( i != 0 )
oss << " or ";
oss << m_matchers[i]->toString();
}
oss << " )";
return oss.str();
}
private:
std::vector<Ptr<Matcher<ExpressionT> > > m_matchers;
};
}
namespace StdString {
inline std::string makeString( std::string const& str ) { return str; }
inline std::string makeString( const char* str ) { return str ? std::string( str ) : std::string(); }
struct Equals : MatcherImpl<Equals, std::string> {
Equals( std::string const& str ) : m_str( str ){}
Equals( Equals const& other ) : m_str( other.m_str ){}
virtual ~Equals();
virtual bool match( std::string const& expr ) const {
return m_str == expr;
}
virtual std::string toString() const {
return "equals: \"" + m_str + "\"";
}
std::string m_str;
};
struct Contains : MatcherImpl<Contains, std::string> {
Contains( std::string const& substr ) : m_substr( substr ){}
Contains( Contains const& other ) : m_substr( other.m_substr ){}
virtual ~Contains();
virtual bool match( std::string const& expr ) const {
return expr.find( m_substr ) != std::string::npos;
}
virtual std::string toString() const {
return "contains: \"" + m_substr + "\"";
}
std::string m_substr;
};
struct StartsWith : MatcherImpl<StartsWith, std::string> {
StartsWith( std::string const& substr ) : m_substr( substr ){}
StartsWith( StartsWith const& other ) : m_substr( other.m_substr ){}
virtual ~StartsWith();
virtual bool match( std::string const& expr ) const {
return expr.find( m_substr ) == 0;
}
virtual std::string toString() const {
return "starts with: \"" + m_substr + "\"";
}
std::string m_substr;
};
struct EndsWith : MatcherImpl<EndsWith, std::string> {
EndsWith( std::string const& substr ) : m_substr( substr ){}
EndsWith( EndsWith const& other ) : m_substr( other.m_substr ){}
virtual ~EndsWith();
virtual bool match( std::string const& expr ) const {
return expr.find( m_substr ) == expr.size() - m_substr.size();
}
virtual std::string toString() const {
return "ends with: \"" + m_substr + "\"";
}
std::string m_substr;
};
} // namespace StdString
} // namespace Impl
// The following functions create the actual matcher objects.
// This allows the types to be inferred
template<typename ExpressionT>
inline Impl::Generic::AllOf<ExpressionT> AllOf( Impl::Matcher<ExpressionT> const& m1,
Impl::Matcher<ExpressionT> const& m2 ) {
return Impl::Generic::AllOf<ExpressionT>().add( m1 ).add( m2 );
}
template<typename ExpressionT>
inline Impl::Generic::AllOf<ExpressionT> AllOf( Impl::Matcher<ExpressionT> const& m1,
Impl::Matcher<ExpressionT> const& m2,
Impl::Matcher<ExpressionT> const& m3 ) {
return Impl::Generic::AllOf<ExpressionT>().add( m1 ).add( m2 ).add( m3 );
}
template<typename ExpressionT>
inline Impl::Generic::AnyOf<ExpressionT> AnyOf( Impl::Matcher<ExpressionT> const& m1,
Impl::Matcher<ExpressionT> const& m2 ) {
return Impl::Generic::AnyOf<ExpressionT>().add( m1 ).add( m2 );
}
template<typename ExpressionT>
inline Impl::Generic::AnyOf<ExpressionT> AnyOf( Impl::Matcher<ExpressionT> const& m1,
Impl::Matcher<ExpressionT> const& m2,
Impl::Matcher<ExpressionT> const& m3 ) {
return Impl::Generic::AnyOf<ExpressionT>().add( m1 ).add( m2 ).add( m3 );
}
inline Impl::StdString::Equals Equals( std::string const& str ) {
return Impl::StdString::Equals( str );
}
inline Impl::StdString::Equals Equals( const char* str ) {
return Impl::StdString::Equals( Impl::StdString::makeString( str ) );
}
inline Impl::StdString::Contains Contains( std::string const& substr ) {
return Impl::StdString::Contains( substr );
}
inline Impl::StdString::Contains Contains( const char* substr ) {
return Impl::StdString::Contains( Impl::StdString::makeString( substr ) );
}
inline Impl::StdString::StartsWith StartsWith( std::string const& substr ) {
return Impl::StdString::StartsWith( substr );
}
inline Impl::StdString::StartsWith StartsWith( const char* substr ) {
return Impl::StdString::StartsWith( Impl::StdString::makeString( substr ) );
}
inline Impl::StdString::EndsWith EndsWith( std::string const& substr ) {
return Impl::StdString::EndsWith( substr );
}
inline Impl::StdString::EndsWith EndsWith( const char* substr ) {
return Impl::StdString::EndsWith( Impl::StdString::makeString( substr ) );
}
} // namespace Matchers
using namespace Matchers;
} // namespace Catch
// #included from: internal/catch_interfaces_tag_alias_registry.h
#define TWOBLUECUBES_CATCH_INTERFACES_TAG_ALIAS_REGISTRY_H_INCLUDED
// #included from: catch_tag_alias.h
#define TWOBLUECUBES_CATCH_TAG_ALIAS_H_INCLUDED
#include <string>
namespace Catch {
struct TagAlias {
TagAlias( std::string _tag, SourceLineInfo _lineInfo ) : tag( _tag ), lineInfo( _lineInfo ) {}
std::string tag;
SourceLineInfo lineInfo;
};
struct RegistrarForTagAliases {
RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo );
};
} // end namespace Catch
#define CATCH_REGISTER_TAG_ALIAS( alias, spec ) namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); }
// #included from: catch_option.hpp
#define TWOBLUECUBES_CATCH_OPTION_HPP_INCLUDED
namespace Catch {
// An optional type
template<typename T>
class Option {
public:
Option() : nullableValue( NULL ) {}
Option( T const& _value )
: nullableValue( new( storage ) T( _value ) )
{}
Option( Option const& _other )
: nullableValue( _other ? new( storage ) T( *_other ) : NULL )
{}
~Option() {
reset();
}
Option& operator= ( Option const& _other ) {
if( &_other != this ) {
reset();
if( _other )
nullableValue = new( storage ) T( *_other );
}
return *this;
}
Option& operator = ( T const& _value ) {
reset();
nullableValue = new( storage ) T( _value );
return *this;
}
void reset() {
if( nullableValue )
nullableValue->~T();
nullableValue = NULL;
}
T& operator*() { return *nullableValue; }
T const& operator*() const { return *nullableValue; }
T* operator->() { return nullableValue; }
const T* operator->() const { return nullableValue; }
T valueOr( T const& defaultValue ) const {
return nullableValue ? *nullableValue : defaultValue;
}
bool some() const { return nullableValue != NULL; }
bool none() const { return nullableValue == NULL; }
bool operator !() const { return nullableValue == NULL; }
operator SafeBool::type() const {
return SafeBool::makeSafe( some() );
}
private:
T* nullableValue;
char storage[sizeof(T)];
};
} // end namespace Catch
namespace Catch {
struct ITagAliasRegistry {
virtual ~ITagAliasRegistry();
virtual Option<TagAlias> find( std::string const& alias ) const = 0;
virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0;
static ITagAliasRegistry const& get();
};
} // end namespace Catch
// These files are included here so the single_include script doesn't put them
// in the conditionally compiled sections
// #included from: internal/catch_test_case_info.h
#define TWOBLUECUBES_CATCH_TEST_CASE_INFO_H_INCLUDED
#include <string>
#include <set>
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpadded"
#endif
namespace Catch {
struct ITestCase;
struct TestCaseInfo {
enum SpecialProperties{
None = 0,
IsHidden = 1 << 1,
ShouldFail = 1 << 2,
MayFail = 1 << 3,
Throws = 1 << 4
};
TestCaseInfo( std::string const& _name,
std::string const& _className,
std::string const& _description,
std::set<std::string> const& _tags,
SourceLineInfo const& _lineInfo );
TestCaseInfo( TestCaseInfo const& other );
bool isHidden() const;
bool throws() const;
bool okToFail() const;
bool expectedToFail() const;
std::string name;
std::string className;
std::string description;
std::set<std::string> tags;
std::set<std::string> lcaseTags;
std::string tagsAsString;
SourceLineInfo lineInfo;
SpecialProperties properties;
};
class TestCase : public TestCaseInfo {
public:
TestCase( ITestCase* testCase, TestCaseInfo const& info );
TestCase( TestCase const& other );
TestCase withName( std::string const& _newName ) const;
void invoke() const;
TestCaseInfo const& getTestCaseInfo() const;
void swap( TestCase& other );
bool operator == ( TestCase const& other ) const;
bool operator < ( TestCase const& other ) const;
TestCase& operator = ( TestCase const& other );
private:
Ptr<ITestCase> test;
};
TestCase makeTestCase( ITestCase* testCase,
std::string const& className,
std::string const& name,
std::string const& description,
SourceLineInfo const& lineInfo );
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __OBJC__
// #included from: internal/catch_objc.hpp
#define TWOBLUECUBES_CATCH_OBJC_HPP_INCLUDED
#import <objc/runtime.h>
#include <string>
// NB. Any general catch headers included here must be included
// in catch.hpp first to make sure they are included by the single
// header for non obj-usage
///////////////////////////////////////////////////////////////////////////////
// This protocol is really only here for (self) documenting purposes, since
// all its methods are optional.
@protocol OcFixture
@optional
-(void) setUp;
-(void) tearDown;
@end
namespace Catch {
class OcMethod : public SharedImpl<ITestCase> {
public:
OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {}
virtual void invoke() const {
id obj = [[m_cls alloc] init];
performOptionalSelector( obj, @selector(setUp) );
performOptionalSelector( obj, m_sel );
performOptionalSelector( obj, @selector(tearDown) );
arcSafeRelease( obj );
}
private:
virtual ~OcMethod() {}
Class m_cls;
SEL m_sel;
};
namespace Detail{
inline std::string getAnnotation( Class cls,
std::string const& annotationName,
std::string const& testCaseName ) {
NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
SEL sel = NSSelectorFromString( selStr );
arcSafeRelease( selStr );
id value = performOptionalSelector( cls, sel );
if( value )
return [(NSString*)value UTF8String];
return "";
}
}
inline size_t registerTestMethods() {
size_t noTestMethods = 0;
int noClasses = objc_getClassList( NULL, 0 );
Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses);
objc_getClassList( classes, noClasses );
for( int c = 0; c < noClasses; c++ ) {
Class cls = classes[c];
{
u_int count;
Method* methods = class_copyMethodList( cls, &count );
for( u_int m = 0; m < count ; m++ ) {
SEL selector = method_getName(methods[m]);
std::string methodName = sel_getName(selector);
if( startsWith( methodName, "Catch_TestCase_" ) ) {
std::string testCaseName = methodName.substr( 15 );
std::string name = Detail::getAnnotation( cls, "Name", testCaseName );
std::string desc = Detail::getAnnotation( cls, "Description", testCaseName );
const char* className = class_getName( cls );
getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, name.c_str(), desc.c_str(), SourceLineInfo() ) );
noTestMethods++;
}
}
free(methods);
}
}
return noTestMethods;
}
namespace Matchers {
namespace Impl {
namespace NSStringMatchers {
template<typename MatcherT>
struct StringHolder : MatcherImpl<MatcherT, NSString*>{
StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){}
StringHolder() {
arcSafeRelease( m_substr );
}
NSString* m_substr;
};
struct Equals : StringHolder<Equals> {
Equals( NSString* substr ) : StringHolder( substr ){}
virtual bool match( ExpressionType const& str ) const {
return (str != nil || m_substr == nil ) &&
[str isEqualToString:m_substr];
}
virtual std::string toString() const {
return "equals string: " + Catch::toString( m_substr );
}
};
struct Contains : StringHolder<Contains> {
Contains( NSString* substr ) : StringHolder( substr ){}
virtual bool match( ExpressionType const& str ) const {
return (str != nil || m_substr == nil ) &&
[str rangeOfString:m_substr].location != NSNotFound;
}
virtual std::string toString() const {
return "contains string: " + Catch::toString( m_substr );
}
};
struct StartsWith : StringHolder<StartsWith> {
StartsWith( NSString* substr ) : StringHolder( substr ){}
virtual bool match( ExpressionType const& str ) const {
return (str != nil || m_substr == nil ) &&
[str rangeOfString:m_substr].location == 0;
}
virtual std::string toString() const {
return "starts with: " + Catch::toString( m_substr );
}
};
struct EndsWith : StringHolder<EndsWith> {
EndsWith( NSString* substr ) : StringHolder( substr ){}
virtual bool match( ExpressionType const& str ) const {
return (str != nil || m_substr == nil ) &&
[str rangeOfString:m_substr].location == [str length] - [m_substr length];
}
virtual std::string toString() const {
return "ends with: " + Catch::toString( m_substr );
}
};
} // namespace NSStringMatchers
} // namespace Impl
inline Impl::NSStringMatchers::Equals
Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); }
inline Impl::NSStringMatchers::Contains
Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); }
inline Impl::NSStringMatchers::StartsWith
StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); }
inline Impl::NSStringMatchers::EndsWith
EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); }
} // namespace Matchers
using namespace Matchers;
} // namespace Catch
///////////////////////////////////////////////////////////////////////////////
#define OC_TEST_CASE( name, desc )\
+(NSString*) INTERNAL_CATCH_UNIQUE_NAME( Catch_Name_test ) \
{\
return @ name; \
}\
+(NSString*) INTERNAL_CATCH_UNIQUE_NAME( Catch_Description_test ) \
{ \
return @ desc; \
} \
-(void) INTERNAL_CATCH_UNIQUE_NAME( Catch_TestCase_test )
#endif
#ifdef CATCH_IMPL
// #included from: internal/catch_impl.hpp
#define TWOBLUECUBES_CATCH_IMPL_HPP_INCLUDED
// Collect all the implementation files together here
// These are the equivalent of what would usually be cpp files
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wweak-vtables"
#endif
// #included from: ../catch_runner.hpp
#define TWOBLUECUBES_CATCH_RUNNER_HPP_INCLUDED
// #included from: internal/catch_commandline.hpp
#define TWOBLUECUBES_CATCH_COMMANDLINE_HPP_INCLUDED
// #included from: catch_config.hpp
#define TWOBLUECUBES_CATCH_CONFIG_HPP_INCLUDED
// #included from: catch_test_spec_parser.hpp
#define TWOBLUECUBES_CATCH_TEST_SPEC_PARSER_HPP_INCLUDED
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpadded"
#endif
// #included from: catch_test_spec.hpp
#define TWOBLUECUBES_CATCH_TEST_SPEC_HPP_INCLUDED
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpadded"
#endif
#include <string>
#include <vector>
namespace Catch {
class TestSpec {
struct Pattern : SharedImpl<> {
virtual ~Pattern();
virtual bool matches( TestCaseInfo const& testCase ) const = 0;
};
class NamePattern : public Pattern {
enum WildcardPosition {
NoWildcard = 0,
WildcardAtStart = 1,
WildcardAtEnd = 2,
WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
};
public:
NamePattern( std::string const& name ) : m_name( toLower( name ) ), m_wildcard( NoWildcard ) {
if( startsWith( m_name, "*" ) ) {
m_name = m_name.substr( 1 );
m_wildcard = WildcardAtStart;
}
if( endsWith( m_name, "*" ) ) {
m_name = m_name.substr( 0, m_name.size()-1 );
m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
}
}
virtual ~NamePattern();
virtual bool matches( TestCaseInfo const& testCase ) const {
switch( m_wildcard ) {
case NoWildcard:
return m_name == toLower( testCase.name );
case WildcardAtStart:
return endsWith( toLower( testCase.name ), m_name );
case WildcardAtEnd:
return startsWith( toLower( testCase.name ), m_name );
case WildcardAtBothEnds:
return contains( toLower( testCase.name ), m_name );
}
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunreachable-code"
#endif
throw std::logic_error( "Unknown enum" );
#ifdef __clang__
#pragma clang diagnostic pop
#endif
}
private:
std::string m_name;
WildcardPosition m_wildcard;
};
class TagPattern : public Pattern {
public:
TagPattern( std::string const& tag ) : m_tag( toLower( tag ) ) {}
virtual ~TagPattern();
virtual bool matches( TestCaseInfo const& testCase ) const {
return testCase.lcaseTags.find( m_tag ) != testCase.lcaseTags.end();
}
private:
std::string m_tag;
};
class ExcludedPattern : public Pattern {
public:
ExcludedPattern( Ptr<Pattern> const& underlyingPattern ) : m_underlyingPattern( underlyingPattern ) {}
virtual ~ExcludedPattern();
virtual bool matches( TestCaseInfo const& testCase ) const { return !m_underlyingPattern->matches( testCase ); }
private:
Ptr<Pattern> m_underlyingPattern;
};
struct Filter {
std::vector<Ptr<Pattern> > m_patterns;
bool matches( TestCaseInfo const& testCase ) const {
// All patterns in a filter must match for the filter to be a match
for( std::vector<Ptr<Pattern> >::const_iterator it = m_patterns.begin(), itEnd = m_patterns.end(); it != itEnd; ++it )
if( !(*it)->matches( testCase ) )
return false;
return true;
}
};
public:
bool hasFilters() const {
return !m_filters.empty();
}
bool matches( TestCaseInfo const& testCase ) const {
// A TestSpec matches if any filter matches
for( std::vector<Filter>::const_iterator it = m_filters.begin(), itEnd = m_filters.end(); it != itEnd; ++it )
if( it->matches( testCase ) )
return true;
return false;
}
private:
std::vector<Filter> m_filters;
friend class TestSpecParser;
};
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
namespace Catch {
class TestSpecParser {
enum Mode{ None, Name, QuotedName, Tag };
Mode m_mode;
bool m_exclusion;
std::size_t m_start, m_pos;
std::string m_arg;
TestSpec::Filter m_currentFilter;
TestSpec m_testSpec;
ITagAliasRegistry const* m_tagAliases;
public:
TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {}
TestSpecParser& parse( std::string const& arg ) {
m_mode = None;
m_exclusion = false;
m_start = std::string::npos;
m_arg = m_tagAliases->expandAliases( arg );
for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
visitChar( m_arg[m_pos] );
if( m_mode == Name )
addPattern<TestSpec::NamePattern>();
return *this;
}
TestSpec testSpec() {
addFilter();
return m_testSpec;
}
private:
void visitChar( char c ) {
if( m_mode == None ) {
switch( c ) {
case ' ': return;
case '~': m_exclusion = true; return;
case '[': return startNewMode( Tag, ++m_pos );
case '"': return startNewMode( QuotedName, ++m_pos );
default: startNewMode( Name, m_pos ); break;
}
}
if( m_mode == Name ) {
if( c == ',' ) {
addPattern<TestSpec::NamePattern>();
addFilter();
}
else if( c == '[' ) {
if( subString() == "exclude:" )
m_exclusion = true;
else
addPattern<TestSpec::NamePattern>();
startNewMode( Tag, ++m_pos );
}
}
else if( m_mode == QuotedName && c == '"' )
addPattern<TestSpec::NamePattern>();
else if( m_mode == Tag && c == ']' )
addPattern<TestSpec::TagPattern>();
}
void startNewMode( Mode mode, std::size_t start ) {
m_mode = mode;
m_start = start;
}
std::string subString() const { return m_arg.substr( m_start, m_pos - m_start ); }
template<typename T>
void addPattern() {
std::string token = subString();
if( startsWith( token, "exclude:" ) ) {
m_exclusion = true;
token = token.substr( 8 );
}
if( !token.empty() ) {
Ptr<TestSpec::Pattern> pattern = new T( token );
if( m_exclusion )
pattern = new TestSpec::ExcludedPattern( pattern );
m_currentFilter.m_patterns.push_back( pattern );
}
m_exclusion = false;
m_mode = None;
}
void addFilter() {
if( !m_currentFilter.m_patterns.empty() ) {
m_testSpec.m_filters.push_back( m_currentFilter );
m_currentFilter = TestSpec::Filter();
}
}
};
inline TestSpec parseTestSpec( std::string const& arg ) {
return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
}
} // namespace Catch
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// #included from: catch_interfaces_config.h
#define TWOBLUECUBES_CATCH_INTERFACES_CONFIG_H_INCLUDED
#include <iostream>
#include <string>
#include <vector>
namespace Catch {
struct Verbosity { enum Level {
NoOutput = 0,
Quiet,
Normal
}; };
struct WarnAbout { enum What {
Nothing = 0x00,
NoAssertions = 0x01
}; };
struct ShowDurations { enum OrNot {
DefaultForReporter,
Always,
Never
}; };
struct RunTests { enum InWhatOrder {
InDeclarationOrder,
InLexicographicalOrder,
InRandomOrder
}; };
class TestSpec;
struct IConfig : IShared {
virtual ~IConfig();
virtual bool allowThrows() const = 0;
virtual std::ostream& stream() const = 0;
virtual std::string name() const = 0;
virtual bool includeSuccessfulResults() const = 0;
virtual bool shouldDebugBreak() const = 0;
virtual bool warnAboutMissingAssertions() const = 0;
virtual int abortAfter() const = 0;
virtual bool showInvisibles() const = 0;
virtual ShowDurations::OrNot showDurations() const = 0;
virtual TestSpec const& testSpec() const = 0;
virtual RunTests::InWhatOrder runOrder() const = 0;
virtual unsigned int rngSeed() const = 0;
virtual bool forceColour() const = 0;
};
}
// #included from: catch_stream.h
#define TWOBLUECUBES_CATCH_STREAM_H_INCLUDED
#include <streambuf>
#ifdef __clang__
#pragma clang diagnostic ignored "-Wpadded"
#endif
namespace Catch {
class Stream {
public:
Stream();
Stream( std::streambuf* _streamBuf, bool _isOwned );
void release();
std::streambuf* streamBuf;
private:
bool isOwned;
};
std::ostream& cout();
std::ostream& cerr();
}
#include <memory>
#include <vector>
#include <string>
#include <iostream>
#include <ctime>
#ifndef CATCH_CONFIG_CONSOLE_WIDTH
#define CATCH_CONFIG_CONSOLE_WIDTH 80
#endif
namespace Catch {
struct ConfigData {
ConfigData()
: listTests( false ),
listTags( false ),
listReporters( false ),
listTestNamesOnly( false ),
showSuccessfulTests( false ),
shouldDebugBreak( false ),
noThrow( false ),
showHelp( false ),
showInvisibles( false ),
forceColour( false ),
abortAfter( -1 ),
rngSeed( 0 ),
verbosity( Verbosity::Normal ),
warnings( WarnAbout::Nothing ),
showDurations( ShowDurations::DefaultForReporter ),
runOrder( RunTests::InDeclarationOrder )
{}
bool listTests;
bool listTags;
bool listReporters;
bool listTestNamesOnly;
bool showSuccessfulTests;
bool shouldDebugBreak;
bool noThrow;
bool showHelp;
bool showInvisibles;
bool forceColour;
int abortAfter;
unsigned int rngSeed;
Verbosity::Level verbosity;
WarnAbout::What warnings;
ShowDurations::OrNot showDurations;
RunTests::InWhatOrder runOrder;
std::string reporterName;
std::string outputFilename;
std::string name;
std::string processName;
std::vector<std::string> testsOrTags;
};
class Config : public SharedImpl<IConfig> {
private:
Config( Config const& other );
Config& operator = ( Config const& other );
virtual void dummy();
public:
Config()
: m_os( Catch::cout().rdbuf() )
{}
Config( ConfigData const& data )
: m_data( data ),
m_os( Catch::cout().rdbuf() )
{
if( !data.testsOrTags.empty() ) {
TestSpecParser parser( ITagAliasRegistry::get() );
for( std::size_t i = 0; i < data.testsOrTags.size(); ++i )
parser.parse( data.testsOrTags[i] );
m_testSpec = parser.testSpec();
}
}
virtual ~Config() {
m_os.rdbuf( Catch::cout().rdbuf() );
m_stream.release();
}
void setFilename( std::string const& filename ) {
m_data.outputFilename = filename;
}
std::string const& getFilename() const {
return m_data.outputFilename ;
}
bool listTests() const { return m_data.listTests; }
bool listTestNamesOnly() const { return m_data.listTestNamesOnly; }
bool listTags() const { return m_data.listTags; }
bool listReporters() const { return m_data.listReporters; }
std::string getProcessName() const { return m_data.processName; }
bool shouldDebugBreak() const { return m_data.shouldDebugBreak; }
void setStreamBuf( std::streambuf* buf ) {
m_os.rdbuf( buf ? buf : Catch::cout().rdbuf() );
}
void useStream( std::string const& streamName ) {
Stream stream = createStream( streamName );
setStreamBuf( stream.streamBuf );
m_stream.release();
m_stream = stream;
}
std::string getReporterName() const { return m_data.reporterName; }
int abortAfter() const { return m_data.abortAfter; }
TestSpec const& testSpec() const { return m_testSpec; }
bool showHelp() const { return m_data.showHelp; }
bool showInvisibles() const { return m_data.showInvisibles; }
// IConfig interface
virtual bool allowThrows() const { return !m_data.noThrow; }
virtual std::ostream& stream() const { return m_os; }
virtual std::string name() const { return m_data.name.empty() ? m_data.processName : m_data.name; }
virtual bool includeSuccessfulResults() const { return m_data.showSuccessfulTests; }
virtual bool warnAboutMissingAssertions() const { return m_data.warnings & WarnAbout::NoAssertions; }
virtual ShowDurations::OrNot showDurations() const { return m_data.showDurations; }
virtual RunTests::InWhatOrder runOrder() const { return m_data.runOrder; }
virtual unsigned int rngSeed() const { return m_data.rngSeed; }
virtual bool forceColour() const { return m_data.forceColour; }
private:
ConfigData m_data;
Stream m_stream;
mutable std::ostream m_os;
TestSpec m_testSpec;
};
} // end namespace Catch
// #included from: catch_clara.h
#define TWOBLUECUBES_CATCH_CLARA_H_INCLUDED
// Use Catch's value for console width (store Clara's off to the side, if present)
#ifdef CLARA_CONFIG_CONSOLE_WIDTH
#define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CLARA_CONFIG_CONSOLE_WIDTH
#undef CLARA_CONFIG_CONSOLE_WIDTH
#endif
#define CLARA_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH
// Declare Clara inside the Catch namespace
#define STITCH_CLARA_OPEN_NAMESPACE namespace Catch {
// #included from: ../external/clara.h
// Only use header guard if we are not using an outer namespace
#if !defined(TWOBLUECUBES_CLARA_H_INCLUDED) || defined(STITCH_CLARA_OPEN_NAMESPACE)
#ifndef STITCH_CLARA_OPEN_NAMESPACE
#define TWOBLUECUBES_CLARA_H_INCLUDED
#define STITCH_CLARA_OPEN_NAMESPACE
#define STITCH_CLARA_CLOSE_NAMESPACE
#else
#define STITCH_CLARA_CLOSE_NAMESPACE }
#endif
#define STITCH_TBC_TEXT_FORMAT_OPEN_NAMESPACE STITCH_CLARA_OPEN_NAMESPACE
// ----------- #included from tbc_text_format.h -----------
// Only use header guard if we are not using an outer namespace
#if !defined(TBC_TEXT_FORMAT_H_INCLUDED) || defined(STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE)
#ifndef STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE
#define TBC_TEXT_FORMAT_H_INCLUDED
#endif
#include <string>
#include <vector>
#include <sstream>
// Use optional outer namespace
#ifdef STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE
namespace STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE {
#endif
namespace Tbc {
#ifdef TBC_TEXT_FORMAT_CONSOLE_WIDTH
const unsigned int consoleWidth = TBC_TEXT_FORMAT_CONSOLE_WIDTH;
#else
const unsigned int consoleWidth = 80;
#endif
struct TextAttributes {
TextAttributes()
: initialIndent( std::string::npos ),
indent( 0 ),
width( consoleWidth-1 ),
tabChar( '\t' )
{}
TextAttributes& setInitialIndent( std::size_t _value ) { initialIndent = _value; return *this; }
TextAttributes& setIndent( std::size_t _value ) { indent = _value; return *this; }
TextAttributes& setWidth( std::size_t _value ) { width = _value; return *this; }
TextAttributes& setTabChar( char _value ) { tabChar = _value; return *this; }
std::size_t initialIndent; // indent of first line, or npos
std::size_t indent; // indent of subsequent lines, or all if initialIndent is npos
std::size_t width; // maximum width of text, including indent. Longer text will wrap
char tabChar; // If this char is seen the indent is changed to current pos
};
class Text {
public:
Text( std::string const& _str, TextAttributes const& _attr = TextAttributes() )
: attr( _attr )
{
std::string wrappableChars = " [({.,/|\\-";
std::size_t indent = _attr.initialIndent != std::string::npos
? _attr.initialIndent
: _attr.indent;
std::string remainder = _str;
while( !remainder.empty() ) {
if( lines.size() >= 1000 ) {
lines.push_back( "... message truncated due to excessive size" );
return;
}
std::size_t tabPos = std::string::npos;
std::size_t width = (std::min)( remainder.size(), _attr.width - indent );
std::size_t pos = remainder.find_first_of( '\n' );
if( pos <= width ) {
width = pos;
}
pos = remainder.find_last_of( _attr.tabChar, width );
if( pos != std::string::npos ) {
tabPos = pos;
if( remainder[width] == '\n' )
width--;
remainder = remainder.substr( 0, tabPos ) + remainder.substr( tabPos+1 );
}
if( width == remainder.size() ) {
spliceLine( indent, remainder, width );
}
else if( remainder[width] == '\n' ) {
spliceLine( indent, remainder, width );
if( width <= 1 || remainder.size() != 1 )
remainder = remainder.substr( 1 );
indent = _attr.indent;
}
else {
pos = remainder.find_last_of( wrappableChars, width );
if( pos != std::string::npos && pos > 0 ) {
spliceLine( indent, remainder, pos );
if( remainder[0] == ' ' )
remainder = remainder.substr( 1 );
}
else {
spliceLine( indent, remainder, width-1 );
lines.back() += "-";
}
if( lines.size() == 1 )
indent = _attr.indent;
if( tabPos != std::string::npos )
indent += tabPos;
}
}
}
void spliceLine( std::size_t _indent, std::string& _remainder, std::size_t _pos ) {
lines.push_back( std::string( _indent, ' ' ) + _remainder.substr( 0, _pos ) );
_remainder = _remainder.substr( _pos );
}
typedef std::vector<std::string>::const_iterator const_iterator;
const_iterator begin() const { return lines.begin(); }
const_iterator end() const { return lines.end(); }
std::string const& last() const { return lines.back(); }
std::size_t size() const { return lines.size(); }
std::string const& operator[]( std::size_t _index ) const { return lines[_index]; }
std::string toString() const {
std::ostringstream oss;
oss << *this;
return oss.str();
}
inline friend std::ostream& operator << ( std::ostream& _stream, Text const& _text ) {
for( Text::const_iterator it = _text.begin(), itEnd = _text.end();
it != itEnd; ++it ) {
if( it != _text.begin() )
_stream << "\n";
_stream << *it;
}
return _stream;
}
private:
std::string str;
TextAttributes attr;
std::vector<std::string> lines;
};
} // end namespace Tbc
#ifdef STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE
} // end outer namespace
#endif
#endif // TBC_TEXT_FORMAT_H_INCLUDED
// ----------- end of #include from tbc_text_format.h -----------
// ........... back in /Users/philnash/Dev/OSS/Clara/srcs/clara.h
#undef STITCH_TBC_TEXT_FORMAT_OPEN_NAMESPACE
#include <map>
#include <algorithm>
#include <stdexcept>
#include <memory>
// Use optional outer namespace
#ifdef STITCH_CLARA_OPEN_NAMESPACE
STITCH_CLARA_OPEN_NAMESPACE
#endif
namespace Clara {
struct UnpositionalTag {};
extern UnpositionalTag _;
#ifdef CLARA_CONFIG_MAIN
UnpositionalTag _;
#endif
namespace Detail {
#ifdef CLARA_CONSOLE_WIDTH
const unsigned int consoleWidth = CLARA_CONFIG_CONSOLE_WIDTH;
#else
const unsigned int consoleWidth = 80;
#endif
using namespace Tbc;
inline bool startsWith( std::string const& str, std::string const& prefix ) {
return str.size() >= prefix.size() && str.substr( 0, prefix.size() ) == prefix;
}
template<typename T> struct RemoveConstRef{ typedef T type; };
template<typename T> struct RemoveConstRef<T&>{ typedef T type; };
template<typename T> struct RemoveConstRef<T const&>{ typedef T type; };
template<typename T> struct RemoveConstRef<T const>{ typedef T type; };
template<typename T> struct IsBool { static const bool value = false; };
template<> struct IsBool<bool> { static const bool value = true; };
template<typename T>
void convertInto( std::string const& _source, T& _dest ) {
std::stringstream ss;
ss << _source;
ss >> _dest;
if( ss.fail() )
throw std::runtime_error( "Unable to convert " + _source + " to destination type" );
}
inline void convertInto( std::string const& _source, std::string& _dest ) {
_dest = _source;
}
inline void convertInto( std::string const& _source, bool& _dest ) {
std::string sourceLC = _source;
std::transform( sourceLC.begin(), sourceLC.end(), sourceLC.begin(), ::tolower );
if( sourceLC == "y" || sourceLC == "1" || sourceLC == "true" || sourceLC == "yes" || sourceLC == "on" )
_dest = true;
else if( sourceLC == "n" || sourceLC == "0" || sourceLC == "false" || sourceLC == "no" || sourceLC == "off" )
_dest = false;
else
throw std::runtime_error( "Expected a boolean value but did not recognise:\n '" + _source + "'" );
}
inline void convertInto( bool _source, bool& _dest ) {
_dest = _source;
}
template<typename T>
inline void convertInto( bool, T& ) {
throw std::runtime_error( "Invalid conversion" );
}
template<typename ConfigT>
struct IArgFunction {
virtual ~IArgFunction() {}
# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS
IArgFunction() = default;
IArgFunction( IArgFunction const& ) = default;
# endif
virtual void set( ConfigT& config, std::string const& value ) const = 0;
virtual void setFlag( ConfigT& config ) const = 0;
virtual bool takesArg() const = 0;
virtual IArgFunction* clone() const = 0;
};
template<typename ConfigT>
class BoundArgFunction {
public:
BoundArgFunction() : functionObj( NULL ) {}
BoundArgFunction( IArgFunction<ConfigT>* _functionObj ) : functionObj( _functionObj ) {}
BoundArgFunction( BoundArgFunction const& other ) : functionObj( other.functionObj ? other.functionObj->clone() : NULL ) {}
BoundArgFunction& operator = ( BoundArgFunction const& other ) {
IArgFunction<ConfigT>* newFunctionObj = other.functionObj ? other.functionObj->clone() : NULL;
delete functionObj;
functionObj = newFunctionObj;
return *this;
}
~BoundArgFunction() { delete functionObj; }
void set( ConfigT& config, std::string const& value ) const {
functionObj->set( config, value );
}
void setFlag( ConfigT& config ) const {
functionObj->setFlag( config );
}
bool takesArg() const { return functionObj->takesArg(); }
bool isSet() const {
return functionObj != NULL;
}
private:
IArgFunction<ConfigT>* functionObj;
};
template<typename C>
struct NullBinder : IArgFunction<C>{
virtual void set( C&, std::string const& ) const {}
virtual void setFlag( C& ) const {}
virtual bool takesArg() const { return true; }
virtual IArgFunction<C>* clone() const { return new NullBinder( *this ); }
};
template<typename C, typename M>
struct BoundDataMember : IArgFunction<C>{
BoundDataMember( M C::* _member ) : member( _member ) {}
virtual void set( C& p, std::string const& stringValue ) const {
convertInto( stringValue, p.*member );
}
virtual void setFlag( C& p ) const {
convertInto( true, p.*member );
}
virtual bool takesArg() const { return !IsBool<M>::value; }
virtual IArgFunction<C>* clone() const { return new BoundDataMember( *this ); }
M C::* member;
};
template<typename C, typename M>
struct BoundUnaryMethod : IArgFunction<C>{
BoundUnaryMethod( void (C::*_member)( M ) ) : member( _member ) {}
virtual void set( C& p, std::string const& stringValue ) const {
typename RemoveConstRef<M>::type value;
convertInto( stringValue, value );
(p.*member)( value );
}
virtual void setFlag( C& p ) const {
typename RemoveConstRef<M>::type value;
convertInto( true, value );
(p.*member)( value );
}
virtual bool takesArg() const { return !IsBool<M>::value; }
virtual IArgFunction<C>* clone() const { return new BoundUnaryMethod( *this ); }
void (C::*member)( M );
};
template<typename C>
struct BoundNullaryMethod : IArgFunction<C>{
BoundNullaryMethod( void (C::*_member)() ) : member( _member ) {}
virtual void set( C& p, std::string const& stringValue ) const {
bool value;
convertInto( stringValue, value );
if( value )
(p.*member)();
}
virtual void setFlag( C& p ) const {
(p.*member)();
}
virtual bool takesArg() const { return false; }
virtual IArgFunction<C>* clone() const { return new BoundNullaryMethod( *this ); }
void (C::*member)();
};
template<typename C>
struct BoundUnaryFunction : IArgFunction<C>{
BoundUnaryFunction( void (*_function)( C& ) ) : function( _function ) {}
virtual void set( C& obj, std::string const& stringValue ) const {
bool value;
convertInto( stringValue, value );
if( value )
function( obj );
}
virtual void setFlag( C& p ) const {
function( p );
}
virtual bool takesArg() const { return false; }
virtual IArgFunction<C>* clone() const { return new BoundUnaryFunction( *this ); }
void (*function)( C& );
};
template<typename C, typename T>
struct BoundBinaryFunction : IArgFunction<C>{
BoundBinaryFunction( void (*_function)( C&, T ) ) : function( _function ) {}
virtual void set( C& obj, std::string const& stringValue ) const {
typename RemoveConstRef<T>::type value;
convertInto( stringValue, value );
function( obj, value );
}
virtual void setFlag( C& obj ) const {
typename RemoveConstRef<T>::type value;
convertInto( true, value );
function( obj, value );
}
virtual bool takesArg() const { return !IsBool<T>::value; }
virtual IArgFunction<C>* clone() const { return new BoundBinaryFunction( *this ); }
void (*function)( C&, T );
};
} // namespace Detail
struct Parser {
Parser() : separators( " \t=:" ) {}
struct Token {
enum Type { Positional, ShortOpt, LongOpt };
Token( Type _type, std::string const& _data ) : type( _type ), data( _data ) {}
Type type;
std::string data;
};
void parseIntoTokens( int argc, char const * const * argv, std::vector<Parser::Token>& tokens ) const {
const std::string doubleDash = "--";
for( int i = 1; i < argc && argv[i] != doubleDash; ++i )
parseIntoTokens( argv[i] , tokens);
}
void parseIntoTokens( std::string arg, std::vector<Parser::Token>& tokens ) const {
while( !arg.empty() ) {
Parser::Token token( Parser::Token::Positional, arg );
arg = "";
if( token.data[0] == '-' ) {
if( token.data.size() > 1 && token.data[1] == '-' ) {
token = Parser::Token( Parser::Token::LongOpt, token.data.substr( 2 ) );
}
else {
token = Parser::Token( Parser::Token::ShortOpt, token.data.substr( 1 ) );
if( token.data.size() > 1 && separators.find( token.data[1] ) == std::string::npos ) {
arg = "-" + token.data.substr( 1 );
token.data = token.data.substr( 0, 1 );
}
}
}
if( token.type != Parser::Token::Positional ) {
std::size_t pos = token.data.find_first_of( separators );
if( pos != std::string::npos ) {
arg = token.data.substr( pos+1 );
token.data = token.data.substr( 0, pos );
}
}
tokens.push_back( token );
}
}
std::string separators;
};
template<typename ConfigT>
struct CommonArgProperties {
CommonArgProperties() {}
CommonArgProperties( Detail::BoundArgFunction<ConfigT> const& _boundField ) : boundField( _boundField ) {}
Detail::BoundArgFunction<ConfigT> boundField;
std::string description;
std::string detail;
std::string placeholder; // Only value if boundField takes an arg
bool takesArg() const {
return !placeholder.empty();
}
void validate() const {
if( !boundField.isSet() )
throw std::logic_error( "option not bound" );
}
};
struct OptionArgProperties {
std::vector<std::string> shortNames;
std::string longName;
bool hasShortName( std::string const& shortName ) const {
return std::find( shortNames.begin(), shortNames.end(), shortName ) != shortNames.end();
}
bool hasLongName( std::string const& _longName ) const {
return _longName == longName;
}
};
struct PositionalArgProperties {
PositionalArgProperties() : position( -1 ) {}
int position; // -1 means non-positional (floating)
bool isFixedPositional() const {
return position != -1;
}
};
template<typename ConfigT>
class CommandLine {
struct Arg : CommonArgProperties<ConfigT>, OptionArgProperties, PositionalArgProperties {
Arg() {}
Arg( Detail::BoundArgFunction<ConfigT> const& _boundField ) : CommonArgProperties<ConfigT>( _boundField ) {}
using CommonArgProperties<ConfigT>::placeholder; // !TBD
std::string dbgName() const {
if( !longName.empty() )
return "--" + longName;
if( !shortNames.empty() )
return "-" + shortNames[0];
return "positional args";
}
std::string commands() const {
std::ostringstream oss;
bool first = true;
std::vector<std::string>::const_iterator it = shortNames.begin(), itEnd = shortNames.end();
for(; it != itEnd; ++it ) {
if( first )
first = false;
else
oss << ", ";
oss << "-" << *it;
}
if( !longName.empty() ) {
if( !first )
oss << ", ";
oss << "--" << longName;
}
if( !placeholder.empty() )
oss << " <" << placeholder << ">";
return oss.str();
}
};
// NOTE: std::auto_ptr is deprecated in c++11/c++0x
#if defined(__cplusplus) && __cplusplus > 199711L
typedef std::unique_ptr<Arg> ArgAutoPtr;
#else
typedef std::auto_ptr<Arg> ArgAutoPtr;
#endif
friend void addOptName( Arg& arg, std::string const& optName )
{
if( optName.empty() )
return;
if( Detail::startsWith( optName, "--" ) ) {
if( !arg.longName.empty() )
throw std::logic_error( "Only one long opt may be specified. '"
+ arg.longName
+ "' already specified, now attempting to add '"
+ optName + "'" );
arg.longName = optName.substr( 2 );
}
else if( Detail::startsWith( optName, "-" ) )
arg.shortNames.push_back( optName.substr( 1 ) );
else
throw std::logic_error( "option must begin with - or --. Option was: '" + optName + "'" );
}
friend void setPositionalArg( Arg& arg, int position )
{
arg.position = position;
}
class ArgBuilder {
public:
ArgBuilder( Arg* arg ) : m_arg( arg ) {}
// Bind a non-boolean data member (requires placeholder string)
template<typename C, typename M>
void bind( M C::* field, std::string const& placeholder ) {
m_arg->boundField = new Detail::BoundDataMember<C,M>( field );
m_arg->placeholder = placeholder;
}
// Bind a boolean data member (no placeholder required)
template<typename C>
void bind( bool C::* field ) {
m_arg->boundField = new Detail::BoundDataMember<C,bool>( field );
}
// Bind a method taking a single, non-boolean argument (requires a placeholder string)
template<typename C, typename M>
void bind( void (C::* unaryMethod)( M ), std::string const& placeholder ) {
m_arg->boundField = new Detail::BoundUnaryMethod<C,M>( unaryMethod );
m_arg->placeholder = placeholder;
}
// Bind a method taking a single, boolean argument (no placeholder string required)
template<typename C>
void bind( void (C::* unaryMethod)( bool ) ) {
m_arg->boundField = new Detail::BoundUnaryMethod<C,bool>( unaryMethod );
}
// Bind a method that takes no arguments (will be called if opt is present)
template<typename C>
void bind( void (C::* nullaryMethod)() ) {
m_arg->boundField = new Detail::BoundNullaryMethod<C>( nullaryMethod );
}
// Bind a free function taking a single argument - the object to operate on (no placeholder string required)
template<typename C>
void bind( void (* unaryFunction)( C& ) ) {
m_arg->boundField = new Detail::BoundUnaryFunction<C>( unaryFunction );
}
// Bind a free function taking a single argument - the object to operate on (requires a placeholder string)
template<typename C, typename T>
void bind( void (* binaryFunction)( C&, T ), std::string const& placeholder ) {
m_arg->boundField = new Detail::BoundBinaryFunction<C, T>( binaryFunction );
m_arg->placeholder = placeholder;
}
ArgBuilder& describe( std::string const& description ) {
m_arg->description = description;
return *this;
}
ArgBuilder& detail( std::string const& detail ) {
m_arg->detail = detail;
return *this;
}
protected:
Arg* m_arg;
};
class OptBuilder : public ArgBuilder {
public:
OptBuilder( Arg* arg ) : ArgBuilder( arg ) {}
OptBuilder( OptBuilder& other ) : ArgBuilder( other ) {}
OptBuilder& operator[]( std::string const& optName ) {
addOptName( *ArgBuilder::m_arg, optName );
return *this;
}
};
public:
CommandLine()
: m_boundProcessName( new Detail::NullBinder<ConfigT>() ),
m_highestSpecifiedArgPosition( 0 ),
m_throwOnUnrecognisedTokens( false )
{}
CommandLine( CommandLine const& other )
: m_boundProcessName( other.m_boundProcessName ),
m_options ( other.m_options ),
m_positionalArgs( other.m_positionalArgs ),
m_highestSpecifiedArgPosition( other.m_highestSpecifiedArgPosition ),
m_throwOnUnrecognisedTokens( other.m_throwOnUnrecognisedTokens )
{
if( other.m_floatingArg.get() )
m_floatingArg.reset( new Arg( *other.m_floatingArg ) );
}
CommandLine& setThrowOnUnrecognisedTokens( bool shouldThrow = true ) {
m_throwOnUnrecognisedTokens = shouldThrow;
return *this;
}
OptBuilder operator[]( std::string const& optName ) {
m_options.push_back( Arg() );
addOptName( m_options.back(), optName );
OptBuilder builder( &m_options.back() );
return builder;
}
ArgBuilder operator[]( int position ) {
m_positionalArgs.insert( std::make_pair( position, Arg() ) );
if( position > m_highestSpecifiedArgPosition )
m_highestSpecifiedArgPosition = position;
setPositionalArg( m_positionalArgs[position], position );
ArgBuilder builder( &m_positionalArgs[position] );
return builder;
}
// Invoke this with the _ instance
ArgBuilder operator[]( UnpositionalTag ) {
if( m_floatingArg.get() )
throw std::logic_error( "Only one unpositional argument can be added" );
m_floatingArg.reset( new Arg() );
ArgBuilder builder( m_floatingArg.get() );
return builder;
}
template<typename C, typename M>
void bindProcessName( M C::* field ) {
m_boundProcessName = new Detail::BoundDataMember<C,M>( field );
}
template<typename C, typename M>
void bindProcessName( void (C::*_unaryMethod)( M ) ) {
m_boundProcessName = new Detail::BoundUnaryMethod<C,M>( _unaryMethod );
}
void optUsage( std::ostream& os, std::size_t indent = 0, std::size_t width = Detail::consoleWidth ) const {
typename std::vector<Arg>::const_iterator itBegin = m_options.begin(), itEnd = m_options.end(), it;
std::size_t maxWidth = 0;
for( it = itBegin; it != itEnd; ++it )
maxWidth = (std::max)( maxWidth, it->commands().size() );
for( it = itBegin; it != itEnd; ++it ) {
Detail::Text usage( it->commands(), Detail::TextAttributes()
.setWidth( maxWidth+indent )
.setIndent( indent ) );
Detail::Text desc( it->description, Detail::TextAttributes()
.setWidth( width - maxWidth - 3 ) );
for( std::size_t i = 0; i < (std::max)( usage.size(), desc.size() ); ++i ) {
std::string usageCol = i < usage.size() ? usage[i] : "";
os << usageCol;
if( i < desc.size() && !desc[i].empty() )
os << std::string( indent + 2 + maxWidth - usageCol.size(), ' ' )
<< desc[i];
os << "\n";
}
}
}
std::string optUsage() const {
std::ostringstream oss;
optUsage( oss );
return oss.str();
}
void argSynopsis( std::ostream& os ) const {
for( int i = 1; i <= m_highestSpecifiedArgPosition; ++i ) {
if( i > 1 )
os << " ";
typename std::map<int, Arg>::const_iterator it = m_positionalArgs.find( i );
if( it != m_positionalArgs.end() )
os << "<" << it->second.placeholder << ">";
else if( m_floatingArg.get() )
os << "<" << m_floatingArg->placeholder << ">";
else
throw std::logic_error( "non consecutive positional arguments with no floating args" );
}
// !TBD No indication of mandatory args
if( m_floatingArg.get() ) {
if( m_highestSpecifiedArgPosition > 1 )
os << " ";
os << "[<" << m_floatingArg->placeholder << "> ...]";
}
}
std::string argSynopsis() const {
std::ostringstream oss;
argSynopsis( oss );
return oss.str();
}
void usage( std::ostream& os, std::string const& procName ) const {
validate();
os << "usage:\n " << procName << " ";
argSynopsis( os );
if( !m_options.empty() ) {
os << " [options]\n\nwhere options are: \n";
optUsage( os, 2 );
}
os << "\n";
}
std::string usage( std::string const& procName ) const {
std::ostringstream oss;
usage( oss, procName );
return oss.str();
}
ConfigT parse( int argc, char const * const * argv ) const {
ConfigT config;
parseInto( argc, argv, config );
return config;
}
std::vector<Parser::Token> parseInto( int argc, char const * const * argv, ConfigT& config ) const {
std::string processName = argv[0];
std::size_t lastSlash = processName.find_last_of( "/\\" );
if( lastSlash != std::string::npos )
processName = processName.substr( lastSlash+1 );
m_boundProcessName.set( config, processName );
std::vector<Parser::Token> tokens;
Parser parser;
parser.parseIntoTokens( argc, argv, tokens );
return populate( tokens, config );
}
std::vector<Parser::Token> populate( std::vector<Parser::Token> const& tokens, ConfigT& config ) const {
validate();
std::vector<Parser::Token> unusedTokens = populateOptions( tokens, config );
unusedTokens = populateFixedArgs( unusedTokens, config );
unusedTokens = populateFloatingArgs( unusedTokens, config );
return unusedTokens;
}
std::vector<Parser::Token> populateOptions( std::vector<Parser::Token> const& tokens, ConfigT& config ) const {
std::vector<Parser::Token> unusedTokens;
std::vector<std::string> errors;
for( std::size_t i = 0; i < tokens.size(); ++i ) {
Parser::Token const& token = tokens[i];
typename std::vector<Arg>::const_iterator it = m_options.begin(), itEnd = m_options.end();
for(; it != itEnd; ++it ) {
Arg const& arg = *it;
try {
if( ( token.type == Parser::Token::ShortOpt && arg.hasShortName( token.data ) ) ||
( token.type == Parser::Token::LongOpt && arg.hasLongName( token.data ) ) ) {
if( arg.takesArg() ) {
if( i == tokens.size()-1 || tokens[i+1].type != Parser::Token::Positional )
errors.push_back( "Expected argument to option: " + token.data );
else
arg.boundField.set( config, tokens[++i].data );
}
else {
arg.boundField.setFlag( config );
}
break;
}
}
catch( std::exception& ex ) {
errors.push_back( std::string( ex.what() ) + "\n- while parsing: (" + arg.commands() + ")" );
}
}
if( it == itEnd ) {
if( token.type == Parser::Token::Positional || !m_throwOnUnrecognisedTokens )
unusedTokens.push_back( token );
else if( errors.empty() && m_throwOnUnrecognisedTokens )
errors.push_back( "unrecognised option: " + token.data );
}
}
if( !errors.empty() ) {
std::ostringstream oss;
for( std::vector<std::string>::const_iterator it = errors.begin(), itEnd = errors.end();
it != itEnd;
++it ) {
if( it != errors.begin() )
oss << "\n";
oss << *it;
}
throw std::runtime_error( oss.str() );
}
return unusedTokens;
}
std::vector<Parser::Token> populateFixedArgs( std::vector<Parser::Token> const& tokens, ConfigT& config ) const {
std::vector<Parser::Token> unusedTokens;
int position = 1;
for( std::size_t i = 0; i < tokens.size(); ++i ) {
Parser::Token const& token = tokens[i];
typename std::map<int, Arg>::const_iterator it = m_positionalArgs.find( position );
if( it != m_positionalArgs.end() )
it->second.boundField.set( config, token.data );
else
unusedTokens.push_back( token );
if( token.type == Parser::Token::Positional )
position++;
}
return unusedTokens;
}
std::vector<Parser::Token> populateFloatingArgs( std::vector<Parser::Token> const& tokens, ConfigT& config ) const {
if( !m_floatingArg.get() )
return tokens;
std::vector<Parser::Token> unusedTokens;
for( std::size_t i = 0; i < tokens.size(); ++i ) {
Parser::Token const& token = tokens[i];
if( token.type == Parser::Token::Positional )
m_floatingArg->boundField.set( config, token.data );
else
unusedTokens.push_back( token );
}
return unusedTokens;
}
void validate() const
{
if( m_options.empty() && m_positionalArgs.empty() && !m_floatingArg.get() )
throw std::logic_error( "No options or arguments specified" );
for( typename std::vector<Arg>::const_iterator it = m_options.begin(),
itEnd = m_options.end();
it != itEnd; ++it )
it->validate();
}
private:
Detail::BoundArgFunction<ConfigT> m_boundProcessName;
std::vector<Arg> m_options;
std::map<int, Arg> m_positionalArgs;
ArgAutoPtr m_floatingArg;
int m_highestSpecifiedArgPosition;
bool m_throwOnUnrecognisedTokens;
};
} // end namespace Clara
STITCH_CLARA_CLOSE_NAMESPACE
#undef STITCH_CLARA_OPEN_NAMESPACE
#undef STITCH_CLARA_CLOSE_NAMESPACE
#endif // TWOBLUECUBES_CLARA_H_INCLUDED
#undef STITCH_CLARA_OPEN_NAMESPACE
// Restore Clara's value for console width, if present
#ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
#define CLARA_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
#undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
#endif
#include <fstream>
namespace Catch {
inline void abortAfterFirst( ConfigData& config ) { config.abortAfter = 1; }
inline void abortAfterX( ConfigData& config, int x ) {
if( x < 1 )
throw std::runtime_error( "Value after -x or --abortAfter must be greater than zero" );
config.abortAfter = x;
}
inline void addTestOrTags( ConfigData& config, std::string const& _testSpec ) { config.testsOrTags.push_back( _testSpec ); }
inline void addWarning( ConfigData& config, std::string const& _warning ) {
if( _warning == "NoAssertions" )
config.warnings = static_cast<WarnAbout::What>( config.warnings | WarnAbout::NoAssertions );
else
throw std::runtime_error( "Unrecognised warning: '" + _warning + "'" );
}
inline void setOrder( ConfigData& config, std::string const& order ) {
if( startsWith( "declared", order ) )
config.runOrder = RunTests::InDeclarationOrder;
else if( startsWith( "lexical", order ) )
config.runOrder = RunTests::InLexicographicalOrder;
else if( startsWith( "random", order ) )
config.runOrder = RunTests::InRandomOrder;
else
throw std::runtime_error( "Unrecognised ordering: '" + order + "'" );
}
inline void setRngSeed( ConfigData& config, std::string const& seed ) {
if( seed == "time" ) {
config.rngSeed = static_cast<unsigned int>( std::time(0) );
}
else {
std::stringstream ss;
ss << seed;
ss >> config.rngSeed;
if( ss.fail() )
throw std::runtime_error( "Argment to --rng-seed should be the word 'time' or a number" );
}
}
inline void setVerbosity( ConfigData& config, int level ) {
// !TBD: accept strings?
config.verbosity = static_cast<Verbosity::Level>( level );
}
inline void setShowDurations( ConfigData& config, bool _showDurations ) {
config.showDurations = _showDurations
? ShowDurations::Always
: ShowDurations::Never;
}
inline void loadTestNamesFromFile( ConfigData& config, std::string const& _filename ) {
std::ifstream f( _filename.c_str() );
if( !f.is_open() )
throw std::domain_error( "Unable to load input file: " + _filename );
std::string line;
while( std::getline( f, line ) ) {
line = trim(line);
if( !line.empty() && !startsWith( line, "#" ) )
addTestOrTags( config, "\"" + line + "\"," );
}
}
inline Clara::CommandLine<ConfigData> makeCommandLineParser() {
using namespace Clara;
CommandLine<ConfigData> cli;
cli.bindProcessName( &ConfigData::processName );
cli["-?"]["-h"]["--help"]
.describe( "display usage information" )
.bind( &ConfigData::showHelp );
cli["-l"]["--list-tests"]
.describe( "list all/matching test cases" )
.bind( &ConfigData::listTests );
cli["-t"]["--list-tags"]
.describe( "list all/matching tags" )
.bind( &ConfigData::listTags );
cli["-s"]["--success"]
.describe( "include successful tests in output" )
.bind( &ConfigData::showSuccessfulTests );
cli["-b"]["--break"]
.describe( "break into debugger on failure" )
.bind( &ConfigData::shouldDebugBreak );
cli["-e"]["--nothrow"]
.describe( "skip exception tests" )
.bind( &ConfigData::noThrow );
cli["-i"]["--invisibles"]
.describe( "show invisibles (tabs, newlines)" )
.bind( &ConfigData::showInvisibles );
cli["-o"]["--out"]
.describe( "output filename" )
.bind( &ConfigData::outputFilename, "filename" );
cli["-r"]["--reporter"]
// .placeholder( "name[:filename]" )
.describe( "reporter to use (defaults to console)" )
.bind( &ConfigData::reporterName, "name" );
cli["-n"]["--name"]
.describe( "suite name" )
.bind( &ConfigData::name, "name" );
cli["-a"]["--abort"]
.describe( "abort at first failure" )
.bind( &abortAfterFirst );
cli["-x"]["--abortx"]
.describe( "abort after x failures" )
.bind( &abortAfterX, "no. failures" );
cli["-w"]["--warn"]
.describe( "enable warnings" )
.bind( &addWarning, "warning name" );
// - needs updating if reinstated
// cli.into( &setVerbosity )
// .describe( "level of verbosity (0=no output)" )
// .shortOpt( "v")
// .longOpt( "verbosity" )
// .placeholder( "level" );
cli[_]
.describe( "which test or tests to use" )
.bind( &addTestOrTags, "test name, pattern or tags" );
cli["-d"]["--durations"]
.describe( "show test durations" )
.bind( &setShowDurations, "yes/no" );
cli["-f"]["--input-file"]
.describe( "load test names to run from a file" )
.bind( &loadTestNamesFromFile, "filename" );
// Less common commands which don't have a short form
cli["--list-test-names-only"]
.describe( "list all/matching test cases names only" )
.bind( &ConfigData::listTestNamesOnly );
cli["--list-reporters"]
.describe( "list all reporters" )
.bind( &ConfigData::listReporters );
cli["--order"]
.describe( "test case order (defaults to decl)" )
.bind( &setOrder, "decl|lex|rand" );
cli["--rng-seed"]
.describe( "set a specific seed for random numbers" )
.bind( &setRngSeed, "'time'|number" );
cli["--force-colour"]
.describe( "force colourised output" )
.bind( &ConfigData::forceColour );
return cli;
}
} // end namespace Catch
// #included from: internal/catch_list.hpp
#define TWOBLUECUBES_CATCH_LIST_HPP_INCLUDED
// #included from: catch_text.h
#define TWOBLUECUBES_CATCH_TEXT_H_INCLUDED
#define TBC_TEXT_FORMAT_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH
#define CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE Catch
// #included from: ../external/tbc_text_format.h
// Only use header guard if we are not using an outer namespace
#ifndef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE
# ifdef TWOBLUECUBES_TEXT_FORMAT_H_INCLUDED
# ifndef TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED
# define TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED
# endif
# else
# define TWOBLUECUBES_TEXT_FORMAT_H_INCLUDED
# endif
#endif
#ifndef TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED
#include <string>
#include <vector>
#include <sstream>
// Use optional outer namespace
#ifdef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE
namespace CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE {
#endif
namespace Tbc {
#ifdef TBC_TEXT_FORMAT_CONSOLE_WIDTH
const unsigned int consoleWidth = TBC_TEXT_FORMAT_CONSOLE_WIDTH;
#else
const unsigned int consoleWidth = 80;
#endif
struct TextAttributes {
TextAttributes()
: initialIndent( std::string::npos ),
indent( 0 ),
width( consoleWidth-1 ),
tabChar( '\t' )
{}
TextAttributes& setInitialIndent( std::size_t _value ) { initialIndent = _value; return *this; }
TextAttributes& setIndent( std::size_t _value ) { indent = _value; return *this; }
TextAttributes& setWidth( std::size_t _value ) { width = _value; return *this; }
TextAttributes& setTabChar( char _value ) { tabChar = _value; return *this; }
std::size_t initialIndent; // indent of first line, or npos
std::size_t indent; // indent of subsequent lines, or all if initialIndent is npos
std::size_t width; // maximum width of text, including indent. Longer text will wrap
char tabChar; // If this char is seen the indent is changed to current pos
};
class Text {
public:
Text( std::string const& _str, TextAttributes const& _attr = TextAttributes() )
: attr( _attr )
{
std::string wrappableChars = " [({.,/|\\-";
std::size_t indent = _attr.initialIndent != std::string::npos
? _attr.initialIndent
: _attr.indent;
std::string remainder = _str;
while( !remainder.empty() ) {
if( lines.size() >= 1000 ) {
lines.push_back( "... message truncated due to excessive size" );
return;
}
std::size_t tabPos = std::string::npos;
std::size_t width = (std::min)( remainder.size(), _attr.width - indent );
std::size_t pos = remainder.find_first_of( '\n' );
if( pos <= width ) {
width = pos;
}
pos = remainder.find_last_of( _attr.tabChar, width );
if( pos != std::string::npos ) {
tabPos = pos;
if( remainder[width] == '\n' )
width--;
remainder = remainder.substr( 0, tabPos ) + remainder.substr( tabPos+1 );
}
if( width == remainder.size() ) {
spliceLine( indent, remainder, width );
}
else if( remainder[width] == '\n' ) {
spliceLine( indent, remainder, width );
if( width <= 1 || remainder.size() != 1 )
remainder = remainder.substr( 1 );
indent = _attr.indent;
}
else {
pos = remainder.find_last_of( wrappableChars, width );
if( pos != std::string::npos && pos > 0 ) {
spliceLine( indent, remainder, pos );
if( remainder[0] == ' ' )
remainder = remainder.substr( 1 );
}
else {
spliceLine( indent, remainder, width-1 );
lines.back() += "-";
}
if( lines.size() == 1 )
indent = _attr.indent;
if( tabPos != std::string::npos )
indent += tabPos;
}
}
}
void spliceLine( std::size_t _indent, std::string& _remainder, std::size_t _pos ) {
lines.push_back( std::string( _indent, ' ' ) + _remainder.substr( 0, _pos ) );
_remainder = _remainder.substr( _pos );
}
typedef std::vector<std::string>::const_iterator const_iterator;
const_iterator begin() const { return lines.begin(); }
const_iterator end() const { return lines.end(); }
std::string const& last() const { return lines.back(); }
std::size_t size() const { return lines.size(); }
std::string const& operator[]( std::size_t _index ) const { return lines[_index]; }
std::string toString() const {
std::ostringstream oss;
oss << *this;
return oss.str();
}
inline friend std::ostream& operator << ( std::ostream& _stream, Text const& _text ) {
for( Text::const_iterator it = _text.begin(), itEnd = _text.end();
it != itEnd; ++it ) {
if( it != _text.begin() )
_stream << "\n";
_stream << *it;
}
return _stream;
}
private:
std::string str;
TextAttributes attr;
std::vector<std::string> lines;
};
} // end namespace Tbc
#ifdef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE
} // end outer namespace
#endif
#endif // TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED
#undef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE
namespace Catch {
using Tbc::Text;
using Tbc::TextAttributes;
}
// #included from: catch_console_colour.hpp
#define TWOBLUECUBES_CATCH_CONSOLE_COLOUR_HPP_INCLUDED
namespace Catch {
struct Colour {
enum Code {
None = 0,
White,
Red,
Green,
Blue,
Cyan,
Yellow,
Grey,
Bright = 0x10,
BrightRed = Bright | Red,
BrightGreen = Bright | Green,
LightGrey = Bright | Grey,
BrightWhite = Bright | White,
// By intention
FileName = LightGrey,
Warning = Yellow,
ResultError = BrightRed,
ResultSuccess = BrightGreen,
ResultExpectedFailure = Warning,
Error = BrightRed,
Success = Green,
OriginalExpression = Cyan,
ReconstructedExpression = Yellow,
SecondaryText = LightGrey,
Headers = White
};
// Use constructed object for RAII guard
Colour( Code _colourCode );
Colour( Colour const& other );
~Colour();
// Use static method for one-shot changes
static void use( Code _colourCode );
private:
bool m_moved;
};
inline std::ostream& operator << ( std::ostream& os, Colour const& ) { return os; }
} // end namespace Catch
// #included from: catch_interfaces_reporter.h
#define TWOBLUECUBES_CATCH_INTERFACES_REPORTER_H_INCLUDED
#include <string>
#include <ostream>
#include <map>
#include <assert.h>
namespace Catch
{
struct ReporterConfig {
explicit ReporterConfig( Ptr<IConfig> const& _fullConfig )
: m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
ReporterConfig( Ptr<IConfig> const& _fullConfig, std::ostream& _stream )
: m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
std::ostream& stream() const { return *m_stream; }
Ptr<IConfig> fullConfig() const { return m_fullConfig; }
private:
std::ostream* m_stream;
Ptr<IConfig> m_fullConfig;
};
struct ReporterPreferences {
ReporterPreferences()
: shouldRedirectStdOut( false )
{}
bool shouldRedirectStdOut;
};
template<typename T>
struct LazyStat : Option<T> {
LazyStat() : used( false ) {}
LazyStat& operator=( T const& _value ) {
Option<T>::operator=( _value );
used = false;
return *this;
}
void reset() {
Option<T>::reset();
used = false;
}
bool used;
};
struct TestRunInfo {
TestRunInfo( std::string const& _name ) : name( _name ) {}
std::string name;
};
struct GroupInfo {
GroupInfo( std::string const& _name,
std::size_t _groupIndex,
std::size_t _groupsCount )
: name( _name ),
groupIndex( _groupIndex ),
groupsCounts( _groupsCount )
{}
std::string name;
std::size_t groupIndex;
std::size_t groupsCounts;
};
struct AssertionStats {
AssertionStats( AssertionResult const& _assertionResult,
std::vector<MessageInfo> const& _infoMessages,
Totals const& _totals )
: assertionResult( _assertionResult ),
infoMessages( _infoMessages ),
totals( _totals )
{
if( assertionResult.hasMessage() ) {
// Copy message into messages list.
// !TBD This should have been done earlier, somewhere
MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
builder << assertionResult.getMessage();
builder.m_info.message = builder.m_stream.str();
infoMessages.push_back( builder.m_info );
}
}
virtual ~AssertionStats();
# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS
AssertionStats( AssertionStats const& ) = default;
AssertionStats( AssertionStats && ) = default;
AssertionStats& operator = ( AssertionStats const& ) = default;
AssertionStats& operator = ( AssertionStats && ) = default;
# endif
AssertionResult assertionResult;
std::vector<MessageInfo> infoMessages;
Totals totals;
};
struct SectionStats {
SectionStats( SectionInfo const& _sectionInfo,
Counts const& _assertions,
double _durationInSeconds,
bool _missingAssertions )
: sectionInfo( _sectionInfo ),
assertions( _assertions ),
durationInSeconds( _durationInSeconds ),
missingAssertions( _missingAssertions )
{}
virtual ~SectionStats();
# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS
SectionStats( SectionStats const& ) = default;
SectionStats( SectionStats && ) = default;
SectionStats& operator = ( SectionStats const& ) = default;
SectionStats& operator = ( SectionStats && ) = default;
# endif
SectionInfo sectionInfo;
Counts assertions;
double durationInSeconds;
bool missingAssertions;
};
struct TestCaseStats {
TestCaseStats( TestCaseInfo const& _testInfo,
Totals const& _totals,
std::string const& _stdOut,
std::string const& _stdErr,
bool _aborting )
: testInfo( _testInfo ),
totals( _totals ),
stdOut( _stdOut ),
stdErr( _stdErr ),
aborting( _aborting )
{}
virtual ~TestCaseStats();
# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS
TestCaseStats( TestCaseStats const& ) = default;
TestCaseStats( TestCaseStats && ) = default;
TestCaseStats& operator = ( TestCaseStats const& ) = default;
TestCaseStats& operator = ( TestCaseStats && ) = default;
# endif
TestCaseInfo testInfo;
Totals totals;
std::string stdOut;
std::string stdErr;
bool aborting;
};
struct TestGroupStats {
TestGroupStats( GroupInfo const& _groupInfo,
Totals const& _totals,
bool _aborting )
: groupInfo( _groupInfo ),
totals( _totals ),
aborting( _aborting )
{}
TestGroupStats( GroupInfo const& _groupInfo )
: groupInfo( _groupInfo ),
aborting( false )
{}
virtual ~TestGroupStats();
# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS
TestGroupStats( TestGroupStats const& ) = default;
TestGroupStats( TestGroupStats && ) = default;
TestGroupStats& operator = ( TestGroupStats const& ) = default;
TestGroupStats& operator = ( TestGroupStats && ) = default;
# endif
GroupInfo groupInfo;
Totals totals;
bool aborting;
};
struct TestRunStats {
TestRunStats( TestRunInfo const& _runInfo,
Totals const& _totals,
bool _aborting )
: runInfo( _runInfo ),
totals( _totals ),
aborting( _aborting )
{}
virtual ~TestRunStats();
# ifndef CATCH_CONFIG_CPP11_GENERATED_METHODS
TestRunStats( TestRunStats const& _other )
: runInfo( _other.runInfo ),
totals( _other.totals ),
aborting( _other.aborting )
{}
# else
TestRunStats( TestRunStats const& ) = default;
TestRunStats( TestRunStats && ) = default;
TestRunStats& operator = ( TestRunStats const& ) = default;
TestRunStats& operator = ( TestRunStats && ) = default;
# endif
TestRunInfo runInfo;
Totals totals;
bool aborting;
};
struct IStreamingReporter : IShared {
virtual ~IStreamingReporter();
// Implementing class must also provide the following static method:
// static std::string getDescription();
virtual ReporterPreferences getPreferences() const = 0;
virtual void noMatchingTestCases( std::string const& spec ) = 0;
virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0;
virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0;
virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0;
virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0;
virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0;
// The return value indicates if the messages buffer should be cleared:
virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0;
virtual void sectionEnded( SectionStats const& sectionStats ) = 0;
virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0;
virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0;
virtual void testRunEnded( TestRunStats const& testRunStats ) = 0;
virtual void skipTest( TestCaseInfo const& testInfo ) = 0;
};
struct IReporterFactory {
virtual ~IReporterFactory();
virtual IStreamingReporter* create( ReporterConfig const& config ) const = 0;
virtual std::string getDescription() const = 0;
};
struct IReporterRegistry {
typedef std::map<std::string, IReporterFactory*> FactoryMap;
virtual ~IReporterRegistry();
virtual IStreamingReporter* create( std::string const& name, Ptr<IConfig> const& config ) const = 0;
virtual FactoryMap const& getFactories() const = 0;
};
}
#include <limits>
#include <algorithm>
namespace Catch {
inline std::size_t listTests( Config const& config ) {
TestSpec testSpec = config.testSpec();
if( config.testSpec().hasFilters() )
Catch::cout() << "Matching test cases:\n";
else {
Catch::cout() << "All available test cases:\n";
testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec();
}
std::size_t matchedTests = 0;
TextAttributes nameAttr, tagsAttr;
nameAttr.setInitialIndent( 2 ).setIndent( 4 );
tagsAttr.setIndent( 6 );
std::vector<TestCase> matchedTestCases;
getRegistryHub().getTestCaseRegistry().getFilteredTests( testSpec, config, matchedTestCases );
for( std::vector<TestCase>::const_iterator it = matchedTestCases.begin(), itEnd = matchedTestCases.end();
it != itEnd;
++it ) {
matchedTests++;
TestCaseInfo const& testCaseInfo = it->getTestCaseInfo();
Colour::Code colour = testCaseInfo.isHidden()
? Colour::SecondaryText
: Colour::None;
Colour colourGuard( colour );
Catch::cout() << Text( testCaseInfo.name, nameAttr ) << std::endl;
if( !testCaseInfo.tags.empty() )
Catch::cout() << Text( testCaseInfo.tagsAsString, tagsAttr ) << std::endl;
}
if( !config.testSpec().hasFilters() )
Catch::cout() << pluralise( matchedTests, "test case" ) << "\n" << std::endl;
else
Catch::cout() << pluralise( matchedTests, "matching test case" ) << "\n" << std::endl;
return matchedTests;
}
inline std::size_t listTestsNamesOnly( Config const& config ) {
TestSpec testSpec = config.testSpec();
if( !config.testSpec().hasFilters() )
testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec();
std::size_t matchedTests = 0;
std::vector<TestCase> matchedTestCases;
getRegistryHub().getTestCaseRegistry().getFilteredTests( testSpec, config, matchedTestCases );
for( std::vector<TestCase>::const_iterator it = matchedTestCases.begin(), itEnd = matchedTestCases.end();
it != itEnd;
++it ) {
matchedTests++;
TestCaseInfo const& testCaseInfo = it->getTestCaseInfo();
Catch::cout() << testCaseInfo.name << std::endl;
}
return matchedTests;
}
struct TagInfo {
TagInfo() : count ( 0 ) {}
void add( std::string const& spelling ) {
++count;
spellings.insert( spelling );
}
std::string all() const {
std::string out;
for( std::set<std::string>::const_iterator it = spellings.begin(), itEnd = spellings.end();
it != itEnd;
++it )
out += "[" + *it + "]";
return out;
}
std::set<std::string> spellings;
std::size_t count;
};
inline std::size_t listTags( Config const& config ) {
TestSpec testSpec = config.testSpec();
if( config.testSpec().hasFilters() )
Catch::cout() << "Tags for matching test cases:\n";
else {
Catch::cout() << "All available tags:\n";
testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec();
}
std::map<std::string, TagInfo> tagCounts;
std::vector<TestCase> matchedTestCases;
getRegistryHub().getTestCaseRegistry().getFilteredTests( testSpec, config, matchedTestCases );
for( std::vector<TestCase>::const_iterator it = matchedTestCases.begin(), itEnd = matchedTestCases.end();
it != itEnd;
++it ) {
for( std::set<std::string>::const_iterator tagIt = it->getTestCaseInfo().tags.begin(),
tagItEnd = it->getTestCaseInfo().tags.end();
tagIt != tagItEnd;
++tagIt ) {
std::string tagName = *tagIt;
std::string lcaseTagName = toLower( tagName );
std::map<std::string, TagInfo>::iterator countIt = tagCounts.find( lcaseTagName );
if( countIt == tagCounts.end() )
countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
countIt->second.add( tagName );
}
}
for( std::map<std::string, TagInfo>::const_iterator countIt = tagCounts.begin(),
countItEnd = tagCounts.end();
countIt != countItEnd;
++countIt ) {
std::ostringstream oss;
oss << " " << std::setw(2) << countIt->second.count << " ";
Text wrapper( countIt->second.all(), TextAttributes()
.setInitialIndent( 0 )
.setIndent( oss.str().size() )
.setWidth( CATCH_CONFIG_CONSOLE_WIDTH-10 ) );
Catch::cout() << oss.str() << wrapper << "\n";
}
Catch::cout() << pluralise( tagCounts.size(), "tag" ) << "\n" << std::endl;
return tagCounts.size();
}
inline std::size_t listReporters( Config const& /*config*/ ) {
Catch::cout() << "Available reporters:\n";
IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
IReporterRegistry::FactoryMap::const_iterator itBegin = factories.begin(), itEnd = factories.end(), it;
std::size_t maxNameLen = 0;
for(it = itBegin; it != itEnd; ++it )
maxNameLen = (std::max)( maxNameLen, it->first.size() );
for(it = itBegin; it != itEnd; ++it ) {
Text wrapper( it->second->getDescription(), TextAttributes()
.setInitialIndent( 0 )
.setIndent( 7+maxNameLen )
.setWidth( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 ) );
Catch::cout() << " "
<< it->first
<< ":"
<< std::string( maxNameLen - it->first.size() + 2, ' ' )
<< wrapper << "\n";
}
Catch::cout() << std::endl;
return factories.size();
}
inline Option<std::size_t> list( Config const& config ) {
Option<std::size_t> listedCount;
if( config.listTests() )
listedCount = listedCount.valueOr(0) + listTests( config );
if( config.listTestNamesOnly() )
listedCount = listedCount.valueOr(0) + listTestsNamesOnly( config );
if( config.listTags() )
listedCount = listedCount.valueOr(0) + listTags( config );
if( config.listReporters() )
listedCount = listedCount.valueOr(0) + listReporters( config );
return listedCount;
}
} // end namespace Catch
// #included from: internal/catch_runner_impl.hpp
#define TWOBLUECUBES_CATCH_RUNNER_IMPL_HPP_INCLUDED
// #included from: catch_test_case_tracker.hpp
#define TWOBLUECUBES_CATCH_TEST_CASE_TRACKER_HPP_INCLUDED
#include <map>
#include <string>
#include <assert.h>
namespace Catch {
namespace SectionTracking {
class TrackedSection {
typedef std::map<std::string, TrackedSection> TrackedSections;
public:
enum RunState {
NotStarted,
Executing,
ExecutingChildren,
Completed
};
TrackedSection( std::string const& name, TrackedSection* parent )
: m_name( name ), m_runState( NotStarted ), m_parent( parent )
{}
RunState runState() const { return m_runState; }
TrackedSection* findChild( std::string const& childName );
TrackedSection* acquireChild( std::string const& childName );
void enter() {
if( m_runState == NotStarted )
m_runState = Executing;
}
void leave();
TrackedSection* getParent() {
return m_parent;
}
bool hasChildren() const {
return !m_children.empty();
}
private:
std::string m_name;
RunState m_runState;
TrackedSections m_children;
TrackedSection* m_parent;
};
inline TrackedSection* TrackedSection::findChild( std::string const& childName ) {
TrackedSections::iterator it = m_children.find( childName );
return it != m_children.end()
? &it->second
: NULL;
}
inline TrackedSection* TrackedSection::acquireChild( std::string const& childName ) {
if( TrackedSection* child = findChild( childName ) )
return child;
m_children.insert( std::make_pair( childName, TrackedSection( childName, this ) ) );
return findChild( childName );
}
inline void TrackedSection::leave() {
for( TrackedSections::const_iterator it = m_children.begin(), itEnd = m_children.end();
it != itEnd;
++it )
if( it->second.runState() != Completed ) {
m_runState = ExecutingChildren;
return;
}
m_runState = Completed;
}
class TestCaseTracker {
public:
TestCaseTracker( std::string const& testCaseName )
: m_testCase( testCaseName, NULL ),
m_currentSection( &m_testCase ),
m_completedASectionThisRun( false )
{}
bool enterSection( std::string const& name ) {
TrackedSection* child = m_currentSection->acquireChild( name );
if( m_completedASectionThisRun || child->runState() == TrackedSection::Completed )
return false;
m_currentSection = child;
m_currentSection->enter();
return true;
}
void leaveSection() {
m_currentSection->leave();
m_currentSection = m_currentSection->getParent();
assert( m_currentSection != NULL );
m_completedASectionThisRun = true;
}
bool currentSectionHasChildren() const {
return m_currentSection->hasChildren();
}
bool isCompleted() const {
return m_testCase.runState() == TrackedSection::Completed;
}
class Guard {
public:
Guard( TestCaseTracker& tracker ) : m_tracker( tracker ) {
m_tracker.enterTestCase();
}
~Guard() {
m_tracker.leaveTestCase();
}
private:
Guard( Guard const& );
void operator = ( Guard const& );
TestCaseTracker& m_tracker;
};
private:
void enterTestCase() {
m_currentSection = &m_testCase;
m_completedASectionThisRun = false;
m_testCase.enter();
}
void leaveTestCase() {
m_testCase.leave();
}
TrackedSection m_testCase;
TrackedSection* m_currentSection;
bool m_completedASectionThisRun;
};
} // namespace SectionTracking
using SectionTracking::TestCaseTracker;
} // namespace Catch
// #included from: catch_fatal_condition.hpp
#define TWOBLUECUBES_CATCH_FATAL_CONDITION_H_INCLUDED
namespace Catch {
// Report the error condition then exit the process
inline void fatal( std::string const& message, int exitCode ) {
IContext& context = Catch::getCurrentContext();
IResultCapture* resultCapture = context.getResultCapture();
resultCapture->handleFatalErrorCondition( message );
if( Catch::alwaysTrue() ) // avoids "no return" warnings
exit( exitCode );
}
} // namespace Catch
#if defined ( CATCH_PLATFORM_WINDOWS ) /////////////////////////////////////////
namespace Catch {
struct FatalConditionHandler {
void reset() {}
};
} // namespace Catch
#else // Not Windows - assumed to be POSIX compatible //////////////////////////
#include <signal.h>
namespace Catch {
struct SignalDefs { int id; const char* name; };
extern SignalDefs signalDefs[];
SignalDefs signalDefs[] = {
{ SIGINT, "SIGINT - Terminal interrupt signal" },
{ SIGILL, "SIGILL - Illegal instruction signal" },
{ SIGFPE, "SIGFPE - Floating point error signal" },
{ SIGSEGV, "SIGSEGV - Segmentation violation signal" },
{ SIGTERM, "SIGTERM - Termination request signal" },
{ SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
};
struct FatalConditionHandler {
static void handleSignal( int sig ) {
for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i )
if( sig == signalDefs[i].id )
fatal( signalDefs[i].name, -sig );
fatal( "<unknown signal>", -sig );
}
FatalConditionHandler() : m_isSet( true ) {
for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i )
signal( signalDefs[i].id, handleSignal );
}
~FatalConditionHandler() {
reset();
}
void reset() {
if( m_isSet ) {
for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i )
signal( signalDefs[i].id, SIG_DFL );
m_isSet = false;
}
}
bool m_isSet;
};
} // namespace Catch
#endif // not Windows
#include <set>
#include <string>
namespace Catch {
class StreamRedirect {
public:
StreamRedirect( std::ostream& stream, std::string& targetString )
: m_stream( stream ),
m_prevBuf( stream.rdbuf() ),
m_targetString( targetString )
{
stream.rdbuf( m_oss.rdbuf() );
}
~StreamRedirect() {
m_targetString += m_oss.str();
m_stream.rdbuf( m_prevBuf );
}
private:
std::ostream& m_stream;
std::streambuf* m_prevBuf;
std::ostringstream m_oss;
std::string& m_targetString;
};
///////////////////////////////////////////////////////////////////////////
class RunContext : public IResultCapture, public IRunner {
RunContext( RunContext const& );
void operator =( RunContext const& );
public:
explicit RunContext( Ptr<IConfig const> const& config, Ptr<IStreamingReporter> const& reporter )
: m_runInfo( config->name() ),
m_context( getCurrentMutableContext() ),
m_activeTestCase( NULL ),
m_config( config ),
m_reporter( reporter ),
m_prevRunner( m_context.getRunner() ),
m_prevResultCapture( m_context.getResultCapture() ),
m_prevConfig( m_context.getConfig() )
{
m_context.setRunner( this );
m_context.setConfig( m_config );
m_context.setResultCapture( this );
m_reporter->testRunStarting( m_runInfo );
}
virtual ~RunContext() {
m_reporter->testRunEnded( TestRunStats( m_runInfo, m_totals, aborting() ) );
m_context.setRunner( m_prevRunner );
m_context.setConfig( NULL );
m_context.setResultCapture( m_prevResultCapture );
m_context.setConfig( m_prevConfig );
}
void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount ) {
m_reporter->testGroupStarting( GroupInfo( testSpec, groupIndex, groupsCount ) );
}
void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount ) {
m_reporter->testGroupEnded( TestGroupStats( GroupInfo( testSpec, groupIndex, groupsCount ), totals, aborting() ) );
}
Totals runTest( TestCase const& testCase ) {
Totals prevTotals = m_totals;
std::string redirectedCout;
std::string redirectedCerr;
TestCaseInfo testInfo = testCase.getTestCaseInfo();
m_reporter->testCaseStarting( testInfo );
m_activeTestCase = &testCase;
m_testCaseTracker = TestCaseTracker( testInfo.name );
do {
do {
runCurrentTest( redirectedCout, redirectedCerr );
}
while( !m_testCaseTracker->isCompleted() && !aborting() );
}
while( getCurrentContext().advanceGeneratorsForCurrentTest() && !aborting() );
Totals deltaTotals = m_totals.delta( prevTotals );
m_totals.testCases += deltaTotals.testCases;
m_reporter->testCaseEnded( TestCaseStats( testInfo,
deltaTotals,
redirectedCout,
redirectedCerr,
aborting() ) );
m_activeTestCase = NULL;
m_testCaseTracker.reset();
return deltaTotals;
}
Ptr<IConfig const> config() const {
return m_config;
}
private: // IResultCapture
virtual void assertionEnded( AssertionResult const& result ) {
if( result.getResultType() == ResultWas::Ok ) {
m_totals.assertions.passed++;
}
else if( !result.isOk() ) {
m_totals.assertions.failed++;
}
if( m_reporter->assertionEnded( AssertionStats( result, m_messages, m_totals ) ) )
m_messages.clear();
// Reset working state
m_lastAssertionInfo = AssertionInfo( "", m_lastAssertionInfo.lineInfo, "{Unknown expression after the reported line}" , m_lastAssertionInfo.resultDisposition );
m_lastResult = result;
}
virtual bool sectionStarted (
SectionInfo const& sectionInfo,
Counts& assertions
)
{
std::ostringstream oss;
oss << sectionInfo.name << "@" << sectionInfo.lineInfo;
if( !m_testCaseTracker->enterSection( oss.str() ) )
return false;
m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
m_reporter->sectionStarting( sectionInfo );
assertions = m_totals.assertions;
return true;
}
bool testForMissingAssertions( Counts& assertions ) {
if( assertions.total() != 0 ||
!m_config->warnAboutMissingAssertions() ||
m_testCaseTracker->currentSectionHasChildren() )
return false;
m_totals.assertions.failed++;
assertions.failed++;
return true;
}
virtual void sectionEnded( SectionInfo const& info, Counts const& prevAssertions, double _durationInSeconds ) {
if( std::uncaught_exception() ) {
m_unfinishedSections.push_back( UnfinishedSections( info, prevAssertions, _durationInSeconds ) );
return;
}
Counts assertions = m_totals.assertions - prevAssertions;
bool missingAssertions = testForMissingAssertions( assertions );
m_testCaseTracker->leaveSection();
m_reporter->sectionEnded( SectionStats( info, assertions, _durationInSeconds, missingAssertions ) );
m_messages.clear();
}
virtual void pushScopedMessage( MessageInfo const& message ) {
m_messages.push_back( message );
}
virtual void popScopedMessage( MessageInfo const& message ) {
m_messages.erase( std::remove( m_messages.begin(), m_messages.end(), message ), m_messages.end() );
}
virtual std::string getCurrentTestName() const {
return m_activeTestCase
? m_activeTestCase->getTestCaseInfo().name
: "";
}
virtual const AssertionResult* getLastResult() const {
return &m_lastResult;
}
virtual void handleFatalErrorCondition( std::string const& message ) {
ResultBuilder resultBuilder = makeUnexpectedResultBuilder();
resultBuilder.setResultType( ResultWas::FatalErrorCondition );
resultBuilder << message;
resultBuilder.captureExpression();
handleUnfinishedSections();
// Recreate section for test case (as we will lose the one that was in scope)
TestCaseInfo const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
SectionInfo testCaseSection( testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description );
Counts assertions;
assertions.failed = 1;
SectionStats testCaseSectionStats( testCaseSection, assertions, 0, false );
m_reporter->sectionEnded( testCaseSectionStats );
TestCaseInfo testInfo = m_activeTestCase->getTestCaseInfo();
Totals deltaTotals;
deltaTotals.testCases.failed = 1;
m_reporter->testCaseEnded( TestCaseStats( testInfo,
deltaTotals,
"",
"",
false ) );
m_totals.testCases.failed++;
testGroupEnded( "", m_totals, 1, 1 );
m_reporter->testRunEnded( TestRunStats( m_runInfo, m_totals, false ) );
}
public:
// !TBD We need to do this another way!
bool aborting() const {
return m_totals.assertions.failed == static_cast<std::size_t>( m_config->abortAfter() );
}
private:
void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr ) {
TestCaseInfo const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
SectionInfo testCaseSection( testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description );
m_reporter->sectionStarting( testCaseSection );
Counts prevAssertions = m_totals.assertions;
double duration = 0;
try {
m_lastAssertionInfo = AssertionInfo( "TEST_CASE", testCaseInfo.lineInfo, "", ResultDisposition::Normal );
TestCaseTracker::Guard guard( *m_testCaseTracker );
Timer timer;
timer.start();
if( m_reporter->getPreferences().shouldRedirectStdOut ) {
StreamRedirect coutRedir( Catch::cout(), redirectedCout );
StreamRedirect cerrRedir( Catch::cerr(), redirectedCerr );
invokeActiveTestCase();
}
else {
invokeActiveTestCase();
}
duration = timer.getElapsedSeconds();
}
catch( TestFailureException& ) {
// This just means the test was aborted due to failure
}
catch(...) {
makeUnexpectedResultBuilder().useActiveException();
}
handleUnfinishedSections();
m_messages.clear();
Counts assertions = m_totals.assertions - prevAssertions;
bool missingAssertions = testForMissingAssertions( assertions );
if( testCaseInfo.okToFail() ) {
std::swap( assertions.failedButOk, assertions.failed );
m_totals.assertions.failed -= assertions.failedButOk;
m_totals.assertions.failedButOk += assertions.failedButOk;
}
SectionStats testCaseSectionStats( testCaseSection, assertions, duration, missingAssertions );
m_reporter->sectionEnded( testCaseSectionStats );
}
void invokeActiveTestCase() {
FatalConditionHandler fatalConditionHandler; // Handle signals
m_activeTestCase->invoke();
fatalConditionHandler.reset();
}
private:
ResultBuilder makeUnexpectedResultBuilder() const {
return ResultBuilder( m_lastAssertionInfo.macroName.c_str(),
m_lastAssertionInfo.lineInfo,
m_lastAssertionInfo.capturedExpression.c_str(),
m_lastAssertionInfo.resultDisposition );
}
void handleUnfinishedSections() {
// If sections ended prematurely due to an exception we stored their
// infos here so we can tear them down outside the unwind process.
for( std::vector<UnfinishedSections>::const_reverse_iterator it = m_unfinishedSections.rbegin(),
itEnd = m_unfinishedSections.rend();
it != itEnd;
++it )
sectionEnded( it->info, it->prevAssertions, it->durationInSeconds );
m_unfinishedSections.clear();
}
struct UnfinishedSections {
UnfinishedSections( SectionInfo const& _info, Counts const& _prevAssertions, double _durationInSeconds )
: info( _info ), prevAssertions( _prevAssertions ), durationInSeconds( _durationInSeconds )
{}
SectionInfo info;
Counts prevAssertions;
double durationInSeconds;
};
TestRunInfo m_runInfo;
IMutableContext& m_context;
TestCase const* m_activeTestCase;
Option<TestCaseTracker> m_testCaseTracker;
AssertionResult m_lastResult;
Ptr<IConfig const> m_config;
Totals m_totals;
Ptr<IStreamingReporter> m_reporter;
std::vector<MessageInfo> m_messages;
IRunner* m_prevRunner;
IResultCapture* m_prevResultCapture;
Ptr<IConfig const> m_prevConfig;
AssertionInfo m_lastAssertionInfo;
std::vector<UnfinishedSections> m_unfinishedSections;
};
IResultCapture& getResultCapture() {
if( IResultCapture* capture = getCurrentContext().getResultCapture() )
return *capture;
else
throw std::logic_error( "No result capture instance" );
}
} // end namespace Catch
// #included from: internal/catch_version.h
#define TWOBLUECUBES_CATCH_VERSION_H_INCLUDED
namespace Catch {
// Versioning information
struct Version {
Version( unsigned int _majorVersion,
unsigned int _minorVersion,
unsigned int _patchNumber,
std::string const& _branchName,
unsigned int _buildNumber );
unsigned int const majorVersion;
unsigned int const minorVersion;
unsigned int const patchNumber;
// buildNumber is only used if branchName is not null
std::string const branchName;
unsigned int const buildNumber;
friend std::ostream& operator << ( std::ostream& os, Version const& version );
private:
void operator=( Version const& );
};
extern Version libraryVersion;
}
#include <fstream>
#include <stdlib.h>
#include <limits>
namespace Catch {
class Runner {
public:
Runner( Ptr<Config> const& config )
: m_config( config )
{
openStream();
makeReporter();
}
Totals runTests() {
RunContext context( m_config.get(), m_reporter );
Totals totals;
context.testGroupStarting( "all tests", 1, 1 ); // deprecated?
TestSpec testSpec = m_config->testSpec();
if( !testSpec.hasFilters() )
testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "~[.]" ).testSpec(); // All not hidden tests
std::vector<TestCase> testCases;
getRegistryHub().getTestCaseRegistry().getFilteredTests( testSpec, *m_config, testCases );
int testsRunForGroup = 0;
for( std::vector<TestCase>::const_iterator it = testCases.begin(), itEnd = testCases.end();
it != itEnd;
++it ) {
testsRunForGroup++;
if( m_testsAlreadyRun.find( *it ) == m_testsAlreadyRun.end() ) {
if( context.aborting() )
break;
totals += context.runTest( *it );
m_testsAlreadyRun.insert( *it );
}
}
std::vector<TestCase> skippedTestCases;
getRegistryHub().getTestCaseRegistry().getFilteredTests( testSpec, *m_config, skippedTestCases, true );
for( std::vector<TestCase>::const_iterator it = skippedTestCases.begin(), itEnd = skippedTestCases.end();
it != itEnd;
++it )
m_reporter->skipTest( *it );
context.testGroupEnded( "all tests", totals, 1, 1 );
return totals;
}
private:
void openStream() {
// Open output file, if specified
if( !m_config->getFilename().empty() ) {
m_ofs.open( m_config->getFilename().c_str() );
if( m_ofs.fail() ) {
std::ostringstream oss;
oss << "Unable to open file: '" << m_config->getFilename() << "'";
throw std::domain_error( oss.str() );
}
m_config->setStreamBuf( m_ofs.rdbuf() );
}
}
void makeReporter() {
std::string reporterName = m_config->getReporterName().empty()
? "console"
: m_config->getReporterName();
m_reporter = getRegistryHub().getReporterRegistry().create( reporterName, m_config.get() );
if( !m_reporter ) {
std::ostringstream oss;
oss << "No reporter registered with name: '" << reporterName << "'";
throw std::domain_error( oss.str() );
}
}
private:
Ptr<Config> m_config;
std::ofstream m_ofs;
Ptr<IStreamingReporter> m_reporter;
std::set<TestCase> m_testsAlreadyRun;
};
class Session : NonCopyable {
static bool alreadyInstantiated;
public:
struct OnUnusedOptions { enum DoWhat { Ignore, Fail }; };
Session()
: m_cli( makeCommandLineParser() ) {
if( alreadyInstantiated ) {
std::string msg = "Only one instance of Catch::Session can ever be used";
Catch::cerr() << msg << std::endl;
throw std::logic_error( msg );
}
alreadyInstantiated = true;
}
~Session() {
Catch::cleanUp();
}
void showHelp( std::string const& processName ) {
Catch::cout() << "\nCatch v" << libraryVersion << "\n";
m_cli.usage( Catch::cout(), processName );
Catch::cout() << "For more detail usage please see the project docs\n" << std::endl;
}
int applyCommandLine( int argc, char* const argv[], OnUnusedOptions::DoWhat unusedOptionBehaviour = OnUnusedOptions::Fail ) {
try {
m_cli.setThrowOnUnrecognisedTokens( unusedOptionBehaviour == OnUnusedOptions::Fail );
m_unusedTokens = m_cli.parseInto( argc, argv, m_configData );
if( m_configData.showHelp )
showHelp( m_configData.processName );
m_config.reset();
}
catch( std::exception& ex ) {
{
Colour colourGuard( Colour::Red );
Catch::cerr()
<< "\nError(s) in input:\n"
<< Text( ex.what(), TextAttributes().setIndent(2) )
<< "\n\n";
}
m_cli.usage( Catch::cout(), m_configData.processName );
return (std::numeric_limits<int>::max)();
}
return 0;
}
void useConfigData( ConfigData const& _configData ) {
m_configData = _configData;
m_config.reset();
}
int run( int argc, char* const argv[] ) {
int returnCode = applyCommandLine( argc, argv );
if( returnCode == 0 )
returnCode = run();
return returnCode;
}
int run() {
if( m_configData.showHelp )
return 0;
try
{
config(); // Force config to be constructed
std::srand( m_configData.rngSeed );
Runner runner( m_config );
// Handle list request
if( Option<std::size_t> listed = list( config() ) )
return static_cast<int>( *listed );
return static_cast<int>( runner.runTests().assertions.failed );
}
catch( std::exception& ex ) {
Catch::cerr() << ex.what() << std::endl;
return (std::numeric_limits<int>::max)();
}
}
Clara::CommandLine<ConfigData> const& cli() const {
return m_cli;
}
std::vector<Clara::Parser::Token> const& unusedTokens() const {
return m_unusedTokens;
}
ConfigData& configData() {
return m_configData;
}
Config& config() {
if( !m_config )
m_config = new Config( m_configData );
return *m_config;
}
private:
Clara::CommandLine<ConfigData> m_cli;
std::vector<Clara::Parser::Token> m_unusedTokens;
ConfigData m_configData;
Ptr<Config> m_config;
};
bool Session::alreadyInstantiated = false;
} // end namespace Catch
// #included from: catch_registry_hub.hpp
#define TWOBLUECUBES_CATCH_REGISTRY_HUB_HPP_INCLUDED
// #included from: catch_test_case_registry_impl.hpp
#define TWOBLUECUBES_CATCH_TEST_CASE_REGISTRY_IMPL_HPP_INCLUDED
#include <vector>
#include <set>
#include <sstream>
#include <iostream>
#include <algorithm>
namespace Catch {
class TestRegistry : public ITestCaseRegistry {
struct LexSort {
bool operator() (TestCase i,TestCase j) const { return (i<j);}
};
struct RandomNumberGenerator {
int operator()( int n ) const { return std::rand() % n; }
};
public:
TestRegistry() : m_unnamedCount( 0 ) {}
virtual ~TestRegistry();
virtual void registerTest( TestCase const& testCase ) {
std::string name = testCase.getTestCaseInfo().name;
if( name == "" ) {
std::ostringstream oss;
oss << "Anonymous test case " << ++m_unnamedCount;
return registerTest( testCase.withName( oss.str() ) );
}
if( m_functions.find( testCase ) == m_functions.end() ) {
m_functions.insert( testCase );
m_functionsInOrder.push_back( testCase );
if( !testCase.isHidden() )
m_nonHiddenFunctions.push_back( testCase );
}
else {
TestCase const& prev = *m_functions.find( testCase );
{
Colour colourGuard( Colour::Red );
Catch::cerr() << "error: TEST_CASE( \"" << name << "\" ) already defined.\n"
<< "\tFirst seen at " << prev.getTestCaseInfo().lineInfo << "\n"
<< "\tRedefined at " << testCase.getTestCaseInfo().lineInfo << std::endl;
}
exit(1);
}
}
virtual std::vector<TestCase> const& getAllTests() const {
return m_functionsInOrder;
}
virtual std::vector<TestCase> const& getAllNonHiddenTests() const {
return m_nonHiddenFunctions;
}
virtual void getFilteredTests( TestSpec const& testSpec, IConfig const& config, std::vector<TestCase>& matchingTestCases, bool negated = false ) const {
for( std::vector<TestCase>::const_iterator it = m_functionsInOrder.begin(),
itEnd = m_functionsInOrder.end();
it != itEnd;
++it ) {
bool includeTest = testSpec.matches( *it ) && ( config.allowThrows() || !it->throws() );
if( includeTest != negated )
matchingTestCases.push_back( *it );
}
sortTests( config, matchingTestCases );
}
private:
static void sortTests( IConfig const& config, std::vector<TestCase>& matchingTestCases ) {
switch( config.runOrder() ) {
case RunTests::InLexicographicalOrder:
std::sort( matchingTestCases.begin(), matchingTestCases.end(), LexSort() );
break;
case RunTests::InRandomOrder:
{
RandomNumberGenerator rng;
std::random_shuffle( matchingTestCases.begin(), matchingTestCases.end(), rng );
}
break;
case RunTests::InDeclarationOrder:
// already in declaration order
break;
}
}
std::set<TestCase> m_functions;
std::vector<TestCase> m_functionsInOrder;
std::vector<TestCase> m_nonHiddenFunctions;
size_t m_unnamedCount;
};
///////////////////////////////////////////////////////////////////////////
class FreeFunctionTestCase : public SharedImpl<ITestCase> {
public:
FreeFunctionTestCase( TestFunction fun ) : m_fun( fun ) {}
virtual void invoke() const {
m_fun();
}
private:
virtual ~FreeFunctionTestCase();
TestFunction m_fun;
};
inline std::string extractClassName( std::string const& classOrQualifiedMethodName ) {
std::string className = classOrQualifiedMethodName;
if( startsWith( className, "&" ) )
{
std::size_t lastColons = className.rfind( "::" );
std::size_t penultimateColons = className.rfind( "::", lastColons-1 );
if( penultimateColons == std::string::npos )
penultimateColons = 1;
className = className.substr( penultimateColons, lastColons-penultimateColons );
}
return className;
}
///////////////////////////////////////////////////////////////////////////
AutoReg::AutoReg( TestFunction function,
SourceLineInfo const& lineInfo,
NameAndDesc const& nameAndDesc ) {
registerTestCase( new FreeFunctionTestCase( function ), "", nameAndDesc, lineInfo );
}
AutoReg::~AutoReg() {}
void AutoReg::registerTestCase( ITestCase* testCase,
char const* classOrQualifiedMethodName,
NameAndDesc const& nameAndDesc,
SourceLineInfo const& lineInfo ) {
getMutableRegistryHub().registerTest
( makeTestCase( testCase,
extractClassName( classOrQualifiedMethodName ),
nameAndDesc.name,
nameAndDesc.description,
lineInfo ) );
}
} // end namespace Catch
// #included from: catch_reporter_registry.hpp
#define TWOBLUECUBES_CATCH_REPORTER_REGISTRY_HPP_INCLUDED
#include <map>
namespace Catch {
class ReporterRegistry : public IReporterRegistry {
public:
virtual ~ReporterRegistry() {
deleteAllValues( m_factories );
}
virtual IStreamingReporter* create( std::string const& name, Ptr<IConfig> const& config ) const {
FactoryMap::const_iterator it = m_factories.find( name );
if( it == m_factories.end() )
return NULL;
return it->second->create( ReporterConfig( config ) );
}
void registerReporter( std::string const& name, IReporterFactory* factory ) {
m_factories.insert( std::make_pair( name, factory ) );
}
FactoryMap const& getFactories() const {
return m_factories;
}
private:
FactoryMap m_factories;
};
}
// #included from: catch_exception_translator_registry.hpp
#define TWOBLUECUBES_CATCH_EXCEPTION_TRANSLATOR_REGISTRY_HPP_INCLUDED
#ifdef __OBJC__
#import "Foundation/Foundation.h"
#endif
namespace Catch {
class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
public:
~ExceptionTranslatorRegistry() {
deleteAll( m_translators );
}
virtual void registerTranslator( const IExceptionTranslator* translator ) {
m_translators.push_back( translator );
}
virtual std::string translateActiveException() const {
try {
#ifdef __OBJC__
// In Objective-C try objective-c exceptions first
@try {
throw;
}
@catch (NSException *exception) {
return Catch::toString( [exception description] );
}
#else
throw;
#endif
}
catch( TestFailureException& ) {
throw;
}
catch( std::exception& ex ) {
return ex.what();
}
catch( std::string& msg ) {
return msg;
}
catch( const char* msg ) {
return msg;
}
catch(...) {
return tryTranslators( m_translators.begin() );
}
}
std::string tryTranslators( std::vector<const IExceptionTranslator*>::const_iterator it ) const {
if( it == m_translators.end() )
return "Unknown exception";
try {
return (*it)->translate();
}
catch(...) {
return tryTranslators( it+1 );
}
}
private:
std::vector<const IExceptionTranslator*> m_translators;
};
}
namespace Catch {
namespace {
class RegistryHub : public IRegistryHub, public IMutableRegistryHub {
RegistryHub( RegistryHub const& );
void operator=( RegistryHub const& );
public: // IRegistryHub
RegistryHub() {
}
virtual IReporterRegistry const& getReporterRegistry() const {
return m_reporterRegistry;
}
virtual ITestCaseRegistry const& getTestCaseRegistry() const {
return m_testCaseRegistry;
}
virtual IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() {
return m_exceptionTranslatorRegistry;
}
public: // IMutableRegistryHub
virtual void registerReporter( std::string const& name, IReporterFactory* factory ) {
m_reporterRegistry.registerReporter( name, factory );
}
virtual void registerTest( TestCase const& testInfo ) {
m_testCaseRegistry.registerTest( testInfo );
}
virtual void registerTranslator( const IExceptionTranslator* translator ) {
m_exceptionTranslatorRegistry.registerTranslator( translator );
}
private:
TestRegistry m_testCaseRegistry;
ReporterRegistry m_reporterRegistry;
ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
};
// Single, global, instance
inline RegistryHub*& getTheRegistryHub() {
static RegistryHub* theRegistryHub = NULL;
if( !theRegistryHub )
theRegistryHub = new RegistryHub();
return theRegistryHub;
}
}
IRegistryHub& getRegistryHub() {
return *getTheRegistryHub();
}
IMutableRegistryHub& getMutableRegistryHub() {
return *getTheRegistryHub();
}
void cleanUp() {
delete getTheRegistryHub();
getTheRegistryHub() = NULL;
cleanUpContext();
}
std::string translateActiveException() {
return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
}
} // end namespace Catch
// #included from: catch_notimplemented_exception.hpp
#define TWOBLUECUBES_CATCH_NOTIMPLEMENTED_EXCEPTION_HPP_INCLUDED
#include <ostream>
namespace Catch {
NotImplementedException::NotImplementedException( SourceLineInfo const& lineInfo )
: m_lineInfo( lineInfo ) {
std::ostringstream oss;
oss << lineInfo << ": function ";
oss << "not implemented";
m_what = oss.str();
}
const char* NotImplementedException::what() const CATCH_NOEXCEPT {
return m_what.c_str();
}
} // end namespace Catch
// #included from: catch_context_impl.hpp
#define TWOBLUECUBES_CATCH_CONTEXT_IMPL_HPP_INCLUDED
// #included from: catch_stream.hpp
#define TWOBLUECUBES_CATCH_STREAM_HPP_INCLUDED
// #included from: catch_streambuf.h
#define TWOBLUECUBES_CATCH_STREAMBUF_H_INCLUDED
#include <streambuf>
namespace Catch {
class StreamBufBase : public std::streambuf {
public:
virtual ~StreamBufBase() CATCH_NOEXCEPT;
};
}
#include <stdexcept>
#include <cstdio>
#include <iostream>
namespace Catch {
template<typename WriterF, size_t bufferSize=256>
class StreamBufImpl : public StreamBufBase {
char data[bufferSize];
WriterF m_writer;
public:
StreamBufImpl() {
setp( data, data + sizeof(data) );
}
~StreamBufImpl() CATCH_NOEXCEPT {
sync();
}
private:
int overflow( int c ) {
sync();
if( c != EOF ) {
if( pbase() == epptr() )
m_writer( std::string( 1, static_cast<char>( c ) ) );
else
sputc( static_cast<char>( c ) );
}
return 0;
}
int sync() {
if( pbase() != pptr() ) {
m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
setp( pbase(), epptr() );
}
return 0;
}
};
///////////////////////////////////////////////////////////////////////////
struct OutputDebugWriter {
void operator()( std::string const&str ) {
writeToDebugConsole( str );
}
};
Stream::Stream()
: streamBuf( NULL ), isOwned( false )
{}
Stream::Stream( std::streambuf* _streamBuf, bool _isOwned )
: streamBuf( _streamBuf ), isOwned( _isOwned )
{}
void Stream::release() {
if( isOwned ) {
delete streamBuf;
streamBuf = NULL;
isOwned = false;
}
}
#ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement this functions
std::ostream& cout() {
return std::cout;
}
std::ostream& cerr() {
return std::cerr;
}
#endif
}
namespace Catch {
class Context : public IMutableContext {
Context() : m_config( NULL ), m_runner( NULL ), m_resultCapture( NULL ) {}
Context( Context const& );
void operator=( Context const& );
public: // IContext
virtual IResultCapture* getResultCapture() {
return m_resultCapture;
}
virtual IRunner* getRunner() {
return m_runner;
}
virtual size_t getGeneratorIndex( std::string const& fileInfo, size_t totalSize ) {
return getGeneratorsForCurrentTest()
.getGeneratorInfo( fileInfo, totalSize )
.getCurrentIndex();
}
virtual bool advanceGeneratorsForCurrentTest() {
IGeneratorsForTest* generators = findGeneratorsForCurrentTest();
return generators && generators->moveNext();
}
virtual Ptr<IConfig const> getConfig() const {
return m_config;
}
public: // IMutableContext
virtual void setResultCapture( IResultCapture* resultCapture ) {
m_resultCapture = resultCapture;
}
virtual void setRunner( IRunner* runner ) {
m_runner = runner;
}
virtual void setConfig( Ptr<IConfig const> const& config ) {
m_config = config;
}
friend IMutableContext& getCurrentMutableContext();
private:
IGeneratorsForTest* findGeneratorsForCurrentTest() {
std::string testName = getResultCapture()->getCurrentTestName();
std::map<std::string, IGeneratorsForTest*>::const_iterator it =
m_generatorsByTestName.find( testName );
return it != m_generatorsByTestName.end()
? it->second
: NULL;
}
IGeneratorsForTest& getGeneratorsForCurrentTest() {
IGeneratorsForTest* generators = findGeneratorsForCurrentTest();
if( !generators ) {
std::string testName = getResultCapture()->getCurrentTestName();
generators = createGeneratorsForTest();
m_generatorsByTestName.insert( std::make_pair( testName, generators ) );
}
return *generators;
}
private:
Ptr<IConfig const> m_config;
IRunner* m_runner;
IResultCapture* m_resultCapture;
std::map<std::string, IGeneratorsForTest*> m_generatorsByTestName;
};
namespace {
Context* currentContext = NULL;
}
IMutableContext& getCurrentMutableContext() {
if( !currentContext )
currentContext = new Context();
return *currentContext;
}
IContext& getCurrentContext() {
return getCurrentMutableContext();
}
Stream createStream( std::string const& streamName ) {
if( streamName == "stdout" ) return Stream( Catch::cout().rdbuf(), false );
if( streamName == "stderr" ) return Stream( Catch::cerr().rdbuf(), false );
if( streamName == "debug" ) return Stream( new StreamBufImpl<OutputDebugWriter>, true );
throw std::domain_error( "Unknown stream: " + streamName );
}
void cleanUpContext() {
delete currentContext;
currentContext = NULL;
}
}
// #included from: catch_console_colour_impl.hpp
#define TWOBLUECUBES_CATCH_CONSOLE_COLOUR_IMPL_HPP_INCLUDED
namespace Catch {
namespace {
struct IColourImpl {
virtual ~IColourImpl() {}
virtual void use( Colour::Code _colourCode ) = 0;
};
struct NoColourImpl : IColourImpl {
void use( Colour::Code ) {}
static IColourImpl* instance() {
static NoColourImpl s_instance;
return &s_instance;
}
};
} // anon namespace
} // namespace Catch
#if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )
# ifdef CATCH_PLATFORM_WINDOWS
# define CATCH_CONFIG_COLOUR_WINDOWS
# else
# define CATCH_CONFIG_COLOUR_ANSI
# endif
#endif
#if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) /////////////////////////////////////////
#ifndef NOMINMAX
#define NOMINMAX
#endif
#ifdef __AFXDLL
#include <AfxWin.h>
#else
#include <windows.h>
#endif
namespace Catch {
namespace {
class Win32ColourImpl : public IColourImpl {
public:
Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
{
CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
originalAttributes = csbiInfo.wAttributes;
}
virtual void use( Colour::Code _colourCode ) {
switch( _colourCode ) {
case Colour::None: return setTextAttribute( originalAttributes );
case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
case Colour::Red: return setTextAttribute( FOREGROUND_RED );
case Colour::Green: return setTextAttribute( FOREGROUND_GREEN );
case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE );
case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
case Colour::Grey: return setTextAttribute( 0 );
case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY );
case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
case Colour::Bright: throw std::logic_error( "not a colour" );
}
}
private:
void setTextAttribute( WORD _textAttribute ) {
SetConsoleTextAttribute( stdoutHandle, _textAttribute );
}
HANDLE stdoutHandle;
WORD originalAttributes;
};
IColourImpl* platformColourInstance() {
static Win32ColourImpl s_instance;
return &s_instance;
}
} // end anon namespace
} // end namespace Catch
#elif defined( CATCH_CONFIG_COLOUR_ANSI ) //////////////////////////////////////
#include <unistd.h>
namespace Catch {
namespace {
// use POSIX/ ANSI console terminal codes
// Thanks to Adam Strzelecki for original contribution
// (http://github.com/nanoant)
// https://github.com/philsquared/Catch/pull/131
class PosixColourImpl : public IColourImpl {
public:
virtual void use( Colour::Code _colourCode ) {
switch( _colourCode ) {
case Colour::None:
case Colour::White: return setColour( "[0m" );
case Colour::Red: return setColour( "[0;31m" );
case Colour::Green: return setColour( "[0;32m" );
case Colour::Blue: return setColour( "[0:34m" );
case Colour::Cyan: return setColour( "[0;36m" );
case Colour::Yellow: return setColour( "[0;33m" );
case Colour::Grey: return setColour( "[1;30m" );
case Colour::LightGrey: return setColour( "[0;37m" );
case Colour::BrightRed: return setColour( "[1;31m" );
case Colour::BrightGreen: return setColour( "[1;32m" );
case Colour::BrightWhite: return setColour( "[1;37m" );
case Colour::Bright: throw std::logic_error( "not a colour" );
}
}
static IColourImpl* instance() {
static PosixColourImpl s_instance;
return &s_instance;
}
private:
void setColour( const char* _escapeCode ) {
Catch::cout() << '\033' << _escapeCode;
}
};
IColourImpl* platformColourInstance() {
Ptr<IConfig const> config = getCurrentContext().getConfig();
return (config && config->forceColour()) || isatty(STDOUT_FILENO)
? PosixColourImpl::instance()
: NoColourImpl::instance();
}
} // end anon namespace
} // end namespace Catch
#else // not Windows or ANSI ///////////////////////////////////////////////
namespace Catch {
static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); }
} // end namespace Catch
#endif // Windows/ ANSI/ None
namespace Catch {
Colour::Colour( Code _colourCode ) : m_moved( false ) { use( _colourCode ); }
Colour::Colour( Colour const& _other ) : m_moved( false ) { const_cast<Colour&>( _other ).m_moved = true; }
Colour::~Colour(){ if( !m_moved ) use( None ); }
void Colour::use( Code _colourCode ) {
static IColourImpl* impl = isDebuggerActive()
? NoColourImpl::instance()
: platformColourInstance();
impl->use( _colourCode );
}
} // end namespace Catch
// #included from: catch_generators_impl.hpp
#define TWOBLUECUBES_CATCH_GENERATORS_IMPL_HPP_INCLUDED
#include <vector>
#include <string>
#include <map>
namespace Catch {
struct GeneratorInfo : IGeneratorInfo {
GeneratorInfo( std::size_t size )
: m_size( size ),
m_currentIndex( 0 )
{}
bool moveNext() {
if( ++m_currentIndex == m_size ) {
m_currentIndex = 0;
return false;
}
return true;
}
std::size_t getCurrentIndex() const {
return m_currentIndex;
}
std::size_t m_size;
std::size_t m_currentIndex;
};
///////////////////////////////////////////////////////////////////////////
class GeneratorsForTest : public IGeneratorsForTest {
public:
~GeneratorsForTest() {
deleteAll( m_generatorsInOrder );
}
IGeneratorInfo& getGeneratorInfo( std::string const& fileInfo, std::size_t size ) {
std::map<std::string, IGeneratorInfo*>::const_iterator it = m_generatorsByName.find( fileInfo );
if( it == m_generatorsByName.end() ) {
IGeneratorInfo* info = new GeneratorInfo( size );
m_generatorsByName.insert( std::make_pair( fileInfo, info ) );
m_generatorsInOrder.push_back( info );
return *info;
}
return *it->second;
}
bool moveNext() {
std::vector<IGeneratorInfo*>::const_iterator it = m_generatorsInOrder.begin();
std::vector<IGeneratorInfo*>::const_iterator itEnd = m_generatorsInOrder.end();
for(; it != itEnd; ++it ) {
if( (*it)->moveNext() )
return true;
}
return false;
}
private:
std::map<std::string, IGeneratorInfo*> m_generatorsByName;
std::vector<IGeneratorInfo*> m_generatorsInOrder;
};
IGeneratorsForTest* createGeneratorsForTest()
{
return new GeneratorsForTest();
}
} // end namespace Catch
// #included from: catch_assertionresult.hpp
#define TWOBLUECUBES_CATCH_ASSERTIONRESULT_HPP_INCLUDED
namespace Catch {
AssertionInfo::AssertionInfo( std::string const& _macroName,
SourceLineInfo const& _lineInfo,
std::string const& _capturedExpression,
ResultDisposition::Flags _resultDisposition )
: macroName( _macroName ),
lineInfo( _lineInfo ),
capturedExpression( _capturedExpression ),
resultDisposition( _resultDisposition )
{}
AssertionResult::AssertionResult() {}
AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )
: m_info( info ),
m_resultData( data )
{}
AssertionResult::~AssertionResult() {}
// Result was a success
bool AssertionResult::succeeded() const {
return Catch::isOk( m_resultData.resultType );
}
// Result was a success, or failure is suppressed
bool AssertionResult::isOk() const {
return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
}
ResultWas::OfType AssertionResult::getResultType() const {
return m_resultData.resultType;
}
bool AssertionResult::hasExpression() const {
return !m_info.capturedExpression.empty();
}
bool AssertionResult::hasMessage() const {
return !m_resultData.message.empty();
}
std::string AssertionResult::getExpression() const {
if( isFalseTest( m_info.resultDisposition ) )
return "!" + m_info.capturedExpression;
else
return m_info.capturedExpression;
}
std::string AssertionResult::getExpressionInMacro() const {
if( m_info.macroName.empty() )
return m_info.capturedExpression;
else
return m_info.macroName + "( " + m_info.capturedExpression + " )";
}
bool AssertionResult::hasExpandedExpression() const {
return hasExpression() && getExpandedExpression() != getExpression();
}
std::string AssertionResult::getExpandedExpression() const {
return m_resultData.reconstructedExpression;
}
std::string AssertionResult::getMessage() const {
return m_resultData.message;
}
SourceLineInfo AssertionResult::getSourceInfo() const {
return m_info.lineInfo;
}
std::string AssertionResult::getTestMacroName() const {
return m_info.macroName;
}
} // end namespace Catch
// #included from: catch_test_case_info.hpp
#define TWOBLUECUBES_CATCH_TEST_CASE_INFO_HPP_INCLUDED
namespace Catch {
inline TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {
if( startsWith( tag, "." ) ||
tag == "hide" ||
tag == "!hide" )
return TestCaseInfo::IsHidden;
else if( tag == "!throws" )
return TestCaseInfo::Throws;
else if( tag == "!shouldfail" )
return TestCaseInfo::ShouldFail;
else if( tag == "!mayfail" )
return TestCaseInfo::MayFail;
else
return TestCaseInfo::None;
}
inline bool isReservedTag( std::string const& tag ) {
return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !isalnum( tag[0] );
}
inline void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) {
if( isReservedTag( tag ) ) {
{
Colour colourGuard( Colour::Red );
Catch::cerr()
<< "Tag name [" << tag << "] not allowed.\n"
<< "Tag names starting with non alpha-numeric characters are reserved\n";
}
{
Colour colourGuard( Colour::FileName );
Catch::cerr() << _lineInfo << std::endl;
}
exit(1);
}
}
TestCase makeTestCase( ITestCase* _testCase,
std::string const& _className,
std::string const& _name,
std::string const& _descOrTags,
SourceLineInfo const& _lineInfo )
{
bool isHidden( startsWith( _name, "./" ) ); // Legacy support
// Parse out tags
std::set<std::string> tags;
std::string desc, tag;
bool inTag = false;
for( std::size_t i = 0; i < _descOrTags.size(); ++i ) {
char c = _descOrTags[i];
if( !inTag ) {
if( c == '[' )
inTag = true;
else
desc += c;
}
else {
if( c == ']' ) {
TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
if( prop == TestCaseInfo::IsHidden )
isHidden = true;
else if( prop == TestCaseInfo::None )
enforceNotReservedTag( tag, _lineInfo );
tags.insert( tag );
tag.clear();
inTag = false;
}
else
tag += c;
}
}
if( isHidden ) {
tags.insert( "hide" );
tags.insert( "." );
}
TestCaseInfo info( _name, _className, desc, tags, _lineInfo );
return TestCase( _testCase, info );
}
TestCaseInfo::TestCaseInfo( std::string const& _name,
std::string const& _className,
std::string const& _description,
std::set<std::string> const& _tags,
SourceLineInfo const& _lineInfo )
: name( _name ),
className( _className ),
description( _description ),
tags( _tags ),
lineInfo( _lineInfo ),
properties( None )
{
std::ostringstream oss;
for( std::set<std::string>::const_iterator it = _tags.begin(), itEnd = _tags.end(); it != itEnd; ++it ) {
oss << "[" << *it << "]";
std::string lcaseTag = toLower( *it );
properties = static_cast<SpecialProperties>( properties | parseSpecialTag( lcaseTag ) );
lcaseTags.insert( lcaseTag );
}
tagsAsString = oss.str();
}
TestCaseInfo::TestCaseInfo( TestCaseInfo const& other )
: name( other.name ),
className( other.className ),
description( other.description ),
tags( other.tags ),
lcaseTags( other.lcaseTags ),
tagsAsString( other.tagsAsString ),
lineInfo( other.lineInfo ),
properties( other.properties )
{}
bool TestCaseInfo::isHidden() const {
return ( properties & IsHidden ) != 0;
}
bool TestCaseInfo::throws() const {
return ( properties & Throws ) != 0;
}
bool TestCaseInfo::okToFail() const {
return ( properties & (ShouldFail | MayFail ) ) != 0;
}
bool TestCaseInfo::expectedToFail() const {
return ( properties & (ShouldFail ) ) != 0;
}
TestCase::TestCase( ITestCase* testCase, TestCaseInfo const& info ) : TestCaseInfo( info ), test( testCase ) {}
TestCase::TestCase( TestCase const& other )
: TestCaseInfo( other ),
test( other.test )
{}
TestCase TestCase::withName( std::string const& _newName ) const {
TestCase other( *this );
other.name = _newName;
return other;
}
void TestCase::swap( TestCase& other ) {
test.swap( other.test );
name.swap( other.name );
className.swap( other.className );
description.swap( other.description );
tags.swap( other.tags );
lcaseTags.swap( other.lcaseTags );
tagsAsString.swap( other.tagsAsString );
std::swap( TestCaseInfo::properties, static_cast<TestCaseInfo&>( other ).properties );
std::swap( lineInfo, other.lineInfo );
}
void TestCase::invoke() const {
test->invoke();
}
bool TestCase::operator == ( TestCase const& other ) const {
return test.get() == other.test.get() &&
name == other.name &&
className == other.className;
}
bool TestCase::operator < ( TestCase const& other ) const {
return name < other.name;
}
TestCase& TestCase::operator = ( TestCase const& other ) {
TestCase temp( other );
swap( temp );
return *this;
}
TestCaseInfo const& TestCase::getTestCaseInfo() const
{
return *this;
}
} // end namespace Catch
// #included from: catch_version.hpp
#define TWOBLUECUBES_CATCH_VERSION_HPP_INCLUDED
namespace Catch {
Version::Version
( unsigned int _majorVersion,
unsigned int _minorVersion,
unsigned int _patchNumber,
std::string const& _branchName,
unsigned int _buildNumber )
: majorVersion( _majorVersion ),
minorVersion( _minorVersion ),
patchNumber( _patchNumber ),
branchName( _branchName ),
buildNumber( _buildNumber )
{}
std::ostream& operator << ( std::ostream& os, Version const& version ) {
os << version.majorVersion << "."
<< version.minorVersion << "."
<< version.patchNumber;
if( !version.branchName.empty() ) {
os << "-" << version.branchName
<< "." << version.buildNumber;
}
return os;
}
Version libraryVersion( 1, 2, 1, "", 0 );
}
// #included from: catch_msg.hpp
#define TWOBLUECUBES_CATCH_MSG_HPP_INCLUDED
namespace Catch {
MessageInfo::MessageInfo( std::string const& _macroName,
SourceLineInfo const& _lineInfo,
ResultWas::OfType _type )
: macroName( _macroName ),
lineInfo( _lineInfo ),
type( _type ),
sequence( ++globalCount )
{}
// This may need protecting if threading support is added
unsigned int MessageInfo::globalCount = 0;
////////////////////////////////////////////////////////////////////////////
ScopedMessage::ScopedMessage( MessageBuilder const& builder )
: m_info( builder.m_info )
{
m_info.message = builder.m_stream.str();
getResultCapture().pushScopedMessage( m_info );
}
ScopedMessage::ScopedMessage( ScopedMessage const& other )
: m_info( other.m_info )
{}
ScopedMessage::~ScopedMessage() {
getResultCapture().popScopedMessage( m_info );
}
} // end namespace Catch
// #included from: catch_legacy_reporter_adapter.hpp
#define TWOBLUECUBES_CATCH_LEGACY_REPORTER_ADAPTER_HPP_INCLUDED
// #included from: catch_legacy_reporter_adapter.h
#define TWOBLUECUBES_CATCH_LEGACY_REPORTER_ADAPTER_H_INCLUDED
namespace Catch
{
// Deprecated
struct IReporter : IShared {
virtual ~IReporter();
virtual bool shouldRedirectStdout() const = 0;
virtual void StartTesting() = 0;
virtual void EndTesting( Totals const& totals ) = 0;
virtual void StartGroup( std::string const& groupName ) = 0;
virtual void EndGroup( std::string const& groupName, Totals const& totals ) = 0;
virtual void StartTestCase( TestCaseInfo const& testInfo ) = 0;
virtual void EndTestCase( TestCaseInfo const& testInfo, Totals const& totals, std::string const& stdOut, std::string const& stdErr ) = 0;
virtual void StartSection( std::string const& sectionName, std::string const& description ) = 0;
virtual void EndSection( std::string const& sectionName, Counts const& assertions ) = 0;
virtual void NoAssertionsInSection( std::string const& sectionName ) = 0;
virtual void NoAssertionsInTestCase( std::string const& testName ) = 0;
virtual void Aborted() = 0;
virtual void Result( AssertionResult const& result ) = 0;
};
class LegacyReporterAdapter : public SharedImpl<IStreamingReporter>
{
public:
LegacyReporterAdapter( Ptr<IReporter> const& legacyReporter );
virtual ~LegacyReporterAdapter();
virtual ReporterPreferences getPreferences() const;
virtual void noMatchingTestCases( std::string const& );
virtual void testRunStarting( TestRunInfo const& );
virtual void testGroupStarting( GroupInfo const& groupInfo );
virtual void testCaseStarting( TestCaseInfo const& testInfo );
virtual void sectionStarting( SectionInfo const& sectionInfo );
virtual void assertionStarting( AssertionInfo const& );
virtual bool assertionEnded( AssertionStats const& assertionStats );
virtual void sectionEnded( SectionStats const& sectionStats );
virtual void testCaseEnded( TestCaseStats const& testCaseStats );
virtual void testGroupEnded( TestGroupStats const& testGroupStats );
virtual void testRunEnded( TestRunStats const& testRunStats );
virtual void skipTest( TestCaseInfo const& );
private:
Ptr<IReporter> m_legacyReporter;
};
}
namespace Catch
{
LegacyReporterAdapter::LegacyReporterAdapter( Ptr<IReporter> const& legacyReporter )
: m_legacyReporter( legacyReporter )
{}
LegacyReporterAdapter::~LegacyReporterAdapter() {}
ReporterPreferences LegacyReporterAdapter::getPreferences() const {
ReporterPreferences prefs;
prefs.shouldRedirectStdOut = m_legacyReporter->shouldRedirectStdout();
return prefs;
}
void LegacyReporterAdapter::noMatchingTestCases( std::string const& ) {}
void LegacyReporterAdapter::testRunStarting( TestRunInfo const& ) {
m_legacyReporter->StartTesting();
}
void LegacyReporterAdapter::testGroupStarting( GroupInfo const& groupInfo ) {
m_legacyReporter->StartGroup( groupInfo.name );
}
void LegacyReporterAdapter::testCaseStarting( TestCaseInfo const& testInfo ) {
m_legacyReporter->StartTestCase( testInfo );
}
void LegacyReporterAdapter::sectionStarting( SectionInfo const& sectionInfo ) {
m_legacyReporter->StartSection( sectionInfo.name, sectionInfo.description );
}
void LegacyReporterAdapter::assertionStarting( AssertionInfo const& ) {
// Not on legacy interface
}
bool LegacyReporterAdapter::assertionEnded( AssertionStats const& assertionStats ) {
if( assertionStats.assertionResult.getResultType() != ResultWas::Ok ) {
for( std::vector<MessageInfo>::const_iterator it = assertionStats.infoMessages.begin(), itEnd = assertionStats.infoMessages.end();
it != itEnd;
++it ) {
if( it->type == ResultWas::Info ) {
ResultBuilder rb( it->macroName.c_str(), it->lineInfo, "", ResultDisposition::Normal );
rb << it->message;
rb.setResultType( ResultWas::Info );
AssertionResult result = rb.build();
m_legacyReporter->Result( result );
}
}
}
m_legacyReporter->Result( assertionStats.assertionResult );
return true;
}
void LegacyReporterAdapter::sectionEnded( SectionStats const& sectionStats ) {
if( sectionStats.missingAssertions )
m_legacyReporter->NoAssertionsInSection( sectionStats.sectionInfo.name );
m_legacyReporter->EndSection( sectionStats.sectionInfo.name, sectionStats.assertions );
}
void LegacyReporterAdapter::testCaseEnded( TestCaseStats const& testCaseStats ) {
m_legacyReporter->EndTestCase
( testCaseStats.testInfo,
testCaseStats.totals,
testCaseStats.stdOut,
testCaseStats.stdErr );
}
void LegacyReporterAdapter::testGroupEnded( TestGroupStats const& testGroupStats ) {
if( testGroupStats.aborting )
m_legacyReporter->Aborted();
m_legacyReporter->EndGroup( testGroupStats.groupInfo.name, testGroupStats.totals );
}
void LegacyReporterAdapter::testRunEnded( TestRunStats const& testRunStats ) {
m_legacyReporter->EndTesting( testRunStats.totals );
}
void LegacyReporterAdapter::skipTest( TestCaseInfo const& ) {
}
}
// #included from: catch_timer.hpp
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wc++11-long-long"
#endif
#ifdef CATCH_PLATFORM_WINDOWS
#include <windows.h>
#else
#include <sys/time.h>
#endif
namespace Catch {
namespace {
#ifdef CATCH_PLATFORM_WINDOWS
uint64_t getCurrentTicks() {
static uint64_t hz=0, hzo=0;
if (!hz) {
QueryPerformanceFrequency( reinterpret_cast<LARGE_INTEGER*>( &hz ) );
QueryPerformanceCounter( reinterpret_cast<LARGE_INTEGER*>( &hzo ) );
}
uint64_t t;
QueryPerformanceCounter( reinterpret_cast<LARGE_INTEGER*>( &t ) );
return ((t-hzo)*1000000)/hz;
}
#else
uint64_t getCurrentTicks() {
timeval t;
gettimeofday(&t,NULL);
return static_cast<uint64_t>( t.tv_sec ) * 1000000ull + static_cast<uint64_t>( t.tv_usec );
}
#endif
}
void Timer::start() {
m_ticks = getCurrentTicks();
}
unsigned int Timer::getElapsedMicroseconds() const {
return static_cast<unsigned int>(getCurrentTicks() - m_ticks);
}
unsigned int Timer::getElapsedMilliseconds() const {
return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
}
double Timer::getElapsedSeconds() const {
return getElapsedMicroseconds()/1000000.0;
}
} // namespace Catch
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// #included from: catch_common.hpp
#define TWOBLUECUBES_CATCH_COMMON_HPP_INCLUDED
namespace Catch {
bool startsWith( std::string const& s, std::string const& prefix ) {
return s.size() >= prefix.size() && s.substr( 0, prefix.size() ) == prefix;
}
bool endsWith( std::string const& s, std::string const& suffix ) {
return s.size() >= suffix.size() && s.substr( s.size()-suffix.size(), suffix.size() ) == suffix;
}
bool contains( std::string const& s, std::string const& infix ) {
return s.find( infix ) != std::string::npos;
}
void toLowerInPlace( std::string& s ) {
std::transform( s.begin(), s.end(), s.begin(), ::tolower );
}
std::string toLower( std::string const& s ) {
std::string lc = s;
toLowerInPlace( lc );
return lc;
}
std::string trim( std::string const& str ) {
static char const* whitespaceChars = "\n\r\t ";
std::string::size_type start = str.find_first_not_of( whitespaceChars );
std::string::size_type end = str.find_last_not_of( whitespaceChars );
return start != std::string::npos ? str.substr( start, 1+end-start ) : "";
}
bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
bool replaced = false;
std::size_t i = str.find( replaceThis );
while( i != std::string::npos ) {
replaced = true;
str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
if( i < str.size()-withThis.size() )
i = str.find( replaceThis, i+withThis.size() );
else
i = std::string::npos;
}
return replaced;
}
pluralise::pluralise( std::size_t count, std::string const& label )
: m_count( count ),
m_label( label )
{}
std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
os << pluraliser.m_count << " " << pluraliser.m_label;
if( pluraliser.m_count != 1 )
os << "s";
return os;
}
SourceLineInfo::SourceLineInfo() : line( 0 ){}
SourceLineInfo::SourceLineInfo( char const* _file, std::size_t _line )
: file( _file ),
line( _line )
{}
SourceLineInfo::SourceLineInfo( SourceLineInfo const& other )
: file( other.file ),
line( other.line )
{}
bool SourceLineInfo::empty() const {
return file.empty();
}
bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const {
return line == other.line && file == other.file;
}
bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const {
return line < other.line || ( line == other.line && file < other.file );
}
std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
#ifndef __GNUG__
os << info.file << "(" << info.line << ")";
#else
os << info.file << ":" << info.line;
#endif
return os;
}
void throwLogicError( std::string const& message, SourceLineInfo const& locationInfo ) {
std::ostringstream oss;
oss << locationInfo << ": Internal Catch error: '" << message << "'";
if( alwaysTrue() )
throw std::logic_error( oss.str() );
}
}
// #included from: catch_section.hpp
#define TWOBLUECUBES_CATCH_SECTION_HPP_INCLUDED
namespace Catch {
SectionInfo::SectionInfo
( SourceLineInfo const& _lineInfo,
std::string const& _name,
std::string const& _description )
: name( _name ),
description( _description ),
lineInfo( _lineInfo )
{}
Section::Section( SectionInfo const& info )
: m_info( info ),
m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
{
m_timer.start();
}
Section::~Section() {
if( m_sectionIncluded )
getResultCapture().sectionEnded( m_info, m_assertions, m_timer.getElapsedSeconds() );
}
// This indicates whether the section should be executed or not
Section::operator bool() const {
return m_sectionIncluded;
}
} // end namespace Catch
// #included from: catch_debugger.hpp
#define TWOBLUECUBES_CATCH_DEBUGGER_HPP_INCLUDED
#include <iostream>
#ifdef CATCH_PLATFORM_MAC
#include <assert.h>
#include <stdbool.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/sysctl.h>
namespace Catch{
// The following function is taken directly from the following technical note:
// http://developer.apple.com/library/mac/#qa/qa2004/qa1361.html
// Returns true if the current process is being debugged (either
// running under the debugger or has a debugger attached post facto).
bool isDebuggerActive(){
int mib[4];
struct kinfo_proc info;
size_t size;
// Initialize the flags so that, if sysctl fails for some bizarre
// reason, we get a predictable result.
info.kp_proc.p_flag = 0;
// Initialize mib, which tells sysctl the info we want, in this case
// we're looking for information about a specific process ID.
mib[0] = CTL_KERN;
mib[1] = KERN_PROC;
mib[2] = KERN_PROC_PID;
mib[3] = getpid();
// Call sysctl.
size = sizeof(info);
if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, NULL, 0) != 0 ) {
Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
return false;
}
// We're being debugged if the P_TRACED flag is set.
return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
}
} // namespace Catch
#elif defined(_MSC_VER)
extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
namespace Catch {
bool isDebuggerActive() {
return IsDebuggerPresent() != 0;
}
}
#elif defined(__MINGW32__)
extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
namespace Catch {
bool isDebuggerActive() {
return IsDebuggerPresent() != 0;
}
}
#else
namespace Catch {
inline bool isDebuggerActive() { return false; }
}
#endif // Platform
#ifdef CATCH_PLATFORM_WINDOWS
extern "C" __declspec(dllimport) void __stdcall OutputDebugStringA( const char* );
namespace Catch {
void writeToDebugConsole( std::string const& text ) {
::OutputDebugStringA( text.c_str() );
}
}
#else
namespace Catch {
void writeToDebugConsole( std::string const& text ) {
// !TBD: Need a version for Mac/ XCode and other IDEs
Catch::cout() << text;
}
}
#endif // Platform
// #included from: catch_to_string.hpp
#define TWOBLUECUBES_CATCH_TOSTRING_HPP_INCLUDED
namespace Catch {
namespace Detail {
std::string unprintableString = "{?}";
namespace {
struct Endianness {
enum Arch { Big, Little };
static Arch which() {
union _{
int asInt;
char asChar[sizeof (int)];
} u;
u.asInt = 1;
return ( u.asChar[sizeof(int)-1] == 1 ) ? Big : Little;
}
};
}
std::string rawMemoryToString( const void *object, std::size_t size )
{
// Reverse order for little endian architectures
int i = 0, end = static_cast<int>( size ), inc = 1;
if( Endianness::which() == Endianness::Little ) {
i = end-1;
end = inc = -1;
}
unsigned char const *bytes = static_cast<unsigned char const *>(object);
std::ostringstream os;
os << "0x" << std::setfill('0') << std::hex;
for( ; i != end; i += inc )
os << std::setw(2) << static_cast<unsigned>(bytes[i]);
return os.str();
}
}
std::string toString( std::string const& value ) {
std::string s = value;
if( getCurrentContext().getConfig()->showInvisibles() ) {
for(size_t i = 0; i < s.size(); ++i ) {
std::string subs;
switch( s[i] ) {
case '\n': subs = "\\n"; break;
case '\t': subs = "\\t"; break;
default: break;
}
if( !subs.empty() ) {
s = s.substr( 0, i ) + subs + s.substr( i+1 );
++i;
}
}
}
return "\"" + s + "\"";
}
std::string toString( std::wstring const& value ) {
std::string s;
s.reserve( value.size() );
for(size_t i = 0; i < value.size(); ++i )
s += value[i] <= 0xff ? static_cast<char>( value[i] ) : '?';
return Catch::toString( s );
}
std::string toString( const char* const value ) {
return value ? Catch::toString( std::string( value ) ) : std::string( "{null string}" );
}
std::string toString( char* const value ) {
return Catch::toString( static_cast<const char*>( value ) );
}
std::string toString( const wchar_t* const value )
{
return value ? Catch::toString( std::wstring(value) ) : std::string( "{null string}" );
}
std::string toString( wchar_t* const value )
{
return Catch::toString( static_cast<const wchar_t*>( value ) );
}
std::string toString( int value ) {
std::ostringstream oss;
oss << value;
if( value >= 255 )
oss << " (0x" << std::hex << value << ")";
return oss.str();
}
std::string toString( unsigned long value ) {
std::ostringstream oss;
oss << value;
if( value >= 255 )
oss << " (0x" << std::hex << value << ")";
return oss.str();
}
std::string toString( unsigned int value ) {
return Catch::toString( static_cast<unsigned long>( value ) );
}
template<typename T>
std::string fpToString( T value, int precision ) {
std::ostringstream oss;
oss << std::setprecision( precision )
<< std::fixed
<< value;
std::string d = oss.str();
std::size_t i = d.find_last_not_of( '0' );
if( i != std::string::npos && i != d.size()-1 ) {
if( d[i] == '.' )
i++;
d = d.substr( 0, i+1 );
}
return d;
}
std::string toString( const double value ) {
return fpToString( value, 10 );
}
std::string toString( const float value ) {
return fpToString( value, 5 ) + "f";
}
std::string toString( bool value ) {
return value ? "true" : "false";
}
std::string toString( char value ) {
return value < ' '
? toString( static_cast<unsigned int>( value ) )
: Detail::makeString( value );
}
std::string toString( signed char value ) {
return toString( static_cast<char>( value ) );
}
std::string toString( unsigned char value ) {
return toString( static_cast<char>( value ) );
}
#ifdef CATCH_CONFIG_CPP11_NULLPTR
std::string toString( std::nullptr_t ) {
return "nullptr";
}
#endif
#ifdef __OBJC__
std::string toString( NSString const * const& nsstring ) {
if( !nsstring )
return "nil";
return "@" + toString([nsstring UTF8String]);
}
std::string toString( NSString * CATCH_ARC_STRONG const& nsstring ) {
if( !nsstring )
return "nil";
return "@" + toString([nsstring UTF8String]);
}
std::string toString( NSObject* const& nsObject ) {
return toString( [nsObject description] );
}
#endif
} // end namespace Catch
// #included from: catch_result_builder.hpp
#define TWOBLUECUBES_CATCH_RESULT_BUILDER_HPP_INCLUDED
namespace Catch {
ResultBuilder::ResultBuilder( char const* macroName,
SourceLineInfo const& lineInfo,
char const* capturedExpression,
ResultDisposition::Flags resultDisposition )
: m_assertionInfo( macroName, lineInfo, capturedExpression, resultDisposition ),
m_shouldDebugBreak( false ),
m_shouldThrow( false )
{}
ResultBuilder& ResultBuilder::setResultType( ResultWas::OfType result ) {
m_data.resultType = result;
return *this;
}
ResultBuilder& ResultBuilder::setResultType( bool result ) {
m_data.resultType = result ? ResultWas::Ok : ResultWas::ExpressionFailed;
return *this;
}
ResultBuilder& ResultBuilder::setLhs( std::string const& lhs ) {
m_exprComponents.lhs = lhs;
return *this;
}
ResultBuilder& ResultBuilder::setRhs( std::string const& rhs ) {
m_exprComponents.rhs = rhs;
return *this;
}
ResultBuilder& ResultBuilder::setOp( std::string const& op ) {
m_exprComponents.op = op;
return *this;
}
void ResultBuilder::endExpression() {
m_exprComponents.testFalse = isFalseTest( m_assertionInfo.resultDisposition );
captureExpression();
}
void ResultBuilder::useActiveException( ResultDisposition::Flags resultDisposition ) {
m_assertionInfo.resultDisposition = resultDisposition;
m_stream.oss << Catch::translateActiveException();
captureResult( ResultWas::ThrewException );
}
void ResultBuilder::captureResult( ResultWas::OfType resultType ) {
setResultType( resultType );
captureExpression();
}
void ResultBuilder::captureExpression() {
AssertionResult result = build();
getResultCapture().assertionEnded( result );
if( !result.isOk() ) {
if( getCurrentContext().getConfig()->shouldDebugBreak() )
m_shouldDebugBreak = true;
if( getCurrentContext().getRunner()->aborting() || (m_assertionInfo.resultDisposition & ResultDisposition::Normal) )
m_shouldThrow = true;
}
}
void ResultBuilder::react() {
if( m_shouldThrow )
throw Catch::TestFailureException();
}
bool ResultBuilder::shouldDebugBreak() const { return m_shouldDebugBreak; }
bool ResultBuilder::allowThrows() const { return getCurrentContext().getConfig()->allowThrows(); }
AssertionResult ResultBuilder::build() const
{
assert( m_data.resultType != ResultWas::Unknown );
AssertionResultData data = m_data;
// Flip bool results if testFalse is set
if( m_exprComponents.testFalse ) {
if( data.resultType == ResultWas::Ok )
data.resultType = ResultWas::ExpressionFailed;
else if( data.resultType == ResultWas::ExpressionFailed )
data.resultType = ResultWas::Ok;
}
data.message = m_stream.oss.str();
data.reconstructedExpression = reconstructExpression();
if( m_exprComponents.testFalse ) {
if( m_exprComponents.op == "" )
data.reconstructedExpression = "!" + data.reconstructedExpression;
else
data.reconstructedExpression = "!(" + data.reconstructedExpression + ")";
}
return AssertionResult( m_assertionInfo, data );
}
std::string ResultBuilder::reconstructExpression() const {
if( m_exprComponents.op == "" )
return m_exprComponents.lhs.empty() ? m_assertionInfo.capturedExpression : m_exprComponents.op + m_exprComponents.lhs;
else if( m_exprComponents.op == "matches" )
return m_exprComponents.lhs + " " + m_exprComponents.rhs;
else if( m_exprComponents.op != "!" ) {
if( m_exprComponents.lhs.size() + m_exprComponents.rhs.size() < 40 &&
m_exprComponents.lhs.find("\n") == std::string::npos &&
m_exprComponents.rhs.find("\n") == std::string::npos )
return m_exprComponents.lhs + " " + m_exprComponents.op + " " + m_exprComponents.rhs;
else
return m_exprComponents.lhs + "\n" + m_exprComponents.op + "\n" + m_exprComponents.rhs;
}
else
return "{can't expand - use " + m_assertionInfo.macroName + "_FALSE( " + m_assertionInfo.capturedExpression.substr(1) + " ) instead of " + m_assertionInfo.macroName + "( " + m_assertionInfo.capturedExpression + " ) for better diagnostics}";
}
} // end namespace Catch
// #included from: catch_tag_alias_registry.hpp
#define TWOBLUECUBES_CATCH_TAG_ALIAS_REGISTRY_HPP_INCLUDED
// #included from: catch_tag_alias_registry.h
#define TWOBLUECUBES_CATCH_TAG_ALIAS_REGISTRY_H_INCLUDED
#include <map>
namespace Catch {
class TagAliasRegistry : public ITagAliasRegistry {
public:
virtual ~TagAliasRegistry();
virtual Option<TagAlias> find( std::string const& alias ) const;
virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const;
void add( char const* alias, char const* tag, SourceLineInfo const& lineInfo );
static TagAliasRegistry& get();
private:
std::map<std::string, TagAlias> m_registry;
};
} // end namespace Catch
#include <map>
#include <iostream>
namespace Catch {
TagAliasRegistry::~TagAliasRegistry() {}
Option<TagAlias> TagAliasRegistry::find( std::string const& alias ) const {
std::map<std::string, TagAlias>::const_iterator it = m_registry.find( alias );
if( it != m_registry.end() )
return it->second;
else
return Option<TagAlias>();
}
std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const {
std::string expandedTestSpec = unexpandedTestSpec;
for( std::map<std::string, TagAlias>::const_iterator it = m_registry.begin(), itEnd = m_registry.end();
it != itEnd;
++it ) {
std::size_t pos = expandedTestSpec.find( it->first );
if( pos != std::string::npos ) {
expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
it->second.tag +
expandedTestSpec.substr( pos + it->first.size() );
}
}
return expandedTestSpec;
}
void TagAliasRegistry::add( char const* alias, char const* tag, SourceLineInfo const& lineInfo ) {
if( !startsWith( alias, "[@" ) || !endsWith( alias, "]" ) ) {
std::ostringstream oss;
oss << "error: tag alias, \"" << alias << "\" is not of the form [@alias name].\n" << lineInfo;
throw std::domain_error( oss.str().c_str() );
}
if( !m_registry.insert( std::make_pair( alias, TagAlias( tag, lineInfo ) ) ).second ) {
std::ostringstream oss;
oss << "error: tag alias, \"" << alias << "\" already registered.\n"
<< "\tFirst seen at " << find(alias)->lineInfo << "\n"
<< "\tRedefined at " << lineInfo;
throw std::domain_error( oss.str().c_str() );
}
}
TagAliasRegistry& TagAliasRegistry::get() {
static TagAliasRegistry instance;
return instance;
}
ITagAliasRegistry::~ITagAliasRegistry() {}
ITagAliasRegistry const& ITagAliasRegistry::get() { return TagAliasRegistry::get(); }
RegistrarForTagAliases::RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo ) {
try {
TagAliasRegistry::get().add( alias, tag, lineInfo );
}
catch( std::exception& ex ) {
Colour colourGuard( Colour::Red );
Catch::cerr() << ex.what() << std::endl;
exit(1);
}
}
} // end namespace Catch
// #included from: ../reporters/catch_reporter_xml.hpp
#define TWOBLUECUBES_CATCH_REPORTER_XML_HPP_INCLUDED
// #included from: catch_reporter_bases.hpp
#define TWOBLUECUBES_CATCH_REPORTER_BASES_HPP_INCLUDED
#include <cstring>
namespace Catch {
struct StreamingReporterBase : SharedImpl<IStreamingReporter> {
StreamingReporterBase( ReporterConfig const& _config )
: m_config( _config.fullConfig() ),
stream( _config.stream() )
{}
virtual ~StreamingReporterBase();
virtual void noMatchingTestCases( std::string const& ) {}
virtual void testRunStarting( TestRunInfo const& _testRunInfo ) {
currentTestRunInfo = _testRunInfo;
}
virtual void testGroupStarting( GroupInfo const& _groupInfo ) {
currentGroupInfo = _groupInfo;
}
virtual void testCaseStarting( TestCaseInfo const& _testInfo ) {
currentTestCaseInfo = _testInfo;
}
virtual void sectionStarting( SectionInfo const& _sectionInfo ) {
m_sectionStack.push_back( _sectionInfo );
}
virtual void sectionEnded( SectionStats const& /* _sectionStats */ ) {
m_sectionStack.pop_back();
}
virtual void testCaseEnded( TestCaseStats const& /* _testCaseStats */ ) {
currentTestCaseInfo.reset();
}
virtual void testGroupEnded( TestGroupStats const& /* _testGroupStats */ ) {
currentGroupInfo.reset();
}
virtual void testRunEnded( TestRunStats const& /* _testRunStats */ ) {
currentTestCaseInfo.reset();
currentGroupInfo.reset();
currentTestRunInfo.reset();
}
virtual void skipTest( TestCaseInfo const& ) {
// Don't do anything with this by default.
// It can optionally be overridden in the derived class.
}
Ptr<IConfig> m_config;
std::ostream& stream;
LazyStat<TestRunInfo> currentTestRunInfo;
LazyStat<GroupInfo> currentGroupInfo;
LazyStat<TestCaseInfo> currentTestCaseInfo;
std::vector<SectionInfo> m_sectionStack;
};
struct CumulativeReporterBase : SharedImpl<IStreamingReporter> {
template<typename T, typename ChildNodeT>
struct Node : SharedImpl<> {
explicit Node( T const& _value ) : value( _value ) {}
virtual ~Node() {}
typedef std::vector<Ptr<ChildNodeT> > ChildNodes;
T value;
ChildNodes children;
};
struct SectionNode : SharedImpl<> {
explicit SectionNode( SectionStats const& _stats ) : stats( _stats ) {}
virtual ~SectionNode();
bool operator == ( SectionNode const& other ) const {
return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
}
bool operator == ( Ptr<SectionNode> const& other ) const {
return operator==( *other );
}
SectionStats stats;
typedef std::vector<Ptr<SectionNode> > ChildSections;
typedef std::vector<AssertionStats> Assertions;
ChildSections childSections;
Assertions assertions;
std::string stdOut;
std::string stdErr;
};
struct BySectionInfo {
BySectionInfo( SectionInfo const& other ) : m_other( other ) {}
BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {}
bool operator() ( Ptr<SectionNode> const& node ) const {
return node->stats.sectionInfo.lineInfo == m_other.lineInfo;
}
private:
void operator=( BySectionInfo const& );
SectionInfo const& m_other;
};
typedef Node<TestCaseStats, SectionNode> TestCaseNode;
typedef Node<TestGroupStats, TestCaseNode> TestGroupNode;
typedef Node<TestRunStats, TestGroupNode> TestRunNode;
CumulativeReporterBase( ReporterConfig const& _config )
: m_config( _config.fullConfig() ),
stream( _config.stream() )
{}
~CumulativeReporterBase();
virtual void testRunStarting( TestRunInfo const& ) {}
virtual void testGroupStarting( GroupInfo const& ) {}
virtual void testCaseStarting( TestCaseInfo const& ) {}
virtual void sectionStarting( SectionInfo const& sectionInfo ) {
SectionStats incompleteStats( sectionInfo, Counts(), 0, false );
Ptr<SectionNode> node;
if( m_sectionStack.empty() ) {
if( !m_rootSection )
m_rootSection = new SectionNode( incompleteStats );
node = m_rootSection;
}
else {
SectionNode& parentNode = *m_sectionStack.back();
SectionNode::ChildSections::const_iterator it =
std::find_if( parentNode.childSections.begin(),
parentNode.childSections.end(),
BySectionInfo( sectionInfo ) );
if( it == parentNode.childSections.end() ) {
node = new SectionNode( incompleteStats );
parentNode.childSections.push_back( node );
}
else
node = *it;
}
m_sectionStack.push_back( node );
m_deepestSection = node;
}
virtual void assertionStarting( AssertionInfo const& ) {}
virtual bool assertionEnded( AssertionStats const& assertionStats ) {
assert( !m_sectionStack.empty() );
SectionNode& sectionNode = *m_sectionStack.back();
sectionNode.assertions.push_back( assertionStats );
return true;
}
virtual void sectionEnded( SectionStats const& sectionStats ) {
assert( !m_sectionStack.empty() );
SectionNode& node = *m_sectionStack.back();
node.stats = sectionStats;
m_sectionStack.pop_back();
}
virtual void testCaseEnded( TestCaseStats const& testCaseStats ) {
Ptr<TestCaseNode> node = new TestCaseNode( testCaseStats );
assert( m_sectionStack.size() == 0 );
node->children.push_back( m_rootSection );
m_testCases.push_back( node );
m_rootSection.reset();
assert( m_deepestSection );
m_deepestSection->stdOut = testCaseStats.stdOut;
m_deepestSection->stdErr = testCaseStats.stdErr;
}
virtual void testGroupEnded( TestGroupStats const& testGroupStats ) {
Ptr<TestGroupNode> node = new TestGroupNode( testGroupStats );
node->children.swap( m_testCases );
m_testGroups.push_back( node );
}
virtual void testRunEnded( TestRunStats const& testRunStats ) {
Ptr<TestRunNode> node = new TestRunNode( testRunStats );
node->children.swap( m_testGroups );
m_testRuns.push_back( node );
testRunEndedCumulative();
}
virtual void testRunEndedCumulative() = 0;
virtual void skipTest( TestCaseInfo const& ) {}
Ptr<IConfig> m_config;
std::ostream& stream;
std::vector<AssertionStats> m_assertions;
std::vector<std::vector<Ptr<SectionNode> > > m_sections;
std::vector<Ptr<TestCaseNode> > m_testCases;
std::vector<Ptr<TestGroupNode> > m_testGroups;
std::vector<Ptr<TestRunNode> > m_testRuns;
Ptr<SectionNode> m_rootSection;
Ptr<SectionNode> m_deepestSection;
std::vector<Ptr<SectionNode> > m_sectionStack;
};
template<char C>
char const* getLineOfChars() {
static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
if( !*line ) {
memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
}
return line;
}
} // end namespace Catch
// #included from: ../internal/catch_reporter_registrars.hpp
#define TWOBLUECUBES_CATCH_REPORTER_REGISTRARS_HPP_INCLUDED
namespace Catch {
template<typename T>
class LegacyReporterRegistrar {
class ReporterFactory : public IReporterFactory {
virtual IStreamingReporter* create( ReporterConfig const& config ) const {
return new LegacyReporterAdapter( new T( config ) );
}
virtual std::string getDescription() const {
return T::getDescription();
}
};
public:
LegacyReporterRegistrar( std::string const& name ) {
getMutableRegistryHub().registerReporter( name, new ReporterFactory() );
}
};
template<typename T>
class ReporterRegistrar {
class ReporterFactory : public IReporterFactory {
// *** Please Note ***:
// - If you end up here looking at a compiler error because it's trying to register
// your custom reporter class be aware that the native reporter interface has changed
// to IStreamingReporter. The "legacy" interface, IReporter, is still supported via
// an adapter. Just use REGISTER_LEGACY_REPORTER to take advantage of the adapter.
// However please consider updating to the new interface as the old one is now
// deprecated and will probably be removed quite soon!
// Please contact me via github if you have any questions at all about this.
// In fact, ideally, please contact me anyway to let me know you've hit this - as I have
// no idea who is actually using custom reporters at all (possibly no-one!).
// The new interface is designed to minimise exposure to interface changes in the future.
virtual IStreamingReporter* create( ReporterConfig const& config ) const {
return new T( config );
}
virtual std::string getDescription() const {
return T::getDescription();
}
};
public:
ReporterRegistrar( std::string const& name ) {
getMutableRegistryHub().registerReporter( name, new ReporterFactory() );
}
};
}
#define INTERNAL_CATCH_REGISTER_LEGACY_REPORTER( name, reporterType ) \
namespace{ Catch::LegacyReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); }
#define INTERNAL_CATCH_REGISTER_REPORTER( name, reporterType ) \
namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); }
// #included from: ../internal/catch_xmlwriter.hpp
#define TWOBLUECUBES_CATCH_XMLWRITER_HPP_INCLUDED
#include <sstream>
#include <string>
#include <vector>
namespace Catch {
class XmlWriter {
public:
class ScopedElement {
public:
ScopedElement( XmlWriter* writer )
: m_writer( writer )
{}
ScopedElement( ScopedElement const& other )
: m_writer( other.m_writer ){
other.m_writer = NULL;
}
~ScopedElement() {
if( m_writer )
m_writer->endElement();
}
ScopedElement& writeText( std::string const& text, bool indent = true ) {
m_writer->writeText( text, indent );
return *this;
}
template<typename T>
ScopedElement& writeAttribute( std::string const& name, T const& attribute ) {
m_writer->writeAttribute( name, attribute );
return *this;
}
private:
mutable XmlWriter* m_writer;
};
XmlWriter()
: m_tagIsOpen( false ),
m_needsNewline( false ),
m_os( &Catch::cout() )
{}
XmlWriter( std::ostream& os )
: m_tagIsOpen( false ),
m_needsNewline( false ),
m_os( &os )
{}
~XmlWriter() {
while( !m_tags.empty() )
endElement();
}
XmlWriter& startElement( std::string const& name ) {
ensureTagClosed();
newlineIfNecessary();
stream() << m_indent << "<" << name;
m_tags.push_back( name );
m_indent += " ";
m_tagIsOpen = true;
return *this;
}
ScopedElement scopedElement( std::string const& name ) {
ScopedElement scoped( this );
startElement( name );
return scoped;
}
XmlWriter& endElement() {
newlineIfNecessary();
m_indent = m_indent.substr( 0, m_indent.size()-2 );
if( m_tagIsOpen ) {
stream() << "/>\n";
m_tagIsOpen = false;
}
else {
stream() << m_indent << "</" << m_tags.back() << ">\n";
}
m_tags.pop_back();
return *this;
}
XmlWriter& writeAttribute( std::string const& name, std::string const& attribute ) {
if( !name.empty() && !attribute.empty() ) {
stream() << " " << name << "=\"";
writeEncodedText( attribute );
stream() << "\"";
}
return *this;
}
XmlWriter& writeAttribute( std::string const& name, bool attribute ) {
stream() << " " << name << "=\"" << ( attribute ? "true" : "false" ) << "\"";
return *this;
}
template<typename T>
XmlWriter& writeAttribute( std::string const& name, T const& attribute ) {
if( !name.empty() )
stream() << " " << name << "=\"" << attribute << "\"";
return *this;
}
XmlWriter& writeText( std::string const& text, bool indent = true ) {
if( !text.empty() ){
bool tagWasOpen = m_tagIsOpen;
ensureTagClosed();
if( tagWasOpen && indent )
stream() << m_indent;
writeEncodedText( text );
m_needsNewline = true;
}
return *this;
}
XmlWriter& writeComment( std::string const& text ) {
ensureTagClosed();
stream() << m_indent << "<!--" << text << "-->";
m_needsNewline = true;
return *this;
}
XmlWriter& writeBlankLine() {
ensureTagClosed();
stream() << "\n";
return *this;
}
void setStream( std::ostream& os ) {
m_os = &os;
}
private:
XmlWriter( XmlWriter const& );
void operator=( XmlWriter const& );
std::ostream& stream() {
return *m_os;
}
void ensureTagClosed() {
if( m_tagIsOpen ) {
stream() << ">\n";
m_tagIsOpen = false;
}
}
void newlineIfNecessary() {
if( m_needsNewline ) {
stream() << "\n";
m_needsNewline = false;
}
}
void writeEncodedText( std::string const& text ) {
static const char* charsToEncode = "<&\"";
std::string mtext = text;
std::string::size_type pos = mtext.find_first_of( charsToEncode );
while( pos != std::string::npos ) {
stream() << mtext.substr( 0, pos );
switch( mtext[pos] ) {
case '<':
stream() << "<";
break;
case '&':
stream() << "&";
break;
case '\"':
stream() << """;
break;
}
mtext = mtext.substr( pos+1 );
pos = mtext.find_first_of( charsToEncode );
}
stream() << mtext;
}
bool m_tagIsOpen;
bool m_needsNewline;
std::vector<std::string> m_tags;
std::string m_indent;
std::ostream* m_os;
};
}
namespace Catch {
class XmlReporter : public StreamingReporterBase {
public:
XmlReporter( ReporterConfig const& _config )
: StreamingReporterBase( _config ),
m_sectionDepth( 0 )
{}
virtual ~XmlReporter();
static std::string getDescription() {
return "Reports test results as an XML document";
}
public: // StreamingReporterBase
virtual ReporterPreferences getPreferences() const {
ReporterPreferences prefs;
prefs.shouldRedirectStdOut = true;
return prefs;
}
virtual void noMatchingTestCases( std::string const& s ) {
StreamingReporterBase::noMatchingTestCases( s );
}
virtual void testRunStarting( TestRunInfo const& testInfo ) {
StreamingReporterBase::testRunStarting( testInfo );
m_xml.setStream( stream );
m_xml.startElement( "Catch" );
if( !m_config->name().empty() )
m_xml.writeAttribute( "name", m_config->name() );
}
virtual void testGroupStarting( GroupInfo const& groupInfo ) {
StreamingReporterBase::testGroupStarting( groupInfo );
m_xml.startElement( "Group" )
.writeAttribute( "name", groupInfo.name );
}
virtual void testCaseStarting( TestCaseInfo const& testInfo ) {
StreamingReporterBase::testCaseStarting(testInfo);
m_xml.startElement( "TestCase" ).writeAttribute( "name", trim( testInfo.name ) );
if ( m_config->showDurations() == ShowDurations::Always )
m_testCaseTimer.start();
}
virtual void sectionStarting( SectionInfo const& sectionInfo ) {
StreamingReporterBase::sectionStarting( sectionInfo );
if( m_sectionDepth++ > 0 ) {
m_xml.startElement( "Section" )
.writeAttribute( "name", trim( sectionInfo.name ) )
.writeAttribute( "description", sectionInfo.description );
}
}
virtual void assertionStarting( AssertionInfo const& ) { }
virtual bool assertionEnded( AssertionStats const& assertionStats ) {
const AssertionResult& assertionResult = assertionStats.assertionResult;
// Print any info messages in <Info> tags.
if( assertionStats.assertionResult.getResultType() != ResultWas::Ok ) {
for( std::vector<MessageInfo>::const_iterator it = assertionStats.infoMessages.begin(), itEnd = assertionStats.infoMessages.end();
it != itEnd;
++it ) {
if( it->type == ResultWas::Info ) {
m_xml.scopedElement( "Info" )
.writeText( it->message );
} else if ( it->type == ResultWas::Warning ) {
m_xml.scopedElement( "Warning" )
.writeText( it->message );
}
}
}
// Drop out if result was successful but we're not printing them.
if( !m_config->includeSuccessfulResults() && isOk(assertionResult.getResultType()) )
return true;
// Print the expression if there is one.
if( assertionResult.hasExpression() ) {
m_xml.startElement( "Expression" )
.writeAttribute( "success", assertionResult.succeeded() )
.writeAttribute( "type", assertionResult.getTestMacroName() )
.writeAttribute( "filename", assertionResult.getSourceInfo().file )
.writeAttribute( "line", assertionResult.getSourceInfo().line );
m_xml.scopedElement( "Original" )
.writeText( assertionResult.getExpression() );
m_xml.scopedElement( "Expanded" )
.writeText( assertionResult.getExpandedExpression() );
}
// And... Print a result applicable to each result type.
switch( assertionResult.getResultType() ) {
case ResultWas::ThrewException:
m_xml.scopedElement( "Exception" )
.writeAttribute( "filename", assertionResult.getSourceInfo().file )
.writeAttribute( "line", assertionResult.getSourceInfo().line )
.writeText( assertionResult.getMessage() );
break;
case ResultWas::FatalErrorCondition:
m_xml.scopedElement( "Fatal Error Condition" )
.writeAttribute( "filename", assertionResult.getSourceInfo().file )
.writeAttribute( "line", assertionResult.getSourceInfo().line )
.writeText( assertionResult.getMessage() );
break;
case ResultWas::Info:
m_xml.scopedElement( "Info" )
.writeText( assertionResult.getMessage() );
break;
case ResultWas::Warning:
// Warning will already have been written
break;
case ResultWas::ExplicitFailure:
m_xml.scopedElement( "Failure" )
.writeText( assertionResult.getMessage() );
break;
default:
break;
}
if( assertionResult.hasExpression() )
m_xml.endElement();
return true;
}
virtual void sectionEnded( SectionStats const& sectionStats ) {
StreamingReporterBase::sectionEnded( sectionStats );
if( --m_sectionDepth > 0 ) {
XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" );
e.writeAttribute( "successes", sectionStats.assertions.passed );
e.writeAttribute( "failures", sectionStats.assertions.failed );
e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk );
if ( m_config->showDurations() == ShowDurations::Always )
e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds );
m_xml.endElement();
}
}
virtual void testCaseEnded( TestCaseStats const& testCaseStats ) {
StreamingReporterBase::testCaseEnded( testCaseStats );
XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" );
e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() );
if ( m_config->showDurations() == ShowDurations::Always )
e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
m_xml.endElement();
}
virtual void testGroupEnded( TestGroupStats const& testGroupStats ) {
StreamingReporterBase::testGroupEnded( testGroupStats );
// TODO: Check testGroupStats.aborting and act accordingly.
m_xml.scopedElement( "OverallResults" )
.writeAttribute( "successes", testGroupStats.totals.assertions.passed )
.writeAttribute( "failures", testGroupStats.totals.assertions.failed )
.writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk );
m_xml.endElement();
}
virtual void testRunEnded( TestRunStats const& testRunStats ) {
StreamingReporterBase::testRunEnded( testRunStats );
m_xml.scopedElement( "OverallResults" )
.writeAttribute( "successes", testRunStats.totals.assertions.passed )
.writeAttribute( "failures", testRunStats.totals.assertions.failed )
.writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk );
m_xml.endElement();
}
private:
Timer m_testCaseTimer;
XmlWriter m_xml;
int m_sectionDepth;
};
INTERNAL_CATCH_REGISTER_REPORTER( "xml", XmlReporter )
} // end namespace Catch
// #included from: ../reporters/catch_reporter_junit.hpp
#define TWOBLUECUBES_CATCH_REPORTER_JUNIT_HPP_INCLUDED
#include <assert.h>
namespace Catch {
class JunitReporter : public CumulativeReporterBase {
public:
JunitReporter( ReporterConfig const& _config )
: CumulativeReporterBase( _config ),
xml( _config.stream() )
{}
~JunitReporter();
static std::string getDescription() {
return "Reports test results in an XML format that looks like Ant's junitreport target";
}
virtual void noMatchingTestCases( std::string const& /*spec*/ ) {}
virtual ReporterPreferences getPreferences() const {
ReporterPreferences prefs;
prefs.shouldRedirectStdOut = true;
return prefs;
}
virtual void testRunStarting( TestRunInfo const& runInfo ) {
CumulativeReporterBase::testRunStarting( runInfo );
xml.startElement( "testsuites" );
}
virtual void testGroupStarting( GroupInfo const& groupInfo ) {
suiteTimer.start();
stdOutForSuite.str("");
stdErrForSuite.str("");
unexpectedExceptions = 0;
CumulativeReporterBase::testGroupStarting( groupInfo );
}
virtual bool assertionEnded( AssertionStats const& assertionStats ) {
if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException )
unexpectedExceptions++;
return CumulativeReporterBase::assertionEnded( assertionStats );
}
virtual void testCaseEnded( TestCaseStats const& testCaseStats ) {
stdOutForSuite << testCaseStats.stdOut;
stdErrForSuite << testCaseStats.stdErr;
CumulativeReporterBase::testCaseEnded( testCaseStats );
}
virtual void testGroupEnded( TestGroupStats const& testGroupStats ) {
double suiteTime = suiteTimer.getElapsedSeconds();
CumulativeReporterBase::testGroupEnded( testGroupStats );
writeGroup( *m_testGroups.back(), suiteTime );
}
virtual void testRunEndedCumulative() {
xml.endElement();
}
void writeGroup( TestGroupNode const& groupNode, double suiteTime ) {
XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" );
TestGroupStats const& stats = groupNode.value;
xml.writeAttribute( "name", stats.groupInfo.name );
xml.writeAttribute( "errors", unexpectedExceptions );
xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions );
xml.writeAttribute( "tests", stats.totals.assertions.total() );
xml.writeAttribute( "hostname", "tbd" ); // !TBD
if( m_config->showDurations() == ShowDurations::Never )
xml.writeAttribute( "time", "" );
else
xml.writeAttribute( "time", suiteTime );
xml.writeAttribute( "timestamp", "tbd" ); // !TBD
// Write test cases
for( TestGroupNode::ChildNodes::const_iterator
it = groupNode.children.begin(), itEnd = groupNode.children.end();
it != itEnd;
++it )
writeTestCase( **it );
xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite.str() ), false );
xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite.str() ), false );
}
void writeTestCase( TestCaseNode const& testCaseNode ) {
TestCaseStats const& stats = testCaseNode.value;
// All test cases have exactly one section - which represents the
// test case itself. That section may have 0-n nested sections
assert( testCaseNode.children.size() == 1 );
SectionNode const& rootSection = *testCaseNode.children.front();
std::string className = stats.testInfo.className;
if( className.empty() ) {
if( rootSection.childSections.empty() )
className = "global";
}
writeSection( className, "", rootSection );
}
void writeSection( std::string const& className,
std::string const& rootName,
SectionNode const& sectionNode ) {
std::string name = trim( sectionNode.stats.sectionInfo.name );
if( !rootName.empty() )
name = rootName + "/" + name;
if( !sectionNode.assertions.empty() ||
!sectionNode.stdOut.empty() ||
!sectionNode.stdErr.empty() ) {
XmlWriter::ScopedElement e = xml.scopedElement( "testcase" );
if( className.empty() ) {
xml.writeAttribute( "classname", name );
xml.writeAttribute( "name", "root" );
}
else {
xml.writeAttribute( "classname", className );
xml.writeAttribute( "name", name );
}
xml.writeAttribute( "time", Catch::toString( sectionNode.stats.durationInSeconds ) );
writeAssertions( sectionNode );
if( !sectionNode.stdOut.empty() )
xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), false );
if( !sectionNode.stdErr.empty() )
xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), false );
}
for( SectionNode::ChildSections::const_iterator
it = sectionNode.childSections.begin(),
itEnd = sectionNode.childSections.end();
it != itEnd;
++it )
if( className.empty() )
writeSection( name, "", **it );
else
writeSection( className, name, **it );
}
void writeAssertions( SectionNode const& sectionNode ) {
for( SectionNode::Assertions::const_iterator
it = sectionNode.assertions.begin(), itEnd = sectionNode.assertions.end();
it != itEnd;
++it )
writeAssertion( *it );
}
void writeAssertion( AssertionStats const& stats ) {
AssertionResult const& result = stats.assertionResult;
if( !result.isOk() ) {
std::string elementName;
switch( result.getResultType() ) {
case ResultWas::ThrewException:
case ResultWas::FatalErrorCondition:
elementName = "error";
break;
case ResultWas::ExplicitFailure:
elementName = "failure";
break;
case ResultWas::ExpressionFailed:
elementName = "failure";
break;
case ResultWas::DidntThrowException:
elementName = "failure";
break;
// We should never see these here:
case ResultWas::Info:
case ResultWas::Warning:
case ResultWas::Ok:
case ResultWas::Unknown:
case ResultWas::FailureBit:
case ResultWas::Exception:
elementName = "internalError";
break;
}
XmlWriter::ScopedElement e = xml.scopedElement( elementName );
xml.writeAttribute( "message", result.getExpandedExpression() );
xml.writeAttribute( "type", result.getTestMacroName() );
std::ostringstream oss;
if( !result.getMessage().empty() )
oss << result.getMessage() << "\n";
for( std::vector<MessageInfo>::const_iterator
it = stats.infoMessages.begin(),
itEnd = stats.infoMessages.end();
it != itEnd;
++it )
if( it->type == ResultWas::Info )
oss << it->message << "\n";
oss << "at " << result.getSourceInfo();
xml.writeText( oss.str(), false );
}
}
XmlWriter xml;
Timer suiteTimer;
std::ostringstream stdOutForSuite;
std::ostringstream stdErrForSuite;
unsigned int unexpectedExceptions;
};
INTERNAL_CATCH_REGISTER_REPORTER( "junit", JunitReporter )
} // end namespace Catch
// #included from: ../reporters/catch_reporter_console.hpp
#define TWOBLUECUBES_CATCH_REPORTER_CONSOLE_HPP_INCLUDED
namespace Catch {
struct ConsoleReporter : StreamingReporterBase {
ConsoleReporter( ReporterConfig const& _config )
: StreamingReporterBase( _config ),
m_headerPrinted( false )
{}
virtual ~ConsoleReporter();
static std::string getDescription() {
return "Reports test results as plain lines of text";
}
virtual ReporterPreferences getPreferences() const {
ReporterPreferences prefs;
prefs.shouldRedirectStdOut = false;
return prefs;
}
virtual void noMatchingTestCases( std::string const& spec ) {
stream << "No test cases matched '" << spec << "'" << std::endl;
}
virtual void assertionStarting( AssertionInfo const& ) {
}
virtual bool assertionEnded( AssertionStats const& _assertionStats ) {
AssertionResult const& result = _assertionStats.assertionResult;
bool printInfoMessages = true;
// Drop out if result was successful and we're not printing those
if( !m_config->includeSuccessfulResults() && result.isOk() ) {
if( result.getResultType() != ResultWas::Warning )
return false;
printInfoMessages = false;
}
lazyPrint();
AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
printer.print();
stream << std::endl;
return true;
}
virtual void sectionStarting( SectionInfo const& _sectionInfo ) {
m_headerPrinted = false;
StreamingReporterBase::sectionStarting( _sectionInfo );
}
virtual void sectionEnded( SectionStats const& _sectionStats ) {
if( _sectionStats.missingAssertions ) {
lazyPrint();
Colour colour( Colour::ResultError );
if( m_sectionStack.size() > 1 )
stream << "\nNo assertions in section";
else
stream << "\nNo assertions in test case";
stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
}
if( m_headerPrinted ) {
if( m_config->showDurations() == ShowDurations::Always )
stream << "Completed in " << _sectionStats.durationInSeconds << "s" << std::endl;
m_headerPrinted = false;
}
else {
if( m_config->showDurations() == ShowDurations::Always )
stream << _sectionStats.sectionInfo.name << " completed in " << _sectionStats.durationInSeconds << "s" << std::endl;
}
StreamingReporterBase::sectionEnded( _sectionStats );
}
virtual void testCaseEnded( TestCaseStats const& _testCaseStats ) {
StreamingReporterBase::testCaseEnded( _testCaseStats );
m_headerPrinted = false;
}
virtual void testGroupEnded( TestGroupStats const& _testGroupStats ) {
if( currentGroupInfo.used ) {
printSummaryDivider();
stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
printTotals( _testGroupStats.totals );
stream << "\n" << std::endl;
}
StreamingReporterBase::testGroupEnded( _testGroupStats );
}
virtual void testRunEnded( TestRunStats const& _testRunStats ) {
printTotalsDivider( _testRunStats.totals );
printTotals( _testRunStats.totals );
stream << std::endl;
StreamingReporterBase::testRunEnded( _testRunStats );
}
private:
class AssertionPrinter {
void operator= ( AssertionPrinter const& );
public:
AssertionPrinter( std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages )
: stream( _stream ),
stats( _stats ),
result( _stats.assertionResult ),
colour( Colour::None ),
message( result.getMessage() ),
messages( _stats.infoMessages ),
printInfoMessages( _printInfoMessages )
{
switch( result.getResultType() ) {
case ResultWas::Ok:
colour = Colour::Success;
passOrFail = "PASSED";
//if( result.hasMessage() )
if( _stats.infoMessages.size() == 1 )
messageLabel = "with message";
if( _stats.infoMessages.size() > 1 )
messageLabel = "with messages";
break;
case ResultWas::ExpressionFailed:
if( result.isOk() ) {
colour = Colour::Success;
passOrFail = "FAILED - but was ok";
}
else {
colour = Colour::Error;
passOrFail = "FAILED";
}
if( _stats.infoMessages.size() == 1 )
messageLabel = "with message";
if( _stats.infoMessages.size() > 1 )
messageLabel = "with messages";
break;
case ResultWas::ThrewException:
colour = Colour::Error;
passOrFail = "FAILED";
messageLabel = "due to unexpected exception with message";
break;
case ResultWas::FatalErrorCondition:
colour = Colour::Error;
passOrFail = "FAILED";
messageLabel = "due to a fatal error condition";
break;
case ResultWas::DidntThrowException:
colour = Colour::Error;
passOrFail = "FAILED";
messageLabel = "because no exception was thrown where one was expected";
break;
case ResultWas::Info:
messageLabel = "info";
break;
case ResultWas::Warning:
messageLabel = "warning";
break;
case ResultWas::ExplicitFailure:
passOrFail = "FAILED";
colour = Colour::Error;
if( _stats.infoMessages.size() == 1 )
messageLabel = "explicitly with message";
if( _stats.infoMessages.size() > 1 )
messageLabel = "explicitly with messages";
break;
// These cases are here to prevent compiler warnings
case ResultWas::Unknown:
case ResultWas::FailureBit:
case ResultWas::Exception:
passOrFail = "** internal error **";
colour = Colour::Error;
break;
}
}
void print() const {
printSourceInfo();
if( stats.totals.assertions.total() > 0 ) {
if( result.isOk() )
stream << "\n";
printResultType();
printOriginalExpression();
printReconstructedExpression();
}
else {
stream << "\n";
}
printMessage();
}
private:
void printResultType() const {
if( !passOrFail.empty() ) {
Colour colourGuard( colour );
stream << passOrFail << ":\n";
}
}
void printOriginalExpression() const {
if( result.hasExpression() ) {
Colour colourGuard( Colour::OriginalExpression );
stream << " ";
stream << result.getExpressionInMacro();
stream << "\n";
}
}
void printReconstructedExpression() const {
if( result.hasExpandedExpression() ) {
stream << "with expansion:\n";
Colour colourGuard( Colour::ReconstructedExpression );
stream << Text( result.getExpandedExpression(), TextAttributes().setIndent(2) ) << "\n";
}
}
void printMessage() const {
if( !messageLabel.empty() )
stream << messageLabel << ":" << "\n";
for( std::vector<MessageInfo>::const_iterator it = messages.begin(), itEnd = messages.end();
it != itEnd;
++it ) {
// If this assertion is a warning ignore any INFO messages
if( printInfoMessages || it->type != ResultWas::Info )
stream << Text( it->message, TextAttributes().setIndent(2) ) << "\n";
}
}
void printSourceInfo() const {
Colour colourGuard( Colour::FileName );
stream << result.getSourceInfo() << ": ";
}
std::ostream& stream;
AssertionStats const& stats;
AssertionResult const& result;
Colour::Code colour;
std::string passOrFail;
std::string messageLabel;
std::string message;
std::vector<MessageInfo> messages;
bool printInfoMessages;
};
void lazyPrint() {
if( !currentTestRunInfo.used )
lazyPrintRunInfo();
if( !currentGroupInfo.used )
lazyPrintGroupInfo();
if( !m_headerPrinted ) {
printTestCaseAndSectionHeader();
m_headerPrinted = true;
}
}
void lazyPrintRunInfo() {
stream << "\n" << getLineOfChars<'~'>() << "\n";
Colour colour( Colour::SecondaryText );
stream << currentTestRunInfo->name
<< " is a Catch v" << libraryVersion << " host application.\n"
<< "Run with -? for options\n\n";
if( m_config->rngSeed() != 0 )
stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
currentTestRunInfo.used = true;
}
void lazyPrintGroupInfo() {
if( !currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1 ) {
printClosedHeader( "Group: " + currentGroupInfo->name );
currentGroupInfo.used = true;
}
}
void printTestCaseAndSectionHeader() {
assert( !m_sectionStack.empty() );
printOpenHeader( currentTestCaseInfo->name );
if( m_sectionStack.size() > 1 ) {
Colour colourGuard( Colour::Headers );
std::vector<SectionInfo>::const_iterator
it = m_sectionStack.begin()+1, // Skip first section (test case)
itEnd = m_sectionStack.end();
for( ; it != itEnd; ++it )
printHeaderString( it->name, 2 );
}
SourceLineInfo lineInfo = m_sectionStack.front().lineInfo;
if( !lineInfo.empty() ){
stream << getLineOfChars<'-'>() << "\n";
Colour colourGuard( Colour::FileName );
stream << lineInfo << "\n";
}
stream << getLineOfChars<'.'>() << "\n" << std::endl;
}
void printClosedHeader( std::string const& _name ) {
printOpenHeader( _name );
stream << getLineOfChars<'.'>() << "\n";
}
void printOpenHeader( std::string const& _name ) {
stream << getLineOfChars<'-'>() << "\n";
{
Colour colourGuard( Colour::Headers );
printHeaderString( _name );
}
}
// if string has a : in first line will set indent to follow it on
// subsequent lines
void printHeaderString( std::string const& _string, std::size_t indent = 0 ) {
std::size_t i = _string.find( ": " );
if( i != std::string::npos )
i+=2;
else
i = 0;
stream << Text( _string, TextAttributes()
.setIndent( indent+i)
.setInitialIndent( indent ) ) << "\n";
}
struct SummaryColumn {
SummaryColumn( std::string const& _label, Colour::Code _colour )
: label( _label ),
colour( _colour )
{}
SummaryColumn addRow( std::size_t count ) {
std::ostringstream oss;
oss << count;
std::string row = oss.str();
for( std::vector<std::string>::iterator it = rows.begin(); it != rows.end(); ++it ) {
while( it->size() < row.size() )
*it = " " + *it;
while( it->size() > row.size() )
row = " " + row;
}
rows.push_back( row );
return *this;
}
std::string label;
Colour::Code colour;
std::vector<std::string> rows;
};
void printTotals( Totals const& totals ) {
if( totals.testCases.total() == 0 ) {
stream << Colour( Colour::Warning ) << "No tests ran\n";
}
else if( totals.assertions.total() > 0 && totals.assertions.allPassed() ) {
stream << Colour( Colour::ResultSuccess ) << "All tests passed";
stream << " ("
<< pluralise( totals.assertions.passed, "assertion" ) << " in "
<< pluralise( totals.testCases.passed, "test case" ) << ")"
<< "\n";
}
else {
std::vector<SummaryColumn> columns;
columns.push_back( SummaryColumn( "", Colour::None )
.addRow( totals.testCases.total() )
.addRow( totals.assertions.total() ) );
columns.push_back( SummaryColumn( "passed", Colour::Success )
.addRow( totals.testCases.passed )
.addRow( totals.assertions.passed ) );
columns.push_back( SummaryColumn( "failed", Colour::ResultError )
.addRow( totals.testCases.failed )
.addRow( totals.assertions.failed ) );
columns.push_back( SummaryColumn( "failed as expected", Colour::ResultExpectedFailure )
.addRow( totals.testCases.failedButOk )
.addRow( totals.assertions.failedButOk ) );
printSummaryRow( "test cases", columns, 0 );
printSummaryRow( "assertions", columns, 1 );
}
}
void printSummaryRow( std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row ) {
for( std::vector<SummaryColumn>::const_iterator it = cols.begin(); it != cols.end(); ++it ) {
std::string value = it->rows[row];
if( it->label.empty() ) {
stream << label << ": ";
if( value != "0" )
stream << value;
else
stream << Colour( Colour::Warning ) << "- none -";
}
else if( value != "0" ) {
stream << Colour( Colour::LightGrey ) << " | ";
stream << Colour( it->colour )
<< value << " " << it->label;
}
}
stream << "\n";
}
static std::size_t makeRatio( std::size_t number, std::size_t total ) {
std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number/ total : 0;
return ( ratio == 0 && number > 0 ) ? 1 : ratio;
}
static std::size_t& findMax( std::size_t& i, std::size_t& j, std::size_t& k ) {
if( i > j && i > k )
return i;
else if( j > k )
return j;
else
return k;
}
void printTotalsDivider( Totals const& totals ) {
if( totals.testCases.total() > 0 ) {
std::size_t failedRatio = makeRatio( totals.testCases.failed, totals.testCases.total() );
std::size_t failedButOkRatio = makeRatio( totals.testCases.failedButOk, totals.testCases.total() );
std::size_t passedRatio = makeRatio( totals.testCases.passed, totals.testCases.total() );
while( failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH-1 )
findMax( failedRatio, failedButOkRatio, passedRatio )++;
while( failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH-1 )
findMax( failedRatio, failedButOkRatio, passedRatio )--;
stream << Colour( Colour::Error ) << std::string( failedRatio, '=' );
stream << Colour( Colour::ResultExpectedFailure ) << std::string( failedButOkRatio, '=' );
if( totals.testCases.allPassed() )
stream << Colour( Colour::ResultSuccess ) << std::string( passedRatio, '=' );
else
stream << Colour( Colour::Success ) << std::string( passedRatio, '=' );
}
else {
stream << Colour( Colour::Warning ) << std::string( CATCH_CONFIG_CONSOLE_WIDTH-1, '=' );
}
stream << "\n";
}
void printSummaryDivider() {
stream << getLineOfChars<'-'>() << "\n";
}
private:
bool m_headerPrinted;
};
INTERNAL_CATCH_REGISTER_REPORTER( "console", ConsoleReporter )
} // end namespace Catch
// #included from: ../reporters/catch_reporter_compact.hpp
#define TWOBLUECUBES_CATCH_REPORTER_COMPACT_HPP_INCLUDED
namespace Catch {
struct CompactReporter : StreamingReporterBase {
CompactReporter( ReporterConfig const& _config )
: StreamingReporterBase( _config )
{}
virtual ~CompactReporter();
static std::string getDescription() {
return "Reports test results on a single line, suitable for IDEs";
}
virtual ReporterPreferences getPreferences() const {
ReporterPreferences prefs;
prefs.shouldRedirectStdOut = false;
return prefs;
}
virtual void noMatchingTestCases( std::string const& spec ) {
stream << "No test cases matched '" << spec << "'" << std::endl;
}
virtual void assertionStarting( AssertionInfo const& ) {
}
virtual bool assertionEnded( AssertionStats const& _assertionStats ) {
AssertionResult const& result = _assertionStats.assertionResult;
bool printInfoMessages = true;
// Drop out if result was successful and we're not printing those
if( !m_config->includeSuccessfulResults() && result.isOk() ) {
if( result.getResultType() != ResultWas::Warning )
return false;
printInfoMessages = false;
}
AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
printer.print();
stream << std::endl;
return true;
}
virtual void testRunEnded( TestRunStats const& _testRunStats ) {
printTotals( _testRunStats.totals );
stream << "\n" << std::endl;
StreamingReporterBase::testRunEnded( _testRunStats );
}
private:
class AssertionPrinter {
void operator= ( AssertionPrinter const& );
public:
AssertionPrinter( std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages )
: stream( _stream )
, stats( _stats )
, result( _stats.assertionResult )
, messages( _stats.infoMessages )
, itMessage( _stats.infoMessages.begin() )
, printInfoMessages( _printInfoMessages )
{}
void print() {
printSourceInfo();
itMessage = messages.begin();
switch( result.getResultType() ) {
case ResultWas::Ok:
printResultType( Colour::ResultSuccess, passedString() );
printOriginalExpression();
printReconstructedExpression();
if ( ! result.hasExpression() )
printRemainingMessages( Colour::None );
else
printRemainingMessages();
break;
case ResultWas::ExpressionFailed:
if( result.isOk() )
printResultType( Colour::ResultSuccess, failedString() + std::string( " - but was ok" ) );
else
printResultType( Colour::Error, failedString() );
printOriginalExpression();
printReconstructedExpression();
printRemainingMessages();
break;
case ResultWas::ThrewException:
printResultType( Colour::Error, failedString() );
printIssue( "unexpected exception with message:" );
printMessage();
printExpressionWas();
printRemainingMessages();
break;
case ResultWas::FatalErrorCondition:
printResultType( Colour::Error, failedString() );
printIssue( "fatal error condition with message:" );
printMessage();
printExpressionWas();
printRemainingMessages();
break;
case ResultWas::DidntThrowException:
printResultType( Colour::Error, failedString() );
printIssue( "expected exception, got none" );
printExpressionWas();
printRemainingMessages();
break;
case ResultWas::Info:
printResultType( Colour::None, "info" );
printMessage();
printRemainingMessages();
break;
case ResultWas::Warning:
printResultType( Colour::None, "warning" );
printMessage();
printRemainingMessages();
break;
case ResultWas::ExplicitFailure:
printResultType( Colour::Error, failedString() );
printIssue( "explicitly" );
printRemainingMessages( Colour::None );
break;
// These cases are here to prevent compiler warnings
case ResultWas::Unknown:
case ResultWas::FailureBit:
case ResultWas::Exception:
printResultType( Colour::Error, "** internal error **" );
break;
}
}
private:
// Colour::LightGrey
static Colour::Code dimColour() { return Colour::FileName; }
#ifdef CATCH_PLATFORM_MAC
static const char* failedString() { return "FAILED"; }
static const char* passedString() { return "PASSED"; }
#else
static const char* failedString() { return "failed"; }
static const char* passedString() { return "passed"; }
#endif
void printSourceInfo() const {
Colour colourGuard( Colour::FileName );
stream << result.getSourceInfo() << ":";
}
void printResultType( Colour::Code colour, std::string passOrFail ) const {
if( !passOrFail.empty() ) {
{
Colour colourGuard( colour );
stream << " " << passOrFail;
}
stream << ":";
}
}
void printIssue( std::string issue ) const {
stream << " " << issue;
}
void printExpressionWas() {
if( result.hasExpression() ) {
stream << ";";
{
Colour colour( dimColour() );
stream << " expression was:";
}
printOriginalExpression();
}
}
void printOriginalExpression() const {
if( result.hasExpression() ) {
stream << " " << result.getExpression();
}
}
void printReconstructedExpression() const {
if( result.hasExpandedExpression() ) {
{
Colour colour( dimColour() );
stream << " for: ";
}
stream << result.getExpandedExpression();
}
}
void printMessage() {
if ( itMessage != messages.end() ) {
stream << " '" << itMessage->message << "'";
++itMessage;
}
}
void printRemainingMessages( Colour::Code colour = dimColour() ) {
if ( itMessage == messages.end() )
return;
// using messages.end() directly yields compilation error:
std::vector<MessageInfo>::const_iterator itEnd = messages.end();
const std::size_t N = static_cast<std::size_t>( std::distance( itMessage, itEnd ) );
{
Colour colourGuard( colour );
stream << " with " << pluralise( N, "message" ) << ":";
}
for(; itMessage != itEnd; ) {
// If this assertion is a warning ignore any INFO messages
if( printInfoMessages || itMessage->type != ResultWas::Info ) {
stream << " '" << itMessage->message << "'";
if ( ++itMessage != itEnd ) {
Colour colourGuard( dimColour() );
stream << " and";
}
}
}
}
private:
std::ostream& stream;
AssertionStats const& stats;
AssertionResult const& result;
std::vector<MessageInfo> messages;
std::vector<MessageInfo>::const_iterator itMessage;
bool printInfoMessages;
};
// Colour, message variants:
// - white: No tests ran.
// - red: Failed [both/all] N test cases, failed [both/all] M assertions.
// - white: Passed [both/all] N test cases (no assertions).
// - red: Failed N tests cases, failed M assertions.
// - green: Passed [both/all] N tests cases with M assertions.
std::string bothOrAll( std::size_t count ) const {
return count == 1 ? "" : count == 2 ? "both " : "all " ;
}
void printTotals( const Totals& totals ) const {
if( totals.testCases.total() == 0 ) {
stream << "No tests ran.";
}
else if( totals.testCases.failed == totals.testCases.total() ) {
Colour colour( Colour::ResultError );
const std::string qualify_assertions_failed =
totals.assertions.failed == totals.assertions.total() ?
bothOrAll( totals.assertions.failed ) : "";
stream <<
"Failed " << bothOrAll( totals.testCases.failed )
<< pluralise( totals.testCases.failed, "test case" ) << ", "
"failed " << qualify_assertions_failed <<
pluralise( totals.assertions.failed, "assertion" ) << ".";
}
else if( totals.assertions.total() == 0 ) {
stream <<
"Passed " << bothOrAll( totals.testCases.total() )
<< pluralise( totals.testCases.total(), "test case" )
<< " (no assertions).";
}
else if( totals.assertions.failed ) {
Colour colour( Colour::ResultError );
stream <<
"Failed " << pluralise( totals.testCases.failed, "test case" ) << ", "
"failed " << pluralise( totals.assertions.failed, "assertion" ) << ".";
}
else {
Colour colour( Colour::ResultSuccess );
stream <<
"Passed " << bothOrAll( totals.testCases.passed )
<< pluralise( totals.testCases.passed, "test case" ) <<
" with " << pluralise( totals.assertions.passed, "assertion" ) << ".";
}
}
};
INTERNAL_CATCH_REGISTER_REPORTER( "compact", CompactReporter )
} // end namespace Catch
namespace Catch {
NonCopyable::~NonCopyable() {}
IShared::~IShared() {}
StreamBufBase::~StreamBufBase() CATCH_NOEXCEPT {}
IContext::~IContext() {}
IResultCapture::~IResultCapture() {}
ITestCase::~ITestCase() {}
ITestCaseRegistry::~ITestCaseRegistry() {}
IRegistryHub::~IRegistryHub() {}
IMutableRegistryHub::~IMutableRegistryHub() {}
IExceptionTranslator::~IExceptionTranslator() {}
IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() {}
IReporter::~IReporter() {}
IReporterFactory::~IReporterFactory() {}
IReporterRegistry::~IReporterRegistry() {}
IStreamingReporter::~IStreamingReporter() {}
AssertionStats::~AssertionStats() {}
SectionStats::~SectionStats() {}
TestCaseStats::~TestCaseStats() {}
TestGroupStats::~TestGroupStats() {}
TestRunStats::~TestRunStats() {}
CumulativeReporterBase::SectionNode::~SectionNode() {}
CumulativeReporterBase::~CumulativeReporterBase() {}
StreamingReporterBase::~StreamingReporterBase() {}
ConsoleReporter::~ConsoleReporter() {}
CompactReporter::~CompactReporter() {}
IRunner::~IRunner() {}
IMutableContext::~IMutableContext() {}
IConfig::~IConfig() {}
XmlReporter::~XmlReporter() {}
JunitReporter::~JunitReporter() {}
TestRegistry::~TestRegistry() {}
FreeFunctionTestCase::~FreeFunctionTestCase() {}
IGeneratorInfo::~IGeneratorInfo() {}
IGeneratorsForTest::~IGeneratorsForTest() {}
TestSpec::Pattern::~Pattern() {}
TestSpec::NamePattern::~NamePattern() {}
TestSpec::TagPattern::~TagPattern() {}
TestSpec::ExcludedPattern::~ExcludedPattern() {}
Matchers::Impl::StdString::Equals::~Equals() {}
Matchers::Impl::StdString::Contains::~Contains() {}
Matchers::Impl::StdString::StartsWith::~StartsWith() {}
Matchers::Impl::StdString::EndsWith::~EndsWith() {}
void Config::dummy() {}
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif
#ifdef CATCH_CONFIG_MAIN
// #included from: internal/catch_default_main.hpp
#define TWOBLUECUBES_CATCH_DEFAULT_MAIN_HPP_INCLUDED
#ifndef __OBJC__
// Standard C/C++ main entry point
int main (int argc, char * const argv[]) {
return Catch::Session().run( argc, argv );
}
#else // __OBJC__
// Objective-C entry point
int main (int argc, char * const argv[]) {
#if !CATCH_ARC_ENABLED
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
#endif
Catch::registerTestMethods();
int result = Catch::Session().run( argc, (char* const*)argv );
#if !CATCH_ARC_ENABLED
[pool drain];
#endif
return result;
}
#endif // __OBJC__
#endif
#ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
# undef CLARA_CONFIG_MAIN
#endif
//////
// If this config identifier is defined then all CATCH macros are prefixed with CATCH_
#ifdef CATCH_CONFIG_PREFIX_ALL
#define CATCH_REQUIRE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::Normal, "CATCH_REQUIRE" )
#define CATCH_REQUIRE_FALSE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, "CATCH_REQUIRE_FALSE" )
#define CATCH_REQUIRE_THROWS( expr ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::Normal, "CATCH_REQUIRE_THROWS" )
#define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( expr, exceptionType, Catch::ResultDisposition::Normal, "CATCH_REQUIRE_THROWS_AS" )
#define CATCH_REQUIRE_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( expr, Catch::ResultDisposition::Normal, "CATCH_REQUIRE_NOTHROW" )
#define CATCH_CHECK( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK" )
#define CATCH_CHECK_FALSE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, "CATCH_CHECK_FALSE" )
#define CATCH_CHECKED_IF( expr ) INTERNAL_CATCH_IF( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECKED_IF" )
#define CATCH_CHECKED_ELSE( expr ) INTERNAL_CATCH_ELSE( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECKED_ELSE" )
#define CATCH_CHECK_NOFAIL( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, "CATCH_CHECK_NOFAIL" )
#define CATCH_CHECK_THROWS( expr ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_THROWS" )
#define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( expr, exceptionType, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_THROWS_AS" )
#define CATCH_CHECK_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_NOTHROW" )
#define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_THAT" )
#define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::Normal, "CATCH_REQUIRE_THAT" )
#define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( msg, "CATCH_INFO" )
#define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, "CATCH_WARN", msg )
#define CATCH_SCOPED_INFO( msg ) INTERNAL_CATCH_INFO( msg, "CATCH_INFO" )
#define CATCH_CAPTURE( msg ) INTERNAL_CATCH_INFO( #msg " := " << msg, "CATCH_CAPTURE" )
#define CATCH_SCOPED_CAPTURE( msg ) INTERNAL_CATCH_INFO( #msg " := " << msg, "CATCH_CAPTURE" )
#ifdef CATCH_CONFIG_VARIADIC_MACROS
#define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
#define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
#define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
#define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
#define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, "CATCH_FAIL", __VA_ARGS__ )
#define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, "CATCH_SUCCEED", __VA_ARGS__ )
#else
#define CATCH_TEST_CASE( name, description ) INTERNAL_CATCH_TESTCASE( name, description )
#define CATCH_TEST_CASE_METHOD( className, name, description ) INTERNAL_CATCH_TEST_CASE_METHOD( className, name, description )
#define CATCH_METHOD_AS_TEST_CASE( method, name, description ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, name, description )
#define CATCH_SECTION( name, description ) INTERNAL_CATCH_SECTION( name, description )
#define CATCH_FAIL( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, "CATCH_FAIL", msg )
#define CATCH_SUCCEED( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, "CATCH_SUCCEED", msg )
#endif
#define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE( "", "" )
#define CATCH_REGISTER_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_REPORTER( name, reporterType )
#define CATCH_REGISTER_LEGACY_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_LEGACY_REPORTER( name, reporterType )
#define CATCH_GENERATE( expr) INTERNAL_CATCH_GENERATE( expr )
// "BDD-style" convenience wrappers
#ifdef CATCH_CONFIG_VARIADIC_MACROS
#define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
#define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
#else
#define CATCH_SCENARIO( name, tags ) CATCH_TEST_CASE( "Scenario: " name, tags )
#define CATCH_SCENARIO_METHOD( className, name, tags ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " name, tags )
#endif
#define CATCH_GIVEN( desc ) CATCH_SECTION( "Given: " desc, "" )
#define CATCH_WHEN( desc ) CATCH_SECTION( " When: " desc, "" )
#define CATCH_AND_WHEN( desc ) CATCH_SECTION( " And: " desc, "" )
#define CATCH_THEN( desc ) CATCH_SECTION( " Then: " desc, "" )
#define CATCH_AND_THEN( desc ) CATCH_SECTION( " And: " desc, "" )
// If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
#else
#define REQUIRE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::Normal, "REQUIRE" )
#define REQUIRE_FALSE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, "REQUIRE_FALSE" )
#define REQUIRE_THROWS( expr ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::Normal, "REQUIRE_THROWS" )
#define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( expr, exceptionType, Catch::ResultDisposition::Normal, "REQUIRE_THROWS_AS" )
#define REQUIRE_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( expr, Catch::ResultDisposition::Normal, "REQUIRE_NOTHROW" )
#define CHECK( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure, "CHECK" )
#define CHECK_FALSE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, "CHECK_FALSE" )
#define CHECKED_IF( expr ) INTERNAL_CATCH_IF( expr, Catch::ResultDisposition::ContinueOnFailure, "CHECKED_IF" )
#define CHECKED_ELSE( expr ) INTERNAL_CATCH_ELSE( expr, Catch::ResultDisposition::ContinueOnFailure, "CHECKED_ELSE" )
#define CHECK_NOFAIL( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, "CHECK_NOFAIL" )
#define CHECK_THROWS( expr ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::ContinueOnFailure, "CHECK_THROWS" )
#define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( expr, exceptionType, Catch::ResultDisposition::ContinueOnFailure, "CHECK_THROWS_AS" )
#define CHECK_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( expr, Catch::ResultDisposition::ContinueOnFailure, "CHECK_NOTHROW" )
#define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::ContinueOnFailure, "CHECK_THAT" )
#define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::Normal, "REQUIRE_THAT" )
#define INFO( msg ) INTERNAL_CATCH_INFO( msg, "INFO" )
#define WARN( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, "WARN", msg )
#define SCOPED_INFO( msg ) INTERNAL_CATCH_INFO( msg, "INFO" )
#define CAPTURE( msg ) INTERNAL_CATCH_INFO( #msg " := " << msg, "CAPTURE" )
#define SCOPED_CAPTURE( msg ) INTERNAL_CATCH_INFO( #msg " := " << msg, "CAPTURE" )
#ifdef CATCH_CONFIG_VARIADIC_MACROS
#define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
#define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
#define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
#define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
#define FAIL( ... ) INTERNAL_CATCH_MSG( Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, "FAIL", __VA_ARGS__ )
#define SUCCEED( ... ) INTERNAL_CATCH_MSG( Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, "SUCCEED", __VA_ARGS__ )
#else
#define TEST_CASE( name, description ) INTERNAL_CATCH_TESTCASE( name, description )
#define TEST_CASE_METHOD( className, name, description ) INTERNAL_CATCH_TEST_CASE_METHOD( className, name, description )
#define METHOD_AS_TEST_CASE( method, name, description ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, name, description )
#define SECTION( name, description ) INTERNAL_CATCH_SECTION( name, description )
#define FAIL( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, "FAIL", msg )
#define SUCCEED( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, "SUCCEED", msg )
#endif
#define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE( "", "" )
#define REGISTER_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_REPORTER( name, reporterType )
#define REGISTER_LEGACY_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_LEGACY_REPORTER( name, reporterType )
#define GENERATE( expr) INTERNAL_CATCH_GENERATE( expr )
#endif
#define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
// "BDD-style" convenience wrappers
#ifdef CATCH_CONFIG_VARIADIC_MACROS
#define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ )
#define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
#else
#define SCENARIO( name, tags ) TEST_CASE( "Scenario: " name, tags )
#define SCENARIO_METHOD( className, name, tags ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " name, tags )
#endif
#define GIVEN( desc ) SECTION( " Given: " desc, "" )
#define WHEN( desc ) SECTION( " When: " desc, "" )
#define AND_WHEN( desc ) SECTION( "And when: " desc, "" )
#define THEN( desc ) SECTION( " Then: " desc, "" )
#define AND_THEN( desc ) SECTION( " And: " desc, "" )
using Catch::Detail::Approx;
// #included from: internal/catch_reenable_warnings.h
#define TWOBLUECUBES_CATCH_REENABLE_WARNINGS_H_INCLUDED
#ifdef __clang__
# ifdef __ICC // icpc defines the __clang__ macro
# pragma warning(pop)
# else
# pragma clang diagnostic pop
# endif
#elif defined __GNUC__
# pragma GCC diagnostic pop
#endif
#endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
|
// Copyright 2019, Nawin
#include "Workspace.h"
|
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the documentation of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** BSD License Usage
** Alternatively, you may use this file under the terms of the BSD license
** as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of The Qt Company Ltd nor the names of its
** contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtGui>
#include "mainwindow.h"
MainWindow::MainWindow()
{
QMenu *fileMenu = new QMenu(tr("&File"));
QAction *quitAction = fileMenu->addAction(tr("E&xit"));
quitAction->setShortcut(tr("Ctrl+Q"));
QMenu *itemsMenu = new QMenu(tr("&Items"));
insertAction = itemsMenu->addAction(tr("&Insert Item"));
removeAction = itemsMenu->addAction(tr("&Remove Item"));
QAction *ascendingAction = itemsMenu->addAction(tr("Sort in &Ascending Order"));
QAction *descendingAction = itemsMenu->addAction(tr("Sort in &Descending Order"));
menuBar()->addMenu(fileMenu);
menuBar()->addMenu(itemsMenu);
/* For convenient quoting:
//! [0]
QListWidget *listWidget = new QListWidget(this);
//! [0]
*/
listWidget = new QListWidget(this);
listWidget->setSelectionMode(QAbstractItemView::SingleSelection);
connect(quitAction, SIGNAL(triggered()), this, SLOT(close()));
connect(ascendingAction, SIGNAL(triggered()), this, SLOT(sortAscending()));
connect(descendingAction, SIGNAL(triggered()), this, SLOT(sortDescending()));
connect(insertAction, SIGNAL(triggered()), this, SLOT(insertItem()));
connect(removeAction, SIGNAL(triggered()), this, SLOT(removeItem()));
connect(listWidget,
SIGNAL(currentItemChanged(QListWidgetItem*,QListWidgetItem*)),
this, SLOT(updateMenus(QListWidgetItem*)));
setupListItems();
updateMenus(listWidget->currentItem());
setCentralWidget(listWidget);
setWindowTitle(tr("List Widget"));
}
void MainWindow::setupListItems()
{
//! [1]
new QListWidgetItem(tr("Oak"), listWidget);
new QListWidgetItem(tr("Fir"), listWidget);
new QListWidgetItem(tr("Pine"), listWidget);
//! [1]
new QListWidgetItem(tr("Birch"), listWidget);
//! [2]
new QListWidgetItem(tr("Hazel"), listWidget);
//! [2]
new QListWidgetItem(tr("Redwood"), listWidget);
//! [3]
new QListWidgetItem(tr("Sycamore"), listWidget);
new QListWidgetItem(tr("Chestnut"), listWidget);
new QListWidgetItem(tr("Mahogany"), listWidget);
//! [3]
}
void MainWindow::sortAscending()
{
//! [4]
listWidget->sortItems(Qt::AscendingOrder);
//! [4]
}
void MainWindow::sortDescending()
{
//! [5]
listWidget->sortItems(Qt::DescendingOrder);
//! [5]
}
void MainWindow::insertItem()
{
if (!listWidget->currentItem())
return;
QString itemText = QInputDialog::getText(this, tr("Insert Item"),
tr("Input text for the new item:"));
if (itemText.isNull())
return;
//! [6]
QListWidgetItem *newItem = new QListWidgetItem;
newItem->setText(itemText);
//! [6]
int row = listWidget->row(listWidget->currentItem());
//! [7]
listWidget->insertItem(row, newItem);
//! [7]
QString toolTipText = tr("Tooltip:") + itemText;
QString statusTipText = tr("Status tip:") + itemText;
QString whatsThisText = tr("What's This?:") + itemText;
//! [8]
newItem->setToolTip(toolTipText);
newItem->setStatusTip(toolTipText);
newItem->setWhatsThis(whatsThisText);
//! [8]
}
void MainWindow::removeItem()
{
listWidget->takeItem(listWidget->row(listWidget->currentItem()));
}
void MainWindow::updateMenus(QListWidgetItem *current)
{
insertAction->setEnabled(current != 0);
removeAction->setEnabled(current != 0);
}
|
//
// Created by taylor-santos on 1/2/2022 at 21:02.
//
#pragma once
#include <string>
#include "ast/type.hpp"
namespace AST {
class ObjectType final : public Type {
public:
ObjectType(std::string name, const yy::location &name_loc, const yy::location &loc);
~ObjectType() override;
void
to_json(std::ostream &os) const override;
[[nodiscard]] const TypeChecker::Type &
get_type(TypeChecker::Context &ctx) const override;
private:
std::string name_;
yy::location name_loc_;
};
} // namespace AST
|
// Generated from /POI/java/org/apache/poi/hpsf/wellknown/SectionIDMap.java
#pragma once
#include <fwd-POI.hpp>
#include <java/lang/fwd-POI.hpp>
#include <org/apache/poi/hpsf/fwd-POI.hpp>
#include <org/apache/poi/hpsf/wellknown/fwd-POI.hpp>
#include <java/lang/Object.hpp>
template<typename ComponentType, typename... Bases> struct SubArray;
namespace poi
{
namespace hpsf
{
typedef ::SubArray< ::poi::hpsf::ClassID, ::java::lang::ObjectArray > ClassIDArray;
} // hpsf
} // poi
struct default_init_tag;
class poi::hpsf::wellknown::SectionIDMap
: public virtual ::java::lang::Object
{
public:
typedef ::java::lang::Object super;
private:
static ::java::lang::ThreadLocal* defaultMap_;
static ::poi::hpsf::ClassID* SUMMARY_INFORMATION_ID_;
static ::poi::hpsf::ClassID* DOC_SUMMARY_INFORMATION_;
static ::poi::hpsf::ClassID* USER_DEFINED_PROPERTIES_;
static ::poi::hpsf::ClassIDArray* DOCUMENT_SUMMARY_INFORMATION_ID_;
static ::java::lang::String* UNDEFINED_;
public:
static SectionIDMap* getInstance();
static ::java::lang::String* getPIDString(::poi::hpsf::ClassID* sectionFormatID, int64_t pid);
virtual PropertyIDMap* get(::poi::hpsf::ClassID* sectionFormatID);
virtual PropertyIDMap* put(::poi::hpsf::ClassID* sectionFormatID, PropertyIDMap* propertyIDMap);
public: /* protected */
virtual PropertyIDMap* put(::java::lang::String* key, PropertyIDMap* value);
// Generated
public:
SectionIDMap();
protected:
SectionIDMap(const ::default_init_tag&);
public:
static ::java::lang::Class *class_();
static void clinit();
private:
static ::java::lang::ThreadLocal*& defaultMap();
public:
static ::poi::hpsf::ClassID*& SUMMARY_INFORMATION_ID();
private:
static ::poi::hpsf::ClassID*& DOC_SUMMARY_INFORMATION();
static ::poi::hpsf::ClassID*& USER_DEFINED_PROPERTIES();
public:
static ::poi::hpsf::ClassIDArray*& DOCUMENT_SUMMARY_INFORMATION_ID();
static ::java::lang::String*& UNDEFINED();
private:
virtual ::java::lang::Class* getClass0();
};
|
//===--- PlatformKind.cpp - Swift Language Platform Kinds -----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements the platform kinds for API availability.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/PlatformKind.h"
#include "swift/Basic/LangOptions.h"
#include "swift/Basic/Platform.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/ErrorHandling.h"
using namespace swift;
StringRef swift::platformString(PlatformKind platform) {
switch (platform) {
case PlatformKind::none:
return "*";
#define AVAILABILITY_PLATFORM(X, PrettyName) \
case PlatformKind::X: \
return #X;
#include "swift/AST/PlatformKinds.def"
}
llvm_unreachable("bad PlatformKind");
}
StringRef swift::prettyPlatformString(PlatformKind platform) {
switch (platform) {
case PlatformKind::none:
return "*";
#define AVAILABILITY_PLATFORM(X, PrettyName) \
case PlatformKind::X: \
return PrettyName;
#include "swift/AST/PlatformKinds.def"
}
llvm_unreachable("bad PlatformKind");
}
Optional<PlatformKind> swift::platformFromString(StringRef Name) {
if (Name == "*")
return PlatformKind::none;
return llvm::StringSwitch<Optional<PlatformKind>>(Name)
#define AVAILABILITY_PLATFORM(X, PrettyName) .Case(#X, PlatformKind::X)
#include "swift/AST/PlatformKinds.def"
.Case("OSX", PlatformKind::macOS)
.Case("OSXApplicationExtension", PlatformKind::macOSApplicationExtension)
.Default(Optional<PlatformKind>());
}
static bool isPlatformActiveForTarget(PlatformKind Platform,
const llvm::Triple &Target,
bool EnableAppExtensionRestrictions) {
if (Platform == PlatformKind::none)
return true;
if (Platform == PlatformKind::macOSApplicationExtension ||
Platform == PlatformKind::iOSApplicationExtension ||
Platform == PlatformKind::macCatalystApplicationExtension)
if (!EnableAppExtensionRestrictions)
return false;
// FIXME: This is an awful way to get the current OS.
switch (Platform) {
case PlatformKind::macOS:
case PlatformKind::macOSApplicationExtension:
return Target.isMacOSX();
case PlatformKind::iOS:
case PlatformKind::iOSApplicationExtension:
return Target.isiOS() && !Target.isTvOS();
case PlatformKind::macCatalyst:
case PlatformKind::macCatalystApplicationExtension:
return tripleIsMacCatalystEnvironment(Target);
case PlatformKind::tvOS:
case PlatformKind::tvOSApplicationExtension:
return Target.isTvOS();
case PlatformKind::watchOS:
case PlatformKind::watchOSApplicationExtension:
return Target.isWatchOS();
case PlatformKind::none:
llvm_unreachable("handled above");
}
llvm_unreachable("bad PlatformKind");
}
bool swift::isPlatformActive(PlatformKind Platform, const LangOptions &LangOpts,
bool ForTargetVariant) {
llvm::Triple TT = LangOpts.Target;
if (ForTargetVariant) {
assert(LangOpts.TargetVariant && "Must have target variant triple");
TT = *LangOpts.TargetVariant;
}
return isPlatformActiveForTarget(Platform, TT,
LangOpts.EnableAppExtensionRestrictions);
}
PlatformKind swift::targetPlatform(const LangOptions &LangOpts) {
if (LangOpts.Target.isMacOSX()) {
return (LangOpts.EnableAppExtensionRestrictions
? PlatformKind::macOSApplicationExtension
: PlatformKind::macOS);
}
if (LangOpts.Target.isTvOS()) {
return (LangOpts.EnableAppExtensionRestrictions
? PlatformKind::tvOSApplicationExtension
: PlatformKind::tvOS);
}
if (LangOpts.Target.isWatchOS()) {
return (LangOpts.EnableAppExtensionRestrictions
? PlatformKind::watchOSApplicationExtension
: PlatformKind::watchOS);
}
if (LangOpts.Target.isiOS()) {
if (tripleIsMacCatalystEnvironment(LangOpts.Target))
return (LangOpts.EnableAppExtensionRestrictions
? PlatformKind::macCatalystApplicationExtension
: PlatformKind::macCatalyst);
return (LangOpts.EnableAppExtensionRestrictions
? PlatformKind::iOSApplicationExtension
: PlatformKind::iOS);
}
return PlatformKind::none;
}
bool swift::inheritsAvailabilityFromPlatform(PlatformKind Child,
PlatformKind Parent) {
if (Child == PlatformKind::macCatalyst && Parent == PlatformKind::iOS)
return true;
if (Child == PlatformKind::macCatalystApplicationExtension) {
if (Parent == PlatformKind::iOS ||
Parent == PlatformKind::iOSApplicationExtension ||
Parent == PlatformKind::macCatalyst) {
return true;
}
}
// Ideally we would have all ApplicationExtension platforms
// inherit from their non-extension platform.
return false;
}
llvm::VersionTuple swift::canonicalizePlatformVersion(
PlatformKind platform, const llvm::VersionTuple &version) {
// Canonicalize macOS version for macOS Big Sur to treat
// 10.16 as 11.0.
if (platform == PlatformKind::macOS ||
platform == PlatformKind::macOSApplicationExtension) {
return llvm::Triple::getCanonicalVersionForOS(llvm::Triple::MacOSX,
version);
}
return version;
}
|
/***********************************************************************
This file is part of the librjmcmc project source files.
Copyright : Institut Geographique National (2008-2012)
Contributors : Mathieu Brédif, Olivier Tournaire, Didier Boldo
email : librjmcmc@ign.fr
This software is a generic C++ library for stochastic optimization.
This software is governed by the CeCILL license under French law and
abiding by the rules of distribution of free software. You can use,
modify and/or redistribute the software under the terms of the CeCILL
license as circulated by CEA, CNRS and INRIA at the following URL
"http://www.cecill.info".
As a counterpart to the access to the source code and rights to copy,
modify and redistribute granted by the license, users are provided only
with a limited warranty and the software's author, the holder of the
economic rights, and the successive licensors have only limited liability.
In this respect, the user's attention is drawn to the risks associated
with loading, using, modifying and/or developing or reproducing the
software by the user in light of its specific status of free software,
that may mean that it is complicated to manipulate, and that also
therefore means that it is reserved for developers and experienced
professionals having in-depth computer knowledge. Users are therefore
encouraged to load and test the software's suitability as regards their
requirements in conditions enabling the security of their systems and/or
data to be ensured and, more generally, to use and operate it in the
same conditions as regards security.
The fact that you are presently reading this means that you have had
knowledge of the CeCILL license and that you accept its terms.
***********************************************************************/
#ifndef VECTOR_CONFIGURATION_HPP
#define VECTOR_CONFIGURATION_HPP
#include "configuration.hpp"
#include "rjmcmc/util/variant.hpp"
namespace marked_point_process {
template<typename T, typename UnaryEnergy, typename BinaryEnergy, typename Accelerator=trivial_accelerator>
class vector_configuration
{
typedef std::vector<T> container;
container m_container;
UnaryEnergy m_unary_energy;
BinaryEnergy m_binary_energy;
Accelerator m_accelerator;
public:
typedef typename container::const_iterator const_iterator;
typedef typename container::iterator iterator;
typedef T value_type;
typedef vector_configuration<T,UnaryEnergy, BinaryEnergy, Accelerator> self;
typedef internal::modification<self> modification;
vector_configuration(UnaryEnergy unary_energy, BinaryEnergy binary_energy, Accelerator accelerator=Accelerator())
: m_unary_energy(unary_energy), m_binary_energy(binary_energy), m_accelerator(accelerator)
{}
// objects
inline size_t size() const { return m_container.size(); }
inline bool empty() const { return m_container.empty(); }
inline iterator begin() { return m_container.begin(); }
inline iterator end () { return m_container.end (); }
inline const_iterator begin() const { return m_container.begin(); }
inline const_iterator end () const { return m_container.end (); }
inline const value_type& value( const_iterator v ) const { return *v; }
// container
inline void clear() { m_container.clear(); }
template<typename U>
void insert(const U&u) {
m_container.push_back(u);
}
void remove( const_iterator v ) {
std::swap(const_cast<value_type&>(*v),m_container.back());
m_container.pop_back();
}
template<typename F> inline void for_each(F f) { std::for_each(m_container.begin(),m_container.end(),f); }
template<typename F> inline void for_each(F f) const { std::for_each(m_container.begin(),m_container.end(),f); }
// energy
inline double energy () const {
return unary_energy()+binary_energy();
}
double unary_energy() const
{
double e = 0.;
for (const_iterator it = m_container.begin(); it != m_container.end(); ++it)
e += rjmcmc::apply_visitor(m_unary_energy, *it );
return e;
}
double binary_energy() const
{
double e = 0.;
for (const_iterator i = m_container.begin(); i != m_container.end(); ++i)
for (const_iterator j = i+1; j != m_container.end(); ++j)
e += rjmcmc::apply_visitor(m_binary_energy, *i, *j );
return e;
}
// delta energy
template <typename Modification> double delta_energy(const Modification &modif) const
{
return delta_birth(modif)+delta_death(modif);
}
template <typename Modification> double delta_birth(const Modification &modif) const
{
double delta = 0;
typedef typename Modification::birth_type::const_iterator bci;
typedef typename Modification::death_type::const_iterator dci;
bci bbeg = modif.birth().begin();
bci bend = modif.birth().end();
dci dbeg = modif.death().begin();
dci dend = modif.death().end();
for(bci it=bbeg; it!=bend; ++it) {
delta += rjmcmc::apply_visitor(m_unary_energy,*it);
for (const_iterator it2=m_container.begin(); it2 != m_container.end(); ++it2)
if (std::find(dbeg,dend,it2)==dend)
delta += rjmcmc::apply_visitor(m_binary_energy, *it, value(it2) );
for (bci it2=it+1; it2 != bend; ++it2)
delta += rjmcmc::apply_visitor(m_binary_energy, *it, *it2);
}
return delta;
}
template <typename Modification> double delta_death(const Modification &modif) const
{
double delta = 0;
typedef typename Modification::death_type::const_iterator dci;
dci dbeg = modif.death().begin();
dci dend = modif.death().end();
for(dci it=dbeg; it!=dend; ++it) {
delta -= rjmcmc::apply_visitor(m_unary_energy, value(*it));
for (const_iterator it2=m_container.begin(); it2 != m_container.end(); ++it2)
if(std::find(it,dend,it2)==dend)
delta -= rjmcmc::apply_visitor(m_binary_energy, value(*it), *it2 );
}
return delta;
}
// audit energy
inline double audit_unary_energy () const { return unary_energy();}
inline double audit_binary_energy() const { return binary_energy();}
inline unsigned int audit_structure() const { return 0; }
};
}; // namespace marked_point_process
#endif // VECTOR_CONFIGURATION_HPP
|
//HEADER_GOES_HERE
#include "../types.h"
// Tracks which missile files are already loaded
int MissileFileFlag;
int monster_cpp_init_value; // weak
int monstkills[MAXMONSTERS];
int monstactive[MAXMONSTERS];
int nummonsters;
int sgbSaveSoundOn; // weak
MonsterStruct monster[MAXMONSTERS];
int totalmonsters; // weak
CMonster Monsters[16];
// int END_Monsters_17; // weak
int monstimgtot; // weak
int uniquetrans;
int nummtypes;
const int monster_inf = 0x7F800000; // weak
const char plr2monst[9] = { 0, 5, 3, 7, 1, 4, 6, 0, 2 };
const unsigned char counsmiss[4] = { MIS_FIREBOLT, MIS_CBOLT, MIS_LIGHTCTRL, MIS_FIREBALL };
/* data */
MonsterData monsterdata[112] =
{
{ 128, 799, "Monsters\\Zombie\\Zombie%c.CL2", 0, "Monsters\\Zombie\\Zombie%c%i.WAV", 0, 0, NULL, { 11, 24, 12, 6, 16, 0 }, { 4, 0, 0, 0, 0, 0 }, "Zombie", 1, 3, 1, 4, 7, AI_ZOMBIE, 0, 0, 10, 8, 2, 5, 0, 0, 0, 0, 5, MC_UNDEAD, 72, 72, 0, 3, 54 },
{ 128, 799, "Monsters\\Zombie\\Zombie%c.CL2", 0, "Monsters\\Zombie\\Zombie%c%i.WAV", 0, 1, "Monsters\\Zombie\\Bluered.TRN", { 11, 24, 12, 6, 16, 0 }, { 4, 0, 0, 0, 0, 0 }, "Ghoul", 2, 4, 2, 7, 11, AI_ZOMBIE, 0, 1, 10, 8, 3, 10, 0, 0, 0, 0, 10, MC_UNDEAD, 72, 72, 0, 3, 58 },
{ 128, 799, "Monsters\\Zombie\\Zombie%c.CL2", 0, "Monsters\\Zombie\\Zombie%c%i.WAV", 0, 1, "Monsters\\Zombie\\Grey.TRN", { 11, 24, 12, 6, 16, 0 }, { 4, 0, 0, 0, 0, 0 }, "Rotting Carcass", 2, 6, 4, 15, 25, AI_ZOMBIE, 0, 2, 25, 8, 5, 15, 0, 0, 0, 0, 15, MC_UNDEAD, 72, 74, 0, 3, 136 },
{ 128, 799, "Monsters\\Zombie\\Zombie%c.CL2", 0, "Monsters\\Zombie\\Zombie%c%i.WAV", 0, 1, "Monsters\\Zombie\\Yellow.TRN", { 11, 24, 12, 6, 16, 0 }, { 4, 0, 0, 0, 0, 0 }, "Black Death", 4, 8, 6, 25, 40, AI_ZOMBIE, 0, 3, 30, 8, 6, 22, 0, 0, 0, 0, 20, MC_UNDEAD, 72, 76, 0, 3, 240 },
{ 128, 543, "Monsters\\FalSpear\\Phall%c.CL2", 1, "Monsters\\FalSpear\\Phall%c%i.WAV", 1, 1, "Monsters\\FalSpear\\FallenT.TRN", { 11, 11, 13, 11, 18, 13 }, { 3, 0, 0, 0, 0, 0 }, "Fallen One", 1, 3, 1, 1, 4, AI_FALLEN, 0, 0, 15, 7, 1, 3, 0, 5, 0, 0, 0, MC_ANIMAL, 0, 0, 0, 3, 46 },
{ 128, 543, "Monsters\\FalSpear\\Phall%c.CL2", 1, "Monsters\\FalSpear\\Phall%c%i.WAV", 1, 1, "Monsters\\FalSpear\\Dark.TRN", { 11, 11, 13, 11, 18, 13 }, { 3, 0, 0, 0, 0, 0 }, "Carver", 2, 5, 3, 4, 8, AI_FALLEN, 0, 2, 20, 7, 2, 5, 0, 5, 0, 0, 5, MC_ANIMAL, 0, 0, 0, 3, 80 },
{ 128, 543, "Monsters\\FalSpear\\Phall%c.CL2", 1, "Monsters\\FalSpear\\Phall%c%i.WAV", 1, 0, NULL, { 11, 11, 13, 11, 18, 13 }, { 3, 0, 0, 0, 0, 0 }, "Devil Kin", 3, 7, 5, 12, 24, AI_FALLEN, 0, 2, 25, 7, 3, 7, 0, 5, 0, 0, 10, MC_ANIMAL, 0, 2, 0, 3, 155 },
{ 128, 543, "Monsters\\FalSpear\\Phall%c.CL2", 1, "Monsters\\FalSpear\\Phall%c%i.WAV", 1, 1, "Monsters\\FalSpear\\Blue.TRN", { 11, 11, 13, 11, 18, 13 }, { 3, 0, 0, 0, 0, 0 }, "Dark One", 5, 9, 7, 20, 36, AI_FALLEN, 0, 3, 30, 7, 4, 8, 0, 5, 0, 0, 15, MC_ANIMAL, 64, 68, 0, 3, 255 },
{ 128, 553, "Monsters\\SkelAxe\\SklAx%c.CL2", 1, "Monsters\\SkelAxe\\SklAx%c%i.WAV", 0, 1, "Monsters\\SkelAxe\\White.TRN", { 12, 8, 13, 6, 17, 16 }, { 5, 0, 0, 0, 0, 0 }, "Skeleton", 1, 3, 1, 2, 4, AI_SKELSD, 0, 0, 20, 8, 1, 4, 0, 0, 0, 0, 0, MC_UNDEAD, 72, 72, 0, 3, 64 },
{ 128, 553, "Monsters\\SkelAxe\\SklAx%c.CL2", 1, "Monsters\\SkelAxe\\SklAx%c%i.WAV", 0, 1, "Monsters\\SkelAxe\\Skelt.TRN", { 12, 8, 13, 6, 17, 16 }, { 4, 0, 0, 0, 0, 0 }, "Corpse Axe", 2, 5, 2, 4, 7, AI_SKELSD, 0, 1, 25, 8, 3, 5, 0, 0, 0, 0, 0, MC_UNDEAD, 72, 72, 0, 3, 68 },
{ 128, 553, "Monsters\\SkelAxe\\SklAx%c.CL2", 1, "Monsters\\SkelAxe\\SklAx%c%i.WAV", 0, 0, NULL, { 12, 8, 13, 6, 17, 16 }, { 2, 0, 0, 0, 0, 0 }, "Burning Dead", 2, 6, 4, 8, 12, AI_SKELSD, 0, 2, 30, 8, 3, 7, 0, 0, 0, 0, 5, MC_UNDEAD, 74, 88, 0, 3, 154 },
{ 128, 553, "Monsters\\SkelAxe\\SklAx%c.CL2", 1, "Monsters\\SkelAxe\\SklAx%c%i.WAV", 0, 1, "Monsters\\SkelAxe\\Black.TRN", { 12, 8, 13, 6, 17, 16 }, { 3, 0, 0, 0, 0, 0 }, "Horror", 4, 8, 6, 12, 20, AI_SKELSD, 0, 3, 35, 8, 4, 9, 0, 0, 0, 0, 15, MC_UNDEAD, 76, 76, 0, 3, 264 },
{ 128, 623, "Monsters\\FalSword\\Fall%c.CL2", 1, "Monsters\\FalSword\\Fall%c%i.WAV", 1, 1, "Monsters\\FalSword\\FallenT.TRN", { 12, 12, 13, 11, 14, 15 }, { 3, 0, 0, 0, 0, 0 }, "Fallen One", 1, 3, 1, 2, 5, AI_FALLEN, 0, 0, 15, 8, 1, 4, 0, 5, 0, 0, 10, MC_ANIMAL, 0, 0, 0, 3, 52 },
{ 128, 623, "Monsters\\FalSword\\Fall%c.CL2", 1, "Monsters\\FalSword\\Fall%c%i.WAV", 1, 1, "Monsters\\FalSword\\Dark.TRN", { 12, 12, 13, 11, 14, 15 }, { 3, 0, 0, 0, 0, 0 }, "Carver", 2, 5, 3, 5, 9, AI_FALLEN, 0, 1, 20, 8, 2, 7, 0, 5, 0, 0, 15, MC_ANIMAL, 0, 0, 0, 3, 90 },
{ 128, 623, "Monsters\\FalSword\\Fall%c.CL2", 1, "Monsters\\FalSword\\Fall%c%i.WAV", 1, 0, NULL, { 12, 12, 13, 11, 14, 15 }, { 3, 0, 0, 0, 0, 0 }, "Devil Kin", 3, 7, 5, 16, 24, AI_FALLEN, 0, 2, 25, 8, 4, 10, 0, 5, 0, 0, 20, MC_ANIMAL, 0, 2, 0, 3, 180 },
{ 128, 623, "Monsters\\FalSword\\Fall%c.CL2", 1, "Monsters\\FalSword\\Fall%c%i.WAV", 1, 1, "Monsters\\FalSword\\Blue.TRN", { 12, 12, 13, 11, 14, 15 }, { 3, 0, 0, 0, 0, 0 }, "Dark One", 5, 9, 7, 24, 36, AI_FALLEN, 0, 3, 30, 8, 4, 12, 0, 5, 0, 0, 25, MC_ANIMAL, 64, 68, 0, 3, 280 },
{ 128, 410, "Monsters\\Scav\\Scav%c.CL2", 1, "Monsters\\Scav\\Scav%c%i.WAV", 0, 0, NULL, { 12, 8, 12, 6, 20, 11 }, { 2, 0, 0, 0, 0, 0 }, "Scavenger", 1, 4, 2, 3, 6, AI_SCAV, 0, 0, 20, 7, 1, 5, 0, 0, 0, 0, 10, MC_ANIMAL, 0, 2, 0, 3, 80 },
{ 128, 410, "Monsters\\Scav\\Scav%c.CL2", 1, "Monsters\\Scav\\Scav%c%i.WAV", 0, 1, "Monsters\\Scav\\ScavBr.TRN", { 12, 8, 12, 6, 20, 11 }, { 2, 0, 0, 0, 0, 0 }, "Plague Eater", 3, 6, 4, 12, 24, AI_SCAV, 0, 1, 30, 7, 1, 8, 0, 0, 0, 0, 20, MC_ANIMAL, 0, 4, 0, 3, 188 },
{ 128, 410, "Monsters\\Scav\\Scav%c.CL2", 1, "Monsters\\Scav\\Scav%c%i.WAV", 0, 1, "Monsters\\Scav\\ScavBe.TRN", { 12, 8, 12, 6, 20, 11 }, { 2, 0, 0, 0, 0, 0 }, "Shadow Beast", 4, 8, 6, 24, 36, AI_SCAV, 0, 2, 35, 7, 3, 12, 0, 0, 0, 0, 25, MC_ANIMAL, 64, 66, 0, 3, 375 },
{ 128, 410, "Monsters\\Scav\\Scav%c.CL2", 1, "Monsters\\Scav\\Scav%c%i.WAV", 0, 1, "Monsters\\Scav\\ScavW.TRN", { 12, 8, 12, 6, 20, 11 }, { 2, 0, 0, 0, 0, 0 }, "Bone Gasher", 6, 10, 8, 28, 40, AI_SCAV, 0, 3, 35, 7, 5, 15, 0, 0, 0, 0, 30, MC_ANIMAL, 65, 68, 0, 3, 552 },
{ 128, 567, "Monsters\\SkelBow\\SklBw%c.CL2", 1, "Monsters\\SkelBow\\SklBw%c%i.WAV", 0, 1, "Monsters\\SkelBow\\White.TRN", { 9, 8, 16, 5, 16, 16 }, { 4, 0, 0, 0, 0, 0 }, "Skeleton", 2, 5, 3, 2, 4, AI_SKELBOW, 0, 0, 15, 12, 1, 2, 0, 0, 0, 0, 0, MC_UNDEAD, 72, 72, 0, 3, 110 },
{ 128, 567, "Monsters\\SkelBow\\SklBw%c.CL2", 1, "Monsters\\SkelBow\\SklBw%c%i.WAV", 0, 1, "Monsters\\SkelBow\\Skelt.TRN", { 9, 8, 16, 5, 16, 16 }, { 4, 0, 0, 0, 0, 0 }, "Corpse Bow", 3, 7, 5, 8, 16, AI_SKELBOW, 0, 1, 25, 12, 1, 4, 0, 0, 0, 0, 0, MC_UNDEAD, 72, 72, 0, 3, 210 },
{ 128, 567, "Monsters\\SkelBow\\SklBw%c.CL2", 1, "Monsters\\SkelBow\\SklBw%c%i.WAV", 0, 0, NULL, { 9, 8, 16, 5, 16, 16 }, { 2, 0, 0, 0, 0, 0 }, "Burning Dead", 5, 9, 7, 10, 24, AI_SKELBOW, 0, 2, 30, 12, 1, 6, 0, 0, 0, 0, 5, MC_UNDEAD, 74, 88, 0, 3, 364 },
{ 128, 567, "Monsters\\SkelBow\\SklBw%c.CL2", 1, "Monsters\\SkelBow\\SklBw%c%i.WAV", 0, 1, "Monsters\\SkelBow\\Black.TRN", { 9, 8, 16, 5, 16, 16 }, { 3, 0, 0, 0, 0, 0 }, "Horror", 7, 11, 9, 15, 45, AI_SKELBOW, 0, 3, 35, 12, 2, 9, 0, 0, 0, 0, 15, MC_UNDEAD, 76, 76, 0, 3, 594 },
{ 128, 575, "Monsters\\SkelSd\\SklSr%c.CL2", 1, "Monsters\\SkelSd\\SklSr%c%i.WAV", 1, 1, "Monsters\\SkelSd\\White.TRN", { 13, 8, 12, 7, 15, 16 }, { 4, 0, 0, 0, 0, 0 }, "Skeleton Captain", 1, 4, 2, 3, 6, AI_SKELSD, 0, 0, 20, 8, 2, 7, 0, 0, 0, 0, 10, MC_UNDEAD, 72, 72, 0, 3, 90 },
{ 128, 575, "Monsters\\SkelSd\\SklSr%c.CL2", 1, "Monsters\\SkelSd\\SklSr%c%i.WAV", 0, 1, "Monsters\\SkelSd\\Skelt.TRN", { 13, 8, 12, 7, 15, 16 }, { 4, 0, 0, 0, 0, 0 }, "Corpse Captain", 2, 6, 4, 12, 20, AI_SKELSD, 0, 1, 30, 8, 3, 9, 0, 0, 0, 0, 5, MC_UNDEAD, 72, 72, 0, 3, 200 },
{ 128, 575, "Monsters\\SkelSd\\SklSr%c.CL2", 1, "Monsters\\SkelSd\\SklSr%c%i.WAV", 0, 0, NULL, { 13, 8, 12, 7, 15, 16 }, { 4, 0, 0, 0, 0, 0 }, "Burning Dead Captain", 4, 8, 6, 16, 30, AI_SKELSD, 0, 2, 35, 8, 4, 10, 0, 0, 0, 0, 15, MC_UNDEAD, 74, 88, 0, 3, 393 },
{ 128, 575, "Monsters\\SkelSd\\SklSr%c.CL2", 1, "Monsters\\SkelSd\\SklSr%c%i.WAV", 0, 1, "Monsters\\SkelSd\\Black.TRN", { 13, 8, 12, 7, 15, 16 }, { 4, 0, 0, 0, 0, 0 }, "Horror Captain", 6, 10, 8, 35, 50, AI_SKELSD, 256, 3, 40, 8, 5, 14, 0, 0, 0, 0, 30, MC_UNDEAD, 76, 76, 0, 3, 604 },
{ 128, 2000, "Monsters\\TSneak\\TSneak%c.CL2", 0, "Monsters\\TSneak\\Sneakl%c%i.WAV", 0, 0, NULL, { 13, 13, 15, 11, 16, 0 }, { 2, 0, 0, 0, 0, 0 }, "Invisible Lord", 14, 14, 14, 278, 278, AI_SKELSD, 256, 3, 65, 8, 16, 30, 0, 0, 0, 0, 60, MC_DEMON, 71, 71, 0, 3, 2000 },
{ 128, 992, "Monsters\\Sneak\\Sneak%c.CL2", 1, "Monsters\\Sneak\\Sneak%c%i.WAV", 0, 0, NULL, { 16, 8, 12, 8, 24, 15 }, { 2, 0, 0, 0, 0, 0 }, "Hidden", 3, 8, 5, 8, 24, AI_SNEAK, 1, 0, 35, 8, 3, 6, 0, 0, 0, 0, 25, MC_DEMON, 0, 64, 0, 3, 278 },
{ 128, 992, "Monsters\\Sneak\\Sneak%c.CL2", 1, "Monsters\\Sneak\\Sneak%c%i.WAV", 0, 1, "Monsters\\Sneak\\Sneakv2.TRN", { 16, 8, 12, 8, 24, 15 }, { 2, 0, 0, 0, 0, 0 }, "Stalker", 8, 12, 9, 30, 45, AI_SNEAK, 257, 1, 40, 8, 8, 16, 0, 0, 0, 0, 30, MC_DEMON, 0, 64, 0, 3, 630 },
{ 128, 992, "Monsters\\Sneak\\Sneak%c.CL2", 1, "Monsters\\Sneak\\Sneak%c%i.WAV", 0, 1, "Monsters\\Sneak\\Sneakv3.TRN", { 16, 8, 12, 8, 24, 15 }, { 2, 0, 0, 0, 0, 0 }, "Unseen", 10, 14, 11, 35, 50, AI_SNEAK, 257, 2, 45, 8, 12, 20, 0, 0, 0, 0, 30, MC_DEMON, 65, 72, 0, 3, 935 },
{ 128, 992, "Monsters\\Sneak\\Sneak%c.CL2", 1, "Monsters\\Sneak\\Sneak%c%i.WAV", 0, 1, "Monsters\\Sneak\\Sneakv1.TRN", { 16, 8, 12, 8, 24, 15 }, { 2, 0, 0, 0, 0, 0 }, "Illusion Weaver", 14, 18, 13, 40, 60, AI_SNEAK, 257, 3, 60, 8, 16, 24, 0, 0, 0, 0, 30, MC_DEMON, 3, 74, 0, 3, 1500 },
{ 160, 2000, "Monsters\\GoatLord\\GoatL%c.CL2", 0, "Monsters\\GoatLord\\Goatl%c%i.WAV", 0, 0, NULL, { 13, 13, 14, 9, 16, 0 }, { 2, 0, 0, 0, 0, 0 }, "Lord Sayter", 13, 13, 12, 351, 351, AI_SKELSD, 256, 3, 80, 8, 14, 24, 0, 0, 0, 0, 60, MC_DEMON, 67, 67, 0, 3, 1500 },
{ 128, 1030, "Monsters\\GoatMace\\Goat%c.CL2", 1, "Monsters\\GoatMace\\Goat%c%i.WAV", 0, 0, NULL, { 12, 8, 12, 6, 20, 12 }, { 2, 0, 0, 0, 1, 0 }, "Flesh Clan", 6, 10, 8, 30, 45, AI_GOATMC, 768, 0, 50, 8, 4, 10, 0, 0, 0, 0, 40, MC_DEMON, 0, 0, 0, 3, 460 },
{ 128, 1030, "Monsters\\GoatMace\\Goat%c.CL2", 1, "Monsters\\GoatMace\\Goat%c%i.WAV", 0, 1, "Monsters\\GoatMace\\Beige.TRN", { 12, 8, 12, 6, 20, 12 }, { 2, 0, 0, 0, 1, 0 }, "Stone Clan", 8, 12, 10, 40, 55, AI_GOATMC, 768, 1, 60, 8, 6, 12, 0, 0, 0, 0, 40, MC_DEMON, 65, 72, 0, 3, 685 },
{ 128, 1030, "Monsters\\GoatMace\\Goat%c.CL2", 1, "Monsters\\GoatMace\\Goat%c%i.WAV", 0, 1, "Monsters\\GoatMace\\Red.TRN", { 12, 8, 12, 6, 20, 12 }, { 2, 0, 0, 0, 1, 0 }, "Fire Clan", 10, 14, 12, 50, 65, AI_GOATMC, 768, 2, 70, 8, 8, 16, 0, 0, 0, 0, 45, MC_DEMON, 2, 16, 0, 3, 906 },
{ 128, 1030, "Monsters\\GoatMace\\Goat%c.CL2", 1, "Monsters\\GoatMace\\Goat%c%i.WAV", 0, 1, "Monsters\\GoatMace\\Gray.TRN", { 12, 8, 12, 6, 20, 12 }, { 2, 0, 0, 0, 1, 0 }, "Night Clan", 12, 16, 14, 55, 70, AI_GOATMC, 768, 3, 80, 8, 10, 20, 15, 0, 30, 30, 50, MC_DEMON, 65, 72, 0, 3, 1190 },
{ 96, 364, "Monsters\\Bat\\Bat%c.CL2", 0, "Monsters\\Bat\\Bat%c%i.WAV", 0, 1, "Monsters\\Bat\\red.trn", { 9, 13, 10, 9, 13, 0 }, { 0, 0, 0, 0, 0, 0 }, "Fiend", 2, 5, 3, 3, 6, AI_BAT, 0, 0, 35, 5, 1, 6, 0, 0, 0, 0, 0, MC_ANIMAL, 0, 0, 16384, 6, 102 },
{ 96, 364, "Monsters\\Bat\\Bat%c.CL2", 0, "Monsters\\Bat\\Bat%c%i.WAV", 0, 0, NULL, { 9, 13, 10, 9, 13, 0 }, { 0, 0, 0, 0, 0, 0 }, "Blink", 5, 9, 7, 12, 28, AI_BAT, 0, 1, 45, 5, 1, 8, 0, 0, 0, 0, 15, MC_ANIMAL, 0, 0, 16384, 6, 340 },
{ 96, 364, "Monsters\\Bat\\Bat%c.CL2", 0, "Monsters\\Bat\\Bat%c%i.WAV", 0, 1, "Monsters\\Bat\\grey.trn", { 9, 13, 10, 9, 13, 0 }, { 0, 0, 0, 0, 0, 0 }, "Gloom", 7, 11, 9, 28, 36, AI_BAT, 256, 2, 70, 5, 4, 12, 0, 0, 0, 0, 35, MC_ANIMAL, 1, 65, 16384, 6, 509 },
{ 96, 364, "Monsters\\Bat\\Bat%c.CL2", 0, "Monsters\\Bat\\Bat%c%i.WAV", 0, 1, "Monsters\\Bat\\orange.trn", { 9, 13, 10, 9, 13, 0 }, { 0, 0, 0, 0, 0, 0 }, "Familiar", 11, 15, 13, 20, 35, AI_BAT, 256, 3, 50, 5, 4, 16, 0, 0, 0, 0, 35, MC_DEMON, 33, 97, 16384, 6, 448 },
{ 128, 1040, "Monsters\\GoatBow\\GoatB%c.CL2", 0, "Monsters\\GoatBow\\GoatB%c%i.WAV", 0, 0, NULL, { 12, 8, 16, 6, 20, 0 }, { 3, 0, 0, 0, 0, 0 }, "Flesh Clan", 6, 10, 8, 20, 35, AI_GOATBOW, 512, 0, 35, 13, 1, 7, 0, 0, 0, 0, 35, MC_DEMON, 0, 0, 0, 3, 448 },
{ 128, 1040, "Monsters\\GoatBow\\GoatB%c.CL2", 0, "Monsters\\GoatBow\\GoatB%c%i.WAV", 0, 1, "Monsters\\GoatBow\\Beige.TRN", { 12, 8, 16, 6, 20, 0 }, { 3, 0, 0, 0, 0, 0 }, "Stone Clan", 8, 12, 10, 30, 40, AI_GOATBOW, 512, 1, 40, 13, 2, 9, 0, 0, 0, 0, 35, MC_DEMON, 65, 72, 0, 3, 645 },
{ 128, 1040, "Monsters\\GoatBow\\GoatB%c.CL2", 0, "Monsters\\GoatBow\\GoatB%c%i.WAV", 0, 1, "Monsters\\GoatBow\\Red.TRN", { 12, 8, 16, 6, 20, 0 }, { 3, 0, 0, 0, 0, 0 }, "Fire Clan", 10, 14, 12, 40, 50, AI_GOATBOW, 768, 2, 45, 13, 3, 11, 0, 0, 0, 0, 35, MC_DEMON, 2, 16, 0, 3, 822 },
{ 128, 1040, "Monsters\\GoatBow\\GoatB%c.CL2", 0, "Monsters\\GoatBow\\GoatB%c%i.WAV", 0, 1, "Monsters\\GoatBow\\Gray.TRN", { 12, 8, 16, 6, 20, 0 }, { 3, 0, 0, 0, 0, 0 }, "Night Clan", 12, 16, 14, 50, 65, AI_GOATBOW, 768, 3, 50, 13, 4, 13, 15, 0, 0, 0, 40, MC_DEMON, 65, 72, 0, 3, 1092 },
{ 128, 716, "Monsters\\Acid\\Acid%c.CL2", 1, "Monsters\\Acid\\Acid%c%i.WAV", 1, 0, NULL, { 13, 8, 12, 8, 16, 12 }, { 0, 0, 0, 0, 0, 0 }, "Acid Beast", 10, 14, 11, 40, 66, AI_ACID, 0, 0, 40, 8, 4, 12, 25, 8, 0, 0, 30, MC_ANIMAL, 128, 136, 0, 3, 846 },
{ 128, 716, "Monsters\\Acid\\Acid%c.CL2", 1, "Monsters\\Acid\\Acid%c%i.WAV", 1, 1, "Monsters\\Acid\\AcidBlk.TRN", { 13, 8, 12, 8, 16, 12 }, { 0, 0, 0, 0, 0, 0 }, "Poison Spitter", 14, 18, 15, 60, 85, AI_ACID, 0, 1, 45, 8, 4, 16, 25, 8, 0, 0, 30, MC_ANIMAL, 128, 136, 0, 3, 1248 },
{ 128, 716, "Monsters\\Acid\\Acid%c.CL2", 1, "Monsters\\Acid\\Acid%c%i.WAV", 1, 1, "Monsters\\Acid\\AcidB.TRN", { 13, 8, 12, 8, 16, 12 }, { 0, 0, 0, 0, 0, 0 }, "Pit Beast", 18, 22, 21, 80, 110, AI_ACID, 0, 2, 55, 8, 8, 18, 35, 8, 0, 0, 35, MC_ANIMAL, 129, 140, 0, 3, 2060 },
{ 128, 716, "Monsters\\Acid\\Acid%c.CL2", 1, "Monsters\\Acid\\Acid%c%i.WAV", 1, 1, "Monsters\\Acid\\AcidR.TRN", { 13, 8, 12, 8, 16, 12 }, { 0, 0, 0, 0, 0, 0 }, "Lava Maw", 22, 27, 25, 100, 150, AI_ACID, 0, 3, 65, 8, 10, 20, 40, 8, 0, 0, 35, MC_ANIMAL, 145, 152, 0, 3, 2940 },
{ 160, 1010, "Monsters\\SKing\\SKing%c.CL2", 1, "Monsters\\SKing\\SKing%c%i.WAV", 1, 1, "Monsters\\SkelAxe\\White.TRN", { 8, 6, 16, 6, 16, 6 }, { 2, 0, 0, 0, 0, 2 }, "Skeleton King", 6, 6, 9, 140, 140, AI_SKELKING, 768, 3, 60, 8, 6, 16, 0, 0, 0, 0, 70, MC_UNDEAD, 78, 120, 32769, 7, 570 },
{ 128, 980, "Monsters\\FatC\\FatC%c.CL2", 0, "Monsters\\FatC\\FatC%c%i.WAV", 0, 0, NULL, { 10, 8, 12, 6, 16, 0 }, { 1, 0, 0, 0, 0, 0 }, "The Butcher", 0, 0, 1, 320, 320, AI_CLEAVER, 0, 3, 50, 8, 6, 12, 0, 0, 0, 0, 50, MC_DEMON, 6, 49, 32768, 3, 710 },
{ 128, 1130, "Monsters\\Fat\\Fat%c.CL2", 1, "Monsters\\Fat\\Fat%c%i.WAV", 0, 0, NULL, { 8, 10, 15, 6, 16, 10 }, { 4, 0, 0, 0, 0, 0 }, "Overlord", 8, 12, 10, 60, 80, AI_FAT, 0, 0, 55, 8, 6, 12, 0, 0, 0, 0, 55, MC_DEMON, 0, 2, 0, 3, 635 },
{ 128, 1130, "Monsters\\Fat\\Fat%c.CL2", 1, "Monsters\\Fat\\Fat%c%i.WAV", 0, 1, "Monsters\\Fat\\Blue.TRN", { 8, 10, 15, 6, 16, 10 }, { 4, 0, 0, 0, 0, 0 }, "Mud Man", 13, 17, 14, 100, 125, AI_FAT, 256, 1, 60, 8, 8, 16, 0, 0, 0, 0, 60, MC_DEMON, 0, 32, 0, 3, 1165 },
{ 128, 1130, "Monsters\\Fat\\Fat%c.CL2", 1, "Monsters\\Fat\\Fat%c%i.WAV", 0, 1, "Monsters\\Fat\\FatB.TRN", { 8, 10, 15, 6, 16, 10 }, { 4, 0, 0, 0, 0, 0 }, "Toad Demon", 15, 19, 16, 135, 160, AI_FAT, 256, 2, 70, 8, 8, 16, 40, 0, 8, 20, 65, MC_DEMON, 8, 12, 0, 3, 1380 },
{ 128, 1130, "Monsters\\Fat\\Fat%c.CL2", 1, "Monsters\\Fat\\Fat%c%i.WAV", 0, 1, "Monsters\\Fat\\FatF.TRN", { 8, 10, 15, 6, 16, 10 }, { 4, 0, 0, 0, 0, 0 }, "Flayed One", 19, 23, 20, 160, 200, AI_FAT, 256, 3, 85, 8, 10, 20, 0, 0, 0, 0, 70, MC_DEMON, 17, 24, 0, 3, 2058 },
{ 160, 2420, "Monsters\\Worm\\Worm%c.CL2", 0, "Monsters\\Fat\\Fat%c%i.WAV", 0, 0, NULL, { 13, 13, 13, 11, 19, 0 }, { 0, 0, 0, 0, 0, 0 }, "Wyrm", 9, 13, 11, 60, 90, AI_SKELSD, 0, 0, 40, 8, 4, 10, 0, 0, 0, 0, 25, MC_ANIMAL, 1, 1, 0, 3, 660 },
{ 160, 2420, "Monsters\\Worm\\Worm%c.CL2", 0, "Monsters\\Fat\\Fat%c%i.WAV", 0, 0, NULL, { 13, 13, 13, 11, 19, 0 }, { 0, 0, 0, 0, 0, 0 }, "Cave Slug", 11, 15, 13, 75, 110, AI_SKELSD, 0, 1, 50, 8, 6, 13, 0, 0, 0, 0, 30, MC_ANIMAL, 1, 1, 0, 3, 994 },
{ 160, 2420, "Monsters\\Worm\\Worm%c.CL2", 0, "Monsters\\Fat\\Fat%c%i.WAV", 0, 0, NULL, { 13, 13, 13, 11, 19, 0 }, { 0, 0, 0, 0, 0, 0 }, "Devil Wyrm", 13, 17, 15, 100, 140, AI_SKELSD, 0, 2, 55, 8, 8, 16, 0, 0, 0, 0, 30, MC_ANIMAL, 3, 3, 0, 3, 1320 },
{ 160, 2420, "Monsters\\Worm\\Worm%c.CL2", 0, "Monsters\\Fat\\Fat%c%i.WAV", 0, 0, NULL, { 13, 13, 13, 11, 19, 0 }, { 0, 0, 0, 0, 0, 0 }, "Devourer", 15, 19, 17, 125, 200, AI_SKELSD, 0, 3, 60, 8, 10, 20, 0, 0, 0, 0, 35, MC_ANIMAL, 67, 67, 0, 3, 1827 },
{ 128, 1680, "Monsters\\Magma\\Magma%c.CL2", 1, "Monsters\\Magma\\Magma%c%i.WAV", 1, 0, NULL, { 8, 10, 14, 7, 18, 18 }, { 2, 0, 0, 0, 1, 0 }, "Magma Demon", 14, 17, 13, 50, 70, AI_MAGMA, 768, 0, 45, 4, 2, 10, 50, 13, 0, 0, 45, MC_DEMON, 10, 24, 0, 7, 1076 },
{ 128, 1680, "Monsters\\Magma\\Magma%c.CL2", 1, "Monsters\\Magma\\Magma%c%i.WAV", 1, 1, "Monsters\\Magma\\Yellow.TRN", { 8, 10, 14, 7, 18, 18 }, { 2, 0, 0, 0, 1, 0 }, "Blood Stone", 15, 19, 14, 55, 75, AI_MAGMA, 768, 1, 50, 4, 2, 12, 50, 14, 0, 0, 45, MC_DEMON, 24, 24, 0, 7, 1309 },
{ 128, 1680, "Monsters\\Magma\\Magma%c.CL2", 1, "Monsters\\Magma\\Magma%c%i.WAV", 1, 1, "Monsters\\Magma\\Blue.TRN", { 8, 10, 14, 7, 18, 18 }, { 2, 0, 0, 0, 1, 0 }, "Hell Stone", 16, 20, 16, 60, 80, AI_MAGMA, 768, 2, 60, 4, 2, 20, 60, 14, 0, 0, 50, MC_DEMON, 24, 24, 0, 7, 1680 },
{ 128, 1680, "Monsters\\Magma\\Magma%c.CL2", 1, "Monsters\\Magma\\Magma%c%i.WAV", 1, 1, "Monsters\\Magma\\Wierd.TRN", { 8, 10, 14, 7, 18, 18 }, { 2, 0, 0, 0, 1, 0 }, "Lava Lord", 17, 21, 18, 70, 85, AI_MAGMA, 768, 3, 75, 4, 4, 24, 60, 14, 0, 0, 60, MC_DEMON, 24, 24, 0, 7, 2124 },
{ 160, 1630, "Monsters\\Rhino\\Rhino%c.CL2", 1, "Monsters\\Rhino\\Rhino%c%i.WAV", 1, 0, NULL, { 8, 8, 14, 6, 16, 6 }, { 2, 0, 0, 0, 0, 0 }, "Horned Demon", 12, 16, 13, 40, 80, AI_RHINO, 768, 0, 60, 7, 2, 16, 100, 0, 5, 32, 40, MC_ANIMAL, 0, 2, 0, 7, 1172 },
{ 160, 1630, "Monsters\\Rhino\\Rhino%c.CL2", 1, "Monsters\\Rhino\\Rhino%c%i.WAV", 1, 1, "Monsters\\Rhino\\Orange.TRN", { 8, 8, 14, 6, 16, 6 }, { 2, 0, 0, 0, 0, 0 }, "Mud Runner", 14, 18, 15, 50, 90, AI_RHINO, 768, 1, 70, 7, 6, 18, 100, 0, 12, 36, 45, MC_ANIMAL, 0, 2, 0, 7, 1404 },
{ 160, 1630, "Monsters\\Rhino\\Rhino%c.CL2", 1, "Monsters\\Rhino\\Rhino%c%i.WAV", 1, 1, "Monsters\\Rhino\\Blue.TRN", { 8, 8, 14, 6, 16, 6 }, { 2, 0, 0, 0, 0, 0 }, "Frost Charger", 16, 20, 17, 60, 100, AI_RHINO, 768, 2, 80, 7, 8, 20, 100, 0, 20, 40, 50, MC_ANIMAL, 12, 12, 0, 7, 1720 },
{ 160, 1630, "Monsters\\Rhino\\Rhino%c.CL2", 1, "Monsters\\Rhino\\Rhino%c%i.WAV", 1, 1, "Monsters\\Rhino\\RhinoB.TRN", { 8, 8, 14, 6, 16, 6 }, { 2, 0, 0, 0, 0, 0 }, "Obsidian Lord", 18, 22, 19, 70, 110, AI_RHINO, 768, 3, 90, 7, 10, 22, 100, 0, 20, 50, 55, MC_ANIMAL, 12, 56, 0, 7, 1809 },
{ 128, 1740, "Monsters\\Demskel\\Demskl%c.CL2", 1, "Monsters\\Thin\\Thin%c%i.WAV", 1, 0, "Monsters\\Thin\\Thinv3.TRN", { 10, 8, 20, 6, 24, 16 }, { 3, 0, 0, 0, 0, 0 }, "Bone Demon", 10, 14, 12, 70, 70, AI_STORM, 0, 0, 60, 8, 6, 14, 12, 0, 0, 0, 50, MC_DEMON, 72, 72, 0, 7, 1344 },
{ 160, 1740, "Monsters\\Thin\\Thin%c.CL2", 1, "Monsters\\Thin\\Thin%c%i.WAV", 1, 1, "Monsters\\Thin\\Thinv3.TRN", { 8, 8, 18, 4, 17, 14 }, { 3, 0, 0, 0, 0, 0 }, "Red Death", 14, 18, 16, 96, 96, AI_STORM, 0, 1, 75, 5, 10, 20, 0, 0, 0, 0, 60, MC_DEMON, 24, 24, 0, 7, 2168 },
{ 160, 1740, "Monsters\\Thin\\Thin%c.CL2", 1, "Monsters\\Thin\\Thin%c%i.WAV", 1, 1, "Monsters\\Thin\\Thinv3.TRN", { 8, 8, 18, 4, 17, 14 }, { 3, 0, 0, 0, 0, 0 }, "Litch Demon", 16, 20, 18, 110, 110, AI_STORM, 0, 2, 80, 5, 10, 24, 0, 0, 0, 0, 45, MC_DEMON, 104, 104, 0, 7, 2736 },
{ 160, 1740, "Monsters\\Thin\\Thin%c.CL2", 1, "Monsters\\Thin\\Thin%c%i.WAV", 1, 1, "Monsters\\Thin\\Thinv3.TRN", { 8, 8, 18, 4, 17, 14 }, { 3, 0, 0, 0, 0, 0 }, "Undead Balrog", 20, 24, 22, 130, 130, AI_STORM, 0, 3, 85, 5, 12, 30, 0, 0, 0, 0, 65, MC_DEMON, 78, 78, 0, 7, 3575 },
{ 128, 1460, "Monsters\\Fireman\\FireM%c.CL2", 1, "Monsters\\Acid\\Acid%c%i.WAV", 0, 0, NULL, { 14, 19, 20, 8, 14, 23 }, { 0, 0, 0, 0, 0, 0 }, "Incinerator", 14, 18, 16, 30, 45, AI_FIREMAN, 0, 0, 75, 8, 8, 16, 0, 0, 0, 0, 25, MC_DEMON, 24, 24, 0, 3, 1888 },
{ 128, 1460, "Monsters\\Fireman\\FireM%c.CL2", 1, "Monsters\\Acid\\Acid%c%i.WAV", 0, 0, NULL, { 14, 19, 20, 8, 14, 23 }, { 0, 0, 0, 0, 0, 0 }, "Flame Lord", 16, 20, 18, 40, 55, AI_FIREMAN, 0, 1, 75, 8, 10, 20, 0, 0, 0, 0, 25, MC_DEMON, 24, 24, 0, 3, 2250 },
{ 128, 1460, "Monsters\\Fireman\\FireM%c.CL2", 1, "Monsters\\Acid\\Acid%c%i.WAV", 0, 0, NULL, { 14, 19, 20, 8, 14, 23 }, { 0, 0, 0, 0, 0, 0 }, "Doom Fire", 18, 22, 20, 50, 65, AI_FIREMAN, 0, 2, 80, 8, 12, 24, 0, 0, 0, 0, 30, MC_DEMON, 28, 28, 0, 3, 2740 },
{ 128, 1460, "Monsters\\Fireman\\FireM%c.CL2", 1, "Monsters\\Acid\\Acid%c%i.WAV", 0, 0, NULL, { 14, 19, 20, 8, 14, 23 }, { 0, 0, 0, 0, 0, 0 }, "Hell Burner", 20, 24, 22, 60, 80, AI_FIREMAN, 0, 3, 85, 8, 15, 30, 0, 0, 0, 0, 30, MC_DEMON, 28, 28, 0, 3, 3355 },
{ 160, 1740, "Monsters\\Thin\\Thin%c.CL2", 1, "Monsters\\Thin\\Thin%c%i.WAV", 1, 1, "Monsters\\Thin\\Thinv3.TRN", { 8, 8, 18, 4, 17, 14 }, { 3, 0, 0, 0, 0, 0 }, "Red Storm", 17, 21, 18, 55, 110, AI_STORM, 768, 0, 80, 5, 8, 18, 75, 8, 4, 16, 30, MC_DEMON, 12, 40, 0, 7, 2160 },
{ 160, 1740, "Monsters\\Thin\\Thin%c.CL2", 1, "Monsters\\Thin\\Thin%c%i.WAV", 1, 0, NULL, { 8, 8, 18, 4, 17, 14 }, { 3, 0, 0, 0, 0, 0 }, "Storm Rider", 19, 23, 20, 60, 120, AI_STORM, 768, 1, 80, 5, 8, 18, 80, 8, 4, 16, 30, MC_DEMON, 33, 40, 0, 7, 2391 },
{ 160, 1740, "Monsters\\Thin\\Thin%c.CL2", 1, "Monsters\\Thin\\Thin%c%i.WAV", 1, 1, "Monsters\\Thin\\Thinv2.TRN", { 8, 8, 18, 4, 17, 14 }, { 3, 0, 0, 0, 0, 0 }, "Storm Lord", 21, 25, 22, 75, 135, AI_STORM, 768, 2, 85, 5, 12, 24, 75, 8, 4, 16, 35, MC_DEMON, 33, 40, 0, 7, 2775 },
{ 160, 1740, "Monsters\\Thin\\Thin%c.CL2", 1, "Monsters\\Thin\\Thin%c%i.WAV", 1, 1, "Monsters\\Thin\\Thinv1.TRN", { 8, 8, 18, 4, 17, 14 }, { 3, 0, 0, 0, 0, 0 }, "Maelstorm", 23, 27, 24, 90, 150, AI_STORM, 768, 3, 90, 5, 12, 28, 75, 8, 4, 16, 40, MC_DEMON, 97, 104, 0, 7, 3177 },
{ 128, 1650, "Monsters\\BigFall\\Fallg%c.CL2", 1, "Monsters\\BigFall\\Bfal%c%i.WAV", 0, 0, NULL, { 10, 8, 11, 8, 17, 0 }, { 0, 0, 0, 0, 2, 2 }, "Devil Kin Brute", 20, 20, 24, 160, 220, AI_SKELSD, 768, 3, 100, 6, 18, 24, 0, 0, 0, 0, 75, MC_ANIMAL, 0, 0, 0, 6, 2000 },
{ 160, 1650, "Monsters\\Gargoyle\\Gargo%c.CL2", 1, "Monsters\\Gargoyle\\Gargo%c%i.WAV", 0, 0, NULL, { 14, 14, 14, 10, 18, 14 }, { 0, 0, 0, 0, 0, 2 }, "Winged-Demon", 8, 12, 9, 45, 60, AI_GARG, 512, 0, 50, 7, 10, 16, 0, 0, 0, 0, 45, MC_DEMON, 74, 88, 0, 6, 662 },
{ 160, 1650, "Monsters\\Gargoyle\\Gargo%c.CL2", 1, "Monsters\\Gargoyle\\Gargo%c%i.WAV", 0, 1, "Monsters\\Gargoyle\\GarE.TRN", { 14, 14, 14, 10, 18, 14 }, { 0, 0, 0, 0, 0, 2 }, "Gargoyle", 12, 16, 13, 60, 90, AI_GARG, 512, 1, 65, 7, 10, 16, 0, 0, 0, 0, 45, MC_DEMON, 76, 104, 0, 6, 1205 },
{ 160, 1650, "Monsters\\Gargoyle\\Gargo%c.CL2", 1, "Monsters\\Gargoyle\\Gargo%c%i.WAV", 0, 1, "Monsters\\Gargoyle\\GargBr.TRN", { 14, 14, 14, 10, 18, 14 }, { 0, 0, 0, 0, 0, 0 }, "Blood Claw", 16, 20, 19, 75, 125, AI_GARG, 512, 2, 80, 7, 14, 22, 0, 0, 0, 0, 50, MC_DEMON, 88, 92, 0, 6, 1873 },
{ 160, 1650, "Monsters\\Gargoyle\\Gargo%c.CL2", 1, "Monsters\\Gargoyle\\Gargo%c%i.WAV", 0, 1, "Monsters\\Gargoyle\\GargB.TRN", { 14, 14, 14, 10, 18, 14 }, { 0, 0, 0, 0, 0, 0 }, "Death Wing", 18, 22, 23, 90, 150, AI_GARG, 512, 3, 95, 7, 16, 28, 0, 0, 0, 0, 60, MC_DEMON, 104, 106, 0, 6, 2278 },
{ 160, 2220, "Monsters\\Mega\\Mega%c.CL2", 1, "Monsters\\Mega\\Mega%c%i.WAV", 1, 0, NULL, { 6, 7, 14, 1, 24, 5 }, { 3, 0, 0, 0, 2, 0 }, "Slayer", 19, 23, 20, 120, 140, AI_MEGA, 768, 0, 100, 8, 12, 20, 0, 3, 0, 0, 60, MC_DEMON, 17, 17, 0, 7, 2300 },
{ 160, 2220, "Monsters\\Mega\\Mega%c.CL2", 1, "Monsters\\Mega\\Mega%c%i.WAV", 1, 1, "Monsters\\Mega\\Guard.TRN", { 6, 7, 14, 1, 24, 5 }, { 3, 0, 0, 0, 2, 0 }, "Guardian", 21, 25, 22, 140, 160, AI_MEGA, 768, 1, 110, 8, 14, 22, 0, 3, 0, 0, 65, MC_DEMON, 17, 17, 0, 7, 2714 },
{ 160, 2220, "Monsters\\Mega\\Mega%c.CL2", 1, "Monsters\\Mega\\Mega%c%i.WAV", 1, 1, "Monsters\\Mega\\Vtexl.TRN", { 6, 7, 14, 1, 24, 5 }, { 3, 0, 0, 0, 2, 0 }, "Vortex Lord", 23, 26, 24, 160, 180, AI_MEGA, 768, 2, 120, 8, 18, 24, 0, 3, 0, 0, 70, MC_DEMON, 81, 85, 0, 7, 3252 },
{ 160, 2220, "Monsters\\Mega\\Mega%c.CL2", 1, "Monsters\\Mega\\Mega%c%i.WAV", 1, 1, "Monsters\\Mega\\Balr.TRN", { 6, 7, 14, 1, 24, 5 }, { 3, 0, 0, 0, 2, 0 }, "Balrog", 25, 29, 26, 180, 200, AI_MEGA, 768, 3, 130, 8, 22, 30, 0, 3, 0, 0, 75, MC_DEMON, 81, 85, 0, 7, 3643 },
{ 160, 1270, "Monsters\\Snake\\Snake%c.CL2", 0, "Monsters\\Snake\\Snake%c%i.WAV", 0, 0, NULL, { 12, 11, 13, 5, 18, 0 }, { 2, 0, 0, 0, 1, 0 }, "Cave Viper", 20, 24, 21, 100, 150, AI_SNAKE, 256, 0, 90, 8, 8, 20, 0, 0, 0, 0, 60, MC_DEMON, 8, 8, 0, 7, 2725 },
{ 160, 1270, "Monsters\\Snake\\Snake%c.CL2", 0, "Monsters\\Snake\\Snake%c%i.WAV", 0, 1, "Monsters\\Snake\\SnakR.TRN", { 12, 11, 13, 5, 18, 0 }, { 2, 0, 0, 0, 1, 0 }, "Fire Drake", 22, 26, 23, 120, 170, AI_SNAKE, 256, 1, 105, 8, 12, 24, 0, 0, 0, 0, 65, MC_DEMON, 10, 24, 0, 7, 3139 },
{ 160, 1270, "Monsters\\Snake\\Snake%c.CL2", 0, "Monsters\\Snake\\Snake%c%i.WAV", 0, 1, "Monsters\\Snake\\Snakg.TRN", { 12, 11, 13, 5, 18, 0 }, { 2, 0, 0, 0, 1, 0 }, "Gold Viper", 24, 27, 25, 140, 180, AI_SNAKE, 256, 2, 120, 8, 15, 26, 0, 0, 0, 0, 70, MC_DEMON, 12, 12, 0, 7, 3540 },
{ 160, 1270, "Monsters\\Snake\\Snake%c.CL2", 0, "Monsters\\Snake\\Snake%c%i.WAV", 0, 1, "Monsters\\Snake\\Snakb.TRN", { 12, 11, 13, 5, 18, 0 }, { 2, 0, 0, 0, 1, 0 }, "Azure Drake", 28, 30, 27, 160, 200, AI_SNAKE, 256, 3, 130, 8, 18, 30, 0, 0, 0, 0, 75, MC_DEMON, 6, 42, 0, 7, 3791 },
{ 160, 2120, "Monsters\\Black\\Black%c.CL2", 0, "Monsters\\Black\\Black%c%i.WAV", 0, 0, NULL, { 8, 8, 16, 4, 24, 0 }, { 2, 0, 0, 0, 0, 0 }, "Black Knight", 23, 27, 24, 150, 150, AI_SKELSD, 256, 0, 110, 8, 15, 20, 0, 0, 0, 0, 75, MC_DEMON, 69, 97, 0, 7, 3360 },
{ 160, 2120, "Monsters\\Black\\Black%c.CL2", 0, "Monsters\\Black\\Black%c%i.WAV", 0, 1, "Monsters\\Black\\BlkKntRT.TRN", { 8, 8, 16, 4, 24, 0 }, { 2, 0, 0, 0, 0, 0 }, "Doom Guard", 25, 29, 26, 165, 165, AI_SKELSD, 256, 0, 130, 8, 18, 25, 0, 0, 0, 0, 75, MC_DEMON, 67, 81, 0, 7, 3650 },
{ 160, 2120, "Monsters\\Black\\Black%c.CL2", 0, "Monsters\\Black\\Black%c%i.WAV", 0, 1, "Monsters\\Black\\BlkKntBT.TRN", { 8, 8, 16, 4, 24, 0 }, { 2, 0, 0, 0, 0, 0 }, "Steel Lord", 27, 30, 28, 180, 180, AI_SKELSD, 256, 1, 120, 8, 20, 30, 0, 0, 0, 0, 80, MC_DEMON, 85, 92, 0, 7, 4252 },
{ 160, 2120, "Monsters\\Black\\Black%c.CL2", 0, "Monsters\\Black\\Black%c%i.WAV", 0, 1, "Monsters\\Black\\BlkKntBe.TRN", { 8, 8, 16, 4, 24, 0 }, { 2, 0, 0, 0, 0, 0 }, "Blood Knight", 24, 26, 30, 200, 200, AI_SKELSD, 256, 1, 130, 8, 25, 35, 0, 0, 0, 0, 85, MC_DEMON, 106, 106, 0, 7, 5130 },
{ 96, 484, "Monsters\\Unrav\\Unrav%c.CL2", 0, "Monsters\\Acid\\Acid%c%i.WAV", 0, 0, NULL, { 10, 10, 12, 5, 16, 0 }, { 0, 0, 0, 0, 0, 0 }, "Unraveler", 26, 28, 25, 70, 150, AI_SKELSD, 0, 0, 75, 7, 10, 20, 0, 0, 0, 0, 70, MC_UNDEAD, 106, 106, 0, 3, 3812 },
{ 96, 484, "Monsters\\Unrav\\Unrav%c.CL2", 0, "Monsters\\Acid\\Acid%c%i.WAV", 0, 0, NULL, { 10, 10, 12, 5, 16, 0 }, { 0, 0, 0, 0, 0, 0 }, "Hollow One", 28, 30, 27, 135, 240, AI_SKELSD, 0, 1, 75, 7, 12, 24, 0, 0, 0, 0, 75, MC_UNDEAD, 92, 92, 0, 3, 4374 },
{ 96, 484, "Monsters\\Unrav\\Unrav%c.CL2", 0, "Monsters\\Acid\\Acid%c%i.WAV", 0, 0, NULL, { 10, 10, 12, 5, 16, 0 }, { 0, 0, 0, 0, 0, 0 }, "Pain Master", 27, 30, 29, 110, 200, AI_SKELSD, 0, 2, 80, 7, 16, 30, 0, 0, 0, 0, 80, MC_UNDEAD, 92, 92, 0, 3, 5147 },
{ 96, 484, "Monsters\\Unrav\\Unrav%c.CL2", 0, "Monsters\\Acid\\Acid%c%i.WAV", 0, 0, NULL, { 10, 10, 12, 5, 16, 0 }, { 0, 0, 0, 0, 0, 0 }, "Reality Weaver", 28, 30, 30, 135, 240, AI_SKELSD, 0, 3, 85, 7, 20, 35, 0, 0, 0, 0, 85, MC_UNDEAD, 113, 113, 0, 3, 5925 },
{ 128, 980, "Monsters\\Succ\\Scbs%c.CL2", 0, "Monsters\\Succ\\Scbs%c%i.WAV", 0, 0, NULL, { 14, 8, 16, 7, 24, 0 }, { 0, 0, 0, 0, 0, 0 }, "Succubus", 22, 26, 24, 120, 150, AI_SUCC, 512, 0, 100, 10, 1, 20, 0, 0, 0, 0, 60, MC_DEMON, 1, 10, 0, 3, 3696 },
{ 128, 980, "Monsters\\Succ\\Scbs%c.CL2", 0, "Monsters\\Succ\\Scbs%c%i.WAV", 0, 1, "Monsters\\Succ\\Succb.TRN", { 14, 8, 16, 7, 24, 0 }, { 0, 0, 0, 0, 0, 0 }, "Snow Witch", 25, 28, 26, 135, 175, AI_SUCC, 512, 1, 110, 10, 1, 24, 0, 0, 0, 0, 65, MC_DEMON, 68, 76, 0, 3, 4084 },
{ 128, 980, "Monsters\\Succ\\Scbs%c.CL2", 0, "Monsters\\Succ\\Scbs%c%i.WAV", 0, 1, "Monsters\\Succ\\Succrw.TRN", { 14, 8, 16, 7, 24, 0 }, { 0, 0, 0, 0, 0, 0 }, "Hell Spawn", 27, 30, 28, 150, 200, AI_SUCC, 768, 2, 115, 10, 1, 30, 0, 0, 0, 0, 75, MC_DEMON, 33, 28, 0, 3, 4480 },
{ 128, 980, "Monsters\\Succ\\Scbs%c.CL2", 0, "Monsters\\Succ\\Scbs%c%i.WAV", 0, 1, "Monsters\\Succ\\Succbw.TRN", { 14, 8, 16, 7, 24, 0 }, { 0, 0, 0, 0, 0, 0 }, "Soul Burner", 28, 30, 30, 140, 225, AI_SUCC, 768, 3, 120, 10, 1, 35, 0, 0, 0, 0, 85, MC_DEMON, 21, 56, 0, 3, 4644 },
{ 128, 2000, "Monsters\\Mage\\Mage%c.CL2", 1, "Monsters\\Mage\\Mage%c%i.WAV", 0, 0, NULL, { 12, 1, 20, 8, 28, 20 }, { 0, 0, 0, 0, 0, 0 }, "Counselor", 24, 26, 25, 70, 70, AI_COUNSLR, 512, 0, 90, 8, 8, 20, 0, 0, 0, 0, 0, MC_DEMON, 7, 7, 0, 7, 4070 },
{ 128, 2000, "Monsters\\Mage\\Mage%c.CL2", 1, "Monsters\\Mage\\Mage%c%i.WAV", 0, 1, "Monsters\\Mage\\Cnselg.TRN", { 12, 1, 20, 8, 28, 20 }, { 0, 0, 0, 0, 0, 0 }, "Magistrate", 26, 28, 27, 85, 85, AI_COUNSLR, 512, 1, 100, 8, 10, 24, 0, 0, 0, 0, 0, MC_DEMON, 85, 92, 0, 7, 4478 },
{ 128, 2000, "Monsters\\Mage\\Mage%c.CL2", 1, "Monsters\\Mage\\Mage%c%i.WAV", 0, 1, "Monsters\\Mage\\Cnselgd.TRN", { 12, 1, 20, 8, 28, 20 }, { 0, 0, 0, 0, 0, 0 }, "Cabalist", 28, 30, 29, 120, 120, AI_COUNSLR, 512, 2, 110, 8, 14, 30, 0, 0, 0, 0, 0, MC_DEMON, 99, 106, 0, 7, 4929 },
{ 128, 2000, "Monsters\\Mage\\Mage%c.CL2", 1, "Monsters\\Mage\\Mage%c%i.WAV", 0, 1, "Monsters\\Mage\\Cnselbk.TRN", { 12, 1, 20, 8, 28, 20 }, { 0, 0, 0, 0, 0, 0 }, "Advocate", 30, 30, 30, 145, 145, AI_COUNSLR, 512, 3, 120, 8, 15, 25, 0, 0, 0, 0, 0, MC_DEMON, 106, 120, 0, 7, 4968 },
{ 96, 386, "Monsters\\Golem\\Golem%c.CL2", 1, "Monsters\\Golem\\Golm%c%i.WAV", 0, 0, NULL, { 0, 16, 12, 0, 12, 20 }, { 0, 0, 0, 0, 0, 0 }, "Golem", 0, 0, 12, 1, 1, AI_GOLUM, 512, 0, 0, 7, 1, 1, 0, 0, 0, 0, 1, MC_DEMON, 0, 0, 0, 0, 0 },
{ 160, 2000, "Monsters\\Diablo\\Diablo%c.CL2", 1, "Monsters\\Diablo\\Diablo%c%i.WAV", 1, 0, NULL, { 16, 6, 16, 6, 16, 16 }, { 0, 0, 0, 0, 0, 0 }, "The Dark Lord", 50, 50, 30, 1666, 1666, AI_DIABLO, 896, 3, 220, 4, 30, 60, 0, 11, 0, 0, 70, MC_DEMON, 78, 78, 0, 7, 31666 },
{ 128, 1060, "Monsters\\DarkMage\\Dmage%c.CL2", 1, "Monsters\\DarkMage\\Dmag%c%i.WAV", 0, 0, NULL, { 6, 1, 21, 6, 23, 18 }, { 0, 0, 0, 0, 0, 0 }, "The Arch-Litch Malignus", 30, 30, 30, 160, 160, AI_COUNSLR, 512, 3, 120, 8, 20, 40, 0, 0, 0, 0, 70, MC_DEMON, 71, 120, 0, 7, 4968 }
};
char MonstConvTbl[128] =
{
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26, 27, 29, 30,
31, 32, 34, 35, 36, 37, 38, 40, 39, 41,
42, 43, 44, 45, 46, 47, 48, 49, 50, 52,
53, 54, 55, 56, 57, 59, 58, 60, 61, 62,
63, 64, 65, 66, 67, 68, 69, 70, 71, 0,
0, 0, 0, 72, 73, 74, 75, 0, 0, 0,
0, 77, 76, 78, 79, 81, 82, 83, 84, 85,
86, 87, 88, 89, 90, 92, 91, 93, 94, 95,
96, 97, 98, 99, 100, 101, 102, 103, 104, 105,
106, 107, 108, 0, 110, 0, 109, 0, 0, 0,
0, 0, 0, 0, 0, 0, 80, 111
};
unsigned char MonstAvailTbl[112] =
{
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 0, 2,
2, 2, 2, 0, 2, 2, 2, 2, 1, 1,
1, 1, 2, 2, 2, 2, 2, 2, 2, 2,
0, 0, 2, 2, 2, 2, 0, 0, 0, 0,
2, 2, 2, 2, 2, 2, 2, 2, 0, 0,
0, 0, 0, 0, 0, 0, 2, 2, 2, 2,
0, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 0, 0, 0,
0, 2, 2, 2, 2, 2, 2, 2, 2, 0,
0, 0
};
UniqMonstStruct UniqMonst[98] =
{
{ MT_NGOATMC, "Gharbad the Weak", "BSDB", 4, 120, AI_GARBUD, 3, 8, 16, 96, 0, 0, 0, QUEST_GARBUD1 },
{ MT_SKING, "Skeleton King", "GENRL", 0, 240, AI_SKELKING, 3, 6, 16, 78, 1, 0, 0, 0 },
{ MT_COUNSLR, "Zhar the Mad", "GENERAL", 8, 360, AI_ZHAR, 3, 16, 40, 14, 0, 0, 0, QUEST_ZHAR1 },
{ MT_BFALLSP, "Snotspill", "BNG", 4, 220, AI_SNOTSPIL, 3, 10, 18, 4, 0, 0, 0, QUEST_BANNER10 },
{ MT_ADVOCATE, "Arch-Bishop Lazarus", "GENERAL", 0, 600, AI_LAZURUS, 3, 30, 50, 78, 0, 0, 0, QUEST_VILE13 },
{ MT_HLSPWN, "Red Vex", "REDV", 0, 400, AI_LAZHELP, 3, 30, 50, 74, 0, 0, 0, QUEST_VILE13 },
{ MT_HLSPWN, "BlackJade", "BLKJD", 0, 400, AI_LAZHELP, 3, 30, 50, 76, 0, 0, 0, QUEST_VILE13 },
{ MT_RBLACK, "Lachdanan", "BHKA", 14, 500, AI_LACHDAN, 3, 0, 0, 0, 0, 0, 0, QUEST_VEIL9 },
{ MT_BTBLACK, "Warlord of Blood", "GENERAL", 13, 850, AI_WARLORD, 3, 35, 50, 120, 0, 0, 0, QUEST_WARLRD9 },
{ MT_CLEAVER, "The Butcher", "GENRL", 0, 220, AI_CLEAVER, 3, 6, 12, 70, 0, 0, 0, 0 },
{ MT_TSKELAX, "Bonehead Keenaxe", "BHKA", 2, 91, AI_SKELSD, 2, 4, 10, 72, 7, 100, 0, 0 },
{ MT_RFALLSD, "Bladeskin the Slasher", "BSTS", 2, 51, AI_FALLEN, 0, 6, 18, 2, 11, 45, 0, 0 },
{ MT_NZOMBIE, "Soulpus", "GENERAL", 2, 133, AI_ZOMBIE, 0, 4, 8, 6, 0, 0, 0, 0 },
{ MT_RFALLSP, "Pukerat the Unclean", "PTU", 2, 77, AI_FALLEN, 3, 1, 5, 2, 0, 0, 0, 0 },
{ MT_WSKELAX, "Boneripper", "BR", 2, 54, AI_BAT, 0, 6, 15, 88, 3, 0, 0, 0 },
{ MT_NZOMBIE, "Rotfeast the Hungry", "ETH", 2, 85, AI_SKELSD, 3, 4, 12, 72, 3, 0, 0, 0 },
{ MT_DFALLSD, "Gutshank the Quick", "GTQ", 3, 66, AI_BAT, 2, 6, 16, 2, 3, 0, 0, 0 },
{ MT_TSKELSD, "Brokenhead Bangshield", "BHBS", 3, 108, AI_SKELSD, 3, 12, 20, 76, 3, 0, 0, 0 },
{ MT_YFALLSP, "Bongo", "BNG", 3, 178, AI_FALLEN, 3, 9, 21, 0, 3, 0, 0, 0 },
{ MT_BZOMBIE, "Rotcarnage", "RCRN", 3, 102, AI_ZOMBIE, 3, 9, 24, 76, 11, 45, 0, 0 },
{ MT_NSCAV, "Shadowbite", "SHBT", 2, 60, AI_SKELSD, 3, 3, 20, 16, 3, 0, 0, 0 },
{ MT_WSKELBW, "Deadeye", "DE", 2, 49, AI_GOATBOW, 0, 6, 9, 74, 0, 0, 0, 0 },
{ MT_RSKELAX, "Madeye the Dead", "MTD", 4, 75, AI_BAT, 0, 9, 21, 24, 11, 30, 0, 0 },
{ MT_BSCAV, "El Chupacabras", "GENERAL", 3, 120, AI_GOATMC, 0, 10, 18, 2, 3, 30, 0, 0 },
{ MT_TSKELBW, "Skullfire", "SKFR", 3, 125, AI_GOATBOW, 1, 6, 10, 16, 0, 100, 0, 0 },
{ MT_SNEAK, "Warpskull", "TSPO", 3, 117, AI_SNEAK, 2, 6, 18, 6, 3, 0, 0, 0 },
{ MT_GZOMBIE, "Goretongue", "PMR", 3, 156, AI_SKELSD, 1, 15, 30, 72, 0, 0, 0, 0 },
{ MT_WSCAV, "Pulsecrawler", "BHKA", 4, 150, AI_SCAV, 0, 16, 20, 20, 11, 45, 0, 0 },
{ MT_BLINK, "Moonbender", "GENERAL", 4, 135, AI_BAT, 0, 9, 27, 16, 3, 0, 0, 0 },
{ MT_BLINK, "Wrathraven", "GENERAL", 5, 135, AI_BAT, 2, 9, 22, 16, 3, 0, 0, 0 },
{ MT_YSCAV, "Spineeater", "GENERAL", 4, 180, AI_SCAV, 1, 18, 25, 96, 3, 0, 0, 0 },
{ MT_RSKELBW, "Blackash the Burning", "BASHTB", 4, 120, AI_GOATBOW, 0, 6, 16, 24, 3, 0, 0, 0 },
{ MT_BFALLSD, "Shadowcrow", "GENERAL", 5, 270, AI_SNEAK, 2, 12, 25, 0, 3, 0, 0, 0 },
{ MT_LRDSAYTR, "Blightstone the Weak", "BHKA", 4, 360, AI_SKELSD, 0, 4, 12, 12, 7, 70, 0, 0 },
{ MT_FAT, "Bilefroth the Pit Master", "BFTP", 6, 210, AI_BAT, 1, 16, 23, 28, 3, 0, 0, 0 },
{ MT_NGOATBW, "Bloodskin Darkbow", "BSDB", 5, 207, AI_GOATBOW, 0, 3, 16, 6, 11, 55, 0, 0 },
{ MT_GLOOM, "Foulwing", "DB", 5, 246, AI_RHINO, 3, 12, 28, 2, 3, 0, 0, 0 },
{ MT_XSKELSD, "Shadowdrinker", "SHDR", 5, 300, AI_SNEAK, 1, 18, 26, 78, 8, 45, 0, 0 },
{ MT_UNSEEN, "Hazeshifter", "BHKA", 5, 285, AI_SNEAK, 3, 18, 30, 96, 3, 0, 0, 0 },
{ MT_NACID, "Deathspit", "BFDS", 6, 303, AI_ACIDUNIQ, 0, 12, 32, 6, 3, 0, 0, 0 },
{ MT_RGOATMC, "Bloodgutter", "BGBL", 6, 315, AI_BAT, 1, 24, 34, 16, 3, 0, 0, 0 },
{ MT_BGOATMC, "Deathshade Fleshmaul", "DSFM", 6, 276, AI_RHINO, 0, 12, 24, 10, 8, 65, 0, 0 },
{ MT_WYRM, "Warmaggot the Mad", "GENERAL", 6, 246, AI_BAT, 3, 15, 30, 4, 3, 0, 0, 0 },
{ MT_STORM, "Glasskull the Jagged", "BHKA", 7, 354, AI_STORM, 0, 18, 30, 88, 3, 0, 0, 0 },
{ MT_RGOATBW, "Blightfire", "BLF", 7, 321, AI_SUCC, 2, 13, 21, 16, 3, 0, 0, 0 },
{ MT_GARGOYLE, "Nightwing the Cold", "GENERAL", 7, 342, AI_BAT, 1, 18, 26, 76, 3, 0, 0, 0 },
{ MT_GGOATBW, "Gorestone", "GENERAL", 7, 303, AI_GOATBOW, 1, 15, 28, 68, 7, 70, 0, 0 },
{ MT_BMAGMA, "Bronzefist Firestone", "GENERAL", 8, 360, AI_MAGMA, 0, 30, 36, 10, 3, 0, 0, 0 },
{ MT_INCIN, "Wrathfire the Doomed", "WFTD", 8, 270, AI_SKELSD, 2, 20, 30, 14, 3, 0, 0, 0 },
{ MT_NMAGMA, "Firewound the Grim", "BHKA", 8, 303, AI_MAGMA, 0, 18, 22, 10, 3, 0, 0, 0 },
{ MT_MUDMAN, "Baron Sludge", "BSM", 8, 315, AI_SNEAK, 3, 25, 34, 78, 11, 75, 0, 0 },
{ MT_GGOATMC, "Blighthorn Steelmace", "BHSM", 7, 250, AI_RHINO, 0, 20, 28, 4, 11, 45, 0, 0 },
{ MT_RACID, "Chaoshowler", "GENERAL", 8, 240, AI_ACIDUNIQ, 0, 12, 20, 0, 3, 0, 0, 0 },
{ MT_REDDTH, "Doomgrin the Rotting", "GENERAL", 8, 405, AI_STORM, 3, 25, 50, 78, 3, 0, 0, 0 },
{ MT_FLAMLRD, "Madburner", "GENERAL", 9, 270, AI_STORM, 0, 20, 40, 56, 3, 0, 0, 0 },
{ MT_LTCHDMN, "Bonesaw the Litch", "GENERAL", 9, 495, AI_STORM, 2, 30, 55, 78, 3, 0, 0, 0 },
{ MT_MUDRUN, "Breakspine", "GENERAL", 9, 351, AI_RHINO, 0, 25, 34, 2, 3, 0, 0, 0 },
{ MT_REDDTH, "Devilskull Sharpbone", "GENERAL", 9, 444, AI_STORM, 1, 25, 40, 16, 3, 0, 0, 0 },
{ MT_STORM, "Brokenstorm", "GENERAL", 9, 411, AI_STORM, 2, 25, 36, 32, 3, 0, 0, 0 },
{ MT_RSTORM, "Stormbane", "GENERAL", 9, 555, AI_STORM, 3, 30, 30, 32, 3, 0, 0, 0 },
{ MT_TOAD, "Oozedrool", "GENERAL", 9, 483, AI_FAT, 3, 25, 30, 4, 3, 0, 0, 0 },
{ MT_BLOODCLW, "Goldblight of the Flame", "GENERAL", 10, 405, AI_GARG, 0, 15, 35, 24, 11, 80, 0, 0 },
{ MT_OBLORD, "Blackstorm", "GENERAL", 10, 525, AI_RHINO, 3, 20, 40, 40, 11, 90, 0, 0 },
{ MT_RACID, "Plaguewrath", "GENERAL", 10, 450, AI_ACIDUNIQ, 2, 20, 30, 74, 3, 0, 0, 0 },
{ MT_RSTORM, "The Flayer", "GENERAL", 10, 501, AI_STORM, 1, 20, 35, 99, 3, 0, 0, 0 },
{ MT_FROSTC, "Bluehorn", "GENERAL", 11, 477, AI_RHINO, 1, 25, 30, 10, 11, 90, 0, 0 },
{ MT_HELLBURN, "Warpfire Hellspawn", "GENERAL", 11, 525, AI_FIREMAN, 3, 10, 40, 17, 3, 0, 0, 0 },
{ MT_NSNAKE, "Fangspeir", "GENERAL", 11, 444, AI_SKELSD, 1, 15, 32, 80, 3, 0, 0, 0 },
{ MT_UDEDBLRG, "Festerskull", "GENERAL", 11, 600, AI_STORM, 2, 15, 30, 72, 3, 0, 0, 0 },
{ MT_NBLACK, "Lionskull the Bent", "GENERAL", 12, 525, AI_SKELSD, 2, 25, 25, 120, 3, 0, 0, 0 },
{ MT_COUNSLR, "Blacktongue", "GENERAL", 12, 360, AI_COUNSLR, 3, 15, 30, 66, 3, 0, 0, 0 },
{ MT_DEATHW, "Viletouch", "GENERAL", 12, 525, AI_GARG, 3, 20, 40, 96, 3, 0, 0, 0 },
{ MT_RSNAKE, "Viperflame", "GENERAL", 12, 570, AI_SKELSD, 1, 25, 35, 20, 3, 0, 0, 0 },
{ MT_BSNAKE, "Fangskin", "BHKA", 14, 681, AI_SKELSD, 2, 15, 50, 12, 3, 0, 0, 0 },
{ MT_SUCCUBUS, "Witchfire the Unholy", "GENERAL", 12, 444, AI_SUCC, 3, 10, 20, 28, 3, 0, 0, 0 },
{ MT_BALROG, "Blackskull", "BHKA", 13, 750, AI_SKELSD, 3, 25, 40, 12, 3, 0, 0, 0 },
{ MT_UNRAV, "Soulslash", "GENERAL", 12, 450, AI_SKELSD, 0, 25, 25, 72, 3, 0, 0, 0 },
{ MT_VTEXLRD, "Windspawn", "GENERAL", 12, 711, AI_SKELSD, 1, 35, 40, 24, 3, 0, 0, 0 },
{ MT_GSNAKE, "Lord of the Pit", "GENERAL", 13, 762, AI_SKELSD, 2, 25, 42, 66, 3, 0, 0, 0 },
{ MT_RTBLACK, "Rustweaver", "GENERAL", 13, 400, AI_SKELSD, 3, 1, 60, 120, 0, 0, 0, 0 },
{ MT_HOLOWONE, "Howlingire the Shade", "GENERAL", 13, 450, AI_SKELSD, 2, 40, 75, 6, 3, 0, 0, 0 },
{ MT_MAEL, "Doomcloud", "GENERAL", 13, 612, AI_STORM, 1, 1, 60, 34, 0, 0, 0, 0 },
{ MT_PAINMSTR, "Bloodmoon Soulfire", "GENERAL", 13, 684, AI_SKELSD, 1, 15, 40, 14, 3, 0, 0, 0 },
{ MT_SNOWWICH, "Witchmoon", "GENERAL", 13, 310, AI_SUCC, 3, 30, 40, 4, 0, 0, 0, 0 },
{ MT_VTEXLRD, "Gorefeast", "GENERAL", 13, 771, AI_SKELSD, 3, 20, 55, 66, 0, 0, 0, 0 },
{ MT_RTBLACK, "Graywar the Slayer", "GENERAL", 14, 672, AI_SKELSD, 1, 30, 50, 68, 0, 0, 0, 0 },
{ MT_MAGISTR, "Dreadjudge", "GENERAL", 14, 540, AI_COUNSLR, 1, 30, 40, 14, 3, 0, 0, 0 },
{ MT_HLSPWN, "Stareye the Witch", "GENERAL", 14, 726, AI_SUCC, 2, 30, 50, 16, 0, 0, 0, 0 },
{ MT_BTBLACK, "Steelskull the Hunter", "GENERAL", 14, 831, AI_SKELSD, 3, 40, 50, 68, 0, 0, 0, 0 },
{ MT_RBLACK, "Sir Gorash", "GENERAL", 16, 1050, AI_SKELSD, 1, 20, 60, 64, 0, 0, 0, 0 },
{ MT_CABALIST, "The Vizier", "GENERAL", 15, 850, AI_COUNSLR, 2, 25, 40, 16, 3, 0, 0, 0 },
{ MT_REALWEAV, "Zamphir", "GENERAL", 15, 891, AI_SKELSD, 2, 30, 50, 78, 3, 0, 0, 0 },
{ MT_HLSPWN, "Bloodlust", "GENERAL", 15, 825, AI_SUCC, 1, 20, 55, 104, 0, 0, 0, 0 },
{ MT_HLSPWN, "Webwidow", "GENERAL", 16, 774, AI_SUCC, 1, 20, 50, 88, 0, 0, 0, 0 },
{ MT_SOLBRNR, "Fleshdancer", "GENERAL", 16, 999, AI_SUCC, 3, 30, 50, 74, 0, 0, 0, 0 },
{ MT_OBLORD, "Grimspike", "GENERAL", 19, 534, AI_SNEAK, 1, 25, 40, 74, 3, 0, 0, 0 },
{ MT_STORML, "Doomlock", "GENERAL", 28, 534, AI_SNEAK, 1, 35, 55, 78, 3, 0, 0, 0 },
{ -1, NULL, NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};
int MWVel[24][3] =
{
{ 256, 512, 1024 },
{ 128, 256, 512 },
{ 85, 170, 341 },
{ 64, 128, 256 },
{ 51, 102, 204 },
{ 42, 85, 170 },
{ 36, 73, 146 },
{ 32, 64, 128 },
{ 28, 56, 113 },
{ 26, 51, 102 },
{ 23, 46, 93 },
{ 21, 42, 85 },
{ 19, 39, 78 },
{ 18, 36, 73 },
{ 17, 34, 68 },
{ 16, 32, 64 },
{ 15, 30, 60 },
{ 14, 28, 57 },
{ 13, 26, 54 },
{ 12, 25, 51 },
{ 12, 24, 48 },
{ 11, 23, 46 },
{ 11, 22, 44 },
{ 10, 21, 42 }
};
char animletter[7] = "nwahds";
int left[8] = { 7, 0, 1, 2, 3, 4, 5, 6 };
int right[8] = { 1, 2, 3, 4, 5, 6, 7, 0 };
int opposite[8] = { 4, 5, 6, 7, 0, 1, 2, 3 };
int offset_x[8] = { 1, 0, -1, -1, -1, 0, 1, 1 };
int offset_y[8] = { 1, 1, 1, 0, -1, -1, -1, 0 };
/* unused */
int rnd5[4] = { 5, 10, 15, 20 };
int rnd10[4] = { 10, 15, 20, 30 };
int rnd20[4] = { 20, 30, 40, 50 };
int rnd60[4] = { 60, 70, 80, 90 };
//
void(__fastcall *AiProc[])(int i) =
{
&MAI_Zombie,
&MAI_Fat,
&MAI_SkelSd,
&MAI_SkelBow,
&MAI_Scav,
&MAI_Rhino,
&MAI_GoatMc,
&MAI_GoatBow,
&MAI_Fallen,
&MAI_Magma,
&MAI_SkelKing,
&MAI_Bat,
&MAI_Garg,
&MAI_Cleaver,
&MAI_Succ,
&MAI_Sneak,
&MAI_Storm,
&MAI_Fireman,
&MAI_Garbud,
&MAI_Acid,
&MAI_AcidUniq,
&MAI_Golum,
&MAI_Zhar,
&MAI_SnotSpil,
&MAI_Snake,
&MAI_Counselor,
&MAI_Mega,
&MAI_Diablo,
&MAI_Lazurus,
&MAI_Lazhelp,
&MAI_Lachdanan,
&MAI_Warlord
};
struct monster_cpp_init
{
monster_cpp_init()
{
monster_cpp_init_value = monster_inf;
}
} _monster_cpp_init;
// 47F130: using guessed type int monster_inf;
// 64CCE4: using guessed type int monster_cpp_init_value;
void __fastcall InitMonsterTRN(int monst, BOOL special)
{
BYTE *f = Monsters[monst].trans_file;
for ( int i = 0; i < 256; i++ )
{
if ( *f == 255 )
{
*f = 0;
}
f++;
}
int n = special ? 6 : 5;
for ( int j = 0; j < n; ++j )
{
if ( j != 1 || Monsters[monst].mtype < MT_COUNSLR || Monsters[monst].mtype > MT_ADVOCATE )
{
for ( int k = 0; k < 8; k++ )
{
Cl2ApplyTrans(
Monsters[monst].Anims[j].Frames[k],
Monsters[monst].trans_file,
Monsters[monst].Anims[j].Rate);
}
}
}
}
void __cdecl InitLevelMonsters()
{
int i;
nummtypes = 0;
monstimgtot = 0;
MissileFileFlag = 0;
for ( i = 0; i < MAX_LVLMTYPES; i++ )
{
Monsters[i].mPlaceFlags = 0;
}
ClrAllMonsters();
nummonsters = 0;
totalmonsters = MAXMONSTERS;
for ( i = 0; i < MAXMONSTERS; i++ )
{
monstactive[i] = i;
}
uniquetrans = 0;
}
int __fastcall AddMonsterType(int type, int placeflag)
{
BOOL done = FALSE;
int i;
for ( i = 0; i < nummtypes && !done; i++ )
{
done = Monsters[i].mtype == type;
}
i--;
if ( !done )
{
i = nummtypes;
nummtypes++;
Monsters[i].mtype = type;
monstimgtot += monsterdata[type].mType;
InitMonsterGFX(i);
InitMonsterSND(i);
}
Monsters[i].mPlaceFlags |= placeflag;
return i;
}
void __cdecl GetLevelMTypes()
{
int i;
// this array is merged with skeltypes down below.
int typelist[MAXMONSTERS];
int skeltypes[NUM_MTYPES];
int minl; // min level
int maxl; // max level
char mamask = 3; // monster availability mask
int nt; // number of types
AddMonsterType(MT_GOLEM, 2);
if ( currlevel == 16 )
{
AddMonsterType(MT_ADVOCATE, 1);
AddMonsterType(MT_RBLACK, 1);
AddMonsterType(MT_DIABLO, 2);
return;
}
if ( !setlevel )
{
if ( QuestStatus(QTYPE_BUTCH) )
AddMonsterType(MT_CLEAVER, 2);
if ( QuestStatus(QTYPE_GARB) )
AddMonsterType(UniqMonst[0].mtype, 4);
if ( QuestStatus(QTYPE_ZHAR) )
AddMonsterType(UniqMonst[2].mtype, 4);
if ( QuestStatus(QTYPE_BOL) )
AddMonsterType(UniqMonst[3].mtype, 4);
if ( QuestStatus(QTYPE_VEIL) )
AddMonsterType(UniqMonst[7].mtype, 4);
if ( QuestStatus(QTYPE_WARLRD) )
AddMonsterType(UniqMonst[8].mtype, 4);
if ( gbMaxPlayers != 1 && currlevel == quests[QTYPE_KING]._qlevel )
{
AddMonsterType(MT_SKING, 4);
const int numskeltypes = 19;
nt = 0;
for ( i = MT_WSKELAX; i <= MT_WSKELAX + numskeltypes; i++ )
{
if ( IsSkel(i) )
{
minl = 15 * monsterdata[i].mMinDLvl / 30 + 1;
maxl = 15 * monsterdata[i].mMaxDLvl / 30 + 1;
if ( currlevel >= minl && currlevel <= maxl )
{
if ( MonstAvailTbl[i] & mamask )
{
skeltypes[nt++] = i;
}
}
}
}
AddMonsterType(skeltypes[random(88, nt)], 1);
}
nt = 0;
for ( i = 0; i < 111; i++ )
{
minl = 15 * monsterdata[i].mMinDLvl / 30 + 1;
maxl = 15 * monsterdata[i].mMaxDLvl / 30 + 1;
if ( currlevel >= minl && currlevel <= maxl )
{
if ( MonstAvailTbl[i] & mamask )
{
typelist[nt++] = i;
}
}
}
if ( monstdebug )
{
for ( i = 0; i < debugmonsttypes; i++ )
AddMonsterType(DebugMonsters[i], 1);
}
else
{
while ( nt > 0 && nummtypes < MAX_LVLMTYPES && monstimgtot < 4000 )
{
for ( i = 0; i < nt; )
{
if ( monsterdata[typelist[i]].mType > 4000 - monstimgtot )
{
typelist[i] = typelist[--nt];
continue;
}
i++;
}
if ( nt != 0 )
{
i = random(88, nt);
AddMonsterType(typelist[i], 1);
typelist[i] = typelist[--nt];
}
}
}
}
else
{
if ( setlvlnum == SL_SKELKING )
{
AddMonsterType(MT_SKING, 4);
}
}
}
void __fastcall InitMonsterGFX(int monst)
{
int mtype = (unsigned char)Monsters[monst].mtype;
char strBuff[256];
for ( int anim = 0; anim < 6; anim++ )
{
if ( (animletter[anim] != 's' || monsterdata[mtype].has_special) && monsterdata[mtype].Frames[anim] > 0 )
{
sprintf(strBuff, monsterdata[mtype].GraphicType, animletter[anim]);
unsigned char* celBuf = LoadFileInMem(strBuff, NULL);
Monsters[monst].Anims[anim].CMem = celBuf;
if ( Monsters[monst].mtype != MT_GOLEM || (animletter[anim] != 's' && animletter[anim] != 'd') )
{
for ( int i = 0; i < 8; i++ )
{
Monsters[monst].Anims[anim].Frames[i] =
&celBuf[((int *)celBuf)[i]];
}
}
else
{
for ( int i = 0; i < 8; i++ )
{
Monsters[monst].Anims[anim].Frames[i] = celBuf;
}
}
}
// TODO: either the AnimStruct members have wrong naming or the MonsterData ones it seems
Monsters[monst].Anims[anim].Rate = monsterdata[mtype].Frames[anim];
Monsters[monst].Anims[anim].Delay = monsterdata[mtype].Rate[anim];
}
Monsters[monst].flags_1 = monsterdata[mtype].flags;
Monsters[monst].flags_2 = (monsterdata[mtype].flags - 64) >> 1;
Monsters[monst].mMinHP = monsterdata[mtype].mMinHP;
Monsters[monst].mMaxHP = monsterdata[mtype].mMaxHP;
Monsters[monst].has_special = monsterdata[mtype].has_special;
Monsters[monst].mAFNum = monsterdata[mtype].mAFNum;
Monsters[monst].MData = &monsterdata[mtype];
if ( monsterdata[mtype].has_trans )
{
Monsters[monst].trans_file = LoadFileInMem(monsterdata[mtype].TransFile, NULL);
InitMonsterTRN(monst, monsterdata[mtype].has_special);
void *trans_file = Monsters[monst].trans_file;
Monsters[monst].trans_file = NULL;
mem_free_dbg(trans_file);
}
if ( mtype >= MT_NMAGMA && mtype <= MT_WMAGMA && !(MissileFileFlag & 1) )
{
MissileFileFlag |= 1;
LoadMissileGFX(MFILE_MAGBALL);
}
if ( mtype >= MT_STORM && mtype <= MT_MAEL && !(MissileFileFlag & 2) )
{
MissileFileFlag |= 2;
LoadMissileGFX(MFILE_THINLGHT);
}
if ( mtype == MT_SUCCUBUS )
{
if ( MissileFileFlag & 4 ) return;
MissileFileFlag |= 4;
LoadMissileGFX(MFILE_FLARE);
LoadMissileGFX(MFILE_FLAREEXP);
}
if ( mtype == MT_SNOWWICH )
{
if ( MissileFileFlag & 0x20 ) return;
MissileFileFlag |= 0x20;
LoadMissileGFX(MFILE_SCUBMISB);
LoadMissileGFX(MFILE_SCBSEXPB);
}
if ( mtype == MT_HLSPWN )
{
if ( MissileFileFlag & 0x40 ) return;
MissileFileFlag |= 0x40;
LoadMissileGFX(MFILE_SCUBMISD);
LoadMissileGFX(MFILE_SCBSEXPD);
}
if ( mtype == MT_SOLBRNR )
{
if ( MissileFileFlag & 0x80 ) return;
MissileFileFlag |= 0x80;
LoadMissileGFX(MFILE_SCUBMISC);
LoadMissileGFX(MFILE_SCBSEXPC);
}
if ( mtype >= MT_INCIN && mtype <= MT_HELLBURN && !(MissileFileFlag & 8) )
{
MissileFileFlag |= 8;
LoadMissileGFX(MFILE_KRULL);
}
if ( mtype >= MT_NACID && mtype <= MT_XACID && !(MissileFileFlag & 0x10) )
{
MissileFileFlag |= 0x10;
LoadMissileGFX(MFILE_ACIDBF);
LoadMissileGFX(MFILE_ACIDSPLA);
LoadMissileGFX(MFILE_ACIDPUD);
}
if ( mtype == MT_DIABLO )
{
LoadMissileGFX(MFILE_FIREPLAR);
}
}
void __fastcall ClearMVars(int i)
{
monster[i]._mVar1 = 0;
monster[i]._mVar2 = 0;
monster[i]._mVar3 = 0;
monster[i]._mVar4 = 0;
monster[i]._mVar5 = 0;
monster[i]._mVar6 = 0;
monster[i]._mVar7 = 0;
monster[i]._mVar8 = 0;
}
void __fastcall InitMonster(int i, int rd, int mtype, int x, int y)
{
CMonster *monst = &Monsters[mtype];
monster[i]._mdir = rd;
monster[i]._mx = x;
monster[i]._my = y;
monster[i]._mfutx = x;
monster[i]._mfuty = y;
monster[i]._moldx = x;
monster[i]._moldy = y;
monster[i]._mmode = MM_STAND;
monster[i]._mMTidx = mtype;
monster[i].mName = monst->MData->mName;
monster[i].MType = monst;
monster[i].MData = monst->MData;
monster[i]._mAnimData = monst->Anims[0].Frames[rd];
monster[i]._mAnimDelay = monst->Anims[0].Delay;
monster[i]._mAnimCnt = random(88, monst->Anims[0].Delay - 1);
monster[i]._mAnimLen = monst->Anims[0].Rate;
monster[i]._mAnimFrame = random(88, monst->Anims[0].Rate - 1) + 1;
if ( monst->mtype == MT_DIABLO )
{
monster[i]._mmaxhp = (random(88, 1) + 1666) << 6;
}
else
{
monster[i]._mmaxhp = (monst->mMinHP + random(88, monst->mMaxHP - monst->mMinHP + 1)) << 6;
}
if ( gbMaxPlayers == 1 )
{
monster[i]._mmaxhp >>= 1;
if ( monster[i]._mmaxhp < 64 )
{
monster[i]._mmaxhp = 64;
}
}
monster[i]._mhitpoints = monster[i]._mmaxhp;
monster[i]._mAi = monst->MData->mAi;
monster[i]._mint = monst->MData->mInt;
monster[i]._mgoal = 1;
monster[i]._mgoalvar1 = 0;
monster[i]._mgoalvar2 = 0;
monster[i]._mgoalvar3 = 0;
monster[i]._pathcount = 0;
monster[i]._uniqtype = 0;
monster[i]._msquelch = 0;
monster[i].field_18 = 0;
monster[i]._mDelFlag = 0;
monster[i]._mRndSeed = GetRndSeed();
monster[i]._mAISeed = GetRndSeed();
monster[i].mWhoHit = 0;
monster[i].mLevel = monst->MData->mLevel;
monster[i].mExp = monst->MData->mExp;
monster[i].mHit = monst->MData->mHit;
monster[i].mMinDamage = monst->MData->mMinDamage;
monster[i].mMaxDamage = monst->MData->mMaxDamage;
monster[i].mHit2 = monst->MData->mHit2;
monster[i].mMinDamage2 = monst->MData->mMinDamage2;
monster[i].mMaxDamage2 = monst->MData->mMaxDamage2;
monster[i].mArmorClass = monst->MData->mArmorClass;
monster[i].mMagicRes = monst->MData->mMagicRes;
monster[i].leader = 0;
monster[i].leaderflag = 0;
monster[i]._mFlags = monst->MData->mFlags;
monster[i].mtalkmsg = 0;
if ( monster[i]._mAi == AI_GARG )
{
monster[i]._mAnimData = monst->Anims[5].Frames[rd];
monster[i]._mAnimFrame = 1;
monster[i]._mFlags |= 4u;
monster[i]._mmode = MM_SATTACK;
}
if ( gnDifficulty == DIFF_NIGHTMARE )
{
monster[i].mLevel += 15;
monster[i].mHit += 85;
monster[i].mHit2 += 85;
monster[i]._mmaxhp = 3 * monster[i]._mmaxhp + 64;
monster[i]._mhitpoints = monster[i]._mmaxhp;
monster[i].mExp = 2 * (monster[i].mExp + 1000);
monster[i].mMinDamage = 2 * (monster[i].mMinDamage + 2);
monster[i].mMaxDamage = 2 * (monster[i].mMaxDamage + 2);
monster[i].mMinDamage2 = 2 * (monster[i].mMinDamage2 + 2);
monster[i].mMaxDamage2 = 2 * (monster[i].mMaxDamage2 + 2);
monster[i].mArmorClass += 50;
}
if ( gnDifficulty == DIFF_HELL )
{
monster[i].mLevel += 30;
monster[i]._mmaxhp = 4 * monster[i]._mmaxhp + 192;
monster[i]._mhitpoints = monster[i]._mmaxhp;
monster[i].mHit += 120;
monster[i].mHit2 += 120;
monster[i].mExp = 4 * (monster[i].mExp + 1000);
monster[i].mMinDamage = 4 * monster[i].mMinDamage + 6;
monster[i].mMaxDamage = 4 * monster[i].mMaxDamage + 6;
monster[i].mMinDamage2 = 4 * monster[i].mMinDamage2 + 6;
monster[i].mMaxDamage2 = 4 * monster[i].mMaxDamage2 + 6;
monster[i].mArmorClass += 80;
monster[i].mMagicRes = monst->MData->mMagicRes2;
}
}
void __cdecl ClrAllMonsters()
{
MonsterStruct *Monst;
for ( int i = 0; i < 200; i++ )
{
Monst = &monster[i];
ClearMVars(i);
Monst->mName = "Invalid Monster";
Monst->_mgoal = 0;
Monst->_mmode = MM_STAND;
Monst->_mVar1 = 0;
Monst->_mVar2 = 0;
Monst->_mx = 0;
Monst->_my = 0;
Monst->_mfutx = 0;
Monst->_mfuty = 0;
Monst->_moldx = 0;
Monst->_moldy = 0;
Monst->_mdir = random(89, 8);
Monst->_mxvel = 0;
Monst->_myvel = 0;
Monst->_mAnimData = NULL;
Monst->_mAnimDelay = 0;
Monst->_mAnimCnt = 0;
Monst->_mAnimLen = 0;
Monst->_mAnimFrame = 0;
Monst->_mFlags = 0;
Monst->_mDelFlag = 0;
Monst->_menemy = random(89, gbActivePlayers);
Monst->_menemyx = plr[Monst->_menemy]._px;
Monst->_menemyy = plr[Monst->_menemy]._py;
}
}
BOOL __fastcall MonstPlace(int xp, int yp)
{
if ( xp < 0 || xp >= 112
|| yp < 0 || yp >= 112
|| dMonster[xp][yp]
|| dPlayer[xp][yp] )
{
return FALSE;
}
char f = dFlags[xp][yp];
// TODO: Add enum values here
if ( f & 2 )
{
return FALSE;
}
if ( f & 8 )
{
return FALSE;
}
return !SolidLoc(xp, yp);
}
void __fastcall PlaceMonster(int i, int mtype, int x, int y)
{
dMonster[x][y] = i + 1;
int rd = random(90, 8);
InitMonster(i, rd, mtype, x, y);
}
void __fastcall PlaceUniqueMonst(int uniqindex, int miniontype, int unpackfilesize)
{
int xp;
int yp;
char filestr[64];
UniqMonstStruct *Uniq = &UniqMonst[uniqindex];
MonsterStruct *Monst = &monster[nummonsters];
int count = 0;
if ( (uniquetrans + 19) << 8 >= LIGHTSIZE )
{
return;
}
int uniqtype;
for ( uniqtype = 0; uniqtype < nummtypes; uniqtype++ )
{
if ( Monsters[uniqtype].mtype == Uniq->mtype )
{
break;
}
}
while (true)
{
xp = random(91, 80) + 16;
yp = random(91, 80) + 16;
int count2 = 0;
for ( int x = xp - 3; x < xp + 3; x++ )
{
for ( int y = yp - 3; y < yp + 3; y++ )
{
if ( y >= 0 && y < 112 && x >= 0 && x < 112 && MonstPlace(x, y) )
{
count2++;
}
}
}
if ( count2 < 9 ) {
count++;
if ( count < 1000 )
{
continue;
}
}
if ( MonstPlace(xp, yp) )
{
break;
}
}
if ( uniqindex == 3 )
{
xp = 2 * setpc_x + 24;
yp = 2 * setpc_y + 28;
}
if ( uniqindex == 8 )
{
xp = 2 * setpc_x + 22;
yp = 2 * setpc_y + 23;
}
if ( uniqindex == 2 )
{
BOOL zharflag = TRUE;
for ( int i = 0; i < themeCount; i++ )
{
if ( i == zharlib && zharflag == TRUE )
{
zharflag = FALSE;
xp = 2 * themeLoc[i].x + 20;
yp = 2 * themeLoc[i].y + 20;
}
}
}
if ( gbMaxPlayers == 1 )
{
if ( uniqindex == 4 )
{
xp = 32;
yp = 46;
}
if ( uniqindex == 5 )
{
xp = 40;
yp = 45;
}
if ( uniqindex == 6 )
{
xp = 38;
yp = 49;
}
if ( uniqindex == 1 )
{
xp = 35;
yp = 47;
}
}
else
{
if ( uniqindex == 4 )
{
xp = 2 * setpc_x + 19;
yp = 2 * setpc_y + 22;
}
if ( uniqindex == 5 )
{
xp = 2 * setpc_x + 21;
yp = 2 * setpc_y + 19;
}
if ( uniqindex == 6 )
{
xp = 2 * setpc_x + 21;
yp = 2 * setpc_y + 25;
}
}
if ( uniqindex == 9 )
{
BOOL done = FALSE;
for ( yp = 0; yp < 112 && !done; yp++ )
{
for ( xp = 0; xp < 112 && !done; xp++ )
{
done = dPiece[xp][yp] == 367;
}
}
}
PlaceMonster(nummonsters, uniqtype, xp, yp);
Monst->_uniqtype = uniqindex + 1;
if ( Uniq->mlevel )
{
Monst->mLevel = 2 * Uniq->mlevel;
}
else
{
Monst->mLevel += 5;
}
Monst->mExp *= 2;
Monst->mName = Uniq->mName;
Monst->_mmaxhp = Uniq->mmaxhp << 6;
if ( gbMaxPlayers == 1 )
{
Monst->_mmaxhp = Monst->_mmaxhp >> 1;
if ( Monst->_mmaxhp < 64 )
{
Monst->_mmaxhp = 64;
}
}
Monst->_mhitpoints = Monst->_mmaxhp;
Monst->_mAi = Uniq->mAi;
Monst->_mint = Uniq->mint;
Monst->mMinDamage = Uniq->mMinDamage;
Monst->mMaxDamage = Uniq->mMaxDamage;
Monst->mMinDamage2 = Uniq->mMinDamage;
Monst->mMaxDamage2 = Uniq->mMaxDamage;
Monst->mMagicRes = Uniq->mMagicRes;
Monst->mtalkmsg = Uniq->mtalkmsg;
Monst->mlid = AddLight(Monst->_mx, Monst->_my, 3);
if ( gbMaxPlayers == 1 )
{
if ( Monst->mtalkmsg )
{
Monst->_mgoal = 6;
}
}
else
{
if ( Monst->_mAi == AI_LAZHELP )
{
Monst->mtalkmsg = 0;
}
if ( Monst->_mAi != AI_LAZURUS || quests[15]._qvar1 <= 3 )
{
if ( Monst->mtalkmsg )
{
Monst->_mgoal = 6;
}
}
else
{
Monst->_mgoal = 1;
}
}
if ( gnDifficulty == DIFF_NIGHTMARE )
{
Monst->mLevel += 15;
Monst->_mmaxhp = 3 * Monst->_mmaxhp + 64;
Monst->_mhitpoints = Monst->_mmaxhp;
Monst->mExp = 2 * (Monst->mExp + 1000);
Monst->mMinDamage = 2 * (Monst->mMinDamage + 2);
Monst->mMaxDamage = 2 * (Monst->mMaxDamage + 2);
Monst->mMinDamage2 = 2 * (Monst->mMinDamage2 + 2);
Monst->mMaxDamage2 = 2 * (Monst->mMaxDamage2 + 2);
}
if ( gnDifficulty == DIFF_HELL )
{
Monst->mLevel += 30;
Monst->_mmaxhp = 4 * Monst->_mmaxhp + 192;
Monst->_mhitpoints = Monst->_mmaxhp;
Monst->mExp = 4 * (Monst->mExp + 1000);
Monst->mMinDamage = 4 * Monst->mMinDamage + 6;
Monst->mMaxDamage = 4 * Monst->mMaxDamage + 6;
Monst->mMinDamage2 = 4 * Monst->mMinDamage2 + 6;
Monst->mMaxDamage2 = 4 * Monst->mMaxDamage2 + 6;
}
sprintf(filestr, "Monsters\\Monsters\\%s.TRN", Uniq->mMode);
LoadFileWithMem(filestr, &pLightTbl[256 * (uniquetrans + 19)]);
Monst->_uniqtrans = uniquetrans++;
if ( Uniq->mUnqAttr & 4 )
{
Monst->mHit = Uniq->mUnqVar1;
Monst->mHit2 = Uniq->mUnqVar1;
}
if ( Uniq->mUnqAttr & 8 )
{
Monst->mArmorClass = Uniq->mUnqVar1;
}
nummonsters++;
if ( Uniq->mUnqAttr & 1 )
{
PlaceGroup(miniontype, unpackfilesize, Uniq->mUnqAttr, nummonsters - 1);
}
if ( Monst->_mAi != AI_GARG )
{
Monst->_mAnimData = Monst->MType->Anims[0].Frames[Monst->_mdir];
Monst->_mAnimFrame = random(88, Monst->_mAnimLen - 1) + 1;
Monst->_mFlags &= 0xFFFFFFFB;
Monst->_mmode = MM_STAND;
}
}
void __cdecl PlaceQuestMonsters()
{
int skeltype;
unsigned char *setp;
if ( !setlevel )
{
if ( QuestStatus(QTYPE_BUTCH) )
{
PlaceUniqueMonst(9, 0, 0);
}
if ( currlevel == quests[12]._qlevel && gbMaxPlayers != 1 )
{
skeltype = 0;
for ( skeltype = 0; skeltype < nummtypes; skeltype++ )
{
if ( IsSkel(Monsters[skeltype].mtype) )
{
break;
}
}
PlaceUniqueMonst(1, skeltype, 30);
}
if ( QuestStatus(QTYPE_BOL) )
{
setp = LoadFileInMem("Levels\\L1Data\\Banner1.DUN", 0);
SetMapMonsters(setp, 2 * setpc_x, 2 * setpc_y);
mem_free_dbg(setp);
}
if ( QuestStatus(QTYPE_BLOOD) )
{
setp = LoadFileInMem("Levels\\L2Data\\Blood2.DUN", 0);
SetMapMonsters(setp, 2 * setpc_x, 2 * setpc_y);
mem_free_dbg(setp);
}
if ( QuestStatus(QTYPE_BLIND) )
{
setp = LoadFileInMem("Levels\\L2Data\\Blind2.DUN", 0);
SetMapMonsters(setp, 2 * setpc_x, 2 * setpc_y);
mem_free_dbg(setp);
}
if ( QuestStatus(QTYPE_ANVIL) )
{
setp = LoadFileInMem("Levels\\L3Data\\Anvil.DUN", 0);
SetMapMonsters(setp, 2 * setpc_x + 2, 2 * setpc_y + 2);
mem_free_dbg(setp);
}
if ( QuestStatus(QTYPE_WARLRD) )
{
setp = LoadFileInMem("Levels\\L4Data\\Warlord.DUN", 0);
SetMapMonsters(setp, 2 * setpc_x, 2 * setpc_y);
mem_free_dbg(setp);
AddMonsterType(UniqMonst[8].mtype, 1);
}
if ( QuestStatus(QTYPE_VEIL) )
{
AddMonsterType(UniqMonst[7].mtype, 1);
}
if ( QuestStatus(QTYPE_ZHAR) && zharlib == -1 )
{
quests[3]._qactive = 0;
}
if ( currlevel == quests[15]._qlevel && gbMaxPlayers != 1 )
{
AddMonsterType(UniqMonst[4].mtype, 4);
AddMonsterType(UniqMonst[5].mtype, 4);
PlaceUniqueMonst(4, 0, 0);
PlaceUniqueMonst(5, 0, 0);
PlaceUniqueMonst(6, 0, 0);
setp = LoadFileInMem("Levels\\L4Data\\Vile1.DUN", 0);
SetMapMonsters(setp, 2 * setpc_x, 2 * setpc_y);
mem_free_dbg(setp);
}
}
else
{
if ( setlvlnum == SL_SKELKING )
{
PlaceUniqueMonst(1, 0, 0);
}
}
}
void __fastcall PlaceGroup(int mtype, int num, int leaderf, int leader)
{
int placed = 0;
int xp;
int yp;
int x1;
int y1;
for ( int try1 = 0; try1 < 10; try1++ )
{
while ( placed )
{
nummonsters--;
placed--;
dMonster[monster[nummonsters]._mx][monster[nummonsters]._my] = 0;
}
if ( leaderf & 1 )
{
int offset = random(92, 8);
xp = monster[leader]._mx + offset_x[offset];
yp = monster[leader]._my + offset_y[offset];
x1 = xp;
y1 = yp;
}
else
{
do
{
xp = random(93, 80) + 16;
x1 = xp;
yp = random(93, 80) + 16;
y1 = yp;
}
while ( !MonstPlace(xp, yp) );
}
if ( num + nummonsters > totalmonsters )
{
num = totalmonsters - nummonsters;
}
int j = 0;
for ( int try2 = 0; j < num && try2 < 100; xp += offset_x[random(94, 8)], yp += offset_x[random(94, 8)] )
{
if ( !MonstPlace(xp, yp)
|| (dung_map[x1][y1] != dung_map[xp][yp])
|| (leaderf & 2) && ((abs(xp - x1) >= 4) || (abs(yp - y1) >= 4)) )
{
try2++;
continue;
}
PlaceMonster(nummonsters, mtype, xp, yp);
if ( leaderf & 1 )
{
monster[nummonsters]._mmaxhp *= 2;
monster[nummonsters]._mhitpoints = monster[nummonsters]._mmaxhp;
monster[nummonsters]._mint = monster[leader]._mint;
if ( leaderf & 2 )
{
monster[nummonsters].leader = leader;
monster[nummonsters].leaderflag = 1;
monster[nummonsters]._mAi = monster[leader]._mAi;
}
if ( monster[nummonsters]._mAi != AI_GARG )
{
monster[nummonsters]._mAnimData = monster[nummonsters].MType->Anims[0].Frames[monster[nummonsters]._mdir];
monster[nummonsters]._mAnimFrame = random(88, monster[nummonsters]._mAnimLen - 1) + 1;
monster[nummonsters]._mFlags &= 0xFFFFFFFB;
monster[nummonsters]._mmode = MM_STAND;
}
}
nummonsters++;
placed++;
j++;
}
if ( placed >= num )
{
break;
}
}
if ( leaderf & 2 )
{
monster[leader].unpackfilesize = placed;
}
}
void __cdecl LoadDiabMonsts()
{
unsigned char *lpSetPiece; // esi
lpSetPiece = LoadFileInMem("Levels\\L4Data\\diab1.DUN", 0);
SetMapMonsters(lpSetPiece, 2 * diabquad1x, 2 * diabquad1y);
mem_free_dbg(lpSetPiece);
lpSetPiece = LoadFileInMem("Levels\\L4Data\\diab2a.DUN", 0);
SetMapMonsters(lpSetPiece, 2 * diabquad2x, 2 * diabquad2y);
mem_free_dbg(lpSetPiece);
lpSetPiece = LoadFileInMem("Levels\\L4Data\\diab3a.DUN", 0);
SetMapMonsters(lpSetPiece, 2 * diabquad3x, 2 * diabquad3y);
mem_free_dbg(lpSetPiece);
lpSetPiece = LoadFileInMem("Levels\\L4Data\\diab4a.DUN", 0);
SetMapMonsters(lpSetPiece, 2 * diabquad4x, 2 * diabquad4y);
mem_free_dbg(lpSetPiece);
}
// 5289C4: using guessed type int diabquad1x;
// 5289C8: using guessed type int diabquad1y;
void __cdecl InitMonsters()
{
int v0; // ebp
int v1; // ebx
TriggerStruct *v2; // esi
signed int v3; // ebp
signed int v4; // edi
int v5; // edi
int v6; // esi
int v7; // eax
int v8; // ecx
int v9; // edx
int v10; // eax
int v11; // esi
unsigned char *v12; // edi
int v13; // ebx
int v15; // esi
int v17; // eax
int v18; // eax
int v19; // ebx
TriggerStruct *v20; // esi
signed int v21; // ebp
signed int v22; // edi
int max; // [esp+10h] [ebp-1C4h]
int v24; // [esp+14h] [ebp-1C0h]
int scattertypes[111]; // [esp+18h] [ebp-1BCh]
v0 = 0;
max = 0;
if ( gbMaxPlayers != 1 )
CheckDungeonClear();
if ( !setlevel )
{
AddMonster(1, 0, 0, 0, 0);
AddMonster(1, 0, 0, 0, 0);
AddMonster(1, 0, 0, 0, 0);
AddMonster(1, 0, 0, 0, 0);
if ( !setlevel && currlevel == 16 )
LoadDiabMonsts();
}
v24 = trigflag[4];
if ( currlevel == 15 )
v24 = 1;
v1 = v24;
if ( v24 > 0 )
{
v2 = trigs;
do
{
v3 = -2;
do
{
v4 = -2;
do
DoVision(v3 + v2->_tx, v4++ + v2->_ty, 15, 0, 0);
while ( v4 < 2 );
++v3;
}
while ( v3 < 2 );
++v2;
--v1;
}
while ( v1 );
v0 = 0;
}
PlaceQuestMonsters();
if ( !setlevel )
{
PlaceUniques();
v5 = 16;
do
{
v6 = 16;
do
{
if ( !SolidLoc(v5, v6) )
++v0;
++v6;
}
while ( v6 < 96 );
++v5;
}
while ( v5 < 96 );
v7 = v0 / 30;
if ( gbMaxPlayers != 1 )
v7 += v7 >> 1;
v8 = nummonsters;
if ( nummonsters + v7 > 190 )
v7 = 190 - nummonsters;
v9 = nummtypes;
v10 = nummonsters + v7;
v11 = 0;
totalmonsters = v10;
if ( nummtypes > 0 )
{
v12 = &Monsters[0].mPlaceFlags;
do
{
if ( *v12 & 1 )
{
v13 = max++;
scattertypes[v13] = v11;
}
++v11;
v12 += 328;
}
while ( v11 < v9 );
}
if ( v8 < v10 )
{
while ( 1 )
{
v15 = scattertypes[random(95, max)];
if ( currlevel == 1 )
break;
if ( !random(95, 2) )
break;
if ( currlevel == 2 )
{
v17 = random(95, 2) + 1;
LABEL_40:
v18 = v17 + 1;
goto LABEL_41;
}
v18 = random(95, 3) + 3;
LABEL_41:
PlaceGroup(v15, v18, 0, 0);
if ( nummonsters >= totalmonsters )
goto LABEL_42;
}
v17 = 0;
goto LABEL_40;
}
}
LABEL_42:
v19 = v24;
if ( v24 > 0 )
{
v20 = trigs;
do
{
v21 = -2;
do
{
v22 = -2;
do
DoUnVision(v21 + v20->_tx, v22++ + v20->_ty, 15);
while ( v22 < 2 );
++v21;
}
while ( v21 < 2 );
++v20;
--v19;
}
while ( v19 );
}
}
// 5CF31D: using guessed type char setlevel;
// 658550: using guessed type int totalmonsters;
// 679660: using guessed type char gbMaxPlayers;
// 432637: using guessed type int var_1BC[111];
void __cdecl PlaceUniques()
{
int v0; // edi
int v1; // eax
UniqMonstStruct *v2; // ecx
int v3; // eax
int v4; // edx
CMonster *v5; // esi
int v6; // eax
int v7; // edx
v0 = 0;
if ( UniqMonst[0].mtype != -1 )
{
v1 = 0;
v2 = UniqMonst;
while ( UniqMonst[v1].mlevel != currlevel )
{
LABEL_25:
v1 = ++v0;
v2 = &UniqMonst[v0];
if ( v2->mtype == -1 )
return;
}
v3 = 0;
v4 = 0;
if ( nummtypes > 0 )
{
v5 = Monsters;
do
{
if ( v3 )
break;
v6 = -((char)v2->mtype != (unsigned char)v5->mtype);
++v5;
v3 = v6 + 1;
++v4;
}
while ( v4 < nummtypes );
}
v7 = v4 - 1;
if ( !v0 )
{
if ( quests[2]._qactive )
goto LABEL_23;
v3 = 0;
}
if ( v0 == 2 )
{
if ( quests[3]._qactive )
goto LABEL_23;
v3 = 0;
}
if ( v0 == 3 )
{
if ( quests[7]._qactive )
goto LABEL_23;
v3 = 0;
}
if ( v0 != 7 )
{
LABEL_20:
if ( v0 == 8 && !quests[11]._qactive )
v3 = 0;
goto LABEL_23;
}
if ( !quests[4]._qactive )
{
v3 = 0;
goto LABEL_20;
}
LABEL_23:
if ( v3 )
PlaceUniqueMonst(v0, v7, 8);
goto LABEL_25;
}
}
void __fastcall SetMapMonsters(unsigned char *pMap, int startx, int starty)
{
unsigned char *v3; // esi
unsigned short v4; // cx
int v5; // edx
int v6; // edi
int v7; // ecx
unsigned char *v8; // edx
int i; // esi
int v10; // eax
int v11; // ecx
int v12; // [esp+Ch] [ebp-Ch]
int v13; // [esp+10h] [ebp-8h]
unsigned char *v14; // [esp+14h] [ebp-4h]
int startya; // [esp+20h] [ebp+8h]
v12 = startx;
v3 = pMap;
AddMonsterType(MT_GOLEM, 2);
AddMonster(1, 0, 0, 0, 0);
AddMonster(1, 0, 0, 0, 0);
AddMonster(1, 0, 0, 0, 0);
AddMonster(1, 0, 0, 0, 0);
if ( setlevel && setlvlnum == SL_VILEBETRAYER )
{
AddMonsterType((char)UniqMonst[4].mtype, 4);
AddMonsterType((char)UniqMonst[5].mtype, 4);
AddMonsterType((char)UniqMonst[6].mtype, 4);
PlaceUniqueMonst(4, 0, 0);
PlaceUniqueMonst(5, 0, 0);
PlaceUniqueMonst(6, 0, 0);
}
v4 = *((_WORD *)v3 + 1);
v5 = *(unsigned short *)v3 * v4;
v6 = (unsigned short)(2 * *(_WORD *)v3);
v7 = (unsigned short)(2 * v4);
v8 = &v3[2 * v5 + 4 + 2 * v7 * v6];
v14 = v8;
if ( v7 > 0 )
{
v13 = v7;
startya = starty + 16;
do
{
for ( i = 0; i < v6; v14 += 2 )
{
if ( *(_WORD *)v8 )
{
v10 = AddMonsterType(MonstConvTbl[*(unsigned short *)v8 - 1], 2); /* fix */
v11 = nummonsters++;
PlaceMonster(v11, v10, i + v12 + 16, startya);
}
v8 = v14 + 2;
++i;
}
++startya;
--v13;
}
while ( v13 );
}
}
// 5CCB10: using guessed type char setlvlnum;
// 5CF31D: using guessed type char setlevel;
void __fastcall DeleteMonster(int i)
{
int *v1; // ecx
int *v2; // eax
int v3; // edx
--nummonsters;
v1 = &monstactive[i];
v2 = &monstactive[nummonsters];
v3 = *v2;
*v2 = *v1;
*v1 = v3;
}
int __fastcall AddMonster(int x, int y, int dir, int mtype, int InMap)
{
int i; // esi
if ( nummonsters >= MAXMONSTERS )
return -1;
i = monstactive[nummonsters++];
if ( InMap )
dMonster[x][y] = i + 1;
InitMonster(i, dir, mtype, x, y);
return i;
}
void __fastcall NewMonsterAnim(int i, AnimStruct *anim, int md)
{
MonsterStruct *v3; // eax
int v4; // esi
int v5; // edx
v3 = &monster[i];
v3->_mAnimData = anim->Frames[md];
v4 = anim->Rate;
v3->_mAnimCnt = 0;
v3->_mAnimLen = v4;
v3->_mAnimFrame = 1;
v5 = anim->Delay;
v3->_mFlags &= 0xFFFFFFF9;
v3->_mAnimDelay = v5;
v3->_mdir = md;
}
bool __fastcall M_Ranged(int i)
{
char v1; // cl
v1 = monster[i]._mAi;
return v1 == AI_SKELBOW || v1 == AI_GOATBOW || v1 == AI_SUCC || v1 == AI_LAZHELP;
}
bool __fastcall M_Talker(int i)
{
char v1; // cl
v1 = monster[i]._mAi;
return v1 == AI_LAZURUS
|| v1 == AI_WARLORD
|| v1 == AI_GARBUD
|| v1 == AI_ZHAR
|| v1 == AI_SNOTSPIL
|| v1 == AI_LACHDAN
|| v1 == AI_LAZHELP;
}
void __fastcall M_Enemy(int i)
{
MonsterStruct *v1; // esi
int *v2; // edi
int v3; // eax
int v4; // ecx
int v5; // ebx
int v6; // eax
int v7; // eax
int v8; // eax
int v9; // ecx
int v10; // edi
//int v11; // edx
int v12; // eax
int v13; // ecx
int v14; // ebx
int v15; // eax
int v16; // eax
int v17; // [esp+Ch] [ebp-20h]
int v18; // [esp+10h] [ebp-1Ch]
BOOL v19; // [esp+14h] [ebp-18h]
BOOL v20; // [esp+14h] [ebp-18h]
signed int v21; // [esp+18h] [ebp-14h]
int j; // [esp+18h] [ebp-14h]
signed int v23; // [esp+1Ch] [ebp-10h]
signed int v24; // [esp+20h] [ebp-Ch]
BOOL v25; // [esp+24h] [ebp-8h]
char v26; // [esp+2Ah] [ebp-2h]
char v27; // [esp+2Bh] [ebp-1h]
v24 = -1;
v18 = i;
v23 = -1;
v1 = &monster[i];
v25 = 0;
if ( !(v1->_mFlags & 0x20) )
{
v21 = 0;
v2 = &plr[0].plrlevel;
do
{
if ( !*((_BYTE *)v2 - 23) || currlevel != *v2 || *((_BYTE *)v2 + 267) || !v2[89] && gbMaxPlayers != 1 )
goto LABEL_18;
v3 = v1->_my;
v4 = v2[2];
v19 = dung_map[v2[1]][v4] == dung_map[v1->_mx][v3];
v5 = abs(v3 - v4);
if ( abs(v1->_mx - v2[1]) <= v5 )
v6 = v1->_my - v2[2];
else
v6 = v1->_mx - v2[1];
v7 = abs(v6);
if ( v19 )
{
if ( !v25 )
goto LABEL_17;
}
else if ( v25 )
{
goto LABEL_16;
}
if ( v7 < v23 )
goto LABEL_17;
LABEL_16:
if ( v24 == -1 )
{
LABEL_17:
v1->_mFlags &= 0xFFFFFFEF;
v24 = v21;
v27 = *((_BYTE *)v2 + 12);
v26 = *((_BYTE *)v2 + 16);
v23 = v7;
v25 = v19;
}
LABEL_18:
++v21;
v2 += 5430;
}
while ( (signed int)v2 < (signed int)&plr[4].plrlevel );
}
v8 = 0;
for ( j = 0; j < nummonsters; v8 = j++ + 1 )
{
v9 = monstactive[v8];
v17 = monstactive[v8];
if ( v9 == v18 )
continue;
v10 = v9;
if ( monster[v9]._mx == 1 && !monster[v10]._my )
continue;
if ( M_Talker(v9) && monster[v10].mtalkmsg )
continue;
if ( !(v1->_mFlags & 0x20)
&& ((abs(monster[v10]._mx - v1->_mx) >= 2 || abs(monster[v10]._my - v1->_my) >= 2) && !M_Ranged(v18) /* v11 */
|| !(v1->_mFlags & 0x20) && !(monster[v10]._mFlags & 0x20)) )
{
continue;
}
v12 = v1->_my;
v13 = monster[v10]._my;
v20 = dung_map[monster[v10]._mx][v13] == dung_map[v1->_mx][v12];
v14 = abs(v12 - v13);
if ( abs(v1->_mx - monster[v10]._mx) <= v14 )
v15 = v1->_my - monster[v10]._my;
else
v15 = v1->_mx - monster[v10]._mx;
v16 = abs(v15);
if ( v20 )
{
if ( !v25 )
goto LABEL_40;
}
else if ( v25 )
{
goto LABEL_39;
}
if ( v16 < v23 )
goto LABEL_40;
LABEL_39:
if ( v24 == -1 )
{
LABEL_40:
v1->_mFlags |= 0x10u;
v24 = v17;
v27 = monster[v10]._mfutx;
v26 = monster[v10]._mfuty;
v23 = v16;
v25 = v20;
}
}
if ( v24 == -1 )
{
BYTE1(v1->_mFlags) |= 4u;
}
else
{
BYTE1(v1->_mFlags) &= 0xFBu;
v1->_menemy = v24;
v1->_menemyx = v27;
v1->_menemyy = v26;
}
}
// 679660: using guessed type char gbMaxPlayers;
int __fastcall M_GetDir(int i)
{
return GetDirection(
monster[i]._mx,
monster[i]._my,
(unsigned char)monster[i]._menemyx,
(unsigned char)monster[i]._menemyy);
}
void __fastcall M_CheckEFlag(int i)
{
int v1; // ecx
int v2; // edi
char *v3; // eax
signed int v4; // edx
v1 = i;
v2 = 0;
v3 = (char *)dpiece_defs_map_2 + 32 * (112 * (monster[v1]._mx - 1) + monster[v1]._my + 1);
if ( v3 < (char *)dpiece_defs_map_2 )
goto LABEL_9;
v4 = 2;
do
v2 |= *(unsigned short *)&v3[2 * v4++];
while ( v4 < 10 );
if ( v2 | dArch[monster[v1]._mx - 1][monster[v1]._my + 1] )
monster[v1]._meflag = 1;
else
LABEL_9:
monster[v1]._meflag = 0;
}
void __fastcall M_StartStand(int i, int md)
{
int v2; // ebx
int v3; // edi
int v4; // esi
CMonster *v5; // eax
AnimStruct *v6; // edx
int v7; // eax
int v8; // ecx
v2 = md;
v3 = i;
ClearMVars(i);
v4 = v3;
v5 = monster[v3].MType;
v6 = &v5->Anims[1];
if ( v5->mtype != MT_GOLEM )
v6 = v5->Anims;
NewMonsterAnim(v3, v6, v2);
monster[v4]._mdir = v2;
monster[v4]._mVar1 = monster[v4]._mmode;
monster[v4]._mVar2 = 0;
monster[v4]._mmode = MM_STAND;
v7 = monster[v4]._mx;
monster[v4]._mxoff = 0;
monster[v4]._myoff = 0;
v8 = monster[v4]._my;
monster[v4]._mfuty = v8;
monster[v4]._moldy = v8;
monster[v4]._mfutx = v7;
monster[v4]._moldx = v7;
M_CheckEFlag(v3);
M_Enemy(v3);
}
void __fastcall M_StartDelay(int i, int len)
{
int v2; // eax
if ( len > 0 )
{
v2 = i;
if ( monster[i]._mAi != AI_LAZURUS )
{
monster[v2]._mVar2 = len;
monster[v2]._mmode = MM_DELAY;
}
}
}
void __fastcall M_StartSpStand(int i, int md)
{
int v2; // ebx
int v3; // esi
int v4; // edi
int v5; // eax
int v6; // ecx
v2 = i;
v3 = i;
v4 = md;
NewMonsterAnim(i, &monster[i].MType->Anims[5], md);
v5 = monster[v3]._mx;
v6 = monster[v3]._my;
monster[v3]._mxoff = 0;
monster[v3]._myoff = 0;
monster[v3]._mdir = v4;
monster[v3]._mmode = MM_SPSTAND;
monster[v3]._mfutx = v5;
monster[v3]._mfuty = v6;
monster[v3]._moldx = v5;
monster[v3]._moldy = v6;
M_CheckEFlag(v2);
}
void __fastcall M_StartWalk(int i, int xvel, int yvel, int xadd, int yadd, int EndDir)
{
int v6; // ST18_4
int v7; // esi
int v8; // eax
int v9; // ecx
CMonster *v10; // edx
v6 = i;
v7 = i;
v8 = monster[i]._mx;
monster[v7]._moldx = v8;
v9 = monster[i]._my;
monster[v7]._mfuty = v9 + yadd;
monster[v7]._mxvel = xvel;
monster[v7]._myvel = yvel;
monster[v7]._mVar1 = xadd;
monster[v7]._mVar2 = yadd;
dMonster[0][v9 + yadd + 112 * (v8 + xadd)] = -1 - v6;
v10 = monster[v7].MType;
monster[v7]._moldy = v9;
monster[v7]._mmode = MM_WALK;
monster[v7]._mfutx = v8 + xadd;
monster[v7]._mVar3 = EndDir;
monster[v7]._mdir = EndDir;
NewMonsterAnim(v6, &v10->Anims[1], EndDir);
monster[v7]._mVar6 = 0;
monster[v7]._mVar7 = 0;
monster[v7]._mVar8 = 0;
M_CheckEFlag(v6);
}
void __fastcall M_StartWalk2(int i, int xvel, int yvel, int xoff, int yoff, int xadd, int yadd, int EndDir)
{
int v8; // esi
int v9; // edx
int v10; // ecx
int v11; // eax
int v12; // eax
bool v13; // zf
CMonster *v14; // edx
int v15; // [esp+Ch] [ebp-8h]
int ia; // [esp+10h] [ebp-4h]
int EndDira; // [esp+28h] [ebp+14h]
v15 = xvel;
ia = i;
v8 = i;
v9 = xadd + monster[i]._mx;
EndDira = monster[i]._mx;
v10 = monster[i]._my;
v11 = monster[v8]._my;
monster[v8]._mVar2 = v10;
dMonster[0][v10 + 112 * EndDira] = -1 - ia;
monster[v8]._mVar1 = EndDira;
monster[v8]._moldx = EndDira;
v12 = yadd + v11;
monster[v8]._moldy = v10;
v13 = monster[v8]._uniqtype == 0;
monster[v8]._mx = v9;
monster[v8]._my = v12;
monster[v8]._mfutx = v9;
monster[v8]._mfuty = v12;
dMonster[0][v12 + 112 * v9] = ia + 1;
if ( !v13 )
ChangeLightXY((unsigned char)monster[v8].mlid, v9, v12);
v14 = monster[v8].MType;
monster[v8]._mxvel = v15;
monster[v8]._myvel = yvel;
monster[v8]._mxoff = xoff;
monster[v8]._myoff = yoff;
monster[v8]._mmode = MM_WALK2;
monster[v8]._mVar3 = EndDir;
monster[v8]._mdir = EndDir;
NewMonsterAnim(ia, &v14->Anims[1], EndDir);
monster[v8]._mVar8 = 0;
monster[v8]._mVar6 = 16 * xoff;
monster[v8]._mVar7 = 16 * yoff;
M_CheckEFlag(ia);
}
void __fastcall M_StartWalk3(int i, int xvel, int yvel, int xoff, int yoff, int xadd, int yadd, int mapx, int mapy, int EndDir)
{
int v10; // esi
int v11; // ebx
int v12; // edi
int v13; // edi
int v14; // ebx
int v15; // ecx
CMonster *v16; // edx
int v17; // [esp+Ch] [ebp-8h]
int ia; // [esp+10h] [ebp-4h]
int a6a; // [esp+28h] [ebp+14h]
int a7a; // [esp+2Ch] [ebp+18h]
ia = i;
v10 = i;
v11 = monster[i]._my;
v12 = monster[i]._mx;
v17 = xvel;
a6a = v12 + xadd;
a7a = v11 + yadd;
v13 = mapx + v12;
v14 = mapy + v11;
if ( monster[i]._uniqtype )
ChangeLightXY((unsigned char)monster[v10].mlid, v13, v14);
v15 = monster[v10]._my + 112 * monster[v10]._mx;
monster[v10]._mVar4 = v13;
dMonster[0][v15] = -1 - ia;
monster[v10]._mVar5 = v14;
dMonster[0][a7a + 112 * a6a] = -1 - ia;
monster[v10]._moldx = monster[v10]._mx;
monster[v10]._moldy = monster[v10]._my;
monster[v10]._mfutx = a6a;
monster[v10]._mxvel = v17;
dFlags[v13][v14] |= 0x10u;
v16 = monster[v10].MType;
monster[v10]._myvel = yvel;
monster[v10]._mfuty = a7a;
monster[v10]._mVar1 = a6a;
monster[v10]._mVar2 = a7a;
monster[v10]._mxoff = xoff;
monster[v10]._myoff = yoff;
monster[v10]._mmode = MM_WALK3;
monster[v10]._mVar3 = EndDir;
monster[v10]._mdir = EndDir;
NewMonsterAnim(ia, &v16->Anims[1], EndDir);
monster[v10]._mVar8 = 0;
monster[v10]._mVar6 = 16 * xoff;
monster[v10]._mVar7 = 16 * yoff;
M_CheckEFlag(ia);
}
void __fastcall M_StartAttack(int i)
{
int v1; // edi
int v2; // ebx
int v3; // esi
int v4; // ecx
int v5; // eax
v1 = i;
v2 = M_GetDir(i);
v3 = v1;
NewMonsterAnim(v1, &monster[v1].MType->Anims[2], v2);
v4 = monster[v1]._my;
v5 = monster[v1]._mx;
monster[v3]._mxoff = 0;
monster[v3]._myoff = 0;
monster[v3]._mfuty = v4;
monster[v3]._moldy = v4;
monster[v3]._mmode = MM_ATTACK;
monster[v3]._mfutx = v5;
monster[v3]._moldx = v5;
monster[v3]._mdir = v2;
M_CheckEFlag(v1);
}
void __fastcall M_StartRAttack(int i, int missile_type, int dam)
{
int v3; // ebp
int v4; // edi
int v5; // ebx
int v6; // esi
int v7; // ecx
int v8; // eax
v3 = missile_type;
v4 = i;
v5 = M_GetDir(i);
v6 = v4;
NewMonsterAnim(v4, &monster[v4].MType->Anims[2], v5);
v7 = monster[v4]._my;
monster[v6]._mxoff = 0;
monster[v6]._myoff = 0;
monster[v6]._mVar2 = dam;
v8 = monster[v4]._mx;
monster[v6]._mfuty = v7;
monster[v6]._moldy = v7;
monster[v6]._mmode = MM_RATTACK;
monster[v6]._mVar1 = v3;
monster[v6]._mfutx = v8;
monster[v6]._moldx = v8;
monster[v6]._mdir = v5;
M_CheckEFlag(v4);
}
void __fastcall M_StartRSpAttack(int i, int missile_type, int dam)
{
int v3; // ebp
int v4; // edi
int v5; // ebx
int v6; // esi
int v7; // ecx
int v8; // eax
v3 = missile_type;
v4 = i;
v5 = M_GetDir(i);
v6 = v4;
NewMonsterAnim(v4, &monster[v4].MType->Anims[5], v5);
monster[v6]._mmode = MM_RSPATTACK;
monster[v6]._mVar2 = 0;
monster[v6]._mVar3 = dam;
v7 = monster[v4]._my;
monster[v6]._mxoff = 0;
monster[v6]._myoff = 0;
v8 = monster[v4]._mx;
monster[v6]._mfuty = v7;
monster[v6]._moldy = v7;
monster[v6]._mVar1 = v3;
monster[v6]._mfutx = v8;
monster[v6]._moldx = v8;
monster[v6]._mdir = v5;
M_CheckEFlag(v4);
}
void __fastcall M_StartSpAttack(int i)
{
int v1; // edi
int v2; // ebx
int v3; // esi
int v4; // ecx
int v5; // eax
v1 = i;
v2 = M_GetDir(i);
v3 = v1;
NewMonsterAnim(v1, &monster[v1].MType->Anims[5], v2);
v4 = monster[v1]._my;
v5 = monster[v1]._mx;
monster[v3]._mxoff = 0;
monster[v3]._myoff = 0;
monster[v3]._mfuty = v4;
monster[v3]._moldy = v4;
monster[v3]._mmode = MM_SATTACK;
monster[v3]._mfutx = v5;
monster[v3]._moldx = v5;
monster[v3]._mdir = v2;
M_CheckEFlag(v1);
}
void __fastcall M_StartEat(int i)
{
int v1; // edi
int v2; // esi
int v3; // ecx
int v4; // eax
v1 = i;
v2 = i;
NewMonsterAnim(i, &monster[i].MType->Anims[5], monster[i]._mdir);
v3 = monster[v2]._my;
v4 = monster[v2]._mx;
monster[v2]._mxoff = 0;
monster[v2]._myoff = 0;
monster[v2]._mfuty = v3;
monster[v2]._moldy = v3;
monster[v2]._mmode = MM_SATTACK;
monster[v2]._mfutx = v4;
monster[v2]._moldx = v4;
M_CheckEFlag(v1);
}
void __fastcall M_ClearSquares(int i)
{
int v1; // edx
int v2; // eax
int v3; // esi
int v4; // ecx
int v5; // edi
int v6; // [esp+8h] [ebp-Ch]
_DWORD *v7; // [esp+Ch] [ebp-8h]
int v8; // [esp+10h] [ebp-4h]
v1 = monster[i]._moldx;
v2 = monster[i]._moldy;
v3 = -1 - i;
v6 = i + 1;
v4 = v2 - 1;
v5 = v2 + 1;
if ( (unsigned char)(__OFSUB__(v2 - 1, v2 + 1) ^ 1) | (v2 - 1 == v2 + 1) )
{
do
{
if ( v4 >= 0 && v4 < 112 )
{
v8 = v1 - 1;
if ( (unsigned char)(__OFSUB__(v1 - 1, v1 + 1) ^ 1) | (v1 - 1 == v1 + 1) )
{
v7 = (_DWORD *)((char *)dMonster + 4 * (v4 + 112 * (v1 - 1)));
do
{
if ( v8 >= 0 && v8 < 112 && (*v7 == v3 || *v7 == v6) )
*v7 = 0;
++v8;
v7 += 112;
}
while ( v8 <= v1 + 1 );
}
}
++v4;
v5 = v2 + 1;
}
while ( v4 <= v2 + 1 );
}
if ( v1 + 1 < 112 )
dFlags[v1 + 1][v2] &= 0xEFu;
if ( v5 < 112 )
dFlags[v1][v2 + 1] &= 0xEFu;
}
void __fastcall M_GetKnockback(int i)
{
int v1; // edi
int v2; // esi
int v3; // ebx
//int v4; // eax
int v5; // ST00_4
AnimStruct *v6; // edx
int v7; // eax
int v8; // ecx
int v9; // eax
v1 = i;
v2 = i;
v3 = ((unsigned char)monster[i]._mdir - 4) & 7;
//_LOBYTE(v4) = DirOK(i, v3);
if ( DirOK(i, v3) )
{
M_ClearSquares(v1);
v5 = monster[v2]._mdir;
v6 = &monster[v2].MType->Anims[3];
v7 = offset_y[v3];
monster[v2]._moldx += offset_x[v3];
monster[v2]._moldy += v7;
NewMonsterAnim(v1, v6, v5);
v8 = monster[v2]._moldy;
v9 = monster[v2]._moldx;
monster[v2]._mxoff = 0;
monster[v2]._myoff = 0;
monster[v2]._my = v8;
monster[v2]._mfuty = v8;
monster[v2]._mmode = MM_GOTHIT;
monster[v2]._mx = v9;
monster[v2]._mfutx = v9;
M_CheckEFlag(v1);
M_ClearSquares(v1);
dMonster[0][monster[v2]._my + 112 * monster[v2]._mx] = v1 + 1;
}
}
void __fastcall M_StartHit(int i, int pnum, int dam)
{
int v3; // ebx
int v4; // edi
int v5; // esi
unsigned char v6; // al
char v7; // al
unsigned char v8; // al
int v9; // ecx
int v10; // eax
v3 = pnum;
v4 = i;
if ( pnum >= 0 )
monster[i].mWhoHit |= 1 << pnum;
if ( pnum == myplr )
{
delta_monster_hp(i, monster[i]._mhitpoints, currlevel);
NetSendCmdParam2(0, CMD_MONSTDAMAGE, v4, dam);
}
PlayEffect(v4, 1);
v5 = v4;
v6 = monster[v4].MType->mtype;
if ( v6 >= MT_SNEAK && v6 <= MT_ILLWEAV || dam >> 6 >= SLOBYTE(monster[v5].mLevel) + 3 )
{
if ( v3 >= 0 )
{
monster[v5]._mFlags &= 0xFFFFFFEF;
monster[v5]._menemy = v3;
v7 = plr[v3]._py;
monster[v5]._menemyx = plr[v3]._px;
monster[v5]._menemyy = v7;
monster[v5]._mdir = M_GetDir(v4);
}
v8 = monster[v5].MType->mtype;
if ( v8 == MT_BLINK )
{
M_Teleport(v4);
}
else if ( v8 >= MT_NSCAV && v8 <= MT_YSCAV )
{
_LOBYTE(monster[v5]._mgoal) = 1;
}
if ( monster[v5]._mmode != MM_STONE )
{
NewMonsterAnim(v4, &monster[v5].MType->Anims[3], monster[v5]._mdir);
v9 = monster[v5]._moldy;
v10 = monster[v5]._moldx;
monster[v5]._mxoff = 0;
monster[v5]._myoff = 0;
monster[v5]._my = v9;
monster[v5]._mfuty = v9;
monster[v5]._mmode = MM_GOTHIT;
monster[v5]._mx = v10;
monster[v5]._mfutx = v10;
M_CheckEFlag(v4);
M_ClearSquares(v4);
dMonster[0][monster[v5]._my + 112 * monster[v5]._mx] = v4 + 1;
}
}
}
void __fastcall M_DiabloDeath(int i, unsigned char sendmsg)
{
int v2; // esi
int v3; // edi
int v4; // eax
int v5; // ebx
int v6; // esi
int v7; // ecx
int v8; // eax
int v9; // esi
int v10; // eax
double v11; // st7
int v12; // eax
int v13; // ecx
int v14; // esi
int v15; // [esp+8h] [ebp-8h]
int j; // [esp+Ch] [ebp-4h]
int v17; // [esp+Ch] [ebp-4h]
v15 = i;
v2 = sendmsg;
v3 = i;
PlaySFX(USFX_DIABLOD);
quests[5]._qactive = 3;
if ( v2 )
NetSendCmdQuest(1u, 5u);
gbProcessPlayers = 0;
_LOBYTE(sgbSaveSoundOn) = gbSoundOn;
v4 = 0;
for ( j = 0; j < nummonsters; ++j )
{
v5 = monstactive[v4];
if ( v5 != v15 && monster[v3]._msquelch )
{
v6 = v5;
NewMonsterAnim(monstactive[v4], &monster[v5].MType->Anims[4], monster[v5]._mdir);
v7 = monster[v5]._moldy;
monster[v6]._mxoff = 0;
monster[v6]._myoff = 0;
monster[v6]._mVar1 = 0;
v8 = monster[v5]._moldx;
monster[v6]._my = v7;
monster[v6]._mfuty = v7;
monster[v6]._mmode = MM_DEATH;
monster[v6]._mx = v8;
monster[v6]._mfutx = v8;
M_CheckEFlag(v5);
M_ClearSquares(v5);
dMonster[0][monster[v6]._my + 112 * monster[v6]._mx] = v5 + 1;
}
v4 = j + 1;
}
AddLight(monster[v3]._mx, monster[v3]._my, 8);
DoVision(monster[v3]._mx, monster[v3]._my, 8, 0, 1);
v9 = abs(ViewY - monster[v3]._my);
if ( abs(ViewX - monster[v3]._mx) <= v9 )
v10 = ViewY - monster[v3]._my;
else
v10 = ViewX - monster[v3]._mx;
v17 = abs(v10);
if ( v17 > 20 )
v17 = 20;
v11 = (double)v17;
v12 = ViewX << 16;
v13 = monster[v3]._mx << 16;
monster[v3]._mVar3 = ViewX << 16;
v14 = ViewY << 16;
monster[v3]._mVar4 = ViewY << 16;
monster[v3]._mVar5 = (signed __int64)((double)(v12 - v13) / v11);
monster[v3]._mVar6 = (signed __int64)((double)(v14 - (monster[v3]._my << 16)) / v11);
}
// 4A22D5: using guessed type char gbSoundOn;
// 5256A0: using guessed type int gbProcessPlayers;
// 64D32C: using guessed type int sgbSaveSoundOn;
void __fastcall M2MStartHit(int mid, int i, int dam)
{
int v3; // edi
int v4; // ebx
int v5; // esi
CMonster *v6; // eax
char v7; // al
CMonster *v8; // eax
int v9; // ecx
int v10; // eax
int v11; // [esp+Ch] [ebp-4h]
v3 = mid;
v4 = i;
v11 = i;
if ( (unsigned int)mid >= MAXMONSTERS )
TermMsg("Invalid monster %d getting hit by monster", mid);
v5 = v3;
if ( !monster[v3].MType )
TermMsg("Monster %d \"%s\" getting hit by monster: MType NULL", v3, monster[v5].mName);
if ( v4 >= 0 )
monster[v4].mWhoHit |= 1 << v4;
delta_monster_hp(v3, monster[v5]._mhitpoints, currlevel);
NetSendCmdParam2(0, CMD_MONSTDAMAGE, v3, dam);
PlayEffect(v3, 1);
v6 = monster[v5].MType;
if ( v6->mtype >= MT_SNEAK && v6->mtype <= MT_ILLWEAV || dam >> 6 >= SLOBYTE(monster[v5].mLevel) + 3 )
{
if ( v11 >= 0 )
monster[v5]._mdir = ((unsigned char)monster[v11]._mdir - 4) & 7;
v7 = v6->mtype;
if ( v7 == 39 )
{
M_Teleport(v3);
}
else if ( v7 >= MT_NSCAV && v7 <= MT_YSCAV )
{
_LOBYTE(monster[v5]._mgoal) = 1;
}
if ( monster[v5]._mmode != MM_STONE )
{
v8 = monster[v5].MType;
if ( v8->mtype != MT_GOLEM )
{
NewMonsterAnim(v3, &v8->Anims[3], monster[v5]._mdir);
monster[v5]._mmode = MM_GOTHIT;
}
v9 = monster[v5]._moldy;
v10 = monster[v5]._moldx;
monster[v5]._mxoff = 0;
monster[v5]._myoff = 0;
monster[v5]._my = v9;
monster[v5]._mfuty = v9;
monster[v5]._mx = v10;
monster[v5]._mfutx = v10;
M_CheckEFlag(v3);
M_ClearSquares(v3);
dMonster[0][monster[v5]._my + 112 * monster[v5]._mx] = v3 + 1;
}
}
}
void __fastcall MonstStartKill(int i, int pnum, unsigned char sendmsg)
{
signed int v3; // edi
int v4; // ebx
signed int v5; // esi
int v6; // ecx
int v7; // eax
//int v8; // eax
int v9; // eax
AnimStruct *v10; // edx
int v11; // ecx
int v12; // eax
unsigned char v13; // al
v3 = i;
v4 = pnum;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("MonstStartKill: Invalid monster %d", i);
v5 = v3;
if ( !monster[v3].MType )
TermMsg("MonstStartKill: Monster %d \"%s\" MType NULL", v3, monster[v5].mName);
if ( v4 >= 0 )
monster[v5].mWhoHit |= 1 << v4;
if ( v4 < 4 && v3 > 4 )
AddPlrMonstExper(SLOBYTE(monster[v5].mLevel), (unsigned short)monster[v5].mExp, monster[v5].mWhoHit);
v6 = monster[v5]._mRndSeed;
v7 = monster[v5].MType->mtype;
monster[v5]._mhitpoints = 0;
++monstkills[v7];
SetRndSeed(v6);
//_LOBYTE(v8) = QuestStatus(2);
if ( QuestStatus(2) && monster[v5].mName == UniqMonst[0].mName )
{
CreateTypeItem(monster[v5]._mx + 1, monster[v5]._my + 1, 1u, 4, 0, 1, 0);
}
else if ( v3 > 3 )
{
SpawnItem(v3, monster[v5]._mx, monster[v5]._my, sendmsg);
}
if ( monster[v5].MType->mtype == MT_DIABLO )
M_DiabloDeath(v3, 1u);
else
PlayEffect(v3, 2);
if ( v4 < 0 )
v9 = monster[v5]._mdir;
else
v9 = M_GetDir(v3);
v10 = &monster[v5].MType->Anims[4];
monster[v5]._mdir = v9;
NewMonsterAnim(v3, v10, v9);
v11 = monster[v5]._moldy;
v12 = monster[v5]._moldx;
monster[v5]._my = v11;
monster[v5]._mfuty = v11;
monster[v5]._mmode = MM_DEATH;
monster[v5]._mxoff = 0;
monster[v5]._myoff = 0;
monster[v5]._mVar1 = 0;
monster[v5]._mx = v12;
monster[v5]._mfutx = v12;
M_CheckEFlag(v3);
M_ClearSquares(v3);
dMonster[0][monster[v5]._my + 112 * monster[v5]._mx] = v3 + 1;
CheckQuestKill(v3, sendmsg);
M_FallenFear(monster[v5]._mx, monster[v5]._my);
v13 = monster[v5].MType->mtype;
if ( v13 >= MT_NACID && v13 <= MT_XACID )
AddMissile(monster[v5]._mx, monster[v5]._my, 0, 0, 0, 59, 1, v3, (unsigned char)monster[v5]._mint + 1, 0);
}
void __fastcall M2MStartKill(int i, int mid)
{
signed int v2; // ebx
signed int v3; // edi
signed int v4; // esi
int v5; // ecx
int v6; // eax
CMonster *v7; // ecx
int v8; // eax
int v9; // ecx
int v10; // eax
unsigned char v11; // al
v2 = i;
v3 = mid;
if ( (unsigned int)i >= MAXMONSTERS )
{
TermMsg("M2MStartKill: Invalid monster (attacker) %d", i);
TermMsg("M2MStartKill: Invalid monster (killed) %d", v3);
}
if ( !monster[v2].MType )
TermMsg("M2MStartKill: Monster %d \"%s\" MType NULL", v3, monster[v3].mName);
v4 = v3;
delta_kill_monster(v3, monster[v3]._mx, monster[v3]._my, currlevel);
NetSendCmdLocParam1(0, CMD_MONSTDEATH, monster[v4]._mx, monster[v4]._my, v3);
monster[v4].mWhoHit |= 1 << v2;
if ( v2 < 4 )
AddPlrMonstExper(SLOBYTE(monster[v4].mLevel), (unsigned short)monster[v4].mExp, monster[v3].mWhoHit);
v5 = monster[v4]._mRndSeed;
v6 = monster[v4].MType->mtype;
monster[v4]._mhitpoints = 0;
++monstkills[v6];
SetRndSeed(v5);
if ( v3 >= 4 )
SpawnItem(v3, monster[v4]._mx, monster[v4]._my, 1u);
if ( monster[v4].MType->mtype == MT_DIABLO )
M_DiabloDeath(v3, 1u);
else
PlayEffect(v2, 2);
PlayEffect(v3, 2);
v7 = monster[v4].MType;
v8 = ((unsigned char)monster[v2]._mdir - 4) & 7;
if ( v7->mtype == MT_GOLEM )
v8 = 0;
monster[v4]._mdir = v8;
NewMonsterAnim(v3, &v7->Anims[4], v8);
v9 = monster[v4]._moldy;
v10 = monster[v4]._moldx;
monster[v4]._my = v9;
monster[v4]._mfuty = v9;
monster[v4]._mmode = MM_DEATH;
monster[v4]._mxoff = 0;
monster[v4]._myoff = 0;
monster[v4]._mx = v10;
monster[v4]._mfutx = v10;
M_CheckEFlag(v3);
M_ClearSquares(v3);
dMonster[0][monster[v4]._my + 112 * monster[v4]._mx] = v3 + 1;
CheckQuestKill(v3, 1u);
M_FallenFear(monster[v4]._mx, monster[v4]._my);
v11 = monster[v4].MType->mtype;
if ( v11 >= MT_NACID && v11 <= MT_XACID )
AddMissile(monster[v4]._mx, monster[v4]._my, 0, 0, 0, 59, 1, v3, (unsigned char)monster[v4]._mint + 1, 0);
}
void __fastcall M_StartKill(int i, int pnum)
{
int v2; // edi
int v3; // ebx
int v4; // esi
int v5; // eax
v2 = i;
v3 = pnum;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("M_StartKill: Invalid monster %d", i);
if ( myplr == v3 )
{
v4 = v2;
delta_kill_monster(v2, monster[v2]._mx, monster[v2]._my, currlevel);
if ( v2 == v3 )
{
_LOWORD(v5) = currlevel;
NetSendCmdLocParam1(0, CMD_KILLGOLEM, monster[v4]._mx, monster[v4]._my, v5);
}
else
{
NetSendCmdLocParam1(0, CMD_MONSTDEATH, monster[v4]._mx, monster[v4]._my, v2);
}
}
MonstStartKill(v2, v3, 1u);
}
void __fastcall M_SyncStartKill(int i, int x, int y, int pnum)
{
int v4; // esi
int v5; // ebx
int v6; // esi
int arglist; // [esp+Ch] [ebp-4h]
v4 = i;
v5 = x;
arglist = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("M_SyncStartKill: Invalid monster %d", i);
v6 = v4;
if ( monster[v6]._mhitpoints && monster[v6]._mmode != MM_DEATH )
{
if ( !dMonster[0][y + 112 * v5] )
{
M_ClearSquares(arglist);
monster[v6]._mx = v5;
monster[v6]._my = y;
monster[v6]._moldx = v5;
monster[v6]._moldy = y;
}
if ( monster[v6]._mmode == MM_STONE )
{
MonstStartKill(arglist, pnum, 0);
monster[v6]._mmode = MM_STONE;
}
else
{
MonstStartKill(arglist, pnum, 0);
}
}
}
void __fastcall M_StartFadein(int i, int md, unsigned char backwards)
{
int v3; // esi
int v4; // ebx
int v5; // esi
int v6; // ecx
int v7; // eax
int *v8; // eax
int arglist; // [esp+Ch] [ebp-4h]
v3 = i;
v4 = md;
arglist = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("M_StartFadein: Invalid monster %d", i);
v5 = v3;
if ( !monster[v5].MType )
TermMsg("M_StartFadein: Monster %d \"%s\" MType NULL", arglist, monster[v5].mName);
NewMonsterAnim(arglist, &monster[v5].MType->Anims[5], v4);
v6 = monster[v5]._my;
v7 = monster[v5]._mx;
monster[v5]._mfuty = v6;
monster[v5]._moldy = v6;
monster[v5]._mmode = MM_FADEIN;
monster[v5]._mxoff = 0;
monster[v5]._myoff = 0;
monster[v5]._mfutx = v7;
monster[v5]._moldx = v7;
M_CheckEFlag(arglist);
v8 = &monster[v5]._mFlags;
monster[v5]._mdir = v4;
*v8 &= 0xFFFFFFFE;
if ( backwards )
{
*v8 = monster[v5]._mFlags | 2;
monster[v5]._mAnimFrame = monster[v5]._mAnimLen;
}
}
void __fastcall M_StartFadeout(int i, int md, unsigned char backwards)
{
int v3; // ebx
int v4; // esi
CMonster **v5; // edi
int v6; // ecx
int v7; // eax
int v8; // eax
int mda; // [esp+Ch] [ebp-4h]
v3 = i;
mda = md;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("M_StartFadeout: Invalid monster %d", i);
v4 = v3;
v5 = &monster[v3].MType;
if ( !*v5 )
TermMsg("M_StartFadeout: Monster %d \"%s\" MType NULL", v3, monster[v4].mName);
NewMonsterAnim(v3, &(*v5)->Anims[5], mda);
v6 = monster[v4]._my;
v7 = monster[v4]._mx;
monster[v4]._mfuty = v6;
monster[v4]._moldy = v6;
monster[v4]._mmode = MM_FADEOUT;
monster[v4]._mxoff = 0;
monster[v4]._myoff = 0;
monster[v4]._mfutx = v7;
monster[v4]._moldx = v7;
M_CheckEFlag(v3);
monster[v4]._mdir = mda;
if ( backwards )
{
v8 = monster[v4]._mAnimLen;
monster[v4]._mFlags |= 2u;
monster[v4]._mAnimFrame = v8;
}
}
void __fastcall M_StartHeal(int i)
{
int v1; // edi
int v2; // esi
CMonster *v3; // eax
unsigned char *v4; // ecx
int v5; // eax
v1 = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("M_StartHeal: Invalid monster %d", i);
v2 = v1;
if ( !monster[v1].MType )
TermMsg("M_StartHeal: Monster %d \"%s\" MType NULL", v1, monster[v2].mName);
v3 = monster[v2].MType;
v4 = v3->Anims[5].Frames[monster[v2]._mdir];
monster[v2]._mAnimData = v4;
v5 = v3->Anims[5].Rate;
monster[v2]._mFlags |= 2u;
monster[v2]._mAnimFrame = v5;
monster[v2]._mmode = MM_HEAL;
monster[v2]._mVar1 = monster[v2]._mmaxhp / (16 * (random(97, 5) + 4));
}
void __fastcall M_ChangeLightOffset(int monst)
{
int v1; // esi
int v2; // ecx
int v3; // eax
int v4; // esi
int v5; // edx
int v6; // eax
signed int v7; // esi
int v8; // edx
signed int v9; // esi
v1 = monst;
if ( (unsigned int)monst >= MAXMONSTERS )
TermMsg("M_ChangeLightOffset: Invalid monster %d", monst);
v2 = v1;
v3 = monster[v1]._myoff;
v4 = monster[v1]._mxoff;
v3 *= 2;
v5 = v4 + v3;
v6 = v3 - v4;
if ( v5 >= 0 )
{
v7 = 1;
}
else
{
v7 = -1;
v5 = -v5;
}
v8 = v7 * (v5 >> 3);
if ( v6 >= 0 )
{
v9 = 1;
}
else
{
v9 = -1;
v6 = -v6;
}
ChangeLightOff((unsigned char)monster[v2].mlid, v8, v9 * (v6 >> 3));
}
int __fastcall M_DoStand(int i)
{
int v1; // edi
int v2; // esi
CMonster *v3; // eax
int v4; // ecx
unsigned char *v5; // eax
v1 = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("M_DoStand: Invalid monster %d", i);
v2 = v1;
if ( !monster[v1].MType )
TermMsg("M_DoStand: Monster %d \"%s\" MType NULL", v1, monster[v2].mName);
v3 = monster[v2].MType;
v4 = monster[v2]._mdir;
if ( v3->mtype == MT_GOLEM )
v5 = v3->Anims[1].Frames[v4];
else
v5 = v3->Anims[0].Frames[v4];
monster[v2]._mAnimData = v5;
if ( monster[v2]._mAnimFrame == monster[v2]._mAnimLen )
M_Enemy(v1);
++monster[v2]._mVar2;
return 0;
}
int __fastcall M_DoWalk(int i)
{
int v1; // ebx
int v2; // esi
int v3; // edi
int v4; // eax
int v5; // edi
int v6; // ecx
int v7; // edx
int v8; // eax
bool v9; // zf
int v10; // ecx
int v11; // edx
int v12; // eax
int v13; // ecx
v1 = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("M_DoWalk: Invalid monster %d", i);
v2 = v1;
v3 = 0;
if ( !monster[v1].MType )
TermMsg("M_DoWalk: Monster %d \"%s\" MType NULL", v1, monster[v2].mName);
v4 = monster[v2]._mVar8;
if ( v4 == monster[v2].MType->Anims[1].Rate )
{
v5 = monster[v2]._my;
v6 = monster[v2]._mx;
dMonster[0][v5 + 112 * monster[v2]._mx] = 0;
v7 = v6 + monster[v2]._mVar1;
monster[v2]._mx = v7;
v8 = v5 + monster[v2]._mVar2;
v9 = monster[v2]._uniqtype == 0;
monster[v2]._my = v8;
dMonster[0][v8 + 112 * v7] = v1 + 1;
if ( !v9 )
ChangeLightXY((unsigned char)monster[v2].mlid, v7, v8);
M_StartStand(v1, monster[v2]._mdir);
v3 = 1;
}
else if ( !monster[v2]._mAnimCnt )
{
v10 = monster[v2]._mxvel;
v11 = monster[v2]._myvel;
monster[v2]._mVar8 = v4 + 1;
monster[v2]._mVar6 += v10;
v12 = monster[v2]._mVar6 >> 4;
monster[v2]._mVar7 += v11;
v13 = monster[v2]._mVar7 >> 4;
monster[v2]._mxoff = v12;
monster[v2]._myoff = v13;
}
if ( monster[v2]._uniqtype )
M_ChangeLightOffset(v1);
return v3;
}
int __fastcall M_DoWalk2(int i)
{
int v1; // ebp
int v2; // esi
int v3; // eax
bool v4; // zf
int v5; // edi
int v6; // ecx
int v7; // edx
int v8; // eax
int v9; // ecx
v1 = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("M_DoWalk2: Invalid monster %d", i);
v2 = v1;
if ( !monster[v1].MType )
TermMsg("M_DoWalk2: Monster %d \"%s\" MType NULL", v1, monster[v2].mName);
v3 = monster[v2]._mVar8;
if ( v3 == monster[v2].MType->Anims[1].Rate )
{
v4 = monster[v2]._uniqtype == 0;
dMonster[0][monster[v2]._mVar2 + 112 * monster[v2]._mVar1] = 0;
if ( !v4 )
ChangeLightXY((unsigned char)monster[v2].mlid, monster[v2]._mx, monster[v2]._my);
M_StartStand(v1, monster[v2]._mdir);
v5 = 1;
}
else
{
if ( !monster[v2]._mAnimCnt )
{
v6 = monster[v2]._mxvel;
v7 = monster[v2]._myvel;
monster[v2]._mVar8 = v3 + 1;
monster[v2]._mVar6 += v6;
v8 = monster[v2]._mVar6 >> 4;
monster[v2]._mVar7 += v7;
v9 = monster[v2]._mVar7 >> 4;
monster[v2]._mxoff = v8;
monster[v2]._myoff = v9;
}
v5 = 0;
}
if ( monster[v2]._uniqtype )
M_ChangeLightOffset(v1);
return v5;
}
int __fastcall M_DoWalk3(int i)
{
int v1; // ebp
int v2; // esi
int v3; // eax
int v4; // edi
int v5; // edx
int v6; // ecx
int v7; // edx
char *v8; // eax
bool v9; // zf
int v10; // edi
int v11; // ecx
int v12; // edx
int v13; // eax
int v14; // ecx
v1 = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("M_DoWalk3: Invalid monster %d", i);
v2 = v1;
if ( !monster[v1].MType )
TermMsg("M_DoWalk3: Monster %d \"%s\" MType NULL", v1, monster[v2].mName);
v3 = monster[v2]._mVar8;
if ( v3 == monster[v2].MType->Anims[1].Rate )
{
v4 = monster[v2]._mVar2;
v5 = monster[v2]._my + 112 * monster[v2]._mx;
monster[v2]._my = v4;
v6 = monster[v2]._mVar5;
dMonster[0][v5] = 0;
v7 = monster[v2]._mVar1;
monster[v2]._mx = v7;
v8 = &dFlags[monster[v2]._mVar4][v6];
*v8 &= 0xEFu;
v9 = monster[v2]._uniqtype == 0;
dMonster[0][v4 + 112 * v7] = v1 + 1;
if ( !v9 )
ChangeLightXY((unsigned char)monster[v2].mlid, v7, v4);
M_StartStand(v1, monster[v2]._mdir);
v10 = 1;
}
else
{
if ( !monster[v2]._mAnimCnt )
{
v11 = monster[v2]._mxvel;
v12 = monster[v2]._myvel;
monster[v2]._mVar8 = v3 + 1;
monster[v2]._mVar6 += v11;
v13 = monster[v2]._mVar6 >> 4;
monster[v2]._mVar7 += v12;
v14 = monster[v2]._mVar7 >> 4;
monster[v2]._mxoff = v13;
monster[v2]._myoff = v14;
}
v10 = 0;
}
if ( monster[v2]._uniqtype )
M_ChangeLightOffset(v1);
return v10;
}
void __fastcall M_TryM2MHit(int i, int mid, int hper, int mind, int maxd)
{
int v5; // edi
//int v6; // ST08_4
int v7; // esi
int v8; // ebx
//int v9; // eax
int v11; // eax
BOOL ret; // [esp+Ch] [ebp-Ch]
char v13[4]; // [esp+10h] [ebp-8h]
char arglist[4]; // [esp+14h] [ebp-4h]
v5 = mid;
*(_DWORD *)arglist = mid;
*(_DWORD *)v13 = i;
if ( (unsigned int)mid >= MAXMONSTERS )
{
TermMsg("M_TryM2MHit: Invalid monster %d", mid);
//i = v6;
}
v7 = v5;
if ( !monster[v5].MType )
TermMsg("M_TryM2MHit: Monster %d \"%s\" MType NULL", v5, monster[v7].mName);
if ( (signed int)(monster[v7]._mhitpoints & 0xFFFFFFC0) > 0
&& (monster[v7].MType->mtype != MT_ILLWEAV || _LOBYTE(monster[v7]._mgoal) != 2) )
{
v8 = random(4, 100);
if ( monster[v7]._mmode == MM_STONE )
v8 = 0;
//_LOBYTE(v9) = CheckMonsterHit(*(int *)arglist, &ret);
if ( !CheckMonsterHit(*(int *)arglist, &ret) && v8 < hper )
{
v11 = (mind + random(5, maxd - mind + 1)) << 6;
monster[v7]._mhitpoints -= v11;
if ( (signed int)(monster[v7]._mhitpoints & 0xFFFFFFC0) > 0 )
{
if ( monster[v7]._mmode == MM_STONE )
{
M2MStartHit(*(int *)arglist, *(int *)v13, v11);
goto LABEL_15;
}
M2MStartHit(*(int *)arglist, *(int *)v13, v11);
}
else
{
if ( monster[v7]._mmode == MM_STONE )
{
M2MStartKill(*(int *)v13, *(int *)arglist);
LABEL_15:
monster[v7]._mmode = MM_STONE;
return;
}
M2MStartKill(*(int *)v13, *(int *)arglist);
}
}
}
}
void __fastcall M_TryH2HHit(int i, int pnum, int Hit, int MinDam, int MaxDam)
{
int v5; // esi
int v6; // ebx
int v7; // esi
int v8; // edi
int v9; // eax
//int v10; // ST08_4
int v12; // ecx
int v13; // edi
int v14; // eax
int v15; // eax
int *v16; // ecx
int v17; // eax
int v18; // edi
int v19; // edx
int v20; // eax
int v21; // eax
int v22; // edx
int v23; // eax
bool v24; // zf
bool v25; // sf
unsigned char v26; // of
int v27; // eax
int v29; // edi
int v30; // eax
int v31; // eax
int v32; // eax
int v33; // edi
int v34; // ebx
int v35; // edx
int v36; // [esp+Ch] [ebp-Ch]
int arglist; // [esp+10h] [ebp-8h]
int plr_num; // [esp+14h] [ebp-4h]
int hper; // [esp+20h] [ebp+8h]
v5 = i;
plr_num = pnum;
arglist = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("M_TryH2HHit: Invalid monster %d", i);
v6 = v5;
if ( !monster[v5].MType )
TermMsg("M_TryH2HHit: Monster %d \"%s\" MType NULL", v5, monster[v6].mName);
if ( monster[v6]._mFlags & 0x10 )
{
M_TryM2MHit(v5, plr_num, Hit, MinDam, MaxDam);
return;
}
v7 = plr_num;
if ( (signed int)(plr[plr_num]._pHitPoints & 0xFFFFFFC0) > 0 && !plr[v7]._pInvincible && !(plr[v7]._pSpellFlags & 1) )
{
v8 = abs(monster[v6]._mx - plr[v7].WorldX);
v9 = abs(monster[v6]._my - plr[v7].WorldY);
//v11 = v10;
if ( v8 < 2 && v9 < 2 )
{
v36 = random(98, 100);
#ifdef _DEBUG
if ( debug_mode_dollar_sign || debug_mode_key_inverted_v )
v36 = 1000;
#endif
v12 = 5;
v13 = Hit
+ 2 * (SLOBYTE(monster[v6].mLevel) - plr[v7]._pLevel)
+ 30
- plr[v7]._pIBonusAC
- plr[v7]._pIAC
- plr[v7]._pDexterity / 5;
if ( v13 < 15 )
v13 = 15;
if ( currlevel == 14 )
{
if ( v13 >= 20 )
goto LABEL_23;
v13 = 20;
}
if ( currlevel != 15 )
{
LABEL_20:
if ( currlevel == 16 && v13 < 30 )
v13 = 30;
goto LABEL_23;
}
if ( v13 < 25 )
{
v13 = 25;
goto LABEL_20;
}
LABEL_23:
v14 = plr[v7]._pmode;
if ( v14 && v14 != 4 || !plr[v7]._pBlockFlag )
{
v15 = 100;
}
else
{
v15 = random(98, 100);
}
v16 = (int *)(plr[v7]._pDexterity
+ plr[v7]._pBaseToBlk
- 2 * SLOBYTE(monster[v6].mLevel)
+ 2 * plr[v7]._pLevel);
if ( (signed int)v16 < 0 )
v16 = 0;
if ( (signed int)v16 > 100 )
v16 = (int *)100;
if ( v36 < v13 )
{
if ( v15 >= (signed int)v16 )
{
if ( monster[v6].MType->mtype == MT_YZOMBIE && plr_num == myplr )
{
v18 = -1;
v19 = 0;
for ( hper = -1; v19 < nummissiles; ++v19 )
{
v20 = missileactive[v19];
if ( missile[v20]._mitype == 13 )
{
if ( missile[v20]._misource == plr_num )
{
v18 = missileactive[v19];
hper = missileactive[v19];
}
else
{
v18 = hper;
}
}
}
v16 = &plr[v7]._pMaxHP;
v21 = plr[v7]._pMaxHP;
if ( v21 > 64 )
{
v22 = plr[v7]._pMaxHPBase;
if ( v22 > 64 )
{
v23 = v21 - 64;
v26 = __OFSUB__(plr[v7]._pHitPoints, v23);
v24 = plr[v7]._pHitPoints == v23;
v25 = plr[v7]._pHitPoints - v23 < 0;
*v16 = v23;
if ( !((unsigned char)(v25 ^ v26) | v24) )
{
plr[v7]._pHitPoints = v23;
if ( v18 >= 0 )
missile[v18]._miVar1 = v23;
}
v16 = &plr[v7]._pHPBase;
v27 = v22 - 64;
plr[v7]._pMaxHPBase = v22 - 64;
if ( plr[v7]._pHPBase > v22 - 64 )
{
*v16 = v27;
if ( v18 >= 0 )
missile[v18]._miVar2 = v27;
}
}
}
}
v29 = (plr[v7]._pIGetHit << 6) + (MinDam << 6) + random(99, (MaxDam - MinDam + 1) << 6);
if ( v29 < 64 )
v29 = 64;
if ( plr_num == myplr )
{
plr[v7]._pHitPoints -= v29;
plr[v7]._pHPBase -= v29;
}
if ( plr[v7]._pIFlags & 0x4000000 )
{
v30 = (random(99, 3) + 1) << 6;
monster[v6]._mhitpoints -= v30;
if ( (signed int)(monster[v6]._mhitpoints & 0xFFFFFFC0) > 0 )
M_StartHit(arglist, plr_num, v30);
else
M_StartKill(arglist, plr_num);
}
if ( !(monster[v6]._mFlags & 0x1000) && monster[v6].MType->mtype == MT_SKING && gbMaxPlayers != 1 )
monster[v6]._mhitpoints += v29;
v31 = plr[v7]._pMaxHP;
if ( plr[v7]._pHitPoints > v31 )
{
plr[v7]._pHitPoints = v31;
plr[v7]._pHPBase = plr[v7]._pMaxHPBase;
}
if ( (signed int)(plr[v7]._pHitPoints & 0xFFFFFFC0) > 0 )
{
StartPlrHit(plr_num, v29, 0);
if ( SLOBYTE(monster[v6]._mFlags) < 0 )
{
if ( plr[v7]._pmode != PM_GOTHIT )
StartPlrHit(plr_num, 0, 1u);
v32 = monster[v6]._mdir;
v33 = plr[v7].WorldX + offset_x[v32];
v34 = plr[v7].WorldY + offset_y[v32];
if ( PosOkPlayer(plr_num, v33, v34) )
{
v35 = plr[v7]._pdir;
plr[v7].WorldX = v33;
plr[v7].WorldY = v34;
FixPlayerLocation(plr_num, v35);
FixPlrWalkTags(plr_num);
dPlayer[v33][v34] = plr_num + 1;
SetPlayerOld(plr_num);
}
}
}
else
{
SyncPlrKill(plr_num, 0);
}
}
else
{
v17 = GetDirection(plr[v7].WorldX, plr[v7].WorldY, monster[v6]._mx, monster[v6]._my);
StartPlrBlock(plr_num, v17);
}
}
return;
}
}
}
// 679660: using guessed type char gbMaxPlayers;
int __fastcall M_DoAttack(int i)
{
int v1; // edi
int v2; // esi
CMonster **v3; // ebx
unsigned char v4; // al
unsigned char v5; // al
v1 = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("M_DoAttack: Invalid monster %d", i);
v2 = v1;
v3 = &monster[v1].MType;
if ( !*v3 )
{
TermMsg("M_DoAttack: Monster %d \"%s\" MType NULL", v1, monster[v2].mName);
if ( !*v3 )
TermMsg("M_DoAttack: Monster %d \"%s\" MData NULL", v1, monster[v2].mName);
}
if ( monster[v2]._mAnimFrame == monster[v2].MData->mAFNum )
{
M_TryH2HHit(
v1,
monster[v2]._menemy,
(unsigned char)monster[v2].mHit,
(unsigned char)monster[v2].mMinDamage,
(unsigned char)monster[v2].mMaxDamage);
if ( monster[v2]._mAi != AI_SNAKE )
PlayEffect(v1, 0);
}
v4 = monster[v2].MType->mtype;
if ( v4 >= MT_NMAGMA && v4 <= MT_WMAGMA && monster[v2]._mAnimFrame == 9 )
{
M_TryH2HHit(
v1,
monster[v2]._menemy,
(unsigned char)monster[v2].mHit + 10,
(unsigned char)monster[v2].mMinDamage - 2,
(unsigned char)monster[v2].mMaxDamage - 2);
PlayEffect(v1, 0);
}
v5 = monster[v2].MType->mtype;
if ( v5 >= MT_STORM && v5 <= MT_MAEL && monster[v2]._mAnimFrame == 13 )
{
M_TryH2HHit(
v1,
monster[v2]._menemy,
(unsigned char)monster[v2].mHit - 20,
(unsigned char)monster[v2].mMinDamage + 4,
(unsigned char)monster[v2].mMaxDamage + 4);
PlayEffect(v1, 0);
}
if ( monster[v2]._mAi == AI_SNAKE && monster[v2]._mAnimFrame == 1 )
PlayEffect(v1, 0);
if ( monster[v2]._mAnimFrame != monster[v2]._mAnimLen )
return 0;
M_StartStand(v1, monster[v2]._mdir);
return 1;
}
int __fastcall M_DoRAttack(int i)
{
int v1; // ebx
int v2; // esi
CMonster **v3; // edi
int v4; // eax
int v5; // eax
int v6; // edi
v1 = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("M_DoRAttack: Invalid monster %d", i);
v2 = v1;
v3 = &monster[v1].MType;
if ( !*v3 )
{
TermMsg("M_DoRAttack: Monster %d \"%s\" MType NULL", v1, monster[v2].mName);
if ( !*v3 )
TermMsg("M_DoRAttack: Monster %d \"%s\" MData NULL", v1, monster[v2].mName);
}
if ( monster[v2]._mAnimFrame == monster[v2].MData->mAFNum )
{
v4 = monster[v2]._mVar1;
if ( v4 != -1 )
{
v5 = 2 * (v4 == 52) + 1;
if ( v5 > 0 )
{
v6 = v5;
do
{
AddMissile(
monster[v2]._mx,
monster[v2]._my,
(unsigned char)monster[v2]._menemyx,
(unsigned char)monster[v2]._menemyy,
monster[v2]._mdir,
monster[v2]._mVar1,
1,
v1,
monster[v2]._mVar2,
0);
--v6;
}
while ( v6 );
}
}
PlayEffect(v1, 0);
}
if ( monster[v2]._mAnimFrame != monster[v2]._mAnimLen )
return 0;
M_StartStand(v1, monster[v2]._mdir);
return 1;
}
int __fastcall M_DoRSpAttack(int i)
{
int v1; // ebx
int v2; // esi
CMonster **v3; // edi
bool v4; // zf
int v5; // ecx
v1 = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("M_DoRSpAttack: Invalid monster %d", i);
v2 = v1;
v3 = &monster[v1].MType;
v4 = *v3 == 0;
if ( !*v3 )
{
TermMsg("M_DoRSpAttack: Monster %d \"%s\" MType NULL", v1, monster[v2].mName);
v4 = *v3 == 0;
}
if ( v4 )
TermMsg("M_DoRSpAttack: Monster %d \"%s\" MData NULL", v1, monster[v2].mName);
if ( monster[v2]._mAnimFrame == monster[v2].MData->mAFNum2 && !monster[v2]._mAnimCnt )
{
AddMissile(
monster[v2]._mx,
monster[v2]._my,
(unsigned char)monster[v2]._menemyx,
(unsigned char)monster[v2]._menemyy,
monster[v2]._mdir,
monster[v2]._mVar1,
1,
v1,
monster[v2]._mVar3,
0);
PlayEffect(v1, 3);
}
if ( monster[v2]._mAi == AI_MEGA && monster[v2]._mAnimFrame == 3 )
{
v5 = monster[v2]._mVar2;
monster[v2]._mVar2 = v5 + 1;
if ( v5 )
{
if ( v5 == 14 )
monster[v2]._mFlags &= 0xFFFFFFFB;
}
else
{
monster[v2]._mFlags |= 4u;
}
}
if ( monster[v2]._mAnimFrame != monster[v2]._mAnimLen )
return 0;
M_StartStand(v1, monster[v2]._mdir);
return 1;
}
int __fastcall M_DoSAttack(int i)
{
int v1; // ebx
int v2; // esi
CMonster **v3; // edi
bool v4; // zf
v1 = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("M_DoSAttack: Invalid monster %d", i);
v2 = v1;
v3 = &monster[v1].MType;
v4 = *v3 == 0;
if ( !*v3 )
{
TermMsg("M_DoSAttack: Monster %d \"%s\" MType NULL", v1, monster[v2].mName);
v4 = *v3 == 0;
}
if ( v4 )
TermMsg("M_DoSAttack: Monster %d \"%s\" MData NULL", v1, monster[v2].mName);
if ( monster[v2]._mAnimFrame == monster[v2].MData->mAFNum2 )
M_TryH2HHit(
v1,
monster[v2]._menemy,
(unsigned char)monster[v2].mHit2,
(unsigned char)monster[v2].mMinDamage2,
(unsigned char)monster[v2].mMaxDamage2);
if ( monster[v2]._mAnimFrame != monster[v2]._mAnimLen )
return 0;
M_StartStand(v1, monster[v2]._mdir);
return 1;
}
int __fastcall M_DoFadein(int i)
{
int v1; // edi
int v2; // esi
v1 = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("M_DoFadein: Invalid monster %d", i);
v2 = v1;
if ( (!(monster[v1]._mFlags & 2) || monster[v2]._mAnimFrame != 1)
&& (monster[v1]._mFlags & 2 || monster[v2]._mAnimFrame != monster[v2]._mAnimLen) )
{
return 0;
}
M_StartStand(v1, monster[v2]._mdir);
monster[v2]._mFlags &= 0xFFFFFFFD;
return 1;
}
int __fastcall M_DoFadeout(int i)
{
int v1; // esi
int v2; // eax
int v3; // ecx
signed int v4; // edx
int v5; // ecx
int v6; // edx
v1 = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("M_DoFadeout: Invalid monster %d", i);
v2 = v1;
v3 = monster[v1]._mFlags;
if ( (!(monster[v1]._mFlags & 2) || monster[v2]._mAnimFrame != 1)
&& (monster[v1]._mFlags & 2 || monster[v2]._mAnimFrame != monster[v2]._mAnimLen) )
{
return 0;
}
v4 = monster[v2].MType->mtype;
if ( v4 < MT_INCIN || v4 > MT_HELLBURN )
v5 = v3 & 0xFFFFFFFD | 1;
else
v5 = v3 & 0xFFFFFFFD;
v6 = monster[v2]._mdir;
monster[v2]._mFlags = v5;
M_StartStand(v1, v6);
return 1;
}
int __fastcall M_DoHeal(int i)
{
int v1; // esi
int v2; // eax
int v3; // esi
int *v4; // edx
int v5; // ecx
int v6; // edi
int v7; // edi
int v8; // esi
v1 = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("M_DoHeal: Invalid monster %d", i);
v2 = v1;
if ( monster[v1]._mFlags & 8 )
{
monster[v2]._mFlags &= 0xFFFFFFFB;
monster[v2]._mmode = MM_SATTACK;
}
else if ( monster[v2]._mAnimFrame == 1 )
{
v3 = monster[v2]._mVar1;
v4 = &monster[v2]._mhitpoints;
v5 = monster[v2]._mFlags & 0xFFFFFFFD | 4;
v6 = monster[v2]._mhitpoints;
monster[v2]._mFlags = v5;
v7 = v3 + v6;
v8 = monster[v2]._mmaxhp;
if ( v7 >= v8 )
{
*v4 = v8;
monster[v2]._mFlags = v5 & 0xFFFFFFFB;
monster[v2]._mmode = MM_SATTACK;
}
else
{
*v4 = v7;
}
}
return 0;
}
int __fastcall M_DoTalk(int i)
{
int v1; // edi
int v2; // esi
//int v3; // eax
int v4; // eax
int v5; // edx
int v6; // ecx
char v7; // bl
int v8; // eax
char *v9; // eax
v1 = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("M_DoTalk: Invalid monster %d", i);
v2 = v1;
M_StartStand(v1, monster[v1]._mdir);
_LOBYTE(monster[v1]._mgoal) = 7;
//_LOBYTE(v3) = effect_is_playing(alltext[monster[v1].mtalkmsg].sfxnr);
if ( !effect_is_playing(alltext[monster[v1].mtalkmsg].sfxnr) )
{
InitQTextMsg(monster[v2].mtalkmsg);
if ( monster[v2].mName == UniqMonst[0].mName )
{
v4 = monster[v2].mtalkmsg;
if ( v4 == QUEST_GARBUD1 )
quests[2]._qactive = 2;
quests[2]._qlog = 1;
if ( v4 == QUEST_GARBUD2 && !(monster[v2]._mFlags & 0x40) )
{
SpawnItem(v1, monster[v2]._mx + 1, monster[v2]._my + 1, 1u);
monster[v2]._mFlags |= 0x40u;
}
}
if ( monster[v2].mName == UniqMonst[2].mName
&& monster[v2].mtalkmsg == QUEST_ZHAR1
&& !(monster[v2]._mFlags & 0x40) )
{
v5 = monster[v2]._my + 1;
v6 = monster[v2]._mx + 1;
quests[3]._qactive = 2;
quests[3]._qlog = 1;
CreateTypeItem(v6, v5, 0, 0, 24, 1, 0);
monster[v2]._mFlags |= 0x40u;
}
if ( monster[v2].mName == UniqMonst[3].mName )
{
if ( monster[v2].mtalkmsg == QUEST_BANNER10 && !(monster[v2]._mFlags & 0x40) )
{
ObjChangeMap(setpc_x, setpc_y, (setpc_w >> 1) + setpc_x + 2, (setpc_h >> 1) + setpc_y - 2);
v7 = TransVal;
TransVal = 9;
DRLG_MRectTrans(setpc_x, setpc_y, (setpc_w >> 1) + setpc_x + 4, setpc_y + (setpc_h >> 1));
TransVal = v7;
quests[7]._qvar1 = 2;
if ( quests[7]._qactive == 1 )
quests[7]._qactive = 2;
monster[v2]._mFlags |= 0x40u;
}
if ( quests[7]._qvar1 < 2u )
{
sprintf(tempstr, "SS Talk = %i, Flags = %i", monster[v2].mtalkmsg, monster[v2]._mFlags);
TermMsg(tempstr);
}
}
if ( monster[v2].mName == UniqMonst[7].mName )
{
v8 = monster[v2].mtalkmsg;
if ( v8 == QUEST_VEIL9 )
{
quests[4]._qactive = 2;
quests[4]._qlog = 1;
}
if ( v8 == QUEST_VEIL11 && !(monster[v2]._mFlags & 0x40) )
{
SpawnUnique(UITEM_STEELVEIL, monster[v2]._mx + 1, monster[v2]._my + 1);
monster[v2]._mFlags |= 0x40u;
}
}
v9 = monster[v2].mName;
if ( v9 == UniqMonst[8].mName )
quests[11]._qvar1 = 2;
if ( v9 == UniqMonst[4].mName && gbMaxPlayers != 1 )
{
monster[v2]._msquelch = -1;
monster[v2].mtalkmsg = 0;
quests[15]._qvar1 = 6;
_LOBYTE(monster[v2]._mgoal) = 1;
}
}
return 0;
}
// 4351F5: could not find valid save-restore pair for ebp
// 5A5590: using guessed type char TransVal;
// 5CF330: using guessed type int setpc_h;
// 5CF334: using guessed type int setpc_w;
// 679660: using guessed type char gbMaxPlayers;
void __fastcall M_Teleport(int i)
{
int v1; // ebx
//int v2; // ST04_4
MonsterStruct *v3; // esi
int v4; // eax
int v6; // edi
int v7; // ebx
int v8; // eax
int v9; // [esp+Ch] [ebp-24h]
int v10; // [esp+10h] [ebp-20h]
int v11; // [esp+14h] [ebp-1Ch]
int v12; // [esp+18h] [ebp-18h]
int v13; // [esp+1Ch] [ebp-14h]
int a1; // [esp+20h] [ebp-10h]
signed int v15; // [esp+24h] [ebp-Ch]
signed int v16; // [esp+28h] [ebp-8h]
signed int v17; // [esp+2Ch] [ebp-4h]
v1 = i;
a1 = i;
if ( (unsigned int)i >= MAXMONSTERS )
{
TermMsg("M_Teleport: Invalid monster %d", i);
//i = v2;
}
v15 = 0;
v3 = &monster[v1];
if ( v3->_mmode != MM_STONE )
{
v10 = (unsigned char)v3->_menemyx;
v12 = (unsigned char)v3->_menemyy;
v4 = random(100, 2);
v11 = 2 * v4 - 1;
v17 = -1;
v6 = 0; /* v9 */
v13 = 2 * random(100, 2) - 1;
while ( !v15 )
{
v16 = -1;
v7 = v12 - v13;
do
{
if ( v15 )
break;
if ( v17 || v16 )
{
v9 = v7;
v6 = v10 + v11 * v17;
if ( v7 >= 0 && v7 < 112 && v6 >= 0 && v6 < 112 && v6 != v3->_mx && v7 != v3->_my )
{
if ( PosOkMonst(a1, v10 + v11 * v17, v7) )
v15 = 1;
}
}
++v16;
v7 += v13;
}
while ( v16 < 1 );
if ( ++v17 > 1 )
{
if ( !v15 )
return;
v1 = a1;
break;
}
v1 = a1;
}
M_ClearSquares(v1);
v8 = v3->_my + 112 * v3->_mx;
v3->_moldx = v6;
dMonster[0][v8] = 0;
v3->_moldy = v9;
dMonster[0][v9 + 112 * v6] = v1 + 1;
v3->_mdir = M_GetDir(v1);
M_CheckEFlag(v1);
}
}
int __fastcall M_DoGotHit(int i)
{
int v1; // edi
int v2; // esi
v1 = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("M_DoGotHit: Invalid monster %d", i);
v2 = v1;
if ( !monster[v1].MType )
TermMsg("M_DoGotHit: Monster %d \"%s\" MType NULL", v1, monster[v2].mName);
if ( monster[v2]._mAnimFrame != monster[v2]._mAnimLen )
return 0;
M_StartStand(v1, monster[v2]._mdir);
return 1;
}
void __fastcall M_UpdateLeader(int i)
{
int v1; // edi
int v2; // esi
int j; // edx
int v4; // eax
unsigned char *v5; // eax
v1 = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("M_UpdateLeader: Invalid monster %d", i);
v2 = nummonsters;
for ( j = 0; j < v2; ++j )
{
v4 = monstactive[j];
if ( monster[v4].leaderflag == 1 && (unsigned char)monster[v4].leader == v1 )
monster[v4].leaderflag = 0;
}
if ( monster[v1].leaderflag == 1 )
{
v5 = &monster[(unsigned char)monster[v1].leader].unpackfilesize;
--*v5;
}
}
void __cdecl DoEnding()
{
if ( gbMaxPlayers > 1 ) {
SNetLeaveGame(0x40000004);
}
music_stop();
if ( gbMaxPlayers > 1 ) {
Sleep(1000);
}
if ( plr[myplr]._pClass == PC_WARRIOR ) {
play_movie("gendata\\DiabVic2.smk", 0);
} else if ( plr[myplr]._pClass == PC_SORCERER ) {
play_movie("gendata\\DiabVic1.smk", 0);
} else {
play_movie("gendata\\DiabVic3.smk", 0);
}
play_movie("gendata\\Diabend.smk", 0);
BOOL bMusicOn = gbMusicOn;
gbMusicOn = 1;
int musicVolume = sound_get_or_set_music_volume(1);
sound_get_or_set_music_volume(0);
music_start(2);
loop_movie = 1;
play_movie("gendata\\loopdend.smk", 1);
loop_movie = 0;
music_stop();
sound_get_or_set_music_volume(musicVolume);
gbMusicOn = bMusicOn;
}
// 4A22D4: using guessed type char gbMusicOn;
// 659AFC: using guessed type int loop_movie;
// 679660: using guessed type char gbMaxPlayers;
void __cdecl PrepDoEnding()
{
int *v0; // eax
int v1; // ecx
int *v2; // eax
bool v3; // cf
bool v4; // zf
gbSoundOn = sgbSaveSoundOn;
gbRunGame = 0;
deathflag = 0;
v0 = &plr[myplr].pDiabloKillLevel;
v1 = gnDifficulty + 1;
cineflag = 1;
if ( *v0 > (unsigned int)(gnDifficulty + 1) )
v1 = *v0;
*v0 = v1;
v2 = &plr[0]._pHitPoints;
do
{
v3 = (unsigned char)gbMaxPlayers < 1u;
v4 = gbMaxPlayers == 1;
*(v2 - 102) = 11;
*((_BYTE *)v2 - 91) = 1;
if ( !v3 && !v4 )
{
if ( !(*v2 & 0xFFFFFFC0) )
*v2 = 64;
if ( !(v2[5] & 0xFFFFFFC0) )
v2[5] = 64;
}
v2 += 5430;
}
while ( (signed int)v2 < (signed int)&plr[4]._pHitPoints );
}
// 4A22D5: using guessed type char gbSoundOn;
// 525650: using guessed type int gbRunGame;
// 525718: using guessed type char cineflag;
// 64D32C: using guessed type int sgbSaveSoundOn;
// 679660: using guessed type char gbMaxPlayers;
int __fastcall M_DoDeath(int i)
{
int v1; // edi
int v2; // esi
CMonster *v3; // ecx
int v4; // eax
int v5; // ecx
signed int v6; // ecx
int v7; // esi
int v8; // esi
signed int v9; // ecx
char v10; // al
int v11; // eax
v1 = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("M_DoDeath: Invalid monster %d", i);
v2 = v1;
if ( !monster[v1].MType )
TermMsg("M_DoDeath: Monster %d \"%s\" MType NULL", v1, monster[v2].mName);
v3 = monster[v2].MType;
v4 = ++monster[v2]._mVar1;
if ( v3->mtype == MT_DIABLO )
{
v5 = monster[v2]._mx - ViewX;
if ( v5 >= 0 )
v6 = v5 > 0;
else
v6 = -1;
v7 = monster[v2]._my;
ViewX += v6;
v8 = v7 - ViewY;
if ( v8 >= 0 )
{
v9 = v8 < 0;
_LOBYTE(v9) = v8 > 0;
}
else
{
v9 = -1;
}
ViewY += v9;
if ( v4 == 140 )
PrepDoEnding();
}
else if ( monster[v2]._mAnimFrame == monster[v2]._mAnimLen )
{
if ( monster[v2]._uniqtype )
v10 = monster[v2]._udeadval;
else
v10 = v3->mdeadval;
AddDead(monster[v2]._mx, monster[v2]._my, v10, (direction)monster[v2]._mdir);
v11 = monster[v2]._my + 112 * monster[v2]._mx;
monster[v2]._mDelFlag = 1;
dMonster[0][v11] = 0;
M_UpdateLeader(v1);
}
return 0;
}
int __fastcall M_DoSpStand(int i)
{
int v1; // ebx
int v2; // esi
v1 = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("M_DoSpStand: Invalid monster %d", i);
v2 = v1;
if ( !monster[v1].MType )
TermMsg("M_DoSpStand: Monster %d \"%s\" MType NULL", v1, monster[v2].mName);
if ( monster[v2]._mAnimFrame == monster[v2].MData->mAFNum2 )
PlayEffect(v1, 3);
if ( monster[v2]._mAnimFrame != monster[v2]._mAnimLen )
return 0;
M_StartStand(v1, monster[v2]._mdir);
return 1;
}
int __fastcall M_DoDelay(int i)
{
int v1; // ebp
int v2; // esi
int v3; // eax
bool v4; // zf
int v5; // ecx
int v6; // ecx
int v7; // ebx
v1 = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("M_DoDelay: Invalid monster %d", i);
v2 = v1;
if ( !monster[v1].MType )
TermMsg("M_DoDelay: Monster %d \"%s\" MType NULL", v1, monster[v2].mName);
v3 = M_GetDir(v1);
v4 = monster[v2]._mAi == AI_LAZURUS;
monster[v2]._mAnimData = monster[v2].MType->Anims[0].Frames[v3];
if ( v4 )
{
v5 = monster[v2]._mVar2;
if ( v5 > 8 || v5 < 0 )
monster[v2]._mVar2 = 8;
}
v6 = monster[v2]._mVar2;
monster[v2]._mVar2 = v6 - 1;
if ( v6 )
return 0;
v7 = monster[v2]._mAnimFrame;
M_StartStand(v1, monster[v2]._mdir);
monster[v2]._mAnimFrame = v7;
return 1;
}
int __fastcall M_DoStone(int i)
{
int v1; // esi
int v2; // eax
int v3; // ecx
v1 = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("M_DoStone: Invalid monster %d", i);
v2 = v1;
if ( !monster[v1]._mhitpoints )
{
v3 = monster[v2]._mx;
monster[v2]._mDelFlag = 1;
dMonster[0][monster[v2]._my + 112 * v3] = 0;
}
return 0;
}
void __fastcall M_WalkDir(int i, int md)
{
int v2; // esi
int v3; // edi
int v4; // eax
int v5; // eax
int v6; // edx
int v7; // ecx
int v8; // eax
int v9; // edx
int v10; // eax
int v11; // [esp-14h] [ebp-1Ch]
int v12; // [esp-Ch] [ebp-14h]
int v13; // [esp-Ch] [ebp-14h]
int v14; // [esp-8h] [ebp-10h]
int v15; // [esp-8h] [ebp-10h]
int v16; // [esp-4h] [ebp-Ch]
int v17; // [esp-4h] [ebp-Ch]
v2 = i;
v3 = md;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("M_WalkDir: Invalid monster %d", i);
v4 = monster[v2].MType->Anims[1].Rate - 1;
switch ( v3 )
{
case DIR_S:
M_StartWalk2(v2, 0, MWVel[v4][1], 0, -32, 1, 1, 0);
return;
case DIR_SW:
v17 = 1;
v8 = v4;
v15 = 1;
v13 = 0;
v11 = 32;
v9 = -MWVel[v8][1];
goto LABEL_10;
case DIR_W:
M_StartWalk3(v2, -MWVel[v4][2], 0, 32, -16, -1, 1, 0, 1, 2);
return;
case DIR_NW:
v16 = 3;
v10 = v4;
v14 = 0;
v12 = -1;
v7 = -MWVel[v10][0];
v6 = -MWVel[v10][1];
goto LABEL_15;
case DIR_N:
M_StartWalk(v2, 0, -MWVel[v4][1], -1, -1, 4);
break;
case DIR_NE:
v16 = 5;
v5 = v4;
v14 = -1;
v12 = 0;
v6 = MWVel[v5][1];
v7 = -MWVel[v5][0];
LABEL_15:
M_StartWalk(v2, v6, v7, v12, v14, v16);
break;
case DIR_E:
M_StartWalk3(v2, MWVel[v4][2], 0, -32, -16, 1, -1, 1, 0, 6);
break;
case DIR_SE:
v17 = 7;
v8 = v4;
v15 = 0;
v13 = 1;
v9 = MWVel[v8][1];
v11 = -32;
LABEL_10:
M_StartWalk2(v2, v9, MWVel[v8][0], v11, -16, v13, v15, v17);
break;
default:
return;
}
}
void __fastcall GroupUnity(int i)
{
int v1; // ebx
int v2; // esi
int v3; // ebp
int v4; // edi
bool v5; // eax
int v6; // eax
int v7; // ecx
unsigned char v8; // al
int v9; // ebp
int j; // edi
int v11; // eax
int v12; // ecx
//int v13; // [esp+10h] [ebp-4h]
v1 = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("GroupUnity: Invalid monster %d", i);
v2 = v1;
if ( monster[v1].leaderflag )
{
v3 = (unsigned char)monster[v2].leader;
v4 = v3;
v5 = LineClearF(
CheckNoSolid,
monster[v2]._mx,
monster[v2]._my,
monster[v4]._mfutx,
monster[v4]._mfuty);
if ( v5 )
{
if ( monster[v2].leaderflag == 2
&& abs(monster[v2]._mx - monster[v4]._mfutx) < 4
&& abs(monster[v2]._my - monster[v4]._mfuty) < 4 )
{
++monster[v4].unpackfilesize;
monster[v2].leaderflag = 1;
}
}
else
{
if ( monster[v2].leaderflag != 1 )
goto LABEL_18;
--monster[v4].unpackfilesize;
monster[v2].leaderflag = 2;
}
}
else
{
v3 = 0; /* v13 */
}
if ( monster[v2].leaderflag == 1 )
{
v6 = v3;
if ( monster[v2]._msquelch > monster[v3]._msquelch )
{
monster[v6]._lastx = monster[v2]._mx;
monster[v6]._lasty = monster[v2]._my;
monster[v6]._msquelch = monster[v2]._msquelch - 1;
}
if ( monster[v6]._mAi == AI_GARG )
{
v7 = monster[v6]._mFlags;
if ( v7 & 4 )
{
monster[v6]._mmode = MM_SATTACK;
monster[v6]._mFlags = v7 & 0xFFFFFFFB;
}
}
return;
}
LABEL_18:
v8 = monster[v2]._uniqtype;
if ( v8 )
{
if ( UniqMonst[v8 - 1].mUnqAttr & 2 )
{
v9 = nummonsters;
for ( j = 0; j < v9; ++j )
{
v11 = monstactive[j];
if ( monster[v11].leaderflag == 1 && (unsigned char)monster[v11].leader == v1 )
{
if ( monster[v2]._msquelch > monster[v11]._msquelch )
{
monster[v11]._lastx = monster[v2]._mx;
monster[v11]._lasty = monster[v2]._my;
monster[v11]._msquelch = monster[v2]._msquelch - 1;
}
if ( monster[v11]._mAi == AI_GARG )
{
v12 = monster[v11]._mFlags;
if ( v12 & 4 )
{
monster[v11]._mmode = MM_SATTACK;
monster[v11]._mFlags = v12 & 0xFFFFFFFB;
}
}
}
}
}
}
}
bool __fastcall M_CallWalk(int i, int md)
{
int v2; // esi
int v3; // edi
int v4; // ebp
//int v5; // eax
bool v7; // ebx
int v9; // ebx
//int v10; // eax
int v11; // ebx
//int v12; // eax
//int v13; // eax
signed int v14; // ebx
//int v15; // eax
//int v16; // eax
//int v17; // eax
unsigned char v18; // bl
v2 = md;
v3 = i;
v4 = md;
//_LOBYTE(v5) = DirOK(i, md);
v7 = DirOK(i, md);
if ( random(101, 2) )
{
if ( v7 )
goto LABEL_10;
v9 = v2;
v2 = left[v2];
//_LOBYTE(v10) = DirOK(v3, v2);
if ( DirOK(v3, v2) )
goto LABEL_10;
v2 = right[v9];
}
else
{
if ( v7 )
goto LABEL_10;
v11 = v2;
v2 = right[v2];
//_LOBYTE(v12) = DirOK(v3, v2);
if ( DirOK(v3, v2) )
goto LABEL_10;
v2 = left[v11];
}
//_LOBYTE(v13) = DirOK(v3, v2);
if ( !DirOK(v3, v2) )
{
v14 = 0;
goto LABEL_11;
}
LABEL_10:
v14 = 1;
LABEL_11:
if ( random(102, 2) )
{
if ( v14 )
goto LABEL_20;
v2 = right[right[v4]];
//_LOBYTE(v15) = DirOK(v3, v2);
if ( DirOK(v3, v2) )
goto LABEL_20;
v2 = left[left[v4]];
}
else
{
if ( v14 )
goto LABEL_20;
v2 = left[left[v4]];
//_LOBYTE(v16) = DirOK(v3, v2);
if ( DirOK(v3, v2) )
goto LABEL_20;
v2 = right[right[v4]];
}
//_LOBYTE(v17) = DirOK(v3, v2);
if ( DirOK(v3, v2) )
{
LABEL_20:
v18 = 1;
M_WalkDir(v3, v2);
return v18;
}
return 0;
}
bool __fastcall M_PathWalk(int i)
{
int v1; // esi
BOOL(__fastcall *Check)(int, int, int); // ecx
char path[25]; // [esp+4h] [ebp-1Ch]
v1 = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("M_PathWalk: Invalid monster %d", i);
Check = PosOkMonst3;
if ( !(monster[v1]._mFlags & 0x200) )
Check = PosOkMonst;
if ( !FindPath(
Check,
v1,
monster[v1]._mx,
monster[v1]._my,
(unsigned char)monster[v1]._menemyx,
(unsigned char)monster[v1]._menemyy,
path) )
return 0;
M_CallWalk(v1, (char)plr2monst[path[0]]); /* plr2monst is local */
return 1;
}
bool __fastcall M_CallWalk2(int i, int md)
{
int v2; // esi
int v3; // ebx
//int v4; // eax
bool v6; // edi
int v7; // edi
//int v8; // eax
int v9; // edi
//int v10; // eax
//int v11; // eax
bool v12; // di
v2 = md;
v3 = i;
//_LOBYTE(v4) = DirOK(i, md);
v6 = DirOK(i, md);
if ( random(101, 2) )
{
if ( v6 )
goto LABEL_10;
v7 = v2;
v2 = left[v2];
//_LOBYTE(v8) = DirOK(v3, v2);
if ( DirOK(v3, v2) )
goto LABEL_10;
v2 = right[v7];
}
else
{
if ( v6 )
goto LABEL_10;
v9 = v2;
v2 = right[v2];
//_LOBYTE(v10) = DirOK(v3, v2);
if ( DirOK(v3, v2) )
goto LABEL_10;
v2 = left[v9];
}
//_LOBYTE(v11) = DirOK(v3, v2);
if ( DirOK(v3, v2) )
{
LABEL_10:
v12 = 1;
M_WalkDir(v3, v2);
return v12;
}
return 0;
}
bool __fastcall M_DumbWalk(int i, int md)
{
int v2; // esi
int v3; // edi
//int v4; // eax
bool v5; // bl
v2 = md;
v3 = i;
//_LOBYTE(v4) = DirOK(i, md);
v5 = DirOK(i, md);
if ( v5 )
M_WalkDir(v3, v2);
return v5;
}
bool __fastcall M_RoundWalk(int i, int md, int *dir)
{
int *v3; // ebp
int v4; // ebx
int v5; // esi
//int v6; // eax
bool v7; // di
int v8; // edi
//int v9; // eax
//int v10; // eax
int *v11; // ebp
//int v12; // eax
//int v13; // eax
v3 = dir;
v4 = i;
if ( *dir )
v5 = left[left[md]];
else
v5 = right[right[md]];
//_LOBYTE(v6) = DirOK(i, v5);
v7 = DirOK(i, v5);
if ( v7 )
goto LABEL_12;
v8 = v5;
if ( !*dir )
{
v11 = &left[v8];
v5 = left[v8];
//_LOBYTE(v12) = DirOK(v4, left[v8]);
if ( DirOK(v4, left[v8]) )
goto LABEL_11;
v5 = left[*v11];
//_LOBYTE(v13) = DirOK(v4, left[*v11]);
if ( DirOK(v4, left[*v11]) )
goto LABEL_11;
v3 = dir;
LABEL_14:
*v3 = *v3 == 0;
return M_CallWalk(v4, opposite[v8]);
}
v5 = right[v8];
//_LOBYTE(v9) = DirOK(v4, right[v8]);
if ( !DirOK(v4, right[v8]) )
{
v5 = right[right[v8]];
//_LOBYTE(v10) = DirOK(v4, v5);
if ( !DirOK(v4, v5) )
goto LABEL_14;
}
LABEL_11:
v7 = 1;
LABEL_12:
M_WalkDir(v4, v5);
return v7;
}
void __fastcall MAI_Zombie(int i)
{
int v1; // esi
//int v2; // ST04_4
MonsterStruct *v3; // esi
int v4; // edi
int v5; // ebx
int v6; // edi
int v7; // eax
int v8; // ecx
int v9; // eax
int v10; // eax
int v11; // eax
int v12; // ecx
int md; // [esp+Ch] [ebp-Ch]
int v14; // [esp+10h] [ebp-8h]
int arglist; // [esp+14h] [ebp-4h]
v1 = i;
arglist = i;
if ( (unsigned int)i >= MAXMONSTERS )
{
TermMsg("MAI_Zombie: Invalid monster %d", i);
//i = v2;
}
v3 = &monster[v1];
if ( v3->_mmode == MM_STAND )
{
v4 = v3->_my;
if ( dFlags[v3->_mx][v4] & 2 )
{
v5 = v3->_mx - (unsigned char)v3->_menemyx;
v6 = v4 - (unsigned char)v3->_menemyy;
md = v3->_mdir;
v14 = random(103, 100);
if ( abs(v5) >= 2 || abs(v6) >= 2 )
{
if ( v14 < 2 * (unsigned char)v3->_mint + 10 )
{
v7 = abs(v5);
v8 = 2 * (unsigned char)v3->_mint + 4;
if ( v7 >= v8 || (v9 = abs(v6), v8 = 2 * (unsigned char)v3->_mint + 4, v9 >= v8) )
{
v11 = random(104, 100);
v12 = 2 * (unsigned char)v3->_mint + 20;
if ( v11 < v12 )
{
md = random(104, 8);
}
M_DumbWalk(arglist, md);
}
else
{
v10 = M_GetDir(arglist);
M_CallWalk(arglist, v10);
}
}
}
else if ( v14 < 2 * (unsigned char)v3->_mint + 10 )
{
M_StartAttack(arglist);
}
if ( v3->_mmode == MM_STAND )
v3->_mAnimData = v3->MType->Anims[0].Frames[v3->_mdir];
}
}
}
void __fastcall MAI_SkelSd(int i)
{
int v1; // esi
MonsterStruct *v2; // esi
int v3; // ecx
int v4; // edx
int v5; // edi
int v6; // ebp
int v7; // ebx
int v8; // eax
//int v9; // ST04_4
int v11; // eax
//int v12; // ST04_4
int v13; // eax
int v14; // ecx
int v15; // edx
int v16; // eax
int v17; // ecx
int arglist; // [esp+8h] [ebp-4h]
v1 = i;
arglist = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("MAI_SkelSd: Invalid monster %d", i);
v2 = &monster[v1];
if ( v2->_mmode == MM_STAND && v2->_msquelch )
{
v3 = v2->_mx;
v4 = v2->_my;
v5 = v3 - (unsigned char)v2->_menemyx;
v6 = v4 - (unsigned char)v2->_menemyy;
v7 = GetDirection(v3, v4, v2->_lastx, v2->_lasty);
v2->_mdir = v7;
v8 = abs(v5);
//v10 = v9;
if ( v8 >= 2 || (v11 = abs(v6), v11 >= 2) ) /* v10 = v12, */
{
if ( v2->_mVar1 != 13 )
{
v16 = random(106, 100);
v17 = 4 * (unsigned char)v2->_mint;
if ( v16 < 35 - v17 )
{
v15 = 15 - 2 * (unsigned char)v2->_mint + random(106, 10);
goto LABEL_10;
}
}
M_CallWalk(arglist, v7);
}
else
{
if ( v2->_mVar1 != 13 )
{
v13 = random(105, 100);
v14 = 2 * (unsigned char)v2->_mint + 20;
if ( v13 >= v14 )
{
v15 = random(105, 10) + 2 * (5 - (unsigned char)v2->_mint);
LABEL_10:
M_StartDelay(arglist, v15);
goto LABEL_16;
}
}
M_StartAttack(arglist);
}
LABEL_16:
if ( v2->_mmode == MM_STAND )
v2->_mAnimData = v2->MType->Anims[0].Frames[v7];
}
}
bool __fastcall MAI_Path(int i)
{
int v1; // edi
MonsterStruct *v2; // esi
char v3; // al
bool v4; // eax
unsigned char v5; // al
v1 = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("MAI_Path: Invalid monster %d", i);
v2 = &monster[v1];
if ( v2->MType->mtype != MT_GOLEM )
{
if ( !v2->_msquelch )
return 0;
if ( v2->_mmode )
return 0;
v3 = v2->_mgoal;
if ( v3 != 1 && v3 != 4 && v3 != 5 )
return 0;
if ( v2->_mx == 1 && !v2->_my )
return 0;
}
v4 = LineClearF1(
PosOkMonst2,
v1,
v2->_mx,
v2->_my,
(unsigned char)v2->_menemyx,
(unsigned char)v2->_menemyy);
if ( !v4 || (v5 = v2->_pathcount, v5 >= 5u) && v5 < 8u )
{
if ( v2->_mFlags & 0x200 )
MonstCheckDoors(v1);
if ( ++_LOBYTE(v2->_pathcount) < 5u )
return 0;
if ( M_PathWalk(v1) )
return 1;
}
if ( v2->MType->mtype != MT_GOLEM )
_LOBYTE(v2->_pathcount) = 0;
return 0;
}
void __fastcall MAI_Snake(int i)
{
int esi1; // esi
MonsterStruct *esi3; // esi
bool v3; // zf
int v4; // ecx
int v5; // eax
int v6; // ST1C_4
int v7; // edi
int v8; // edx
int v9; // ST18_4
int v10; // ebx
int v11; // eax
//int v12; // ST1C_4
int v14; // eax
int v15; // eax
int v16; // ecx
int v17; // edx
int v18; // ecx
int v19; // eax
//int v20; // ST1C_4
int v22; // eax
//int v23; // ST1C_4
int v24; // ebx
int v26; // ecx
int v27; // eax
int v28; // ecx
int v29; // ecx
int v30; // eax
int v31; // edx
int v32; // eax
int v33; // ecx
int v34; // ecx
int v35; // eax
char pattern[6]; // [esp+4h] [ebp-1Ch]
int micaster; // [esp+Ch] [ebp-14h]
int midir; // [esp+10h] [ebp-10h]
int v1; // [esp+14h] [ebp-Ch]
int v2; // [esp+18h] [ebp-8h]
int arglist; // [esp+1Ch] [ebp-4h]
esi1 = i;
arglist = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("MAI_Snake: Invalid monster %d", i);
pattern[2] = 0;
pattern[3] = -1;
pattern[4] = -1;
pattern[5] = 0;
esi3 = &monster[esi1];
pattern[0] = 1;
pattern[1] = 1;
v3 = esi3->_mmode == MM_STAND;
micaster = esi3->_menemy;
if ( v3 && esi3->_msquelch )
{
v4 = esi3->_mx;
v5 = (unsigned char)esi3->_menemyy;
v6 = esi3->_lasty;
v1 = (unsigned char)esi3->_menemyx;
v7 = v4 - v1;
v8 = esi3->_my;
v9 = esi3->_lastx;
v2 = v5;
v10 = v8 - v5;
midir = GetDirection(v4, v8, v9, v6);
esi3->_mdir = midir;
if ( abs(v7) < 2 )
{
v11 = abs(v10);
//v13 = v12;
if ( v11 < 2 )
{
v14 = esi3->_mVar1;
if ( v14 == 13
|| v14 == 14
|| (v15 = random(105, 100), v16 = (unsigned char)esi3->_mint + 20, v15 < v16) )
{
M_StartAttack(arglist);
LABEL_49:
if ( esi3->_mmode == MM_STAND )
esi3->_mAnimData = esi3->MType->Anims[0].Frames[esi3->_mdir];
return;
}
v17 = 10 - (unsigned char)esi3->_mint + random(105, 10);
v18 = arglist;
LABEL_11:
M_StartDelay(v18, v17);
goto LABEL_49;
}
}
v19 = abs(v7);
//v21 = v20;
if ( v19 >= 3 || (v22 = abs(v10), v22 >= 3) ) /* v21 = v23, */
{
v24 = arglist;
}
else
{
v24 = arglist;
if ( LineClearF1(PosOkMonst, arglist, esi3->_mx, esi3->_my, v1, v2) && esi3->_mVar1 != 14 )
{
if ( AddMissile(esi3->_mx, esi3->_my, v1, v2, midir, 20, micaster, arglist, 0, 0) != -1 )
{
PlayEffect(arglist, 0);
v26 = esi3->_my + 112 * esi3->_mx;
esi3->_mmode = MM_CHARGE;
dMonster[0][v26] = -1 - v24;
}
goto LABEL_49;
}
}
if ( esi3->_mVar1 != 13 )
{
v27 = random(106, 100);
v28 = 2 * (unsigned char)esi3->_mint;
if ( v27 < 35 - v28 )
{
v17 = 15 - (unsigned char)esi3->_mint + random(106, 10);
v18 = v24;
goto LABEL_11;
}
}
v29 = esi3->_mgoalvar1;
v30 = midir + pattern[v29];
if ( v30 >= 0 )
{
v31 = v30 - 8;
if ( v30 < 8 )
v31 = midir + pattern[v29];
}
else
{
v31 = v30 + 8;
}
esi3->_mgoalvar1 = v29 + 1;
if ( v29 + 1 > 5 )
esi3->_mgoalvar1 = 0;
v32 = esi3->_mgoalvar2;
v33 = v31 - v32;
if ( v31 - v32 >= 0 )
{
if ( v33 >= 8 )
v33 -= 8;
}
else
{
v33 += 8;
}
if ( v33 <= 0 )
{
LABEL_47:
if ( !M_DumbWalk(v24, esi3->_mgoalvar2) )
M_CallWalk2(v24, esi3->_mdir);
goto LABEL_49;
}
if ( v33 >= 4 )
{
if ( v33 == 4 )
{
esi3->_mgoalvar2 = v31;
goto LABEL_47;
}
v34 = v32 - 1;
if ( v32 - 1 < 0 )
{
v35 = v32 + 7;
goto LABEL_46;
}
if ( v34 >= 8 )
{
v35 = v32 - 9;
goto LABEL_46;
}
}
else
{
v34 = v32 + 1;
if ( v32 + 1 < 0 )
{
v35 = v32 + 9;
LABEL_46:
esi3->_mgoalvar2 = v35;
goto LABEL_47;
}
if ( v34 >= 8 )
{
v35 = v32 - 7;
goto LABEL_46;
}
}
v35 = v34;
goto LABEL_46;
}
}
void __fastcall MAI_Bat(int i)
{
int esi1; // esi
MonsterStruct *esi3; // esi
int v3; // ecx
int v4; // edx
int v5; // edi
int v6; // ebx
int v7; // eax
int v10; // edx
bool v11; // eax
int v12; // ecx
CMonster *v14; // eax
int v15; // edi
int v16; // eax
signed int v17; // ecx
int v18; // eax
int micaster; // [esp+Ch] [ebp-18h]
int v1; // [esp+10h] [ebp-14h]
int v2; // [esp+14h] [ebp-10h]
int v22; // [esp+18h] [ebp-Ch]
int midir; // [esp+1Ch] [ebp-8h]
int arglist; // [esp+20h] [ebp-4h]
esi1 = i;
arglist = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("MAI_Bat: Invalid monster %d", i);
esi3 = &monster[esi1];
micaster = esi3->_menemy;
if ( esi3->_mmode == MM_STAND && esi3->_msquelch )
{
v3 = esi3->_mx;
v4 = esi3->_my;
v5 = v3 - (unsigned char)esi3->_menemyx;
v6 = v4 - (unsigned char)esi3->_menemyy;
v7 = GetDirection(v3, v4, esi3->_lastx, esi3->_lasty);
midir = v7;
esi3->_mdir = v7;
v22 = random(107, 100);
if ( _LOBYTE(esi3->_mgoal) == 2 )
{
if ( esi3->_mgoalvar1 )
{
if ( random(108, 2) )
v10 = left[midir];
else
v10 = right[midir];
M_CallWalk(arglist, v10);
_LOBYTE(esi3->_mgoal) = 1;
}
else
{
M_CallWalk(arglist, opposite[midir]);
++esi3->_mgoalvar1;
}
}
else
{
v1 = (unsigned char)esi3->_menemyx;
v2 = (unsigned char)esi3->_menemyy;
if ( esi3->MType->mtype == MT_GLOOM
&& (abs(v5) >= 5 || abs(v6) >= 5)
&& v22 < 4 * (unsigned char)esi3->_mint + 33
&& (v11 = LineClearF1(
PosOkMonst,
arglist,
esi3->_mx,
esi3->_my,
v1,
v2),
v11) )
{
if ( AddMissile(esi3->_mx, esi3->_my, v1, v2, midir, 20, micaster, arglist, 0, 0) != -1 )
{
v12 = esi3->_my + 112 * esi3->_mx;
esi3->_mmode = MM_CHARGE;
dMonster[0][v12] = -1 - arglist;
}
}
else if ( abs(v5) >= 2 || abs(v6) >= 2 )
{
v17 = esi3->_mVar2;
if ( v17 > 20 && v22 < (unsigned char)esi3->_mint + 13
|| ((v18 = esi3->_mVar1, v18 == 1) || v18 == 2 || v18 == 3)
&& !v17
&& v22 < (unsigned char)esi3->_mint + 63 )
{
M_CallWalk(arglist, midir);
}
}
else if ( v22 < 4 * (unsigned char)esi3->_mint + 8 )
{
M_StartAttack(arglist);
v14 = esi3->MType;
esi3->_mgoalvar1 = 0;
_LOBYTE(esi3->_mgoal) = 2;
if ( v14->mtype == 41 )
{
v15 = (unsigned char)esi3->_menemyx;
v16 = random(109, 10);
AddMissile(v15, (unsigned char)esi3->_menemyy, v15 + 1, 0, -1, 8, 1, arglist, v16 + 1, 0);
}
}
if ( esi3->_mmode == MM_STAND )
esi3->_mAnimData = esi3->MType->Anims[0].Frames[midir];
}
}
}
void __fastcall MAI_SkelBow(int i)
{
int v1; // esi
MonsterStruct *v2; // esi
int v3; // edi
int v4; // ebx
int v5; // eax
int v7; // eax
//int v8; // ST04_4
int v9; // ecx
int v10; // eax
//int v11; // ST04_4
int v12; // eax
//int v13; // eax
int v14; // edi
int v15; // ebx
//int v16; // eax
int v17; // [esp+4h] [ebp-10h]
bool v18; // [esp+8h] [ebp-Ch]
int v19; // [esp+Ch] [ebp-8h]
int arglist; // [esp+10h] [ebp-4h]
v18 = 0;
v1 = i;
arglist = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("MAI_SkelBow: Invalid monster %d", i);
v2 = &monster[v1];
if ( v2->_mmode == MM_STAND && v2->_msquelch )
{
v3 = v2->_mx - (unsigned char)v2->_menemyx;
v4 = v2->_my - (unsigned char)v2->_menemyy;
v5 = M_GetDir(arglist);
v17 = v5;
v2->_mdir = v5;
v19 = random(110, 100);
v7 = abs(v3);
//v9 = v8;
if ( v7 < 4 )
{
v10 = abs(v4);
//v9 = v11;
if ( v10 < 4 )
{
if ( (v9 = v2->_mVar2, v9 > 20) && v19 < 2 * (unsigned char)v2->_mint + 13
|| ((v12 = v2->_mVar1, v12 == 1) || v12 == 2 || v12 == 3)
&& !v9
&& v19 < 2 * (unsigned char)v2->_mint + 63 )
{
//_LOBYTE(v13) = M_DumbWalk(arglist, opposite[v17]);
v18 = M_DumbWalk(arglist, opposite[v17]);
}
}
}
v14 = (unsigned char)v2->_menemyx;
v15 = (unsigned char)v2->_menemyy;
if ( !v18 )
{
if ( random(110, 100) < 2 * (unsigned char)v2->_mint + 3 )
{
//_LOBYTE(v16) = LineClear(v2->_mx, v2->_my, v14, v15);
if ( LineClear(v2->_mx, v2->_my, v14, v15) )
M_StartRAttack(arglist, 0, 4);
}
}
if ( v2->_mmode == MM_STAND )
v2->_mAnimData = v2->MType->Anims[0].Frames[v17];
}
}
void __fastcall MAI_Fat(int i)
{
int v1; // esi
MonsterStruct *v2; // esi
int v3; // edi
int v4; // ebx
int v5; // eax
int v7; // eax
signed int v8; // ecx
int v9; // eax
int md; // [esp+4h] [ebp-Ch]
int arglist; // [esp+8h] [ebp-8h]
int v12; // [esp+Ch] [ebp-4h]
v1 = i;
arglist = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("MAI_Fat: Invalid monster %d", i);
v2 = &monster[v1];
if ( v2->_mmode == MM_STAND && v2->_msquelch )
{
v3 = v2->_mx - (unsigned char)v2->_menemyx;
v4 = v2->_my - (unsigned char)v2->_menemyy;
v5 = M_GetDir(arglist);
md = v5;
v2->_mdir = v5;
v12 = random(111, 100);
if ( abs(v3) >= 2 || abs(v4) >= 2 )
{
v8 = v2->_mVar2;
if ( v8 > 20 && v12 < 4 * (unsigned char)v2->_mint + 20
|| ((v9 = v2->_mVar1, v9 == 1) || v9 == 2 || v9 == 3) && !v8 && v12 < 4 * (unsigned char)v2->_mint + 70 )
{
M_CallWalk(arglist, md);
}
}
else
{
v7 = (unsigned char)v2->_mint;
if ( v12 >= 4 * v7 + 15 )
{
if ( v12 < 4 * v7 + 20 )
M_StartSpAttack(arglist);
}
else
{
M_StartAttack(arglist);
}
}
if ( v2->_mmode == MM_STAND )
v2->_mAnimData = v2->MType->Anims[0].Frames[md];
}
}
void __fastcall MAI_Sneak(int i)
{
int v1; // edi
MonsterStruct *v2; // esi
int v3; // ebx
int v4; // ebx
int v6; // edi
int v7; // eax
//int v8; // ST04_4
int v9; // eax
//int v10; // ST04_4
int v11; // eax
int v12; // edi
signed int v13; // ecx
int v14; // eax
int v15; // [esp+Ch] [ebp-10h]
int arglist; // [esp+10h] [ebp-Ch]
int v17; // [esp+14h] [ebp-8h]
int md; // [esp+18h] [ebp-4h]
v1 = i;
arglist = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("MAI_Sneak: Invalid monster %d", i);
v2 = &monster[v1];
if ( v2->_mmode == MM_STAND )
{
v3 = v2->_my;
if ( dTransVal[v2->_mx][v3] != lightmax )
{
v17 = v2->_mx - (unsigned char)v2->_menemyx;
v4 = v3 - (unsigned char)v2->_menemyy;
md = M_GetDir(v1);
v6 = 5 - (unsigned char)v2->_mint;
if ( v2->_mVar1 == 5 )
{
v2->_mgoalvar1 = 0;
_LOBYTE(v2->_mgoal) = 2;
}
else
{
v7 = abs(v17);
//v5 = v8;
if ( v7 >= v6 + 3 || (v9 = abs(v4), v9 >= v6 + 3) || v2->_mgoalvar1 > 8 ) /* v5 = v10, */
{
v2->_mgoalvar1 = 0;
_LOBYTE(v2->_mgoal) = 1;
}
}
if ( _LOBYTE(v2->_mgoal) == 2 )
{
if ( v2->_mFlags & 0x10 )
md = GetDirection(v2->_mx, v2->_my, plr[v2->_menemy]._pownerx, plr[v2->_menemy]._pownery);
md = opposite[md];
if ( v2->MType->mtype == MT_UNSEEN )
{
if ( random(112, 2) )
v11 = left[md];
else
v11 = right[md];
md = v11;
}
}
v2->_mdir = md;
v15 = random(112, 100);
if ( abs(v17) < v6 && abs(v4) < v6 && v2->_mFlags & 1 )
{
M_StartFadein(arglist, md, 0);
}
else
{
v12 = v6 + 1;
if ( abs(v17) < v12 && abs(v4) < v12 || v2->_mFlags & 1 )
{
if ( _LOBYTE(v2->_mgoal) == 2
|| (abs(v17) >= 2 || abs(v4) >= 2)
&& ((v13 = v2->_mVar2, v13 > 20) && v15 < 4 * (unsigned char)v2->_mint + 14
|| ((v14 = v2->_mVar1, v14 == 1) || v14 == 2 || v14 == 3)
&& !v13
&& v15 < 4 * (unsigned char)v2->_mint + 64) )
{
++v2->_mgoalvar1;
M_CallWalk(arglist, md);
}
}
else
{
M_StartFadeout(arglist, md, 1u);
}
}
if ( v2->_mmode == MM_STAND )
{
if ( abs(v17) >= 2 || abs(v4) >= 2 || v15 >= 4 * (unsigned char)v2->_mint + 10 )
v2->_mAnimData = v2->MType->Anims[0].Frames[md];
else
M_StartAttack(arglist);
}
}
}
}
// 642A14: using guessed type char lightmax;
void __fastcall MAI_Fireman(int i)
{
int esi1; // esi
int esi3; // esi
int v3; // ecx
int v4; // eax
int v5; // ebx
int v6; // edi
int v7; // edx
char v9; // al
//int v10; // eax
//int v11; // eax
int v13; // eax
//int v14; // eax
int v15; // edx
//int v16; // eax
int v17; // eax
int micaster; // [esp+Ch] [ebp-14h]
int v1; // [esp+10h] [ebp-10h]
int v2; // [esp+14h] [ebp-Ch]
int midir; // [esp+18h] [ebp-8h]
int arglist; // [esp+1Ch] [ebp-4h]
esi1 = i;
arglist = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("MAI_Fireman: Invalid monster %d", i);
esi3 = esi1;
if ( monster[esi3]._mmode || !monster[esi3]._msquelch )
return;
v3 = (unsigned char)monster[esi3]._menemyy;
micaster = monster[esi3]._menemy;
v4 = (unsigned char)monster[esi3]._menemyx;
v2 = v3;
v5 = monster[esi3]._my - v3;
v1 = v4;
v6 = monster[esi3]._mx - v4;
v7 = M_GetDir(arglist);
v9 = monster[esi3]._mgoal;
midir = v7;
switch ( v9 )
{
case 1:
//_LOBYTE(v10) = LineClear(monster[esi3]._mx, monster[esi3]._my, v1, v2);
if ( !LineClear(monster[esi3]._mx, monster[esi3]._my, v1, v2)
|| AddMissile(monster[esi3]._mx, monster[esi3]._my, v1, v2, midir, 50, micaster, arglist, 0, 0) == -1 )
{
break;
}
monster[esi3]._mgoalvar1 = 0;
monster[esi3]._mmode = MM_CHARGE;
goto LABEL_18;
case 5:
if ( monster[esi3]._mgoalvar1 == 3 )
{
_LOBYTE(monster[esi3]._mgoal) = 1;
M_StartFadeout(arglist, v7, 1u);
}
else
{
//_LOBYTE(v11) = LineClear(monster[esi3]._mx, monster[esi3]._my, v1, v2);
if ( LineClear(monster[esi3]._mx, monster[esi3]._my, v1, v2) )
{
M_StartRAttack(arglist, 51, 4);
}
else
{
//_LOBYTE(v11) = LineClear(monster[esi3]._mx, monster[esi3]._my, v1, v2);
if ( LineClear(monster[esi3]._mx, monster[esi3]._my, v1, v2) )
{
M_StartRAttack(arglist, 51, 4);
}
else
{
v13 = random(112, 10);
M_StartDelay(arglist, v13 + 5);
}
++monster[esi3]._mgoalvar1;
}
++monster[esi3]._mgoalvar1;
}
break;
case 2:
M_StartFadein(arglist, v7, 0);
LABEL_18:
_LOBYTE(monster[esi3]._mgoal) = 5;
break;
}
monster[esi3]._mdir = midir;
random(112, 100);
if ( monster[esi3]._mmode == MM_STAND )
return;
if ( abs(v6) < 2 && abs(v5) < 2 && _LOBYTE(monster[esi3]._mgoal) == 1 )
{
M_TryH2HHit(
arglist,
monster[esi3]._menemy,
(unsigned char)monster[esi3].mHit,
(unsigned char)monster[esi3].mMinDamage,
(unsigned char)monster[esi3].mMaxDamage);
_LOBYTE(monster[esi3]._mgoal) = 2;
//_LOBYTE(v14) = M_CallWalk(arglist, opposite[midir]);
if ( M_CallWalk(arglist, opposite[midir]) )
return;
v15 = midir;
goto LABEL_29;
}
//_LOBYTE(v16) = M_CallWalk(arglist, midir);
if ( !M_CallWalk(arglist, midir) )
{
v17 = _LOBYTE(monster[esi3]._mgoal);
if ( (_BYTE)v17 == 1 || (_BYTE)v17 == 2 )
{
v15 = midir;
LABEL_29:
M_StartFadein(arglist, v15, 0);
_LOBYTE(monster[esi3]._mgoal) = 5;
return;
}
}
}
void __fastcall MAI_Fallen(int i)
{
int v1; // edi
//int v2; // ST04_4
int v3; // esi
int v4; // eax
int v5; // ecx
int *v6; // eax
int v7; // edx
int v8; // edx
int j; // edi
int k; // ecx
int v11; // eax
int v12; // eax
char v13; // al
int v14; // edx
int v15; // eax
int v16; // esi
v1 = i;
if ( (unsigned int)i >= MAXMONSTERS )
{
TermMsg("MAI_Fallen: Invalid monster %d", i);
//i = v2;
}
v3 = v1;
if ( _LOBYTE(monster[v1]._mgoal) == 5 )
{
i = monster[v3]._mgoalvar1;
if ( i )
monster[v3]._mgoalvar1 = --i;
else
_LOBYTE(monster[v3]._mgoal) = 1;
}
if ( monster[v3]._mmode == MM_STAND && monster[v3]._msquelch )
{
if ( _LOBYTE(monster[v3]._mgoal) == 2 )
{
i = monster[v3]._mgoalvar1;
monster[v3]._mgoalvar1 = i - 1;
if ( !i )
{
v4 = monster[v3]._mdir;
_LOBYTE(monster[v3]._mgoal) = 1;
M_StartStand(v1, opposite[v4]);
}
}
if ( monster[v3]._mAnimFrame != monster[v3]._mAnimLen )
{
v13 = monster[v3]._mgoal;
if ( v13 == 2 )
{
v14 = monster[v3]._mdir;
}
else
{
if ( v13 != 5 )
{
MAI_SkelSd(v1);
return;
}
v15 = monster[v3]._mx - (unsigned char)monster[v3]._menemyx;
v16 = monster[v3]._my - (unsigned char)monster[v3]._menemyy;
if ( abs(v15) < 2 && abs(v16) < 2 )
{
M_StartAttack(v1);
return;
}
v14 = M_GetDir(v1);
}
M_CallWalk(v1, v14);
return;
}
if ( !random(113, 4) )
{
if ( !(monster[v3]._mFlags & 8) )
{
M_StartSpStand(v1, monster[v3]._mdir);
v5 = 2 * (unsigned char)monster[v3]._mint + 2;
v6 = &monster[v3]._mhitpoints;
v7 = monster[v3]._mhitpoints;
if ( monster[v3]._mmaxhp - v5 < v7 )
*v6 = monster[v3]._mmaxhp;
else
*v6 = v5 + v7;
}
v8 = 2 * (unsigned char)monster[v3]._mint + 4;
for ( j = -v8; j <= v8; ++j )
{
for ( k = -v8; k <= v8; ++k )
{
if ( j >= 0 && j < 112 && k >= 0 && k < 112 )
{
v11 = dMonster[0][j + monster[v3]._my + 112 * (k + monster[v3]._mx)];
if ( v11 > 0 )
{
v12 = v11 - 1;
if ( monster[v12]._mAi == AI_FALLEN )
{
_LOBYTE(monster[v12]._mgoal) = 5;
monster[v12]._mgoalvar1 = 30 * (unsigned char)monster[v3]._mint + 105;
}
}
}
}
}
}
}
}
void __fastcall MAI_Cleaver(int i)
{
int v1; // esi
MonsterStruct *v2; // esi
int v3; // ecx
int v4; // edx
int v5; // edi
int v6; // ebp
int v7; // ebx
int arglist; // [esp+8h] [ebp-4h]
v1 = i;
arglist = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("MAI_Cleaver: Invalid monster %d", i);
v2 = &monster[v1];
if ( v2->_mmode == MM_STAND && v2->_msquelch )
{
v3 = v2->_mx;
v4 = v2->_my;
v5 = v3 - (unsigned char)v2->_menemyx;
v6 = v4 - (unsigned char)v2->_menemyy;
v7 = GetDirection(v3, v4, v2->_lastx, v2->_lasty);
v2->_mdir = v7;
if ( abs(v5) >= 2 || abs(v6) >= 2 )
M_CallWalk(arglist, v7);
else
M_StartAttack(arglist);
if ( v2->_mmode == MM_STAND )
v2->_mAnimData = v2->MType->Anims[0].Frames[v7];
}
}
void __fastcall MAI_Round(int i, unsigned char special)
{
int v2; // esi
MonsterStruct *v3; // esi
int v4; // edx
int v5; // ecx
int v6; // edi
int v7; // ebx
int v9; // eax
//int v10; // ST04_4
int v12; // eax
//int v13; // ST04_4
int v15; // edi
int v16; // eax
int v17; // ecx
bool v18; // eax
//int v19; // eax
int v21; // eax
int v22; // eax
//int v23; // ST04_4
signed int v25; // ecx
int v26; // eax
int v27; // [esp+4h] [ebp-18h]
int v28; // [esp+8h] [ebp-14h]
char *v29; // [esp+8h] [ebp-14h]
int v30; // [esp+Ch] [ebp-10h]
int md; // [esp+10h] [ebp-Ch]
int v32; // [esp+14h] [ebp-8h]
int arglist; // [esp+18h] [ebp-4h]
v2 = i;
v27 = special;
arglist = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("MAI_Round: Invalid monster %d", i);
v3 = &monster[v2];
if ( v3->_mmode == MM_STAND && v3->_msquelch )
{
v4 = v3->_my;
v5 = v3->_mx;
v28 = (unsigned char)v3->_menemyy;
v6 = (unsigned char)v3->_menemyx;
v7 = v5 - v6;
v32 = v4 - v28;
md = GetDirection(v5, v4, v3->_lastx, v3->_lasty);
if ( v3->_msquelch < 0xFFu ) /* check sign */
MonstCheckDoors(arglist);
v30 = random(114, 100);
if ( (abs(v7) >= 2 || abs(v32) >= 2) && v3->_msquelch == -1 )
{
v29 = &dung_map[v6][v28];
if ( dung_map[v3->_mx][v3->_my] == *v29 )
{
if ( _LOBYTE(v3->_mgoal) != 4 )
{
v9 = abs(v7);
//v11 = v10;
if ( v9 < 4 )
{
v12 = abs(v32);
//v11 = v13;
if ( v12 < 4 )
goto LABEL_26;
}
if ( random(115, 4) )
goto LABEL_26;
if ( _LOBYTE(v3->_mgoal) != 4 )
{
v3->_mgoalvar1 = 0;
v3->_mgoalvar2 = random(116, 2);
}
}
_LOBYTE(v3->_mgoal) = 4;
v15 = abs(v32);
if ( abs(v7) <= v15 )
v16 = abs(v32);
else
v16 = abs(v7);
v17 = v3->_mgoalvar1;
v3->_mgoalvar1 = v17 + 1;
if ( v17 < 2 * v16 || (v18 = DirOK(arglist, md), !v18) )
{
if ( dung_map[v3->_mx][v3->_my] == *v29 )
{
//_LOBYTE(v19) = M_RoundWalk(arglist, md, &v3->_mgoalvar2);
if ( !M_RoundWalk(arglist, md, &v3->_mgoalvar2) )
{
v21 = random(125, 10);
M_StartDelay(arglist, v21 + 10);
}
goto LABEL_26;
}
}
}
}
_LOBYTE(v3->_mgoal) = 1;
LABEL_26:
if ( _LOBYTE(v3->_mgoal) == 1 )
{
if ( abs(v7) >= 2 || (v22 = abs(v32), v22 >= 2) ) /* v24 = v23, */
{
v25 = v3->_mVar2;
if ( v25 > 20 && v30 < 2 * (unsigned char)v3->_mint + 28
|| ((v26 = v3->_mVar1, v26 == 1) || v26 == 2 || v26 == 3)
&& !v25
&& v30 < 2 * (unsigned char)v3->_mint + 78 )
{
M_CallWalk(arglist, md);
}
}
else if ( v30 < 2 * (unsigned char)v3->_mint + 23 )
{
v3->_mdir = md;
if ( v27 && v3->_mhitpoints < v3->_mmaxhp >> 1 && random(117, 2) )
M_StartSpAttack(arglist);
else
M_StartAttack(arglist);
}
}
if ( v3->_mmode == MM_STAND )
v3->_mAnimData = v3->MType->Anims[0].Frames[md];
}
}
void __fastcall MAI_GoatMc(int i)
{
MAI_Round(i, 1u);
}
void __fastcall MAI_Ranged(int i, int missile_type, unsigned char special)
{
int v3; // edi
int v4; // esi
char v5; // al
int v6; // eax
int v7; // ecx
int v8; // ebx
int v9; // edi
bool v11; // zf
int v12; // eax
int v13; // eax
//int v14; // ST00_4
//int v16; // eax
int x2; // [esp+8h] [ebp-14h]
int y2; // [esp+Ch] [ebp-10h]
int missile_typea; // [esp+10h] [ebp-Ch]
int v20; // [esp+14h] [ebp-8h]
int arglist; // [esp+18h] [ebp-4h]
v3 = i;
missile_typea = missile_type;
arglist = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("MAI_Ranged: Invalid monster %d", i);
v4 = v3;
if ( monster[v3]._mmode == MM_STAND )
{
v5 = monster[v4]._msquelch;
if ( v5 == -1 || monster[v4]._mFlags & 0x10 )
{
v7 = (unsigned char)monster[v4]._menemyy;
y2 = v7;
v8 = monster[v4]._my - v7;
x2 = (unsigned char)monster[v4]._menemyx;
v9 = monster[v4]._mx - x2;
v20 = M_GetDir(arglist);
if ( monster[v4]._msquelch < 0xFFu ) /* check sign */
MonstCheckDoors(arglist);
v11 = monster[v4]._mVar1 == 10;
monster[v4]._mdir = v20;
if ( v11 )
{
v12 = random(118, 20);
M_StartDelay(arglist, v12);
}
else if ( abs(v9) < 4 )
{
v13 = abs(v8);
//v15 = v14;
if ( v13 < 4 )
{
if ( random(119, 100) < 10 * ((unsigned char)monster[v4]._mint + 7) )
M_CallWalk(arglist, opposite[v20]);
}
}
if ( monster[v4]._mmode == MM_STAND )
{
//_LOBYTE(v16) = LineClear(monster[v4]._mx, monster[v4]._my, x2, y2);
if ( LineClear(monster[v4]._mx, monster[v4]._my, x2, y2) )
{
if ( special )
M_StartRSpAttack(arglist, missile_typea, 4);
else
M_StartRAttack(arglist, missile_typea, 4);
}
else
{
monster[v4]._mAnimData = monster[v4].MType->Anims[0].Frames[v20];
}
}
}
else if ( v5 )
{
v6 = GetDirection(monster[v4]._mx, monster[v4]._my, monster[v4]._lastx, monster[v4]._lasty);
M_CallWalk(v3, v6);
}
}
}
void __fastcall MAI_GoatBow(int i)
{
MAI_Ranged(i, 0, 0);
}
void __fastcall MAI_Succ(int i)
{
MAI_Ranged(i, 24, 0);
}
void __fastcall MAI_AcidUniq(int i)
{
MAI_Ranged(i, 57, 1u);
}
void __fastcall MAI_Scav(int i)
{
int v1; // edi
int v2; // esi
unsigned char *v3; // eax
int v4; // ecx
int v5; // ecx
signed int v6; // ebx
signed int v7; // edi
int v8; // edx
int v9; // eax
bool v10; // eax
int v11; // ebx
int v12; // edi
signed int v13; // edi
int v14; // edx
int v15; // eax
bool v16; // eax
int v17; // eax
int v18; // eax
int arglist; // [esp+Ch] [ebp-8h]
BOOL v20; // [esp+10h] [ebp-4h]
v1 = i;
arglist = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("MAI_Scav: Invalid monster %d", i);
v2 = v1;
v20 = 0;
if ( monster[v1]._mmode == MM_STAND )
{
if ( monster[v2]._mhitpoints < monster[v2]._mmaxhp >> 1 )
{
if ( _LOBYTE(monster[v2]._mgoal) == 3 )
goto LABEL_10;
if ( monster[v2].leaderflag )
{
v3 = &monster[(unsigned char)monster[v2].leader].unpackfilesize;
--*v3;
monster[v2].leaderflag = 0;
}
_LOBYTE(monster[v2]._mgoal) = 3;
monster[v2]._mgoalvar3 = 10;
}
if ( _LOBYTE(monster[v2]._mgoal) != 3 )
{
LABEL_52:
if ( monster[v2]._mmode == MM_STAND )
MAI_SkelSd(arglist);
return;
}
LABEL_10:
v4 = monster[v2]._mgoalvar3;
if ( v4 )
{
monster[v2]._mgoalvar3 = v4 - 1;
v5 = monster[v2]._my;
if ( dDead[monster[v2]._mx][v5] )
{
M_StartEat(v1);
if ( !(monster[v2]._mFlags & 8) )
monster[v2]._mhitpoints += 64;
if ( monster[v2]._mhitpoints >= (monster[v2]._mmaxhp >> 1) + (monster[v2]._mmaxhp >> 2) )
{
_LOBYTE(monster[v2]._mgoal) = 1;
monster[v2]._mgoalvar1 = 0;
monster[v2]._mgoalvar2 = 0;
}
}
else
{
if ( !monster[v2]._mgoalvar1 )
{
v6 = arglist;
if ( random(120, 2) )
{
v7 = -4;
do
{
if ( v20 )
break;
v6 = -4;
do
{
if ( v20 )
break;
if ( v7 >= 0 && v7 < 112 && v6 >= 0 && v6 < 112 )
{
v8 = monster[v2]._mx;
v9 = monster[v2]._my;
v20 = dDead[v8 + v6][v9 + v7]
&& (v10 = LineClearF(
CheckNoSolid,
v8,
v9,
v8 + v6,
v9 + v7),
v10);
}
++v6;
}
while ( v6 <= 4 );
++v7;
}
while ( v7 <= 4 );
v11 = v6 - 1;
v12 = v7 - 1;
}
else
{
v13 = 4;
do
{
if ( v20 )
break;
v6 = 4;
do
{
if ( v20 )
break;
if ( v13 >= 0 && v13 < 112 && v6 >= 0 && v6 < 112 )
{
v14 = monster[v2]._mx;
v15 = monster[v2]._my;
v20 = dDead[v14 + v6][v15 + v13]
&& (v16 = LineClearF(
CheckNoSolid,
v14,
v15,
v14 + v6,
v15 + v13),
v16);
}
--v6;
}
while ( v6 >= -4 );
--v13;
}
while ( v13 >= -4 );
v11 = v6 + 1;
v12 = v13 + 1;
}
if ( v20 )
{
monster[v2]._mgoalvar1 = monster[v2]._mx + v11 + 1;
monster[v2]._mgoalvar2 = monster[v2]._my + v12 + 1;
}
}
v17 = monster[v2]._mgoalvar1;
if ( v17 )
{
v18 = GetDirection(monster[v2]._mx, monster[v2]._my, v17 - 1, monster[v2]._mgoalvar2 - 1);
monster[v2]._mdir = v18;
M_CallWalk(arglist, v18);
}
}
}
goto LABEL_52;
}
}
void __fastcall MAI_Garg(int i)
{
int v1; // ebp
MonsterStruct *v2; // esi
int v3; // edi
int v4; // ebx
char v5; // al
int v6; // edi
//int v7; // eax
int v8; // [esp+10h] [ebp-4h]
v1 = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("MAI_Garg: Invalid monster %d", i);
v2 = &monster[v1];
v3 = v2->_mx - v2->_lastx;
v4 = v2->_my - v2->_lasty;
v8 = M_GetDir(v1);
v5 = v2->_msquelch;
if ( v5 && v2->_mFlags & 4 )
{
M_Enemy(v1);
v6 = v2->_my - (unsigned char)v2->_menemyy;
if ( abs(v2->_mx - (unsigned char)v2->_menemyx) < (unsigned char)v2->_mint + 2
&& abs(v6) < (unsigned char)v2->_mint + 2 )
{
v2->_mFlags &= 0xFFFFFFFB;
}
}
else if ( v2->_mmode == MM_STAND && v5 )
{
if ( v2->_mhitpoints < v2->_mmaxhp >> 1 && !(v2->_mFlags & 8) )
_LOBYTE(v2->_mgoal) = 2;
if ( _LOBYTE(v2->_mgoal) == 2 )
{
if ( abs(v3) >= (unsigned char)v2->_mint + 2 || abs(v4) >= (unsigned char)v2->_mint + 2 )
{
_LOBYTE(v2->_mgoal) = 1;
M_StartHeal(v1);
}
else
{
//_LOBYTE(v7) = M_CallWalk(v1, opposite[v8]);
if ( !M_CallWalk(v1, opposite[v8]) )
_LOBYTE(v2->_mgoal) = 1;
}
}
MAI_Round(v1, 0);
}
}
void __fastcall MAI_RoundRanged(int i, int missile_type, unsigned char checkdoors, int dam, int lessmissiles)
{
int v5; // esi
MonsterStruct *v6; // esi
int v7; // edx
int v8; // ebx
int v9; // edi
int v11; // eax
//int v12; // ST04_4
int v13; // ecx
int v14; // eax
//int v15; // ST04_4
int v16; // eax
//int v17; // ST04_4
int v18; // ecx
int v19; // ebx
int v20; // eax
int v21; // ecx
bool v22; // eax
bool v23; // eax
bool v24; // eax
int v25; // eax
//int v26; // ST04_4
int v27; // eax
//int v28; // ST04_4
int v29; // eax
int v30; // edx
int v31; // eax
int missile_typea; // [esp+4h] [ebp-18h]
int v33; // [esp+8h] [ebp-14h]
int x2; // [esp+Ch] [ebp-10h]
int md; // [esp+10h] [ebp-Ch]
int y2; // [esp+14h] [ebp-8h]
int arglist; // [esp+18h] [ebp-4h]
int checkdoorsa; // [esp+24h] [ebp+8h]
v5 = i;
missile_typea = missile_type;
arglist = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("MAI_RoundRanged: Invalid monster %d", i);
v6 = &monster[v5];
if ( v6->_mmode == MM_STAND && v6->_msquelch )
{
v7 = v6->_my;
y2 = (unsigned char)v6->_menemyy;
v8 = v7 - y2;
x2 = (unsigned char)v6->_menemyx;
v9 = v6->_mx - x2;
v33 = v7 - y2;
md = GetDirection(v6->_mx, v7, v6->_lastx, v6->_lasty);
if ( checkdoors && v6->_msquelch < 0xFFu ) /* check sign */
MonstCheckDoors(arglist);
checkdoorsa = random(121, 10000);
v11 = abs(v9);
//v13 = v12;
if ( v11 < 2 )
{
v14 = abs(v8);
//v13 = v15;
if ( v14 < 2 )
goto LABEL_50;
}
if ( v6->_msquelch != -1 )
goto LABEL_50;
//v13 = y2;
if ( dung_map[v6->_mx][v6->_my] != dung_map[x2][y2] )
goto LABEL_50;
if ( _LOBYTE(v6->_mgoal) != 4 )
{
if ( abs(v9) < 3 )
{
v16 = abs(v8);
//v13 = v17;
if ( v16 < 3 )
goto LABEL_28;
}
v18 = lessmissiles;
if ( random(122, 4 << lessmissiles) )
goto LABEL_28;
if ( _LOBYTE(v6->_mgoal) != 4 )
{
v6->_mgoalvar1 = 0;
v6->_mgoalvar2 = random(123, 2);
}
}
_LOBYTE(v6->_mgoal) = 4;
v19 = abs(v8);
if ( abs(v9) <= v19 )
{
v8 = v33;
v20 = abs(v33);
}
else
{
v20 = abs(v9);
v8 = v33;
}
v21 = v6->_mgoalvar1;
v6->_mgoalvar1 = v21 + 1;
if ( v21 >= 2 * v20 && (v22 = DirOK(arglist, md), v22) )
{
LABEL_50:
_LOBYTE(v6->_mgoal) = 1;
}
else if ( checkdoorsa < 500 * ((unsigned char)v6->_mint + 1) >> lessmissiles
&& (v23 = LineClear(v6->_mx, v6->_my, x2, y2), v23) )
{
M_StartRSpAttack(arglist, missile_typea, dam);
}
else
{
M_RoundWalk(arglist, md, &v6->_mgoalvar2);
}
LABEL_28:
if ( _LOBYTE(v6->_mgoal) == 1 )
{
if ( ((abs(v9) >= 3 || abs(v8) >= 3) && checkdoorsa < 500 * ((unsigned char)v6->_mint + 2) >> lessmissiles
|| checkdoorsa < 500 * ((unsigned char)v6->_mint + 1) >> lessmissiles)
&& (v24 = LineClear(v6->_mx, v6->_my, x2, y2), v24) )
{
M_StartRSpAttack(arglist, missile_typea, dam);
}
else
{
v25 = abs(v9);
//v13 = v26;
if ( v25 >= 2 || (v27 = abs(v8), v27 >= 2) ) /* v13 = v28, */
{
v29 = random(124, 100);
v30 = (unsigned char)v6->_mint;
if ( v29 < 1000 * (v30 + 5)
|| ((v13 = v6->_mVar1, v13 == 1) || v13 == 2 || v13 == 3) && !v6->_mVar2 && v29 < 1000 * (v30 + 8) )
{
M_CallWalk(arglist, md);
}
}
else if ( checkdoorsa < 1000 * ((unsigned char)v6->_mint + 6) )
{
v6->_mdir = md;
M_StartAttack(arglist);
}
}
}
if ( v6->_mmode == MM_STAND )
{
v31 = random(125, 10);
M_StartDelay(arglist, v31 + 5);
}
}
}
void __fastcall MAI_Magma(int i)
{
MAI_RoundRanged(i, 21, 1u, 4, 0);
}
void __fastcall MAI_Storm(int i)
{
MAI_RoundRanged(i, 22, 1u, 4, 0);
}
void __fastcall MAI_Acid(int i)
{
MAI_RoundRanged(i, 57, 0, 4, 1);
}
void __fastcall MAI_Diablo(int i)
{
MAI_RoundRanged(i, 67, 0, 40, 0);
}
void __fastcall MAI_RR2(int i, int mistype, int dam)
{
int v3; // ebx
MonsterStruct *v4; // esi
int v5; // edi
int v6; // edx
int v7; // ebx
int v8; // edi
int v10; // eax
//int v11; // ST04_4
int v12; // ecx
int v13; // eax
//int v14; // ST04_4
int v15; // eax
//int v16; // ST04_4
int v17; // eax
//int v18; // ST04_4
int v19; // ebx
int v20; // eax
bool v21; // eax
bool v22; // eax
int v23; // ecx
int v24; // eax
//int v25; // ST04_4
int v27; // eax
//int v28; // ST04_4
int v29; // eax
int v30; // eax
int v31; // eax
int v32; // edx
int v33; // eax
int missile_type; // [esp+Ch] [ebp-1Ch]
int x2; // [esp+10h] [ebp-18h]
int v36; // [esp+14h] [ebp-14h]
int y2; // [esp+18h] [ebp-10h]
int v38; // [esp+1Ch] [ebp-Ch]
int md; // [esp+20h] [ebp-8h]
int arglist; // [esp+24h] [ebp-4h]
v3 = i;
missile_type = mistype;
arglist = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("MAI_RR2: Invalid monster %d", i);
v4 = &monster[v3];
v5 = v4->_my - (unsigned char)v4->_menemyy;
if ( abs(v4->_mx - (unsigned char)v4->_menemyx) >= 5 || abs(v5) >= 5 )
{
MAI_SkelSd(v3);
return;
}
if ( v4->_mmode == MM_STAND && v4->_msquelch )
{
v6 = v4->_my;
y2 = (unsigned char)v4->_menemyy;
v7 = v6 - y2;
x2 = (unsigned char)v4->_menemyx;
v8 = v4->_mx - x2;
v36 = v6 - y2;
md = GetDirection(v4->_mx, v6, v4->_lastx, v4->_lasty);
if ( v4->_msquelch < 0xFFu ) /* check sign */
MonstCheckDoors(arglist);
v38 = random(121, 100);
v10 = abs(v8);
//v12 = v11;
if ( v10 >= 2 || (v13 = abs(v7), v13 >= 2) ) /* v12 = v14, */
{
if ( v4->_msquelch == -1 )
{
//v12 = y2;
if ( dung_map[v4->_mx][v4->_my] == dung_map[x2][y2] )
{
if ( _LOBYTE(v4->_mgoal) != 4 )
{
v15 = abs(v8);
//v12 = v16;
if ( v15 < 3 )
{
v17 = abs(v7);
//v12 = v18;
if ( v17 < 3 )
goto LABEL_26;
}
if ( _LOBYTE(v4->_mgoal) != 4 )
{
v4->_mgoalvar1 = 0;
v4->_mgoalvar2 = random(123, 2);
}
}
_LOBYTE(v4->_mgoal) = 4;
v4->_mgoalvar3 = 4;
v19 = abs(v7);
if ( abs(v8) <= v19 )
{
v7 = v36;
v20 = abs(v36);
}
else
{
v20 = abs(v8);
v7 = v36;
}
v12 = v4->_mgoalvar1;
v4->_mgoalvar1 = v12 + 1;
if ( v12 < 2 * v20 || (v21 = DirOK(arglist, md), !v21) )
{
if ( v38 < 5 * ((unsigned char)v4->_mint + 16) )
M_RoundWalk(arglist, md, &v4->_mgoalvar2);
LABEL_26:
if ( _LOBYTE(v4->_mgoal) != 1 )
goto LABEL_48;
if ( ((abs(v8) >= 3 || abs(v7) >= 3) && v38 < 5 * ((unsigned char)v4->_mint + 2)
|| v38 < 5 * ((unsigned char)v4->_mint + 1)
|| v4->_mgoalvar3 == 4)
&& (v22 = LineClear(v4->_mx, v4->_my, x2, y2), v22) )
{
v23 = arglist;
}
else
{
v24 = abs(v8);
//v26 = v25;
if ( v24 >= 2 || (v27 = abs(v7), v27 >= 2) ) /* v26 = v28, */
{
v31 = random(124, 100);
v12 = (unsigned char)v4->_mint;
if ( v31 < 2 * (5 * v12 + 25)
|| ((v32 = v4->_mVar1, v32 == 1) || v32 == 2 || v32 == 3)
&& !v4->_mVar2
&& (v12 = 2 * (5 * v12 + 40), v31 < v12) )
{
M_CallWalk(arglist, md);
}
goto LABEL_47;
}
v29 = random(124, 100);
v12 = 10 * ((unsigned char)v4->_mint + 4);
if ( v29 >= v12 )
{
LABEL_47:
v4->_mgoalvar3 = 1;
LABEL_48:
if ( v4->_mmode == MM_STAND )
{
v33 = random(125, 10);
M_StartDelay(arglist, v33 + 5);
}
return;
}
v4->_mdir = md;
v30 = random(124, 2);
v23 = arglist;
if ( v30 )
{
M_StartAttack(arglist);
goto LABEL_47;
}
}
M_StartRSpAttack(v23, missile_type, dam);
goto LABEL_47;
}
}
}
}
_LOBYTE(v4->_mgoal) = 1;
goto LABEL_26;
}
}
void __fastcall MAI_Mega(int i)
{
MAI_RR2(i, 49, 0);
}
void __fastcall MAI_Golum(int i)
{
int v1; // edi
int v2; // esi
int v3; // eax
int v4; // eax
int v5; // edx
int v6; // edi
int v7; // ebx
int v8; // eax
char v9; // cl
//char v10; // eax
signed int v11; // edx
signed int v12; // ecx
int v13; // eax
bool v14; // eax
unsigned char *v15; // esi
bool v16; // eax
int v17; // esi
int v18; // edi
int v19; // [esp+Ch] [ebp-Ch]
unsigned int v20; // [esp+10h] [ebp-8h]
int arglist; // [esp+14h] [ebp-4h]
v1 = i;
arglist = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("MAI_Golum: Invalid monster %d", i);
v2 = v1;
if ( monster[v1]._mx != 1 || monster[v2]._my )
{
v3 = monster[v2]._mmode;
if ( v3 != MM_DEATH && v3 != MM_SPSTAND && (v3 < MM_WALK || v3 > MM_WALK3) )
{
if ( !(monster[v2]._mFlags & 0x10) )
M_Enemy(v1);
v20 = ((unsigned int)~monster[v2]._mFlags >> 10) & 1;
if ( monster[v2]._mmode != MM_ATTACK )
{
v4 = monster[v2]._menemy;
v5 = monster[v2]._my;
v6 = monster[v2]._mx - monster[v4]._mfutx;
v7 = v5 - monster[v4]._mfuty;
v19 = GetDirection(monster[v2]._mx, v5, monster[v4]._mx, monster[v4]._my);
monster[v2]._mdir = v19;
if ( abs(v6) >= 2 || abs(v7) >= 2 )
{
if ( v20 )
{
v14 = MAI_Path(arglist);
if ( v14 )
return;
}
}
else if ( v20 )
{
v8 = monster[v2]._menemy;
monster[v2]._menemyx = monster[v8]._mx;
v9 = monster[v8]._my;
monster[v2]._menemyy = v9;
if ( !monster[v8]._msquelch )
{
monster[v8]._msquelch = -1;
monster[monster[v2]._menemy]._lastx = monster[v2]._mx;
v11 = 0;
monster[monster[v2]._menemy]._lasty = monster[v2]._my;
do
{
v12 = 0;
do
{
/* v13 = *(_DWORD *)&nTransTable[4
* (monster[v2]._my + v11 + 112 * (v12 + monster[v2]._mx))
+ 1148]; check */
v13 = dMonster[monster[v2]._mx + v12 - 2][monster[v2]._my + v11 - 2];
if ( v13 > 0 )
monster[v13]._msquelch = -1;
++v12;
}
while ( v12 < 5 );
++v11;
}
while ( v11 < 5 );
}
M_StartAttack(arglist);
return;
}
v15 = &monster[v2]._pathcount;
if ( ++*(_BYTE *)v15 > 8u )
*(_BYTE *)v15 = 5;
v16 = M_CallWalk(arglist, plr[arglist]._pdir);
if ( !v16 )
{
v17 = ((_BYTE)v19 - 1) & 7;
v18 = 0;
while ( !v16 )
{
v17 = ((_BYTE)v17 + 1) & 7;
v16 = DirOK(arglist, v17);
if ( ++v18 >= 8 )
{
if ( !v16 )
return;
break;
}
}
M_WalkDir(arglist, v17);
}
}
}
}
}
void __fastcall MAI_SkelKing(int i)
{
int v1; // esi
MonsterStruct *v2; // esi
int v3; // edx
int v4; // ebx
int v5; // edi
int v7; // eax
//int v8; // ST04_4
int v10; // eax
//int v11; // ST04_4
int v13; // ebx
int v14; // eax
int v15; // ecx
bool v16; // eax
//int v17; // eax
int v19; // eax
bool v20; // eax
int v21; // edi
int v22; // ebx
int v23; // eax
//int v24; // ST04_4
int v26; // eax
//int v27; // ST04_4
int v28; // eax
int v29; // ecx
int v30; // edx
int v31; // eax
char *v32; // [esp+4h] [ebp-1Ch]
int x2; // [esp+8h] [ebp-18h]
int v34; // [esp+Ch] [ebp-14h]
int v35; // [esp+10h] [ebp-10h]
int y2; // [esp+14h] [ebp-Ch]
int md; // [esp+18h] [ebp-8h]
int arglist; // [esp+1Ch] [ebp-4h]
v1 = i;
arglist = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("MAI_SkelKing: Invalid monster %d", i);
v2 = &monster[v1];
if ( v2->_mmode == MM_STAND && v2->_msquelch )
{
v3 = v2->_my;
y2 = (unsigned char)v2->_menemyy;
v4 = v3 - y2;
x2 = (unsigned char)v2->_menemyx;
v5 = v2->_mx - x2;
v34 = v3 - y2;
md = GetDirection(v2->_mx, v3, v2->_lastx, v2->_lasty);
if ( v2->_msquelch < 0xFFu ) /* check sign */
MonstCheckDoors(arglist);
v35 = random(126, 100);
if ( (abs(v5) >= 2 || abs(v4) >= 2) && v2->_msquelch == -1 )
{
v32 = &dung_map[x2][y2];
if ( dung_map[v2->_mx][v2->_my] == *v32 )
{
if ( _LOBYTE(v2->_mgoal) != 4 )
{
v7 = abs(v5);
//v9 = v8;
if ( v7 < 3 )
{
v10 = abs(v4);
//v9 = v11;
if ( v10 < 3 )
goto LABEL_26;
}
if ( random(127, 4) )
goto LABEL_26;
if ( _LOBYTE(v2->_mgoal) != 4 )
{
v2->_mgoalvar1 = 0;
v2->_mgoalvar2 = random(128, 2);
}
}
_LOBYTE(v2->_mgoal) = 4;
v13 = abs(v4);
if ( abs(v5) <= v13 )
{
v4 = v34;
v14 = abs(v34);
}
else
{
v14 = abs(v5);
v4 = v34;
}
v15 = v2->_mgoalvar1;
v2->_mgoalvar1 = v15 + 1;
if ( v15 < 2 * v14 || (v16 = DirOK(arglist, md), !v16) )
{
if ( dung_map[v2->_mx][v2->_my] == *v32 )
{
//_LOBYTE(v17) = M_RoundWalk(arglist, md, &v2->_mgoalvar2);
if ( !M_RoundWalk(arglist, md, &v2->_mgoalvar2) )
{
v19 = random(125, 10);
M_StartDelay(arglist, v19 + 10);
}
goto LABEL_26;
}
}
}
}
_LOBYTE(v2->_mgoal) = 1;
LABEL_26:
if ( _LOBYTE(v2->_mgoal) == 1 )
{
if ( gbMaxPlayers == 1
&& ((abs(v5) >= 3 || abs(v4) >= 3) && v35 < 4 * (unsigned char)v2->_mint + 35 || v35 < 6)
&& (v20 = LineClear(v2->_mx, v2->_my, x2, y2), v20) )
{
v21 = v2->_mx + offset_x[md];
v22 = v2->_my + offset_y[md];
if ( PosOkMonst(arglist, v21, v22) && nummonsters < MAXMONSTERS )
{
M_SpawnSkel(v21, v22, md);
M_StartSpStand(arglist, md);
}
}
else
{
v23 = abs(v5);
//v25 = v24;
if ( v23 >= 2 || (v26 = abs(v4), v26 >= 2) ) /* v25 = v27, */
{
v28 = random(129, 100);
v29 = (unsigned char)v2->_mint;
if ( v28 >= v29 + 25
&& ((v30 = v2->_mVar1, v30 != 1) && v30 != 2 && v30 != 3 || v2->_mVar2 || (v29 += 75, v28 >= v29)) )
{
v31 = random(130, 10);
M_StartDelay(arglist, v31 + 10);
}
else
{
M_CallWalk(arglist, md);
}
}
else if ( v35 < (unsigned char)v2->_mint + 20 )
{
v2->_mdir = md;
M_StartAttack(arglist);
}
}
}
if ( v2->_mmode == MM_STAND )
v2->_mAnimData = v2->MType->Anims[0].Frames[md];
}
}
// 679660: using guessed type char gbMaxPlayers;
void __fastcall MAI_Rhino(int i)
{
int esi1; // esi
MonsterStruct *esi3; // esi
int v3; // edx
int v4; // ebx
int v5; // edi
int v7; // eax
//int v8; // ST1C_4
int v10; // eax
//int v11; // ST1C_4
int v13; // ebx
int v14; // eax
int v15; // ecx
//int v16; // eax
int v18; // eax
bool v19; // eax
int v20; // ecx
int v21; // eax
//int v22; // ST1C_4
int v24; // eax
//int v25; // ST1C_4
int v26; // eax
int v27; // ecx
int v28; // edx
int v29; // eax
int v30; // [esp+4h] [ebp-18h]
int v31; // [esp+8h] [ebp-14h]
int v1; // [esp+Ch] [ebp-10h]
int midir; // [esp+10h] [ebp-Ch]
int v2; // [esp+14h] [ebp-8h]
int arglist; // [esp+18h] [ebp-4h]
esi1 = i;
arglist = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("MAI_Rhino: Invalid monster %d", i);
esi3 = &monster[esi1];
if ( esi3->_mmode == MM_STAND && esi3->_msquelch )
{
v3 = esi3->_my;
v2 = (unsigned char)esi3->_menemyy;
v4 = v3 - v2;
v1 = (unsigned char)esi3->_menemyx;
v5 = esi3->_mx - v1;
v31 = v3 - v2;
midir = GetDirection(esi3->_mx, v3, esi3->_lastx, esi3->_lasty);
if ( esi3->_msquelch < 0xFFu ) /* check sign */
MonstCheckDoors(arglist);
v30 = random(131, 100);
if ( abs(v5) >= 2 || abs(v4) >= 2 )
{
if ( _LOBYTE(esi3->_mgoal) != 4 )
{
v7 = abs(v5);
//v9 = v8;
if ( v7 < 5 )
{
v10 = abs(v4);
//v9 = v11;
if ( v10 < 5 )
goto LABEL_23;
}
if ( !random(132, 4) )
goto LABEL_23;
if ( _LOBYTE(esi3->_mgoal) != 4 )
{
esi3->_mgoalvar1 = 0;
esi3->_mgoalvar2 = random(133, 2);
}
}
_LOBYTE(esi3->_mgoal) = 4;
v13 = abs(v4);
if ( abs(v5) <= v13 )
{
v4 = v31;
v14 = abs(v31);
}
else
{
v14 = abs(v5);
v4 = v31;
}
v15 = esi3->_mgoalvar1;
esi3->_mgoalvar1 = v15 + 1;
if ( v15 < 2 * v14 && dung_map[esi3->_mx][esi3->_my] == dung_map[v1][v2] )
{
//_LOBYTE(v16) = M_RoundWalk(arglist, midir, &esi3->_mgoalvar2);
if ( !M_RoundWalk(arglist, midir, &esi3->_mgoalvar2) )
{
v18 = random(125, 10);
M_StartDelay(arglist, v18 + 10);
}
goto LABEL_23;
}
}
_LOBYTE(esi3->_mgoal) = 1;
LABEL_23:
if ( _LOBYTE(esi3->_mgoal) == 1 )
{
if ( (abs(v5) >= 5 || abs(v4) >= 5)
&& v30 < 2 * (unsigned char)esi3->_mint + 43
&& (v19 = LineClearF1(
PosOkMonst,
arglist,
esi3->_mx,
esi3->_my,
v1,
v2),
v19) )
{
if ( AddMissile(esi3->_mx, esi3->_my, v1, v2, midir, 20, esi3->_menemy, arglist, 0, 0) != -1 )
{
if ( esi3->MData->snd_special )
PlayEffect(arglist, 3);
v20 = esi3->_my + 112 * esi3->_mx;
esi3->_mmode = MM_CHARGE;
dMonster[0][v20] = -1 - arglist;
}
}
else
{
v21 = abs(v5);
//v23 = v22;
if ( v21 >= 2 || (v24 = abs(v4), v24 >= 2) ) /* v23 = v25, */
{
v26 = random(134, 100);
v27 = 2 * (unsigned char)esi3->_mint;
if ( v26 >= v27 + 33
&& ((v28 = esi3->_mVar1, v28 != 1) && v28 != 2 && v28 != 3
|| esi3->_mVar2
|| (v27 += 83, v26 >= v27)) )
{
v29 = random(135, 10);
M_StartDelay(arglist, v29 + 10);
}
else
{
M_CallWalk(arglist, midir);
}
}
else if ( v30 < 2 * (unsigned char)esi3->_mint + 28 )
{
esi3->_mdir = midir;
M_StartAttack(arglist);
}
}
}
if ( esi3->_mmode == MM_STAND )
esi3->_mAnimData = esi3->MType->Anims[0].Frames[esi3->_mdir];
}
}
void __fastcall MAI_Counselor(int i)
{
int v1; // ebx
int v2; // esi
int v3; // ecx
int v4; // edi
int v5; // edx
int v6; // ebp
char v9; // al
int v10; // ecx
bool v11; // zf
bool v12; // sf
unsigned char v13; // of
int v14; // edx
int v15; // ecx
int v16; // ebx
int v17; // eax
int v18; // ebx
int v19; // edx
int v20; // ecx
//int v21; // eax
int v22; // eax
//int v23; // ST1C_4
int v25; // eax
//int v26; // ST1C_4
int v27; // edx
int v28; // eax
int v29; // eax
int v30; // ecx
//int v31; // eax
int v32; // eax
int v33; // eax
int v34; // eax
int md; // [esp+8h] [ebp-14h]
int arglist; // [esp+Ch] [ebp-10h]
int y2; // [esp+10h] [ebp-Ch]
int x2; // [esp+14h] [ebp-8h]
int v39; // [esp+18h] [ebp-4h]
v1 = i;
arglist = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("MAI_Counselor: Invalid monster %d", i);
v2 = v1;
if ( monster[v1]._mmode == MM_STAND && monster[v2]._msquelch )
{
v3 = monster[v2]._mx;
x2 = (unsigned char)monster[v2]._menemyx;
v4 = v3 - x2;
v5 = monster[v2]._my;
y2 = (unsigned char)monster[v2]._menemyy;
v6 = v5 - y2;
md = GetDirection(v3, v5, monster[v2]._lastx, monster[v2]._lasty);
if ( monster[v2]._msquelch < 0xFFu ) /* check sign */
MonstCheckDoors(v1);
v39 = random(121, 100);
v9 = monster[v2]._mgoal;
if ( v9 == 2 )
{
v10 = monster[v2]._mgoalvar1;
v13 = __OFSUB__(v10, 3);
v11 = v10 == 3;
v12 = v10 - 3 < 0;
v14 = v10 + 1;
v15 = v1;
monster[v2]._mgoalvar1 = v14;
if ( (unsigned char)(v12 ^ v13) | v11 )
{
M_CallWalk(v1, opposite[md]);
goto LABEL_39;
}
goto LABEL_21;
}
if ( v9 == 4 )
{
v16 = abs(v6);
if ( abs(v4) <= v16 )
v17 = abs(v6);
else
v17 = abs(v4);
v18 = v17;
if ( abs(v4) < 2 && abs(v6) < 2
|| monster[v2]._msquelch != -1
|| dung_map[monster[v2]._mx][monster[v2]._my] != dung_map[x2][y2] )
{
v1 = arglist;
LABEL_20:
v15 = v1;
LABEL_21:
_LOBYTE(monster[v2]._mgoal) = 1;
M_StartFadein(v15, md, 1u);
goto LABEL_39;
}
v19 = 2 * v18;
v1 = arglist;
v20 = monster[v2]._mgoalvar1;
monster[v2]._mgoalvar1 = v20 + 1;
if ( v20 >= v19 )
{
//_LOBYTE(v21) = DirOK(arglist, md);
if ( DirOK(arglist, md) )
goto LABEL_20;
}
M_RoundWalk(arglist, md, &monster[v2]._mgoalvar2);
LABEL_39:
if ( monster[v2]._mmode == MM_STAND )
{
v34 = random(125, 10);
M_StartDelay(v1, v34 + 5);
}
return;
}
if ( v9 != 1 )
goto LABEL_39;
v22 = abs(v4);
//v24 = v23;
if ( v22 >= 2 || (v25 = abs(v6), v25 >= 2) ) /* v24 = v26, */
{
if ( v39 < 5 * ((unsigned char)monster[v2]._mint + 10) )
{
//_LOBYTE(v31) = LineClear(monster[v2]._mx, monster[v2]._my, x2, y2);
if ( LineClear(monster[v2]._mx, monster[v2]._my, x2, y2) )
{
v32 = random(
77,
(unsigned char)monster[v2].mMaxDamage - (unsigned char)monster[v2].mMinDamage + 1);
M_StartRAttack(
v1,
(unsigned char)counsmiss[(unsigned char)monster[v2]._mint], /* counsmiss is local */
(unsigned char)monster[v2].mMinDamage + v32);
goto LABEL_39;
}
}
if ( random(124, 100) < 30 )
{
v27 = md;
_LOBYTE(monster[v2]._mgoal) = 4;
goto LABEL_29;
}
}
else
{
v27 = md;
v28 = monster[v2]._mmaxhp >> 1;
v13 = __OFSUB__(monster[v2]._mhitpoints, v28);
v12 = monster[v2]._mhitpoints - v28 < 0;
monster[v2]._mdir = md;
if ( v12 ^ v13 )
{
_LOBYTE(monster[v2]._mgoal) = 2;
LABEL_29:
monster[v2]._mgoalvar1 = 0;
M_StartFadeout(v1, v27, 0);
goto LABEL_39;
}
if ( monster[v2]._mVar1 == 13
|| (v29 = random(105, 100),
v30 = 2 * (unsigned char)monster[v2]._mint + 20,
v29 < v30) )
{
M_StartRAttack(v1, -1, 0);
AddMissile(monster[v2]._mx, monster[v2]._my, 0, 0, monster[v2]._mdir, 11, 1, v1, 4, 0);
AddMissile(monster[v2]._mx, monster[v2]._my, 0, 0, monster[v2]._mdir, 12, 1, v1, 4, 0);
goto LABEL_39;
}
}
v33 = random(105, 10);
M_StartDelay(v1, v33 + 2 * (5 - (unsigned char)monster[v2]._mint));
goto LABEL_39;
}
}
void __fastcall MAI_Garbud(int i)
{
int v1; // esi
int v2; // esi
int v3; // ebx
int v4; // edi
int v5; // eax
//int v6; // eax
char v7; // al
int v8; // [esp+4h] [ebp-8h]
int arglist; // [esp+8h] [ebp-4h]
v1 = i;
arglist = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("MAI_Garbud: Invalid monster %d", i);
v2 = v1;
if ( monster[v2]._mmode == MM_STAND )
{
v3 = monster[v2]._my;
v4 = monster[v2]._mx;
v8 = M_GetDir(arglist);
v5 = monster[v2].mtalkmsg;
if ( v5 < (signed int)QUEST_GARBUD4
&& v5 >(signed int)QUEST_DOOM10
&& !(dFlags[v4][v3] & 2)
&& _LOBYTE(monster[v2]._mgoal) == 7 )
{
_LOBYTE(monster[v2]._mgoal) = 6;
monster[v2].mtalkmsg = v5 + 1;
}
if ( dFlags[v4][v3] & 2 )
{
if ( monster[v2].mtalkmsg == QUEST_GARBUD4 )
{
//_LOBYTE(v6) = effect_is_playing(USFX_GARBUD4);
if ( !effect_is_playing(USFX_GARBUD4) && _LOBYTE(monster[v2]._mgoal) == 7 )
{
monster[v2]._msquelch = -1;
monster[v2].mtalkmsg = 0;
_LOBYTE(monster[v2]._mgoal) = 1;
}
}
}
v7 = monster[v2]._mgoal;
if ( v7 == 1 || v7 == 4 )
MAI_Round(arglist, 1u);
monster[v2]._mdir = v8;
if ( monster[v2]._mmode == MM_STAND )
monster[v2]._mAnimData = monster[v2].MType->Anims[0].Frames[v8];
}
}
void __fastcall MAI_Zhar(int i)
{
int v1; // ebp
int v2; // esi
int v3; // ebx
int v4; // edi
int v5; // edi
int v6; // ebx
int v7; // ebp
//int v8; // eax
char v9; // al
int arglist; // [esp+8h] [ebp-8h]
int v11; // [esp+Ch] [ebp-4h]
v1 = i;
arglist = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("MAI_Zhar: Invalid monster %d", i);
v2 = v1;
if ( monster[v1]._mmode == MM_STAND )
{
v3 = monster[v2]._my;
v4 = monster[v2]._mx;
v11 = M_GetDir(v1);
if ( monster[v2].mtalkmsg == QUEST_ZHAR1 && !(dFlags[v4][v3] & 2) && _LOBYTE(monster[v2]._mgoal) == 7 )
{
monster[v2].mtalkmsg = QUEST_ZHAR2;
_LOBYTE(monster[v2]._mgoal) = 6;
}
if ( dFlags[v4][v3] & 2 )
{
v5 = monster[v2]._mx - (unsigned char)monster[v2]._menemyx;
v6 = monster[v2]._my - (unsigned char)monster[v2]._menemyy;
v7 = abs(v6);
if ( abs(v5) <= v7 )
abs(v6);
else
abs(v5);
if ( monster[v2].mtalkmsg == QUEST_ZHAR2 )
{
//_LOBYTE(v8) = effect_is_playing(USFX_ZHAR2);
if ( !effect_is_playing(USFX_ZHAR2) && _LOBYTE(monster[v2]._mgoal) == 7 )
{
monster[v2]._msquelch = -1;
monster[v2].mtalkmsg = 0;
_LOBYTE(monster[v2]._mgoal) = 1;
}
}
}
v9 = monster[v2]._mgoal;
if ( v9 == 1 || v9 == 2 || v9 == 4 )
MAI_Counselor(arglist);
monster[v2]._mdir = v11;
if ( monster[v2]._mmode == MM_STAND )
monster[v2]._mAnimData = monster[v2].MType->Anims[0].Frames[v11];
}
}
void __fastcall MAI_SnotSpil(int i)
{
int v1; // ebp
int v2; // esi
int v3; // ebx
int v4; // edi
int v5; // ebp
//int v6; // eax
char v7; // al
int arglist; // [esp+8h] [ebp-4h]
v1 = i;
arglist = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("MAI_SnotSpil: Invalid monster %d", i);
v2 = v1;
if ( monster[v1]._mmode == MM_STAND )
{
v3 = monster[v2]._my;
v4 = monster[v2]._mx;
v5 = M_GetDir(v1);
if ( monster[v2].mtalkmsg == QUEST_BANNER10 && !(dFlags[v4][v3] & 2) && _LOBYTE(monster[v2]._mgoal) == 7 )
{
monster[v2].mtalkmsg = QUEST_BANNER11;
_LOBYTE(monster[v2]._mgoal) = 6;
}
if ( monster[v2].mtalkmsg == QUEST_BANNER11 && quests[7]._qvar1 == 3 )
{
monster[v2].mtalkmsg = 0;
_LOBYTE(monster[v2]._mgoal) = 1;
}
if ( dFlags[v4][v3] & 2 )
{
if ( monster[v2].mtalkmsg == QUEST_BANNER12 )
{
//_LOBYTE(v6) = effect_is_playing(USFX_SNOT3);
if ( !effect_is_playing(USFX_SNOT3) && _LOBYTE(monster[v2]._mgoal) == 7 )
{
ObjChangeMap(setpc_x, setpc_y, setpc_w + setpc_x + 1, setpc_h + setpc_y + 1);
quests[7]._qvar1 = 3;
RedoPlayerVision();
monster[v2]._msquelch = -1;
monster[v2].mtalkmsg = 0;
_LOBYTE(monster[v2]._mgoal) = 1;
}
}
if ( quests[7]._qvar1 == 3 )
{
v7 = monster[v2]._mgoal;
if ( v7 == 1 || v7 == 5 )
MAI_Fallen(arglist);
}
}
monster[v2]._mdir = v5;
if ( monster[v2]._mmode == MM_STAND )
monster[v2]._mAnimData = monster[v2].MType->Anims[0].Frames[v5];
}
}
// 5CF330: using guessed type int setpc_h;
// 5CF334: using guessed type int setpc_w;
void __fastcall MAI_Lazurus(int i)
{
int v1; // ebx
int v2; // esi
int v3; // ebp
int v4; // edi
int v5; // ebx
//int v6; // eax
char v7; // al
int v8; // eax
int arglist; // [esp+8h] [ebp-4h]
v1 = i;
arglist = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("MAI_Lazurus: Invalid monster %d", i);
v2 = v1;
if ( monster[v1]._mmode == MM_STAND )
{
v3 = monster[v2]._my;
v4 = monster[v2]._mx;
v5 = M_GetDir(v1);
if ( dFlags[v4][v3] & 2 )
{
if ( gbMaxPlayers != 1 )
goto LABEL_29;
if ( monster[v2].mtalkmsg == QUEST_VILE13 )
{
if ( _LOBYTE(monster[v2]._mgoal) == 6 && plr[myplr].WorldX == QUEST_VILE13 && plr[myplr].WorldY == 46 )
{
PlayInGameMovie("gendata\\fprst3.smk");
monster[v2]._mmode = MM_TALK;
quests[15]._qvar1 = 5;
}
if ( monster[v2].mtalkmsg == QUEST_VILE13 )
{
//_LOBYTE(v6) = effect_is_playing(USFX_LAZ1);
if ( !effect_is_playing(USFX_LAZ1) && _LOBYTE(monster[v2]._mgoal) == 7 )
{
ObjChangeMapResync(1, 18, 20, 24);
RedoPlayerVision();
monster[v2]._msquelch = -1;
monster[v2].mtalkmsg = 0;
quests[15]._qvar1 = 6;
_LOBYTE(monster[v2]._mgoal) = 1;
}
}
}
if ( gbMaxPlayers != 1 )
{
LABEL_29:
if ( monster[v2].mtalkmsg == QUEST_VILE13 && _LOBYTE(monster[v2]._mgoal) == 6 && quests[15]._qvar1 <= 3u )
monster[v2]._mmode = MM_TALK;
}
}
v7 = monster[v2]._mgoal;
if ( v7 == 1 || v7 == 2 || v7 == 4 )
{
monster[v2].mtalkmsg = 0;
MAI_Counselor(arglist);
}
monster[v2]._mdir = v5;
v8 = monster[v2]._mmode;
if ( v8 == MM_STAND || v8 == MM_TALK )
monster[v2]._mAnimData = monster[v2].MType->Anims[0].Frames[v5];
}
}
// 679660: using guessed type char gbMaxPlayers;
void __fastcall MAI_Lazhelp(int i)
{
int v1; // esi
int v2; // esi
int v3; // ebx
int v4; // edi
int v5; // [esp+4h] [ebp-8h]
int ia; // [esp+8h] [ebp-4h]
v1 = i;
ia = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("MAI_Lazhelp: Invalid monster %d", i);
v2 = v1;
if ( monster[v2]._mmode == MM_STAND )
{
v3 = monster[v2]._my;
v4 = monster[v2]._mx;
v5 = M_GetDir(ia);
if ( dFlags[v4][v3] & 2 )
{
if ( gbMaxPlayers == 1 )
{
if ( quests[15]._qvar1 <= 5u )
{
_LOBYTE(monster[v2]._mgoal) = 6;
goto LABEL_10;
}
monster[v2].mtalkmsg = 0;
}
_LOBYTE(monster[v2]._mgoal) = 1;
}
LABEL_10:
if ( _LOBYTE(monster[v2]._mgoal) == 1 )
MAI_Succ(ia);
monster[v2]._mdir = v5;
if ( monster[v2]._mmode == MM_STAND )
monster[v2]._mAnimData = monster[v2].MType->Anims[0].Frames[v5];
}
}
// 679660: using guessed type char gbMaxPlayers;
void __fastcall MAI_Lachdanan(int i)
{
int v1; // ebp
int v2; // esi
int v3; // ebx
int v4; // edi
//int v5; // eax
int v6; // [esp+8h] [ebp-4h]
v1 = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("MAI_Lachdanan: Invalid monster %d", i);
v2 = v1;
if ( monster[v1]._mmode == MM_STAND )
{
v3 = monster[v2]._my;
v4 = monster[v2]._mx;
v6 = M_GetDir(v1);
if ( monster[v2].mtalkmsg == QUEST_VEIL9 && !(dFlags[v4][v3] & 2) && _LOBYTE(monster[v2]._mgoal) == 7 )
{
monster[v2].mtalkmsg = QUEST_VEIL10;
_LOBYTE(monster[v2]._mgoal) = 6;
}
if ( dFlags[v4][v3] & 2 )
{
if ( monster[v2].mtalkmsg == QUEST_VEIL11 )
{
//_LOBYTE(v5) = effect_is_playing(USFX_LACH3);
if ( !effect_is_playing(USFX_LACH3) && _LOBYTE(monster[v2]._mgoal) == 7 )
{
monster[v2].mtalkmsg = 0;
quests[4]._qactive = 3;
M_StartKill(v1, -1);
}
}
}
monster[v2]._mdir = v6;
if ( monster[v2]._mmode == MM_STAND )
monster[v2]._mAnimData = monster[v2].MType->Anims[0].Frames[v6];
}
}
void __fastcall MAI_Warlord(int i)
{
int v1; // ebp
int v2; // esi
int v3; // ebx
int v4; // edi
int v5; // ebp
//int v6; // eax
int v7; // eax
int arglist; // [esp+8h] [ebp-4h]
v1 = i;
arglist = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("MAI_Warlord: Invalid monster %d", i);
v2 = v1;
if ( monster[v1]._mmode == MM_STAND )
{
v3 = monster[v2]._my;
v4 = monster[v2]._mx;
v5 = M_GetDir(v1);
if ( dFlags[v4][v3] & 2 && monster[v2].mtalkmsg == QUEST_WARLRD9 )
{
if ( _LOBYTE(monster[v2]._mgoal) == 6 )
monster[v2]._mmode = MM_TALK;
//_LOBYTE(v6) = effect_is_playing(USFX_WARLRD1);
if ( !effect_is_playing(USFX_WARLRD1) && _LOBYTE(monster[v2]._mgoal) == 7 )
{
monster[v2]._msquelch = -1;
monster[v2].mtalkmsg = 0;
_LOBYTE(monster[v2]._mgoal) = 1;
}
}
if ( _LOBYTE(monster[v2]._mgoal) == 1 )
MAI_SkelSd(arglist);
monster[v2]._mdir = v5;
v7 = monster[v2]._mmode;
if ( v7 == MM_STAND || v7 == MM_TALK )
monster[v2]._mAnimData = monster[v2].MType->Anims[0].Frames[v5];
}
}
void __cdecl DeleteMonsterList()
{
int *v0; // eax
signed int v1; // ecx
v0 = &monster[0]._my;
do
{
if ( v0[18] )
{
*(v0 - 1) = 1;
*v0 = 0;
v0[1] = 0;
v0[2] = 0;
v0[3] = 0;
v0[4] = 0;
v0[18] = 0;
}
v0 += 57;
}
while ( (signed int)v0 < (signed int)&monster[4]._my );
v1 = 4;
while ( v1 < nummonsters )
{
if ( monster[monstactive[v1]]._mDelFlag )
{
DeleteMonster(v1);
v1 = 0;
}
else
{
++v1;
}
}
}
void __cdecl ProcessMonsters()
{
int v0; // edi
int v1; // esi
int v2; // ecx
int v3; // eax
char *v4; // ebx
unsigned int v5; // eax
int v6; // eax
int v7; // edx
int v8; // eax
unsigned int v9; // eax
int v10; // eax
bool v11; // zf
char *v12; // ecx
char *v13; // eax
int v14; // ecx
int v15; // eax
char v16; // al
int v17; // ecx
bool v18; // eax
int v19; // eax
int v20; // ecx
int *v21; // eax
int *v22; // eax
int v23; // [esp+0h] [ebp-Ch]
int v24; // [esp+4h] [ebp-8h]
int v25; // [esp+8h] [ebp-4h]
DeleteMonsterList();
v24 = 0;
if ( nummonsters <= 0 )
goto LABEL_60;
do
{
v25 = 0;
v23 = monstactive[v24];
v0 = v23;
v1 = v23;
if ( (unsigned char)gbMaxPlayers > 1u )
{
SetRndSeed(monster[v1]._mAISeed);
monster[v1]._mAISeed = GetRndSeed();
}
if ( !(monster[v1]._mFlags & 8) )
{
v2 = monster[v1]._mhitpoints;
if ( v2 < monster[v1]._mmaxhp && (signed int)(v2 & 0xFFFFFFC0) > 0 )
{
v3 = SLOBYTE(monster[v1].mLevel);
if ( (char)v3 > 1 )
v3 = (char)v3 >> 1;
monster[v1]._mhitpoints = v2 + v3;
}
}
v4 = &dFlags[monster[v1]._mx][monster[v1]._my];
if ( *v4 & 2 && !monster[v1]._msquelch && monster[v1].MType->mtype == MT_CLEAVER )
PlaySFX(USFX_CLEAVER);
if ( monster[v1]._mFlags & 0x10 )
{
v5 = monster[v1]._menemy;
if ( v5 >= MAXMONSTERS )
TermMsg("Illegal enemy monster %d for monster \"%s\"", v5, monster[v1].mName);
v6 = monster[v1]._menemy;
v7 = monster[v6]._mfutx;
monster[v1]._lastx = v7;
monster[v1]._menemyx = v7;
v8 = monster[v6]._mfuty;
monster[v1]._menemyy = v8;
monster[v1]._lasty = v8;
}
else
{
v9 = monster[v1]._menemy;
if ( v9 >= MAX_PLRS )
TermMsg("Illegal enemy player %d for monster \"%s\"", v9, monster[v1].mName);
v10 = monster[v1]._menemy;
v11 = (*v4 & 2) == 0;
v12 = (char *)&plr[v10]._px;
v13 = (char *)&plr[v10]._py;
monster[v1]._menemyx = *v12;
monster[v1]._menemyy = *v13;
if ( v11 )
{
v16 = monster[v1]._msquelch;
if ( v16 && monster[v1]._mAi != MT_DIABLO ) /// BUGFIX: test `MT_DIABLO` with 'MType->mtype' instead of '_mAi'
monster[v1]._msquelch = v16 - 1;
}
else
{
v14 = *(_DWORD *)v12;
v15 = *(_DWORD *)v13;
monster[v1]._msquelch = -1;
monster[v1]._lastx = v14;
monster[v1]._lasty = v15;
}
v0 = v23;
}
while ( 1 )
{
v17 = v0;
if ( monster[v1]._mFlags & 0x100 )
{
v18 = MAI_Path(v0);
if ( v18 )
goto LABEL_30;
v17 = v0;
}
AiProc[(unsigned char)monster[v1]._mAi](v17);
LABEL_30:
switch ( monster[v1]._mmode )
{
case MM_STAND:
v19 = M_DoStand(v0);
goto LABEL_48;
case MM_WALK:
v19 = M_DoWalk(v0);
goto LABEL_48;
case MM_WALK2:
v19 = M_DoWalk2(v0);
goto LABEL_48;
case MM_WALK3:
v19 = M_DoWalk3(v0);
goto LABEL_48;
case MM_ATTACK:
v19 = M_DoAttack(v0);
goto LABEL_48;
case MM_GOTHIT:
v19 = M_DoGotHit(v0);
goto LABEL_48;
case MM_DEATH:
v19 = M_DoDeath(v0);
goto LABEL_48;
case MM_SATTACK:
v19 = M_DoSAttack(v0);
goto LABEL_48;
case MM_FADEIN:
v19 = M_DoFadein(v0);
goto LABEL_48;
case MM_FADEOUT:
v19 = M_DoFadeout(v0);
goto LABEL_48;
case MM_RATTACK:
v19 = M_DoRAttack(v0);
goto LABEL_48;
case MM_SPSTAND:
v19 = M_DoSpStand(v0);
goto LABEL_48;
case MM_RSPATTACK:
v19 = M_DoRSpAttack(v0);
goto LABEL_48;
case MM_DELAY:
v19 = M_DoDelay(v0);
goto LABEL_48;
case MM_CHARGE:
goto LABEL_51;
case MM_STONE:
v19 = M_DoStone(v0);
goto LABEL_48;
case MM_HEAL:
v19 = M_DoHeal(v0);
goto LABEL_48;
case MM_TALK:
v19 = M_DoTalk(v0);
LABEL_48:
v25 = v19;
break;
default:
break;
}
if ( !v25 )
break;
GroupUnity(v0);
}
LABEL_51:
if ( monster[v1]._mmode != MM_STONE )
{
v20 = monster[v1]._mFlags;
v21 = &monster[v1]._mAnimCnt;
++*v21;
if ( !(v20 & 4) && monster[v1]._mAnimCnt >= monster[v1]._mAnimDelay )
{
*v21 = 0;
v22 = &monster[v1]._mAnimFrame;
if ( v20 & 2 )
{
v11 = (*v22)-- == 1;
if ( v11 )
*v22 = monster[v1]._mAnimLen;
}
else if ( ++*v22 > monster[v1]._mAnimLen )
{
*v22 = 1;
}
}
}
++v24;
}
while ( v24 < nummonsters );
LABEL_60:
DeleteMonsterList();
}
// 679660: using guessed type char gbMaxPlayers;
void __cdecl FreeMonsters()
{
void **v0; // edi
int v1; // ebx
signed int v2; // ebp
void **v3; // esi
void *v4; // ecx
int v5; // [esp+0h] [ebp-4h]
v5 = 0;
if ( nummtypes > 0 )
{
v0 = (void **)Monsters[0].Anims;
do
{
v1 = *((unsigned char *)v0 - 4);
v2 = 0;
v3 = v0;
do
{
if ( animletter[v2] != 's' || monsterdata[v1].has_special )
{
v4 = *v3;
*v3 = 0;
mem_free_dbg(v4);
}
++v2;
v3 += 11;
}
while ( v2 < 6 );
++v5;
v0 += 82;
}
while ( v5 < nummtypes );
}
FreeMissiles2();
}
bool __fastcall DirOK(int i, int mdir)
{
int v2; // ebx
int v3; // esi
int v4; // ebx
int v5; // edi
int v6; // esi
int v7; // edi
bool v8; // zf
int v9; // edx
unsigned char *v11; // ebx
unsigned char v12; // al
int v13; // edx
int v14; // eax
int v15; // edi
int v16; // ecx
signed int j; // esi
int v18; // eax
bool v19; // zf
int v20; // eax
int v21; // [esp+Ch] [ebp-14h]
int v22; // [esp+10h] [ebp-10h]
int v23; // [esp+14h] [ebp-Ch]
int a1; // [esp+18h] [ebp-8h]
int v25; // [esp+1Ch] [ebp-4h]
int v26; // [esp+1Ch] [ebp-4h]
v2 = i;
v3 = mdir;
v25 = mdir;
a1 = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("DirOK: Invalid monster %d", i);
v4 = v2;
v5 = offset_y[v3];
v6 = monster[v4]._mx + offset_x[v3];
v7 = monster[v4]._my + v5;
if ( v7 < 0 || v7 >= 112 || v6 < 0 || v6 >= 112 || !PosOkMonst(a1, v6, v7) )
return 0;
if ( v25 == DIR_E )
{
if ( !SolidLoc(v6, v7 + 1) )
{
v8 = (dFlags[v6][v7 + 1] & 0x10) == 0;
goto LABEL_18;
}
return 0;
}
if ( v25 == DIR_W )
{
if ( SolidLoc(v6 + 1, v7) )
return 0;
v8 = (dFlags[v6 + 1][v7] & 0x10) == 0;
}
else
{
if ( v25 == DIR_N )
{
if ( SolidLoc(v6 + 1, v7) )
return 0;
v9 = v7 + 1;
}
else
{
if ( v25 )
goto LABEL_24;
if ( SolidLoc(v6 - 1, v7) )
return 0;
v9 = v7 - 1;
}
v8 = SolidLoc(v6, v9) == 0;
}
LABEL_18:
if ( !v8 )
return 0;
LABEL_24:
if ( monster[v4].leaderflag == 1 )
{
v11 = &monster[v4].leader;
if ( abs(v6 - monster[(unsigned char)*v11]._mfutx) >= 4
|| abs(v7 - monster[(unsigned char)*v11]._mfuty) >= 4 )
{
return 0;
}
return 1;
}
v12 = monster[v4]._uniqtype;
if ( !v12 || !(UniqMonst[v12 - 1].mUnqAttr & 2) )
return 1;
v26 = 0;
v13 = v6 - 3;
v21 = v6 + 3;
if ( v6 - 3 <= v6 + 3 )
{
v14 = v7 - 3;
v15 = v7 + 3;
v23 = v14;
v22 = v15;
v16 = 112 * v13;
do
{
for ( j = v23; j <= v15; ++j )
{
if ( j >= 0 && j < 112 && v16 >= 0 && v16 < 12544 )
{
v18 = dMonster[0][v16 + j];
v19 = v18 == 0;
if ( v18 < 0 )
{
v18 = -v18;
v19 = v18 == 0;
}
if ( !v19 )
--v18;
v20 = v18;
if ( monster[v20].leaderflag == 1
&& (unsigned char)monster[v20].leader == a1
&& monster[v20]._mfutx == v13
&& monster[v20]._mfuty == j )
{
++v26;
}
}
v15 = v22;
}
++v13;
v16 += 112;
}
while ( v13 <= v21 );
}
return v26 == (unsigned char)monster[v4].unpackfilesize;
}
BOOL __fastcall PosOkMissile(int x, int y)
{
return !nMissileTable[dPiece[x][y]] && !(dFlags[x][y] & 0x10);
}
BOOL __fastcall CheckNoSolid(int x, int y)
{
return nSolidTable[dPiece[x][y]] == 0;
}
BOOL __fastcall LineClearF(BOOL(__fastcall *Clear)(int, int), int x1, int y1, int x2, int y2)
{
int v5; // esi
int v6; // edi
int v7; // ebx
int v8; // eax
int v9; // eax
int v10; // eax
int v11; // ebx
int v12; // esi
signed int v13; // edi
int v14; // edx
int v15; // ecx
int v16; // eax
int v17; // eax
int v18; // eax
int v19; // ebx
int v20; // edi
signed int v21; // esi
int v22; // ecx
int v25; // [esp+10h] [ebp-10h]
int v26; // [esp+14h] [ebp-Ch]
int v27; // [esp+18h] [ebp-8h]
int v28; // [esp+18h] [ebp-8h]
int v29; // [esp+1Ch] [ebp-4h]
v5 = y2 - y1;
v29 = x1;
v25 = x1;
v26 = y1;
v6 = x2 - x1;
v7 = abs(y2 - y1);
if ( abs(v6) <= v7 )
{
if ( v5 < 0 )
{
v16 = y1;
y1 = y2;
y2 = v16;
v17 = v29;
v5 = -v5;
v29 = x2;
x2 = v17;
v6 = -v6;
}
v18 = 2 * v6;
v28 = 2 * v6;
if ( v6 <= 0 )
{
v19 = v18 + v5;
v20 = 2 * (v5 + v6);
v21 = -1;
}
else
{
v19 = v18 - v5;
v20 = 2 * (v6 - v5);
v21 = 1;
}
while ( 1 )
{
v22 = v29;
if ( y1 == y2 && v29 == x2 )
break;
if ( v19 <= 0 == v21 < 0 )
{
v19 += v20;
v22 = v21 + v29;
v29 += v21;
}
else
{
v19 += v28;
}
if ( (++y1 != v26 || v22 != v25) && !Clear(v22, y1) ) /* check args */
goto LABEL_29;
}
}
else
{
if ( v6 < 0 )
{
v8 = v29;
v29 = x2;
x2 = v8;
v9 = y1;
v6 = -v6;
y1 = y2;
y2 = v9;
v5 = -v5;
}
v10 = 2 * v5;
v27 = 2 * v5;
if ( v5 <= 0 )
{
v11 = v10 + v6;
v12 = 2 * (v6 + v5);
v13 = -1;
}
else
{
v11 = v10 - v6;
v12 = 2 * (v5 - v6);
v13 = 1;
}
do
{
v14 = y1;
if ( v29 == x2 && y1 == y2 )
break;
if ( v11 <= 0 == v13 < 0 )
{
v11 += v12;
v14 = v13 + y1;
y1 += v13;
}
else
{
v11 += v27;
}
v15 = v29 + 1;
}
while ( ++v29 == v25 && v14 == v26 || Clear(v15, v14) );
LABEL_29:
if ( v29 != x2 )
return 0;
}
if ( y1 == y2 )
return 1;
return 0;
}
BOOL __fastcall LineClear(int x1, int y1, int x2, int y2)
{
return LineClearF(PosOkMissile, x1, y1, x2, y2);
}
BOOL __fastcall LineClearF1(BOOL(__fastcall *Clear)(int, int, int), int monst, int x1, int y1, int x2, int y2)
{
int v6; // esi
int v7; // edi
int v8; // ebx
int v9; // eax
int v10; // eax
int v11; // eax
int v12; // ebx
int v13; // esi
signed int v14; // edi
int v15; // eax
int v16; // eax
int v17; // eax
int v18; // eax
int v19; // ebx
int v20; // edi
signed int v21; // esi
int v22; // edx
int v25; // [esp+10h] [ebp-10h]
int v26; // [esp+14h] [ebp-Ch]
int v27; // [esp+18h] [ebp-8h]
int v28; // [esp+1Ch] [ebp-4h]
int v29; // [esp+1Ch] [ebp-4h]
v6 = y2 - y1;
v25 = monst;
v26 = x1;
v27 = y1;
v7 = x2 - x1;
v8 = abs(y2 - y1);
if ( abs(x2 - x1) <= v8 )
{
if ( v6 < 0 )
{
v16 = y1;
y1 = y2;
y2 = v16;
v17 = x1;
v6 = -v6;
x1 = x2;
x2 = v17;
v7 = -v7;
}
v18 = 2 * v7;
v29 = 2 * v7;
if ( v7 <= 0 )
{
v19 = v18 + v6;
v20 = 2 * (v6 + v7);
v21 = -1;
}
else
{
v19 = v18 - v6;
v20 = 2 * (v7 - v6);
v21 = 1;
}
while ( 1 )
{
v22 = x1;
if ( y1 == y2 && x1 == x2 )
break;
if ( v19 <= 0 == v21 < 0 )
{
v19 += v20;
v22 = v21 + x1;
x1 += v21;
}
else
{
v19 += v29;
}
if ( (++y1 != v27 || v22 != v26) && !Clear(v25, v22, y1) )
goto LABEL_29;
}
}
else
{
if ( v7 < 0 )
{
v9 = x1;
x1 = x2;
x2 = v9;
v10 = y1;
v7 = -v7;
y1 = y2;
y2 = v10;
v6 = -v6;
}
v11 = 2 * v6;
v28 = 2 * v6;
if ( v6 <= 0 )
{
v12 = v11 + v7;
v13 = 2 * (v7 + v6);
v14 = -1;
}
else
{
v12 = v11 - v7;
v13 = 2 * (v6 - v7);
v14 = 1;
}
do
{
v15 = y1;
if ( x1 == x2 && y1 == y2 )
break;
if ( v12 <= 0 == v14 < 0 )
{
v12 += v13;
v15 = v14 + y1;
y1 += v14;
}
else
{
v12 += v28;
}
}
while ( ++x1 == v26 && v15 == v27 || Clear(v25, x1, v15) ); /* check args */
LABEL_29:
if ( x1 != x2 )
return 0;
}
if ( y1 == y2 )
return 1;
return 0;
}
void __fastcall SyncMonsterAnim(int i)
{
int v1; // esi
int v2; // eax
int v3; // edx
MonsterData *v4; // esi
CMonster *v5; // ecx
unsigned char v6; // dl
char *v7; // edx
int v8; // esi
int v9; // edx
unsigned char *v10; // ecx
unsigned char *v11; // edx
int v12; // ecx
unsigned char *v13; // edx
v1 = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("SyncMonsterAnim: Invalid monster %d", i);
v2 = v1;
v3 = monster[v1]._mMTidx;
v4 = Monsters[v3].MData;
v5 = &Monsters[v3];
v6 = monster[v2]._uniqtype;
monster[v2].MType = v5;
monster[v2].MData = v4;
if ( v6 )
v7 = UniqMonst[v6 - 1].mName;
else
v7 = v4->mName;
v8 = monster[v2]._mmode;
monster[v2].mName = v7;
v9 = monster[v2]._mdir;
switch ( v8 )
{
case MM_STAND:
case MM_DELAY:
case MM_TALK:
v10 = v5->Anims[0].Frames[v9];
goto LABEL_13;
case MM_WALK:
case MM_WALK2:
case MM_WALK3:
v10 = v5->Anims[1].Frames[v9];
goto LABEL_13;
case MM_ATTACK:
case MM_RATTACK:
v10 = v5->Anims[2].Frames[v9];
goto LABEL_13;
case MM_GOTHIT:
v10 = v5->Anims[3].Frames[v9];
goto LABEL_13;
case MM_DEATH:
v10 = v5->Anims[4].Frames[v9];
goto LABEL_13;
case MM_SATTACK:
case MM_FADEIN:
case MM_FADEOUT:
case MM_SPSTAND:
case MM_RSPATTACK:
case MM_HEAL:
v10 = v5->Anims[5].Frames[v9];
LABEL_13:
monster[v2]._mAnimData = v10;
return;
case MM_CHARGE:
v11 = v5->Anims[2].Frames[v9];
monster[v2]._mAnimFrame = 1;
monster[v2]._mAnimData = v11;
v12 = v5->Anims[2].Rate;
break;
default:
v13 = v5->Anims[0].Frames[v9];
monster[v2]._mAnimFrame = 1;
monster[v2]._mAnimData = v13;
v12 = v5->Anims[0].Rate;
break;
}
monster[v2]._mAnimLen = v12;
}
void __fastcall M_FallenFear(int x, int y)
{
int v2; // eax
int *v3; // ebx
int v4; // edi
int v5; // esi
signed int v6; // eax
int v7; // eax
bool v8; // zf
int v9; // eax
int v10; // eax
signed int v11; // [esp-10h] [ebp-1Ch]
int v12; // [esp+0h] [ebp-Ch]
int x1; // [esp+4h] [ebp-8h]
int y1; // [esp+8h] [ebp-4h]
v2 = 0;
y1 = y;
x1 = x;
v12 = 0;
if ( nummonsters > 0 )
{
v3 = &monster[0]._mx;
do
{
v4 = 0;
v5 = monstactive[v2];
v6 = monster[v5].MType->mtype;
if ( v6 > MT_RFALLSD )
{
v9 = v6 - 13;
v8 = v9 == 0;
}
else
{
if ( v6 == MT_RFALLSD || (v7 = v6 - 4) == 0 )
{
v11 = 7;
goto LABEL_15;
}
v9 = v7 - 1;
v8 = v9 == 0;
}
if ( v8 )
{
v11 = 5;
}
else
{
v10 = v9 - 1;
if ( v10 )
{
if ( v10 != 1 )
goto LABEL_16;
v11 = 2;
}
else
{
v11 = 3;
}
}
LABEL_15:
v4 = v11;
LABEL_16:
if ( monster[v5]._mAi == AI_FALLEN
&& v4
&& abs(x1 - monster[v5]._mx) < 5
&& abs(y1 - monster[v5]._my) < 5
&& (signed int)(monster[v5]._mhitpoints & 0xFFFFFFC0) > 0 )
{
_LOBYTE(monster[v5]._mgoal) = 2;
monster[v5]._mgoalvar1 = v4;
monster[v5]._mdir = GetDirection(x1, y1, *v3, v3[1]);
}
v3 += 57;
v2 = v12++ + 1;
}
while ( v12 < nummonsters );
}
}
void __fastcall PrintMonstHistory(int mt)
{
int v1; // edi
int *v2; // ebx
int v3; // ecx
int v4; // eax
int v5; // edi
short v6; // bx
int v7; // ebx
v1 = mt;
v2 = &monstkills[mt];
sprintf(tempstr, "Total kills : %i", *v2);
AddPanelString(tempstr, 1);
if ( *v2 >= 30 )
{
v3 = monsterdata[v1].mMinHP;
v4 = monsterdata[v1].mMaxHP;
if ( gbMaxPlayers == 1 )
{
v3 = monsterdata[v1].mMinHP >> 1;
v4 = monsterdata[v1].mMaxHP >> 1;
}
if ( v3 < 1 )
v3 = 1;
if ( v4 < 1 )
v4 = 1;
if ( gnDifficulty == DIFF_NIGHTMARE )
{
v3 = 3 * v3 + 1;
v4 = 3 * v4 + 1;
}
if ( gnDifficulty == DIFF_HELL )
{
v3 = 4 * v3 + 3;
v4 = 4 * v4 + 3;
}
sprintf(tempstr, "Hit Points : %i-%i", v3, v4);
AddPanelString(tempstr, 1);
}
if ( *v2 >= 15 )
{
v5 = v1 << 7;
if ( gnDifficulty == DIFF_HELL )
v6 = *(short *)((char *)&monsterdata[0].mMagicRes2 + v5);
else
v6 = *(short *)((char *)&monsterdata[0].mMagicRes + v5);
v7 = v6 & 0x3F;
if ( v7 )
{
if ( v7 & 7 )
{
strcpy(tempstr, "Resists : ");
if ( v7 & 1 )
strcat(tempstr, "Magic ");
if ( v7 & 2 )
strcat(tempstr, "Fire ");
if ( v7 & 4 )
strcat(tempstr, "Lightning ");
tempstr[strlen(tempstr) - 1] = '\0';
AddPanelString(tempstr, 1);
}
if ( v7 & 0x38 )
{
strcpy(tempstr, "Immune : ");
if ( v7 & 8 )
strcat(tempstr, "Magic ");
if ( v7 & 0x10 )
strcat(tempstr, "Fire ");
if ( v7 & 0x20 )
strcat(tempstr, "Lightning ");
tempstr[strlen(tempstr) - 1] = '\0';
AddPanelString(tempstr, 1);
}
}
else
{
strcpy(tempstr, "No magic resistance");
AddPanelString(tempstr, 1);
}
}
pinfoflag = 1;
}
// 4B8824: using guessed type int pinfoflag;
// 679660: using guessed type char gbMaxPlayers;
void __cdecl PrintUniqueHistory()
{
char v0; // bl
v0 = monster[pcursmonst].mMagicRes & 0x3F;
if ( v0 )
{
if ( monster[pcursmonst].mMagicRes & 7 )
strcpy(tempstr, "Some Magic Resistances");
else
strcpy(tempstr, "No resistances");
AddPanelString(tempstr, 1);
if ( v0 & 0x38 )
{
strcpy(tempstr, "Some Magic Immunities");
goto LABEL_4;
}
}
else
{
strcpy(tempstr, "No resistances");
AddPanelString(tempstr, 1);
}
strcpy(tempstr, "No Immunities");
LABEL_4:
AddPanelString(tempstr, 1);
pinfoflag = 1;
}
// 4B8824: using guessed type int pinfoflag;
void __fastcall MissToMonst(int i, int x, int y)
{
int v3; // edi
MissileStruct *v4; // edi
unsigned int v5; // ebx
MonsterStruct *v6; // esi
int v7; // edx
char v8; // al
int v9; // eax
char *v10; // edi
int v11; // eax
int v12; // edx
char v13; // al
char v14; // al
int v15; // ebx
int v16; // eax
int v17; // esi
int v18; // edi
int v19; // esi
int v20; // edx
int *v21; // ebx
char v22; // cl
char v23; // al
int v24; // esi
int v25; // edi
int v26; // esi
int v27; // eax
int v28; // eax
int ia; // [esp+Ch] [ebp-10h]
int v30; // [esp+10h] [ebp-Ch]
int v31; // [esp+14h] [ebp-8h]
int v32; // [esp+18h] [ebp-4h]
int arglist; // [esp+24h] [ebp+8h]
v3 = i;
v30 = x;
if ( (unsigned int)i >= MAXMISSILES )
TermMsg("MissToMonst: Invalid missile %d", i);
v4 = &missile[v3];
v5 = v4->_misource;
ia = v4->_misource;
if ( v5 >= MAXMONSTERS )
TermMsg("MissToMonst: Invalid monster %d", v5);
v32 = v4->_mix;
v31 = v4->_miy;
v6 = &monster[v5];
v6->_mx = v30;
dMonster[0][y + 112 * v30] = v5 + 1;
v7 = v4->_mimfnum;
v6->_mdir = v7;
v6->_my = y;
M_StartStand(v5, v7);
v8 = v6->MType->mtype;
if ( v8 < MT_INCIN || v8 > MT_HELLBURN )
{
if ( v6->_mFlags & 0x10 )
M2MStartHit(v5, -1, 0);
else
M_StartHit(v5, -1, 0);
}
else
{
M_StartFadein(v5, v6->_mdir, 0);
}
v9 = v32;
if ( v6->_mFlags & 0x10 )
{
v21 = (int *)((char *)dMonster + 4 * (v31 + v9 * 112));
if ( *v21 > 0 )
{
v22 = v6->MType->mtype;
if ( v22 != MT_GLOOM && (v22 < MT_INCIN || v22 > MT_HELLBURN) )
{
M_TryM2MHit(ia, *v21 - 1, 500, (unsigned char)v6->mMinDamage2, (unsigned char)v6->mMaxDamage2);
v23 = v6->MType->mtype;
if ( v23 < MT_NSNAKE || v23 > MT_GSNAKE )
{
v24 = v6->_mdir;
v25 = v32 + offset_x[v24];
v26 = v31 + offset_y[v24];
if ( PosOkMonst(*v21 - 1, v25, v26) )
{
v27 = *v21;
dMonster[0][v26 + 112 * v25] = *v21;
*v21 = 0;
v28 = v27 - 1;
monster[v28]._mx = v25;
monster[v28]._mfutx = v25;
monster[v28]._my = v26;
monster[v28]._mfuty = v26;
}
}
}
}
}
else
{
v10 = &dPlayer[v9][v31];
v11 = *v10;
v12 = v11 - 1;
arglist = v11 - 1;
if ( *v10 > 0 )
{
v13 = v6->MType->mtype;
if ( v13 != MT_GLOOM && (v13 < MT_INCIN || v13 > MT_HELLBURN) )
{
M_TryH2HHit(v5, v12, 500, (unsigned char)v6->mMinDamage2, (unsigned char)v6->mMaxDamage2);
if ( arglist == *v10 - 1 )
{
v14 = v6->MType->mtype;
if ( v14 < MT_NSNAKE || v14 > MT_GSNAKE )
{
v15 = arglist;
v16 = plr[arglist]._pmode;
if ( v16 != 7 && v16 != 8 )
StartPlrHit(arglist, 0, 1u);
v17 = v6->_mdir;
v18 = v32 + offset_x[v17];
v19 = v31 + offset_y[v17];
if ( PosOkPlayer(arglist, v18, v19) )
{
v20 = plr[v15]._pdir;
plr[v15].WorldX = v18;
plr[v15].WorldY = v19;
FixPlayerLocation(arglist, v20);
FixPlrWalkTags(arglist);
dPlayer[v18][v19] = arglist + 1;
SetPlayerOld(arglist);
}
}
}
}
}
}
}
BOOL __fastcall PosOkMonst(int i, int x, int y)
{
int v3; // edi
signed int v4; // ebx
int v5; // ecx
char v6; // dl
bool result; // eax
int v8; // edx
int v9; // ecx
int v10; // [esp+Ch] [ebp-4h]
v3 = x;
v10 = i;
v4 = 0;
if ( SolidLoc(x, y) )
return 0;
v5 = 112 * v3;
if ( dPlayer[v3][y] || dMonster[0][v5 + y] )
return 0;
v6 = dObject[0][v5 + y];
result = 1;
if ( v6 )
{
v8 = v6 <= 0 ? -1 - v6 : v6 - 1;
if ( object[v8]._oSolidFlag )
return 0;
}
_LOBYTE(v5) = dMissile[0][v5 + y];
if ( (_BYTE)v5 )
{
if ( v10 >= 0 )
{
v5 = (char)v5;
if ( (char)v5 > 0 )
{
if ( missile[v5]._mitype == 5 )
goto LABEL_24;
v9 = 0;
if ( nummissiles > 0 )
{
do
{
if ( missile[missileactive[v9]]._mitype == 5 )
v4 = 1;
++v9;
}
while ( v9 < nummissiles );
if ( v4 )
{
LABEL_24:
if ( !(monster[v10].mMagicRes & 0x10) || monster[v10].MType->mtype == MT_DIABLO )
return 0;
}
}
}
}
}
return result;
}
BOOL __fastcall PosOkMonst2(int i, int x, int y)
{
int v3; // edi
int v4; // ebx
signed int v5; // ebp
bool result; // eax
char v7; // dl
int v8; // edx
int v9; // ecx
int v10; // ecx
v3 = x;
v4 = i;
v5 = 0;
result = SolidLoc(x, y) == 0;
if ( result )
{
v7 = dObject[v3][y];
if ( v7 )
{
v8 = v7 <= 0 ? -1 - v7 : v7 - 1;
if ( object[v8]._oSolidFlag )
result = 0;
}
if ( result )
{
_LOBYTE(v9) = dMissile[v3][y];
if ( (_BYTE)v9 )
{
if ( v4 >= 0 )
{
v9 = (char)v9;
if ( (char)v9 > 0 )
{
if ( missile[v9]._mitype == 5 )
goto LABEL_23;
v10 = 0;
if ( nummissiles > 0 )
{
do
{
if ( missile[missileactive[v10]]._mitype == 5 )
v5 = 1;
++v10;
}
while ( v10 < nummissiles );
if ( v5 )
{
LABEL_23:
if ( !(monster[v4].mMagicRes & 0x10) || monster[v4].MType->mtype == MT_DIABLO )
result = 0;
}
}
}
}
}
}
}
return result;
}
BOOL __fastcall PosOkMonst3(int i, int x, int y)
{
int v3; // esi
signed int v4; // ebp
char v5; // al
int v6; // eax
int v7; // eax
int v8; // ecx
int v9; // ecx
bool result; // eax
int v11; // ecx
signed int v12; // [esp+10h] [ebp-8h]
int v13; // [esp+14h] [ebp-4h]
v12 = 0;
v3 = x;
v4 = 0;
v13 = i;
v5 = dObject[x][y];
if ( v5 )
{
if ( v5 <= 0 )
v6 = -1 - v5;
else
v6 = v5 - 1;
v7 = v6;
v8 = object[v7]._otype;
v4 = 1;
if ( v8 != 1
&& v8 != OBJ_L1RDOOR
&& v8 != OBJ_L2LDOOR
&& v8 != OBJ_L2RDOOR
&& v8 != OBJ_L3LDOOR
&& v8 != OBJ_L3RDOOR )
{
v4 = 0;
}
if ( object[v7]._oSolidFlag && !v4 )
return 0;
}
if ( SolidLoc(x, y) && !v4 || dPlayer[v3][y] || dMonster[0][v3 * 112 + y] )
return 0;
_LOBYTE(v9) = dMissile[v3][y];
result = 1;
if ( (_BYTE)v9 )
{
if ( v13 >= 0 )
{
v9 = (char)v9;
if ( (char)v9 > 0 )
{
if ( missile[v9]._mitype == 5 )
goto LABEL_33;
v11 = 0;
if ( nummissiles > 0 )
{
do
{
if ( missile[missileactive[v11]]._mitype == 5 )
v12 = 1;
++v11;
}
while ( v11 < nummissiles );
if ( v12 )
{
LABEL_33:
if ( !(monster[v13].mMagicRes & 0x10) || monster[v13].MType->mtype == MT_DIABLO )
return 0;
}
}
}
}
}
return result;
}
BOOL __fastcall IsSkel(int mt)
{
return mt >= MT_WSKELAX && mt <= MT_XSKELAX
|| mt >= MT_WSKELBW && mt <= MT_XSKELBW
|| mt >= MT_WSKELSD && mt <= MT_XSKELSD;
}
bool __fastcall IsGoat(int mt)
{
return mt >= MT_NGOATMC && mt <= MT_GGOATMC || mt >= MT_NGOATBW && mt <= MT_GGOATBW;
}
int __fastcall M_SpawnSkel(int x, int y, int dir)
{
CMonster *v3; // ebx
CMonster *v4; // esi
int v5; // edx
int v7; // esi
//int v8; // edx
int v9; // eax
int v10; // esi
int xa; // [esp+Ch] [ebp-10h]
int ya; // [esp+10h] [ebp-Ch]
int v14; // [esp+14h] [ebp-8h]
int v15; // [esp+18h] [ebp-4h]
int v16; // [esp+18h] [ebp-4h]
ya = y;
xa = x;
v5 = 0;
if ( nummtypes <= 0 )
return -1;
v3 = Monsters;
v15 = nummtypes;
v4 = Monsters;
do
{
if ( IsSkel((unsigned char)v4->mtype) )
++v5;
++v4;
--v15;
}
while ( v15 );
if ( !v5 )
return -1;
v7 = 0;
v14 = random(136, v5);
v16 = 0;
if ( nummtypes > 0 )
{
do
{
if ( v16 > v14 )
break;
if ( IsSkel((unsigned char)v3->mtype) )
++v16;
++v7;
++v3;
}
while ( v7 < nummtypes ); /* v8 */
}
v9 = AddMonster(xa, ya, dir, v7 - 1, 1);
v10 = v9;
if ( v9 != -1 )
M_StartSpStand(v9, dir);
return v10;
}
void __fastcall ActivateSpawn(int i, int x, int y, int dir)
{
int v4; // eax
dMonster[0][y + 112 * x] = i + 1;
v4 = i;
monster[v4]._mx = x;
monster[v4]._mfutx = x;
monster[v4]._moldx = x;
monster[v4]._my = y;
monster[v4]._mfuty = y;
monster[v4]._moldy = y;
M_StartSpStand(i, dir);
}
bool __fastcall SpawnSkeleton(int ii, int x, int y)
{
int v3; // esi
int v4; // ebx
int v5; // ST04_4
int v6; // ecx
int v7; // edi
int *v8; // esi
bool v9; // eax
int v11; // eax
int v12; // ecx
int v13; // edx
int v14; // esi
int v15; // edi
int v16; // ST04_4
int monstok[9]; // [esp+Ch] [ebp-34h]
int i; // [esp+30h] [ebp-10h]
int x2; // [esp+34h] [ebp-Ch]
int v20; // [esp+38h] [ebp-8h]
int *v21; // [esp+3Ch] [ebp-4h]
int a3; // [esp+48h] [ebp+8h]
int a3a; // [esp+48h] [ebp+8h]
i = ii;
v3 = x;
x2 = x;
if ( ii == -1 )
return 0;
v4 = y;
if ( !PosOkMonst(-1, x, y) )
{
v20 = 0;
v6 = y - 1;
a3 = y - 1;
if ( (unsigned char)(__OFSUB__(v4 - 1, v4 + 1) ^ 1) | (v4 - 1 == v4 + 1) )
{
v21 = monstok;
do
{
v7 = v3 - 1;
if ( (unsigned char)(__OFSUB__(v3 - 1, v3 + 1) ^ 1) | (v3 - 1 == v3 + 1) )
{
v8 = v21;
do
{
v9 = PosOkMonst(-1, v7, a3);
v20 |= v9;
*v8 = v9;
v8 += 3;
++v7;
}
while ( v7 <= x2 + 1 );
v3 = x2;
}
++v21;
++a3;
}
while ( a3 <= v4 + 1 );
if ( v20 )
{
v11 = random(137, 15);
v12 = 0;
v13 = 0;
a3a = v11 + 1;
if ( v11 + 1 > 0 )
{
while ( 1 )
{
if ( monstok[v13 + 2 * v12 + v12] )
--a3a;
if ( a3a <= 0 )
break;
if ( ++v12 == 3 )
{
v12 = 0;
if ( ++v13 == 3 )
v13 = 0;
}
}
}
v14 = v12 + v3 - 1;
v15 = v13 + v4 - 1;
v16 = GetDirection(v14, v15, x2, v4);
ActivateSpawn(i, v14, v15, v16);
return 1;
}
}
return 0;
}
v5 = GetDirection(v3, y, v3, y);
ActivateSpawn(i, v3, y, v5);
return 1;
}
// 43A879: using guessed type int var_34[9];
int __cdecl PreSpawnSkeleton()
{
int skeltypes; // edx // should be i/j
int j; // edx // remove
int skel; // eax
int i; // [esp+10h] [ebp-4h] // should be skeltypes
skeltypes = 0;
if ( nummtypes <= 0 )
return -1;
for ( i = 0; i < nummtypes; i++ )
{
if ( IsSkel(Monsters[i].mtype) )
++skeltypes;
}
if ( !skeltypes )
return -1;
j = random(136, skeltypes); /* check this code -i integer is messed up*/
skeltypes = 0;
for ( i = 0; i < nummtypes; ++i )
{
if ( skeltypes > j )
break;
if ( IsSkel(Monsters[i].mtype) )
++skeltypes;
}
skel = AddMonster(0, 0, 0, i - 1, 0);
if ( skel != -1 )
M_StartStand(skel, 0);
return skel;
}
void __fastcall TalktoMonster(int i)
{
int v1; // esi
MonsterStruct *v2; // esi
char v3; // al
int v4; // edi
//int v5; // eax
//int v6; // eax
int inv_item_num; // [esp+8h] [ebp-4h]
v1 = i;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("TalktoMonster: Invalid monster %d", i);
v2 = &monster[v1];
v3 = v2->_mAi;
v4 = v2->_menemy;
v2->_mmode = MM_TALK;
if ( v3 == AI_SNOTSPIL || v3 == AI_LACHDAN )
{
//_LOBYTE(v5) = QuestStatus(7);
if ( QuestStatus(7) && quests[7]._qvar1 == 2 && PlrHasItem(v4, IDI_BANNER, &inv_item_num) )
{
RemoveInvItem(v4, inv_item_num);
quests[7]._qactive = 3;
v2->mtalkmsg = QUEST_BANNER12;
_LOBYTE(v2->_mgoal) = 6;
}
//_LOBYTE(v6) = QuestStatus(4);
if ( QuestStatus(4) && v2->mtalkmsg >= (signed int)QUEST_VEIL9 )
{
if ( PlrHasItem(v4, IDI_GLDNELIX, &inv_item_num) )
{
RemoveInvItem(v4, inv_item_num);
v2->mtalkmsg = QUEST_VEIL11;
_LOBYTE(v2->_mgoal) = 6;
}
}
}
}
void __fastcall SpawnGolum(int i, int x, int y, int mi)
{
int v4; // edi
int v5; // ebx
int v6; // esi
int v7; // eax
int *v8; // edx
int v9; // eax
char v10; // cl
int v11; // eax
v4 = i;
v5 = x;
if ( (unsigned int)i >= MAXMONSTERS )
TermMsg("SpawnGolum: Invalid monster %d", i);
v6 = v4;
monster[v6]._mx = v5;
monster[v6]._my = y;
monster[v6]._mfuty = y;
monster[v6]._moldy = y;
monster[v6]._mfutx = v5;
monster[v6]._moldx = v5;
v7 = plr[v4]._pMaxMana;
dMonster[0][y + 112 * v5] = v4 + 1;
_LOBYTE(monster[v6]._pathcount) = 0;
monster[v6]._mFlags |= 0x20u;
v8 = &missile[mi]._mispllvl;
monster[v6].mArmorClass = 25;
v9 = 320 * *v8 + v7 / 3;
v10 = *(_BYTE *)v8;
_LOBYTE(v8) = plr[v4]._pLevel;
v9 *= 2;
monster[v6]._mmaxhp = v9;
monster[v6]._mhitpoints = v9;
monster[v6].mHit = 5 * (v10 + 8) + 2 * (_BYTE)v8;
monster[v6].mMinDamage = 2 * (v10 + 4);
monster[v6].mMaxDamage = 2 * (v10 + 8);
M_StartSpStand(v4, 0);
M_Enemy(v4);
if ( v4 == myplr )
{
_LOBYTE(v11) = currlevel;
NetSendCmdGolem(
monster[v6]._mx,
monster[v6]._my,
monster[v6]._mdir,
monster[v6]._menemy,
monster[v6]._mhitpoints,
v11);
}
}
bool __fastcall CanTalkToMonst(int m)
{
int v1; // esi
char v2; // al
bool result; // al
v1 = m;
if ( (unsigned int)m >= MAXMONSTERS )
TermMsg("CanTalkToMonst: Invalid monster %d", m);
v2 = monster[v1]._mgoal;
if ( v2 == 6 )
result = 1;
else
result = v2 == 7;
return result;
}
BOOL __fastcall CheckMonsterHit(int m, BOOL *ret)
{
if ( (DWORD)m >= MAXMONSTERS ) {
TermMsg("CheckMonsterHit: Invalid monster %d", m);
}
if ( monster[m]._mAi == AI_GARG && monster[m]._mFlags & 4) {
monster[m]._mmode = MM_SATTACK;
monster[m]._mFlags &= 0xFFFFFFFB;
*ret = TRUE;
return TRUE;
}
if ( monster[m].MType->mtype < MT_COUNSLR || monster[m].MType->mtype > MT_ADVOCATE || monster[m]._mgoal == 1 ) {
return FALSE;
} else {
*ret = FALSE;
}
return TRUE;
}
int __fastcall encode_enemy(int m)
{
int v1; // ecx
int result; // eax
v1 = m;
result = monster[v1]._menemy;
if ( monster[v1]._mFlags & 0x10 )
result += 4;
return result;
}
void __fastcall decode_enemy(int m, int enemy)
{
int v2; // eax
int v3; // edx
char v4; // cl
int v5; // edx
v2 = m;
if ( enemy >= 4 )
{
monster[v2]._mFlags |= 0x10u;
v5 = enemy - 4;
monster[v2]._menemy = v5;
monster[v2]._menemyx = monster[v5]._mfutx;
v4 = monster[v5]._mfuty;
}
else
{
monster[v2]._mFlags &= 0xFFFFFFEF;
monster[v2]._menemy = enemy;
v3 = enemy;
monster[v2]._menemyx = plr[v3]._px;
v4 = plr[v3]._py;
}
monster[v2]._menemyy = v4;
}
|
/* Scroll
*
* Copyright (c) 2008-2021 Orx-Project
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
//! Constants
// Param
const orxSTRING ScrollEd::szMapShortParam = "m";
const orxSTRING ScrollEd::szMapLongParam = "map";
const orxSTRING ScrollEd::szMapShortDesc = "Works on the specified map.";
const orxSTRING ScrollEd::szMapLongDesc = "Loads the specified map and allows to work on it, add/remove tiles and save the map.";
// Input
const orxSTRING ScrollEd::szInputResetZoom = "ResetZoom";
const orxSTRING ScrollEd::szInputAction = "Action";
const orxSTRING ScrollEd::szInputClearSelection = "ClearSelection";
const orxSTRING ScrollEd::szInputSoftClearSelection = "SoftClearSelection";
const orxSTRING ScrollEd::szInputCopy = "Copy";
const orxSTRING ScrollEd::szInputZoom = "Zoom";
const orxSTRING ScrollEd::szInputPan = "Pan";
const orxSTRING ScrollEd::szInputDelete = "Delete";
const orxSTRING ScrollEd::szInputSave = "Save";
const orxSTRING ScrollEd::szInputReload = "Reload";
const orxSTRING ScrollEd::szInputNextSet = "NextSet";
const orxSTRING ScrollEd::szInputPreviousSet = "PreviousSet";
const orxSTRING ScrollEd::szInputHideSet = "HideSet";
const orxSTRING ScrollEd::szInputPreviousLayer = "PreviousLayer";
const orxSTRING ScrollEd::szInputNextLayer = "NextLayer";
const orxSTRING ScrollEd::szInputAntialiasing = "Antialiasing";
const orxSTRING ScrollEd::szInputTiling = "Tiling";
const orxSTRING ScrollEd::szInputStartGame = "StartGame";
const orxSTRING ScrollEd::szInputStopGame = "StopGame";
const orxSTRING ScrollEd::szInputScreenshot = "Screenshot";
const orxSTRING ScrollEd::szInputToggleMove = "ToggleMove";
const orxSTRING ScrollEd::szInputToggleScale = "ToggleScale";
const orxSTRING ScrollEd::szInputToggleRotate = "ToggleRotate";
const orxSTRING ScrollEd::szInputToggleGrid = "ToggleGrid";
const orxSTRING ScrollEd::szInputDifferential = "ToggleDifferential";
const orxSTRING ScrollEd::szInputToggleSnap = "ToggleSnap";
const orxSTRING ScrollEd::szInputEditAlpha = "EditAlpha";
const orxSTRING ScrollEd::szInputEditRed = "EditRed";
const orxSTRING ScrollEd::szInputEditGreen = "EditGreen";
const orxSTRING ScrollEd::szInputEditBlue = "EditBlue";
const orxSTRING ScrollEd::szInputToggleFullScreen = "ToggleFullScreen";
const orxSTRING ScrollEd::szInputReloadHistory = "ReloadHistory";
const orxSTRING ScrollEd::szInputSetEditor = "ScrollEdInput";
// Config
const orxSTRING ScrollEd::szConfigFile = "scrolled/scrolled.ini";
const orxSTRING ScrollEd::szConfigSectionEditor = "ScrollEd";
const orxSTRING ScrollEd::szConfigScrollEdSet = "ScrollEdSet";
const orxSTRING ScrollEd::szConfigSetContainer = "SetContainer";
const orxSTRING ScrollEd::szConfigSetContainerLine = "SetContainerLine";
const orxSTRING ScrollEd::szConfigSetContainerSize = "SetContainerSize";
const orxSTRING ScrollEd::szConfigSetContainerShow = "SetContainerShow";
const orxSTRING ScrollEd::szConfigSetContainerHide = "SetContainerHide";
const orxSTRING ScrollEd::szConfigEncryptSave = "EncryptSave";
const orxSTRING ScrollEd::szConfigZoom = "Zoom";
const orxSTRING ScrollEd::szConfigZoomLerp = "ZoomLerp";
const orxSTRING ScrollEd::szConfigZoomStep = "ZoomStep";
const orxSTRING ScrollEd::szConfigZoomMin = "ZoomMin";
const orxSTRING ScrollEd::szConfigZoomMax = "ZoomMax";
const orxSTRING ScrollEd::szConfigSelectionShader = "SelectionShader";
const orxSTRING ScrollEd::szConfigGainFocusFX = "GainFocusFX";
const orxSTRING ScrollEd::szConfigLoseFocusFX = "LoseFocusFX";
const orxSTRING ScrollEd::szConfigRotationSnap = "RotationSnap";
const orxSTRING ScrollEd::szConfigGridSize = "GridSize";
const orxSTRING ScrollEd::szConfigNameText = "NameText";
const orxSTRING ScrollEd::szConfigLayerText = "LayerText";
const orxSTRING ScrollEd::szConfigPropertyText = "PropertyText";
const orxSTRING ScrollEd::szConfigActionText = "ActionText";
const orxSTRING ScrollEd::szConfigLayerTextFormat = "LayerTextFormat";
const orxSTRING ScrollEd::szConfigColorTextFormat = "ColorTextFormat";
const orxSTRING ScrollEd::szConfigAlphaTextFormat = "AlphaTextFormat";
const orxSTRING ScrollEd::szConfigScaleTextFormat = "ScaleTextFormat";
const orxSTRING ScrollEd::szConfigRotationTextFormat= "RotationTextFormat";
const orxSTRING ScrollEd::szConfigPositionTextFormat= "PositionTextFormat";
const orxSTRING ScrollEd::szConfigLayerNumber = "LayerNumber";
const orxSTRING ScrollEd::szConfigLayerIndex = "LayerIndex";
const orxSTRING ScrollEd::szConfigDefaultCursor = "DefaultCursor";
const orxSTRING ScrollEd::szConfigMoveCursor = "MoveCursor";
const orxSTRING ScrollEd::szConfigScaleCursor = "ScaleCursor";
const orxSTRING ScrollEd::szConfigRotateCursor = "RotateCursor";
const orxSTRING ScrollEd::szConfigCursor = "Cursor";
const orxSTRING ScrollEd::szConfigGrid = "Grid";
const orxSTRING ScrollEd::szAutoSaveInterval = "AutoSaveInterval";
const orxSTRING ScrollEd::szLocaleBackup = "Backup";
const orxSTRING ScrollEd::szConfigButtonList = "ButtonList";
const orxSTRING ScrollEd::szConfigButtonBase = "Base";
const orxSTRING ScrollEd::szConfigButtonHighlight = "Highlight";
const orxSTRING ScrollEd::szConfigButtonActive = "Active";
const orxSTRING ScrollEd::szConfigButtonAction = "Action";
const orxSTRING ScrollEd::szConfigButtonCursor = "Cursor";
const orxSTRING ScrollEd::szConfigShaderCameraPos = "camerapos";
const orxSTRING ScrollEd::szConfigShaderCameraZoom = "camerazoom";
const orxSTRING ScrollEd::szConfigShaderColor = "color";
const orxSTRING ScrollEd::szConfigShaderTime = "time";
//! Static variables
ScrollEd *ScrollEd::spoInstance = orxNULL;
//! Code
class ScrollEdSet
{
public:
orxBANK *mpstObjectBank;
ScrollObject *mpoContainer;
const orxSTRING mzName;
};
ScrollEd &ScrollEd::GetInstance()
{
if(!spoInstance)
{
spoInstance = new ScrollEd();
}
return *spoInstance;
}
ScrollEd::ScrollEd() : mpstButtonBank(orxNULL), mpstSetBank(orxNULL), mu32SelectedSet(0), mpstGrid(orxNULL), mpstLayerText(orxNULL), mpstNameText(orxNULL),
mpstPropertyText(orxNULL), mpstBasicCursor(orxNULL), mpoSelectedModel(orxNULL), mpoCursorObject(orxNULL), mpoSelection(NULL),
mpstButtonHighlight(NULL), mzMapName(orxNULL), mfLocalTime(orxFLOAT_0), mfAutoSaveInterval(orxFLOAT_0),
mfAutoSaveTimeStamp(orxFLOAT_0), mfZoom(orxFLOAT_0), mfWorkRotation(orxFLOAT_0), mu32LayerIndex(0), mu32CursorObjectIndex(0),
mxFlags(FlagNone)
{
// Clears other members
orxVector_Copy(&mvWorkBase, &orxVECTOR_0);
orxVector_Copy(&mvWorkPosition, &orxVECTOR_0);
orxVector_Copy(&mvWorkScale, &orxVECTOR_0);
orxVector_Copy(&mvWorkSize, &orxVECTOR_0);
orxMemory_Zero(&mstButtonList, sizeof(orxLINKLIST));
}
ScrollEd::~ScrollEd()
{
}
orxSTATUS ScrollEd::Init()
{
orxSTATUS eResult;
// Gets game instance
ScrollBase &roGame = ScrollBase::GetInstance();
// Inits base game
roGame.SetEditorMode();
eResult = roGame.BaseInit();
// Valid?
if(eResult != orxSTATUS_FAILURE)
{
orxPARAM stParams;
orxCOLOR stColor;
// Loads config file
orxConfig_Load(szConfigFile);
// Enforces video mode
orxDisplay_SetVideoMode(orxNULL);
// Reloads inputs
orxInput_Load(orxSTRING_EMPTY);
// Has any locale language?
if(orxLocale_GetLanguageCount())
{
// Selects first available
orxLocale_SelectLanguage(orxLocale_GetLanguage(0));
}
// Pushes viewport section
orxConfig_PushSection(roGame.szConfigMainViewport);
// Has color?
if(orxConfig_HasValue("BackgroundColor"))
{
// Gets it
orxVector_Mulf(&stColor.vRGB, orxConfig_GetVector("BackgroundColor", &stColor.vRGB), orxCOLOR_NORMALIZER);
// Updates viewport color
orxViewport_SetBackgroundColor(roGame.GetMainViewport(), &stColor);
}
// Pops config section
orxConfig_PopSection();
// Asks for command line map parameter
orxMemory_Zero(&stParams, sizeof(orxPARAM));
stParams.pfnParser = StaticProcessParams;
stParams.u32Flags = orxPARAM_KU32_FLAG_NONE;
stParams.zShortName = szMapShortParam;
stParams.zLongName = szMapLongParam;
stParams.zShortDesc = szMapShortDesc;
stParams.zLongDesc = szMapLongDesc;
orxParam_Register(&stParams);
// Disables physics simulation while editing
orxPhysics_EnableSimulation(orxFALSE);
// Pushes editor section
orxConfig_PushSection(szConfigSectionEditor);
// Has default layer count?
if(orxConfig_HasValue(szConfigLayerNumber))
{
// Sets it
roGame.SetLayerNumber(orxConfig_GetU32(szConfigLayerNumber));
}
// Gets autosave interval
mfAutoSaveInterval = orxConfig_GetFloat(szAutoSaveInterval);
// Pops section
orxConfig_PopSection();
// Can load map?
if((roGame.SetMapName(mzMapName) != orxSTATUS_FAILURE) && (roGame.LoadMap() != orxSTATUS_FAILURE))
{
// Pushes editor section
orxConfig_PushSection(szConfigSectionEditor);
// Gets current layer
mu32LayerIndex = orxConfig_GetU32(szConfigLayerIndex);
// Clamps it
if(mu32LayerIndex >= roGame.GetLayerNumber())
{
mu32LayerIndex = roGame.GetLayerNumber() - 1;
}
// Pops previous section
orxConfig_PopSection();
// Updates layer
UpdateLayerDisplay();
// Inits sets
InitSets();
}
else
{
// Updates result
eResult = orxSTATUS_FAILURE;
}
// Successful?
if(eResult != orxSTATUS_FAILURE)
{
// Inits UI
if((eResult = InitUI()) != orxSTATUS_FAILURE)
{
// Is map defined?
if(GetMapName())
{
// Adds group to camera
orxCamera_AddGroupID(roGame.GetMainCamera(), orxString_GetID(orxOBJECT_KZ_DEFAULT_GROUP), orxFALSE);
// Registers update
eResult = orxClock_Register(orxClock_Get(orxCLOCK_KZ_CORE), StaticUpdate, orxNULL, orxMODULE_ID_MAIN, orxCLOCK_PRIORITY_NORMAL);
// Registers event handler
eResult = ((eResult != orxSTATUS_FAILURE) && (orxEvent_AddHandler(orxEVENT_TYPE_SHADER, StaticEventHandler) != orxSTATUS_FAILURE)) ? orxSTATUS_SUCCESS : orxSTATUS_FAILURE;
eResult = ((eResult != orxSTATUS_FAILURE) && (orxEvent_AddHandler(orxEVENT_TYPE_INPUT, StaticEventHandler) != orxSTATUS_FAILURE)) ? orxSTATUS_SUCCESS : orxSTATUS_FAILURE;
}
}
}
}
// Done!
return eResult;
}
orxSTATUS ScrollEd::Run()
{
orxSTATUS eResult = orxSTATUS_SUCCESS;
// Quiting?
if(orxInput_IsActive("Quit"))
{
// Updates result
eResult = orxSTATUS_FAILURE;
}
else
{
// Runs base game
ScrollBase::GetInstance().Run();
}
// Done!
return eResult;
}
void ScrollEd::Exit()
{
// Removes event handlers
orxEvent_RemoveHandler(orxEVENT_TYPE_INPUT, StaticEventHandler);
orxEvent_RemoveHandler(orxEVENT_TYPE_SHADER, StaticEventHandler);
// Exits UI
ExitUI();
// Exits sets
ExitSets();
// Exits from base game
ScrollBase::GetInstance().Exit();
}
void ScrollEd::Update(const orxCLOCK_INFO &_rstInfo)
{
orxFLOAT fZoom;
// Gets game instance
ScrollBase &roGame = ScrollBase::GetInstance();
// Not in game?
if(!TestFlags(FlagInGame))
{
// Hides object properties
SetPropertyText();
// Updates buttons
UpdateButtons(_rstInfo);
// Start game?
if(orxInput_IsActive(szInputStartGame) && orxInput_HasNewStatus(szInputStartGame))
{
// Removes selection
SetSelection();
// Deletes cursor
DeleteCursorObject();
// Hides basic cursor
ShowBasicCursor(orxFALSE);
// Sets game input set
orxInput_SelectSet(roGame.szInputSetGame);
// Updates status
SetFlags(FlagInGame);
// Updates layer display
UpdateLayerDisplay();
// Re-enables physics simulation
orxPhysics_EnableSimulation(orxTRUE);
// Selects camera section
orxConfig_PushSection(orxCamera_GetName(roGame.GetMainCamera()));
// Resets it
mfZoom = orxConfig_GetFloat(szConfigZoom);
// Pops config section
orxConfig_PopSection();
// Removes editor mode
roGame.SetEditorMode(orxFALSE);
// Saves map
SaveMap();
// Reloads it
roGame.LoadMap();
// Starts game
roGame.StartGame();
}
else
{
orxVECTOR vMousePos, vMouseMove;
orxBOOL bIsMouseInScope;
// Updates local time
mfLocalTime += _rstInfo.fDT;
// Uses autosave?
if(mfAutoSaveInterval > orxFLOAT_0)
{
// Is it time?
if(mfLocalTime >= mfAutoSaveTimeStamp + mfAutoSaveInterval)
{
// Saves backup
SaveMapBackup();
// Updates time stamp
mfAutoSaveTimeStamp = mfLocalTime;
}
}
// Gets mouse position
bIsMouseInScope = orxRender_GetWorldPosition(orxMouse_GetPosition(&vMousePos), orxNULL, &vMousePos) != orxNULL;
vMousePos.fZ = roGame.GetLayerDepth(mu32LayerIndex);
// In differential mode?
if(roGame.IsDifferentialMode())
{
// Gets depth corrected position
GetDepthCorrectedPosition(vMousePos.fZ, vMousePos);
}
// Gets mouse move
orxMouse_GetMoveDelta(&vMouseMove);
// Is set shown?
if(TestFlags(FlagSetShown))
{
// Action?
if(orxInput_IsActive(szInputAction))
{
const ScrollObject *poModel;
// Selects corresponding model
if((poModel = GetSetModel(vMousePos)))
{
// Selects it
mpoSelectedModel = poModel;
// Creates cursor from it
CreateCursorObject();
// Hides set
HideSet();
}
}
// Should hide it?
else if(orxInput_IsActive(szInputHideSet))
{
// Creates former cursor
CreateCursorObject();
// Hides selected set
HideSet();
}
// Next set?
else if(orxInput_IsActive(szInputNextSet))
{
// Deletes current cursor
DeleteCursorObject();
// Removes selection
SetSelection();
// Displays next set
ShowNextSet();
}
// Previous set?
else if(orxInput_IsActive(szInputPreviousSet))
{
// Deletes current cursor
DeleteCursorObject();
// Removes selection
SetSelection();
// Displays previous set
ShowPreviousSet();
}
}
else
{
// Has mouse in scope?
if(bIsMouseInScope)
{
// Zoom?
if(orxInput_IsActive(szInputZoom))
{
// Updates desired zoom
orxConfig_PushSection(szConfigSectionEditor);
mfZoom *= orxFLOAT_1 + (orxConfig_GetFloat(szConfigZoomStep) * -vMouseMove.fY) + (orxConfig_GetFloat(szConfigZoomStep) * vMouseMove.fX);
mfZoom = orxCLAMP(mfZoom, orxConfig_GetFloat(szConfigZoomMin), orxConfig_GetFloat(szConfigZoomMax));
orxConfig_PopSection();
}
// Pan?
else if(orxInput_IsActive(szInputPan))
{
orxVECTOR vPos, vMouseRelMove;
orxCAMERA *pstCamera;
// Gets camera
pstCamera = roGame.GetMainCamera();
// Updates mouse move with current zoom
orxVector_Divf(&vMouseRelMove, &vMouseMove, orxCamera_GetZoom(pstCamera));
// In differential mode?
if(roGame.IsDifferentialMode())
{
// Updates mouse relative move
orxVector_Divf(&vMouseRelMove, &vMouseRelMove, GetDepthCoef(roGame.GetLayerDepth(mu32LayerIndex)));
}
// Updates camera position
orxCamera_SetPosition(pstCamera, orxVector_Sub(&vPos, orxCamera_GetPosition(pstCamera, &vPos), &vMouseRelMove));
}
// Edit alpha?
else if(orxInput_IsActive(szInputEditAlpha) && mpoSelection)
{
// Action?
if(orxInput_IsActive(szInputAction))
{
orxCOLOR stColor;
// Gets selection object color
if(orxObject_HasColor(mpoSelection->GetOrxObject()))
{
orxObject_GetColor(mpoSelection->GetOrxObject(), &stColor);
}
else
{
roGame.GetObjectConfigColor(mpoSelection, stColor);
}
// Updates its alpha
stColor.fAlpha += orx2F(0.0025f) * vMouseMove.fX;
stColor.fAlpha = orxCLAMP(stColor.fAlpha, orxFLOAT_0, orxFLOAT_1);
// Sets selection object color
roGame.SetObjectConfigColor(mpoSelection, stColor);
}
// Shows selection's alpha property
DisplayObjectAlpha(mpoSelection);
}
// Edit color?
else if((orxInput_IsActive(szInputEditRed) || orxInput_IsActive(szInputEditGreen) || orxInput_IsActive(szInputEditBlue)) && mpoSelection)
{
// Action?
if(orxInput_IsActive(szInputAction))
{
orxCOLOR stColor;
// Gets selection object color
if(orxObject_HasColor(mpoSelection->GetOrxObject()))
{
orxObject_GetColor(mpoSelection->GetOrxObject(), &stColor);
}
else
{
roGame.GetObjectConfigColor(mpoSelection, stColor);
}
// Edit red?
if(orxInput_IsActive(szInputEditRed))
{
stColor.vRGB.fR += orx2F(0.0025f) * vMouseMove.fX;
stColor.vRGB.fR = orxCLAMP(stColor.vRGB.fR, orxFLOAT_0, orxFLOAT_1);
}
// Edit green?
if(orxInput_IsActive(szInputEditGreen))
{
stColor.vRGB.fG += orx2F(0.0025f) * vMouseMove.fX;
stColor.vRGB.fG = orxCLAMP(stColor.vRGB.fG, orxFLOAT_0, orxFLOAT_1);
}
// Edit blue?
if(orxInput_IsActive(szInputEditBlue))
{
stColor.vRGB.fB += orx2F(0.0025f) * vMouseMove.fX;
stColor.vRGB.fB = orxCLAMP(stColor.vRGB.fB, orxFLOAT_0, orxFLOAT_1);
}
// Sets selection object color
roGame.SetObjectConfigColor(mpoSelection, stColor);
}
// Shows selection's color property
DisplayObjectColor(mpoSelection);
}
// Copy?
else if(orxInput_IsActive(szInputCopy) && orxInput_HasNewStatus(szInputCopy))
{
orxOBJECT *pstPick;
ScrollObject *poObject;
// Picks object
pstPick = PickObject(vMousePos);
// Clears selected model
mpoSelectedModel = orxNULL;
// Found?
if(pstPick && (poObject = (ScrollObject *)orxObject_GetUserData(pstPick)))
{
// Creates cursor from it
CreateCursorObject(poObject);
}
else
{
// Deletes cursor
DeleteCursorObject();
// Removes selection
SetSelection();
}
}
// Action?
else if(orxInput_IsActive(szInputAction))
{
// Has cursor?
if(mpoCursorObject)
{
// First time?
if(orxInput_HasNewStatus(szInputAction))
{
// Adds object
AddObject(mpoCursorObject);
}
}
else
{
// First time?
if(orxInput_HasNewStatus(szInputAction))
{
orxOBJECT *pstPick;
// Gets object in current layer
pstPick = PickObject(vMousePos);
// Selects it
SetSelection(pstPick ? (ScrollObject *)orxObject_GetUserData(pstPick) : orxNULL);
// Deletes cursor object
DeleteCursorObject();
}
// Has selection?
if(mpoSelection)
{
// Depending on mode
switch(GetFlags(MaskToggle))
{
// Move
case FlagToggleMove:
{
// First time?
if(orxInput_HasNewStatus(szInputAction))
{
// Stores current mouse & object positions
orxVector_Copy(&mvWorkBase, &vMousePos);
orxObject_GetPosition(mpoSelection->GetOrxObject(), &mvWorkPosition);
}
else
{
orxVECTOR vPos;
orxFLOAT fSnap;
// Gets object position
orxObject_GetPosition(mpoSelection->GetOrxObject(), &vPos);
// Pushes editor section
orxConfig_PushSection(szConfigSectionEditor);
// Snap?
if(TestFlags(FlagSnap) && ((fSnap = orxConfig_GetFloat(szConfigGridSize)) > orxFLOAT_0))
{
// Updates position
orxVector_Set(&vPos, orxMath_Round((mvWorkPosition.fX + vMousePos.fX - mvWorkBase.fX) / fSnap) * fSnap, orxMath_Round((mvWorkPosition.fY + vMousePos.fY - mvWorkBase.fY) / fSnap) * fSnap, vPos.fZ);
}
else
{
// Updates position
orxVector_Set(&vPos, orxMath_Round(mvWorkPosition.fX + vMousePos.fX - mvWorkBase.fX), orxMath_Round(mvWorkPosition.fY + vMousePos.fY - mvWorkBase.fY), vPos.fZ);
}
// Pops to previous section
orxConfig_PopSection();
// Updates its position
orxObject_SetPosition(mpoSelection->GetOrxObject(), &vPos);
}
break;
}
// Scale
case FlagToggleScale:
{
// First time?
if(orxInput_HasNewStatus(szInputAction))
{
orxOBJECT *pstPick;
// Gets object in current layer
pstPick = PickObject(vMousePos);
// Selects it
SetSelection(pstPick ? (ScrollObject *)orxObject_GetUserData(pstPick) : orxNULL);
// Deletes cursor object
DeleteCursorObject();
}
// Has selection?
if(mpoSelection)
{
orxOBJECT *pstOrxObject;
// Gets its internal object
pstOrxObject = mpoSelection->GetOrxObject();
// First activation?
if(orxInput_HasNewStatus(szInputAction))
{
orxVECTOR vTemp;
// Stores current work info
orxVector_FromCartesianToSpherical(&mvWorkBase, orxVector_Sub(&vTemp, &vMousePos, orxObject_GetPosition(pstOrxObject, &vTemp)));
orxObject_GetScale(pstOrxObject, &mvWorkScale);
orxObject_GetSize(pstOrxObject, &mvWorkSize);
mfWorkRotation = orxObject_GetRotation(pstOrxObject);
}
else
{
orxVECTOR vNewBase, vScale;
// Pushes editor section
orxConfig_PushSection(szConfigSectionEditor);
// Gets spherical diff vector
orxVector_FromCartesianToSpherical(&vNewBase, orxVector_Sub(&vNewBase, &vMousePos, orxObject_GetPosition(pstOrxObject, &vNewBase)));
// Gets values
vScale.fX = (orxMath_Cos(vNewBase.fTheta - mfWorkRotation) * vNewBase.fRho) / (orxMath_Cos(mvWorkBase.fTheta - mfWorkRotation) * mvWorkBase.fRho);
vScale.fY = (orxMath_Sin(vNewBase.fTheta - mfWorkRotation) * vNewBase.fRho) / (orxMath_Sin(mvWorkBase.fTheta - mfWorkRotation) * mvWorkBase.fRho);
// Applies old scale
orxVector_Mul(&vScale, &vScale, &mvWorkScale);
// Snap?
if(TestFlags(FlagSnap))
{
// Updates scale
orxVector_Floor(&vScale, &vScale);
// Needs correction
if(vScale.fX == orxFLOAT_0)
{
vScale.fX = orxFLOAT_1;
}
if(vScale.fY == orxFLOAT_0)
{
vScale.fY = orxFLOAT_1;
}
}
else
{
// Gets final size
vScale.fX *= mvWorkSize.fX;
vScale.fY *= mvWorkSize.fY;
// Rounds it
orxVector_Floor(&vScale, &vScale);
// Gets final scale
vScale.fX /= mvWorkSize.fX;
vScale.fY /= mvWorkSize.fY;
// Corrects them if too small
if(orxMath_Abs(vScale.fX) <= orx2F(0.01f))
{
vScale.fX = orx2F(0.01f);
}
if(orxMath_Abs(vScale.fY) <= orx2F(0.01f))
{
vScale.fY = orx2F(0.01f);
}
vScale.fZ = orxFLOAT_1;
}
// Scales object
orxObject_SetScale(pstOrxObject, &vScale);
// Uses tiling?
if(mpoSelection->TestFlags(ScrollObject::FlagTiled))
{
// Sets its repeat factor
orxObject_SetRepeat(pstOrxObject, orxMath_Abs(vScale.fX), orxMath_Abs(vScale.fY));
}
else
{
// Resets its repeat factor
orxObject_SetRepeat(pstOrxObject, orxFLOAT_1, orxFLOAT_1);
}
// Restores map section
orxConfig_PopSection();
}
// Displays its name
DisplayObjectName(mpoSelection, orxTRUE);
}
break;
}
// Rotate
case FlagToggleRotate:
{
// First time?
if(orxInput_HasNewStatus(szInputAction))
{
orxOBJECT *pstPick;
// Gets object in current layer
pstPick = PickObject(vMousePos);
// Selects it
SetSelection(pstPick ? (ScrollObject *)orxObject_GetUserData(pstPick) : orxNULL);
// Deletes cursor object
DeleteCursorObject();
}
// Has selection?
if(mpoSelection)
{
orxOBJECT *pstOrxObject;
// Gets its internal object
pstOrxObject = mpoSelection->GetOrxObject();
// First activation?
if(orxInput_HasNewStatus(szInputAction))
{
orxVECTOR vTemp;
// Stores current work info
orxVector_FromCartesianToSpherical(&mvWorkBase, orxVector_Sub(&vTemp, &vMousePos, orxObject_GetPosition(pstOrxObject, &vTemp)));
mfWorkRotation = orxObject_GetRotation(pstOrxObject);
}
else
{
orxVECTOR vNewBase;
orxFLOAT fRotation, fSnap;
// Pushes editor section
orxConfig_PushSection(szConfigSectionEditor);
// Gets spherical diff vector
orxVector_FromCartesianToSpherical(&vNewBase, orxVector_Sub(&vNewBase, &vMousePos, orxObject_GetPosition(pstOrxObject, &vNewBase)));
// Updates rotation
fRotation = mfWorkRotation + vNewBase.fTheta - mvWorkBase.fTheta;
// Snap?
if(TestFlags(FlagSnap) && ((fSnap = orxConfig_GetFloat(szConfigRotationSnap)) > orxFLOAT_0))
{
// Updates snapping value
fSnap *= orxMATH_KF_DEG_TO_RAD;
// Updates rotation
fRotation /= fSnap;
fRotation = orxMath_Round(fRotation);
fRotation *= fSnap;
}
// Rotates object
orxObject_SetRotation(pstOrxObject, fRotation);
// Restores map section
orxConfig_PopSection();
}
}
break;
}
default:
{
orxASSERT(0 && "Invalid control mode (%#X).", GetFlags(MaskToggle));
break;
}
}
}
}
}
}
// Update control toggles
UpdateToggle(szInputToggleMove, FlagToggleMove);
UpdateToggle(szInputToggleScale, FlagToggleScale);
UpdateToggle(szInputToggleRotate, FlagToggleRotate);
// Screenshot?
if(orxInput_IsActive(szInputScreenshot) && orxInput_HasNewStatus(szInputScreenshot))
{
// Captures a screenshot
orxScreenshot_Capture();
}
// Toggle snap?
if(orxInput_IsActive(szInputToggleSnap) && orxInput_HasNewStatus(szInputToggleSnap))
{
// Swap its flag
SwapFlags(FlagSnap);
}
// Toggle grid?
if(orxInput_IsActive(szInputToggleGrid) && orxInput_HasNewStatus(szInputToggleGrid))
{
// Has grid?
if(mpstGrid)
{
// Updates shader status
orxObject_EnableShader(mpstGrid, !orxObject_IsShaderEnabled(mpstGrid));
}
}
// Previous layer?
if(orxInput_IsActive(szInputPreviousLayer))
{
// Updates current layer
mu32LayerIndex = (mu32LayerIndex == 0) ? roGame.GetLayerNumber() - 1 : mu32LayerIndex - 1;
// Updates layer display
UpdateLayerDisplay();
}
// Next layer?
else if(orxInput_IsActive(szInputNextLayer))
{
// Updates current layer
mu32LayerIndex = (mu32LayerIndex >= roGame.GetLayerNumber() - 1) ? 0 : mu32LayerIndex + 1;
// Updates layer display
UpdateLayerDisplay();
}
// Next set?
else if(orxInput_IsActive(szInputNextSet))
{
// Deletes current cursor
DeleteCursorObject();
// Removes selection
SetSelection();
// Displays next set
ShowNextSet();
}
// Previous set?
else if(orxInput_IsActive(szInputPreviousSet))
{
// Deletes current cursor
DeleteCursorObject();
// Removes selection
SetSelection();
// Displays previous set
ShowPreviousSet();
}
// Clear selection?
else if(orxInput_IsActive(szInputClearSelection) && orxInput_HasNewStatus(szInputClearSelection))
{
// Clears selected model
mpoSelectedModel = orxNULL;
// Removes selection
SetSelection();
// Deletes cursor
DeleteCursorObject();
}
// Soft clear selection?
else if(orxInput_IsActive(szInputSoftClearSelection) && orxInput_HasNewStatus(szInputSoftClearSelection))
{
// Clears selected model
mpoSelectedModel = orxNULL;
// Removes selection
SetSelection();
// Not a copy?
if(!TestFlags(FlagUsingCopy))
{
// Deletes cursor
DeleteCursorObject();
}
}
// Delete?
if(orxInput_IsActive(szInputDelete))
{
// Has selection?
if(mpoSelection)
{
// Deletes it
RemoveObject(mpoSelection);
}
}
// Antialiasing?
if(orxInput_IsActive(szInputAntialiasing) && orxInput_HasNewStatus(szInputAntialiasing))
{
// Has selection?
if(mpoSelection)
{
// Smoothed?
if(mpoSelection->TestFlags(ScrollObject::FlagSmoothed))
{
// Removes its smoothing
orxObject_SetSmoothing(mpoSelection->GetOrxObject(), orxDISPLAY_SMOOTHING_OFF);
// Updates its flags
mpoSelection->SetFlags(ScrollObject::FlagNone, ScrollObject::FlagSmoothed);
}
else
{
// Activates its smoothing
orxObject_SetSmoothing(mpoSelection->GetOrxObject(), orxDISPLAY_SMOOTHING_ON);
// Updates its flags
mpoSelection->SetFlags(ScrollObject::FlagSmoothed);
}
}
}
// Tiling?
if(orxInput_IsActive(szInputTiling) && orxInput_HasNewStatus(szInputTiling))
{
// Has selection?
if(mpoSelection)
{
// Was using tiling?
if(mpoSelection->TestFlags(ScrollObject::FlagTiled))
{
// Resets its repeat factor
orxObject_SetRepeat(mpoSelection->GetOrxObject(), orxFLOAT_1, orxFLOAT_1);
// Updates its flags
mpoSelection->SetFlags(ScrollObject::FlagNone, ScrollObject::FlagTiled);
}
else
{
orxVECTOR vScale;
// Gets object scale
orxObject_GetScale(mpoSelection->GetOrxObject(), &vScale);
// Sets its repeat factor
orxObject_SetRepeat(mpoSelection->GetOrxObject(), orxMath_Abs(vScale.fX), orxMath_Abs(vScale.fY));
// Updates its flags
mpoSelection->SetFlags(ScrollObject::FlagTiled);
}
}
}
// Differential scrolling?
if(orxInput_IsActive(szInputDifferential) && orxInput_HasNewStatus(szInputDifferential))
{
// Swaps differential mode
roGame.SetDifferentialMode(!roGame.IsDifferentialMode());
// Updates layer display
UpdateLayerDisplay();
// Is in differential scrolling?
if(roGame.IsDifferentialMode())
{
// Has name text?
if(mpstNameText)
{
// Enforces differential flags
orxStructure_SetFlags(orxOBJECT_GET_STRUCTURE(mpstNameText, FRAME), orxFRAME_KU32_FLAG_SCROLL_X|orxFRAME_KU32_FLAG_SCROLL_Y, orxFRAME_KU32_FLAG_NONE);
}
// Has property text?
if(mpstPropertyText)
{
// Enforces differential flags
orxStructure_SetFlags(orxOBJECT_GET_STRUCTURE(mpstPropertyText, FRAME), orxFRAME_KU32_FLAG_SCROLL_X|orxFRAME_KU32_FLAG_SCROLL_Y, orxFRAME_KU32_FLAG_NONE);
}
}
else
{
// Has name text?
if(mpstNameText)
{
// Removes differential flags
orxStructure_SetFlags(orxOBJECT_GET_STRUCTURE(mpstNameText, FRAME), orxFRAME_KU32_FLAG_NONE, orxFRAME_KU32_FLAG_SCROLL_X|orxFRAME_KU32_FLAG_SCROLL_Y);
}
// Has property text?
if(mpstPropertyText)
{
// Enforces differential flags
orxStructure_SetFlags(orxOBJECT_GET_STRUCTURE(mpstPropertyText, FRAME), orxFRAME_KU32_FLAG_NONE, orxFRAME_KU32_FLAG_SCROLL_X|orxFRAME_KU32_FLAG_SCROLL_Y);
}
}
}
// Toggle full screen?
if(orxInput_IsActive(szInputToggleFullScreen) && orxInput_HasNewStatus(szInputToggleFullScreen))
{
// Toggles full screen
orxDisplay_SetFullScreen(!orxDisplay_IsFullScreen());
}
// Reload history?
if(orxInput_IsActive(szInputReloadHistory) && orxInput_HasNewStatus(szInputReloadHistory))
{
// Reloads config history
orxConfig_ReloadHistory();
}
// Save?
if(orxInput_IsActive(szInputSave) && orxInput_HasNewStatus(szInputSave))
{
// Save maps
SaveMap();
}
// Reload?
if(orxInput_IsActive(szInputReload) && orxInput_HasNewStatus(szInputReload))
{
// Removes selection
SetSelection();
// Deletes cursor
DeleteCursorObject();
// Reloads map
roGame.ResetMap();
// Updates layer
UpdateLayerDisplay();
// For all buttons
for(ButtonData *pstButtonData = (ButtonData *)orxLinkList_GetFirst(&mstButtonList);
pstButtonData;
pstButtonData = (ButtonData *)orxLinkList_GetNext(&pstButtonData->mstNode))
{
// Is active button?
if(!orxString_Compare(pstButtonData->mzName, pstButtonData->mzActive))
{
// Matches?
if(!orxString_Compare(szInputDifferential, pstButtonData->mzAction))
{
// Updates its status
orxObject_Enable(pstButtonData->mpstObject, roGame.IsDifferentialMode());
break;
}
}
}
}
}
}
}
else
{
// Stop game?
if(orxInput_IsActive(szInputStopGame) && orxInput_HasNewStatus(szInputStopGame))
{
// Stops game
roGame.StopGame();
// Restores editor mode
roGame.SetEditorMode();
// Disables physics simulation
orxPhysics_EnableSimulation(orxFALSE);
// Restores map section
orxConfig_SelectSection(ScrollBase::szConfigSectionMap);
// Updates status
SetFlags(FlagNone, FlagInGame);
// Removes selection
SetSelection();
// Deletes cursor
DeleteCursorObject();
// Reloads map
roGame.LoadMap();
// Updates layer
UpdateLayerDisplay();
// Restores input set
orxInput_SelectSet(szInputSetEditor);
}
}
// No zoom yet?
if(mfZoom == orxFLOAT_0)
{
// Updates it
mfZoom = orxCamera_GetZoom(roGame.GetMainCamera());
}
// Reset zoom?
if(orxInput_IsActive(szInputResetZoom))
{
// Selects camera section
orxConfig_PushSection(orxCamera_GetName(roGame.GetMainCamera()));
// Resets it
mfZoom = orxConfig_GetFloat(szConfigZoom);
if(mfZoom <= orxFLOAT_0)
{
mfZoom = orxFLOAT_1;
}
// Pops config section
orxConfig_PopSection();
}
// Smoothes camera zoom
orxConfig_PushSection(szConfigSectionEditor);
fZoom = orxLERP(orxCamera_GetZoom(roGame.GetMainCamera()), mfZoom, orxConfig_GetFloat(szConfigZoomLerp) * _rstInfo.fDT);
orxConfig_PopSection();
// Updates it
orxCamera_SetZoom(roGame.GetMainCamera(), fZoom);
// Update UI
UpdateUI(_rstInfo);
}
orxBOOL ScrollEd::MapSaveFilter(const orxSTRING _zSectionName, const orxSTRING _zKeyName, const orxSTRING _zFileName, orxBOOL _bUseEncryption)
{
orxBOOL bResult;
// Is editor section layer count or encrypt save?
if(!orxString_Compare(_zSectionName, szConfigSectionEditor)
&& (!_zKeyName
|| !orxString_Compare(_zKeyName, szConfigLayerIndex)
|| !orxString_Compare(_zKeyName, szConfigEncryptSave)))
{
bResult = orxTRUE;
}
else
{
bResult = orxFALSE;
}
// Done!
return bResult;
}
orxSTATUS ScrollEd::SaveMap() const
{
orxBOOL bEncrypt;
// Gets game instance
ScrollBase &roGame = ScrollBase::GetInstance();
// Pushes editor section
orxConfig_PushSection(szConfigSectionEditor);
// Gets encryption
bEncrypt = orxConfig_GetBool(szConfigEncryptSave);
// Sets layer index
orxConfig_SetU32(szConfigLayerIndex, mu32LayerIndex);
// Pops previous section
orxConfig_PopSection();
// Saves map
return roGame.SaveMap(bEncrypt, StaticMapSaveFilter);
}
orxSTATUS ScrollEd::SaveMapBackup() const
{
orxCHAR acBuffer[256];
orxBOOL bEncrypt;
orxSTRING zMapName;
orxSTATUS eResult;
// Gets game instance
ScrollBase &roGame = ScrollBase::GetInstance();
// Pushes editor section
orxConfig_PushSection(szConfigSectionEditor);
// Gets encryption
bEncrypt = orxConfig_GetBool(szConfigEncryptSave);
// Sets layer index
orxConfig_SetU32(szConfigLayerIndex, mu32LayerIndex);
// Pops previous section
orxConfig_PopSection();
// Gets current map name
zMapName = orxString_Duplicate(roGame.GetMapName());
// Sets backup name
orxString_NPrint(acBuffer, 256, "%s-%d.bak", zMapName, orxSystem_GetRealTime());
acBuffer[255] = orxCHAR_NULL;
roGame.SetMapName(acBuffer);
// Saves backup
eResult = SaveMap();
// Successful?
if(eResult != orxSTATUS_FAILURE)
{
// Adds action display
AddActionDisplay(orxLocale_GetString(szLocaleBackup));
}
// Restores map name
roGame.SetMapName(zMapName);
// Deletes local copy
orxString_Delete(zMapName);
// Done!
return eResult;
}
orxSTATUS orxFASTCALL ScrollEd::StaticProcessParams(orxU32 _u32ParamCount, const orxSTRING _azParams[])
{
orxSTATUS eResult;
// Has a valid map parameter?
if(_u32ParamCount >= 2)
{
// Stores map's name
ScrollEd::GetInstance().SetMapName(_azParams[1]);
// Updates result
eResult = orxSTATUS_SUCCESS;
}
else
{
// Updates result
eResult = orxSTATUS_FAILURE;
}
// Done!
return eResult;
}
orxBOOL orxFASTCALL ScrollEd::StaticMapSaveFilter(const orxSTRING _zSectionName, const orxSTRING _zKeyName, const orxSTRING _zFileName, orxBOOL _bUseEncryption)
{
ScrollEd &roEditor = GetInstance();
// Calls map save filter
return roEditor.MapSaveFilter(_zSectionName, _zKeyName, _zFileName, _bUseEncryption);
}
orxSTATUS ScrollEd::StaticInit()
{
orxSTATUS eResult;
ScrollEd &roEditor = GetInstance();
// Calls init method
eResult = roEditor.Init();
// Done!
return eResult;
}
orxSTATUS ScrollEd::StaticRun()
{
orxSTATUS eResult;
ScrollEd &roEditor = GetInstance();
// Calls run method
eResult = roEditor.Run();
// Done!
return eResult;
}
void ScrollEd::StaticExit()
{
ScrollEd &roEditor = GetInstance();
// Calls exit method
roEditor.Exit();
}
void orxFASTCALL ScrollEd::StaticUpdate(const orxCLOCK_INFO *_pstInfo, void *_pstContext)
{
ScrollEd &roEditor = GetInstance();
// Calls base method
roEditor.Update(*_pstInfo);
}
// Event handler
orxSTATUS orxFASTCALL ScrollEd::StaticEventHandler(const orxEVENT *_pstEvent)
{
orxSTATUS eResult = orxSTATUS_SUCCESS;
// Depending on event type
switch(_pstEvent->eType)
{
// Shader
case orxEVENT_TYPE_SHADER:
{
orxSHADER_EVENT_PAYLOAD *pstPayload;
// Get game instance
ScrollBase &roGame = ScrollBase::GetInstance();
// Checks
orxASSERT(_pstEvent->eID == orxSHADER_EVENT_SET_PARAM);
// Gets its payload
pstPayload = (orxSHADER_EVENT_PAYLOAD *)_pstEvent->pstPayload;
// Camera zoom?
if(!orxString_Compare(pstPayload->zParamName, szConfigShaderCameraZoom))
{
// Updates its value
pstPayload->fValue = orxCamera_GetZoom(roGame.GetMainCamera());
}
// Camera position?
else if(!orxString_Compare(pstPayload->zParamName, szConfigShaderCameraPos))
{
// Updates its value
orxCamera_GetPosition(roGame.GetMainCamera(), &pstPayload->vValue);
}
// Color?
else if(!orxString_Compare(pstPayload->zParamName, szConfigShaderColor))
{
// Does object has color?
if(orxObject_HasColor(orxOBJECT(_pstEvent->hSender)))
{
orxCOLOR stColor;
// Gets it
orxObject_GetColor(orxOBJECT(_pstEvent->hSender), &stColor);
// Updates shader's value
orxVector_Copy(&pstPayload->vValue, &stColor.vRGB);
}
else
{
// Updates shader's value
orxVector_SetAll(&pstPayload->vValue, orxFLOAT_1);
}
}
// Time?
else if(!orxString_Compare(pstPayload->zParamName, szConfigShaderTime))
{
// Updates its value
pstPayload->fValue = ScrollEd::GetInstance().mfLocalTime;
}
break;
}
// Input
case orxEVENT_TYPE_INPUT:
{
// Is on?
if(_pstEvent->eID == orxINPUT_EVENT_ON)
{
// Not game running?
if(!ScrollBase::GetInstance().IsGameRunning())
{
ButtonData *pstButtonData;
orxINPUT_EVENT_PAYLOAD *pstPayload;
// Gets instance
ScrollEd &roEditor = GetInstance();
// Gets its payload
pstPayload = (orxINPUT_EVENT_PAYLOAD *)_pstEvent->pstPayload;
// No set shown?
if(!roEditor.TestFlags(ScrollEd::FlagSetShown))
{
// Has localized description?
if(orxLocale_HasString(pstPayload->zInputName))
{
// Display it
roEditor.AddActionDisplay(orxLocale_GetString(pstPayload->zInputName));
}
}
// For all buttons
for(pstButtonData = (ButtonData *)orxLinkList_GetFirst(&roEditor.mstButtonList);
pstButtonData;
pstButtonData = (ButtonData *)orxLinkList_GetNext(&pstButtonData->mstNode))
{
// Is active button?
if(!orxString_Compare(pstButtonData->mzName, pstButtonData->mzActive))
{
// Matches?
if(!orxString_Compare(pstPayload->zInputName, pstButtonData->mzAction))
{
// Updates its status
orxObject_Enable(pstButtonData->mpstObject, !orxObject_IsEnabled(pstButtonData->mpstObject));
break;
}
}
}
}
}
break;
}
default:
{
break;
}
}
// Done!
return eResult;
}
void ScrollEd::Execute(int argc, char **argv)
{
// Makes sure the game instance has been created
ScrollBase::GetInstance();
// Executes orx
orx_Execute(argc, argv, StaticInit, StaticRun, StaticExit);
}
orxSTATUS ScrollEd::SetMapName(const orxSTRING _zMapName)
{
if(mzMapName)
{
orxString_Delete(mzMapName);
mzMapName = orxNULL;
}
if(_zMapName)
{
mzMapName = orxString_Duplicate(_zMapName);
}
return orxSTATUS_SUCCESS;
}
const orxSTRING ScrollEd::GetMapName() const
{
return mzMapName;
}
orxSTATUS ScrollEd::InitSets()
{
orxVECTOR vFXOffest;
orxS32 s32ContainerSize;
// Gets game instance
ScrollBase &roGame = ScrollBase::GetInstance();
// Pushes editor section
orxConfig_PushSection(szConfigSectionEditor);
// Gets container size
s32ContainerSize = orxConfig_GetS32(szConfigSetContainerSize);
// Pops config section
orxConfig_PopSection();
// Gets FX offset
orxDisplay_GetScreenSize(&vFXOffest.fX, &vFXOffest.fY);
vFXOffest.fY = vFXOffest.fZ = orxFLOAT_0;
// Pushes set container show section
orxConfig_PushSection(szConfigSetContainerShow);
// Updates its end value
orxConfig_SetVector("EndValue", &vFXOffest);
// Pops config section
orxConfig_PopSection();
// Pushes set container hide section
orxConfig_PushSection(szConfigSetContainerHide);
// Updates its end value
orxConfig_SetVector("EndValue", orxVector_Neg(&vFXOffest, &vFXOffest));
// Pops config section
orxConfig_PopSection();
// Creates set bank
mpstSetBank = orxBank_Create(32, sizeof(ScrollEdSet), orxBANK_KU32_FLAG_NONE, orxMEMORY_TYPE_MAIN);
// For all config sections
for(orxS32 i = 0, s32SectionCount = orxConfig_GetSectionCount();
i < s32SectionCount;
i++)
{
const orxSTRING zSection;
// Gets its name
zSection = orxConfig_GetSection(i);
// Pushes it
orxConfig_PushSection(zSection);
// Has ScrollEd type and a graphic?
if(orxConfig_HasValue(szConfigScrollEdSet) && orxConfig_HasValue("Graphic"))
{
orxCHAR zInstanceName[32];
const orxSTRING zSet;
ScrollEdSet *poSelectedSet = orxNULL;
ScrollObject *poModel;
// Gets its type
zSet = orxConfig_GetString(szConfigScrollEdSet);
// For all existing sets
for(ScrollEdSet *poSet = (ScrollEdSet *)orxBank_GetNext(mpstSetBank, orxNULL);
poSet;
poSet = (ScrollEdSet *)orxBank_GetNext(mpstSetBank, poSet))
{
// Matches?
if(!orxString_Compare(zSet, poSet->mzName))
{
// Selects it
poSelectedSet = poSet;
break;
}
}
// No set selected?
if(!poSelectedSet)
{
orxCHAR zInstanceName[32];
orxVECTOR vSize;
// Creates a new set
poSelectedSet = (ScrollEdSet *)orxBank_Allocate(mpstSetBank);
// Inits it
poSelectedSet->mpstObjectBank = orxBank_Create(64, sizeof(ScrollObject *), orxBANK_KU32_FLAG_NONE, orxMEMORY_TYPE_MAIN);
poSelectedSet->mpoContainer = roGame.CreateObject(szConfigSetContainer, ScrollObject::FlagNone, roGame.GetNewObjectName(zInstanceName, orxTRUE));
poSelectedSet->mzName = orxString_Duplicate(zSet);
poSelectedSet->mpoContainer->PushConfigSection(orxTRUE);
orxConfig_SetBool(ScrollBase::szConfigNoSave, orxTRUE);
poSelectedSet->mpoContainer->PopConfigSection();
// Gets its size
orxObject_GetScale(poSelectedSet->mpoContainer->GetOrxObject(), &vSize);
// For all cells
for(orxS32 j = 1; j < s32ContainerSize; j++)
{
orxVECTOR vPosition, vScale;
orxOBJECT *poLine;
// Creates horizontal line
poLine = orxObject_CreateFromConfig(szConfigSetContainerLine);
// Updates its parent
orxObject_SetParent(poLine, poSelectedSet->mpoContainer->GetOrxObject());
orxObject_SetOwner(poLine, poSelectedSet->mpoContainer->GetOrxObject());
// Updates its position
orxVector_Set(&vPosition, orxFLOAT_0, orxS2F(j) / orxS2F(s32ContainerSize), orx2F(-0.0002f));
orxObject_SetPosition(poLine, &vPosition);
// Updates its scale
orxVector_Set(&vScale, orxFLOAT_1, orxFLOAT_1 / vSize.fY, orxFLOAT_1);
orxObject_SetScale(poLine, &vScale);
// Creates vertical line
poLine = orxObject_CreateFromConfig(szConfigSetContainerLine);
// Updates its parent
orxObject_SetParent(poLine, poSelectedSet->mpoContainer->GetOrxObject());
orxObject_SetOwner(poLine, poSelectedSet->mpoContainer->GetOrxObject());
// Updates its position
orxVector_Set(&vPosition, orxS2F(j) / orxS2F(s32ContainerSize), orxFLOAT_0, orx2F(-0.0002f));
orxObject_SetPosition(poLine, &vPosition);
// Updates its scale
orxVector_Set(&vScale, orxFLOAT_1 / vSize.fX, orxFLOAT_1, orxFLOAT_1);
orxObject_SetScale(poLine, &vScale);
}
}
// Creates model
poModel = CreateModel(zSection, roGame.GetNewObjectName(zInstanceName, orxTRUE));
// Valid?
if(poModel)
{
orxVECTOR vSize;
// Gets model size
if(orxObject_GetSize(poModel->GetOrxObject(), &vSize))
{
orxVECTOR vPosition, vContainerScale, vFitScale, vScale, vPivot, vOffset;
orxS32 s32ModelIndex;
// Fixes Z dimension
vSize.fZ = orxFLOAT_1;
// Gets model's index
s32ModelIndex = orxBank_GetCount(poSelectedSet->mpstObjectBank);
// Stores it
*((ScrollObject **)orxBank_Allocate(poSelectedSet->mpstObjectBank)) = poModel;
// Sets container as parent
orxObject_SetParent(poModel->GetOrxObject(), poSelectedSet->mpoContainer->GetOrxObject());
// Gets container scale
orxVector_Rec(&vContainerScale, orxObject_GetScale(poSelectedSet->mpoContainer->GetOrxObject(), &vContainerScale));
// Gets anisotropic scale
orxVector_Div(&vFitScale, orxVector_Divf(&vFitScale, orxVector_Set(&vFitScale, orxFLOAT_1, orxFLOAT_1, orxS2F(s32ContainerSize)), orxS2F(s32ContainerSize)), &vSize);
orxVector_Set(&vScale, orxMIN(vContainerScale.fX, orxMIN(vFitScale.fX, vFitScale.fY)) - orx2F(0.005f) * vContainerScale.fX, orxMIN(vContainerScale.fY, orxMIN(vFitScale.fX, vFitScale.fY)) - orx2F(0.005f) * vContainerScale.fY, orxFLOAT_1);
// Applies scale
orxObject_SetScale(poModel->GetOrxObject(), &vScale);
// Gets offset
orxVector_Sub(&vFitScale, &vFitScale, &vScale);
orxVector_Set(&vOffset, orx2F(0.5f) * orxMAX(orxFLOAT_0, vFitScale.fX) * vSize.fX, orx2F(0.5f) * orxMAX(orxFLOAT_0, vFitScale.fY) * vSize.fY, orx2F(-0.0001f));
// Gets object's scaled pivot
orxObject_GetPivot(poModel->GetOrxObject(), &vPivot);
orxVector_Add(&vOffset, &vOffset, orxVector_Mul(&vPivot, &vPivot, &vScale));
// Gets grid position
orxVector_Set(&vPosition, orxS2F(s32ModelIndex % s32ContainerSize), orxS2F(s32ModelIndex / s32ContainerSize), orxFLOAT_0);
// Gets position in container space
orxVector_Add(&vPosition, orxVector_Divf(&vPosition, &vPosition, orxS2F(s32ContainerSize)), &vOffset);
// Applies it
orxObject_SetPosition(poModel->GetOrxObject(), &vPosition);
}
else
{
// Deletes model
roGame.DeleteObject(poModel);
}
}
else
{
// Logs message
orxLOG("Couldn't create a model object <%s> to store in set <%s>.", zSection, zSet);
}
}
// Pops config section
orxConfig_PopSection();
}
// Done!
return orxSTATUS_SUCCESS;
}
void ScrollEd::ExitSets()
{
// Gets game instance
ScrollBase &roGame = ScrollBase::GetInstance();
// For all sets
for(ScrollEdSet *poSet= (ScrollEdSet *)orxBank_GetNext(mpstSetBank, orxNULL);
poSet;
poSet = (ScrollEdSet *)orxBank_GetNext(mpstSetBank, poSet))
{
ScrollObject **ppoModel;
// For all its objects
for(ppoModel = (ScrollObject **)orxBank_GetNext(poSet->mpstObjectBank, orxNULL);
ppoModel;
ppoModel = (ScrollObject **)orxBank_GetNext(poSet->mpstObjectBank, ppoModel))
{
// Deletes it
roGame.DeleteObject(*ppoModel);
}
// Deletes its bank
orxBank_Delete(poSet->mpstObjectBank);
// Deletes its container
roGame.DeleteObject(poSet->mpoContainer);
// Deletes its name
orxString_Delete((orxSTRING)poSet->mzName);
}
// Deletes set bank
orxBank_Delete(mpstSetBank);
mpstSetBank = orxNULL;
}
void ScrollEd::ShowPreviousSet()
{
// Has sets?
if(orxBank_GetCount(mpstSetBank) > 0)
{
ScrollEdSet *poSet;
// Is selected set already shown?
if(TestFlags(FlagSetShown))
{
// Gets it
poSet = (ScrollEdSet *)orxBank_GetAtIndex(mpstSetBank, mu32SelectedSet);
// Hides it
poSet->mpoContainer->AddFX(szConfigSetContainerHide, orxFALSE);
// Gets previous one
mu32SelectedSet = (mu32SelectedSet == 0) ? orxBank_GetCount(mpstSetBank) - 1 : mu32SelectedSet - 1;
poSet = (ScrollEdSet *)orxBank_GetAtIndex(mpstSetBank, mu32SelectedSet);
// Pushes hide FX section
orxConfig_PushSection(szConfigSetContainerHide);
// Shows it
poSet->mpoContainer->AddFX(szConfigSetContainerShow, orxConfig_GetFloat("EndTime"), orxFALSE);
// Pops config section
orxConfig_PopSection();
}
else
{
// Gets selected set
poSet = (ScrollEdSet *)orxBank_GetAtIndex(mpstSetBank, mu32SelectedSet);
// Shows it
poSet->mpoContainer->AddFX(szConfigSetContainerShow, orxFALSE);
}
// Adds action display
AddActionDisplay(poSet->mzName);
// Updates status
SetFlags(FlagSetShown);
}
}
void ScrollEd::ShowNextSet()
{
// Has sets?
if(orxBank_GetCount(mpstSetBank) > 0)
{
ScrollEdSet *poSet;
// Is selected set already shown?
if(TestFlags(FlagSetShown))
{
// Gets it
poSet = (ScrollEdSet *)orxBank_GetAtIndex(mpstSetBank, mu32SelectedSet);
// Hides it
poSet->mpoContainer->AddFX(szConfigSetContainerHide, orxFALSE);
// Gets next one
mu32SelectedSet = (mu32SelectedSet + 1) % orxBank_GetCount(mpstSetBank);
poSet = (ScrollEdSet *)orxBank_GetAtIndex(mpstSetBank, mu32SelectedSet);
// Pushes hide FX section
orxConfig_PushSection(szConfigSetContainerHide);
// Shows it
poSet->mpoContainer->AddFX(szConfigSetContainerShow, orxConfig_GetFloat("EndTime"), orxFALSE);
// Pops config section
orxConfig_PopSection();
}
else
{
// Gets selected set
poSet = (ScrollEdSet *)orxBank_GetAtIndex(mpstSetBank, mu32SelectedSet);
// Shows it
poSet->mpoContainer->AddFX(szConfigSetContainerShow, orxFALSE);
}
// Adds action display
AddActionDisplay(poSet->mzName);
// Updates status
SetFlags(FlagSetShown);
}
}
void ScrollEd::HideSet()
{
// Has sets?
if(orxBank_GetCount(mpstSetBank) > 0)
{
ScrollEdSet *poSet;
// Is selected set shown?
if(TestFlags(FlagSetShown))
{
// Gets it
poSet = (ScrollEdSet *)orxBank_GetAtIndex(mpstSetBank, mu32SelectedSet);
// Hides it
poSet->mpoContainer->AddFX(szConfigSetContainerHide, orxFALSE);
}
// Updates status
SetFlags(FlagNone, FlagSetShown);
}
}
const ScrollObject *ScrollEd::GetSetModel(const orxVECTOR &_rvPosition) const
{
const ScrollObject *poResult = orxNULL;
// Is set shown?
if(TestFlags(FlagSetShown))
{
orxVECTOR vRelativePos, vSize;
orxFLOAT fContainerSize;
orxU32 u32ModelIndex;
ScrollEdSet *poSet;
// Gets selected set
poSet = (ScrollEdSet *)orxBank_GetAtIndex(mpstSetBank, mu32SelectedSet);
// Gets container size
orxObject_GetWorldScale(poSet->mpoContainer->GetOrxObject(), &vSize);
// Gets relative position
orxVector_Sub(&vRelativePos, &_rvPosition, orxObject_GetWorldPosition(poSet->mpoContainer->GetOrxObject(), &vRelativePos));
// Pushs editor section
orxConfig_PushSection(szConfigSectionEditor);
// Gets container size
fContainerSize = orxConfig_GetFloat(szConfigSetContainerSize);
// Pops config section
orxConfig_PopSection();
// Gets container grid position
orxVector_Floor(&vRelativePos, orxVector_Mulf(&vRelativePos, orxVector_Div(&vRelativePos, &vRelativePos, &vSize), fContainerSize));
// Gets model index
u32ModelIndex = orxF2U(vRelativePos.fX + vRelativePos.fY * fContainerSize);
// Valid?
if(u32ModelIndex < orxBank_GetCount(poSet->mpstObjectBank))
{
// Updates result
poResult = *(ScrollObject **)orxBank_GetAtIndex(poSet->mpstObjectBank, u32ModelIndex);
}
}
// Done!
return poResult;
}
orxSTATUS ScrollEd::InitUI()
{
orxS32 i, s32Number;
orxSTATUS eResult = orxSTATUS_SUCCESS;
// Pushes editor section
orxConfig_PushSection(szConfigSectionEditor);
// Creates grid
mpstGrid = orxObject_CreateFromConfig(orxConfig_GetString(szConfigGrid));
// Valid?
if(mpstGrid)
{
// Disables its shader
orxObject_EnableShader(mpstGrid, orxFALSE);
}
// Creates button bank
mpstButtonBank = orxBank_Create((orxU32)orxConfig_GetListCount(szConfigButtonList), sizeof(ButtonData), orxBANK_KU32_FLAG_NOT_EXPANDABLE, orxMEMORY_TYPE_MAIN);
// For all buttons
for(i = 0, s32Number = orxConfig_GetListCount(szConfigButtonList); i < s32Number; i++)
{
const orxSTRING zName;
orxOBJECT *pstButton;
// Gets its name
zName = orxConfig_GetListString(szConfigButtonList, i);
// Creates it
pstButton = orxObject_CreateFromConfig(zName);
// Valid?
if(pstButton)
{
ButtonData *pstData;
// Pushes its section
orxConfig_PushSection(zName);
// Allocates a data cell
pstData = (ButtonData *)orxBank_Allocate(mpstButtonBank);
orxMemory_Zero(pstData, sizeof(ButtonData));
// Inits it
pstData->mpstObject = pstButton;
pstData->mzName = orxObject_GetName(pstButton);
pstData->mzBase = orxConfig_GetString(szConfigButtonBase);
pstData->mzHighlight = orxConfig_GetString(szConfigButtonHighlight);
pstData->mzActive = orxConfig_GetString(szConfigButtonActive);
pstData->mzAction = orxConfig_GetString(szConfigButtonAction);
// Adds it to list
orxLinkList_AddEnd(&mstButtonList, &pstData->mstNode);
// Not its base?
if(orxString_Compare(pstData->mzName, pstData->mzBase))
{
// Disables it
orxObject_Enable(pstButton, orxFALSE);
}
// Pops config section
orxConfig_PopSection();
}
}
// Pops config section
orxConfig_PopSection();
// Creates default cursor
CreateCursorObject();
// For all buttons
for(ButtonData *pstButtonData = (ButtonData *)orxLinkList_GetFirst(&mstButtonList);
pstButtonData;
pstButtonData = (ButtonData *)orxLinkList_GetNext(&pstButtonData->mstNode))
{
// Is active button?
if(!orxString_Compare(pstButtonData->mzName, pstButtonData->mzActive))
{
// Matches?
if(!orxString_Compare(szInputDifferential, pstButtonData->mzAction))
{
// Updates its status
orxObject_Enable(pstButtonData->mpstObject, ScrollBase::GetInstance().IsDifferentialMode());
break;
}
}
}
// Done!
return eResult;
}
void ScrollEd::ExitUI()
{
// Deletes button bank
orxBank_Delete(mpstButtonBank);
mpstButtonBank = orxNULL;
}
void ScrollEd::UpdateUI(const orxCLOCK_INFO &_rstInfo)
{
// Updates cursor
UpdateCursor();
// No control mode
if(!TestFlags(MaskToggle))
{
// Still active?
if(orxInput_IsActive(szInputToggleMove) && !orxInput_HasNewStatus(szInputToggleMove))
{
// Removes its input
orxInput_ResetValue(szInputToggleMove);
}
else
{
// Defaults to move mode
orxInput_SetValue(szInputToggleMove, orxFLOAT_1);
}
}
// Had an highlighted button?
if(mpstButtonHighlight)
{
// Disables it
orxObject_Enable(mpstButtonHighlight->mpstObject, orxFALSE);
// Removes its reference
mpstButtonHighlight = orxNULL;
}
// Not in game?
if(!TestFlags(FlagInGame))
{
// Has a selection and no property text?
if(mpoSelection && !mpstPropertyText)
{
// Depending on current toggle
switch(GetFlags(MaskToggle))
{
case FlagToggleMove:
{
// Displays its position
DisplayObjectPosition(mpoSelection);
break;
}
case FlagToggleScale:
{
// Displays its scale
DisplayObjectScale(mpoSelection);
break;
}
case FlagToggleRotate:
{
// Displays its rotation
DisplayObjectRotation(mpoSelection);
break;
}
default:
{
break;
}
}
}
// Has cursor?
else if(mpoCursorObject)
{
// Displays its position
DisplayObjectPosition(mpoCursorObject);
}
}
}
void ScrollEd::UpdateButtons(const orxCLOCK_INFO &_rstInfo)
{
orxVECTOR vMousePos;
// Gets mouse world position
if(orxRender_GetWorldPosition(orxMouse_GetPosition(&vMousePos), orxNULL, &vMousePos))
{
orxOBJECT *pstPickedObject;
orxAABOX stCameraFrustum;
orxVECTOR vCameraPos;
// Gets game instance
ScrollBase &roGame = ScrollBase::GetInstance();
// Updates mouse position
orxCamera_GetFrustum(roGame.GetMainCamera(), &stCameraFrustum);
vMousePos.fZ = stCameraFrustum.vTL.fZ + orxCamera_GetPosition(roGame.GetMainCamera(), &vCameraPos)->fZ + orx2F(0.0002f);
// Picks object
pstPickedObject = orxObject_Pick(&vMousePos, orxU32_UNDEFINED);
// Found?
if(pstPickedObject)
{
// Pushes its section
orxConfig_PushSection(orxObject_GetName(pstPickedObject));
// Is a button?
if(orxConfig_HasValue(szConfigButtonBase))
{
ButtonData *pstButtonData;
const orxSTRING zHighlightName;
// Action input?
if(orxInput_IsActive(szInputAction) && orxInput_HasNewStatus(szInputAction))
{
// Deletes cursor object
DeleteCursorObject();
// Has action?
if(orxConfig_HasValue(szConfigButtonAction))
{
const orxSTRING zActionName;
// Gets action
zActionName = orxConfig_GetString(szConfigButtonAction);
// Activates it
orxInput_SetValue(zActionName, orxFLOAT_1);
}
}
// Gets its highlight name
zHighlightName = orxConfig_GetString(szConfigButtonHighlight);
// For all buttons
for(pstButtonData = (ButtonData *)orxLinkList_GetFirst(&mstButtonList);
pstButtonData;
pstButtonData = (ButtonData *)orxLinkList_GetNext(&pstButtonData->mstNode))
{
// Is the highlight?
if(!orxString_Compare(zHighlightName, pstButtonData->mzName))
{
// Stores it
mpstButtonHighlight = pstButtonData;
// Enables it
orxObject_Enable(pstButtonData->mpstObject, orxTRUE);
// Shows basic cursor
ShowBasicCursor();
break;
}
}
}
// Pops config section
orxConfig_PopSection();
}
}
}
void ScrollEd::UpdateLayerDisplay()
{
ScrollObject *poObject;
// Gets game instance
ScrollBase &roGame = ScrollBase::GetInstance();
// Removes selection
SetSelection();
// In game?
if(TestFlags(FlagInGame))
{
// Has layer text?
if(mpstLayerText)
{
// Deletes it
orxObject_Delete(mpstLayerText);
mpstLayerText = orxNULL;
}
}
else
{
orxCHAR acBuffer[64];
// Hides mouse cursor
orxMouse_ShowCursor(orxFALSE);
// No layer text?
if(!mpstLayerText)
{
// Creates it
mpstLayerText = orxObject_CreateFromConfig(szConfigLayerText);
}
// Pushes editor section
orxConfig_PushSection(szConfigSectionEditor);
// Updates layer text
orxString_NPrint(acBuffer, 64, orxConfig_GetString(szConfigLayerTextFormat), mu32LayerIndex - (roGame.GetLayerNumber() >> 1));
// Updates its content
orxObject_SetTextString(mpstLayerText, acBuffer);
// Restores map section
orxConfig_PopSection();
// For all map objects
for(poObject = roGame.GetNextObject();
poObject;
poObject = roGame.GetNextObject(poObject))
{
// Has no owner? (otherwise it'll get updated through it)
if(!orxObject_GetOwner(poObject->GetOrxObject()))
{
static const ScrollObject::Flag seFocusFlag = (ScrollObject::Flag)0x80000000;
orxVECTOR vPos;
// Gets its position
orxObject_GetPosition(poObject->GetOrxObject(), &vPos);
// Is in current layer or cursor?
if((roGame.GetLayer(vPos) == mu32LayerIndex)
|| (poObject == mpoCursorObject))
{
// Was out of layer?
if(poObject->TestFlags(seFocusFlag))
{
// Adds gain focus FX
poObject->AddFX(szConfigGainFocusFX);
// Updates status
poObject->SetFlags(ScrollObject::FlagNone, seFocusFlag);
}
}
else
{
// Wasn't out of focus?
if(!poObject->TestFlags(seFocusFlag))
{
// Adds lose focus FX
poObject->AddFX(szConfigLoseFocusFX);
// Updates status
poObject->SetFlags(seFocusFlag);
}
}
// Updates its differential mode
poObject->SetDifferentialMode(roGame.IsDifferentialMode());
}
}
}
}
ScrollObject *ScrollEd::CreateModel(const orxSTRING _zModelName, const orxSTRING _zInstanceName, ScrollObject::Flag _xFlags)
{
ScrollObject *poResult;
// Checks
orxASSERT(_zModelName);
// Gets game instance
ScrollBase &roGame = ScrollBase::GetInstance();
// Creates object
poResult = roGame.CreateObject(_zModelName, _xFlags & (~ScrollObject::FlagSave), _zInstanceName);
// Valid?
if(poResult)
{
orxANIMPOINTER *pstAnimPointer;
orxOBJECT *pstOrxObject;
// Gets its internal object
pstOrxObject = poResult->GetOrxObject();
// Updates its status
poResult->SetFlags(ScrollObject::FlagNone, ScrollObject::FlagSave);
poResult->PushConfigSection(orxTRUE);
orxConfig_SetBool(ScrollBase::szConfigNoSave, orxTRUE);
poResult->PopConfigSection();
// Gets animpointer
pstAnimPointer = orxOBJECT_GET_STRUCTURE(pstOrxObject, ANIMPOINTER);
// Valid?
if(pstAnimPointer)
{
// Updates its animation time
orxAnimPointer_SetTime(pstAnimPointer, mfLocalTime);
}
}
// Done!
return poResult;
}
void ScrollEd::CreateCursorObject(const ScrollObject *_poModel)
{
// Gets game instance
ScrollBase &roGame = ScrollBase::GetInstance();
// Deletes previous cursor
DeleteCursorObject();
// Removes selection
SetSelection();
// Has a model?
if(_poModel)
{
// Creates it
mpoCursorObject = CreateModel(_poModel->GetModelName(), szConfigCursor, _poModel->GetFlags());
// Updates status
SetFlags(FlagUsingCopy);
// Valid?
if(mpoCursorObject)
{
orxVECTOR vTemp;
orxCOLOR stColor;
orxOBJECT *pstModelOrxObject;
orxOBJECT *pstOrxObject;
// Gets both internal objects
pstOrxObject = mpoCursorObject->GetOrxObject();
pstModelOrxObject = _poModel->GetOrxObject();
// Gets model color
if(roGame.GetObjectConfigColor(_poModel, stColor))
{
// Applies it
roGame.SetObjectConfigColor(mpoCursorObject, stColor);
}
// Uses differential scrolling?
if(roGame.IsDifferentialMode())
{
orxVECTOR vPos;
// Gets model position
orxObject_GetWorldPosition(pstModelOrxObject, &vPos);
// Gets corrected scale
orxVector_Mulf(&vTemp, orxObject_GetScale(pstModelOrxObject, &vTemp), GetDepthCoef(vPos.fZ));
}
else
{
// Gets model scale
orxObject_GetScale(pstModelOrxObject, &vTemp);
}
// Updates it
orxObject_SetScale(pstOrxObject, &vTemp);
orxObject_SetRotation(pstOrxObject, orxObject_GetRotation(pstModelOrxObject));
orxObject_SetSmoothing(pstOrxObject, orxObject_GetSmoothing(pstModelOrxObject));
// Has tiling?
if(_poModel->TestFlags(ScrollObject::FlagTiled))
{
orxFLOAT fRepeatX, fRepeatY;
// Gets its tiling
if(orxObject_GetRepeat(pstModelOrxObject, &fRepeatX, &fRepeatY) != orxSTATUS_FAILURE)
{
// Updates cursor tiling
orxObject_SetRepeat(pstOrxObject, fRepeatX, fRepeatY);
}
}
}
}
else
{
// Updates status
SetFlags(FlagNone, FlagUsingCopy);
// Has selected model?
if(mpoSelectedModel)
{
// Creates it
mpoCursorObject = CreateModel(mpoSelectedModel->GetModelName(), szConfigCursor);
}
}
// Valid?
if(mpoCursorObject)
{
// Updates cursor
UpdateCursor();
}
}
void ScrollEd::DeleteCursorObject()
{
// Updates status
SetFlags(FlagNone, FlagUsingCopy);
// Has a cursor?
if(mpoCursorObject)
{
// Gets game instance
ScrollBase &roGame = ScrollBase::GetInstance();
// Deletes it
roGame.DeleteObject(mpoCursorObject);
mpoCursorObject = orxNULL;
// Hides its name
DisplayObjectName();
}
}
void ScrollEd::UpdateCursor()
{
// Not in game?
if(!TestFlags(FlagInGame))
{
// Has cursor object?
if(mpoCursorObject)
{
orxVECTOR vMousePos;
// Gets mouse position
if(orxRender_GetWorldPosition(orxMouse_GetPosition(&vMousePos), orxNULL, &vMousePos))
{
orxVECTOR vPos;
orxFLOAT fSnap;
// Gets game instance
ScrollBase &roGame = ScrollBase::GetInstance();
// Pushes editor section
orxConfig_PushSection(szConfigSectionEditor);
// Snap?
if(TestFlags(FlagSnap) && ((fSnap = orxConfig_GetFloat(szConfigGridSize)) > orxFLOAT_0))
{
// Updates position
orxVector_Set(&vPos, orxMath_Round(vMousePos.fX / fSnap) * fSnap, orxMath_Round(vMousePos.fY / fSnap) * fSnap, roGame.GetLayerDepth(mu32LayerIndex) - orx2F(0.01f));
}
else
{
// Updates cursor position
orxVector_Set(&vPos, orxMath_Round(vMousePos.fX), orxMath_Round(vMousePos.fY), roGame.GetLayerDepth(mu32LayerIndex) - orx2F(0.01f));
}
// Pops to previous section
orxConfig_PopSection();
// Updates cursor
orxObject_SetPosition(mpoCursorObject->GetOrxObject(), &vPos);
}
// Displays cursor name
DisplayObjectName(mpoCursorObject, orxTRUE);
// Hides basic cursor
ShowBasicCursor(orxFALSE);
}
else
{
// Shows basic cursor
ShowBasicCursor();
// Is set shown?
if(TestFlags(FlagSetShown))
{
orxVECTOR vMousePos;
// Gets mouse position
if(orxRender_GetWorldPosition(orxMouse_GetPosition(&vMousePos), orxNULL, &vMousePos))
{
const ScrollObject *poModel;
// Gets model under mouse position
poModel = GetSetModel(vMousePos);
// Valid?
if(poModel)
{
// Displays its name
DisplayObjectName(poModel, orxFALSE);
}
else
{
// Hides name
DisplayObjectName();
}
}
}
else
{
// Has selection?
if(mpoSelection)
{
// Displays its name
DisplayObjectName(mpoSelection);
}
}
}
}
else
{
// Hides basic cursor
ShowBasicCursor(orxFALSE);
}
// Shoud display basic cursor?
if(TestFlags(FlagShowBasicCursor))
{
orxVECTOR vMousePos;
// Gets mouse position
if(orxRender_GetWorldPosition(orxMouse_GetPosition(&vMousePos), orxNULL, &vMousePos))
{
orxVECTOR vPos, vScale;
orxFLOAT fScale;
const orxSTRING zCursorName = szConfigDefaultCursor;
// Gets game instance
ScrollBase &roGame = ScrollBase::GetInstance();
// Has selection?
if(mpoSelection)
{
// Depending on current toggle
switch(GetFlags(MaskToggle))
{
case FlagToggleMove:
{
zCursorName = szConfigMoveCursor;
break;
}
case FlagToggleScale:
{
zCursorName = szConfigScaleCursor;
break;
}
case FlagToggleRotate:
{
zCursorName = szConfigRotateCursor;
break;
}
default:
{
break;
}
}
}
// Not already created?
if(!mpstBasicCursor)
{
// Creates it
mpstBasicCursor = orxObject_CreateFromConfig(zCursorName);
}
else
{
// Not the current cursor?
if(orxString_Compare(orxObject_GetName(mpstBasicCursor), zCursorName))
{
// Deletes current cursor
orxObject_Delete(mpstBasicCursor);
// Creates new one
mpstBasicCursor = orxObject_CreateFromConfig(zCursorName);
}
}
// Calculates cursor position
orxVector_Set(&vPos, vMousePos.fX, vMousePos.fY, vMousePos.fZ + orx2F(0.0001f));
// Calculates its scale
fScale = orxFLOAT_1 / orxCamera_GetZoom(roGame.GetMainCamera());
orxVector_Set(&vScale, fScale, fScale, orxFLOAT_1);
// Updates cursor
orxObject_SetScale(mpstBasicCursor, &vScale);
orxObject_SetPosition(mpstBasicCursor, &vPos);
}
}
else
{
// Not already deleted?
if(mpstBasicCursor)
{
// Deletes it
orxObject_Delete(mpstBasicCursor);
mpstBasicCursor = orxNULL;
}
}
}
void ScrollEd::ShowBasicCursor(orxBOOL _bShow)
{
// Show?
if(_bShow)
{
// Updates status
SetFlags(FlagShowBasicCursor);
}
else
{
// Updates status
SetFlags(FlagNone, FlagShowBasicCursor);
}
}
void ScrollEd::SetPropertyText(const ScrollObject *_poObject, const orxSTRING _zText, const orxCOLOR *_pstColor)
{
// Has property text?
if(mpstPropertyText)
{
// Deletes it
orxObject_Delete(mpstPropertyText);
mpstPropertyText = orxNULL;
}
// Has object?
if(_poObject)
{
// Creates property text
mpstPropertyText = orxObject_CreateFromConfig(szConfigPropertyText);
// Valid?
if(mpstPropertyText)
{
orxVECTOR vPos, vSize, vPivot, vScale, vTemp;
orxOBJECT *pstOrxObject;
// Gets game instance
ScrollBase &roGame = ScrollBase::GetInstance();
// Gets its internal object
pstOrxObject = _poObject->GetOrxObject();
// Updates differential flags
orxStructure_SetFlags(orxOBJECT_GET_STRUCTURE(mpstPropertyText, FRAME), orxStructure_GetFlags(orxOBJECT_GET_STRUCTURE(pstOrxObject, FRAME), orxFRAME_KU32_FLAG_SCROLL_X|orxFRAME_KU32_FLAG_SCROLL_Y), orxFRAME_KU32_FLAG_SCROLL_X|orxFRAME_KU32_FLAG_SCROLL_Y);
// Updates its parent
orxObject_SetParent(mpstPropertyText, pstOrxObject);
// Gets object size, scale & pivot
orxObject_GetSize(pstOrxObject, &vSize);
orxObject_GetScale(pstOrxObject, &vScale);
orxObject_GetPivot(pstOrxObject, &vPivot);
// Updates its position
orxVector_Mul(&vPos, &vSize, orxObject_GetPosition(mpstPropertyText, &vTemp));
orxVector_Set(&vPos, vPos.fX - vPivot.fX, vPos.fY - vPivot.fY, orxFLOAT_0);
orxObject_SetPosition(mpstPropertyText, &vPos);
// Updates its scale for conservation
orxVector_Div(&vScale, orxObject_GetScale(mpstPropertyText, &vTemp), &vScale);
orxObject_SetScale(mpstPropertyText, orxVector_Divf(&vScale, &vScale, orxCamera_GetZoom(roGame.GetMainCamera())));
// Updates its text
orxObject_SetTextString(mpstPropertyText, _zText);
// Has color?
if(_pstColor)
{
// Updates its color
orxObject_SetColor(mpstPropertyText, _pstColor);
}
}
}
}
void ScrollEd::DisplayObjectName(const ScrollObject *_poObject, orxBOOL _bDisplayInstanceName)
{
// Has name text?
if(mpstNameText)
{
// Deletes it
orxObject_Delete(mpstNameText);
mpstNameText = orxNULL;
}
// Has object?
if(_poObject)
{
// Creates name text
mpstNameText = orxObject_CreateFromConfig(szConfigNameText);
// Valid?
if(mpstNameText)
{
orxVECTOR vPos, vSize, vPivot, vScale, vTemp;
orxCHAR acBuffer[256];
orxOBJECT *pstOrxObject;
// Gets its internal object
pstOrxObject = _poObject->GetOrxObject();
// Gets game instance
ScrollBase &roGame = ScrollBase::GetInstance();
// Updates differential flags
orxStructure_SetFlags(orxOBJECT_GET_STRUCTURE(mpstNameText, FRAME), orxStructure_GetFlags(orxOBJECT_GET_STRUCTURE(pstOrxObject, FRAME), orxFRAME_KU32_FLAG_SCROLL_X|orxFRAME_KU32_FLAG_SCROLL_Y), orxFRAME_KU32_FLAG_SCROLL_X|orxFRAME_KU32_FLAG_SCROLL_Y);
// Updates its parent
orxObject_SetParent(mpstNameText, pstOrxObject);
// Gets object size, scale & pivot
orxObject_GetSize(pstOrxObject, &vSize);
orxObject_GetWorldScale(pstOrxObject, &vScale);
orxObject_GetPivot(pstOrxObject, &vPivot);
// Updates its position
orxVector_Mul(&vPos, &vSize, orxObject_GetPosition(mpstNameText, &vTemp));
orxVector_Set(&vPos, vPos.fX - vPivot.fX, vPos.fY - vPivot.fY, orxFLOAT_0);
orxObject_SetPosition(mpstNameText, &vPos);
// Updates its scale for conservation
orxVector_Div(&vScale, orxObject_GetScale(mpstNameText, &vTemp), &vScale);
orxObject_SetScale(mpstNameText, orxVector_Divf(&vScale, &vScale, orxCamera_GetZoom(roGame.GetMainCamera())));
// Updates its content
if(_bDisplayInstanceName)
{
orxString_NPrint(acBuffer, 256, "%s(%s)", _poObject->GetName(), _poObject->GetModelName());
}
else
{
orxString_NPrint(acBuffer, 256, "%s", _poObject->GetModelName());
}
acBuffer[255] = orxCHAR_NULL;
orxObject_SetTextString(mpstNameText, acBuffer);
}
}
}
void ScrollEd::DisplayObjectColor(const ScrollObject *_poObject)
{
// Has object?
if(_poObject)
{
static const orxS32 ss32BufferSize = 256;
orxCOLOR stColor;
orxCHAR acBuffer[ss32BufferSize];
// Gets game instance
ScrollBase &roGame = ScrollBase::GetInstance();
// Pushes editor section
orxConfig_PushSection(szConfigSectionEditor);
// Gets object's color
if(orxObject_HasColor(_poObject->GetOrxObject()))
{
orxObject_GetColor(_poObject->GetOrxObject(), &stColor);
}
else
{
roGame.GetObjectConfigColor(_poObject, stColor);
}
// Updates it
stColor.fAlpha = orxFLOAT_1;
// Creates color string
orxString_NPrint(acBuffer, ss32BufferSize, orxConfig_GetString(szConfigColorTextFormat), orxF2S(stColor.vRGB.fR * orxCOLOR_DENORMALIZER), orxF2S(stColor.vRGB.fG * orxCOLOR_DENORMALIZER), orxF2S(stColor.vRGB.fB * orxCOLOR_DENORMALIZER));
// Sets property text
SetPropertyText(_poObject, acBuffer, &stColor);
// Pops previous section
orxConfig_PopSection();
}
else
{
// Clears property text
SetPropertyText();
}
}
void ScrollEd::DisplayObjectAlpha(const ScrollObject *_poObject)
{
// Has object?
if(_poObject)
{
static const orxS32 ss32BufferSize = 256;
orxCOLOR stColor;
orxCHAR acBuffer[ss32BufferSize];
// Gets game instance
ScrollBase &roGame = ScrollBase::GetInstance();
// Pushes editor section
orxConfig_PushSection(szConfigSectionEditor);
// Gets object's color
if(orxObject_HasColor(_poObject->GetOrxObject()))
{
orxObject_GetColor(_poObject->GetOrxObject(), &stColor);
}
else
{
roGame.GetObjectConfigColor(_poObject, stColor);
}
// Updates it
orxVector_Copy(&stColor.vRGB, &orxVECTOR_WHITE);
// Creates alpha string
orxString_NPrint(acBuffer, ss32BufferSize, orxConfig_GetString(szConfigAlphaTextFormat), orxF2S(orx2F(100.0f) * stColor.fAlpha));
// Sets property text
SetPropertyText(_poObject, acBuffer, &stColor);
// Pops previous section
orxConfig_PopSection();
}
else
{
// Clears property text
SetPropertyText();
}
}
void ScrollEd::DisplayObjectScale(const ScrollObject *_poObject)
{
// Has object?
if(_poObject)
{
static const orxS32 ss32BufferSize = 256;
orxVECTOR vScale, vSize;
orxCHAR acBuffer[ss32BufferSize];
// Pushes editor section
orxConfig_PushSection(szConfigSectionEditor);
// Gets object's scale & size
orxObject_GetScale(_poObject->GetOrxObject(), &vScale);
orxObject_GetSize(_poObject->GetOrxObject(), &vSize);
orxVector_Mul(&vSize, &vSize, &vScale);
vSize.fX = orxMath_Abs(vSize.fX);
vSize.fY = orxMath_Abs(vSize.fY);
// Creates text
orxString_NPrint(acBuffer, ss32BufferSize, orxConfig_GetString(szConfigScaleTextFormat), vScale.fX, vScale.fY, vSize.fX, vSize.fY);
// Sets property text
SetPropertyText(_poObject, acBuffer);
// Pops previous section
orxConfig_PopSection();
}
else
{
// Clears property text
SetPropertyText();
}
}
void ScrollEd::DisplayObjectRotation(const ScrollObject *_poObject)
{
// Has object?
if(_poObject)
{
static const orxS32 ss32BufferSize = 256;
orxFLOAT fRotation;
orxCHAR acBuffer[ss32BufferSize];
// Pushes editor section
orxConfig_PushSection(szConfigSectionEditor);
// Gets object's rotation
fRotation = orxObject_GetRotation(_poObject->GetOrxObject());
// Clamps it in ]-Pi, Pi]
fRotation = (fRotation + orxMATH_KF_PI) * (orxFLOAT_1 / orxMATH_KF_2_PI);
fRotation = fRotation - orxMath_Floor(fRotation);
fRotation = (fRotation * orxMATH_KF_2_PI) - orxMATH_KF_PI;
// Creates text
orxString_NPrint(acBuffer, ss32BufferSize, orxConfig_GetString(szConfigRotationTextFormat), orxMATH_KF_RAD_TO_DEG * fRotation);
// Sets property text
SetPropertyText(_poObject, acBuffer);
// Pops previous section
orxConfig_PopSection();
}
else
{
// Clears property text
SetPropertyText();
}
}
void ScrollEd::DisplayObjectPosition(const ScrollObject *_poObject)
{
// Has object?
if(_poObject)
{
static const orxS32 ss32BufferSize = 256;
orxVECTOR vPosition;
orxCHAR acBuffer[ss32BufferSize];
// Pushes editor section
orxConfig_PushSection(szConfigSectionEditor);
// Gets object's position
orxObject_GetPosition(_poObject->GetOrxObject(), &vPosition);
// Creates text
orxString_NPrint(acBuffer, ss32BufferSize, orxConfig_GetString(szConfigPositionTextFormat), vPosition.fX, vPosition.fY, vPosition.fZ);
// Sets property text
SetPropertyText(_poObject, acBuffer);
// Pops previous section
orxConfig_PopSection();
}
else
{
// Clears property text
SetPropertyText();
}
}
orxSTATUS ScrollEd::AddActionDisplay(const orxSTRING _zAction) const
{
orxSTATUS eResult = orxSTATUS_FAILURE;
// Has valid action
if(_zAction)
{
orxOBJECT *pstActionText;
// Creates action test
pstActionText = orxObject_CreateFromConfig(szConfigActionText);
// Valid?
if(pstActionText)
{
// Updates its content
orxObject_SetTextString(pstActionText, _zAction);
// Updates result
eResult = orxSTATUS_SUCCESS;
}
}
// Done!
return eResult;
}
void ScrollEd::SetSelection(ScrollObject *_poObject)
{
// New selection?
if(_poObject != mpoSelection)
{
// Deletes cursor
DeleteCursorObject();
// Removes selected model
mpoSelectedModel = orxNULL;
// Has a previous selection?
if(mpoSelection)
{
// Removes its shader
mpoSelection->RemoveShader("SelectionShader");
}
// Stores new selection
mpoSelection = _poObject;
// Valid?
if(mpoSelection)
{
// Adds selection FX
mpoSelection->AddShader("SelectionShader");
// Displays its name
DisplayObjectName(mpoSelection, orxTRUE);
}
else
{
// Hides name
DisplayObjectName();
}
}
}
orxOBJECT *ScrollEd::PickObject(const orxVECTOR &_rvPos, orxU32 _u32GroupID) const
{
orxOBJECT *pstResult;
orxVECTOR vPick;
// Gets game instance
ScrollBase &roGame = ScrollBase::GetInstance();
// Sets picking vector
orxVector_Copy(&vPick, &_rvPos);
vPick.fZ = roGame.GetLayerDepth(mu32LayerIndex);
// Updates picking position
vPick.fZ -= orx2F(0.001f);
// Updates result
pstResult = orxObject_Pick(&vPick, _u32GroupID);
// Has result?
if(pstResult)
{
// Not in the current layer?
if((!orxObject_GetWorldPosition(pstResult, &vPick) || (vPick.fZ > (roGame.GetLayerDepth(mu32LayerIndex + 1) - orx2F(0.01f)))))
{
// Cleans result
pstResult = orxNULL;
}
else
{
// Gets its root
for(orxOBJECT *pstOwner = orxOBJECT(orxObject_GetOwner(pstResult));
pstOwner;
pstResult = pstOwner, pstOwner = orxOBJECT(orxObject_GetOwner(pstOwner)));
}
}
// Done!
return pstResult;
}
ScrollObject *ScrollEd::AddObject(const ScrollObject *_poModel)
{
ScrollObject *poResult = orxNULL;
// Gets game instance
ScrollBase &roGame = ScrollBase::GetInstance();
// Creates object
poResult = roGame.CreateObject(_poModel->GetModelName(), ScrollObject::FlagSave);
// Valid?
if(poResult)
{
orxVECTOR vPos, vScale;
orxFLOAT fRepeatX, fRepeatY;
orxCOLOR stColor;
orxOBJECT *pstOrxObject, *pstModelOrxObject;
// Gets internal objects
pstOrxObject = poResult->GetOrxObject();
pstModelOrxObject = _poModel->GetOrxObject();
// Gets model color
if(roGame.GetObjectConfigColor(_poModel, stColor))
{
// Applies it
roGame.SetObjectConfigColor(poResult, stColor);
}
// Updates it
orxObject_GetPosition(pstModelOrxObject, &vPos);
vPos.fZ = roGame.GetLayerDepth(mu32LayerIndex);
orxObject_GetScale(pstModelOrxObject, &vScale);
orxObject_SetRotation(pstOrxObject, orxObject_GetRotation(pstModelOrxObject));
orxObject_SetSmoothing(pstOrxObject, orxObject_GetSmoothing(pstModelOrxObject));
// Updates its differential mode
poResult->SetDifferentialMode(roGame.IsDifferentialMode());
// Uses differential scrolling?
if(roGame.IsDifferentialMode())
{
// Gets depth-corrected scale & position
GetDepthCorrectedScale(vPos.fZ, vScale);
GetDepthCorrectedPosition(vPos.fZ, vPos);
}
// Updates object's position & scale
orxObject_SetPosition(pstOrxObject, &vPos);
orxObject_SetScale(pstOrxObject, &vScale);
// Updates its flags
poResult->SetFlags(_poModel->GetFlags() | ScrollObject::FlagSave);
// Use tiling?
if(poResult->TestFlags(ScrollObject::FlagTiled))
{
// Gets tiling values
orxObject_GetRepeat(pstModelOrxObject, &fRepeatX, &fRepeatY);
// Applies it to object
orxObject_SetRepeat(pstOrxObject, fRepeatX, fRepeatY);
}
}
// Done!
return poResult;
}
void ScrollEd::RemoveObject(ScrollObject *_poObject)
{
// Was selected?
if(_poObject == mpoSelection)
{
// Clears selection
SetSelection();
}
// Deletes it
ScrollBase::GetInstance().DeleteObject(_poObject);
}
orxFLOAT ScrollEd::GetDepthCoef(orxFLOAT _fDepth) const
{
orxVECTOR vCameraPosition;
orxAABOX stFrustum;
orxFLOAT fRelativeDepth, fCameraDepth, fResult;
// Gets game instance
ScrollBase &roGame = ScrollBase::GetInstance();
// Gets camera position
orxFrame_GetPosition(orxCamera_GetFrame(roGame.GetMainCamera()), orxFRAME_SPACE_GLOBAL, &vCameraPosition);
// Gets camera frustum
orxCamera_GetFrustum(roGame.GetMainCamera(), &stFrustum);
// Gets camera depth
fCameraDepth = stFrustum.vBR.fZ - stFrustum.vTL.fZ;
// Gets relative depth
fRelativeDepth = _fDepth - vCameraPosition.fZ;
// Near space?
if(fRelativeDepth < (orx2F(0.5f) * fCameraDepth))
{
// Updates result
fResult = (orx2F(0.5f) * fCameraDepth) / fRelativeDepth;
}
// Far space
else
{
// Updates result
fResult = (fCameraDepth - fRelativeDepth) / (orx2F(0.5f) * fCameraDepth);
}
// Done!
return fResult;
}
orxVECTOR &ScrollEd::GetDepthCorrectedPosition(orxFLOAT _fDepth, orxVECTOR &_rvPos) const
{
orxVECTOR vCameraCenter, vCameraPos;
orxAABOX stFrustum;
orxFLOAT fRecDepthCoef;
// Gets game instance
ScrollBase &roGame = ScrollBase::GetInstance();
// Gets reciprocal depth coef
fRecDepthCoef = orxFLOAT_1 / GetDepthCoef(_fDepth);
// Gets camera frustum and position
orxCamera_GetFrustum(roGame.GetMainCamera(), &stFrustum);
orxCamera_GetPosition(roGame.GetMainCamera(), &vCameraPos);
// Gets camera center
orxVector_Add(&vCameraCenter, &(stFrustum.vTL), &(stFrustum.vBR));
orxVector_Mulf(&vCameraCenter, &vCameraCenter, orx2F(0.5f));
orxVector_Add(&vCameraCenter, &vCameraCenter, &vCameraPos);
// Gets position in camera space
orxVector_Sub(&_rvPos, &_rvPos, &vCameraCenter);
// Corrects it
_rvPos.fX *= fRecDepthCoef;
_rvPos.fY *= fRecDepthCoef;
// Gets position in world space
orxVector_Add(&_rvPos, &_rvPos, &vCameraCenter);
// Done!
return _rvPos;
}
orxVECTOR &ScrollEd::GetDepthCorrectedScale(orxFLOAT _fDepth, orxVECTOR &_rvScale) const
{
orxFLOAT fRecDepthCoef;
// Gets reciprocal depth coef
fRecDepthCoef = orxFLOAT_1 / GetDepthCoef(_fDepth);
// Gets corrected scale
_rvScale.fX = fRecDepthCoef * _rvScale.fX;
_rvScale.fY = fRecDepthCoef * _rvScale.fY;
// Done!
return _rvScale;
}
void ScrollEd::UpdateToggle(const orxSTRING _zToggleName, Flag _xToggleFlag)
{
Flag xCurrentFlag;
ButtonData *pstButtonData;
// Checks
orxASSERT(orxFLAG_TEST(_xToggleFlag, MaskToggle));
// Gets current toggle flag
xCurrentFlag = GetFlags(MaskToggle);
// Has new active status?
if(orxInput_IsActive(_zToggleName) && orxInput_HasNewStatus(_zToggleName))
{
// Updates current mode
SetFlags(_xToggleFlag, MaskToggle);
}
// Gets corresponding button
pstButtonData = GetActiveButton(_zToggleName);
// Found?
if(pstButtonData)
{
// Updates its status
orxObject_Enable(pstButtonData->mpstObject, TestFlags(_xToggleFlag));
}
}
ScrollEd::ButtonData *ScrollEd::GetActiveButton(const orxSTRING _zAction) const
{
ButtonData *pstButtonData, *pstResult = orxNULL;
// For all buttons
for(pstButtonData = (ButtonData *)orxLinkList_GetFirst(&mstButtonList);
pstButtonData;
pstButtonData = (ButtonData *)orxLinkList_GetNext(&pstButtonData->mstNode))
{
// Is active button?
if(!orxString_Compare(pstButtonData->mzName, pstButtonData->mzActive))
{
// Matches?
if(!orxString_Compare(_zAction, pstButtonData->mzAction))
{
// Updates result
pstResult = pstButtonData;
break;
}
}
}
// Done!
return pstResult;
}
|
/**
* @file addCustomValidator.cpp
* @brief Example creating a custom validator to be called during validation
* @author Frank T. Bergmann
*
* <!--------------------------------------------------------------------------
* This sample program is distributed under a different license than the rest
* of libSBML. This program uses the open-source MIT license, as follows:
*
* Copyright (c) 2013-2018 by the California Institute of Technology
* (California, USA), the European Bioinformatics Institute (EMBL-EBI, UK)
* and the University of Heidelberg (Germany), with support from the National
* Institutes of Health (USA) under grant R01GM070923. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Neither the name of the California Institute of Technology (Caltech), nor
* of the European Bioinformatics Institute (EMBL-EBI), nor of the University
* of Heidelberg, nor the names of any contributors, may be used to endorse
* or promote products derived from this software without specific prior
* written permission.
* ------------------------------------------------------------------------ -->
*/
#include <iostream>
#include <sbml/SBMLTypes.h>
#include <sbml/validator/SBMLValidator.h>
using namespace std;
LIBSBML_CPP_NAMESPACE_USE
/**
* Declares a custom validator to be called. This allows you to validate
* any aspect of an SBML Model that you want to be notified about. You could
* use this to notify your application that a model contains an unsupported
* feature of SBML (either as warning).
*
* In this example the validator will go through the model and test for the
* presence of 'fast' reactions and algebraic rules. If either is used a
* warning will be added to the error log.
*/
class MyCustomValidator : public SBMLValidator
{
public:
MyCustomValidator() : SBMLValidator() {}
MyCustomValidator(const MyCustomValidator& orig) : SBMLValidator(orig) {
}
virtual ~MyCustomValidator() {}
virtual SBMLValidator* clone() const { return new MyCustomValidator(*this); }
virtual unsigned int validate() {
// if we don't have a model we don't apply this validator.
if (getDocument() == NULL || getModel() == NULL)
return 0;
// if we have no rules and reactions we don't apply this validator either
if (getModel()->getNumReactions() == 0 && getModel()->getNumRules() == 0)
return 0;
unsigned int numErrors = 0;
// test for algebraic rules
for (unsigned int i = 0; i < getModel()->getNumRules(); i++)
{
if (getModel()->getRule(i)->getTypeCode() == SBML_ALGEBRAIC_RULE) {
getErrorLog()->add(SBMLError(99999, 3, 1,
"This model uses algebraic rules, however this application does not support them.",
0, 0,
LIBSBML_SEV_WARNING, // or LIBSBML_SEV_ERROR if you want to stop
LIBSBML_CAT_SBML // or whatever category you prefer
));
numErrors++;
}
}
// test for fast reactions
for (unsigned int i = 0; i < getModel()->getNumReactions(); i++)
{
// test whether value is set, and true
if (getModel()->getReaction(i)->isSetFast() &&
getModel()->getReaction(i)->getFast()) {
getErrorLog()->add(SBMLError(99999, 3, 1,
"This model uses fast reactions, however this application does not support them.",
0, 0,
LIBSBML_SEV_WARNING, // or LIBSBML_SEV_ERROR if you want to stop
LIBSBML_CAT_SBML // or whatever category you prefer
));
numErrors++;
}
}
return numErrors;
}
};
int
main (int argc, char *argv[])
{
if (argc != 2)
{
cout << endl << "Usage: addCustomValidator filename" << endl << endl;
return 1;
}
const char* filename = argv[1];
// read the file name
SBMLDocument* document = readSBML(filename);
// add a custom validator
MyCustomValidator* myCustomValidator = new MyCustomValidator();
document->addValidator(myCustomValidator);
delete myCustomValidator;
// check consistency like before
int numErrors = document->checkConsistency();
// print errors and warnings
document->printErrors();
delete document;
// return number of errors
return numErrors;
}
|
#include "mocks.h"
#include "source/common/network/address_impl.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using testing::Const;
using testing::Return;
using testing::ReturnRef;
namespace Envoy {
namespace LocalInfo {
MockLocalInfo::MockLocalInfo() : address_(new Network::Address::Ipv4Instance("127.0.0.1")) {
node_.set_id("node_name");
node_.set_cluster("cluster_name");
node_.mutable_locality()->set_zone("zone_name");
ON_CALL(*this, address()).WillByDefault(Return(address_));
ON_CALL(*this, zoneName()).WillByDefault(ReturnRef(node_.locality().zone()));
ON_CALL(*this, zoneStatName()).WillByDefault(ReturnRef(makeZoneStatName()));
ON_CALL(*this, clusterName()).WillByDefault(ReturnRef(node_.cluster()));
ON_CALL(*this, nodeName()).WillByDefault(ReturnRef(node_.id()));
ON_CALL(*this, node()).WillByDefault(ReturnRef(node_));
ON_CALL(*this, contextProvider()).WillByDefault(ReturnRef(context_provider_));
ON_CALL(Const(*this), contextProvider()).WillByDefault(ReturnRef(context_provider_));
}
MockLocalInfo::~MockLocalInfo() = default;
const Stats::StatName& MockLocalInfo::makeZoneStatName() const {
if (zone_stat_name_storage_ == nullptr ||
symbol_table_->toString(zone_stat_name_) != node_.locality().zone()) {
zone_stat_name_storage_ =
std::make_unique<Stats::StatNameManagedStorage>(node_.locality().zone(), *symbol_table_);
zone_stat_name_ = zone_stat_name_storage_->statName();
}
return zone_stat_name_;
}
} // namespace LocalInfo
} // namespace Envoy
|
// Lines.cpp: implementation of the CLines class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "Lines.h"
#include "Token.h"
#include "Param.h"
//////////////////////////////////////////////////////////////////////
// CLine class.
CInnoScript::CLine::CLine(SECTION sec) : m_sec(sec), m_pParams(NULL) {
m_dwUserFlags = 0;
}
CInnoScript::CLine::~CLine() {
CParam* pParam = m_pParams;
while(pParam) {
CParam* pSave = pParam;
pParam = pParam->GetNext();
delete pSave;
}
m_pParams = NULL;
}
CInnoScript::SECTION CInnoScript::CLine::GetSection() {
return m_sec;
}
LPCTSTR CInnoScript::CLine::GetComment() {
return NULL;
}
void CInnoScript::CLine::SetIndent(const CString& strIndent) {
m_strIndent = strIndent;
}
LPCTSTR CInnoScript::CLine::GetIndent() const {
return m_strIndent;
}
LPSTR CInnoScript::CLine::UnQuote(LPSTR pszLine) {
if(!pszLine) return pszLine;
UINT nLength = _tcslen(pszLine);
if(pszLine[0]!='"' || pszLine[nLength-1]!='"') {
CString str(pszLine);
str.TrimLeft();
str.TrimRight();
_tcscpy(pszLine,str);
return pszLine;
}
LPSTR pszDest = pszLine;
LPSTR pszSave = pszLine;
nLength-=2;
pszLine++;
pszLine[nLength] = 0;
while(*pszLine) {
if(pszLine[0]=='"' && pszLine[1]=='"') {
pszLine+=2;
*pszDest++ = '"';
} else
*pszDest++ = *pszLine++;
}
*pszDest = 0;
return pszSave;
}
LPCTSTR CInnoScript::CLine::GetParameter(LPCTSTR pszName) {
CParam* pParam = m_pParams;
while(pParam) {
if(!_stricmp(pParam->GetName(),pszName))
return pParam->GetValue();
pParam = pParam->GetNext();
}
return NULL;
}
void CInnoScript::CLine::AddParameter(LPCTSTR pszName,LPCTSTR pszValue) {
CParam* pParam = new CParam(pszName,pszValue);
if(m_pParams)
m_pParams->AddTail(pParam);
else
m_pParams = pParam;
}
void CInnoScript::CLine::SetParameter(LPCTSTR pszName,LPCTSTR pszValue) {
CParam* pParam = m_pParams;
while(pParam) {
if(!_stricmp(pParam->GetName(),pszName)) {
pParam->SetValue(pszValue);
return;
}
pParam = pParam->GetNext();
}
AddParameter(pszName,pszValue);
}
void CInnoScript::CLine::DeleteParameter(LPCTSTR pszName) {
CParam* pParam = m_pParams;
CParam* pParent = NULL;
while(pParam) {
if(!_stricmp(pParam->GetName(),pszName)) {
if(pParent)
pParent->m_pNext = pParam->m_pNext;
else
m_pParams = pParam->m_pNext;
break;
}
pParent = pParam;
pParam = pParam->GetNext();
}
delete pParam;
}
bool CInnoScript::CLine::GetParameterFlag(LPCTSTR pszName,LPCTSTR pszFlag) {
LPCTSTR pszValue = GetParameter(pszName);
if(pszValue) {
CToken flags(pszValue," ");
LPCTSTR psz;
while(psz = flags.GetNext()) {
if(!_stricmp(pszFlag,psz))
return true;
}
}
return false;
}
void CInnoScript::CLine::SetParameterFlag(LPCTSTR pszName,LPCTSTR pszFlag,bool bSet) {
char szBuffer[1024];
LPCTSTR pszValue = GetParameter(pszName);
if(!pszValue) {
if(bSet) SetParameter(pszName,pszFlag);
} else {
CToken flags(pszValue," ");
if(bSet) {
while(LPCTSTR psz=flags.GetNext()) {
// Already there?
if(!_stricmp(pszFlag,psz))
return;
}
// Need to add it
_tcscpy(szBuffer,pszValue);
_tcscat(szBuffer," ");
_tcscat(szBuffer,pszFlag);
SetParameter(pszName,szBuffer);
} else {
szBuffer[0] = 0;
bool bFound = false;
while(LPCTSTR psz=flags.GetNext()) {
if(_stricmp(pszFlag,psz)) {
if(szBuffer[0]) _tcscat(szBuffer," ");
_tcscat(szBuffer,psz);
} else
bFound = true;
}
// If found flags is empty, remove parameter
if(!szBuffer[0])
DeleteParameter(pszName);
// If current flag was found, set new flags
else if(bFound)
SetParameter(pszName,szBuffer);
}
}
}
void CInnoScript::CLine::Write(LPSTR pszOut,UINT nLength) {
*pszOut = 0;
if(!m_strIndent.IsEmpty())
_tcscpy(pszOut,m_strIndent);
CParam* pParam = m_pParams;
bool bKey = false; // Special for ini entries
bool bString = false; // Special for ini entries
while(pParam) {
// Special for ini entries
if(m_sec==SEC_INI) {
if(!_stricmp("Key",pParam->GetName())) bKey = true;
else if(!_stricmp("String",pParam->GetName())) bString = true;
}
if(*pszOut) {
if(_tcslen(pszOut)+2>nLength) return;
_tcscat(pszOut,"; ");
}
if(_tcslen(pszOut)+_tcslen(pParam->GetName())>nLength) return;
_tcscat(pszOut,pParam->GetName());
if(_tcslen(pszOut)+2>nLength) return;
_tcscat(pszOut,": ");
LPCTSTR pszValue = pParam->GetValue();
LPSTR pszQuoted = NULL;
// Do we need to quote the damn thing?
if(_tcschr(pszValue,'"') || _tcschr(pszValue,';') || pszValue[0]==' ' || pszValue[_tcslen(pszValue)-1]==' ') {
pszQuoted = new char[_tcslen(pszValue)*2+1];
char* pszDest = pszQuoted;
*pszDest++ = '"';
while(*pszValue) {
if(*pszValue=='"')
*pszDest++ = *pszValue;
*pszDest++ = *pszValue++;
}
*pszDest++ = '"';
*pszDest = 0;
pszValue = pszQuoted;
}
if(_tcslen(pszOut)+_tcslen(pszValue)>nLength) return;
_tcscat(pszOut,pszValue);
pParam = pParam->GetNext();
if(pszQuoted) delete []pszQuoted;
}
// Special for ini entries
if(m_sec==SEC_INI && bKey && !bString) {
if(*pszOut) {
if(_tcslen(pszOut)+2>nLength) return;
_tcscat(pszOut,"; ");
}
if(_tcslen(pszOut)+10>nLength) return;
_tcscat(pszOut,"String: \"\"");
}
if(m_dwUserFlags & FLG_CONCAT) {
if(_tcslen(pszOut)+3>nLength) return;
if(*pszOut) {
_tcscat(pszOut,";");
}
_tcscat(pszOut," \\");
}
}
LPCTSTR CInnoScript::CLine::GetKey() {
return NULL;
}
LPCTSTR CInnoScript::CLine::GetValue() {
return NULL;
}
CInnoScript::CLine* CInnoScript::CLine::Copy() {
CLine* pLine = new CLine(m_sec);
pLine->m_dwUserFlags = m_dwUserFlags;
CParam* pParams = m_pParams;
while(pParams) {
pLine->AddParameter(pParams->GetName(),pParams->GetValue());
pParams = pParams->GetNext();
}
return pLine;
}
bool CInnoScript::CLine::IsHash() {
return false;
}
//////////////////////////////////////////////////////////////////////
// CLineComment class.
CInnoScript::CLineComment::CLineComment(SECTION sec,LPCTSTR pszLine) : CLine(sec) {
int nLength = _tcslen(pszLine);
m_pszLine = new char[nLength+1];
_tcscpy(m_pszLine,pszLine);
}
CInnoScript::CLineComment::~CLineComment() {
if(m_pszLine) delete []m_pszLine;
}
void CInnoScript::CLineComment::Write(LPSTR pszOut,UINT nLength) {
if(_tcslen(m_pszLine)<nLength) {
_tcscpy(pszOut,m_pszLine);
if(m_dwUserFlags & FLG_CONCAT) {
if(_tcslen(pszOut)+3>nLength) return;
if(*pszOut) {
_tcscat(pszOut,";");
}
_tcscat(pszOut," \\");
}
} else
*pszOut = 0;
}
LPCTSTR CInnoScript::CLineComment::GetComment() {
return m_pszLine;
}
CInnoScript::CLine* CInnoScript::CLineComment::Copy() {
CLine* pLine = new CLineComment(m_sec,m_pszLine);
pLine->m_dwUserFlags = m_dwUserFlags;
CParam* pParams = m_pParams;
while(pParams) {
pLine->AddParameter(pParams->GetName(),pParams->GetValue());
pParams = pParams->GetNext();
}
return pLine;
}
//////////////////////////////////////////////////////////////////////
// CLineHash class.
CInnoScript::CLineHash::CLineHash(SECTION sec,LPCTSTR pszLine) : CLine(sec) {
int nLength = _tcslen(pszLine);
m_pszLine = new char[nLength+1];
_tcscpy(m_pszLine,pszLine);
}
CInnoScript::CLineHash::~CLineHash() {
if(m_pszLine) delete []m_pszLine;
}
void CInnoScript::CLineHash::Write(LPSTR pszOut,UINT nLength) {
if(_tcslen(m_pszLine)<nLength) {
_tcscpy(pszOut,m_pszLine);
if(m_dwUserFlags & FLG_CONCAT) {
if(_tcslen(pszOut)+3>nLength) return;
if(*pszOut) {
_tcscat(pszOut,";");
}
_tcscat(pszOut," \\");
}
} else
*pszOut = 0;
}
LPCTSTR CInnoScript::CLineHash::GetComment() {
return m_pszLine;
}
CInnoScript::CLine* CInnoScript::CLineHash::Copy() {
CLine* pLine = new CLineHash(m_sec,m_pszLine);
pLine->m_dwUserFlags = m_dwUserFlags;
CParam* pParams = m_pParams;
while(pParams) {
pLine->AddParameter(pParams->GetName(),pParams->GetValue());
pParams = pParams->GetNext();
}
return pLine;
}
bool CInnoScript::CLineHash::IsHash() {
return true;
}
//////////////////////////////////////////////////////////////////////
// CLineSetup class.
CInnoScript::CLineSetup::CLineSetup(SECTION sec,LPCTSTR pszLine) : CLine(sec) {
CToken params(pszLine,"=");
LPCTSTR pszParam = params.GetNext();
LPCTSTR pszValue = UnQuote(params.GetRest());
if(!pszParam /*|| !pszValue*/) throw "Invalid line.";
// Add all parameters as strings
if(m_pParams)
m_pParams->AddTail(new CParam(pszParam,pszValue));
else
m_pParams = new CParam(pszParam,pszValue);
}
CInnoScript::CLineSetup::CLineSetup(SECTION sec) : CLine(sec) {
}
CInnoScript::CLineSetup::~CLineSetup() {}
void CInnoScript::CLineSetup::Write(LPSTR pszOut,UINT nLength) {
*pszOut = 0;
if(!m_strIndent.IsEmpty())
_tcscpy(pszOut,m_strIndent);
CParam* pParam = m_pParams;
while(pParam) {
_tcscpy(pszOut,pParam->GetName());
_tcscat(pszOut,"=");
_tcscat(pszOut,pParam->GetValue());
pParam = pParam->GetNext();
}
}
LPCTSTR CInnoScript::CLineSetup::GetKey() {
return m_pParams ? m_pParams->GetName() : NULL;
}
LPCTSTR CInnoScript::CLineSetup::GetValue() {
return m_pParams ? m_pParams->GetValue() : NULL;
}
void CInnoScript::CLineSetup::SetKey(LPCTSTR pszKey) {
if(m_pParams)
m_pParams->SetName(pszKey);
else
m_pParams = new CParam(pszKey,NULL);
}
void CInnoScript::CLineSetup::SetValue(LPCTSTR pszValue) {
m_pParams->SetValue(pszValue);
}
CInnoScript::CLine* CInnoScript::CLineSetup::Copy() {
CLine* pLine = new CLineSetup(m_sec);
pLine->m_dwUserFlags = m_dwUserFlags;
CParam* pParams = m_pParams;
while(pParams) {
pLine->AddParameter(pParams->GetName(),pParams->GetValue());
pParams = pParams->GetNext();
}
return pLine;
}
//////////////////////////////////////////////////////////////////////
// CLineParam class.
CInnoScript::CLineParam::CLineParam(SECTION sec,LPCTSTR pszLine) : CLine(sec) {
CToken tokens(pszLine,";");
LPCTSTR psz;
while(psz=tokens.GetNext()) {
CToken params(psz,":");
LPCTSTR pszParam = params.GetNext();
LPCTSTR pszValue = UnQuote(params.GetRest());
if(!pszParam) throw "Invalid line.";
// Add all parameters as strings
if(m_pParams)
m_pParams->AddTail(new CParam(pszParam,pszValue));
else
m_pParams = new CParam(pszParam,pszValue);
}
}
CInnoScript::CLineParam::~CLineParam() {}
CInnoScript::CLine* CInnoScript::CLineParam::Copy() {
CLine* pLine = new CLineParam(m_sec,"");
pLine->m_dwUserFlags = m_dwUserFlags;
CParam* pParams = m_pParams;
while(pParams) {
pLine->AddParameter(pParams->GetName(),pParams->GetValue());
pParams = pParams->GetNext();
}
return pLine;
}
|
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++98, c++03, c++11, c++14, c++17
// UNSUPPORTED: libcpp-no-concepts
#include <cassert>
#include <numbers>
constexpr bool tests() {
assert(std::numbers::e == 0x1.5bf0a8b145769p+1);
assert(std::numbers::e_v<double> == 0x1.5bf0a8b145769p+1);
assert(std::numbers::e_v<long double> == 0x1.5bf0a8b145769p+1l);
assert(std::numbers::e_v<float> == 0x1.5bf0a8p+1f);
assert(std::numbers::log2e == 0x1.71547652b82fep+0);
assert(std::numbers::log2e_v<double> == 0x1.71547652b82fep+0);
assert(std::numbers::log2e_v<long double> == 0x1.71547652b82fep+0l);
assert(std::numbers::log2e_v<float> == 0x1.715476p+0f);
assert(std::numbers::log10e == 0x1.bcb7b1526e50ep-2);
assert(std::numbers::log10e_v<double> == 0x1.bcb7b1526e50ep-2);
assert(std::numbers::log10e_v<long double> == 0x1.bcb7b1526e50ep-2l);
assert(std::numbers::log10e_v<float> == 0x1.bcb7b15p-2f);
assert(std::numbers::pi == 0x1.921fb54442d18p+1);
assert(std::numbers::pi_v<double> == 0x1.921fb54442d18p+1);
assert(std::numbers::pi_v<long double> == 0x1.921fb54442d18p+1l);
assert(std::numbers::pi_v<float> == 0x1.921fb54p+1f);
assert(std::numbers::inv_pi == 0x1.45f306dc9c883p-2);
assert(std::numbers::inv_pi_v<double> == 0x1.45f306dc9c883p-2);
assert(std::numbers::inv_pi_v<long double> == 0x1.45f306dc9c883p-2l);
assert(std::numbers::inv_pi_v<float> == 0x1.45f306p-2f);
assert(std::numbers::inv_sqrtpi == 0x1.20dd750429b6dp-1);
assert(std::numbers::inv_sqrtpi_v<double> == 0x1.20dd750429b6dp-1);
assert(std::numbers::inv_sqrtpi_v<long double> == 0x1.20dd750429b6dp-1l);
assert(std::numbers::inv_sqrtpi_v<float> == 0x1.20dd76p-1f);
assert(std::numbers::ln2 == 0x1.62e42fefa39efp-1);
assert(std::numbers::ln2_v<double> == 0x1.62e42fefa39efp-1);
assert(std::numbers::ln2_v<long double> == 0x1.62e42fefa39efp-1l);
assert(std::numbers::ln2_v<float> == 0x1.62e42fp-1f);
assert(std::numbers::ln10 == 0x1.26bb1bbb55516p+1);
assert(std::numbers::ln10_v<double> == 0x1.26bb1bbb55516p+1);
assert(std::numbers::ln10_v<long double> == 0x1.26bb1bbb55516p+1l);
assert(std::numbers::ln10_v<float> == 0x1.26bb1bp+1f);
assert(std::numbers::sqrt2 == 0x1.6a09e667f3bcdp+0);
assert(std::numbers::sqrt2_v<double> == 0x1.6a09e667f3bcdp+0);
assert(std::numbers::sqrt2_v<long double> == 0x1.6a09e667f3bcdp+0l);
assert(std::numbers::sqrt2_v<float> == 0x1.6a09e6p+0f);
assert(std::numbers::sqrt3 == 0x1.bb67ae8584caap+0);
assert(std::numbers::sqrt3_v<double> == 0x1.bb67ae8584caap+0);
assert(std::numbers::sqrt3_v<long double> == 0x1.bb67ae8584caap+0l);
assert(std::numbers::sqrt3_v<float> == 0x1.bb67aep+0f);
assert(std::numbers::inv_sqrt3 == 0x1.279a74590331cp-1);
assert(std::numbers::inv_sqrt3_v<double> == 0x1.279a74590331cp-1);
assert(std::numbers::inv_sqrt3_v<long double> == 0x1.279a74590331cp-1l);
assert(std::numbers::inv_sqrt3_v<float> == 0x1.279a74p-1f);
assert(std::numbers::egamma == 0x1.2788cfc6fb619p-1);
assert(std::numbers::egamma_v<double> == 0x1.2788cfc6fb619p-1);
assert(std::numbers::egamma_v<long double> == 0x1.2788cfc6fb619p-1l);
assert(std::numbers::egamma_v<float> == 0x1.2788cfp-1f);
assert(std::numbers::phi == 0x1.9e3779b97f4a8p+0);
assert(std::numbers::phi_v<double> == 0x1.9e3779b97f4a8p+0);
assert(std::numbers::phi_v<long double> == 0x1.9e3779b97f4a8p+0l);
assert(std::numbers::phi_v<float> == 0x1.9e3779ap+0f);
return true;
}
static_assert(tests());
int main() { tests(); }
|
/// YANG Development Kit
// Copyright 2019 Cisco Systems. All rights reserved
//
////////////////////////////////////////////////////////////////
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
//////////////////////////////////////////////////////////////////
#include <iostream>
#include <string>
#include "ydk/path_api.hpp"
#include "ydk/netconf_provider.hpp"
#include "ydk/crud_service.hpp"
#include "ydk/codec_service.hpp"
#include "ydk/codec_provider.hpp"
#include "ydk/filters.hpp"
#include "ydk/json_subtree_codec.hpp"
#include "ydk_ydktest/openconfig_bgp.hpp"
#include "ydk_ydktest/openconfig_bgp_types.hpp"
#include "ydk_ydktest/openconfig_routing_policy.hpp"
#include "ydk_ydktest/ydktest_sanity.hpp"
#include "ydk_ydktest/ydktest_sanity_types.hpp"
#include "config.hpp"
#include "catch.hpp"
#include "test_utils.hpp"
using namespace ydk;
using namespace ydktest;
using namespace std;
TEST_CASE("json_codec_leaf")
{
JsonSubtreeCodec jcodec{};
NetconfServiceProvider provider("127.0.0.1", "admin", "admin", 12022);
auto & session = provider.get_session();
auto runner = ydktest_sanity::Runner();
auto json = jcodec.encode(runner, session.get_root_schema(), false);
REQUIRE(json == "{\"ydktest-sanity:runner\":null}");
runner.ytypes->built_in_t->number8 = 10;
runner.ytypes->built_in_t->number16 = 102;
json = jcodec.encode(runner, session.get_root_schema(), false);
REQUIRE(json == R"({"ydktest-sanity:runner":{"ytypes":{"built-in-t":{"number16":102,"number8":10}}}})");
auto top_entity = make_shared<ydktest_sanity::Runner>();
auto entity = jcodec.decode(json, top_entity);
auto runner_d = dynamic_cast<ydktest_sanity::Runner*>(entity.get());
REQUIRE(*runner_d == runner);
}
TEST_CASE("json_codec_leaf_list")
{
JsonSubtreeCodec jcodec{};
NetconfServiceProvider provider("127.0.0.1", "admin", "admin", 12022);
auto & session = provider.get_session();
auto runner = ydktest_sanity::Runner();
runner.ytypes->built_in_t->llstring.append("abc");
runner.ytypes->built_in_t->llstring.append("klm");
runner.ytypes->built_in_t->llstring.append("xyz");
auto json = jcodec.encode(runner, session.get_root_schema(), false);
REQUIRE(json == R"({"ydktest-sanity:runner":{"ytypes":{"built-in-t":{"llstring":["abc","klm","xyz"]}}}})");
auto top_entity = make_shared<ydktest_sanity::Runner>();
auto entity = jcodec.decode(json, top_entity);
auto runner_d = dynamic_cast<ydktest_sanity::Runner*>(entity.get());
REQUIRE(*runner_d == runner);
}
TEST_CASE("json_codec_identity")
{
NetconfServiceProvider provider("127.0.0.1", "admin", "admin", 12022);
auto & session = provider.get_session();
JsonSubtreeCodec jcodec{};
auto bgp = make_unique<openconfig_bgp::Bgp>();
bgp->global->config->as = 65172;
bgp->global->config->router_id = "1.2.3.4";
auto afi_safi = make_shared<openconfig_bgp::Bgp::Global::AfiSafis::AfiSafi>();
afi_safi->afi_safi_name = openconfig_bgp_types::L3VPNIPV4UNICAST();
afi_safi->config->afi_safi_name = openconfig_bgp_types::L3VPNIPV4UNICAST();
afi_safi->config->enabled = true;
bgp->global->afi_safis->afi_safi.append(afi_safi);
auto json = jcodec.encode(*bgp, session.get_root_schema());
string expected = R"({
"openconfig-bgp:bgp": {
"global": {
"afi-safis": {
"afi-safi": [
{
"afi-safi-name": "openconfig-bgp-types:L3VPN_IPV4_UNICAST",
"config": {
"afi-safi-name": "openconfig-bgp-types:L3VPN_IPV4_UNICAST",
"enabled": true
}
}
]
},
"config": {
"as": 65172,
"router-id": "1.2.3.4"
}
}
}
})";
REQUIRE(json == expected);
auto top_entity = make_shared<openconfig_bgp::Bgp>();
auto entity = jcodec.decode(json, top_entity);
auto bgp_d = dynamic_cast<openconfig_bgp::Bgp*>(entity.get());
REQUIRE(*bgp_d == *bgp);
}
TEST_CASE("json_codec_identity_subtree")
{
NetconfServiceProvider provider("127.0.0.1", "admin", "admin", 12022);
auto & session = provider.get_session();
JsonSubtreeCodec jcodec{};
auto afi_safi = make_shared<openconfig_bgp::Bgp::Global::AfiSafis::AfiSafi>();
afi_safi->afi_safi_name = openconfig_bgp_types::L3VPNIPV4UNICAST();
afi_safi->config->afi_safi_name = openconfig_bgp_types::L3VPNIPV4UNICAST();
afi_safi->config->enabled = true;
auto json = jcodec.encode(*afi_safi, session.get_root_schema());
string expected = R"({
"openconfig-bgp:afi-safi": {
"afi-safi-name": "openconfig-bgp-types:L3VPN_IPV4_UNICAST",
"config": {
"afi-safi-name": "openconfig-bgp-types:L3VPN_IPV4_UNICAST",
"enabled": true
}
}
})";
REQUIRE(json == expected);
auto top_entity = make_shared<openconfig_bgp::Bgp::Global::AfiSafis::AfiSafi>();
auto entity = jcodec.decode(json, top_entity);
auto afi_safi_d = dynamic_cast<openconfig_bgp::Bgp::Global::AfiSafis::AfiSafi*>(entity.get());
REQUIRE(*afi_safi_d == *afi_safi);
}
TEST_CASE("json_codec_no_key_list")
{
NetconfServiceProvider provider("127.0.0.1", "admin", "admin", 12022);
auto & session = provider.get_session();
JsonSubtreeCodec jcodec{};
auto runner = ydktest_sanity::Runner();
auto t1 = make_shared<ydktest_sanity::Runner::NoKeyList>(); t1->test = "abc";
auto t2 = make_shared<ydktest_sanity::Runner::NoKeyList>(); t2->test = "xyz";
runner.no_key_list.extend( { t1, t2 });
auto json = jcodec.encode(runner, session.get_root_schema(), false);
REQUIRE(json == R"({"ydktest-sanity:runner":{"no-key-list":[{"test":"abc"},{"test":"xyz"}]}})");
auto top_entity = make_shared<ydktest_sanity::Runner>();
auto entity = jcodec.decode(json, top_entity);
auto runner_d = dynamic_cast<ydktest_sanity::Runner*>(entity.get());
REQUIRE(*runner_d == runner);
}
TEST_CASE("json_codec_augment_presence")
{
ydk::path::Repository repo{TEST_HOME};
ydk::path::NetconfSession session{repo, "127.0.0.1", "admin", "admin", 12022};
auto i = make_shared<ydktest_sanity::Runner::Passive::Interfac>();
i->test = "abc";
auto passive = make_shared<ydktest_sanity::Runner::Passive>();
passive->name = "xyz";
passive->interfac.append(i);
auto r_1 = make_shared<ydktest_sanity::Runner>();
r_1->passive.append(passive);
passive->testc->xyz = make_shared<ydktest_sanity::Runner::Passive::Testc::Xyz>();
passive->testc->xyz->parent = passive.get();
passive->testc->xyz->xyz = 25;
CodecServiceProvider codec_provider{EncodingFormat::JSON};
CodecService codec_service{};
auto jsonC = codec_service.encode(codec_provider, *r_1, false);
auto cs_runner = codec_service.decode(codec_provider, jsonC, make_shared<ydktest_sanity::Runner>());
REQUIRE(*r_1 == *cs_runner);
JsonSubtreeCodec json_codec{};
auto jsonJ = json_codec.encode(*r_1, session.get_root_schema(), false);
auto runner = json_codec.decode(jsonC, make_shared<ydktest_sanity::Runner>());
REQUIRE(*r_1 == *runner);
}
|
#include <sstream>
#include <vector>
#include "regex"
#include <iostream>
#include "NumberDecorator.hpp"
std::string NumberDecorator::toString() {
std::stringstream ss(StreamDecorator::toString());
std::string temp;
std::vector<std::string> tokens;
std::string tokenized;
std::regex pattern("^\\d+$");
std::smatch result;
while (getline(ss, temp, ' ')) {
tokens.push_back(temp);
}
for (int i = 0; i < tokens.size(); ++i) {
if (std::regex_search(tokens[i], result, pattern)) {
tokenized += " +" + tokens[i];
} else {
tokenized += " " + tokens[i];
}
}
return tokenized;
}
|
/**
* UGENE - Integrated Bioinformatics Tools.
* Copyright (C) 2008-2012 UniPro <ugene@unipro.ru>
* http://ugene.unipro.ru
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include "TCoffeeSupportTask.h"
#include "TCoffeeSupport.h"
#include <U2Core/AppContext.h>
#include <U2Core/AppSettings.h>
#include <U2Core/Counter.h>
#include <U2Core/UserApplicationsSettings.h>
#include <U2Core/DocumentModel.h>
#include <U2Core/ExternalToolRegistry.h>
#include <U2Core/Log.h>
#include <U2Core/ProjectModel.h>
#include <U2Core/MAlignmentObject.h>
#include <U2Core/MSAUtils.h>
#include <U2Core/AddDocumentTask.h>
#include <U2Core/IOAdapterUtils.h>
#include <U2Core/U2SafePoints.h>
#include <U2Gui/OpenViewTask.h>
namespace U2 {
void TCoffeeSupportTaskSettings::reset() {
gapExtenstionPenalty = -1;
gapOpenPenalty = -1;
numIterations=0;
inputFilePath="";
}
TCoffeeSupportTask::TCoffeeSupportTask(MAlignmentObject* _mAObject, const TCoffeeSupportTaskSettings& _settings) :
Task("Run T-Coffee alignment task", TaskFlags_NR_FOSCOE),
mAObject(_mAObject), settings(_settings)
{
GCOUNTER( cvar, tvar, "TCoffeeSupportTask" );
currentDocument = mAObject->getDocument();
saveTemporaryDocumentTask=NULL;
loadTmpDocumentTask=NULL;
tCoffeeTask=NULL;
newDocument=NULL;
logParser=NULL;
}
void TCoffeeSupportTask::prepare(){
algoLog.info(tr("T-Coffee alignment started"));
//Add new subdir for temporary files
//Directory name is ExternalToolName + CurrentDate + CurrentTime
QString tmpDirName = "TCoffee_"+QString::number(this->getTaskId())+"_"+
QDate::currentDate().toString("dd.MM.yyyy")+"_"+
QTime::currentTime().toString("hh.mm.ss.zzz")+"_"+
QString::number(QCoreApplication::applicationPid())+"/";
QString tmpDirPath = AppContext::getAppSettings()->getUserAppsSettings()->getCurrentProcessTemporaryDirPath(TCOFFEE_TMP_DIR) + "/" + tmpDirName;
url = tmpDirPath + "tmp.fa";
ioLog.details(tr("Saving data to temporary file '%1'").arg(url));
//Check and remove subdir for temporary files
QDir tmpDir(tmpDirPath);
if(tmpDir.exists()){
foreach(QString file, tmpDir.entryList()){
tmpDir.remove(file);
}
if(!tmpDir.rmdir(tmpDir.absolutePath())){
stateInfo.setError(tr("Subdir for temporary files exists. Can not remove this directory."));
return;
}
}
if(!tmpDir.mkpath(tmpDirPath)){
stateInfo.setError(tr("Can not create directory for temporary files."));
return;
}
saveTemporaryDocumentTask=new SaveMSA2SequencesTask(mAObject->getMAlignment(), url, false, BaseDocumentFormats::FASTA);
saveTemporaryDocumentTask->setSubtaskProgressWeight(5);
addSubTask(saveTemporaryDocumentTask);
}
QList<Task*> TCoffeeSupportTask::onSubTaskFinished(Task* subTask) {
QList<Task*> res;
if(subTask->hasError()) {
stateInfo.setError(subTask->getError());
return res;
}
if(hasError() || isCanceled()) {
return res;
}
QString outputUrl = url+".msf";
if(subTask==saveTemporaryDocumentTask){
QStringList arguments;
if(url.contains(" ")){
stateInfo.setError("Temporary directory path have space(s). Try select any other directory without spaces.");
return res;
}
arguments <<url;
arguments <<"-output"<<"msf";
if(settings.gapOpenPenalty != -1) {
arguments <<"-gapopen" << QString::number(settings.gapOpenPenalty);
}
if(settings.gapExtenstionPenalty != -1) {
arguments <<"-gapext"<<QString::number(settings.gapExtenstionPenalty);
}
if(settings.numIterations!= -1) {
arguments <<"-iterate"<<QString::number(settings.numIterations);
}
arguments <<"-outfile"<<outputUrl;
logParser=new TCoffeeLogParser();
tCoffeeTask=new ExternalToolRunTask(TCOFFEE_TOOL_NAME, arguments, logParser);
tCoffeeTask->setSubtaskProgressWeight(95);
res.append(tCoffeeTask);
}else if(subTask==tCoffeeTask){
assert(logParser);
delete logParser;
if(!QFileInfo(outputUrl).exists()){
if(AppContext::getExternalToolRegistry()->getByName(TCOFFEE_TOOL_NAME)->isValid()){
stateInfo.setError(tr("Output file %1 not found").arg(outputUrl));
}else{
stateInfo.setError(tr("Output file %3 not found. May be %1 tool path '%2' not valid?")
.arg(AppContext::getExternalToolRegistry()->getByName(TCOFFEE_TOOL_NAME)->getName())
.arg(AppContext::getExternalToolRegistry()->getByName(TCOFFEE_TOOL_NAME)->getPath())
.arg(outputUrl));
}
emit si_stateChanged();
return res;
}
ioLog.details(tr("Loading output file '%1'").arg(outputUrl));
IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(BaseIOAdapters::LOCAL_FILE);
QVariantMap hints;
loadTmpDocumentTask = new LoadDocumentTask(BaseDocumentFormats::MSF, outputUrl, iof, hints);
loadTmpDocumentTask->setSubtaskProgressWeight(5);
res.append(loadTmpDocumentTask);
} else if (subTask==loadTmpDocumentTask) {
newDocument=loadTmpDocumentTask->takeDocument();
SAFE_POINT(newDocument!=NULL, QString("output document '%1' not loaded").arg(newDocument->getURLString()), res);
SAFE_POINT(newDocument->getObjects().length()!=0, QString("no objects in output document '%1'").arg(newDocument->getURLString()), res);
//move MAlignment from new alignment to old document
MAlignmentObject* newMAligmentObject=qobject_cast<MAlignmentObject*>(newDocument->getObjects().first());
assert(newMAligmentObject!=NULL);
resultMA=newMAligmentObject->getMAlignment();
mAObject->setMAlignment(resultMA);
if (currentDocument != NULL){
currentDocument->setModified(true);
}
algoLog.info(tr("T-Coffee alignment successfully finished"));
//new document deleted in destructor of LoadDocumentTask
}
return res;
}
Task::ReportResult TCoffeeSupportTask::report(){
//Remove subdir for temporary files, that created in prepare
if(!url.isEmpty()){
QDir tmpDir(QFileInfo(url).absoluteDir());
foreach(QString file, tmpDir.entryList()){
tmpDir.remove(file);
}
if(!tmpDir.rmdir(tmpDir.absolutePath())){
stateInfo.setError(tr("Can not remove directory for temporary files."));
emit si_stateChanged();
}
}
return ReportResult_Finished;
}
////////////////////////////////////////
//TCoffeeWithExtFileSpecifySupportTask
TCoffeeWithExtFileSpecifySupportTask::TCoffeeWithExtFileSpecifySupportTask(const TCoffeeSupportTaskSettings& _settings) :
Task("Run T-Coffee alignment task", TaskFlags_NR_FOSCOE),
settings(_settings)
{
GCOUNTER( cvar, tvar, "TCoffeeSupportTask" );
mAObject = NULL;
currentDocument = NULL;
saveDocumentTask = NULL;
loadDocumentTask = NULL;
tCoffeeSupportTask = NULL;
cleanDoc = true;
}
TCoffeeWithExtFileSpecifySupportTask::~TCoffeeWithExtFileSpecifySupportTask(){
if (cleanDoc){
delete currentDocument;
}
}
void TCoffeeWithExtFileSpecifySupportTask::prepare(){
DocumentFormatConstraints c;
c.checkRawData = true;
c.supportedObjectTypes += GObjectTypes::MULTIPLE_ALIGNMENT;
c.rawData = IOAdapterUtils::readFileHeader(settings.inputFilePath);
QList<DocumentFormatId> formats = AppContext::getDocumentFormatRegistry()->selectFormats(c);
if (formats.isEmpty()) {
stateInfo.setError( tr("input_format_error") );
return;
}
DocumentFormatId alnFormat = formats.first();
IOAdapterFactory* iof = AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(IOAdapterUtils::url2io(settings.inputFilePath));
QVariantMap hints;
if(alnFormat == BaseDocumentFormats::FASTA){
hints[DocumentReadingMode_SequenceAsAlignmentHint] = true;
}
loadDocumentTask = new LoadDocumentTask(alnFormat, settings.inputFilePath, iof, hints);
addSubTask(loadDocumentTask);
}
QList<Task*> TCoffeeWithExtFileSpecifySupportTask::onSubTaskFinished(Task* subTask) {
QList<Task*> res;
if (subTask->hasError()) {
stateInfo.setError(subTask->getError());
return res;
}
if (hasError() || isCanceled()) {
return res;
}
if (subTask==loadDocumentTask){
currentDocument=loadDocumentTask->takeDocument();
SAFE_POINT(currentDocument != NULL, QString("Failed loading document: %1").arg(loadDocumentTask->getURLString()), res);
SAFE_POINT(currentDocument->getObjects().length() == 1, QString("Number of objects != 1 : %1").arg(loadDocumentTask->getURLString()), res);
mAObject=qobject_cast<MAlignmentObject*>(currentDocument->getObjects().first());
SAFE_POINT(mAObject != NULL, QString("MA object not found!: %1").arg(loadDocumentTask->getURLString()), res);
tCoffeeSupportTask=new TCoffeeSupportTask(mAObject,settings);
res.append(tCoffeeSupportTask);
} else if (subTask == tCoffeeSupportTask){
saveDocumentTask = new SaveDocumentTask(currentDocument,AppContext::getIOAdapterRegistry()->getIOAdapterFactoryById(IOAdapterUtils::url2io(settings.outputFilePath)),settings.outputFilePath);
res.append(saveDocumentTask);
} else if (subTask==saveDocumentTask){
//Project* proj = AppContext::getProject();
//if (proj == NULL) {
// res.append(AppContext::getProjectLoader()->openWithProjectTask(currentDocument->getURL(), currentDocument->getGHintsMap()));
//} else {
// Document* projDoc = proj->findDocumentByURL(currentDocument->getURL());
// if (projDoc != NULL) {
// projDoc->setLastUpdateTime();
// res.append(new LoadUnloadedDocumentAndOpenViewTask(projDoc));
// } else {
// // Add document to project
// res.append(new AddDocumentAndOpenViewTask(currentDocument));
// cleanDoc = false;
// }
//}
Task* openTask = AppContext::getProjectLoader()->openWithProjectTask(settings.outputFilePath);
res << openTask;
}
return res;
}
Task::ReportResult TCoffeeWithExtFileSpecifySupportTask::report(){
return ReportResult_Finished;
}
////////////////////////////////////////
//TCoffeeLogParser
TCoffeeLogParser::TCoffeeLogParser()
{
progress=0;
}
void TCoffeeLogParser::parseOutput(const QString& partOfLog){
Q_UNUSED(partOfLog)
}
void TCoffeeLogParser::parseErrOutput(const QString& partOfLog){
lastPartOfLog=partOfLog.split(QRegExp("(\n|\r)"));
lastPartOfLog.first()=lastErrLine+lastPartOfLog.first();
lastErrLine=lastPartOfLog.takeLast();
foreach(QString buf, lastPartOfLog){
if(buf.contains("WARNING")){
algoLog.info("T-Coffee: " + buf);
}else{
algoLog.trace(buf);
}
}
}
int TCoffeeLogParser::getProgress(){
/* parse progress string:
[Submit Job][TOT= 18][ 22 %][ELAPSED TIME: 0 sec.]
*/
if(!lastPartOfLog.isEmpty()){
QString lastMessage=lastPartOfLog.last();
if(lastMessage.contains(QRegExp("\\[Submit +Job\\]\\[TOT="))){
QRegExp rx("(.*)\\[ +(\\d+) %\\](.*)");
assert(rx.indexIn(lastMessage)>-1);
rx.indexIn(lastMessage);
return rx.cap(2).toInt();
}
}
return progress;
}
}//namespace
|
//
//
// Copyright 2021 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
#include <grpc/support/port_platform.h>
#include "src/core/ext/filters/server_config_selector/server_config_selector_filter.h"
#include "src/core/ext/filters/server_config_selector/server_config_selector.h"
#include "src/core/ext/service_config/service_config_call_data.h"
#include "src/core/lib/transport/error_utils.h"
namespace grpc_core {
namespace {
class ChannelData {
public:
static grpc_error_handle Init(grpc_channel_element* elem,
grpc_channel_element_args* args);
static void Destroy(grpc_channel_element* elem);
absl::StatusOr<RefCountedPtr<ServerConfigSelector>> config_selector() {
MutexLock lock(&mu_);
return config_selector_.value();
}
private:
class ServerConfigSelectorWatcher
: public ServerConfigSelectorProvider::ServerConfigSelectorWatcher {
public:
explicit ServerConfigSelectorWatcher(ChannelData* chand) : chand_(chand) {}
void OnServerConfigSelectorUpdate(
absl::StatusOr<RefCountedPtr<ServerConfigSelector>> update) override {
MutexLock lock(&chand_->mu_);
chand_->config_selector_ = std::move(update);
}
private:
ChannelData* chand_;
};
explicit ChannelData(RefCountedPtr<ServerConfigSelectorProvider>
server_config_selector_provider);
~ChannelData();
RefCountedPtr<ServerConfigSelectorProvider> server_config_selector_provider_;
Mutex mu_;
absl::optional<absl::StatusOr<RefCountedPtr<ServerConfigSelector>>>
config_selector_ ABSL_GUARDED_BY(mu_);
};
class CallData {
public:
static grpc_error_handle Init(grpc_call_element* elem,
const grpc_call_element_args* args);
static void Destroy(grpc_call_element* elem,
const grpc_call_final_info* /* final_info */,
grpc_closure* /* then_schedule_closure */);
static void StartTransportStreamOpBatch(grpc_call_element* elem,
grpc_transport_stream_op_batch* op);
private:
CallData(grpc_call_element* elem, const grpc_call_element_args& args);
~CallData();
static void RecvInitialMetadataReady(void* user_data,
grpc_error_handle error);
static void RecvTrailingMetadataReady(void* user_data,
grpc_error_handle error);
void MaybeResumeRecvTrailingMetadataReady();
grpc_call_context_element* call_context_;
CallCombiner* call_combiner_;
ServiceConfigCallData service_config_call_data_;
// Overall error for the call
grpc_error_handle error_ = GRPC_ERROR_NONE;
// State for keeping track of recv_initial_metadata
grpc_metadata_batch* recv_initial_metadata_ = nullptr;
grpc_closure* original_recv_initial_metadata_ready_ = nullptr;
grpc_closure recv_initial_metadata_ready_;
// State for keeping of track of recv_trailing_metadata
grpc_closure* original_recv_trailing_metadata_ready_;
grpc_closure recv_trailing_metadata_ready_;
grpc_error_handle recv_trailing_metadata_ready_error_;
bool seen_recv_trailing_metadata_ready_ = false;
};
// ChannelData
grpc_error_handle ChannelData::Init(grpc_channel_element* elem,
grpc_channel_element_args* args) {
GPR_ASSERT(elem->filter == &kServerConfigSelectorFilter);
RefCountedPtr<ServerConfigSelectorProvider> server_config_selector_provider =
ServerConfigSelectorProvider::GetFromChannelArgs(*args->channel_args);
if (server_config_selector_provider == nullptr) {
return GRPC_ERROR_CREATE_FROM_STATIC_STRING(
"No ServerConfigSelectorProvider object found");
}
new (elem->channel_data)
ChannelData(std::move(server_config_selector_provider));
return GRPC_ERROR_NONE;
}
void ChannelData::Destroy(grpc_channel_element* elem) {
auto* chand = static_cast<ChannelData*>(elem->channel_data);
chand->~ChannelData();
}
ChannelData::ChannelData(
RefCountedPtr<ServerConfigSelectorProvider> server_config_selector_provider)
: server_config_selector_provider_(
std::move(server_config_selector_provider)) {
GPR_ASSERT(server_config_selector_provider_ != nullptr);
auto server_config_selector_watcher =
absl::make_unique<ServerConfigSelectorWatcher>(this);
auto config_selector = server_config_selector_provider_->Watch(
std::move(server_config_selector_watcher));
MutexLock lock(&mu_);
// It's possible for the watcher to have already updated config_selector_
if (!config_selector_.has_value()) {
config_selector_ = std::move(config_selector);
}
}
ChannelData::~ChannelData() { server_config_selector_provider_->CancelWatch(); }
// CallData
grpc_error_handle CallData::Init(grpc_call_element* elem,
const grpc_call_element_args* args) {
new (elem->call_data) CallData(elem, *args);
return GRPC_ERROR_NONE;
}
void CallData::Destroy(grpc_call_element* elem,
const grpc_call_final_info* /*final_info*/,
grpc_closure* /*then_schedule_closure*/) {
auto* calld = static_cast<CallData*>(elem->call_data);
calld->~CallData();
}
void CallData::StartTransportStreamOpBatch(grpc_call_element* elem,
grpc_transport_stream_op_batch* op) {
CallData* calld = static_cast<CallData*>(elem->call_data);
if (op->recv_initial_metadata) {
calld->recv_initial_metadata_ =
op->payload->recv_initial_metadata.recv_initial_metadata;
calld->original_recv_initial_metadata_ready_ =
op->payload->recv_initial_metadata.recv_initial_metadata_ready;
op->payload->recv_initial_metadata.recv_initial_metadata_ready =
&calld->recv_initial_metadata_ready_;
}
if (op->recv_trailing_metadata) {
// We might generate errors on receiving initial metadata which we need to
// bubble up through recv_trailing_metadata_ready
calld->original_recv_trailing_metadata_ready_ =
op->payload->recv_trailing_metadata.recv_trailing_metadata_ready;
op->payload->recv_trailing_metadata.recv_trailing_metadata_ready =
&calld->recv_trailing_metadata_ready_;
}
// Chain to the next filter.
grpc_call_next_op(elem, op);
}
CallData::CallData(grpc_call_element* elem, const grpc_call_element_args& args)
: call_context_(args.context), call_combiner_(args.call_combiner) {
GRPC_CLOSURE_INIT(&recv_initial_metadata_ready_, RecvInitialMetadataReady,
elem, grpc_schedule_on_exec_ctx);
GRPC_CLOSURE_INIT(&recv_trailing_metadata_ready_, RecvTrailingMetadataReady,
elem, grpc_schedule_on_exec_ctx);
}
CallData::~CallData() {
// Remove the entry from call context, just in case anyone above us
// tries to look at it during call stack destruction.
call_context_[GRPC_CONTEXT_SERVICE_CONFIG_CALL_DATA].value = nullptr;
GRPC_ERROR_UNREF(error_);
}
void CallData::RecvInitialMetadataReady(void* user_data,
grpc_error_handle error) {
grpc_call_element* elem = static_cast<grpc_call_element*>(user_data);
CallData* calld = static_cast<CallData*>(elem->call_data);
ChannelData* chand = static_cast<ChannelData*>(elem->channel_data);
if (error == GRPC_ERROR_NONE) {
auto config_selector = chand->config_selector();
if (config_selector.ok()) {
auto call_config =
config_selector.value()->GetCallConfig(calld->recv_initial_metadata_);
if (call_config.error != GRPC_ERROR_NONE) {
calld->error_ = call_config.error;
error = call_config.error; // Does not take a ref
} else {
calld->service_config_call_data_ =
ServiceConfigCallData(std::move(call_config.service_config),
call_config.method_configs, {});
calld->call_context_[GRPC_CONTEXT_SERVICE_CONFIG_CALL_DATA].value =
&calld->service_config_call_data_;
}
} else {
calld->error_ = absl_status_to_grpc_error(config_selector.status());
error = calld->error_;
}
}
calld->MaybeResumeRecvTrailingMetadataReady();
grpc_closure* closure = calld->original_recv_initial_metadata_ready_;
calld->original_recv_initial_metadata_ready_ = nullptr;
Closure::Run(DEBUG_LOCATION, closure, GRPC_ERROR_REF(error));
}
void CallData::RecvTrailingMetadataReady(void* user_data,
grpc_error_handle error) {
grpc_call_element* elem = static_cast<grpc_call_element*>(user_data);
CallData* calld = static_cast<CallData*>(elem->call_data);
if (calld->original_recv_initial_metadata_ready_ != nullptr) {
calld->seen_recv_trailing_metadata_ready_ = true;
calld->recv_trailing_metadata_ready_error_ = GRPC_ERROR_REF(error);
GRPC_CALL_COMBINER_STOP(calld->call_combiner_,
"Deferring RecvTrailingMetadataReady until after "
"RecvInitialMetadataReady");
return;
}
error = grpc_error_add_child(GRPC_ERROR_REF(error), calld->error_);
calld->error_ = GRPC_ERROR_NONE;
grpc_closure* closure = calld->original_recv_trailing_metadata_ready_;
calld->original_recv_trailing_metadata_ready_ = nullptr;
Closure::Run(DEBUG_LOCATION, closure, error);
}
void CallData::MaybeResumeRecvTrailingMetadataReady() {
if (seen_recv_trailing_metadata_ready_) {
seen_recv_trailing_metadata_ready_ = false;
grpc_error_handle error = recv_trailing_metadata_ready_error_;
recv_trailing_metadata_ready_error_ = GRPC_ERROR_NONE;
GRPC_CALL_COMBINER_START(call_combiner_, &recv_trailing_metadata_ready_,
error, "Continuing RecvTrailingMetadataReady");
}
}
} // namespace
const grpc_channel_filter kServerConfigSelectorFilter = {
CallData::StartTransportStreamOpBatch,
grpc_channel_next_op,
sizeof(CallData),
CallData::Init,
grpc_call_stack_ignore_set_pollset_or_pollset_set,
CallData::Destroy,
sizeof(ChannelData),
ChannelData::Init,
ChannelData::Destroy,
grpc_channel_next_get_info,
"server_config_selector_filter",
};
} // namespace grpc_core
|
#include <QtGui>
#include <QAction>
#include <QFile>
#include <QKeyEvent>
#include <QMainWindow>
#include <QMenu>
#include <QMenuBar>
#include <QPixmap>
#include <QString>
#include <QTextStream>
#include <QStringList>
#include <QPushButton>
#include <QCheckBox>
#include <QStringList>
#include <QDesktopServices>
#include <QUrl>
#include "quizapp.h"
#include "AminoAcidList.h"
#include "SelectAminoAcidDialog.h"
#include <QuizOptionsDialog.h>
#include <StudyOptionsDialog.h>
#include <QuizDialog.h>
#include <StudyDialog.h>
#include <AdvancedOptionsDialog.h>
#include <ProgressReport.h>
#include <sysfolders.h>
#include <sysscale.h>
#define MIN_WIDTH ppp(630)
#define MIN_HEIGHT ppp(200)
#define MAX_MODES 4
const char *mode[ MAX_MODES ] = {
"Image Naming with Prompt",
"Image Naming without Prompt",
"Image Comparison",
"Image Verification"
};
void QuizApp::writeUserData(QStringList records)
{
QFile outFile;
outFile.setFileName(fname + ".csv");
// If for whatever reason current user file could not be opened
// then current user session info will not be saved
if (!outFile.open( QIODevice::WriteOnly | QIODevice::Text))
{
QMessageBox::warning(this, "Error", tr("Could NOT save this session"));
return;
}
QTextStream out;
out.setDevice(&outFile);
// First record is Advanced settings
// Every other line after that is a progress report
for (int i = 0; i < records.size(); ++i)
{
out << records[ i ].trimmed();
out << "\n";
}
outFile.close();
}
// Create a StringList to be written to file
// Only up to MAX_REPORTS reports are allowed
void QuizApp::updateUserData()
{
// Stores the advanced options of the current session followed by the current progress reports and
// then the rest of the progress reports read from the existing user file.
QStringList records;
// Save advanced options
records << AdvancedOptionsDialog::instance()->getSettings();
QStringList currentRecords = QuizDialog::instance()->getCurrentRecords();
int reportCounter = 0;
int n = currentRecords.size();
// If there are progress reports of the currect session save those
if (n != 0)
{
for (int i = n - 1; i >= 0 && reportCounter < MAX_REPORTS; --i)
{
records << currentRecords[i];
reportCounter++;
}
}
// After saving all the data for the current session
// we append to the end of the list all the previous user data
QFile inFile;
inFile.setFileName(fname + ".csv");
if (!inFile.open( QIODevice::ReadOnly | QIODevice::Text))
{
QMessageBox::warning( this, "Error", tr( "Cannot open %1 for reading." ).arg(fname + ".csv"));
inFile.close();
// If the saved user file could not be read try to save the current session
writeUserData(records);
return;
}
QTextStream in;
in.setDevice(&inFile);
QString line = in.readLine();
while (!in.atEnd() && reportCounter < MAX_REPORTS)
{
line = in.readLine();
if (!line.isEmpty())
{
records << line;
++reportCounter;
}
else
break;
}
inFile.close();
// Write all the data back to the user file
writeUserData(records);
}
// Exit the program
bool QuizApp::exit()
{
int yesNo;
yesNo = QMessageBox::question(this, "Quit", "Are you sure?", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
if (yesNo == QMessageBox::Yes)
{
// If the user is logged in then save the current session info
// Otherwise just quit
if (loggedIn)
updateUserData();
return close();
}
return false;
}
// View the Progress Report
void QuizApp::viewProgress()
{
// Move the dialog to the center of the screen
moveDialog(ProgressReport::instance());
ProgressReport::instance()->generateReport(QuizDialog::instance()->getCurrentRecords(), fname);
ProgressReport::instance()->exec();
}
// Show help page
void QuizApp::showHelp()
{
QString urlString = ResourceFolder().c_str();
urlString = "file:///" + urlString + "Help/";
urlString += "Help.html";
QDesktopServices::openUrl(QUrl(urlString));
}
// Show tutorial page
void QuizApp::showTutorial()
{
QString urlString = ResourceFolder().c_str();
urlString = "file:///" + urlString + "Help/";
urlString += "Tutorial.html";
QDesktopServices::openUrl(QUrl(urlString));
}
// Reset the dialog positions when the main dialog is moving
void QuizApp::updateCenter()
{
QRect rect = geometry();
center.setX(rect.center().x());
center.setY(rect.center().y());
ProgressReport::instance(this)->setCoordinates(center.x(), center.y());
StudyOptionsDialog::instance(this)->setCoordinates(center.x(), center.y());
QuizOptionsDialog::instance(this)->setCoordinates(center.x(), center.y());
}
// Handle main dialog resize event
void QuizApp::resizeEvent(QResizeEvent * e)
{
QSize windowSize = size();
int x = windowSize.width() / 2;
int y = windowSize.height() / 2;
// If the user is not logged in then setup login widgets otherwise quiz and study widgets.
if (!loggedIn)
{
int width = ppp(300);
int height = ppp(100);
int separation = ppp(5);
loginGroupBox->setGeometry(QRect(x - width - separation, y - height / 2, width, height));
loginGroupBox->show();
newUserGroupBox->setGeometry(QRect(x + separation, y - height / 2, width, height));
newUserGroupBox->show();
}
else
{
int buttonWidth = ppp(300);
int buttonHeight = ppp(75);
selectionButton->setGeometry(QRect(x - buttonWidth - ppp(5), y - buttonHeight - ppp(5 + 10), buttonWidth, buttonHeight));
studyButton->setGeometry(QRect(x + ppp(5), y - buttonHeight - ppp(5 + 10), buttonWidth, buttonHeight));
quizButton->setGeometry(QRect(x - buttonWidth - ppp(5), y + ppp(5 + 10), buttonWidth, buttonHeight));
testButton->setGeometry(QRect(x + ppp(5), y + ppp(5 + 10), buttonWidth, buttonHeight));
}
updateCenter();
}
// Handle main dialog move event
void QuizApp::moveEvent(QMoveEvent * m)
{
updateCenter();
}
// Reposition the dialog so that it is in the center of the main dialog
void QuizApp::moveDialog(QDialog * dialog)
{
// First find out the center of the dialog
// with respect to the screen and not relative to itself
QPoint centerOfDialog = dialog->geometry().center() - dialog->geometry().topLeft();
int x = center.x() - centerOfDialog.x();
int y = center.y() - centerOfDialog.y();
dialog->move(x, y);
}
void QuizApp::showSelectAminoAcidDialog()
{
// There are two scenarios when we would want to show this dialog
// One is if the button is clicked directly. Which is this case. The
// other is if the user tried to start a quiz/test or study session
// without selecting an amino acids. The user will be notified that
// in order to start a quiz/test or study session he would have to chose
// amino acids first. If the user agreess then the user will be shown
// this dialog
// Since this is scenario 1 we set the TryingToStudy
// and TryingToTakeQuiz flags to false.
SelectAminoAcidDialog::instance(this)->setTryingToStudy(false);
SelectAminoAcidDialog::instance(this)->setTryingToTakeQuiz(false);
// Position the dialog in the
// middle of the main dialog
moveDialog(SelectAminoAcidDialog::instance());
// Show the dialog.
SelectAminoAcidDialog::instance()->exec();
}
// The Quiz and Test options are exactly the same
// except that in Test mode you don't have the option
// "Image naming with prompt"
void QuizApp::showOptionsDialog(bool mode)
{
// Set the mode, Quiz or Test
QuizOptionsDialog::instance()->setMode(mode);
// Check if Amino Acids are selected. If
// they are the move the Quiz/Test options
// dialog to the center and show it.
if (SelectAminoAcidDialog::instance()->isChosenAminoAcids())
{
moveDialog( QuizOptionsDialog::instance());
QuizOptionsDialog::instance()->exec();
}
// If they are not then ask the user
// if he wants to select Amino Acids or not
else
{
int yesno = QMessageBox::question(this,
"No Amino Acids Selected",
"There are no Amino Acids selected for studying.\n"
"Would you like to select Amino Acids now?",
QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes
);
// If yes then show the select Amino Acid dialog
if ( yesno == QMessageBox::Yes )
{
// We set the TryingToTakeQuiz flag so that
// once the user selects Amino Acids the user
// can be shown the Quiz/Test options dialog
SelectAminoAcidDialog::instance()->setTryingToTakeQuiz(true);
moveDialog(SelectAminoAcidDialog::instance());
SelectAminoAcidDialog::instance()->exec();
}
}
}
void QuizApp::showQuizOptionsDialog()
{
QuizOptionsDialog::instance()->clearComboBox();
for (int i = 0; i < MAX_MODES; ++i)
QuizOptionsDialog::instance()->addItemToComboBox(mode[i]);
showOptionsDialog(true);
}
void QuizApp::showTestOptionsDialog()
{
QuizOptionsDialog::instance()->clearComboBox();
for (int i = 1; i < MAX_MODES; ++i)
QuizOptionsDialog::instance()->addItemToComboBox(mode[i]);
showOptionsDialog(false);
}
void QuizApp::showStudyAminoAcidDialog()
{
// Check if Amino Acids are selected. If they are - move
// the Study options dialog to the center and show it
if (SelectAminoAcidDialog::instance()->isChosenAminoAcids())
{
moveDialog( StudyOptionsDialog::instance() );
StudyOptionsDialog::instance()->exec();
}
else
{
int yesno = QMessageBox::question(this,
"No Amino Acids Selected",
"There are no Amino Acids selected for studying.\n"
"Would you like to select Amino Acids now?",
QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes
);
// If yes then show the select Amino Acid dialog
if (yesno == QMessageBox::Yes)
{
// We set the TryingToStudy flag so that
// once the user selects Amino Acids the user
// can be shown the Study options dialog
SelectAminoAcidDialog::instance()->setTryingToStudy(true);
moveDialog(SelectAminoAcidDialog::instance());
SelectAminoAcidDialog::instance()->exec();
}
}
}
void QuizApp::showAdvancedOptionsDialog()
{
moveDialog(AdvancedOptionsDialog::instance());
AdvancedOptionsDialog::instance()->exec();
}
void QuizApp::create_actions()
{
exitAct = new QAction("E&xit", this);
connect(exitAct, SIGNAL(triggered()), this, SLOT(close()));
viewProgressAct = new QAction("&View Progress", this);
viewProgressAct->setShortcut(tr("Ctrl+V"));
connect(viewProgressAct, SIGNAL(triggered()), this, SLOT(viewProgress()));
aminoAcidSelectionAct = new QAction("Amino Acid Selection", this);
aminoAcidSelectionAct->setShortcut(tr("Ctrl+R"));
connect(aminoAcidSelectionAct, SIGNAL(triggered()), this, SLOT(showSelectAminoAcidDialog()));
studyAct = new QAction("Study", this );
studyAct->setShortcut( tr("Ctrl+S"));
connect(studyAct, SIGNAL(triggered()), this, SLOT(showStudyAminoAcidDialog()));
quizAct = new QAction("Quiz", this);
quizAct->setShortcut(tr("Ctrl+Q"));
connect(quizAct, SIGNAL(triggered()), this, SLOT(showQuizOptionsDialog()));
testAct = new QAction( "Test", this );
testAct->setShortcut(tr("Ctrl+T"));
connect(testAct, SIGNAL(triggered()), this, SLOT(showTestOptionsDialog()));
advancedOptionsAct = new QAction("Advanced Options", this);
connect(advancedOptionsAct, SIGNAL(triggered()), this, SLOT(showAdvancedOptionsDialog()));
helpAct = new QAction( "Help", this );
helpAct->setShortcut( Qt::Key_F1 );
connect(helpAct, SIGNAL(triggered()), this, SLOT(showHelp()));
tutorialAct = new QAction( "Tutorial", this );
connect(tutorialAct, SIGNAL(triggered()), this, SLOT(showTutorial()));
}
void QuizApp::create_menus()
{
fileMenu = new QMenu("&File", this);
fileMenu->addAction(viewProgressAct);
fileMenu->addSeparator();
fileMenu->addAction(exitAct);
runMenu = new QMenu("&Run", this);
runMenu->addAction( aminoAcidSelectionAct );
runMenu->addSeparator();
runMenu->addAction(studyAct);
runMenu->addAction(quizAct);
runMenu->addAction(testAct);
optionsMenu = new QMenu("&Options", this);
optionsMenu->addAction(advancedOptionsAct);
helpMenu = new QMenu("&Help", this);
helpMenu->addAction(helpAct);
helpMenu->addAction(tutorialAct);
menuBar()->addMenu(fileMenu);
menuBar()->addMenu(runMenu);
menuBar()->addMenu(optionsMenu);
menuBar()->addMenu(helpMenu);
}
void QuizApp::create_buttons()
{
QFont font("Times", 20, QFont::Bold);
font.setPixelSize(ppp(20));
selectionButton = new QPushButton("Amino Acid Selection", this);
selectionButton->setFont(font);
selectionButton->show();
QObject::connect(selectionButton, SIGNAL(clicked()), this, SLOT(showSelectAminoAcidDialog()));
studyButton = new QPushButton("Study Amino Acids", this);
studyButton->setFont( font );
studyButton->show();
QObject::connect(studyButton, SIGNAL(clicked()), this, SLOT(showStudyAminoAcidDialog()));
quizButton = new QPushButton("Take a Quiz", this);
quizButton->setFont(font);
quizButton->show();
QObject::connect(quizButton, SIGNAL(clicked()), this, SLOT(showQuizOptionsDialog()));
testButton = new QPushButton("Take a Test", this );
testButton->setFont(font);
testButton->show();
QObject::connect(testButton, SIGNAL(clicked()), this, SLOT(showTestOptionsDialog()));
}
// Called when the user logs in
void QuizApp::init(QString username)
{
// Set the size of the Study and Quiz dialog
// to the size of the main screen
StudyDialog::instance(this)->setSize(size());
QuizDialog::instance(this)->setSize(size());
// Read the advanced options from the last
// saved session and restore those setting
AdvancedOptionsDialog::instance(this)->updateVariables(username);
// Set the flag that user has successfully logged in
loggedIn = true;
// Hide the login widgets
loginGroupBox->hide();
newUserGroupBox->hide();
create_buttons();
create_actions();
create_menus();
updateCenter();
QuizDialog::instance()->setUsername(username);
resizeEvent(0);
}
// Called when the user tries to login
void QuizApp::login()
{
// User information is stored in user files
// in the 'Amino' folder with the name
// <username>.csv
fname = (UserDataFolder()).c_str() + loginLineEdit->text();
QFile inFile(fname + ".csv");
if (!inFile.exists())
{
QMessageBox::warning(this, "User does not exist! ", tr(
"<b>Your file was not found. "
"If you do not have a file please create one by "
"using the create new user box on the right.</b>"
));
loginLineEdit->selectAll();
}
else
init(fname);
}
// Called when the user tries to create a new user
void QuizApp::createNewUser()
{
QString username = newUserLineEdit->text();
fname = (UserDataFolder()).c_str() + username;
qDebug() << "creating user file " << fname;
QFile file(fname + ".csv");
if (file.exists())
{
QMessageBox::warning(this, "User already exists!", tr(
"<b>The username %1 already exists. "
"Please use another username.</b>"
).arg(username)
);
newUserLineEdit->selectAll();
}
else
{
if (file.open(QIODevice::WriteOnly | QIODevice::Text))
{
QMessageBox::information(this, "New user created!", tr(
"<b>Username (%1) has been successfully created. "
"Please remember your username.</b>"
).arg(username)
);
init(fname);
file.close();
}
}
}
// Organize the login related widgets
void QuizApp::createLoginScreen()
{
QFont font("Times", 15, QFont::Bold);
font.setPixelSize(ppp(15));
loginGroupBox = new QGroupBox("Existing Users Login Here.", this);
loginGroupBox->setFont(font);
label1 = new QLabel("Username:", loginGroupBox);
label1->setGeometry(QRect(ppp(10), ppp(25), ppp(100), ppp(25)));
label1->setFont(font);
label1->show();
loginLineEdit = new QLineEdit(loginGroupBox);
loginLineEdit->setGeometry(QRect(ppp(105), ppp(25), ppp(180), ppp(25)));
loginLineEdit->setFont(font);
loginLineEdit->setFocus();
loginLineEdit->show();
QObject::connect(loginLineEdit, SIGNAL(returnPressed()), this, SLOT(login()));
loginButton = new QPushButton("Login", loginGroupBox);
loginButton->setGeometry(QRect(ppp(10), ppp(60), ppp(280), ppp(30)));
loginButton->setFont(font);
loginButton->show();
QObject::connect(loginButton, SIGNAL(clicked()), this, SLOT(login()));
newUserGroupBox = new QGroupBox("Create a New User Here.", this);
newUserGroupBox->setFont(font);
label2 = new QLabel("Username:", newUserGroupBox);
label2->setGeometry(QRect(ppp(10), ppp(25), ppp(100), ppp(25)));
label2->setFont(font);
label2->show();
newUserLineEdit = new QLineEdit(newUserGroupBox);
newUserLineEdit->setGeometry(QRect(ppp(105), ppp(25), ppp(180), ppp(25)));
newUserLineEdit->setFont(font);
newUserLineEdit->show();
QObject::connect(newUserLineEdit, SIGNAL(returnPressed()), this, SLOT(createNewUser()));
newUserButton = new QPushButton( "Create New User", newUserGroupBox );
newUserButton->setGeometry(QRect(ppp(10), ppp(60), ppp(280), ppp(30)));
newUserButton->setFont(font);
newUserButton->show();
QObject::connect(newUserButton, SIGNAL(clicked()), this, SLOT(createNewUser()));
}
// Called when the X in the upper left is clicked
void QuizApp::closeEvent(QCloseEvent * e)
{
if (!exit())
e->ignore();
}
QuizApp::QuizApp()
{
// Keyboard focus to get keystrokes
setFocusPolicy(Qt::StrongFocus);
setMinimumSize(MIN_WIDTH, MIN_HEIGHT);
loggedIn = false;
createLoginScreen();
showMaximized();
setWindowTitle("Amino");
}
QuizApp::~QuizApp()
{
}
|
// ********************************************************
// This C++ code was automatically generated by ml2cpp (development version).
// Copyright 2020
// https://github.com/antoinecarme/ml2cpp
// Model : LGBMClassifier_Pipeline
// Dataset : iris
// This CPP code can be compiled using any C++-17 compiler.
// g++ -Wall -Wno-unused-function -std=c++17 -g -o ml2cpp-demo_LGBMClassifier_Pipeline_iris.exe ml2cpp-demo_LGBMClassifier_Pipeline_iris.cpp
// Model deployment code
// ********************************************************
#include "../../Generic.i"
namespace {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
namespace imputer {
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = { "imputer_output_2", "imputer_output_3", "imputer_output_4", "imputer_output_5" };
return lOutputs;
}
tTable compute_features(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3) {
tTable lTable;
lTable["imputer_output_2"] = { ((Feature_0 == std::any()) ? ( 5.8474999999999975 ) : ( Feature_0)) };
lTable["imputer_output_3"] = { ((Feature_1 == std::any()) ? ( 3.040833333333332 ) : ( Feature_1)) };
lTable["imputer_output_4"] = { ((Feature_2 == std::any()) ? ( 3.844166666666667 ) : ( Feature_2)) };
lTable["imputer_output_5"] = { ((Feature_3 == std::any()) ? ( 1.2458333333333336 ) : ( Feature_3)) };
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_features(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0]);
return lTable;
}
} // eof namespace imputer
namespace scaler {
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "imputer_output_2", "imputer_output_3", "imputer_output_4", "imputer_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lOutputs;
}
tTable compute_features(std::any imputer_output_2, std::any imputer_output_3, std::any imputer_output_4, std::any imputer_output_5) {
tTable lTable;
lTable["scaler_output_2"] = { ( ( imputer_output_2 - 5.8474999999999975 ) / 0.827039146594646 ) };
lTable["scaler_output_3"] = { ( ( imputer_output_3 - 3.040833333333332 ) / 0.43922200789830873 ) };
lTable["scaler_output_4"] = { ( ( imputer_output_4 - 3.844166666666667 ) / 1.7109839193347847 ) };
lTable["scaler_output_5"] = { ( ( imputer_output_5 - 1.2458333333333336 ) / 0.7486538845747673 ) };
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_features(iTable.at("imputer_output_2")[0], iTable.at("imputer_output_3")[0], iTable.at("imputer_output_4")[0], iTable.at("imputer_output_5")[0]);
return lTable;
}
} // eof namespace scaler
namespace model {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
namespace LGBM_Tree_0_0 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 2 , {-1.098577633576391 }} ,
{ 3 , {-1.2127184097138204 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_4 <= -0.40571197591182095 ) ? ( 2 ) : ( 3 ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
lNodeValue [ 0 ],
0.0,
0.0
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_0_0
namespace LGBM_Tree_1_0 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 3 , {-1.1361122895063 }} ,
{ 4 , {-1.1331517631243377 }} ,
{ 10 , {-1.0236122869917292 }} ,
{ 11 , {-1.066469430806804 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_4 <= 0.7047601790449031 ) ? ( ( ( scaler_output_4 <= -0.40571197591182095 ) ? ( 4 ) : ( ( ( scaler_output_5 <= 0.2727116907736775 ) ? ( 10 ) : ( 11 ) ) ) ) ) : ( 3 ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
0.0,
lNodeValue [ 0 ],
0.0
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_1_0
namespace LGBM_Tree_2_0 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 5 , {-1.0548975721429792 }} ,
{ 6 , {-0.972833457269183 }} ,
{ 7 , {-0.9565241852280185 }} ,
{ 8 , {-1.0652526655024486 }} ,
{ 9 , {-1.0652526655024486 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_4 <= 0.5878683732599849 ) ? ( ( ( scaler_output_4 <= 0.23719295590522982 ) ? ( ( ( scaler_output_4 <= -1.1947316649600193 ) ? ( 8 ) : ( 9 ) ) ) : ( 5 ) ) ) : ( ( ( scaler_output_5 <= 0.9405770559337051 ) ? ( 6 ) : ( 7 ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
0.0,
0.0,
lNodeValue [ 0 ]
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_2_0
namespace LGBM_Tree_0_1 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 2 , {0.07203709754130887 }} ,
{ 6 , {-0.03560466438872138 }} ,
{ 14 , {-0.03546232753800146 }} ,
{ 15 , {-0.03557263246000808 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_4 <= -0.40571197591182095 ) ? ( 2 ) : ( ( ( scaler_output_4 <= 0.5878683732599849 ) ? ( 6 ) : ( ( ( scaler_output_4 <= 0.9969896935071989 ) ? ( 14 ) : ( 15 ) ) ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
lNodeValue [ 0 ],
0.0,
0.0
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_0_1
namespace LGBM_Tree_1_1 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 2 , {-0.03687402568505773 }} ,
{ 12 , {0.05471091282297931 }} ,
{ 13 , {0.06549038259359759 }} ,
{ 14 , {-0.020160621203689815 }} ,
{ 15 , {-0.036848255606056916 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_4 <= -1.1947316649600193 ) ? ( 2 ) : ( ( ( scaler_output_4 <= 0.5878683732599849 ) ? ( ( ( scaler_output_2 <= -0.11789042925169398 ) ? ( 12 ) : ( 13 ) ) ) : ( ( ( scaler_output_5 <= 0.9405770559337051 ) ? ( 14 ) : ( 15 ) ) ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
0.0,
lNodeValue [ 0 ],
0.0
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_1_1
namespace LGBM_Tree_2_1 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 5 , {-0.02794490709807418 }} ,
{ 6 , {0.050456153796761306 }} ,
{ 7 , {0.06536468519994394 }} ,
{ 8 , {-0.038146971656005446 }} ,
{ 9 , {-0.03814000705850624 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_4 <= 0.5878683732599849 ) ? ( ( ( scaler_output_4 <= 0.23719295590522982 ) ? ( ( ( scaler_output_4 <= -1.1947316649600193 ) ? ( 8 ) : ( 9 ) ) ) : ( 5 ) ) ) : ( ( ( scaler_output_5 <= 0.9405770559337051 ) ? ( 6 ) : ( 7 ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
0.0,
0.0,
lNodeValue [ 0 ]
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_2_1
namespace LGBM_Tree_0_2 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 2 , {0.06710583031172605 }} ,
{ 6 , {-0.03507439933836642 }} ,
{ 14 , {-0.03490998640237942 }} ,
{ 15 , {-0.035004861891144254 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_4 <= -0.40571197591182095 ) ? ( 2 ) : ( ( ( scaler_output_4 <= 0.5878683732599849 ) ? ( 6 ) : ( ( ( scaler_output_4 <= 0.9969896935071989 ) ? ( 14 ) : ( 15 ) ) ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
lNodeValue [ 0 ],
0.0,
0.0
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_0_2
namespace LGBM_Tree_1_2 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 2 , {-0.036308694220767664 }} ,
{ 12 , {0.05183542073163149 }} ,
{ 13 , {0.061350994955675364 }} ,
{ 14 , {-0.01955410437926108 }} ,
{ 15 , {-0.036164628007685835 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_5 <= -1.063019039546377 ) ? ( 2 ) : ( ( ( scaler_output_4 <= 0.5878683732599849 ) ? ( ( ( scaler_output_2 <= -0.11789042925169398 ) ? ( 12 ) : ( 13 ) ) ) : ( ( ( scaler_output_5 <= 0.9405770559337051 ) ? ( 14 ) : ( 15 ) ) ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
0.0,
lNodeValue [ 0 ],
0.0
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_1_2
namespace LGBM_Tree_2_2 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 5 , {-0.027175741831872935 }} ,
{ 6 , {0.047634793193730714 }} ,
{ 7 , {0.061466030358232684 }} ,
{ 8 , {-0.037360474274365625 }} ,
{ 9 , {-0.03742598346375149 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_4 <= 0.5878683732599849 ) ? ( ( ( scaler_output_4 <= 0.23719295590522982 ) ? ( ( ( scaler_output_2 <= -0.8433699938775219 ) ? ( 8 ) : ( 9 ) ) ) : ( 5 ) ) ) : ( ( ( scaler_output_5 <= 0.9405770559337051 ) ? ( 6 ) : ( 7 ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
0.0,
0.0,
lNodeValue [ 0 ]
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_2_2
namespace LGBM_Tree_0_3 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 2 , {0.06288417480323484 }} ,
{ 6 , {-0.034588139626609414 }} ,
{ 14 , {-0.03440569155695775 }} ,
{ 15 , {-0.03446795493205667 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_4 <= -0.40571197591182095 ) ? ( 2 ) : ( ( ( scaler_output_4 <= 0.44175361602883695 ) ? ( 6 ) : ( ( ( scaler_output_4 <= 0.7632060819373623 ) ? ( 14 ) : ( 15 ) ) ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
lNodeValue [ 0 ],
0.0,
0.0
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_0_3
namespace LGBM_Tree_1_3 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 2 , {-0.03570855183326651 }} ,
{ 7 , {-0.030522505306779326 }} ,
{ 12 , {0.05513184020491312 }} ,
{ 13 , {0.04671403387150432 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_5 <= -1.063019039546377 ) ? ( 2 ) : ( ( ( scaler_output_5 <= 0.5398578368376886 ) ? ( ( ( scaler_output_2 <= 0.12393609229024888 ) ? ( 12 ) : ( 13 ) ) ) : ( 7 ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
0.0,
lNodeValue [ 0 ],
0.0
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_1_3
namespace LGBM_Tree_2_3 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 5 , {-0.026428733936072608 }} ,
{ 6 , {0.04510991997777966 }} ,
{ 7 , {0.05809329936406861 }} ,
{ 8 , {-0.03663376207423026 }} ,
{ 9 , {-0.03675053679260615 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_4 <= 0.5878683732599849 ) ? ( ( ( scaler_output_4 <= 0.23719295590522982 ) ? ( ( ( scaler_output_2 <= -0.8433699938775219 ) ? ( 8 ) : ( 9 ) ) ) : ( 5 ) ) ) : ( ( ( scaler_output_5 <= 0.9405770559337051 ) ? ( 6 ) : ( 7 ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
0.0,
0.0,
lNodeValue [ 0 ]
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_2_3
namespace LGBM_Tree_0_4 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 2 , {0.059249424563210244 }} ,
{ 6 , {-0.034139483803533176 }} ,
{ 14 , {-0.0338682214733499 }} ,
{ 15 , {-0.03394220726138208 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_4 <= -0.40571197591182095 ) ? ( 2 ) : ( ( ( scaler_output_4 <= 0.5878683732599849 ) ? ( 6 ) : ( ( ( scaler_output_4 <= 0.9969896935071989 ) ? ( 14 ) : ( 15 ) ) ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
lNodeValue [ 0 ],
0.0,
0.0
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_0_4
namespace LGBM_Tree_1_4 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 3 , {-0.03526170605977342 }} ,
{ 4 , {-0.032151011171800005 }} ,
{ 10 , {0.059151204965902905 }} ,
{ 11 , {0.02739817862696709 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_4 <= 0.7047601790449031 ) ? ( ( ( scaler_output_4 <= -0.40571197591182095 ) ? ( 4 ) : ( ( ( scaler_output_5 <= 0.2727116907736775 ) ? ( 10 ) : ( 11 ) ) ) ) ) : ( 3 ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
0.0,
lNodeValue [ 0 ],
0.0
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_1_4
namespace LGBM_Tree_2_4 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 5 , {-0.025879323134733852 }} ,
{ 6 , {0.04304016306737694 }} ,
{ 7 , {0.055229940647735946 }} ,
{ 8 , {-0.03595304601527121 }} ,
{ 9 , {-0.03610540456473311 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_4 <= 0.5878683732599849 ) ? ( ( ( scaler_output_4 <= 0.23719295590522982 ) ? ( ( ( scaler_output_2 <= -0.8433699938775219 ) ? ( 8 ) : ( 9 ) ) ) : ( 5 ) ) ) : ( ( ( scaler_output_5 <= 0.9405770559337051 ) ? ( 6 ) : ( 7 ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
0.0,
0.0,
lNodeValue [ 0 ]
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_2_4
namespace LGBM_Tree_0_5 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 2 , {0.05599767583132714 }} ,
{ 6 , {-0.03369616217069678 }} ,
{ 14 , {-0.03336218480130148 }} ,
{ 15 , {-0.033489673174888664 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_4 <= -0.40571197591182095 ) ? ( 2 ) : ( ( ( scaler_output_4 <= 0.5878683732599849 ) ? ( 6 ) : ( ( ( scaler_output_4 <= 0.9969896935071989 ) ? ( 14 ) : ( 15 ) ) ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
lNodeValue [ 0 ],
0.0,
0.0
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_0_5
namespace LGBM_Tree_1_5 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 3 , {-0.034713002480153396 }} ,
{ 4 , {-0.03156203262598963 }} ,
{ 10 , {0.056144291694111226 }} ,
{ 11 , {0.026222882372044145 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_4 <= 0.7047601790449031 ) ? ( ( ( scaler_output_4 <= -0.40571197591182095 ) ? ( 4 ) : ( ( ( scaler_output_5 <= 0.2727116907736775 ) ? ( 10 ) : ( 11 ) ) ) ) ) : ( 3 ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
0.0,
lNodeValue [ 0 ],
0.0
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_1_5
namespace LGBM_Tree_2_5 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 5 , {-0.025273928047555044 }} ,
{ 6 , {0.041894429027994375 }} ,
{ 7 , {0.05350233245386084 }} ,
{ 8 , {-0.03533603196091717 }} ,
{ 9 , {-0.03547323670914954 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_4 <= 0.5878683732599849 ) ? ( ( ( scaler_output_4 <= 0.23719295590522982 ) ? ( ( ( scaler_output_2 <= -0.8433699938775219 ) ? ( 8 ) : ( 9 ) ) ) : ( 5 ) ) ) : ( ( ( scaler_output_4 <= 0.9969896935071989 ) ? ( 6 ) : ( 7 ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
0.0,
0.0,
lNodeValue [ 0 ]
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_2_5
namespace LGBM_Tree_0_6 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 2 , {0.053145108405744206 }} ,
{ 6 , {-0.03327635444917742 }} ,
{ 14 , {-0.03291530769909316 }} ,
{ 15 , {-0.033036150217049726 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_4 <= -0.40571197591182095 ) ? ( 2 ) : ( ( ( scaler_output_4 <= 0.5878683732599849 ) ? ( 6 ) : ( ( ( scaler_output_4 <= 0.9969896935071989 ) ? ( 14 ) : ( 15 ) ) ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
lNodeValue [ 0 ],
0.0,
0.0
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_0_6
namespace LGBM_Tree_1_6 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 2 , {-0.034206556691768135 }} ,
{ 7 , {-0.029164965472322127 }} ,
{ 12 , {0.04831887704248408 }} ,
{ 13 , {0.04151320992791824 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_4 <= -1.1947316649600193 ) ? ( 2 ) : ( ( ( scaler_output_5 <= 0.5398578368376886 ) ? ( ( ( scaler_output_2 <= 0.12393609229024888 ) ? ( 12 ) : ( 13 ) ) ) : ( 7 ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
0.0,
lNodeValue [ 0 ],
0.0
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_1_6
namespace LGBM_Tree_2_6 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 3 , {0.04847832460710317 }} ,
{ 5 , {-0.01723918230110742 }} ,
{ 8 , {-0.034762801723106605 }} ,
{ 9 , {-0.03511596385110626 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_5 <= 0.5398578368376886 ) ? ( ( ( scaler_output_2 <= 0.12393609229024888 ) ? ( ( ( scaler_output_4 <= -0.40571197591182095 ) ? ( 8 ) : ( 9 ) ) ) : ( 5 ) ) ) : ( 3 ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
0.0,
0.0,
lNodeValue [ 0 ]
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_2_6
namespace LGBM_Tree_0_7 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 2 , {0.05068525826516349 }} ,
{ 6 , {-0.03287388507221969 }} ,
{ 14 , {-0.03251983451376361 }} ,
{ 15 , {-0.03261792547942402 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_4 <= -0.40571197591182095 ) ? ( 2 ) : ( ( ( scaler_output_4 <= 0.5878683732599849 ) ? ( 6 ) : ( ( ( scaler_output_4 <= 0.9969896935071989 ) ? ( 14 ) : ( 15 ) ) ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
lNodeValue [ 0 ],
0.0,
0.0
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_0_7
namespace LGBM_Tree_1_7 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 3 , {-0.03385142114716804 }} ,
{ 4 , {-0.03371950595207674 }} ,
{ 10 , {0.0471443591542228 }} ,
{ 11 , {0.024564110303857398 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_4 <= 0.7047601790449031 ) ? ( ( ( scaler_output_4 <= -1.1947316649600193 ) ? ( 4 ) : ( ( ( scaler_output_5 <= 0.2727116907736775 ) ? ( 10 ) : ( 11 ) ) ) ) ) : ( 3 ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
0.0,
lNodeValue [ 0 ],
0.0
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_1_7
namespace LGBM_Tree_2_7 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 5 , {-0.024395225365071625 }} ,
{ 6 , {0.03859271803929604 }} ,
{ 7 , {0.04939745719485434 }} ,
{ 8 , {-0.03420394206113458 }} ,
{ 9 , {-0.03435243349876829 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_4 <= 0.5878683732599849 ) ? ( ( ( scaler_output_4 <= 0.23719295590522982 ) ? ( ( ( scaler_output_2 <= -0.8433699938775219 ) ? ( 8 ) : ( 9 ) ) ) : ( 5 ) ) ) : ( ( ( scaler_output_4 <= 0.9969896935071989 ) ? ( 6 ) : ( 7 ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
0.0,
0.0,
lNodeValue [ 0 ]
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_2_7
namespace LGBM_Tree_0_8 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 2 , {0.048498810954971605 }} ,
{ 6 , {-0.03251116796550338 }} ,
{ 14 , {-0.032216412351179516 }} ,
{ 15 , {-0.032130234428115405 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_4 <= -0.40571197591182095 ) ? ( 2 ) : ( ( ( scaler_output_4 <= 0.5878683732599849 ) ? ( 6 ) : ( ( ( scaler_output_5 <= 0.9405770559337051 ) ? ( 14 ) : ( 15 ) ) ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
lNodeValue [ 0 ],
0.0,
0.0
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_0_8
namespace LGBM_Tree_1_8 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 3 , {-0.03338082069192506 }} ,
{ 4 , {-0.03331143106484881 }} ,
{ 10 , {0.04542036345029271 }} ,
{ 11 , {0.02356847480030867 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_4 <= 0.7047601790449031 ) ? ( ( ( scaler_output_5 <= -1.063019039546377 ) ? ( 4 ) : ( ( ( scaler_output_5 <= 0.2727116907736775 ) ? ( 10 ) : ( 11 ) ) ) ) ) : ( 3 ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
0.0,
lNodeValue [ 0 ],
0.0
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_1_8
namespace LGBM_Tree_2_8 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 5 , {-0.023842838714539263 }} ,
{ 6 , {0.03622613217683845 }} ,
{ 7 , {0.04693561159037301 }} ,
{ 8 , {-0.033686507784718746 }} ,
{ 9 , {-0.033849651209211906 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_4 <= 0.5878683732599849 ) ? ( ( ( scaler_output_4 <= 0.23719295590522982 ) ? ( ( ( scaler_output_2 <= -0.8433699938775219 ) ? ( 8 ) : ( 9 ) ) ) : ( 5 ) ) ) : ( ( ( scaler_output_5 <= 0.9405770559337051 ) ? ( 6 ) : ( 7 ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
0.0,
0.0,
lNodeValue [ 0 ]
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_2_8
namespace LGBM_Tree_0_9 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 2 , {0.0465394611940145 }} ,
{ 6 , {-0.03216640541899468 }} ,
{ 14 , {-0.03186118583313035 }} ,
{ 15 , {-0.03174240507767745 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_4 <= -0.40571197591182095 ) ? ( 2 ) : ( ( ( scaler_output_4 <= 0.5878683732599849 ) ? ( 6 ) : ( ( ( scaler_output_5 <= 0.9405770559337051 ) ? ( 14 ) : ( 15 ) ) ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
lNodeValue [ 0 ],
0.0,
0.0
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_0_9
namespace LGBM_Tree_1_9 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 3 , {-0.032943283475885966 }} ,
{ 4 , {-0.032875684639598134 }} ,
{ 10 , {0.043689559243602565 }} ,
{ 11 , {0.02264906126520682 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_4 <= 0.7047601790449031 ) ? ( ( ( scaler_output_4 <= -1.1947316649600193 ) ? ( 4 ) : ( ( ( scaler_output_5 <= 0.2727116907736775 ) ? ( 10 ) : ( 11 ) ) ) ) ) : ( 3 ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
0.0,
lNodeValue [ 0 ],
0.0
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_1_9
namespace LGBM_Tree_2_9 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 3 , {0.04348381263648364 }} ,
{ 5 , {-0.016528860614149935 }} ,
{ 8 , {-0.03321200864312551 }} ,
{ 9 , {-0.033649938701344535 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_5 <= 0.5398578368376886 ) ? ( ( ( scaler_output_2 <= 0.12393609229024888 ) ? ( ( ( scaler_output_4 <= -0.40571197591182095 ) ? ( 8 ) : ( 9 ) ) ) : ( 5 ) ) ) : ( 3 ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
0.0,
0.0,
lNodeValue [ 0 ]
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_2_9
namespace LGBM_Tree_0_10 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 2 , {0.0447790053327801 }} ,
{ 6 , {-0.03181639101439957 }} ,
{ 14 , {-0.03155995923733284 }} ,
{ 15 , {-0.03138561810980161 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_4 <= -0.40571197591182095 ) ? ( 2 ) : ( ( ( scaler_output_4 <= 0.5878683732599849 ) ? ( 6 ) : ( ( ( scaler_output_5 <= 0.9405770559337051 ) ? ( 14 ) : ( 15 ) ) ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
lNodeValue [ 0 ],
0.0,
0.0
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_0_10
namespace LGBM_Tree_1_10 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 3 , {-0.03255969186440175 }} ,
{ 4 , {-0.032514520030900274 }} ,
{ 10 , {0.04231776764603347 }} ,
{ 11 , {0.021836778626793073 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_4 <= 0.7047601790449031 ) ? ( ( ( scaler_output_5 <= -1.063019039546377 ) ? ( 4 ) : ( ( ( scaler_output_5 <= 0.2727116907736775 ) ? ( 10 ) : ( 11 ) ) ) ) ) : ( 3 ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
0.0,
lNodeValue [ 0 ],
0.0
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_1_10
namespace LGBM_Tree_2_10 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 3 , {0.04202302556367313 }} ,
{ 5 , {-0.01615048952202365 }} ,
{ 8 , {-0.03276000924896212 }} ,
{ 9 , {-0.033208293330844005 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_5 <= 0.5398578368376886 ) ? ( ( ( scaler_output_2 <= 0.12393609229024888 ) ? ( ( ( scaler_output_4 <= -0.40571197591182095 ) ? ( 8 ) : ( 9 ) ) ) : ( 5 ) ) ) : ( 3 ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
0.0,
0.0,
lNodeValue [ 0 ]
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_2_10
namespace LGBM_Tree_0_11 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 2 , {0.043185809436165 }} ,
{ 6 , {-0.03148595129797325 }} ,
{ 14 , {-0.03127803466761719 }} ,
{ 15 , {-0.03104942574111612 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_4 <= -0.40571197591182095 ) ? ( 2 ) : ( ( ( scaler_output_4 <= 0.5878683732599849 ) ? ( 6 ) : ( ( ( scaler_output_5 <= 0.9405770559337051 ) ? ( 14 ) : ( 15 ) ) ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
lNodeValue [ 0 ],
0.0,
0.0
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_0_11
namespace LGBM_Tree_1_11 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 3 , {-0.032199938420065036 }} ,
{ 4 , {-0.03212187847833443 }} ,
{ 10 , {0.040898935735628486 }} ,
{ 11 , {0.021073446390819855 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_4 <= 0.7047601790449031 ) ? ( ( ( scaler_output_4 <= -1.1947316649600193 ) ? ( 4 ) : ( ( ( scaler_output_5 <= 0.2727116907736775 ) ? ( 10 ) : ( 11 ) ) ) ) ) : ( 3 ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
0.0,
lNodeValue [ 0 ],
0.0
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_1_11
namespace LGBM_Tree_2_11 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 5 , {-0.02268301100850852 }} ,
{ 6 , {0.03282194389506779 }} ,
{ 7 , {0.04262264588106126 }} ,
{ 8 , {-0.0323250127234722 }} ,
{ 9 , {-0.03252273324995232 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_4 <= 0.5878683732599849 ) ? ( ( ( scaler_output_4 <= 0.23719295590522982 ) ? ( ( ( scaler_output_2 <= -0.8433699938775219 ) ? ( 8 ) : ( 9 ) ) ) : ( 5 ) ) ) : ( ( ( scaler_output_5 <= 0.9405770559337051 ) ? ( 6 ) : ( 7 ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
0.0,
0.0,
lNodeValue [ 0 ]
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_2_11
namespace LGBM_Tree_0_12 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 2 , {0.04174118804990898 }} ,
{ 7 , {-0.03072427344481081 }} ,
{ 12 , {-0.03095300320395938 }} ,
{ 13 , {-0.031263363983538225 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_4 <= -0.40571197591182095 ) ? ( 2 ) : ( ( ( scaler_output_5 <= 0.9405770559337051 ) ? ( ( ( scaler_output_5 <= 0.2727116907736775 ) ? ( 12 ) : ( 13 ) ) ) : ( 7 ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
lNodeValue [ 0 ],
0.0,
0.0
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_0_12
namespace LGBM_Tree_1_12 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 3 , {-0.031832102499346863 }} ,
{ 4 , {-0.031803149073094374 }} ,
{ 10 , {0.039758068565201844 }} ,
{ 11 , {0.020296531017118803 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_4 <= 0.7047601790449031 ) ? ( ( ( scaler_output_5 <= -1.063019039546377 ) ? ( 4 ) : ( ( ( scaler_output_5 <= 0.2727116907736775 ) ? ( 10 ) : ( 11 ) ) ) ) ) : ( 3 ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
0.0,
lNodeValue [ 0 ],
0.0
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_1_12
namespace LGBM_Tree_2_12 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 3 , {0.0396666661188759 }} ,
{ 5 , {-0.015730041646917933 }} ,
{ 8 , {-0.03193837573522237 }} ,
{ 9 , {-0.03242046259370106 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_5 <= 0.5398578368376886 ) ? ( ( ( scaler_output_2 <= 0.12393609229024888 ) ? ( ( ( scaler_output_4 <= -0.40571197591182095 ) ? ( 8 ) : ( 9 ) ) ) : ( 5 ) ) ) : ( 3 ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
0.0,
0.0,
lNodeValue [ 0 ]
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_2_12
namespace LGBM_Tree_0_13 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 2 , {0.04042297585669757 }} ,
{ 7 , {-0.030424922101528612 }} ,
{ 12 , {-0.03066130472492843 }} ,
{ 13 , {-0.030992990547433652 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_4 <= -0.40571197591182095 ) ? ( 2 ) : ( ( ( scaler_output_5 <= 0.9405770559337051 ) ? ( ( ( scaler_output_5 <= 0.2727116907736775 ) ? ( 12 ) : ( 13 ) ) ) : ( 7 ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
lNodeValue [ 0 ],
0.0,
0.0
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_0_13
namespace LGBM_Tree_1_13 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 3 , {-0.03151418706851478 }} ,
{ 4 , {-0.03144959359970684 }} ,
{ 10 , {0.03856481867136396 }} ,
{ 11 , {0.019614723402753966 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_4 <= 0.7047601790449031 ) ? ( ( ( scaler_output_5 <= -1.063019039546377 ) ? ( 4 ) : ( ( ( scaler_output_5 <= 0.2727116907736775 ) ? ( 10 ) : ( 11 ) ) ) ) ) : ( 3 ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
0.0,
lNodeValue [ 0 ],
0.0
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_1_13
namespace LGBM_Tree_2_13 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 4 , {-0.024999910685942105 }} ,
{ 6 , {0.026394400790221206 }} ,
{ 7 , {0.04087730872717531 }} ,
{ 10 , {-0.03158227243048794 }} ,
{ 11 , {-0.03289703619943964 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_4 <= 0.5294224703675258 ) ? ( ( ( scaler_output_3 <= -0.6621556481765994 ) ? ( 4 ) : ( ( ( scaler_output_2 <= -0.6620001027210645 ) ? ( 10 ) : ( 11 ) ) ) ) ) : ( ( ( scaler_output_4 <= 0.8800978877222807 ) ? ( 6 ) : ( 7 ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
0.0,
0.0,
lNodeValue [ 0 ]
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_2_13
namespace LGBM_Tree_0_14 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 2 , {0.03921986107914058 }} ,
{ 7 , {-0.030149015861194863 }} ,
{ 12 , {-0.03037455394316346 }} ,
{ 13 , {-0.03073712113593486 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_4 <= -0.40571197591182095 ) ? ( 2 ) : ( ( ( scaler_output_5 <= 0.9405770559337051 ) ? ( ( ( scaler_output_5 <= 0.2727116907736775 ) ? ( 12 ) : ( 13 ) ) ) : ( 7 ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
lNodeValue [ 0 ],
0.0,
0.0
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_0_14
namespace LGBM_Tree_1_14 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 3 , {-0.031183916074223657 }} ,
{ 4 , {-0.031168211882030623 }} ,
{ 10 , {0.037639119576233844 }} ,
{ 11 , {0.018876527774799243 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_4 <= 0.7047601790449031 ) ? ( ( ( scaler_output_4 <= -1.1947316649600193 ) ? ( 4 ) : ( ( ( scaler_output_5 <= 0.2727116907736775 ) ? ( 10 ) : ( 11 ) ) ) ) ) : ( 3 ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
0.0,
lNodeValue [ 0 ],
0.0
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_1_14
namespace LGBM_Tree_2_14 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 3 , {0.03763380408977582 }} ,
{ 5 , {-0.015279318344802499 }} ,
{ 8 , {-0.0312142883947812 }} ,
{ 9 , {-0.031730147330013996 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_5 <= 0.5398578368376886 ) ? ( ( ( scaler_output_2 <= 0.12393609229024888 ) ? ( ( ( scaler_output_4 <= -0.40571197591182095 ) ? ( 8 ) : ( 9 ) ) ) : ( 5 ) ) ) : ( 3 ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
0.0,
0.0,
lNodeValue [ 0 ]
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_2_14
namespace LGBM_Tree_0_15 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 2 , {0.0381125588785606 }} ,
{ 7 , {-0.02988176832820983 }} ,
{ 12 , {-0.03011387163471796 }} ,
{ 13 , {-0.030496240065494458 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_4 <= -0.40571197591182095 ) ? ( 2 ) : ( ( ( scaler_output_5 <= 0.9405770559337051 ) ? ( ( ( scaler_output_5 <= 0.2727116907736775 ) ? ( 12 ) : ( 13 ) ) ) : ( 7 ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
lNodeValue [ 0 ],
0.0,
0.0
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_0_15
namespace LGBM_Tree_1_15 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 3 , {-0.030902637439763198 }} ,
{ 4 , {-0.03085024460385748 }} ,
{ 10 , {0.03662201043150378 }} ,
{ 11 , {0.01826803553273802 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_4 <= 0.7047601790449031 ) ? ( ( ( scaler_output_4 <= -1.1947316649600193 ) ? ( 4 ) : ( ( ( scaler_output_5 <= 0.2727116907736775 ) ? ( 10 ) : ( 11 ) ) ) ) ) : ( 3 ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
0.0,
lNodeValue [ 0 ],
0.0
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_1_15
namespace LGBM_Tree_2_15 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 3 , {0.036664559671497406 }} ,
{ 5 , {-0.014932936214246947 }} ,
{ 8 , {-0.030884238534663183 }} ,
{ 9 , {-0.03139819022339432 }}
};
int get_decision_tree_node_index(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
int lNodeIndex = ( ( scaler_output_5 <= 0.5398578368376886 ) ? ( ( ( scaler_output_2 <= 0.12393609229024888 ) ? ( ( ( scaler_output_4 <= -0.40571197591182095 ) ? ( 8 ) : ( 9 ) ) ) : ( 5 ) ) ) : ( 3 ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
0.0,
0.0,
lNodeValue [ 0 ]
} ;
lTable["Proba"] = {
std::any(),
std::any(),
std::any()
} ;
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace LGBM_Tree_2_15
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "scaler_output_2", "scaler_output_3", "scaler_output_4", "scaler_output_5" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2",
"Decision", "DecisionProba" };
return lOutputs;
}
tTable compute_classification_scores(std::any scaler_output_2, std::any scaler_output_3, std::any scaler_output_4, std::any scaler_output_5) {
auto lClasses = get_classes();
std::vector<tTable> lTreeScores = {
LGBM_Tree_0_0::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_1_0::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_2_0::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_0_1::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_1_1::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_2_1::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_0_2::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_1_2::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_2_2::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_0_3::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_1_3::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_2_3::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_0_4::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_1_4::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_2_4::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_0_5::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_1_5::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_2_5::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_0_6::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_1_6::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_2_6::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_0_7::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_1_7::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_2_7::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_0_8::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_1_8::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_2_8::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_0_9::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_1_9::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_2_9::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_0_10::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_1_10::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_2_10::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_0_11::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_1_11::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_2_11::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_0_12::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_1_12::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_2_12::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_0_13::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_1_13::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_2_13::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_0_14::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_1_14::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_2_14::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_0_15::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_1_15::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5),
LGBM_Tree_2_15::compute_classification_scores(scaler_output_2, scaler_output_3, scaler_output_4, scaler_output_5)
};
tTable lAggregatedTable = aggregate_lgb_scores(lTreeScores, {"Score"});
tTable lSoftMaxTable = soft_max(lAggregatedTable);
tTable lTable = lSoftMaxTable;
int lBestClass = get_arg_max( lTable["Proba"] );
auto lDecision = lClasses[lBestClass];
lTable["Decision"] = { lDecision } ;
lTable["DecisionProba"] = { lTable["Proba"][lBestClass] };
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("scaler_output_2")[0], iTable.at("scaler_output_3")[0], iTable.at("scaler_output_4")[0], iTable.at("scaler_output_5")[0]);
return lTable;
}
} // eof namespace model
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2",
"Proba_0", "Proba_1", "Proba_2",
"LogProba_0", "LogProba_1", "LogProba_2",
"Decision", "DecisionProba" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3) {
auto lClasses = get_classes();
tTable lTable_imputer = imputer::compute_features(Feature_0, Feature_1, Feature_2, Feature_3);
tTable lTable_scaler = scaler::compute_model_outputs_from_table( lTable_imputer );
tTable lTable_model = model::compute_model_outputs_from_table( lTable_scaler );
tTable lTable = lTable_model;
int lBestClass = get_arg_max( lTable["Proba"] );
auto lDecision = lClasses[lBestClass];
lTable["Decision"] = { lDecision } ;
lTable["DecisionProba"] = { lTable["Proba"][lBestClass] };
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0]);
return lTable;
}
} // eof namespace
int main() {
score_csv_file("outputs/ml2cpp-demo/datasets/iris.csv");
return 0;
}
|
#include "Lines_window.h"
Lines_window::Lines_window(Point xy, int w, int h, const string& title)
:Window{xy,w,h,title},
next_button{Point{x_max()-300,0}, 150, 40, "Next point",
[](Address, Address pw) {reference_to<Lines_window>(pw).next();}},
quit_button{Point{x_max()-150,0}, 150, 40, "Quit",
[](Address, Address pw) {reference_to<Lines_window>(pw).quit();}},
next_x{Point{300,0}, 50, 40, "next x:"},
next_y{Point{450,0}, 50, 40, "next y:"},
xy_out{Point{100,0}, 100, 40, "current (x,y):"}
{
attach(next_button);
attach(quit_button);
attach(next_x);
attach(next_y);
attach(xy_out);
attach(lines);
}
void Lines_window::quit()
{
hide();
}
void Lines_window::next()
{
int x = next_x.get_int();
int y = next_y.get_int();
lines.add(Point{x,y});
ostringstream ss;
ss << '(' << x << ',' << y << ')';
xy_out.put(ss.str());
redraw();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.