text string | size int64 | token_count int64 |
|---|---|---|
/* Taken from
* https://github.com/FastFilter/fastfilter_cpp
* */
#ifndef FILTERS_WRAPPERS_HPP
#define FILTERS_WRAPPERS_HPP
#include <climits>
#include <iomanip>
#include <iostream>
#include <map>
#include <random>
#include <set>
#include <stdexcept>
#include <stdio.h>
#include <vector>
#include "../Bloom_Filter/bloom.hpp"
#include "../PD_Filter/dict.hpp"
#include "TPD_Filter/T_dict.hpp"
//#include "../TPD_Filter/pd512_wrapper.hpp"
//#include "dict512.hpp"
#include "TPD_Filter/dict512.hpp"
#include "d512/att_d512.hpp"
#include "d512/twoChoicer.hpp"
// #include "../cuckoo/cuckoofilter.h"
#include "../cuckoofilter/src/cuckoofilter.h"
//#include "../morton/compressed_cuckoo_filter.h"
#include "../Bloom_Filter/simd-block-fixed-fpp.h"
#include "../Bloom_Filter/simd-block.h"
#include "../morton/morton_sample_configs.h"
//#include "xorfilter.h"
//#include "../xorfilter/xorfilter_2.h"
//#include "../xorfilter/xorfilter_2n.h"
//#include "../xorfilter/xorfilter_10bit.h"
//#include "../xorfilter/xorfilter_10_666bit.h"
//#include "../xorfilter/xorfilter_13bit.h"
//#include "../xorfilter/xorfilter_plus.h"
//#include "../xorfilter/xorfilter_singleheader.h"
//#include "../xorfilter/xor_fuse_filter.h"
#define CONTAIN_ATTRIBUTES __attribute__((noinline))
enum filter_id
{
BF,
CF,
CF_ss,
MF,
SIMD,
pd_id,
tpd_id,
d512,
att_d512_id,
twoChoicer_id
};
template <typename Table>
struct FilterAPI
{
};
template <typename ItemType, size_t bits_per_item, template <size_t> class TableType, typename HashFamily>
struct FilterAPI<cuckoofilter::CuckooFilter<ItemType, bits_per_item, TableType, HashFamily>>
{
using Table = cuckoofilter::CuckooFilter<ItemType, bits_per_item, TableType, HashFamily>;
static Table ConstructFromAddCount(size_t add_count)
{
return Table(add_count);
}
static void Add(uint64_t key, Table *table)
{
if (table->Add(key) != cuckoofilter::Ok)
{
std::cerr << "Cuckoo filter is too full. Inertion of the element (" << key << ") failed.\n";
get_info(table);
throw logic_error("The filter is too small to hold all of the elements");
}
}
static void AddAll(const vector<ItemType> keys, const size_t start, const size_t end, Table *table)
{
for (int i = start; i < end; ++i)
{
if (table->Add(keys[i]) != cuckoofilter::Ok)
{
std::cerr << "Cuckoo filter is too full. Inertion of the element (" << keys[i] << ") failed.\n";
get_info(table);
throw logic_error("The filter is too small to hold all of the elements");
}
}
}
static void AddAll(const std::vector<ItemType> keys, Table *table)
{
for (int i = 0; i < keys.size(); ++i)
{
if (table->Add(keys[i]) != cuckoofilter::Ok) {
std::cerr << "Cuckoo filter is too full. Inertion of the element (" << keys[i] << ") failed.\n";
// std::cerr << "Load before insertion is: " << ;
get_info(table);
throw logic_error("The filter is too small to hold all of the elements");
}
}
// table->AddAll(keys, 0, keys.size());
}
static void Remove(uint64_t key, Table *table)
{
table->Delete(key);
}
CONTAIN_ATTRIBUTES static bool Contain(uint64_t key, const Table *table)
{
return (0 == table->Contain(key));
}
static string get_name(Table *table)
{
auto ss = table->Info();
std::string temp = "PackedHashtable";
if (ss.find(temp)!= std::string::npos){
return "CF-ss";
}
return "Cuckoo";
}
static auto get_info(const Table *table) ->std::stringstream
{
std::string state = table->Info();
std::stringstream ss;
ss << state;
return ss;
// std::cout << state << std::endl;
}
static auto get_ID(Table *table) -> filter_id
{
return CF;
}
};
template <
class TableType, typename spareItemType,
typename itemType>
struct FilterAPI<att_d512<TableType, spareItemType, itemType>>
{
using Table = att_d512<TableType, spareItemType, itemType, 8, 51, 50>;
// using Table = dict512<TableType, spareItemType, itemType>;
static Table ConstructFromAddCount(size_t add_count)
{
return Table(add_count, .955, .5);
}
static void Add(itemType key, Table *table)
{
// assert(table->case_validate());
table->insert(key);
// assert(table->case_validate());
}
static void AddAll(const std::vector<itemType> keys, const size_t start, const size_t end, Table *table)
{
for (int i = start; i < end; ++i)
{
table->insert(keys[i]);
}
}
static void AddAll(const std::vector<itemType> keys, Table *table)
{
for (int i = 0; i < keys.size(); ++i)
{
table->insert(keys[i]);
}
}
static void Remove(itemType key, Table *table)
{
// std::cout << "Remove in Wrapper!" << std::endl;
table->remove(key);
}
CONTAIN_ATTRIBUTES static bool Contain(itemType key, const Table *table)
{
return table->lookup(key);
}
static string get_name(Table *table)
{
return table->get_name();
}
static auto get_info(Table *table) ->std::stringstream
{
return table->get_extended_info();
}
static auto get_ID(Table *table) -> filter_id
{
return att_d512_id;
}
};
template <typename itemType>
struct FilterAPI<twoChoicer<itemType>>
{
using Table = twoChoicer<itemType, 8, 51, 50>;
// using Table = dict512<TableType, spareItemType, itemType>;
static Table ConstructFromAddCount(size_t add_count)
{
return Table(add_count, .9, .5);
}
static void Add(itemType key, Table *table)
{
// assert(table->case_validate());
table->insert(key);
// assert(table->case_validate());
}
static void AddAll(const std::vector<itemType> keys, const size_t start, const size_t end, Table *table)
{
for (int i = start; i < end; ++i)
{
table->insert(keys[i]);
}
}
static void AddAll(const std::vector<itemType> keys, Table *table)
{
for (int i = 0; i < keys.size(); ++i)
{
table->insert(keys[i]);
}
}
static void Remove(itemType key, Table *table)
{
table->remove(key);
}
CONTAIN_ATTRIBUTES static bool Contain(itemType key, const Table *table)
{
return table->lookup(key);
}
static string get_name(Table *table)
{
return table->get_name();
}
static auto get_info(Table *table) ->std::stringstream
{
return table->get_extended_info();
}
static auto get_ID(Table *table) -> filter_id
{
return twoChoicer_id;
}
};
////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename ItemType, size_t bits_per_item, bool branchless, typename HashFamily>
struct FilterAPI<bloomfilter::bloom<ItemType, bits_per_item, branchless, HashFamily>>
{
using Table = bloomfilter::bloom<ItemType, bits_per_item, branchless, HashFamily>;
static Table ConstructFromAddCount(size_t add_count) {
return Table(add_count);
}
static void Add(uint64_t key, Table *table)
{
table->Add(key);
}
static void AddAll(const std::vector<ItemType> keys, const size_t start, const size_t end, Table *table)
{
table->AddAll(keys, start, end);
}
static void AddAll(const std::vector<ItemType> keys, Table *table)
{
table->AddAll(keys, 0, keys.size());
}
static void Remove(uint64_t key, Table *table)
{
throw std::runtime_error("Unsupported");
}
static string get_name(Table *table)
{
return "Bloom";
}
static auto get_info(Table *table) ->std::stringstream
{
assert(false);
std::stringstream ss;
return ss;
}
CONTAIN_ATTRIBUTES static bool Contain(uint64_t key, const Table *table)
{
return (0 == table->Contain(key));
}
static auto get_ID(Table *table) -> filter_id
{
return BF;
}
};
template <>
struct FilterAPI<SimdBlockFilter<>>
{
using Table = SimdBlockFilter<>;
static Table ConstructFromAddCount(size_t add_count)
{
Table ans(ceil(log2(add_count * 8.0 / CHAR_BIT)));
return ans;
}
static void Add(uint64_t key, Table *table)
{
table->Add(key);
}
static void AddAll(const vector<uint64_t> keys, const size_t start, const size_t end, Table *table)
{
for (int i = start; i < end; ++i)
{
table->Add(keys[i]);
}
}
static void AddAll(const std::vector<uint64_t> keys, Table *table)
{
AddAll(keys, 0, keys.size(), table);
/* for (int i = 0; i < keys.size(); ++i) {
table->Add(keys[i]);
}*/
}
static bool Contain(uint64_t key, const Table *table)
{
return table->Find(key);
}
static void Remove(uint64_t key, Table *table)
{
throw std::runtime_error("Unsupported");
}
static string get_name(Table *table)
{
return "SimdBlockFilter";
}
static auto get_info(Table *table) ->std::stringstream
{
assert(false);
std::stringstream ss;
return ss;
}
static auto get_ID(Table *table) -> filter_id
{
return SIMD;
}
};
class MortonFilter
{
using mf7_6 = CompressedCuckoo::Morton7_6;
mf7_6 *filter;
size_t size;
public:
MortonFilter(const size_t size)
{
// filter = new CompressedCuckoo::Morton3_8((size_t) (size / 0.95) + 64);
// filter = new CompressedCuckoo::Morton3_8((size_t) (2.1 * size) + 64);
filter = new mf7_6((size_t)(size / 0.95) + 64);
this->size = size;
}
~MortonFilter()
{
delete filter;
}
void Add(uint64_t key)
{
filter->insert(key);
}
void AddAll(const vector<uint64_t> keys, const size_t start, const size_t end)
{
size_t size = end - start;
::std::vector<uint64_t> k(size);
::std::vector<bool> status(size);
for (size_t i = start; i < end; i++)
{
k[i - start] = keys[i];
}
// TODO return value and status is ignored currently
filter->insert_many(k, status, size);
}
void AddAll(const std::vector<uint64_t> keys)
{
AddAll(keys, 0, keys.size());
}
inline bool Contain(uint64_t &item)
{
return filter->likely_contains(item);
};
size_t SizeInBytes() const
{
// according to morton_sample_configs.h:
// Morton3_8 - 3-slot buckets with 8-bit fingerprints: 11.7 bits/item
// (load factor = 0.95)
// so in theory we could just hardcode the size here,
// and don't measure it
// return (size_t)((size * 11.7) / 8);
return filter->SizeInBytes();
}
};
template <>
struct FilterAPI<MortonFilter>
{
using Table = MortonFilter;
static Table ConstructFromAddCount(size_t add_count)
{
return Table(add_count);
}
static void Add(uint64_t key, Table *table)
{
table->Add(key);
}
static void AddAll(const vector<uint64_t> keys, const size_t start, const size_t end, Table *table)
{
for (int i = start; i < end; ++i)
{
table->Add(keys[i]);
}
// table->AddAll(keys, start, end);
}
static void AddAll(const std::vector<uint64_t> keys, Table *table)
{
for (unsigned long key : keys)
{
table->Add(key);
}
}
static void Remove(uint64_t key, Table *table)
{
throw std::runtime_error("Unsupported");
}
CONTAIN_ATTRIBUTES static bool Contain(uint64_t key, Table *table)
{
return table->Contain(key);
}
static string get_name(Table *table)
{
return "Morton";
}
static auto get_info(Table *table) ->std::stringstream
{
assert(false);
std::stringstream ss;
return ss;
}
static auto get_ID(Table *table) -> filter_id
{
return MF;
}
};
//template<typename itemType, size_t bits_per_item,brancless, Hashfam>
//template<typename itemType, size_t bits_per_item, bool branchless, typename HashFamily>
//template<typename itemType, template<typename> class TableType>
//template<template<typename> class TableType, typename itemType, size_t bits_per_item>
//struct FilterAPI<dict<PD, TableType, itemType, bits_per_item>> {
template <template <typename> class TableType, typename itemType, typename spareItemType>
struct FilterAPI<dict<PD, TableType, itemType, spareItemType>>
{
// using Table = dict<PD, hash_table<uint32_t>, itemType, bits_per_item, branchless, HashFamily>;
using Table = dict<PD, TableType, itemType, spareItemType>;
static Table ConstructFromAddCount(size_t add_count, size_t bits_per_item)
{
return Table(add_count, bits_per_item, .95, .5);
}
static void Add(itemType key, Table *table)
{
table->insert(key);
}
static void AddAll(const std::vector<itemType> keys, const size_t start, const size_t end, Table *table)
{
for (int i = start; i < end; ++i)
{
table->insert(keys[i]);
}
}
static void AddAll(const std::vector<itemType> keys, Table *table)
{
for (int i = 0; i < keys.size(); ++i)
{
table->insert(keys[i]);
}
}
static void Remove(itemType key, Table *table)
{
table->remove(key);
}
CONTAIN_ATTRIBUTES static bool Contain(itemType key, const Table *table)
{
return table->lookup(key);
}
static string get_name(Table *table)
{
return "PD";
}
static auto get_info(Table *table) ->std::stringstream
{
assert(false);
std::stringstream ss;
return ss;
}
static auto get_ID(Table *table) -> filter_id
{
return pd_id;
}
};
/*
template<class temp_PD, template<typename> class TableType, typename itemType, typename spareItemType>
struct FilterAPI<dict<temp_PD, TableType, itemType, spareItemType>> {
using Table = dict<temp_PD, TableType, itemType, spareItemType>;
static Table ConstructFromAddCount(size_t add_count, size_t bits_per_item) {
return Table(add_count, bits_per_item, .95, .5);
}
static void Add(itemType key, Table *table) {
table->insert(key);
}
static void AddAll(const std::vector<itemType> keys, const size_t start, const size_t end, Table *table) {
for (int i = start; i < end; ++i) {
table->insert(keys[i]);
}
}
static void AddAll(const std::vector<itemType> keys, Table *table) {
for (int i = 0; i < keys.size(); ++i) {
table->insert(keys[i]);
}
}
static void Remove(itemType key, Table *table) {
table->remove(key);
}
CONTAIN_ATTRIBUTES static bool Contain(itemType key, const Table *table) {
return table->lookup(key);
}
static string get_name() {
// string res = "TPD";
// res += sizeof()
return "TPD";
}
};
*/
/*
template<template<typename, size_t, size_t> class temp_PD, typename slot_type, size_t bits_per_item, size_t max_capacity,
typename itemType,
template<typename> class TableType, typename spareItemType>
struct FilterAPI<dict<temp_PD<slot_type, bits_per_item, max_capacity>, TableType, itemType, spareItemType>> {
// using Table = dict<PD, hash_table<uint32_t>, itemType, bits_per_item, branchless, HashFamily>;
using Table = dict<TPD_name::TPD<slot_type, bits_per_item, max_capacity>, TableType, itemType, spareItemType>;
static Table ConstructFromAddCount(size_t add_count) {
return Table(add_count, bits_per_item, .95, .5, max_capacity);
}
static void Add(itemType key, Table *table) {
table->insert(key);
}
static void AddAll(const std::vector<itemType> keys, const size_t start, const size_t end, Table *table) {
for (int i = start; i < end; ++i) {
table->insert(keys[i]);
}
}
static void AddAll(const std::vector<itemType> keys, Table *table) {
for (int i = 0; i < keys.size(); ++i) {
table->insert(keys[i]);
}
}
static void Remove(itemType key, Table *table) {
table->remove(key);
}
CONTAIN_ATTRIBUTES static bool Contain(itemType key, const Table *table) {
return table->lookup(key);
}
static string get_name() {
// string res = "TPD";
// res += sizeof()
return "TPD";
}
};
*/
//<slot_type, bits_per_item, max_capacity>
template <
class temp_PD,
typename slot_type, size_t bits_per_item, size_t max_capacity,
typename itemType,
class TableType, typename spareItemType>
struct FilterAPI<
T_dict<temp_PD,
slot_type, bits_per_item, max_capacity,
TableType, spareItemType,
itemType>>
{
// using Table = T_dict<TPD_name::TPD<slot_type,bits_per_item, max_capacity>, slot_type, bits_per_item, max_capacity, TableType, spareItemType, itemType>;
using Table = T_dict<temp_PD, slot_type, bits_per_item, max_capacity, TableType, spareItemType, itemType>;
static Table ConstructFromAddCount(size_t add_count)
{
return Table(add_count, .95, .5);
}
static void Add(itemType key, Table *table)
{
table->insert(key);
}
static void AddAll(const std::vector<itemType> keys, const size_t start, const size_t end, Table *table)
{
for (int i = start; i < end; ++i)
{
table->insert(keys[i]);
}
}
static void AddAll(const std::vector<itemType> keys, Table *table)
{
for (int i = 0; i < keys.size(); ++i)
{
table->insert(keys[i]);
}
}
static void Remove(itemType key, Table *table)
{
table->remove(key);
}
CONTAIN_ATTRIBUTES static bool Contain(itemType key, const Table *table)
{
return table->lookup(key);
}
static string get_name(Table *table)
{
return table->get_name();
}
static auto get_info(Table *table) ->std::stringstream
{
table->get_dynamic_info();
std::stringstream ss;
return ss;
}
static auto get_ID(Table *table) -> filter_id
{
return tpd_id;
}
};
template <
class TableType, typename spareItemType,
typename itemType>
struct FilterAPI<
dict512<TableType, spareItemType,
itemType>>
{
using Table = dict512<TableType, spareItemType, itemType, 8, 51, 50>;
// using Table = dict512<TableType, spareItemType, itemType>;
static Table ConstructFromAddCount(size_t add_count)
{
return Table(add_count, 1, .5);
}
static void Add(itemType key, Table *table)
{
table->insert(key);
}
static void AddAll(const std::vector<itemType> keys, const size_t start, const size_t end, Table *table)
{
for (int i = start; i < end; ++i)
{
table->insert(keys[i]);
}
}
static void AddAll(const std::vector<itemType> keys, Table *table)
{
for (int i = 0; i < keys.size(); ++i)
{
table->insert(keys[i]);
}
}
static void Remove(itemType key, Table *table)
{
table->remove(key);
}
CONTAIN_ATTRIBUTES static bool Contain(itemType key, const Table *table)
{
return table->lookup(key);
}
static string get_name(Table *table)
{
return table->get_name();
}
static auto get_info(Table *table) ->std::stringstream
{
table->get_dynamic_info();
std::stringstream ss;
return ss;
}
static auto get_ID(Table *table) -> filter_id
{
return d512;
}
};
/**Before changing first argument in T_dict template argument*/
/*
template<
template<typename, size_t, size_t> class temp_PD,
typename slot_type, size_t bits_per_item, size_t max_capacity,
typename itemType,
template<typename> class TableType, typename spareItemType
>
struct FilterAPI<
T_dict<temp_PD,
slot_type, bits_per_item, max_capacity,
TableType, spareItemType,
itemType>
> {
using Table = T_dict<TPD_name::TPD, slot_type, bits_per_item, max_capacity, TableType, spareItemType, itemType>;
static Table ConstructFromAddCount(size_t add_count) {
return Table(add_count, .95, .5);
}
static void Add(itemType key, Table *table) {
table->insert(key);
}
static void AddAll(const std::vector<itemType> keys, const size_t start, const size_t end, Table *table) {
for (int i = start; i < end; ++i) {
table->insert(keys[i]);
}
}
static void AddAll(const std::vector<itemType> keys, Table *table) {
for (int i = 0; i < keys.size(); ++i) {
table->insert(keys[i]);
}
}
static void Remove(itemType key, Table *table) {
table->remove(key);
}
CONTAIN_ATTRIBUTES static bool Contain(itemType key, const Table *table) {
return table->lookup(key);
}
static string get_name() {
// string res = "TPD";
// res += sizeof()
return "T_dict";
}
};
*/
/*
#ifdef __AVX2__
template<typename HashFamily>
struct FilterAPI<SimdBlockFilter<HashFamily>> {
using Table = SimdBlockFilter<HashFamily>;
static Table ConstructFromAddCount(size_t add_count) {
Table ans(ceil(log2(add_count * 8.0 / CHAR_BIT)));
return ans;
}
static void Add(uint64_t key, Table *table) {
table->Add(key);
}
static void AddAll(const vector<uint64_t> keys, const size_t start, const size_t end, Table *table) {
throw std::runtime_error("Unsupported");
}
static void AddAll(const vector<uint64_t> keys, Table *table) {
throw std::runtime_error("Unsupported");
}
static void Remove(uint64_t key, Table *table) {
throw std::runtime_error("Unsupported");
}
CONTAIN_ATTRIBUTES static bool Contain(uint64_t key, const Table *table) {
return table->Find(key);
}
static string get_name() {
return "SimdBlockFilter";
}
};
template<typename HashFamily>
struct FilterAPI<SimdBlockFilterFixed64<HashFamily>> {
using Table = SimdBlockFilterFixed64<HashFamily>;
static Table ConstructFromAddCount(size_t add_count) {
Table ans(ceil(add_count * 8.0 / CHAR_BIT));
return ans;
}
static void Add(uint64_t key, Table *table) {
table->Add(key);
}
static void AddAll(const vector<uint64_t> keys, const size_t start, const size_t end, Table *table) {
throw std::runtime_error("Unsupported");
}
static void AddAll(const vector<uint64_t> keys, Table *table) {
throw std::runtime_error("Unsupported");
}
static void Remove(uint64_t key, Table *table) {
throw std::runtime_error("Unsupported");
}
CONTAIN_ATTRIBUTES static bool Contain(uint64_t key, const Table *table) {
return table->Find(key);
}
static string get_name() {
return "SimdBlockFilterFixed64";
}
};
*/
/*
template <typename HashFamily>
struct FilterAPI<SimdBlockFilterFixed16<HashFamily>> {
using Table = SimdBlockFilterFixed16<HashFamily>;
static Table ConstructFromAddCount(size_t add_count) {
Table ans(ceil(add_count * 8.0 / CHAR_BIT));
return ans;
}
static void Add(uint64_t key, Table* table) {
table->Add(key);
}
static void AddAll(const vector<uint64_t> keys, const size_t start, const size_t end, Table* table) {
throw std::runtime_error("Unsupported");
}
static void Remove(uint64_t key, Table * table) {
throw std::runtime_error("Unsupported");
}
CONTAIN_ATTRIBUTES static bool Contain(uint64_t key, const Table * table) {
return table->Find(key);
}
};
*/
/*
template<typename HashFamily>
struct FilterAPI<SimdBlockFilterFixed<HashFamily>> {
using Table = SimdBlockFilterFixed<HashFamily>;
static Table ConstructFromAddCount(size_t add_count) {
Table ans(ceil(add_count * 8.0 / CHAR_BIT));
return ans;
}
static void Add(uint64_t key, Table *table) {
table->Add(key);
}
static void AddAll(const vector<uint64_t> keys, const size_t start, const size_t end, Table *table) {
table->AddAll(keys, start, end);
}
static void AddAll(const vector<uint64_t> keys, Table *table) {
table->AddAll(keys, 0, keys.size());
}
static void Remove(uint64_t key, Table *table) {
throw std::runtime_error("Unsupported");
}
CONTAIN_ATTRIBUTES static bool Contain(uint64_t key, const Table *table) {
return table->Find(key);
}
static string get_name() {
return "SimdBlockFilterFixed";
}
};
#endif
*/
/*
template<typename itemType>
struct FilterAPI<set<itemType>> {
// using Table = dict<PD, hash_table<uint32_t>, itemType, bits_per_item, branchless, HashFamily>;
// using Table = set<itemType>;
static set<itemType> ConstructFromAddCount(size_t add_count) { return set<itemType>(); }
static void Add(itemType key, set<itemType> *table) {
table->insert(key);
}
static void AddAll(const std::vector<itemType> keys, const size_t start, const size_t end, set<itemType> *table) {
table->insert(keys);
// for (int i = start; i < end; ++i) {
// table->insert(keys[i]);
// }
}
static void AddAll(const std::vector<itemType> keys, Table *table) {
table->insert(keys);
// for (int i = 0; i < keys.size(); ++i) {
// table->insert(keys[i]);
// }
}
static void Remove(itemType key, Table *table) {
table->remove(key);
}
CONTAIN_ATTRIBUTES static bool Contain(itemType key, const Table *table) {
return table->lookup(key);
}
static string get_name() {
return "std::set";
}
};
*/
//typedef struct FilterAPI<bloomfilter::bloom<uint64_t, 8, false, HashUtil>> filter_api_bloom;
/*
template<typename itemType, typename FingerprintType, typename HashFamily>
struct FilterAPI<xorfilter::XorFilter<itemType, FingerprintType, HashFamily>> {
using Table = xorfilter::XorFilter<itemType, FingerprintType, HashFamily>;
static Table ConstructFromAddCount(size_t add_count) { return Table(add_count); }
static void Add(uint64_t key, Table *table) {
throw std::runtime_error("Unsupported");
}
static void AddAll(const vector<itemType> keys, const size_t start, const size_t end, Table *table) {
table->AddAll(keys, start, end);
}
static void AddAll(const std::vector<itemType> keys, Table *table) {
table->AddAll(keys, 0, keys.size());
}
static void Remove(uint64_t key, Table *table) {
throw std::runtime_error("Unsupported");
}
CONTAIN_ATTRIBUTES static bool Contain(uint64_t key, const Table *table) {
return (0 == table->Contain(key));
}
};
template<typename itemType, typename FingerprintType, typename FingerprintStorageType, typename HashFamily>
struct FilterAPI<xorfilter2::XorFilter2<itemType, FingerprintType, FingerprintStorageType, HashFamily>> {
using Table = xorfilter2::XorFilter2<itemType, FingerprintType, FingerprintStorageType, HashFamily>;
static Table ConstructFromAddCount(size_t add_count) { return Table(add_count); }
static void Add(uint64_t key, Table *table) {
throw std::runtime_error("Unsupported");
}
static void AddAll(const vector<itemType> keys, const size_t start, const size_t end, Table *table) {
table->AddAll(keys, start, end);
}
static void AddAll(const std::vector<itemType> keys, Table *table) {
table->AddAll(keys, 0, keys.size());
}
static void Remove(uint64_t key, Table *table) {
throw std::runtime_error("Unsupported");
}
CONTAIN_ATTRIBUTES static bool Contain(uint64_t key, const Table *table) {
return (0 == table->Contain(key));
}
};
template<typename itemType, typename HashFamily>
struct FilterAPI<xorfilter::XorFilter10<itemType, HashFamily>> {
using Table = xorfilter::XorFilter10<itemType, HashFamily>;
static Table ConstructFromAddCount(size_t add_count) { return Table(add_count); }
static void Add(uint64_t key, Table *table) {
throw std::runtime_error("Unsupported");
}
static void AddAll(const vector<itemType> keys, const size_t start, const size_t end, Table *table) {
table->AddAll(keys, start, end);
}
static void AddAll(const std::vector<itemType> keys, Table *table) {
table->AddAll(keys, 0, keys.size());
}
static void Remove(uint64_t key, Table *table) {
throw std::runtime_error("Unsupported");
}
CONTAIN_ATTRIBUTES static bool Contain(uint64_t key, const Table *table) {
return (0 == table->Contain(key));
}
};
template<typename itemType, typename HashFamily>
struct FilterAPI<xorfilter::XorFilter13<itemType, HashFamily>> {
using Table = xorfilter::XorFilter13<itemType, HashFamily>;
static Table ConstructFromAddCount(size_t add_count) { return Table(add_count); }
static void Add(uint64_t key, Table *table) {
throw std::runtime_error("Unsupported");
}
static void AddAll(const vector<itemType> keys, const size_t start, const size_t end, Table *table) {
table->AddAll(keys, start, end);
}
static void AddAll(const std::vector<itemType> keys, Table *table) {
table->AddAll(keys, 0, keys.size());
}
static void Remove(uint64_t key, Table *table) {
throw std::runtime_error("Unsupported");
}
CONTAIN_ATTRIBUTES static bool Contain(uint64_t key, const Table *table) {
return (0 == table->Contain(key));
}
};
template<typename itemType, typename HashFamily>
struct FilterAPI<xorfilter::XorFilter10_666<itemType, HashFamily>> {
using Table = xorfilter::XorFilter10_666<itemType, HashFamily>;
static Table ConstructFromAddCount(size_t add_count) { return Table(add_count); }
static void Add(uint64_t key, Table *table) {
throw std::runtime_error("Unsupported");
}
static void AddAll(const vector<itemType> keys, const size_t start, const size_t end, Table *table) {
table->AddAll(keys, start, end);
}
static void AddAll(const std::vector<itemType> keys, Table *table) {
table->AddAll(keys, 0, keys.size());
}
static void Remove(uint64_t key, Table *table) {
throw std::runtime_error("Unsupported");
}
CONTAIN_ATTRIBUTES static bool Contain(uint64_t key, const Table *table) {
return (0 == table->Contain(key));
}
};
template<typename itemType, typename FingerprintType, typename FingerprintStorageType, typename HashFamily>
struct FilterAPI<xorfilter2n::XorFilter2n<itemType, FingerprintType, FingerprintStorageType, HashFamily>> {
using Table = xorfilter2n::XorFilter2n<itemType, FingerprintType, FingerprintStorageType, HashFamily>;
static Table ConstructFromAddCount(size_t add_count) { return Table(add_count); }
static void Add(uint64_t key, Table *table) {
throw std::runtime_error("Unsupported");
}
static void AddAll(const vector<itemType> keys, const size_t start, const size_t end, Table *table) {
table->AddAll(keys, start, end);
}
static void AddAll(const std::vector<itemType> keys, Table *table) {
table->AddAll(keys, 0, keys.size());
}
static void Remove(uint64_t key, Table *table) {
throw std::runtime_error("Unsupported");
}
CONTAIN_ATTRIBUTES static bool Contain(uint64_t key, const Table *table) {
return (0 == table->Contain(key));
}
};
template<typename itemType, typename FingerprintType, typename HashFamily>
struct FilterAPI<xorfilter_plus::XorFilterPlus<itemType, FingerprintType, HashFamily>> {
using Table = xorfilter_plus::XorFilterPlus<itemType, FingerprintType, HashFamily>;
static Table ConstructFromAddCount(size_t add_count) { return Table(add_count); }
static void Add(uint64_t key, Table *table) {
throw std::runtime_error("Unsupported");
}
static void AddAll(const vector<itemType> keys, const size_t start, const size_t end, Table *table) {
table->AddAll(keys, start, end);
}
static void AddAll(const std::vector<itemType> keys, Table *table) {
table->AddAll(keys, 0, keys.size());
}
static void Remove(uint64_t key, Table *table) {
throw std::runtime_error("Unsupported");
}
CONTAIN_ATTRIBUTES static bool Contain(uint64_t key, const Table *table) {
return (0 == table->Contain(key));
}
};
*/
#endif //FILTERS_WRAPPERS_HPP
| 33,660 | 11,257 |
// This file is licensed under the Elastic License 2.0. Copyright 2021-present, StarRocks Limited.
#include <gtest/gtest.h>
#include <iostream>
#include <vector>
#include "formats/parquet/schema.h"
namespace starrocks::parquet {
class ParquetSchemaTest : public testing::Test {
public:
ParquetSchemaTest() {}
virtual ~ParquetSchemaTest() {}
};
TEST_F(ParquetSchemaTest, EmptySchema) {
std::vector<tparquet::SchemaElement> t_schemas;
SchemaDescriptor desc;
auto st = desc.from_thrift(t_schemas);
ASSERT_FALSE(st.ok());
}
TEST_F(ParquetSchemaTest, OnlyRoot) {
std::vector<tparquet::SchemaElement> t_schemas;
t_schemas.resize(1);
{
auto& t_schema = t_schemas[0];
t_schema.name = "hive-schema";
t_schema.__set_num_children(0);
}
SchemaDescriptor desc;
auto st = desc.from_thrift(t_schemas);
ASSERT_FALSE(st.ok());
}
TEST_F(ParquetSchemaTest, OnlyLeafType) {
std::vector<tparquet::SchemaElement> t_schemas;
t_schemas.resize(3);
// Root
{
auto& t_schema = t_schemas[0];
t_schema.name = "hive-schema";
t_schema.__set_num_children(2);
}
// INT32
{
auto& t_schema = t_schemas[1];
t_schema.__set_type(tparquet::Type::INT32);
t_schema.name = "col1";
t_schema.__set_num_children(0);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL);
}
// BYTE_ARRAY
{
auto& t_schema = t_schemas[2];
t_schema.__set_type(tparquet::Type::BYTE_ARRAY);
t_schema.name = "col2";
t_schema.__set_num_children(0);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::REQUIRED);
}
SchemaDescriptor desc;
auto st = desc.from_thrift(t_schemas);
ASSERT_TRUE(st.ok());
{
auto idx = desc.get_column_index("col1");
ASSERT_EQ(0, idx);
auto field = desc.get_stored_column_by_idx(0);
ASSERT_STREQ("col1", field->name.c_str());
ASSERT_EQ(0, field->physical_column_index);
ASSERT_EQ(1, field->max_def_level());
ASSERT_EQ(0, field->max_rep_level());
ASSERT_EQ(true, field->is_nullable);
}
{
auto idx = desc.get_column_index("col2");
ASSERT_EQ(1, idx);
auto field = desc.get_stored_column_by_idx(1);
ASSERT_STREQ("col2", field->name.c_str());
ASSERT_EQ(1, field->physical_column_index);
ASSERT_EQ(0, field->max_def_level());
ASSERT_EQ(0, field->max_rep_level());
ASSERT_EQ(false, field->is_nullable);
}
LOG(INFO) << desc.debug_string();
}
TEST_F(ParquetSchemaTest, NestedType) {
std::vector<tparquet::SchemaElement> t_schemas;
t_schemas.resize(8);
// Root
{
auto& t_schema = t_schemas[0];
t_schema.name = "hive-schema";
t_schema.__set_num_children(3);
}
// col1: INT32
{
auto& t_schema = t_schemas[1];
t_schema.__set_type(tparquet::Type::INT32);
t_schema.name = "col1";
t_schema.__set_num_children(0);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL);
}
// col2: LIST(BYTE_ARRAY)
{
int idx_base = 2;
// level-1
{
auto& t_schema = t_schemas[idx_base + 0];
t_schema.name = "col2";
t_schema.__set_num_children(1);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL);
t_schema.__set_converted_type(tparquet::ConvertedType::LIST);
}
// level-2
{
auto& t_schema = t_schemas[idx_base + 1];
t_schema.name = "list";
t_schema.__set_num_children(1);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::REPEATED);
}
// level-3
{
auto& t_schema = t_schemas[idx_base + 2];
t_schema.__set_type(tparquet::Type::BYTE_ARRAY);
t_schema.name = "element";
t_schema.__set_num_children(0);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL);
}
}
// col3: STRUCT{ a: INT32, b: BYTE_ARRAY}
{
int idx_base = 5;
{
auto& t_schema = t_schemas[idx_base + 0];
t_schema.name = "col3";
t_schema.__set_num_children(2);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL);
}
// field-a
{
auto& t_schema = t_schemas[idx_base + 1];
t_schema.__set_type(tparquet::Type::INT32);
t_schema.name = "a";
t_schema.__set_num_children(0);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL);
}
// field-b
{
auto& t_schema = t_schemas[idx_base + 2];
t_schema.__set_type(tparquet::Type::BYTE_ARRAY);
t_schema.name = "b";
t_schema.__set_num_children(0);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::REQUIRED);
}
}
SchemaDescriptor desc;
auto st = desc.from_thrift(t_schemas);
ASSERT_TRUE(st.ok());
// Check col2
{
auto field = desc.resolve_by_name("col2");
ASSERT_EQ(TYPE_ARRAY, field->type.type);
ASSERT_EQ(2, field->max_def_level());
ASSERT_EQ(1, field->max_rep_level());
ASSERT_EQ(0, field->level_info.immediate_repeated_ancestor_def_level);
ASSERT_EQ(true, field->is_nullable);
auto child = &field->children[0];
ASSERT_EQ(3, child->max_def_level());
ASSERT_EQ(1, child->max_rep_level());
ASSERT_EQ(2, child->level_info.immediate_repeated_ancestor_def_level);
ASSERT_EQ(1, child->physical_column_index);
ASSERT_EQ(true, child->is_nullable);
}
// Check col3
{
auto field = desc.resolve_by_name("col3");
ASSERT_EQ(TYPE_STRUCT, field->type.type);
ASSERT_EQ(1, field->max_def_level());
ASSERT_EQ(0, field->max_rep_level());
ASSERT_EQ(true, field->is_nullable);
auto child_a = &field->children[0];
ASSERT_EQ(2, child_a->max_def_level());
ASSERT_EQ(0, child_a->max_rep_level());
ASSERT_EQ(2, child_a->physical_column_index);
ASSERT_EQ(true, child_a->is_nullable);
auto child_b = &field->children[1];
ASSERT_EQ(1, child_b->max_def_level());
ASSERT_EQ(0, child_b->max_rep_level());
ASSERT_EQ(3, child_b->physical_column_index);
ASSERT_EQ(false, child_b->is_nullable);
}
LOG(INFO) << desc.debug_string();
}
TEST_F(ParquetSchemaTest, InvalidCase1) {
std::vector<tparquet::SchemaElement> t_schemas;
t_schemas.resize(3);
// Root
{
auto& t_schema = t_schemas[0];
t_schema.name = "hive-schema";
t_schema.__set_num_children(1);
}
// INT32
{
auto& t_schema = t_schemas[1];
t_schema.__set_type(tparquet::Type::INT32);
t_schema.name = "col1";
t_schema.__set_num_children(0);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL);
}
// BYTE_ARRAY
{
auto& t_schema = t_schemas[2];
t_schema.__set_type(tparquet::Type::BYTE_ARRAY);
t_schema.name = "col2";
t_schema.__set_num_children(0);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::REQUIRED);
}
SchemaDescriptor desc;
auto st = desc.from_thrift(t_schemas);
ASSERT_FALSE(st.ok());
}
TEST_F(ParquetSchemaTest, InvalidCase2) {
std::vector<tparquet::SchemaElement> t_schemas;
t_schemas.resize(3);
// Root
{
auto& t_schema = t_schemas[0];
t_schema.name = "hive-schema";
t_schema.__set_num_children(3);
}
// INT32
{
auto& t_schema = t_schemas[1];
t_schema.__set_type(tparquet::Type::INT32);
t_schema.name = "col1";
t_schema.__set_num_children(0);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL);
}
// BYTE_ARRAY
{
auto& t_schema = t_schemas[2];
t_schema.__set_type(tparquet::Type::BYTE_ARRAY);
t_schema.name = "col2";
t_schema.__set_num_children(0);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::REQUIRED);
}
SchemaDescriptor desc;
auto st = desc.from_thrift(t_schemas);
ASSERT_FALSE(st.ok());
}
TEST_F(ParquetSchemaTest, InvalidList1) {
std::vector<tparquet::SchemaElement> t_schemas;
t_schemas.resize(2);
// Root
{
auto& t_schema = t_schemas[0];
t_schema.name = "hive-schema";
t_schema.__set_num_children(1);
}
// Col1: Array
{
int idx_base = 1;
// level-1
{
auto& t_schema = t_schemas[idx_base + 0];
t_schema.name = "col2";
t_schema.__set_num_children(1);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::REPEATED);
t_schema.__set_converted_type(tparquet::ConvertedType::LIST);
}
}
SchemaDescriptor desc;
auto st = desc.from_thrift(t_schemas);
ASSERT_FALSE(st.ok());
}
TEST_F(ParquetSchemaTest, InvalidList2) {
std::vector<tparquet::SchemaElement> t_schemas;
t_schemas.resize(2);
// Root
{
auto& t_schema = t_schemas[0];
t_schema.name = "hive-schema";
t_schema.__set_num_children(1);
}
// Col1: Array
{
int idx_base = 1;
// level-1
{
auto& t_schema = t_schemas[idx_base + 0];
t_schema.name = "col2";
t_schema.__set_num_children(2);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL);
t_schema.__set_converted_type(tparquet::ConvertedType::LIST);
}
}
SchemaDescriptor desc;
auto st = desc.from_thrift(t_schemas);
ASSERT_FALSE(st.ok());
}
TEST_F(ParquetSchemaTest, InvalidList3) {
std::vector<tparquet::SchemaElement> t_schemas;
t_schemas.resize(2);
// Root
{
auto& t_schema = t_schemas[0];
t_schema.name = "hive-schema";
t_schema.__set_num_children(1);
}
// Col1: Array
{
int idx_base = 1;
// level-1
{
auto& t_schema = t_schemas[idx_base + 0];
t_schema.name = "col2";
t_schema.__set_num_children(1);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL);
t_schema.__set_converted_type(tparquet::ConvertedType::LIST);
}
}
SchemaDescriptor desc;
auto st = desc.from_thrift(t_schemas);
ASSERT_FALSE(st.ok());
}
TEST_F(ParquetSchemaTest, InvalidList4) {
std::vector<tparquet::SchemaElement> t_schemas;
t_schemas.resize(3);
// Root
{
auto& t_schema = t_schemas[0];
t_schema.name = "hive-schema";
t_schema.__set_num_children(1);
}
// Col1: Array
{
int idx_base = 1;
// level-1
{
auto& t_schema = t_schemas[idx_base + 0];
t_schema.name = "col2";
t_schema.__set_num_children(1);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL);
t_schema.__set_converted_type(tparquet::ConvertedType::LIST);
}
// level-2
{
auto& t_schema = t_schemas[idx_base + 1];
t_schema.name = "list";
t_schema.__set_num_children(1);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL);
}
}
SchemaDescriptor desc;
auto st = desc.from_thrift(t_schemas);
ASSERT_FALSE(st.ok());
}
TEST_F(ParquetSchemaTest, SimpleArray) {
std::vector<tparquet::SchemaElement> t_schemas;
t_schemas.resize(2);
// Root
{
auto& t_schema = t_schemas[0];
t_schema.name = "hive-schema";
t_schema.__set_num_children(1);
}
// Col1: Array
{
int idx_base = 1;
// level-1
{
auto& t_schema = t_schemas[idx_base + 0];
t_schema.name = "col2";
t_schema.__set_type(tparquet::Type::INT32);
t_schema.__set_num_children(0);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::REPEATED);
}
}
SchemaDescriptor desc;
auto st = desc.from_thrift(t_schemas);
ASSERT_TRUE(st.ok());
{
auto field = desc.resolve_by_name("col2");
ASSERT_EQ(TYPE_ARRAY, field->type.type);
ASSERT_EQ(1, field->max_def_level());
ASSERT_EQ(1, field->max_rep_level());
ASSERT_EQ(false, field->is_nullable);
ASSERT_EQ(0, field->level_info.immediate_repeated_ancestor_def_level);
auto child = &field->children[0];
ASSERT_EQ(1, child->max_def_level());
ASSERT_EQ(1, child->max_rep_level());
ASSERT_EQ(false, child->is_nullable);
ASSERT_EQ(1, child->level_info.immediate_repeated_ancestor_def_level);
ASSERT_EQ(0, child->physical_column_index);
}
}
TEST_F(ParquetSchemaTest, TwoLevelArray) {
std::vector<tparquet::SchemaElement> t_schemas;
t_schemas.resize(3);
// Root
{
auto& t_schema = t_schemas[0];
t_schema.name = "hive-schema";
t_schema.__set_num_children(1);
}
// Col1: Array
{
int idx_base = 1;
// level-1
{
auto& t_schema = t_schemas[idx_base + 0];
t_schema.name = "col2";
t_schema.__set_num_children(1);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL);
t_schema.__set_converted_type(tparquet::ConvertedType::LIST);
}
// level-2
{
auto& t_schema = t_schemas[idx_base + 1];
t_schema.name = "field";
t_schema.__set_type(tparquet::Type::INT32);
t_schema.__set_num_children(0);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::REPEATED);
}
}
SchemaDescriptor desc;
auto st = desc.from_thrift(t_schemas);
ASSERT_TRUE(st.ok());
{
auto field = desc.resolve_by_name("col2");
ASSERT_EQ(TYPE_ARRAY, field->type.type);
ASSERT_EQ(2, field->max_def_level());
ASSERT_EQ(1, field->max_rep_level());
ASSERT_EQ(true, field->is_nullable);
ASSERT_EQ(0, field->level_info.immediate_repeated_ancestor_def_level);
auto child = &field->children[0];
ASSERT_EQ(2, child->max_def_level());
ASSERT_EQ(1, child->max_rep_level());
ASSERT_EQ(false, child->is_nullable);
ASSERT_EQ(2, child->level_info.immediate_repeated_ancestor_def_level);
ASSERT_EQ(0, child->physical_column_index);
}
}
TEST_F(ParquetSchemaTest, MapNormal) {
std::vector<tparquet::SchemaElement> t_schemas;
t_schemas.resize(5);
// Root
{
auto& t_schema = t_schemas[0];
t_schema.name = "hive-schema";
t_schema.__set_num_children(1);
}
// Col1: Array
{
int idx_base = 1;
// level-1
{
auto& t_schema = t_schemas[idx_base + 0];
t_schema.name = "col2";
t_schema.__set_num_children(1);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL);
t_schema.__set_converted_type(tparquet::ConvertedType::MAP);
}
// level-2
{
auto& t_schema = t_schemas[idx_base + 1];
t_schema.name = "key_value";
t_schema.__set_type(tparquet::Type::INT32);
t_schema.__set_num_children(2);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::REPEATED);
}
// key
{
auto& t_schema = t_schemas[idx_base + 2];
t_schema.name = "key";
t_schema.__set_type(tparquet::Type::INT32);
t_schema.__set_num_children(0);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::REQUIRED);
}
// value
{
auto& t_schema = t_schemas[idx_base + 3];
t_schema.name = "value";
t_schema.__set_type(tparquet::Type::INT32);
t_schema.__set_num_children(0);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL);
}
}
SchemaDescriptor desc;
auto st = desc.from_thrift(t_schemas);
ASSERT_TRUE(st.ok());
{
auto field = desc.resolve_by_name("col2");
ASSERT_EQ(TYPE_MAP, field->type.type);
ASSERT_EQ(2, field->max_def_level());
ASSERT_EQ(1, field->max_rep_level());
ASSERT_EQ(true, field->is_nullable);
ASSERT_EQ(0, field->level_info.immediate_repeated_ancestor_def_level);
auto key_value = &field->children[0];
ASSERT_EQ(2, key_value->max_def_level());
ASSERT_EQ(1, key_value->max_rep_level());
ASSERT_EQ(false, key_value->is_nullable);
ASSERT_EQ(2, key_value->level_info.immediate_repeated_ancestor_def_level);
}
}
TEST_F(ParquetSchemaTest, InvalidMap1) {
std::vector<tparquet::SchemaElement> t_schemas;
t_schemas.resize(3);
// Root
{
auto& t_schema = t_schemas[0];
t_schema.name = "hive-schema";
t_schema.__set_num_children(1);
}
// Col1: Array
{
int idx_base = 1;
// level-1
{
auto& t_schema = t_schemas[idx_base + 0];
t_schema.name = "col2";
t_schema.__set_num_children(1);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL);
t_schema.__set_converted_type(tparquet::ConvertedType::MAP);
}
// level-2
{
auto& t_schema = t_schemas[idx_base + 1];
t_schema.name = "key_value";
t_schema.__set_type(tparquet::Type::INT32);
t_schema.__set_num_children(2);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::REPEATED);
}
}
SchemaDescriptor desc;
auto st = desc.from_thrift(t_schemas);
ASSERT_FALSE(st.ok());
}
TEST_F(ParquetSchemaTest, InvalidMap2) {
std::vector<tparquet::SchemaElement> t_schemas;
t_schemas.resize(4);
// Root
{
auto& t_schema = t_schemas[0];
t_schema.name = "hive-schema";
t_schema.__set_num_children(1);
}
// Col1: Array
{
int idx_base = 1;
// level-1
{
auto& t_schema = t_schemas[idx_base + 0];
t_schema.name = "col2";
t_schema.__set_num_children(2);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL);
t_schema.__set_converted_type(tparquet::ConvertedType::MAP);
}
// key
{
auto& t_schema = t_schemas[idx_base + 1];
t_schema.name = "key";
t_schema.__set_type(tparquet::Type::INT32);
t_schema.__set_num_children(0);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::REQUIRED);
}
// value
{
auto& t_schema = t_schemas[idx_base + 2];
t_schema.name = "value";
t_schema.__set_type(tparquet::Type::INT32);
t_schema.__set_num_children(0);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL);
}
}
SchemaDescriptor desc;
auto st = desc.from_thrift(t_schemas);
ASSERT_FALSE(st.ok());
}
TEST_F(ParquetSchemaTest, InvalidMap3) {
std::vector<tparquet::SchemaElement> t_schemas;
t_schemas.resize(4);
// Root
{
auto& t_schema = t_schemas[0];
t_schema.name = "hive-schema";
t_schema.__set_num_children(1);
}
// Col1: Array
{
int idx_base = 1;
// level-1
{
auto& t_schema = t_schemas[idx_base + 0];
t_schema.name = "col2";
t_schema.__set_num_children(2);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::REPEATED);
t_schema.__set_converted_type(tparquet::ConvertedType::MAP);
}
// key
{
auto& t_schema = t_schemas[idx_base + 1];
t_schema.name = "key";
t_schema.__set_type(tparquet::Type::INT32);
t_schema.__set_num_children(0);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::REQUIRED);
}
// value
{
auto& t_schema = t_schemas[idx_base + 2];
t_schema.name = "value";
t_schema.__set_type(tparquet::Type::INT32);
t_schema.__set_num_children(0);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL);
}
}
SchemaDescriptor desc;
auto st = desc.from_thrift(t_schemas);
ASSERT_FALSE(st.ok());
}
TEST_F(ParquetSchemaTest, InvalidMap4) {
std::vector<tparquet::SchemaElement> t_schemas;
t_schemas.resize(5);
// Root
{
auto& t_schema = t_schemas[0];
t_schema.name = "hive-schema";
t_schema.__set_num_children(1);
}
// Col1: Array
{
int idx_base = 1;
// level-1
{
auto& t_schema = t_schemas[idx_base + 0];
t_schema.name = "col2";
t_schema.__set_num_children(1);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL);
t_schema.__set_converted_type(tparquet::ConvertedType::MAP);
}
// level-2
{
auto& t_schema = t_schemas[idx_base + 1];
t_schema.name = "key_value";
t_schema.__set_type(tparquet::Type::INT32);
t_schema.__set_num_children(2);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL);
}
// key
{
auto& t_schema = t_schemas[idx_base + 2];
t_schema.name = "key";
t_schema.__set_type(tparquet::Type::INT32);
t_schema.__set_num_children(0);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::REQUIRED);
}
// value
{
auto& t_schema = t_schemas[idx_base + 3];
t_schema.name = "value";
t_schema.__set_type(tparquet::Type::INT32);
t_schema.__set_num_children(0);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL);
}
}
SchemaDescriptor desc;
auto st = desc.from_thrift(t_schemas);
ASSERT_FALSE(st.ok());
}
TEST_F(ParquetSchemaTest, InvalidMap5) {
std::vector<tparquet::SchemaElement> t_schemas;
t_schemas.resize(5);
// Root
{
auto& t_schema = t_schemas[0];
t_schema.name = "hive-schema";
t_schema.__set_num_children(1);
}
// Col1: Array
{
int idx_base = 1;
// level-1
{
auto& t_schema = t_schemas[idx_base + 0];
t_schema.name = "col2";
t_schema.__set_num_children(1);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL);
t_schema.__set_converted_type(tparquet::ConvertedType::MAP);
}
// level-2
{
auto& t_schema = t_schemas[idx_base + 1];
t_schema.name = "key_value";
t_schema.__set_type(tparquet::Type::INT32);
t_schema.__set_num_children(2);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::REPEATED);
}
// key
{
auto& t_schema = t_schemas[idx_base + 2];
t_schema.name = "key";
t_schema.__set_type(tparquet::Type::INT32);
t_schema.__set_num_children(0);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL);
}
// value
{
auto& t_schema = t_schemas[idx_base + 3];
t_schema.name = "value";
t_schema.__set_type(tparquet::Type::INT32);
t_schema.__set_num_children(0);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL);
}
}
SchemaDescriptor desc;
auto st = desc.from_thrift(t_schemas);
ASSERT_FALSE(st.ok());
}
TEST_F(ParquetSchemaTest, InvalidMap6) {
std::vector<tparquet::SchemaElement> t_schemas;
t_schemas.resize(6);
// Root
{
auto& t_schema = t_schemas[0];
t_schema.name = "hive-schema";
t_schema.__set_num_children(1);
}
// Col1: Array
{
int idx_base = 1;
// level-1
{
auto& t_schema = t_schemas[idx_base + 0];
t_schema.name = "col2";
t_schema.__set_num_children(1);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL);
t_schema.__set_converted_type(tparquet::ConvertedType::MAP);
}
// level-2
{
auto& t_schema = t_schemas[idx_base + 1];
t_schema.name = "key_value";
t_schema.__set_type(tparquet::Type::INT32);
t_schema.__set_num_children(3);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::REPEATED);
}
// key
{
auto& t_schema = t_schemas[idx_base + 2];
t_schema.name = "key";
t_schema.__set_type(tparquet::Type::INT32);
t_schema.__set_num_children(0);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL);
}
// value
{
auto& t_schema = t_schemas[idx_base + 3];
t_schema.name = "value";
t_schema.__set_type(tparquet::Type::INT32);
t_schema.__set_num_children(0);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL);
}
// value3
{
auto& t_schema = t_schemas[idx_base + 4];
t_schema.name = "value2";
t_schema.__set_type(tparquet::Type::INT32);
t_schema.__set_num_children(0);
t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL);
}
}
SchemaDescriptor desc;
auto st = desc.from_thrift(t_schemas);
ASSERT_FALSE(st.ok());
}
} // namespace starrocks::parquet
| 26,359 | 9,349 |
class WebQueryTest;
#define TEST_FRIEND WebQueryTest;
#include <plugintest.h>
#include <QtGui/QGuiApplication>
#include "updaterserver.h"
using namespace QtAutoUpdater;
class WebQueryTest : public PluginTest
{
Q_OBJECT
protected:
bool init() override;
bool cleanup() override;
QString backend() const override;
QVariantMap config() override;
QVariantMap performConfig() override;
QList<UpdateInfo> createInfos(const QVersionNumber &versionFrom, const QVersionNumber &versionTo) override;
bool simulateInstall(const QVersionNumber &version) override;
bool prepareUpdate(const QVersionNumber &version) override;
bool canAbort(bool hard) const override;
bool cancelState() const override;
private Q_SLOTS:
void testSpecialUpdates_data();
void testSpecialUpdates();
private:
UpdaterServer *_server = nullptr;
QString _parser = QStringLiteral("auto");
bool _autoQuery = true;
};
bool WebQueryTest::init()
{
TEST_WRAP_BEGIN
_server = new UpdaterServer{this};
QVERIFY(_server->create());
TEST_WRAP_END
}
bool WebQueryTest::cleanup()
{
_server->deleteLater();
_server = nullptr;
return true;
}
QString WebQueryTest::backend() const
{
return QStringLiteral("webquery");
}
QVariantMap WebQueryTest::config()
{
return {
{QStringLiteral("check/url"), _server->checkUrl()},
{QStringLiteral("check/autoQuery"), _autoQuery},
{QStringLiteral("check/parser"), _parser},
#ifdef Q_OS_WIN
{QStringLiteral("install/tool"), QStringLiteral("python")},
#else
{QStringLiteral("install/tool"), QStringLiteral("python3")},
#endif
{QStringLiteral("install/parallel"), true},
{QStringLiteral("install/arguments"), QStringList {
QStringLiteral(SRCDIR "installer.py"),
_server->installUrl().toString(QUrl::FullyEncoded)
}},
{QStringLiteral("install/addDataArgs"), true},
{QStringLiteral("install/runAsAdmin"), false}
};
}
QVariantMap WebQueryTest::performConfig()
{
return {
{QStringLiteral("check/url"), _server->checkUrl()},
{QStringLiteral("check/autoQuery"), _autoQuery},
{QStringLiteral("check/parser"), _parser},
{QStringLiteral("install/download"), true},
{QStringLiteral("install/downloadUrl"), _server->downloadUrl()},
#ifdef Q_OS_WIN
{QStringLiteral("install/tool"), QStringLiteral("python")},
#else
{QStringLiteral("install/tool"), QStringLiteral("python3")},
#endif
{QStringLiteral("install/parallel"), true},
{QStringLiteral("install/arguments"), QStringList {
QStringLiteral("%{downloadPath}"),
_server->installUrl().toString(QUrl::FullyEncoded)
}},
{QStringLiteral("install/addDataArgs"), true},
{QStringLiteral("install/runAsAdmin"), false}
};
}
QList<UpdateInfo> WebQueryTest::createInfos(const QVersionNumber &versionFrom, const QVersionNumber &versionTo)
{
if (versionTo > versionFrom) {
if (_parser == QStringLiteral("version")) {
return {
{
QCoreApplication::applicationName(),
QGuiApplication::applicationDisplayName(),
versionTo
}
};
} else {
return {
{
QStringLiteral("test-update"),
QStringLiteral("test-update"),
versionTo,
{
{QStringLiteral("arguments"), QStringList {
QVariant{true}.toString(),
versionTo.toString()
}},
{QStringLiteral("eulas"), QVariantList {
QStringLiteral("EULA 1"),
QVariantMap {
{QStringLiteral("text"), QStringLiteral("EULA 2")},
{QStringLiteral("required"), true},
},
QVariantMap {
{QStringLiteral("text"), QStringLiteral("EULA 3")},
{QStringLiteral("required"), false},
}
}}
}
}
};
}
} else
return {};
}
bool WebQueryTest::simulateInstall(const QVersionNumber &version)
{
QCoreApplication::setApplicationVersion(version.toString());
return true;
}
bool WebQueryTest::prepareUpdate(const QVersionNumber &version)
{
if (_parser == QStringLiteral("version")) {
_server->setUpdateInfo(version > QVersionNumber::fromString(QCoreApplication::applicationVersion()) ?
version :
QVersionNumber{});
} else {
_server->setUpdateInfo(createInfos(QVersionNumber::fromString(QCoreApplication::applicationVersion()),
version));
}
QUrlQuery query;
if (_autoQuery) {
query.addQueryItem(QStringLiteral("name"), QCoreApplication::applicationName());
query.addQueryItem(QStringLiteral("version"), QCoreApplication::applicationVersion());
query.addQueryItem(QStringLiteral("domain"), QCoreApplication::organizationDomain());
query.addQueryItem(QStringLiteral("abi"), QSysInfo::buildAbi());
query.addQueryItem(QStringLiteral("kernel-type"), QSysInfo::kernelType());
query.addQueryItem(QStringLiteral("kernel-version"), QSysInfo::kernelVersion());
query.addQueryItem(QStringLiteral("os-type"), QSysInfo::productType());
query.addQueryItem(QStringLiteral("os-version"), QSysInfo::productVersion());
}
_server->setQuery(query);
return true;
}
bool WebQueryTest::canAbort(bool hard) const
{
Q_UNUSED(hard)
return true;
}
bool WebQueryTest::cancelState() const
{
return false;
}
void WebQueryTest::testSpecialUpdates_data()
{
QTest::addColumn<QVersionNumber>("installedVersion");
QTest::addColumn<QVersionNumber>("updateVersion");
QTest::addColumn<int>("abortLevel");
QTest::addColumn<bool>("success");
QTest::addColumn<bool>("simpleVersion");
QTest::addColumn<bool>("noQuery");
QTest::newRow("complexVersion.noUpdates") << QVersionNumber(1, 0, 0)
<< QVersionNumber(1, 0, 0)
<< 0
<< true
<< false
<< false;
QTest::newRow("complexVersion.simpleUpdate") << QVersionNumber(1, 0, 0)
<< QVersionNumber(1, 1, 0)
<< 0
<< true
<< false
<< false;
QTest::newRow("simpleVersion.noUpdates") << QVersionNumber(1, 0, 0)
<< QVersionNumber(1, 0, 0)
<< 0
<< true
<< true
<< false;
QTest::newRow("simpleVersion.simpleUpdate") << QVersionNumber(1, 0, 0)
<< QVersionNumber(1, 1, 0)
<< 0
<< true
<< true
<< false;
QTest::newRow("noQuery.noUpdates") << QVersionNumber(1, 0, 0)
<< QVersionNumber(1, 0, 0)
<< 0
<< true
<< false
<< true;
QTest::newRow("noQuery.simpleUpdate") << QVersionNumber(1, 0, 0)
<< QVersionNumber(1, 1, 0)
<< 0
<< true
<< false
<< true;
}
void WebQueryTest::testSpecialUpdates()
{
QFETCH(bool, simpleVersion);
QFETCH(bool, noQuery);
_parser = simpleVersion ? QStringLiteral("version") : QStringLiteral("json");
_autoQuery = !noQuery;
testUpdateCheck();
}
QTEST_GUILESS_MAIN(WebQueryTest)
#include "tst_webquery.moc"
| 6,763 | 2,746 |
/* * Copyright (c) 2016 Regents of the University of California. 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. The names of its contributors may not 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.
*
* *********************************************************************************************** *
* CARLsim
* created by: (MDR) Micah Richert, (JN) Jayram M. Nageswaran
* maintained by:
* (MA) Mike Avery <averym@uci.edu>
* (MB) Michael Beyeler <mbeyeler@uci.edu>,
* (KDC) Kristofor Carlson <kdcarlso@uci.edu>
* (TSC) Ting-Shuo Chou <tingshuc@uci.edu>
* (HK) Hirak J Kashyap <kashyaph@uci.edu>
*
* CARLsim v1.0: JM, MDR
* CARLsim v2.0/v2.1/v2.2: JM, MDR, MA, MB, KDC
* CARLsim3: MB, KDC, TSC
* CARLsim4: TSC, HK
* CARLsim5: HK, JX, KC
*
* CARLsim available from http://socsci.uci.edu/~jkrichma/CARLsim/
* Ver 05/24/2017
*/
#include <neuron_monitor.h>
#include <neuron_monitor_core.h> // NeuronMonitor private implementation
#include <user_errors.h> // fancy user error messages
#include <sstream> // std::stringstream
#include <algorithm> // std::transform
// we aren't using namespace std so pay attention!
NeuronMonitor::NeuronMonitor(NeuronMonitorCore* neuronMonitorCorePtr){
// make sure the pointer is NULL
neuronMonitorCorePtr_ = neuronMonitorCorePtr;
}
NeuronMonitor::~NeuronMonitor() {
delete neuronMonitorCorePtr_;
}
void NeuronMonitor::clear(){
std::string funcName = "clear()";
UserErrors::assertTrue(!isRecording(), UserErrors::CANNOT_BE_ON, funcName, "Recording");
neuronMonitorCorePtr_->clear();
}
bool NeuronMonitor::isRecording(){
return neuronMonitorCorePtr_->isRecording();
}
void NeuronMonitor::startRecording() {
std::string funcName = "startRecording()";
UserErrors::assertTrue(!isRecording(), UserErrors::CANNOT_BE_ON, funcName, "Recording");
neuronMonitorCorePtr_->startRecording();
}
void NeuronMonitor::stopRecording(){
std::string funcName = "stopRecording()";
UserErrors::assertTrue(isRecording(), UserErrors::MUST_BE_ON, funcName, "Recording");
neuronMonitorCorePtr_->stopRecording();
}
void NeuronMonitor::setLogFile(const std::string& fileName) {
std::string funcName = "setLogFile";
FILE* fid;
std::string fileNameLower = fileName;
std::transform(fileNameLower.begin(), fileNameLower.end(), fileNameLower.begin(), ::tolower);
if (fileNameLower == "null") {
// user does not want a binary created
fid = NULL;
} else {
fid = fopen(fileName.c_str(),"wb");
//printf("%s\n", fileName.c_str());
if (fid==NULL) {
// default case: print error and exit
std::string fileError = " Double-check file permissions and make sure directory exists.";
UserErrors::assertTrue(false, UserErrors::FILE_CANNOT_OPEN, funcName, fileName, fileError);
}
}
// tell new file id to core object
neuronMonitorCorePtr_->setNeuronFileId(fid);
}
void NeuronMonitor::print() {
std::string funcName = "print()";
UserErrors::assertTrue(!isRecording(), UserErrors::CANNOT_BE_ON, funcName, "Recording");
neuronMonitorCorePtr_->print();
}
| 4,341 | 1,593 |
#pragma once
#include "device/Device.hpp"
#include "debug/Font.hpp"
#include "rendering/Mesh.hpp"
namespace lucent
{
class TextMesh
{
public:
TextMesh(Device* device, const Font& font);
void SetScreenSize(uint32 width, uint32 height);
float Draw(const std::string& str, float x, float y, Color color = Color::White());
float Draw(char c, float screenX, float screenY, Color color = Color::White());
void Clear();
void Upload();
void Render(Context& context);
private:
const Font& m_Font;
bool m_Dirty;
std::vector<Mesh::Vertex> m_Vertices;
std::vector<uint32> m_Indices;
Device* m_Device;
Buffer* m_VertexBuffer;
Buffer* m_IndexBuffer;
uint32 m_ScreenWidth;
uint32 m_ScreenHeight;
};
}
| 764 | 268 |
#include <bits/stdc++.h>
#define ll long long
using namespace std;
bool b[1005];
vector<vector<pair<ll,ll> > > vc(1005);
vector<vector<ll>> par(1005);
ll dis[1005][1005];
ll tr[1005];
void dij(ll i){
dis[i][i]=0;
// ll pr=i;
tr[i]=i;
priority_queue<pair<ll,ll>,vector<pair<ll,ll>>,greater<pair<ll,ll>> > pq;
pq.push({0,i});
while(!pq.empty()) {
ll el= pq.top().second;
pq.pop();
if(b[el]) continue;
b[el]=1;
par[i][el]=tr[el];
// pr=el;
// cout<<el<<"_";
for(auto elem:vc[el]) {
if(dis[i][elem.first]>dis[i][el]+elem.second) {
dis[i][elem.first]=dis[i][el]+elem.second;
pq.push({dis[i][elem.first],elem.first});
tr[elem.first]=el;
}
}
}
}
ll path_tracer(ll fr,ll to){
while(fr!=to){
cout<<to<<" ";
to=par[fr][to];
}
return 0;
}
int main(){
freopen("input_data.txt","r",stdin);
for(ll i=0;i<1005;i++)for(ll j=0;j<1005;j++)par[i].push_back(0),dis[i][j]=1e18;
ll n,x,y,w;
cin>>n;
for(ll i=0; i<n; i++) {
cin>>x>>y>>w;
vc[x].push_back({y,w});
vc[y].push_back({x,w});
}
for(ll i=1;i<37;i++){
dij(i);memset(b,0,sizeof(b)),memset(tr,0,sizeof(tr));
}
// for(ll i=1;i<6;i++){
// for(ll j=0;j<6;j++)cout<<i<<" "<<j<<" : "<<par[i][j]<<"_"<<dis[i][j]<<"\n";cout<<"\n";
// }
cout<<"___";
// path_tracer(2,5);
cout<<18<<" "<<26<<" "<<dis[18][26]<<"\n";
cout<<18<<" "<<36<<" "<<dis[18][36]<<"\n";
}
| 1,365 | 780 |
//
// Created by James Noeckel on 10/13/20.
//
#include "reconstruction/ReconstructionData.h"
#include <opencv2/opencv.hpp>
using namespace Eigen;
void saveEpipolarLines(ReconstructionData &reconstruction) {
for (auto &pair : reconstruction.images) {
Vector3d origin1 = pair.second.origin();
double minL2 = std::numeric_limits<double>::max();
int matchImgInd = -1;
for (const auto &pair2 : reconstruction.images) {
if (pair.first != pair2.first) {
Vector3d origin2 = pair2.second.origin();
double L2 = (origin1 - origin2).squaredNorm();
if (L2 < minL2) {
minL2 = L2;
matchImgInd = pair2.first;
}
}
}
Vector3d center(0, 0, 0);
Vector2d midpoint1 = reconstruction.project(center.transpose(), pair.first).transpose();
Vector2d midpoint2 = reconstruction.project(center.transpose(), matchImgInd).transpose();
// Vector2d midpoint1 = reconstruction.resolution(pair.first) * 0.5;
// Vector2d midpoint2 = reconstruction.resolution(matchImgInd) * 0.5;
Vector2d epipolarLine1 = reconstruction.epipolar_line(midpoint1.y(), midpoint1.x(),
pair.first, matchImgInd);
Vector2d epipolarLine2 = reconstruction.epipolar_line(midpoint2.y(), midpoint2.x(),
matchImgInd, pair.first);
Vector2d startpoint1 = midpoint1 - epipolarLine1 * midpoint1.x();
Vector2d otherpoint1 = midpoint1 + epipolarLine1 * midpoint1.x();
Vector2d startpoint2 = midpoint2 - epipolarLine2 * midpoint2.x();
Vector2d otherpoint2 = midpoint2 + epipolarLine2 * midpoint2.x();
cv::Mat img1 = pair.second.getImage().clone();
cv::line(img1, cv::Point(startpoint1.x(), startpoint1.y()), cv::Point(otherpoint1.x(), otherpoint1.y()), cv::Scalar(255, 100, 255), 2);
cv::circle(img1, cv::Point(midpoint1.x(), midpoint1.y()), 2, cv::Scalar(0, 0, 255), CV_FILLED);
cv::imwrite("image_" + std::to_string(pair.first) + "_" + std::to_string(matchImgInd) + "_" + std::to_string(pair.first) + ".png", img1);
cv::Mat img2 = reconstruction.images[matchImgInd].getImage().clone();
cv::line(img2, cv::Point(startpoint2.x(), startpoint2.y()), cv::Point(otherpoint2.x(), otherpoint2.y()), cv::Scalar(255, 100, 255), 2);
cv::circle(img2, cv::Point(midpoint2.x(), midpoint2.y()), 2, cv::Scalar(0, 0, 255), CV_FILLED);
cv::imwrite("image_" + std::to_string(pair.first) + "_" + std::to_string(matchImgInd) + "_" + std::to_string(matchImgInd) + ".png", img2);
}
}
int main(int argc, char **argv) {
ReconstructionData reconstruction;
if (!reconstruction.load_bundler_file("../data/bench/alignment_complete3/complete3.out")) {
std::cout << "failed to load reconstruction" << std::endl;
return 1;
}
//saveEpipolarLines(reconstruction);
reconstruction.setImageScale(0.25);
saveEpipolarLines(reconstruction);
return 0;
} | 3,139 | 1,058 |
#include "pch.h"
#include "Asteroids.h"
#include "BasicTimer.h"
#define STRINGIFY(str) #str
#define PLAYER_ACCELERATION 100.0f
#define TURN_SPEED 200.0f
#define MAX_ASTEROIDS 32
#define MAX_FALLOUT_PER_ASTEROID 20
#define FALLOUT_INITIAL_VEL 500.0f
#define BULLET_SPEED 300.0f
#define DESTROYED_ASTEROID_SPEED 100.0f
#define REGULAR_WEAPON_COOLDOWN 0.2f
#define SPREAD_WEAPON_COOLDOWN 0.5f
#define LASER_WEAPON_COOLDOWN 2.0f
#define THRUST_OUTPUT_RATE 5
#define MAX_THRUST_PARTICLES 200
#define LASER_LIFETIME 4.0f
#define PLAYER_STATE_W 0x1
#define PLAYER_STATE_A 0x2
#define PLAYER_STATE_S 0x4
#define PLAYER_STATE_D 0x8
#define PLAYER_STATE_SPACE 0x10
#define RENDER_TARGET_WIDTH 1024
#define RENDER_TARGET_HEIGHT 512
using namespace Windows::ApplicationModel;
using namespace Windows::ApplicationModel::Core;
using namespace Windows::ApplicationModel::Activation;
using namespace Windows::UI::Core;
using namespace Windows::System;
using namespace Windows::Foundation;
using namespace Windows::Graphics::Display;
using namespace concurrency;
using namespace DirectX;
Asteroids::Asteroids() :
m_playerState(0),
m_regularWeaponTimer(0),
m_spreadWeaponTimer(0),
m_laserWeaponTimer(0),
m_weapon(Weapon::Regular),
m_asteroidRespawnTime(10),
m_windowClosed(false),
m_windowVisible(false)
{
}
void Asteroids::Initialize(CoreApplicationView^ applicationView)
{
applicationView->Activated +=
ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &Asteroids::OnActivated);
CoreApplication::Suspending +=
ref new EventHandler<SuspendingEventArgs^>(this, &Asteroids::OnSuspending);
CoreApplication::Resuming +=
ref new EventHandler<Platform::Object^>(this, &Asteroids::OnResuming);
//m_renderer = ref new CubeRenderer();
m_player.m_scale = glm::vec2(40);
for(int i = 0; i < MAX_ASTEROIDS; ++i)
{
GameObject asteroid;
asteroid.m_pos.x = static_cast<float>(rand() % 10000);
asteroid.m_pos.y = static_cast<float>(rand() % 10000);
asteroid.m_angle = (rand() % 1000) / 10.0f - 50;
asteroid.m_omega = (rand() % 1000) / 10.0f - 50;
asteroid.m_vel.x = (rand() % 1000) / 10.0f - 50;
asteroid.m_vel.y = (rand() % 1000) / 10.0f - 50;
asteroid.m_scale.x = (rand() % 1000) / 20.0f + 50;
asteroid.m_scale.y = asteroid.m_scale.x;//(rand() % 1000) / 10.0f - 50;
asteroid.m_lives = 2;
m_asteroids.push_back(asteroid);
}
m_rocketThrust.m_emissionRate = THRUST_OUTPUT_RATE;
m_rocketThrust.m_maxParticles = MAX_THRUST_PARTICLES;
m_rocketThrust.m_emissionTimer = 0;
}
void Asteroids::SetWindow(CoreWindow^ window)
{
window->SizeChanged +=
ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &Asteroids::OnWindowSizeChanged);
window->VisibilityChanged +=
ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &Asteroids::OnVisibilityChanged);
window->Closed +=
ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &Asteroids::OnWindowClosed);
window->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);
window->PointerPressed +=
ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &Asteroids::OnPointerPressed);
window->PointerMoved +=
ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &Asteroids::OnPointerMoved);
window->KeyDown +=
ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &Asteroids::OnKeyDown);
window->KeyUp +=
ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &Asteroids::OnKeyUp);
//m_renderer->Initialize(CoreWindow::GetForCurrentThread());
m_orientation = DisplayProperties::CurrentOrientation;
m_windowBounds = window->Bounds;
esInitContext ( &m_esContext );
m_esContext.hWnd.window = CoreWindow::GetForCurrentThread();
esCreateWindow ( &m_esContext, TEXT("Simple Instancing"), 320, 240, ES_WINDOW_RGB );
const char *vs = STRINGIFY(
attribute vec3 a_position;
attribute vec4 a_color;
varying vec4 v_color;
uniform mat4 u_mvp;
void main(void)
{
v_color = a_color;
v_color.rgb *= a_color.a;
gl_Position = u_mvp * vec4(a_position, 1);
}
);
const char *fs = STRINGIFY(
precision mediump float;
varying vec4 v_color;
void main(void)
{
gl_FragColor = v_color;
}
);
m_drawProgram = esLoadProgram(vs, fs);
m_uMvpDraw = glGetUniformLocation(m_drawProgram, "u_mvp");
m_aPositionDraw = glGetAttribLocation(m_drawProgram, "a_position");
m_aColorDraw = glGetAttribLocation(m_drawProgram, "a_color");
vs = STRINGIFY(
attribute vec2 a_position;
varying vec2 v_uv;
void main(void)
{
gl_Position = vec4(a_position, 0, 1);
v_uv = a_position * 0.5 + 0.5;
}
);
fs = STRINGIFY(
precision mediump float;
varying vec2 v_uv;
uniform sampler2D u_texture;
uniform vec2 u_offset;
void main(void)
{
vec4 color;
const int radius = 1;
const float gaussianOffset = 1.4;
int divisor = 0;
for(int i = -radius; i <= radius; ++i)
{
vec2 uv = v_uv + u_offset * float(i) * gaussianOffset;
color += texture2D(u_texture, uv);
++divisor;
}
gl_FragColor = color / float(divisor);
}
);
m_blurProgram = esLoadProgram(vs, fs);
m_uTextureBlur = glGetUniformLocation(m_blurProgram, "u_texture");
m_uOffsetBlur = glGetUniformLocation(m_blurProgram, "u_offset");
m_aPositionBlur = glGetAttribLocation(m_blurProgram, "a_position");
fs = STRINGIFY(
precision mediump float;
varying vec2 v_uv;
uniform sampler2D u_texture;
void main(void)
{
gl_FragColor = texture2D(u_texture, v_uv);
}
);
m_texturePassThruProgram = esLoadProgram(vs, fs);
m_uTextureTexturePassThru = glGetUniformLocation(m_texturePassThruProgram, "u_texture");
m_aPositionTexturePassThru = glGetAttribLocation(m_texturePassThruProgram, "a_position");
fs = STRINGIFY(
precision mediump float;
varying vec2 v_uv;
uniform sampler2D u_texture[4];
void main(void)
{
vec4 color;
for(int i = 0; i < 4; ++i)
color += texture2D(u_texture[i], v_uv);
const float bloomPower = 3.0;
gl_FragColor.r = (color.r + (max(color.g - 1.0, 0.0) + max(color.b - 1.0, 0.0)) * 0.5 * bloomPower) * color.a;
gl_FragColor.g = (color.g + (max(color.r - 1.0, 0.0) + max(color.b - 1.0, 0.0)) * 0.5 * bloomPower) * color.a;
gl_FragColor.b = (color.b + (max(color.r - 1.0, 0.0) + max(color.g - 1.0, 0.0)) * 0.5 * bloomPower) * color.a;
gl_FragColor.a = color.a;
}
);
m_bloomProgram = esLoadProgram(vs, fs);
for(int i = 0; i < 4; ++i)
{
char buffer[] = "u_texture[0]";
sprintf(buffer, "u_texture[%i]", i);
m_uTextureBloom[i] = glGetUniformLocation(m_bloomProgram, buffer);
}
m_aPositionBloom = glGetAttribLocation(m_bloomProgram, "a_position");
//setup the FBO
CreateFBO();
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
}
void Asteroids::Load(Platform::String^ entryPoint)
{
}
void Asteroids::Run()
{
BasicTimer^ timer = ref new BasicTimer();
while (!m_windowClosed)
{
if (m_windowVisible)
{
timer->Update();
CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
Update();
Draw();
//m_renderer->Update(timer->Total, timer->Delta);
//m_renderer->Render();
//m_renderer->Present(); // This call is synchronized to the display frame rate.
}
else
{
CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending);
}
}
}
void Asteroids::Uninitialize()
{
}
void Asteroids::OnWindowSizeChanged(CoreWindow^ sender, WindowSizeChangedEventArgs^ args)
{
//m_renderer->UpdateForWindowSizeChange();
if (sender->Bounds.Width != m_windowBounds.Width ||
sender->Bounds.Height != m_windowBounds.Height ||
m_orientation != DisplayProperties::CurrentOrientation)
{
// Internally calls DX11's version of flush
glFlush();
// Store the window bounds so the next time we get a SizeChanged event we can
// avoid rebuilding everything if the size is identical.
m_windowBounds = sender->Bounds;
// Calculate the necessary swap chain and render target size in pixels.
float windowWidth = ConvertDipsToPixels(m_windowBounds.Width);
float windowHeight = ConvertDipsToPixels(m_windowBounds.Height);
// The width and height of the swap chain must be based on the window's
// landscape-oriented width and height. If the window is in a portrait
// orientation, the dimensions must be reversed.
m_orientation = DisplayProperties::CurrentOrientation;
bool swapDimensions =
m_orientation == DisplayOrientations::Portrait ||
m_orientation == DisplayOrientations::PortraitFlipped;
m_renderTargetSize.Width = swapDimensions ? windowHeight : windowWidth;
m_renderTargetSize.Height = swapDimensions ? windowWidth : windowHeight;
// Actually resize the underlying swapchain
//esResizeWindow(&m_esContext, static_cast<UINT>(m_renderTargetSize.Width), static_cast<UINT>(m_renderTargetSize.Height));
glViewport(0, 0, static_cast<UINT>(m_renderTargetSize.Width), static_cast<UINT>(m_renderTargetSize.Height));
// Recreate the FBO with the new dimensions
glDeleteFramebuffers(8, m_offscreenFBO);
glDeleteTextures(8, m_offscreenTex);
//setup the FBO
CreateFBO();
}
}
void Asteroids::OnVisibilityChanged(CoreWindow^ sender, VisibilityChangedEventArgs^ args)
{
m_windowVisible = args->Visible;
}
void Asteroids::OnWindowClosed(CoreWindow^ sender, CoreWindowEventArgs^ args)
{
m_windowClosed = true;
glDeleteProgram(m_drawProgram);
glDeleteProgram(m_blurProgram);
glDeleteProgram(m_texturePassThruProgram);
glDeleteProgram(m_bloomProgram);
glDeleteTextures(8, m_offscreenTex);
glDeleteFramebuffers(8, m_offscreenFBO);
}
void Asteroids::OnPointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
{
// Insert your code here.
}
void Asteroids::OnPointerMoved(CoreWindow^ sender, PointerEventArgs^ args)
{
// Insert your code here.
}
void Asteroids::OnKeyDown(CoreWindow^ sender, KeyEventArgs ^args)
{
switch(args->VirtualKey)
{
case VirtualKey::W:
case VirtualKey::Up:
m_playerState |= PLAYER_STATE_W;
break;
case VirtualKey::S:
case VirtualKey::Down:
m_playerState |= PLAYER_STATE_S;
break;
case VirtualKey::A:
case VirtualKey::Left:
m_playerState |= PLAYER_STATE_A;
break;
case VirtualKey::D:
case VirtualKey::Right:
m_playerState |= PLAYER_STATE_D;
break;
case VirtualKey::Space:
m_playerState |= PLAYER_STATE_SPACE;
break;
case VirtualKey::Number1:
m_weapon = Weapon::Regular;
break;
case VirtualKey::Number2:
m_weapon = Weapon::Spread;
break;
case VirtualKey::Number3:
m_weapon = Weapon::LaserWeapon;
break;
}
}
void Asteroids::OnKeyUp(CoreWindow^ sender, KeyEventArgs ^args)
{
switch(args->VirtualKey)
{
case VirtualKey::W:
case VirtualKey::Up:
m_playerState &= ~PLAYER_STATE_W;
break;
case VirtualKey::S:
case VirtualKey::Down:
m_playerState &= ~PLAYER_STATE_S;
break;
case VirtualKey::A:
case VirtualKey::Left:
m_playerState &= ~PLAYER_STATE_A;
break;
case VirtualKey::D:
case VirtualKey::Right:
m_playerState &= ~PLAYER_STATE_D;
break;
case VirtualKey::Space:
m_playerState &= ~PLAYER_STATE_SPACE;
break;
}
}
float Asteroids::ConvertDipsToPixels(float dips)
{
static const float dipsPerInch = 96.0f;
return floor(dips * DisplayProperties::LogicalDpi / dipsPerInch + 0.5f); // Round to nearest integer.
}
void Asteroids::OnActivated(CoreApplicationView^ applicationView, IActivatedEventArgs^ args)
{
CoreWindow::GetForCurrentThread()->Activate();
}
void Asteroids::OnSuspending(Platform::Object^ sender, SuspendingEventArgs^ args)
{
// Save app state asynchronously after requesting a deferral. Holding a deferral
// indicates that the application is busy performing suspending operations. Be
// aware that a deferral may not be held indefinitely. After about five seconds,
// the app will be forced to exit.
SuspendingDeferral^ deferral = args->SuspendingOperation->GetDeferral();
create_task([this, deferral]()
{
// Insert your code here.
deferral->Complete();
});
}
void Asteroids::OnResuming(Platform::Object^ sender, Platform::Object^ args)
{
// Restore any data or state that was unloaded on suspend. By default, data
// and state are persisted when resuming from suspend. Note that this event
// does not occur if the app was previously terminated.
}
Asteroids::GameObject::GameObject(void) : m_angle(0), m_omega(0), m_scale(1, 1), m_lives(1), m_lifeTime(0.2f)
{
}
void Asteroids::GameObject::Update(float dt)
{
//do semi-implicit euler
m_vel += m_acc * dt;
m_pos += m_vel * dt;
m_angle += m_omega * dt;
m_lifeTime -= dt;
}
glm::mat4 Asteroids::GameObject::TransformMatrix(void) const
{
return glm::translate(glm::vec3(m_pos, 0)) * glm::rotate(m_angle, glm::vec3(0, 0, 1)) * glm::scale(glm::vec3(m_scale, 0));
}
static float MagnitudeSquared(float x, float y)
{
return x * x + y * y;
}
static float MagnitudeSquared(const glm::vec2 &v)
{
return MagnitudeSquared(v.x, v.y);
}
void Asteroids::Update()
{
const float dt = 1.0f / 60;
//handle input
float radians = glm::radians(m_player.m_angle);
if((m_playerState & PLAYER_STATE_W) && !(m_playerState & PLAYER_STATE_S))
m_player.m_acc = glm::vec2(cos(radians), sin(radians)) * PLAYER_ACCELERATION;
if((m_playerState & PLAYER_STATE_S) && !(m_playerState &PLAYER_STATE_W))
m_player.m_acc = glm::vec2(cos(radians), sin(radians)) * -PLAYER_ACCELERATION;
else if(!(m_playerState & PLAYER_STATE_S) && !(m_playerState &PLAYER_STATE_W))
m_player.m_acc = glm::vec2();
if(m_playerState & PLAYER_STATE_A)
m_player.m_omega = TURN_SPEED;
if(m_playerState & PLAYER_STATE_D)
m_player.m_omega = -TURN_SPEED;
if(!(m_playerState & PLAYER_STATE_A) && !(m_playerState & PLAYER_STATE_D))
m_player.m_omega = 0;
m_regularWeaponTimer -= dt;
m_spreadWeaponTimer -= dt;
m_laserWeaponTimer -= dt;
if(m_playerState & PLAYER_STATE_SPACE)
FireBullet();
//move everything around
m_player.Update(dt);
GameObjectIter end = m_asteroids.end();
for(GameObjectIter it = m_asteroids.begin(); it != end; ++it)
it->Update(dt);
end = m_bullets.end();
for(GameObjectIter it = m_bullets.begin(); it != end; ++it)
it->Update(dt);
end = m_asteroidFallout.end();
for(GameObjectIter it = m_asteroidFallout.begin(); it != end; ++it)
it->Update(dt);
//update the thrust particles
end = m_rocketThrustParticles.end();
for(GameObjectIter it = m_rocketThrustParticles.begin(); it != end;)
{
it->Update(dt);
if(it->m_lifeTime <= 0)
{
it = m_rocketThrustParticles.erase(it);
end = m_rocketThrustParticles.end();
}
else
++it;
}
if(m_rocketThrustParticles.size() < MAX_THRUST_PARTICLES)
{
--m_rocketThrust.m_emissionTimer;
if(m_rocketThrust.m_emissionTimer <= 0)
{
GameObject particle;
particle.m_color = glm::vec4(1, 0.4f, 0, 1);
particle.m_lifeTime = (rand() % 1000) / 3000.0f + 0.1f;
float radians = glm::radians(m_player.m_angle);
glm::vec2 rearEnd = m_player.m_pos - glm::vec2(cos(radians), sin(radians)) * m_player.m_scale.x * 0.5f;
particle.m_pos = rearEnd;
radians = glm::radians(m_player.m_angle + (rand() % 6000) / 200.0f - 15);
float velScale;
if(m_playerState & PLAYER_STATE_W)
velScale = (rand() % 1000) / 50.0f + 200.0f;
else if(m_playerState & PLAYER_STATE_S)
velScale = -((rand() % 1000) / 50.0f + 200.0f);
else
velScale = (rand() % 1000) / 50.0f + 50.0f;
particle.m_vel = m_player.m_vel + -glm::vec2(cos(radians), sin(radians)) * velScale;
particle.m_scale = glm::vec2(5);
particle.m_omega = (rand() % 1000) / 5.0f - 100;
m_rocketThrustParticles.push_back(particle);
if(m_rocketThrustParticles.size() == MAX_THRUST_PARTICLES)
m_rocketThrust.m_emissionTimer = THRUST_OUTPUT_RATE;
}
}
//update the lasers
for(LaserIter it = m_lasers.begin(); it != m_lasers.end();)
{
it->m_lifeTime -= dt;
if(it->m_lifeTime <= 0)
it = m_lasers.erase(it);
else
++it;
}
//wrap player and asteroids to the other side of the universe if out of bounds
WrapAround(m_player);
end = m_asteroids.end();
for(GameObjectIter it = m_asteroids.begin(); it != end; ++it)
WrapAround(*it);
//collide the asteroids and bullets using circles
end = m_bullets.end();
for(GameObjectIter it = m_bullets.begin(); it != end; )
{
GameObjectIter end2 = m_asteroids.end();
for(GameObjectIter it2 = m_asteroids.begin(); it2 != end2;)
{
float radius1 = MagnitudeSquared(it->m_scale * 0.5f);
float radius2 = MagnitudeSquared(it2->m_scale * 0.5f);
float distance = MagnitudeSquared(it->m_pos - it2->m_pos);
//they've collided so delete them
if(radius1 + radius2 > distance)
{
it = m_bullets.erase(it);
end = m_bullets.end();
//split the asteroid into 4 smaller ones
if(it2->m_lives == 2)
{
int position = it2 - m_asteroids.begin();
GameObject asteroid;
float radians = glm::radians(glm::radians(it2->m_angle + 45));
glm::vec2 vel = it2->m_vel;
glm::vec2 pos = it2->m_pos;
glm::vec2 dir1(cos(radians), sin(radians));
glm::vec2 dir2(dir1.y, -dir1.x);
float scale = it2->m_scale.x;
float angle = it2->m_angle;
float omega = it2->m_omega;
asteroid.m_scale.x = asteroid.m_scale.y = scale * 0.5f;
asteroid.m_pos = pos + dir1 * scale * 0.25f;
asteroid.m_angle = angle;
asteroid.m_omega = omega + (rand() % 1000) / 10.0f - 50;
asteroid.m_vel = vel + dir1 * DESTROYED_ASTEROID_SPEED;
m_asteroids.push_back(asteroid);
asteroid.m_pos = pos - dir1 * scale * 0.25f;
asteroid.m_angle = angle;
asteroid.m_omega = omega + (rand() % 1000) / 10.0f - 50;
asteroid.m_vel = vel - dir1 * DESTROYED_ASTEROID_SPEED;
m_asteroids.push_back(asteroid);
asteroid.m_pos = pos + dir2 * scale * 0.25f;
asteroid.m_angle = angle;
asteroid.m_omega = omega + (rand() % 1000) / 10.0f - 50;
asteroid.m_vel = vel + dir2 * DESTROYED_ASTEROID_SPEED;
m_asteroids.push_back(asteroid);
asteroid.m_pos = pos - dir2 * scale * 0.25f;
asteroid.m_angle = angle;
asteroid.m_omega = omega + (rand() % 1000) / 10.0f - 50;
asteroid.m_vel = vel - dir2 * DESTROYED_ASTEROID_SPEED;
m_asteroids.push_back(asteroid);
it2 = m_asteroids.begin() + position;
}
else
{
GameObject fallout;
fallout.m_pos = it2->m_pos;
fallout.m_scale = glm::vec2(5);
for(int i = 0; i < MAX_FALLOUT_PER_ASTEROID; ++i)
{
fallout.m_angle = static_cast<float>(rand() % 10000);
fallout.m_omega = (rand() % 1000) - 500.0f;
float radians = glm::radians(static_cast<float>(rand() % 10000));
fallout.m_vel = it2->m_vel + glm::vec2(cos(radians), sin(radians)) * (rand() % 100 + FALLOUT_INITIAL_VEL);
m_asteroidFallout.push_back(fallout);
}
}
it2 = m_asteroids.erase(it2);
end2 = m_asteroids.end();
if(it == end)
break;
}
else
++it2;
}
if(it != end)
++it;
}
//collide asteroid fallout and asteroids
end = m_asteroidFallout.end();
for(GameObjectIter it = m_asteroidFallout.begin(); it != end; )
{
if(it->m_lifeTime <= 0)
{
it = m_asteroidFallout.erase(it);
end = m_asteroidFallout.end();
continue;
}
GameObjectIter end2 = m_asteroids.end();
for(GameObjectIter it2 = m_asteroids.begin(); it2 != end2;)
{
float radius1 = MagnitudeSquared(it->m_scale * 0.5f);
float radius2 = MagnitudeSquared(it2->m_scale * 0.5f);
float distance = MagnitudeSquared(it->m_pos - it2->m_pos);
//they've collided so delete them
if(radius1 + radius2 > distance)
{
it = m_asteroidFallout.erase(it);
end = m_asteroidFallout.end();
//split the asteroid into 4 smaller ones
if(it2->m_lives == 2)
{
int position = it2 - m_asteroids.begin();
GameObject asteroid;
float radians = glm::radians(glm::radians(it2->m_angle + 45));
glm::vec2 vel = it2->m_vel;
glm::vec2 pos = it2->m_pos;
glm::vec2 dir1(cos(radians), sin(radians));
glm::vec2 dir2(dir1.y, -dir1.x);
float scale = it2->m_scale.x;
float angle = it2->m_angle;
float omega = it2->m_omega;
asteroid.m_scale.x = asteroid.m_scale.y = scale * 0.5f;
asteroid.m_pos = pos + dir1 * scale * 0.25f;
asteroid.m_angle = angle;
asteroid.m_omega = omega + (rand() % 1000) / 10.0f - 50;
asteroid.m_vel = vel + dir1 * DESTROYED_ASTEROID_SPEED;
m_asteroids.push_back(asteroid);
asteroid.m_pos = pos - dir1 * scale * 0.25f;
asteroid.m_angle = angle;
asteroid.m_omega = omega + (rand() % 1000) / 10.0f - 50;
asteroid.m_vel = vel - dir1 * DESTROYED_ASTEROID_SPEED;
m_asteroids.push_back(asteroid);
asteroid.m_pos = pos + dir2 * scale * 0.25f;
asteroid.m_angle = angle;
asteroid.m_omega = omega + (rand() % 1000) / 10.0f - 50;
asteroid.m_vel = vel + dir2 * DESTROYED_ASTEROID_SPEED;
m_asteroids.push_back(asteroid);
asteroid.m_pos = pos - dir2 * scale * 0.25f;
asteroid.m_angle = angle;
asteroid.m_omega = omega + (rand() % 1000) / 10.0f - 50;
asteroid.m_vel = vel - dir2 * DESTROYED_ASTEROID_SPEED;
m_asteroids.push_back(asteroid);
it2 = m_asteroids.begin() + position;
}
else
{
int index = it - m_asteroidFallout.begin();
GameObject fallout;
fallout.m_pos = it2->m_pos;
fallout.m_scale = glm::vec2(5);
for(int i = 0; i < MAX_FALLOUT_PER_ASTEROID; ++i)
{
fallout.m_angle = static_cast<float>(rand() % 10000);
fallout.m_omega = (rand() % 1000) - 500.0f;
float radians = glm::radians(static_cast<float>(rand() % 10000));
fallout.m_vel = it2->m_vel + glm::vec2(cos(radians), sin(radians)) * (rand() % 100 + FALLOUT_INITIAL_VEL);
m_asteroidFallout.push_back(fallout);
}
it = m_asteroidFallout.begin() + index;
end = m_asteroidFallout.end();
}
it2 = m_asteroids.erase(it2);
end2 = m_asteroids.end();
if(it == end)
break;
}
else
++it2;
}
if(it != end)
++it;
}
//collide the asteroids and lasers
for(LaserIter it = m_lasers.begin(); it != m_lasers.end(); ++it)
{
if(!it->m_lethal)
continue;
for(GameObjectIter it2 = m_asteroids.begin(); it2 != m_asteroids.end();)
{
//project asteroid to laser direction
glm::vec2 projectedPos = it->m_pos + glm::dot(it2->m_pos - it->m_pos, it->m_dir) / MagnitudeSquared(it->m_dir) * it->m_dir;
if(it2->m_scale.x > glm::length(it2->m_pos - projectedPos) && glm::dot(projectedPos - it->m_pos, it->m_dir) >= 0)
{
//split the asteroid into 4 smaller ones
if(it2->m_lives == 2)
{
int position = it2 - m_asteroids.begin();
GameObject asteroid;
float radians = glm::radians(glm::radians(it2->m_angle + 45));
glm::vec2 vel = it2->m_vel;
glm::vec2 pos = it2->m_pos;
glm::vec2 dir1(cos(radians), sin(radians));
glm::vec2 dir2(dir1.y, -dir1.x);
float scale = it2->m_scale.x;
float angle = it2->m_angle;
float omega = it2->m_omega;
asteroid.m_scale.x = asteroid.m_scale.y = scale * 0.5f;
asteroid.m_pos = pos + dir1 * scale * 0.25f;
asteroid.m_angle = angle;
asteroid.m_omega = omega + (rand() % 1000) / 10.0f - 50;
asteroid.m_vel = vel + dir1 * DESTROYED_ASTEROID_SPEED;
m_asteroids.push_back(asteroid);
asteroid.m_pos = pos - dir1 * scale * 0.25f;
asteroid.m_angle = angle;
asteroid.m_omega = omega + (rand() % 1000) / 10.0f - 50;
asteroid.m_vel = vel - dir1 * DESTROYED_ASTEROID_SPEED;
m_asteroids.push_back(asteroid);
asteroid.m_pos = pos + dir2 * scale * 0.25f;
asteroid.m_angle = angle;
asteroid.m_omega = omega + (rand() % 1000) / 10.0f - 50;
asteroid.m_vel = vel + dir2 * DESTROYED_ASTEROID_SPEED;
m_asteroids.push_back(asteroid);
asteroid.m_pos = pos - dir2 * scale * 0.25f;
asteroid.m_angle = angle;
asteroid.m_omega = omega + (rand() % 1000) / 10.0f - 50;
asteroid.m_vel = vel - dir2 * DESTROYED_ASTEROID_SPEED;
m_asteroids.push_back(asteroid);
it2 = m_asteroids.begin() + position;
}
else
{
GameObject fallout;
fallout.m_pos = it2->m_pos;
fallout.m_scale = glm::vec2(5);
for(int i = 0; i < MAX_FALLOUT_PER_ASTEROID; ++i)
{
fallout.m_angle = static_cast<float>(rand() % 10000);
fallout.m_omega = (rand() % 1000) - 500.0f;
float radians = glm::radians(static_cast<float>(rand() % 10000));
fallout.m_vel = it2->m_vel + glm::vec2(cos(radians), sin(radians)) * (rand() % 100 + FALLOUT_INITIAL_VEL);
m_asteroidFallout.push_back(fallout);
}
}
it2 = m_asteroids.erase(it2);
}
else
++it2;
}
it->m_lethal = false;
}
//keep the asteroids coming when the universe runs low
if(m_asteroids.size() < MAX_ASTEROIDS)
{
--m_asteroidRespawnTime;
if(m_asteroidRespawnTime <= 0)
{
for(unsigned i = m_asteroids.size(); i < MAX_ASTEROIDS; ++i)
{
GameObject asteroid;
asteroid.m_pos.x = static_cast<float>(rand() % 10000);
asteroid.m_pos.y = static_cast<float>(rand() % 10000);
asteroid.m_angle = (rand() % 1000) / 10.0f - 50;
asteroid.m_omega = (rand() % 1000) / 10.0f - 50;
asteroid.m_vel.x = (rand() % 1000) / 10.0f - 50;
asteroid.m_vel.y = (rand() % 1000) / 10.0f - 50;
asteroid.m_scale = glm::vec2((rand() % 1000) / 20.0f + 50);
asteroid.m_lives = 2;
m_asteroids.push_back(asteroid);
}
m_asteroidRespawnTime = 30;
}
}
}
void Asteroids::Draw()
{
glUseProgram(m_drawProgram);
CoreWindow ^window = CoreWindow::GetForCurrentThread();
float halfWindowWidth = window->Bounds.Width * 0.5f;
float halfWindowHeight = window->Bounds.Height * 0.5f;
glm::mat4 ortho = glm::ortho(-halfWindowWidth, halfWindowWidth, -halfWindowHeight, halfWindowHeight, -1.0f, 1.0f);
glUniformMatrix4fv(m_uMvpDraw, 1, GL_FALSE, &ortho[0][0]);
DrawPlayer();
DrawAsteroids();
DrawBullets();
DrawRocket();
const int stride = sizeof(glm::vec3) + sizeof(glm::vec4);
glEnableVertexAttribArray(m_aPositionDraw);
glEnableVertexAttribArray(m_aColorDraw);
glVertexAttribPointer(m_aPositionDraw, 3, GL_FLOAT, GL_FALSE, stride, &m_vertexBuffer[0]);
glVertexAttribPointer(m_aColorDraw, 4, GL_FLOAT, GL_FALSE, stride, &m_vertexBuffer[3]);
bool swapDimensions =
m_orientation == Windows::Graphics::Display::DisplayOrientations::Portrait ||
m_orientation == Windows::Graphics::Display::DisplayOrientations::PortraitFlipped;
for(int i = 0; i < 4; ++i)
{
if(swapDimensions)
glViewport(0, 0, RENDER_TARGET_HEIGHT >> i, RENDER_TARGET_WIDTH >> i);
else
glViewport(0, 0, RENDER_TARGET_WIDTH >> i, RENDER_TARGET_HEIGHT >> i);
glBindFramebuffer(GL_FRAMEBUFFER, m_offscreenFBO[i]);
glClear(GL_COLOR_BUFFER_BIT);
glDrawArrays(GL_LINES, 0, m_vertexBuffer.size() / 7);
}
m_vertexBuffer.clear();
DrawLasers();
if(m_lasers.size())
{
glVertexAttribPointer(m_aPositionDraw, 3, GL_FLOAT, GL_FALSE, stride, &m_vertexBuffer[0]);
glVertexAttribPointer(m_aColorDraw, 4, GL_FLOAT, GL_FALSE, stride, &m_vertexBuffer[3]);
for(int i = 0; i < 4; ++i)
{
if(swapDimensions)
glViewport(0, 0, RENDER_TARGET_HEIGHT >> i, RENDER_TARGET_WIDTH >> i);
else
glViewport(0, 0, RENDER_TARGET_WIDTH >> i, RENDER_TARGET_HEIGHT >> i);
glBindFramebuffer(GL_FRAMEBUFFER, m_offscreenFBO[i]);
glDrawArrays(GL_TRIANGLES, 0, m_vertexBuffer.size() / 7);
}
}
m_vertexBuffer.clear();
glDisableVertexAttribArray(m_aPositionDraw);
glDisableVertexAttribArray(m_aColorDraw);
float fullScreen[] = {
-1, 1,
-1, -1,
1, 1,
1, -1
};
glDisable(GL_BLEND);
glUseProgram(m_blurProgram);
glActiveTexture(GL_TEXTURE0);
glUniform1i(m_uTextureBlur, 0);
glEnableVertexAttribArray(m_aPositionBlur);
glVertexAttribPointer(m_aPositionBlur, 2, GL_FLOAT, GL_FALSE, sizeof(glm::vec2), fullScreen);
for(int i = 0; i < 4; ++i)
{
int width = (swapDimensions) ? RENDER_TARGET_HEIGHT >> i : RENDER_TARGET_WIDTH >> i;
int height = (swapDimensions) ? RENDER_TARGET_WIDTH >> i : RENDER_TARGET_HEIGHT >> i;
glViewport(0, 0, width, height);
glBindFramebuffer(GL_FRAMEBUFFER, m_offscreenFBO[i + 4]);
glBindTexture(GL_TEXTURE_2D, m_offscreenTex[i]);
glm::vec2 horiOffset(1.0f / width, 0.0f);
glUniform2f(m_uOffsetBlur, horiOffset.x, horiOffset.y);
glClear(GL_COLOR_BUFFER_BIT);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
glBindFramebuffer(GL_FRAMEBUFFER, m_offscreenFBO[i]);
glBindTexture(GL_TEXTURE_2D, m_offscreenTex[i + 4]);
glm::vec2 vertOffset = glm::vec2(0.0f, 1.0f / height);
glUniform2f(m_uOffsetBlur, vertOffset.x, vertOffset.y);
glClear(GL_COLOR_BUFFER_BIT);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
}
glDisableVertexAttribArray(m_aPositionBlur);
glEnable(GL_BLEND);
glViewport(0, 0, static_cast<int>(ConvertDipsToPixels(window->Bounds.Width)), static_cast<int>(ConvertDipsToPixels(window->Bounds.Height)));
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(m_bloomProgram);
for(int i = 0; i < 4; ++i)
{
glActiveTexture(GL_TEXTURE0 + i);
glBindTexture(GL_TEXTURE_2D, m_offscreenTex[i]);
glUniform1i(m_uTextureBloom[i], i);
}
glUniform1i(m_uTextureTexturePassThru, 0);
glEnableVertexAttribArray(m_aPositionBloom);
glVertexAttribPointer(m_aPositionBloom, 2, GL_FLOAT, GL_FALSE, sizeof(glm::vec2), fullScreen);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
glDisableVertexAttribArray(m_aPositionBloom);
eglSwapBuffers(m_esContext.eglDisplay, m_esContext.eglSurface);
}
void Asteroids::WrapAround(GameObject &object)
{
CoreWindow ^window = CoreWindow::GetForCurrentThread();
float halfWindowWidth = window->Bounds.Width * 0.5f;
float halfWindowHeight = window->Bounds.Height * 0.5f;
if(object.m_pos.x - object.m_scale.x > halfWindowWidth)
object.m_pos.x = -halfWindowWidth - object.m_scale.x * 0.5f;
if(object.m_pos.x + object.m_scale.x < -halfWindowWidth)
object.m_pos.x = halfWindowWidth + object.m_scale.x * 0.5f;
if(object.m_pos.y - object.m_scale.y > halfWindowHeight)
object.m_pos.y = -halfWindowHeight - object.m_scale.y * 0.5f;
if(object.m_pos.y + object.m_scale.y < -halfWindowHeight)
object.m_pos.y = halfWindowHeight + object.m_scale.y * 0.5f;
}
void Asteroids::FireBullet()
{
if(m_weapon == Weapon::Regular)
{
if(m_regularWeaponTimer <= 0)
{
GameObject bullet;
float radians = glm::radians(m_player.m_angle);
glm::vec2 dir(cos(radians), sin(radians));
bullet.m_pos = m_player.m_pos + dir * m_player.m_scale.x * 0.5f;
bullet.m_scale = glm::vec2(10, 10);
bullet.m_angle = m_player.m_angle;
bullet.m_vel = dir * BULLET_SPEED + m_player.m_vel;
m_bullets.push_back(bullet);
m_regularWeaponTimer = REGULAR_WEAPON_COOLDOWN;
}
}
else if(m_weapon == Weapon::Spread)
{
if(m_spreadWeaponTimer <= 0)
{
GameObject bullet;
bullet.m_scale = glm::vec2(10, 10);
bullet.m_angle = m_player.m_angle;
for(int i = -2; i <= 2; ++i)
{
float radians = glm::radians(m_player.m_angle + i * 10);
glm::vec2 dir(cos(radians), sin(radians));
bullet.m_vel = dir * BULLET_SPEED + m_player.m_vel;
bullet.m_pos = m_player.m_pos + dir * m_player.m_scale.x * 0.5f;
m_bullets.push_back(bullet);
}
m_spreadWeaponTimer = SPREAD_WEAPON_COOLDOWN;
}
}
else if(m_weapon == Weapon::LaserWeapon)
{
if(m_laserWeaponTimer <= 0)
{
Laser laser;
laser.m_lifeTime = 2;
float radians = glm::radians(m_player.m_angle);
laser.m_dir = glm::vec2(cos(radians), sin(radians));
laser.m_pos = m_player.m_pos + laser.m_dir * m_player.m_scale * 0.5f;
laser.m_lethal = true;
m_lasers.push_back(laser);
m_laserWeaponTimer = LASER_WEAPON_COOLDOWN;
}
}
}
void Asteroids::RemoveOutOfBoundsBullets()
{
CoreWindow ^window = CoreWindow::GetForCurrentThread();
float halfWindowWidth = window->Bounds.Width * 0.5f;
float halfWindowHeight = window->Bounds.Height * 0.5f;
GameObjectIter end = m_bullets.end();
for(GameObjectIter it = m_bullets.begin(); it != end;)
{
if(it->m_pos.x - it->m_scale.x > halfWindowWidth || it->m_pos.x + it->m_scale.x < halfWindowWidth ||
it->m_pos.y - it->m_scale.y > halfWindowHeight || it->m_pos.y + it->m_scale.y < halfWindowHeight)
it = m_bullets.erase(it);
else
++it;
}
}
static void FillVertexBuffer(std::vector<float> &buffer, const glm::vec3 &position, const glm::vec4 &color)
{
buffer.insert(buffer.end(), &position.x, &position.x + 3);
buffer.insert(buffer.end(), &color.x, &color.x + 4);
}
void Asteroids::DrawPlayer(void)
{
glm::mat4 transform = m_player.TransformMatrix();
glm::vec4 verts[] = {
glm::vec4(0.5f, 0, 0, 1),
glm::vec4(-0.5f, 0.3f, 0, 1),
glm::vec4(-0.5f, 0.3f, 0, 1),
glm::vec4(-0.2f, 0, 0, 1),
glm::vec4(-0.2f, 0, 0, 1),
glm::vec4(-0.5f, -0.3f, 0, 1),
glm::vec4(-0.5f, -0.3f, 0, 1),
glm::vec4(0.5f, 0, 0, 1),
};
for(int i = 0; i < sizeof(verts) / sizeof(*verts); ++i)
FillVertexBuffer(m_vertexBuffer, glm::vec3(transform * verts[i]), glm::vec4(0, 1, 0, 1));
}
void Asteroids::DrawAsteroids(void)
{
glm::vec4 verts[] = {
glm::vec4(0.5f, 0.5f, 0, 1),
glm::vec4(-0.5f, 0.5f, 0, 1),
glm::vec4(-0.5f, 0.5f, 0, 1),
glm::vec4(-0.5f, -0.5f, 0, 1),
glm::vec4(-0.5f, -0.5f, 0, 1),
glm::vec4(0.5f, -0.5f, 0, 1),
glm::vec4(0.5f, -0.5f, 0, 1),
glm::vec4(0.5f, 0.5f, 0, 1),
};
GameObjectIter end = m_asteroids.end();
for(GameObjectIter it = m_asteroids.begin(); it != end; ++it)
{
glm::mat4 transform = it->TransformMatrix();
for(int i = 0; i < sizeof(verts) / sizeof(*verts); ++i)
FillVertexBuffer(m_vertexBuffer, glm::vec3(transform * verts[i]), glm::vec4(1, 0, 0, 1));
}
end = m_asteroidFallout.end();
for(GameObjectIter it = m_asteroidFallout.begin(); it != end; ++it)
{
glm::mat4 transform = it->TransformMatrix();
for(int i = 0; i < sizeof(verts) / sizeof(*verts); ++i)
FillVertexBuffer(m_vertexBuffer, glm::vec3(transform * verts[i]), glm::vec4(1, 0.7f, 0, 1));
}
}
void Asteroids::DrawBullets(void)
{
glm::vec4 verts[] = {
glm::vec4(0.5f, 0, 0, 1),
glm::vec4(-0.5f, 0.5f, 0, 1),
glm::vec4(-0.5f, 0.5f, 0, 1),
glm::vec4(-0.5f, -0.5f, 0, 1),
glm::vec4(-0.5f, -0.5f, 0, 1),
glm::vec4(0.5f, 0, 0, 1),
};
GameObjectIter end = m_bullets.end();
for(GameObjectIter it = m_bullets.begin(); it != end; ++it)
{
glm::mat4 transform = it->TransformMatrix();
for(int i = 0; i < sizeof(verts) / sizeof(*verts); ++i)
FillVertexBuffer(m_vertexBuffer, glm::vec3(transform * verts[i]), glm::vec4(0, 0.5f, 1, 1));
}
}
void Asteroids::DrawRocket(void)
{
glm::vec4 verts[] = {
glm::vec4(0.5f, 0, 0, 1),
glm::vec4(-0.5f, 0.5f, 0, 1),
glm::vec4(-0.5f, 0.5f, 0, 1),
glm::vec4(-0.5f, -0.5f, 0, 1),
glm::vec4(-0.5f, -0.5f, 0, 1),
glm::vec4(0.5f, 0, 0, 1),
};
GameObjectIter end = m_rocketThrustParticles.end();
for(GameObjectIter it = m_rocketThrustParticles.begin(); it != end; ++it)
{
glm::mat4 transform = it->TransformMatrix();
for(int i = 0; i < sizeof(verts) / sizeof(*verts); ++i)
FillVertexBuffer(m_vertexBuffer, glm::vec3(transform * verts[i]), it->m_color);
}
}
void Asteroids::DrawLasers(void)
{
for(LaserIter it = m_lasers.begin(); it != m_lasers.end(); ++it)
{
glm::vec2 dir2(it->m_dir.y, -it->m_dir.x);
glm::vec2 lowerRight(it->m_pos + dir2 * 10.0f);
glm::vec2 upperRight(it->m_pos - dir2 * 10.0f);
glm::vec2 lowerLeft(lowerRight + it->m_dir * 100000.0f);
glm::vec2 upperLeft(upperRight + it->m_dir * 100000.0f);
float alpha = 1;
if(it->m_lifeTime < 1)
alpha = it->m_lifeTime;
FillVertexBuffer(m_vertexBuffer, glm::vec3(lowerRight, 0), glm::vec4(0, 1, 1, alpha));
FillVertexBuffer(m_vertexBuffer, glm::vec3(upperRight, 0), glm::vec4(0, 1, 1, alpha));
FillVertexBuffer(m_vertexBuffer, glm::vec3(lowerLeft, 0), glm::vec4(0, 1, 1, alpha));
FillVertexBuffer(m_vertexBuffer, glm::vec3(upperRight, 0), glm::vec4(0, 1, 1, alpha));
FillVertexBuffer(m_vertexBuffer, glm::vec3(upperLeft, 0), glm::vec4(0, 1, 1, alpha));
FillVertexBuffer(m_vertexBuffer, glm::vec3(lowerLeft, 0), glm::vec4(0, 1, 1, alpha));
}
}
void Asteroids::CreateFBO(void)
{
bool swapDimensions =
m_orientation == DisplayOrientations::Portrait ||
m_orientation == DisplayOrientations::PortraitFlipped;
glGenFramebuffers(8, m_offscreenFBO);
glGenTextures(8, m_offscreenTex);
for(int i = 0; i < 4; ++i)
{
int width = (swapDimensions) ? RENDER_TARGET_HEIGHT >> i : RENDER_TARGET_WIDTH >> i;
int height = (swapDimensions) ? RENDER_TARGET_WIDTH >> i : RENDER_TARGET_HEIGHT >> i;
glBindFramebuffer(GL_FRAMEBUFFER, m_offscreenFBO[i]);
glBindTexture(GL_TEXTURE_2D, m_offscreenTex[i]);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_offscreenTex[i], 0);
if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
throw FBOIncompleteException();
glBindFramebuffer(GL_FRAMEBUFFER, m_offscreenFBO[i + 4]);
glBindTexture(GL_TEXTURE_2D, m_offscreenTex[i + 4]);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_offscreenTex[i + 4], 0);
if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
throw FBOIncompleteException();
}
glBindTexture(GL_TEXTURE_2D, 0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
IFrameworkView^ Direct3DApplicationSource::CreateView()
{
return ref new Asteroids();
}
[Platform::MTAThread]
int main(Platform::Array<Platform::String^>^)
{
auto direct3DApplicationSource = ref new Direct3DApplicationSource();
CoreApplication::Run(direct3DApplicationSource);
return 0;
}
| 44,406 | 16,551 |
/*=========================================================================
medInria
Copyright (c) INRIA 2013. All rights reserved.
See LICENSE.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
=========================================================================*/
#include "v3dViewFiberInteractor.h"
#include <dtkCore/dtkAbstractData.h>
#include <dtkCore/dtkAbstractDataFactory.h>
#include <dtkCore/dtkAbstractView.h>
#include <dtkCore/dtkAbstractViewFactory.h>
#include <medMessageController.h>
#include <vtkSmartPointer.h>
#include <vtkPolyData.h>
#include <vtkFiberDataSetManager.h>
#include <vtkImageView.h>
#include <vtkImageView2D.h>
#include <vtkImageView3D.h>
#include <vtkLimitFibersToVOI.h>
#include <vtkPointData.h>
#include <vtkLookupTableManager.h>
#include <vtkFiberDataSet.h>
#include <vtkMatrix4x4.h>
#include <vtkLimitFibersToROI.h>
#include <vtkIsosurfaceManager.h>
#include <itkImage.h>
#include <itkImageToVTKImageFilter.h>
#include <itkFiberBundleStatisticsCalculator.h>
#include "v3dView.h"
#include "medVtkView.h"
#include <QInputDialog>
#include <QColorDialog>
class v3dViewFiberInteractorPrivate
{
public:
dtkAbstractData *data;
v3dView *view;
dtkAbstractData *projectionData;
vtkFiberDataSetManager *manager;
vtkIsosurfaceManager *roiManager;
vtkSmartPointer<vtkFiberDataSet> dataset;
QMap<QString, double> meanFAList;
QMap<QString, double> minFAList;
QMap<QString, double> maxFAList;
QMap<QString, double> varFAList;
QMap<QString, double> meanADCList;
QMap<QString, double> minADCList;
QMap<QString, double> maxADCList;
QMap<QString, double> varADCList;
QMap<QString, double> meanLengthList;
QMap<QString, double> minLengthList;
QMap<QString, double> maxLengthList;
QMap<QString, double> varLengthList;
};
v3dViewFiberInteractor::v3dViewFiberInteractor(): medAbstractVtkViewInteractor(), d(new v3dViewFiberInteractorPrivate)
{
d->data = 0;
d->dataset = 0;
d->view = 0;
d->manager = vtkFiberDataSetManager::New();
d->manager->SetHelpMessageVisibility(0);
d->roiManager = vtkIsosurfaceManager::New();
// d->manager->SetBoxWidget (0);
vtkLookupTable* lut = vtkLookupTableManager::GetSpectrumLookupTable();
d->manager->SetLookupTable(lut);
lut->Delete();
}
v3dViewFiberInteractor::~v3dViewFiberInteractor()
{
this->disable();
d->manager->Delete();
d->roiManager->Delete();
delete d;
d = 0;
}
QString v3dViewFiberInteractor::description() const
{
return tr("Interactor to help visualising Fibers");
}
QString v3dViewFiberInteractor::identifier() const
{
return "v3dViewFiberInteractor";
}
QStringList v3dViewFiberInteractor::handled() const
{
return QStringList () << v3dView::s_identifier() << medVtkView::s_identifier();
}
bool v3dViewFiberInteractor::isDataTypeHandled(QString dataType) const
{
if (dataType == "v3dDataFibers")
return true;
return false;
}
bool v3dViewFiberInteractor::registered()
{
return dtkAbstractViewFactory::instance()->registerViewInteractorType("v3dViewFiberInteractor",
QStringList () << v3dView::s_identifier() << medVtkView::s_identifier(),
createV3dViewFiberInteractor);
}
void v3dViewFiberInteractor::setData(dtkAbstractData *data)
{
if (!data)
return;
if (data->identifier()=="v3dDataFibers") {
if (vtkFiberDataSet *dataset = static_cast<vtkFiberDataSet *>(data->data())) {
d->dataset = dataset;
d->manager->SetInput (d->dataset);
if (!data->hasMetaData("BundleList"))
data->addMetaData("BundleList", QStringList());
if (!data->hasMetaData("BundleColorList"))
data->addMetaData("BundleColorList", QStringList());
// add bundles to 2d
vtkFiberDataSet::vtkFiberBundleListType bundles = d->dataset->GetBundleList();
vtkFiberDataSet::vtkFiberBundleListType::iterator it = bundles.begin();
while (it!=bundles.end())
{
if (d->view)
d->view->renderer2d()->AddActor(
d->manager->GetBundleActor ((*it).first ));
++it;
}
this->clearStatistics();
d->data = data;
}
}
}
dtkAbstractData *v3dViewFiberInteractor::data()
{
return d->data;
}
void v3dViewFiberInteractor::setView(dtkAbstractView *view)
{
if (v3dView *v3dview = qobject_cast<v3dView*>(view) ) {
d->view = v3dview;
d->manager->SetRenderer( d->view->renderer3d() );
d->manager->SetRenderWindowInteractor( d->view->interactor() );
d->view->renderer2d()->AddActor( d->manager->GetOutput() );
d->roiManager->SetRenderWindowInteractor( d->view->interactor() );
}
}
dtkAbstractView *v3dViewFiberInteractor::view()
{
return d->view;
}
void v3dViewFiberInteractor::enable()
{
if (this->enabled())
return;
if (d->view) {
d->manager->Enable();
d->roiManager->Enable();
if (d->dataset) {
vtkFiberDataSet::vtkFiberBundleListType bundles = d->dataset->GetBundleList();
vtkFiberDataSet::vtkFiberBundleListType::iterator it = bundles.begin();
while (it!=bundles.end())
{
if (d->view)
d->view->renderer2d()->AddActor(
d->manager->GetBundleActor ((*it).first ));
++it;
}
}
}
dtkAbstractViewInteractor::enable();
}
void v3dViewFiberInteractor::disable()
{
if (!this->enabled())
return;
if (d->view) {
d->manager->Disable();
d->roiManager->Disable();
if (d->dataset) {
vtkFiberDataSet::vtkFiberBundleListType bundles = d->dataset->GetBundleList();
vtkFiberDataSet::vtkFiberBundleListType::iterator it = bundles.begin();
while (it!=bundles.end())
{
if (d->view)
d->view->renderer2d()->RemoveActor(
d->manager->GetBundleActor ((*it).first ));
++it;
}
}
}
dtkAbstractViewInteractor::disable();
}
void v3dViewFiberInteractor::setVisibility(bool visible)
{
d->manager->SetVisibility(visible);
}
void v3dViewFiberInteractor::setBoxVisibility(bool visible)
{
if (d->view && d->view->property("Orientation") != "3D") {
medMessageController::instance()->showError("View must be in 3D mode to activate the bundling box",
3000);
d->manager->SetBoxWidget(false);
return;
}
d->manager->SetBoxWidget(visible);
d->view->update();
}
void v3dViewFiberInteractor::setRenderingMode(RenderingMode mode)
{
switch(mode)
{
case v3dViewFiberInteractor::Lines:
d->manager->SetRenderingModeToPolyLines();
break;
case v3dViewFiberInteractor::Ribbons:
d->manager->SetRenderingModeToRibbons();
break;
case v3dViewFiberInteractor::Tubes:
d->manager->SetRenderingModeToTubes();
break;
default:
qDebug() << "v3dViewFiberInteractor: unknown rendering mode";
}
d->view->update();
}
void v3dViewFiberInteractor::activateGPU(bool activate)
{
if (activate) {
vtkFibersManager::UseHardwareShadersOn();
d->manager->ChangeMapperToUseHardwareShaders();
} else {
vtkFibersManager::UseHardwareShadersOff();
d->manager->ChangeMapperToDefault();
}
d->view->update();
}
void v3dViewFiberInteractor::setColorMode(ColorMode mode)
{
switch(mode)
{
case v3dViewFiberInteractor::Local:
d->manager->SetColorModeToLocalFiberOrientation();
break;
case v3dViewFiberInteractor::Global:
d->manager->SetColorModelToGlobalFiberOrientation();
break;
case v3dViewFiberInteractor::FA:
d->manager->SetColorModeToLocalFiberOrientation();
for (int i=0; i<d->manager->GetNumberOfPointArrays(); i++) {
if (d->manager->GetPointArrayName (i)) {
if (strcmp ( d->manager->GetPointArrayName (i), "FA")==0)
{
d->manager->SetColorModeToPointArray (i);
break;
}
}
}
break;
default:
qDebug() << "v3dViewFiberInteractor: unknown color mode";
}
d->view->update();
}
void v3dViewFiberInteractor::setBoxBooleanOperation(BooleanOperation op)
{
switch(op)
{
case v3dViewFiberInteractor::Plus:
d->manager->GetVOILimiter()->SetBooleanOperationToAND();
break;
case v3dViewFiberInteractor::Minus:
d->manager->GetVOILimiter()->SetBooleanOperationToNOT();
break;
default:
qDebug() << "v3dViewFiberInteractor: Unknown boolean operations";
}
d->manager->GetVOILimiter()->Modified();
d->view->update();
}
void v3dViewFiberInteractor::tagSelection()
{
d->manager->SwapInputOutput();
d->view->update();
}
void v3dViewFiberInteractor::resetSelection()
{
d->manager->Reset();
d->view->update();
}
void v3dViewFiberInteractor::validateSelection(const QString &name, const QColor &color)
{
if (!d->data)
return;
double color_d[3] = {(double)color.red()/255.0, (double)color.green()/255.0, (double)color.blue()/255.0};
d->manager->Validate (name.toAscii().constData(), color_d);
d->view->renderer2d()->AddActor (d->manager->GetBundleActor(name.toAscii().constData()));
d->data->addMetaData("BundleList", name);
d->data->addMetaData("BundleColorList", color.name());
// reset to initial navigation state
d->manager->Reset();
d->view->update();
}
void v3dViewFiberInteractor::computeBundleFAStatistics (const QString &name,
double &mean,
double &min,
double &max,
double &var)
{
itk::FiberBundleStatisticsCalculator::Pointer statCalculator = itk::FiberBundleStatisticsCalculator::New();
statCalculator->SetInput (d->dataset->GetBundle (name.toAscii().constData()).Bundle);
try
{
statCalculator->Compute();
}
catch(itk::ExceptionObject &e)
{
qDebug() << e.GetDescription();
mean = 0.0;
min = 0.0;
max = 0.0;
var = 0.0;
return;
}
statCalculator->GetFAStatistics(mean, min, max, var);
}
void v3dViewFiberInteractor::bundleFAStatistics(const QString &name,
double &mean,
double &min,
double &max,
double &var)
{
if (!d->meanFAList.contains(name)) {
this->computeBundleFAStatistics(name, mean, min, max, var);
d->meanFAList[name] = mean;
d->minFAList[name] = min;
d->maxFAList[name] = max;
d->varFAList[name] = var;
}
else {
mean = d->meanFAList[name];
min = d->minFAList[name];
max = d->maxFAList[name];
var = d->varFAList[name];
}
}
void v3dViewFiberInteractor::computeBundleADCStatistics (const QString &name,
double &mean,
double &min,
double &max,
double &var)
{
itk::FiberBundleStatisticsCalculator::Pointer statCalculator = itk::FiberBundleStatisticsCalculator::New();
statCalculator->SetInput (d->dataset->GetBundle (name.toAscii().constData()).Bundle);
try
{
statCalculator->Compute();
}
catch(itk::ExceptionObject &e)
{
qDebug() << e.GetDescription();
mean = 0.0;
min = 0.0;
max = 0.0;
var = 0.0;
return;
}
statCalculator->GetADCStatistics(mean, min, max, var);
}
void v3dViewFiberInteractor::bundleADCStatistics(const QString &name,
double &mean,
double &min,
double &max,
double &var)
{
if (!d->meanADCList.contains(name)) {
this->computeBundleADCStatistics(name, mean, min, max, var);
d->meanADCList[name] = mean;
d->minADCList[name] = min;
d->maxADCList[name] = max;
d->varADCList[name] = var;
}
else {
mean = d->meanADCList[name];
min = d->minADCList[name];
max = d->maxADCList[name];
var = d->varADCList[name];
}
}
void v3dViewFiberInteractor::computeBundleLengthStatistics (const QString &name,
double &mean,
double &min,
double &max,
double &var)
{
itk::FiberBundleStatisticsCalculator::Pointer statCalculator = itk::FiberBundleStatisticsCalculator::New();
statCalculator->SetInput (d->dataset->GetBundle (name.toAscii().constData()).Bundle);
try
{
statCalculator->Compute();
}
catch(itk::ExceptionObject &e)
{
qDebug() << e.GetDescription();
mean = 0.0;
min = 0.0;
max = 0.0;
var = 0.0;
return;
}
statCalculator->GetLengthStatistics(mean, min, max, var);
}
void v3dViewFiberInteractor::bundleLengthStatistics(const QString &name,
double &mean,
double &min,
double &max,
double &var)
{
if (!d->meanLengthList.contains(name)) {
this->computeBundleLengthStatistics(name, mean, min, max, var);
d->meanLengthList[name] = mean;
d->minLengthList[name] = min;
d->maxLengthList[name] = max;
d->varLengthList[name] = var;
}
else {
mean = d->meanLengthList[name];
min = d->minLengthList[name];
max = d->maxLengthList[name];
var = d->varLengthList[name];
}
}
void v3dViewFiberInteractor::clearStatistics(void)
{
d->meanFAList.clear();
d->minFAList.clear();
d->maxFAList.clear();
d->varFAList.clear();
d->meanADCList.clear();
d->minADCList.clear();
d->maxADCList.clear();
d->varADCList.clear();
d->meanLengthList.clear();
d->minLengthList.clear();
d->maxLengthList.clear();
d->varLengthList.clear();
}
void v3dViewFiberInteractor::setProjection(const QString& value)
{
if (!d->view)
return;
if (value=="true") {
d->view->view2d()->AddDataSet( d->manager->GetCallbackOutput() );
}
}
void v3dViewFiberInteractor::setRadius (int value)
{
d->manager->SetRadius (value);
if (d->view)
d->view->update();
}
void v3dViewFiberInteractor::setROI(dtkAbstractData *data)
{
if (!data)
return;
if (data->identifier()!="itkDataImageUChar3")
return;
typedef itk::Image<unsigned char, 3> ROIType;
ROIType::Pointer roiImage = static_cast<ROIType*>(data->data());
if (!roiImage.IsNull()) {
itk::ImageToVTKImageFilter<ROIType>::Pointer converter = itk::ImageToVTKImageFilter<ROIType>::New();
converter->SetReferenceCount(2);
converter->SetInput(roiImage);
converter->Update();
ROIType::DirectionType directions = roiImage->GetDirection();
vtkMatrix4x4 *matrix = vtkMatrix4x4::New();
matrix->Identity();
for (int i=0; i<3; i++)
for (int j=0; j<3; j++)
matrix->SetElement (i, j, directions (i,j));
d->manager->Reset();
d->manager->GetROILimiter()->SetMaskImage (converter->GetOutput());
d->manager->GetROILimiter()->SetDirectionMatrix (matrix);
ROIType::PointType origin = roiImage->GetOrigin();
vtkMatrix4x4 *matrix2 = vtkMatrix4x4::New();
matrix2->Identity();
for (int i=0; i<3; i++)
for (int j=0; j<3; j++)
matrix2->SetElement (i, j, directions (i,j));
double v_origin[4], v_origin2[4];
for (int i=0; i<3; i++)
v_origin[i] = origin[i];
v_origin[3] = 1.0;
matrix->MultiplyPoint (v_origin, v_origin2);
for (int i=0; i<3; i++)
matrix2->SetElement (i, 3, v_origin[i]-v_origin2[i]);
d->roiManager->SetInput (converter->GetOutput());
d->roiManager->SetDirectionMatrix (matrix2);
// d->manager->GetROILimiter()->Update();
d->roiManager->GenerateData();
matrix->Delete();
matrix2->Delete();
}
else {
d->manager->GetROILimiter()->SetMaskImage (0);
d->manager->GetROILimiter()->SetDirectionMatrix (0);
d->roiManager->ResetData();
}
d->view->update();
}
void v3dViewFiberInteractor::setRoiBoolean(int roi, int meaning)
{
d->manager->GetROILimiter()->SetBooleanOperation (roi, meaning);
d->view->update();
}
int v3dViewFiberInteractor::roiBoolean(int roi)
{
return d->manager->GetROILimiter()->GetBooleanOperationVector()[roi+1];
}
void v3dViewFiberInteractor::setBundleVisibility(const QString &name, bool visibility)
{
d->manager->SetBundleVisibility(name.toAscii().constData(), (int)visibility);
d->view->update();
}
bool v3dViewFiberInteractor::bundleVisibility(const QString &name) const
{
return d->manager->GetBundleVisibility(name.toAscii().constData());
}
void v3dViewFiberInteractor::setAllBundlesVisibility(bool visibility)
{
if (visibility)
d->manager->ShowAllBundles();
else
d->manager->HideAllBundles();
d->view->update();
}
void v3dViewFiberInteractor::setOpacity(dtkAbstractData * /*data*/, double /*opacity*/)
{
}
double v3dViewFiberInteractor::opacity(dtkAbstractData * /*data*/) const
{
//TODO
return 100;
}
void v3dViewFiberInteractor::setVisible(dtkAbstractData * /*data*/, bool /*visible*/)
{
//TODO
}
bool v3dViewFiberInteractor::isVisible(dtkAbstractData * /*data*/) const
{
//TODO
return true;
}
// /////////////////////////////////////////////////////////////////
// Type instantiation
// /////////////////////////////////////////////////////////////////
dtkAbstractViewInteractor *createV3dViewFiberInteractor()
{
return new v3dViewFiberInteractor;
}
| 19,392 | 6,076 |
/*******************************************************************************
** Toolbox-base **
** MIT License **
** Copyright (c) [2018] [Florian Lance] **
** **
** 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 "assimp_loader.hpp"
// std
#include <filesystem>
#include <algorithm>
// assimp
#include <assimp/Importer.hpp>
#include <assimp/postprocess.h>
using namespace tool::geo;
using namespace tool::files;
//Texture2D *AiLoader::read_texture(Model *model, aiMaterial *mat, aiTextureType type, unsigned int index){
// // ai data
// aiString path; // receives the path to the texture. If the texture is embedded, receives a '*' followed by the id of the texture
// // (for the textures stored in the corresponding scene) which can be converted to an int using a function like atoi. NULL is a valid value
// aiTextureMapping mapping; // texture mapping, NULL is allowed as value
// unsigned int uvIndex; // uv index of the texture (NULL is valid value)
// ai_real blend; // blend factor for the texture
// aiTextureOp operation; // texture operation to be performed between this texture and the previous texture
// aiTextureMapMode mapMode[3];// mapping modes to be used for the texture, the parameter may be NULL but if it is a valid pointer it MUST
// // point to an array of 3 aiTextureMapMode's (one for each axis: UVW order (=XYZ)).
// mat->GetTexture(type, index, &path, &mapping, &uvIndex, &blend, &operation, &mapMode[0]);
// // auto wrapping = read_texture_property<int>(MatP::text_mapping, aiMat, texturesPerType.first, ii).value();
// // auto uvwSource = read_texture_property<int>(MatP::text_uvw_source, aiMat, texturesPerType.first, ii).value();
// // auto mappingModeU = read_texture_property<int>(MatP::text_mapping_mode_u, aiMat, texturesPerType.first, ii).value();
// // auto mappingModeV = read_texture_property<int>(MatP::text_mapping_mode_v, aiMat, texturesPerType.first, ii).value();
// // auto flags = read_texture_property<int>(MatP::text_flags, aiMat, texturesPerType.first, ii).value();
// // auto texmapAxis = read_texture_property<aiVector3D>(MatP::text_texmap_axis, aiMat, texturesPerType.first, ii).value();
// // auto blend = read_texture_property<float>(MatP::text_blend, aiMat, texturesPerType.first, ii).value();
// // find texture
// namespace fs = std::filesystem;
// const std::string aiPath = path.C_Str();
// if(aiPath.length() > 0){
// if(aiPath[0] == '*'){
// std::cout << "[ASSIMP_LOADER] Embedded texture detected, not managed yet\n";
// return nullptr;
// }
// }
// fs::path texturePath = aiPath;
// if(!fs::exists(texturePath)){ // check if full path exist
// fs::path dirPath = model->directory;
// std_v1<fs::path> pathsToTest;
// pathsToTest.emplace_back(dirPath / texturePath.filename());
// pathsToTest.emplace_back(dirPath / "texture" / texturePath.filename());
// pathsToTest.emplace_back(dirPath / "textures" / texturePath.filename());
// pathsToTest.emplace_back(dirPath / ".." / "texture" / texturePath.filename());
// pathsToTest.emplace_back(dirPath / ".." / "textures" / texturePath.filename());
// bool found = false;
// for(const auto &pathToTest : pathsToTest){
// if(fs::exists(pathToTest)){
// found = true;
// texturePath = pathToTest;
// break;
// }
// }
// if(!found){
// std::cerr << "[ASSIMP_LOADER] Cannot find texture " << texturePath.filename() << "\n";
// return nullptr;
// }
// }
// std::string foundPath = texturePath.u8string();
// auto textures = &model->m_textures;
// if(textures->count(foundPath) == 0){
// // load texture
// Texture2D texture(foundPath);
// // type
// texture.type = get_texture_type(type);
// // mapping
// texture.mapping = get_texture_mapping(mapping);
// // operation
// texture.operation = get_texture_operation(operation);
// // mapMode
// texture.mapMode = Pt3<TexMapMode>{get_texture_map_mode(mapMode[0]),get_texture_map_mode(mapMode[1]),get_texture_map_mode(mapMode[2])};
// // add texture to model
// (*textures)[foundPath] = std::move(texture);
// }
// return &(*textures)[foundPath];
//}
std::shared_ptr<Model> AiLoader::load_model(std::string path, bool verbose){
if(verbose){
std::cout << "[ASSIMP_LOADER] Load model with path: " << path << "\n";
}
namespace fs = std::filesystem;
fs::path pathModel = path;
if(!fs::exists(pathModel)){
// throw std::runtime_error("[ASSIMP_LOADER] Path " + path + " doesn't exists, cannot load model.\n");
std::cerr << "[ASSIMP_LOADER] Path " << path << " doesn't exists, cannot load model.\n";
return nullptr;
}
// read from assimp
Assimp::Importer import;
const aiScene *scene = import.ReadFile(path, aiProcess_Triangulate); // aiProcess_EmbedTextures / aiProcess_FlipUVs
if(!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode){
std::cerr << "[ASSIMP_LOADER] " << import.GetErrorString() << "\n";
return nullptr;
}
// create model
auto model = std::make_shared<Model>();
model->directory = pathModel.parent_path().string();
model->name = scene->mRootNode->mName.C_Str();
if(verbose){
std::cout << "[ASSIMP_LOADER] Model name: " << model->name << "\n";
}
// retrieve global inverse transform
model->globalInverseTr = scene->mRootNode->mTransformation;
model->globalInverseTr.Inverse();
auto m = scene->mRootNode->mTransformation;
m.Inverse();
model->globalInverseTr2 = geo::Mat4f{
m.a1,m.a2,m.a3,m.a4,
m.b1,m.b2,m.b3,m.b4,
m.c1,m.c2,m.c3,m.c4,
m.d1,m.d2,m.d3,m.d4,
};
// aiVector3t<float> aiTr,aiRot,aiSc;
// m_GlobalInverseTransform.Decompose(aiSc,aiRot,aiTr);
// auto r = geo::Pt3f{aiRot.x,aiRot.y,aiRot.z};
// model->globalInverseTr = geo::Mat4f::transform(
// geo::Pt3f{aiSc.x,aiSc.y,aiSc.z},
// geo::Pt3f{rad_2_deg(r.x()),rad_2_deg(r.y()),rad_2_deg(r.z())},
// geo::Pt3f{aiTr.x,aiTr.y,aiTr.z}
// );
// std::cout << "GLOBAL INVERSE:\n " <<geo::Pt3f{aiSc.x,aiSc.y,aiSc.z} << " " << geo::Pt3f{rad_2_deg(r.x()),rad_2_deg(r.y()),rad_2_deg(r.z())} << " "<< geo::Pt3f{aiTr.x,aiTr.y,aiTr.z} << "\n";
// // read embedded textures // EMBEDDED
// if(scene->HasTextures()){
// for(size_t ii = 0; ii < scene->mNumTextures; ++ii){
// auto aiTexture = scene->mTextures[ii];
// std::string file = aiTexture->mFilename.C_Str();
// std::cout << "embedded texture " << ii << " " << file << " " << aiTexture->mWidth << " " << aiTexture->mHeight << "\n";
// for(size_t jj = 0; jj < aiTexture->mWidth * aiTexture->mHeight; ++jj){
// aiTexture->pcData->r;
// aiTexture->pcData->g;
// aiTexture->pcData->b;
// aiTexture->pcData->a;
// }
// }
// }
// retrieve materials
if(scene->HasMaterials()){
if(verbose){
std::cout << "[ASSIMP_LOADER] Load materials: " << scene->mNumMaterials << "\n";
}
for(size_t ii = 0; ii < scene->mNumMaterials; ++ii){
read_material(model.get(), scene->mMaterials[ii]);
}
}
// retrieve meshes
if(scene->HasMeshes()){
if(verbose){
std::cout << "[ASSIMP_LOADER] Load meshes: " << scene->mNumMeshes << "\n";
}
for(size_t ii = 0; ii < scene->mNumMeshes; ++ii){
if(verbose){
std::cout << "[ASSIMP_LOADER] Mesh: " << scene->mMeshes[ii]->mName.C_Str() << "\n";
}
read_mesh(model.get(), scene->mMeshes[ii]);
}
}
// retrieve animations
if(scene->HasAnimations()){
if(verbose){
std::cout << "[ASSIMP_LOADER] Load animations: " << scene->mNumAnimations << "\n";
}
for(size_t ii = 0; ii < scene->mNumAnimations; ++ii){
if(verbose){
std::cout << "[ASSIMP_LOADER] Animation: " << scene->mAnimations[ii]->mName.C_Str() << "\n";
}
auto assimpAnimation = scene->mAnimations[ii];
graphics::Animation animation;
animation.duration = assimpAnimation->mDuration;
animation.ticksPerSecond = assimpAnimation->mTicksPerSecond;
animation.name = assimpAnimation->mName.C_Str();
for(size_t jj = 0; jj < assimpAnimation->mNumChannels; ++jj){
auto assimpChannel = assimpAnimation->mChannels[jj];
const std::string affectedNodeName = assimpChannel->mNodeName.C_Str();
tool::graphics::AnimationKeys keys;
keys.positionTimes.resize(assimpChannel->mNumPositionKeys);
keys.positionKeys.resize(assimpChannel->mNumPositionKeys);
for(size_t kk = 0; kk < keys.positionTimes.size(); ++kk){
auto &key = assimpChannel->mPositionKeys[kk];
keys.positionTimes[kk] = key.mTime;
keys.positionKeys[kk] = {key.mValue.x,key.mValue.y,key.mValue.z};
}
keys.rotationTimes.resize(assimpChannel->mNumRotationKeys);
keys.rotationKeys.resize(assimpChannel->mNumRotationKeys);
for(size_t kk = 0; kk < keys.rotationTimes.size(); ++kk){
auto &key = assimpChannel->mRotationKeys[kk];
keys.rotationTimes[kk] = key.mTime;
keys.rotationKeys[kk] = {key.mValue.x,key.mValue.y,key.mValue.z, key.mValue.w};
}
keys.scalingTimes.resize(assimpChannel->mNumScalingKeys);
keys.scalingKeys.resize(assimpChannel->mNumScalingKeys);
for(size_t kk = 0; kk < keys.scalingTimes.size(); ++kk){
auto &key = assimpChannel->mScalingKeys[kk];
keys.scalingTimes[kk] = key.mTime;
keys.scalingKeys[kk] = {key.mValue.x,key.mValue.y,key.mValue.z};
}
model->animationsKeys[animation.name][affectedNodeName] = std::move(keys);
}
model->animations.emplace_back(std::move(animation));
}
}
// bones
read_bones_hierarchy(&model->bonesHierachy, scene->mRootNode);
return model;
}
void AiLoader::read_mesh(Model *model, aiMesh *aiMesh){
bool verbose = false;
auto gmesh = std::make_shared<GMesh>();
gmesh->name = aiMesh->mName.C_Str();
gmesh->material = &model->m_materials[aiMesh->mMaterialIndex];
Mesh *mesh = &gmesh->mesh;
bool hasPoints = aiMesh->mPrimitiveTypes & aiPrimitiveType::aiPrimitiveType_POINT;
bool hasLines = aiMesh->mPrimitiveTypes & aiPrimitiveType::aiPrimitiveType_LINE;
bool hasTriangles = aiMesh->mPrimitiveTypes & aiPrimitiveType::aiPrimitiveType_TRIANGLE;
bool hasPolygons = aiMesh->mPrimitiveTypes & aiPrimitiveType::aiPrimitiveType_POLYGON;
// process vertex positions, normals and texture coordinates
mesh->vertices.reserve(aiMesh->mNumVertices);
if(aiMesh->HasNormals()){
mesh->normals.reserve(aiMesh->mNumVertices);
}
if(aiMesh->HasTextureCoords(0)){
mesh->tCoords.reserve(aiMesh->mNumVertices);
}else{
mesh->tCoords.resize(aiMesh->mNumVertices);
std::fill(std::begin(mesh->tCoords), std::end(mesh->tCoords), Pt2f{0.f,0.f});
}
if(aiMesh->HasTangentsAndBitangents()){
mesh->tangents.resize(aiMesh->mNumVertices);
}
if(aiMesh->HasVertexColors(0)){
mesh->colors.reserve(aiMesh->mNumVertices);
}
if(aiMesh->HasBones()){
mesh->bones.resize(aiMesh->mNumVertices);
}
for(unsigned int ii = 0; ii < aiMesh->mNumVertices; ii++){
// position
mesh->vertices.emplace_back(Pt3f{aiMesh->mVertices[ii].x, aiMesh->mVertices[ii].y, aiMesh->mVertices[ii].z});
// normal
if(aiMesh->HasNormals()){
mesh->normals.emplace_back(Vec3f{aiMesh->mNormals[ii].x, aiMesh->mNormals[ii].y, aiMesh->mNormals[ii].z});
}
// uv
// aiMesh->GetNumUVChannels()
if(aiMesh->HasTextureCoords(0)){
mesh->tCoords.emplace_back(Pt2f{aiMesh->mTextureCoords[0][ii].x, aiMesh->mTextureCoords[0][ii].y});
}
// tangents
if(aiMesh->HasTangentsAndBitangents()){
mesh->tangents.emplace_back(Pt4f{aiMesh->mTangents->x,aiMesh->mTangents->y,aiMesh->mTangents->z,1.f});
}
// colors
// aiMesh->GetNumColorChannels()
if(aiMesh->HasVertexColors(0)){
mesh->colors.emplace_back(Pt4f{
aiMesh->mColors[0][ii].r,
aiMesh->mColors[0][ii].g,
aiMesh->mColors[0][ii].b,
aiMesh->mColors[0][ii].a
});
}
// aiMesh->mBitangents
// aiMesh->mMethod
// aiMesh->mAnimMeshes
}
// process indices
if(hasTriangles && !hasPoints && !hasLines && !hasPolygons){
mesh->triIds.reserve(aiMesh->mNumFaces);
for(unsigned int ii = 0; ii < aiMesh->mNumFaces; ii++){
aiFace face = aiMesh->mFaces[ii];
mesh->triIds.emplace_back(TriIds{face.mIndices[0], face.mIndices[1], face.mIndices[2]});
}
}else{
std::cerr << "[ASSIMP_LOADER] Face format not managed.\n";
}
// compute normals if necessary
if(!aiMesh->HasNormals()){
mesh->generate_normals();
}
// generate tangents if necessary
if(!aiMesh->HasTangentsAndBitangents() && (mesh->normals.size() > 0) && aiMesh->HasTextureCoords(0)){
mesh->generate_tangents();
}
// if(mesh->tangents.size() != mesh->vertices.size()){
// std::cout << "[ASSIMP_LOADER] Invalid tangents. Recomputing.\n";
// mesh->generate_tangents();
// }
// bones
if(aiMesh->HasBones()){
// for (uint i = 0 ; i < pMesh->mNumBones ; i++) {
// uint BoneIndex = 0;
// string BoneName(pMesh->mBones[i]->mName.data);
// if (m_BoneMapping.find(BoneName) == m_BoneMapping.end()) {
// BoneIndex = m_NumBones;
// m_NumBones++;
// BoneInfo bi;
// m_BoneInfo.push_back(bi);
// }
// else {
// BoneIndex = m_BoneMapping[BoneName];
// }
// m_BoneMapping[BoneName] = BoneIndex;
// m_BoneInfo[BoneIndex].BoneOffset = pMesh->mBones[i]->mOffsetMatrix;
// for (uint j = 0 ; j < pMesh->mBones[i]->mNumWeights ; j++) {
// uint VertexID = m_Entries[MeshIndex].BaseVertex + pMesh->mBones[i]->mWeights[j].mVertexId;
// float Weight = pMesh->mBones[i]->mWeights[j].mWeight;
// Bones[VertexID].AddBoneData(BoneIndex, Weight);
// }
// }
if(verbose){
std::cout << "Num bones: " << aiMesh->mNumBones << "\n";
}
for(size_t ii = 0; ii < aiMesh->mNumBones; ++ii){
unsigned int boneIndex = 0;
auto bone = aiMesh->mBones[ii];
std::string boneName(bone->mName.C_Str());
if(verbose){
std::cout << "Bone: " << boneName << "\n";
}
if(model->bonesMapping.count(boneName) == 0){
boneIndex = static_cast<unsigned int>(model->bonesMapping.size());
model->bonesInfo.emplace_back(graphics::BoneInfo{});
// model->bonesMapping[boneName] = boneIndex;
if(verbose){
std::cout << "Add bone in mapping, current index: " << boneIndex << " " << model->bonesMapping.size() << "\n";
}
}else{
boneIndex = model->bonesMapping[boneName];
if(verbose){
std::cout << "Bone already in mapping at index: " << boneIndex << "\n";
}
}
model->bonesMapping[boneName] = boneIndex;
model->bonesInfo[boneIndex].offset = bone->mOffsetMatrix;
// model->bonesInfo[boneIndex].offset = geo::Mat4f
// {
// m.a1,m.a2,m.a3,m.a4,
// m.b1,m.b2,m.b3,m.b4,
// m.c1,m.c2,m.c3,m.c4,
// m.d1,m.d2,m.d3,m.d4,
// };
// // bone offset
// // # decompose
// aiVector3t<float> aiTr,aiRot,aiSc;
// bone->mOffsetMatrix.Decompose(aiSc,aiRot,aiTr);
// // # create offset transform
// auto r = geo::Pt3f{aiRot.x,aiRot.y,aiRot.z};
// model->bonesInfo[boneIndex].offset = geo::Mat4f::transform(
// geo::Pt3f{aiSc.x,aiSc.y,aiSc.z},
// geo::Pt3f{rad_2_deg(r.x()),rad_2_deg(r.y()),rad_2_deg(r.z())},
//// geo::Pt3f{(r.x()),(r.y()),(r.z())},
// geo::Pt3f{aiTr.x,aiTr.y,aiTr.z}
// );
if(verbose){
std::cout << "Num weights: " << bone->mNumWeights << "\n";
}
for (size_t jj = 0 ; jj < bone->mNumWeights; jj++) {
unsigned int VertexId = bone->mWeights[jj].mVertexId;
float Weight = bone->mWeights[jj].mWeight;
mesh->bones[VertexId].add_bone_data(boneIndex, Weight);
}
}
}
model->gmeshes.emplace_back(std::move(gmesh));
}
void AiLoader::read_material(Model *model, aiMaterial *aiMat){
using MatP = Material::Property;
// read properties
Material material;
// # str
material.name = to_string(read_property<aiString>(MatP::name, aiMat));
// # int
material.backfaceCulling = read_property<int>(MatP::twosided, aiMat).value() != 0;
material.wireframe = read_property<int>(MatP::enable_wireframe, aiMat).value() != 0;
// # float
material.opacity = read_property<float>(MatP::opacity, aiMat).value();
material.shininess = read_property<float>(MatP::shininess, aiMat).value();
material.shininessStrength = read_property<float>(MatP::shininess_strength, aiMat).value();
material.refraction = read_property<float>(MatP::refacti, aiMat).value();
material.reflectivity = read_property<float>(MatP::reflectivity, aiMat).value();
// # point3f
material.ambiantColor = to_color(read_property<aiColor3D>(MatP::color_ambient, aiMat));
material.diffuseColor = to_color(read_property<aiColor3D>(MatP::color_diffuse, aiMat));
material.specularColor = to_color(read_property<aiColor3D>(MatP::color_specular, aiMat));
material.emissiveColor = to_color(read_property<aiColor3D>(MatP::color_emissive, aiMat));
material.transparentColor = to_color(read_property<aiColor3D>(MatP::color_transparent, aiMat));
material.reflectiveColor = to_color(read_property<aiColor3D>(MatP::color_reflective, aiMat));
// mat.mNumAllocated;
// mat.mNumProperties;
// read textures
for(const auto &type : textureTypes.data){
for(unsigned int ii = 0; ii < aiMat->GetTextureCount(std::get<1>(type)); ++ii){
// ai data
aiString path; // receives the path to the texture. If the texture is embedded, receives a '*' followed by the id of the texture
// (for the textures stored in the corresponding scene) which can be converted to an int using a function like atoi. NULL is a valid value
aiTextureMapping mapping = aiTextureMapping_UV; // texture mapping, NULL is allowed as value
unsigned int uvIndex; // uv index of the texture (NULL is valid value)
ai_real blend; // blend factor for the texture
aiTextureOp operation = aiTextureOp_Multiply;// texture operation to be performed between this texture and the previous texture
aiTextureMapMode mapMode[3];// mapping modes to be used for the texture, the parameter may be NULL but if it is a valid pointer it MUST
aiMat->GetTexture(std::get<1>(type), ii, &path, &mapping, &uvIndex, &blend, &operation, &mapMode[0]);
if(auto pathTexture = retrieve_texture_path(model, path); pathTexture.has_value()){
Texture2D *texture = nullptr;
if(model->m_textures.count(pathTexture.value()) == 0){ // add texture
model->m_textures[pathTexture.value()] = Texture2D(pathTexture.value());
}
texture = &model->m_textures[pathTexture.value()];
TextureInfo textureInfo;
textureInfo.texture = texture;
textureInfo.options.type = std::get<0>(type);
textureInfo.options.mapping = get_texture_mapping(mapping);
textureInfo.options.operation = get_texture_operation(operation);
textureInfo.options.mapMode = Pt3<TextureMapMode>{
get_texture_map_mode(mapMode[0]),
get_texture_map_mode(mapMode[1]),
get_texture_map_mode(mapMode[2])
};
// others textures info
auto wrapping = read_texture_property<int>(MatP::text_mapping, aiMat, textureInfo.options.type, ii).value();
auto uvwSource = read_texture_property<int>(MatP::text_uvw_source, aiMat, textureInfo.options.type, ii).value();
auto mappingModeU = read_texture_property<int>(MatP::text_mapping_mode_u, aiMat, textureInfo.options.type, ii).value();
auto mappingModeV = read_texture_property<int>(MatP::text_mapping_mode_v, aiMat, textureInfo.options.type, ii).value();
auto flags = read_texture_property<int>(MatP::text_flags, aiMat, textureInfo.options.type, ii).value();
auto texmapAxis = read_texture_property<aiVector3D>(MatP::text_texmap_axis, aiMat, textureInfo.options.type, ii).value();
auto blend = read_texture_property<float>(MatP::text_blend, aiMat, textureInfo.options.type, ii).value();
static_cast<void>(wrapping);
static_cast<void>(uvwSource);
static_cast<void>(mappingModeU);
static_cast<void>(mappingModeV);
static_cast<void>(flags);
static_cast<void>(texmapAxis);
static_cast<void>(blend);
// name,twosided,shading_model,enable_wireframe,blend_func,opacity, bumpscaling, shininess, reflectivity,
// shininess_strength, refacti, color_diffuse, color_ambient, color_specular, color_emissive, color_transparent,
// color_reflective, global_background_image,
// text_blend, text_mapping, text_operation, text_uvw_source,
// text_mapping_mode_u, text_mapping_mode_v,
// text_texmap_axis, text_flags,
// add infos
material.texturesInfo[textureInfo.options.type].emplace_back(std::move(textureInfo));
}
}
}
model->m_materials.emplace_back(std::move(material));
}
std::optional<std::string> AiLoader::retrieve_texture_path(Model *model, const aiString &aiPath){
const std::string path = aiPath.C_Str();
if(path.length() > 0){
if(path[0] == '*'){
std::cout << "[ASSIMP_LOADER] Embedded texture detected, not managed yet\n";
return {};
}
}
namespace fs = std::filesystem;
fs::path texturePath = path;
std::error_code code;
if(!fs::exists(texturePath,code)){ // check if full path exist
fs::path dirPath = model->directory;
std_v1<fs::path> pathsToTest;
pathsToTest.emplace_back(dirPath / texturePath.filename());
pathsToTest.emplace_back(dirPath / "texture" / texturePath.filename());
pathsToTest.emplace_back(dirPath / "textures" / texturePath.filename());
pathsToTest.emplace_back(dirPath / ".." / "texture" / texturePath.filename());
pathsToTest.emplace_back(dirPath / ".." / "textures" / texturePath.filename());
bool found = false;
for(const auto &pathToTest : pathsToTest){
if(fs::exists(pathToTest)){
found = true;
texturePath = pathToTest;
break;
}
}
if(!found){
std::cerr << "[ASSIMP_LOADER] Cannot find texture " << texturePath.filename() << "\n";
return {};
}
}
// found path
return texturePath.string();
}
void AiLoader::read_bones_hierarchy(tool::graphics::BonesHierarchy *bones, aiNode *node){
bones->boneName = node->mName.C_Str();
// set transform
// const auto &m = node->mTransformation;
// aiVector3t<float> aiTr,aiRot,aiSc;
// node->mTransformation.Decompose(aiSc,aiRot,aiTr);
// auto r = geo::Pt3f{aiRot.x,aiRot.y,aiRot.z};
// bones->tr = geo::Mat4f::transform(
// geo::Pt3f{aiSc.x,aiSc.y,aiSc.z},
// geo::Pt3f{rad_2_deg(r.x()),rad_2_deg(r.y()),rad_2_deg(r.z())},
//// geo::Pt3f{(r.x()),(r.y()),(r.z())},
// geo::Pt3f{aiTr.x,aiTr.y,aiTr.z}
// );
bones->tr = node->mTransformation;
// const auto &m = node->mTransformation;//.Transpose();
// bones->tr = geo::Mat4f
// {
// m.a1,m.a2,m.a3,m.a4,
// m.b1,m.b2,m.b3,m.b4,
// m.c1,m.c2,m.c3,m.c4,
// m.d1,m.d2,m.d3,m.d4,
// };
// std::cout << "TR: " << geo::Pt3f{aiSc.x,aiSc.y,aiSc.z} << " " << geo::Pt3f{rad_2_deg(r.x()),rad_2_deg(r.y()),rad_2_deg(r.z())} << " " << geo::Pt3f{aiTr.x,aiTr.y,aiTr.z} << "\n";
for(size_t ii = 0; ii < node->mNumChildren; ++ii){
graphics::BonesHierarchy bh;
read_bones_hierarchy(&bh, node->mChildren[ii]);
bones->children.emplace_back(std::move(bh));
}
}
| 28,059 | 9,257 |
// Copyright (c) 2018-2019 VMware, Inc. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
#include "utils/concord_eth_hash.hpp"
#include "utils/concord_eth_sign.hpp"
#include "utils/concord_utils.hpp"
#include "utils/rlp.hpp"
using namespace std;
using concord::utils::dehex;
using concord::utils::EthSign;
using concord::utils::RLPBuilder;
using concord::utils::RLPParser;
std::vector<uint8_t> next_part(RLPParser &parser, const char *label) {
if (parser.at_end()) {
cerr << "Transaction too short: missing " << label << endl;
exit(-1);
}
return parser.next();
}
std::string addr_to_string(evm_address a) {
static const char hexes[] = "0123456789abcdef";
std::string out;
for (size_t i = 0; i < sizeof(evm_address); i++) {
out.append(hexes + (a.bytes[i] >> 4), 1)
.append(hexes + (a.bytes[i] & 0x0f), 1);
}
return out;
}
uint64_t uint_from_vector(std::vector<uint8_t> v, const char *label) {
if (v.size() > 8) {
cerr << label << " > uint64_t\n" << endl;
exit(-1);
}
uint64_t u = 0;
for (size_t i = 0; i < v.size(); i++) {
u = u << 8;
u += v[i];
}
return u;
}
int main(int argc, char **argv) {
if (argc != 2) {
cerr << "Usage: ecrecover <signed transaction hex>" << endl;
return -1;
}
string tx_s(argv[1]);
vector<uint8_t> tx = dehex(tx_s);
// Decode RLP
RLPParser tx_envelope_p = RLPParser(tx);
std::vector<uint8_t> tx_envelope = tx_envelope_p.next();
if (!tx_envelope_p.at_end()) {
cerr << "Warning: There are more bytes here than one transaction\n";
}
RLPParser tx_parts_p = RLPParser(tx_envelope);
std::vector<uint8_t> nonce_v = next_part(tx_parts_p, "nonce");
std::vector<uint8_t> gasPrice_v = next_part(tx_parts_p, "gas price");
std::vector<uint8_t> gas_v = next_part(tx_parts_p, "start gas");
std::vector<uint8_t> to = next_part(tx_parts_p, "to address");
std::vector<uint8_t> value_v = next_part(tx_parts_p, "value");
std::vector<uint8_t> data = next_part(tx_parts_p, "data");
std::vector<uint8_t> v = next_part(tx_parts_p, "signature V");
std::vector<uint8_t> r_v = next_part(tx_parts_p, "signature R");
std::vector<uint8_t> s_v = next_part(tx_parts_p, "signature S");
uint64_t nonce = uint_from_vector(nonce_v, "nonce");
uint64_t gasPrice = uint_from_vector(gasPrice_v, "gas price");
uint64_t gas = uint_from_vector(gas_v, "start gas");
uint64_t value = uint_from_vector(value_v, "value");
if (r_v.size() != sizeof(evm_uint256be)) {
cout << "Signature R is too short (" << r_v.size() << ")" << endl;
return -1;
}
evm_uint256be r;
std::copy(r_v.begin(), r_v.end(), r.bytes);
if (s_v.size() != sizeof(evm_uint256be)) {
cout << "Signature S is too short (" << s_v.size() << ")" << endl;
return -1;
}
evm_uint256be s;
std::copy(s_v.begin(), s_v.end(), s.bytes);
// Figure out non-signed V
if (v.size() < 1) {
cerr << "Signature V is empty\n" << endl;
return -1;
}
uint64_t chainID = uint_from_vector(v, "chain ID");
uint8_t actualV;
if (chainID < 37) {
cerr << "Non-EIP-155 signature V value" << endl;
return -1;
}
if (chainID % 2) {
actualV = 0;
chainID = (chainID - 35) / 2;
} else {
actualV = 1;
chainID = (chainID - 36) / 2;
}
// Re-encode RLP
RLPBuilder unsignedTX_b;
unsignedTX_b.start_list();
std::vector<uint8_t> empty;
unsignedTX_b.add(empty); // S
unsignedTX_b.add(empty); // R
unsignedTX_b.add(chainID); // V
unsignedTX_b.add(data);
if (value == 0) {
// signing hash expects 0x80 here, not 0x00
unsignedTX_b.add(empty);
} else {
unsignedTX_b.add(value);
}
unsignedTX_b.add(to);
if (gas == 0) {
unsignedTX_b.add(empty);
} else {
unsignedTX_b.add(gas);
}
if (gasPrice == 0) {
unsignedTX_b.add(empty);
} else {
unsignedTX_b.add(gasPrice);
}
if (nonce == 0) {
unsignedTX_b.add(empty);
} else {
unsignedTX_b.add(nonce);
}
std::vector<uint8_t> unsignedTX = unsignedTX_b.build();
// Recover Address
evm_uint256be unsignedTX_h =
concord::utils::eth_hash::keccak_hash(unsignedTX);
EthSign verifier;
evm_address from = verifier.ecrecover(unsignedTX_h, actualV, r, s);
cout << "Recovered: " << addr_to_string(from) << endl;
return 0;
}
| 4,292 | 1,838 |
#include <QtCore>
#include <QDebug>
#include <QCoreApplication>
#include <iostream>
#include <unistd.h>
#include "dbusutil.h"
using namespace std;
ENUM_BUS g_session_bus = USE_SYSTEM_BUS;
void msgHandler(QtMsgType type, const QMessageLogContext& ctx, const QString& msg)
{
Q_UNUSED(ctx);
const char symbols[] = { 'I', 'E', '!', 'X' };
QString output = QString("[%1] %2").arg( symbols[type] ).arg( msg );
std::cerr << output.toStdString() << std::endl;
if( type == QtFatalMsg ) abort();
}
void usage()
{
cout << "bustx - send two kinds of signals to dbus" << endl
<< "options:" << endl
<< "\t-c send COMMAND signal" << endl
<< "\t-m send MESSAGE signal" << endl
<< "\t-h this usage" << endl
<< "\t-n assign name of sender" << endl
<< "\t-s use session bus" << endl
<< endl
<< "option -c will override -s and -m" << endl;
}
void process_args(int argc, char* argv[])
{
int c;
const size_t MAX_CMD_LEN = 64;
char cmd[MAX_CMD_LEN];
char sender[MAX_CMD_LEN];
bool has_sender = false;
bool has_message = false;
while (true) {
c = getopt(argc, argv, "hc:m:n:sy");
if (c == -1)
break;
switch (c) {
case 'h':
case '?':
usage();
return;
case 'c':
memset(cmd, 0, MAX_CMD_LEN);
strncpy(cmd, optarg, qMin(MAX_CMD_LEN, strlen(optarg)));
send_dbus_signal_to_command(cmd);
return;
case 'm':
has_message = true;
memset(cmd, 0, MAX_CMD_LEN);
strncpy(cmd, optarg, qMin(MAX_CMD_LEN, strlen(optarg)));
break;
case 'n':
has_sender = true;
memset(sender, 0, MAX_CMD_LEN);
strncpy(sender, optarg, qMin(MAX_CMD_LEN, strlen(optarg)));
break;
case 's':
g_session_bus = USE_SESSION_BUS;
printf("use session bus");
break;
case 'y':
g_session_bus = USE_SYSTEM_BUS;
printf("use system bus");
break;
default:
break;
}
}
if (has_message) {
send_dbus_signal_to_message(
cmd,
(has_sender ? sender : argv[0]) );
}
if (argc > optind) {
for (int i = optind; i < argc; i++) {
send_dbus_signal_to_message(
argv[i],
(has_sender ? sender : argv[0]) );
}
}
}
int main(int argc, char *argv[])
{
Q_UNUSED(argc);
Q_UNUSED(argv);
//qInstallMessageHandler(msgHandler);
//QCoreApplication app(argc, argv);
if (argc == 1) {
usage();
return 0;
}
process_args(argc, argv);
return 0;
}
| 2,787 | 999 |
#pragma once
namespace gem::expr
{
// Expression produced by the - operator
template <typename LHS, typename RHS>
class diff_expr
{
LHS const& m_lhs_expr;
RHS const& m_rhs_expr;
public:
using result_type
= gem::meta::sum<typename LHS::result_type,
typename RHS::result_type>::type;
constexpr diff_expr(LHS const& lhs, RHS const& rhs)
: m_lhs_expr(lhs), m_rhs_expr(rhs)
{
}
template <std::size_t I>
auto constexpr subscript() const
{
// Find which indices in sub expressions map to index I
using index_mapping
= gem::meta::sum_sub_indices<I, result_type,
typename LHS::result_type,
typename RHS::result_type>;
// Only rhs contributes a term.
if constexpr(index_mapping::I1 == LHS::result_type::size)
{
return -m_rhs_expr. template subscript<index_mapping::I2>();
}
// Only lhs contributes a term.
else if constexpr(index_mapping::I2 == RHS::result_type::size)
{
return m_lhs_expr. template subscript<index_mapping::I1>();
}
// Both rhs and lhs contribute a term each.
else
{
return m_lhs_expr. template subscript<index_mapping::I1>()
- m_rhs_expr. template subscript<index_mapping::I2>();
}
}
};
} // namespace gem::expr
namespace gem
{
// Difference of two expressions
template <expression LHS, expression RHS>
auto constexpr operator - (LHS const& lhs, RHS const& rhs)
{
return expr::diff_expr<LHS, RHS>(lhs, rhs);
}
// Difference of scalar and expression
template <expression RHS>
auto constexpr operator - (mvec<blade<0,0,0>> const& lhs, RHS const& rhs)
{
return expr::diff_expr(lhs, rhs);
}
// Difference of expression and scalar
template <expression LHS>
auto constexpr operator - (LHS const& lhs, mvec<blade<0,0,0>> const& rhs)
{
return expr::diff_expr(lhs, rhs);
}
} // namespace gem | 2,323 | 679 |
#include "MenuModelManager.hpp"
#include <cmath>
#include "../../ui/UiManager.hpp"
MenuModelManager::MenuModelManager()
: ModelManager(64) {
//
}
void MenuModelManager::updateOneTick() {
//
}
void MenuModelManager::draw(UiManager &uiManager) {
uiManager.setColorMask({1,1,1});
uiManager.setObjectScale(1 + .8f*sin(modelTick*.01618f +.8f));
uiManager.drawSprite(-3 + sin(modelTick*.01f +.8f), .5f*cos(modelTick*.01f +.8f), SPRITE_ID_TEX1);
uiManager.setObjectScale(1 + .2f*sin(modelTick*.01618f));
uiManager.drawSprite(.5f*cos(modelTick*.01f +.4f), 1 - sin(modelTick*.01f +.4f), SPRITE_ID_GEOM);
uiManager.setObjectScale(1);
uiManager.drawSprite(3 + sin(modelTick*.01f), .5f*cos(modelTick*.01f), SPRITE_ID_TEX1);
uiManager.setObjectScale(3, 1);
uiManager.drawSprite(3 + sin(modelTick*.01f +.3f), 3 + .5f*cos(modelTick*.01f +.3f), SPRITE_ID_TEX2);
uiManager.setObjectScale(1);
uiManager.drawSprite(-3 + sin(modelTick*.01f), 1 + .5f*cos(modelTick*.01f), SPRITE_ID_TEX3);
uiManager.setObjectScale(1);
uiManager.drawSprite(-3 + sin(modelTick*.015f), -2 + cos(modelTick*.015f), SPRITE_ID_TEX4);
}
| 1,170 | 529 |
#pragma once
#include "GpProtoHeaderValue.hpp"
#include "../Enums/GpEnums.hpp"
namespace GPlatform {
class GPNETWORK_API GpProtoHeaders: public GpTypeStructBase
{
public:
CLASS_DECLARE_DEFAULTS(GpProtoHeaders)
TYPE_STRUCT_DECLARE("88a01e4e-9105-4cd5-9990-4578ebb14b51"_sv)
public:
explicit GpProtoHeaders (void) noexcept;
GpProtoHeaders (const GpProtoHeaders& aHeaders);
GpProtoHeaders (GpProtoHeaders&& aHeaders) noexcept;
virtual ~GpProtoHeaders (void) noexcept override;
void Set (const GpProtoHeaders& aHeaders);
void Set (GpProtoHeaders&& aHeaders) noexcept;
void Clear (void);
GpProtoHeaderValue::C::MapStr::SP& Headers (void) noexcept {return headers;}
const GpProtoHeaderValue::C::MapStr::SP&
Headers (void) const noexcept {return headers;}
GpProtoHeaders& Replace (std::string aName,
std::string_view aValue);
GpProtoHeaders& Replace (std::string aName,
std::string&& aValue);
GpProtoHeaders& Replace (std::string aName,
const u_int_64 aValue);
GpProtoHeaders& Add (std::string aName,
std::string_view aValue);
GpProtoHeaders& Add (std::string aName,
std::string&& aValue);
GpProtoHeaders& Add (std::string aName,
const u_int_64 aValue);
protected:
template<typename T, typename V>
GpProtoHeaders& Replace (const typename T::EnumT aType,
std::string_view aValue);
template<typename T, typename V>
GpProtoHeaders& Replace (const typename T::EnumT aType,
std::string&& aValue);
template<typename T, typename V>
GpProtoHeaders& Replace (const typename T::EnumT aType,
const u_int_64 aValue);
template<typename T, typename V>
GpProtoHeaders& Add (const typename T::EnumT aType,
std::string_view aValue);
template<typename T, typename V>
GpProtoHeaders& Add (const typename T::EnumT aType,
std::string&& aValue);
template<typename T, typename V>
GpProtoHeaders& Add (const typename T::EnumT aType,
const u_int_64 aValue);
private:
GpProtoHeaderValue::C::MapStr::SP headers;
public:
static const GpArray<std::string, GpContentType::SCount().As<size_t>()> sContentType;
static const GpArray<std::string, GpCharset::SCount().As<size_t>()> sCharset;
};
template<typename T, typename V>
GpProtoHeaders& GpProtoHeaders::Replace
(
const typename T::EnumT aType,
std::string_view aValue
)
{
return Replace<T, V>(aType, std::string(aValue));
}
template<typename T, typename V>
GpProtoHeaders& GpProtoHeaders::Replace
(
const typename T::EnumT aType,
std::string&& aValue
)
{
const std::string& headerName = V::sHeadersNames.at(size_t(aType));
headers[headerName] = MakeSP<GpProtoHeaderValue>(std::move(aValue));
return *this;
}
template<typename T, typename V>
GpProtoHeaders& GpProtoHeaders::Replace
(
const typename T::EnumT aType,
const u_int_64 aValue)
{
return Replace<T, V>(aType, StrOps::SFromUI64(aValue));
}
template<typename T, typename V>
GpProtoHeaders& GpProtoHeaders::Add
(
const typename T::EnumT aType,
std::string_view aValue
)
{
return Add<T, V>(aType, std::string(aValue));
}
template<typename T, typename V>
GpProtoHeaders& GpProtoHeaders::Add
(
const typename T::EnumT aType,
std::string&& aValue
)
{
const std::string& headerName = V::sHeadersNames.at(size_t(aType));
auto iter = headers.find(headerName);
if (iter == headers.end())
{
return Replace<T, V>(aType, std::move(aValue));
} else
{
iter->second->elements.emplace_back(std::move(aValue));
}
return *this;
}
template<typename T, typename V>
GpProtoHeaders& GpProtoHeaders::Add
(
const typename T::EnumT aType,
const u_int_64 aValue
)
{
return Add<T, V>(aType, StrOps::SFromUI64(aValue));
}
}//namespace GPlatform
| 5,738 | 1,581 |
/* Line.cpp (exercise 1.5.5)
Description:
* Declare Line class that represents a line in 2-D Euclidean space.
State Variables/Objects:
*Point p1, p2: Points in 2-D Euclidean space.
Member Functions:
*Line(): Default constructor (allocates memory for both state Point objects, sets their states to (0,0)).
*Line(const Point&, const Point&): Overloaded constructor (allocates memory for both state Point objects, sets their states to (0,0)).
*Line(const Line&): Copy constructor (allocates memory for both state Point objects, sets their states to passed Line's point's states).
*~Line(): Destructor (frees memory previously allocated by constructor).
// Accessors:
*Point P1() const: Return copy of P1 Point Object.
*Point P2() const: Return copy of P2 Point Object.
// Mutators:
*void P1(const Point&): Change P1's state to state of passed Point object.
*void P2(const Point&): Change P2's state to state of passed Point object.
// Misc. Methods:
*double Length() const: Return length of line.
*void Draw() const: Draw calling Line object.
*string ToString() const: Return string description of Length object's state ("Line((P1_X(), P1_Y()), (P2_X(), P2_Y()))").
*/
#include <iostream>
#include <string>
#include <sstream>
#include "IODevice.hpp"
#include "Line.hpp"
#include "Shape.hpp"
////////////////////////////////
// Constructors/Destructor:
////////////////////////////////
Line::Line() noexcept : p1(), p2(), Shape() /* Default constructor. */
{
}
Line::Line(const Point &p1_in, const Point &p2_in) noexcept : p1(p1_in), p2(p2_in), Shape() /* Overloaded constructor (parameters reference existing point objects). */
{
}
Line::Line(const Line &line_in) noexcept : p1(line_in.p1), p2(line_in.p2), Shape(line_in) /* Copy constructor. */
{
}
Line::~Line() noexcept /* Destructor. */
{
}
////////////////////////////////
// Accessors:
////////////////////////////////
Point Line::P1() const noexcept /* Return P1. */
{
return p1;
}
Point Line::P2() const noexcept /* Return P2. */
{
return p2;
}
////////////////////////////////
// Mutators:
////////////////////////////////
void Line::P1(const Point &point_in) noexcept /* Set state of P1 by using assignment operator with point_in. */
{
p1 = point_in;
}
void Line::P2(const Point &point_in) noexcept /* Set state of P2 by using assignment operator with point_in. */
{
p2 = point_in;
}
////////////////////////////////
// Misc. methods:
////////////////////////////////
double Line::Length() const noexcept /* Return euclidean distance between P1 and P2. */
{
return (p1.Distance(p2));
}
void Line::Draw() const noexcept /* Draw current Line object. */
{
std::cout << "Line has been drawn. " << std::endl;
}
void Line::display(const IODevice &in) const noexcept /* Display Circle object on passed input-output device. */
{
in << *this;
}
std::string Line::ToString() const noexcept /* Return description of Line object's state ("Line((P1_X(), P1_Y()), (P2_X(), P2_Y()))") */
{
std::stringstream ss;
// Append the base Shape object description to Line object description:
std::string s = Shape::ToString();
ss << "Line({" << p1.X() << ", " << p1.Y() << "},{" << p2.X() << ", " << p2.Y() << "}) " << s;
return ss.str();
}
//////////////////////////////////////
// Overloaded Operators:
//////////////////////////////////////
// Member operators:
Line& Line::operator=(const Line& line_in) noexcept /* Assignment operator. */
{
// Preclude self-assignment (check if passed line has the same memory address):
if (this != &line_in)
{
p1 = line_in.p1;
p2 = line_in.p2;
// Copy passed Line object's base state:
Shape::operator=(line_in);
}
return *this;
}
// Global operators:
std::ostream& operator<<(std::ostream& os, const Line& line_in) noexcept /* Overloaded ostream operator. */
{
os << "Line((" << line_in.p1.X() << ", " << line_in.p1.Y() << "),(" << line_in.p2.X() << ", " << line_in.p2.Y() << "))";
return os;
}
| 3,991 | 1,351 |
// Copyright 2018 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 "third_party/blink/renderer/core/html/anchor_element_metrics_sender.h"
#include "base/metrics/histogram_macros.h"
#include "third_party/blink/public/common/browser_interface_broker_proxy.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/html/anchor_element_metrics.h"
#include "third_party/blink/renderer/core/html/html_anchor_element.h"
#include "ui/gfx/geometry/mojom/geometry.mojom-shared.h"
namespace blink {
namespace {
// Returns true if |anchor_element| should be discarded, and not used for
// navigation prediction.
bool ShouldDiscardAnchorElement(const HTMLAnchorElement& anchor_element) {
Frame* frame = anchor_element.GetDocument().GetFrame();
auto* local_frame = DynamicTo<LocalFrame>(frame);
if (!local_frame)
return true;
return local_frame->IsAdSubframe();
}
} // namespace
// static
const char AnchorElementMetricsSender::kSupplementName[] =
"DocumentAnchorElementMetricsSender";
AnchorElementMetricsSender::~AnchorElementMetricsSender() = default;
// static
AnchorElementMetricsSender* AnchorElementMetricsSender::From(
Document& document) {
DCHECK(HasAnchorElementMetricsSender(document));
AnchorElementMetricsSender* sender =
Supplement<Document>::From<AnchorElementMetricsSender>(document);
if (!sender) {
sender = MakeGarbageCollected<AnchorElementMetricsSender>(document);
ProvideTo(document, sender);
}
return sender;
}
// static
bool AnchorElementMetricsSender::HasAnchorElementMetricsSender(
Document& document) {
bool is_feature_enabled =
base::FeatureList::IsEnabled(features::kNavigationPredictor);
const KURL& url = document.BaseURL();
return is_feature_enabled && !document.ParentDocument() && url.IsValid() &&
url.ProtocolIsInHTTPFamily();
}
void AnchorElementMetricsSender::SendClickedAnchorMetricsToBrowser(
mojom::blink::AnchorElementMetricsPtr metric) {
if (!AssociateInterface())
return;
metrics_host_->ReportAnchorElementMetricsOnClick(std::move(metric));
}
void AnchorElementMetricsSender::SendAnchorMetricsVectorToBrowser(
Vector<mojom::blink::AnchorElementMetricsPtr> metrics,
const IntSize& viewport_size) {
if (!AssociateInterface())
return;
metrics_host_->ReportAnchorElementMetricsOnLoad(std::move(metrics),
gfx::Size(viewport_size));
has_onload_report_sent_ = true;
anchor_elements_.clear();
}
void AnchorElementMetricsSender::AddAnchorElement(HTMLAnchorElement& element) {
if (has_onload_report_sent_)
return;
bool is_ad_frame_element = ShouldDiscardAnchorElement(element);
// We ignore anchor elements that are in ad frames.
if (is_ad_frame_element)
return;
anchor_elements_.insert(&element);
}
const HeapHashSet<Member<HTMLAnchorElement>>&
AnchorElementMetricsSender::GetAnchorElements() const {
return anchor_elements_;
}
void AnchorElementMetricsSender::Trace(Visitor* visitor) const {
visitor->Trace(anchor_elements_);
visitor->Trace(metrics_host_);
Supplement<Document>::Trace(visitor);
}
bool AnchorElementMetricsSender::AssociateInterface() {
if (metrics_host_.is_bound())
return true;
Document* document = GetSupplementable();
// Unable to associate since no frame is attached.
if (!document->GetFrame())
return false;
document->GetFrame()->GetBrowserInterfaceBroker().GetInterface(
metrics_host_.BindNewPipeAndPassReceiver(
document->GetExecutionContext()->GetTaskRunner(
TaskType::kInternalDefault)));
return true;
}
AnchorElementMetricsSender::AnchorElementMetricsSender(Document& document)
: Supplement<Document>(document),
metrics_host_(document.GetExecutionContext()) {
DCHECK(!document.ParentDocument());
}
void AnchorElementMetricsSender::DidFinishLifecycleUpdate(
const LocalFrameView& local_frame_view) {
// Check that layout is stable. If it is, we can perform the onload update and
// stop observing future events.
Document* document = local_frame_view.GetFrame().GetDocument();
if (document->Lifecycle().GetState() <
DocumentLifecycle::kAfterPerformLayout) {
return;
}
// Stop listening to updates, as the onload report can be sent now.
document->View()->UnregisterFromLifecycleNotifications(this);
// Send onload report.
AnchorElementMetrics::MaybeReportViewportMetricsOnLoad(*document);
}
} // namespace blink
| 4,865 | 1,459 |
#include <signal.h> // our new library
extern volatile sig_atomic_t flag;
void delay(float time);
void defining_sigaction();
void my_handler(int signal); | 157 | 51 |
#include "meshFIM.h"
#include "Vec.h"
#include <math.h>
#include <sstream>
#include <fstream>
#include <stdio.h>
//#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
//#include <termios.h>
#define NB_ENABLE 0
#define NB_DISABLE 1
#ifndef PI
#define PI 3.1415927
#endif
#ifndef MIN
#define MIN(a,b) (((a)<(b))?(a):(b))
#endif
#ifndef MAX
#define MAX(a,b) (((a)>(b))?(a):(b))
#endif
#define LARGENUM 10000000.0
#define EPS 1e-6
typedef std::pair<unsigned int, float> gDistPair;
void meshFIM::need_kdtree() {
if (!kd) {
kd = new KDtree(m_meshPtr->vertices);
}
if (maxEdgeLength == 0.0) {
need_maxedgelength();
}
}
void meshFIM::need_oneringfaces() {
if (vertOneringFaces.empty()) {
vertOneringFaces.resize(m_meshPtr->vertices.size());
for (int i = 0; i < m_meshPtr->vertices.size(); i++) {
vertOneringFaces[i] = GetOneRing(i);
}
}
}
void meshFIM::need_speed() {
need_abs_curvatures();
int nf = m_meshPtr->faces.size();
for (int i = 0; i < nf; i++) {
TriMesh::Face f = m_meshPtr->faces[i];
float speedInv = 0;
switch (speedType) {
case CURVATURE:
speedInv = (abs_curv[f[0]] + abs_curv[f[1]] + abs_curv[f[2]]) / 3.0;
break;
case ONE:
speedInv = 1.0;
break;
}
speedInvVector.push_back(speedInv);
}
}
void meshFIM::need_abs_curvatures() {
m_meshPtr->need_curvatures();
if (abs_curv.size() == m_meshPtr->vertices.size())
return;
abs_curv.clear();
//compute rms curvature and max/min
for (int i = 0; i < m_meshPtr->vertices.size(); i++) {
float crv1 = m_meshPtr->curv1[i];
float crv2 = m_meshPtr->curv2[i];
float abs_c = (fabs(crv1) + fabs(crv2)) / 2.0 + 1.0;
abs_curv.push_back(abs_c);
}
std::vector<float> abs_curv_mean;
float max_abs = -9e99;
float min_abs = 9e99;
for (int i = 0; i < abs_curv.size(); i++) {
float abs_c = abs_curv[i];
if (abs_c > max_abs) {
max_abs = abs_c;
}
if (abs_c < min_abs) {
min_abs = abs_c;
}
}
for (int i = 0; i < abs_curv.size(); i++) {
abs_curv[i] /= max_abs;
abs_curv[i] = sqrt(abs_curv[i]);
}
}
//compute the edge length
void meshFIM::need_edge_lengths() {
if (m_meshPtr->faces.empty()) {
std::cerr << "No faces to compute face edges!!!\n";
throw(1);
}
int numFaces = m_meshPtr->faces.size();
for (int i = 0; i < numFaces; i++) {
TriMesh::Face f = m_meshPtr->faces[i];
vec3 edge01 = ( vec3) (m_meshPtr->vertices[f[1]] - m_meshPtr->vertices[f[0]]);
vec3 edge12 = ( vec3) (m_meshPtr->vertices[f[2]] - m_meshPtr->vertices[f[1]]);
vec3 edge20 = ( vec3) (m_meshPtr->vertices[f[0]] - m_meshPtr->vertices[f[2]]);
vec3 edgeLengths;
edgeLengths[0] = sqrt(edge01[0] * edge01[0] + edge01[1] * edge01[1] + edge01[2] * edge01[2]);
edgeLengths[1] = sqrt(edge12[0] * edge12[0] + edge12[1] * edge12[1] + edge12[2] * edge12[2]);
edgeLengths[2] = sqrt(edge20[0] * edge20[0] + edge20[1] * edge20[1] + edge20[2] * edge20[2]);
edgeLengthsVector.push_back(edgeLengths);
}
}
void meshFIM::SetMesh(TriMesh *mesh) {
m_meshPtr = mesh;
this->geodesicMap.resize(m_meshPtr->vertices.size());
// orient the mesh for consistent vertex ordering...
orient(m_meshPtr);// Manasi
// have to recompute the normals and other attributes required for rendering
if (!m_meshPtr->normals.empty())
m_meshPtr->normals.clear();// Manasi
m_meshPtr->need_normals();// Manasi
if (!m_meshPtr->adjacentfaces.empty())
m_meshPtr->adjacentfaces.clear();// Manasi
m_meshPtr->need_adjacentfaces();// Manasi
if (!m_meshPtr->across_edge.empty())
m_meshPtr->across_edge.clear();// Manasi
m_meshPtr->need_across_edge();// Manasi
if (!m_meshPtr->tstrips.empty())
m_meshPtr->tstrips.clear();// Manasi
m_meshPtr->need_tstrips();// Manasi
need_edge_lengths();
m_meshPtr->need_curvatures();
need_speed();
}
void meshFIM::InitializeLabels() {
if (!m_meshPtr) {
std::cerr << "Label-vector size unknown, please set the mesh first..." << std::endl;
throw(1);
}
else {
// initialize all labels to 'Far'
int nv = m_meshPtr->vertices.size();
if (m_Label.size() != nv) m_Label.resize(nv);
for (int l = 0; l < nv; l++) {
m_Label[l] = FarPoint;
}
// if seeed-points are present, treat them differently
if (!m_SeedPoints.empty()) {
for (int s = 0; s < m_SeedPoints.size(); s++) {
m_Label[m_SeedPoints[s]] = SeedPoint;//m_Label[s] = LabelType::SeedPoint;
}
}
}
}
void meshFIM::InitializeActivePoints() {
if (!m_SeedPoints.empty()) {
int ns = m_SeedPoints.size();
std::vector<index> nb;
for (int s = 0; s < ns; s++) {
nb = m_meshPtr->neighbors[m_SeedPoints[s]];
for (int i = 0; i < nb.size(); i++) {
if (m_Label[nb[i]] != SeedPoint) {
m_ActivePoints.push_back(nb[i]);
m_Label[nb[i]] = ActivePoint;
}
}
}
}
}
float meshFIM::PointLength(point v) {
float length = 0;
for (int i = 0; i < 3; i++) {
length += v[i] * v[i];
}
return sqrt(length);
}
// FIM: check angle for at a given vertex, for a given face
bool meshFIM::IsNonObtuse(int v, TriMesh::Face f) {
int iV = f.indexof(v);
point A = m_meshPtr->vertices[v];
point B = m_meshPtr->vertices[f[(iV + 1) % 3]];
point C = m_meshPtr->vertices[f[(iV + 2) % 3]];
float a = trimesh::dist(B, C);
float b = trimesh::dist(A, C);
float c = trimesh::dist(A, B);
float angA = 0.0; /* = acos( (b*b + c*c - a*a) / (2*b*c) )*/
if ((a > 0) && (b > 0) && (c > 0))// Manasi stack overflow
{// Manasi stack overflow
angA = acos((b * b + c * c - a * a) / (2 * b * c));// Manasi stack overflow
}// Manasi stack overflow
return (angA < M_PI / 2.0f);
}
// FIM: given a vertex, find an all-acute neighborhood of faces
void meshFIM::SplitFace(std::vector<TriMesh::Face> &acFaces, int v, TriMesh::Face cf, int nfAdj/*, int currentVert*/) {
// get all the four vertices in order
/* v1 v4
+-------+
\ . \
\ . \
\ . \
+-------+
v2 v3 */
int iV = cf.indexof(v); // get index of v in terms of cf
int v1 = v;
int v2 = cf[(iV + 1) % 3];
int v4 = cf[(iV + 2) % 3];
iV = m_meshPtr->faces[nfAdj].indexof(v2); // get index of v in terms of adjacent face
int v3 = m_meshPtr->faces[nfAdj][(iV + 1) % 3];
// create faces (v1,v3,v4) and (v1,v2,v3), check angle at v1
TriMesh::Face f11(v1, v3, v4);
TriMesh::Face f22(v1, v2, v3);
std::vector<TriMesh::Face> f1f2;
f1f2.push_back(f11);
f1f2.push_back(f22);
for (int i = 0; i < f1f2.size(); i++) {
TriMesh::Face face = f1f2[i];
if (IsNonObtuse(v, face)) {
acFaces.push_back(face);
}
else {
int nfAdj_new = m_meshPtr->across_edge[nfAdj][m_meshPtr->faces[nfAdj].indexof(v2)];
if (nfAdj_new > -1) {
SplitFace(acFaces, v, face, nfAdj_new/*, currentVert*/);
}
else {
//printf("NO cross edge!!! Maybe a hole!!\n");
}
}
}
}
std::vector<TriMesh::Face> meshFIM::GetOneRing(int v/*, int currentVert*/) {
if (m_meshPtr->across_edge.empty())
m_meshPtr->need_across_edge();
// variables required
std::vector<TriMesh::Face> oneRingFaces;
std::vector<TriMesh::Face> t_faces;
// get adjacent faces
int naf = m_meshPtr->adjacentfaces[v].size();
if (!naf) {
std::cout << "vertex " << v << " has 0 adjacent faces..." << std::endl;
}
else {
for (int af = 0; af < naf; af++) {
TriMesh::Face cf = m_meshPtr->faces[m_meshPtr->adjacentfaces[v][af]];
t_faces.clear();
if (IsNonObtuse(v, cf))// check angle: if non-obtuse, return existing face
{
t_faces.push_back(cf);
}
else {
//t_faces.push_back(cf);
int nfae = m_meshPtr->across_edge[m_meshPtr->adjacentfaces[v][af]][cf.indexof(v)];
if (nfae > -1) {
SplitFace(t_faces, v, cf, nfae/*,currentVert*/);// if obtuse, split face till we get all acute angles
}
else {
//printf("NO cross edge!!! Maybe a hole!!\n");
}
}
for (int tf = 0; tf < t_faces.size(); tf++) {
oneRingFaces.push_back(t_faces[tf]);
}
}
}
return oneRingFaces;
}
float meshFIM::LocalSolver(index vet, TriMesh::Face triangle, index currentVert) {
float a, b, delta, cosA, lamda1, lamda2, TC1, TC2;
float TAB, TA, TB, TC;
int A, B, C;
float squareAB;
float LenAB, LenBC, LenAC, LenCD, LenAD;
float EdgeTA, EdgeTB;
float speedInv;
switch (speedType) {
case CURVATURE:
speedInv = (abs_curv[triangle[0]] +
abs_curv[triangle[1]] +
abs_curv[triangle[2]]) / 3.0;
break;
case ONE:
default:
speedInv = 1.0;
break;
}
float speedI;
if (speedType == CURVATURE) {
speedI = 100 * speedInv;
}
else {
speedI = speedInv;
}
C = triangle.indexof(vet);
A = (C + 1) % 3;
B = (A + 1) % 3;
TC1 = LARGENUM;
TC2 = LARGENUM;
TA = this->geodesic[triangle[A]];
TB = this->geodesic[triangle[B]];
TC = this->geodesic[triangle[C]];
TAB = TB - TA;
vec3 edge01 = ( vec3) (m_meshPtr->vertices[triangle[1]] - m_meshPtr->vertices[triangle[0]]);
vec3 edge12 = ( vec3) (m_meshPtr->vertices[triangle[2]] - m_meshPtr->vertices[triangle[1]]);
vec3 edge20 = ( vec3) (m_meshPtr->vertices[triangle[0]] - m_meshPtr->vertices[triangle[2]]);
vec3 edgeLengths;
edgeLengths[0] = sqrt(edge01[0] * edge01[0] + edge01[1] * edge01[1] + edge01[2] * edge01[2]);
edgeLengths[1] = sqrt(edge12[0] * edge12[0] + edge12[1] * edge12[1] + edge12[2] * edge12[2]);
edgeLengths[2] = sqrt(edge20[0] * edge20[0] + edge20[1] * edge20[1] + edge20[2] * edge20[2]);
LenAB = edgeLengths[A];
LenBC = edgeLengths[B];
LenAC = edgeLengths[C];
a = (speedI * speedI * LenAB * LenAB - TAB * TAB) * LenAB * LenAB;
EdgeTA = TA /*oldValues1 */ + LenAC /*s_triMem[tx*TRIMEMLENGTH + 0]*/ * speedI;
EdgeTB = TB /*oldValues2*/ + LenBC /*s_triMem[tx*TRIMEMLENGTH + 2]*/ * speedI;
if (a > 0) {
cosA = (LenAC * LenAC + LenAB * LenAB - LenBC * LenBC) / (2 * LenAC * LenAB);
b = 2 * LenAB * LenAC * cosA * (TAB * TAB - speedI * speedI * LenAB * LenAB);
delta = 4 * LenAC * LenAC * a * TAB * TAB * (1 - cosA * cosA);
lamda1 = (-b + sqrt(delta)) / (2 * a);
lamda2 = (-b - sqrt(delta)) / (2 * a);
if (lamda1 >= 0 && lamda1 <= 1) {
LenAD = lamda1 * LenAB;
LenCD = sqrt(LenAC * LenAC + LenAD * LenAD - 2 * LenAC * LenAD * cosA);
TC1 = lamda1 * TAB + TA + LenCD * speedI;
}
if (lamda2 >= 0 && lamda2 <= 1) {
LenAD = lamda2 * LenAB;
LenCD = sqrt(LenAC * LenAC + LenAD * LenAD - 2 * LenAC * LenAD * cosA);
TC2 = lamda2 * TAB + TA + LenCD * speedI;
}
TC = MIN(TC, MIN(TC2, MIN(TC1, MIN(EdgeTA, EdgeTB))));
}
else {
TC = MIN(TC, MIN(EdgeTA, EdgeTB));
}
return TC;
}
float meshFIM::Upwind(index currentVert,index vet)
{
float result=LARGENUM;
float tmp;
std::vector<TriMesh::Face> neighborFaces = this->GetOneRing(vet/*, currentVert*/);
// WAS THIS LINE BELOW ON Nov17 - Change Back when GetOneRing works for speed!
//vector<TriMesh::Face> neighborFaces = m_meshPtr->vertOneringFaces[vet];
//vector<int> neighborFaces = m_meshPtr->adjacentfaces[vet];
int i;
for (i = 0; i < neighborFaces.size(); i++)
{
tmp = LocalSolver(vet, neighborFaces[i], currentVert);
//tmp = LocalSolver(vet, m_meshPtr->faces[neighborFaces[i]], currentVert);
NumComputation++;
result = MIN(result,tmp );
//m_meshPtr->vertT[currentVert][vet] = result;
}
return result;
}
// FIM: initialize attributes
void meshFIM::InitializeAttributes(int currentVert, std::vector<int> seeds = std::vector<int>()) {
for (int v = 0; v < m_meshPtr->vertices.size(); v++) {
this->geodesic.push_back(LARGENUM);
}
// initialize seed points if present...
for (int s = 0; s < seeds.size(); s++) {
this->geodesic[seeds[s]] = 0;
}
// pre-compute faces, normals, and other per-vertex properties that may be needed
m_meshPtr->need_neighbors();
m_meshPtr->need_normals();
m_meshPtr->need_adjacentfaces();
m_meshPtr->need_across_edge();
m_meshPtr->need_faces();
}
// FIM: Remove data lingering from computation
void meshFIM::CleanupAttributes() {
this->geodesic.clear();
}
void meshFIM::GenerateReducedData() {
std::list<index>::iterator iter = m_ActivePoints.begin();
float oldT1, newT1, oldT2, newT2;
index tmpIndex1, tmpIndex2;
std::vector<int> nb;
NumComputation = 0;
double total_duration = 0;
clock_t starttime, endtime;
starttime = clock();
char c;
int i = 0;
for (int currentVert = 0; currentVert < m_meshPtr->vertices.size(); currentVert++) {
std::vector<int> seedPointList(1, currentVert);
SetSeedPoint(seedPointList);
this->InitializeAttributes(currentVert, m_SeedPoints);
InitializeLabels();
InitializeActivePoints();
while (!m_ActivePoints.empty()) {
iter = m_ActivePoints.begin();
while (iter != m_ActivePoints.end()) {
tmpIndex1 = *iter;
nb = m_meshPtr->neighbors[tmpIndex1];
oldT1 = this->geodesic[tmpIndex1];
newT1 = Upwind(currentVert, tmpIndex1);
if (abs(oldT1 - newT1) < _EPS) //if converges
{
if (oldT1 > newT1) {
this->geodesic[tmpIndex1] = newT1;
}
if (this->geodesic[tmpIndex1] < m_StopDistance) {
for (i = 0; i < nb.size(); i++) {
tmpIndex2 = nb[i];
if (m_Label[tmpIndex2] == AlivePoint || m_Label[tmpIndex2] == FarPoint) {
oldT2 = this->geodesic[tmpIndex2];
newT2 = Upwind(currentVert, tmpIndex2);
if (oldT2 > newT2) {
this->geodesic[tmpIndex2] = newT2;
if (m_Label[tmpIndex2] != ActivePoint) {
m_ActivePoints.insert(iter, tmpIndex2);
m_Label[tmpIndex2] = ActivePoint;
}
}
}
}
}
iter = m_ActivePoints.erase(iter);
m_Label[tmpIndex1] = AlivePoint;
}
else // if not converge
{
if (newT1 < oldT1) {
this->geodesic[tmpIndex1] = newT1;
}
iter++;
}
}
}
// Loop Through And Copy Only Values < than m_StopDistance
int nv = m_meshPtr->vertices.size();
for (int v = 0; v < currentVert; v++) {
if ((this->geodesic[v] <= m_StopDistance) && (this->geodesic[v] > 0)) {
//m_meshPtr->geoMap[currentVert][v] = m_meshPtr->geodesic[v];
//(*(m_meshPtr->dMap))[currentVert].push_back(m_meshPtr->geodesic[v]);
//(*(m_meshPtr->iMap))[currentVert].push_back(v);
(this->geodesicMap[currentVert])[v] = this->geodesic[v];
}
}
// Now Erase the duplicate data
this->CleanupAttributes();
endtime = clock();
total_duration = ( double) (endtime - starttime) / CLOCKS_PER_SEC;
float percent = (currentVert + 1) / ( float) m_meshPtr->vertices.size();
double total_time = total_duration / percent;
double time_left = total_time - total_duration;
int hours = ( int) (time_left / (60 * 60));
int minutes = ( int) ((time_left - hours * 60 * 60) / 60);
int seconds = ( int) (time_left - hours * 60 * 60 - minutes * 60);
int count = (this->geodesicMap[currentVert]).size();
}
}
// SHIREEN - modified the loading to control the generation of geo files (till we add the geo repulsion stuff)
void meshFIM::loadGeodesicFile(TriMesh *mesh, const char *geoFileName)
{
// cout << "Looking for file: " << geoFileName << " ... " << flush;
std::ifstream infile(geoFileName, std::ios::binary);
if (!infile.is_open())
{
if(GENERATE_GEO_FILES == 1)
{
// cout << "File Not Found, will generate the geo file now ..." << endl;
int numVert = mesh->vertices.size();
this->geodesicMap.resize(numVert);
this->computeFIM(mesh,geoFileName);
}
// else
// cout << "File Not Found and geo file generation is DISABLED ..." << endl;
}
else
{
int numVert = mesh->vertices.size();
//mesh->geoMap.resize(numVert);
//mesh->geoIndex.resize(numVert);
this->geodesicMap.resize(numVert);
// read stop distance
float distance;
infile.read(reinterpret_cast<char *>(&distance), sizeof(float));
this->SetStopDistance(distance);
// loop over vertices
for (int i = 0; i < numVert; i++)
{
// read map size for vertex
unsigned int dLength;
infile.read( reinterpret_cast<char *>(&dLength), sizeof(unsigned int) );
// read key and distance pair
for (int j = 0; j < dLength; j++)
{
unsigned int index;
infile.read( reinterpret_cast<char *>(&index), sizeof(unsigned int) );
float dist;
infile.read( reinterpret_cast<char *>(&dist), sizeof(float) );
(this->geodesicMap[i])[index] = dist;
}
}
infile.close();
}
}
// end SHIREEN
//Praful
void meshFIM::computeCoordXFiles(TriMesh *mesh, const char *vertT_filename)
{
unsigned int numVert = mesh->vertices.size();
this->SetMesh(mesh);
std::ofstream outfile(vertT_filename, std::ios::binary);
std::cout << "# vertices in mesh: " << numVert << std::endl;
outfile.write( reinterpret_cast<char *>(&numVert), sizeof(unsigned int) );
// loop over each vertex
for (int i = 0; i < numVert; i++)
{
float coordVal = mesh->vertices[i][0];
outfile.write( reinterpret_cast<char *>(&coordVal), sizeof(float) );
}
outfile.close();
}
void meshFIM::computeCoordYFiles(TriMesh *mesh, const char *vertT_filename)
{
unsigned int numVert = mesh->vertices.size();
this->SetMesh(mesh);
std::ofstream outfile(vertT_filename, std::ios::binary);
std::cout << "# vertices in mesh: " << numVert << std::endl;
outfile.write( reinterpret_cast<char *>(&numVert), sizeof(unsigned int) );
// loop over each vertex
for (int i = 0; i < numVert; i++)
{
float coordVal = mesh->vertices[i][1];
outfile.write( reinterpret_cast<char *>(&coordVal), sizeof(float) );
}
outfile.close();
}
void meshFIM::computeCoordZFiles(TriMesh *mesh, const char *vertT_filename)
{
unsigned int numVert = mesh->vertices.size();
this->SetMesh(mesh);
std::ofstream outfile(vertT_filename, std::ios::binary);
std::cout << "# vertices in mesh: " << numVert << std::endl;
outfile.write( reinterpret_cast<char *>(&numVert), sizeof(unsigned int) );
// loop over each vertex
for (int i = 0; i < numVert; i++)
{
float coordVal = mesh->vertices[i][2];
outfile.write( reinterpret_cast<char *>(&coordVal), sizeof(float) );
}
outfile.close();
}
void meshFIM::computeCurvFiles(TriMesh *mesh, const char *vertT_filename)
{
unsigned int numVert = mesh->vertices.size();
this->SetMesh(mesh);
std::ofstream outfile(vertT_filename, std::ios::binary);
std::cout << "# vertices in mesh: " << numVert << std::endl;
outfile.write( reinterpret_cast<char *>(&numVert), sizeof(unsigned int) );
// loop over each vertex
for (int i = 0; i < numVert; i++)
{
float absCurvVal = this->abs_curv[i];
outfile.write( reinterpret_cast<char *>(&absCurvVal), sizeof(float) );
}
outfile.close();
}
//end Praful
void meshFIM::computeFIM(TriMesh *mesh, const char *vertT_filename)
{
std::cout << "Trying to load: " << vertT_filename << std::endl;
// FILE* vertTFile = fopen(vertT_filename, "r+");
std::ifstream infile(vertT_filename, std::ios::binary);
unsigned int numVert = mesh->vertices.size();
//(mesh->dMap)->resize(numVert);
//(mesh->iMap)->resize(numVert);
this->geodesicMap.resize(numVert);
this->SetMesh(mesh);
if (!infile.is_open())
{
//vertTFile = fopen(vertT_filename, "w+");
// ofstream outfile(vertT_filename, std::ios::binary);
std::ofstream outfile(vertT_filename, std::ofstream::out);
std::cout << "No vertT file!!!\n Writing..." << std::endl;
std::cout << "stop distance = " << this->GetStopDistance() << std::endl;
std::cout << "# vertices in mesh: " << numVert << std::endl;
this->GenerateReducedData();
// write stop distance
float dStop = this->GetStopDistance();
// outfile.write( reinterpret_cast<char *>(&dStop), sizeof(float) );
// loop over each vertex
for (int i = 0; i < numVert; i++)
{
// write map size for vertex
unsigned int dLength = this->geodesicMap[i].size();
// outfile.write( reinterpret_cast<char *>(&dLength), sizeof(unsigned int) );
// write key and distance pair
for (std::map<unsigned int,float>::iterator it= this->geodesicMap[i].begin(); it != this->geodesicMap[i].end(); it++)
{
unsigned int index = (*it).first;
// outfile.write( reinterpret_cast<char *>(&index), sizeof(unsigned int) );
float dist = (*it).second;
// outfile.write( reinterpret_cast<char *>(&dist), sizeof(float) );
outfile << i << " " << index << " " << dist << std::endl;
}
}
//// First Line In File Is Stop Distance
//outfile << this->GetStopDistance() * s << endl;
//// Loop Over Each Vertex
//for (int i = 0; i < numVert; i++)
//{
// std::map<unsigned int,unsigned int>::iterator mIter;
//
// for(mIter = mesh->geodesicMap[i].begin(); mIter != mesh->geodesicMap[i].end(); mIter++)
// {
// outfile << (*mIter).first << " " << (*mIter).second << " ";
// }
// outfile << endl;
//}
outfile.close();
}
else
{
// read stop distance
float distance;
infile.read(reinterpret_cast<char *>(&distance), sizeof(float));
this->SetStopDistance(distance);
// loop over vertices
for (int i = 0; i < numVert; i++)
{
// read map size for vertex
unsigned int dLength;
infile.read( reinterpret_cast<char *>(&dLength), sizeof(unsigned int) );
// read key and distance pair
for (int j = 0; j < dLength; j++)
{
unsigned int index;
infile.read( reinterpret_cast<char *>(&index), sizeof(unsigned int) );
float dist;
infile.read( reinterpret_cast<char *>(&dist), sizeof(float) );
(this->geodesicMap[i])[index] = dist;
}
}
//unsigned int vertex;
//unsigned int distance;
//string line;
//// First Line In File Is Stop Distance
//getline(infile, line);
//stringstream str(line);
//str >> distance;
//
//this->SetStopDistance((float)distance/(float)s);
// cout << "Loading " << vertT_filename << endl;
//for(int i=0; i < numVert; i++){
//
// string line;
// getline(infile, line);
// stringstream str(line);
//
// str >> vertex >> distance;
// while(!str.eof())
// {
// //mesh->geoMap[i].push_back(distance);
// //mesh->geoIndex[i].push_back(vertex);
// (mesh->geodesicMap[i])[vertex] = distance;
// str >> vertex >> distance;
// }
// //printf("\r \r");
// //printf("progress %.1f%%", (i+1.0f)/(numVert)*100);
// //fflush(stdout);
//
//}
//cout << endl;
infile.close();
}
}
void meshFIM::physicalPointToXYZ(point x, VoxelIndexType *imageX, float imageOrigin[3], float imageSpacing[3]) {
imageX[0] = static_cast<VoxelIndexType> ((x[0] - imageOrigin[0]) / imageSpacing[0]);
imageX[1] = static_cast<VoxelIndexType> ((x[1] - imageOrigin[1]) / imageSpacing[1]);
imageX[2] = static_cast<VoxelIndexType> ((x[2] - imageOrigin[2]) / imageSpacing[2]);
}
meshFIM::VoxelIndexType meshFIM::indexToLinearIndex(VoxelIndexType *imageX, int imageSize[3]) {
VoxelIndexType linearIndX = imageX[0] + imageX[1] * imageSize[0] + imageX[2] * imageSize[0] * imageSize[1];
return linearIndX;
}
meshFIM::VoxelIndexType meshFIM::physicalPointToLinearIndex(point x) {
VoxelIndexType imageX[3];
this->physicalPointToXYZ(x, imageX, this->imageOrigin, this->imageSpacing);
VoxelIndexType linearIndX = this->indexToLinearIndex(imageX, this->imageSize);
return linearIndX;
}
meshFIM::VoxelIndexType meshFIM::physicalPointToLinearIndex(point x, float imageOrigin[3], float imageSpacing[3], int imageSize[3]) {
VoxelIndexType imageX[3];
this->physicalPointToXYZ(x, imageX, imageOrigin, imageSpacing);
VoxelIndexType linearIndX = this->indexToLinearIndex(imageX, imageSize);
return linearIndX;
}
/* Prateep
* http://www.geometrictools.com/Documentation/DistancePoint3Triangle3.pdf
* ^t
* \ |
* \reg2|
* \ |
* \ |
* \ |
* \|
* *P2
* |\
* | \
* reg3 | \ reg1
* | \
* |reg0\
* | \
* | \ P1
* -------*-------*------->s
* |P0 \
* reg4 | reg5 \ reg6
*/
double meshFIM::pointTriangleDistance(point P, TriMesh::Face face, point &PP) {
// rewrite vertices in normal form
point B = m_meshPtr->vertices[face[0]];
point E0 = m_meshPtr->vertices[face[1]] - B;
point E1 = m_meshPtr->vertices[face[2]] - B;
point D = B - P;
float a = E0 DOT E0;
float b = E0 DOT E1;
float c = E1 DOT E1;
float d = E0 DOT D;
float e = E1 DOT D;
float f = D DOT D;
float det = a * c - b * b;
float s = b * e - c * d;
float t = b * d - a * e;
float distSqr = 0.0f;
if (s + t <= det) {
if (s < 0) {
if (t < 0) {
// region 4
if (d < 0) {
t = 0;
if (-d >= a) {
s = 1.0;
distSqr = a + 2.0f * d + f;
}
else {
s = -d / a;
distSqr = d * s + f;
}
}
else {
s = 0.0f;
if (e >= 0.0f) {
t = 0.0f;
distSqr = f;
}
else {
if (-e >= c) {
t = 1.0f;
distSqr = c + 2.0f * e + f;
}
else {
t = -e / c;
distSqr = e * t + f;
}
}
} // end of region 4
}
else {
// region 3
s = 0.0f;
if (e >= 0.0f) {
t = 0.0f;
distSqr = f;
}
else {
if (-e >= c) {
t = 1.0f;
distSqr = c + 2.0f * e + f;
}
else {
t = -e / c;
distSqr = e * t + f;
}
}
} // end of region 3
}
else {
if (t < 0.0f) {
// region 5
t = 0.0f;
if (d >= 0.0f) {
s = 0.0f;
distSqr = f;
}
else {
if (-d >= a) {
s = 1.0f;
distSqr = a + 2 * d + f;
}
else {
s = -d / a;
distSqr = d * s + f;
}
}
// end of region 5
}
else {
// region 0
float invDet = 1.0f / det;
s *= invDet;
t *= invDet;
distSqr = s * (a * s + b * t + 2 * d) + t * (b * s + c * t + 2 * e) + f;
// end of region 0
}
}
}
else {
if (s < 0.0f) {
// region 2
float tmp0 = b + d;
float tmp1 = c + e;
if (tmp1 > tmp0) {
float numer = tmp1 - tmp0;
float denom = a - 2 * b + c;
if (numer >= denom) {
s = 1.0f;
t = 0.0f;
distSqr = a + 2 * d + f;
}
else {
s = numer / denom;
t = 1.0 - s;
distSqr = s * (a * s + b * t + 2 * d) + t * (b * s + c * t + 2 * e) + f;
}
}
else {
s = 0.0f;
if (tmp1 <= 0.0f) {
t = 1.0f;
distSqr = c + 2 * e + f;
}
else {
if (e >= 0.0f) {
t = 0.0f;
distSqr = f;
}
else {
t = -e / c;
distSqr = e * t + f;
}
}
}
// end of region 2
}
else {
if (t < 0) {
// region 6
float tmp0 = b + e;
float tmp1 = a + d;
if (tmp1 > tmp0) {
float numer = tmp1 - tmp0;
float denom = a - 2 * b + c;
if (numer >= denom) {
t = 1.0f;
s = 0.0f;
distSqr = c + 2 * e + f;
}
else {
t = numer / denom;
s = 1.0 - t;
distSqr = s * (a * s + b * t + 2 * d) + t * (b * s + c * t + 2 * e) + f;
}
}
else {
t = 0.0f;
if (tmp1 <= 0.0f) {
s = 1.0f;
distSqr = a + 2 * d + f;
}
else {
if (d >= 0.0f) {
s = 0.0f;
distSqr = f;
}
else {
s = -d / a;
distSqr = d * s + f;
}
}
}
// end of region 6
}
else {
// region 1
float numer = c + e - b - d;
if (numer <= 0) {
s = 0.0f;
t = 1.0f;
distSqr = c + 2 * e + f;
}
else {
float denom = a - 2 * b + c;
if (numer >= denom) {
s = 1.0f;
t = 0.0f;
distSqr = a + 2 * d + f;
}
else {
s = numer / denom;
t = 1.0f - s;
distSqr = s * (a * s + b * t + 2 * d) + t * (b * s + c * t + 2 * e) + f;
}
}
// end of region 1
}
}
}
if (distSqr < 0.0f) distSqr = 0.0f;
float dist = std::sqrt(distSqr);
PP = B + s * E0 + t * E1;
return dist;
}
vec3 meshFIM::ComputeBarycentricCoordinates(point p, TriMesh::Face f) {
vec3 bCoords; bCoords.clear();
point a, b, c;
a = m_meshPtr->vertices[f[0]];
b = m_meshPtr->vertices[f[1]];
c = m_meshPtr->vertices[f[2]];
point n = (b - a) CROSS(c - a);
normalize(n);
float area = ((b - a) CROSS(c - a)) DOT n;
float inv_area = 1.0f / (area + EPS);
// shireen
bCoords[0] = (((c - b) CROSS(p - b)) DOT n) * inv_area; // * areaInvPerTri[f];map <face, double> didnot work
bCoords[1] = (((a - c) CROSS(p - c)) DOT n) * inv_area; // * areaInvPerTri[f];map <face, double> didnot work
bCoords[2] = (((b - a) CROSS(p - a)) DOT n) * inv_area; // * areaInvPerTri[f];map <face, double> didnot work
float sum = bCoords.sum();
bCoords[0] /= sum;
bCoords[1] /= sum;
bCoords[2] /= sum;
return bCoords;
}
void meshFIM::need_maxedgelength() {
this->need_edge_lengths();
for (int f = 0; f < m_meshPtr->faces.size(); f++) {
for (int d = 0; d < 3; d++) {
if (this->edgeLengthsVector[f][d] >= maxEdgeLength) {
maxEdgeLength = this->edgeLengthsVector[f][d];
}
}
}
}
int meshFIM::FindNearestVertex(point pt) {
//std::cerr << "FindNearestVertexA\n";
if (!kd) {
kd = new KDtree(m_meshPtr->vertices);
}
//std::cerr << "FindNearestVertexB\n";
if (maxEdgeLength == 0.0) {
need_maxedgelength();
}
//std::cerr << "FindNearestVertexC\n";
const float *match = kd->closest_to_pt(pt, 100000.0 * maxEdgeLength * maxEdgeLength); // SHIREEN - enlargen the neighborhood size for kdtree to find a match
int imatch = 0;
if (!match) {
std::cout << "failed to find vertex within " << maxEdgeLength << " for point " << pt << ". using vertex 0" << std::endl;
return imatch;
}
//std::cerr << "FindNearestVertexD\n";
imatch = (match - (const float *) & (m_meshPtr->vertices[0][0])) / 3;
return imatch;
}
int meshFIM::GetTriangleInfoForPoint(point x, TriMesh::Face &triangleX, float &alphaX, float &betaX, float &gammaX) {
int faceID;
//std::cerr << "GetTriangleInfoForPoint\n";
if (this->faceIndexMap.size() > 0) // there is a generated face index map so used it
{
std::cerr << "Doing face index stuff\n";
// Physical point to Image Index
VoxelIndexType linearIndX = this->physicalPointToLinearIndex(x);
// collect face indices for this voxel
std::map<VoxelIndexType, std::vector<int> >::iterator it = this->faceIndexMap.find(linearIndX);
if (it != this->faceIndexMap.end()) // see if the linearIndX already exist in the face index map
{
// std::cout << "WOW, fids will be used ... \n" ;
std::vector<int> faceList = this->faceIndexMap[linearIndX];
double minDist = LARGENUM;
int winnerIndex;
for (std::vector<int>::iterator it = faceList.begin(); it != faceList.end(); ++it) {
triangleX = m_meshPtr->faces[(*it)];
// project the point onto the plane of the current triangle
point projPoint;
double dist = this->pointTriangleDistance(x, triangleX, projPoint);
if (dist < minDist) {
minDist = dist;
winnerIndex = (*it);
}
}
triangleX = m_meshPtr->faces[winnerIndex];
faceID = winnerIndex;
point projPoint;
double dist = this->pointTriangleDistance(x, triangleX, projPoint);
vec3 barycentric = this->ComputeBarycentricCoordinates(projPoint, triangleX);
alphaX = barycentric[0];
betaX = barycentric[1];
gammaX = barycentric[2];
return faceID;
}
}
#if SHOW_WARNING
std::cerr << "warning: using kdtree for triangle info because there is no face index map !!! ...\n";
#endif
//std::cerr << "warning: using kdtree for triangle info because there is no face index map !!! ...\n";
// get vertex closest to first point - x
int vertX = this->FindNearestVertex(x);
//std::cerr << "FindNearestVertex finished\n";
unsigned int fNumber;
// scan all adjacent faces to see which face (f) includes point x
triangleX = m_meshPtr->faces[m_meshPtr->adjacentfaces[vertX][0]];
faceID = m_meshPtr->adjacentfaces[vertX][0];
for (fNumber = 0; fNumber < m_meshPtr->adjacentfaces[vertX].size(); fNumber++) {
// check if face contains x and store barycentric coordinates for x in face f
triangleX = m_meshPtr->faces[m_meshPtr->adjacentfaces[vertX][fNumber]];
faceID = m_meshPtr->adjacentfaces[vertX][fNumber];
vec3 barycentric = this->ComputeBarycentricCoordinates(x, triangleX);
alphaX = barycentric[0];
betaX = barycentric[1];
gammaX = barycentric[2];
if (((barycentric[0] >= 0) && (barycentric[0] <= 1)) &&
((barycentric[1] >= 0) && (barycentric[1] <= 1)) &&
((barycentric[2] >= 0) && (barycentric[2] <= 1))) {
fNumber = m_meshPtr->adjacentfaces[vertX].size();
}
}
if (alphaX < 0.0 || betaX < 0.0f || gammaX < 0.0f) {
int t = 0;
}
return faceID;
}
float meshFIM::GetVirtualSource(vnl_vector<float> baryCoord, vnl_matrix<float> X, vnl_vector<float> ds, vnl_vector< float > &x0) {
// vcl_cout<<"X:"<<std::endl<<X.extract(2,3,0,0);
// vcl_cout<<"ds: "<<ds<<std::endl;
vgl_homg_point_2d<float> centre1(X(0, 0), X(1, 0), 1);
vgl_homg_point_2d<float> centre2(X(0, 1), X(1, 1), 1);
vgl_homg_point_2d<float> centre3(X(0, 2), X(1, 2), 1);
vgl_conic<float> circle1(centre1, ds[0], ds[0], 0.0f);
vgl_conic<float> circle2(centre2, ds[1], ds[1], 0.0f);
vgl_conic<float> circle3(centre3, ds[2], ds[2], 0.0f);
// vcl_cout<<"Circle1: "<<circle1<<std::endl;
// vcl_cout<<"Circle2: "<<circle2<<std::endl;
// vcl_cout<<"Circle3: "<<circle3<<std::endl;
vcl_list<vgl_homg_point_2d<float> > pts1;
pts1 = vgl_homg_operators_2d<float>::intersection(circle1, circle2);
int n1 = ( int) (pts1.size());
vcl_list<vgl_homg_point_2d<float> > pts2;
pts2 = vgl_homg_operators_2d<float>::intersection(circle2, circle3);
int n2 = ( int) (pts2.size());
vcl_list<vgl_homg_point_2d<float> > pts3;
pts3 = vgl_homg_operators_2d<float>::intersection(circle1, circle3);
int n3 = ( int) (pts3.size());
int n = n1 + n2 + n3;
// std::cout<<"n= "<<n<<std::endl;
if (n == 0) {
x0 = vnl_vector<float>(2, -1.0f);
return -1.0f;
}
else {
vnl_matrix< float > xinit(2, n, 0);
int i = 0;
typedef vcl_list< vgl_homg_point_2d < float > > container;
vgl_homg_point_2d<float> temp;
for (container::iterator p = pts1.begin(); p != pts1.end(); p++) {
// std::cout<<"n1 = "<<n1<<std::endl;
temp = *p;
if (!std::isfinite(temp.x()) || !std::isfinite(temp.y()) || !std::isfinite(temp.w())) continue;
// std::cout<<"x: "<<temp.x()<<" y: "<<temp.y()<<" w: "<<temp.w()<<std::endl;
xinit(0, i) = temp.x() / temp.w();
xinit(1, i) = temp.y() / temp.w();
// vcl_cout<<"i= "<<i<<" xinit(i)="<<xinit.get_column(i)<<std::endl;
i++;
}
for (container::iterator p = pts2.begin(); p != pts2.end(); p++) {
// std::cout<<"n2 = "<<n2<<std::endl;
temp = *p;
if (!std::isfinite(temp.x()) || !std::isfinite(temp.y()) || !std::isfinite(temp.w())) continue;
// std::cout<<"x: "<<temp.x()<<" y: "<<temp.y()<<" w: "<<temp.w()<<std::endl;
xinit(0, i) = temp.x() / temp.w();
xinit(1, i) = temp.y() / temp.w();
// vcl_cout<<"i= "<<i<<" xinit(i)="<<xinit.get_column(i)<<std::endl;
i++;
}
for (container::iterator p = pts3.begin(); p != pts3.end(); p++) {
// std::cout<<"n3 = "<<n3<<std::endl;
temp = *p;
if (!std::isfinite(temp.x()) || !std::isfinite(temp.y()) || !std::isfinite(temp.w())) continue;
// std::cout<<"x: "<<temp.x()<<" y: "<<temp.y()<<" w: "<<temp.w()<<std::endl;
xinit(0, i) = temp.x() / temp.w();
xinit(1, i) = temp.y() / temp.w();
// vcl_cout<<"i= "<<i<<" xinit(i)="<<xinit.get_column(i)<<std::endl;
i++;
}
if (i == 0) {
x0 = vnl_vector<float>(2, -1.0f);
return -1.0f;
}
// vcl_cout<<"xinit:"<<std::endl<<xinit.extract(2,n,0,0)<<std::endl;
// vcl_cout<<"xinit:"<<std::endl<<xinit.extract(2,i,0,0)<<std::endl;
double minE = 10000000000.0;
int flag = 0;
int winner = -1;
for (int i1 = 0; i1 < i; i1++) {
double energy = 0.0;
vnl_vector<float> pt = xinit.get_column(i1);
// vcl_cout<<"pt= "<<pt<<std::endl;
for (int j = 0; j < 3; j++) {
vnl_vector<float> tmp1 = pt - X.get_column(j);
float residual = std::abs(tmp1.squared_magnitude() - ds[j] * ds[j]); //write the dot product in place of tmp1.*tmp1
energy += ( double) (residual * baryCoord[j]);
// float residual = tmp1.squared_magnitude() - ds[j]*ds[j]; //write the dot product in place of tmp1.*tmp1
// energy += (double)(residual*residual*baryCoord[j]);
}
// std::cout<<"Energy: "<<energy<<std::endl;
if (flag == 0) {
minE = energy;
winner = i1;
flag = 1;
}
else {
if (energy < minE) {
minE = energy;
winner = i1;
}
}
}
// std::cout<<winner<<std::endl;
x0 = xinit.get_column(winner);
// vcl_cout<<"x0: "<<x0<<std::endl;
return 1.0f;
}
}
namespace {
/* Praful */
float ComputeGradient(vnl_vector<float> x0, vnl_vector<float> baryCoord, vnl_matrix<float> X, vnl_vector<float> ds, vnl_vector<float> &G) {
G = vnl_vector<float>(2, 0.0f);
for (int k = 0; k < 2; k++) {
for (int ii = 0; ii < 3; ii++) {
vnl_vector<float> xi = X.get_column(ii);
vnl_vector<float> tmp = x0 - xi;
float residual = dot_product(tmp, tmp) - ds[ii] * ds[ii];
G[k] += 4 * baryCoord[ii] * residual * tmp[k];
}
}
return 1.0f;
}
/* Praful */
float ComputeHessian(vnl_vector<float> x0, vnl_vector<float> baryCoord, vnl_matrix<float> X, vnl_vector<float> ds, vnl_matrix<float> &H) {
H = vnl_matrix<float>(2, 2, 0.0f);
for (int k = 0; k < 2; k++) {
for (int kp = 0; kp < 2; kp++) {
for (int ii = 0; ii < 3; ii++) {
vnl_vector<float> xi = X.get_column(ii);
vnl_vector<float> tmp = x0 - xi;
float residual = dot_product(tmp, tmp) - ds[ii] * ds[ii];
if (k == kp) {
H(k, k) += 4 * baryCoord[ii] * (residual + 2 * tmp[k] * tmp[k]);
}
else {
H(k, kp) += 8 * baryCoord[ii] * tmp[k] * tmp[kp];
}
}
}
}
return 1.0f;
}
}
float meshFIM::ComputeThreePointApproximatedGeodesic(vnl_vector<float> x, vnl_vector<float> baryCoord, vnl_matrix<float> X, vnl_vector<float> ds, char *method) {
float geo_approx = -1.0f;
vnl_vector<float> x0;
// std::cout<<"check4"<<std::endl;
float n = this->GetVirtualSource(baryCoord, X, ds, x0);
// std::cout<<"check5"<<std::endl;
char check2[] = "Bary";
if (n == -1.0f || strcmp(method, check2) == 0) {
// std::cout<<"Using Bary..."<<std::endl;
geo_approx = dot_product(baryCoord, ds);
}
else {
char check1[] = "Newton";
if (strcmp(method, check1) == 0) //Newton method
{
// std::cout<<"Using Newton iterations..."<<std::endl;
// vcl_cout<<"Initial x0= "<<x0<<std::endl;
float eta = 1.0f;
for (int iter = 0; iter < 10; iter++) {
vnl_matrix<float> H;
vnl_vector<float> G;
ComputeGradient(x0, baryCoord, X, ds, G);
ComputeHessian(x0, baryCoord, X, ds, H);
vnl_matrix<float> Hinv = vnl_matrix_inverse<float>(H);
x0 -= eta * Hinv * G;
}
// vcl_cout<<"Final x0= "<<x0<<std::endl;
}
else //LM method
{
// std::cout<<"LM..coming soon.."<<std::endl;
// std::cout<<"Using LM..."<<std::endl;
float v = 2.0f;
float eps1 = 0.000001f;
float eps2 = 0.000001f;
float tau = 0.001f;
int m = 3;
int n = 2;
float k = 0.0f;
float kmax = 10.0f;
// computing Jacobian
// vcl_cout<<"x0: "<<std::endl<<x0<<std::endl;
// vcl_cout<<"baryCoord: "<<std::endl<<baryCoord<<std::endl;
vnl_matrix<float> J(m, n, 0.0f);
for (int i = 0; i < m; i++) {
vnl_vector<float> xi = X.get_column(i);
// vcl_cout<<"xi: "<<std::endl<<xi<<std::endl;
for (int j = 0; j < n; j++) {
J(i, j) = 2.0f * ( float) (std::sqrt(baryCoord[i])) * (x0[j] - xi[j]);
}
}
// vcl_cout<<"J: "<<std::endl<<J.extract(m,n,0,0)<<std::endl;
// computing function values given the current guess
vnl_vector<float> f(m, 0.0f);
for (int i = 0; i < m; i++) {
vnl_vector<float> xi = X.get_column(i);
float di = ds[i];
vnl_vector<float> x0_m_xi;
x0_m_xi = x0 - xi;
float r_i = dot_product(x0_m_xi, x0_m_xi) - di * di;
f[i] = ( float) (std::sqrt(baryCoord[i])) * r_i;
}
float F;
F = dot_product(f, f);
F = 0.5f * F;
vnl_matrix<float> A(n, n, 0.0f);
A = J.transpose() * J;
vnl_vector<float> g(n, 0.0f);
g = J.transpose() * f;
vnl_vector<float> diagA = A.get_diagonal();
float max_diagA = diagA.max_value();
float mu = tau * max_diagA;
float norm_g = g.two_norm();
vnl_matrix<float> muId(n, n, 0.0f);
vnl_matrix<float> A_mu(n, n, 0.0f);
vnl_matrix<float> A_mu_inv;
vnl_vector<float> hlm(n, 0.0f);
vnl_vector<float> xnew(n, 0.0f);
vnl_vector<float> fnew(m, 0.0f);
float Fnew = 0.0f, delta_L = 0.0f, rho = 0.0f;
// std::cout<<"****************"<<std::endl;
bool found = norm_g <= eps1;
while (!found && k < kmax) {
k = k + 1.0f;
muId.set_identity();
muId = mu * muId;
A_mu = A + muId;
// std::cout<<"check4"<<std::endl;
// vcl_cout<<"A: "<<std::endl<<A.extract(n,n,0,0)<<std::endl;
// std::cout<<"mu: "<<mu<<std::endl;
// vcl_cout<<"A_mu: "<<std::endl<<A_mu.extract(n,n,0,0)<<std::endl;
A_mu_inv = vnl_matrix_inverse<float>(A_mu);
// std::cout<<"check51"<<std::endl;
// vcl_cout<<"A_mu_inv: "<<std::endl<<A_mu_inv.extract(n,n,0,0)<<std::endl;
A_mu_inv = -1.0f * A_mu_inv;
// vcl_cout<<"A_mu_inv: "<<std::endl<<A_mu_inv.extract(n,n,0,0)<<std::endl;
hlm = A_mu_inv * g;
float norm_hlm = hlm.two_norm();
float norm_x0 = x0.two_norm();
if (norm_hlm <= (eps1 * (norm_x0 + eps2))) {
found = true;
}
else {
xnew = x0 + hlm;
for (int i = 0; i < m; i++) {
vnl_vector<float> xi = X.get_column(i);
float di = ds[i];
vnl_vector<float> x_m_xi;
x_m_xi = xnew - xi;
float r_i = dot_product(x_m_xi, x_m_xi) - di * di;
fnew[i] = ( float) (std::sqrt(baryCoord[i])) * r_i;
}
Fnew = dot_product(fnew, fnew);
Fnew = 0.5f * Fnew;
delta_L = 0.5f * dot_product(hlm, (mu * hlm - g));
rho = (F - Fnew) / delta_L;
if (rho > 0.0f) {
x0 = xnew;
// computing Jacobian
for (int i = 0; i < m; i++) {
vnl_vector<float> xi = X.get_column(i);
for (int j = 0; j < n; j++) {
J(i, j) = 2.0f * ( float) (std::sqrt(baryCoord[i])) * (x0[j] - xi[j]);
}
}
// computing function values given the current guess
for (int i = 0; i < m; i++) {
vnl_vector<float> xi = X.get_column(i);
float di = ds[i];
vnl_vector<float> x0_m_xi;
x0_m_xi = x0 - xi;
float r_i = dot_product(x0_m_xi, x0_m_xi) - di * di;
f[i] = ( float) (std::sqrt(baryCoord[i])) * r_i;
}
F = dot_product(f, f);
F = 0.5f * F;
A = J.transpose() * J;
g = J.transpose() * f;
norm_g = g.two_norm();
found = norm_g <= eps1;
// std::cout<<"=================="<<std::endl;
// std::cout<<"mu= "<<mu<<std::endl;
// std::cout<<"=================="<<std::endl;
float cmp1 = 1.0f - (2.0f * rho - 1.0f) * (2.0f * rho - 1.0f) * (2.0f * rho - 1.0f);
if (0.3f > cmp1) {
mu = mu * 0.3f;
}
else {
mu = mu * cmp1;
}
// std::cout<<"=================="<<std::endl;
// std::cout<<"cmp1= "<<cmp1<<" mu= "<<mu<<std::endl;
// std::cout<<"=================="<<std::endl;
v = 2.0f;
}
else {
mu = mu * v;
v = 2.0f * v;
}
}
}
// vcl_cout<<x0<<std::endl;
}
geo_approx = (x0 - x).two_norm();
} //end else xinit not empty
// std::cout<<"Returning geo_approx..."<<geo_approx<<std::endl;
return geo_approx;
}
float meshFIM::ComputeCanonicalForm(point s, vnl_vector<float> &x, vnl_matrix<float> &X)//, Face S)
{
TriMesh::Face S;
float alpS, betS, gamS;
GetTriangleInfoForPoint(s, S, alpS, betS, gamS);
vnl_matrix<float> S_(3, 3);
vnl_vector<float> muS(3, 0);
for (int i = 0; i < 3; i++) {
point vertex = m_meshPtr->vertices[S[i]];
for (int j = 0; j < 3; j++) S_(i, j) = ( float) (vertex[j]);
}
// std::cout<<"*****************"<<std::endl;
// vcl_cout<<"Face: "<<std::endl<<S_.extract(3,3,0,0)<<std::endl;
// std::cout<<"*****************"<<std::endl;
S_ = S_.transpose();
// std::cout<<"*****************"<<std::endl;
// vcl_cout<<"Transposed: "<<std::endl<<S_.extract(3,3,0,0)<<std::endl;
// std::cout<<"*****************"<<std::endl;
for (int r = 0; r < 3; r++) {
for (int c = 0; c < 3; c++) muS[r] += S_(r, c);
muS[r] /= 3.0f;
}
// std::cout<<"*****************"<<std::endl;
// vcl_cout<<"muS: "<<std::endl<<muS<<std::endl;
// std::cout<<"*****************"<<std::endl;
// Scent = S - muS
vnl_matrix<float> Scent(3, 3);
for (int r = 0; r < 3; r++) {
for (int c = 0; c < 3; c++) Scent(r, c) = S_(r, c) - muS[r];
}
// vcl_cout<<"Scent: "<<Scent.extract(3,3,0,0)<<std::endl;
vnl_svd<float> svd(Scent);
// bool vld_svd = vnl_svd<float>::valid();
// std::cout<<"Valid SVD? "<<vld_svd<<std::endl;
// std::cout<<"checkpoint SVD"<<std::endl;
// vnl_diag_matrix<point::value_type> W_ = svd.W();
vnl_matrix<float> U_ = svd.U();
// vcl_cout<<"U_: "<<U_.extract(3,2,0,0)<<std::endl;
// std::cout<<"check32"<<std::endl;
// vnl_matrix<point::value_type> V_ = svd.V();
/* top 2 eigen vectors */
vnl_matrix<float> U(3, 2);
for (int r = 0; r < 3; r++) {
for (int c = 0; c < 2; c++) U(r, c) = U_(r, c);
}
// std::cout<<"............................"<<std::endl;
// vcl_cout<<"U: "<<U.extract(2,3,0,0)<<std::endl;
// std::cout<<"............................"<<std::endl;
/*vnl_matrix<point::value_type>*/ X = U.transpose() * Scent;
vnl_vector<float> sCent(3);
for (int c = 0; c < 3; c++) sCent[c] = s[c] - muS[c];
/*vnl_vector<point::value_type>*/ x = U.transpose() * sCent;
// std::cout<<"-----------------------------"<<std::endl;
// vcl_cout<<x<<std::endl;
// std::cout<<"-----------------------------"<<std::endl;
return 1.0f;
// printing for debugging
// std::cout<<std::endl<<std::endl<<"Canonical form computed..."<<std::endl;
// vcl_cerr<<x;
// std::cout<<std::endl;
// vcl_cerr<<X.extract(2,3,0,0);
}
float meshFIM::GetGeodesicDistance(int v1, int v2) {
float gDist = 0.000001f;
if (v1 == v2) return gDist;
int vert = v1;
int key = v2;
if (v2 > v1) {
vert = v2;
key = v1;
}
std::map<unsigned int, float>::iterator geoIter = this->geodesicMap[vert].find(key);
if (geoIter != this->geodesicMap[vert].end()) {
gDist = geoIter->second;
}
else {
gDist = LARGENUM;
}
return gDist;
}
float meshFIM::GetBronsteinGeodesicDistance(TriMesh::Face Sa, TriMesh::Face Sb, vnl_vector <float> baryCoord_a, vnl_vector <float> baryCoord_b, char *method) {
point a; a.clear();
point b; b.clear();
for (int d1 = 0; d1 < 3; d1++) {
a[d1] = 0.0;
b[d1] = 0.0;
for (int d2 = 0; d2 < 3; d2++) {
point vt = m_meshPtr->vertices[Sa[d2]];
a[d1] += baryCoord_a[d2] * vt[d1];
point vt2 = m_meshPtr->vertices[Sb[d2]];
b[d1] += baryCoord_b[d2] * vt2[d1];
}
}
float alp_a, alp_b, bet_a, bet_b, gam_a, gam_b;
alp_a = baryCoord_a[0];
bet_a = baryCoord_a[1];
gam_a = baryCoord_a[2];
alp_b = baryCoord_b[0];
bet_b = baryCoord_b[1];
gam_b = baryCoord_b[2];
if (alp_a < 0.000001f) {
alp_a = 0.000001f;
}
if (bet_a < 0.000001f) {
bet_a = 0.000001f;
}
if (gam_a < 0.000001f) {
gam_a = 0.000001f;
}
if (alp_b < 0.000001f) {
alp_b = 0.000001f;
}
if (bet_b < 0.000001f) {
bet_b = 0.000001f;
}
if (gam_b < 0.000001f) {
gam_b = 0.000001f;
}
alp_a /= (alp_a + bet_a + gam_a);
bet_a /= (alp_a + bet_a + gam_a);
gam_a /= (alp_a + bet_a + gam_a);
alp_b /= (alp_b + bet_b + gam_b);
bet_b /= (alp_b + bet_b + gam_b);
gam_b /= (alp_b + bet_b + gam_b);
baryCoord_a[0] = alp_a;
baryCoord_a[1] = bet_a;
baryCoord_a[2] = gam_a;
baryCoord_b[0] = alp_b;
baryCoord_b[1] = bet_b;
baryCoord_b[2] = gam_b;
vnl_vector<float> xA(2);
vnl_vector<float> xB(2);
vnl_matrix<float> Xa(2, 3);
vnl_matrix<float> Xb(2, 3);
if (baryCoord_a.max_value() > 1.0f || baryCoord_a.min_value() < 0.0f || baryCoord_b.max_value() > 1.0f || baryCoord_b.min_value() < 0.0f) {
std::cerr << "incorrect barycentric coordinates...!!" << std::endl;
std::cerr << "baryCoord_a: " << baryCoord_a << std::endl;
std::cerr << "baryCoord_b: " << baryCoord_b << std::endl;
return EXIT_FAILURE;
}
ComputeCanonicalForm(a, xA, Xa);
ComputeCanonicalForm(b, xB, Xb);
vnl_matrix<float> dA_2_B(3, 3);
bool tooFar = false;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
dA_2_B(i, j) = this->GetGeodesicDistance(Sa[i], Sb[j]);
// SHIREEN: if triangles are too far, don't bother to complete
if (dA_2_B(i, j) == LARGENUM) {
tooFar = true;
break;
}
}
if (tooFar)
break;
}
if (tooFar)
return LARGENUM;
vnl_vector<float> geo_approx_2_B(3);
for (int vertB_id = 0; vertB_id < 3; vertB_id++)
geo_approx_2_B[vertB_id] = ComputeThreePointApproximatedGeodesic(xA, baryCoord_a, Xa, dA_2_B.get_column(vertB_id), method);
float dGeo_a_2_b = 0.0f;
dGeo_a_2_b = ComputeThreePointApproximatedGeodesic(xB, baryCoord_b, Xb, geo_approx_2_B, method);
return dGeo_a_2_b;
}
// Praful - compute distance to landmarks based on geodesic approximation with given triangle info
void meshFIM::ComputeDistanceToLandmarksGivenTriangleInfo(TriMesh *mesh, const char *infilename , const char *outfilename)
{
// initialize the geodesic map to hold the geodesics from the triangle vertices of the given landmark to all other mesh vertices
SetStopDistance(1e7);
int numVert = mesh->vertices.size();
this->geodesicMap.resize(numVert);
SetMesh(mesh);
std::ifstream pointsFile(infilename);
std::ofstream outfile(outfilename);
if (!pointsFile)
{
std::cerr << "points file not found: " << infilename << std::endl;
}
int count = 0;
while(pointsFile)
{
point tmpPt; tmpPt.clear();
vnl_vector<float> baryCoords(3, 0.0);
int faceId;
for (int d=0; d<3; d++)
pointsFile >> tmpPt[d];
if (!pointsFile)
{
count--;
break;
}
pointsFile >> faceId;
if (!pointsFile)
{
count--;
break;
}
for (int d=0; d<3; d++)
pointsFile >> baryCoords[d];
if (!pointsFile)
{
count--;
break;
}
TriMesh::Face triangleX = mesh->faces[faceId];
std::vector<int> vertexIdlist;
vertexIdlist.clear();
vertexIdlist.push_back(triangleX[0]);
vertexIdlist.push_back(triangleX[1]);
vertexIdlist.push_back(triangleX[2]);
// update the geodesic map with geodesic distances from each triangle vertex to all other mesh vertices
UpdateGeodesicMapWithDistancesFromVertices(vertexIdlist);
std::cout << "Point# " << count++ << " fid: " << faceId << " baryCoords: " << baryCoords[0] << " " << baryCoords[1] << " " << baryCoords[2] << std::endl;
for (int i = 0; i < numVert; i++)
{
// std::cout << "Vertex: " << i << std::endl;
point curVertex = mesh->vertices[i];
TriMesh::Face vertFace = mesh->faces[mesh->adjacentfaces[i][0]];
vec3 barycentric = this->ComputeBarycentricCoordinates(curVertex, vertFace);
vnl_vector<float> baryVert(3, 0.0);
for (int d = 0; d < 3; d++)
baryVert[d] = barycentric[d];
float distToLandmark = this->GetBronsteinGeodesicDistance(triangleX, vertFace, baryCoords, baryVert, (char*) "LM");
outfile << distToLandmark << " ";
}
outfile << std::endl;
}
std::cout << "Total number of points: " << count+1 << std::endl;
pointsFile.close();
outfile.close();
}
/* Praful */
float meshFIM::GetBronsteinGeodesicDistance(point a, point b, char *method)//, Face Sa, Face Sb, vnl_vector <float> baryCoord_a, vnl_vector <float> baryCoord_b)
{
TriMesh::Face Sa, Sb;
vnl_vector <float> baryCoord_a(3), baryCoord_b(3);
float alp_a, alp_b, bet_a, bet_b, gam_a, gam_b;
GetTriangleInfoForPoint(a, Sa, alp_a, bet_a, gam_a);
GetTriangleInfoForPoint(b, Sb, alp_b, bet_b, gam_b);
float dGeo_a_2_b = GetBronsteinGeodesicDistance(Sa, Sb, baryCoord_a, baryCoord_b, method);
return dGeo_a_2_b;
}
// SHIREEN - compute distance to landmarks based on geodesic approximation
void meshFIM::ComputeDistanceToLandmark(TriMesh *mesh, point landmark, bool apply_log, const char *outfilename)
{
// initialize the geodesic map to hold the geodesics from the triangle vertices of the given landmark to all other mesh vertices
int numVert = mesh->vertices.size();
this->geodesicMap.resize(numVert);
SetMesh(mesh);
// get which triangle the given landmark should belong to
TriMesh::Face triangleX;
float alphaX, betaX, gammaX;
int faceId = this->GetTriangleInfoForPoint(landmark, triangleX, alphaX, betaX, gammaX);
std::vector<int> vertexIdlist;
vertexIdlist.clear();
vertexIdlist.push_back(triangleX[0]);
vertexIdlist.push_back(triangleX[1]);
vertexIdlist.push_back(triangleX[2]);
// update the geodesic map with geodesic distances from each triangle vertex to all other mesh vertices
UpdateGeodesicMapWithDistancesFromVertices(vertexIdlist);
// now start approximating the geodesics to the given landmarks based on the geodesics to its triangle vertices
// write out distance to curve
std::ofstream outfile(outfilename, std::ios::binary);
// write numVertices to facilitate reading later
outfile.write( reinterpret_cast<char *>(&numVert), sizeof(unsigned int) );
//std::cout << "vertices (" << numVert << "): ";
// loop over each vertex
for (int i = 0; i < numVert; i++)
{
//if ((i % 50) == 0)
// std::cout << std::endl;
//std::cout << i << ", ";
point curVertex = mesh->vertices[i];
float distToLandmark = this->GetBronsteinGeodesicDistance(landmark, curVertex, (char*) "LM");
distToLandmark += 0.00001f;
if (apply_log)
distToLandmark = std::log(distToLandmark);
// write distance to curve
outfile.write( reinterpret_cast<char *>(&distToLandmark), sizeof(float) );
}
//std::cout << std::endl;
outfile.close();
}
void meshFIM::UpdateGeodesicMapWithDistancesFromVertices(std::vector<int> vertexIdlist)
{
std::list<index>::iterator iter = m_ActivePoints.begin();
float oldT1 , newT1, oldT2, newT2;
index tmpIndex1, tmpIndex2;
std::vector<int> nb;
int i = 0;
for (int ii = 0 ; ii < vertexIdlist.size(); ii++)
{
int currentVert = vertexIdlist[ii];
std::vector<int> seedPointList(1, currentVert);
SetSeedPoint(seedPointList);
this->InitializeAttributes(currentVert, m_SeedPoints);
InitializeLabels();
InitializeActivePoints();
// to enable computing geodesic from the current vertex to all mesh vertices
SetStopDistance(LARGENUM);
while (!m_ActivePoints.empty())
{
//printf("Size of Activelist is: %d \n", m_ActivePoints.size());
iter = m_ActivePoints.begin();
while(iter != m_ActivePoints.end()) {
tmpIndex1 = *iter;
nb = m_meshPtr->neighbors[tmpIndex1];
oldT1 = this->geodesic[tmpIndex1];
newT1 = Upwind(currentVert,tmpIndex1);
if (abs(oldT1-newT1)<_EPS) //if converges
{
if (oldT1>newT1){
this->geodesic[tmpIndex1] = newT1;
}
if(this->geodesic[tmpIndex1] < m_StopDistance)
{
for (i=0;i<nb.size();i++)
{
tmpIndex2 = nb[i];
if (m_Label[tmpIndex2]==AlivePoint || m_Label[tmpIndex2]==FarPoint)
{
oldT2 = this->geodesic[tmpIndex2];
newT2 = Upwind(currentVert,tmpIndex2);
if (oldT2>newT2)
{
this->geodesic[tmpIndex2] = newT2;
if (m_Label[tmpIndex2]!=ActivePoint)
{
m_ActivePoints.insert(iter, tmpIndex2);
//iter++;
m_Label[tmpIndex2] = ActivePoint;
}
}
}
}
}
iter = m_ActivePoints.erase(iter);
m_Label[tmpIndex1] = AlivePoint;
}
else // if not converge
{
if(newT1 < oldT1){
this->geodesic[tmpIndex1] = newT1;
}
iter++;
}
}
}
// Loop Through And Copy Only Values < than
int nv = m_meshPtr->vertices.size();
for(int v = 0; v < nv; v++){
if ((this->geodesic[v] <= m_StopDistance) && (this->geodesic[v] > 0))
{
int v1 = currentVert;
int v2 = v;
int vert = v1;
int key = v2;
if (v2 > v1)
{
vert = v2;
key = v1;
}
//(m_meshPtr->geodesicMap[currentVert])[v] = m_meshPtr->geodesic[v];
(this->geodesicMap[vert])[key] = this->geodesic[v];
}
}
// Now Erase the duplicate data
this->CleanupAttributes();
}
}
// end SHIREEN
// SHIREEN - compute distance to curve based on geodesic approximation
void meshFIM::ComputeDistanceToCurve(TriMesh *mesh, std::vector< point > curvePoints, const char *outfilename)
{
// initialize the geodesic map to hold the geodesics from the triangle vertices of the given landmark to all other mesh vertices
int numVert = mesh->vertices.size();
this->geodesicMap.resize(numVert);
SetMesh(mesh);
// get which triangle the given landmark should belong to
TriMesh::Face triangleX;
float alphaX, betaX, gammaX;
std::vector<int> vertexIdlist;
vertexIdlist.clear();
for (int pIndex = 0; pIndex < curvePoints.size(); pIndex++)
{
int faceId = this->GetTriangleInfoForPoint(curvePoints[pIndex], triangleX, alphaX, betaX, gammaX);
vertexIdlist.push_back(triangleX[0]);
vertexIdlist.push_back(triangleX[1]);
vertexIdlist.push_back(triangleX[2]);
}
// update the geodesic map with geodesic distances from each triangle vertex of each curve point to all other mesh vertices
UpdateGeodesicMapWithDistancesFromVertices(vertexIdlist);
// now start approximating the geodesics to the given curve points based on the geodesics to its triangle vertices
// write out distance to curve
std::ofstream outfile(outfilename, std::ios::binary);
// write numVertices to facilitate reading later
outfile.write( reinterpret_cast<char *>(&numVert), sizeof(unsigned int) );
//std::cout << "vertices (" << numVert << "): ";
// loop over each vertex
for (int i = 0; i < numVert; i++)
{
float distToCurve = 1e20;
point curVertex = mesh->vertices[i];
for (int pIndex = 0; pIndex < curvePoints.size(); pIndex++)
{
point landmark = curvePoints[pIndex];
float curDist = this->GetBronsteinGeodesicDistance(landmark, curVertex, (char*) "LM");
if (curDist < distToCurve)
distToCurve = curDist;
}
distToCurve += 0.00001f;
// write distance to curve
outfile.write( reinterpret_cast<char *>(&distToCurve), sizeof(float) );
}
//std::cout << std::endl;
outfile.close();
}
// end SHIREEN
int meshFIM::GetVertexInfoForPoint(point x) {
int vertX;
TriMesh::Face triangleX;
float alphaX, betaX, gammaX;
if (this->faceIndexMap.size() > 0) // there is a generated face index map so used it
{
//std::cout << "WOW, fids will be used ... \n" ;
// Physical point to Image Index
VoxelIndexType linearIndX = this->physicalPointToLinearIndex(x);
// collect face indices for this voxel
std::map<VoxelIndexType, std::vector<int> >::iterator it = this->faceIndexMap.find(linearIndX);
if (it != this->faceIndexMap.end()) {
std::vector<int> faceList = this->faceIndexMap[linearIndX];
double minDist = LARGENUM;
int winnerIndex;
for (std::vector<int>::iterator it = faceList.begin(); it != faceList.end(); ++it) {
triangleX = m_meshPtr->faces[(*it)];
// project the point onto the plane of the current triangle
point projPoint;
double dist = this->pointTriangleDistance(x, triangleX, projPoint);
if (dist < minDist) {
minDist = dist;
winnerIndex = (*it);
}
}
triangleX = m_meshPtr->faces[winnerIndex];
point projPoint;
double dist = this->pointTriangleDistance(x, triangleX, projPoint);
vec3 barycentric = this->ComputeBarycentricCoordinates(projPoint, triangleX);
alphaX = barycentric[0];
betaX = barycentric[1];
gammaX = barycentric[2];
// get vertex closest to first point - x
vertX = this->FindNearestVertex(projPoint);
}
else //kdtree based
{
#if SHOW_WARNING
std::cout << "warning: using kdtree for triangle info because voxel index " << linearIndX << " is not found in the face index map !!! ...\n";
#endif
// get vertex closest to first point - x
vertX = this->FindNearestVertex(x);
// scan all adjacent faces to see which face (f) includes point x
triangleX = m_meshPtr->faces[m_meshPtr->adjacentfaces[vertX][0]];
for (unsigned int fNumber = 0; fNumber < m_meshPtr->adjacentfaces[vertX].size(); fNumber++) {
// check if face contains x and store barycentric coordinates for x in face f
triangleX = m_meshPtr->faces[m_meshPtr->adjacentfaces[vertX][fNumber]];
vec3 barycentric = this->ComputeBarycentricCoordinates(x, triangleX);
alphaX = barycentric[0];
betaX = barycentric[1];
gammaX = barycentric[2];
if (((barycentric[0] >= 0) && (barycentric[0] <= 1)) &&
((barycentric[1] >= 0) && (barycentric[1] <= 1)) &&
((barycentric[2] >= 0) && (barycentric[2] <= 1))) {
fNumber = m_meshPtr->adjacentfaces[vertX].size();
}
}
}
}
else {
#if SHOW_WARNING
std::cout << "warning: using kdtree for triangle info because there is no face index map !!! ...\n";
#endif
// get vertex closest to first point - x
vertX = this->FindNearestVertex(x);
// scan all adjacent faces to see which face (f) includes point x
triangleX = m_meshPtr->faces[m_meshPtr->adjacentfaces[vertX][0]];
for (unsigned int fNumber = 0; fNumber < m_meshPtr->adjacentfaces[vertX].size(); fNumber++) {
// check if face contains x and store barycentric coordinates for x in face f
triangleX = m_meshPtr->faces[m_meshPtr->adjacentfaces[vertX][fNumber]];
vec3 barycentric = this->ComputeBarycentricCoordinates(x, triangleX);
alphaX = barycentric[0];
betaX = barycentric[1];
gammaX = barycentric[2];
if (((barycentric[0] >= 0) && (barycentric[0] <= 1)) &&
((barycentric[1] >= 0) && (barycentric[1] <= 1)) &&
((barycentric[2] >= 0) && (barycentric[2] <= 1))) {
fNumber = m_meshPtr->adjacentfaces[vertX].size();
}
}
}
return vertX;
}
// SHIREEN - computing geo distance on the fly for fuzzy geodesics
std::vector<float> meshFIM::ComputeDistanceToCurve(TriMesh *mesh, std::vector< point > curvePoints)
{
int numVert = mesh->vertices.size();
this->geodesicMap.resize(numVert);
SetMesh(mesh);
std::list<index>::iterator iter = m_ActivePoints.begin();
float oldT1 , newT1, oldT2, newT2;
index tmpIndex1, tmpIndex2;
std::vector<int> nb;
NumComputation = 0;
double total_duration = 0;
char c;
int i=0;
std::vector<int> seedPointList;
for (int pIndex = 0; pIndex < curvePoints.size(); pIndex++)
{
// SHIREEN
seedPointList.push_back(this->GetVertexInfoForPoint(curvePoints[pIndex]) );
//seedPointList.push_back( mesh->FindNearestVertex(curvePoints[pIndex]) );
// end SHIREEN
}
SetSeedPoint(seedPointList);
this->InitializeAttributes(0, m_SeedPoints);
InitializeLabels();
InitializeActivePoints();
SetStopDistance(LARGENUM);
while (!m_ActivePoints.empty())
{
//printf("Size of Activelist is: %d \n", m_ActivePoints.size());
iter = m_ActivePoints.begin();
while(iter != m_ActivePoints.end())
{
tmpIndex1 = *iter;
nb = m_meshPtr->neighbors[tmpIndex1];
oldT1 = this->geodesic[tmpIndex1];
newT1 = Upwind(0,tmpIndex1);
if (abs(oldT1-newT1)<_EPS) //if converges
{
if (oldT1>newT1)
{
this->geodesic[tmpIndex1] = newT1;
}
if(this->geodesic[tmpIndex1] < m_StopDistance)
{
for (i=0;i<nb.size();i++)
{
tmpIndex2 = nb[i];
if (m_Label[tmpIndex2]==AlivePoint || m_Label[tmpIndex2]==FarPoint)
{
oldT2 = this->geodesic[tmpIndex2];
newT2 = Upwind(0,tmpIndex2);
if (oldT2>newT2)
{
this->geodesic[tmpIndex2] = newT2;
if (m_Label[tmpIndex2]!=ActivePoint)
{
m_ActivePoints.insert(iter, tmpIndex2);
m_Label[tmpIndex2] = ActivePoint;
}
}
}
}
}
iter = m_ActivePoints.erase(iter);
m_Label[tmpIndex1] = AlivePoint;
}
else // if not converge
{
if(newT1 < oldT1)
{
this->geodesic[tmpIndex1] = newT1;
}
iter++;
}
}
}
std::vector<float> geodesics;geodesics.clear();
// loop over each vertex
for (int i = 0; i < numVert; i++)
{
geodesics.push_back(this->geodesic[i] + 0.0001f);
}
// Now Erase the duplicate data
this->CleanupAttributes();
return geodesics;
}
void meshFIM::WriteFeaFile(TriMesh *mesh, char* outfilename)
{
int numVert = mesh->vertices.size();
// write out distance to curve
std::ofstream outfile(outfilename, std::ios::binary);
// write numVertices to facilitate reading later
outfile.write( reinterpret_cast<char *>(&numVert), sizeof(unsigned int) );
// loop over each vertex
for (int i = 0; i < numVert; i++)
{
// write distance to curve
float distToCurve;
distToCurve = this->geodesic[i] + 0.0001f;
outfile.write( reinterpret_cast<char *>(&distToCurve), sizeof(float) );
}
outfile.close();
}
void meshFIM::WriteFeaFile(std::vector<float> fea, char* outfilename)
{
int numVert = fea.size();
// write out distance to curve
std::ofstream outfile(outfilename, std::ios::binary);
// write numVertices to facilitate reading later
outfile.write( reinterpret_cast<char *>(&numVert), sizeof(unsigned int) );
// loop over each vertex
for (int i = 0; i < numVert; i++)
{
// write distance to curve
float distToCurve;
distToCurve = fea[i];
outfile.write( reinterpret_cast<char *>(&distToCurve), sizeof(float) );
}
outfile.close();
}
// end SHIREEN
/* Praful */
void meshFIM::GetFeatureValues(point x, std::vector<float> &vals) {
float alphaX, betaX, gammaX;
TriMesh::Face triangleX;
GetTriangleInfoForPoint(x, triangleX, alphaX, betaX, gammaX);
if (alphaX < 0.000001f)
alphaX = 0.000001f;
if (betaX < 0.000001f)
betaX = 0.000001f;
if (gammaX < 0.000001f)
gammaX = 0.000001f;
alphaX /= (alphaX + betaX + gammaX);
betaX /= (alphaX + betaX + gammaX);
gammaX /= (alphaX + betaX + gammaX);
vals.resize(this->features.size());
for (unsigned int i = 0; i < this->features.size(); i++) {
float f0 = this->features[i][triangleX[0]];
float f1 = this->features[i][triangleX[1]];
float f2 = this->features[i][triangleX[2]];
vals[i] = (alphaX * f0) + (betaX * f1) + (gammaX * f2);
}
}
/* Prateep */
void meshFIM::ReadFaceIndexMap(const char *infilename) {
std::ifstream infile(infilename);
if (!infile.is_open()) {
std::cout << "File Not Found:" << infilename << std::endl;
}
else {
std::cout << "reading face indices from " << infilename << std::endl;
// map<VoxelIndexType, set<int> > tmpFaceIndexMap;
std::string line;
while (infile) {
getline(infile, line);
std::stringstream ss(line);
VoxelIndexType index;
char delim;
ss >> index >> delim;
int fid;
while (ss >> fid) {
this->faceIndexMap[index].push_back(fid);
// tmpFaceIndexMap[index].insert(fid);
}
}
// if(tmpFaceIndexMap.size() != 0 )
// {
// this->faceIndexMap = tmpFaceIndexMap;
// }
// tmpFaceIndexMap.clear(); // clear memory
infile.close();
}
}
void meshFIM::ReadFeatureFromFile(const char *infilename) {
std::ifstream infile(infilename, std::ios::binary);
if (!infile.is_open()) {
std::cerr << "File Not Found: " << infilename << std::endl;
throw(1);
}
else {
// read # vertices
unsigned int numVert;
infile.read(reinterpret_cast<char *>(&numVert), sizeof(unsigned int));
if (numVert != m_meshPtr->vertices.size()) {
std::cerr << "size of feature vector does not match # vertices in mesh" << std::endl;
throw(1);
}
else {
// std::cout << "reading feature from file " << infilename << std::endl;
std::vector< float > tmpFeatureVec;
// loop over vertices
for (int i = 0; i < numVert; i++) {
// read feature value
float value;
infile.read(reinterpret_cast<char *>(&value), sizeof(float));
tmpFeatureVec.push_back(value);
}
this->features.push_back(tmpFeatureVec);
}
infile.close();
}
}
/* Praful */
void meshFIM::ReadFeatureGradientFromFile(const char *infilename) {
std::ifstream infile(infilename);
if (!infile.is_open()) {
std::cerr << "File Not Found" << std::endl;
throw(1);//exit(1);
}
else {
// read # vertices
unsigned int numVert;
infile.read(reinterpret_cast<char *>(&numVert), sizeof(unsigned int));
if (numVert != m_meshPtr->vertices.size()) {
std::cerr << "size of feature vector does not match # vertices in mesh" << std::endl;
throw(1); //exit(1);
}
else {
// std::cout << "reading feature gradient from file " << infilename << std::endl;
std::vector<point> tempFeatureGradVec;
// loop over vertices
for (int i = 0; i < numVert; i++) {
// read feature gradient
point val;
float value;
for (int j = 0; j < 3; j++) {
infile.read(reinterpret_cast<char *>(&value), sizeof(float));
val[j] = ( float) value;
}
tempFeatureGradVec.push_back(val);
}
this->featureGradients.push_back(tempFeatureGradVec);
}
infile.close();
}
}
/* Praful */
point meshFIM::ComputeFeatureDerivative(int v, int nFeature = 0) {
if (featureGradients.size() > 0)
return featureGradients[nFeature][v];
else {
point df; df.clear();
df[0] = 0.0f; df[1] = 0.0f; df[2] = 0.0f;
// feature value at v
float valueV = this->features[nFeature][v];
point ptV = m_meshPtr->vertices[v];
// iterate over neighbors of v to compute derivative as central difference
for (unsigned int n = 0; n < m_meshPtr->neighbors[v].size(); n++) {
int indexN = m_meshPtr->neighbors[v][n];
float valueN = this->features[nFeature][indexN];
point ptN = m_meshPtr->vertices[indexN];
float valueDiff = valueN - valueV;
point ptDiff = ptN - ptV;
df[0] = df[0] + valueDiff / (ptDiff[0] + 0.0001f);
df[1] = df[1] + valueDiff / (ptDiff[1] + 0.0001f);
df[2] = df[2] + valueDiff / (ptDiff[2] + 0.0001f);
}
df[0] = df[0] / ( float) (m_meshPtr->neighbors[v].size());
df[1] = df[1] / ( float) (m_meshPtr->neighbors[v].size());
df[2] = df[2] / ( float) (m_meshPtr->neighbors[v].size());
return df;
}
}
/* Prateep -- updated Praful */
point meshFIM::GetFeatureDerivative(point p, int fIndex = 0) {
point dP; dP.clear();
dP[0] = 0.0f; dP[1] = 0.0f; dP[2] = 0.0f;
float alphaP, betaP, gammaP;
TriMesh::Face triangleP;
GetTriangleInfoForPoint(p, triangleP, alphaP, betaP, gammaP);
if (alphaP < 0.000001f)
alphaP = 0.000001f;
if (betaP < 0.000001f)
betaP = 0.000001f;
if (gammaP < 0.000001f)
gammaP = 0.000001f;
alphaP /= (alphaP + betaP + gammaP);
betaP /= (alphaP + betaP + gammaP);
gammaP /= (alphaP + betaP + gammaP);
// compute derivative at 3 vertices (A,B,C)
int A = triangleP[0];
int B = triangleP[1];
int C = triangleP[2];
// // Get derivatives of Barycentric coordinates
// vec fNorm = GetFaceNormal(triangleP);
// float mag = fNorm DOT fNorm;
// mag = std::sqrt(mag);
// fNorm[0] /= mag;
// fNorm[1] /= mag;
// fNorm[2] /= mag;
// float fArea = GetFaceArea(triangleP);
// vec v0 = this->vertices[triangleP.v[0]];
// vec v1 = this->vertices[triangleP.v[1]];
// vec v2 = this->vertices[triangleP.v[2]];
// vec dAlpha = GetGradientBaryCentricCoord(fNorm, v2-v1, fArea);
// vec dBeta = GetGradientBaryCentricCoord(fNorm, v0-v2, fArea);
// vec dGamma = GetGradientBaryCentricCoord(fNorm, v1-v0, fArea);
point dA = ComputeFeatureDerivative(A, fIndex);
point dB = ComputeFeatureDerivative(B, fIndex);
point dC = ComputeFeatureDerivative(C, fIndex);
// float f0 = this->features[fIndex][A];
// float f1 = this->features[fIndex][B];
// float f2 = this->features[fIndex][C];
// interpolate
dP[0] = (alphaP * dA[0]) + (betaP * dB[0]) + (gammaP * dC[0]);// + ( dAlpha[0] * f0 ) + ( dBeta[0] * f1 ) + ( dGamma[0] * f2 );
dP[1] = (alphaP * dA[1]) + (betaP * dB[1]) + (gammaP * dC[1]);// + ( dAlpha[1] * f0 ) + ( dBeta[1] * f1 ) + ( dGamma[1] * f2 );
dP[2] = (alphaP * dA[2]) + (betaP * dB[2]) + (gammaP * dC[2]);// + ( dAlpha[2] * f0 ) + ( dBeta[2] * f1 ) + ( dGamma[2] * f2 );
return dP;
}
| 80,205 | 30,440 |
#pragma once
#include "utilities.hpp"
class i_client_leaf_system
{
public:
void create_renderable_handle(void* obj)
{
return utilities::call_virtual< void, 0, std::uintptr_t, bool, int, int, std::uint32_t >(this, reinterpret_cast<std::uintptr_t>(obj) + 4, false, 0, -1, 0xFFFFFFFF);
}
}; | 294 | 124 |
/* This file is part of Cloudy and is copyright (C)1978-2019 by Gary J. Ferland and
* others. For conditions of distribution and use see copyright notice in license.txt */
/*InitCoreloadPostparse initialization at start, called from cloudy
* after parser one time per core load */
#include "cddefines.h"
#include "init.h"
#include "dense.h"
#include "iso.h"
#include "species.h"
/*InitCoreloadPostparse initialization at start, called from cloudy
* after parser, one time per core load */
void InitCoreloadPostparse( void )
{
static int nCalled = 0;
DEBUG_ENTRY( "InitCoreloadPostparse()" );
/* only do this once per coreload */
if( nCalled > 0 )
{
return;
}
/* this is first call, increment the nCalled counter so we never do this again */
++nCalled;
for( long ipISO=ipH_LIKE; ipISO<NISO; ++ipISO )
{
for( long nelem=ipISO; nelem<LIMELM; ++nelem)
{
/* only grab core for elements that are turned on */
if( nelem < 2 || dense.lgElmtOn[nelem] )
{
iso_update_num_levels( ipISO, nelem );
ASSERT( iso_sp[ipISO][nelem].numLevels_max > 0 );
iso_ctrl.nLyman_alloc[ipISO] = iso_ctrl.nLyman[ipISO];
iso_ctrl.nLyman_max[ipISO] = iso_ctrl.nLyman[ipISO];
// resolved and collapsed levels
long numLevels = iso_sp[ipISO][nelem].numLevels_max;
// "extra" Lyman lines
numLevels += iso_ctrl.nLyman_alloc[ipISO] - 2;
// satellite lines (one for doubly-excited continuum)
if( iso_ctrl.lgDielRecom[ipISO] )
numLevels += 1;
iso_sp[ipISO][nelem].st.init( makeChemical( nelem, nelem-ipISO ).c_str(), numLevels );
}
}
}
return;
}
| 1,597 | 657 |
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// TGUI - Texus's Graphical User Interface
// Copyright (C) 2012-2017 Bruno Van de Velde (vdv_b@tgui.eu)
//
// 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.
//
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "../Tests.hpp"
#include <TGUI/Widgets/Label.hpp>
TEST_CASE("[Label]") {
tgui::Label::Ptr label = std::make_shared<tgui::Label>();
label->setFont("resources/DroidSansArmenian.ttf");
SECTION("Signals") {
REQUIRE_NOTHROW(label->connect("DoubleClicked", [](){}));
REQUIRE_NOTHROW(label->connect("DoubleClicked", [](sf::String){}));
}
SECTION("WidgetType") {
REQUIRE(label->getWidgetType() == "Label");
}
SECTION("Text") {
REQUIRE(label->getText() == "");
label->setText("SomeText");
REQUIRE(label->getText() == "SomeText");
}
SECTION("TextStyle") {
REQUIRE(label->getTextStyle() == sf::Text::Regular);
label->setTextStyle(sf::Text::Bold | sf::Text::Italic);
REQUIRE(label->getTextStyle() == (sf::Text::Bold | sf::Text::Italic));
}
SECTION("TextSize") {
label->setTextSize(25);
REQUIRE(label->getTextSize() == 25);
}
SECTION("Alignment") {
REQUIRE(label->getHorizontalAlignment() == tgui::Label::HorizontalAlignment::Left);
REQUIRE(label->getVerticalAlignment() == tgui::Label::VerticalAlignment::Top);
label->setHorizontalAlignment(tgui::Label::HorizontalAlignment::Center);
REQUIRE(label->getHorizontalAlignment() == tgui::Label::HorizontalAlignment::Center);
REQUIRE(label->getVerticalAlignment() == tgui::Label::VerticalAlignment::Top);
label->setHorizontalAlignment(tgui::Label::HorizontalAlignment::Right);
REQUIRE(label->getHorizontalAlignment() == tgui::Label::HorizontalAlignment::Right);
label->setHorizontalAlignment(tgui::Label::HorizontalAlignment::Left);
REQUIRE(label->getHorizontalAlignment() == tgui::Label::HorizontalAlignment::Left);
label->setVerticalAlignment(tgui::Label::VerticalAlignment::Center);
REQUIRE(label->getHorizontalAlignment() == tgui::Label::HorizontalAlignment::Left);
REQUIRE(label->getVerticalAlignment() == tgui::Label::VerticalAlignment::Center);
label->setVerticalAlignment(tgui::Label::VerticalAlignment::Bottom);
REQUIRE(label->getVerticalAlignment() == tgui::Label::VerticalAlignment::Bottom);
label->setVerticalAlignment(tgui::Label::VerticalAlignment::Top);
REQUIRE(label->getVerticalAlignment() == tgui::Label::VerticalAlignment::Top);
}
SECTION("AutoSize") {
REQUIRE(label->getAutoSize());
label->setAutoSize(false);
REQUIRE(!label->getAutoSize());
label->setAutoSize(true);
REQUIRE(label->getAutoSize());
label->setSize(200, 100);
REQUIRE(!label->getAutoSize());
}
SECTION("MaximumTextWidth") {
REQUIRE(label->getMaximumTextWidth() == 0);
label->setMaximumTextWidth(300);
REQUIRE(label->getMaximumTextWidth() == 300);
}
SECTION("Renderer") {
auto renderer = label->getRenderer();
SECTION("set serialized property") {
REQUIRE_NOTHROW(renderer->setProperty("TextColor", "rgb(100, 50, 150)"));
REQUIRE_NOTHROW(renderer->setProperty("BackgroundColor", "rgb(150, 100, 50)"));
REQUIRE_NOTHROW(renderer->setProperty("BorderColor", "rgb(50, 150, 100)"));
REQUIRE_NOTHROW(renderer->setProperty("Borders", "(1, 2, 3, 4)"));
REQUIRE_NOTHROW(renderer->setProperty("Padding", "(5, 6, 7, 8)"));
}
SECTION("set object property") {
REQUIRE_NOTHROW(renderer->setProperty("TextColor", sf::Color{100, 50, 150}));
REQUIRE_NOTHROW(renderer->setProperty("BackgroundColor", sf::Color{150, 100, 50}));
REQUIRE_NOTHROW(renderer->setProperty("BorderColor", sf::Color{50, 150, 100}));
REQUIRE_NOTHROW(renderer->setProperty("Borders", tgui::Borders{1, 2, 3, 4}));
REQUIRE_NOTHROW(renderer->setProperty("Padding", tgui::Borders{5, 6, 7, 8}));
}
SECTION("functions") {
renderer->setTextColor({100, 50, 150});
renderer->setBackgroundColor({150, 100, 50});
renderer->setBorderColor({50, 150, 100});
renderer->setBorders({1, 2, 3, 4});
renderer->setPadding({5, 6, 7, 8});
SECTION("getPropertyValuePairs") {
auto pairs = renderer->getPropertyValuePairs();
REQUIRE(pairs.size() == 5);
REQUIRE(pairs["TextColor"].getColor() == sf::Color(100, 50, 150));
REQUIRE(pairs["BackgroundColor"].getColor() == sf::Color(150, 100, 50));
REQUIRE(pairs["BorderColor"].getColor() == sf::Color(50, 150, 100));
REQUIRE(pairs["Borders"].getBorders() == tgui::Borders(1, 2, 3, 4));
REQUIRE(pairs["Padding"].getBorders() == tgui::Borders(5, 6, 7, 8));
}
}
REQUIRE(renderer->getProperty("TextColor").getColor() == sf::Color(100, 50, 150));
REQUIRE(renderer->getProperty("BackgroundColor").getColor() == sf::Color(150, 100, 50));
REQUIRE(renderer->getProperty("BorderColor").getColor() == sf::Color(50, 150, 100));
REQUIRE(renderer->getProperty("Borders").getBorders() == tgui::Borders(1, 2, 3, 4));
REQUIRE(renderer->getProperty("Padding").getBorders() == tgui::Borders(5, 6, 7, 8));
}
SECTION("Saving and loading from file") {
REQUIRE_NOTHROW(label = std::make_shared<tgui::Theme>()->load("Label"));
auto theme = std::make_shared<tgui::Theme>("resources/Black.txt");
REQUIRE_NOTHROW(label = theme->load("Label"));
REQUIRE(label->getPrimaryLoadingParameter() == "resources/Black.txt");
REQUIRE(label->getSecondaryLoadingParameter() == "label");
auto parent = std::make_shared<tgui::GuiContainer>();
parent->add(label);
label->setOpacity(0.8f);
label->setText("SomeText");
label->setTextSize(25);
label->setTextStyle(sf::Text::Bold | sf::Text::Italic);
label->setHorizontalAlignment(tgui::Label::HorizontalAlignment::Center);
label->setVerticalAlignment(tgui::Label::VerticalAlignment::Bottom);
label->setMaximumTextWidth(300);
REQUIRE_NOTHROW(parent->saveWidgetsToFile("WidgetFileLabel1.txt"));
parent->removeAllWidgets();
REQUIRE_NOTHROW(parent->loadWidgetsFromFile("WidgetFileLabel1.txt"));
REQUIRE_NOTHROW(parent->saveWidgetsToFile("WidgetFileLabel2.txt"));
REQUIRE(compareFiles("WidgetFileLabel1.txt", "WidgetFileLabel2.txt"));
SECTION("Copying widget") {
tgui::Label temp;
temp = *label;
parent->removeAllWidgets();
parent->add(tgui::Label::copy(std::make_shared<tgui::Label>(temp)));
REQUIRE_NOTHROW(parent->saveWidgetsToFile("WidgetFileLabel2.txt"));
REQUIRE(compareFiles("WidgetFileLabel1.txt", "WidgetFileLabel2.txt"));
}
}
}
| 8,167 | 2,604 |
//@HEADER
// ************************************************************************
//
// HPCCG: Simple Conjugate Gradient Benchmark Code
// Copyright (2006) Sandia Corporation
//
// Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive
// license for use of this work by or on behalf of the U.S. Government.
//
// BSD 3-Clause License
//
// 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 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.
//
// Questions? Contact Michael A. Heroux (maherou@sandia.gov)
//
// ************************************************************************
//@HEADER
/////////////////////////////////////////////////////////////////////////
// Routine to dump matrix in row, col, val format for analysis with Matlab
// Writes to mat.dat
// NOTE: THIS CODE ONLY WORKS ON SINGLE PROCESSOR RUNS
// Read into matlab using:
// load mat.dat
// A=spconvert(mat);
// A - known matrix
/////////////////////////////////////////////////////////////////////////
#include <cstdio>
#include "dump_matlab_matrix.hpp"
int dump_matlab_matrix( HPC_Sparse_Matrix *A, int rank) {
const int nrow = A->local_nrow;
int start_row = nrow*rank; // Each processor gets a section of a chimney stack domain
FILE * handle = 0;
if (rank==0)
handle = fopen("mat0.dat", "w");
else if (rank==1)
handle = fopen("mat1.dat", "w");
else if (rank==2)
handle = fopen("mat2.dat", "w");
else if (rank==3)
handle = fopen("mat3.dat", "w");
else return(0);
for (int i=0; i< nrow; i++) {
const double * const cur_vals = A->ptr_to_vals_in_row[i];
const int * const cur_inds = A->ptr_to_inds_in_row[i];
const int cur_nnz = A->nnz_in_row[i];
for (int j=0; j< cur_nnz; j++) fprintf(handle, " %d %d %22.16e\n",start_row+i+1,cur_inds[j]+1,cur_vals[j]);
}
fclose(handle);
return(0);
}
| 3,302 | 1,139 |
// Created on: 1994-04-21
// Created by: Christian CAILLET
// Copyright (c) 1994-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _IFSelect_SelectSignature_HeaderFile
#define _IFSelect_SelectSignature_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <TCollection_AsciiString.hxx>
#include <Standard_Integer.hxx>
#include <TColStd_SequenceOfAsciiString.hxx>
#include <TColStd_SequenceOfInteger.hxx>
#include <IFSelect_SelectExtract.hxx>
#include <Standard_CString.hxx>
#include <Standard_Boolean.hxx>
class IFSelect_Signature;
class IFSelect_SignCounter;
class Standard_Transient;
class Interface_Graph;
class Interface_InterfaceModel;
class IFSelect_SelectSignature;
DEFINE_STANDARD_HANDLE(IFSelect_SelectSignature, IFSelect_SelectExtract)
//! A SelectSignature sorts the Entities on a Signature Matching.
//! The signature to match is given at creation time. Also, the
//! required match is given at creation time : exact (IsEqual) or
//! contains (the Type's Name must contain the criterium Text)
//!
//! Remark that no more interpretation is done, it is an
//! alpha-numeric signature : for instance, DynamicType is matched
//! as such, super-types are not considered
//!
//! Also, numeric (integer) comparisons are supported : an item
//! can be <val ou <=val or >val or >=val , val being an Integer
//!
//! A SelectSignature may also be created from a SignCounter,
//! which then just gives its LastValue as SignatureValue
class IFSelect_SelectSignature : public IFSelect_SelectExtract
{
public:
//! Creates a SelectSignature with its Signature and its Text to
//! Match.
//! <exact> if True requires exact match,
//! if False requires <signtext> to be contained in the Signature
//! of the entity (default is "exact")
Standard_EXPORT IFSelect_SelectSignature(const Handle(IFSelect_Signature)& matcher, const Standard_CString signtext, const Standard_Boolean exact = Standard_True);
//! As above with an AsciiString
Standard_EXPORT IFSelect_SelectSignature(const Handle(IFSelect_Signature)& matcher, const TCollection_AsciiString& signtext, const Standard_Boolean exact = Standard_True);
//! Creates a SelectSignature with a Counter, more precisely a
//! SelectSignature. Which is used here to just give a Signature
//! Value (by SignOnly Mode)
//! Matching is the default provided by the class Signature
Standard_EXPORT IFSelect_SelectSignature(const Handle(IFSelect_SignCounter)& matcher, const Standard_CString signtext, const Standard_Boolean exact = Standard_True);
//! Returns the used Signature, then it is possible to access it,
//! modify it as required. Can be null, hence see Counter
Standard_EXPORT Handle(IFSelect_Signature) Signature() const;
//! Returns the used SignCounter. Can be used as alternative for
//! Signature
Standard_EXPORT Handle(IFSelect_SignCounter) Counter() const;
//! Returns True for an Entity (model->Value(num)) of which the
//! signature matches the text given as creation time
//! May also work with a Counter from the Graph
Standard_EXPORT virtual Standard_Boolean SortInGraph (const Standard_Integer rank, const Handle(Standard_Transient)& ent, const Interface_Graph& G) const Standard_OVERRIDE;
//! Not called, defined only to remove a deferred method here
Standard_EXPORT Standard_Boolean Sort (const Standard_Integer rank, const Handle(Standard_Transient)& ent, const Handle(Interface_InterfaceModel)& model) const Standard_OVERRIDE;
//! Returns Text used to Sort Entity on its Signature or SignCounter
Standard_EXPORT const TCollection_AsciiString& SignatureText() const;
//! Returns True if match must be exact
Standard_EXPORT Standard_Boolean IsExact() const;
//! Returns a text defining the criterium.
//! (it refers to the text and exact flag to be matched, and is
//! qualified by the Name provided by the Signature)
Standard_EXPORT TCollection_AsciiString ExtractLabel() const Standard_OVERRIDE;
DEFINE_STANDARD_RTTIEXT(IFSelect_SelectSignature,IFSelect_SelectExtract)
protected:
private:
Handle(IFSelect_Signature) thematcher;
Handle(IFSelect_SignCounter) thecounter;
TCollection_AsciiString thesigntext;
Standard_Integer theexact;
TColStd_SequenceOfAsciiString thesignlist;
TColStd_SequenceOfInteger thesignmode;
};
#endif // _IFSelect_SelectSignature_HeaderFile
| 5,005 | 1,491 |
#pragma once
#include <anton/allocator.hpp>
#include <anton/assert.hpp>
#include <anton/iterators.hpp>
#include <anton/math/math.hpp>
#include <anton/memory.hpp>
#include <anton/swap.hpp>
#include <anton/tags.hpp>
#include <anton/type_traits.hpp>
#include <anton/utility.hpp>
namespace anton {
#define ANTON_ARRAY_MIN_ALLOCATION_SIZE ((i64)64)
template<typename T, typename Allocator = Allocator>
struct Array {
public:
using value_type = T;
using allocator_type = Allocator;
using size_type = i64;
using difference_type = i64;
using iterator = T*;
using const_iterator = T const*;
Array();
explicit Array(allocator_type const& allocator);
// Construct an array with n default constructed elements
explicit Array(size_type n);
// Construct an array with n default constructed elements
explicit Array(size_type n, allocator_type const& allocator);
// Construct an array with n copies of value
explicit Array(size_type n, value_type const& value);
// Construct an array with n copies of value
explicit Array(size_type n, value_type const& value, allocator_type const& allocator);
// Construct an array with capacity to fit at least n elements
explicit Array(Reserve_Tag, size_type n);
// Construct an array with capacity to fit at least n elements
explicit Array(Reserve_Tag, size_type n, allocator_type const& allocator);
// Copies the allocator
Array(Array const& other);
Array(Array const& other, allocator_type const& allocator);
// Moves the allocator
Array(Array&& other);
Array(Array&& other, allocator_type const& allocator);
template<typename Input_Iterator>
Array(Range_Construct_Tag, Input_Iterator first, Input_Iterator last);
template<typename... Args>
Array(Variadic_Construct_Tag, Args&&...);
~Array();
Array& operator=(Array const& other);
Array& operator=(Array&& other);
[[nodiscard]] T& operator[](size_type);
[[nodiscard]] T const& operator[](size_type) const;
// back
// Accesses the last element of the array. The behaviour is undefined when the array is empty.
//
[[nodiscard]] T& back();
[[nodiscard]] T const& back() const;
[[nodiscard]] T* data();
[[nodiscard]] T const* data() const;
[[nodiscard]] iterator begin();
[[nodiscard]] iterator end();
[[nodiscard]] const_iterator begin() const;
[[nodiscard]] const_iterator end() const;
[[nodiscard]] const_iterator cbegin() const;
[[nodiscard]] const_iterator cend() const;
// size
// The number of elements contained in the array.
//
[[nodiscard]] size_type size() const;
// size_bytes
// The size of all the elements contained in the array in bytes.
// Equivalent to 'sizeof(T) * size()'.
//
[[nodiscard]] size_type size_bytes() const;
[[nodiscard]] size_type capacity() const;
[[nodiscard]] allocator_type& get_allocator();
[[nodiscard]] allocator_type const& get_allocator() const;
// resize
// Resizes the array allocating additional memory if n is greater than capacity.
// If n is greater than size, the new elements are default constructed.
// If n is less than size, the excess elements are destroyed.
//
void resize(size_type n);
// resize
// Resizes the array allocating additional memory if n is greater than capacity.
// If n is greater than size, the new elements are copy constructed from v.
// If n is less than size, the excess elements are destroyed.
//
void resize(size_type n, value_type const& v);
// ensure_capacity
// Allocates enough memory to fit requested_capacity elements of type T.
// Does nothing if requested_capacity is less than capacity().
//
void ensure_capacity(size_type requested_capacity);
// set_capacity
// Sets the capacity to exactly match n.
// If n is not equal capacity, contents are reallocated.
//
void set_capacity(size_type n);
// force_size
// Changes the size of the array to n. Useful in situations when the user
// writes to the array via external means.
//
void force_size(size_type n);
template<typename Input_Iterator>
void assign(Input_Iterator first, Input_Iterator last);
// insert
// Constructs an object directly into array at position avoiding copies or moves.
// position must be a valid iterator.
//
// Returns: iterator to the inserted element.
//
template<typename... Args>
iterator insert(Variadic_Construct_Tag, const_iterator position, Args&&... args);
// insert
// Constructs an object directly into array at position avoiding copies or moves.
// position must be an index greater than or equal 0 and less than or equal size.
//
// Returns: iterator to the inserted element.
//
template<typename... Args>
iterator insert(Variadic_Construct_Tag, size_type position, Args&&... args);
// insert
// Insert a range of elements into array at position.
// position must be a valid iterator.
//
// Returns: iterator to the first of the inserted elements.
//
template<typename Input_Iterator>
iterator insert(const_iterator position, Input_Iterator first, Input_Iterator last);
// insert
// Insert a range of elements into array at position.
// position must be an index greater than or equal 0 and less than or equal size.
//
// Returns: iterator to the first of the inserted elements.
//
template<typename Input_Iterator>
iterator insert(size_type position, Input_Iterator first, Input_Iterator last);
// insert_unsorted
// Inserts an element into array by moving the object at position to the end of the array
// and then copying value into position.
// position must be a valid iterator.
//
// Returns:
// Iterator to the inserted element.
//
iterator insert_unsorted(const_iterator position, value_type const& value);
iterator insert_unsorted(const_iterator position, value_type&& value);
// insert_unsorted
// Inserts an element into array by moving the object at position to the end of the array
// and then copying value into position.
// position must be an index greater than or equal 0 and less than or equal size.
//
// Returns:
// Iterator to the inserted element.
//
iterator insert_unsorted(size_type position, value_type const& value);
iterator insert_unsorted(size_type position, value_type&& value);
T& push_back(value_type const&);
T& push_back(value_type&&);
template<typename... Args>
T& emplace_back(Args&&... args);
iterator erase(const_iterator first, const_iterator last);
void erase_unsorted(size_type index);
void erase_unsorted_unchecked(size_type index);
iterator erase_unsorted(const_iterator first);
// iterator erase_unsorted(const_iterator first, const_iterator last);
void pop_back();
void clear();
// swap
// Exchanges the contents of the two arrays without copying,
// moving or swapping the individual elements.
// Exchanges the allocators.
//
// Parameters:
// lhs, rhs - the containers to exchange the contents of.
//
// Complexity:
// Constant.
//
friend void swap(Array& lhs, Array& rhs) {
// We do not follow the C++ Standard in its complex ways to swap containers
// and always swap both the allocator and the memory since it is a common expectation
// of the users, is much faster than copying all the elements and does not break
// the container or put it in an invalid state.
using anton::swap;
swap(lhs._allocator, rhs._allocator);
swap(lhs._capacity, rhs._capacity);
swap(lhs._size, rhs._size);
swap(lhs._data, rhs._data);
}
private:
Allocator _allocator;
size_type _capacity = 0;
size_type _size = 0;
T* _data = nullptr;
T* allocate(size_type);
void deallocate(void*, size_type);
};
} // namespace anton
namespace anton {
template<typename T, typename Allocator>
Array<T, Allocator>::Array(): _allocator() {}
template<typename T, typename Allocator>
Array<T, Allocator>::Array(allocator_type const& allocator): _allocator(allocator) {}
template<typename T, typename Allocator>
Array<T, Allocator>::Array(size_type const n): Array(n, allocator_type()) {}
template<typename T, typename Allocator>
Array<T, Allocator>::Array(size_type const n, allocator_type const& allocator): _allocator(allocator) {
_capacity = math::max(ANTON_ARRAY_MIN_ALLOCATION_SIZE, n);
_data = allocate(_capacity);
anton::uninitialized_default_construct_n(_data, n);
_size = n;
}
template<typename T, typename Allocator>
Array<T, Allocator>::Array(size_type n, value_type const& value): Array(n, value, allocator_type()) {}
template<typename T, typename Allocator>
Array<T, Allocator>::Array(size_type n, value_type const& value, allocator_type const& allocator) {
_capacity = math::max(ANTON_ARRAY_MIN_ALLOCATION_SIZE, n);
_data = allocate(_capacity);
anton::uninitialized_fill_n(_data, n, value);
_size = n;
}
template<typename T, typename Allocator>
Array<T, Allocator>::Array(Reserve_Tag, size_type const n): Array(reserve, n, allocator_type()) {}
template<typename T, typename Allocator>
Array<T, Allocator>::Array(Reserve_Tag, size_type const n, allocator_type const& allocator): _allocator(allocator) {
_capacity = math::max(ANTON_ARRAY_MIN_ALLOCATION_SIZE, n);
_data = allocate(_capacity);
}
template<typename T, typename Allocator>
Array<T, Allocator>::Array(Array const& other): _allocator(other._allocator), _capacity(other._capacity) {
if(_capacity > 0) {
_data = allocate(_capacity);
anton::uninitialized_copy_n(other._data, other._size, _data);
_size = other._size;
}
}
template<typename T, typename Allocator>
Array<T, Allocator>::Array(Array&& other): _allocator(ANTON_MOV(other._allocator)), _capacity(other._capacity), _size(other._size), _data(other._data) {
other._data = nullptr;
other._capacity = 0;
other._size = 0;
}
template<typename T, typename Allocator>
template<typename Input_Iterator>
Array<T, Allocator>::Array(Range_Construct_Tag, Input_Iterator first, Input_Iterator last) {
// TODO: Use distance?
size_type const count = last - first;
_capacity = math::max(ANTON_ARRAY_MIN_ALLOCATION_SIZE, count);
_data = allocate(_capacity);
anton::uninitialized_copy(first, last, _data);
_size = count;
}
template<typename T, typename Allocator>
template<typename... Args>
Array<T, Allocator>::Array(Variadic_Construct_Tag, Args&&... args) {
_capacity = math::max(ANTON_ARRAY_MIN_ALLOCATION_SIZE, static_cast<size_type>(sizeof...(Args)));
_data = allocate(_capacity);
anton::uninitialized_variadic_construct(_data, ANTON_FWD(args)...);
_size = static_cast<size_type>(sizeof...(Args));
}
template<typename T, typename Allocator>
Array<T, Allocator>::~Array() {
anton::destruct_n(_data, _size);
deallocate(_data, _capacity);
}
template<typename T, typename Allocator>
Array<T, Allocator>& Array<T, Allocator>::operator=(Array const& other) {
anton::destruct_n(_data, _size);
deallocate(_data, _capacity);
_capacity = other._capacity;
_size = other._size;
_allocator = other._allocator;
if(_capacity > 0) {
_data = allocate(_capacity);
anton::uninitialized_copy_n(other._data, other._size, _data);
}
return *this;
}
template<typename T, typename Allocator>
Array<T, Allocator>& Array<T, Allocator>::operator=(Array&& other) {
swap(*this, other);
return *this;
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::operator[](size_type index) -> T& {
if constexpr(ANTON_ITERATOR_DEBUG) {
ANTON_FAIL(index < _size && index >= 0, u8"index out of bounds");
}
return _data[index];
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::operator[](size_type index) const -> T const& {
if constexpr(ANTON_ITERATOR_DEBUG) {
ANTON_FAIL(index < _size && index >= 0, u8"index out of bounds");
}
return _data[index];
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::back() -> T& {
if constexpr(ANTON_ITERATOR_DEBUG) {
ANTON_FAIL(_size > 0, u8"attempting to call back() on empty Array");
}
return _data[_size - 1];
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::back() const -> T const& {
if constexpr(ANTON_ITERATOR_DEBUG) {
ANTON_FAIL(_size > 0, u8"attempting to call back() on empty Array");
}
return _data[_size - 1];
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::data() -> T* {
return _data;
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::data() const -> T const* {
return _data;
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::begin() -> iterator {
return _data;
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::end() -> iterator {
return _data + _size;
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::begin() const -> const_iterator {
return _data;
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::end() const -> const_iterator {
return _data + _size;
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::cbegin() const -> const_iterator {
return _data;
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::cend() const -> const_iterator {
return _data + _size;
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::size() const -> size_type {
return _size;
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::size_bytes() const -> size_type {
return _size * sizeof(T);
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::capacity() const -> size_type {
return _capacity;
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::get_allocator() -> allocator_type& {
return _allocator;
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::get_allocator() const -> allocator_type const& {
return _allocator;
}
template<typename T, typename Allocator>
void Array<T, Allocator>::resize(size_type n, value_type const& value) {
ensure_capacity(n);
if(n > _size) {
anton::uninitialized_fill(_data + _size, _data + n, value);
} else {
anton::destruct(_data + n, _data + _size);
}
_size = n;
}
template<typename T, typename Allocator>
void Array<T, Allocator>::resize(size_type n) {
ensure_capacity(n);
if(n > _size) {
anton::uninitialized_default_construct(_data + _size, _data + n);
} else {
anton::destruct(_data + n, _data + _size);
}
_size = n;
}
template<typename T, typename Allocator>
void Array<T, Allocator>::ensure_capacity(size_type requested_capacity) {
if(requested_capacity > _capacity) {
size_type new_capacity = (_capacity > 0 ? _capacity : ANTON_ARRAY_MIN_ALLOCATION_SIZE);
while(new_capacity < requested_capacity) {
new_capacity *= 2;
}
T* new_data = allocate(new_capacity);
if constexpr(is_move_constructible<T>) {
uninitialized_move(_data, _data + _size, new_data);
} else {
uninitialized_copy(_data, _data + _size, new_data);
}
anton::destruct_n(_data, _size);
deallocate(_data, _capacity);
_data = new_data;
_capacity = new_capacity;
}
}
template<typename T, typename Allocator>
void Array<T, Allocator>::set_capacity(size_type new_capacity) {
ANTON_ASSERT(new_capacity >= 0, "capacity must be greater than or equal 0");
if(new_capacity != _capacity) {
i64 const new_size = math::min(new_capacity, _size);
T* new_data = nullptr;
if(new_capacity > 0) {
new_data = allocate(new_capacity);
}
if constexpr(is_move_constructible<T>) {
anton::uninitialized_move_n(_data, new_size, new_data);
} else {
anton::uninitialized_copy_n(_data, new_size, new_data);
}
anton::destruct_n(_data, _size);
deallocate(_data, _capacity);
_data = new_data;
_capacity = new_capacity;
_size = new_size;
}
}
template<typename T, typename Allocator>
void Array<T, Allocator>::force_size(size_type n) {
ANTON_ASSERT(n <= _capacity, u8"requested size is greater than capacity");
_size = n;
}
template<typename T, typename Allocator>
template<typename Input_Iterator>
void Array<T, Allocator>::assign(Input_Iterator first, Input_Iterator last) {
anton::destruct_n(_data, _size);
ensure_capacity(last - first);
anton::uninitialized_copy(first, last, _data);
_size = last - first;
}
template<typename T, typename Allocator>
template<typename... Args>
auto Array<T, Allocator>::insert(Variadic_Construct_Tag, const_iterator position, Args&&... args) -> iterator {
size_type const offset = static_cast<size_type>(position - begin());
return insert(variadic_construct, offset, ANTON_FWD(args)...);
}
template<typename T, typename Allocator>
template<typename... Args>
auto Array<T, Allocator>::insert(Variadic_Construct_Tag, size_type const position, Args&&... args) -> iterator {
if constexpr(ANTON_ITERATOR_DEBUG) {
ANTON_FAIL(position >= 0 && position <= _size, u8"index out of bounds");
}
if(_size == _capacity || position != _size) {
if(_size != _capacity) {
anton::uninitialized_move_n(_data + _size - 1, 1, _data + _size);
anton::move_backward(_data + position, _data + _size - 1, _data + _size);
anton::construct(_data + position, ANTON_FWD(args)...);
_size += 1;
} else {
i64 const new_capacity = (_capacity > 0 ? _capacity * 2 : ANTON_ARRAY_MIN_ALLOCATION_SIZE);
T* const new_data = allocate(new_capacity);
i64 moved = 0;
anton::uninitialized_move(_data, _data + position, new_data);
moved = position;
anton::construct(new_data + position, ANTON_FWD(args)...);
moved += 1;
anton::uninitialized_move(_data + position, _data + _size, new_data + moved);
anton::destruct_n(_data, _size);
deallocate(_data, _capacity);
_capacity = new_capacity;
_data = new_data;
_size += 1;
}
} else {
// Quick path when position points to end and we have room for one more element.
anton::construct(_data + _size, ANTON_FWD(args)...);
_size += 1;
}
return _data + position;
}
template<typename T, typename Allocator>
template<typename Input_Iterator>
auto Array<T, Allocator>::insert(const_iterator position, Input_Iterator first, Input_Iterator last) -> iterator {
size_type const offset = static_cast<size_type>(position - begin());
return insert(offset, first, last);
}
template<typename T, typename Allocator>
template<typename Input_Iterator>
auto Array<T, Allocator>::insert(size_type position, Input_Iterator first, Input_Iterator last) -> iterator {
if constexpr(ANTON_ITERATOR_DEBUG) {
ANTON_FAIL(position >= 0 && position <= _size, u8"index out of bounds");
}
// TODO: Distance and actual support for input iterators.
if(first != last) {
i64 const new_elems = last - first;
ANTON_ASSERT(new_elems > 0, "the difference of first and last must be greater than 0");
if(_size + new_elems <= _capacity && position == _size) {
// Quick path when position points to end and we have room for new_elems elements.
anton::uninitialized_copy(first, last, _data + _size);
_size += new_elems;
} else {
if(_size + new_elems <= _capacity) {
// total number of elements we want to move
i64 const total_elems = _size - position;
// when new_elems < total_elems, we have to unititialized_move min(total_elems, new_elems)
// and move_backward the rest because the target range will overlap the source range
i64 const elems_outside = math::min(total_elems, new_elems);
i64 const elems_inside = total_elems - elems_outside;
// we move the 'outside' elements to _size unless position + new_elems is greater than _size
i64 const target_offset = math::max(position + new_elems, _size);
anton::uninitialized_move_n(_data + position + elems_inside, elems_outside, _data + target_offset);
anton::move_backward(_data + position, _data + position + elems_inside, _data + position + new_elems + elems_inside);
// we always have to destruct at most total_elems and at least new_elems
// if we attempt to destruct more than total_elems, we will call destruct on uninitialized memory
anton::destruct_n(_data + position, elems_outside);
anton::uninitialized_copy(first, last, _data + position);
_size += new_elems;
} else {
i64 new_capacity = (_capacity > 0 ? _capacity : ANTON_ARRAY_MIN_ALLOCATION_SIZE);
while(new_capacity <= _size + new_elems) {
new_capacity *= 2;
}
T* const new_data = allocate(new_capacity);
i64 moved = 0;
anton::uninitialized_move(_data, _data + position, new_data);
moved = position;
anton::uninitialized_copy(first, last, new_data + moved);
moved += new_elems;
anton::uninitialized_move(_data + position, _data + _size, new_data + moved);
anton::destruct_n(_data, _size);
deallocate(_data, _capacity);
_capacity = new_capacity;
_data = new_data;
_size += new_elems;
}
}
}
return _data + position;
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::insert_unsorted(const_iterator position, value_type const& value) -> iterator {
size_type const offset = static_cast<size_type>(position - begin());
return insert_unsorted(offset, value);
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::insert_unsorted(const_iterator position, value_type&& value) -> iterator {
size_type const offset = static_cast<size_type>(position - begin());
return insert_unsorted(offset, ANTON_MOV(value));
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::insert_unsorted(size_type position, value_type const& value) -> iterator {
if constexpr(ANTON_ITERATOR_DEBUG) {
ANTON_FAIL(position >= 0 && position <= _size, u8"index out of bounds");
}
ensure_capacity(_size + 1);
T* elem_ptr = _data + position;
if(position == _size) {
anton::construct(elem_ptr, value);
} else {
if constexpr(is_move_constructible<T>) {
anton::construct(_data + _size, ANTON_MOV(*elem_ptr));
} else {
anton::construct(_data + _size, *elem_ptr);
}
anton::destruct(elem_ptr);
anton::construct(elem_ptr, value);
}
++_size;
return elem_ptr;
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::insert_unsorted(size_type position, value_type&& value) -> iterator {
if constexpr(ANTON_ITERATOR_DEBUG) {
ANTON_FAIL(position >= 0 && position <= _size, u8"index out of bounds");
}
ensure_capacity(_size + 1);
T* elem_ptr = _data + position;
if(position == _size) {
anton::construct(elem_ptr, ANTON_MOV(value));
} else {
if constexpr(is_move_constructible<T>) {
anton::construct(_data + _size, ANTON_MOV(*elem_ptr));
} else {
anton::construct(_data + _size, *elem_ptr);
}
anton::destruct(elem_ptr);
anton::construct(elem_ptr, ANTON_MOV(value));
}
++_size;
return elem_ptr;
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::push_back(value_type const& value) -> T& {
ensure_capacity(_size + 1);
T* const element = _data + _size;
anton::construct(element, value);
++_size;
return *element;
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::push_back(value_type&& value) -> T& {
ensure_capacity(_size + 1);
T* const element = _data + _size;
anton::construct(element, ANTON_MOV(value));
++_size;
return *element;
}
template<typename T, typename Allocator>
template<typename... Args>
auto Array<T, Allocator>::emplace_back(Args&&... args) -> T& {
ensure_capacity(_size + 1);
T* const element = _data + _size;
anton::construct(element, ANTON_FWD(args)...);
++_size;
return *element;
}
template<typename T, typename Allocator>
void Array<T, Allocator>::erase_unsorted(size_type index) {
if constexpr(ANTON_ITERATOR_DEBUG) {
ANTON_FAIL(index <= size && index >= 0, u8"index out of bounds");
}
erase_unsorted_unchecked(index);
}
template<typename T, typename Allocator>
void Array<T, Allocator>::erase_unsorted_unchecked(size_type index) {
T* const element = _data + index;
T* const last_element = _data + _size - 1;
if(element != last_element) { // Prevent self assignment
*element = ANTON_MOV(*last_element);
}
anton::destruct(last_element);
--_size;
}
template<typename T, typename Allocator>
auto Array<T, Allocator>::erase_unsorted(const_iterator iter) -> iterator {
if constexpr(ANTON_ITERATOR_DEBUG) {
ANTON_FAIL(iter - _data >= 0 && iter - _data <= _size, "iterator out of bounds");
}
T* const position = const_cast<T*>(iter);
T* const last_element = _data + _size - 1;
if(position != last_element) {
*position = ANTON_MOV(*last_element);
}
anton::destruct(last_element);
--_size;
return position;
}
// template <typename T, typename Allocator>
// auto Array<T, Allocator>::erase_unsorted(const_iterator first, const_iterator last) -> iterator {
// #if ANTON_ITERATOR_DEBUG
// #endif // ANTON_ITERATOR_DEBUG
// if (first != last) {
// auto first_last_elems = last - first;
// auto last_end_elems = end() - last;
// auto elems_till_end = math::min(first_last_elems, last_end_elems);
// move(end() - elems_till_end, end(), first);
// destruct(end() - elems_till_end, end());
// _size -= first_last_elems;
// }
// return first;
// }
template<typename T, typename Allocator>
auto Array<T, Allocator>::erase(const_iterator first, const_iterator last) -> iterator {
if constexpr(ANTON_ITERATOR_DEBUG) {
ANTON_FAIL(first - _data >= 0 && first - _data <= _size, "iterator out of bounds");
ANTON_FAIL(last - _data >= 0 && last - _data <= _size, "iterator out of bounds");
}
if(first != last) {
iterator pos = anton::move(const_cast<value_type*>(last), end(), const_cast<value_type*>(first));
anton::destruct(pos, end());
_size -= last - first;
}
return const_cast<value_type*>(first);
}
template<typename T, typename Allocator>
void Array<T, Allocator>::pop_back() {
ANTON_VERIFY(_size > 0, u8"pop_back called on an empty Array");
anton::destruct(_data + _size - 1);
--_size;
}
template<typename T, typename Allocator>
void Array<T, Allocator>::clear() {
anton::destruct(_data, _data + _size);
_size = 0;
}
template<typename T, typename Allocator>
T* Array<T, Allocator>::allocate(size_type const size) {
void* mem = _allocator.allocate(size * static_cast<isize>(sizeof(T)), static_cast<isize>(alignof(T)));
return static_cast<T*>(mem);
}
template<typename T, typename Allocator>
void Array<T, Allocator>::deallocate(void* mem, size_type const size) {
_allocator.deallocate(mem, size * static_cast<isize>(sizeof(T)), static_cast<isize>(alignof(T)));
}
} // namespace anton
| 30,975 | 9,249 |
#include "stdafx.h"
using namespace std;
using namespace cv;
using namespace cvproc;
using namespace cvproc::imagematch;
void main()
{
cMatchManager mng;
mng.Init("match-script.txt", "@test");
cMatchResult *result = mng.m_sharedData.AllocMatchResult();
list<string> exts;
exts.push_back("jpg");
exts.push_back("png");
list <string> out;
CollectFiles(exts, "./image/", out);
out.sort();
for each (auto &str in out)
{
Mat img = imread(str);
result->Init(&mng.m_matchScript, img, "",
(sParseTree*)mng.m_matchScript.FindTreeLabel("@test"), true, true);
mng.Match(*result);
cout << "image=" << str << ", result = " << result->m_resultStr << endl;
}
mng.m_sharedData.FreeMatchResult(result);
cout << endl << endl << "press key down to exit program" << endl;
getchar();
}
| 802 | 310 |
version https://git-lfs.github.com/spec/v1
oid sha256:4bee13f1ae0dfeeb63f8afbdabf2f2c704da45573edd3063e914ae9149cba03c
size 2868
| 129 | 86 |
/*
* Semaphore.cpp
*
* Copyright (C) 2016 Cyrille Potereau
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
#include "Semaphore.h"
#include <time.h>
CSemaphore::CSemaphore (int32_t maxcount) :
m_MaxCnt(maxcount)
{
sem_init (&m_Sem, 0, 0);
}
CSemaphore::~CSemaphore ()
{
sem_destroy(&m_Sem);
}
bool CSemaphore::wait(int32_t timeout)
{
int32_t ret;
if(timeout == SEM_TIMEOUT_DONTWAIT)
{
ret = sem_trywait(&m_Sem);
}
else if (timeout == SEM_TIMEOUT_FOREVER)
{
ret = sem_wait(&m_Sem);
}
else
{
timespec t;
clock_gettime(CLOCK_REALTIME,&t);
t.tv_sec += timeout/1000;
t.tv_nsec += (timeout % 1000) * 1000000;
ret = sem_timedwait(&m_Sem, &t);
}
return (ret == 0);
}
void CSemaphore::post(void)
{
if (m_MaxCnt > 0)
{
int32_t val;
sem_getvalue(&m_Sem, &val);
if (val < m_MaxCnt)
{
sem_post(&m_Sem);
}
}
else
{
sem_post(&m_Sem);
}
}
| 964 | 490 |
#include "Trainer.h"
using namespace std;
void Trainer::bindModel(Model* pm){
this->pm = pm;
}
void Trainer::bindDataset(const DataHolder* pd){
this->pd = pd;
}
void Trainer::prepare()
{
}
void Trainer::ready()
{
}
void Trainer::initBasic(const std::vector<std::string>& param)
{
this->param = param;
}
std::vector<std::string> Trainer::getParam() const
{
return param;
}
bool Trainer::needAveragedDelta() const
{
return true;
}
double Trainer::loss(const size_t topn) const {
double res = 0;
size_t n = topn == 0 ? pd->size() : topn;
for(size_t i = 0; i < n; ++i){
res += pm->loss(pd->get(i));
}
return res / static_cast<double>(n);
}
Trainer::DeltaResult Trainer::batchDelta(std::atomic<bool>& cond,
const size_t start, const size_t cnt, const bool avg, const double slow)
{
return batchDelta(cond, start, cnt, avg);
}
void Trainer::applyDelta(const vector<double>& delta, const double factor)
{
pm->accumulateParameter(delta, factor);
}
| 965 | 368 |
// Copyright Take Vos 2021.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
#include "momentary_button_widget.hpp"
namespace hi::inline v1 {
widget_constraints const &momentary_button_widget::set_constraints() noexcept
{
_layout = {};
// On left side a check mark, on right side short-cut. Around the label extra margin.
hilet extra_size = extent2{theme().margin * 2.0f, theme().margin * 2.0f};
_constraints = set_constraints_button() + extra_size;
_constraints.margins = theme().margin;
return _constraints;
}
void momentary_button_widget::set_layout(widget_layout const &layout) noexcept
{
if (compare_store(_layout, layout)) {
_label_rectangle = aarectangle{theme().margin, 0.0f, layout.width() - theme().margin * 2.0f, layout.height()};
}
set_layout_button(layout);
}
void momentary_button_widget::draw(draw_context const &context) noexcept
{
if (*mode > widget_mode::invisible and overlaps(context, layout())) {
draw_label_button(context);
draw_button(context);
}
}
void momentary_button_widget::draw_label_button(draw_context const &context) noexcept
{
// Move the border of the button in the middle of a pixel.
context.draw_box(
layout(),
layout().rectangle(),
background_color(),
focus_color(),
theme().border_width,
border_side::inside,
corner_radii{theme().rounding_radius});
}
} // namespace hi::inline v1
| 1,563 | 502 |
//==================================================================================================
/**
EVE - Expressive Vector Engine
Copyright : EVE Contributors & Maintainers
SPDX-License-Identifier: MIT
**/
//==================================================================================================
#include <eve/function/diff/maxmag.hpp>
#include <type_traits>
TTS_CASE_TPL("Check diff(maxmag) return type", EVE_TYPE)
{
if constexpr(eve::floating_value<T>)
{
TTS_EXPR_IS(eve::diff_nth<2>(eve::maxmag)(T(), T()), T);
TTS_EXPR_IS(eve::diff_nth<1>(eve::maxmag)(T(), T()), T);
}
else
{
TTS_PASS("Unsupported type");
}
}
TTS_CASE_TPL("Check eve::diff(eve::maxmag) behavior", EVE_TYPE)
{
if constexpr(eve::floating_value<T>)
{
TTS_EQUAL(eve::diff_1st(eve::maxmag)(T{2},T{-3}), T(0));
TTS_EQUAL(eve::diff_2nd(eve::maxmag)(T{2},T{-3}), T(1));
TTS_EQUAL(eve::diff_1st(eve::maxmag)(T{-4},T{3}), T(1));
TTS_EQUAL(eve::diff_2nd(eve::maxmag)(T{-4},T{3}), T(0));
using v_t = eve::element_type_t<T>;
TTS_EQUAL(eve::diff_1st(eve::maxmag)(T(1), T(2), T(3), T(4), T(5)),T(0));
TTS_EQUAL(eve::diff_3rd(eve::maxmag)(T(1), T(2), T(10), T(4), T(5)),T(1));
TTS_EQUAL(eve::diff_nth<3>(eve::maxmag)(T(1), T(2), T(3), T(4), T(5)),T(0));
TTS_EQUAL(eve::diff_nth<6>(eve::maxmag)(T(1), T(2), T(3), T(4), T(5)),T(0));
TTS_EQUAL(eve::diff_nth<4>(eve::maxmag)(v_t(1), T(3), T(3), T(7), T(5)),T(1));
}
else
{
TTS_PASS("Unsupported type");
}
}
| 1,513 | 699 |
#include <iostream>
#include "stdlib.h"
#include "math.h"
#include "UnitTest++.h"
#include <Epetra_MpiComm.h>
#include "Epetra_SerialComm.h"
#include "Teuchos_ParameterList.hpp"
#include "Teuchos_ParameterXMLFileReader.hpp"
#include "CycleDriver.hh"
#include "eos_registration.hh"
#include "Mesh.hh"
#include "MeshFactory.hh"
#include "mpc_pks_registration.hh"
#include "PK_Factory.hh"
#include "PK.hh"
#include "pks_flow_registration.hh"
#include "pks_transport_registration.hh"
#include "pks_chemistry_registration.hh"
#include "State.hh"
TEST(MPC_DRIVER_FLOW_REACTIVE_TRANSPORT) {
using namespace Amanzi;
using namespace Amanzi::AmanziMesh;
using namespace Amanzi::AmanziGeometry;
auto comm = Amanzi::getDefaultComm();
// read the main parameter list
std::string xmlInFileName = "test/mpc_flow_reactive_transport.xml";
Teuchos::ParameterXMLFileReader xmlreader(xmlInFileName);
Teuchos::ParameterList plist = xmlreader.getParameters();
// For now create one geometric model from all the regions in the spec
Teuchos::ParameterList region_list = plist.get<Teuchos::ParameterList>("regions");
Teuchos::RCP<Amanzi::AmanziGeometry::GeometricModel> gm =
Teuchos::rcp(new Amanzi::AmanziGeometry::GeometricModel(3, region_list, *comm));
// create mesh
Preference pref;
pref.clear();
pref.push_back(Framework::MSTK);
pref.push_back(Framework::STK);
MeshFactory meshfactory(comm,gm);
meshfactory.set_preference(pref);
Teuchos::RCP<Mesh> mesh = meshfactory.create(0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 100, 1, 1);
AMANZI_ASSERT(!mesh.is_null());
// create dummy observation data object
double avg1, avg2;
Amanzi::ObservationData obs_data;
Teuchos::RCP<Teuchos::ParameterList> glist = Teuchos::rcp(new Teuchos::ParameterList(plist));
Teuchos::ParameterList state_plist = glist->sublist("state");
Teuchos::RCP<Amanzi::State> S = Teuchos::rcp(new Amanzi::State(state_plist));
S->RegisterMesh("domain", mesh);
{
Amanzi::CycleDriver cycle_driver(glist, S, comm, obs_data);
try {
cycle_driver.Go();
S->GetFieldData("pressure")->MeanValue(&avg1);
} catch (...) {
CHECK(false);
}
// check observations
std::vector<std::string> labels = obs_data.observationLabels();
std::vector<ObservationData::DataQuadruple> tmp = obs_data[labels[0]];
for (int k = 1; k < tmp.size(); ++k) {
CHECK_CLOSE(tmp[k].value, -0.0006, 1.0e-5);
}
tmp = obs_data[labels[1]];
for (int k = 1; k < tmp.size(); ++k) {
CHECK_CLOSE(tmp[k].value, -0.0002, 1.0e-5);
}
}
// restart simulation and compare results
glist->sublist("cycle driver").sublist("restart").set<std::string>("file name", "chk_frt00005.h5");
S = Teuchos::null;
avg2 = 0.;
S = Teuchos::rcp(new Amanzi::State(state_plist));
S->RegisterMesh("domain", mesh);
{
Amanzi::CycleDriver cycle_driver(glist, S, comm, obs_data);
try {
cycle_driver.Go();
S->GetFieldData("pressure")->MeanValue(&avg2);
} catch (...) {
CHECK(false);
}
}
CHECK_CLOSE(avg1, avg2, 1e-5 * avg1);
}
| 3,093 | 1,222 |
#include <date.h>
#include <gmock/gmock.h>
#include <boost/asio/buffer.hpp>
#include <reader.hpp>
#include <writer.hpp>
#include "SerializationTestTypes.hpp"
using namespace testing;
using namespace detail;
using namespace date;
using namespace std::chrono;
namespace asio = boost::asio;
template <size_t N>
class ReaderBase : public Test {
protected:
constexpr static auto arr_size = N;
ReaderBase()
: buf_{asio::buffer(main_buf_)}, writer_{buf_}, reader_{buf_} {}
private:
std::array<char, arr_size> main_buf_;
protected:
asio::mutable_buffer buf_;
writer writer_;
reader reader_;
};
class ReaderTest : public ReaderBase<10u> {
protected:
ReaderTest() {
writer_(fourByteNum);
writer_(twoByteNum);
}
int32_t fourByteNum = 5;
uint16_t twoByteNum = 15;
};
TEST_F(ReaderTest, ReadsIntegralValueAfterWrite) {
int32_t readFourByteNum;
reader_(readFourByteNum);
ASSERT_THAT(readFourByteNum, Eq(fourByteNum));
}
TEST_F(ReaderTest, ReadsTwoConsecutiveIntegralValuesAfterWrite) {
int32_t readFourByteNum;
reader_(readFourByteNum);
uint16_t readTwoByteNum;
reader_(readTwoByteNum);
ASSERT_THAT(readTwoByteNum, Eq(twoByteNum));
}
template <typename T>
class IntegralTypeReader : public ReaderBase<1024u> {
protected:
IntegralTypeReader() { writer_(num); }
T num{5};
};
using MyIntegralTypes = ::testing::Types<char, int8_t, int16_t, int64_t,
uint8_t, uint32_t, uint64_t>;
TYPED_TEST_CASE(IntegralTypeReader, MyIntegralTypes);
TYPED_TEST(IntegralTypeReader, ReadssVariousIntegralTypes) {
TypeParam readNum;
this->reader_(readNum);
ASSERT_THAT(readNum, Eq(this->num));
}
class BooleanTypeReader : public ReaderBase<4u> {
protected:
BooleanTypeReader() {
writer_(true);
writer_(false);
}
};
TEST_F(BooleanTypeReader, ReadsBooleanValuesAfterWrite) {
bool trueValueRead;
bool falseValueRead;
reader_(trueValueRead);
reader_(falseValueRead);
ASSERT_TRUE(trueValueRead);
ASSERT_FALSE(falseValueRead);
}
class FloatingPointTypeReader : public ReaderBase<14u> {
protected:
FloatingPointTypeReader() {
writer_(e);
writer_(ePrecise);
}
float e = 2.718281;
double ePrecise = 2.718281828459;
};
TEST_F(FloatingPointTypeReader, ReadsFloatValueAfterWrite) {
float eRead;
reader_(eRead);
ASSERT_THAT(eRead, Eq(e));
}
TEST_F(FloatingPointTypeReader, ReadsDoubleValueAfterWrite) {
float eRead;
reader_(eRead);
double ePreciseRead;
reader_(ePreciseRead);
ASSERT_THAT(ePreciseRead, ePrecise);
}
class EnumTypeReader : public ReaderBase<8u> {
protected:
enum class CharEnum : char { A = 'A', B = 'B', C = 'C' };
enum class UInt32Enum : uint32_t { X, Y };
EnumTypeReader() {
writer_(CharEnum::B);
writer_(UInt32Enum::X);
}
};
TEST_F(EnumTypeReader, ReadsCharEnumValueAfterWrite) {
CharEnum readValue;
reader_(readValue);
ASSERT_THAT(readValue, Eq(CharEnum::B));
}
TEST_F(EnumTypeReader, ReadsMultipleEnumValuesAfterWrite) {
CharEnum readFirst;
reader_(readFirst);
UInt32Enum readSecond;
reader_(readSecond);
ASSERT_THAT(readSecond, Eq(UInt32Enum::X));
}
class IntegralConstantReader : public ReaderBase<32u> {
protected:
using IntConstUInt16 = std::integral_constant<uint16_t, 0xf001>;
using IntConstUInt32 = std::integral_constant<uint32_t, 0xf0010203>;
IntegralConstantReader() {
writer_(uint16Member);
writer_(regularNum);
writer_(uint32Member);
writer_(regularNum);
}
IntConstUInt16 uint16Member;
int32_t regularNum = 5;
IntConstUInt32 uint32Member;
};
TEST_F(IntegralConstantReader, ReadsUInt16IntegralConstantValueAfterWrite) {
IntConstUInt16 readUint16Member;
reader_(readUint16Member);
int32_t readRegularNum;
reader_(readRegularNum);
ASSERT_THAT(readRegularNum, Eq(5));
}
TEST_F(IntegralConstantReader, ReadsMultipleIntegralConstantValuesAfterWrite) {
IntConstUInt16 readUint16Member;
reader_(readUint16Member);
int32_t readRegularNum;
reader_(readRegularNum);
IntConstUInt32 readUint32Member;
reader_(readUint32Member);
int32_t readSedondRegularNum;
reader_(readSedondRegularNum);
ASSERT_THAT(readSedondRegularNum, Eq(5));
}
TEST_F(IntegralConstantReader,
ConfirmsThatExceptionIsGeneratedWhenConstValueDoesNotMatchReadValue) {
std::integral_constant<uint16_t, 0xf002> differentConstValue;
ASSERT_THROW(reader_(differentConstValue), std::domain_error);
}
class StringReader : public ReaderBase<20u> {
protected:
StringReader() {
writer_("ABC");
writer_("12345");
}
};
TEST_F(StringReader, ReadsStringValueAfterWrite) {
std::string readWord;
reader_(readWord);
ASSERT_THAT(readWord, Eq("ABC"));
}
TEST_F(StringReader, ReadsConsecutiveStringValuesAfterWrite) {
std::string firstWord;
reader_(firstWord);
std::string secondWord;
reader_(secondWord);
ASSERT_THAT(secondWord, Eq("12345"));
}
class VectorReader : public ReaderBase<50u> {
protected:
VectorReader() {
writer_(numbers);
writer_(words);
}
std::vector<int32_t> numbers{1, 5, 10, 15};
std::vector<std::string> words{"A", "AB", "ABC"};
};
TEST_F(VectorReader, ReadsVectorOfIntegralValuesAfterWrite) {
std::vector<int32_t> readNumbers;
reader_(readNumbers);
ASSERT_THAT(readNumbers, Eq(numbers));
}
TEST_F(VectorReader, ReadsConsecutiveVectorsOfDifferentTypeslAfterWrite) {
std::vector<int32_t> readNumbers;
reader_(readNumbers);
std::vector<std::string> readWords;
reader_(readWords);
ASSERT_THAT(readWords, Eq(words));
}
class DateTimeReader : public ReaderBase<15u> {
protected:
DateTimeReader() { writer_(microsecDateTime); }
sys_time<microseconds> microsecDateTime{sys_days(2016_y / 05 / 01) +
hours{5} + minutes{15} +
seconds{0} + microseconds{123456}};
};
TEST_F(DateTimeReader, ReadsTimePointWithMicrosecondsAfterWrite) {
sys_time<microseconds> microsecDateTimeRead;
reader_(microsecDateTimeRead);
ASSERT_THAT(microsecDateTimeRead, Eq(microsecDateTime));
}
class UnorderedMapReader : public ReaderBase<50u> {
protected:
UnorderedMapReader() {
writer_(elements);
writer_(numElements);
}
std::unordered_map<int32_t, std::string> elements{
{1, "A"}, {2, "B"}, {3, "AB"}};
std::unordered_map<int16_t, uint32_t> numElements{{1, 5}, {2, 10}, {3, 15}};
};
TEST_F(UnorderedMapReader, ReadsUnorderedMapValueAfterWrite) {
std::unordered_map<int32_t, std::string> readElements;
reader_(readElements);
ASSERT_THAT(readElements, Eq(elements));
}
TEST_F(UnorderedMapReader, ReadsMultipleUnorderedMapValuesAfterWrite) {
std::unordered_map<int32_t, std::string> readElements;
reader_(readElements);
std::unordered_map<int16_t, uint32_t> readNumElements;
reader_(readNumElements);
ASSERT_THAT(readNumElements, Eq(numElements));
}
class SimpleFusionSequenceReader : public ReaderBase<20u> {
protected:
SimpleFusionSequenceReader() { writer_(header); }
SerializationTestTypes::header_t header = {
{}, 1, SerializationTestTypes::msg_type_t::B};
};
TEST_F(SimpleFusionSequenceReader, ReadsSequenceValuesAfterWrite) {
SerializationTestTypes::header_t readHeader;
reader_(readHeader);
ASSERT_THAT(readHeader.version, Eq(header.version));
ASSERT_THAT(readHeader.msg_type, Eq(header.msg_type));
ASSERT_THAT(readHeader.seq_num, Eq(header.seq_num));
}
class NestedFusionSequenceReader : public ReaderBase<30u> {
protected:
NestedFusionSequenceReader() { writer_(msg); }
SerializationTestTypes::some_message_t msg = {{"12"}, {{"AB", "C"}}};
};
TEST_F(NestedFusionSequenceReader, ReadsNestedFusionSequenceValueAfterWrite) {
SerializationTestTypes::some_message_t readMsg;
reader_(readMsg);
ASSERT_THAT(readMsg.id, Eq(msg.id));
ASSERT_THAT(readMsg.properties.value, Eq(msg.properties.value));
}
class OptionalFieldReader : public ReaderBase<10u> {
protected:
OptionalFieldReader() {
writer_(optFieldsMask);
writer_(optIntField);
writer_(optMsg);
writer_(description);
}
SerializationTestTypes::opt_fields optFieldsMask;
SerializationTestTypes::opt_int32_field optIntField = 5;
SerializationTestTypes::opt_msg_type_t optMsg;
SerializationTestTypes::opt_string_t description = {"AB"};
};
TEST_F(OptionalFieldReader, ReadsOptionalFieldSetAndOptionalValueAfterWrite) {
SerializationTestTypes::opt_fields readOptFieldsMask;
reader_(readOptFieldsMask);
SerializationTestTypes::opt_int32_field readOptIntField;
reader_(readOptIntField);
ASSERT_THAT(*readOptIntField, Eq(*optIntField));
}
TEST_F(OptionalFieldReader, ReadsNonSetOptionalFieldValueAfterWrite) {
SerializationTestTypes::opt_fields readOptFieldsMask;
reader_(readOptFieldsMask);
SerializationTestTypes::opt_int32_field readOptIntField;
reader_(readOptIntField);
SerializationTestTypes::opt_msg_type_t readOptMsg;
reader_(readOptMsg);
ASSERT_FALSE(readOptMsg);
}
TEST_F(OptionalFieldReader, ReadsOptionalFieldValueAfterNonSetValueAfterWrite) {
SerializationTestTypes::opt_fields readOptFieldsMask;
reader_(readOptFieldsMask);
SerializationTestTypes::opt_int32_field readOptIntField;
reader_(readOptIntField);
SerializationTestTypes::opt_msg_type_t readOptMsg;
reader_(readOptMsg);
SerializationTestTypes::opt_string_t readDescription;
reader_(readDescription);
ASSERT_THAT(*readDescription, Eq(description));
}
TEST_F(OptionalFieldReader,
ConfirmsThatExceptionIsGeneratedWhenFieldIsReadBeforeFieldSet) {
SerializationTestTypes::opt_int32_field readOptIntField;
ASSERT_THROW(reader_(readOptIntField), std::domain_error);
}
TEST_F(ReaderTest, ReadsIntegralValueWithReadFunction) {
auto readFourByteNum = read<int32_t>(buf_);
auto readTwoByteNum = read<uint16_t>(readFourByteNum.second);
ASSERT_THAT(readFourByteNum.first, Eq(fourByteNum));
ASSERT_THAT(readTwoByteNum.first, Eq(twoByteNum));
}
TEST_F(EnumTypeReader, ReadsMultipleEnumValuesWithReadFunction) {
auto readFirst = read<CharEnum>(buf_);
auto readSecond = read<UInt32Enum>(readFirst.second);
ASSERT_THAT(readFirst.first, Eq(CharEnum::B));
ASSERT_THAT(readSecond.first, Eq(UInt32Enum::X));
}
TEST_F(IntegralConstantReader,
ReadsMultipleIntegralConstantValuesWithReadFunction) {
auto readUint16Member = read<IntConstUInt16>(buf_);
auto readRegularNum = read<int32_t>(readUint16Member.second);
auto readUint32Member = read<IntConstUInt32>(readRegularNum.second);
auto readSedondRegularNum = read<int32_t>(readUint32Member.second);
ASSERT_THAT(readSedondRegularNum.first, Eq(5));
}
TEST_F(StringReader, ReadsConsecutiveStringValuesWithReadFunction) {
auto firstWord = read<std::string>(buf_);
auto secondWord = read<std::string>(firstWord.second);
ASSERT_THAT(secondWord.first, Eq("12345"));
}
TEST_F(VectorReader, ReadsConsecutiveVectorsOfDifferentTypesWithReadFunction) {
auto readNumbes = read<std::vector<int32_t>>(buf_);
auto readWords = read<std::vector<std::string>>(readNumbes.second);
ASSERT_THAT(readWords.first, Eq(words));
}
TEST_F(UnorderedMapReader, ReadsMultipleUnorderedMapValuesWithReadFunction) {
auto readElements = read<std::unordered_map<int32_t, std::string>>(buf_);
auto readNumElements =
read<std::unordered_map<int16_t, uint32_t>>(readElements.second);
ASSERT_THAT(readNumElements.first, Eq(numElements));
}
TEST_F(NestedFusionSequenceReader,
ReadsNestedFusionSequenceValueWithReadFunction) {
auto readMsg = read<SerializationTestTypes::some_message_t>(buf_);
ASSERT_THAT(readMsg.first.id, Eq(msg.id));
ASSERT_THAT(readMsg.first.properties.value, Eq(msg.properties.value));
}
TEST_F(
OptionalFieldReader,
ConfirmsThatExceptionIsGeneratedWhenReadingOptionalFieldsWithReadFunction) {
auto readOptFieldsMask = read<SerializationTestTypes::opt_fields>(buf_);
ASSERT_THROW(
read<SerializationTestTypes::opt_int32_field>(readOptFieldsMask.second),
std::domain_error);
}
class FusionSequenceWithOptionalFieldReader : public ReaderBase<50u> {
protected:
FusionSequenceWithOptionalFieldReader() { writer_(msg); }
SerializationTestTypes::msg_with_opt_fields_t msg = {
{{"A", "B", "AB"}}, {}, {5}, {}};
};
TEST_F(FusionSequenceWithOptionalFieldReader,
ReadOptionalFieldsAsPartOfFusionSequenceWithReadFunction) {
auto readMsg = read<SerializationTestTypes::msg_with_opt_fields_t>(buf_);
ASSERT_THAT(readMsg.first.properties.value, Eq(msg.properties.value));
ASSERT_THAT(readMsg.first.number, Eq(5));
}
| 12,975 | 4,506 |
#include <climits>
#include <cmath>
#include <queue>
#include <vector>
using namespace std;
class Solution
{
public:
int minimumEffortPath(vector<vector<int>> &heights)
{
int M = heights.size(), N = heights[0].size();
priority_queue<pair<int, int>> q; //{effort,position}
vector<vector<int>> seen(M, vector<int>(N, INT_MAX));
seen[0][0] = 0;
q.push({0, 0});
while (!q.empty())
{
int x = q.top().second / N, y = q.top().second % N;
int effort = -q.top().first;
q.pop();
if (x == M - 1 && y == N - 1)
return effort;
//board dfs direction
int path[5] = {-1, 0, 1, 0, -1};
for (int i = 0; i < 4; ++i)
{
int dx = x + path[i], dy = y + path[i + 1];
if (dx < 0 || dx >= M || dy < 0 || dy >= N)
continue;
int curEffort = abs(heights[x][y] - heights[dx][dy]);
curEffort = max(curEffort, effort);
if (curEffort < seen[dx][dy])
{
seen[dx][dy] = curEffort;
q.push({-curEffort, dx * N + dy});
}
}
}
return -1;
}
}; | 997 | 497 |
/*
* Copyright 2019 pixiv Inc. All Rights Reserved.
*
* Use of this source code is governed by a license that can be
* found in the LICENSE.pixiv file in the root of the source tree.
*/
#include "api/media_stream_interface.h"
#include "rtc_base/ref_counted_object.h"
#include "sdk/c/api/media_stream_interface.h"
namespace webrtc {
class DelegatingAudioSourceInterface : public AudioSourceInterface {
public:
DelegatingAudioSourceInterface(
void* context,
const struct AudioSourceInterfaceFunctions* functions) {
context_ = context;
functions_ = functions;
}
~DelegatingAudioSourceInterface() { functions_->on_destruction(context_); }
void RegisterObserver(ObserverInterface* observer) {
functions_->register_observer(context_, rtc::ToC(observer));
}
void UnregisterObserver(ObserverInterface* observer) {
functions_->unregister_observer(context_, rtc::ToC(observer));
}
void AddSink(AudioTrackSinkInterface* sink) {
functions_->add_sink(context_, rtc::ToC(sink));
}
void RemoveSink(AudioTrackSinkInterface* sink) {
functions_->remove_sink(context_, rtc::ToC(sink));
}
SourceState state() const {
return static_cast<SourceState>(functions_->state(context_));
}
bool remote() const { return functions_->remote(context_); }
private:
void* context_;
const struct AudioSourceInterfaceFunctions* functions_;
};
}
extern "C" WebrtcMediaSourceInterface*
webrtcAudioSourceInterfaceToWebrtcMediaSourceInterface(
WebrtcAudioSourceInterface* source) {
return rtc::ToC(
static_cast<webrtc::MediaSourceInterface*>(rtc::ToCplusplus(source)));
}
extern "C" void webrtcAudioTrackInterfaceAddSink(
WebrtcAudioTrackInterface* track,
WebrtcAudioTrackSinkInterface* sink) {
rtc::ToCplusplus(track)->AddSink(rtc::ToCplusplus(sink));
}
extern "C" WebrtcMediaStreamTrackInterface*
webrtcAudioTrackInterfaceToWebrtcMediaStreamTrackInterface(
WebrtcAudioTrackInterface* track) {
return rtc::ToC(
static_cast<webrtc::MediaStreamTrackInterface*>(rtc::ToCplusplus(track)));
}
extern "C" void webrtcAudioTrackSinkInterfaceOnData(
WebrtcAudioTrackSinkInterface* sink,
const void* audio_data,
int bits_per_sample,
int sample_rate,
size_t number_of_channels,
size_t number_of_frames) {
rtc::ToCplusplus(sink)->OnData(audio_data, bits_per_sample, sample_rate,
number_of_channels, number_of_frames);
}
extern "C" void webrtcMediaSourceInterfaceRelease(
const WebrtcMediaSourceInterface* source) {
rtc::ToCplusplus(source)->Release();
}
extern "C" WebrtcVideoTrackSourceInterface*
webrtcMediaSourceInterfaceToWebrtcVideoTrackSourceInterface(
WebrtcMediaSourceInterface* source) {
return rtc::ToC(static_cast<webrtc::VideoTrackSourceInterface*>(
rtc::ToCplusplus(source)));
}
extern "C" void webrtcMediaStreamInterfaceRelease(
const WebrtcMediaStreamInterface* stream) {
rtc::ToCplusplus(stream)->Release();
}
extern "C" RtcString* webrtcMediaStreamTrackInterfaceId(
const WebrtcMediaStreamTrackInterface* track) {
return rtc::ToC(new auto(rtc::ToCplusplus(track)->id()));
}
extern "C" void webrtcMediaStreamTrackInterfaceRelease(
const WebrtcMediaStreamTrackInterface* track) {
rtc::ToCplusplus(track)->Release();
}
extern "C" const char* webrtcMediaStreamTrackInterfaceKAudioKind() {
return webrtc::MediaStreamTrackInterface::kAudioKind;
}
extern "C" const char* webrtcMediaStreamTrackInterfaceKind(
const WebrtcMediaStreamTrackInterface* track) {
auto kind = rtc::ToCplusplus(track)->kind();
if (kind == webrtc::MediaStreamTrackInterface::kAudioKind) {
return webrtc::MediaStreamTrackInterface::kAudioKind;
}
if (kind == webrtc::MediaStreamTrackInterface::kVideoKind) {
return webrtc::MediaStreamTrackInterface::kVideoKind;
}
RTC_NOTREACHED();
return nullptr;
}
extern "C" const char* webrtcMediaStreamTrackInterfaceKVideoKind() {
return webrtc::MediaStreamTrackInterface::kVideoKind;
}
extern "C" WebrtcAudioTrackInterface*
webrtcMediaStreamTrackInterfaceToWebrtcAudioTrackInterface(
WebrtcMediaStreamTrackInterface* track) {
return rtc::ToC(
static_cast<webrtc::AudioTrackInterface*>(rtc::ToCplusplus(track)));
}
extern "C" WebrtcVideoTrackInterface*
webrtcMediaStreamTrackInterfaceToWebrtcVideoTrackInterface(
WebrtcMediaStreamTrackInterface* track) {
return rtc::ToC(
static_cast<webrtc::VideoTrackInterface*>(rtc::ToCplusplus(track)));
}
extern "C" WebrtcAudioSourceInterface* webrtcNewAudioSourceInterface(
void* context,
const struct AudioSourceInterfaceFunctions* functions) {
auto source =
new rtc::RefCountedObject<webrtc::DelegatingAudioSourceInterface>(
context, functions);
source->AddRef();
return rtc::ToC(static_cast<webrtc::AudioSourceInterface*>(source));
}
extern "C" void webrtcVideoTrackInterfaceAddOrUpdateSink(
WebrtcVideoTrackInterface* track,
RtcVideoSinkInterface* sink,
const struct RtcVideoSinkWants* cwants) {
rtc::VideoSinkWants wants;
wants.rotation_applied = cwants->rotation_applied;
wants.black_frames = cwants->black_frames;
wants.max_pixel_count = cwants->max_pixel_count;
wants.max_framerate_fps = cwants->max_framerate_fps;
if (cwants->has_target_pixel_count) {
wants.target_pixel_count = cwants->target_pixel_count;
}
return rtc::ToCplusplus(track)->AddOrUpdateSink(rtc::ToCplusplus(sink),
wants);
}
extern "C" WebrtcMediaStreamTrackInterface*
webrtcVideoTrackInterfaceToWebrtcMediaStreamTrackInterface(
WebrtcVideoTrackInterface* track) {
return rtc::ToC(
static_cast<webrtc::MediaStreamTrackInterface*>(rtc::ToCplusplus(track)));
}
| 5,810 | 1,897 |
//
// Created by kier on 2018/6/29.
//
#include "global/operator_factory.h"
#include <map>
#include <global/operator_factory.h>
#include "global/memory_device.h"
namespace ts {
using Name = std::pair<DeviceType, std::string>;
template<typename K, typename V>
using map = std::map<K, V>;
static map<Name, OperatorCreator::function> &MapNameCreator() {
static map<Name, OperatorCreator::function> map_name_creator;
return map_name_creator;
};
OperatorCreator::function OperatorCreator::Query(const DeviceType &device_type,
const std::string &operator_name) TS_NOEXCEPT {
auto &map_name_creator = MapNameCreator();
Name device_operator_name = std::make_pair(device_type, operator_name);
auto name_creator = map_name_creator.find(device_operator_name);
if (name_creator != map_name_creator.end()) {
return name_creator->second;
}
return OperatorCreator::function(nullptr);
}
void OperatorCreator::Register(const DeviceType &device_type,
const std::string &operator_name,
const OperatorCreator::function &operator_creator) TS_NOEXCEPT {
auto &map_name_creator = MapNameCreator();
Name device_operator_name = std::make_pair(device_type, operator_name);
map_name_creator[device_operator_name] = operator_creator;
}
const OperatorCreator::CreatorFucMap OperatorCreator::GetCreatorFucMap(){
auto map_name_creator = MapNameCreator();
return std::move(map_name_creator);
}
void OperatorCreator::flush(const OperatorCreator::CreatorFucMap& creator_map){
auto &map_name_creator = MapNameCreator();
map_name_creator.clear();
for(auto it=creator_map.begin(); it!=creator_map.end(); ++it){
map_name_creator[it->first] = it->second;
}
}
void OperatorCreator::Clear() {
auto &map_name_creator = MapNameCreator();
map_name_creator.clear();
}
static OperatorCreator::function TalentQuery(const DeviceType &device_type,
const std::string &operator_name, bool strict) {
// step 1: check in strict mode
auto creator = OperatorCreator::Query(device_type, operator_name);
if (strict) return creator;
if (creator == nullptr) {
// step 2.x: try find operator on memory device, if computing device failed
auto memory_device = ComputingMemory::Query(device_type);
creator = OperatorCreator::Query(memory_device, operator_name);
}
if (creator == nullptr) {
// step 2.y: try find operator on CPU version
if (device_type != CPU) {
creator = OperatorCreator::Query(CPU, operator_name);
}
}
return creator;
}
Operator::shared OperatorCreator::CreateNoException(const DeviceType &device_type, const std::string &operator_name,
bool strict) TS_NOEXCEPT {
auto creator = TalentQuery(device_type, operator_name, strict);
if (!creator) return nullptr;
return creator();
}
OperatorCreator::function
OperatorCreator::Query(const DeviceType &device_type, const std::string &operator_name, bool strict) TS_NOEXCEPT {
return TalentQuery(device_type, operator_name, strict);
}
Operator::shared
OperatorCreator::Create(const DeviceType &device_type, const std::string &operator_name, bool strict) {
auto op = CreateNoException(device_type, operator_name, strict);
if (op == nullptr) throw OperatorNotFoundException(device_type, operator_name);
return op;
}
std::set<std::pair<std::string, std::string>> OperatorCreator::AllKeys() TS_NOEXCEPT {
auto &map_name_creator = MapNameCreator();
std::set<std::pair<std::string, std::string>> set_name;
for (auto &name : map_name_creator) {
auto &pair = name.first;
set_name.insert(std::make_pair(pair.first.std(), pair.second));
}
return set_name;
}
}
| 4,252 | 1,260 |
// Generated by the gRPC C++ plugin.
// If you make any local change, they will be lost.
// source: tensorflow_serving/apis/prediction_service.proto
#include "tensorflow_serving/apis/prediction_service.pb.h"
#include "tensorflow_serving/apis/prediction_service.grpc.pb.h"
#include <grpcpp/impl/codegen/async_stream.h>
#include <grpcpp/impl/codegen/async_unary_call.h>
#include <grpcpp/impl/codegen/channel_interface.h>
#include <grpcpp/impl/codegen/client_unary_call.h>
#include <grpcpp/impl/codegen/method_handler_impl.h>
#include <grpcpp/impl/codegen/rpc_service_method.h>
#include <grpcpp/impl/codegen/service_type.h>
#include <grpcpp/impl/codegen/sync_stream.h>
namespace tensorflow {
namespace serving {
static const char* PredictionService_method_names[] = {
"/tensorflow.serving.PredictionService/Classify",
"/tensorflow.serving.PredictionService/Regress",
"/tensorflow.serving.PredictionService/Predict",
"/tensorflow.serving.PredictionService/MultiInference",
"/tensorflow.serving.PredictionService/GetModelMetadata",
};
std::unique_ptr< PredictionService::Stub> PredictionService::NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& options) {
(void)options;
std::unique_ptr< PredictionService::Stub> stub(new PredictionService::Stub(channel));
return stub;
}
PredictionService::Stub::Stub(const std::shared_ptr< ::grpc::ChannelInterface>& channel)
: channel_(channel), rpcmethod_Classify_(PredictionService_method_names[0], ::grpc::internal::RpcMethod::NORMAL_RPC, channel)
, rpcmethod_Regress_(PredictionService_method_names[1], ::grpc::internal::RpcMethod::NORMAL_RPC, channel)
, rpcmethod_Predict_(PredictionService_method_names[2], ::grpc::internal::RpcMethod::NORMAL_RPC, channel)
, rpcmethod_MultiInference_(PredictionService_method_names[3], ::grpc::internal::RpcMethod::NORMAL_RPC, channel)
, rpcmethod_GetModelMetadata_(PredictionService_method_names[4], ::grpc::internal::RpcMethod::NORMAL_RPC, channel)
{}
::grpc::Status PredictionService::Stub::Classify(::grpc::ClientContext* context, const ::tensorflow::serving::ClassificationRequest& request, ::tensorflow::serving::ClassificationResponse* response) {
return ::grpc::internal::BlockingUnaryCall(channel_.get(), rpcmethod_Classify_, context, request, response);
}
::grpc::ClientAsyncResponseReader< ::tensorflow::serving::ClassificationResponse>* PredictionService::Stub::AsyncClassifyRaw(::grpc::ClientContext* context, const ::tensorflow::serving::ClassificationRequest& request, ::grpc::CompletionQueue* cq) {
return ::grpc::internal::ClientAsyncResponseReaderFactory< ::tensorflow::serving::ClassificationResponse>::Create(channel_.get(), cq, rpcmethod_Classify_, context, request, true);
}
::grpc::ClientAsyncResponseReader< ::tensorflow::serving::ClassificationResponse>* PredictionService::Stub::PrepareAsyncClassifyRaw(::grpc::ClientContext* context, const ::tensorflow::serving::ClassificationRequest& request, ::grpc::CompletionQueue* cq) {
return ::grpc::internal::ClientAsyncResponseReaderFactory< ::tensorflow::serving::ClassificationResponse>::Create(channel_.get(), cq, rpcmethod_Classify_, context, request, false);
}
::grpc::Status PredictionService::Stub::Regress(::grpc::ClientContext* context, const ::tensorflow::serving::RegressionRequest& request, ::tensorflow::serving::RegressionResponse* response) {
return ::grpc::internal::BlockingUnaryCall(channel_.get(), rpcmethod_Regress_, context, request, response);
}
::grpc::ClientAsyncResponseReader< ::tensorflow::serving::RegressionResponse>* PredictionService::Stub::AsyncRegressRaw(::grpc::ClientContext* context, const ::tensorflow::serving::RegressionRequest& request, ::grpc::CompletionQueue* cq) {
return ::grpc::internal::ClientAsyncResponseReaderFactory< ::tensorflow::serving::RegressionResponse>::Create(channel_.get(), cq, rpcmethod_Regress_, context, request, true);
}
::grpc::ClientAsyncResponseReader< ::tensorflow::serving::RegressionResponse>* PredictionService::Stub::PrepareAsyncRegressRaw(::grpc::ClientContext* context, const ::tensorflow::serving::RegressionRequest& request, ::grpc::CompletionQueue* cq) {
return ::grpc::internal::ClientAsyncResponseReaderFactory< ::tensorflow::serving::RegressionResponse>::Create(channel_.get(), cq, rpcmethod_Regress_, context, request, false);
}
::grpc::Status PredictionService::Stub::Predict(::grpc::ClientContext* context, const ::tensorflow::serving::PredictRequest& request, ::tensorflow::serving::PredictResponse* response) {
return ::grpc::internal::BlockingUnaryCall(channel_.get(), rpcmethod_Predict_, context, request, response);
}
::grpc::ClientAsyncResponseReader< ::tensorflow::serving::PredictResponse>* PredictionService::Stub::AsyncPredictRaw(::grpc::ClientContext* context, const ::tensorflow::serving::PredictRequest& request, ::grpc::CompletionQueue* cq) {
return ::grpc::internal::ClientAsyncResponseReaderFactory< ::tensorflow::serving::PredictResponse>::Create(channel_.get(), cq, rpcmethod_Predict_, context, request, true);
}
::grpc::ClientAsyncResponseReader< ::tensorflow::serving::PredictResponse>* PredictionService::Stub::PrepareAsyncPredictRaw(::grpc::ClientContext* context, const ::tensorflow::serving::PredictRequest& request, ::grpc::CompletionQueue* cq) {
return ::grpc::internal::ClientAsyncResponseReaderFactory< ::tensorflow::serving::PredictResponse>::Create(channel_.get(), cq, rpcmethod_Predict_, context, request, false);
}
::grpc::Status PredictionService::Stub::MultiInference(::grpc::ClientContext* context, const ::tensorflow::serving::MultiInferenceRequest& request, ::tensorflow::serving::MultiInferenceResponse* response) {
return ::grpc::internal::BlockingUnaryCall(channel_.get(), rpcmethod_MultiInference_, context, request, response);
}
::grpc::ClientAsyncResponseReader< ::tensorflow::serving::MultiInferenceResponse>* PredictionService::Stub::AsyncMultiInferenceRaw(::grpc::ClientContext* context, const ::tensorflow::serving::MultiInferenceRequest& request, ::grpc::CompletionQueue* cq) {
return ::grpc::internal::ClientAsyncResponseReaderFactory< ::tensorflow::serving::MultiInferenceResponse>::Create(channel_.get(), cq, rpcmethod_MultiInference_, context, request, true);
}
::grpc::ClientAsyncResponseReader< ::tensorflow::serving::MultiInferenceResponse>* PredictionService::Stub::PrepareAsyncMultiInferenceRaw(::grpc::ClientContext* context, const ::tensorflow::serving::MultiInferenceRequest& request, ::grpc::CompletionQueue* cq) {
return ::grpc::internal::ClientAsyncResponseReaderFactory< ::tensorflow::serving::MultiInferenceResponse>::Create(channel_.get(), cq, rpcmethod_MultiInference_, context, request, false);
}
::grpc::Status PredictionService::Stub::GetModelMetadata(::grpc::ClientContext* context, const ::tensorflow::serving::GetModelMetadataRequest& request, ::tensorflow::serving::GetModelMetadataResponse* response) {
return ::grpc::internal::BlockingUnaryCall(channel_.get(), rpcmethod_GetModelMetadata_, context, request, response);
}
::grpc::ClientAsyncResponseReader< ::tensorflow::serving::GetModelMetadataResponse>* PredictionService::Stub::AsyncGetModelMetadataRaw(::grpc::ClientContext* context, const ::tensorflow::serving::GetModelMetadataRequest& request, ::grpc::CompletionQueue* cq) {
return ::grpc::internal::ClientAsyncResponseReaderFactory< ::tensorflow::serving::GetModelMetadataResponse>::Create(channel_.get(), cq, rpcmethod_GetModelMetadata_, context, request, true);
}
::grpc::ClientAsyncResponseReader< ::tensorflow::serving::GetModelMetadataResponse>* PredictionService::Stub::PrepareAsyncGetModelMetadataRaw(::grpc::ClientContext* context, const ::tensorflow::serving::GetModelMetadataRequest& request, ::grpc::CompletionQueue* cq) {
return ::grpc::internal::ClientAsyncResponseReaderFactory< ::tensorflow::serving::GetModelMetadataResponse>::Create(channel_.get(), cq, rpcmethod_GetModelMetadata_, context, request, false);
}
PredictionService::Service::Service() {
AddMethod(new ::grpc::internal::RpcServiceMethod(
PredictionService_method_names[0],
::grpc::internal::RpcMethod::NORMAL_RPC,
new ::grpc::internal::RpcMethodHandler< PredictionService::Service, ::tensorflow::serving::ClassificationRequest, ::tensorflow::serving::ClassificationResponse>(
std::mem_fn(&PredictionService::Service::Classify), this)));
AddMethod(new ::grpc::internal::RpcServiceMethod(
PredictionService_method_names[1],
::grpc::internal::RpcMethod::NORMAL_RPC,
new ::grpc::internal::RpcMethodHandler< PredictionService::Service, ::tensorflow::serving::RegressionRequest, ::tensorflow::serving::RegressionResponse>(
std::mem_fn(&PredictionService::Service::Regress), this)));
AddMethod(new ::grpc::internal::RpcServiceMethod(
PredictionService_method_names[2],
::grpc::internal::RpcMethod::NORMAL_RPC,
new ::grpc::internal::RpcMethodHandler< PredictionService::Service, ::tensorflow::serving::PredictRequest, ::tensorflow::serving::PredictResponse>(
std::mem_fn(&PredictionService::Service::Predict), this)));
AddMethod(new ::grpc::internal::RpcServiceMethod(
PredictionService_method_names[3],
::grpc::internal::RpcMethod::NORMAL_RPC,
new ::grpc::internal::RpcMethodHandler< PredictionService::Service, ::tensorflow::serving::MultiInferenceRequest, ::tensorflow::serving::MultiInferenceResponse>(
std::mem_fn(&PredictionService::Service::MultiInference), this)));
AddMethod(new ::grpc::internal::RpcServiceMethod(
PredictionService_method_names[4],
::grpc::internal::RpcMethod::NORMAL_RPC,
new ::grpc::internal::RpcMethodHandler< PredictionService::Service, ::tensorflow::serving::GetModelMetadataRequest, ::tensorflow::serving::GetModelMetadataResponse>(
std::mem_fn(&PredictionService::Service::GetModelMetadata), this)));
}
PredictionService::Service::~Service() {
}
::grpc::Status PredictionService::Service::Classify(::grpc::ServerContext* context, const ::tensorflow::serving::ClassificationRequest* request, ::tensorflow::serving::ClassificationResponse* response) {
(void) context;
(void) request;
(void) response;
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
::grpc::Status PredictionService::Service::Regress(::grpc::ServerContext* context, const ::tensorflow::serving::RegressionRequest* request, ::tensorflow::serving::RegressionResponse* response) {
(void) context;
(void) request;
(void) response;
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
::grpc::Status PredictionService::Service::Predict(::grpc::ServerContext* context, const ::tensorflow::serving::PredictRequest* request, ::tensorflow::serving::PredictResponse* response) {
(void) context;
(void) request;
(void) response;
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
::grpc::Status PredictionService::Service::MultiInference(::grpc::ServerContext* context, const ::tensorflow::serving::MultiInferenceRequest* request, ::tensorflow::serving::MultiInferenceResponse* response) {
(void) context;
(void) request;
(void) response;
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
::grpc::Status PredictionService::Service::GetModelMetadata(::grpc::ServerContext* context, const ::tensorflow::serving::GetModelMetadataRequest* request, ::tensorflow::serving::GetModelMetadataResponse* response) {
(void) context;
(void) request;
(void) response;
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
} // namespace tensorflow
} // namespace serving
| 11,612 | 3,427 |
#include <iostream>
#include <math.h>
#include <random>
#include <vector>
#include <fstream>
#include <map>
#include <string>
#include <algorithm>
#include <mpi.h>
#include <omp.h>
#include "Randomize.h"
#include "Ising.h"
#include "ArrayUtilities.h"
/*
*
* This function runs totalS number of parallel chains each on a temperature level defined in temps.
* Each MPI process is responsible for 1 or more chains in the pool.
* Each chain is run iterNum number of iterations where each iteration consists of T number of steps
* The chains communicates via MPI send and receive. temperedChains outputs result in the result array.
*
* Function Arguments:
* iterNum: number of iterations
* totalS: total number of parallel chains (each core may run more than one chain)
* Nd: dimension of state space
* T: number of steps each iteration
* rank: rank of current MPI process
* size: number of concurrent MPI processes
*
* */
void temperedChainsIsing(int iterNum, int totalS, int Nd, int T, double *temps, int rank, int size, int kernel)
{
// Each MPI process is assigned S chains to run
int S=totalS/size;
if (rank==size-1)
{
S=totalS/size+totalS%size;
}
// Each MPI process stores results in partialresult array of S columns and iterNum rows
int **partialresult;
create2Dmemory(partialresult,iterNum,S);
// Each MPI process has a different seed
srand(unsigned(time(0))+rank);
// Each chain creates a new starting state from uniform sampling
int ***xs;
create3Dmemory(xs, S, Nd,Nd);
for (int chains=0; chains<S; ++chains)
{
for (int i=0; i<Nd; ++i)
{
for (int j=0;j<Nd; ++j)
{
if (unifrnd(0,1)<0.5)
xs[chains][i][j]=1;
else{
xs[chains][i][j]=0;
}
}
}
}
/* Define variables used in the loop */
int exchangetimes=0; // total number of exchange that occur
double originallog; // store value of log target in prev step
double proplog; // store value of log target of the proposal
int glbc1; // global idx of chain 1 to exchange
int glbc2; // global idx of chain 2 to exchange
int rank1; // processor that runs chain 1
int rank2; // processor that runs chain 2
int c1; // local idx of chain 1 to exchange
int c2; // local idx of chain 2 to exchange
double coin; // store value of coin toss
double accpt; // store value of acceptance ratio
for (int iter=0; iter<iterNum; ++iter){
for (int chains=0; chains<S; ++chains)
{
if (kernel==0)
{
oneChainIsing(xs[chains], T, Nd, temps[chains+rank*S]);
} else {
oneChainIsingChess(xs[chains], T, Nd, temps[chains+rank*S]);
}
partialresult[iter][chains]=t(xs[chains],Nd);
}
// Global index of the two chain to exchange positions
glbc1=iterNum % totalS;
glbc2=(iterNum+1) % totalS;
if (totalS==1)
{
glbc1=0;
glbc2=0;
}
// Which processors these two indexes belong to
rank1=glbc1/S;
rank2=glbc2/S;
// Current process is not involved in exchange
if ((rank1!=rank)&&(rank2!=rank))
{
continue;
}
// Both indexes to exchange belong to current process
else if (rank1==rank2){
// Convert global indexes to local indexes
c1=glbc1%S;
c2=glbc2%S;
// Compute acceptance ratio
originallog=logtargetIsing(xs[c1],Nd,temps[c1])+logtargetIsing(xs[c2],Nd,temps[c2]);
proplog=logtargetIsing(xs[c1],Nd,temps[c2])+logtargetIsing(xs[c2],Nd,temps[c1]);
accpt=exp(proplog-originallog);
// Determine if accept by toss a random coin
coin=unifrnd(0,1);
if (coin<accpt){
// We indeed accept the proposal
int **imp;
imp=xs[c1];
xs[c1]=xs[c2];
xs[c2]=imp;
exchangetimes+=1;
}
}
// Indexes to exchange occur on two different processes
else {
if (rank == rank1){
int c1=glbc1%S;
double logtgtc1c1=logtargetIsing(xs[c1],Nd,temps[glbc1]);
double logtgtc1c2=logtargetIsing(xs[c1],Nd,temps[glbc2]);
int **xsc2;
create2Dmemory(xsc2,Nd,Nd);
int xsc21D[Nd*Nd];
MPI_Recv(xsc21D,Nd*Nd,MPI_INT,rank2,0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
conv1Dto2D(xsc21D, xsc2, Nd, Nd);
double logtgtc2c2=logtargetIsing(xsc2,Nd,temps[glbc2]);
double logtgtc2c1=logtargetIsing(xsc2,Nd,temps[glbc1]);
originallog=logtgtc1c1+logtgtc2c2;
proplog=logtgtc1c2+logtgtc2c1;
accpt=exp(proplog-originallog);
coin=unifrnd(0,1);
if (coin<accpt){
// We indeed accept the proposal, notify the other chain
int accptstatus=1;
MPI_Send(&accptstatus,1,MPI_INT,rank2,0,MPI_COMM_WORLD);
int xsc11D[Nd*Nd];
conv2Dto1D(xs[c1],xsc11D,Nd,Nd);
MPI_Send(xsc11D,Nd*Nd,MPI_INT,rank2,0,MPI_COMM_WORLD);
deepcopy2Darray(xsc2,xs[c1], Nd, Nd);
exchangetimes+=1;
} else {
int accptstatus=0;
MPI_Send(&accptstatus,1,MPI_INT,rank2,0,MPI_COMM_WORLD);
}
} else {
int c2=glbc2%S;
int accptstatus;
int xsc21D[Nd*Nd];
conv2Dto1D(xs[c2],xsc21D,Nd,Nd);
MPI_Send(xsc21D,Nd*Nd,MPI_INT,rank1,0,MPI_COMM_WORLD);
MPI_Recv(&accptstatus,1,MPI_INT,rank1,0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
if (accptstatus==1)
{
int **xsc1;
create2Dmemory(xsc1,Nd,Nd);
int xsc11D[Nd*Nd];
MPI_Recv(xsc11D,Nd*Nd,MPI_INT,rank1,0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
conv1Dto2D(xsc11D,xsc1,Nd,Nd);
deepcopy2Darray(xsc1,xs[c2], Nd,Nd);
exchangetimes+=1;
}
}
}
}
print2Darray(partialresult,iterNum,S,"output"+std::to_string(rank)+".txt");
free3Dmemory(xs, S, Nd,Nd);
}
/*
* This function takes the Markov chain T steps forward. The parallelization used is
* the strip partitioning.
*
* Function Argument:
* x: pointer to the starting state;
* T: number fo steps
* Nd: side length of the Ising lattice
* temp: temperature of the Ising lattice
*
* */
void oneChainIsing(int **x, int T, int Nd, double temp)
{
#pragma omp parallel shared(x)
{
//int numthreads=2;
//for (int threadid=0; threadid<numthreads; ++threadid)
//{
for (int t=0; t<T; ++t)
{
int threadid = omp_get_thread_num();
int numthreads = omp_get_num_threads();
if (Nd/numthreads<=1)
{
throw "Too many threads! One thread must have at least 2 rows";
}
// Partition the matrix in strips
int low = Nd*threadid/numthreads;
int high=Nd*(threadid+1)/numthreads;
if (high>Nd)
{
high=Nd;
}
// The schedule now is to update everything except the last row
for(int i=low; i<high-1; ++i)
{
for(int j=0; j<Nd; ++j)
{
int leftj=j-1;
int rightj=j+1;
if (j==0)
{
leftj=Nd-1;
}
else if (j==(Nd-1))
{
rightj=0;
}
int upi=i-1;
int downi=i+1;
if (i==0)
{
upi=Nd-1;
}else if (i==Nd-1)
{
downi=0;
}
double s=x[upi][j]+x[downi][j]+x[i][leftj]+x[i][rightj];
double cond_p=exp(temp*s)/(exp(temp*s)+exp(-temp*s));
if (unifrnd(0,1)<cond_p)
{
x[i][j]=1;
} else{
x[i][j]=0;
}
}
}
// put a barrier here go ensure all threads update the last row on new values from neighboring regions
#pragma omp barrier
int i=high-1;
for (int j=0;j<Nd;++j)
{
int leftj=j-1;
int rightj=j+1;
if (j==0)
{
leftj=Nd-1;
}
else if (j==(Nd-1))
{
rightj=0;
}
int upi=i-1;
int downi=i+1;
if (i==0)
{
upi=Nd-1;
}else if (i==Nd-1)
{
downi=0;
}
double s=x[upi][j]+x[downi][j]+x[i][leftj]+x[i][rightj];
double cond_p=exp(temp*s)/(exp(temp*s)+exp(-temp*s));
if (unifrnd(0,1)<cond_p)
{
x[i][j]=1;
} else{
x[i][j]=0;
}
}
// Put a barrier here to ensure iteration is synchronized each step
#pragma omp barrier
}
//}
}
}
void oneChainIsingChess(int **x, int T, int Nd, double temp)
{
// We specify that the chess board starts first row with white
// Update all white cells
#pragma omp parallel for
for (int i=0; i<Nd; ++i)
{
int jst=0;
if (i%2==1)
{
jst=1;
}
int upi=i-1;
int downi=i+1;
if (i==0)
{
upi=Nd-1;
}else if (i==Nd-1)
{
downi=0;
}
for (int j=jst; j<Nd; j=j+2)
{
int leftj=j-1;
int rightj=j+1;
if (j==0)
{
leftj=Nd-1;
}
else if (j==(Nd-1))
{
rightj=0;
}
double s=x[upi][j]+x[downi][j]+x[i][leftj]+x[i][rightj];
double cond_p=exp(temp*s)/(exp(temp*s)+exp(-temp*s));
if (unifrnd(0,1)<cond_p)
{
x[i][j]=1;
} else{
x[i][j]=0;
}
}
}
// Update all black cells
#pragma omp parallel for
for (int i=0; i<Nd; ++i)
{
int jst=1;
if (i%2==1)
{
jst=0;
}
int upi=i-1;
int downi=i+1;
if (i==0)
{
upi=Nd-1;
}else if (i==Nd-1)
{
downi=0;
}
for (int j=jst; j<Nd; j=j+2)
{
int leftj=j-1;
int rightj=j+1;
if (j==0)
{
leftj=Nd-1;
}
else if (j==(Nd-1))
{
rightj=0;
}
double s=x[upi][j]+x[downi][j]+x[i][leftj]+x[i][rightj];
double cond_p=exp(temp*s)/(exp(temp*s)+exp(-temp*s));
if (unifrnd(0,1)<cond_p)
{
x[i][j]=1;
} else{
x[i][j]=0;
}
}
}
}
double t(int **x, int Nd)
{
double result=0;
#pragma omp parallel for reduction(+:result)
for(int i=0; i<Nd; ++i)
{
for(int j=0; j<Nd; ++j)
{
int leftj=j-1;
int rightj=j+1;
if (j==0)
{
leftj=Nd-1;
}
else if (j==(Nd-1))
{
rightj=0;
}
int upi=i-1;
int downi=i+1;
if (i==0)
{
upi=Nd-1;
}else if (i==Nd-1)
{
downi=0;
}
result+=x[i][j]*(x[upi][j]+x[downi][j]+x[i][leftj]+x[i][rightj]);
}
}
return 0.5*result;
}
double logtargetIsing(int **x, int Nd,double temp)
{
double result=0;
result=t(x,Nd);
result=exp(temp*result);
return result;
}
| 13,045 | 4,372 |
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2017 Realm Inc.
//
// 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 "object.hpp"
#include "impl/object_accessor_impl.hpp"
#include "object_schema.hpp"
#include "object_store.hpp"
#include "property.hpp"
#include "schema.hpp"
#include "sync/sync_permission.hpp"
#include "sync_test_utils.hpp"
#include "util/test_file.hpp"
#include "util/test_utils.hpp"
#include <unistd.h>
using namespace realm;
TEST_CASE("`Permission` class", "[sync]") {
SECTION("paths_are_equivalent() properly returns true") {
// Identical paths and identical users for tilde-paths.
CHECK(Permission::paths_are_equivalent("/~/foo", "/~/foo", "user1", "user1"));
// Identical paths for non-tilde paths.
CHECK(Permission::paths_are_equivalent("/user2/foo", "/user2/foo", "user1", "user1"));
CHECK(Permission::paths_are_equivalent("/user2/foo", "/user2/foo", "user1", "user2"));
// First path can be turned into second path.
CHECK(Permission::paths_are_equivalent("/~/foo", "/user1/foo", "user1", "user2"));
// Second path can be turned into first path.
CHECK(Permission::paths_are_equivalent("/user1/foo", "/~/foo", "user2", "user1"));
}
SECTION("paths_are_equivalent() properly returns false") {
// Different tilde-paths.
CHECK(!Permission::paths_are_equivalent("/~/foo", "/~/bar", "user1", "user1"));
// Different non-tilde paths.
CHECK(!Permission::paths_are_equivalent("/user1/foo", "/user2/bar", "user1", "user1"));
// Identical paths and different users for tilde-paths.
CHECK(!Permission::paths_are_equivalent("/~/foo", "/~/foo", "user1", "user2"));
// First path cannot be turned into second path.
CHECK(!Permission::paths_are_equivalent("/~/foo", "/user1/foo", "user2", "user2"));
// Second path cannot be turned into first path.
CHECK(!Permission::paths_are_equivalent("/user1/foo", "/~/foo", "user2", "user2"));
}
}
constexpr const char* result_sets_type_name = "__ResultSets";
static void update_schema(Group& group, Property matches_property)
{
Schema current_schema;
std::string table_name = ObjectStore::table_name_for_object_type(result_sets_type_name);
if (group.has_table(table_name))
current_schema = {ObjectSchema{group, result_sets_type_name}};
Schema desired_schema({
ObjectSchema(result_sets_type_name, {
{"name", PropertyType::String},
{"matches_property", PropertyType::String},
{"query", PropertyType::String},
{"status", PropertyType::Int},
{"error_message", PropertyType::String},
{"query_parse_counter", PropertyType::Int},
std::move(matches_property)
})
});
auto required_changes = current_schema.compare(desired_schema);
if (!required_changes.empty())
ObjectStore::apply_additive_changes(group, required_changes, true);
}
static void subscribe_to_all(std::shared_ptr<Realm> const& r)
{
using namespace std::string_literals;
r->begin_transaction();
update_schema(r->read_group(),
Property("object_matches", PropertyType::Object|PropertyType::Array, "object"));
ObjectSchema schema{r->read_group(), result_sets_type_name};
CppContext context;
auto obj = Object::create<util::Any>(context, r, schema, AnyDict{
{"name", ""s},
{"matches_property", "object_matches"s},
{"query", "TRUEPREDICATE"s},
{"status", int64_t(0)},
{"error_message", ""s},
{"query_parse_counter", int64_t(0)},
{"matches_count", int64_t(0)},
{"created_at", Timestamp(0, 0)},
{"updated_at", Timestamp(0, 0)},
{"expires_at", Timestamp()},
{"time_to_live", {}},
});
r->commit_transaction();
while (any_cast<int64_t>(obj.get_property_value<util::Any>(context, "status")) != 1) {
wait_for_download(*r);
r->refresh();
}
}
TEST_CASE("Object-level Permissions") {
TestSyncManager init_sync_manager;
SyncServer server{StartImmediately{false}};
SyncTestFile config{server, "default"};
config.cache = false;
config.automatic_change_notifications = false;
config.schema = Schema{
{"object", {
{"value", PropertyType::Int}
}},
};
auto create_object = [](auto&& r) -> Table& {
r->begin_transaction();
auto& table = *r->read_group().get_table("class_object");
sync::create_object(r->read_group(), table);
r->commit_transaction();
return table;
};
SECTION("Non-sync Realms") {
SECTION("permit all operations") {
config.sync_config = nullptr;
auto r = Realm::get_shared_realm(config);
auto& table = create_object(r);
CHECK(r->get_privileges() == ComputedPrivileges::AllRealm);
CHECK(r->get_privileges("object") == ComputedPrivileges::AllClass);
CHECK(r->get_privileges(table[0]) == ComputedPrivileges::AllObject);
}
}
SECTION("Full sync Realms") {
SECTION("permit all operations") {
auto r = Realm::get_shared_realm(config);
auto& table = create_object(r);
CHECK(r->get_privileges() == ComputedPrivileges::AllRealm);
CHECK(r->get_privileges("object") == ComputedPrivileges::AllClass);
CHECK(r->get_privileges(table[0]) == ComputedPrivileges::AllObject);
}
}
SECTION("Query-based sync Realms") {
SECTION("permit all operations prior to first sync") {
config.sync_config->is_partial = true;
auto r = Realm::get_shared_realm(config);
auto& table = create_object(r);
CHECK(r->get_privileges() == ComputedPrivileges::AllRealm);
CHECK(r->get_privileges("object") == ComputedPrivileges::AllClass);
CHECK(r->get_privileges(table[0]) == ComputedPrivileges::AllObject);
}
SECTION("continue to permit all operations after syncing locally-created data") {
config.sync_config->is_partial = true;
auto r = Realm::get_shared_realm(config);
auto& table = create_object(r);
server.start();
wait_for_upload(*r);
wait_for_download(*r);
CHECK(r->get_privileges() == ComputedPrivileges::AllRealm);
CHECK(r->get_privileges("object") == ComputedPrivileges::AllClass);
CHECK(r->get_privileges(table[0]) == ComputedPrivileges::AllObject);
}
SECTION("permit all operations on a downloaded Realm created as a Full Realm when logged in as an admin") {
server.start();
{
auto r = Realm::get_shared_realm(config);
create_object(r);
wait_for_upload(*r);
}
SyncTestFile config2{server, "default", true};
config2.automatic_change_notifications = false;
auto r = Realm::get_shared_realm(config2);
wait_for_download(*r);
subscribe_to_all(r);
CHECK(r->get_privileges() == ComputedPrivileges::AllRealm);
CHECK(r->get_privileges("object") == ComputedPrivileges::AllClass);
CHECK(r->get_privileges(r->read_group().get_table("class_object")->get(0)) == ComputedPrivileges::AllObject);
}
SECTION("permit nothing on pre-existing types in a downloaded Realm created as a Full Realm") {
server.start();
{
auto r = Realm::get_shared_realm(config);
create_object(r);
wait_for_upload(*r);
}
SyncTestFile config2{server, "default", true};
config2.automatic_change_notifications = false;
config2.sync_config->user->set_is_admin(false);
auto r = Realm::get_shared_realm(config2);
wait_for_download(*r);
subscribe_to_all(r);
// should have no objects as we don't have read permission
CHECK(r->read_group().get_table("class_object")->size() == 0);
CHECK(r->get_privileges() == ComputedPrivileges::AllRealm);
CHECK(r->get_privileges("object") == ComputedPrivileges::None);
}
SECTION("automatically add newly created users to 'everyone'") {
using namespace std::string_literals;
config.schema = Schema{
{"__User", {
{"id", PropertyType::String, Property::IsPrimary{true}}
}},
};
config.sync_config->is_partial = true;
auto r = Realm::get_shared_realm(config);
r->begin_transaction();
CppContext c;
auto user = Object::create<util::Any>(c, r, *r->schema().find("__User"), AnyDict{{"id", "test user"s}});
auto role_table = r->read_group().get_table("class___Role");
REQUIRE(role_table);
size_t ndx = role_table->find_first_string(role_table->get_column_index("name"), "everyone");
REQUIRE(ndx != npos);
REQUIRE(role_table->get_linklist(role_table->get_column_index("members"), ndx)->find(user.row().get_index()) != npos);
r->commit_transaction();
}
SECTION("automatically create private roles for newly-created users") {
using namespace std::string_literals;
config.schema = Schema{
{"__User", {
{"id", PropertyType::String, Property::IsPrimary{true}}
}},
};
config.sync_config->is_partial = true;
auto r = Realm::get_shared_realm(config);
r->begin_transaction();
auto validate_user_role = [](const Object& user) {
auto user_table = user.row().get_table();
REQUIRE(user_table);
size_t ndx = user.row().get_link(user_table->get_column_index("role"));
REQUIRE(ndx != npos);
auto role_table = user.realm()->read_group().get_table("class___Role");
REQUIRE(role_table);
auto members = role_table->get_linklist(role_table->get_column_index("members"), ndx);
REQUIRE(members->size() == 1);
REQUIRE(members->find(user.row().get_index()) != npos);
};
SECTION("logged-in user") {
auto user_table = r->read_group().get_table("class___User");
REQUIRE(user_table);
REQUIRE(user_table->size() == 1);
validate_user_role(Object(r, "__User", 0));
}
SECTION("manually created user") {
CppContext c;
auto user = Object::create<util::Any>(c, r, *r->schema().find("__User"), AnyDict{{"id", "test user"s}});
validate_user_role(user);
}
r->commit_transaction();
}
}
SECTION("schema change error reporting") {
config.sync_config->is_partial = true;
// Create the Realm with an admin user
server.start();
{
auto r = Realm::get_shared_realm(config);
create_object(r);
// FIXME: required due to https://github.com/realm/realm-sync/issues/2071
wait_for_upload(*r);
wait_for_download(*r);
// Revoke modifySchema permission for all users
r->begin_transaction();
TableRef permission_table = r->read_group().get_table("class___Permission");
size_t col = permission_table->get_column_index("canModifySchema");
for (size_t i = 0; i < permission_table->size(); ++i)
permission_table->set_bool(col, i, false);
r->commit_transaction();
wait_for_upload(*r);
}
SyncTestFile nonadmin{server, "default", true, "user2"};
nonadmin.automatic_change_notifications = false;
nonadmin.sync_config->user->set_is_admin(false);
auto bind_session_handler = nonadmin.sync_config->bind_session_handler;
nonadmin.sync_config->bind_session_handler = [](auto, auto, auto) { };
auto log_in = [&](auto& realm) {
auto session = SyncManager::shared().get_session(nonadmin.path, *nonadmin.sync_config);
bind_session_handler("", *nonadmin.sync_config, session);
wait_for_upload(realm);
wait_for_download(realm);
};
SECTION("reverted column insertion") {
nonadmin.schema = Schema{
{"object", {
{"value", PropertyType::Int},
{"value 2", PropertyType::Int}
}},
};
auto r = Realm::get_shared_realm(nonadmin);
r->invalidate();
SECTION("no active read transaction") {
log_in(*r);
REQUIRE_THROWS_WITH(r->read_group(),
Catch::Matchers::Contains("Property 'object.value 2' has been removed."));
}
SECTION("notify()") {
r->read_group();
log_in(*r);
REQUIRE_THROWS_WITH(r->notify(),
Catch::Matchers::Contains("Property 'object.value 2' has been removed."));
}
SECTION("refresh()") {
r->read_group();
log_in(*r);
REQUIRE_THROWS_WITH(r->refresh(),
Catch::Matchers::Contains("Property 'object.value 2' has been removed."));
}
SECTION("begin_transaction()") {
r->read_group();
log_in(*r);
REQUIRE_THROWS_WITH(r->begin_transaction(),
Catch::Matchers::Contains("Property 'object.value 2' has been removed."));
}
}
SECTION("reverted table insertion") {
nonadmin.schema = Schema{
{"object", {
{"value", PropertyType::Int},
}},
{"object 2", {
{"value", PropertyType::Int},
}},
};
auto r = Realm::get_shared_realm(nonadmin);
r->read_group();
log_in(*r);
REQUIRE_THROWS_WITH(r->notify(),
Catch::Matchers::Contains("Class 'object 2' has been removed."));
}
}
}
| 15,206 | 4,428 |
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> v;
void dfs(TreeNode* root) {
if (root->left) {
dfs(root->left);
}
v.push_back(root->val);
if (root->right) {
dfs(root->right);
}
}
TreeNode* increasingBST(TreeNode* root) {
dfs(root);
TreeNode* node = new TreeNode(v[0]);
TreeNode* s = node;
for (int i = 1; i < v.size(); i++) {
node->right = new TreeNode(v[i]);
node = node->right;
}
return s;
}
}; | 907 | 309 |
#include "5_System_Processes.h"
#include "defines.h"
#include <EEPROM.h>
#include "Preferences.h"
#include "nvs.h"
#include "nvs_flash.h"
#include "esp32-hal-log.h"
const char * my_nvs_errors[] = { "OTHER", "NOT_INITIALIZED", "NOT_FOUND", "TYPE_MISMATCH", "READ_ONLY", "NOT_ENOUGH_SPACE", "INVALID_NAME", "INVALID_HANDLE", "REMOVE_FAILED", "KEY_TOO_LONG", "PAGE_FULL", "INVALID_STATE", "INVALID_LENGTH"};
#define my_nvs_error(e) (((e)>ESP_ERR_NVS_BASE)? my_nvs_errors[(e)&~(ESP_ERR_NVS_BASE)]: my_nvs_errors[0])
class MyPreferences : public Preferences
{
public:
MyPreferences() : Preferences() {}
size_t myPutChar(const char* key, int8_t value){
if(!_started || !key || _readOnly){
return 0;
}
esp_err_t err = nvs_set_i8(_handle, key, value);
if(err){
log_e("nvs_set_i8 fail: %s %s", key, my_nvs_error(err));
return 0;
}
return 1;
}
size_t myPutUChar(const char* key, uint8_t value){
if(!_started || !key || _readOnly){
return 0;
}
esp_err_t err = nvs_set_u8(_handle, key, value);
if(err){
log_e("nvs_set_u8 fail: %s %s", key, my_nvs_error(err));
return 0;
}
return 1;
}
size_t myPutShort(const char* key, int16_t value){
if(!_started || !key || _readOnly){
return 0;
}
esp_err_t err = nvs_set_i16(_handle, key, value);
if(err){
log_e("nvs_set_i16 fail: %s %s", key, my_nvs_error(err));
return 0;
}
return 2;
}
size_t myPutUShort(const char* key, uint16_t value){
if(!_started || !key || _readOnly){
return 0;
}
esp_err_t err = nvs_set_u16(_handle, key, value);
if(err){
log_e("nvs_set_u16 fail: %s %s", key, my_nvs_error(err));
return 0;
}
return 2;
}
size_t myPutInt(const char* key, int32_t value){
if(!_started || !key || _readOnly){
return 0;
}
esp_err_t err = nvs_set_i32(_handle, key, value);
if(err){
log_e("nvs_set_i32 fail: %s %s", key, my_nvs_error(err));
return 0;
}
return 4;
}
size_t myPutUInt(const char* key, uint32_t value){
if(!_started || !key || _readOnly){
return 0;
}
esp_err_t err = nvs_set_u32(_handle, key, value);
if(err){
log_e("nvs_set_u32 fail: %s %s", key, my_nvs_error(err));
return 0;
}
return 4;
}
size_t myPutLong(const char* key, int32_t value){
return myPutInt(key, value);
}
size_t myPutULong(const char* key, uint32_t value){
return myPutUInt(key, value);
}
size_t myPutLong64(const char* key, int64_t value){
if(!_started || !key || _readOnly){
return 0;
}
esp_err_t err = nvs_set_i64(_handle, key, value);
if(err){
log_e("nvs_set_i64 fail: %s %s", key, my_nvs_error(err));
return 0;
}
return 8;
}
size_t myPutULong64(const char* key, uint64_t value){
if(!_started || !key || _readOnly){
return 0;
}
esp_err_t err = nvs_set_u64(_handle, key, value);
if(err){
log_e("nvs_set_u64 fail: %s %s", key, my_nvs_error(err));
return 0;
}
return 8;
}
size_t myPutFloat(const char* key, const float_t value){
return myPutBytes(key, (void*)&value, sizeof(float_t));
}
size_t myPutDouble(const char* key, const double_t value){
return myPutBytes(key, (void*)&value, sizeof(double_t));
}
size_t myPutBool(const char* key, const bool value){
return myPutUChar(key, (uint8_t) (value ? 1 : 0));
}
size_t myPutString(const char* key, const char* value){
if(!_started || !key || !value || _readOnly){
return 0;
}
esp_err_t err = nvs_set_str(_handle, key, value);
if(err){
log_e("nvs_set_str fail: %s %s", key, my_nvs_error(err));
return 0;
}
return strlen(value);
}
size_t myPutString(const char* key, const String value){
return myPutString(key, value.c_str());
}
size_t myPutBytes(const char* key, const void* value, size_t len){
if(!_started || !key || !value || !len || _readOnly){
return 0;
}
esp_err_t err = nvs_set_blob(_handle, key, value, len);
if(err){
log_e("nvs_set_blob fail: %s %s", key, my_nvs_error(err));
return 0;
}
return len;
}
void myCommit() {
esp_err_t err = nvs_commit(_handle);
if(err){
log_e("nvs_commit fail: %s", my_nvs_error(err));
return ;
}
}
};
void resetVariables(){
secondsElapsed = 0;
energySavings = 0;
daysRunning = 0;
timeOn = 0;
}
void System_Processes(){
///////////////// FAN COOLING /////////////////
if(enableFan==true){
if(enableDynamicCooling==false){ //STATIC PWM COOLING MODE (2-PIN FAN - no need for hysteresis, temp data only refreshes after 'avgCountTS' or every 500 loop cycles)
if(overrideFan==true){fanStatus=true;} //Force on fan
else if(temperature>=temperatureFan){fanStatus=1;} //Turn on fan when set fan temp reached
else if(temperature<temperatureFan){fanStatus=0;} //Turn off fan when set fan temp reached
digitalWrite(FAN,fanStatus); //Send a digital signal to the fan MOSFET
}
else{} //DYNAMIC PWM COOLING MODE (3-PIN FAN - coming soon)
}
else{digitalWrite(FAN,LOW);} //Fan Disabled
//////////// LOOP TIME STOPWATCH ////////////
loopTimeStart = micros(); //Record Start Time
loopTime = (loopTimeStart-loopTimeEnd)/1000.000; //Compute Loop Cycle Speed (mS)
loopTimeEnd = micros(); //Record End Time
///////////// AUTO DATA RESET /////////////
if(telemCounterReset==0){} //Never Reset
else if(telemCounterReset==1 && daysRunning>1) { resetVariables(); } //Daily Reset
else if(telemCounterReset==2 && daysRunning>7) { resetVariables(); } //Weekly Reset
else if(telemCounterReset==3 && daysRunning>30) { resetVariables(); } //Monthly Reset
else if(telemCounterReset==4 && daysRunning>365){ resetVariables(); } //Yearly Reset
///////////// LOW POWER MODE /////////////
if(lowPowerMode==1){}
else{}
}
MyPreferences prefe;
void setupPreferences() {
prefe.begin("MPPT");
}
void loadSettings() {
flashMemLoad = prefe.getBool("flashMemLoad", 1);
MPPT_Mode = prefe.getBool("MPPT_Mode", 1);
output_Mode = prefe.getBool("output_Mode", 1);
enableFan = prefe.getBool("enableFan", 1);
enableWiFi = prefe.getBool("enableWiFi", 1);
temperatureFan = prefe.getInt("temperatureFan", 60);
temperatureMax = prefe.getInt("temperatureMax", 90);
backlightSleepMode = prefe.getInt("backlightSleepMode", 0);
voltageBatteryMax = prefe.getFloat("voltageBatteryMax", 25.5);
voltageBatteryMin = prefe.getFloat("voltageBatteryMin", 20);
currentChargingMax = prefe.getFloat("currentChargingMax", 50);
// MPPT_Mode = EEPROM.read(0); // Load saved charging mode setting
// output_Mode = EEPROM.read(12); // Load saved charging mode setting
// voltageBatteryMax = EEPROM.read(1)+(EEPROM.read(2)*.01); // Load saved maximum battery voltage setting
// voltageBatteryMin = EEPROM.read(3)+(EEPROM.read(4)*.01); // Load saved minimum battery voltage setting
// currentChargingMax = EEPROM.read(5)+(EEPROM.read(6)*.01); // Load saved charging current setting
// enableFan = EEPROM.read(7); // Load saved fan enable settings
// temperatureFan = EEPROM.read(8); // Load saved fan temperature settings
// temperatureMax = EEPROM.read(9); // Load saved shutdown temperature settings
// enableWiFi = EEPROM.read(10); // Load saved WiFi enable settings
// flashMemLoad = EEPROM.read(11); // Load saved flash memory autoload feature
// backlightSleepMode = EEPROM.read(13); // Load saved lcd backlight sleep timer
}
void saveSettings() {
prefe.myPutBool("MPPT_Mode", MPPT_Mode);
prefe.myPutBool("output_Mode", output_Mode);
prefe.myPutBool("enableFan", enableFan);
prefe.myPutBool("enableWiFi", enableWiFi);
prefe.myPutInt("temperatureFan", temperatureFan);
prefe.myPutInt("temperatureMax", temperatureMax);
prefe.myPutInt("backlightSleepMode", backlightSleepMode);
prefe.myPutFloat("voltageBatteryMax", voltageBatteryMax);
prefe.myPutFloat("voltageBatteryMin", voltageBatteryMin);
prefe.myPutFloat("currentChargingMax", currentChargingMax);
prefe.myCommit();
// // EEPROM.write(0,MPPT_Mode); //STORE: Algorithm
// EEPROM.write(12,output_Mode); //STORE: Charge/PSU Mode Selection
// conv1 = voltageBatteryMax*100; //STORE: Maximum Battery Voltage (gets whole number)
// conv2 = conv1%100; //STORE: Maximum Battery Voltage (gets decimal number and converts to a whole number)
// EEPROM.write(1,voltageBatteryMax);
// EEPROM.write(2,conv2);
// conv1 = voltageBatteryMin*100; //STORE: Minimum Battery Voltage (gets whole number)
// conv2 = conv1%100; //STORE: Minimum Battery Voltage (gets decimal number and converts to a whole number)
// EEPROM.write(3,voltageBatteryMin);
// EEPROM.write(4,conv2);
// conv1 = currentChargingMax*100; //STORE: Charging Current
// conv2 = conv1%100;
// EEPROM.write(5,currentChargingMax);
// EEPROM.write(6,conv2);
// EEPROM.write(7,enableFan); //STORE: Fan Enable
// EEPROM.write(8,temperatureFan); //STORE: Fan Temp
// EEPROM.write(9,temperatureMax); //STORE: Shutdown Temp
// EEPROM.write(10,enableWiFi); //STORE: Enable WiFi
// //EEPROM.write(11,flashMemLoad); //STORE: Enable autoload (must be excluded from bulk save, uncomment under discretion)
// EEPROM.write(13,backlightSleepMode); //STORE: LCD backlight sleep timer
// EEPROM.commit(); //Saves setting changes to flash memory
}
void factoryReset(){
prefe.myPutBool("flashMemLoad", 1);
prefe.myPutBool("MPPT_Mode", 1);
prefe.myPutBool("output_Mode", 1);
prefe.myPutBool("enableFan", 1);
prefe.myPutBool("enableWiFi", 1);
prefe.myPutInt("temperatureFan", 60);
prefe.myPutInt("temperatureMax", 90);
prefe.myPutInt("backlightSleepMode", 0);
prefe.myPutFloat("voltageBatteryMax", 25.5);
prefe.myPutFloat("voltageBatteryMin", 20);
prefe.myPutFloat("currentChargingMax", 50);
prefe.myCommit();
// EEPROM.write(0,1); //STORE: Charging Algorithm (1 = MPPT Mode)
// EEPROM.write(12,1); //STORE: Charger/PSU Mode Selection (1 = Charger Mode)
// EEPROM.write(1,12); //STORE: Max Battery Voltage (whole)
// EEPROM.write(2,0); //STORE: Max Battery Voltage (decimal)
// EEPROM.write(3,9); //STORE: Min Battery Voltage (whole)
// EEPROM.write(4,0); //STORE: Min Battery Voltage (decimal)
// EEPROM.write(5,30); //STORE: Charging Current (whole)
// EEPROM.write(6,0); //STORE: Charging Current (decimal)
// EEPROM.write(7,1); //STORE: Fan Enable (Bool)
// EEPROM.write(8,60); //STORE: Fan Temp (Integer)
// EEPROM.write(9,90); //STORE: Shutdown Temp (Integer)
// EEPROM.write(10,1); //STORE: Enable WiFi (Boolean)
// EEPROM.write(11,1); //STORE: Enable autoload (on by default)
// // EEPROM.write(13,0); //STORE: LCD backlight sleep timer (default: 0 = never)
// EEPROM.commit();
loadSettings();
}
void saveAutoloadSettings(){
// EEPROM.write(11,flashMemLoad); //STORE: Enable autoload
// EEPROM.commit(); //Saves setting changes to flash memory
prefe.putBool("flashMemLoad", flashMemLoad);
}
void initializeFlashAutoload() {
if(disableFlashAutoLoad==0){
flashMemLoad = prefe.getBool("flashMemLoad", false);
// flashMemLoad = EEPROM.read(11); //Load saved autoload (must be excluded from bulk save, uncomment under discretion)
if(flashMemLoad==1){loadSettings();} //Load stored settings from flash memory
}
}
| 12,451 | 4,608 |
#include "util.h"
#include "invoiceutil.h"
namespace InvoiceUtil {
bool validateInvoiceNumber(std::string input)
{
int size = input.size();
if(size > 32) {
return false;
}
for(int idx=0; idx < size; ++idx)
{
int ch = input.at(idx);
if(((ch >= '0' && ch<='9') ||
(ch >= 'a' && ch<='z') ||
(ch >= 'A' && ch<='Z') ||
(ch == '-')))
{
// Alphanumeric or -
}
else
{
return false;
}
}
return true;
}
void parseInvoiceNumberAndAddress(std::string input, std::string& outAddress, std::string& outInvoiceNumber)
{
size_t plusIndex = input.find('+');
if(plusIndex == string::npos)
{ //no +
outAddress = input;
outInvoiceNumber = "";
}
else
{ //+
outAddress = input.substr(0, plusIndex);
outInvoiceNumber = input.substr(plusIndex + 1, input.size());
}
}
} | 1,103 | 338 |
#include "FragTrap.hpp"
#include "ScavTrap.hpp"
int main()
{
FragTrap frag_trap;
FragTrap R2D2("R2D2");
FragTrap test("BMO");
FragTrap BMO(test);
FragTrap test2("C-3PO");
FragTrap C_3PO = test2;
frag_trap.rangeAttack("Blue bird");
frag_trap.meleeAttack("Handsome Jack");
frag_trap.takeDamage(42);
frag_trap.takeDamage(1);
frag_trap.beRepaired(42);
frag_trap.takeDamage(200);
for (int i=0; i < 5; i++) {
BMO.vaulthunter_dot_exe("Jake the Dog");
C_3PO.vaulthunter_dot_exe("Jar Jar Binks");
R2D2.vaulthunter_dot_exe("Yoda");
}
ScavTrap scav_trap("Happy");
for (int i=0; i < 5; i++)
scav_trap.challengeNewcomer("Jojo");
return 0;
}
| 656 | 353 |
// @HEADER
// ***********************************************************************
//
// Teuchos: Common Tools Package
// Copyright (2004) Sandia Corporation
//
// Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive
// license for use of this work by or on behalf of the U.S. Government.
//
// 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 Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR 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.
//
// Questions? Contact Michael A. Heroux (maherou@sandia.gov)
//
// ***********************************************************************
// @HEADER
// Kris
// 07.08.03 -- Move into Teuchos package/namespace
#ifndef TEUCHOS_FLOPS_HPP
#define TEUCHOS_FLOPS_HPP
/*! \file Teuchos_Flops.hpp
\brief Object for providing basic support and consistent interfaces for
counting/reporting floating-point operations performed in Teuchos computational
classes.
*/
/*! \class Teuchos::Flops
\brief The Teuchos Floating Point Operations Class.
The Teuchos_Flops class provides basic support and consistent interfaces
for counting and reporting floating point operations performed in
the Teuchos computational classes. All classes based on the Teuchos::CompObject
can count flops by the user creating an Teuchos::Flops object and calling the SetFlopCounter()
method for an Teuchos_CompObject.
*/
namespace Teuchos
{
class Flops
{
public:
//! @name Constructor/Destructor.
//@{
//! Default Constructor.
/*! Creates a Flops instance. This instance can be queried for
the number of floating point operations performed for the associated
\e this object.
*/
Flops();
//! Copy Constructor.
/*! Makes an exact copy of an existing Flops instance.
*/
Flops(const Flops &flops);
//! Destructor.
/*! Completely deletes a Flops object.
*/
virtual ~Flops();
//@}
//! @name Accessor methods.
//@{
//! Returns the number of floating point operations with \e this object and resets the count.
double flops() const { return flops_; }
//@}
//! @name Reset methods.
//@{
//! Resets the number of floating point operations to zero for \e this multi-std::vector.
void resetFlops() {flops_ = 0.0;}
//@}
friend class CompObject;
protected:
mutable double flops_;
//! @name Updating methods.
//@{
//! Increment Flop count for \e this object from an int
void updateFlops(int addflops) const {flops_ += (double) addflops; }
//! Increment Flop count for \e this object from a long int
void updateFlops(long int addflops) const {flops_ += (double) addflops; }
//! Increment Flop count for \e this object from a double
void updateFlops(double addflops) const {flops_ += (double) addflops; }
//! Increment Flop count for \e this object from a float
void updateFlops(float addflops) const {flops_ += (double) addflops; }
//@}
private:
};
// #include "Teuchos_Flops.cpp"
} // namespace Teuchos
#endif // end of TEUCHOS_FLOPS_HPP
| 4,381 | 1,452 |
/***********************************************************************************************************************
**
** Copyright (c) 2015 ETH Zurich
** 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 the ETH Zurich 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.
**
***********************************************************************************************************************/
#include "CodeReviewCommentOverlay.h"
#include "VisualizationBase/src/declarative/GridLayoutFormElement.h"
#include "VisualizationBase/src/declarative/DeclarativeItem.hpp"
#include "VisualizationBase/src/items/Item.h"
#include "VisualizationBase/src/VisualizationManager.h"
#include "../handlers/HCodeReviewOverlay.h"
namespace CodeReview
{
DEFINE_ITEM_COMMON(CodeReviewCommentOverlay, "item")
CodeReviewCommentOverlay::CodeReviewCommentOverlay(Visualization::Item* associatedItem,
NodeReviews* nodeReviews, const StyleType* style) :
Super{{associatedItem}, style}, nodeReviews_{nodeReviews}
{
setAcceptedMouseButtons(Qt::AllButtons);
setItemCategory(Visualization::Scene::MenuItemCategory);
offsetItemLocal_ = QPoint{nodeReviews->offsetX(), nodeReviews->offsetY()};
}
void CodeReviewCommentOverlay::updateGeometry(int availableWidth, int availableHeight)
{
Super::updateGeometry(availableWidth, availableHeight);
setPos(associatedItem()->mapToScene(offsetItemLocal_));
setScale(1.0/Visualization::VisualizationManager::instance().mainScene()->mainViewScalingFactor());
}
void CodeReviewCommentOverlay::initializeForms()
{
auto container = (new Visualization::GridLayoutFormElement{})
->setTopMargin(10)
->put(0, 0, item(&I::nodeReviewsItem_, [](I* v) {return v->nodeReviews_;}));
addForm(container);
}
void CodeReviewCommentOverlay::updateOffsetItemLocal(QPointF scenePos)
{
offsetItemLocal_ = CodeReviewCommentOverlay::associatedItem()->mapFromScene(scenePos);
nodeReviews_->beginModification("edit node");
nodeReviews_->setOffsetX(offsetItemLocal_.x());
nodeReviews_->setOffsetY(offsetItemLocal_.y());
nodeReviews_->endModification();
}
}
| 3,494 | 1,107 |
#include "ExecuteConfigSection.h"
#include "Messages.h"
#include <cstdio>
#include <cstring>
ExecuteConfigSection *g_executeConfig = NULL;
ExecuteConfigSection::ExecuteConfigSection() {}
ExecuteConfigSection::~ExecuteConfigSection() {}
CONFIG_SEC_RET ExecuteConfigSection::ProcessKeyValue(char *name, char *value) {
if (strcasecmp(name, "task") == 0) {
TOLOWER(value);
std::map<std::string, TaskConfigSection *>::iterator itr =
g_taskConfigs.find(value);
if (itr == g_taskConfigs.end()) {
ERROR_LOGF("Unknown task \"%s\"!", value);
return INVALID_RESULT;
}
tasks.push_back(itr->second);
} else if (strcasecmp(name, "ensembletask") == 0) {
TOLOWER(value);
std::map<std::string, EnsTaskConfigSection *>::iterator itr =
g_ensTaskConfigs.find(value);
if (itr == g_ensTaskConfigs.end()) {
ERROR_LOGF("Unknown ensemble task \"%s\"!", value);
return INVALID_RESULT;
}
ensTasks.push_back(itr->second);
} else {
return INVALID_RESULT;
}
return VALID_RESULT;
}
CONFIG_SEC_RET ExecuteConfigSection::ValidateSection() {
if (tasks.size() == 0) {
ERROR_LOG("No tasks were defined!");
return INVALID_RESULT;
}
return VALID_RESULT;
}
std::vector<TaskConfigSection *> *ExecuteConfigSection::GetTasks() {
return &tasks;
}
std::vector<EnsTaskConfigSection *> *ExecuteConfigSection::GetEnsTasks() {
return &ensTasks;
}
| 1,420 | 491 |
/*
* Main authors:
* Roberto Castaneda Lozano <roberto.castaneda@ri.se>
*
* This file is part of Unison, see http://unison-code.github.io
*
* Copyright (c) 2016, RISE SICS 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.
* 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.
*/
#ifndef __DOT__
#define __DOT__
#include <tuple>
#include <vector>
#include <map>
#include <QtGui>
#include <graphviz/gvc.h>
using namespace std;
typedef QString NodeId;
typedef tuple<NodeId, NodeId, int> EdgeId;
EdgeId edgeId(const NodeId& source, const NodeId& target, int instance = 0);
EdgeId edgeId(int source, int target, int instance = 0);
#define POSITION(l) (l->pos)
#define BB(g) (GD_bb(g))
#define NDNAME(n) (agnameof(n))
#define NDCOORD(n) (ND_coord(n))
#define NDHEIGHT(n) (ND_height(n))
#define NDWIDTH(n) (ND_width(n))
#define EDLABEL(e) (ED_label(e))
#define EDTAILNAME(e) (NDNAME(agtail(e)))
#define EDHEADNAME(e) (NDNAME(aghead(e)))
#define EDSPLLIST(e) (ED_spl(e)->list)
class DotNode {
public:
NodeId name;
QPointF topLeftPos;
double width, height;
QRectF rect;
vector<QRectF> rects;
};
class DotEdge {
public:
EdgeId key;
QPointF topLeftPos;
double width, height;
QPainterPath path;
QPainterPath arrow;
};
class Dot {
public:
static const double DPI;
static const double DOT2QT;
Dot();
~Dot();
void setGlobalGraphAttribute(const QString &attr, const QString &val);
void setGlobalNodeAttribute(const QString &attr, const QString &val);
void setGlobalEdgeAttribute(const QString &attr, const QString &val);
void insert(const NodeId& name);
void insert(const EdgeId& key);
void setEdgeAttribute(EdgeId key, const QString &attr, const QString &val);
void setNodeSize(const NodeId &name, double w, double h);
void setNodeAttribute(const NodeId &name,
const QString &attr, const QString &val);
void draw(void);
void dump(FILE * file);
QRectF box() const;
vector<DotNode> getNodes() const;
vector<DotEdge> getEdges() const;
QPainterPath drawArrow(QLineF line) const;
private:
GVC_t * context;
Agraph_t *graph;
map<NodeId, Agnode_t*> nodes;
map<EdgeId, Agedge_t*> edges;
static void gvSet(void *object, QString attr, QString value) {
agsafeset(object, const_cast<char *>(qPrintable(attr)),
const_cast<char *>(qPrintable(value)),
const_cast<char *>(qPrintable(value)));
}
Agnode_t * gvNode(NodeId node) {
return agnode(graph, const_cast<char *>(qPrintable(node)),1);
}
};
#endif
| 3,990 | 1,463 |
#include "thread_group.h"
#include <algorithm>
#include <cassert>
namespace concurrencpp::details {
class thread_group_worker {
private:
task m_task;
std::thread m_thread;
thread_group& m_parent_pool;
typename std::list<thread_group_worker>::iterator m_self_it;
void execute_and_retire();
public:
thread_group_worker(task& function, thread_group& parent_pool) noexcept;
~thread_group_worker() noexcept;
std::thread::id get_id() const noexcept;
std::thread::id start(std::list<thread_group_worker>::iterator self_it);
};
}
using concurrencpp::task;
using concurrencpp::details::thread_group;
using concurrencpp::details::thread_group_worker;
using concurrencpp::details::thread_pool_listener_base;
using listener_ptr = std::shared_ptr<thread_pool_listener_base>;
thread_group_worker::thread_group_worker(task& function, thread_group& parent_pool) noexcept :
m_task(std::move(function)),
m_parent_pool(parent_pool) {}
thread_group_worker::~thread_group_worker() noexcept {
m_thread.join();
}
void thread_group_worker::execute_and_retire() {
m_task();
m_task.clear();
m_parent_pool.retire_worker(m_self_it);
}
std::thread::id thread_group_worker::get_id() const noexcept {
return m_thread.get_id();
}
std::thread::id thread_group_worker::start(std::list<thread_group_worker>::iterator self_it) {
m_self_it = self_it;
m_thread = std::thread([this] { execute_and_retire(); });
return m_thread.get_id();
}
thread_group::thread_group(listener_ptr listener) :
m_listener(std::move(listener)) {}
thread_group::~thread_group() noexcept {
wait_all();
assert(m_workers.empty());
clear_last_retired(std::move(m_last_retired));
}
std::thread::id thread_group::enqueue(task callable) {
std::unique_lock<decltype(m_lock)> lock(m_lock);
auto& new_worker = m_workers.emplace_back(callable, *this);
auto worker_it = std::prev(m_workers.end());
const auto id = new_worker.start(worker_it);
const auto& listener = get_listener();
if (static_cast<bool>(listener)) {
listener->on_thread_created(id);
}
return id;
}
void concurrencpp::details::thread_group::wait_all() {
std::unique_lock<decltype(m_lock)> lock(m_lock);
m_condition.wait(lock, [this] { return m_workers.empty(); });
}
bool concurrencpp::details::thread_group::wait_all(std::chrono::milliseconds ms) {
std::unique_lock<decltype(m_lock)> lock(m_lock);
return m_condition.wait_for(lock, ms, [this] { return m_workers.empty(); });
}
const listener_ptr& thread_group::get_listener() const noexcept {
return m_listener;
}
void thread_group::clear_last_retired(std::list<thread_group_worker> last_retired) {
if (last_retired.empty()) {
return;
}
assert(last_retired.size() == 1);
const auto thread_id = last_retired.front().get_id();
last_retired.clear();
const auto& listener = get_listener();
if (static_cast<bool>(listener)) {
listener->on_thread_destroyed(thread_id);
}
}
void thread_group::retire_worker(std::list<thread_group_worker>::iterator it) {
std::list<thread_group_worker> last_retired;
const auto id = it->get_id();
std::unique_lock<decltype(m_lock)> lock(m_lock);
last_retired = std::move(m_last_retired);
m_last_retired.splice(m_last_retired.begin(), m_workers, it);
lock.unlock();
m_condition.notify_one();
const auto& listener = get_listener();
if (static_cast<bool>(listener)) {
listener->on_thread_idling(id);
}
clear_last_retired(std::move(last_retired));
} | 3,422 | 1,270 |
/* Copyright (c) 2021 Xie Meiyi(xiemeiyi@hust.edu.cn) and OceanBase and/or its affiliates. All rights reserved.
miniob is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details. */
//
// Created by Wangyunlai on 2021/5/14.
//
#include "sql/executor/tuple.h"
#include "storage/common/table.h"
#include "common/log/log.h"
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
Tuple::Tuple(const Tuple &other)
{
LOG_PANIC("Copy constructor of tuple is not supported");
exit(1);
}
Tuple::Tuple(Tuple &&other) noexcept : values_(std::move(other.values_))
{
selectComareIndex = -1;
}
Tuple &Tuple::operator=(Tuple &&other) noexcept
{
if (&other == this)
{
return *this;
}
values_.clear();
values_.swap(other.values_);
return *this;
}
Tuple::~Tuple()
{
}
// add (Value && value)
void Tuple::add(TupleValue *value)
{
values_.emplace_back(value);
}
void Tuple::add(const std::shared_ptr<TupleValue> &other)
{
values_.emplace_back(other);
}
void Tuple::add(int value)
{
add(new IntValue(value, 0));
}
void Tuple::add_null_value()
{
add(new NullValue());
}
void Tuple::add(float value)
{
add(new FloatValue(value, 0));
}
//按照列的名字,添加 values
void Tuple::add(const char *s, int len)
{
add(new StringValue(s, len, 0));
}
void Tuple::add_text(const char *s, int len)
{
add(new TextValue(s, len, 0));
}
void Tuple::add_date(int value)
{
add(new DateValue(value, 0));
}
////////////////////////////////////////////////////////////////////////////////
std::string TupleField::to_string() const
{
return std::string(table_name_) + "." + field_name_ + std::to_string(type_);
}
////////////////////////////////////////////////////////////////////////////////
void TupleSchema::from_table(const Table *table, TupleSchema &schema)
{
const char *table_name = table->name(); //表名字
const TableMeta &table_meta = table->table_meta(); //表结构
const int field_num = table_meta.field_num(); //字段个数
for (int i = 0; i < field_num; i++)
{
const FieldMeta *field_meta = table_meta.field(i);
if (field_meta->visible())
{
schema.add(field_meta->type(), table_name, field_meta->name(), field_meta->nullable());
}
}
}
void TupleSchema::add(AttrType type, const char *table_name, const char *field_name, int nullable)
{
fields_.emplace_back(type, table_name, field_name, nullable);
}
void TupleSchema::add(AttrType type, const char *table_name, const char *field_name)
{
fields_.emplace_back(type, table_name, field_name);
}
void TupleSchema::add(AttrType type, const char *table_name, const char *field_name, bool visible)
{
fields_.emplace_back(type, table_name, field_name, visible);
}
void TupleSchema::add_if_not_exists(AttrType type, const char *table_name, const char *field_name)
{
for (const auto &field : fields_)
{
if (0 == strcmp(field.table_name(), table_name) &&
0 == strcmp(field.field_name(), field_name))
{
LOG_INFO(">>>>>>>>>>add_if_exists. %s.%s", table_name, field_name);
return;
}
}
LOG_INFO("add_if_not_exists. %s.%s", table_name, field_name);
add(type, table_name, field_name);
}
void TupleSchema::add_if_not_exists1(AttrType type, const char *table_name, const char *field_name, int nullable)
{
for (const auto &field : fields_)
{
if (0 == strcmp(field.table_name(), table_name) &&
0 == strcmp(field.field_name(), field_name))
{
LOG_INFO(">>>>>>>>>>add_if_exists. %s.%s", table_name, field_name);
return;
}
}
// LOG_INFO("add_if_not_exists. %s.%s", table_name, field_name);
add(type, table_name, field_name, nullable);
}
void TupleSchema::add_if_not_exists(AttrType type, const char *table_name, const char *field_name, FunctionType ftype)
{
//判断列是否存在
for (const auto &field : fields_)
{
if (0 == strcmp(field.table_name(), table_name) &&
0 == strcmp(field.field_name(), field_name) &&
ftype == field.get_function_type())
{
LOG_INFO(">>>>>>>>>>add_if_exists. %s.%s", table_name, field_name);
return;
}
}
LOG_INFO("add_if_not_exists. %s.%s", table_name, field_name);
add(type, table_name, field_name, ftype);
}
void TupleSchema::append(const TupleSchema &other)
{
fields_.reserve(fields_.size() + other.fields_.size());
for (const auto &field : other.fields_)
{
fields_.emplace_back(field);
}
}
int TupleSchema::index_of_field(const char *table_name, const char *field_name) const
{
const int size = fields_.size();
for (int i = 0; i < size; i++)
{
const TupleField &field = fields_[i];
if (0 == strcmp(field.table_name(), table_name) && 0 == strcmp(field.field_name(), field_name))
{
return i;
}
}
return -1;
}
//列信息: fields_:(type_ = INTS, table_name_ = "t1", field_name_ = "id")
void TupleSchema::print(std::ostream &os) const
{
if (fields_.empty())
{
os << "No schema";
return;
}
// 判断有多张表还是只有一张表
//并不使用 table_names的数据
std::set<std::string> table_names;
for (const auto &field : fields_)
{
table_names.insert(field.table_name());
}
//单表逻辑
if (table_names.size() == 1)
{
//遍历n-1个元素.
for (std::vector<TupleField>::const_iterator iter = fields_.begin(), end = --fields_.end();
iter != end; ++iter)
{
//如果多个表:添加表名t.id
if (table_names.size() > 1 || realTabeNumber > 1)
{
os << iter->table_name() << ".";
}
if (FunctionType::FUN_COUNT_ALL == iter->get_function_type())
{
//count(1)
//if (0 == strcmp("*", iter->field_name()))
//{
//os << "count(*)"
// << " | ";
//}
//else
//{
os << "count(" << iter->field_name_count_number() << ")"
<< " | ";
//}
}
if (FunctionType::FUN_COUNT_ALL_ALl == iter->get_function_type())
{
//count(*)
os << "count(*)"
<< " | ";
}
else if (iter->get_function_type() == FunctionType::FUN_COUNT)
{
os << "count(" << iter->field_name() << ")"
<< " | ";
}
else if (iter->get_function_type() == FunctionType::FUN_MAX)
{
os << "max(" << iter->field_name() << ")"
<< " | ";
}
else if (iter->get_function_type() == FunctionType::FUN_MIN)
{
os << "min(" << iter->field_name() << ")"
<< " | ";
}
else if (iter->get_function_type() == FunctionType::FUN_AVG)
{
os << "avg(" << iter->field_name() << ")"
<< " | ";
}
else
{
//正常情况
os << iter->field_name() << " | ";
}
}
//last col
//visible
if (table_names.size() > 1 || realTabeNumber > 1)
{
os << fields_.back().table_name() << ".";
}
//id ---- 最后一个列,后面没有 |,只有名字
if (FunctionType::FUN_COUNT_ALL_ALl == fields_.back().get_function_type())
{
//count(*)
os << "count(*)" << std::endl;
}
else if (fields_.back().get_function_type() == FunctionType::FUN_COUNT_ALL)
{
//os << "count(*)" << std::endl; //select count(*) from t;
//if (0 == strcmp("*", fields_.back().field_name()))
//{
//os << "count(*)" << std::endl;
//}
//else
//{
os << "count(" << fields_.back().field_name_count_number() << ")" << std::endl;
//}
}
else if (fields_.back().get_function_type() == FunctionType::FUN_COUNT)
{
os << "count(" << fields_.back().field_name() << ")" << std::endl;
}
else if (fields_.back().get_function_type() == FunctionType::FUN_MAX)
{
os << "max(" << fields_.back().field_name() << ")" << std::endl;
}
else if (fields_.back().get_function_type() == FunctionType::FUN_MIN)
{
os << "min(" << fields_.back().field_name() << ")" << std::endl;
}
else if (fields_.back().get_function_type() == FunctionType::FUN_AVG)
{
os << "avg(" << fields_.back().field_name() << ")" << std::endl;
}
//bug1 else if ->if
else
{ //正常情况
os << fields_.back().field_name() << std::endl;
}
//单表 列逻辑 ///////////////////////////////////////// end
}
else
{
//多表逻辑///////////////////////////////////////// 开始
//https://github.com/oceanbase/miniob/blob/main/src/observer/sql/executor/tuple.cpp#123
LOG_INFO(" join query cols >>>>>>>>>>>>>>");
//删除不显示的列
/**
std::vector<TupleField> tuplefields;
for (std::vector<TupleField>::const_iterator iter = fields_.begin(), end =fields_.end();
iter != end; ++iter)
{
tuplefields.push_back(*iter);
}
for (std::vector<TupleField>::iterator iter = tuplefields.begin(), end =tuplefields.end();
iter != end; )
{
if( false ==iter->visible()){
iter = tuplefields.erase(iter);
}else{
iter++;
}
}**/
for (std::vector<TupleField>::const_iterator iter = fields_.begin(), end = --fields_.end();
iter != end; ++iter)
{
if (FunctionType::FUN_COUNT_ALL == iter->get_function_type())
{
//count(1)
os << "count(" << iter->field_name_count_number() << ")"
<< " | ";
}
else if (FunctionType::FUN_COUNT_ALL_ALl == iter->get_function_type())
{
//count(*)
os << "count(*)"
<< " | ";
}
else if (iter->get_function_type() == FunctionType::FUN_COUNT)
{
os << "count(";
if (table_names.size() > 1)
{
os << iter->table_name() << ".";
}
os << iter->field_name() << ")"
<< " | ";
}
else if (iter->get_function_type() == FunctionType::FUN_MAX)
{
os << "max(";
if (table_names.size() > 1)
{
os << iter->table_name() << ".";
}
os << iter->field_name() << ")"
<< " | ";
}
else if (iter->get_function_type() == FunctionType::FUN_MIN)
{
os << "min(";
if (table_names.size() > 1)
{
os << iter->table_name() << ".";
}
os << iter->field_name() << ")"
<< " | ";
}
else if (iter->get_function_type() == FunctionType::FUN_AVG)
{
os << "avg(";
if (table_names.size() > 1)
{
os << iter->table_name() << ".";
}
os << iter->field_name() << ")"
<< " | ";
}
else
{
//正常情况
if (table_names.size() > 1)
{
os << iter->table_name() << ".";
}
os << iter->field_name() << " | ";
}
}
//最后一列:显示
if (FunctionType::FUN_COUNT_ALL == fields_.back().get_function_type())
{
//count(1)
os << "count(" << fields_.back().field_name_count_number() << ")"
<< std::endl;
}
else if (FunctionType::FUN_COUNT_ALL_ALl == fields_.back().get_function_type())
{
//count(*)
os << "count(*)"
<< std::endl;
}
else if (fields_.back().get_function_type() == FunctionType::FUN_COUNT)
{
os << "count(";
if (table_names.size() > 1)
{
os << fields_.back().table_name() << ".";
}
os << fields_.back().field_name() << ")"
<< std::endl;
}
else if (fields_.back().get_function_type() == FunctionType::FUN_MAX)
{
os << "max(";
if (table_names.size() > 1)
{
os << fields_.back().table_name() << ".";
}
os << fields_.back().field_name() << ")"
<< std::endl;
}
else if (fields_.back().get_function_type() == FunctionType::FUN_MIN)
{
os << "min(";
if (table_names.size() > 1)
{
os << fields_.back().table_name() << ".";
}
os << fields_.back().field_name() << ")"
<< std::endl;
}
else if (fields_.back().get_function_type() == FunctionType::FUN_AVG)
{
os << "avg(";
if (table_names.size() > 1)
{
os << fields_.back().table_name() << ".";
}
os << fields_.back().field_name() << ")"
<< std::endl;
}
else
{
//正常情况,普通的字
if (table_names.size() > 1)
{
os << fields_.back().table_name() << ".";
}
os << fields_.back().field_name() << std::endl;
}
///////////////////////////end,多表逻辑////////////////////////////end
}
}
/////////////////////////////////////////////////////////////////////////////
TupleSet::TupleSet(TupleSet &&other) : tuples_(std::move(other.tuples_)), schema_(other.schema_)
{
other.schema_.clear();
realTabeNumber = other.realTabeNumber;
//push_back(std::move(TupleSet))
old_schema = other.old_schema;
commonIndex = other.commonIndex;
select_table_type = other.select_table_type;
dp = other.dp;
}
TupleSet &TupleSet::operator=(TupleSet &&other)
{
if (this == &other)
{
return *this;
}
schema_.clear();
schema_.append(other.schema_);
other.schema_.clear();
realTabeNumber = -1;
tuples_.clear();
//swap 交换
tuples_.swap(other.tuples_);
return *this;
}
void TupleSet::add(Tuple &&tuple)
{
tuples_.emplace_back(std::move(tuple));
}
void TupleSet::clear()
{
tuples_.clear();
schema_.clear();
old_schema.clear();
dp.clear();
}
//print shows
void TupleSet::print(std::ostream &os)
{
//列信息: (type_ = INTS, table_name_ = "t1", field_name_ = "id")
if (schema_.fields().empty())
{
LOG_WARN("Got empty schema");
return;
}
if (realTabeNumber > 1)
{
schema_.realTabeNumber = realTabeNumber;
}
else
{
schema_.realTabeNumber = -1;
}
schema_.print(os); //打印 列字段 (已经考虑到多个表)
// 判断有多张表还是只有一张表
std::set<std::string> table_names;
for (const auto &field : schema_.fields())
{
table_names.insert(field.table_name());
}
//一个表:
if (table_names.size() == 1)
{
//分组 group-by
if (ptr_group_selects && ptr_group_selects->attr_group_num > 0)
{
print_group_by(os);
return;
}
//单表聚合:只有一行
if (true == avg_print(os))
{
LOG_INFO("this is avg query >>>>>>>>>>>>>>>>>> ");
return;
}
//排序 order-by
int order_by_num = -1;
RelAttr *ptr_attr_order_by = nullptr;
if (ptr_group_selects && ptr_group_selects->attr_order_num > 0)
{
order_by_num = ptr_group_selects->attr_order_num;
ptr_attr_order_by = ptr_group_selects->attr_order_by;
}
int group_by_num = -1;
RelAttr *ptr_attr_group_by = nullptr;
if (ptr_group_selects && ptr_group_selects->attr_group_num > 0)
{
group_by_num = ptr_group_selects->attr_group_num;
ptr_attr_group_by = ptr_group_selects->attr_group_by;
}
if (order_by_num > 0)
{
//order by
//std::vector<Tuple> tuples_; //一个表头信息
//TupleSchema schema_; //一个表内容信息
//SELECT * FROM T_ORDER_BY ORDER BY ID, SCORE, NAME;
std::vector<int> order_index;
order_index.clear();
const std::vector<TupleField> &fields = schema_.fields();
int index = 0;
for (std::vector<TupleField>::const_iterator iter = fields.begin(), end = fields.end();
iter != end; ++iter)
{
//SELECT * FROM T_ORDER_BY ORDER BY ID, SCORE, NAME;
for (int cols = 0; cols < order_by_num; cols++)
{
if (0 == strcmp(iter->field_name(), ptr_attr_order_by[cols].attribute_name))
{
order_index.push_back(index);
LOG_INFO("题目:排序 >>>>>> index=%d,cols=%d,name=%s", index, cols, ptr_attr_order_by[cols].attribute_name);
}
}
index++;
}
if (order_by_num != order_index.size())
{
LOG_INFO("排序 order-by 失败 order_by_num != order_index.size()");
return;
}
LOG_INFO("排序 order-by 开始排序 order_index=%d", order_by_num);
auto sortRuleLambda = [=](const Tuple &s1, const Tuple &s2) -> bool {
//std::vector<std::shared_ptr<TupleValue>> values_;
std::vector<std::shared_ptr<TupleValue>> sp1;
std::vector<std::shared_ptr<TupleValue>> sp2;
//根据位置--查找value
for (int i = 0; i < order_index.size(); i++)
{
sp1.push_back(s1.get_pointer(order_index[i]));
sp2.push_back(s2.get_pointer(order_index[i]));
}
//多个字段如何比较呀?
for (int op_index = 0; op_index < order_index.size(); op_index++)
{
int op_comp = 0;
std::shared_ptr<TupleValue> sp_1 = sp1[op_index];
std::shared_ptr<TupleValue> sp_2 = sp2[op_index];
if (sp_1 && sp_2)
{
op_comp = sp_1->compare(*sp_2);
}
//不相等才比较 ,相等下一个
if (op_comp != 0)
{
int index_order = order_index.size() - op_index - 1;
if (CompOp::ORDER_ASC == ptr_attr_order_by[index_order].is_asc)
{
LOG_INFO("排序 order-by ORDER_ASC op_index=%d, order_index=%d,name=%s", op_index, order_by_num, ptr_attr_order_by[index_order].attribute_name);
return op_comp < 0; //true
}
else if (CompOp::ORDER_DESC == ptr_attr_order_by[index_order].is_asc)
{
LOG_INFO("排序 order-by ORDER_DESC op_index=%d,order_index=%d,name=%s", op_index, order_by_num, ptr_attr_order_by[index_order].attribute_name);
return op_comp > 0; //true
}
else
{
LOG_INFO("排序 order-by err err err err order_index=%d,name=%s", order_by_num, ptr_attr_order_by[index_order].attribute_name);
}
}
} ////多个字段如何比较呀?
//为什么std::sort比较函数在参数相等时返回false?
return false;
};
if (tuples_.size() > 0)
{
std::sort(tuples_.begin(), tuples_.end(), sortRuleLambda);
}
}
//rows cols
for (const Tuple &item : tuples_)
{
//第n-1列
const std::vector<std::shared_ptr<TupleValue>> &values = item.values();
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = --values.end();
iter != end; ++iter)
{
(*iter)->to_string(os);
os << " | ";
}
//最后一列
values.back()->to_string(os);
os << std::endl;
//1 | 2 | 3
}
}
else if (table_names.size() == 2)
{
////多表操作/////////////////////////////////////
//笛卡尔积算法描述
if (tuples1_.size() == 0 || tuples2_.size() == 0)
{
return;
}
//t1.rows[i][j]
//t2.rows[i][j]
for (const Tuple &item_left : tuples1_)
{
std::shared_ptr<TupleValue> sp1;
int col1 = 0;
std::stringstream os_left;
{
//std::vector<std::shared_ptr<TupleValue>> values_; 每一行 多个字段
const std::vector<std::shared_ptr<TupleValue>> &values = item_left.values();
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end();
iter != end; ++iter)
{
if (is_join == true && joins_index == col1)
{
sp1 = *iter;
cout << ">>>>>>>>>>>>>join select " << endl;
}
(*iter)->to_string(os_left);
os_left << " | ";
col1++;
}
}
//b表的多行 tuples_right 多行
for (const Tuple &item_right : tuples2_)
{
std::shared_ptr<TupleValue> sp2;
int col2 = 0;
std::stringstream os_right;
{
const std::vector<std::shared_ptr<TupleValue>> &values = item_right.values();
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = --values.end();
iter != end; ++iter)
{
//笛卡尔积:查询条件
if (is_join == true && joins_index == col2)
{
sp2 = *iter;
cout << ">>>>>>>>>>>>>join select " << endl;
}
(*iter)->to_string(os_right);
os_right << " | ";
col2++;
}
//小王疑问:为啥还有最后行 不是上面遍历完毕了吗?
values.back()->to_string(os_right);
os_right << std::endl;
}
//多表:join查询
if (is_join == true)
{
LOG_INFO(" two table join select ");
if (sp1 && sp2 && 0 == sp1->compare(*sp2))
{
os << os_left.str();
os << os_right.str();
}
else
{
LOG_INFO(" not equal ");
}
}
else
{
os << os_left.str();
os << os_right.str();
}
}
}
}
else
{
LOG_INFO(" no support three table query ");
}
}
void TupleSet::set_schema(const TupleSchema &schema)
{
schema_ = schema;
}
const TupleSchema &TupleSet::get_schema() const
{
return schema_;
}
bool TupleSet::is_empty() const
{
return tuples_.empty();
}
int TupleSet::size() const
{
return tuples_.size();
}
const Tuple &TupleSet::get(int index) const
{
return tuples_[index];
}
const std::vector<Tuple> &TupleSet::tuples() const
{
return tuples_;
}
/////////////////////////////////////////////////////////////////////////////
TupleRecordConverter::TupleRecordConverter(Table *table, TupleSet &tuple_set) : table_(table), tuple_set_(tuple_set)
{
}
//record:value 开始地址
//record --->显示
void TupleRecordConverter::add_record(const char *record)
{
const TupleSchema &schema = tuple_set_.schema();
//查询条件的表信息 可能全部列 可能部分
Tuple tuple;
const TableMeta &table_meta = table_->table_meta();
for (const TupleField &field : schema.fields())
{
const FieldMeta *field_meta = table_meta.field(field.field_name());
assert(field_meta != nullptr);
int null_able = field_meta->nullable();
switch (field_meta->type())
{
case INTS:
{
if (null_able == 1)
{
const char *s = record + field_meta->offset();
if (0 == strcmp(s, "999"))
{
tuple.add_null_value();
}
else
{
int value = *(int *)(record + field_meta->offset());
//LOG_INFO(" tuple add int =%d ", value);
tuple.add(value);
}
}
else
{
int value = *(int *)(record + field_meta->offset());
// LOG_INFO(" tuple add int =%d ", value);
tuple.add(value);
}
}
break;
case FLOATS:
{
if (null_able == 1)
{
//memset 改为
const char *s = record + field_meta->offset();
if (0 == strcmp(s, "999"))
{
//LOG_INFO("99999 FLOATS");
tuple.add_null_value();
}
else
{
float value = *(float *)(record + field_meta->offset());
//LOG_INFO(" tuple add float =%d ", value);
tuple.add(value);
}
}
else
{
float value = *(float *)(record + field_meta->offset());
LOG_INFO(" tuple add float =%d ", value);
tuple.add(value);
}
}
break;
case CHARS:
{
if (null_able == 1)
{
//memset 改为
const char *s = record + field_meta->offset();
if (0 == strcmp(s, "999"))
{
//LOG_INFO("99999 FLOATS");
tuple.add_null_value();
}
else
{
const char *s = record + field_meta->offset(); // 现在当做Cstring来处理
// LOG_INFO(" tuple add string =%s ", s);
tuple.add(s, strlen(s));
}
}
else
{
const char *s = record + field_meta->offset(); // 现在当做Cstring来处理
LOG_INFO(" tuple add string =%s ", s);
tuple.add(s, strlen(s));
}
}
break;
case DATES:
{
if (null_able == 1)
{
//memset memcpy
const char *s = record + field_meta->offset();
if (0 == strcmp(s, "999"))
{
// LOG_INFO("99999 FLOATS");
tuple.add_null_value();
}
else
{
int value = *(int *)(record + field_meta->offset());
// LOG_INFO(" tuple.add_date=%d ", value);
tuple.add_date(value);
}
}
else
{
int value = *(int *)(record + field_meta->offset());
// LOG_INFO(" tuple.add_date=%d ", value);
tuple.add_date(value);
}
}
break;
case TEXTS:
{
if (null_able == 1)
{
//memset 改为
const char *s = record + field_meta->offset();
if (0 == strcmp(s, "999"))
{
//LOG_INFO("99999 FLOATS");
tuple.add_null_value();
}
else
{
const char *s = record + field_meta->offset(); // 现在当做Cstring来处理
// LOG_INFO(" tuple add string =%s ", s);
int key = *(int *)s;
if (table()->pTextMap.count(key) == 1)
{
s = table()->pTextMap[key];
LOG_INFO(" 题目 超长文本 >>>>>>>>>>>> key=%d,value=%s ", key, s);
}
else
{
LOG_INFO(" 题目 超长文本 失败 失败 失败 失败 =%s ", s);
}
tuple.add_text(s, strlen(s));
}
}
else
{
const char *s = record + field_meta->offset(); // 现在当做Cstring来处理
int key = *(int *)s;
if (table()->pTextMap.count(key) == 1)
{
s = table()->pTextMap[key];
LOG_INFO(" 题目 超长文本 >>>>>>>>>>>> key=%d,value=%s ", key, s);
}
else
{
LOG_INFO(" 题目 超长文本 失败 失败 失败 失败 key=%d,value=%s ", key, s);
}
tuple.add(s, strlen(s));
}
}
break;
default:
{
LOG_PANIC("Unsupported field type. type=%d", field_meta->type());
}
}
}
tuple_set_.add(std::move(tuple));
}
//聚合
void TupleSchema::from_table_first(const Table *table, TupleSchema &schema, FunctionType functiontype)
{
const char *table_name = table->name(); //表名字
const TableMeta &table_meta = table->table_meta(); //表结构
//const int field_num = table_meta.field_num(); //字段个数
const FieldMeta *field_meta = table_meta.field(1);
if (field_meta && field_meta->visible())
{
schema.add(field_meta->type(), table_name, field_meta->name(), functiontype, field_meta->nullable());
}
}
void TupleSchema::add(AttrType type, const char *table_name, const char *field_name, FunctionType functiontype)
{
fields_.emplace_back(type, table_name, field_name, functiontype);
}
void TupleSchema::add(AttrType type, const char *table_name, const char *field_name, FunctionType functiontype, int nullable)
{
fields_.emplace_back(type, table_name, field_name, functiontype, nullable);
}
bool TupleSet::avg_print(std::ostream &os) const
{
//步骤
//1. 遍历 属性
//2. 根据不同属性函数,做不同的计算.
//3. 返回是存在聚合
bool isWindows = false;
const std::vector<TupleField> &fields = schema_.fields();
int count = fields.size();
int index = 0;
//遍历n个元素.
for (std::vector<TupleField>::const_iterator iter = fields.begin(), end = fields.end();
iter != end; ++iter)
{
FunctionType window_function = iter->get_function_type();
if (FunctionType::FUN_COUNT_ALL_ALl == window_function || FunctionType::FUN_COUNT_ALL == window_function || FunctionType::FUN_COUNT == window_function)
{
isWindows = true;
int count = 0;
//count(*)
if (FunctionType::FUN_COUNT_ALL_ALl == window_function || FunctionType::FUN_COUNT_ALL == window_function)
{
count = tuples_.size();
}
else
{
//rows count(id)
//字段值是NULL时,比较特殊,不需要统计在内。如果是AVG,不会增加统计行数,也不需要默认值。
for (const Tuple &item : tuples_)
{
int colIndex = 0;
bool null_able = true;
//cols
const std::vector<std::shared_ptr<TupleValue>> &values = item.values();
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end();
iter != end; ++iter)
{
if (colIndex == index)
{
std::shared_ptr<TupleValue> temp = *iter;
if (AttrType::NULLVALUES == temp->get_type())
{
null_able = false;
}
break;
}
colIndex++;
}
if (true == null_able)
{
count++;
}
}
} //end else
os << count;
}
else if (FunctionType::FUN_MAX == window_function)
{
//属性值类型 typedef enum { UNDEFINED, CHARS, INTS, FLOATS,DATES } AttrType;
isWindows = true;
std::shared_ptr<TupleValue> maxValue;
if (0 == tuples_.size())
{
return true;
}
for (const Tuple &item : tuples_)
{
int colIndex = 0;
//第n-1列
const std::vector<std::shared_ptr<TupleValue>> &values = item.values();
if (0 == values.size())
{
continue;
}
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end();
iter != end; ++iter)
{
//(*iter)->to_string(os);
if (colIndex == index)
{
std::shared_ptr<TupleValue> temp = *iter;
//if (AttrType::NULLVALUES == temp->get_type())
//{
//不处理
//}
//else
{
if (nullptr == maxValue)
{
maxValue = temp;
}
else
{
if (maxValue->compare(*temp) < 0)
{
maxValue = temp;
}
}
}
break; //get
}
colIndex++;
}
} //end
maxValue->to_string(os);
}
else if (FunctionType::FUN_MIN == window_function)
{
//属性值类型 typedef enum { UNDEFINED, CHARS, INTS, FLOATS,DATES } AttrType;
isWindows = true;
std::shared_ptr<TupleValue> minValue;
if (0 == tuples_.size())
{
return true;
}
for (const Tuple &item : tuples_)
{
int colIndex = 0;
//列
const std::vector<std::shared_ptr<TupleValue>> &values = item.values();
if (0 == values.size())
{
continue;
}
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end();
iter != end; ++iter)
{
//(*iter)->to_string(os);
if (colIndex == index)
{
std::shared_ptr<TupleValue> temp = *iter;
//if (AttrType::NULLVALUES == temp->get_type())
//{
//不处理
//}
//else
{
if (nullptr == minValue)
{
minValue = *iter;
}
else
{
std::shared_ptr<TupleValue> temp = *iter;
if (minValue->compare(*temp) > 0)
{
minValue = temp;
}
}
}
break; //get
}
colIndex++;
}
} //end
minValue->to_string(os);
}
else if (FunctionType::FUN_AVG == window_function)
{
//属性值类型 typedef enum { UNDEFINED, CHARS, INTS, FLOATS,DATES } AttrType;
isWindows = true;
std::shared_ptr<TupleValue> sumValue;
int count = 0;
bool exits_null_value = false;
if (0 == tuples_.size())
{
return true;
}
for (const Tuple &item : tuples_)
{
int colIndex = 0;
bool null_able = true;
//第n列
const std::vector<std::shared_ptr<TupleValue>> &values = item.values();
if (0 == values.size())
{
continue;
}
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end();
iter != end; ++iter)
{
//(*iter)->to_string(os);
if (colIndex == index)
{
std::shared_ptr<TupleValue> temp = *iter;
if (AttrType::NULLVALUES == temp->get_type())
{
//不处理
null_able = false;
exits_null_value = true;
}
else
{
if (nullptr == sumValue)
{
sumValue = temp;
}
else
{
sumValue->add_value(*temp);
}
}
break; //get
}
colIndex++;
}
if (true == null_able)
{
count++;
}
} //end
//防溢出求平均算法
if (0 == count)
{
if (exits_null_value == true)
{
os << "NULL";
os << std::endl;
}
return true; //是聚合运算
}
sumValue->to_avg(count, os);
}
//聚合函数显示
if (FunctionType::FUN_AVG == window_function ||
FunctionType::FUN_COUNT == window_function ||
FunctionType::FUN_COUNT_ALL == window_function ||
FunctionType::FUN_COUNT_ALL_ALl == window_function ||
FunctionType::FUN_MIN == window_function ||
FunctionType::FUN_MAX == window_function)
{
if (index == count - 1)
{
//os << result.c_str();
os << std::endl;
}
else
{
//os << result.c_str();
os << " | ";
}
}
index++;
} //const std::vector<TupleField> &fields = schema_.fields();
return isWindows;
}
void TupleSchema::add_if_not_exists_visible(AttrType type, const char *table_name, const char *field_name, bool visible)
{
for (const auto &field : fields_)
{
if (0 == strcmp(field.table_name(), table_name) &&
0 == strcmp(field.field_name(), field_name))
{
LOG_INFO(">>>>>>>>>>add_if_exists. %s.%s", table_name, field_name);
return;
}
}
add(type, table_name, field_name, visible);
}
//2个表的join操作
void TupleSet::print_two(std::ostream &os)
{
//列信息: (type_ = INTS, table_name_ = "t1", field_name_ = "id")
if (schema_.fields().empty())
{
LOG_WARN("Got empty schema");
return;
}
if (old_schema.get_size() > 0)
{
old_schema.realTabeNumber = 2;
//修改old_schema成员变量, 去掉const函数
old_schema.print(os);
// 原始查询条件
//select t2.age from t1 ,t2 where t1.age=21;
}
else
{
schema_.print(os); //打印 列字段 (已经考虑到多个表)
}
// 判断有多张表还是只有一张表
std::set<std::string> table_names;
for (const auto &field : schema_.fields())
{
table_names.insert(field.table_name());
}
if (2 != table_names.size())
{
return;
}
////多表操作/////////////////////////////////////
//笛卡尔积算法描述
if (tuples1_.size() == 0 || tuples2_.size() == 0)
{
return;
}
//select t1.age,t2.age from t1 ,t2 where t1.id =t2.id;
//[id(隐藏),age] [age,id(隐藏))
std::map<int, bool> leftVisibleMap;
leftVisibleMap.clear();
int index1 = 0;
int count1 = schema1_.get_size() - 1;
for (const auto &field : schema1_.fields())
{
if (false == field.visible())
{
if (index1 == count1)
{
leftVisibleMap[index1] = true; //最后一个字段
}
else
{
leftVisibleMap[index1] = false;
}
}
index1++;
}
std::map<int, bool> rightVisibleMap;
rightVisibleMap.clear();
int index2 = 0;
int count2 = schema2_.get_size() - 1;
for (const auto &field : schema2_.fields())
{
if (false == field.visible())
{
if (index2 == count2)
{
rightVisibleMap[index2] = true;
}
else
{
rightVisibleMap[index2] = false;
}
}
index2++;
}
order_by_two();
//t1.rows[i][j]
//t2.rows[i][j]
//item_left 一行记录
//第一个表内容
for (const Tuple &item_left : tuples1_)
{
std::shared_ptr<TupleValue> sp1;
vector<std::shared_ptr<TupleValue>> left(dp.size());
//多个过滤条件
//几个过滤条件
//select t1.age,t1.id ,t2.id,t2.age from t1,t2 where t1.id=t2.id and t1.age =t2.age;
int col1 = 0;
std::stringstream os_left; //第一个表的 全部行
std::stringstream os_left1;
std::stringstream os_left2;
{
//std::vector<std::shared_ptr<TupleValue>> values_; 每一行 多个字段
const std::vector<std::shared_ptr<TupleValue>> &values = item_left.values();
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end();
iter != end; ++iter)
{
if (is_join == true && joins_index == col1)
{
sp1 = *iter;
cout << ">>>>>>>>>>>>>join select " << endl;
}
if (is_join == true)
{
for (int i = 0; i < dp.size(); i++)
{
if (col1 == dp[i][0].m_index)
{
left[i] = *iter;
cout << "left " << col1 << endl;
}
}
}
//一个表:是否隐藏
if (leftVisibleMap.size() > 0 && leftVisibleMap.count(col1) == 1)
{
}
else
{
if (b_not_know == true && col1 == 1)
{
(*iter)->to_string(os_left1);
LOG_INFO("11111111111111111 left=");
}
else
{
(*iter)->to_string(os_left);
os_left << " | ";
}
}
col1++;
}
}
//b表的多行 tuples_right 多行
//第2个表内容
for (const Tuple &item_right : tuples2_)
{
std::shared_ptr<TupleValue> sp2;
vector<std::shared_ptr<TupleValue>> right(dp.size());
right.clear();
int col2 = 0;
std::stringstream os_right; //第二个表:一行记录
{
const std::vector<std::shared_ptr<TupleValue>> &values = item_right.values();
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end();
iter != end; ++iter)
{
//笛卡尔积:查询条件
if (is_join == true && joins_index == col2)
{
sp2 = *iter;
}
if (is_join == true)
{
for (int ri = 0; ri < dp.size(); ri++)
{
if (col2 == dp[ri][1].m_index)
{
right[ri] = *iter;
cout << "right " << col2 << endl;
}
}
}
//判断是否最后一行
if (col2 == values.size() - 1)
{
//一个表:是否隐藏
if (rightVisibleMap.size() > 0 && rightVisibleMap.count(col2) == 1)
{
//隐藏 什么都不操作
}
else
{
if (b_not_know == true)
{
(*iter)->to_string(os_right);
os_right << " | ";
os_right << os_left1.str();
os_right << std::endl;
}
else
{
(*iter)->to_string(os_right);
os_right << std::endl;
}
}
}
else
{
if (rightVisibleMap.size() > 0 && rightVisibleMap.count(col2) == 1)
{
//隐藏 什么都不操作
}
else if (rightVisibleMap.size() > 0 && rightVisibleMap.count(col2) == 0)
{
//自己不隐藏,下一行隐藏,下一行是最后一行
////age(当前),id(隐藏)
int next = col2 + 1;
if (rightVisibleMap.count(next) == 1 && true == rightVisibleMap[next])
{
(*iter)->to_string(os_right);
os_right << std::endl;
}
}
else
{
(*iter)->to_string(os_right);
os_right << " | ";
}
}
col2++;
}
}
//多表:有join条件
if (is_join == true)
{
LOG_INFO(" two table join select ");
bool b_equal = false; //符合条件
//join条件全部相等
for (int i = 0; i < dp.size(); i++)
{
CompOp two_comp = dp[i][0].comp;
std::stringstream s1;
std::stringstream s2;
left[i]->to_string(s1);
right[i]->to_string(s2);
std::cout << " >>>>>>> left:" << s1.str() << "right:" << s2.str() << std::endl;
//"=="
if (two_comp == EQUAL_TO)
{
if (left[i] && right[i] && 0 == left[i]->compare(*right[i]))
{
b_equal = true;
}
}
else if (two_comp == GREAT_EQUAL)
{
// ">=" t1.id >=t2.id
if (left[i] && right[i] && left[i]->compare(*right[i]) >= 0)
{
b_equal = true;
}
}
else if (two_comp == GREAT_THAN)
{
// ">"
if (left[i] && right[i] && left[i]->compare(*right[i]) > 0)
{
b_equal = true;
}
}
else if (two_comp == LESS_EQUAL)
{
// "<="
if (left[i] && right[i] && left[i]->compare(*right[i]) <= 0)
{
b_equal = true;
}
}
else if (two_comp == LESS_THAN)
{
// "<"
if (left[i] && right[i] && left[i]->compare(*right[i]) < 0)
{
b_equal = true;
}
}
}
if (true == b_equal)
{
//sql: 1笛卡尔积 2 排序 3 分组 4 输出
//题目:order_by
if (ptr_group_selects && ptr_group_selects->attr_order_num > 0)
{
join_table_for_order_by(item_left, item_right);
}
else if (ptr_group_selects && ptr_group_selects->attr_group_num > 0)
{
join_table_for_group_by(item_left, item_right);
//这里不输出,哪里输出呀
}
else
{
os << os_left.str();
os << os_right.str();
}
}
}
else
{ //没有join条件
os << os_left.str();
os << os_right.str();
}
}
}
//题目:order_by
if (ptr_group_selects && ptr_group_selects->attr_order_num > 0)
{
sort_table_for_order_by();
std::stringstream ss;
join_tuples_to_print(ss);
os << ss.str();
}
else if (ptr_group_selects && ptr_group_selects->attr_group_num > 0)
{
//步骤:排序 分组 统计
//2个表合成一个表了.
print_two_table_group_by(os);
}
}
//聚合
void TupleSchema::from_table_first_count_number(const Table *table, TupleSchema &schema, FunctionType functiontype, const char *field_name_count_number)
{
const char *table_name = table->name(); //表名字
const TableMeta &table_meta = table->table_meta(); //表结构
//const int field_num = table_meta.field_num(); //字段个数
const FieldMeta *field_meta = table_meta.field(1);
if (field_meta && field_meta->visible())
{
// schema.add(field_meta->type(), table_name, field_meta->name(), functiontype);
schema.add_number(field_meta->type(), table_name, field_meta->name(), functiontype, field_name_count_number, field_meta->nullable());
}
}
void TupleSchema::add_number(AttrType type, const char *table_name, const char *field_name, FunctionType functiontype, const char *field_name_count_number, int nullable)
{
TupleField temp(type, table_name, field_name, functiontype);
temp.field_name_count_number_ = field_name_count_number;
fields_.push_back(temp);
//fields_.emplace_back(std::move(temp));
//fields_.emplace_back(type, table_name, field_name, functiontype);
}
//至少3个表
void TupleSet::print_multi_table(std::ostream &os)
{
if (schema_.fields().empty())
{
LOG_WARN(" print_multi_table Got empty schema");
return;
}
schema_.print(os); // 如果显示列有问题 请在看这里 多个表合并一个表
// 判断有多张表还是只有一张表
std::set<std::string> table_names;
for (const auto &field : schema_.fields())
{
table_names.insert(field.table_name());
}
if (3 != table_names.size())
{
return;
}
////多表操作/////////////////////////////////////
//笛卡尔积算法描述
if (tuples1_.size() == 0 || tuples2_.size() == 0 || tuples3_.size() == 0)
{
return;
}
//三次循环
for (Tuple &item_1 : tuples1_)
{
std::stringstream os_tuples_1; //node1
os_tuples_1.clear();
// std::shared_ptr<TupleValue> sp1;
item_1.sp1.reset();
item_1.selectComareIndex = commonIndex; //比较字段位置
item_1.head_table_row_string(os_tuples_1, 1);
for (Tuple &item_2 : tuples2_)
{
std::stringstream os_tuples_2; //node2
os_tuples_2.clear();
item_2.sp2.reset();
item_2.selectComareIndex = commonIndex; //比较字段位置
item_2.head_table_row_string(os_tuples_2, 2);
std::stringstream os_tuples_1_2;
os_tuples_1_2.clear();
if (select_table_type == 2)
{
LOG_WARN(" >>>>>>>>>>>>>>>>>> select_table_type =2");
if (item_1.sp1 && item_2.sp2 && 0 == item_1.sp1->compare(*item_2.sp2))
{
os_tuples_1_2 << os_tuples_1.str();
os_tuples_1_2 << os_tuples_2.str();
LOG_WARN(" >>>>>>>>>>>>>>>>>> 相等 select_table_type =2");
}
else
{
LOG_WARN(" >>>>>>>>>>>>>>>>>> 不相等 select_table_type =2");
}
}
else
{
os_tuples_1_2 << os_tuples_1.str();
os_tuples_1_2 << os_tuples_2.str();
}
for (Tuple &item_3 : tuples3_)
{
std::stringstream os_tuples_3; //node3
os_tuples_3.clear();
item_3.sp3.reset();
item_3.selectComareIndex = commonIndex; //比较字段位置
item_3.tail_table_row_string(os_tuples_3, 3);
//多表:有join条件
//select * from t1,t2,t3;
if (false == is_join)
{
//没有join条件
os << os_tuples_1_2.str();
os << os_tuples_3.str();
}
else
{
//select_table_type
//0 查询无过滤条件
//1 三表完全过滤
//2表过滤 //a ok b ok c (no)
//3 //a (no) b ok c ok
////a (no) b ok c ok
if (select_table_type == 1)
{
bool b_equal = true;
if (item_1.sp1 && item_2.sp2 && 0 == item_1.sp1->compare(*item_2.sp2))
{
}
else
{
b_equal = false;
}
if (item_1.sp1 && item_3.sp3 && 0 == item_1.sp1->compare(*item_3.sp3))
{
}
else
{
b_equal = false;
}
if (true == b_equal)
{
os << os_tuples_1_2.str();
os << os_tuples_3.str();
}
//end if 1
}
else if (select_table_type == 2)
{
//2表过滤 //a ok b ok c (no)
//组合完毕---过滤
bool b_equal = true;
if (item_1.sp1 && item_2.sp2 && 0 == item_1.sp1->compare(*item_2.sp2))
{
}
else
{
b_equal = false;
}
if (true == b_equal)
{
os << os_tuples_1_2.str();
os << os_tuples_3.str();
}
} //end select_table_type == 2
else if (select_table_type == 3)
{
//3 //a (no) b ok c ok
bool b_equal = true;
//组合完毕---过滤
if (item_2.sp2 && item_3.sp3 && 0 == item_2.sp2->compare(*item_3.sp3))
{
}
else
{
b_equal = false;
}
if (true == b_equal)
{
os << os_tuples_1_2.str();
os << os_tuples_3.str();
}
////end select_table_type == 3
}
else if (4 == select_table_type)
{
//a (ok) b (no) c ok
//组合完毕---过滤
bool b_equal = true;
if (item_1.sp1 && item_3.sp3 && 0 == item_1.sp1->compare(*item_3.sp3))
{
}
else
{
b_equal = false;
}
if (true == b_equal)
{
os << os_tuples_1_2.str();
os << os_tuples_3.str();
}
}
} //end else
}
}
}
}
void Tuple::head_table_row_string(std::ostream &os)
{
const std::vector<std::shared_ptr<TupleValue>> &values = this->values();
//int cols =0;
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end();
iter != end; ++iter)
{
(*iter)->to_string(os);
os << " | ";
//if(cols ==selectComareIndex)
//{
// sp1 = *iter;
//}
//cols++;
}
}
void Tuple::tail_table_row_string(std::ostream &os)
{
size_t col2 = 0;
const std::vector<std::shared_ptr<TupleValue>> &values = this->values();
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end();
iter != end; ++iter)
{
//判断是否最后一行
if (col2 == values.size() - 1)
{
(*iter)->to_string(os);
os << std::endl;
}
else
{
(*iter)->to_string(os);
os << " | ";
}
col2++;
}
}
void Tuple::head_table_row_string(std::ostream &os, int type)
{
const std::vector<std::shared_ptr<TupleValue>> &values = this->values();
int cols = 0;
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end();
iter != end; ++iter)
{
(*iter)->to_string(os);
os << " | ";
//如果多个查询条件,考虑 需要更多考虑
if (cols == selectComareIndex)
{
if (1 == type)
{
sp1 = *iter;
}
else if (2 == type)
{
sp2 = *iter;
}
else if (3 == type)
{
sp3 = *iter;
}
}
cols++;
}
}
void Tuple::tail_table_row_string(std::ostream &os, int type)
{
size_t col2 = 0;
const std::vector<std::shared_ptr<TupleValue>> &values = this->values();
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end();
iter != end; ++iter)
{
//判断是否最后一行
if (col2 == values.size() - 1)
{
(*iter)->to_string(os);
os << std::endl;
}
else
{
(*iter)->to_string(os);
os << " | ";
}
//如果多个查询条件,考虑 需要更多考虑
if (col2 == selectComareIndex)
{
if (1 == type)
{
sp1 = *iter;
}
else if (2 == type)
{
sp2 = *iter;
}
else if (3 == type)
{
sp3 = *iter;
}
}
col2++;
}
}
void TupleSet::order_by_two()
{
if (nullptr == ptr_group_selects || ptr_group_selects->attr_order_num < 0)
{
LOG_INFO("不需要 order by");
return;
}
//步骤01 每个表分开计算
std::vector<RelAttr> attr_order_by1;
std::vector<RelAttr> attr_order_by2;
for (int i = ptr_group_selects->attr_order_num - 1; i >= 0; i--)
{
const std::vector<TupleField> &fields = schema1_.fields();
for (std::vector<TupleField>::const_iterator iter = fields.begin(), end = fields.end();
iter != end; ++iter)
{
if (0 == strcmp(iter->field_name(), ptr_group_selects->attr_order_by[i].attribute_name) &&
0 == strcmp(iter->table_name(), ptr_group_selects->attr_order_by[i].relation_name))
{
attr_order_by1.push_back(ptr_group_selects->attr_order_by[i]);
}
}
}
for (int i = ptr_group_selects->attr_order_num - 1; i >= 0; i--)
{
const std::vector<TupleField> &fields2 = schema2_.fields();
for (std::vector<TupleField>::const_iterator iter2 = fields2.begin(), end = fields2.end();
iter2 != end; ++iter2)
{
if (0 == strcmp(iter2->field_name(), ptr_group_selects->attr_order_by[i].attribute_name) &&
0 == strcmp(iter2->table_name(), ptr_group_selects->attr_order_by[i].relation_name))
{
attr_order_by2.push_back(ptr_group_selects->attr_order_by[i]);
}
}
}
if (attr_order_by1.size() == 0 && attr_order_by2.size() == 0)
{
LOG_INFO(" 失败 ");
return;
}
//步骤2:统计排序关键字 在rows中的位置
std::vector<int> order_index1;
order_index1.clear();
std::vector<int> order_index2;
order_index2.clear();
std::map<int, int> value_key1; //index-key
std::map<int, int> value_key2; //index-key
//key --->index
for (int cols = 0; cols < attr_order_by1.size(); cols++)
{
const std::vector<TupleField> &fields = schema1_.fields();
int index1 = 0;
for (std::vector<TupleField>::const_iterator iter = fields.begin(), end = fields.end();
iter != end; ++iter)
{
if (0 == strcmp(iter->field_name(), attr_order_by1[cols].attribute_name))
{
order_index1.push_back(index1);
value_key1[index1] = cols;
LOG_INFO("题目:排序 >>>>>> cols=%d,index1=%d,name=%s", cols, index1, attr_order_by1[cols].attribute_name);
}
index1++;
}
}
//key --->index
for (int cols = 0; cols < attr_order_by2.size(); cols++)
{
const std::vector<TupleField> &fields = schema2_.fields();
int index2 = 0;
for (std::vector<TupleField>::const_iterator iter = fields.begin(), end = fields.end();
iter != end; ++iter)
{
if (0 == strcmp(iter->field_name(), attr_order_by2[cols].attribute_name))
{
order_index2.push_back(index2);
value_key2[index2] = cols;
LOG_INFO("题目:排序 >>>>>> cols=%d,index2=%d,name=%s", cols, index2, attr_order_by2[cols].attribute_name);
}
index2++;
}
}
//03 开始排序
if (order_index1.size() > 0)
{
LOG_INFO("排序 order-by1 开始排序 order_index=%d", order_index1.size());
auto sortRuleLambda1 = [=](const Tuple &s1, const Tuple &s2) -> bool {
//std::vector<std::shared_ptr<TupleValue>> values_;
std::vector<std::shared_ptr<TupleValue>> sp1;
std::vector<std::shared_ptr<TupleValue>> sp2;
//根据位置--查找value
for (int i = 0; i < order_index1.size(); i++)
{
sp1.push_back(s1.get_pointer(order_index1[i]));
sp2.push_back(s2.get_pointer(order_index1[i]));
}
//多个字段如何比较呀?
for (int op_index = 0; op_index < order_index1.size(); op_index++)
{
int op_comp = 0;
std::shared_ptr<TupleValue> sp_1 = sp1[op_index];
std::shared_ptr<TupleValue> sp_2 = sp2[op_index];
if (sp_1 && sp_2)
{
op_comp = sp_1->compare(*sp_2);
}
//不相等才比较 ,相等下一个
if (op_comp != 0)
{
int index_order = value_key1.at(order_index1[op_index]);
if (CompOp::ORDER_ASC == attr_order_by1[index_order].is_asc)
{
LOG_INFO("排序 order-by ORDER_ASC op_index=%d, order_index=%d,name=%s", op_index, order_index1.size(), attr_order_by1[index_order].attribute_name);
return op_comp < 0; //true
}
else if (CompOp::ORDER_DESC == attr_order_by1[index_order].is_asc)
{
LOG_INFO("排序 order-by ORDER_DESC op_index=%d, order_index=%d,name=%s", op_index, order_index1.size(), attr_order_by1[index_order].attribute_name);
return op_comp > 0; //true
}
else
{
LOG_INFO("排序 order-by err order op_index=%d, order_index=%d,name=%s", op_index, order_index1.size(), attr_order_by1[index_order].attribute_name);
}
}
} ////多个字段如何比较呀?
//为什么std::sort比较函数在参数相等时返回false?
return false;
};
if (tuples1_.size() > 0)
{
std::sort(tuples1_.begin(), tuples1_.end(), sortRuleLambda1);
}
}
//03 开始排序
if (order_index2.size() > 0)
{
LOG_INFO("排序 order-by2 开始排序 order_index=%d", order_index2.size());
auto sortRuleLambda2 = [=](const Tuple &s1, const Tuple &s2) -> bool {
//std::vector<std::shared_ptr<TupleValue>> values_;
std::vector<std::shared_ptr<TupleValue>> sp1;
std::vector<std::shared_ptr<TupleValue>> sp2;
//根据位置--查找value
for (int i = 0; i < order_index2.size(); i++)
{
sp1.push_back(s1.get_pointer(order_index2[i]));
sp2.push_back(s2.get_pointer(order_index2[i]));
}
//多个字段如何比较呀?
for (int op_index = 0; op_index < order_index2.size(); op_index++)
{
int op_comp = 0;
std::shared_ptr<TupleValue> sp_1 = sp1[op_index];
std::shared_ptr<TupleValue> sp_2 = sp2[op_index];
if (sp_1 && sp_2)
{
op_comp = sp_1->compare(*sp_2);
}
//不相等才比较 ,相等下一个
if (op_comp != 0)
{
//int index_order = order_index2.size() - op_index - 1;
int index_order = value_key2.at(order_index2[op_index]);
if (CompOp::ORDER_ASC == attr_order_by2[index_order].is_asc)
{
LOG_INFO("排序 order-by ORDER_ASC op_index=%d, order_index=%d,name=%s", op_index, order_index2.size(), attr_order_by2[index_order].attribute_name);
return op_comp < 0; //true
}
else if (CompOp::ORDER_DESC == attr_order_by2[index_order].is_asc)
{
LOG_INFO("排序 order-by ORDER_DESC op_index=%d, order_index=%d,name=%s", op_index, order_index2.size(), attr_order_by2[index_order].attribute_name);
return op_comp > 0; //true
}
else
{
LOG_INFO("排序 order-by err order op_index=%d, order_index=%d,name=%s", op_index, order_index2.size(), attr_order_by2[index_order].attribute_name);
}
}
} ////多个字段如何比较呀?
//为什么std::sort比较函数在参数相等时返回false?
return false;
};
if (tuples2_.size() > 0)
{
std::sort(tuples2_.begin(), tuples2_.end(), sortRuleLambda2);
}
}
}
void TupleSet::join_table_for_order_by(const Tuple &item_left, const Tuple &item_right)
{
Tuple merge;
const std::vector<std::shared_ptr<TupleValue>> &values_left = item_left.values();
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values_left.begin(), end = values_left.end();
iter != end; ++iter)
{
merge.add(*iter);
}
const std::vector<std::shared_ptr<TupleValue>> &values_right = item_right.values();
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values_right.begin(), end = values_right.end();
iter != end; ++iter)
{
merge.add(*iter);
}
join_tuples.push_back(std::move(merge));
}
void TupleSet::join_table_for_group_by(const Tuple &item_left, const Tuple &item_right)
{
//对Tuple深度拷贝,不能=
Tuple merge;
const std::vector<std::shared_ptr<TupleValue>> &values_left = item_left.values();
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values_left.begin(), end = values_left.end();
iter != end; ++iter)
{
merge.add(*iter);
}
const std::vector<std::shared_ptr<TupleValue>> &values_right = item_right.values();
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values_right.begin(), end = values_right.end();
iter != end; ++iter)
{
merge.add(*iter);
}
join_tuples_group.push_back(std::move(merge));
}
void TupleSet::sort_table_for_order_by()
{
//依赖数据结构:
//std::vector<Tuple> join_tuples; 数据
// Selects* ptr_group_selects =nullptr; 排序条件
// TupleSchema schema_; 有可能是old
//if (old_schema.get_size() > 0)
//排序 order-by
int order_by_num = -1;
RelAttr *ptr_attr_order_by = nullptr;
if (ptr_group_selects && ptr_group_selects->attr_order_num > 0)
{
order_by_num = ptr_group_selects->attr_order_num;
ptr_attr_order_by = ptr_group_selects->attr_order_by;
}
if (order_by_num > 0)
{
//order by
//std::vector<Tuple> tuples_; //一个表头信息
//TupleSchema schema_; //一个表内容信息
//SELECT * FROM T_ORDER_BY ORDER BY ID, SCORE, NAME;
//key ---index
//index ---key
std::vector<int> key_value;
std::map<int, int> value_key;
key_value.clear();
value_key.clear();
for (int i = ptr_group_selects->attr_order_num - 1; i >= 0; i--)
{
const std::vector<TupleField> &fields = schema_.fields(); //决定了value 顺序
int index = 0;
for (std::vector<TupleField>::const_iterator iter = fields.begin(), end = fields.end();
iter != end; ++iter)
{
if (ptr_group_selects->attr_order_by[i].relation_name)
{
if (0 == strcmp(iter->field_name(), ptr_group_selects->attr_order_by[i].attribute_name) &&
0 == strcmp(iter->table_name(), ptr_group_selects->attr_order_by[i].relation_name))
{
key_value.push_back(index);
value_key[index] = i;
LOG_INFO(" >>>>>order-by index=%d,table_name=%s,attribute_name=%s", index, iter->table_name(), iter->field_name());
break;
}
}
else
{
if (0 == strcmp(iter->field_name(), ptr_group_selects->attr_order_by[i].attribute_name))
{
key_value.push_back(index);
value_key[index] = i;
LOG_INFO(" >>>>>order-by index=%d,table_name=%s,attribute_name=%s", index, iter->table_name(), iter->field_name());
break;
}
}
index++;
}
}
if (order_by_num != key_value.size())
{
LOG_INFO("排序 order-by 失败 order_by_num != order_index.size()");
return;
}
auto sortRuleLambda = [=](const Tuple &s1, const Tuple &s2) -> bool {
std::vector<std::shared_ptr<TupleValue>> sp1;
std::vector<std::shared_ptr<TupleValue>> sp2;
//key -value
//SELECT * FROM T_ORDER_BY ORDER BY ID, SCORE, NAME;
// 排序数据
for (int i = 0; i < key_value.size(); i++)
{
sp1.push_back(s1.get_pointer(key_value[i]));
sp2.push_back(s2.get_pointer(key_value[i]));
//字段:ID, SCORE, NAME;
//字段之间顺序
//key_value[i]--对应rows的位置
//rows 对应的值
// i
//i -value---key-id
}
//字段之间顺序
for (int op_index = 0; op_index < key_value.size(); op_index++)
{
int op_comp = 0;
std::shared_ptr<TupleValue> sp_1 = sp1[op_index];
std::shared_ptr<TupleValue> sp_2 = sp2[op_index];
if (sp_1 && sp_2)
{
op_comp = sp_1->compare(*sp_2);
}
//不相等才比较 ,相等下一个
if (op_comp != 0)
{
int index_order = value_key.at(key_value[op_index]);
if (CompOp::ORDER_ASC == ptr_attr_order_by[index_order].is_asc)
{
LOG_INFO("排序 order-by ORDER_ASC value=%d, key=%d,name=%s", key_value[op_index], index_order, ptr_attr_order_by[index_order].attribute_name);
return op_comp < 0; //true
}
else if (CompOp::ORDER_DESC == ptr_attr_order_by[index_order].is_asc)
{
LOG_INFO("排序 order-by ORDER_DESC value=%d, key=%d,name=%s", key_value[op_index], index_order, ptr_attr_order_by[index_order].attribute_name);
return op_comp > 0; //true
}
else
{
LOG_INFO("排序 order-by err..... value=%d, key=%d,name=%s", key_value[op_index], index_order, ptr_attr_order_by[index_order].attribute_name);
}
}
} ////多个字段如何比较呀?
//为什么std::sort比较函数在参数相等时返回false?
return false;
};
if (join_tuples.size() > 0)
{
std::sort(join_tuples.begin(), join_tuples.end(), sortRuleLambda);
}
}
}
void TupleSet::join_tuples_to_print(std::ostream &os)
{
os.clear();
for (const Tuple &item : join_tuples)
{
//第n-1列
const std::vector<std::shared_ptr<TupleValue>> &values = item.values();
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = --values.end();
iter != end; ++iter)
{
(*iter)->to_string(os);
os << " | ";
}
//最后一列
values.back()->to_string(os);
os << std::endl;
}
}
void TupleSet::sort_table_for_group_by(std::vector<int> &key_value, std::map<int, int> &value_key)
{
//依赖数据结构:
// std::vector<Tuple> tuples_; //一个表头信息
// TupleSchema schema_; //一个表内容信息
// Selects* ptr_group_selects =nullptr; 排序条件
//排序 order-by
int group_by_num = -1;
RelAttr *ptr_attr_group_by = nullptr;
if (ptr_group_selects && ptr_group_selects->attr_group_num > 0)
{
group_by_num = ptr_group_selects->attr_group_num;
ptr_attr_group_by = ptr_group_selects->attr_group_by;
}
if (group_by_num > 0)
{
//SELECT * FROM T_ORDER_BY ORDER BY ID, SCORE, NAME;
//SELECT ID, AVG(SCORE) FROM T_GROUP_BY GROUP BY ID;
//key ---index
//index ---key
//std::vector<int> key_value;
//std::map<int, int> value_key;
key_value.clear();
value_key.clear();
for (int i = ptr_group_selects->attr_group_num - 1; i >= 0; i--)
{
const std::vector<TupleField> &fields = schema_.fields(); //决定了value 顺序
int index = 0;
for (std::vector<TupleField>::const_iterator iter = fields.begin(), end = fields.end();
iter != end; ++iter)
{
//有表名
if (ptr_group_selects->attr_group_by[i].relation_name)
{
if (0 == strcmp(iter->field_name(), ptr_group_selects->attr_group_by[i].attribute_name) &&
0 == strcmp(iter->table_name(), ptr_group_selects->attr_group_by[i].relation_name))
{
key_value.push_back(index);
value_key[index] = i;
LOG_INFO(" >>>>>order-by index=%d,table_name=%s,attribute_name=%s", index, iter->table_name(), iter->field_name());
break;
}
}
else
{ //无表名
if (0 == strcmp(iter->field_name(), ptr_group_selects->attr_group_by[i].attribute_name))
{
key_value.push_back(index);
value_key[index] = i;
LOG_INFO(" >>>>>order-by index=%d,table_name=%s,attribute_name=%s", index, iter->table_name(), iter->field_name());
break;
}
}
index++;
}
}
if (group_by_num != key_value.size())
{
LOG_INFO("排序 order-by 失败 order_by_num != order_index.size()");
return;
}
auto sortRuleLambda = [=](const Tuple &s1, const Tuple &s2) -> bool {
std::vector<std::shared_ptr<TupleValue>> sp1;
std::vector<std::shared_ptr<TupleValue>> sp2;
//key -value
//SELECT * FROM T_ORDER_BY ORDER BY ID, SCORE, NAME;
// 排序数据
for (int i = 0; i < key_value.size(); i++)
{
sp1.push_back(s1.get_pointer(key_value[i]));
sp2.push_back(s2.get_pointer(key_value[i]));
//字段:ID, SCORE, NAME;
//字段之间顺序
//key_value[i]--对应rows的位置
//rows 对应的值
// i
//i -value---key-id
}
//字段之间顺序
for (int op_index = 0; op_index < key_value.size(); op_index++)
{
int op_comp = 0;
std::shared_ptr<TupleValue> sp_1 = sp1[op_index];
std::shared_ptr<TupleValue> sp_2 = sp2[op_index];
if (sp_1 && sp_2)
{
op_comp = sp_1->compare(*sp_2);
}
//不相等才比较 ,相等下一个
if (op_comp != 0)
{
int index_order = value_key.at(key_value[op_index]);
if (CompOp::ORDER_ASC == ptr_attr_group_by[index_order].is_asc)
{
LOG_INFO("排序 order-by ORDER_ASC value=%d, key=%d,name=%s", key_value[op_index], index_order, ptr_attr_group_by[index_order].attribute_name);
return op_comp < 0; //true
}
else if (CompOp::ORDER_DESC == ptr_attr_group_by[index_order].is_asc)
{
LOG_INFO("排序 order-by ORDER_DESC value=%d, key=%d,name=%s", key_value[op_index], index_order, ptr_attr_group_by[index_order].attribute_name);
return op_comp > 0; //true
}
else
{
LOG_INFO("排序 order-by err..... value=%d, key=%d,name=%s", key_value[op_index], index_order, ptr_attr_group_by[index_order].attribute_name);
}
}
} ////多个字段如何比较呀?
//为什么std::sort比较函数在参数相等时返回false?
return false;
};
if (tuples_.size() > 0)
{
std::sort(tuples_.begin(), tuples_.end(), sortRuleLambda);
}
}
}
void TupleSet::sort_two_table_for_group_by(std::vector<int> &key_value, std::map<int, int> &value_key)
{
//依赖数据结构:
// std::vector<Tuple> tuples_; //一个表头信息
// TupleSchema schema_; //一个表内容信息
// Selects* ptr_group_selects =nullptr; 排序条件
//排序 order-by
LOG_INFO("sort_two_table_for_group_by begin");
int group_by_num = -1;
RelAttr *ptr_attr_group_by = nullptr;
if (ptr_group_selects && ptr_group_selects->attr_group_num > 0)
{
group_by_num = ptr_group_selects->attr_group_num;
ptr_attr_group_by = ptr_group_selects->attr_group_by;
}
if (group_by_num > 0)
{
//SELECT * FROM T_ORDER_BY ORDER BY ID, SCORE, NAME;
//SELECT ID, AVG(SCORE) FROM T_GROUP_BY GROUP BY ID;
//key ---index
//index ---key
//std::vector<int> key_value;
//std::map<int, int> value_key;
key_value.clear();
value_key.clear();
// schema_ 这是2个表的 汇总,注意观察是否正确
for (int i = ptr_group_selects->attr_group_num - 1; i >= 0; i--)
{
//const std::vector<TupleField> &fields = schema_.fields(); //决定了value 顺序
const std::vector<TupleField> &fields = old_schema.fields(); //决定了value 顺序
int index = 0;
for (std::vector<TupleField>::const_iterator iter = fields.begin(), end = fields.end();
iter != end; ++iter)
{
//有表名
if (ptr_group_selects->attr_group_by[i].relation_name)
{
if (0 == strcmp(iter->field_name(), ptr_group_selects->attr_group_by[i].attribute_name) &&
0 == strcmp(iter->table_name(), ptr_group_selects->attr_group_by[i].relation_name))
{
key_value.push_back(index);
value_key[index] = i;
LOG_INFO(" >>>>>order-by index=%d,table_name=%s,attribute_name=%s", index, iter->table_name(), iter->field_name());
break;
}
}
else
{ //无表名
if (0 == strcmp(iter->field_name(), ptr_group_selects->attr_group_by[i].attribute_name))
{
key_value.push_back(index);
value_key[index] = i;
LOG_INFO(" >>>>>order-by index=%d,table_name=%s,attribute_name=%s", index, iter->table_name(), iter->field_name());
break;
}
}
index++;
}
}
if (group_by_num != key_value.size())
{
LOG_INFO("sort_two_table_for_group_by 失败 order_by_num != order_index.size()");
return;
}
auto sortRuleLambda = [=](const Tuple &s1, const Tuple &s2) -> bool {
std::vector<std::shared_ptr<TupleValue>> sp1;
std::vector<std::shared_ptr<TupleValue>> sp2;
//key -value
//SELECT * FROM T_ORDER_BY ORDER BY ID, SCORE, NAME;
// 排序数据
for (int i = 0; i < key_value.size(); i++)
{
sp1.push_back(s1.get_pointer(key_value[i]));
sp2.push_back(s2.get_pointer(key_value[i]));
//字段:ID, SCORE, NAME;
//字段之间顺序
//key_value[i]--对应rows的位置
//rows 对应的值
// i
//i -value---key-id
}
//字段之间顺序
for (int op_index = 0; op_index < key_value.size(); op_index++)
{
int op_comp = 0;
std::shared_ptr<TupleValue> sp_1 = sp1[op_index];
std::shared_ptr<TupleValue> sp_2 = sp2[op_index];
if (sp_1 && sp_2)
{
op_comp = sp_1->compare(*sp_2);
}
//不相等才比较 ,相等下一个
if (op_comp != 0)
{
int index_order = value_key.at(key_value[op_index]);
if (CompOp::ORDER_ASC == ptr_attr_group_by[index_order].is_asc)
{
LOG_INFO("排序 order-by ORDER_ASC value=%d, key=%d,name=%s", key_value[op_index], index_order, ptr_attr_group_by[index_order].attribute_name);
return op_comp < 0; //true
}
else if (CompOp::ORDER_DESC == ptr_attr_group_by[index_order].is_asc)
{
LOG_INFO("排序 order-by ORDER_DESC value=%d, key=%d,name=%s", key_value[op_index], index_order, ptr_attr_group_by[index_order].attribute_name);
return op_comp > 0; //true
}
else
{
LOG_INFO("排序 order-by err..... value=%d, key=%d,name=%s", key_value[op_index], index_order, ptr_attr_group_by[index_order].attribute_name);
}
}
} ////多个字段如何比较呀?
//为什么std::sort比较函数在参数相等时返回false?
return false;
};
if (join_tuples_group.size() > 0)
{
std::sort(join_tuples_group.begin(), join_tuples_group.end(), sortRuleLambda);
}
}
}
//排序 分组 统计 -汇总--返回
//参数写死,新增一个参数要新增一个函数.
bool TupleSet::print_group_by(std::ostream &os)
{
//步骤:单表排序
std::vector<int> key_value;
std::map<int, int> value_key;
sort_table_for_group_by(key_value, value_key);
if (key_value.size() <= 0 || tuples_.size() <= 0)
{
LOG_INFO("分组 失败,无记录");
return false;
}
//步骤:相同的为一组
//const int cols = schema_.size();
std::vector<std::shared_ptr<TupleValue>> sp_last; //分组条件
std::vector<std::shared_ptr<TupleValue>> sp_cur; //分组条件
std::vector<Tuple> group_tuples; //对原始数据tuples_分成不同的组
std::vector<vector<string>> output; //汇总分组统计结果
//初始化 默认第一个行记录
for (int i = 0; i < key_value.size(); i++)
{
sp_last.push_back(tuples_[0].get_pointer(key_value[i]));
}
//rows
for (const Tuple &item : tuples_)
{
//cols
sp_cur.clear();
//const std::vector<std::shared_ptr<TupleValue>> &values = item.values();
for (int i = 0; i < key_value.size(); i++)
{
sp_cur.push_back(item.get_pointer(key_value[i]));
}
bool is_group = true;
for (int i = 0; i < key_value.size(); i++)
{
if (sp_last[i] && sp_cur[i] && 0 == sp_last[i]->compare(*sp_cur[i]))
{
//符合预期
}
else
{
is_group = false;
}
}
//相同就汇总
if (true == is_group)
{
LOG_INFO("同一个分组 ....add");
//constructor of tuple is not supported
//emplace_back
//深度拷贝一行数据
Tuple temp;
const std::vector<std::shared_ptr<TupleValue>> &values_copy = item.values();
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values_copy.begin(), end = values_copy.end();
iter != end; ++iter)
{
temp.add(*iter);
}
group_tuples.emplace_back(std::move(temp));
}
else
{
LOG_INFO("新的分组 .............");
//不相同就统计
//统计
count_group_data(group_tuples, output);
//新的一组
group_tuples.clear();
group_tuples.resize(0);
Tuple temp;
const std::vector<std::shared_ptr<TupleValue>> &values_copy = item.values();
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values_copy.begin(), end = values_copy.end();
iter != end; ++iter)
{
temp.add(*iter);
}
group_tuples.emplace_back(std::move(temp)); //
//新的分组条件
sp_last = sp_cur;
}
} //end data
//最后一个分组
if (group_tuples.size() > 0)
{
count_group_data(group_tuples, output);
}
//步骤:输出
if (output.size() == 0)
{
LOG_INFO(" 题目 分组group-by 失败,没有任何记录");
}
for (int rows = 0; rows < output.size(); rows++)
{
int cols = output[rows].size() - 1;
for (int i = 0; i <= cols; i++)
{
//最后一行
if (i == cols)
{
os << output[rows][i];
os << std::endl;
}
else
{
os << output[rows][i];
os << " | ";
}
}
}
return true;
}
//统计
void TupleSet::count_group_data(std::vector<Tuple> &group_tuples, std::vector<vector<string>> &output)
{
if (group_tuples.size() == 0)
{
LOG_INFO("group_tuples is 0");
}
LOG_INFO("count_group_data group_tuples.size=%d ", group_tuples.size());
vector<string> total; //根据schema产生一行记录
const std::vector<TupleField> &fields = schema_.fields();
int cols = 0;
//遍历n个元素.
for (std::vector<TupleField>::const_iterator iter = fields.begin(), end = fields.end();
iter != end; ++iter)
{
FunctionType window_function = iter->get_function_type();
if (FunctionType::FUN_COUNT_ALL_ALl == window_function || FunctionType::FUN_COUNT_ALL == window_function || FunctionType::FUN_COUNT == window_function)
{
//rows
std::set<std::shared_ptr<TupleValue>> count;
count.clear();
for (const Tuple &item : group_tuples)
{
const std::vector<std::shared_ptr<TupleValue>> &values = item.values();
int colIndex = 0;
//cols
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end();
iter != end; ++iter)
{
//(*iter)->to_string(os);
if (colIndex == cols)
{
//std::shared_ptr<TupleValue> temp = *iter;
count.insert(*iter);
break;
}
colIndex++;
}
}
std::stringstream ss;
ss << count.size();
total.push_back(ss.str());
}
else if (FunctionType::FUN_MAX == window_function)
{
std::shared_ptr<TupleValue> maxValue;
//rows
for (const Tuple &item : group_tuples)
{
const std::vector<std::shared_ptr<TupleValue>> &values = item.values();
if (0 == values.size())
{
continue;
}
int colIndex = 0;
//cols
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end();
iter != end; ++iter)
{
//(*iter)->to_string(os);
if (colIndex == cols)
{
std::shared_ptr<TupleValue> temp = *iter;
if (nullptr == maxValue)
{
maxValue = temp;
}
else
{
if (maxValue->compare(*temp) < 0)
{
maxValue = temp;
}
}
break;
}
colIndex++;
}
}
std::stringstream ss;
maxValue->to_string(ss);
total.push_back(ss.str());
}
else if (FunctionType::FUN_MIN == window_function)
{
std::shared_ptr<TupleValue> minValue;
for (const Tuple &item : group_tuples)
{
int colIndex = 0;
//列
const std::vector<std::shared_ptr<TupleValue>> &values = item.values();
if (0 == values.size())
{
continue;
}
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end();
iter != end; ++iter)
{
if (colIndex == cols)
{
std::shared_ptr<TupleValue> temp = *iter;
{
if (nullptr == minValue)
{
minValue = *iter;
}
else
{
std::shared_ptr<TupleValue> temp = *iter;
if (minValue->compare(*temp) > 0)
{
minValue = temp;
}
}
}
break; //get
}
colIndex++;
}
} //end
std::stringstream ss;
minValue->to_string(ss);
total.push_back(ss.str());
}
else if (FunctionType::FUN_AVG == window_function)
{
std::shared_ptr<TupleValue> sumValue;
int count = 0;
bool exits_null_value = false;
for (const Tuple &item : group_tuples)
{
int colIndex = 0;
bool null_able = true;
//第n列
const std::vector<std::shared_ptr<TupleValue>> &values = item.values();
if (0 == values.size())
{
continue;
}
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end();
iter != end; ++iter)
{
//(*iter)->to_string(os);
if (colIndex == cols)
{
std::shared_ptr<TupleValue> temp = *iter;
if (AttrType::NULLVALUES == temp->get_type())
{
//不处理
null_able = false;
exits_null_value = true;
}
else
{
if (nullptr == sumValue)
{
sumValue = temp;
}
else
{
sumValue->add_value(*temp);
}
}
break; //get
}
colIndex++;
}
if (true == null_able)
{
count++;
}
} //end
//防溢出求平均算法
if (0 == count)
{
if (exits_null_value == true)
{
total.push_back("NULL");
}
}
std::stringstream ss;
sumValue->to_avg(count, ss);
total.push_back(ss.str());
}
else if (FunctionType::FUN_NO == window_function)
{
LOG_INFO(">>>>>>FunctionType::FUN_NO =%s ", iter->field_name());
std::shared_ptr<TupleValue> itemValue;
//只读取其中的一行
if (group_tuples.size() > 0)
{
//第n列
int colIndex = 0;
const std::vector<std::shared_ptr<TupleValue>> &values = group_tuples[0].values();
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end();
iter != end; ++iter)
{
//(*iter)->to_string(os);
if (colIndex == cols)
{
itemValue = *iter;
break; //get
}
colIndex++;
}
std::stringstream ss;
itemValue->to_string(ss);
total.push_back(ss.str());
}
}
else
{
LOG_INFO(">>>>>>errrrrrrrrrrrr=%s ", iter->field_name());
}
cols++;
} //const std::vector<TupleField> &fields = schema_.fields();
output.push_back(total);
}
//代码重复:前期设计不合适导致,2个一样的逻辑
//需要优化
void TupleSet::count_two_table_group_data(std::vector<Tuple> &group_tuples, std::vector<vector<string>> &output)
{
if (group_tuples.size() == 0)
{
LOG_INFO("count_two_table_group_data is 0");
}
LOG_INFO("count_two_table_group_data group_tuples.size=%d ", group_tuples.size());
vector<string> total; //根据schema产生一行记录
const std::vector<TupleField> &fields = old_schema.fields();
int cols = 0;
//遍历n个元素.
for (std::vector<TupleField>::const_iterator field_iter = fields.begin(), end = fields.end();
field_iter != end; ++field_iter)
{
if (false == field_iter->visible())
{
LOG_INFO(">>>>> group by 不可见字段 index =%d,name =%s ", cols, field_iter->field_name());
cols++;
continue;
}
FunctionType window_function = field_iter->get_function_type();
if (FunctionType::FUN_COUNT_ALL_ALl == window_function || FunctionType::FUN_COUNT_ALL == window_function || FunctionType::FUN_COUNT == window_function)
{
//rows
std::set<std::shared_ptr<TupleValue>> count;
count.clear();
for (const Tuple &item : group_tuples)
{
const std::vector<std::shared_ptr<TupleValue>> &values = item.values();
int colIndex = 0;
//cols
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end();
iter != end; ++iter)
{
//(*iter)->to_string(os);
if (colIndex == cols)
{
//std::shared_ptr<TupleValue> temp = *iter;
count.insert(*iter);
break;
}
colIndex++;
}
}
std::stringstream ss;
ss << count.size();
total.push_back(ss.str());
LOG_INFO(">>>>> group by count index =%d,name =%s,value =%d ", cols, field_iter->field_name(), count.size());
}
else if (FunctionType::FUN_MAX == window_function)
{
std::shared_ptr<TupleValue> maxValue;
//rows
for (const Tuple &item : group_tuples)
{
const std::vector<std::shared_ptr<TupleValue>> &values = item.values();
if (0 == values.size())
{
continue;
}
int colIndex = 0;
//cols
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end();
iter != end; ++iter)
{
//(*iter)->to_string(os);
if (colIndex == cols)
{
std::shared_ptr<TupleValue> temp = *iter;
if (nullptr == maxValue)
{
maxValue = temp;
}
else
{
if (maxValue->compare(*temp) < 0)
{
maxValue = temp;
}
}
break;
}
colIndex++;
}
}
std::stringstream ss;
maxValue->to_string(ss);
total.push_back(ss.str());
LOG_INFO(">>>>> group by max index =%d,name =%s,value =%s ", cols, field_iter->field_name(), maxValue->print_string().c_str());
}
else if (FunctionType::FUN_MIN == window_function)
{
std::shared_ptr<TupleValue> minValue;
for (const Tuple &item : group_tuples)
{
int colIndex = 0;
//列
const std::vector<std::shared_ptr<TupleValue>> &values = item.values();
if (0 == values.size())
{
continue;
}
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end();
iter != end; ++iter)
{
if (colIndex == cols)
{
std::shared_ptr<TupleValue> temp = *iter;
{
if (nullptr == minValue)
{
minValue = *iter;
}
else
{
std::shared_ptr<TupleValue> temp = *iter;
if (minValue->compare(*temp) > 0)
{
minValue = temp;
}
}
}
break; //get
}
colIndex++;
}
} //end
std::stringstream ss;
minValue->to_string(ss);
total.push_back(ss.str());
LOG_INFO(">>>>> group by min index =%d,name =%s,value =%s ", cols, field_iter->field_name(), minValue->print_string().c_str());
}
else if (FunctionType::FUN_AVG == window_function)
{
std::shared_ptr<TupleValue> sumValue;
int count = 0;
for (const Tuple &item : group_tuples)
{
int colIndex = 0;
//第n列
const std::vector<std::shared_ptr<TupleValue>> &values = item.values();
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end();
iter != end; ++iter)
{
//(*iter)->to_string(os);
if (colIndex == cols)
{
std::shared_ptr<TupleValue> temp = *iter;
if (nullptr == sumValue)
{
sumValue = temp;
}
else
{
sumValue->add_value(*temp);
}
break; //get
}
colIndex++;
}
count++;
} //end
//防溢出求平均算法
LOG_INFO(">>>>> group by >>>>>>>>>>>>>>>>>>>>>>> ", count);
if (0 == count)
{
total.push_back("NULL");
}
else
{
std::stringstream ss;
sumValue->to_avg(count, ss);
total.push_back(ss.str());
LOG_INFO(">>>>> group by avg index =%d,name =%s ", cols, field_iter->field_name());
}
}
else if (FunctionType::FUN_NO == window_function)
{
LOG_INFO(">>>>>> FunctionType::FUN_NO =%s ", field_iter->field_name());
std::shared_ptr<TupleValue> itemValue;
//只读取其中的一行
if (group_tuples.size() > 0)
{
//第n列
int colIndex = 0;
const std::vector<std::shared_ptr<TupleValue>> &values = group_tuples[0].values();
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end();
iter != end; ++iter)
{
//(*iter)->to_string(os);
if (colIndex == cols)
{
itemValue = *iter;
// break; //get
}
colIndex++;
}
std::stringstream ss;
itemValue->to_string(ss);
total.push_back(ss.str());
LOG_INFO(">>>>> group by index =%d,name =%s,value =%s ", cols, field_iter->field_name(), itemValue->print_string().c_str());
}
}
else
{
LOG_INFO(">>>>>>errrrrrrrrrrrr=%s ", field_iter->field_name());
}
cols++;
} //const std::vector<TupleField> &fields = schema_.fields();
output.push_back(total);
}
//排序 分组 统计 -汇总--返回
//参数写死,新增一个参数要新增一个函数.
bool TupleSet::print_two_table_group_by(std::ostream &os)
{
//步骤:单表排序
std::vector<int> key_value;
std::map<int, int> value_key;
sort_two_table_for_group_by(key_value, value_key);
if (key_value.size() <= 0 || join_tuples_group.size() <= 0)
{
LOG_INFO("分组 失败,无记录");
return false;
}
//步骤:相同的为一组
//const int cols = schema_.size();
std::vector<std::shared_ptr<TupleValue>> sp_last; //分组条件
std::vector<std::shared_ptr<TupleValue>> sp_cur; //分组条件
std::vector<Tuple> onece_group_tuples; //对原始数据tuples_分成不同的组
std::vector<vector<string>> output; //汇总分组统计结果
output.clear();
onece_group_tuples.clear();
//初始化 默认第一个行记录
//std::vector<Tuple> join_tuples_group; //sql:1 笛卡尔积 2 过滤 3 排序 4 分组 5 显示。
//tuples_
for (int i = 0; i < key_value.size(); i++)
{
sp_last.push_back(join_tuples_group[0].get_pointer(key_value[i]));
}
//rows
for (const Tuple &item : join_tuples_group)
{
//cols
sp_cur.clear();
//const std::vector<std::shared_ptr<TupleValue>> &values = item.values();
for (int i = 0; i < key_value.size(); i++)
{
sp_cur.push_back(item.get_pointer(key_value[i]));
}
bool is_group = true;
for (int i = 0; i < key_value.size(); i++)
{
if (sp_last[i] && sp_cur[i] && 0 == sp_last[i]->compare(*sp_cur[i]))
{
//符合预期
}
else
{
is_group = false;
}
}
//相同就汇总
if (true == is_group)
{
LOG_INFO("同一个分组 ....add");
//constructor of tuple is not supported
//emplace_back
//深度拷贝一行数据
Tuple temp;
const std::vector<std::shared_ptr<TupleValue>> &values_copy = item.values();
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values_copy.begin(), end = values_copy.end();
iter != end; ++iter)
{
temp.add(*iter);
}
onece_group_tuples.push_back(std::move(temp));
}
else
{
LOG_INFO("新的分组 .............");
//不相同就统计
//统计
//count_group_data(group_tuples, output);
count_two_table_group_data(onece_group_tuples, output);
//新的一组
onece_group_tuples.clear();
onece_group_tuples.resize(0);
onece_group_tuples.reserve(0);
Tuple temp;
const std::vector<std::shared_ptr<TupleValue>> &values_copy = item.values();
for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values_copy.begin(), end = values_copy.end();
iter != end; ++iter)
{
temp.add(*iter);
}
onece_group_tuples.push_back(std::move(temp)); //
//新的分组条件
sp_last = sp_cur;
}
} //end data
//最后一个分组
if (onece_group_tuples.size() > 0)
{
count_two_table_group_data(onece_group_tuples, output);
}
//步骤:输出
if (output.size() == 0)
{
LOG_INFO(" 题目 分组group-by 失败,没有任何记录");
}
for (int rows = 0; rows < output.size(); rows++)
{
int cols = output[rows].size() - 1;
for (int i = 0; i <= cols; i++)
{
//最后一行
if (i == cols)
{
os << output[rows][i];
os << std::endl;
}
else
{
os << output[rows][i];
os << " | ";
}
}
}
return true;
} | 91,661 | 33,436 |
/**************************************************************
*
* 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.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#include <svx/sdr/contact/viewobjectcontactofgroup.hxx>
#include <svx/sdr/contact/displayinfo.hxx>
#include <svx/sdr/contact/objectcontact.hxx>
#include <basegfx/numeric/ftools.hxx>
#include <drawinglayer/primitive2d/groupprimitive2d.hxx>
#include <basegfx/tools/canvastools.hxx>
#include <svx/sdr/contact/viewcontact.hxx>
//////////////////////////////////////////////////////////////////////////////
using namespace com::sun::star;
//////////////////////////////////////////////////////////////////////////////
namespace sdr
{
namespace contact
{
ViewObjectContactOfGroup::ViewObjectContactOfGroup(ObjectContact& rObjectContact, ViewContact& rViewContact)
: ViewObjectContactOfSdrObj(rObjectContact, rViewContact)
{
}
ViewObjectContactOfGroup::~ViewObjectContactOfGroup()
{
}
drawinglayer::primitive2d::Primitive2DSequence ViewObjectContactOfGroup::getPrimitive2DSequenceHierarchy(DisplayInfo& rDisplayInfo) const
{
drawinglayer::primitive2d::Primitive2DSequence xRetval;
// check model-view visibility
if(isPrimitiveVisible(rDisplayInfo))
{
const sal_uInt32 nSubHierarchyCount(GetViewContact().GetObjectCount());
if(nSubHierarchyCount)
{
const sal_Bool bDoGhostedDisplaying(
GetObjectContact().DoVisualizeEnteredGroup()
&& !GetObjectContact().isOutputToPrinter()
&& GetObjectContact().getActiveViewContact() == &GetViewContact());
if(bDoGhostedDisplaying)
{
rDisplayInfo.ClearGhostedDrawMode();
}
// create object hierarchy
xRetval = getPrimitive2DSequenceSubHierarchy(rDisplayInfo);
if(xRetval.hasElements())
{
// get ranges
const drawinglayer::geometry::ViewInformation2D& rViewInformation2D(GetObjectContact().getViewInformation2D());
const ::basegfx::B2DRange aObjectRange(drawinglayer::primitive2d::getB2DRangeFromPrimitive2DSequence(xRetval, rViewInformation2D));
const basegfx::B2DRange aViewRange(rViewInformation2D.getViewport());
// check geometrical visibility
if(!aViewRange.isEmpty() && !aViewRange.overlaps(aObjectRange))
{
// not visible, release
xRetval.realloc(0);
}
}
if(bDoGhostedDisplaying)
{
rDisplayInfo.SetGhostedDrawMode();
}
}
else
{
// draw replacement object for group. This will use ViewContactOfGroup::createViewIndependentPrimitive2DSequence
// which creates the replacement primitives for an empty group
xRetval = ViewObjectContactOfSdrObj::getPrimitive2DSequenceHierarchy(rDisplayInfo);
}
}
return xRetval;
}
} // end of namespace contact
} // end of namespace sdr
//////////////////////////////////////////////////////////////////////////////
// eof
| 3,777 | 1,288 |
//Approach #1 Brute Force [Accepted]
//Runtime: 24 ms, faster than 33.17% of C++ online submissions for Maximal Square.
//Memory Usage: 8.2 MB, less than 100.00% of C++ online submissions for Maximal Square.
//time: O((mn)^2), space: O(1)
class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
int m = matrix.size();
if(m == 0) return 0;
int n = matrix[0].size();
int maxslen = 0;
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(matrix[i][j] == '0') continue;
int slen = 1;
bool valid = true;
while(slen + i < m && slen + j < n && valid){
for(int k = j; k <= j + slen; k++){
//i+slen: examine the (possible) last row of the square
if(matrix[i+slen][k] != '1'){
valid = false;
break;
}
}
for(int k = i; k <= i + slen; k++){
//j+slen: examine the (possible) last col of the square
if(matrix[k][j+slen] != '1'){
valid = false;
break;
}
}
if(valid){
slen++;
}
}
maxslen = max(maxslen, slen);
}
}
return maxslen * maxslen;
}
};
//Approach #2 (Dynamic Programming) [Accepted]
//Runtime: 24 ms, faster than 33.17% of C++ online submissions for Maximal Square.
//Memory Usage: 8.7 MB, less than 100.00% of C++ online submissions for Maximal Square.
//time: O(mn), space: O(mn)
class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
int m = matrix.size();
if(m == 0) return 0;
int n = matrix[0].size();
int maxslen = 0;
vector<vector<int>> dp(m+1, vector(n+1, 0));
for(int i = 1; i <= m; i++){
for(int j = 1; j <= n; j++){
if(matrix[i-1][j-1] == '0') continue;
//check top, left and top-left
dp[i][j] = min({dp[i-1][j], dp[i][j-1], dp[i-1][j-1]}) + 1;
maxslen = max(maxslen, dp[i][j]);
}
}
return maxslen * maxslen;
}
};
//DP, O(n) space
//Runtime: 20 ms, faster than 77.64% of C++ online submissions for Maximal Square.
//Memory Usage: 8.6 MB, less than 100.00% of C++ online submissions for Maximal Square.
//time: O(mn), space: O(n)
class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
int m = matrix.size();
if(m == 0) return 0;
int n = matrix[0].size();
int maxslen = 0;
vector<int> dp(n+1, 0);
int prev = 0; //top-left
for(int i = 1; i <= m; i++){
for(int j = 1; j <= n; j++){
/*
dp[j] of previous row
it will be used as 'prev' in next j,
at that time, it means the dp value of top-left corner
*/
int tmp = dp[j];
if(matrix[i-1][j-1] == '0'){
dp[j] = 0;
}else{
//check top, left and top-left
dp[j] = min({dp[j], dp[j-1], prev}) + 1;
maxslen = max(maxslen, dp[j]);
}
prev = tmp;
}
}
return maxslen * maxslen;
}
};
| 3,680 | 1,205 |
#include "FalChatChannel.h"
#include "CEGUIPropertyHelper.h"
#include "falagard/CEGUIFalWidgetLookManager.h"
#include "falagard/CEGUIFalWidgetLookFeel.h"
// Start of CEGUI namespace section
namespace CEGUI
{
//===================================================================================
//
// FalagardChatChannel
//
//===================================================================================
const utf8 FalagardChatChannel::WidgetTypeName[] = "Falagard/ChatChannel";
FalagardChatChannelProperties::ItemSize FalagardChatChannel::d_itemSizeProperty;
FalagardChatChannelProperties::AnchorPosition FalagardChatChannel::d_anchorPositionProperty;
FalagardChatChannelProperties::HoverChannelBkg FalagardChatChannel::d_hoverChannelBkgProperty;
FalagardChatChannelProperties::HoverChannel FalagardChatChannel::d_hoverChannelProperty;
FalagardChatChannelProperties::HoverChannelName FalagardChatChannel::d_hoverChannelNameProperty;
FalagardChatChannel::FalagardChatChannel(const String& type, const String& name) :
Window(type, name),
d_itemSize(0.0, 0.0),
d_anchorPosition(0.0, 0.0),
d_hoverChannelBkg(0),
d_hoverChannel(-1),
d_lastHoverChannel(-1),
d_pushed(false)
{
addChatChannelProperties();
setAlwaysOnTop(true);
}
FalagardChatChannel::~FalagardChatChannel()
{
}
void FalagardChatChannel::addChatChannelProperties(void)
{
CEGUI_START_ADD_STATICPROPERTY( FalagardChatChannel )
CEGUI_ADD_STATICPROPERTY( &d_itemSizeProperty );
CEGUI_ADD_STATICPROPERTY( &d_anchorPositionProperty );
CEGUI_ADD_STATICPROPERTY( &d_hoverChannelBkgProperty );
CEGUI_ADD_STATICPROPERTY( &d_hoverChannelProperty );
CEGUI_ADD_STATICPROPERTY( &d_hoverChannelNameProperty );
CEGUI_END_ADD_STATICPROPERTY
}
void FalagardChatChannel::onMouseMove(MouseEventArgs& e)
{
// base class processing
Window::onMouseMove(e);
updateInternalState(e.position);
e.handled = true;
}
void FalagardChatChannel::updateInternalState(const Point& ptMouse)
{
Point pt(ptMouse);
pt.d_x -= windowToScreenX(0);
pt.d_y -= windowToScreenY(0);
Rect absarea(getPixelRect());
absarea.offset(Point(-absarea.d_left, -absarea.d_top));
if(absarea.isPointInRect(pt))
{
float fItemHeight = absarea.getHeight()/(int)d_allChannel.size();
d_hoverChannel = (int)(pt.d_y/fItemHeight);
if(d_lastHoverChannel != d_hoverChannel)
{
requestRedraw();
d_lastHoverChannel = d_hoverChannel;
}
}
}
void FalagardChatChannel::onMouseButtonDown(MouseEventArgs& e)
{
// default processing
Window::onMouseButtonDown(e);
if (e.button == LeftButton)
{
if (captureInput())
{
d_pushed = true;
updateInternalState(e.position);
requestRedraw();
}
// event was handled by us.
e.handled = true;
}
}
void FalagardChatChannel::onMouseButtonUp(MouseEventArgs& e)
{
// default processing
Window::onMouseButtonUp(e);
if (e.button == LeftButton)
{
releaseInput();
// event was handled by us.
e.handled = true;
}
}
void FalagardChatChannel::onMouseLeaves(MouseEventArgs& e)
{
// base class processing
Window::onMouseLeaves(e);
d_hoverChannel = -1;
d_lastHoverChannel = -1;
requestRedraw();
}
void FalagardChatChannel::populateRenderCache(void)
{
// get WidgetLookFeel for the assigned look.
const WidgetLookFeel& wlf = WidgetLookManager::getSingleton().getWidgetLook(d_lookName);
// try and get imagery for our current state
const StateImagery* imagery = &wlf.getStateImagery("Frame");
// peform the rendering operation.
imagery->render(*this);
const Rect rectIconSize(wlf.getNamedArea("IconSize").getArea().getPixelRect(*this));
const FontBase* font = getFont();
Rect absarea(getPixelRect());
absarea.offset(Point(-absarea.d_left, -absarea.d_top));
ColourRect final_cols(colour(1.0f, 1.0f, 1.0f));
float fItemHeight = absarea.getHeight()/(int)d_allChannel.size();
for(int i=0; i<(int)d_allChannel.size(); i++)
{
ChannelItem& theChannel = d_allChannel[i];
Rect rectIcon(rectIconSize);
rectIcon.offset(Point(0, (fItemHeight-rectIconSize.getHeight())/2 + fItemHeight*i));
d_renderCache.cacheImage(
*theChannel.d_headIcon, rectIcon, 0.0f, final_cols);
Rect rectText(absarea.d_left, fItemHeight*i,
absarea.d_right, fItemHeight*(i+1));
rectText.d_left += rectIcon.getWidth()+2;
if(d_hoverChannelBkg && d_hoverChannel == i)
{
d_renderCache.cacheImage(
*d_hoverChannelBkg, rectText, 0.0f, ColourRect(0xFFFF0000, 0xFFFF0000, 0xFFFF0000, 0xFFFF0000));
}
d_renderCache.cacheText(this,
theChannel.d_strName, font, (TextFormatting)WordWrapLeftAligned, rectText, 0.0f, final_cols);
}
}
void FalagardChatChannel::resizeSelf(void)
{
float fTotalHeight = d_itemSize.d_height * (int)d_allChannel.size();
setSize(Absolute,Size(d_itemSize.d_width, fTotalHeight));
float fParentHeight = d_parent->getPixelRect().getHeight();
if(d_parent->getPixelRect().getWidth() < 1024) fParentHeight += 51;
setPosition(Absolute,Point(d_anchorPosition.d_x, fParentHeight - d_anchorPosition.d_y - fTotalHeight));
}
void FalagardChatChannel::clearAllChannel(void)
{
d_allChannel.clear();
resizeSelf();
}
void FalagardChatChannel::addChannel(const String& strType, const String& strIconName, const String& strName)
{
ChannelItem newChannel;
newChannel.d_strType = strType;
newChannel.d_headIcon = PropertyHelper::stringToImage(strIconName);
if(!newChannel.d_headIcon) return;
newChannel.d_strName = strName;
d_allChannel.push_back(newChannel);
resizeSelf();
}
String FalagardChatChannel::getHoverChannel(void) const
{
if(d_hoverChannel >= 0 && d_hoverChannel < (int)d_allChannel.size())
{
return d_allChannel[d_hoverChannel].d_strType;
}
return String("");
}
String FalagardChatChannel::getHoverChannelName(void) const
{
if(d_hoverChannel >= 0 && d_hoverChannel < (int)d_allChannel.size())
{
return d_allChannel[d_hoverChannel].d_strName;
}
return String("");
}
//////////////////////////////////////////////////////////////////////////
/*************************************************************************
Factory Methods
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
Window* FalagardChatChannelFactory::createWindow(const String& name)
{
return new FalagardChatChannel(d_type, name);
}
void FalagardChatChannelFactory::destroyWindow(Window* window)
{
delete window;
}
} | 6,657 | 2,512 |
// Houzi Game Engine
// Copyright (c) 2018 Davide Corradi
// Licensed under the MIT license.
#include "hou/gfx/test_gfx_base.hpp"
#include "hou/gfx/graphics_state.hpp"
using namespace hou;
using namespace testing;
namespace hou
{
class test_graphics_state : public test_gfx_base
{
public:
static std::vector<blending_factor> blending_factors;
static std::vector<blending_equation> blending_equations;
};
std::vector<blending_factor> test_graphics_state::blending_factors{
blending_factor::zero,
blending_factor::one,
blending_factor::src_color,
blending_factor::one_minus_src_color,
blending_factor::dst_color,
blending_factor::one_minus_dst_color,
blending_factor::src_alpha,
blending_factor::one_minus_src_alpha,
blending_factor::dst_alpha,
blending_factor::one_minus_dst_alpha,
blending_factor::constant_color,
blending_factor::one_minus_constant_color,
blending_factor::constant_alpha,
blending_factor::one_minus_constant_alpha,
};
std::vector<blending_equation> test_graphics_state::blending_equations{
blending_equation::add,
blending_equation::subtract,
blending_equation::reverse_subtract,
blending_equation::min,
blending_equation::max,
};
} // namespace hou
TEST_F(test_graphics_state, set_vsync_mode)
{
EXPECT_EQ(vsync_mode::enabled, get_vsync_mode());
EXPECT_TRUE(set_vsync_mode(vsync_mode::disabled));
EXPECT_EQ(vsync_mode::disabled, get_vsync_mode());
if(set_vsync_mode(vsync_mode::adaptive))
{
EXPECT_EQ(vsync_mode::adaptive, get_vsync_mode());
}
EXPECT_TRUE(set_vsync_mode(vsync_mode::enabled));
EXPECT_EQ(vsync_mode::enabled, get_vsync_mode());
}
TEST_F(test_graphics_state, multisampling_enabled)
{
EXPECT_TRUE(is_multisampling_enabled());
set_multisampling_enabled(true);
EXPECT_TRUE(is_multisampling_enabled());
set_multisampling_enabled(false);
EXPECT_FALSE(is_multisampling_enabled());
set_multisampling_enabled(false);
EXPECT_FALSE(is_multisampling_enabled());
set_multisampling_enabled(true);
EXPECT_TRUE(is_multisampling_enabled());
}
TEST_F(test_graphics_state, blending_enabled)
{
EXPECT_TRUE(is_blending_enabled());
set_blending_enabled(true);
EXPECT_TRUE(is_blending_enabled());
set_blending_enabled(false);
EXPECT_FALSE(is_blending_enabled());
set_blending_enabled(false);
EXPECT_FALSE(is_blending_enabled());
set_blending_enabled(true);
EXPECT_TRUE(is_blending_enabled());
}
TEST_F(test_graphics_state, source_blending_factor)
{
blending_factor dst_factor = get_destination_blending_factor();
EXPECT_EQ(blending_factor::src_alpha, get_source_blending_factor());
for(auto f : blending_factors)
{
set_source_blending_factor(f);
EXPECT_EQ(f, get_source_blending_factor());
EXPECT_EQ(dst_factor, get_destination_blending_factor());
}
set_source_blending_factor(blending_factor::src_alpha);
}
TEST_F(test_graphics_state, destination_blending_factor)
{
blending_factor src_factor = get_source_blending_factor();
EXPECT_EQ(
blending_factor::one_minus_src_alpha, get_destination_blending_factor());
for(auto f : blending_factors)
{
set_destination_blending_factor(f);
EXPECT_EQ(f, get_destination_blending_factor());
EXPECT_EQ(src_factor, get_source_blending_factor());
}
set_destination_blending_factor(blending_factor::one_minus_src_alpha);
}
TEST_F(test_graphics_state, blending_equation)
{
EXPECT_EQ(blending_equation::add, get_blending_equation());
for(auto e : blending_equations)
{
set_blending_equation(e);
EXPECT_EQ(e, get_blending_equation());
}
set_blending_equation(blending_equation::add);
}
TEST_F(test_graphics_state, blending_color)
{
EXPECT_EQ(color::transparent(), get_blending_color());
set_blending_color(color::red());
EXPECT_EQ(color::red(), get_blending_color());
set_blending_color(color::transparent());
EXPECT_EQ(color::transparent(), get_blending_color());
}
| 3,922 | 1,475 |
/************************************************************************************
**
* @copyright (c) 2013-2100, ChengDu Duyer Technology Co., LTD. All Right Reserved.
*
*************************************************************************************/
/**
* @file duye_epoll.cpp
* @version
* @brief
* @author duye
* @date 2016-03-29
* @note
*
* 1. 2016-03-29 duye Created this file
*/
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <duye_sys.h>
#include <duye_epoll.h>
namespace duye {
static const int8* DUYE_LOG_PREFIX = "duye.system.epoll";
Epoll::Epoll() : m_epollfd(-1)
, m_maxEvents(0)
, m_sysEvents(NULL)
{
m_error.setPrefix(DUYE_LOG_PREFIX);
}
Epoll::~Epoll()
{
close();
}
bool Epoll::open(const uint32 maxEvents)
{
close();
m_maxEvents = maxEvents;
m_epollfd = epoll_create(m_maxEvents);
if (m_epollfd == -1)
{
ERROR_DUYE_LOG("%s:%d > epoll_create failed \n", __FILE__, __LINE__);
return false;
}
m_sysEvents = (struct epoll_event*)calloc(m_maxEvents, sizeof(struct epoll_event));
if (m_sysEvents == NULL) {
ERROR_DUYE_LOG("%s:%d > calloc return NULL \n", __FILE__, __LINE__);
return false;
}
return true;
}
bool Epoll::close()
{
m_maxEvents = 0;
if (m_epollfd != -1)
{
::close(m_epollfd);
m_epollfd = -1;
}
if (m_sysEvents != NULL)
{
free(m_sysEvents);
m_sysEvents = NULL;
}
return true;
}
bool Epoll::addfd(const int32 fd, const uint32 epollMode)
{
if (m_epollfd == -1) {
ERROR_DUYE_LOG("%s:%d > m_epollfd == -1", __FILE__, __LINE__);
return false;
}
struct epoll_event epollEvent;
bzero(&epollEvent, sizeof(struct epoll_event));
epollEvent.data.fd = fd;
epollEvent.events = epollMode;
int32 ret = epoll_ctl(m_epollfd, EPOLL_CTL_ADD, fd, &epollEvent);
if (ret != 0) {
ERROR_DUYE_LOG("[%s:%d] epoll_ctl() return = %d", __FILE__, __LINE__, ret);
return false;
}
return true;
}
bool Epoll::modfd(const int32 fd, const uint32 epollMode)
{
if (m_epollfd == -1) {
ERROR_DUYE_LOG("[%s:%d] m_epollfd == -1", __FILE__, __LINE__);
return false;
}
struct epoll_event epollEvent;
bzero(&epollEvent, sizeof(struct epoll_event));
epollEvent.data.fd = fd;
epollEvent.events = epollMode;
return epoll_ctl(m_epollfd, EPOLL_CTL_MOD, fd, &epollEvent) == 0 ? true : false;
}
bool Epoll::delfd(const int32 fd)
{
if (m_epollfd == -1) {
ERROR_DUYE_LOG("[%s:%d] m_epollfd == -1", __FILE__, __LINE__);
return false;
}
return epoll_ctl(m_epollfd, EPOLL_CTL_DEL, fd, NULL) == 0 ? true : false;
}
bool Epoll::wait(Epoll::EventList& eventList, const uint32 timeout)
{
if (m_epollfd == -1) {
ERROR_DUYE_LOG("[%s:%d] m_epollfd == -1", __FILE__, __LINE__);
return false;
}
int32 event_count = epoll_wait(m_epollfd, m_sysEvents, m_maxEvents, timeout);
if (event_count <= 0)
{
return false;
}
for (uint32 i = 0; i < (uint32)event_count; i++)
{
if ((m_sysEvents[i].events & EPOLLERR) ||
(m_sysEvents[i].events & EPOLLHUP))
{
ERROR_DUYE_LOG("[%s:%d] epoll error, close fd \n", __FILE__, __LINE__);
delfd(m_sysEvents[i].data.fd);
eventList.push_back(EpollEvent(m_sysEvents[i].data.fd, ERROR_FD));
continue;
}
else if (m_sysEvents[i].events & EPOLLIN)
{
eventList.push_back(EpollEvent(m_sysEvents[i].data.fd, RECV_FD));
}
else if (m_sysEvents[i].events & EPOLLOUT)
{
eventList.push_back(EpollEvent(m_sysEvents[i].data.fd, SEND_FD));
}
else
{
eventList.push_back(EpollEvent(m_sysEvents[i].data.fd, RECV_UN));
}
}
return true;
}
uint8* Epoll::error()
{
return m_error.error;
}
}
| 3,899 | 1,643 |
#include "log.h"
#include "ioloop.h"
#include <memory>
#include <iostream>
void test() {
auto loop = IOLoop::loop();
error_c ec = loop->handle_CtrlC();
if (ec) {
std::cout<<"Ctrl-C handler error "<<ec<<std::endl;
return;
}
auto uart = loop->uart("UartEndpoint");
{
std::shared_ptr<Client> endpoint;
uart->on_connect([&endpoint](std::shared_ptr<Client> cli, std::string name){
endpoint = cli;
endpoint->on_close([name, &endpoint](){
std::cout<<"Close "<<name<<std::endl;
//endpoint.reset();
});
endpoint->on_read([name](void* buf, int len){
std::cout<<"UART "<<name<<" ("<<len<<"): ";
const char* hex = "0123456789ABCDEF";
uint8_t *arr = (uint8_t*)buf;
for (int i = len; i; i--) {
uint8_t b = *arr++;
std::cout<<hex[(b>>4) & 0x0F];
std::cout<<hex[b & 0x0F]<<' ';
}
std::cout<<std::endl;
});
endpoint->on_error([](const error_c& ec) {
std::cout<<"UART cli error:"<<ec<<std::endl;
});
std::cout<<"Connect to "<<name<<std::endl;
});
uart->on_error([](const error_c& ec) {
std::cout<<"UART error:"<<ec<<std::endl;
});
uart->init("/dev/ttyUSB0",115200);
loop->run();
}
}
int main() {
Log::init();
Log::set_level(Log::Level::DEBUG,{"ioloop","uart"});
test();
return 0;
} | 1,593 | 533 |
// Copyright (c) 2013-2017, Matt Godbolt
// 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.
//
// 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 "seasocks/SynchronousResponse.h"
#include "seasocks/ToString.h"
#include "seasocks/StringUtil.h"
using namespace seasocks;
void SynchronousResponse::handle(std::shared_ptr<ResponseWriter> writer) {
auto rc = responseCode();
if (!isOk(rc)) {
writer->error(rc, std::string(payload(), payloadSize()));
return;
}
writer->begin(responseCode());
writer->header("Content-Length", toString(payloadSize()));
writer->header("Content-Type", contentType());
writer->header("Connection", keepConnectionAlive() ? "keep-alive" : "close");
writer->header("Last-Modified", now());
writer->header("Pragma", "no-cache");
auto headers = getAdditionalHeaders();
if (headers.find("Cache-Control") == headers.end()) {
writer->header("Cache-Control", "no-store");
}
if (headers.find("Expires") == headers.end()) {
writer->header("Expires", now());
}
for (auto& header : headers) {
writer->header(header.first, header.second);
}
writer->payload(payload(), payloadSize());
writer->finish(keepConnectionAlive());
}
void SynchronousResponse::cancel() {
}
| 2,518 | 840 |
#include "App.h"
#define STAGES (4)
int main()
{
unsigned char *Input_data = (unsigned char *)malloc(FRAMES * FRAME_SIZE);
unsigned char *Temp_data[STAGES - 1];
unsigned char *Output_data = (unsigned char *)malloc(MAX_OUTPUT_SIZE);
if (Input_data == NULL)
Exit_with_error();
if (Output_data == NULL)
Exit_with_error();
for (int Stage = 0; Stage < STAGES - 1; Stage++)
{
Temp_data[Stage] = (unsigned char *)malloc(FRAME_SIZE);
if (Temp_data[Stage] == NULL)
Exit_with_error();
}
Load_data(Input_data);
stopwatch total_time;
int Size = 0;
total_time.start();
for (int Frame = 0; Frame < FRAMES; Frame++)
{
std::vector<std::thread> ths;
ths.push_back(std::thread(&Scale_coarse, Input_data + Frame * FRAME_SIZE, Temp_data[0], 0, INPUT_HEIGHT_SCALE / 2));
ths.push_back(std::thread(&Scale_coarse, Input_data + Frame * FRAME_SIZE, Temp_data[0], INPUT_HEIGHT_SCALE / 2, INPUT_HEIGHT_SCALE));
pin_thread_to_cpu(ths[0], 0);
pin_thread_to_cpu(ths[1], 1);
for (auto &th : ths)
{
th.join();
}
Filter(Temp_data[0], Temp_data[1]);
Differentiate(Temp_data[1], Temp_data[2]);
Size = Compress(Temp_data[2], Output_data);
}
total_time.stop();
std::cout << "Total time taken by the loop is: " << total_time.latency() << " ns." << std::endl;
Store_data("Output.bin", Output_data, Size);
Check_data(Output_data, Size);
for (int i = 0; i < STAGES - 1; i++)
free(Temp_data[i]);
free(Input_data);
free(Output_data);
return EXIT_SUCCESS;
}
| 1,549 | 631 |
#include <iostream>
int main() {
int k;
while (std::cin >> k, k) {
for (int m{k + 1}; true; m++) {
int pos{0};
int n{k * 2};
bool hasGood{false};
for (int i{1}; i <= k; i++) {
pos = (pos + m - 1) % n;
if (pos < k) {
hasGood = true;
break;
}
n--;
}
if (!hasGood) {
std::cout << m << std::endl;
break;
}
}
}
} | 556 | 171 |
#pragma once
#include "../../Graphics/Material.hpp"
class EmissiveMaterial : public Material
{
public:
EmissiveMaterial(glm::vec3 col = glm::vec3(1, 1, 1));
~EmissiveMaterial();
void SetCol(glm::vec3 col) { m_Color = col; }
private:
void LoadTextures();
void AccessShaderAttributes();
void UploadDerivedVariables();
private:
//Parameters
GLint m_uCol;
glm::vec3 m_Color;
};
| 388 | 149 |
//+------------------------------------------------------------------------
//
// Microsoft Windows
// Copyright (C) Microsoft Corporation, 1993.
//
// File: bm_qi.cxx
//
// Contents: Ole QueryInterface test
//
// Classes: CQueryInterfaceTest
//
// History: 1-July-93 t-martig Created
//
//--------------------------------------------------------------------------
#include <headers.cxx>
#pragma hdrstop
#include <bm_qi.hxx>
// this is just an array of random interface iids. The qi server object
// answers YES to any QI, although the only valid methods on each interface
// are the methods of IUnknown.
//
// the code will answer NO to the following IIDs in order to prevent
// custom marshalling problems...
//
// IID_IMarshal, IID_IStdMarshalInfo, IID_IStdIdentity,
// IID_IPersist, IID_IProxyManager
const IID *iid[] = {&IID_IAdviseSink, &IID_IDataObject,
&IID_IOleObject, &IID_IOleClientSite,
&IID_IParseDisplayName, &IID_IPersistStorage,
&IID_IPersistFile, &IID_IStorage,
&IID_IOleContainer, &IID_IOleItemContainer,
&IID_IOleInPlaceSite, &IID_IOleInPlaceActiveObject,
&IID_IOleInPlaceObject, &IID_IOleInPlaceUIWindow,
&IID_IOleInPlaceFrame, &IID_IOleWindow};
TCHAR *CQueryInterfaceTest::Name ()
{
return TEXT("QueryInterface");
}
SCODE CQueryInterfaceTest::Setup (CTestInput *pInput)
{
SCODE sc;
CTestBase::Setup(pInput);
// get iteration count
m_ulIterations = pInput->GetIterations(Name());
// initialize state
for (ULONG iCtx=0; iCtx<CNT_CLSCTX; iCtx++)
{
sc = pInput->GetGUID(&m_ClsID[iCtx], Name(), apszClsIDName[iCtx]);
if (FAILED(sc))
{
Log (TEXT("Setup - GetClassID failed."), sc);
return sc;
}
INIT_RESULTS(m_ulQueryInterfaceSameTime[iCtx]);
INIT_RESULTS(m_ulPunkReleaseSameTime[iCtx]);
INIT_RESULTS(m_ulQueryInterfaceNewTime[iCtx]);
INIT_RESULTS(m_ulPunkReleaseNewTime[iCtx]);
_pUnk[iCtx] = NULL;
}
sc = InitCOM();
if (FAILED(sc))
{
Log (TEXT("Setup - CoInitialize failed."), sc);
return sc;
}
// create an instance of each qi server object
for (iCtx=0; iCtx<CNT_CLSCTX; iCtx++)
{
sc = CoCreateInstance(m_ClsID[iCtx], NULL, dwaClsCtx[iCtx],
IID_IUnknown, (void **)&_pUnk[iCtx]);
if (FAILED(sc))
{
Log (TEXT("Setup - CoCreateInstance failed"), sc);
}
}
return S_OK;
}
SCODE CQueryInterfaceTest::Cleanup ()
{
for (ULONG iCtx=0; iCtx<CNT_CLSCTX; iCtx++)
{
if (_pUnk[iCtx])
{
_pUnk[iCtx]->Release();
}
}
UninitCOM();
return S_OK;
}
SCODE CQueryInterfaceTest::Run ()
{
CStopWatch sw;
IUnknown *pUnk = NULL;
for (ULONG iCtx=0; iCtx<CNT_CLSCTX; iCtx++)
{
if (!_pUnk[iCtx])
continue;
// same interface each time, releasing after each query
for (ULONG iIter=0; iIter<m_ulIterations; iIter++)
{
sw.Reset ();
SCODE sc = _pUnk[iCtx]->QueryInterface(IID_IStorage, (void **)&pUnk);
m_ulQueryInterfaceSameTime[iCtx][iIter] = sw.Read ();
Log (TEXT("QueryInterface"), sc);
if (SUCCEEDED(sc))
{
sw.Reset();
pUnk->Release ();
m_ulPunkReleaseSameTime[iCtx][iIter] = sw.Read();
}
else
{
m_ulPunkReleaseSameTime[iCtx][iIter] = NOTAVAIL;
}
}
// different interface each time, releasing after each query
for (iIter=0; iIter<m_ulIterations; iIter++)
{
sw.Reset ();
SCODE sc = _pUnk[iCtx]->QueryInterface(*(iid[iIter]), (void **)&pUnk);
m_ulQueryInterfaceNewTime[iCtx][iIter] = sw.Read ();
Log (TEXT("QueryInterface"), sc);
if (SUCCEEDED(sc))
{
sw.Reset();
pUnk->Release ();
m_ulPunkReleaseNewTime[iCtx][iIter] = sw.Read();
}
else
{
m_ulPunkReleaseNewTime[iCtx][iIter] = NOTAVAIL;
}
}
}
return S_OK;
}
SCODE CQueryInterfaceTest::Report (CTestOutput &output)
{
output.WriteSectionHeader (Name(), TEXT("QueryInterface"), *m_pInput);
for (ULONG iCtx=0; iCtx<CNT_CLSCTX; iCtx++)
{
output.WriteString(TEXT("\n"));
output.WriteClassID (&m_ClsID[iCtx]);
output.WriteString(apszClsCtx[iCtx]);
output.WriteString(TEXT("\n"));
output.WriteResults (TEXT("QuerySameInterface"), m_ulIterations,
m_ulQueryInterfaceSameTime[iCtx]);
output.WriteResults (TEXT("Release "), m_ulIterations,
m_ulPunkReleaseSameTime[iCtx]);
output.WriteResults (TEXT("QueryNewInterface "), m_ulIterations,
m_ulQueryInterfaceNewTime[iCtx]);
output.WriteResults (TEXT("Release "), m_ulIterations,
m_ulPunkReleaseNewTime[iCtx]);
}
return S_OK;
}
| 4,765 | 2,011 |
// 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 "i2c-child.h"
#include <lib/sync/completion.h>
#include <threads.h>
#include <zircon/types.h>
#include <ddk/binding.h>
#include <ddk/debug.h>
#include <ddk/device.h>
#include <ddk/metadata.h>
#include <ddk/metadata/i2c.h>
#include <fbl/alloc_checker.h>
#include <fbl/mutex.h>
namespace i2c {
void I2cChild::Transfer(fidl::VectorView<bool> segments_is_write,
fidl::VectorView<fidl::VectorView<uint8_t>> write_segments_data,
fidl::VectorView<uint8_t> read_segments_length,
TransferCompleter::Sync& completer) {
if (segments_is_write.count() < 1) {
completer.ReplyError(ZX_ERR_INVALID_ARGS);
return;
}
auto op_list = std::make_unique<i2c_op_t[]>(segments_is_write.count());
size_t write_cnt = 0;
size_t read_cnt = 0;
for (size_t i = 0; i < segments_is_write.count(); ++i) {
if (segments_is_write[i]) {
if (write_cnt >= write_segments_data.count()) {
completer.ReplyError(ZX_ERR_INVALID_ARGS);
return;
}
op_list[i].data_buffer = write_segments_data[write_cnt].data();
op_list[i].data_size = write_segments_data[write_cnt].count();
op_list[i].is_read = false;
op_list[i].stop = false;
write_cnt++;
} else {
if (read_cnt >= read_segments_length.count()) {
completer.ReplyError(ZX_ERR_INVALID_ARGS);
return;
}
op_list[i].data_buffer = nullptr; // unused.
op_list[i].data_size = read_segments_length[read_cnt];
op_list[i].is_read = true;
op_list[i].stop = false;
read_cnt++;
}
}
op_list[segments_is_write.count() - 1].stop = true;
if (write_segments_data.count() != write_cnt) {
completer.ReplyError(ZX_ERR_INVALID_ARGS);
return;
}
if (read_segments_length.count() != read_cnt) {
completer.ReplyError(ZX_ERR_INVALID_ARGS);
return;
}
struct Ctx {
sync_completion_t done = {};
TransferCompleter::Sync* completer;
} ctx;
ctx.completer = &completer;
auto callback = [](void* ctx, zx_status_t status, const i2c_op_t* op_list, size_t op_count) {
auto ctx2 = static_cast<Ctx*>(ctx);
if (status == ZX_OK) {
auto reads = std::make_unique<fidl::VectorView<uint8_t>[]>(op_count);
for (size_t i = 0; i < op_count; ++i) {
reads[i].set_data(
fidl::unowned_ptr(static_cast<uint8_t*>(const_cast<void*>(op_list[i].data_buffer))));
reads[i].set_count(op_list[i].data_size);
}
fidl::VectorView<fidl::VectorView<uint8_t>> all_reads(fidl::unowned_ptr(reads.get()),
op_count);
ctx2->completer->ReplySuccess(std::move(all_reads));
} else {
ctx2->completer->ReplyError(status);
}
sync_completion_signal(&ctx2->done);
};
bus_->Transact(address_, op_list.get(), segments_is_write.count(), callback, &ctx);
sync_completion_wait(&ctx.done, zx::duration::infinite().get());
}
void I2cChild::I2cTransact(const i2c_op_t* op_list, size_t op_count, i2c_transact_callback callback,
void* cookie) {
bus_->Transact(address_, op_list, op_count, callback, cookie);
}
zx_status_t I2cChild::I2cGetMaxTransferSize(size_t* out_size) {
*out_size = bus_->max_transfer();
return ZX_OK;
}
zx_status_t I2cChild::I2cGetInterrupt(uint32_t flags, zx::interrupt* out_irq) {
// This is only used by the Intel I2C driver.
// TODO: Pass these interrupt numbers from intel-i2c.
if (address_ == 0xa) {
// Please do not use get_root_resource() in new code. See fxbug.dev/31358.
zx_status_t status = zx::interrupt::create(zx::resource(get_root_resource()), 0x1f,
ZX_INTERRUPT_MODE_LEVEL_LOW, out_irq);
if (status != ZX_OK) {
return status;
}
return ZX_OK;
} else if (address_ == 0x49) {
// Please do not use get_root_resource() in new code. See fxbug.dev/31358.
zx_status_t status = zx::interrupt::create(zx::resource(get_root_resource()), 0x33,
ZX_INTERRUPT_MODE_LEVEL_LOW, out_irq);
if (status != ZX_OK) {
return status;
}
return ZX_OK;
} else if (address_ == 0x10) {
// Acer12
// Please do not use get_root_resource() in new code. See fxbug.dev/31358.
zx_status_t status = zx::interrupt::create(zx::resource(get_root_resource()), 0x1f,
ZX_INTERRUPT_MODE_LEVEL_LOW, out_irq);
if (status != ZX_OK) {
return status;
}
return ZX_OK;
} else if (address_ == 0x50) {
// Please do not use get_root_resource() in new code. See fxbug.dev/31358.
zx_status_t status = zx::interrupt::create(zx::resource(get_root_resource()), 0x18,
ZX_INTERRUPT_MODE_EDGE_LOW, out_irq);
if (status != ZX_OK) {
return status;
}
return ZX_OK;
} else if (address_ == 0x15) {
// Please do not use get_root_resource() in new code. See fxbug.dev/31358.
zx_status_t status = zx::interrupt::create(zx::resource(get_root_resource()), 0x2b,
ZX_INTERRUPT_MODE_EDGE_LOW, out_irq);
if (status != ZX_OK) {
return status;
}
return ZX_OK;
}
return ZX_ERR_NOT_FOUND;
}
void I2cChild::DdkUnbind(ddk::UnbindTxn txn) { txn.Reply(); }
void I2cChild::DdkRelease() { delete this; }
} // namespace i2c
| 5,609 | 2,142 |
#include "graphics/Primitives.hpp"
#include <vector>
#include <glm/glm.hpp>
typedef glm::vec3 v3;
typedef glm::vec2 v2;
typedef glm::vec4 v4;
/*
p4 -- p3
| |
p1 -- p2
*/
void add_face(std::vector<v3>& v,
std::vector<v3>& n,
std::vector<v4>& c,
std::vector<v2>& t,
v3 p1,
v3 p2,
v3 p3,
v3 p4,
v3 n1,
v4 c1)
{
v.emplace_back(p1);
v.emplace_back(p2);
v.emplace_back(p3);
v.emplace_back(p1);
v.emplace_back(p3);
v.emplace_back(p4);
t.emplace_back(v2(0,0));
t.emplace_back(v2(1,0));
t.emplace_back(v2(1,1));
t.emplace_back(v2(0,0));
t.emplace_back(v2(1,1));
t.emplace_back(v2(0,1));
n.emplace_back(n1);
n.emplace_back(n1);
n.emplace_back(n1);
n.emplace_back(n1);
n.emplace_back(n1);
n.emplace_back(n1);
c.emplace_back(c1);
c.emplace_back(c1);
c.emplace_back(c1);
c.emplace_back(c1);
c.emplace_back(c1);
c.emplace_back(c1);
}
Model* Primitives::create_cube()
{
Model* model = new Model();
std::vector<v3> pos;
std::vector<v3> norm;
std::vector<v4> cols;
std::vector<v2> tex;
const float n = -0.5f;
const float p = 0.5f;
// FRONT
add_face(pos, norm, cols, tex,
v3(n,n,n),v3(p,n,n),
v3(p,p,n),v3(n,p,n),
v3(0,0,-1),v4(1,1,1,1));
// BACK
add_face(pos, norm, cols, tex,
v3(p,n,p),v3(n,n,p),
v3(n,p,p),v3(p,p,p),
v3(0,0,1),v4(1,1,1,1));
// TOP
add_face(pos, norm, cols, tex,
v3(n,p,n),v3(p,p,n),
v3(p,p,p),v3(n,p,p),
v3(0,1,0),v4(1,1,1,1));
// BOTTOM
add_face(pos, norm, cols, tex,
v3(n,n,p),v3(p,n,p),
v3(p,n,n),v3(n,n,n),
v3(0,-1,0),v4(1,1,1,1));
// LEFT
add_face(pos, norm, cols, tex,
v3(n,n,p),v3(n,n,n),
v3(n,p,n),v3(n,p,p),
v3(-1,0,0),v4(1,1,1,1));
// RIGHT
add_face(pos, norm, cols, tex,
v3(p,n,n),v3(p,n,p),
v3(p,p,p),v3(p,p,n),
v3(1,0,0),v4(1,1,1,1));
model->set_vertices(pos);
model->set_normals(norm);
model->set_colors(cols);
model->set_texcoords(tex);
return model;
}
Model* Primitives::create_quad(const float w, const float h)
{
Model* model = new Model();
std::vector<v3> pos;
std::vector<v3> norm;
std::vector<v4> cols;
std::vector<v2> tex;
add_face(pos, norm, cols, tex,
v3( -w/2.0f, -h/2.0f, 0),v3( w/2.0f, h/2.0f, 0),
v3( w/2.0f, h/2.0f, 0),v3(-w/2.0f, h/2.0f,0),
v3(0,0,-1),v4(1,1,1,1));
model->set_vertices(pos);
model->set_normals(norm);
model->set_colors(cols);
model->set_texcoords(tex);
return model;
}
/*
void make_cube(Model& model, glm::vec4 col, glm::vec3 pos, float scale)
{
float n = -0.5f;
float p = 0.5f;
std::vector<glm::vec3> verts;
std::vector<glm::vec4> colors;
std::vector<glm::vec2> texcoords;
// FRONT
verts.emplace_back(pos + glm::vec3(n,n,n) * scale);
verts.emplace_back(pos + glm::vec3(p,n,n) * scale);
verts.emplace_back(pos + glm::vec3(p,p,n) * scale);
verts.emplace_back(pos + glm::vec3(n,n,n) * scale);
verts.emplace_back(pos + glm::vec3(p,p,n) * scale);
verts.emplace_back(pos + glm::vec3(n,p,n) * scale);
colors.emplace_back(col); colors.emplace_back(col); colors.emplace_back(col);
colors.emplace_back(col); colors.emplace_back(col); colors.emplace_back(col);
texcoords.emplace_back(0,0); texcoords.emplace_back(1,0); texcoords.emplace_back(1,1);
texcoords.emplace_back(0,0); texcoords.emplace_back(1,1); texcoords.emplace_back(0,1);
// TOP
verts.emplace_back(pos + glm::vec3(n,p,n) * scale);
verts.emplace_back(pos + glm::vec3(p,p,p) * scale);
verts.emplace_back(pos + glm::vec3(p,p,n) * scale);
verts.emplace_back(pos + glm::vec3(n,p,n) * scale);
verts.emplace_back(pos + glm::vec3(p,p,p) * scale);
verts.emplace_back(pos + glm::vec3(n,p,p) * scale);
colors.emplace_back(col); colors.emplace_back(col); colors.emplace_back(col);
colors.emplace_back(col); colors.emplace_back(col); colors.emplace_back(col);
texcoords.emplace_back(0,0); texcoords.emplace_back(1,0); texcoords.emplace_back(1,1);
texcoords.emplace_back(0,0); texcoords.emplace_back(1,1); texcoords.emplace_back(0,1);
// LEFT
verts.emplace_back(pos + glm::vec3(n,n,p) * scale);
verts.emplace_back(pos + glm::vec3(n,p,n) * scale);
verts.emplace_back(pos + glm::vec3(n,n,n) * scale);
verts.emplace_back(pos + glm::vec3(n,n,p) * scale);
verts.emplace_back(pos + glm::vec3(n,p,n) * scale);
verts.emplace_back(pos + glm::vec3(n,p,p) * scale);
colors.emplace_back(col); colors.emplace_back(col); colors.emplace_back(col);
colors.emplace_back(col); colors.emplace_back(col); colors.emplace_back(col);
texcoords.emplace_back(0,0); texcoords.emplace_back(1,0); texcoords.emplace_back(1,1);
texcoords.emplace_back(0,0); texcoords.emplace_back(1,1); texcoords.emplace_back(0,1);
// RIGHT
verts.emplace_back(pos + glm::vec3(p,n,n) * scale);
verts.emplace_back(pos + glm::vec3(p,n,p) * scale);
verts.emplace_back(pos + glm::vec3(p,p,p) * scale);
verts.emplace_back(pos + glm::vec3(p,n,n) * scale);
verts.emplace_back(pos + glm::vec3(p,p,p) * scale);
verts.emplace_back(pos + glm::vec3(p,p,n) * scale);
colors.emplace_back(col); colors.emplace_back(col); colors.emplace_back(col);
colors.emplace_back(col); colors.emplace_back(col); colors.emplace_back(col);
texcoords.emplace_back(0,0); texcoords.emplace_back(1,0); texcoords.emplace_back(1,1);
texcoords.emplace_back(0,0); texcoords.emplace_back(1,1); texcoords.emplace_back(0,1);
// BOTTOM
verts.emplace_back(pos + glm::vec3(n,n,p) * scale);
verts.emplace_back(pos + glm::vec3(p,n,p) * scale);
verts.emplace_back(pos + glm::vec3(p,n,n) * scale);
verts.emplace_back(pos + glm::vec3(n,n,p) * scale);
verts.emplace_back(pos + glm::vec3(p,n,n) * scale);
verts.emplace_back(pos + glm::vec3(n,n,n) * scale);
colors.emplace_back(col); colors.emplace_back(col); colors.emplace_back(col);
colors.emplace_back(col); colors.emplace_back(col); colors.emplace_back(col);
texcoords.emplace_back(0,0); texcoords.emplace_back(1,0); texcoords.emplace_back(1,1);
texcoords.emplace_back(0,0); texcoords.emplace_back(1,1); texcoords.emplace_back(0,1);
// BACK
verts.emplace_back(pos + glm::vec3(n,n,p) * scale);
verts.emplace_back(pos + glm::vec3(p,p,p) * scale);
verts.emplace_back(pos + glm::vec3(p,n,p) * scale);
verts.emplace_back(pos + glm::vec3(n,n,p) * scale);
verts.emplace_back(pos + glm::vec3(n,p,p) * scale);
verts.emplace_back(pos + glm::vec3(p,p,p) * scale);
colors.emplace_back(col); colors.emplace_back(col); colors.emplace_back(col);
colors.emplace_back(col); colors.emplace_back(col); colors.emplace_back(col);
texcoords.emplace_back(0,0); texcoords.emplace_back(1,0); texcoords.emplace_back(1,1);
texcoords.emplace_back(0,0); texcoords.emplace_back(1,1); texcoords.emplace_back(0,1);
model.set_vertices(verts);
model.set_colors(colors);
model.set_texcoords(texcoords);
}
*/ | 6,744 | 3,501 |
#include "LevSceneUtil.h"
#include "LevMeshObject.h"
#include "LevSceneObject.h"
#include "LevRAttrRenderObjectAttributeBinder.h"
namespace Leviathan
{
namespace Scene
{
bool LevSceneUtil::InitSceneNodeWithMeshFile(const char * mesh_file, unsigned scene_object_mask, LSPtr<LevSceneNode>& out_scene_node)
{
LSPtr<LevMeshObject> mesh_object = new LevMeshObject;
EXIT_IF_FALSE(mesh_object->LoadMeshFile(mesh_file));
LSPtr<LevSceneObject> scene_object = new LevSceneObject(scene_object_mask);
EXIT_IF_FALSE(scene_object->SetObjectDesc(TryCast<LevMeshObject, LevSceneObjectDescription>(mesh_object)));
out_scene_node.Reset(new LevSceneNode(scene_object));
return true;
}
// TODO: Handle different bind_type
bool LevSceneUtil::BindMeshDataToRenderAttribute(LevSceneNode& node, int bind_type_mask)
{
const Scene::LevMeshObject* meshes = dynamic_cast<const Scene::LevMeshObject*>(&node.GetNodeData()->GetObjectDesc());
EXIT_IF_FALSE(meshes);
// Bind attributes
size_t primitive_vertex_count = 0;
size_t vertex_count = 0;
for (auto& mesh : meshes->GetMesh())
{
primitive_vertex_count += mesh->GetPrimitiveCount();
vertex_count += mesh->GetVertexCount();
}
LSPtr<RAIIBufferData> index_buffer = new RAIIBufferData(3 * sizeof(unsigned) * primitive_vertex_count);
LSPtr<RAIIBufferData> vertex_buffer = new RAIIBufferData(3 * sizeof(float) * vertex_count);
unsigned last_index = 0;
unsigned* index_buffer_pointer = static_cast<unsigned*>(index_buffer->GetArrayData());
float* vertex_buffer_pointer = static_cast<float*>(vertex_buffer->GetArrayData());
for (auto& mesh : meshes->GetMesh())
{
const auto sub_mesh_vertex_count = mesh->GetVertexCount();
const auto sub_mesh_index_count = mesh->GetPrimitiveCount();
const auto* vertex_array = mesh->GetVertex3DCoordArray();
memcpy(vertex_buffer_pointer, vertex_array, 3 * sizeof(float) * sub_mesh_vertex_count);
unsigned* index = mesh->GetPrimitiveIndexArray();
for (unsigned i = 0; i < 3 * sub_mesh_index_count; i++)
{
index_buffer_pointer[0] = index[i] + last_index;
index_buffer_pointer++;
}
last_index += sub_mesh_vertex_count;
vertex_buffer_pointer += 3 * sub_mesh_vertex_count;
}
LSPtr<Scene::LevRAttrRenderObjectAttributeBinder> attribute_binder = new Scene::LevRAttrRenderObjectAttributeBinder(vertex_count);
attribute_binder->BindAttribute(0, new LevRenderObjectAttribute(Scene::RenderObjectAttributeType::EROAT_FLOAT, 3 * sizeof(float), vertex_buffer));
attribute_binder->SetIndexAttribute(new LevRenderObjectAttribute(Scene::RenderObjectAttributeType::EROAT_UINT, sizeof(unsigned), index_buffer));
node.GetNodeData()->AddAttribute(TryCast<Scene::LevRAttrRenderObjectAttributeBinder, Scene::LevSceneObjectAttribute>(attribute_binder));
return true;
}
bool LevSceneUtil::GenerateEmptySceneNode(LSPtr<LevSceneNode>& out)
{
const LSPtr<LevSceneObject> empty_object = new LevSceneObject(ELSOT_EMPTY);
out.Reset(new LevSceneNode(empty_object));
return true;
}
bool LevSceneUtil::GenerateCube(const float* cube_center, float cube_length, LSPtr<LevSceneNode>& out_cube_node)
{
LSPtr<RAIIBufferData> vertices_buffer = new RAIIBufferData(8 * 3 * sizeof(float));
float* data = static_cast<float*>(vertices_buffer->GetArrayData());
LSPtr<RAIIBufferData> normal_buffer = new RAIIBufferData(8 * 3 * sizeof(float));
float* normal_data = static_cast<float*>(vertices_buffer->GetArrayData());
float _cube[] =
{
-cube_length, -cube_length, -cube_length,
-cube_length, -cube_length, cube_length,
-cube_length, cube_length, -cube_length,
-cube_length, cube_length, cube_length,
cube_length, -cube_length, -cube_length,
cube_length, -cube_length, cube_length,
cube_length, cube_length, -cube_length,
cube_length, cube_length, cube_length
};
for (unsigned i = 0; i < 8; i++)
{
_cube[3 * i] += cube_center[0];
_cube[3 * i + 1] += cube_center[1];
_cube[3 * i + 2] += cube_center[2];
}
memcpy(data, _cube, sizeof(_cube));
const float NORMAL_PART_VALUE = 0.57735f;
float _normal[] =
{
-NORMAL_PART_VALUE, -NORMAL_PART_VALUE, -NORMAL_PART_VALUE,
-NORMAL_PART_VALUE, -NORMAL_PART_VALUE, NORMAL_PART_VALUE,
-NORMAL_PART_VALUE, NORMAL_PART_VALUE, -NORMAL_PART_VALUE,
-NORMAL_PART_VALUE, NORMAL_PART_VALUE, NORMAL_PART_VALUE,
NORMAL_PART_VALUE, -NORMAL_PART_VALUE, -NORMAL_PART_VALUE,
NORMAL_PART_VALUE, -NORMAL_PART_VALUE, NORMAL_PART_VALUE,
NORMAL_PART_VALUE, NORMAL_PART_VALUE, -NORMAL_PART_VALUE,
NORMAL_PART_VALUE, NORMAL_PART_VALUE, NORMAL_PART_VALUE,
};
memcpy(normal_data, _normal, sizeof(_normal));
LSPtr<RAIIBufferData> indices_buffer = new RAIIBufferData(6 * 2 * 3 * sizeof(unsigned));
unsigned* indices_data = static_cast<unsigned*>(indices_buffer->GetArrayData());
unsigned indices[] =
{
0, 3, 1,
0, 2, 3,
0, 2, 6,
0, 6, 4,
0, 1, 5,
0, 5, 4,
7, 6, 4,
7, 4, 5,
7, 5, 1,
7, 1, 3,
7, 6, 2,
7, 2, 3
};
memcpy(indices_data, indices, sizeof(indices));
LSPtr<LevRAttrRenderObjectAttributeBinder> attribute_binder = new LevRAttrRenderObjectAttributeBinder(8);
LSPtr<LevRenderObjectAttribute> vertices_attribute = new LevRenderObjectAttribute(EROAT_FLOAT, 3 * sizeof(float), vertices_buffer);
attribute_binder->BindAttribute(0, vertices_attribute);
LSPtr<LevRenderObjectAttribute> normals_attribute = new LevRenderObjectAttribute(EROAT_FLOAT, 3 * sizeof(float), normal_buffer);
attribute_binder->BindAttribute(1, normals_attribute);
LSPtr<LevRenderObjectAttribute> index_attribute = new LevRenderObjectAttribute(EROAT_UINT, sizeof(unsigned), indices_buffer);
attribute_binder->SetIndexAttribute(index_attribute);
LSPtr<LevSceneObject> object = new LevSceneObject(ELSOT_DYNAMIC);
object->AddAttribute(TryCast<LevRAttrRenderObjectAttributeBinder, LevSceneObjectAttribute>(attribute_binder));
out_cube_node.Reset(new LevSceneNode(object));
return true;
}
bool LevSceneUtil::GenerateBallNode(const float* ball_center, float ball_radius, LSPtr<LevSceneNode>& out_ball_node)
{
constexpr float angle_delta = 15.0f * PI_FLOAT / 180.0f;
constexpr size_t step_count = 2 * PI_FLOAT / angle_delta;
Eigen::Vector3f current_scan_half_ball[step_count + 1];
// Init base scan line
for (size_t i = 0; i <= step_count; i++)
{
float coord[] = { sinf(angle_delta * i) , cosf(angle_delta * i) , 0.0f };
memcpy(current_scan_half_ball[i].data(), coord, 3 * sizeof(float));
}
// Generate step rotation matrix (Rotate with x axis)
Eigen::Matrix3f rotation_step;
float rotation[] =
{
1.0f, 0.0f, 0.0f,
0.0f, cosf(angle_delta), sinf(angle_delta),
0.0f, -sinf(angle_delta), cosf(angle_delta),
};
memcpy(rotation_step.data(), rotation, sizeof(rotation));
std::vector<Eigen::Vector3f> m_vertices;
std::vector<Eigen::Vector3f> m_normals;
std::vector<unsigned> m_indices;
unsigned current_index_offset = 0;
for (auto& vertex : current_scan_half_ball)
{
m_vertices.push_back(vertex);
}
/*
Current scan line: 0 - 1 - 2 - 3 - 4 - 5
| / | / | / | / | / |
Next scan line: 6 - 7 - 8 - 9 - 10- 11
*/
unsigned index_delta[2 * 3 * step_count];
for (size_t i = 0; i < step_count; i++)
{
unsigned* data = index_delta + 2 * 3 * i;
data[0] = i;
data[1] = i + 1;
data[2] = step_count + 1 + i;
data[3] = data[2];
data[4] = data[1];
data[5] = data[2] + 1;
}
for (size_t i = 0; i < step_count; i++)
{
Eigen::Vector3f next_scan_half_ball[step_count + 1];
for (size_t j = 0; j <= step_count; j++)
{
next_scan_half_ball[j] = rotation_step * current_scan_half_ball[j];
m_vertices.push_back(next_scan_half_ball[j]);
}
for (auto index : index_delta)
{
m_indices.push_back(index + current_index_offset);
}
memcpy(current_scan_half_ball->data(), next_scan_half_ball->data(), sizeof(next_scan_half_ball));
current_index_offset += (step_count + 1);
}
// calculate normals
size_t vertices_count = m_vertices.size();
for (size_t i = 0; i < vertices_count; i++)
{
m_normals.push_back(m_vertices[i].normalized());
}
// Do radius scale
Eigen::Vector3f ball_center_vector; memcpy(ball_center_vector.data(), ball_center, 3 * sizeof(float));
for (size_t i = 0; i < m_vertices.size(); i++)
{
auto& vertex = m_vertices[i];
vertex *= ball_radius;
vertex += ball_center_vector;
}
// Convert vertices data
LSPtr<RAIIBufferData> vertices_buffer_data = new RAIIBufferData(m_vertices.size() * 3 * sizeof(float));
float* coord_data = static_cast<float*>(vertices_buffer_data->GetArrayData());
for (size_t i = 0; i < m_vertices.size(); i++)
{
float* data = coord_data + 3 * i;
memcpy(data, m_vertices[i].data(), 3 * sizeof(float));
}
LSPtr<RAIIBufferData> normals_buffer_data = new RAIIBufferData(m_normals.size() * 3 * sizeof(float));
float* normal_data = static_cast<float*>(normals_buffer_data->GetArrayData());
for (size_t i = 0; i < m_normals.size(); i++)
{
float* data = normal_data + 3 * i;
memcpy(data, m_normals[i].data(), 3 * sizeof(float));
}
LSPtr<LevRAttrRenderObjectAttributeBinder> attribute_binder = new LevRAttrRenderObjectAttributeBinder(m_vertices.size());
LSPtr<LevRenderObjectAttribute> vertices_attribute = new LevRenderObjectAttribute(EROAT_FLOAT, 3 * sizeof(float), vertices_buffer_data);
attribute_binder->BindAttribute(0, vertices_attribute);
LSPtr<LevRenderObjectAttribute> normals_attribute = new LevRenderObjectAttribute(EROAT_FLOAT, 3 * sizeof(float), normals_buffer_data);
attribute_binder->BindAttribute(1, normals_attribute);
LSPtr<RAIIBufferData> indices_buffer_data = new RAIIBufferData(m_indices.size() * sizeof(unsigned));
unsigned* indices_data = static_cast<unsigned*>(indices_buffer_data->GetArrayData());
for (size_t i = 0; i < m_indices.size(); i++)
{
unsigned* data = indices_data + i;
*data = m_indices[i];
}
LSPtr<LevRenderObjectAttribute> index_attribute = new LevRenderObjectAttribute(EROAT_UINT, sizeof(unsigned), indices_buffer_data);
attribute_binder->SetIndexAttribute(index_attribute);
LSPtr<LevSceneObject> object = new LevSceneObject(ELSOT_DYNAMIC);
object->AddAttribute(TryCast<LevRAttrRenderObjectAttributeBinder, LevSceneObjectAttribute>(attribute_binder));
out_ball_node.Reset(new LevSceneNode(object));
return true;
}
bool LevSceneUtil::GeneratePlaneNode(const float* plane_node0, const float* plane_node1, const float* plane_node2, const float* plane_node3, LSPtr<LevSceneNode>& out_plane_node)
{
float vertices[12];
memcpy(vertices, plane_node0, 3 * sizeof(float));
memcpy(vertices + 3, plane_node1, 3 * sizeof(float));
memcpy(vertices + 6, plane_node2, 3 * sizeof(float));
memcpy(vertices + 9, plane_node3, 3 * sizeof(float));
LSPtr<RAIIBufferData> vertices_buffer_data = new RAIIBufferData(sizeof(vertices));
memcpy(vertices_buffer_data->GetArrayData(), vertices, sizeof(vertices));
/*
Calculate plane normal
*/
Eigen::Vector3f edge0;
edge0.x() = plane_node0[0] - plane_node1[0];
edge0.y() = plane_node0[1] - plane_node1[1];
edge0.z() = plane_node0[2] - plane_node1[2];
Eigen::Vector3f edge1;
edge1.x() = plane_node1[0] - plane_node2[0];
edge1.y() = plane_node1[1] - plane_node2[1];
edge1.z() = plane_node1[2] - plane_node2[2];
Eigen::Vector3f normal;
normal = edge0.cross(edge1);
normal.normalize();
LSPtr<RAIIBufferData> normals_buffer_data = new RAIIBufferData(sizeof(vertices));
float* normal_data = static_cast<float*>(normals_buffer_data->GetArrayData());
for (size_t i = 0; i < 4; i++)
{
memcpy(normal_data + 3 * i, normal.data(), 3 * sizeof(float));
}
LSPtr<LevRenderObjectAttribute> vertex_attibute = new LevRenderObjectAttribute(EROAT_FLOAT, 3 * sizeof(float), vertices_buffer_data);
LSPtr<LevRenderObjectAttribute> normal_attribute = new LevRenderObjectAttribute(EROAT_FLOAT, 3 * sizeof(float), normals_buffer_data);
unsigned indexs[6] =
{
0, 1, 2,
0, 2, 3
};
LSPtr<RAIIBufferData> index_buffer_data = new RAIIBufferData(sizeof(indexs));
memcpy(index_buffer_data->GetArrayData(), indexs, sizeof(indexs));
LSPtr<LevRenderObjectAttribute> index_attribute = new LevRenderObjectAttribute(EROAT_UINT, sizeof(unsigned), index_buffer_data);
LSPtr<LevRAttrRenderObjectAttributeBinder> attribute_binder = new LevRAttrRenderObjectAttributeBinder(4);
attribute_binder->BindAttribute(0, vertex_attibute);
attribute_binder->BindAttribute(1, normal_attribute);
attribute_binder->SetIndexAttribute(index_attribute);
LSPtr<LevSceneObject> plane_object = new LevSceneObject(ELSOT_DYNAMIC);
plane_object->AddAttribute(TryCast<LevRAttrRenderObjectAttributeBinder, LevSceneObjectAttribute>(attribute_binder));
out_plane_node.Reset(new LevSceneNode(plane_object));
return true;
}
bool LevSceneUtil::GeneratePoints(const float* vertices, const float* normals,
unsigned count, LSPtr<LevSceneNode>& out_points_node)
{
LSPtr<LevRAttrRenderObjectAttributeBinder> attribute_binder = new LevRAttrRenderObjectAttributeBinder(count);
LSPtr<RAIIBufferData> vertices_data = new RAIIBufferData(count * 3 * sizeof(float));
memcpy(vertices_data->GetArrayData(), vertices, 3 * count * sizeof(float));
LSPtr<LevRenderObjectAttribute> vertices_attribute = new LevRenderObjectAttribute(EROAT_FLOAT, 3 * sizeof(float), vertices_data);
attribute_binder->BindAttribute(0, vertices_attribute);
if (normals)
{
LSPtr<RAIIBufferData> normals_data = new RAIIBufferData(count * 3 * sizeof(float));
memcpy(normals_data->GetArrayData(), normals, 3 * count * sizeof(float));
LSPtr<LevRenderObjectAttribute> normals_attribute = new LevRenderObjectAttribute(EROAT_FLOAT, 3 * count * sizeof(float), normals_data);
attribute_binder->BindAttribute(1, normals_attribute);
}
attribute_binder->SetPrimitiveType(EROPT_POINTS);
LSPtr<LevSceneObject> point_object = new LevSceneObject(ELSOT_DYNAMIC);
point_object->AddAttribute(attribute_binder);
out_points_node.Reset(new LevSceneNode(point_object));
return true;
}
bool LevSceneUtil::GenerateIdentityMatrixUniform(const char* uniform_name, LSPtr<LevNumericalUniform>& out_uniform)
{
static float identity_matrix[] =
{
1.0f, 0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f
};
out_uniform.Reset(new LevNumericalUniform(uniform_name, TYPE_FLOAT_MAT4));
LSPtr<RAIIBufferData> identity_matrix_buffer_data = new RAIIBufferData(sizeof(identity_matrix));
identity_matrix_buffer_data->SetArrayData(identity_matrix, sizeof(identity_matrix));
out_uniform->SetData(identity_matrix_buffer_data);
return true;
}
bool LevSceneUtil::GenerateLookAtMatrixUniform(const char* uniform_name, const float* eye, const float* target,
const float* up, LSPtr<LevNumericalUniform>& out_uniform)
{
Eigen::Vector3f N, U, V;
Eigen::Vector3f veye; memcpy(veye.data(), eye, 3 * sizeof(float));
Eigen::Vector3f vup; memcpy(vup.data(), up, 3 * sizeof(float));
Eigen::Vector3f vlookat; memcpy(vlookat.data(), target, 3 * sizeof(float));
N = vlookat - veye;
N.normalize();
U = vup.cross(N);
U.normalize();
V = N.cross(U);
V.normalize();
float data[16] =
{
U[0], U[1], U[2], 0.0f,
V[0], V[1], V[2], 0.0f,
N[0], N[1], N[2], 0.0f,
-U.dot(veye), -V.dot(veye), -N.dot(veye), 1.0f,
};
out_uniform.Reset(new LevNumericalUniform(uniform_name, TYPE_FLOAT_MAT4));
LSPtr<RAIIBufferData> identity_matrix_buffer_data = new RAIIBufferData(sizeof(data));
identity_matrix_buffer_data->SetArrayData(data, sizeof(data));
out_uniform->SetData(identity_matrix_buffer_data);
return true;
}
bool LevSceneUtil::GenerateProjectionMatrix(const char* uniform_name, float fov, float aspect, float near, float far, LSPtr<LevNumericalUniform>& out_uniform)
{
float T = tanf(fov / 2.0f);
float N = near - far;
float M = near + far;
float K = aspect * T;
float L = far * near;
float data[16] =
{
1.0f / K, 0.0f, 0.0f, 0.0f,
0.0f, 1.0f / T, 0.0f, 0.0f,
0.0f, 0.0f, -M / N, 1.0f,
0.0f, 0.0f, 2 * L / N, 0.0f
};
out_uniform.Reset(new LevNumericalUniform(uniform_name, TYPE_FLOAT_MAT4));
LSPtr<RAIIBufferData> identity_matrix_buffer_data = new RAIIBufferData(sizeof(data));
identity_matrix_buffer_data->SetArrayData(data, sizeof(data));
out_uniform->SetData(identity_matrix_buffer_data);
return true;
}
}
} | 17,006 | 7,236 |
#include "filereader.h"
ImageRotator::ImageRotator(const QString *pathToSourceSvg, const QString *pathToRendedImage, const QString *fileType, const QString *slash, const QString *svgType, QObject *parent)
: QObject(parent)
, m_file(new QFile())
, m_pathToSourceSvgFolder(pathToSourceSvg)
, m_pathToRendedImageFolder(pathToRendedImage)
, m_fileType(fileType)
, m_slash(slash)
, m_svgType(svgType)
, m_image(new QImage(497, 279, QImage::Format_RGB32))
, m_renderer(new QSvgRenderer())
, m_painter(new QPainter(m_image))
, index(100)
, m_previousCharInArray(' ')
, m_array(Q_NULLPTR)
{
m_painter->setCompositionMode(QPainter::CompositionMode_SourceOver);
m_painter->setRenderHints(QPainter::Antialiasing, true);
m_renderer->setFramesPerSecond(0);
}
ImageRotator::~ImageRotator()
{
delete m_file;
delete m_image;
delete m_renderer;
delete m_painter;
}
void ImageRotator::setParams(QString &tile, QString &azm, QString &layer, char &firstNum, char &secondNum, char &thirdNum)
{
m_pathToSource.append(*m_pathToSourceSvgFolder).append(layer).append(*m_slash).append(tile).append(*m_svgType);
m_pathToRender.append(*m_pathToRendedImageFolder).append(layer).append(*m_slash).append(azm).append(*m_slash).append(tile).append(*m_fileType);
m_firstNum=firstNum;
m_secondNum=secondNum;
m_thirdNum=thirdNum;
}
void ImageRotator::doing()
{
m_file->setFileName(m_pathToSource);
m_file->open(QIODevice::ReadOnly);
m_array=m_file->readAll();
m_file->close();
for (index; index<m_array.size()-10; index=index+1)
{
if(m_previousCharInArray=='('&&m_array.at(index)==' '&&m_array.at(index+1)==' ')
{
m_array.operator[](index+2)=m_firstNum;
m_array.operator[](index+3)=m_secondNum;
m_array.operator[](index+4)=m_thirdNum;
index=index+60;
}
m_previousCharInArray=m_array.at(index);
}
m_renderer->load(m_array);
m_renderer->render(m_painter);
m_image->save(m_pathToRender);
index=40;
// m_file->setFileName(*m_pathToSourceSvg+m_layer+ "_1"+*m_slash+m_tileName+*m_svgType);
// m_file->open(QIODevice::WriteOnly);
// m_file->write(m_array);
// m_file->flush();
// m_file->close();
m_pathToSource.clear();
m_pathToRender.clear();
m_previousCharInArray=' ';
Q_EMIT finished();
}
| 2,409 | 932 |
/**
* @author hans@dkmt.io
* @date 2021-06-24
*/
#include "utils.h"
#include <chrono>
namespace dkcoro {
int64_t utils::current_time_millis() {
using std::chrono::duration_cast;
using std::chrono::milliseconds;
using std::chrono::system_clock;
auto now = system_clock::now();
return duration_cast<milliseconds>(now.time_since_epoch()).count();
}
int64_t utils::now() {
return current_time_millis();
}
int64_t utils::nano_time() {
using std::chrono::duration_cast;
using std::chrono::high_resolution_clock;
using std::chrono::nanoseconds;
auto now = high_resolution_clock::now();
return duration_cast<nanoseconds>(now.time_since_epoch()).count();
}
} // namespace dkcoro | 702 | 271 |
/***************************************************/
/*! \class Mesh2D
\brief Two-dimensional rectilinear waveguide mesh class.
This class implements a rectilinear,
two-dimensional digital waveguide mesh
structure. For details, see Van Duyne and
Smith, "Physical Modeling with the 2-D Digital
Waveguide Mesh", Proceedings of the 1993
International Computer Music Conference.
This is a digital waveguide model, making its
use possibly subject to patents held by Stanford
University, Yamaha, and others.
Control Change Numbers:
- X Dimension = 2
- Y Dimension = 4
- Mesh Decay = 11
- X-Y Input Position = 1
by Julius Smith, 2000 - 2002.
Revised by Gary Scavone for STK, 2002.
*/
/***************************************************/
#include "Mesh2D.h"
#include "SKINI-msg.h"
namespace stk {
Mesh2D :: Mesh2D( short nX, short nY )
{
this->setNX(nX);
this->setNY(nY);
StkFloat pole = 0.05;
short i;
for (i=0; i<NYMAX; i++) {
filterY_[i].setPole( pole );
filterY_[i].setGain( 0.99 );
}
for (i=0; i<NXMAX; i++) {
filterX_[i].setPole( pole );
filterX_[i].setGain( 0.99 );
}
this->clearMesh();
counter_=0;
xInput_ = 0;
yInput_ = 0;
}
Mesh2D :: ~Mesh2D( void )
{
}
void Mesh2D :: clear( void )
{
this->clearMesh();
short i;
for (i=0; i<NY_; i++)
filterY_[i].clear();
for (i=0; i<NX_; i++)
filterX_[i].clear();
counter_=0;
}
void Mesh2D :: clearMesh( void )
{
int x, y;
for (x=0; x<NXMAX-1; x++) {
for (y=0; y<NYMAX-1; y++) {
v_[x][y] = 0;
}
}
for (x=0; x<NXMAX; x++) {
for (y=0; y<NYMAX; y++) {
vxp_[x][y] = 0;
vxm_[x][y] = 0;
vyp_[x][y] = 0;
vym_[x][y] = 0;
vxp1_[x][y] = 0;
vxm1_[x][y] = 0;
vyp1_[x][y] = 0;
vym1_[x][y] = 0;
}
}
}
StkFloat Mesh2D :: energy( void )
{
// Return total energy contained in wave variables Note that some
// energy is also contained in any filter delay elements.
int x, y;
StkFloat t;
StkFloat e = 0;
if ( counter_ & 1 ) { // Ready for Mesh2D::tick1() to be called.
for (x=0; x<NX_; x++) {
for (y=0; y<NY_; y++) {
t = vxp1_[x][y];
e += t*t;
t = vxm1_[x][y];
e += t*t;
t = vyp1_[x][y];
e += t*t;
t = vym1_[x][y];
e += t*t;
}
}
}
else { // Ready for Mesh2D::tick0() to be called.
for (x=0; x<NX_; x++) {
for (y=0; y<NY_; y++) {
t = vxp_[x][y];
e += t*t;
t = vxm_[x][y];
e += t*t;
t = vyp_[x][y];
e += t*t;
t = vym_[x][y];
e += t*t;
}
}
}
return(e);
}
void Mesh2D :: setNX( short lenX )
{
NX_ = lenX;
if ( lenX < 2 ) {
errorString_ << "Mesh2D::setNX(" << lenX << "): Minimum length is 2!";
handleError( StkError::WARNING );
NX_ = 2;
}
else if ( lenX > NXMAX ) {
errorString_ << "Mesh2D::setNX(" << lenX << "): Maximum length is " << NXMAX << '!';;
handleError( StkError::WARNING );
NX_ = NXMAX;
}
}
void Mesh2D :: setNY( short lenY )
{
NY_ = lenY;
if ( lenY < 2 ) {
errorString_ << "Mesh2D::setNY(" << lenY << "): Minimum length is 2!";
handleError( StkError::WARNING );
NY_ = 2;
}
else if ( lenY > NYMAX ) {
errorString_ << "Mesh2D::setNY(" << lenY << "): Maximum length is " << NXMAX << '!';;
handleError( StkError::WARNING );
NY_ = NYMAX;
}
}
void Mesh2D :: setDecay( StkFloat decayFactor )
{
StkFloat gain = decayFactor;
if ( decayFactor < 0.0 ) {
errorString_ << "Mesh2D::setDecay: decayFactor value is less than 0.0!";
handleError( StkError::WARNING );
gain = 0.0;
}
else if ( decayFactor > 1.0 ) {
errorString_ << "Mesh2D::setDecay decayFactor value is greater than 1.0!";
handleError( StkError::WARNING );
gain = 1.0;
}
int i;
for (i=0; i<NYMAX; i++)
filterY_[i].setGain( gain );
for (i=0; i<NXMAX; i++)
filterX_[i].setGain( gain );
}
void Mesh2D :: setInputPosition( StkFloat xFactor, StkFloat yFactor )
{
if ( xFactor < 0.0 ) {
errorString_ << "Mesh2D::setInputPosition xFactor value is less than 0.0!";
handleError( StkError::WARNING );
xInput_ = 0;
}
else if ( xFactor > 1.0 ) {
errorString_ << "Mesh2D::setInputPosition xFactor value is greater than 1.0!";
handleError( StkError::WARNING );
xInput_ = NX_ - 1;
}
else
xInput_ = (short) (xFactor * (NX_ - 1));
if ( yFactor < 0.0 ) {
errorString_ << "Mesh2D::setInputPosition yFactor value is less than 0.0!";
handleError( StkError::WARNING );
yInput_ = 0;
}
else if ( yFactor > 1.0 ) {
errorString_ << "Mesh2D::setInputPosition yFactor value is greater than 1.0!";
handleError( StkError::WARNING );
yInput_ = NY_ - 1;
}
else
yInput_ = (short) (yFactor * (NY_ - 1));
}
void Mesh2D :: noteOn( StkFloat frequency, StkFloat amplitude )
{
// Input at corner.
if ( counter_ & 1 ) {
vxp1_[xInput_][yInput_] += amplitude;
vyp1_[xInput_][yInput_] += amplitude;
}
else {
vxp_[xInput_][yInput_] += amplitude;
vyp_[xInput_][yInput_] += amplitude;
}
#if defined(_STK_DEBUG_)
errorString_ << "Mesh2D::NoteOn: frequency = " << frequency << ", amplitude = " << amplitude << ".";
handleError( StkError::DEBUG_WARNING );
#endif
}
void Mesh2D :: noteOff( StkFloat amplitude )
{
#if defined(_STK_DEBUG_)
errorString_ << "Mesh2D::NoteOff: amplitude = " << amplitude << ".";
handleError( StkError::DEBUG_WARNING );
#endif
}
StkFloat Mesh2D :: inputTick( StkFloat input )
{
if ( counter_ & 1 ) {
vxp1_[xInput_][yInput_] += input;
vyp1_[xInput_][yInput_] += input;
lastFrame_[0] = tick1();
}
else {
vxp_[xInput_][yInput_] += input;
vyp_[xInput_][yInput_] += input;
lastFrame_[0] = tick0();
}
counter_++;
return lastFrame_[0];
}
StkFloat Mesh2D :: tick( unsigned int )
{
lastFrame_[0] = ((counter_ & 1) ? this->tick1() : this->tick0());
counter_++;
return lastFrame_[0];
}
const StkFloat VSCALE = 0.5;
StkFloat Mesh2D :: tick0( void )
{
int x, y;
StkFloat outsamp = 0;
// Update junction velocities.
for (x=0; x<NX_-1; x++) {
for (y=0; y<NY_-1; y++) {
v_[x][y] = ( vxp_[x][y] + vxm_[x+1][y] +
vyp_[x][y] + vym_[x][y+1] ) * VSCALE;
}
}
// Update junction outgoing waves, using alternate wave-variable buffers.
for (x=0; x<NX_-1; x++) {
for (y=0; y<NY_-1; y++) {
StkFloat vxy = v_[x][y];
// Update positive-going waves.
vxp1_[x+1][y] = vxy - vxm_[x+1][y];
vyp1_[x][y+1] = vxy - vym_[x][y+1];
// Update minus-going waves.
vxm1_[x][y] = vxy - vxp_[x][y];
vym1_[x][y] = vxy - vyp_[x][y];
}
}
// Loop over velocity-junction boundary faces, update edge
// reflections, with filtering. We're only filtering on one x and y
// edge here and even this could be made much sparser.
for (y=0; y<NY_-1; y++) {
vxp1_[0][y] = filterY_[y].tick(vxm_[0][y]);
vxm1_[NX_-1][y] = vxp_[NX_-1][y];
}
for (x=0; x<NX_-1; x++) {
vyp1_[x][0] = filterX_[x].tick(vym_[x][0]);
vym1_[x][NY_-1] = vyp_[x][NY_-1];
}
// Output = sum of outgoing waves at far corner. Note that the last
// index in each coordinate direction is used only with the other
// coordinate indices at their next-to-last values. This is because
// the "unit strings" attached to each velocity node to terminate
// the mesh are not themselves connected together.
outsamp = vxp_[NX_-1][NY_-2] + vyp_[NX_-2][NY_-1];
return outsamp;
}
StkFloat Mesh2D :: tick1( void )
{
int x, y;
StkFloat outsamp = 0;
// Update junction velocities.
for (x=0; x<NX_-1; x++) {
for (y=0; y<NY_-1; y++) {
v_[x][y] = ( vxp1_[x][y] + vxm1_[x+1][y] +
vyp1_[x][y] + vym1_[x][y+1] ) * VSCALE;
}
}
// Update junction outgoing waves,
// using alternate wave-variable buffers.
for (x=0; x<NX_-1; x++) {
for (y=0; y<NY_-1; y++) {
StkFloat vxy = v_[x][y];
// Update positive-going waves.
vxp_[x+1][y] = vxy - vxm1_[x+1][y];
vyp_[x][y+1] = vxy - vym1_[x][y+1];
// Update minus-going waves.
vxm_[x][y] = vxy - vxp1_[x][y];
vym_[x][y] = vxy - vyp1_[x][y];
}
}
// Loop over velocity-junction boundary faces, update edge
// reflections, with filtering. We're only filtering on one x and y
// edge here and even this could be made much sparser.
for (y=0; y<NY_-1; y++) {
vxp_[0][y] = filterY_[y].tick(vxm1_[0][y]);
vxm_[NX_-1][y] = vxp1_[NX_-1][y];
}
for (x=0; x<NX_-1; x++) {
vyp_[x][0] = filterX_[x].tick(vym1_[x][0]);
vym_[x][NY_-1] = vyp1_[x][NY_-1];
}
// Output = sum of outgoing waves at far corner.
outsamp = vxp1_[NX_-1][NY_-2] + vyp1_[NX_-2][NY_-1];
return outsamp;
}
void Mesh2D :: controlChange( int number, StkFloat value )
{
StkFloat norm = value * ONE_OVER_128;
if ( norm < 0 ) {
norm = 0.0;
errorString_ << "Mesh2D::controlChange: control value less than zero ... setting to zero!";
handleError( StkError::WARNING );
}
else if ( norm > 1.0 ) {
norm = 1.0;
errorString_ << "Mesh2D::controlChange: control value greater than 128.0 ... setting to 128.0!";
handleError( StkError::WARNING );
}
if (number == 2) // 2
this->setNX( (short) (norm * (NXMAX-2) + 2) );
else if (number == 4) // 4
this->setNY( (short) (norm * (NYMAX-2) + 2) );
else if (number == 11) // 11
this->setDecay( 0.9 + (norm * 0.1) );
else if (number == __SK_ModWheel_) // 1
this->setInputPosition( norm, norm );
else {
errorString_ << "Mesh2D::controlChange: undefined control number (" << number << ")!";
handleError( StkError::WARNING );
}
#if defined(_STK_DEBUG_)
errorString_ << "Mesh2D::controlChange: number = " << number << ", value = " << value << ".";
handleError( StkError::DEBUG_WARNING );
#endif
}
} // stk namespace
| 9,937 | 4,352 |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// There are potenially several ways to solve this problem. This solution
// simply fills a two dimensional boolean array representing whether or
// not a commercial is on for each minute of each station's programming.
// Then, we traverse the array, checking each minute to see if two or more
// stations are playing commercials at that time.
//
// This is probably not the most efficient solution in terms of time or
// memory used, but it is a simple, straightforward way to solve the
// problem.
int main(void)
{
FILE *fp;
char line[256];
int numSessions, numStations;
bool commercials[16][384];
int i, j;
int commercialGap, commercialLength;
int minute;
int commercialCount;
int sessionNum;
int pureCramming;
// Open the input file
fp = fopen("radio.in", "r");
// Get the number of sessions to check
fgets(line, sizeof(line), fp);
sscanf(line, "%d", &numSessions);
// For each session...
for (sessionNum = 1; sessionNum <= numSessions; sessionNum++)
{
// Clear the commercials array to all zeroes (all false values)
memset(commercials, 0, sizeof(commercials));
// Get the number of stations
fgets(line, sizeof(line), fp);
sscanf(line, "%d", &numStations);
// For each station...
for (i = 0; i < numStations; i++)
{
// Read the station's schedule and set up the commercial
// schedule in our array
fgets(line, sizeof(line), fp);
commercialGap = atoi(strtok(line, " \n"));
commercialLength = atoi(strtok(NULL, " \n"));
// Start at minute zero (6:00 PM)
minute = 0;
// Update the schedule all the way through midnight
while (minute < 360)
{
// Skip the commercial gap (the amount of time between
// commercials)
minute += commercialGap;
// Now, iterate through the array for commercialLength
// minutes, and change the entries to true (there is a
// commercial on at this time). Keep track of the overall
// minute as we go, so we don't overrun our array.
j = 0;
while ((j < commercialLength) && (minute < 360))
{
// Change this minute's entry to true
commercials[i][minute] = true;
// Increment the commercial time counter as well as the
// overall minute counter
minute++;
j++;
}
}
}
// Now that the array is set up, scan it minute by minute to see
// how many minutes of pure cramming we have
pureCramming = 0;
for (minute = 0; minute < 360; minute++)
{
// Start with zero commercial on for this minute
commercialCount = 0;
// Check each station for commercials
for (i = 0; i < numStations; i++)
{
// If there's a commercial on this station, increment the
// commercial count
if (commercials[i][minute])
commercialCount++;
}
// If there are two or more commercials on at this time, the
// radio is off and pure cramming ensues
if (commercialCount >= 2)
pureCramming++;
}
// Now, we can print the output
printf("Study session #%d has %d minute(s) of pure cramming."
" Excellent!\n", sessionNum, pureCramming);
}
}
| 3,646 | 1,069 |
// Author: Adam Phillippy
/*
Copyright (C) 2016 Pawel Gajer (pgajer@gmail.com), Adam Phillippy and Jacques Ravel jravel@som.umaryland.edu
Permission to use, copy, modify, and distribute this software and its
documentation with or without modifications and for any purpose and
without fee is hereby granted, provided that any copyright notices
appear in all copies and that both those copyright notices and this
permission notice appear in supporting documentation, and that the
names of the contributors or copyright holders not be used in
advertising or publicity pertaining to distribution of the software
without specific prior permission.
THE CONTRIBUTORS AND COPYRIGHT HOLDERS OF THIS SOFTWARE DISCLAIM ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL THE
CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, 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 <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <queue>
#include <deque>
#include <string>
#include "IOCUtilities.h"
#include "IOCppUtilities.hh"
#include "Newick.hh"
using namespace std;
#define DEBUG 0
//--------------------------------------------- NewickNode_t() -----
NewickNode_t::NewickNode_t(NewickNode_t * parent)
: parent_m(parent)
{
#if DEBUG
fprintf(stderr,"in NewickTree_t(parent)\t(parent==NULL)=%d\n",(int)(parent==NULL));
#endif
if (parent==NULL)
{
#if DEBUG
fprintf(stderr,"in if(parent==NULL)\n");
#endif
depth_m = -1;
}
else
{
#if DEBUG
fprintf(stderr,"in else\n");
#endif
depth_m = parent->depth_m+1;
}
#if DEBUG
fprintf(stderr,"leaving NewickTree_t(parent)\tdepth_m: %d\n", depth_m);
#endif
}
//--------------------------------------------- ~NewickNode_t() -----
NewickNode_t::~NewickNode_t()
{
// for (unsigned int i = 0; i < children_m.size(); i++)
// {
// delete children_m[i];
// }
}
//--------------------------------------------- stitch -----
// make children on the input node the children of the current node
// the children of the input node have the current node as a parent
void NewickNode_t::stitch( NewickNode_t *node )
{
#if DEBUG
fprintf(stderr,"in NewickNode_t::stitch()\n");
#endif
children_m = node->children_m;
int nChildren = children_m.size();
for ( int i = 0; i < nChildren; i++ )
{
children_m[i]->parent_m = this;
}
#if DEBUG
fprintf(stderr,"leaving NewickNode_t::stitch()\n");
#endif
}
//--------------------------------------------- addChild -----
NewickNode_t * NewickNode_t::addChild()
{
#if DEBUG
fprintf(stderr,"in addChild()\n");
#endif
NewickNode_t * child = new NewickNode_t(this);
#if DEBUG
fprintf(stderr,"before children_m.size()\n");
//fprintf(stderr,"children_m.size()=%d\n",(int)children_m.size());
#endif
children_m.push_back(child);
#if DEBUG
fprintf(stderr,"leaving addChild()\n");
#endif
return child;
}
//--------------------------------------------- NewickTree_t -----
NewickTree_t::NewickTree_t()
: root_m(NULL), nLeaves_m(0), minIdx_m(-1)
{
#if DEBUG
fprintf(stderr,"in NewickTree_t()\n");
#endif
}
//--------------------------------------------- ~NewickTree_t -----
NewickTree_t::~NewickTree_t()
{
delete root_m;
}
//--------------------------------------------- rmLeaf -----
// remove leaf with label s
void NewickTree_t::rmLeaf( string &s )
{
queue<NewickNode_t *> bfs2;
bfs2.push(root_m);
int numChildren;
NewickNode_t *pnode;
NewickNode_t *node;
bool go = true;
while ( !bfs2.empty() && go )
{
node = bfs2.front();
bfs2.pop();
numChildren = node->children_m.size();
if ( numChildren )
{
for (int i = 0; i < numChildren; i++)
{
bfs2.push(node->children_m[i]);
}
}
else if ( node->label == s )
{
pnode = node->parent_m;
// identify which element of pnode->children_m vector is s
int n = pnode->children_m.size();
for ( int i = 0; i < n; ++i )
if ( pnode->children_m[i]->label == s )
{
pnode->children_m.erase ( pnode->children_m.begin() + i );
go = false;
break;
}
}
} // end of while() loop
}
//--------------------------------------------- rmNodesWith1child -----
// remove nodes with only one child
void NewickTree_t::rmNodesWith1child()
{
queue<NewickNode_t *> bfs2;
bfs2.push(root_m);
int numChildren;
NewickNode_t *pnode;
NewickNode_t *node;
while ( !bfs2.empty() )
{
node = bfs2.front();
bfs2.pop();
while ( node->children_m.size() == 1 )
{
// finding node in a children array of the parent node
pnode = node->parent_m;
numChildren = pnode->children_m.size();
#if DEBUG_LFTT
fprintf(stderr, "\n\nNode %s has only one child %s; %s's parent is %s with %d children\n",
node->label.c_str(), node->children_m[0]->label.c_str(), node->label.c_str(),
pnode->label.c_str(), numChildren);
#endif
int i;
for ( i = 0; i < numChildren; i++)
{
if ( pnode->children_m[i] == node )
break;
}
if ( i == numChildren )
{
fprintf(stderr, "ERROR in %s at line %d: node %s cannot be found in %s\n",
__FILE__, __LINE__,(node->label).c_str(), (pnode->label).c_str());
exit(1);
}
#if DEBUG_LFTT
fprintf(stderr, "%s is the %d-th child of %s\n",
node->label.c_str(), i, pnode->label.c_str());
fprintf(stderr, "%s children BEFORE change: ", pnode->label.c_str());
for ( int j = 0; j < numChildren; j++)
fprintf(stderr, "%s ", pnode->children_m[j]->label.c_str());
#endif
node = node->children_m[0];
pnode->children_m[i] = node;
node->parent_m = pnode;
#if DEBUG_LFTT
fprintf(stderr, "\n%s children AFTER change: ", pnode->label.c_str());
for ( int j = 0; j < numChildren; j++)
fprintf(stderr, "%s ", pnode->children_m[j]->label.c_str());
#endif
}
numChildren = node->children_m.size();
if ( numChildren )
{
for (int i = 0; i < numChildren; i++)
{
bfs2.push(node->children_m[i]);
}
}
}
}
//--------------------------------------------- loadTree -----
bool NewickTree_t::loadTree(const char *file)
{
#define DEBUGLT 0
#if DEBUGLT
fprintf(stderr, "in NewickTree_t::loadTree()\n");
#endif
FILE * fp = fOpen(file, "r");
char str[256];
NewickNode_t * cur = new NewickNode_t();
int LINE = 1;
char c;
bool DONE = false;
int leafIdx = 0;
int count = 0;
while ((c = fgetc(fp)) != EOF)
{
#if DEBUGLT
fprintf(stderr,"c=|%c|\tcount=%d\t(cur==NULL)=%d\n", c, count,(int)(cur==NULL));
#endif
count++;
if (c == ';') { DONE = true;}
else if (c == '\n') { LINE++; }
else if (c == ' ') { }
else if (DONE)
{
cerr << "ERROR: Unexpected data after ; on line " << LINE << endl;
return false;
}
else if (c == '(')
{
cur = cur->addChild();
if (root_m == NULL) { root_m = cur; }
}
else if (c == ')') // '):bl,' or '):bl' or ')lable:bl'
{
c = fgetc(fp);
#if DEBUGLT
fprintf(stderr,"in ) next c=%c\n", c);
fprintf(stderr,"in ) minIdx_m=%d\n", minIdx_m);
#endif
cur->idx = minIdx_m;
minIdx_m--;
if ( c == ';' )
{
DONE = 1;
break;
}
else if ( c == ':' )
{
fscanf(fp, "%lf", &cur->branch_length);
}
else if ( isdigit(c) )
{
double bootVal;
fscanf(fp, "%lf:%lf", &bootVal, &cur->branch_length);
}
else if ( isalpha(c) ) // label:digit
{
#if DEBUGLT
fprintf(stderr,"in )alpha=%c\n", c);
#endif
char *brkt;
ungetc(c, fp);
int i = 0;
while ( isalnum(c) || c==':' || c=='.' || c=='_' || c=='-' )
{
c = fgetc(fp);
str[i++] = c;
}
str[--i] = '\0';
if (c != ',') { ungetc(c, fp); }
strtok_r(str, ":", &brkt);
cur->label = string(str);
cur->branch_length = 0; //atof(str);
#if DEBUGLT
fprintf(stderr, "label=%s\tbranch_length=%.2f\n", cur->label.c_str(), cur->branch_length);
#endif
}
else //if (c != ':' && !isdigit(c) && c !=';')
{
fprintf(stderr, "ERROR in %s at %d: Unexpected data, %c, after ')' in %s on line %d\n",
__FILE__, __LINE__, c, file, LINE);
return 0;
}
cur = cur->parent_m;
c = fgetc(fp);
if (c != ',') { ungetc(c, fp); }
}
else // 'name:bl' or 'name:bl,' - leaf
{
#if DEBUGLT
fprintf(stderr,"in name:bl=%c\n", c);
#endif
cur = cur->addChild();
nLeaves_m++;
cur->label += c;
while ((c = fgetc(fp)) != ':')
{
cur->label += c;
}
#if DEBUGLT
fprintf(stderr,"in name:bl label=%s\n", cur->label.c_str());
#endif
fscanf(fp, "%lf", &cur->branch_length);
cur->idx = leafIdx;
leafIdx++;
cur = cur->parent_m;
c = fgetc(fp);
if (c != ',') { ungetc(c, fp); }
}
} // end of while()
minIdx_m++;
if (!root_m)
{
fprintf(stderr,"ERROR in %s at line %d: Newick root is null!\n",__FILE__,__LINE__);
exit(EXIT_FAILURE);
}
return true;
}
//--------------------------------------------- writeNewickNode -----
static void writeNewickNode(NewickNode_t * node,
FILE * fp,
int depth)
{
if (!node) { return; }
int numChildren = node->children_m.size();
if (numChildren == 0)
{
if ( node->branch_length )
fprintf(fp, "%s:%0.20lf", node->label.c_str(), node->branch_length);
else
fprintf(fp, "%s:0.1", node->label.c_str());
}
else
{
//fprintf(fp, "(\n");
fprintf(fp, "(");
vector<NewickNode_t *> goodChildren;
for (int i = 0; i < numChildren; i++)
{
goodChildren.push_back(node->children_m[i]);
}
int numGoodChildren = goodChildren.size();
for (int i = 0; i < numGoodChildren; i++)
{
writeNewickNode(goodChildren[i], fp, depth+1);
if (i != numGoodChildren-1) { fprintf(fp, ","); }
//fprintf(fp, "\n");
}
//for (int i = 0; i < depth; i++) { fprintf(fp, " "); }
if ( node->label.empty() )
{
if ( node->branch_length)
fprintf(fp, "):%0.20lf", node->branch_length);
else
fprintf(fp, "):0.1");
}
else
{
if ( node->branch_length)
fprintf(fp, ")%s:%0.20lf", node->label.c_str(), node->branch_length);
else
fprintf(fp, ")%s:0.1", node->label.c_str());
}
if (depth == 0) { fprintf(fp, ";\n"); }
}
}
//--------------------------------------------- writeTree -----
void NewickTree_t::writeTree(FILE * fp)
{
if (root_m == NULL)
{
fprintf(stderr, "ERROR: Root is NULL!\n");
}
writeNewickNode(root_m, fp, 0);
fflush(fp);
}
//--------------------------------------------- writeTree -----
void NewickTree_t::writeTree(FILE * fp, NewickNode_t *node)
{
if (root_m == NULL)
{
fprintf(stderr, "ERROR: Root is NULL!\n");
}
writeNewickNode(node, fp, 0);
fflush(fp);
}
//--------------------------------------------- writeTree -----
void NewickTree_t::writeTree(FILE * fp, const string &nodeLabel)
{
if (root_m == NULL) fprintf(stderr, "ERROR: Root is NULL!\n");
queue<NewickNode_t *> bfs;
bfs.push(root_m);
NewickNode_t *node;
int numChildren;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
if ( node->label==nodeLabel )
{
writeNewickNode(node, fp, 0);
fflush(fp);
break;
}
numChildren = node->children_m.size();
if ( numChildren )
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
}
//--------------------------------------------- getDepth -----
// Determine the depth of a tree
int NewickTree_t::getDepth()
{
deque<NewickNode_t *> dfs;
dfs.push_front(root_m);
NewickNode_t *node;
deque<int> depth;
int maxDepth = 0;
depth.push_front(maxDepth);
while ( !dfs.empty() )
{
node = dfs.front();
dfs.pop_front();
int d = depth.front();
depth.pop_front();
if ( maxDepth < d )
maxDepth = d;
int numChildren = node->children_m.size();
if ( numChildren>0 )
{
for (int i = 0; i < numChildren; i++)
{
dfs.push_front(node->children_m[i]);
depth.push_front(d+1);
}
//if ( maxDepth < d+1 )
// maxDepth = d+1;
}
}
return maxDepth;
}
//--------------------------------------------- printTree -----
//
// prints tree to stdout with different depths at differen indentation levels
// indStr - indentation string
void NewickTree_t::printTree(bool withIdx, const char *indStr)
{
if (root_m == NULL)
{
fprintf(stderr, "ERROR: Root is NULL!\n");
}
// Determine the depth of the tree
int maxDepth = getDepth();
printf("\nmaxDepth: %d\n\n", maxDepth);
maxDepth++;
// Set up indent array of indentation strings
//const char *indStr=" ";
int indStrLen = strlen(indStr);
char **indent = (char **)malloc(maxDepth * sizeof(char*));
indent[0] = (char*)malloc(sizeof(char)); // empty string
indent[0][0] = '\0';
for ( int i = 1; i < maxDepth; i++ )
{
indent[i] = (char*)malloc(indStrLen * (i+1) * sizeof(char));
for ( int j = 0; j < i; j++ )
for ( int k = 0; k < indStrLen; k++ )
indent[i][j * indStrLen + k] = indStr[k];
indent[i][indStrLen * i] = '\0';
}
//Depth first search
deque<NewickNode_t *> dfs;
dfs.push_front(root_m);
NewickNode_t *node;
while ( !dfs.empty() )
{
node = dfs.front();
dfs.pop_front();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
if ( withIdx )
printf("%s%s(%d)\n",indent[node->depth_m],node->label.c_str(), node->idx);
else
//printf("%s%s\n",indent[node->depth_m],node->label.c_str());
printf("(%d)%s%s\n",node->depth_m,indent[node->depth_m],node->label.c_str());
}
else
{
if ( withIdx )
{
if ( node->label.empty() )
printf("%s*(%d)\n",indent[node->depth_m],node->idx);
else
printf("%s%s(%d)\n",indent[node->depth_m],node->label.c_str(), node->idx);
}
else
{
if ( node->label.empty() )
printf("%s*\n",indent[node->depth_m]);
else
//printf("%s%s\n",indent[node->depth_m],node->label.c_str());
printf("(%d)%s%s\n",node->depth_m,indent[node->depth_m],node->label.c_str());
}
for (int i = 0; i < numChildren; i++)
dfs.push_front(node->children_m[i]);
}
}
}
#if 0
//--------------------------------------------- printTreeBFS -----
void NewickTree_t::printTreeBFS()
{
if (root_m == NULL)
{
fprintf(stderr, "ERROR: Root is NULL!\n");
}
//Breath first search
queue<NewickNode_t *> bfs;
bfs.push(root_m);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
printf("%s%s\n",indent[node->depth_m],node->label.c_str());
}
else
{
printf("%s*\n",indent[node->depth_m]);
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
}
#endif
//--------------------------------------------- indexNewickNodes -----
void NewickTree_t::indexNewickNodes( map<int, NewickNode_t*> & idx2node)
/*
populates a hash table of <node index> => <pointer to the node>
returns number of leaves of the tree
*/
{
if ( idx2node_m.size() == 0 )
{
//Breath first search
queue<NewickNode_t *> bfs;
bfs.push(root_m);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
idx2node_m[node->idx] = node;
int numChildren = node->children_m.size();
if ( numChildren != 0 ) // leaf
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
}
idx2node = idx2node_m;
}
//--------------------------------------------- leafLabels -----
char ** NewickTree_t::leafLabels()
{
char **leafLabel = (char**)malloc((nLeaves_m) * sizeof(char*));
queue<NewickNode_t *> bfs;
bfs.push(root_m);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
leafLabel[node->idx] = strdup((node->label).c_str());
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
return leafLabel;
}
// ------------------------- assignIntNodeNames ------------------------
void NewickTree_t::assignIntNodeNames()
/*
Asssign i1, i2, i3 etc names to internal nodes, where iK label corresponds to index -K
*/
{
queue<NewickNode_t *> bfs;
bfs.push(root_m);
NewickNode_t *node;
//int negIdx; // holds negative index of a nod
char str[16]; // holds negIdx
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren ) // not leaf
{
//negIdx = -node->idx;
sprintf(str,"%d", -node->idx);
node->label = string("i") + string(str);
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
}
// ------------------------------ saveCltrMemb ------------------------
void NewickTree_t::saveCltrMemb( const char *outFile,
vector<int> &nodeCut,
int *annIdx,
map<int, string> &idxToAnn)
/*
save clustering membership data to outFile
output file format:
<leaf ID> <cluster ID> <annotation str or NA if absent>
Parameters:
outFile - output file
nodeCut - min-node-cut
annIdx - annIdx[i] = <0-based index of the annotation string assigned to the i-th
element of data table>
annIdx[i] = -1 if the i-th element has no annotation
idxToAnn - idxToAnn[annIdx] = <annotation string associated with annIdx>
*/
{
map<int, NewickNode_t*> idx2node;
indexNewickNodes(idx2node);
FILE *file = fOpen(outFile,"w");
fprintf(file,"readId\tclstr\tannot\n");
int n = nodeCut.size();
for ( int i = 0; i < n; ++i )
{
if ( nodeCut[i] >= 0 )
{
fprintf(file,"%s\t%d\t%s\n",idx2node[nodeCut[i]]->label.c_str(),i,
idxToAnn[ annIdx[nodeCut[i]] ].c_str() );
}
else
{
queue<NewickNode_t *> bfs;
bfs.push(idx2node[nodeCut[i]]);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
fprintf(file,"%s\t%d\t%s\n",node->label.c_str(),i,
idxToAnn[ annIdx[node->idx] ].c_str() );
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
}
}
fclose(file);
}
// ------------------------------ saveCltrMemb2 ------------------------
void NewickTree_t::saveCltrMemb2( const char *outFile,
vector<int> &nodeCut,
int *annIdx,
map<int, string> &idxToAnn)
/*
save clustering membership data to outFile
output file format:
<cluster_1>:
<leaf1> <annotation of leaf1>
<leaf2> <annotation of leaf2>
...
...
Parameters:
outFile - output file
nodeCut - min-node-cut
annIdx - annIdx[i] = <0-based index of the annotation string assigned to the i-th
element of data table>
annIdx[i] = -1 if the i-th element has no annotation
idxToAnn - idxToAnn[annIdx] = <annotation string associated with annIdx>
*/
{
map<int, NewickNode_t*> idx2node;
indexNewickNodes(idx2node);
FILE *file = fOpen(outFile,"w");
int n = nodeCut.size();
for ( int i = 0; i < n; ++i )
{
fprintf(file,"Cluster %d:\n",i);
if ( nodeCut[i] >= 0 )
{
fprintf(file,"\t%s\t%s\n",idx2node[nodeCut[i]]->label.c_str(),
idxToAnn[ annIdx[nodeCut[i]] ].c_str() );
}
else
{
queue<NewickNode_t *> bfs;
bfs.push(idx2node[nodeCut[i]]);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
fprintf(file,"\t%s\t%s\n",node->label.c_str(),
idxToAnn[ annIdx[node->idx] ].c_str() );
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
}
}
fclose(file);
}
// this is going to be used to sort map<string,int> in saveCltrAnnStats()
class sort_map
{
public:
string key;
int val;
};
bool Sort_by(const sort_map& a ,const sort_map& b)
{
return a.val > b.val;
}
// ------------------------------ saveCltrAnnStats --------------------------------
void NewickTree_t::saveCltrAnnStats( const char *outFile,
vector<int> &nodeCut,
int *annIdx,
map<int, string> &idxToAnn)
/*
save annotation summary statistics of the clustering induced by nodeCut to outFile
output file format:
<cluster_1>:
<annotation 1,1> <count1,1> <perc1,1>
<annotation 1,2> <count1,2> <perc1,2>
...
...
<cluster_2>:
<annotation 2,1> <count2,1> <perc2,1>
<annotation 2,2> <count2,2> <perc2,2>
...
...
countX,Y is the count of leaves in cluster_X and Y-th annotation (sorted by count)
percX,Y is the percentage of these leaves in the given cluster
Parameters:
outFile - output file
nodeCut - min-node-cut
annIdx - annIdx[i] = <0-based index of the annotation string assigned to the i-th
element of data table>
annIdx[i] = -1 if the i-th element has no annotation
idxToAnn - idxToAnn[annIdx] = <annotation string associated with annIdx>
*/
{
map<int, NewickNode_t*> idx2node;
indexNewickNodes(idx2node);
FILE *file = fOpen(outFile,"w");
int n = nodeCut.size();
for ( int i = 0; i < n; ++i )
{
fprintf(file,"Cluster %d:\n",i);
if ( nodeCut[i] >= 0 )
{
fprintf(file,"\t%s\t1\t100%%\n", idxToAnn[ annIdx[nodeCut[i]] ].c_str() );
}
else
{
map<string,int> annCount; // count of a given annotation string in the subtree of a given cut-node
queue<NewickNode_t *> bfs;
bfs.push(idx2node[nodeCut[i]]);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
annCount[ idxToAnn[ annIdx[node->idx] ] ]++;
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
// printing annotation counts in the order of their counts
map<string,int>::iterator it;
vector< sort_map > v;
vector< sort_map >::iterator itv;
sort_map sm;
double sum = 0;
for (it = annCount.begin(); it != annCount.end(); ++it)
{
sm.key = (*it).first;
sm.val = (*it).second;
v.push_back(sm);
sum += sm.val;
}
sort(v.begin(),v.end(),Sort_by);
for (itv = v.begin(); itv != v.end(); ++itv)
fprintf(file,"\t%s\t%d\t%.1f%%\n", ((*itv).key).c_str(), (*itv).val, 100.0 * (*itv).val / sum);
if ( v.size() > 1 )
fprintf(file,"\tTOTAL\t%d\t100%%\n", (int)sum);
}
}
fclose(file);
}
// ------------------------------ saveNAcltrAnnStats ------------------------
vector<string> NewickTree_t::saveNAcltrAnnStats( const char *outFile,
vector<int> &nodeCut,
int *annIdx,
map<int, string> &idxToAnn)
/*
It is a version of saveCltrAnnStats() that reports only clusters containig query (NA) elements.
*/
{
map<int, NewickNode_t*> idx2node;
indexNewickNodes(idx2node);
FILE *file = fOpen(outFile,"w");
vector<string> selAnn; // vector of taxons which are memembers of clusters that contain query seqeunces
int n = nodeCut.size();
for ( int i = 0; i < n; ++i )
{
if ( nodeCut[i] < 0 )
{
map<string,int> annCount; // count of a given annotation string in the subtree of a given cut-node
queue<NewickNode_t *> bfs;
bfs.push(idx2node[nodeCut[i]]);
NewickNode_t *node;
bool foundNA = false;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
annCount[ idxToAnn[ annIdx[node->idx] ] ]++;
if ( annIdx[node->idx] == -2) foundNA = true;
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
// printing annotation counts in the order of their counts
if ( foundNA )
{
map<string,int>::iterator it;
vector< sort_map > v;
vector< sort_map >::iterator itv;
sort_map sm;
double sum = 0;
for (it = annCount.begin(); it != annCount.end(); ++it)
{
sm.key = (*it).first;
sm.val = (*it).second;
selAnn.push_back(sm.key);
v.push_back(sm);
sum += sm.val;
}
sort(v.begin(),v.end(),Sort_by);
fprintf(file,"Cluster %d:\n",i);
for (itv = v.begin(); itv != v.end(); ++itv)
fprintf(file,"\t%s\t%d\t%.1f%%\n", ((*itv).key).c_str(), (*itv).val, 100.0 * (*itv).val / sum);
if ( v.size() > 1 )
fprintf(file,"\tTOTAL\t%d\t100%%\n", (int)sum);
}
}
}
fclose(file);
return selAnn;
}
// ------------------------------ saveNAcltrAnnStats ------------------------
void NewickTree_t::saveNAcltrAnnStats( const char *outFileA, // file to with cluster stats of clusters with at least minNA query sequences
const char *outFileB, // file to with cluster stats of clusters with less than minNA query sequences
const char *outFileC, // file with reference IDs of sequences for clusters in outFileA
const char *outFileD, // file with taxons, for clusters in outFileA, with the number of sequences >= minAnn
vector<int> &nodeCut,
int *annIdx,
map<int, string> &idxToAnn,
int minNA,
int minAnn)
/*
It is a version of saveCltrAnnStats() that reports only clusters containig at
least minNA query sequences to outFileA and less than minNA sequences to
outFileB.
output vector contains taxons with at least minAnn elements (in a single cluster).
*/
{
map<int, NewickNode_t*> idx2node;
indexNewickNodes(idx2node);
FILE *fileA = fOpen(outFileA,"w");
FILE *fileB = fOpen(outFileB,"w");
FILE *fileC = fOpen(outFileC,"w");
int nCltrs = 0; // number of clusters with the number of query seq's >= minNA
int nTx = 0; // number of selected taxons from the above clusters with the number of reads >= minAnn
int nRef = 0; // number of reference sequence from the above clusters with taxons with the number of reads >= minAnn
map<string,bool> selTx; // hash table of selected taxons as in nTx; nTx = number of elements in selTx
int n = nodeCut.size();
for ( int i = 0; i < n; ++i )
{
if ( nodeCut[i] < 0 ) // internal node
{
map<string,int> annCount; // count of a given annotation string in the subtree of a given cut-node
queue<NewickNode_t *> bfs;
bfs.push(idx2node[nodeCut[i]]);
NewickNode_t *node;
int naCount = 0;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
annCount[ idxToAnn[ annIdx[node->idx] ] ]++;
if ( annIdx[node->idx] == -2) naCount++;
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
// printing annotation counts in the order of their counts
if ( naCount >= minNA )
{
nCltrs++;
map<string,int>::iterator it;
vector< sort_map > v;
vector< sort_map >::iterator itv;
sort_map sm;
double sum = 0;
for (it = annCount.begin(); it != annCount.end(); ++it)
{
sm.key = (*it).first;
sm.val = (*it).second;
v.push_back(sm);
sum += sm.val;
}
sort(v.begin(),v.end(),Sort_by);
fprintf(fileA,"Cluster %d:\n",i);
for (itv = v.begin(); itv != v.end(); ++itv)
fprintf(fileA,"\t%s\t%d\t%.1f%%\n", ((*itv).key).c_str(), (*itv).val, 100.0 * (*itv).val / sum);
if ( v.size() > 1 )
fprintf(fileA,"\tTOTAL\t%d\t100%%\n", (int)sum);
// traverse the subtree again selecting sequences with annCount of the
// corresponding taxons that have at least minAnn elements to be printed
// in fileC
queue<NewickNode_t *> bfs2;
bfs2.push(idx2node[nodeCut[i]]);
NewickNode_t *node;
while ( !bfs2.empty() )
{
node = bfs2.front();
bfs2.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
if ( annCount[ idxToAnn[ annIdx[node->idx] ] ] > minAnn && idxToAnn[ annIdx[node->idx] ] != "NA" )
{
selTx[ idxToAnn[ annIdx[node->idx] ] ] = true;
nRef++;
fprintf(fileC, "%s\t%s\n",
node->label.c_str(),
idxToAnn[ annIdx[node->idx] ].c_str() );
}
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs2.push(node->children_m[i]);
}
}
}
}
else
{
map<string,int>::iterator it;
vector< sort_map > v;
vector< sort_map >::iterator itv;
sort_map sm;
double sum = 0;
for (it = annCount.begin(); it != annCount.end(); ++it)
{
sm.key = (*it).first;
sm.val = (*it).second;
v.push_back(sm);
sum += sm.val;
}
sort(v.begin(),v.end(),Sort_by);
fprintf(fileB,"Cluster %d:\n",i);
for (itv = v.begin(); itv != v.end(); ++itv)
fprintf(fileB,"\t%s\t%d\t%.1f%%\n", ((*itv).key).c_str(), (*itv).val, 100.0 * (*itv).val / sum);
if ( v.size() > 1 )
fprintf(fileB,"\tTOTAL\t%d\t100%%\n", (int)sum);
}
}
}
fclose(fileA);
fclose(fileB);
fclose(fileC);
// extracting only keys of selTx;
FILE *fileD = fOpen(outFileD,"w");
//vector<string> selTxV; // vector of taxons which are memembers of clusters that contain query seqeunces
for(map<string,bool>::iterator it = selTx.begin(); it != selTx.end(); ++it)
{
//selTxV.push_back(it->first);
fprintf(fileD,"%s\n",(it->first).c_str());
}
fclose(fileD);
nTx = selTx.size();
fprintf(stderr,"\nNumber of clusters with the number of query seq's >= %d: %d\n",minNA, nCltrs);
fprintf(stderr,"Number of selected taxons from the above clusters with the number of reads >= %d: %d\n",minAnn, nTx);
fprintf(stderr,"Number of selected reference sequence from the above clusters with taxons with the number of reads >= %d: %d\n",minAnn, nRef);
}
// comparison between integers producing descending order
bool gr (int i,int j) { return (i>j); }
// ------------------------------ saveNAtaxonomy0 ------------------------
void NewickTree_t::saveNAtaxonomy0( const char *outFile,
const char *logFile, // recording sizes of two most abundant taxa. If there is only one (besides query sequences), recording the number of elements of the dominant taxon and 0.
vector<int> &nodeCut,
int *annIdx,
map<int, string> &idxToAnn,
int minAnn,
int &nNAs,
int &nNAs_with_tx,
int &tx_changed,
int &nClades_modified)
/*
Assigning taxonomy to query sequences and modifying taxonomy of sequences with
non-monolityc clades using majority vote.
This is a special case of saveNAtaxonomy() that does taxonomy assignments of
query sequences from clusters containing at least minAnn reference
sequences. The taxonomy is based on the most abundant reference taxon.
I just extended the algorithm so that taxonomy of all elements of the given
cluster is set to the taxonomy of the cluster with the largest number of
sequences. If there are ties, that is two taxonomies are most abundant, then
there is no change.
*/
{
map<int, NewickNode_t*> idx2node;
indexNewickNodes(idx2node);
map<string,int> otuFreq; // <taxonomic rank name> => number of OTUs already assigned to it
FILE *file = fOpen(outFile,"w");
FILE *logfile = fOpen(logFile,"w");
nNAs = 0;
nNAs_with_tx = 0;
tx_changed = 0;
nClades_modified = 0;
int n = nodeCut.size();
for ( int i = 0; i < n; ++i )
{
map<string,int> annCount; // count of a given annotation string in the subtree of a given node
int naCount = 0;
queue<NewickNode_t *> bfs;
bfs.push(idx2node[nodeCut[i]]);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
//if ( i==262 )printf("\n%s\t%s", node->label.c_str(), idxToAnn[ annIdx[node->idx] ].c_str());
annCount[ idxToAnn[ annIdx[node->idx] ] ]++;
if ( annIdx[node->idx] == -2) naCount++;
if ( idxToAnn[ annIdx[node->idx] ] == "NA" ) nNAs++;
}
else
{
for (int j = 0; j < numChildren; j++)
{
bfs.push(node->children_m[j]);
}
}
}
//if ( i==262 )printf("\n\n");
//if ( naCount >= minNA && annCount.size() >= minAnn )
if ( annCount.size() >= (unsigned)minAnn ) // Assigning taxonomy to query sequences and modifying taxonomy of sequences with non-monolityc clades using majority vote
{
string cltrTx;
int maxCount = 0; // maximal count among annotated sequences in the cluster
map<string,int>::iterator it;
// Make sure there are not ties for max count
// Copying counts into a vector, sorting it and checking that the first two
// values (when sorting in the decreasing order) are not equal to each
// other.
vector<int> counts;
for (it = annCount.begin(); it != annCount.end(); ++it)
{
if ( (*it).first != "NA" )
counts.push_back((*it).second);
if ( (*it).first != "NA" && (*it).second > maxCount )
{
maxCount = (*it).second;
cltrTx = (*it).first;
}
}
sort( counts.begin(), counts.end(), gr );
#if 0
if ( i==231 )
{
fprintf(stderr,"\ncltrTx: %s\n", cltrTx.c_str());
fprintf(stderr,"\nCluster %d\nannCount\n",i);
for (it = annCount.begin(); it != annCount.end(); ++it)
{
fprintf(stderr,"\t%s\t%d\n", ((*it).first).c_str(), (*it).second);
}
fprintf(stderr,"\nsorted counts: ");
for (int j = 0; j < counts.size(); j++)
fprintf(stderr,"%d, ", counts[j]);
fprintf(stderr,"\n\n");
}
#endif
// Traverse the subtree again assigning taxonomy to all query sequences
int counts_size = counts.size();
if ( counts_size==1 || ( counts_size>1 && counts[0] > counts[1] ) )
{
nClades_modified++;
if ( counts_size > 1 )
fprintf(logfile, "%d\t%d\n", counts[0], counts[1]);
else
fprintf(logfile, "%d\t0\n", counts[0]);
queue<NewickNode_t *> bfs2;
bfs2.push(idx2node[nodeCut[i]]);
NewickNode_t *node;
while ( !bfs2.empty() )
{
node = bfs2.front();
bfs2.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
//if ( idxToAnn[ annIdx[node->idx] ] == "NA" && !cltrTx.empty() )
if ( idxToAnn[ annIdx[node->idx] ] !=cltrTx && !cltrTx.empty() )
{
//idxToAnn[ annIdx[node->idx] ] = cltrTx;
fprintf(file, "%s\t%s\n", node->label.c_str(), cltrTx.c_str());
if ( idxToAnn[ annIdx[node->idx] ] == "NA" )
nNAs_with_tx++;
else
tx_changed++;
}
}
else
{
for (int j = 0; j < numChildren; j++)
bfs2.push(node->children_m[j]);
}
} // end while ( !bfs2.empty() )
} // end if ( counts.size()==1 || ( counts.size()>1 && counts[0] > counts[1] ) )
} // end if ( naCount >= minNA && annCount.size() >= minAnn )
} // end for ( int i = 0; i < n; ++i )
fclose(file);
fclose(logfile);
}
// ------------------------------ saveNAtaxonomy ------------------------
void NewickTree_t::saveNAtaxonomy( const char *outFile,
const char *logFile,
const char *genusOTUsFile,
vector<int> &nodeCut,
int *annIdx,
map<int, string> &idxToAnn,
int minNA,
map<string, string> &txParent)
/*
Taxonomy assignments of query sequences from clusters containing either only
query sequences or query sequences with at least minNA query sequences and
minAnn reference sequences; In the last case the taxonomy is based on the most
abundant reference taxon. In the previous case, the taxonomy is determined by
the first ancestor with reference sequences. The content of reference sequences
determines taxonomy. Here are some rules.
If the ancestor contains reference sequences of the same species, then we
assign this species name to the OTU.
If the ref seq's are from the same genus, then we assign to the OTU the name of
the most abundant ref sequence. A justification for this comes from an
observation that often OTUs form a clade in the middle of which there are two
subtrees with two different species of the same genus. I hypothesize that this
is a clade of one species and the other one is an error. Therefore, the name of
the OTU should be the name of the more abundant species, and the other species
should be renamed to the other one.
Alternatively, the name could be of the form
<genus name>_<species1>.<species2>. ... .<speciesN>
where species1, ... , speciesN are species present in the ancestral node
If the ref seq's are from different genera, then we assign to the OTU a name
<tx rank>_OTUi
where tx rank is the taxonomic rank of common to all ref seq's of the ancestral subtree.
In the extreme case of Bacteria_OTU I am merging
*/
{
FILE *file = fOpen(outFile,"w");
FILE *fh = fOpen(logFile,"w");
FILE *genusFH = fOpen(genusOTUsFile,"w");
//map<string,bool> selTx; // hash table of selected taxons as in nTx; nTx = number of elements in selTx
map<int, NewickNode_t*> idx2node;
indexNewickNodes(idx2node);
map<string,int> otuFreq; // <taxonomic rank name> => number of OTUs already assigned to it
int n = nodeCut.size();
for ( int i = 0; i < n; ++i )
{
//if ( nodeCut[i] < 0 ) // internal node
{
map<string,int> annCount; // count of a given annotation string in the subtree of a given cut-node
queue<NewickNode_t *> bfs;
bfs.push(idx2node[nodeCut[i]]);
NewickNode_t *node;
int naCount = 0;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
annCount[ idxToAnn[ annIdx[node->idx] ] ]++;
if ( annIdx[node->idx] == -2) naCount++;
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
if ( naCount >= minNA )
{
string cltrTx; // = "Unclassified"; // taxonomy for all query reads of the cluster with no annotated sequences
if ( annCount.size() > 1 ) // there is at least one annotated element; setting cltrTx to annotation with the max frequency
{
int maxCount = 0; // maximal count among annotated sequences in the cluster
map<string,int>::iterator it;
for (it = annCount.begin(); it != annCount.end(); ++it)
{
if ( (*it).first != "NA" && (*it).second > maxCount )
{
maxCount = (*it).second;
cltrTx = (*it).first;
}
}
}
else // there are no annotated sequences in the cluster; we are looking for the nearest ancestral node with known taxonomy
{
node = idx2node[nodeCut[i]]; // current node
node = node->parent_m; // looking at the parent node
map<string,int> sppFreq;
int nSpp = cltrSpp(node, annIdx, idxToAnn, sppFreq); // table of species frequencies in the subtree of 'node'
while ( nSpp==0 ) // if the parent node does not have any annotation sequences
{
node = node->parent_m; // move up to its parent node
nSpp = cltrSpp(node, annIdx, idxToAnn, sppFreq);
}
// Debug
// fprintf(stderr, "\n--- i: %d\tCluster %d\n", i, node->idx);
// fprintf(stderr,"Number of species detected in the Unassigned node: %d\n",nSpp);
// besides writing frequencies I am finding taxonomic parents of each species
map<string,int> genus; // this is a map not vector so that I avoid duplication and find out frequence of a genus
map<string,int>::iterator it;
for ( it = sppFreq.begin(); it != sppFreq.end(); it++ )
{
//if ( (*it).first != "NA" )
//fprintf(fh, "%s\t%d\n", ((*it).first).c_str(), (*it).second);
if ( !txParent[(*it).first].empty() )
genus[ txParent[(*it).first] ] += (*it).second;
}
#if 0
// Checking of there is more than one genus present
// If so, we are going higher until we get only one taxonomic rank.
int nRks = genus.size();
map<string,int> txRk = genus; // taxonomic rank
map<string,int> pTxRk; // parent taxonomic rank
while ( nRks>1 )
{
for ( it = txRk.begin(); it != txRk.end(); it++ )
if ( !txParent[(*it).first].empty() )
pTxRk[ txParent[(*it).first] ]++;
// fprintf(fh, "\nTx Rank Frequencies\n");
// for ( it = pTxRk.begin(); it != pTxRk.end(); it++ )
// fprintf(fh, "%s\t%d\n", ((*it).first).c_str(), (*it).second);
nRks = pTxRk.size();
txRk = pTxRk;
pTxRk.clear();
// Debug
// fprintf(stderr,"nRks: %d\n",nRks);
}
it = txRk.begin();
string otuRank = (*it).first;
#endif
// assign OTU ID
if ( genus.size() == 1 ) // assign species name of the most frequent OTU
{
int maxCount = 0; // maximal count among annotated sequences in the cluster
map<string,int>::iterator it;
for (it = sppFreq.begin(); it != sppFreq.end(); ++it)
{
if ( (*it).first != "NA" && (*it).second > maxCount )
{
maxCount = (*it).second;
cltrTx = (*it).first;
}
}
}
else
{
// assigning the same OTU id to all OTUs with the same sppFreq profile
string sppProf;
map<string,int>::iterator it;
for (it = sppFreq.begin(); it != sppFreq.end(); ++it)
{
if ( (*it).first != "NA" )
{
sppProf += (*it).first;
}
}
int maxCount = 0; // maximal count among genera
string otuGenus;
for (it = genus.begin(); it != genus.end(); ++it)
{
if ( (*it).first != "NA" && (*it).second > maxCount )
{
maxCount = (*it).second;
otuGenus = (*it).first;
}
}
it = otuFreq.find(sppProf);
int k = 1;
if ( it != otuFreq.end() )
k = it->second + 1;
otuFreq[sppProf] = k;
char kStr[8];
sprintf(kStr,"%d",k);
cltrTx = otuGenus + string("_OTU") + string(kStr);
}
// Writing sppFreq to log file
fprintf(fh,"\n==== %s\tAncestral node ID: %d ====\n\n",cltrTx.c_str(), node->idx);
fprintf(fh, "-- Species Frequencies\n");
int totalSppLen = 0;
for ( it = sppFreq.begin(); it != sppFreq.end(); it++ )
{
fprintf(fh, "%s\t%d\n", ((*it).first).c_str(), (*it).second);
totalSppLen += ((*it).first).length();
}
// For each species of sppFreq, determine its taxonomy parent and write them to the log file
fprintf(fh, "\n-- Genus Frequencies\n");
for ( it = genus.begin(); it != genus.end(); it++ )
fprintf(fh, "%s\t%d\n", ((*it).first).c_str(), (*it).second);
if ( genus.size() == 1 ) // for genus OTUs print OTU name, ancestral node ID and species names into genusOTUsFile
{
//fprintf(stderr, "%s\t genus.size(): %d\n", cltrTx.c_str(), (int)genus.size());
// number of quary sequences in the OTU
it = sppFreq.find("NA");
if ( it == sppFreq.end() )
fprintf(stderr,"ERROR: OTU %s does not contain any quary sequences\n",cltrTx.c_str());
// OTU_ID, number of query sequences in the OTU, ID of the ancestral node that contains ref sequences
fprintf(genusFH,"%s\t%d\t%d\t",cltrTx.c_str(), (*it).second, node->idx);
int n = sppFreq.size();
char *sppStr = (char*)malloc((totalSppLen+n+1) * sizeof(char));
sppStr[0] = '\0';
int foundSpp = 0;
for ( it = sppFreq.begin(); it != sppFreq.end(); it++ )
{
if ( (*it).first != "NA" && (*it).first != "Unclassified" )
{
if ( foundSpp )
strncat(sppStr, ":",1);
strncat(sppStr, ((*it).first).c_str(), ((*it).first).length());
foundSpp = 1;
}
}
fprintf(genusFH,"%s\n", sppStr);
free(sppStr);
}
#if 0
// Higher taxonomic order frequencies
nRks = genus.size();
txRk = genus; // taxonomic rank
pTxRk.clear(); // parent taxonomic rank
while ( nRks>1 )
{
for ( it = txRk.begin(); it != txRk.end(); it++ )
if ( !txParent[(*it).first].empty() )
pTxRk[ txParent[(*it).first] ]++;
fprintf(fh, "\n-- Tx Rank Frequencies\n");
for ( it = pTxRk.begin(); it != pTxRk.end(); it++ )
fprintf(fh, "%s\t%d\n", ((*it).first).c_str(), (*it).second);
nRks = pTxRk.size();
txRk = pTxRk;
pTxRk.clear();
}
#endif
//Debugging
//fprintf(stderr,"OTU ID: %s\n",cltrTx.c_str());
} // end if ( annCount.size() > 1 )
// traverse the subtree again assigning taxonomy to all query sequences
queue<NewickNode_t *> bfs2;
bfs2.push(idx2node[nodeCut[i]]);
NewickNode_t *node;
while ( !bfs2.empty() )
{
node = bfs2.front();
bfs2.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
if ( idxToAnn[ annIdx[node->idx] ] == "NA" )
{
fprintf(file, "%s\t%s\n", node->label.c_str(), cltrTx.c_str());
}
}
else
{
for (int i = 0; i < numChildren; i++)
bfs2.push(node->children_m[i]);
}
} // end while ( !bfs2.empty() )
} // if ( naCount >= minNA )
} // end if ( nodeCut[i] < 0 ) // internal node
} // end for ( int i = 0; i < n; ++i )
fclose(fh);
fclose(genusFH);
fclose(file);
}
// ------------------------------ cltrSpp ------------------------
// Traverses the subtree of the current tree rooted at '_node' and finds
// annotation strings (taxonomies) of reference sequences present in the subtree
// (if any). sppFreq is the frequency table of found species.
//
// Returns the size of sppFreq
//
int NewickTree_t::cltrSpp(NewickNode_t *_node,
int *annIdx,
map<int, string> &idxToAnn,
map<string,int> &sppFreq)
{
queue<NewickNode_t *> bfs;
bfs.push(_node);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
sppFreq[ idxToAnn[ annIdx[node->idx] ] ]++;
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
return int(sppFreq.size());
}
// ------------------------------ maxAnn ------------------------
// traverse the subtree of the current tree rooted at '_node' and find annotation
// string with max frequency Return empty string if there are no annotation
// sequences in the subtree.
string NewickTree_t::maxAnn( NewickNode_t *_node,
int *annIdx,
map<int, string> &idxToAnn)
{
map<string,int> annCount; // count of a given annotation string in the subtree of the given node
queue<NewickNode_t *> bfs;
bfs.push(_node);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
annCount[ idxToAnn[ annIdx[node->idx] ] ]++;
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
string cltrTx; // = "Unclassified"; // taxonomy for all query reads of the cluster with no annotated sequences
if ( annCount.size() > 1 ) // there is at least one annotated element; setting cltrTx to annotation with the max frequency
{
int maxCount = 0; // maximal count among annotated sequences in the cluster
map<string,int>::iterator it;
for (it = annCount.begin(); it != annCount.end(); ++it)
{
if ( (*it).first != "NA" && (*it).second > maxCount )
{
maxCount = (*it).second;
cltrTx = (*it).first;
}
}
}
return cltrTx;
}
// ------------------------------ findAnnNode ------------------------
// Find a node in lable 'label'
NewickNode_t* NewickTree_t::findAnnNode(std::string label)
{
queue<NewickNode_t *> bfs;
bfs.push(root_m);
NewickNode_t *node = 0;
NewickNode_t *searchedNode = 0;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
if ( node->label == label )
{
searchedNode = node;
break;
}
int numChildren = node->children_m.size();
if ( numChildren ) // not leaf
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
return searchedNode;
}
// ------------------------------ printGenusTrees ------------------------
// For each genus print a subtree rooted at the root nodes of the genus
// * to each genus assign a vector of species/OTU's cut-nodes generated by vicut
// * find a node with the smallest depth (from the root)
// * walk ancestors of this node until all OTU nodes are in the subtree of that node
// * print that tree to a file
void NewickTree_t::printGenusTrees( const char *outDir,
vector<int> &nodeCut,
int *annIdx,
int minNA,
map<int, string> &idxToAnn,
map<string, string> &txParent)
{
//fprintf(stderr,"Entering printGenusTrees()\n");
char s[1024];
sprintf(s,"mkdir -p %s",outDir);
system(s);
// === Assign to each genus a vector of species/OTU nodes
map<string, vector<NewickNode_t*> > genusSpp; // <genus> => vector of OTU/species node
map<int, NewickNode_t*> idx2node;
indexNewickNodes(idx2node);
int n = nodeCut.size();
for ( int i = 0; i < n; ++i )
{
//fprintf(stderr,"i: %d\r", i);
if ( nodeCut[i] < 0 ) // internal node
{
map<string,int> annCount; // count of a given annotation string in the subtree of a given cut-node
queue<NewickNode_t *> bfs;
bfs.push(idx2node[nodeCut[i]]);
NewickNode_t *node;
int naCount = 0;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
annCount[ idxToAnn[ annIdx[node->idx] ] ]++;
if ( annIdx[node->idx] == -2) naCount++;
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
if ( naCount >= minNA )
{
string cltrTx; // taxonomy for all query reads of the cluster with no annotated sequences
if ( annCount.size() > 1 ) // there is at least one annotated element; setting cltrTx to annotation with the max frequency
{
int maxCount = 0; // maximal count among annotated sequences in the cluster
map<string,int>::iterator it;
for (it = annCount.begin(); it != annCount.end(); ++it)
{
if ( (*it).first != "NA" && (*it).second > maxCount )
{
maxCount = (*it).second;
cltrTx = (*it).first;
}
}
genusSpp[ txParent[ cltrTx ] ].push_back( idx2node[nodeCut[i]] );
}
else // there are no annotated sequences in the cluster; we are looking for the nearest ancestral node with known taxonomy
{
//fprintf(stderr, "In if ( naCount >= minNA ) else\n");
node = idx2node[nodeCut[i]]; // current node
node = node->parent_m; // looking at the parent node
map<string,int> sppFreq;
int nSpp = cltrSpp(node, annIdx, idxToAnn, sppFreq); // table of species frequencies in the subtree of 'node'
while ( nSpp==0 ) // if the parent node does not have any annotation sequences
{
node = node->parent_m; // move up to its parent node
nSpp = cltrSpp(node, annIdx, idxToAnn, sppFreq);
}
//fprintf(stderr, "nSpp: %d\n", nSpp);
map<string,int> genus; // this is a map not vector so that I avoid duplication and find out frequence of a genus
map<string,int>::iterator it;
for ( it = sppFreq.begin(); it != sppFreq.end(); it++ )
{
if ( !txParent[(*it).first].empty() )
genus[ txParent[(*it).first] ]++;
}
//fprintf(stderr, "genus.size(): %d\n", (int)genus.size());
if ( genus.size() == 1 ) //
{
it = genus.begin();
//fprintf(stderr,"genus: %s\n", (*it).first.c_str());
genusSpp[ (*it).first ].push_back( node );
}
} // end if ( annCount.size() > 1 )
} // if ( naCount >= minNA )
} // end if ( nodeCut[i] < 0 ) // internal node
} // end for ( int i = 0; i < n; ++i )
// === For each genus, find a node with the smallest depth (from the root)
// === Walk this node until all OTU nodes are in the subtree of that node
// === Print that tree to a file
map<string, vector<NewickNode_t*> >::iterator itr;
for ( itr = genusSpp.begin(); itr != genusSpp.end(); itr++ )
{
vector<NewickNode_t*> v = (*itr).second;
int vn = (int)v.size();
//Debugging
// fprintf(stderr,"%s: ", (*itr).first.c_str());
// for ( int j = 0; j < vn; j++ )
// fprintf(stderr,"(%d, %d) ", v[j]->idx, v[j]->depth_m);
// fprintf(stderr,"\n");
NewickNode_t* minDepthNode = v[0];
int minDepth = v[0]->depth_m;
for ( int j = 1; j < vn; j++ )
{
if ( v[j]->depth_m < minDepth )
{
minDepth = v[j]->depth_m;
minDepthNode = v[j];
}
}
NewickNode_t* node = minDepthNode->parent_m;
bool foundParentNode = hasSelSpp(node, v); // looking for a parent node of all elements of v
while ( foundParentNode==false )
{
node = node->parent_m; // move up to its parent node
foundParentNode = hasSelSpp(node, v);
}
// write subtree rooted in node to a file
int n1 = strlen(outDir);
int n2 = ((*itr).first).length();
char *outFile = (char*)malloc((n1+n2+1+5)*sizeof(char));
strcpy(outFile,outDir);
strcat(outFile,((*itr).first).c_str());
strcat(outFile,".tree");
FILE *fh = fOpen(outFile,"w");
writeTree(fh, node);
fclose(fh);
// write leaf labels to a file
vector<string> leaves;
leafLabels(node, leaves);
char *idsFile = (char*)malloc((n1+n2+1+5)*sizeof(char));
strcpy(idsFile,outDir);
strcat(idsFile,((*itr).first).c_str());
strcat(idsFile,".ids");
writeStrVector(idsFile, leaves);
}
}
// ------------------------------ hasSelSpp ------------------------
// Traverses the subtree of the current tree rooted at '_node'
// and checks if that tree contains all elements of v
//
// Returns true if all elements of v are in the subtree of _node
//
bool NewickTree_t::hasSelSpp(NewickNode_t *_node,
vector<NewickNode_t*> &v)
{
queue<NewickNode_t *> bfs;
bfs.push(_node);
NewickNode_t *node;
int countFoundNodes = 0; // count of nodes of v found in the subtree of _node
// table of indixes of nodes of v; return values of the table are not used
// the table is used only to find is a node is in v
map<int,bool> V;
int n = (int)v.size();
for ( int i = 0; i < n; i++ )
V[v[i]->idx] = true;
map<int,bool>::iterator it;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
it = V.find(node->idx);
if ( it != V.end() )
countFoundNodes++;
int numChildren = node->children_m.size();
if ( numChildren!=0 ) // internal node
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
return countFoundNodes == (int)v.size();
}
//--------------------------------------------- leafLabels -----
// Given a node in the tree, the routine gives leaf labels
// of the subtree rooted at 'node'.
void NewickTree_t::leafLabels(NewickNode_t *_node, vector<string> &leaves)
{
leaves.clear();
queue<NewickNode_t *> bfs;
bfs.push(_node);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
leaves.push_back( node->label );
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
}
//--------------------------------------------- leafLabels -----
// Given a node in the tree, the routine returns a vector of pointes to leaf nodes
// of the subtree rooted at 'node'.
void NewickTree_t::leafLabels(NewickNode_t *_node, vector<NewickNode_t *> &leaves)
{
queue<NewickNode_t *> bfs;
bfs.push(_node);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
leaves.push_back( node );
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
}
//--------------------------------------------- leafLabels -----
// Given a node in the tree, the routine returns a vector of pointes to leaf nodes
// (excluding a selected node) of the subtree rooted at 'node'.
void NewickTree_t::leafLabels(NewickNode_t *_node, vector<NewickNode_t *> &leaves, NewickNode_t *selNode)
{
queue<NewickNode_t *> bfs;
bfs.push(_node);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
if ( node != selNode )
leaves.push_back( node );
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
}
//--------------------------------------------- leafLabels -----
// Given a node in the tree, the routine gives leaf labels
// of the subtree rooted at 'node'.
void NewickTree_t::leafLabels(NewickNode_t *_node, set<string> &leaves)
{
queue<NewickNode_t *> bfs;
bfs.push(_node);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
leaves.insert( node->label );
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
}
//--------------------------------------------- getSppProfs -----
void NewickTree_t::getSppProfs( vector<sppProf_t*> &sppProfs,
vector<int> &nodeCut,
int *annIdx,
int minNA,
map<int, string> &idxToAnn,
map<string, string> &txParent)
/*
Given nodeCut + some other parameters
populate a vector of pointers to sppProf_t's
with i-th element of sppProfs corresponding to the i-th
node cut in nodeCut.
*/
{
map<int, NewickNode_t*> idx2node;
indexNewickNodes(idx2node);
int n = nodeCut.size();
for ( int i = 0; i < n; ++i )
{
map<string,int> annCount; // count of a given annotation string in the subtree of a given cut-node
queue<NewickNode_t *> bfs;
bfs.push(idx2node[nodeCut[i]]);
NewickNode_t *node;
int naCount = 0;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
annCount[ idxToAnn[ annIdx[node->idx] ] ]++;
if ( annIdx[node->idx] == -2) naCount++;
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
if ( naCount >= minNA )
{
map<string,int> sppFreq;
node = idx2node[nodeCut[i]]; // current node
NewickNode_t * ancNode;
if ( annCount.size() > 1 ) // there is at least one annotated element; setting cltrTx to annotation with the max frequency
{
cltrSpp(node, annIdx, idxToAnn, sppFreq); // table of species frequencies in the subtree of 'node'
ancNode = node;
}
else // there are no annotated sequences in the cluster; we are looking for the nearest ancestral node with known taxonomy
{
ancNode = node->parent_m; // looking at the parent node
int nSpp = cltrSpp(ancNode, annIdx, idxToAnn, sppFreq); // table of species frequencies in the subtree of 'node'
while ( nSpp==0 ) // if the parent node does not have any annotation sequences
{
ancNode = ancNode->parent_m; // move up to its parent node
nSpp = cltrSpp(ancNode, annIdx, idxToAnn, sppFreq);
}
//ancNode = ancNode->parent_m;
}
sppProf_t *sppProf = new sppProf_t();
sppProf->node = node;
sppProf->ancNode = ancNode;
sppProf->sppFreq = sppFreq;
sppProfs.push_back( sppProf );
}
}
}
#if 0
//--------------------------------------------- strMap2Set -----
set<string> NewickTree_t::strMap2Set(map<string,int> &sppFreq)
/*
Extracts keys from map<string,int> and puts them in to a set<string>
*/
{
set<string> sppSet;
map<string,int>::iterator it;
for (it = sppFreq.begin(); it != sppFreq.end(); ++it)
{
if ( (*it).first != "NA" )
{
sppSet.insert( (*it).first );
}
}
return sppSet;
}
#endif
//--------------------------------------------- strMap2Str -----
string NewickTree_t::strMap2Str(map<string,int> &sppFreq)
/*
Extracts keys from map<string,int>, sorts them and then concatenates them in to a string
*/
{
vector<string> spp;
map<string,int>::iterator it;
for (it = sppFreq.begin(); it != sppFreq.end(); ++it)
{
if ( (*it).first != "NA" )
{
spp.push_back( (*it).first );
}
}
sort (spp.begin(), spp.end());
string sppStr = spp[0];
int n = spp.size();
for ( int i = 1; i < n; i++ )
sppStr += string(".") + spp[i];
return sppStr;
}
//--------------------------------------------- getAncRoots -----
void NewickTree_t::getAncRoots(vector<sppProf_t*> &sppProfs,
vector<sppProf_t*> &ancRootProfs) // ancestral root nodes
/*
Finding root ancestral nodes, which are ancestral nodes of
sppProfs, such that on the path from the ancestral node to the root of the tree
there a no other ancestral nodes with the same species profile (excluding frequencies)
*/
{
// creating a table of indices of all ancestral nodes except those which are root_m or whose parent is root_m
// for the ease of identifying ancestral nodes on the path to the root_m
map<int, int> ancNodes;
int n = sppProfs.size();
for ( int i = 0; i < n; ++i )
{
NewickNode_t *node = sppProfs[i]->ancNode;
if ( node != root_m && node->parent_m != root_m )
{
//node = node->parent_m;
//fprintf(stderr,"i: %d\tidx: %d\r",i,node->idx);
ancNodes[ node->idx ] = i;
}
}
// iterating over all ancestral nodes and checking which of them have no other
// ancestral nodes on the path to root_m
for ( int i = 0; i < n; ++i )
{
if ( sppProfs[i]->ancNode == sppProfs[i]->node // cut node with some reference sequences in its subtree
|| sppProfs[i]->ancNode == root_m
|| (sppProfs[i]->ancNode)->parent_m == root_m )
{
ancRootProfs.push_back( sppProfs[i] );
}
else
{
NewickNode_t *node = sppProfs[i]->ancNode;
map<int,int>::iterator it;
while ( node != root_m )
{
if ( (it = ancNodes.find( node->idx )) != ancNodes.end() && // walking to the root_m, another ancestral node was found
strMap2Str(sppProfs[i]->sppFreq) == strMap2Str( sppProfs[it->second]->sppFreq ) ) // it->second is the index of the ancestral node in sppProfs that was found on the path to root_m
break;
node = node->parent_m;
}
if ( node == root_m ) // no ancestral nodes were found on the path to the root_m
ancRootProfs.push_back( sppProfs[i] );
}
}
}
//--------------------------------------------- rmTxErrors -----
void NewickTree_t::rmTxErrors( vector<sppProf_t*> &ancRootProfs,
int depth,
int *annIdx,
map<int, string> &idxToAnn)
/*
Changing taxonomic assignment in a situation when one species is contained in a
clade of another species of the same genus.
depth parameter controls how many ancestors we want to visit before making a decision.
If at the depth ancestor (going up towards the root) species frequencies are
1 (for the current node) and (depth-1) for other species of the same genus, then
sppFreq of the current node is replaced by the one of the other species nodes.
The modification are only applied to ancestral nodes with ancNode=node, because
others will have homogeneous clade structure by construction.
*/
{
int n = ancRootProfs.size();
for ( int i = 0; i < n; ++i )
{
if ( ancRootProfs[i]->ancNode == ancRootProfs[i]->node )
{
NewickNode_t *node = ancRootProfs[i]->ancNode;
for ( int j = 0; j < depth; j++ )
node = node->parent_m;
// compute sppFreq for node
map<string,int> sppFreq;
cltrSpp(node, annIdx, idxToAnn, sppFreq);
// finding max count species in the original node
// and comparing its frequency in sppFreq
//if ( sppFreq[ (ancRootProfs[i]->node)->label ] = sppFreq[
}
}
}
//--------------------------------------------- printTx -----
void NewickTree_t::printTx( const char *outFile,
vector<sppProf_t*> &ancRootProfs)
/*
Generating taxonomic assignment to all leaves of the tree.
The leaves of the subtree of a root ancestral node all have the same taxonomy
based on the majority vote at the species or genus level.
*/
{
FILE *fh = fOpen(outFile,"w");
int n = ancRootProfs.size();
for ( int i = 0; i < n; ++i )
{
NewickNode_t *node = ancRootProfs[i]->ancNode;
map<string,int> sppFreq = ancRootProfs[i]->sppFreq;
string cltrTx; // taxonomy for all query reads of the cluster with no annotated sequences
// determining taxonomy based on the majority vote
int maxCount = 0; // maximal species count
map<string,int>::iterator it;
for (it = sppFreq.begin(); it != sppFreq.end(); ++it)
{
if ( (*it).first != "NA" && (*it).second > maxCount )
{
maxCount = (*it).second;
cltrTx = (*it).first;
}
}
// propagating the taxonomy to all leaves of the subtree of the ancestral root node
vector<string> leaves;
leafLabels(node, leaves);
int m = leaves.size();
for ( int j = 0; j < m; j++ )
fprintf(fh, "%s\t%s\n", leaves[j].c_str(), cltrTx.c_str());
}
fclose(fh);
}
//---------------------------------------------------------- updateLabels ----
void NewickTree_t::updateLabels( strSet_t &tx2seqIDs )
/*
To test txSet2txTree() this routine updates tree labels so they
include the number of sequences associated with each node
*/
{
queue<NewickNode_t *> bfs;
bfs.push(root_m);
NewickNode_t *node;
strSet_t::iterator it;
char nStr[16];
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
if ( node != root_m )
{
it=tx2seqIDs.find( node->label );
if ( it != tx2seqIDs.end() )
{
int n = (it->second).size();
sprintf(nStr,"%d",n);
node->label += string("{") + string(nStr) + string("}");
}
else
{
fprintf(stderr,"ERROR in %s at line %d: node with label %s not found in tx2seqIDs map\n",
__FILE__,__LINE__, node->label.c_str());
exit(1);
}
}
int numChildren = node->children_m.size();
if ( numChildren )
{
for (int i = 0; i < numChildren; i++)
bfs.push(node->children_m[i]);
}
}
}
//---------------------------------------------------------- txSet2txTree ----
void NewickTree_t::txSet2txTree( strSet_t &tx2seqIDs )
/*
tx2seqIDs maps tx (assumed to be labels of the leaves of the tree) into set of
seqIDs corresponding to the given taxon, tx.
The routine extends tx2seqIDs to map also internal nodes to seqIDs associated
with the leaves of the corresponding subtree.
*/
{
queue<NewickNode_t *> bfs;
bfs.push(root_m);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren )
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
set<string> seqIDs; // sequence IDs from all leaves of the subtree of node->children_m[i]
set<string> leaves;
leafLabels(node->children_m[i], leaves);
set<string>::iterator it;
for (it=leaves.begin(); it!=leaves.end(); it++)
{
set<string> ids = tx2seqIDs[ *it ];
set_union( seqIDs.begin(), seqIDs.end(),
ids.begin(), ids.end(),
inserter(seqIDs, seqIDs.begin()) );
}
if ( (node->children_m[i])->label.empty() )
{
cerr << "ERROR in " << __FILE__ << " at line " << __LINE__ << ": internal node is missing lable\n" << endl;
}
tx2seqIDs[ (node->children_m[i])->label ] = seqIDs;
}
}
}
}
//---------------------------------------------------------- inodeTx ----
void NewickTree_t::inodeTx( const char *fullTxFile, map<string, string> &inodeTx )
/*
Creating <interna node> => <taxonomy> table inodeTx
*/
{
// parse fullTxFile that has the following structure
// BVAB1 g_Shuttleworthia f_Lachnospiraceae o_Clostridiales c_Clostridia p_Firmicutes d_Bacteria
// BVAB2 g_Acetivibrio f_Ruminococcaceae o_Clostridiales c_Clostridia p_Firmicutes d_Bacteria
// BVAB3 g_Acetivibrio f_Ruminococcaceae o_Clostridiales c_Clostridia p_Firmicutes d_Bacteria
// Dialister_sp._type_1 g_Dialister f_Veillonellaceae o_Clostridiales c_Clostridia p_Firmicutes d_Bacteria
const int NUM_TX = 7;
char ***txTbl;
int nRows, nCols;
readCharTbl( fullTxFile, &txTbl, &nRows, &nCols );
#if 0
fprintf(stderr,"fullTxFile txTbl:\n");
printCharTbl(txTbl, 10, nCols); // test
#endif
map<string, vector<string> > fullTx; // fullTx[speciesName] = vector of the corresponding higher rank taxonomies
// for example
// BVAB1 g_Shuttleworthia f_Lachnospiraceae o_Clostridiales c_Clostridia p_Firmicutes d_Bacteria
// corresponds to
// fullTx[BVAB1] = (g_Shuttleworthia, f_Lachnospiraceae, o_Clostridiales, c_Clostridia, p_Firmicutes, d_Bacteria)
charTbl2strVect( txTbl, nRows, nCols, fullTx);
map<string, vector<string> >::iterator it1;
#if 0
map<string, vector<string> >::iterator it1;
for ( it1 = fullTx.begin(); it1 != fullTx.end(); it1++ )
{
fprintf(stderr, "%s: ", (it1->first).c_str());
vector<string> v = it1->second;
for ( int i = 0; i < (int)v.size(); i++ )
fprintf(stderr, "%s ", v[i].c_str());
fprintf(stderr, "\n");
}
for ( it1 = fullTx.begin(); it1 != fullTx.end(); it1++ )
{
vector<string> v = it1->second;
fprintf(stderr, "%s: %d\n", (it1->first).c_str(), (int)v.size());
}
fprintf(stderr, "after\n");
#endif
// traverse the tree and for each internal node find consensus taxonomic rank
// of all leaves of the corresponding subtree
queue<NewickNode_t *> bfs;
bfs.push(root_m);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren ) // internal node
{
for (int i = 0; i < numChildren; i++)
bfs.push(node->children_m[i]);
vector<string> spp;
leafLabels(node, spp);
int txIdx;
set<string> tx;
set<string>::iterator it;
for ( txIdx = 0; txIdx < NUM_TX; txIdx++ )
{
tx.erase( tx.begin(), tx.end() ); // erasing all elements of tx
int n = spp.size();
for ( int j = 0; j < n; j++ )
{
it1 = fullTx.find( spp[j] );
if ( it1==fullTx.end() )
fprintf(stderr, "%s not found in fullTx\n", spp[j].c_str());
tx.insert( fullTx[ spp[j] ][txIdx] );
}
if ( tx.size() == 1 )
break;
}
it = tx.begin(); // now it points to the first and unique element of tx
inodeTx[ node->label ] = *it;
}
}
}
//---------------------------------------------------------- modelIdx ----
// populate model_idx fields of all nodes of the tree
//
// when node labels correspond to model labels model_idx is the index of the node
// label in MarkovChains2_t's modelIds_m
void NewickTree_t::modelIdx( vector<string> &modelIds )
{
map<string, int> modelIdx;
int n = modelIds.size();
for ( int i = 0; i < n; i++ )
modelIdx[ modelIds[i] ] = i;
queue<NewickNode_t *> bfs;
bfs.push(root_m);
NewickNode_t *node;
map<string, int>::iterator it;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
if ( node != root_m )
{
it = modelIdx.find( node->label );
if ( it != modelIdx.end() )
node->model_idx = modelIdx[ node->label ];
#if 0
else
fprintf(stderr, "ERROR in %s at line %d: Node label %s not found in modelIds\n",
__FILE__, __LINE__, (node->label).c_str());
#endif
}
int numChildren = node->children_m.size();
if ( numChildren ) // internal node
{
for (int i = 0; i < numChildren; i++)
bfs.push(node->children_m[i]);
}
}
}
// ----------------------------------------- readNewickNode() ---------------------------------
//
// This code was lifted/adopted from the spimap-1.1 package
// ~/devel/MCclassifier/packages/spimap-1.1/src
// http://compbio.mit.edu/spimap/
// https://academic.oup.com/mbe/article-lookup/doi/10.1093/molbev/msq189
//
float readDist( FILE *infile )
{
float dist = 0;
fscanf(infile, "%f", &dist);
return dist;
}
char readChar(FILE *stream, int &depth)
{
char chr;
do {
if (fread(&chr, sizeof(char), 1, stream) != 1) {
// indicate EOF
return '\0';
}
} while (chr == ' ' || chr == '\n');
// keep track of paren depth
if (chr == '(') depth++;
if (chr == ')') depth--;
return chr;
}
char readUntil(FILE *stream, string &token, const char *stops, int &depth)
{
char chr;
token = "";
while (true) {
chr = readChar(stream, depth);
if (!chr)
return chr;
// compare char to stop characters
for (const char *i=stops; *i; i++) {
if (chr == *i)
return chr;
}
token += chr;
}
}
string getIdent( int depth )
{
string identStr = "";
for ( int i = 0; i < depth; i++ )
{
identStr += string(" ");
}
return identStr;
}
NewickNode_t *readNewickNode(FILE *infile, NewickTree_t *tree, NewickNode_t *parent, int &depth)
{
#define DEBUG_RNN 0
#if DEBUG_RNN
string ident = getIdent( depth );
fprintf(stderr, "%sIn readNewickNode() depth: %d\n", ident.c_str(), depth);
#endif
char chr, char1;
NewickNode_t *node;
string token;
// read first character
if ( !(char1 = readChar(infile, depth)) )
{
fprintf(stderr, "\n\n\tERROR: Unexpected end of file\n\n");
exit(1);
}
if ( char1 == '(' ) // read internal node
{
int depth2 = depth;
if ( parent )
{
node = parent->addChild();
#if DEBUG_RNN
if ( depth )
{
string ident = getIdent( depth );
fprintf( stderr, "%sCurrently at depth: %d - Adding a child to a parent\n", ident.c_str(), depth );
}
else
{
fprintf( stderr, "Currently at depth: %d - Adding a child to a parent\n", depth );
}
#endif
}
else
{
node = new NewickNode_t();
tree->setRoot( node );
#if DEBUG_RNN
fprintf( stderr, "Currently at depth: %d - Creating a root\n", depth );
#endif
}
// updating node's depth
node->depth_m = depth - 1;
// read all child nodes at this depth
while ( depth == depth2 )
{
NewickNode_t *child = readNewickNode(infile, tree, node, depth);
if (!child)
return NULL;
}
// Assigning a numeric index to the node
node->idx = tree->getMinIdx();
tree->decrementMinIdx();
// read branch_length for this node
// this fragment assumes that the internal nodes do not have labels
char chr = readUntil(infile, token, "):,;", depth);
if ( !token.empty() ) // Reading node's label
{
node->label = trim(token.c_str());
#if DEBUG_RNN
string ident = getIdent( depth );
fprintf( stderr, "%sNode name: %s\n", ident.c_str(), token.c_str() );
#endif
}
if (chr == ':')
{
node->branch_length = readDist( infile );
#if DEBUG_RNN
string ident = getIdent( depth );
fprintf( stderr, "%snode->branch_length: %f\n", ident.c_str(), node->branch_length );
#endif
if ( !(chr = readUntil(infile, token, "):,;", depth)) )
return NULL;
}
//if (chr == ';' && depth == 0)
// return node;
#if DEBUG_RNN
string ident = getIdent( node->depth_m );
fprintf( stderr, "%sNode's depth: %d\n", ident.c_str(), node->depth_m );
#endif
return node;
}
else
{
// Parsing leaf
if (parent)
{
node = parent->addChild();
#if DEBUG_RNN
string ident = getIdent(depth);
fprintf( stderr, "%sCurrently at depth: %d - Found leaf: adding it as a child to a parent\n", ident.c_str(), depth );
#endif
}
else
{
fprintf( stderr, "\n\n\tERROR: Found leaf without a parent\n\n" );
exit(1);
}
// Assigning to the leaf a numeric index
node->idx = tree->leafCount();
tree->incrementLeafCount();
// updating leaf's depth
node->depth_m = depth;
// Reading leaf label
if ( !(chr = readUntil(infile, token, ":),", depth)) )
return NULL;
token = char1 + trim(token.c_str());
node->label = token;
#if DEBUG_RNN
string ident = getIdent( depth );
fprintf( stderr, "%sLeaf name: %s\tdepth: %d\tidx: %d\n", ident.c_str(), token.c_str(), node->depth_m, node->idx );
#endif
// read distance for this node
if (chr == ':')
{
node->branch_length = readDist( infile );
#if DEBUG_RNN
fprintf( stderr, "%sLeaf's branch length: %f\n", ident.c_str(), node->branch_length );
#endif
if ( !(chr = readUntil( infile, token, ":),", depth )) )
return NULL;
}
return node;
}
}
NewickTree_t *readNewickTree( const char *filename )
{
FILE *infile = fOpen(filename, "r");
int depth = 0;
NewickTree_t *tree = new NewickTree_t();
NewickNode_t * node = readNewickNode(infile, tree, NULL, depth);
tree->setRoot( node );
fclose(infile);
return tree;
}
| 77,729 | 29,928 |
#ifndef _C4_REGEN_HPP_
#define _C4_REGEN_HPP_
#include "c4/regen/enum.hpp"
#include "c4/regen/function.hpp"
#include "c4/regen/class.hpp"
#include "c4/regen/writer.hpp"
#include <c4/c4_push.hpp>
namespace c4 {
namespace regen {
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
struct Regen
{
std::string m_config_file_name;
std::string m_config_file_yml;
c4::yml::Tree m_config_data;
std::vector<EnumGenerator > m_gens_enum;
std::vector<ClassGenerator > m_gens_class;
std::vector<FunctionGenerator> m_gens_function;
std::vector<Generator* > m_gens_all;
Writer m_writer;
std::vector<SourceFile> m_src_files;
bool m_save_src_files;
ast::StringCollection m_strings;
public:
Regen() : m_save_src_files(false) {}
Regen(const char* config_file) : Regen()
{
load_config(config_file);
}
bool empty() const { return m_gens_all.empty(); }
void load_config(const char* file_name);
void save_src_files(bool yes) { m_save_src_files = yes; }
public:
template<class SourceFileNameCollection>
void gencode(SourceFileNameCollection c$$ collection, const char* db_dir=nullptr, const char* const* flags=nullptr, size_t num_flags=0)
{
ast::CompilationDb db(db_dir);
ast::Index idx;
ast::TranslationUnit unit;
yml::Tree workspace;
SourceFile buf;
if(m_save_src_files)
{
size_t fsz = 0;
for(const char* filename : collection)
{
C4_UNUSED(filename);
fsz++;
}
m_src_files.resize(fsz);
}
m_writer.begin_files();
size_t ifile = 0;
for(const char* filename : collection)
{
if( ! m_save_src_files)
{
buf.clear();
idx.clear();
}
SourceFile &sf = m_save_src_files ? m_src_files[ifile++] : buf;
if(db_dir)
{
unit.reset(idx, filename, db);
}
else
{
unit.reset(idx, filename, flags, num_flags);
}
sf.init_source_file(idx, unit);
sf.extract(m_gens_all.data(), m_gens_all.size());
sf.gencode(m_gens_all.data(), m_gens_all.size(), workspace);
m_writer.write(sf);
}
m_writer.end_files();
m_strings = std::move(idx.yield_strings());
}
template<class SourceFileNameCollection>
void print_output_filenames(SourceFileNameCollection c$$ collection)
{
Writer::set_type workspace;
for(const char* source_file : collection)
{
m_writer.insert_filenames(to_csubstr(source_file), &workspace);
}
for(auto c$$ name : workspace)
{
printf("%s\n", name.c_str());
}
}
private:
template<class GeneratorT>
void _loadgen(c4::yml::NodeRef const& n, std::vector<GeneratorT> *gens)
{
gens->emplace_back();
GeneratorT &g = gens->back();
g.load(n);
m_gens_all.push_back(&g);
}
};
} // namespace regen
} // namespace c4
#include <c4/c4_pop.hpp>
#endif /* _C4_REGEN_HPP_ */
| 3,450 | 1,105 |
#include "../include/aspose.h"
#include "../include/presentation.h"
#include "../include/slide.h"
#include "../include/islide_collection.h"
#include "../include/slide_size.h"
#include <phpcpp.h>
#include <iostream>
#include "../include/master-slide-collection.h"
#include "../include/image-collection.h"
using namespace Aspose::Slides;
using namespace Aspose::Slides::Export;
using namespace System;
using namespace System::Collections::Generic;
using namespace std;
using namespace System::IO;
namespace AsposePhp {
/**
* @brief PHP Constructor
*
* @param params Path to presentation file to read. This is optional. If not defined, an empty presentation will be created.
*/
void Presentation::__construct(Php::Parameters ¶ms)
{
this->load(params);
if(params.size() > 1) {
this->loadLicense(params);
}
}
/**
* @brief Loads license file
*
* @param params Has one param, the path
*
* @throw System::ArgumentException path is invalid
* @throw System::IO::FileNotFoundException File does not exist
* @throw System::UnauthorizedAccessException Has no right access file
* @throw System::Xml::XmlException File contains invalid XML
*
*/
void Presentation::loadLicense(Php::Parameters ¶ms) {
std::string licensePath = params[1].stringValue();
try {
SharedPtr<Aspose::Slides::License> lic = MakeObject<Aspose::Slides::License>();
lic->SetLicense(String(licensePath));
if(!lic->IsLicensed()) {
throw Php::Exception("Invalid license");
}
}
catch(System::ArgumentException &e) {
throw Php::Exception(e.what());
}
catch(System::IO::FileNotFoundException &e) {
throw Php::Exception(e.what());
}
catch(System::UnauthorizedAccessException &e) {
throw Php::Exception(e.what());
}
catch(System::Xml::XmlException &e) {
throw Php::Exception(e.what());
}
catch(System::InvalidOperationException &e) {
throw Php::Exception(e.what());
}
catch(...) {
throw Php::Exception("Unknown error. Unable to loead license file..");
}
}
/**
* @brief Loads a presentation file.
*
* @param params Path to presentation to read.
*
* @throw System::ArgumentException path is invalid
* @throw System::IO::FileNotFoundException File does not exist
* @throw System::UnauthorizedAccessException Has no right access file
* @return Php::Value
*/
Php::Value Presentation::load(Php::Parameters ¶ms) {
std::string path = params[0].stringValue();
// std::string licencePath = params[1].stringValue();
const String templatePath = String(path);
SharedPtr<LoadOptions> loadOptions = MakeObject<LoadOptions>();
try {
_pres = MakeObject<Aspose::Slides::Presentation>(templatePath);
_slides = _pres->get_Slides();
SharedPtr<PresentationFactory> pFactory = PresentationFactory::get_Instance();
_slideText = pFactory->GetPresentationText(templatePath, TextExtractionArrangingMode::Unarranged)->get_SlidesText();
}
catch(System::ArgumentException &e) {
throw Php::Exception(e.what());
}
catch(System::IO::FileNotFoundException &e) {
throw Php::Exception(e.what());
}
catch(System::UnauthorizedAccessException &e) {
throw Php::Exception(e.what());
}
catch(...) {
throw Php::Exception("Uknown error. Unable to loead input file..");
}
return this;
}
/**
* @brief Writes the presentaton to disk or returns it as byte array.
*
* @param params Output path. File must not exist.
* @param params file format.
* @param params AsArray if true, byte array will be returned.
*
* @throw System::IO::IOException cannot access path
* @throw System::UnauthorizedAccessException Has no right access file
*/
Php::Value Presentation::save(Php::Parameters ¶ms) {
String outfile = String(params[0].stringValue());
std::string fmt = params[1].stringValue();
bool asArray = params[2].boolValue();
SaveFormat format = SaveFormat::Ppt;
ArrayPtr<string> formats = new Array<string>(vector<string> {"ppt", "pptx"});
if(formats->IndexOf(fmt) != -1) {
if(fmt == "ppt") {
format = SaveFormat::Ppt;
} else if(fmt == "pptx") {
format = SaveFormat::Pptx;
}
try {
if(asArray) {
SharedPtr<MemoryStream> stream = MakeObject<MemoryStream>();
_pres->Save(stream, format);
vector<uint8_t> res = stream->ToArray()->data();
return Php::Array(res);
} else {
SharedPtr<Stream> stream = MakeObject<FileStream>(outfile, FileMode::Create);
_pres->Save(stream, format);
}
}
catch(System::IO::IOException &e) {
throw Php::Exception(e.what());
}
catch(System::UnauthorizedAccessException &e) {
throw Php::Exception(e.what());
}
catch(...) {
throw Php::Exception("Uknown error. Unable to write output file..");
}
} else {
throw Php::Exception("Uknown format.");
}
return nullptr;
}
/**
* @brief Clones the slide with given index.
*
* @param params 0 based index of the slide to be cloned
*
* @throw System::ArgumentOutOfRangeException slide index does not exist
* @throw Aspose::Slides::PptxEditException PPT modification failed.
*/
void Presentation::cloneSlide(Php::Parameters ¶ms) {
int slideNo = params[0].numericValue();
try {
_slides->AddClone(_slides->idx_get(slideNo));
}
catch(System::ArgumentOutOfRangeException &e) {
throw Php::Exception("Invalid index: " + to_string(slideNo));
}
catch(Aspose::Slides::PptxEditException &e) {
throw Php::Exception(e.what());
}
catch(...) {
throw Php::Exception("Uknown error. Unable to clone slide..");
}
}
/**
* @brief Returns all text from presentation as string. Does NOT include charts and tables.
*
* @param params An array with 2 string elements: a path to the presentation file and a
* type indicating which type of text should be returned. Type can be either of the following:
* - master
* - layout
* - notes
* - all
*
* @throw System::ArgumentException path is invalid
* @throw System::IO::FileNotFoundException File does not exist
* @throw System::UnauthorizedAccessException Has no right access file
* @return Php::Value
*/
Php::Value Presentation::getPresentationText(Php::Parameters ¶ms) {
std::string path = params[0].stringValue();
std::string type = params[1].stringValue();
String templatePath = String(path);
try {
SharedPtr<PresentationFactory> pFactory = PresentationFactory::get_Instance();
ArrayPtr<SharedPtr<ISlideText>> text = pFactory->GetPresentationText(templatePath, TextExtractionArrangingMode::Unarranged)->get_SlidesText();
string texts = "";
for (int i = 0; i < text->get_Length(); i++) {
if(type == "all") {
texts += text[i]->get_Text().ToUtf8String();
} else if(type == "master") {
texts += text[i]->get_MasterText().ToUtf8String();
} else if(type == "layout") {
texts += text[i]->get_LayoutText().ToUtf8String();
} else if(type == "notes") {
texts += text[i]->get_NotesText().ToUtf8String();
}
}
return texts;
}
catch(System::ArgumentException &e) {
throw Php::Exception(e.what());
}
catch(System::IO::FileNotFoundException &e) {
throw Php::Exception(e.what());
}
catch(System::UnauthorizedAccessException &e) {
throw Php::Exception(e.what());
}
}
/**
* @brief Returns the number of slides in presentation.
*
* @return Php::Value
*/
Php::Value Presentation::getNumberOfSlides() {
return _pres->get_Slides()->get_Count();
}
/**
* @brief Returns an array of slides as Slide objects.
*
* @return Php::Value
*/
Php::Value Presentation::getSlides() {
ISlideCollection* coll = new ISlideCollection(_slides);
return Php::Object("AsposePhp\\Slides\\ISlideCollection", coll);
}
/**
* @brief Returns slide size object
*
* @return Php::Value
*/
Php::Value Presentation::get_SlideSize() {
SlideSize * size = new SlideSize(_pres->get_SlideSize());
return Php::Object("AsposePhp\\Slides\\SlideSize", size);
}
Php::Value Presentation::getSlides2() {
if(_slides == nullptr) {
_slides = _pres->get_Slides();
}
int32_t slideCount = _slides->get_Count();
int32_t slideTextCount = _slideText->get_Count();
vector<Php::Object> slideArr;
SmartPtr<ISlide> slide;
try {
for(int i = 0; i < slideCount; i++) {
slide = _slides->idx_get(i);
AsposePhp::Slide* phpSlide;
if(i >= slideTextCount) {
phpSlide = new AsposePhp::Slide(slide, "", "", "", slide->get_SlideNumber());
} else {
phpSlide = new AsposePhp::Slide(slide,
_slideText[i]->get_LayoutText().ToUtf8String(),
_slideText[i]->get_NotesText().ToUtf8String(),
_slideText[i]->get_MasterText().ToUtf8String(), slide->get_SlideNumber());
}
slideArr.push_back(Php::Object("AsposePhp\\Slides\\Slide", phpSlide));
}
return Php::Array(slideArr);
}
catch(ArgumentOutOfRangeException &e) {
return nullptr;
}
}
/**
* @brief Returns a specific slide by index.
*
* @param params The 0 based index of the slide.
*
* @throw System::ArgumentOutOfRangeException index does not exist.
* @return Php::Value
*/
Php::Value Presentation::getSlide(Php::Parameters ¶ms) {
int slideNo = params[0].numericValue();
try {
SharedPtr<ISlide> slide = _pres->get_Slides()->idx_get(slideNo);
Slide* ret = new Slide(slide,
_slideText[slideNo]->get_LayoutText().ToUtf8String(),
_slideText[slideNo]->get_NotesText().ToUtf8String(),
_slideText[slideNo]->get_MasterText().ToUtf8String(),
slide->get_SlideNumber());
return Php::Object("AsposePhp\\Slides\\Slide", ret);
}
catch(System::ArgumentOutOfRangeException &e) {
throw Php::Exception("Invalid index: " + to_string(slideNo));
}
}
/**
* @brief Returns a list of all master slides that are defined in the presentation. Read-only IMasterSlideCollection
*
* @return Php::Value
*/
Php::Value Presentation::get_Masters() {
SharedPtr<IMasterSlideCollection> items = _pres->get_Masters();
MasterSlideCollection * phpValue = new MasterSlideCollection(items);
return Php::Object("AsposePhp\\Slides\\MasterSlideCollection", phpValue);
}
/**
* @brief Returns the collection of all images in the presentation. Read-only IImageCollection
*
* @return Php::Value
*/
Php::Value Presentation::get_Images() {
SharedPtr<IImageCollection> items = _pres->get_Images();
ImageCollection * phpValue = new ImageCollection(items);
return Php::Object("AsposePhp\\Slides\\ImageCollection", phpValue);
}
}
| 12,525 | 3,558 |
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/core/client/AWSError.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/secretsmanager/SecretsManagerErrors.h>
using namespace Aws::Client;
using namespace Aws::Utils;
using namespace Aws::SecretsManager;
namespace Aws
{
namespace SecretsManager
{
namespace SecretsManagerErrorMapper
{
static const int RESOURCE_EXISTS_HASH = HashingUtils::HashString("ResourceExistsException");
static const int MALFORMED_POLICY_DOCUMENT_HASH = HashingUtils::HashString("MalformedPolicyDocumentException");
static const int INTERNAL_SERVICE_HASH = HashingUtils::HashString("InternalServiceError");
static const int INVALID_PARAMETER_HASH = HashingUtils::HashString("InvalidParameterException");
static const int LIMIT_EXCEEDED_HASH = HashingUtils::HashString("LimitExceededException");
static const int DECRYPTION_FAILURE_HASH = HashingUtils::HashString("DecryptionFailure");
static const int PUBLIC_POLICY_HASH = HashingUtils::HashString("PublicPolicyException");
static const int PRECONDITION_NOT_MET_HASH = HashingUtils::HashString("PreconditionNotMetException");
static const int INVALID_NEXT_TOKEN_HASH = HashingUtils::HashString("InvalidNextTokenException");
static const int INVALID_REQUEST_HASH = HashingUtils::HashString("InvalidRequestException");
static const int ENCRYPTION_FAILURE_HASH = HashingUtils::HashString("EncryptionFailure");
AWSError<CoreErrors> GetErrorForName(const char* errorName)
{
int hashCode = HashingUtils::HashString(errorName);
if (hashCode == RESOURCE_EXISTS_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(SecretsManagerErrors::RESOURCE_EXISTS), false);
}
else if (hashCode == MALFORMED_POLICY_DOCUMENT_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(SecretsManagerErrors::MALFORMED_POLICY_DOCUMENT), false);
}
else if (hashCode == INTERNAL_SERVICE_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(SecretsManagerErrors::INTERNAL_SERVICE), false);
}
else if (hashCode == INVALID_PARAMETER_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(SecretsManagerErrors::INVALID_PARAMETER), false);
}
else if (hashCode == LIMIT_EXCEEDED_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(SecretsManagerErrors::LIMIT_EXCEEDED), true);
}
else if (hashCode == DECRYPTION_FAILURE_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(SecretsManagerErrors::DECRYPTION_FAILURE), false);
}
else if (hashCode == PUBLIC_POLICY_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(SecretsManagerErrors::PUBLIC_POLICY), false);
}
else if (hashCode == PRECONDITION_NOT_MET_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(SecretsManagerErrors::PRECONDITION_NOT_MET), false);
}
else if (hashCode == INVALID_NEXT_TOKEN_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(SecretsManagerErrors::INVALID_NEXT_TOKEN), false);
}
else if (hashCode == INVALID_REQUEST_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(SecretsManagerErrors::INVALID_REQUEST), false);
}
else if (hashCode == ENCRYPTION_FAILURE_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(SecretsManagerErrors::ENCRYPTION_FAILURE), false);
}
return AWSError<CoreErrors>(CoreErrors::UNKNOWN, false);
}
} // namespace SecretsManagerErrorMapper
} // namespace SecretsManager
} // namespace Aws
| 3,516 | 1,186 |
// For conditions of distribution and use, see copyright notice in License.txt
#include "../../Debug/Log.h"
#include "../../Debug/Profiler.h"
#include "../Shader.h"
#include "D3D11Graphics.h"
#include "D3D11ShaderVariation.h"
#include "D3D11VertexBuffer.h"
#include <d3d11.h>
#include <d3dcompiler.h>
#include "../../Debug/DebugNew.h"
namespace Turso3D
{
unsigned InspectInputSignature(ID3DBlob* d3dBlob)
{
ID3D11ShaderReflection* reflection = nullptr;
D3D11_SHADER_DESC shaderDesc;
unsigned elementHash = 0;
D3DReflect(d3dBlob->GetBufferPointer(), d3dBlob->GetBufferSize(), IID_ID3D11ShaderReflection, (void**)&reflection);
if (!reflection)
{
LOGERROR("Failed to reflect vertex shader's input signature");
return elementHash;
}
reflection->GetDesc(&shaderDesc);
for (size_t i = 0; i < shaderDesc.InputParameters; ++i)
{
D3D11_SIGNATURE_PARAMETER_DESC paramDesc;
reflection->GetInputParameterDesc((unsigned)i, ¶mDesc);
for (size_t j = 0; elementSemanticNames[j]; ++j)
{
if (!String::Compare(paramDesc.SemanticName, elementSemanticNames[j]))
{
elementHash |= VertexBuffer::ElementHash(i, (ElementSemantic)j);
break;
}
}
}
reflection->Release();
return elementHash;
}
ShaderVariation::ShaderVariation(Shader* parent_, const String& defines_) :
parent(parent_),
stage(parent->Stage()),
defines(defines_),
blob(nullptr),
shader(nullptr),
elementHash(0),
compiled(false)
{
}
ShaderVariation::~ShaderVariation()
{
Release();
}
void ShaderVariation::Release()
{
if (graphics && (graphics->GetVertexShader() == this || graphics->GetPixelShader() == this))
graphics->SetShaders(nullptr, nullptr);
if (blob)
{
ID3DBlob* d3dBlob = (ID3DBlob*)blob;
d3dBlob->Release();
blob = nullptr;
}
if (shader)
{
if (stage == SHADER_VS)
{
ID3D11VertexShader* d3dShader = (ID3D11VertexShader*)shader;
d3dShader->Release();
}
else
{
ID3D11PixelShader* d3dShader = (ID3D11PixelShader*)shader;
d3dShader->Release();
}
shader = nullptr;
}
elementHash = 0;
compiled = false;
}
bool ShaderVariation::Compile()
{
if (compiled)
return shader != nullptr;
PROFILE(CompileShaderVariation);
// Do not retry without a Release() inbetween
compiled = true;
if (!graphics || !graphics->IsInitialized())
{
LOGERROR("Can not compile shader without initialized Graphics subsystem");
return false;
}
if (!parent)
{
LOGERROR("Can not compile shader without parent shader resource");
return false;
}
// Collect defines into macros
Vector<String> defineNames = defines.Split(' ');
Vector<String> defineValues;
Vector<D3D_SHADER_MACRO> macros;
for (size_t i = 0; i < defineNames.Size(); ++i)
{
size_t equalsPos = defineNames[i].Find('=');
if (equalsPos != String::NPOS)
{
defineValues.Push(defineNames[i].Substring(equalsPos + 1));
defineNames[i].Resize(equalsPos);
}
else
defineValues.Push("1");
}
for (size_t i = 0; i < defineNames.Size(); ++i)
{
D3D_SHADER_MACRO macro;
macro.Name = defineNames[i].CString();
macro.Definition = defineValues[i].CString();
macros.Push(macro);
}
D3D_SHADER_MACRO endMacro;
endMacro.Name = nullptr;
endMacro.Definition = nullptr;
macros.Push(endMacro);
/// \todo Level 3 could be used, but can lead to longer shader compile times, considering there is no binary caching yet
DWORD flags = D3DCOMPILE_OPTIMIZATION_LEVEL2 | D3DCOMPILE_PREFER_FLOW_CONTROL;
ID3DBlob* errorBlob = nullptr;
if (FAILED(D3DCompile(parent->SourceCode().CString(), parent->SourceCode().Length(), "", ¯os[0], 0, "main",
stage == SHADER_VS ? "vs_4_0" : "ps_4_0", flags, 0, (ID3DBlob**)&blob, &errorBlob)))
{
if (errorBlob)
{
LOGERRORF("Could not compile shader %s: %s", FullName().CString(), errorBlob->GetBufferPointer());
errorBlob->Release();
}
return false;
}
if (errorBlob)
{
errorBlob->Release();
errorBlob = nullptr;
}
ID3D11Device* d3dDevice = (ID3D11Device*)graphics->D3DDevice();
ID3DBlob* d3dBlob = (ID3DBlob*)blob;
#ifdef SHOW_DISASSEMBLY
ID3DBlob* asmBlob = nullptr;
D3DDisassemble(d3dBlob->GetBufferPointer(), d3dBlob->GetBufferSize(), 0, nullptr, &asmBlob);
if (asmBlob)
{
String text((const char*)asmBlob->GetBufferPointer(), asmBlob->GetBufferSize());
LOGINFOF("Shader %s disassembly: %s", FullName().CString(), text.CString());
asmBlob->Release();
}
#endif
if (stage == SHADER_VS)
{
elementHash = InspectInputSignature(d3dBlob);
d3dDevice->CreateVertexShader(d3dBlob->GetBufferPointer(), d3dBlob->GetBufferSize(), 0, (ID3D11VertexShader**)&shader);
}
else
d3dDevice->CreatePixelShader(d3dBlob->GetBufferPointer(), d3dBlob->GetBufferSize(), 0, (ID3D11PixelShader**)&shader);
if (!shader)
{
LOGERROR("Failed to create shader " + FullName());
return false;
}
else
LOGDEBUGF("Compiled shader %s bytecode size %u", FullName().CString(), (unsigned)d3dBlob->GetBufferSize());
return true;
}
Shader* ShaderVariation::Parent() const
{
return parent;
}
String ShaderVariation::FullName() const
{
if (parent)
return defines.IsEmpty() ? parent->Name() : parent->Name() + " (" + defines + ")";
else
return String::EMPTY;
}
} | 5,848 | 2,024 |
// C++ headers
#include <cstring>
#include <iterator>
#include <string>
// {fmt} headers
#include <fmt/printf.h>
// CMSSW headers
#include "FWCore/Framework/interface/Frameworkfwd.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/LuminosityBlock.h"
#include "FWCore/Framework/interface/Run.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/ParameterSet/interface/ParameterSetDescription.h"
#include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h"
#include "FWCore/ParameterSet/interface/Registry.h"
#include "FWCore/ServiceRegistry/interface/Service.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "DataFormats/Provenance/interface/ProcessHistory.h"
#include "DataFormats/Common/interface/TriggerResults.h"
#include "DataFormats/L1TGlobal/interface/GlobalAlgBlk.h"
#include "CondFormats/DataRecord/interface/L1TUtmTriggerMenuRcd.h"
#include "CondFormats/L1TObjects/interface/L1TUtmTriggerMenu.h"
#include "HLTrigger/HLTcore/interface/HLTConfigProvider.h"
#include "DQMServices/Core/interface/DQMGlobalEDAnalyzer.h"
namespace {
struct RunBasedHistograms {
public:
typedef dqm::reco::MonitorElement MonitorElement;
RunBasedHistograms()
: // L1T and HLT configuration
hltConfig(),
// L1T and HLT results
tcds_bx_all(nullptr),
l1t_bx_all(nullptr),
hlt_bx_all(nullptr),
tcds_bx(),
l1t_bx(),
hlt_bx(),
tcds_bx_2d(),
l1t_bx_2d(),
hlt_bx_2d() {}
public:
// HLT configuration
HLTConfigProvider hltConfig;
// L1T and HLT results
dqm::reco::MonitorElement* tcds_bx_all;
dqm::reco::MonitorElement* l1t_bx_all;
dqm::reco::MonitorElement* hlt_bx_all;
std::vector<dqm::reco::MonitorElement*> tcds_bx;
std::vector<dqm::reco::MonitorElement*> l1t_bx;
std::vector<dqm::reco::MonitorElement*> hlt_bx;
std::vector<dqm::reco::MonitorElement*> tcds_bx_2d;
std::vector<dqm::reco::MonitorElement*> l1t_bx_2d;
std::vector<dqm::reco::MonitorElement*> hlt_bx_2d;
};
} // namespace
class TriggerBxMonitor : public DQMGlobalEDAnalyzer<RunBasedHistograms> {
public:
explicit TriggerBxMonitor(edm::ParameterSet const&);
~TriggerBxMonitor() override = default;
static void fillDescriptions(edm::ConfigurationDescriptions& descriptions);
private:
void dqmBeginRun(edm::Run const&, edm::EventSetup const&, RunBasedHistograms&) const override;
void bookHistograms(DQMStore::IBooker&, edm::Run const&, edm::EventSetup const&, RunBasedHistograms&) const override;
void dqmAnalyze(edm::Event const&, edm::EventSetup const&, RunBasedHistograms const&) const override;
// number of bunch crossings
static const unsigned int s_bx_range = 3564;
// TCDS trigger types
// see https://twiki.cern.ch/twiki/bin/viewauth/CMS/TcdsEventRecord
static constexpr const char* s_tcds_trigger_types[] = {
"Empty", // 0 - No trigger
"Physics", // 1 - GT trigger
"Calibration", // 2 - Sequence trigger (calibration)
"Random", // 3 - Random trigger
"Auxiliary", // 4 - Auxiliary (CPM front panel NIM input) trigger
nullptr, // 5 - reserved
nullptr, // 6 - reserved
nullptr, // 7 - reserved
"Cyclic", // 8 - Cyclic trigger
"Bunch-pattern", // 9 - Bunch-pattern trigger
"Software", // 10 - Software trigger
"TTS", // 11 - TTS-sourced trigger
nullptr, // 12 - reserved
nullptr, // 13 - reserved
nullptr, // 14 - reserved
nullptr // 15 - reserved
};
// module configuration
const edm::ESGetToken<L1TUtmTriggerMenu, L1TUtmTriggerMenuRcd> m_l1tMenuToken;
const edm::EDGetTokenT<GlobalAlgBlkBxCollection> m_l1t_results;
const edm::EDGetTokenT<edm::TriggerResults> m_hlt_results;
const std::string m_dqm_path;
const bool m_make_1d_plots;
const bool m_make_2d_plots;
const uint32_t m_ls_range;
};
// definition
constexpr const char* TriggerBxMonitor::s_tcds_trigger_types[];
void TriggerBxMonitor::fillDescriptions(edm::ConfigurationDescriptions& descriptions) {
edm::ParameterSetDescription desc;
desc.addUntracked<edm::InputTag>("l1tResults", edm::InputTag("gtStage2Digis"));
desc.addUntracked<edm::InputTag>("hltResults", edm::InputTag("TriggerResults"));
desc.addUntracked<std::string>("dqmPath", "HLT/TriggerBx");
desc.addUntracked<bool>("make1DPlots", true);
desc.addUntracked<bool>("make2DPlots", false);
desc.addUntracked<uint32_t>("lsRange", 4000);
descriptions.add("triggerBxMonitor", desc);
}
TriggerBxMonitor::TriggerBxMonitor(edm::ParameterSet const& config)
: // module configuration
m_l1tMenuToken{esConsumes<edm::Transition::BeginRun>()},
m_l1t_results(consumes<GlobalAlgBlkBxCollection>(config.getUntrackedParameter<edm::InputTag>("l1tResults"))),
m_hlt_results(consumes<edm::TriggerResults>(config.getUntrackedParameter<edm::InputTag>("hltResults"))),
m_dqm_path(config.getUntrackedParameter<std::string>("dqmPath")),
m_make_1d_plots(config.getUntrackedParameter<bool>("make1DPlots")),
m_make_2d_plots(config.getUntrackedParameter<bool>("make2DPlots")),
m_ls_range(config.getUntrackedParameter<uint32_t>("lsRange")) {}
void TriggerBxMonitor::dqmBeginRun(edm::Run const& run,
edm::EventSetup const& setup,
RunBasedHistograms& histograms) const {
// initialise the TCDS vector
if (m_make_1d_plots) {
histograms.tcds_bx.clear();
histograms.tcds_bx.resize(std::size(s_tcds_trigger_types));
}
if (m_make_2d_plots) {
histograms.tcds_bx_2d.clear();
histograms.tcds_bx_2d.resize(std::size(s_tcds_trigger_types));
}
// cache the L1 trigger menu
if (m_make_1d_plots) {
histograms.l1t_bx.clear();
histograms.l1t_bx.resize(GlobalAlgBlk::maxPhysicsTriggers);
}
if (m_make_2d_plots) {
histograms.l1t_bx_2d.clear();
histograms.l1t_bx_2d.resize(GlobalAlgBlk::maxPhysicsTriggers);
}
// initialise the HLTConfigProvider
bool changed = true;
edm::EDConsumerBase::Labels labels;
labelsForToken(m_hlt_results, labels);
if (histograms.hltConfig.init(run, setup, labels.process, changed)) {
if (m_make_1d_plots) {
histograms.hlt_bx.clear();
histograms.hlt_bx.resize(histograms.hltConfig.size());
}
if (m_make_2d_plots) {
histograms.hlt_bx_2d.clear();
histograms.hlt_bx_2d.resize(histograms.hltConfig.size());
}
} else {
// HLTConfigProvider not initialised, skip the the HLT monitoring
edm::LogError("TriggerBxMonitor")
<< "failed to initialise HLTConfigProvider, the HLT bx distribution will not be monitored";
}
}
void TriggerBxMonitor::bookHistograms(DQMStore::IBooker& booker,
edm::Run const& run,
edm::EventSetup const& setup,
RunBasedHistograms& histograms) const {
// TCDS trigger type plots
{
size_t size = std::size(s_tcds_trigger_types);
// book 2D histogram to monitor all TCDS trigger types in a single plot
booker.setCurrentFolder(m_dqm_path);
histograms.tcds_bx_all = booker.book2D("TCDS Trigger Types",
"TCDS Trigger Types vs. bunch crossing",
s_bx_range + 1,
-0.5,
s_bx_range + 0.5,
size,
-0.5,
size - 0.5);
// book the individual histograms for the known TCDS trigger types
booker.setCurrentFolder(m_dqm_path + "/TCDS");
for (unsigned int i = 0; i < size; ++i) {
if (s_tcds_trigger_types[i]) {
if (m_make_1d_plots) {
histograms.tcds_bx.at(i) =
booker.book1D(s_tcds_trigger_types[i], s_tcds_trigger_types[i], s_bx_range + 1, -0.5, s_bx_range + 0.5);
}
if (m_make_2d_plots) {
std::string const& name_ls = std::string(s_tcds_trigger_types[i]) + " vs LS";
histograms.tcds_bx_2d.at(i) = booker.book2D(
name_ls, name_ls, s_bx_range + 1, -0.5, s_bx_range + 0.5, m_ls_range, 0.5, m_ls_range + 0.5);
}
histograms.tcds_bx_all->setBinLabel(i + 1, s_tcds_trigger_types[i], 2); // Y axis
}
}
}
// L1T plots
{
// book 2D histogram to monitor all L1 triggers in a single plot
booker.setCurrentFolder(m_dqm_path);
histograms.l1t_bx_all = booker.book2D("Level 1 Triggers",
"Level 1 Triggers vs. bunch crossing",
s_bx_range + 1,
-0.5,
s_bx_range + 0.5,
GlobalAlgBlk::maxPhysicsTriggers,
-0.5,
GlobalAlgBlk::maxPhysicsTriggers - 0.5);
// book the individual histograms for the L1 triggers that are included in the L1 menu
booker.setCurrentFolder(m_dqm_path + "/L1T");
auto const& l1tMenu = setup.getData(m_l1tMenuToken);
for (auto const& keyval : l1tMenu.getAlgorithmMap()) {
unsigned int bit = keyval.second.getIndex();
std::string const& name = fmt::sprintf("%s (bit %d)", keyval.first, bit);
if (m_make_1d_plots) {
histograms.l1t_bx.at(bit) = booker.book1D(name, name, s_bx_range + 1, -0.5, s_bx_range + 0.5);
}
if (m_make_2d_plots) {
std::string const& name_ls = name + " vs LS";
histograms.l1t_bx_2d.at(bit) =
booker.book2D(name_ls, name_ls, s_bx_range + 1, -0.5, s_bx_range + 0.5, m_ls_range, 0.5, m_ls_range + 0.5);
}
histograms.l1t_bx_all->setBinLabel(bit + 1, keyval.first, 2); // Y axis
}
}
// HLT plots
if (histograms.hltConfig.inited()) {
// book 2D histogram to monitor all HLT paths in a single plot
booker.setCurrentFolder(m_dqm_path);
histograms.hlt_bx_all = booker.book2D("High Level Triggers",
"High Level Triggers vs. bunch crossing",
s_bx_range + 1,
-0.5,
s_bx_range + 0.5,
histograms.hltConfig.size(),
-0.5,
histograms.hltConfig.size() - 0.5);
// book the individual HLT triggers histograms
booker.setCurrentFolder(m_dqm_path + "/HLT");
for (unsigned int i = 0; i < histograms.hltConfig.size(); ++i) {
std::string const& name = histograms.hltConfig.triggerName(i);
if (m_make_1d_plots) {
histograms.hlt_bx[i] = booker.book1D(name, name, s_bx_range + 1, -0.5, s_bx_range + 0.5);
}
if (m_make_2d_plots) {
std::string const& name_ls = name + " vs LS";
histograms.hlt_bx_2d[i] =
booker.book2D(name_ls, name_ls, s_bx_range + 1, -0.5, s_bx_range + 0.5, m_ls_range, 0.5, m_ls_range + 0.5);
}
histograms.hlt_bx_all->setBinLabel(i + 1, name, 2); // Y axis
}
}
}
void TriggerBxMonitor::dqmAnalyze(edm::Event const& event,
edm::EventSetup const& setup,
RunBasedHistograms const& histograms) const {
unsigned int bx = event.bunchCrossing();
unsigned int ls = event.luminosityBlock();
// monitor the bx distribution for the TCDS trigger types
{
size_t size = std::size(s_tcds_trigger_types);
unsigned int type = event.experimentType();
if (type < size) {
if (m_make_1d_plots and histograms.tcds_bx.at(type))
histograms.tcds_bx[type]->Fill(bx);
if (m_make_2d_plots and histograms.tcds_bx_2d.at(type))
histograms.tcds_bx_2d[type]->Fill(bx, ls);
}
histograms.tcds_bx_all->Fill(bx, type);
}
// monitor the bx distribution for the L1 triggers
{
auto const& bxvector = event.get(m_l1t_results);
if (not bxvector.isEmpty(0)) {
auto const& results = bxvector.at(0, 0);
for (unsigned int i = 0; i < GlobalAlgBlk::maxPhysicsTriggers; ++i)
if (results.getAlgoDecisionFinal(i)) {
if (m_make_1d_plots and histograms.l1t_bx.at(i))
histograms.l1t_bx[i]->Fill(bx);
if (m_make_2d_plots and histograms.l1t_bx_2d.at(i))
histograms.l1t_bx_2d[i]->Fill(bx, ls);
histograms.l1t_bx_all->Fill(bx, i);
}
}
}
// monitor the bx distribution for the HLT triggers
if (histograms.hltConfig.inited()) {
auto const& hltResults = event.get(m_hlt_results);
for (unsigned int i = 0; i < hltResults.size(); ++i) {
if (hltResults.at(i).accept()) {
if (m_make_1d_plots and histograms.hlt_bx.at(i))
histograms.hlt_bx[i]->Fill(bx);
if (m_make_2d_plots and histograms.hlt_bx_2d.at(i))
histograms.hlt_bx_2d[i]->Fill(bx, ls);
histograms.hlt_bx_all->Fill(bx, i);
}
}
}
}
//define this as a plug-in
#include "FWCore/Framework/interface/MakerMacros.h"
DEFINE_FWK_MODULE(TriggerBxMonitor);
| 13,536 | 5,046 |
// WM_DRAWITEM, SS_OWNERDRAW|SS_NOTIFY, Bmp & hBmp -> global vars
// DPI resize.
/*
Copyright (c) 2014-2017 Maximus5
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. The name of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''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 AUTHOR 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.
*/
#undef HIDE_USE_EXCEPTION_INFO
#define SHOWDEBUGSTR
#include "Header.h"
#include "About.h"
#include "AboutDlg.h"
#include "ConEmu.h"
#include "DpiAware.h"
#include "DynDialog.h"
#include "ImgButton.h"
#include "LngRc.h"
#include "OptionsClass.h"
#include "PushInfo.h"
#include "RealConsole.h"
#include "SearchCtrl.h"
#include "Update.h"
#include "VirtualConsole.h"
#include "VConChild.h"
#include "version.h"
#include "../common/MSetter.h"
#include "../common/WObjects.h"
#include "../common/StartupEnvEx.h"
namespace ConEmuAbout
{
void InitCommCtrls();
bool mb_CommCtrlsInitialized = false;
HWND mh_AboutDlg = NULL;
DWORD nLastCrashReported = 0;
CDpiForDialog* mp_DpiAware = NULL;
INT_PTR WINAPI aboutProc(HWND hDlg, UINT messg, WPARAM wParam, LPARAM lParam);
void searchProc(HWND hDlg, HWND hSearch, bool bReentr);
void OnInfo_DonateLink();
void OnInfo_FlattrLink();
CImgButtons* mp_ImgBtn = NULL;
static struct {LPCWSTR Title; LPCWSTR Text;} Pages[] =
{
{L"About", pAbout},
{L"ConEmu /?", pCmdLine},
{L"Tasks", pAboutTasks},
{L"-new_console", pNewConsoleHelpFull},
{L"ConEmuC /?", pConsoleHelpFull},
{L"Macro", pGuiMacro},
{L"DosBox", pDosBoxHelpFull},
{L"Contributors", pAboutContributors},
{L"License", pAboutLicense},
{L"SysInfo", L""},
};
wchar_t sLastOpenTab[32] = L"";
void TabSelected(HWND hDlg, int idx);
wchar_t* gsSysInfo = NULL;
void ReloadSysInfo();
void LogStartEnvInt(LPCWSTR asText, LPARAM lParam, bool bFirst, bool bNewLine);
DWORD nTextSelStart = 0, nTextSelEnd = 0;
};
INT_PTR WINAPI ConEmuAbout::aboutProc(HWND hDlg, UINT messg, WPARAM wParam, LPARAM lParam)
{
INT_PTR lRc = 0;
if ((mp_ImgBtn && mp_ImgBtn->Process(hDlg, messg, wParam, lParam, lRc))
|| EditIconHint_Process(hDlg, messg, wParam, lParam, lRc))
{
SetWindowLongPtr(hDlg, DWLP_MSGRESULT, lRc);
return TRUE;
}
PatchMsgBoxIcon(hDlg, messg, wParam, lParam);
switch (messg)
{
case WM_INITDIALOG:
{
gpConEmu->OnOurDialogOpened();
mh_AboutDlg = hDlg;
CDynDialog::LocalizeDialog(hDlg);
_ASSERTE(mp_ImgBtn==NULL);
SafeDelete(mp_ImgBtn);
mp_ImgBtn = new CImgButtons(hDlg, pIconCtrl, IDOK);
mp_ImgBtn->AddDonateButtons();
if (mp_DpiAware)
{
mp_DpiAware->Attach(hDlg, ghWnd, CDynDialog::GetDlgClass(hDlg));
}
CDpiAware::CenterDialog(hDlg);
if ((ghOpWnd && IsWindow(ghOpWnd)) || (WS_EX_TOPMOST & GetWindowLongPtr(ghWnd, GWL_EXSTYLE)))
{
SetWindowPos(hDlg, HWND_TOPMOST, 0,0,0,0, SWP_NOMOVE|SWP_NOSIZE);
}
LPCWSTR pszActivePage = (LPCWSTR)lParam;
LPCWSTR psStage = (ConEmuVersionStage == CEVS_STABLE) ? L"{Stable}"
: (ConEmuVersionStage == CEVS_PREVIEW) ? L"{Preview}"
: L"{Alpha}";
CEStr lsTitle(
CLngRc::getRsrc(lng_DlgAbout/*"About"*/),
L" ",
gpConEmu->GetDefaultTitle(),
L" ",
psStage,
NULL);
if (lsTitle)
{
SetWindowText(hDlg, lsTitle);
}
if (hClassIcon)
{
SendMessage(hDlg, WM_SETICON, ICON_BIG, (LPARAM)hClassIcon);
SendMessage(hDlg, WM_SETICON, ICON_SMALL, (LPARAM)CreateNullIcon());
SetClassLongPtr(hDlg, GCLP_HICON, (LONG_PTR)hClassIcon);
}
// "Console Emulation program (local terminal)"
SetDlgItemText(hDlg, stConEmuAbout, CLngRc::getRsrc(lng_AboutAppName));
SetDlgItemText(hDlg, stConEmuUrl, gsHomePage);
EditIconHint_Set(hDlg, GetDlgItem(hDlg, tAboutSearch), true,
CLngRc::getRsrc(lng_Search/*"Search"*/),
false, UM_SEARCH, IDOK);
EditIconHint_Subclass(hDlg);
wchar_t* pszLabel = GetDlgItemTextPtr(hDlg, stConEmuVersion);
if (pszLabel)
{
wchar_t* pszSet = NULL;
if (gpUpd)
{
wchar_t* pszVerInfo = gpUpd->GetCurVerInfo();
if (pszVerInfo)
{
pszSet = lstrmerge(pszLabel, L" ", pszVerInfo);
free(pszVerInfo);
}
}
if (!pszSet)
{
pszSet = lstrmerge(pszLabel, L" ", CLngRc::getRsrc(lng_PleaseCheckManually/*"Please check for updates manually"*/));
}
if (pszSet)
{
SetDlgItemText(hDlg, stConEmuVersion, pszSet);
free(pszSet);
}
free(pszLabel);
}
HWND hTab = GetDlgItem(hDlg, tbAboutTabs);
INT_PTR nPage = -1;
for (size_t i = 0; i < countof(Pages); i++)
{
TCITEM tie = {};
tie.mask = TCIF_TEXT;
tie.pszText = (LPWSTR)Pages[i].Title;
TabCtrl_InsertItem(hTab, i, &tie);
if (pszActivePage && (lstrcmpi(pszActivePage, Pages[i].Title) == 0))
nPage = i;
}
if (nPage >= 0)
{
TabSelected(hDlg, nPage);
TabCtrl_SetCurSel(hTab, (int)nPage);
}
else if (!pszActivePage)
{
TabSelected(hDlg, 0);
}
else
{
_ASSERTE(pszActivePage==NULL && "Unknown page name?");
}
SetFocus(hTab);
return FALSE;
}
case WM_CTLCOLORSTATIC:
if (GetWindowLongPtr((HWND)lParam, GWLP_ID) == stConEmuUrl)
{
SetTextColor((HDC)wParam, GetSysColor(COLOR_HOTLIGHT));
HBRUSH hBrush = GetSysColorBrush(COLOR_3DFACE);
SetBkMode((HDC)wParam, TRANSPARENT);
return (INT_PTR)hBrush;
}
else
{
SetTextColor((HDC)wParam, GetSysColor(COLOR_WINDOWTEXT));
HBRUSH hBrush = GetSysColorBrush(COLOR_3DFACE);
SetBkMode((HDC)wParam, TRANSPARENT);
return (INT_PTR)hBrush;
}
break;
case WM_SETCURSOR:
{
if (GetWindowLongPtr((HWND)wParam, GWLP_ID) == stConEmuUrl)
{
SetCursor(LoadCursor(NULL, IDC_HAND));
SetWindowLongPtr(hDlg, DWLP_MSGRESULT, TRUE);
return TRUE;
}
return FALSE;
}
break;
case WM_COMMAND:
switch (HIWORD(wParam))
{
case BN_CLICKED:
switch (LOWORD(wParam))
{
case IDOK:
case IDCANCEL:
case IDCLOSE:
aboutProc(hDlg, WM_CLOSE, 0, 0);
return 1;
case stConEmuUrl:
ConEmuAbout::OnInfo_HomePage();
return 1;
} // BN_CLICKED
break;
case EN_SETFOCUS:
switch (LOWORD(wParam))
{
case tAboutText:
{
// Do not autosel all text
HWND hEdit = (HWND)lParam;
DWORD nStart = 0, nEnd = 0;
SendMessage(hEdit, EM_GETSEL, (WPARAM)&nStart, (LPARAM)&nEnd);
if (nStart != nEnd)
{
SendMessage(hEdit, EM_SETSEL, nTextSelStart, nTextSelEnd);
}
}
break;
}
} // switch (HIWORD(wParam))
break;
case WM_NOTIFY:
{
LPNMHDR nmhdr = (LPNMHDR)lParam;
if ((nmhdr->code == TCN_SELCHANGE) && (nmhdr->idFrom == tbAboutTabs))
{
int iPage = TabCtrl_GetCurSel(nmhdr->hwndFrom);
if ((iPage >= 0) && (iPage < (int)countof(Pages)))
TabSelected(hDlg, iPage);
}
break;
}
case UM_SEARCH:
searchProc(hDlg, (HWND)lParam, false);
break;
case UM_EDIT_KILL_FOCUS:
SendMessage((HWND)lParam, EM_GETSEL, (WPARAM)&nTextSelStart, (LPARAM)&nTextSelEnd);
break;
case WM_CLOSE:
//if (ghWnd == NULL)
gpConEmu->OnOurDialogClosed();
if (mp_DpiAware)
mp_DpiAware->Detach();
EndDialog(hDlg, IDOK);
SafeDelete(mp_ImgBtn);
break;
case WM_DESTROY:
mh_AboutDlg = NULL;
break;
default:
if (mp_DpiAware && mp_DpiAware->ProcessDpiMessages(hDlg, messg, wParam, lParam))
{
return TRUE;
}
}
return FALSE;
}
void ConEmuAbout::searchProc(HWND hDlg, HWND hSearch, bool bReentr)
{
HWND hEdit = GetDlgItem(hDlg, tAboutText);
wchar_t* pszPart = GetDlgItemTextPtr(hSearch, 0);
wchar_t* pszText = GetDlgItemTextPtr(hEdit, 0);
bool bRetry = false;
if (pszPart && *pszPart && pszText && *pszText)
{
LPCWSTR pszFrom = pszText;
DWORD nStart = 0, nEnd = 0;
SendMessage(hEdit, EM_GETSEL, (WPARAM)&nStart, (LPARAM)&nEnd);
size_t cchMax = wcslen(pszText);
size_t cchFrom = max(nStart,nEnd);
if (cchMax > cchFrom)
pszFrom += cchFrom;
LPCWSTR pszFind = StrStrI(pszFrom, pszPart);
if (!pszFind && bReentr && (pszFrom != pszText))
pszFind = StrStrI(pszText, pszPart);
if (pszFind)
{
const wchar_t szBrkChars[] = L"()[]<>{}:;,.-=\\/ \t\r\n";
LPCWSTR pszEnd = wcspbrk(pszFind, szBrkChars);
INT_PTR nPartLen = wcslen(pszPart);
if (!pszEnd || ((pszEnd - pszFind) > max(nPartLen,60)))
pszEnd = pszFind + nPartLen;
while ((pszFind > pszFrom) && !wcschr(szBrkChars, *(pszFind-1)))
pszFind--;
//SetFocus(hEdit);
nTextSelStart = (DWORD)(pszEnd-pszText);
nTextSelEnd = (DWORD)(pszFind-pszText);
SendMessage(hEdit, EM_SETSEL, nTextSelStart, nTextSelEnd);
SendMessage(hEdit, EM_SCROLLCARET, 0, 0);
}
else if (!bReentr)
{
HWND hTab = GetDlgItem(hDlg, tbAboutTabs);
int iPage = TabCtrl_GetCurSel(hTab);
int iFound = -1;
for (int s = 0; (iFound == -1) && (s <= 1); s++)
{
int iFrom = (s == 0) ? (iPage+1) : 0;
int iTo = (s == 0) ? (int)countof(Pages) : (iPage-1);
for (int i = iFrom; i < iTo; i++)
{
if (StrStrI(Pages[i].Title, pszPart)
|| StrStrI(Pages[i].Text, pszPart))
{
iFound = i; break;
}
}
}
if (iFound >= 0)
{
TabSelected(hDlg, iFound);
TabCtrl_SetCurSel(hTab, iFound);
//SetFocus(hEdit);
bRetry = true;
}
}
}
SafeFree(pszPart);
SafeFree(pszText);
if (bRetry)
{
searchProc(hDlg, hSearch, true);
}
}
void ConEmuAbout::InitCommCtrls()
{
if (mb_CommCtrlsInitialized)
return;
INITCOMMONCONTROLSEX icex;
icex.dwSize = sizeof(INITCOMMONCONTROLSEX);
icex.dwICC = ICC_COOL_CLASSES|ICC_BAR_CLASSES|ICC_TAB_CLASSES|ICC_PROGRESS_CLASS; //|ICC_STANDARD_CLASSES|ICC_WIN95_CLASSES;
InitCommonControlsEx(&icex);
mb_CommCtrlsInitialized = true;
}
void ConEmuAbout::OnInfo_OnlineWiki(LPCWSTR asPageName /*= NULL*/)
{
CEStr szUrl(CEWIKIBASE, asPageName ? asPageName : L"TableOfContents", L".html");
DWORD shellRc = (DWORD)(INT_PTR)ShellExecute(ghWnd, L"open", szUrl, NULL, NULL, SW_SHOWNORMAL);
if (shellRc <= 32)
{
DisplayLastError(L"ShellExecute failed", shellRc);
}
}
void ConEmuAbout::OnInfo_Donate()
{
int nBtn = MsgBox(
L"You can show your appreciation and support future development by donating.\n\n"
L"Open ConEmu's donate web page?"
,MB_YESNO|MB_ICONINFORMATION);
if (nBtn == IDYES)
{
OnInfo_DonateLink();
//OnInfo_HomePage();
}
}
void ConEmuAbout::OnInfo_DonateLink()
{
DWORD shellRc = (DWORD)(INT_PTR)ShellExecute(ghWnd, L"open", gsDonatePage, NULL, NULL, SW_SHOWNORMAL);
if (shellRc <= 32)
{
DisplayLastError(L"ShellExecute failed", shellRc);
}
}
void ConEmuAbout::OnInfo_FlattrLink()
{
DWORD shellRc = (DWORD)(INT_PTR)ShellExecute(ghWnd, L"open", gsFlattrPage, NULL, NULL, SW_SHOWNORMAL);
if (shellRc <= 32)
{
DisplayLastError(L"ShellExecute failed", shellRc);
}
}
void ConEmuAbout::TabSelected(HWND hDlg, int idx)
{
if (idx < 0 || idx >= countof(Pages))
return;
wcscpy_c(sLastOpenTab, Pages[idx].Title);
LPCWSTR pszNewText = Pages[idx].Text;
CEStr lsTemp;
if (gpConEmu->mp_PushInfo && gpConEmu->mp_PushInfo->mp_Active && gpConEmu->mp_PushInfo->mp_Active->pszFullMessage)
{
// EDIT control requires \r\n as line endings
lsTemp = lstrmerge(gpConEmu->mp_PushInfo->mp_Active->pszFullMessage, L"\r\n\r\n\r\n", pszNewText);
pszNewText = lsTemp.ms_Val;
}
SetDlgItemText(hDlg, tAboutText, pszNewText);
}
void ConEmuAbout::LogStartEnvInt(LPCWSTR asText, LPARAM lParam, bool bFirst, bool bNewLine)
{
lstrmerge(&gsSysInfo, asText, bNewLine ? L"\r\n" : NULL);
if (bFirst && gpConEmu)
{
lstrmerge(&gsSysInfo, L" AppID: ", gpConEmu->ms_AppID, L"\r\n");
}
}
void ConEmuAbout::ReloadSysInfo()
{
if (!gpStartEnv)
return;
_ASSERTE(lstrcmp(Pages[countof(Pages)-1].Title, L"SysInfo") == 0);
SafeFree(gsSysInfo);
LoadStartupEnvEx::ToString(gpStartEnv, LogStartEnvInt, 0);
Pages[countof(Pages)-1].Text = gsSysInfo;
}
void ConEmuAbout::OnInfo_About(LPCWSTR asPageName /*= NULL*/)
{
InitCommCtrls();
bool bOk = false;
if (!asPageName && sLastOpenTab[0])
{
// Reopen last active tab
asPageName = sLastOpenTab;
}
ReloadSysInfo();
{
DontEnable de;
if (!mp_DpiAware)
mp_DpiAware = new CDpiForDialog();
HWND hParent = (ghOpWnd && IsWindowVisible(ghOpWnd)) ? ghOpWnd : ghWnd;
// Modal dialog (CreateDialog)
INT_PTR iRc = CDynDialog::ExecuteDialog(IDD_ABOUT, hParent, aboutProc, (LPARAM)asPageName);
bOk = (iRc != 0 && iRc != -1);
mh_AboutDlg = NULL;
if (mp_DpiAware)
mp_DpiAware->Detach();
#ifdef _DEBUG
// Any problems with dialog resource?
if (!bOk) DisplayLastError(L"DialogBoxParam(IDD_ABOUT) failed");
#endif
}
if (!bOk)
{
CEStr szTitle(gpConEmu->GetDefaultTitle(), L" ", CLngRc::getRsrc(lng_DlgAbout/*"About"*/));
DontEnable de;
MSGBOXPARAMS mb = {sizeof(MSGBOXPARAMS), ghWnd, g_hInstance,
pAbout,
szTitle.ms_Val,
MB_USERICON, MAKEINTRESOURCE(IMAGE_ICON), 0, NULL, LANG_NEUTRAL
};
MSetter lInCall(&gnInMsgBox);
// Use MessageBoxIndirect instead of MessageBox to show our icon instead of std ICONINFORMATION
MessageBoxIndirect(&mb);
}
}
void ConEmuAbout::OnInfo_WhatsNew(bool bLocal)
{
wchar_t sFile[MAX_PATH+80];
INT_PTR iExec = -1;
if (bLocal)
{
wcscpy_c(sFile, gpConEmu->ms_ConEmuBaseDir);
wcscat_c(sFile, L"\\WhatsNew-ConEmu.txt");
if (FileExists(sFile))
{
iExec = (INT_PTR)ShellExecute(ghWnd, L"open", sFile, NULL, NULL, SW_SHOWNORMAL);
if (iExec >= 32)
{
return;
}
}
}
wcscpy_c(sFile, gsWhatsNew);
iExec = (INT_PTR)ShellExecute(ghWnd, L"open", sFile, NULL, NULL, SW_SHOWNORMAL);
if (iExec >= 32)
{
return;
}
DisplayLastError(L"File 'WhatsNew-ConEmu.txt' not found, go to web page failed", (int)LODWORD(iExec));
}
void ConEmuAbout::OnInfo_Help()
{
static HMODULE hhctrl = NULL;
if (!hhctrl) hhctrl = GetModuleHandle(L"hhctrl.ocx");
if (!hhctrl) hhctrl = LoadLibrary(L"hhctrl.ocx");
if (hhctrl)
{
typedef BOOL (WINAPI* HTMLHelpW_t)(HWND hWnd, LPCWSTR pszFile, INT uCommand, INT dwData);
HTMLHelpW_t fHTMLHelpW = (HTMLHelpW_t)GetProcAddress(hhctrl, "HtmlHelpW");
if (fHTMLHelpW)
{
wchar_t szHelpFile[MAX_PATH*2];
lstrcpy(szHelpFile, gpConEmu->ms_ConEmuChm);
//wchar_t* pszSlash = wcsrchr(szHelpFile, L'\\');
//if (pszSlash) pszSlash++; else pszSlash = szHelpFile;
//lstrcpy(pszSlash, L"ConEmu.chm");
// lstrcat(szHelpFile, L::/Intro.htm");
#define HH_HELP_CONTEXT 0x000F
#define HH_DISPLAY_TOC 0x0001
//fHTMLHelpW(NULL /*чтобы окно не блокировалось*/, szHelpFile, HH_HELP_CONTEXT, contextID);
fHTMLHelpW(NULL /*чтобы окно не блокировалось*/, szHelpFile, HH_DISPLAY_TOC, 0);
}
}
}
void ConEmuAbout::OnInfo_HomePage()
{
DWORD shellRc = (DWORD)(INT_PTR)ShellExecute(ghWnd, L"open", gsHomePage, NULL, NULL, SW_SHOWNORMAL);
if (shellRc <= 32)
{
DisplayLastError(L"ShellExecute failed", shellRc);
}
}
void ConEmuAbout::OnInfo_DownloadPage()
{
DWORD shellRc = (DWORD)(INT_PTR)ShellExecute(ghWnd, L"open", gsDownlPage, NULL, NULL, SW_SHOWNORMAL);
if (shellRc <= 32)
{
DisplayLastError(L"ShellExecute failed", shellRc);
}
}
void ConEmuAbout::OnInfo_FirstStartPage()
{
DWORD shellRc = (DWORD)(INT_PTR)ShellExecute(ghWnd, L"open", gsFirstStart, NULL, NULL, SW_SHOWNORMAL);
if (shellRc <= 32)
{
DisplayLastError(L"ShellExecute failed", shellRc);
}
}
void ConEmuAbout::OnInfo_ReportBug()
{
DWORD shellRc = (DWORD)(INT_PTR)ShellExecute(ghWnd, L"open", gsReportBug, NULL, NULL, SW_SHOWNORMAL);
if (shellRc <= 32)
{
DisplayLastError(L"ShellExecute failed", shellRc);
}
}
void ConEmuAbout::OnInfo_ReportCrash(LPCWSTR asDumpWasCreatedMsg)
{
if (nLastCrashReported)
{
// if previous gsReportCrash was opened less than 60 sec ago
DWORD nLast = GetTickCount() - nLastCrashReported;
if (nLast < 60000)
{
// Skip this time
return;
}
}
if (asDumpWasCreatedMsg && !*asDumpWasCreatedMsg)
{
asDumpWasCreatedMsg = NULL;
}
DWORD shellRc = (DWORD)(INT_PTR)ShellExecute(ghWnd, L"open", gsReportCrash, NULL, NULL, SW_SHOWNORMAL);
if (shellRc <= 32)
{
DisplayLastError(L"ShellExecute failed", shellRc);
}
else if (asDumpWasCreatedMsg)
{
MsgBox(asDumpWasCreatedMsg, MB_OK|MB_ICONEXCLAMATION|MB_SYSTEMMODAL);
}
nLastCrashReported = GetTickCount();
}
void ConEmuAbout::OnInfo_ThrowTrapException(bool bMainThread)
{
if (bMainThread)
{
if (MsgBox(L"Are you sure?\nApplication will terminate after that!\nThrow exception in ConEmu's main thread?", MB_ICONEXCLAMATION|MB_YESNO|MB_DEFBUTTON2)==IDYES)
{
//#ifdef _DEBUG
//MyAssertTrap();
//#else
//DebugBreak();
//#endif
// -- trigger division by 0
RaiseTestException();
}
}
else
{
if (MsgBox(L"Are you sure?\nApplication will terminate after that!\nThrow exception in ConEmu's monitor thread?", MB_ICONEXCLAMATION|MB_YESNO|MB_DEFBUTTON2)==IDYES)
{
CVConGuard VCon;
if ((gpConEmu->GetActiveVCon(&VCon) >= 0) && VCon->RCon())
VCon->RCon()->MonitorAssertTrap();
}
}
}
| 18,023 | 8,714 |
//
// sharpen_effect.cpp
// liveDemo
//
// Created by apple on 16/5/12.
// Copyright © 2016年 changba. All rights reserved.
//
#include "sharpen_effect.h"
#define LOG_TAG "SharpenEffect"
SharpenEffect::SharpenEffect() {
mVertexShader = SHARPEN_EFFECT_VERTEX_SHADER;
mFragmentShader = SHARPEN_EFFECT_FRAGMENT_SHADER;
}
SharpenEffect::~SharpenEffect() {
}
bool SharpenEffect::init() {
if (BaseVideoEffect::init()) {
sharpnessUniform = glGetUniformLocation(mGLProgId, "sharpness");
checkGlError("glGetUniformLocation sharpnessUniform");
imageWidthFactorUniform = glGetUniformLocation(mGLProgId, "imageWidthFactor");
checkGlError("glGetUniformLocation imageWidthFactorUniform");
imageHeightFactorUniform = glGetUniformLocation(mGLProgId, "imageHeightFactor");
checkGlError("glGetUniformLocation imageHeightFactorUniform");
return true;
}
return false;
}
void SharpenEffect::onDrawArraysPre(EffectCallback * filterCallback) {
if (filterCallback) {
ParamVal val;
bool suc = filterCallback->getParamValue(string(SHARPEN_EFFECT_SHARPNESS), val);
if (suc) {
float sharpness = 0.0f;
if (suc) {
sharpness = val.u.fltVal;
// LOGI("get success, sharpness:%.3f", sharpness);
} else {
LOGI("get sharpness failed, use default value sharpness");
}
glUniform1f(sharpnessUniform, sharpness);
checkGlError("glUniform1f sharpnessUniform");
}
suc = filterCallback->getParamValue(string(IMAGE_EFFECT_GROUP_TEXTURE_WIDTH), val);
if (suc) {
float inputWidth = 720.f;
if (suc) {
inputWidth = val.u.intVal;
// LOGI("get success, inputWidth:%.3f", inputWidth);
} else {
LOGI("get inputWidth failed, use default value inputWidth");
}
glUniform1f(imageWidthFactorUniform, 1.0 / inputWidth);
checkGlError("glUniform1f imageWidthFactorUniform");
}
suc = filterCallback->getParamValue(string(IMAGE_EFFECT_GROUP_TEXTURE_HEIGHT), val);
if (suc) {
float inputHeight = 1280.f;
if (suc) {
inputHeight = val.u.intVal;
// LOGI("get success, inputHeight:%.3f", inputHeight);
} else {
LOGI("get inputHeight failed, use default value inputHeight");
}
glUniform1f(imageHeightFactorUniform, 1.0 / inputHeight);
checkGlError("glUniform1f imageHeightFactorUniform");
}
}
} | 2,655 | 840 |
#include <Arduino.h>
#include "loramesher.h"
LoraMesher *radio;
void setup() {
Serial.begin(9600);
radio = new LoraMesher();
}
void loop() {
sleep(7);
radio->sendDataPacket();
} | 190 | 84 |
// expect-success
/*
* Copyright 2014 Google Inc. 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.
*/
#define IN_FRUIT_CPP_FILE
#include <fruit/impl/util/lambda_invoker.h>
#include "../test_macros.h"
#include <cassert>
using namespace std;
using namespace fruit::impl;
void test_invoke_no_args() {
// This is static because the lambda must have no captures.
static int num_invocations = 0;
auto l = []() {
++num_invocations;
};
using L = decltype(l);
LambdaInvoker::invoke<L>();
Assert(num_invocations == 1);
}
void test_invoke_some_args() {
// This is static because the lambda must have no captures.
static int num_invocations = 0;
auto l = [](int n, double x) {
Assert(n == 5);
Assert(x == 3.14);
++num_invocations;
};
using L = decltype(l);
LambdaInvoker::invoke<L>(5, 3.14);
Assert(num_invocations == 1);
}
int main() {
test_invoke_no_args();
test_invoke_some_args();
return 0;
}
| 1,490 | 520 |
// C++ Program to Implement Rolling Hash
#include <iostream>
#include <string>
using namespace std;
const unsigned PRIME_BASE = 257;
const unsigned PRIME_MOD = 1000000007;
/*
* Hash Function
*/
unsigned hash(const string& s)
{
long long ret = 0;
for (int i = 0; i < s.size(); i++)
{
ret = ret * PRIME_BASE + s[i];
ret %= PRIME_MOD;
}
return ret;
}
/*
* Rabin-Karp (Rolling Hash Implementation)
*/
int rabin_karp(const string& needle, const string& haystack)
{
long long hash1 = hash(needle);
long long hash2 = 0;
long long power = 1;
for (int i = 0; i < needle.size(); i++)
power = (power * PRIME_BASE) % PRIME_MOD;
for (int i = 0; i < haystack.size(); i++)
{
hash2 = hash2*PRIME_BASE + haystack[i];
hash2 %= PRIME_MOD;
if (i >= needle.size())
{
hash2 -= power * haystack[i-needle.size()] % PRIME_MOD;
if (hash2 < 0)
hash2 += PRIME_MOD;
}
if (i >= needle.size()-1 && hash1 == hash2)
return i - (needle.size()-1);
}
return -1;
}
/*
* Main Contains Menu
*/
int main()
{
cout<<"---------------------------"<<endl;
cout<<"Rolling Hash Implementation"<<endl;
cout<<"---------------------------"<<endl;
string s1,s2;
cout<<"Enter Original String: ";
getline(cin,s1);
cout<<"Enter String to find: ";
cin>>s2;
if(rabin_karp(s2, s1) == -1)
cout<<"String not found"<<endl;
else
cout<<"String "<<s2<<"found at position "<<rabin_karp(s2, s1)<<endl;
return 0;
}
| 1,602 | 624 |
// Copyright Aleksey Gurtovoy 2000-2004
//
// 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)
//
// Preprocessed version of "boost/mpl/list/list20.hpp" header
// -- DO NOT modify by hand!
namespace mars_boost {}
namespace boost = mars_boost;
namespace mars_boost {
namespace mpl {
template<
typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10
>
struct list11
: l_item<
long_ < 11>, T0, list10<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>
> {
typedef list11 type;
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11
>
struct list12
: l_item<
long_ < 12>, T0, list11<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>
> {
typedef list12 type;
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12
>
struct list13
: l_item<
long_ < 13>, T0, list12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>
>
{
typedef list13 type;
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13
>
struct list14
: l_item<
long_ < 14>, T0, list13<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>
>
{
typedef list14 type;
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14
>
struct list15
: l_item<
long_ < 15>, T0, list14<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14>
>
{
typedef list15 type;
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15
>
struct list16
: l_item<
long_ < 16>, T0, list15<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15>
>
{
typedef list16 type;
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16
>
struct list17
: l_item<
long_ < 17>, T0, list16<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16>
>
{
typedef list17 type;
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17
>
struct list18
: l_item<
long_ < 18>, T0, list17<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17>
>
{
typedef list18 type;
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18
>
struct list19
: l_item<
long_ < 19>, T0, list18<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18>
>
{
typedef list19 type;
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct list20
: l_item<
long_ < 20>, T0, list19<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19>
>
{
typedef list20 type;
};
}}
| 4,265 | 2,037 |
#include "precompiled.h"
#include "json_tests.h"
#include <boost/format.hpp>
#include <boost/static_assert.hpp>
#include <locale>
#include <stdarg.h>
#include <type_traits>
using namespace bond;
template <typename From, typename To>
const To& operator->*(const From& from, To& to)
{
bond::OutputBuffer buffer;
bond::SimpleJsonWriter<bond::OutputBuffer> json_writer(buffer);
bond::Serialize(from, json_writer);
bond::SimpleJsonReader<bond::InputBuffer> json_reader(buffer.GetBuffer());
bond::Deserialize(json_reader, to);
return to;
}
template <typename Reader, typename Writer>
TEST_CASE_BEGIN(StringRoundtripTest)
{
BondStruct<std::string> str1, str2;
BondStruct<std::wstring> wstr1, wstr2;
str1.field += "Arabic: \xD9\x85\xD8\xB1\xD8\xAD\xD8\xA8\xD8\xA7 \xD8\xA7\xD9\x84\xD8\xB9\xD8\xA7\xD9\x84\xD9\x85 | ";
str1.field += "Chinese: \xE4\xBD\xA0\xE5\xA5\xBD\xE4\xB8\x96\xE7\x95\x8C | ";
str1.field += "Hebrew: \xD7\xA9\xD7\x9C\xD7\x95\xD7\x9D \xD7\xA2\xD7\x95\xD7\x9C\xD7\x9D | ";
str1.field += "Japanese: \xE3\x81\x93\xE3\x82\x93\xE3\x81\xAB\xE3\x81\xA1\xE3\x81\xAF\xE4\xB8\x96\xE7\x95\x8C | ";
str1.field += "Russian: \xD0\x9F\xD1\x80\xD0\xB8\xD0\xB2\xD0\xB5\xD1\x82 \xD0\xBC\xD0\xB8\xD1\x80 | ";
str1.field += "Escaped: \" \\ / \b \f \n \r \t \x1 \x1f ";
str1.field += '\x0';
str1 ->* wstr1 ->* str2 ->* wstr2;
UT_AssertIsTrue(str1 == str2);
UT_AssertIsTrue(wstr1 == wstr2);
}
TEST_CASE_END
template <typename T, typename Reader, typename Writer>
TEST_CASE_BEGIN(StreamDeserializationTest)
{
const int count = 10;
T from[count];
typename Writer::Buffer output;
// Serialize random objects
{
Writer writer(output);
for (int i = count; i--;)
{
from[i] = InitRandom<T>();
Serialize(from[i], writer);
}
}
// Deserialize the objects
{
Reader reader(output.GetBuffer());
bond::bonded<T, Reader&> stream(reader);
for (int i = count; i--;)
{
T record = InitRandom<T>();
stream.Deserialize(record);
UT_Equal(from[i], record);
}
}
// Deserialize the first object twice
{
Reader reader(output.GetBuffer());
T r1, r2;
r1 = InitRandom<T>();
r2 = InitRandom<T>();
Deserialize(reader, r1);
Deserialize(reader, r2);
UT_Equal(r1, r2);
bond::bonded<T> bonded(reader);
r1 = InitRandom<T>();
r2 = InitRandom<T>();
bonded.Deserialize(r1);
bonded.Deserialize(r2);
UT_Equal(r1, r2);
}
}
TEST_CASE_END
template <typename Record, typename Intermediate, typename Reader1, typename Writer1, typename Reader2, typename Writer2>
void StreamTranscoding(uint16_t version = bond::v1)
{
const int count = 10;
Record records[count];
// Serialize random objects using protocol 1
typename Writer1::Buffer output1;
Writer1 writer1(output1);
for (int i = count; i--;)
{
records[i] = InitRandom<Record>();
Serialize(records[i], writer1);
}
// Tanscode the objects from protocol 1 to protocol 2
Reader1 reader1(output1.GetBuffer());
typename Writer2::Buffer output2;
Writer2 writer2(output2, version);
for (int i = count; i--;)
{
bond::bonded<Intermediate> record;
bond::bonded<Intermediate, Reader1&>(reader1).Deserialize(record);
Serialize(record, writer2);
}
// Deserialize the objects from protocol 2
Reader2 reader2(output2.GetBuffer(), version);
bond::bonded<Record, Reader2&> stream(reader2);
for (int i = count; i--;)
{
Record record = InitRandom<Record>();
stream.Deserialize(record);
UT_Equal(records[i], record);
}
}
template <typename Reader, typename Writer>
TEST_CASE_BEGIN(StreamTranscodingTest)
{
StreamTranscoding<
StructWithBase,
SimpleStruct,
Reader,
Writer,
bond::CompactBinaryReader<bond::InputBuffer>,
bond::CompactBinaryWriter<bond::OutputBuffer>
>(bond::v1);
StreamTranscoding<
StructWithBase,
SimpleStruct,
Reader,
Writer,
bond::CompactBinaryReader<bond::InputBuffer>,
bond::CompactBinaryWriter<bond::OutputBuffer>
>(bond::v2);
StreamTranscoding<
NestedStruct,
NestedStructBondedView,
Reader,
Writer,
bond::CompactBinaryReader<bond::InputBuffer>,
bond::CompactBinaryWriter<bond::OutputBuffer>
>(bond::v1);
StreamTranscoding<
NestedStruct,
NestedStructBondedView,
Reader,
Writer,
bond::CompactBinaryReader<bond::InputBuffer>,
bond::CompactBinaryWriter<bond::OutputBuffer>
>(bond::v2);
}
TEST_CASE_END
template <uint16_t N, typename Reader, typename Writer>
void StringTests(UnitTestSuite& suite)
{
BOOST_STATIC_ASSERT(std::is_copy_constructible<Reader>::value);
BOOST_STATIC_ASSERT(std::is_move_constructible<Reader>::value);
BOOST_STATIC_ASSERT(std::is_copy_assignable<Reader>::value);
BOOST_STATIC_ASSERT(std::is_move_assignable<Reader>::value);
AddTestCase<TEST_ID(N),
StringRoundtripTest, Reader, Writer>(suite, "Roundtrip string/wstring");
AddTestCase<TEST_ID(N),
StreamDeserializationTest, NestedStruct, Reader, Writer>(suite, "Stream deserialization test");
}
TEST_CASE_BEGIN(ReaderOverCStr)
{
using Reader = bond::SimpleJsonReader<const char*>;
BOOST_STATIC_ASSERT(std::is_copy_constructible<Reader>::value);
BOOST_STATIC_ASSERT(std::is_move_constructible<Reader>::value);
BOOST_STATIC_ASSERT(std::is_copy_assignable<Reader>::value);
BOOST_STATIC_ASSERT(std::is_move_assignable<Reader>::value);
const char* literalJson = "{ \"m_str\": \"specialized for const char*\" }";
Reader json_reader(literalJson);
SimpleStruct to;
bond::Deserialize(json_reader, to);
BOOST_CHECK_EQUAL("specialized for const char*", to.m_str);
}
TEST_CASE_END
TEST_CASE_BEGIN(DeepNesting)
{
const size_t nestingDepth = 10000;
std::string listOpens(nestingDepth, '[');
std::string listCloses(nestingDepth, ']');
std::string deeplyNestedList = boost::str(
boost::format("{\"deeplyNestedList\": %strue%s}") % listOpens % listCloses);
bond::SimpleJsonReader<const char*> json_reader(deeplyNestedList.c_str());
// The type here doesn't really matter. We need something with no
// required fields, as we're really just testing that we can parse a
// deeply nested JSON array without crashing.
SimpleStruct to;
bond::Deserialize(json_reader, to);
}
TEST_CASE_END
void JSONTest::Initialize()
{
UnitTestSuite suite("Simple JSON test");
TEST_SIMPLE_JSON_PROTOCOL(
StringTests<
0x1c04,
bond::SimpleJsonReader<bond::InputBuffer>,
bond::SimpleJsonWriter<bond::OutputBuffer> >(suite);
);
AddTestCase<TEST_ID(0x1c05), DeepNesting>(suite, "Deeply nested JSON struct");
AddTestCase<TEST_ID(0x1c06), ReaderOverCStr>(suite, "SimpleJsonReader<const char*> specialization");
}
bool init_unit_test()
{
JSONTest::Initialize();
return true;
}
| 7,276 | 2,733 |
#include "aap/android-application-context.h"
namespace aap {
// Android-specific API. Not sure if we would like to keep it in the host API - it is for plugins.
JavaVM *android_vm{nullptr};
jobject application_context{nullptr};
extern "C" JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved) {
android_vm = vm;
return JNI_VERSION_1_6;
}
void unset_application_context(JNIEnv *env) {
if (application_context)
env->DeleteGlobalRef(application_context);
}
void set_application_context(JNIEnv *env, jobject jobjectApplicationContext) {
if (application_context)
unset_application_context(env);
application_context = env->NewGlobalRef((jobject) jobjectApplicationContext);
}
JavaVM *get_android_jvm() { return android_vm; }
jobject get_android_application_context() { return application_context; }
AAssetManager *get_android_asset_manager(JNIEnv* env) {
if (!application_context)
return nullptr;
auto appClass = env->GetObjectClass(application_context);
auto getAssetsID = env->GetMethodID(appClass, "getAssets", "()Landroid/content/res/AssetManager;");
auto assetManagerJ = env->CallObjectMethod(application_context, getAssetsID);
return AAssetManager_fromJava(env, assetManagerJ);
}
}
| 1,215 | 393 |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#include "PlatformConstantsModule.h"
#include <VersionHelpers.h>
using Method = facebook::xplat::module::CxxModule::Method;
#ifndef RNW_PKG_VERSION_MAJOR
#define RNW_PKG_VERSION_MAJOR 1000
#endif
#ifndef RNW_PKG_VERSION_MINOR
#define RNW_PKG_VERSION_MINOR 0
#endif
#ifndef RNW_PKG_VERSION_PATCH
#define RNW_PKG_VERSION_PATCH 0
#endif
namespace facebook::react {
const char *PlatformConstantsModule::Name = "PlatformConstants";
std::string PlatformConstantsModule::getName() {
return PlatformConstantsModule::Name;
}
std::vector<Method> PlatformConstantsModule::getMethods() {
return {};
}
std::map<std::string, folly::dynamic> PlatformConstantsModule::getConstants() {
return {
// We don't currently treat Native code differently in a test environment
{"isTesting", false},
// Since we're out-of-tree, we don't know the exact version of React Native
// we're paired with. Provide something sane for now, and try to provide a
// better source of truth later. Tracked by Issue #4073
{"reactNativeVersion", folly::dynamic::object("major", 0)("minor", 62)("patch", 0)},
// Provide version information for react-native-windows -- which is independant of
// the version of react-native we are built from
{"reactNativeWindowsVersion",
folly::dynamic::object("major", RNW_PKG_VERSION_MAJOR)("minor", RNW_PKG_VERSION_MINOR)(
"patch", RNW_PKG_VERSION_PATCH)}
// We don't provide the typical OS version here. Windows make it hard to
// get an exact version by-design. In the future we should consider
// exposing something here like a facility to check Universal API
// Contract.
};
}
} // namespace facebook::react
| 1,854 | 599 |
// Copyright 2015 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 "config.h"
#include "modules/screen_orientation/ScreenOrientationInspectorAgent.h"
#include "core/InspectorTypeBuilder.h"
#include "core/frame/LocalFrame.h"
#include "core/inspector/InspectorState.h"
#include "modules/screen_orientation/ScreenOrientation.h"
#include "modules/screen_orientation/ScreenOrientationController.h"
namespace blink {
namespace ScreenOrientationInspectorAgentState {
static const char angle[] = "angle";
static const char type[] = "type";
static const char overrideEnabled[] = "overrideEnabled";
}
namespace {
WebScreenOrientationType WebScreenOrientationTypeFromString(const String& type)
{
if (type == TypeBuilder::getEnumConstantValue(TypeBuilder::ScreenOrientation::OrientationType::PortraitPrimary))
return WebScreenOrientationPortraitPrimary;
if (type == TypeBuilder::getEnumConstantValue(TypeBuilder::ScreenOrientation::OrientationType::PortraitSecondary))
return WebScreenOrientationPortraitSecondary;
if (type == TypeBuilder::getEnumConstantValue(TypeBuilder::ScreenOrientation::OrientationType::LandscapePrimary))
return WebScreenOrientationLandscapePrimary;
if (type == TypeBuilder::getEnumConstantValue(TypeBuilder::ScreenOrientation::OrientationType::LandscapeSecondary))
return WebScreenOrientationLandscapeSecondary;
return WebScreenOrientationUndefined;
}
} // namespace
// static
PassOwnPtrWillBeRawPtr<ScreenOrientationInspectorAgent> ScreenOrientationInspectorAgent::create(LocalFrame& frame)
{
return adoptPtrWillBeNoop(new ScreenOrientationInspectorAgent(frame));
}
ScreenOrientationInspectorAgent::~ScreenOrientationInspectorAgent()
{
}
ScreenOrientationInspectorAgent::ScreenOrientationInspectorAgent(LocalFrame& frame)
: InspectorBaseAgent<ScreenOrientationInspectorAgent, InspectorFrontend::ScreenOrientation>("ScreenOrientation")
, m_frame(frame)
{
}
void ScreenOrientationInspectorAgent::setScreenOrientationOverride(ErrorString* error, int angle, const String& typeString)
{
if (angle < 0 || angle >= 360) {
*error = "Angle should be in [0; 360) interval";
return;
}
WebScreenOrientationType type = WebScreenOrientationTypeFromString(typeString);
if (type == WebScreenOrientationUndefined) {
*error = "Wrong type value";
return;
}
ScreenOrientationController* controller = ScreenOrientationController::from(m_frame);
if (!controller) {
*error = "Cannot connect to orientation controller";
return;
}
m_state->setBoolean(ScreenOrientationInspectorAgentState::overrideEnabled, true);
m_state->setLong(ScreenOrientationInspectorAgentState::angle, angle);
m_state->setLong(ScreenOrientationInspectorAgentState::type, type);
controller->setOverride(type, angle);
}
void ScreenOrientationInspectorAgent::clearScreenOrientationOverride(ErrorString* error)
{
ScreenOrientationController* controller = ScreenOrientationController::from(m_frame);
if (!controller) {
*error = "Cannot connect to orientation controller";
return;
}
m_state->setBoolean(ScreenOrientationInspectorAgentState::overrideEnabled, false);
controller->clearOverride();
}
void ScreenOrientationInspectorAgent::disable(ErrorString*)
{
m_state->setBoolean(ScreenOrientationInspectorAgentState::overrideEnabled, false);
if (ScreenOrientationController* controller = ScreenOrientationController::from(m_frame))
controller->clearOverride();
}
void ScreenOrientationInspectorAgent::restore()
{
if (m_state->getBoolean(ScreenOrientationInspectorAgentState::overrideEnabled)) {
WebScreenOrientationType type = static_cast<WebScreenOrientationType>(m_state->getLong(ScreenOrientationInspectorAgentState::type));
int angle = m_state->getLong(ScreenOrientationInspectorAgentState::angle);
if (ScreenOrientationController* controller = ScreenOrientationController::from(m_frame))
controller->setOverride(type, angle);
}
}
} // namespace blink
| 4,190 | 1,097 |
/* -*-c++-*- */
/* osgEarth - Dynamic map generation toolkit for OpenSceneGraph
* Copyright 2008-2012 Pelican Mapping
* http://osgearth.org
*
* osgEarth 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 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
#include <osgEarthUtil/ContourMap>
#include <osgEarth/Registry>
#include <osgEarth/Capabilities>
#include <osgEarth/VirtualProgram>
#include <osgEarth/TerrainEngineNode>
#define LC "[ContourMap] "
using namespace osgEarth;
using namespace osgEarth::Util;
namespace
{
const char* vs =
"#version " GLSL_VERSION_STR "\n"
GLSL_DEFAULT_PRECISION_FLOAT "\n"
"attribute vec4 oe_terrain_attr; \n"
"uniform float oe_contour_min; \n"
"uniform float oe_contour_range; \n"
"varying float oe_contour_lookup; \n"
"void oe_contour_vertex(inout vec4 VertexModel) \n"
"{ \n"
" float height = oe_terrain_attr[3]; \n"
" float height_normalized = (height-oe_contour_min)/oe_contour_range; \n"
" oe_contour_lookup = clamp( height_normalized, 0.0, 1.0 ); \n"
"} \n";
const char* fs =
"#version " GLSL_VERSION_STR "\n"
GLSL_DEFAULT_PRECISION_FLOAT "\n"
"uniform sampler1D oe_contour_xfer; \n"
"uniform float oe_contour_opacity; \n"
"varying float oe_contour_lookup; \n"
"void oe_contour_fragment( inout vec4 color ) \n"
"{ \n"
" vec4 texel = texture1D( oe_contour_xfer, oe_contour_lookup ); \n"
" color.rgb = mix(color.rgb, texel.rgb, texel.a * oe_contour_opacity); \n"
"} \n";
}
ContourMap::ContourMap() :
TerrainEffect()
{
init();
}
ContourMap::ContourMap(const Config& conf) :
TerrainEffect()
{
mergeConfig(conf);
init();
}
void
ContourMap::init()
{
// negative means unset:
_unit = -1;
// uniforms we'll need:
_xferMin = new osg::Uniform(osg::Uniform::FLOAT, "oe_contour_min" );
_xferRange = new osg::Uniform(osg::Uniform::FLOAT, "oe_contour_range" );
_xferSampler = new osg::Uniform(osg::Uniform::SAMPLER_1D, "oe_contour_xfer" );
_opacityUniform = new osg::Uniform(osg::Uniform::FLOAT, "oe_contour_opacity" );
_opacityUniform->set( _opacity.getOrUse(1.0f) );
// Create a 1D texture from the transfer function's image.
_xferTexture = new osg::Texture1D();
_xferTexture->setResizeNonPowerOfTwoHint( false );
_xferTexture->setFilter( osg::Texture::MIN_FILTER, osg::Texture::LINEAR );
_xferTexture->setFilter( osg::Texture::MAG_FILTER, osg::Texture::LINEAR );
_xferTexture->setWrap( osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE );
// build a default transfer function.
// TODO: think about scale/bias controls.
osg::TransferFunction1D* xfer = new osg::TransferFunction1D();
float s = 2500.0f;
xfer->setColor( -1.0000 * s, osg::Vec4f(0, 0, 0.5, 1), false);
xfer->setColor( -0.2500 * s, osg::Vec4f(0, 0, 1, 1), false);
xfer->setColor( 0.0000 * s, osg::Vec4f(0, .5, 1, 1), false);
xfer->setColor( 0.0062 * s, osg::Vec4f(.84,.84,.25,1), false);
//xfer->setColor( 0.0625 * s, osg::Vec4f(.94,.94,.25,1), false);
xfer->setColor( 0.1250 * s, osg::Vec4f(.125,.62,0,1), false);
xfer->setColor( 0.3250 * s, osg::Vec4f(.80,.70,.47,1), false);
xfer->setColor( 0.7500 * s, osg::Vec4f(.5,.5,.5,1), false);
xfer->setColor( 1.0000 * s, osg::Vec4f(1,1,1,1), false);
xfer->updateImage();
this->setTransferFunction( xfer );
}
ContourMap::~ContourMap()
{
//nop
}
void
ContourMap::setTransferFunction(osg::TransferFunction1D* xfer)
{
_xfer = xfer;
_xferTexture->setImage( _xfer->getImage() );
_xferMin->set( _xfer->getMinimum() );
_xferRange->set( _xfer->getMaximum() - _xfer->getMinimum() );
}
void
ContourMap::setOpacity(float opacity)
{
_opacity = osg::clampBetween(opacity, 0.0f, 1.0f);
_opacityUniform->set( _opacity.get() );
}
void
ContourMap::onInstall(TerrainEngineNode* engine)
{
if ( engine )
{
if ( !engine->getTextureCompositor()->reserveTextureImageUnit(_unit) )
{
OE_WARN << LC << "Failed to reserve a texture image unit; disabled." << std::endl;
return;
}
osg::StateSet* stateset = engine->getOrCreateStateSet();
// Install the texture and its sampler uniform:
stateset->setTextureAttributeAndModes( _unit, _xferTexture.get(), osg::StateAttribute::ON );
stateset->addUniform( _xferSampler.get() );
_xferSampler->set( _unit );
// (By the way: if you want to draw image layers on top of the contoured terrain,
// set the "priority" parameter to setFunction() to a negative number so that it draws
// before the terrain's layers.)
VirtualProgram* vp = VirtualProgram::getOrCreate(stateset);
vp->setFunction( "oe_contour_vertex", vs, ShaderComp::LOCATION_VERTEX_MODEL);
vp->setFunction( "oe_contour_fragment", fs, ShaderComp::LOCATION_FRAGMENT_COLORING ); //, -1.0);
// Install some uniforms that tell the shader the height range of the color map.
stateset->addUniform( _xferMin.get() );
_xferMin->set( _xfer->getMinimum() );
stateset->addUniform( _xferRange.get() );
_xferRange->set( _xfer->getMaximum() - _xfer->getMinimum() );
stateset->addUniform( _opacityUniform.get() );
}
}
void
ContourMap::onUninstall(TerrainEngineNode* engine)
{
if ( engine )
{
osg::StateSet* stateset = engine->getStateSet();
if ( stateset )
{
stateset->removeUniform( _xferMin.get() );
stateset->removeUniform( _xferRange.get() );
stateset->removeUniform( _xferSampler.get() );
stateset->removeUniform( _opacityUniform.get() );
stateset->removeTextureAttribute( _unit, osg::StateAttribute::TEXTURE );
VirtualProgram* vp = VirtualProgram::get(stateset);
if ( vp )
{
vp->removeShader( "oe_contour_vertex" );
vp->removeShader( "oe_contour_fragment" );
}
}
if ( _unit >= 0 )
{
engine->getTextureCompositor()->releaseTextureImageUnit( _unit );
_unit = -1;
}
}
}
//-------------------------------------------------------------
void
ContourMap::mergeConfig(const Config& conf)
{
conf.getIfSet("opacity", _opacity);
}
Config
ContourMap::getConfig() const
{
Config conf("contour_map");
conf.addIfSet("opacity", _opacity);
return conf;
}
| 7,142 | 2,614 |
// Mono Native Fixture
// Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// Namespace: System.Runtime.Serialization
// Name: IObjectReference
// C++ Typed Name: mscorlib::System::Runtime::Serialization::IObjectReference
#include <gtest/gtest.h>
#include <mscorlib/System/Runtime/Serialization/mscorlib_System_Runtime_Serialization_IObjectReference.h>
#include <mscorlib/System/Runtime/Serialization/mscorlib_System_Runtime_Serialization_StreamingContext.h>
namespace mscorlib
{
namespace System
{
namespace Runtime
{
namespace Serialization
{
//Public Methods Tests
// Method GetRealObject
// Signature: mscorlib::System::Runtime::Serialization::StreamingContext context
TEST(mscorlib_System_Runtime_Serialization_IObjectReference_Fixture,GetRealObject_Test)
{
}
}
}
}
}
| 878 | 336 |
// Copyright (c) 2018 The Open-Transactions developers
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef OPENTXS_CASH_DIGITALCASH_HPP
#define OPENTXS_CASH_DIGITALCASH_HPP
#include "opentxs/Forward.hpp"
#if OT_CASH
// WHICH DIGITAL CASH LIBRARY?
//
// Many algorithms may come available. We are currently using Lucre, by Ben
// Laurie,
// which is an implementation of Wagner, which is a variant of Chaum.
//
// We plan to have alternatives such as "Magic Money" by Pr0duct Cypher.
//
// Implementations for Chaum and Brands are circulating online. They could all
// be easily added here as options for Open-Transactions.
#if OT_CASH_USING_LUCRE
// IWYU pragma: begin_exports
#include <lucre/bank.h>
// IWYU pragma: end_exports
#endif
#if OT_CASH_USING_MAGIC_MONEY
#include... // someday
#endif
#include <string>
namespace opentxs
{
#if OT_CASH_USING_LUCRE
class LucreDumper
{
std::string m_str_dumpfile;
public:
LucreDumper();
~LucreDumper();
};
#endif
#if OT_CASH_USING_MAGIC_MONEY
// Todo: Someday...
#endif
} // namespace opentxs
#endif // OT_CASH
#endif
| 1,249 | 485 |
#ifndef LOTHAR_UTILS_HH
#define LOTHAR_UTILS_HH
#include "utils.h"
#include "error_handling.hh"
#include <algorithm>
// a bit dirty, but avoid all tr1/c++11/whatever trickery by redeclaring shared_ptr in the lothar namespace
#ifdef HAVE_SHARED_PTR
#include <memory>
namespace lothar
{
template <typename T>
class shared_ptr : public std::shared_ptr<T>
{
public:
explicit shared_ptr(T *p = 0) : std::shared_ptr<T>(p)
{}
};
}
#else // HAVE_SHARED_PTR need the tr1 version
// microsoft has std::tr1::shared_ptr in <memory> by default, others (i.e. gcc) in <tr1/memory>
#if _MSC_VER
#include <memory>
#else
#include <tr1/memory>
#endif
namespace lothar
{
template <typename T>
class shared_ptr : public std::tr1::shared_ptr<T>
{
public:
explicit shared_ptr(T *p = 0) : std::tr1::shared_ptr<T>(p)
{}
};
}
#endif // HAVE_SHARED_PTR
namespace lothar
{
/** \brief return the value, but no smaller than min, no greater than max
*/
template <typename T>
T const &clamp(T const &val, T const &min, T const &max)
{
return (val < min ? min : (val > max ? max : val));
}
/** \brief The minimum value of a and b
*/
template <typename T>
T const &min(T const &a, T const &b)
{
return std::min<T>(a, b);
}
/** \brief The maximum value of a and b
*/
template <typename T>
T const &max(T const &a, T const &b)
{
return std::max<T>(a, b);
}
/** \brief Convert degrees to radians
*/
template <typename T1, typename T2>
T1 degtorad(T2 const °)
{
return static_cast<T1>(deg * M_PI / 180.0);
}
/** \brief Convert radians to degrees
*/
template <typename T1, typename T2>
T1 radtodeg(T2 const &rad)
{
T2 t = static_cast<T2>(rad * 180.0 / M_PI);
return static_cast<T1>(t);
}
/** \brief Convert a short from host endianness to NXT (small) endianness
*
* \param val a 32 bit integer
* \param buf a 2 byte buffer to hold the result
*/
inline void htonxts(uint16_t val, uint8_t buf[2])
{
lothar_htonxts(val, buf);
}
/** \brief Convert a short from NXT (small) endianness to host endianness
*
* \param buf a 2 byte buffer received from the NXT
* \returns the value in host endianness
*/
inline uint16_t nxttohs(uint8_t const buf[2])
{
return lothar_nxttohs(buf);
}
/** \brief Convert a long from host endianness to NXT (small) endianness
*
* \param val a 32 bit integer
* \param buf a 4 byte buffer to hold the result
*/
inline void htonxtl(uint32_t val, uint8_t buf[4])
{
lothar_htonxtl(val, buf);
}
/** \brief Convert a long from NXT (small) endianness to host endianness
*
* \param buf a 4 byte buffer received from the NXT
* \returns the value in host endianness
*/
inline uint32_t nxttohl(uint8_t const buf[4])
{
return lothar_nxttohl(buf);
}
/** \brief The output ports (A-C, ALL)
*/
typedef enum lothar_output_port output_port;
/** \brief The input ports (1-4)
*/
typedef enum lothar_input_port input_port;
/** \brief The motor modes
*/
typedef enum lothar_output_motor_mode output_motor_mode;
/** \brief The motor regulation modes
*/
typedef enum lothar_output_regulation_mode output_regulation_mode;
/** \brief The motor runstates
*/
typedef enum lothar_output_runstate output_runstate;
/** \brief Varius types of sensors
*/
typedef enum lothar_sensor_type sensor_type;
/** \brief varius input modes */
typedef enum lothar_sensor_mode sensor_mode;
/** \brief enum for the SENSOR_COLORFULL detection mode
*/
typedef enum lothar_color color;
/** \brief redaclaration in lothar namespace
*/
typedef lothar_time_t time_t;
/** \brief sleep for the specified number of milliseconds
*/
inline void msleep(lothar_time_t ms)
{
check_return(lothar_msleep(ms));
}
/** \brief simple timer, returns the number of milliseconds since the last time this function was called (0 if this is
* the first time this function is called)
*/
inline time_t time()
{
return lothar_time();
}
/** \brief slightly more advanced timer.
*
* use timer(NULL) to create a new timer, and pass the return value to the next calls to get the number of
* milliseconds since the creation time
*/
inline time_t timer(time_t *timer)
{
return lothar_timer(timer);
}
/** \brief base class for classes that shouldn't allow copying
*/
class no_copy
{
// private and not implemented
no_copy(no_copy const &);
no_copy &operator=(no_copy const &);
public:
no_copy()
{}
};
}
#endif // LOTHAR_UTILS_HH
| 4,643 | 1,731 |
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include <map>
#include "linker.h"
FILE *in; //for read module
FILE *out; //for output link result
/*offset of the current module
assume current module is I+1, the offset of I+1
will be LENGTH(0) + LENGTH(1) + ...... LENGTH(I)
where the LENGTH(I) represents the length of module I
*/
int g_offset = 0;
/*you can modify this function!*/
/*
test_num: which file test, it must between 1 and 9
filename: the file that you should do with
*/
void link(int testNum, const char *filename)
{
char outputfile[128];
memset(outputfile, 0, 128);
sprintf(outputfile, "output-%d.txt", testNum);
in = fopen(filename, "r"); //open file for read,the file contains module that you should do with
out = fopen(outputfile, "w"); //open the "output" file to output link result
if (in == NULL || out == NULL)
{
fprintf(stderr, "can not open file for read or write\n");
exit(-1);
}
processOne(); //resolve
processTwo(); //relocate
fclose(in);
fclose(out);
}
////////////////////////////////////////////////////////////////////////////////
struct ListItem {
std::string variableName;
int offset;
ListItem(char *variableName, int offset) {
this->variableName = variableName;
this->offset = offset;
}
};
struct TextItem {
char addressType;
int word;
TextItem(char addressType, int word) {
this->addressType = addressType;
this->word = word;
}
};
struct ObjectFile {
std::vector<ListItem> definitionList;
std::vector<ListItem> useList;
std::vector<TextItem> programText;
};
struct SymbolItem {
bool isDuplicated;
bool isUsed;
bool isOutsideModule;
int globalOffset;
int definedModule;
SymbolItem() {
this->isDuplicated = false;
this->isUsed = false;
this->isOutsideModule = false;
}
SymbolItem(int globalOffset, int definedModule) {
new (this) SymbolItem();
this->globalOffset = globalOffset;
this->definedModule = definedModule;
}
};
struct MapItem {
bool isNotDefined;
bool isOnChain;
bool isOutsideModule;
char originalType;
int word;
std::string variableName;
MapItem() {
this->isOnChain = false;
this->isNotDefined = false;
this->isOutsideModule = false;
}
MapItem(char originalType, int word) {
new (this) MapItem();
this->originalType = originalType;
this->word = word;
}
};
////////////////////////////////////////////////////////////////////////////////
std::vector<ObjectFile> g_objectFiles;
std::map<std::string, SymbolItem> g_symbolTable;
std::vector<MapItem> g_memoryMap;
////////////////////////////////////////////////////////////////////////////////
/*
Print final results to the output file
*/
void printToOutputFile() {
// print symbol table
fprintf(out, "Symbol Table\n");
for (std::map<std::string, SymbolItem>::iterator it = g_symbolTable.begin();
it != g_symbolTable.end();
it++) {
fprintf(out, "%s=%d", it->first.c_str(), it->second.globalOffset);
if (it->second.isOutsideModule) {
fprintf(out, " Error: The value of %s is outside module 2; zero (relative) used\n", it->first.c_str());
}
else if (it->second.isDuplicated) {
fprintf(out, " Error: This variable is multiply defined; first value used.\n");
}
else {
fprintf(out, "\n");
}
}
fprintf(out, "\n");
// print memory map
fprintf(out, "Memory Map\n");
for (int i = 0; i < g_memoryMap.size(); i++) {
// print
if (i < 10) {
fprintf(out, "%d: %d", i, g_memoryMap[i].word);
}
else {
fprintf(out, "%d: %d", i, g_memoryMap[i].word);
}
// handle errors
if (g_memoryMap[i].isNotDefined == true) {
fprintf(out, " Error: %s is not defined; zero used.\n", g_memoryMap[i].variableName.c_str());
}
else if (g_memoryMap[i].isOutsideModule == true) {
fprintf(out, " Error: Pointer in use chain exceeds module size; chain terminated.\n");
}
else if (g_memoryMap[i].originalType == 'E' && g_memoryMap[i].isOnChain == false) {
fprintf(out, " Error: E type address not on use chain; treated as I type.\n");
}
else if (g_memoryMap[i].originalType != 'E' && g_memoryMap[i].isOnChain == true) {
fprintf(out, " Error: %c type address on use chain; treated as E type.\n", g_memoryMap[i].originalType);
}
else {
fprintf(out, "\n");
}
}
fprintf(out, "\n");
for (std::map<std::string, SymbolItem>::iterator it = g_symbolTable.begin();
it != g_symbolTable.end();
it++) {
if (!it->second.isUsed) {
fprintf(out, "Warning: %s was defined in module %d but never used.\n",
it->first.c_str(), it->second.definedModule);
}
}
}
/*
Process 1
Missions:
- Store all information
- Generate symbol table
*/
void processOne()
{
int fileIndex = 0;
int itemsNum;
char *variableName = new char[80];
int i;
bool isEnd = false;
while (!isEnd) {
// get number of definitions if not EOF
if (fscanf(in, "%d", &itemsNum) == EOF) {
isEnd = true;
break;
}
// new file
fileIndex++;
g_objectFiles.push_back(ObjectFile());
for (i = 0; i < itemsNum; i++) {
// insert definitions
fscanf(in, "%s", variableName);
int innerOffset;
fscanf(in, "%d", &innerOffset);
g_objectFiles.back().definitionList.push_back(ListItem(variableName, innerOffset));
// fill in symbol table
if (g_symbolTable.find(variableName) == g_symbolTable.end()) { // do not find duplication
g_symbolTable.insert(
std::pair<std::string, SymbolItem>(
variableName, SymbolItem(g_offset + innerOffset, fileIndex)));
}
else {
g_symbolTable[variableName].isDuplicated = true;
}
}
// number of uses
fscanf(in, "%d", &itemsNum);
for (i = 0; i < itemsNum; i++) {
// insert uses
fscanf(in, "%s", variableName);
int offset;
fscanf(in, "%d", &offset);
g_objectFiles.back().useList.push_back(ListItem(variableName, offset));
}
// number of instructions
fscanf(in, "%d", &itemsNum);
for (i = 0; i < itemsNum; i++) {
char addressType;
bool isTypeValid = false;
// insert instructions
do {
fscanf(in, "%c", &addressType);
if (addressType >= 'A' && addressType <= 'Z') {
isTypeValid = true;
}
} while (!isTypeValid);
int word;
fscanf(in, "%d", &word);
g_objectFiles.back().programText.push_back(TextItem(addressType, word));
}
// check if definition of variables are outside the module
for (int k = 0; k < g_objectFiles.back().definitionList.size(); k++) {
std::string variableName = g_objectFiles.back().definitionList[k].variableName;
if (g_objectFiles.back().definitionList[k].offset
>= g_objectFiles.back().programText.size()
&& g_symbolTable[variableName].isDuplicated == false) {
g_symbolTable[variableName].isOutsideModule = true;
// reset address to zero (relative)
g_symbolTable[variableName].globalOffset = g_offset;
}
}
// update global offset
g_offset += itemsNum;
}
delete[] variableName;
}
/*
Process 2
Missions:
- Relocation
- Print result
*/
void processTwo()
{
g_offset = 0;
// relocation
for (int i = 0; i < g_objectFiles.size(); i++) {
std::vector<ListItem> &definitionList = g_objectFiles[i].definitionList;
std::vector<ListItem> &useList = g_objectFiles[i].useList;
std::vector<TextItem> &programText = g_objectFiles[i].programText;
// construct memory map
for (int k = 0; k < programText.size(); k++) {
g_memoryMap.push_back(MapItem());
g_memoryMap[g_offset + k].originalType = programText[k].addressType;
if (programText[k].addressType == 'R') {
g_memoryMap[g_offset + k].word = g_offset + programText[k].word;
}
else { // I or A or E(bad type if not on use chain)
g_memoryMap[g_offset + k].word = programText[k].word;
}
}
for (int k = 0; k < useList.size(); k++) {
for (int currentRefIndex = useList[k].offset; // first reference index
currentRefIndex != 777;
currentRefIndex = programText[currentRefIndex].word % 1000) {
// handle errors
std::map<std::string, SymbolItem>::iterator tryFindSymbol = g_symbolTable.find(useList[k].variableName);
if (tryFindSymbol == g_symbolTable.end()) {
g_memoryMap[g_offset + currentRefIndex].isNotDefined = true;
g_memoryMap[g_offset + currentRefIndex].word = 1000;
g_memoryMap[g_offset + currentRefIndex].variableName = useList[k].variableName;
continue;
}
else {
// now the symbol is used
tryFindSymbol->second.isUsed = true;
}
// update memory map
g_memoryMap[g_offset + currentRefIndex].originalType = programText[currentRefIndex].addressType;
g_memoryMap[g_offset + currentRefIndex].word =
programText[currentRefIndex].word / 1000 * 1000 +
g_symbolTable[useList[k].variableName].globalOffset;
g_memoryMap[g_offset + currentRefIndex].isOnChain = true;
if (programText[currentRefIndex].word % 1000 >= programText.size()
&& programText[currentRefIndex].word % 1000 != 777) {
// reference address is outside the module
g_memoryMap[g_offset + currentRefIndex].isOutsideModule = true;
break;
}
}
}
// update global offset
g_offset += programText.size();
}
printToOutputFile();
}
| 9,093 | 3,493 |
#include "FileIO.h"
void FileIO::init(const char* gifDirName) {
// Set the gif directory name and open the dir
m_gifDirName = gifDirName;
m_gifDir = SPIFFS.openDir(m_gifDirName);
m_gifFileId = 0;
// Mount SPIFFS
if (SPIFFS.begin()) {
DEBUGLN("Mounted SPIFFS")
} else {
FATAL("SPIFFS could not be mounted");
}
}
bool FileIO::onGifFileSeek(unsigned long position) {
if (!m_gifFile) return false;
return m_gifFile.seek(position);
}
unsigned long FileIO::onGifFilePosition(void) {
if (!m_gifFile) return -1;
return m_gifFile.position();
}
int FileIO::onGifFileRead(void) {
if (!m_gifFile) return 0;
return m_gifFile.read();
}
int FileIO::onGifFileReadBlock(void * buffer, int numberOfBytes) {
if (!m_gifFile) return 0;
return m_gifFile.read((uint8_t*) buffer, numberOfBytes);
}
void FileIO::nextGifFile() {
// Close the old file
if (m_gifFile) m_gifFile.close();
// Get the next gif file id
m_gifFileId++;
if (m_gifFileId >= FileIO::getNumGifFiles()) m_gifFileId = 0;
// Open the file
String fileName = getNthGifFileName(m_gifFileId);
m_gifFile = SPIFFS.open(fileName, "r");
if (!m_gifFile) {
WARN("Could not open next Gif file")
return;
}
}
void FileIO::prevGifFile() {
// Close the old file
if (m_gifFile) m_gifFile.close();
// Get the next gif file id
m_gifFileId--;
if (m_gifFileId < 0) m_gifFileId = FileIO::getNumGifFiles() - 1;
// Open the file
String fileName = getNthGifFileName(m_gifFileId);
m_gifFile = SPIFFS.open(fileName, "r");
if (!m_gifFile) {
WARN("Could not open previous Gif file")
return;
}
}
String FileIO::getNthGifFileName(int n) {
// Return empty string if n is invalid
if (n < 0) return "";
// Prepare a directory with index counter
int i = 0;
Dir gifDir = SPIFFS.openDir(m_gifDirName);
// Iterate through all files. Return at the correct index
while (gifDir.next()) {
if (i == n) return gifDir.fileName();
i++;
}
// No matching file found. Return empty string
return "";
}
int FileIO::getNumGifFiles() {
int i = 0;
Dir gifDir = SPIFFS.openDir(m_gifDirName);
// Count the number of files and return
while (gifDir.next()) i++;
return i;
} | 2,344 | 865 |
#include "Entity.hpp"
void Entity::scheduleRemoval()
{
m_remove = true;
}
void Entity::update()
{
ext::for_each(m_components, [](auto* ptr)
{
if (ptr != nullptr && ptr->active)
ptr->update();
});
}
| 236 | 85 |
// Copyright 2013 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 "storage/common/data_element.h"
#include <stddef.h>
#include <stdint.h>
#include <algorithm>
#include "base/strings/string_number_conversions.h"
namespace storage {
DataElement::DataElement()
: type_(TYPE_UNKNOWN),
bytes_(NULL),
offset_(0),
length_(std::numeric_limits<uint64_t>::max()) {}
DataElement::~DataElement() {}
void DataElement::SetToFilePathRange(
const base::FilePath& path,
uint64_t offset,
uint64_t length,
const base::Time& expected_modification_time) {
type_ = TYPE_FILE;
path_ = path;
offset_ = offset;
length_ = length;
expected_modification_time_ = expected_modification_time;
}
void DataElement::SetToBlobRange(const std::string& blob_uuid,
uint64_t offset,
uint64_t length) {
type_ = TYPE_BLOB;
blob_uuid_ = blob_uuid;
offset_ = offset;
length_ = length;
}
void DataElement::SetToFileSystemUrlRange(
const GURL& filesystem_url,
uint64_t offset,
uint64_t length,
const base::Time& expected_modification_time) {
type_ = TYPE_FILE_FILESYSTEM;
filesystem_url_ = filesystem_url;
offset_ = offset;
length_ = length;
expected_modification_time_ = expected_modification_time;
}
void DataElement::SetToDiskCacheEntryRange(uint64_t offset, uint64_t length) {
type_ = TYPE_DISK_CACHE_ENTRY;
offset_ = offset;
length_ = length;
}
void PrintTo(const DataElement& x, std::ostream* os) {
const uint64_t kMaxDataPrintLength = 40;
*os << "<DataElement>{type: ";
switch (x.type()) {
case DataElement::TYPE_BYTES: {
uint64_t length = std::min(x.length(), kMaxDataPrintLength);
*os << "TYPE_BYTES, data: ["
<< base::HexEncode(x.bytes(), static_cast<size_t>(length));
if (length < x.length()) {
*os << "<...truncated due to length...>";
}
*os << "]";
break;
}
case DataElement::TYPE_FILE:
*os << "TYPE_FILE, path: " << x.path().AsUTF8Unsafe()
<< ", expected_modification_time: " << x.expected_modification_time();
break;
case DataElement::TYPE_BLOB:
*os << "TYPE_BLOB, uuid: " << x.blob_uuid();
break;
case DataElement::TYPE_FILE_FILESYSTEM:
*os << "TYPE_FILE_FILESYSTEM, filesystem_url: " << x.filesystem_url();
break;
case DataElement::TYPE_DISK_CACHE_ENTRY:
*os << "TYPE_DISK_CACHE_ENTRY";
break;
case DataElement::TYPE_BYTES_DESCRIPTION:
*os << "TYPE_BYTES_DESCRIPTION";
break;
case DataElement::TYPE_UNKNOWN:
*os << "TYPE_UNKNOWN";
break;
}
*os << ", length: " << x.length() << ", offset: " << x.offset() << "}";
}
bool operator==(const DataElement& a, const DataElement& b) {
if (a.type() != b.type() || a.offset() != b.offset() ||
a.length() != b.length())
return false;
switch (a.type()) {
case DataElement::TYPE_BYTES:
return memcmp(a.bytes(), b.bytes(), b.length()) == 0;
case DataElement::TYPE_FILE:
return a.path() == b.path() &&
a.expected_modification_time() == b.expected_modification_time();
case DataElement::TYPE_BLOB:
return a.blob_uuid() == b.blob_uuid();
case DataElement::TYPE_FILE_FILESYSTEM:
return a.filesystem_url() == b.filesystem_url();
case DataElement::TYPE_DISK_CACHE_ENTRY:
// We compare only length and offset; we trust the entry itself was
// compared at some higher level such as in BlobDataItem.
return true;
case DataElement::TYPE_BYTES_DESCRIPTION:
return true;
case DataElement::TYPE_UNKNOWN:
NOTREACHED();
return false;
}
return false;
}
bool operator!=(const DataElement& a, const DataElement& b) {
return !(a == b);
}
} // namespace storage
| 3,926 | 1,359 |
#include <string.h>
#include <sys/mman.h>
#include "thread_start.h"
#include "log.h"
#include "core.h"
#include "simulator.h"
#include "fixed_types.h"
#include "pin_config.h"
#include "tile_manager.h"
#include "thread_manager.h"
#include "thread_support.h"
int spawnThreadSpawner(CONTEXT *ctxt)
{
int res;
IntPtr reg_eip = PIN_GetContextReg(ctxt, REG_INST_PTR);
PIN_LockClient();
AFUNPTR thread_spawner;
IMG img = IMG_FindByAddress(reg_eip);
RTN rtn = RTN_FindByName(img, "CarbonSpawnThreadSpawner");
thread_spawner = RTN_Funptr(rtn);
PIN_UnlockClient();
LOG_ASSERT_ERROR( thread_spawner != NULL, "ThreadSpawner function is null. You may not have linked to the carbon APIs correctly.");
LOG_PRINT("Starting CarbonSpawnThreadSpawner(%p)", thread_spawner);
PIN_CallApplicationFunction(ctxt,
PIN_ThreadId(),
CALLINGSTD_DEFAULT,
thread_spawner,
PIN_PARG(int), &res,
PIN_PARG_END());
LOG_PRINT("Thread spawner spawned");
LOG_ASSERT_ERROR(res == 0, "Failed to spawn Thread Spawner");
return res;
}
VOID copyStaticData(IMG& img)
{
Core* core = Sim()->getTileManager()->getCurrentCore();
LOG_ASSERT_ERROR (core != NULL, "Does not have a valid Core ID");
for (SEC sec = IMG_SecHead(img); SEC_Valid(sec); sec = SEC_Next(sec))
{
IntPtr sec_address;
// I am not sure whether we want ot copy over all the sections or just the
// sections which are relevant like the sections below: DATA, BSS, GOT
// Copy all the mapped sections except the executable section now
SEC_TYPE sec_type = SEC_Type(sec);
if (sec_type != SEC_TYPE_EXEC)
{
if (SEC_Mapped(sec))
{
sec_address = SEC_Address(sec);
LOG_PRINT ("Copying Section: %s at Address: 0x%x of Size: %u to Simulated Memory", SEC_Name(sec).c_str(), (UInt32) sec_address, (UInt32) SEC_Size(sec));
core->accessMemory(Core::NONE, Core::WRITE, sec_address, (char*) sec_address, SEC_Size(sec));
}
}
}
}
VOID copyInitialStackData(IntPtr& reg_esp, core_id_t core_id)
{
// We should not get core_id for this stack_ptr
Core* core = Sim()->getTileManager()->getCurrentCore();
LOG_ASSERT_ERROR (core != NULL, "Does not have a valid Core ID");
// 1) Command Line Arguments
// 2) Environment Variables
// 3) Auxiliary Vector Entries
SInt32 initial_stack_size = 0;
IntPtr stack_ptr_base;
IntPtr stack_ptr_top;
IntPtr params = reg_esp;
carbon_reg_t argc = * ((carbon_reg_t *) params);
char **argv = (char **) (params + sizeof(carbon_reg_t));
char **envir = argv+argc+1;
//////////////////////////////////////////////////////////////////////
// Pass 1
// Determine the Initial Stack Size
// Variables: size_argv_ptrs, size_env_ptrs, size_information_block
//////////////////////////////////////////////////////////////////////
// Write argc
initial_stack_size += sizeof(argc);
// Write argv
for (SInt32 i = 0; i < (SInt32) argc; i++)
{
// Writing argv[i]
initial_stack_size += sizeof(char*);
initial_stack_size += (strlen(argv[i]) + 1);
}
// A '0' at the end
initial_stack_size += sizeof(char*);
// We need to copy over the environmental parameters also
for (SInt32 i = 0; ; i++)
{
// Writing environ[i]
initial_stack_size += sizeof(char*);
if (envir[i] == 0)
{
break;
}
initial_stack_size += (strlen(envir[i]) + 1);
}
// Auxiliary Vector Entry
#ifdef TARGET_IA32
initial_stack_size += sizeof(Elf32_auxv_t);
#elif TARGET_X86_64
initial_stack_size += sizeof(Elf64_auxv_t);
#else
LOG_PRINT_ERROR("Unrecognized Architecture Type");
#endif
//////////////////////////////////////////////////////////////////////
// Pass 2
// Copy over the actual data
// Variables: stack_ptr_base_sim
//////////////////////////////////////////////////////////////////////
PinConfig::StackAttributes stack_attr;
PinConfig::getSingleton()->getStackAttributesFromCoreID (core_id, stack_attr);
stack_ptr_top = stack_attr.lower_limit + stack_attr.size;
stack_ptr_base = stack_ptr_top - initial_stack_size;
stack_ptr_base = (stack_ptr_base >> (sizeof(IntPtr))) << (sizeof(IntPtr));
// Assign the new ESP
reg_esp = stack_ptr_base;
// fprintf (stderr, "argc = %d\n", argc);
// Write argc
core->accessMemory(Core::NONE, Core::WRITE, stack_ptr_base, (char*) &argc, sizeof(argc));
stack_ptr_base += sizeof(argc);
LOG_PRINT("Copying Command Line Arguments to Simulated Memory");
for (SInt32 i = 0; i < (SInt32) argc; i++)
{
// Writing argv[i]
stack_ptr_top -= (strlen(argv[i]) + 1);
core->accessMemory(Core::NONE, Core::WRITE, stack_ptr_top, (char*) argv[i], strlen(argv[i])+1);
core->accessMemory(Core::NONE, Core::WRITE, stack_ptr_base, (char*) &stack_ptr_top, sizeof(stack_ptr_top));
stack_ptr_base += sizeof(stack_ptr_top);
}
// I have found this to be '0' in most cases
core->accessMemory(Core::NONE, Core::WRITE, stack_ptr_base, (char*) &argv[argc], sizeof(argv[argc]));
stack_ptr_base += sizeof(argv[argc]);
// We need to copy over the environmental parameters also
LOG_PRINT("Copying Environmental Variables to Simulated Memory");
for (SInt32 i = 0; ; i++)
{
// Writing environ[i]
if (envir[i] == 0)
{
core->accessMemory(Core::NONE, Core::WRITE, stack_ptr_base, (char*) &envir[i], sizeof(envir[i]));
stack_ptr_base += sizeof(envir[i]);
break;
}
stack_ptr_top -= (strlen(envir[i]) + 1);
core->accessMemory(Core::NONE, Core::WRITE, stack_ptr_top, (char*) envir[i], strlen(envir[i])+1);
core->accessMemory(Core::NONE, Core::WRITE, stack_ptr_base, (char*) &stack_ptr_top, sizeof(stack_ptr_top));
stack_ptr_base += sizeof(stack_ptr_top);
}
LOG_PRINT("Copying Auxiliary Vector to Simulated Memory");
#ifdef TARGET_IA32
Elf32_auxv_t auxiliary_vector_entry_null;
#elif TARGET_X86_64
Elf64_auxv_t auxiliary_vector_entry_null;
#else
LOG_PRINT_ERROR("Unrecognized architecture type");
#endif
auxiliary_vector_entry_null.a_type = AT_NULL;
auxiliary_vector_entry_null.a_un.a_val = 0;
core->accessMemory(Core::NONE, Core::WRITE, stack_ptr_base, (char*) &auxiliary_vector_entry_null, sizeof(auxiliary_vector_entry_null));
stack_ptr_base += sizeof(auxiliary_vector_entry_null);
LOG_ASSERT_ERROR(stack_ptr_base <= stack_ptr_top, "stack_ptr_base = 0x%x, stack_ptr_top = 0x%x", stack_ptr_base, stack_ptr_top);
}
VOID copySpawnedThreadStackData(IntPtr reg_esp)
{
core_id_t core_id = PinConfig::getSingleton()->getCoreIDFromStackPtr(reg_esp);
PinConfig::StackAttributes stack_attr;
PinConfig::getSingleton()->getStackAttributesFromCoreID(core_id, stack_attr);
IntPtr stack_upper_limit = stack_attr.lower_limit + stack_attr.size;
UInt32 num_bytes_to_copy = (UInt32) (stack_upper_limit - reg_esp);
Core* core = Sim()->getTileManager()->getCurrentCore();
core->accessMemory(Core::NONE, Core::WRITE, reg_esp, (char*) reg_esp, num_bytes_to_copy);
}
VOID allocateStackSpace()
{
// Note that 1 core = 1 thread currently
// We should probably get the amount of stack space per thread from a configuration parameter
// Each process allocates whatever it is responsible for !!
__attribute(__unused__) UInt32 stack_size_per_core = PinConfig::getSingleton()->getStackSizePerCore();
__attribute(__unused__) UInt32 num_tiles = Sim()->getConfig()->getNumLocalTiles();
__attribute(__unused__) IntPtr stack_base = PinConfig::getSingleton()->getStackLowerLimit();
LOG_PRINT("allocateStackSpace: stack_size_per_core = 0x%x", stack_size_per_core);
LOG_PRINT("allocateStackSpace: num_local_cores = %i", num_tiles);
LOG_PRINT("allocateStackSpace: stack_base = 0x%x", stack_base);
// TODO: Make sure that this is a multiple of the page size
// mmap() the total amount of memory needed for the stacks
LOG_ASSERT_ERROR((mmap((void*) stack_base, stack_size_per_core * num_tiles, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) == (void*) stack_base),
"mmap(%p, %u) failed: Cannot allocate stack on host machine", (void*) stack_base, stack_size_per_core * num_tiles);
}
VOID SimPthreadAttrInitOtherAttr(pthread_attr_t *attr)
{
LOG_PRINT ("In SimPthreadAttrInitOtherAttr");
//tile_id_t tile_id;
core_id_t core_id;
ThreadSpawnRequest* req = Sim()->getThreadManager()->getThreadSpawnReq();
if (req == NULL)
{
// This is the thread spawner
core_id = Sim()->getConfig()->getCurrentThreadSpawnerCoreId();
}
else
{
// This is an application thread
core_id = (core_id_t) {req->destination.tile_id, req->destination.core_type};
}
PinConfig::StackAttributes stack_attr;
PinConfig::getSingleton()->getStackAttributesFromCoreID(core_id, stack_attr);
pthread_attr_setstack(attr, (void*) stack_attr.lower_limit, stack_attr.size);
LOG_PRINT ("Done with SimPthreadAttrInitOtherAttr");
}
| 9,164 | 3,248 |
// Copyright (c) Matthew Brecknell 2013.
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE.txt or a copy at http://www.boost.org/LICENSE_1_0.txt).
#include <iostream>
#include <string>
#include "tree.hpp"
typedef tree<int> tri;
int main() {
tri foo = tri(tri(tri(1), 2, tri(3)), 4, tri(tri(5), 6, tri()));
tri bar = insert(7, foo);
for (const tri & tr: {foo,bar}) {
std::cout << tr << std::endl;
}
for (const tri & tr: {foo,bar}) {
std::cout
<< map_tree<const int*>([](const int & i) { return &i; }, tr)
<< std::endl;
}
}
| 612 | 251 |
// Runs a plan with mpi enabled without mpirun. This differs from run_plan_mpi
// in the sense that the common world is formed by joining during runtime,
// instead of being set up by mpirun.
//
// This util assumes that you have a common path (like NFS) that multiple
// instances can read from.
#include <mpi.h>
#include "caffe2/core/init.h"
#include "caffe2/core/logging.h"
#include "caffe2/core/operator.h"
#include "caffe2/mpi/mpi_common.h"
#include "caffe2/proto/caffe2.pb.h"
#include "caffe2/utils/proto_utils.h"
using caffe2::MPICommSize;
using caffe2::GlobalMPIComm;
CAFFE2_DEFINE_string(plan, "", "The given path to the plan protobuffer.");
CAFFE2_DEFINE_string(role, "", "server | client");
CAFFE2_DEFINE_int(
replicas,
2,
"The total number of replicas (clients + server) to wait for");
CAFFE2_DEFINE_string(job_path, "", "The path to write to");
namespace {
// RAAI for MPI so that we always run MPI_Finalize when exiting.
class MPIContext {
public:
MPIContext(int argc, char** argv) {
int mpi_ret;
MPI_CHECK(MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &mpi_ret));
if (mpi_ret != MPI_THREAD_MULTIPLE && mpi_ret != MPI_THREAD_SERIALIZED) {
throw std::runtime_error(
"Caffe2 MPI requires the underlying MPI to support the "
"MPI_THREAD_SERIALIZED or MPI_THREAD_MULTIPLE mode.");
}
}
~MPIContext() {
MPI_Finalize();
}
};
}
int main(int argc, char** argv) {
MPIContext mpi_context(argc, argv);
caffe2::SetUsageMessage("Runs a caffe2 plan that has MPI operators in it.");
caffe2::GlobalInit(&argc, &argv);
caffe2::MPISetupPeers(
caffe2::FLAGS_replicas, caffe2::FLAGS_role, caffe2::FLAGS_job_path);
// Only check if plan is specified AFTER MPI setup such that we can test
// whether or not MPI setup works without having a plan to run.
if (FLAGS_plan == "") {
std::cerr << "No plan defined! Exiting...\n";
return 0;
}
caffe2::PlanDef plan_def;
CAFFE_ENFORCE(ReadProtoFromFile(caffe2::FLAGS_plan, &plan_def));
std::unique_ptr<caffe2::Workspace> workspace(new caffe2::Workspace());
workspace->RunPlan(plan_def);
// This is to allow us to use memory leak checks.
google::protobuf::ShutdownProtobufLibrary();
return 0;
}
| 2,253 | 857 |
//======================================================================
//-----------------------------------------------------------------------
/**
* @file printto.cpp
* @brief printto sample
*
* @author t.shirayanagi
* @par copyright
* Copyright (C) 2014-2017, Takazumi Shirayanagi\n
* This software is released under the new BSD License,
* see LICENSE
*/
//-----------------------------------------------------------------------
//======================================================================
#include "../include/iutest.hpp"
/* ---------------------------------------------------
* PrintTo
*//*--------------------------------------------------*/
#if IUTEST_HAS_PRINT_TO
struct Bar
{
int x, y, z;
bool operator == (const Bar& rhs) const
{
return x == rhs.x && y == rhs.y && z == rhs.z;
}
};
::iutest::iu_ostream& operator << (::iutest::iu_ostream& os, const Bar& bar)
{
return os << "X:" << bar.x << " Y:" << bar.y << " Z:" << bar.z;
}
void PrintTo(const Bar& bar, ::iutest::iu_ostream* os)
{
*os << "x:" << bar.x << " y:" << bar.y << " z:" << bar.z;
}
IUTEST(PrintToTest, Test1)
{
::std::vector<int> a;
for( int i=0; i < 10; ++i )
a.push_back(i);
IUTEST_SUCCEED() << ::iutest::PrintToString(a);
int* pi=NULL;
void* p=NULL;
IUTEST_SUCCEED() << ::iutest::PrintToString(p);
IUTEST_SUCCEED() << ::iutest::PrintToString(pi);
Bar bar = {0, 1, 2};
IUTEST_SUCCEED() << ::iutest::PrintToString(bar);
}
IUTEST(PrintToTest, Test2)
{
Bar bar1 = {0, 1, 2};
Bar bar2 = {0, 1, 2};
IUTEST_ASSERT_EQ(bar1, bar2);
}
IUTEST(PrintToTest, RawArray)
{
{
unsigned char a[3] = {0, 1, 2};
const unsigned char b[3] = {0, 1, 2};
const volatile unsigned char c[3] = {0, 1, 2};
volatile unsigned char d[3] = {0, 1, 2};
IUTEST_SUCCEED() << ::iutest::PrintToString(a);
IUTEST_SUCCEED() << ::iutest::PrintToString(b);
IUTEST_SUCCEED() << ::iutest::PrintToString(c);
IUTEST_SUCCEED() << ::iutest::PrintToString(d);
}
{
char a[3] = {0, 1, 2};
const char b[3] = {0, 1, 2};
const volatile char c[3] = {0, 1, 2};
volatile char d[3] = {0, 1, 2};
IUTEST_SUCCEED() << ::iutest::PrintToString(a);
IUTEST_SUCCEED() << ::iutest::PrintToString(b);
IUTEST_SUCCEED() << ::iutest::PrintToString(c);
IUTEST_SUCCEED() << ::iutest::PrintToString(d);
}
}
#if IUTEST_HAS_TYPED_TEST
template<typename T>
class TypedPrintToTest : public ::iutest::Test {};
typedef ::iutest::Types<char, unsigned char
, short, unsigned short
, int, unsigned int
, long, unsigned long
, int*> PrintStringTestTypes;
IUTEST_TYPED_TEST_CASE(TypedPrintToTest, PrintStringTestTypes);
IUTEST_TYPED_TEST(TypedPrintToTest, Print)
{
TypeParam a = 0;
TypeParam& b = a;
const TypeParam c = a;
const volatile TypeParam d = a;
IUTEST_SUCCEED() << ::iutest::PrintToString(a);
IUTEST_SUCCEED() << ::iutest::PrintToString(b);
IUTEST_SUCCEED() << ::iutest::PrintToString(c);
IUTEST_SUCCEED() << ::iutest::PrintToString(d);
}
#if IUTEST_HAS_CHAR16_T
IUTEST(PrintToTest, U16String)
{
IUTEST_SUCCEED() << ::iutest::PrintToString(u"テスト");
}
#endif
#if IUTEST_HAS_CHAR32_T
IUTEST(PrintToTest, U32String)
{
IUTEST_SUCCEED() << ::iutest::PrintToString(U"テスト");
}
#endif
#endif
#endif
| 3,478 | 1,322 |
/*
* Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/dataworks-public/model/GetInstanceStatusCountResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Dataworks_public;
using namespace AlibabaCloud::Dataworks_public::Model;
GetInstanceStatusCountResult::GetInstanceStatusCountResult() :
ServiceResult()
{}
GetInstanceStatusCountResult::GetInstanceStatusCountResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
GetInstanceStatusCountResult::~GetInstanceStatusCountResult()
{}
void GetInstanceStatusCountResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto statusCountNode = value["StatusCount"];
if(!statusCountNode["TotalCount"].isNull())
statusCount_.totalCount = std::stoi(statusCountNode["TotalCount"].asString());
if(!statusCountNode["NotRunCount"].isNull())
statusCount_.notRunCount = std::stoi(statusCountNode["NotRunCount"].asString());
if(!statusCountNode["WaitTimeCount"].isNull())
statusCount_.waitTimeCount = std::stoi(statusCountNode["WaitTimeCount"].asString());
if(!statusCountNode["WaitResCount"].isNull())
statusCount_.waitResCount = std::stoi(statusCountNode["WaitResCount"].asString());
if(!statusCountNode["RunningCount"].isNull())
statusCount_.runningCount = std::stoi(statusCountNode["RunningCount"].asString());
if(!statusCountNode["FailureCount"].isNull())
statusCount_.failureCount = std::stoi(statusCountNode["FailureCount"].asString());
if(!statusCountNode["SuccessCount"].isNull())
statusCount_.successCount = std::stoi(statusCountNode["SuccessCount"].asString());
}
GetInstanceStatusCountResult::StatusCount GetInstanceStatusCountResult::getStatusCount()const
{
return statusCount_;
}
| 2,391 | 708 |
#include <hal/amp-1.0.0/amp-leds.h>
FreeRTOS::Semaphore AmpLeds::ledsReady = FreeRTOS::Semaphore("leds");
void AmpLeds::init() {
// setup the status led
status = new OneWireLED(NeoPixel, STATUS_LED, 0, 1);
(*status)[0] = lightOff;
}
void AmpLeds::deinit() {
delay(50);
}
void AmpLeds::process() {
ledsReady.wait();
if (dirty) {
status->show();
for (auto pair : channels) {
if (pair.second != nullptr) {
if (pair.second->wait(5))
pair.second->show();
}
}
}
// if (statusDirty) {
// ESP_LOGV(LEDS_TAG,"Status is dirty. Re-rendering");
// status->wait();
// status->show();
// statusDirty = false;
// }
// // check the dirty bit for each
// for (auto pair : channels) {
// if (pair.second != nullptr && dirty[pair.first]) {
// ESP_LOGV(LEDS_TAG,"Channel %d is dirty. Re-rendering", pair.first);
// pair.second->wait();
// pair.second->show();
// // unset dirty bit
// dirty[pair.first] = false;
// }
// }
}
LightController* AmpLeds::addLEDStrip(LightChannel data) {
ledsReady.wait();
ledsReady.take();
ESP_LOGD(LEDS_TAG,"Adding type %d strip on channel %d with %d LEDs", data.type, data.channel, data.leds);
AddressableLED *controller = nullptr;
if (channels.find(data.channel) != channels.end()) {
// remove old controller
auto old = channels[data.channel];
delete old;
}
switch(data.type) {
case LEDType::NeoPixel:
case LEDType::WS2813:
case LEDType::SK6812:
controller = new OneWireLED(data.type, lightMap[data.channel], data.channel, data.leds);
break;
case LEDType::SK6812_RGBW:
controller = new OneWireLED(data.type, lightMap[data.channel], data.channel, data.leds, PixelOrder::GRBW);
break;
case LEDType::DotStar:
controller = new TwoWireLED(HSPI_HOST, data.leds, lightMap[data.channel], lightMap[data.channel + 4]);
break;
default:
return nullptr;
}
for (uint16_t i = 0; i < data.leds; i++)
(*controller)[i] = lightOff;
channels[data.channel] = controller;
leds[data.channel] = data.leds;
// dirty[data.channel] = true;
ledsReady.give();
return controller;
}
void AmpLeds::setStatus(Color color) {
(*status)[0] = gammaCorrected(color);
dirty = true;
// statusDirty = true;
}
void AmpLeds::render(bool all, int8_t channel) {
dirty = true;
// statusDirty = true;
// // set all dirty bits
// if (all) {
// for (auto pair : dirty)
// dirty[pair.first] = true;
// }
// else if (channel != -1 && channel >= 1 && channel <= 8)
// dirty[channel] = true;
}
Color AmpLeds::gammaCorrected(Color color) {
return Color(gamma8[color.r], gamma8[color.g], gamma8[color.b]);
}
void AmpLeds::setPixel(uint8_t channelNumber, Color color, uint16_t index) {
ledsReady.wait();
if (index >= leds[channelNumber]) {
ESP_LOGE(LEDS_TAG, "Pixel %d exceeds channel %d led count (%d)", index, channelNumber, leds[channelNumber]);
return;
}
auto controller = channels[channelNumber];
if (controller == nullptr)
return;
(*controller)[index] = color;
}
Color AmpLeds::getPixel(uint8_t channelNumber, uint16_t index) {
ledsReady.wait();
if (index >= leds[channelNumber]) {
ESP_LOGE(LEDS_TAG, "Pixel %d exceeds channel %d led count (%d)", index, channelNumber, leds[channelNumber]);
return lightOff;
}
auto controller = channels[channelNumber];
if (controller == nullptr)
return lightOff;
return (*controller)[index];
}
void AmpLeds::setPixels(uint8_t channelNumber, Color color, uint16_t start, uint16_t end) {
ledsReady.wait();
auto controller = channels[channelNumber];
if (controller == nullptr)
return;
for (uint16_t i = start; i < end; i++) {
if (i < leds[channelNumber])
(*controller)[i] = color;
else
ESP_LOGE(LEDS_TAG, "Pixel %d exceeds channel %d led count (%d)", i, channelNumber, leds[channelNumber]);
}
} | 3,960 | 1,455 |
// Return all non-negative integers of length N such that the absolute difference between every two consecutive digits is K.
// Note that every number in the answer must not have leading zeros except for the number 0 itself. For example, 01 has one leading zero and is invalid, but 0 is valid.
// You may return the answer in any order.
// Example 1:
// Input: N = 3, K = 7
// Output: [181,292,707,818,929]
// Explanation: Note that 070 is not a valid number, because it has leading zeroes.
// Example 2:
// Input: N = 2, K = 1
// Output: [10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98]
// Note:
// 1 <= N <= 9
// 0 <= K <= 9
// solution: dfs
class Solution {
public:
void dfs(int num, int N, int K, vector<int>& result){
if (N == 0) {
result.push_back(num);
return;
}
int last_digit = num%10;
if (last_digit >= K) dfs(num*10 + last_digit - K, N-1, K, result);
if (K > 0 && last_digit + K < 10) dfs(num*10 + last_digit + K, N-1, K, result);
}
vector<int> numsSameConsecDiff(int N, int K) {
vector<int> result;
if (N == 1) result.push_back(0);
for (int d = 1; d < 10; ++d) {
dfs(d, N-1, K, result);
}
return result;
}
}; | 1,284 | 507 |
//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
#include "nf_system_collections.h"
HRESULT Library_nf_system_collections_System_Collections_Queue::CopyTo___VOID__SystemArray__I4( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
NANOCLR_HEADER();
CLR_RT_HeapBlock_Queue* pThis;
CLR_RT_HeapBlock_Array* array;
CLR_INT32 index;
pThis = (CLR_RT_HeapBlock_Queue*)stack.This(); FAULT_ON_NULL(pThis);
array = stack.Arg1().DereferenceArray(); FAULT_ON_NULL_ARG(array);
index = stack.Arg2().NumericByRef().s4;
NANOCLR_SET_AND_LEAVE(pThis->CopyTo( array, index ));
NANOCLR_NOCLEANUP();
}
HRESULT Library_nf_system_collections_System_Collections_Queue::Clear___VOID( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
NANOCLR_HEADER();
CLR_RT_HeapBlock_Queue* pThis = (CLR_RT_HeapBlock_Queue*)stack.This(); FAULT_ON_NULL(pThis);
NANOCLR_SET_AND_LEAVE(pThis->Clear());
NANOCLR_NOCLEANUP();
}
HRESULT Library_nf_system_collections_System_Collections_Queue::Enqueue___VOID__OBJECT( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
NANOCLR_HEADER();
CLR_RT_HeapBlock_Queue* pThis = (CLR_RT_HeapBlock_Queue*)stack.This(); FAULT_ON_NULL(pThis);
NANOCLR_SET_AND_LEAVE(pThis->Enqueue( stack.Arg1().Dereference() ));
NANOCLR_NOCLEANUP();
}
HRESULT Library_nf_system_collections_System_Collections_Queue::Dequeue___OBJECT( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
NANOCLR_HEADER();
CLR_RT_HeapBlock_Queue* pThis = (CLR_RT_HeapBlock_Queue*)stack.This(); FAULT_ON_NULL(pThis);
CLR_RT_HeapBlock* value;
NANOCLR_CHECK_HRESULT(pThis->Dequeue( value ));
stack.SetResult_Object( value );
NANOCLR_NOCLEANUP();
}
HRESULT Library_nf_system_collections_System_Collections_Queue::Peek___OBJECT( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
NANOCLR_HEADER();
CLR_RT_HeapBlock_Queue* pThis = (CLR_RT_HeapBlock_Queue*)stack.This(); FAULT_ON_NULL(pThis);
CLR_RT_HeapBlock* value;
NANOCLR_CHECK_HRESULT(pThis->Peek( value ));
stack.SetResult_Object( value );
NANOCLR_NOCLEANUP();
}
| 2,405 | 988 |
/*
Copyright © 2018, Marko Ranta
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 COPYRIGHT HOLDER 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 "System/window.hpp"
#include "Renderer/canvas.hpp"
#include "System/inputmanager.hpp"
#include "System/timer.hpp"
#include <string>
#include <iostream>
#include <regex> //MEH
#include "Renderer/rendercontext.hpp"
#include "Renderer/mesh.hpp"
#include "starfield.hpp"
#include "Math/quat.hpp"
#define NONE 0
#define STARFIELD 1
#define RENDERCONTEXT 2
#define TEST RENDERCONTEXT
#ifdef NDEBUG
int CALLBACK WinMain(
HINSTANCE /*hInstance*/,
HINSTANCE /*hPrevInstance*/,
LPSTR /*lpCmdLine*/,
int /*nCmdShow*/
)
#else
int main()
#endif
{
int screenWidth = 640, screenHeight = 480;
int canvasWidth = 512, canvasHeight = 384;
std::fstream settings;
settings.open("settings.ini", std::ios::in);
if(!settings.is_open()) {
settings.open("settings.ini", std::ios::out);
settings << "Modify these values at your own risk." << std::endl;
settings << "ScreenWidth = " << screenWidth << std::endl;
settings << "ScreenHeight = " << screenHeight << std::endl;
settings << "CanvasWidth = " << canvasWidth << std::endl;
settings << "CanvasHeight = " << canvasHeight << std::endl;
settings.close();
} else {
std::string line;
std::string var, value;
std::regex match("(\\w+)\\s*=(\\d+)\\s*");
while(std::getline(settings, line)) {
std::smatch subMatches;
if(std::regex_match(line, subMatches, match)) {
if(subMatches.size() == 3) {
var = subMatches[1].str();
value = subMatches[2].str();
}
}
if(var == "ScreenWidth") screenWidth = stoi(value);
if(var == "ScreenHeight") screenHeight = stoi(value);
if(var == "CanvasWidth") canvasWidth = stoi(value);
if(var == "CanvasHeight") canvasHeight = stoi(value);
}
settings.close();
}
Window window;
window.initialize(screenWidth, screenHeight, "Software Renderer");
Canvas canvas(window);
canvas.resize(canvasWidth, canvasHeight);
float aRatio = 4.0f / 3.0f;
InputManager inputs;
inputs.setCustomMessageCallback([&aRatio](Window& window, UINT msg, WPARAM wparam, LPARAM lparam)->LRESULT {
switch(msg) {
case WM_SIZE: {
float w = GET_X_LPARAM(lparam);
float h = GET_Y_LPARAM(lparam);
aRatio = w / h;
} break;
}
return window.defaultWindowProc(msg, wparam, lparam);
});
window.setMessageCallback(inputs.callbackProcessor());
#if TEST == STARFIELD
Starfield starfield(canvas);
#endif
#if TEST == RENDERCONTEXT
RenderContext rc(canvas);
Texture texture1;
texture1.load("res/texture1.png");
Texture texture2;
texture2.load("res/texture2.png");
Mesh mesh1;
mesh1.load("res/suzanne.obj");
Mesh mesh2;
mesh2.load("res/terrain.obj");
Mesh mesh3;
mesh3.load("res/cube.obj");
#endif
auto prevtime = Timer();
double deltaTime = 0.0f;
float ang = 0.0f;
#ifdef TEXT_INPUT_TEST
std::string input;
auto eraseTime = Timer();
#endif
//TL---TR
//| |
//| |
//BL---BR
Vertex vertices[] = {
{-1.0f, -1.0f}, //Bottom left
{-1.0f, 1.0f}, //Top left
{ 1.0f, 1.0f}, //Top right
{ 1.0f, -1.0f} //Bottom right
};
vertices[0].setColor({ 1.0f, 0.0f, 0.0f, 1.0 });
vertices[1].setColor({ 1.0f, 1.0f, 0.0f, 1.0 });
vertices[2].setColor({ 0.0f, 0.0f, 1.0f, 1.0 });
vertices[3].setColor({ 0.0f, 1.0f, 1.0f, 1.0 });
vertices[0].setTexCoord({ 0.0f, 1.0f });
vertices[1].setTexCoord({ 0.0f, 0.0f });
vertices[2].setTexCoord({ 1.0f, 0.0f });
vertices[3].setTexCoord({ 1.0f, 1.0f });
int frames = 0, fps = 0;
float z = -2.0f;
double fpsTime = 0.0f;
float cameraYaw = 0.0f;
float cameraPitch = 0.0f;
vec3 cameraPosition;
float suzanneAngle = 0.f;
rc.setSamplingMode(Texture::Sampling::CubicHermite);
rc.setTextureWrapingMode(Texture::Wraping::Repeat);
rc.enableLighting(true);
rc.setAmbientColor({0.2f, 0.1f, 0.6f});
rc.setAmbientIntensity(0.3f);
rc.setSunColor({ 1.f, 0.6f, 0.2f });
rc.setSunIntensity(4.f);
rc.setSunPosition(vec3(16.f, 3.f, 8.f));
while(!window.isClosed()) {
window.pollEvents();
rc.reset();
canvas.clearCheckerboard(rc.checkerBoard(), rc.ambientColor()*rc.ambientIntensity());
if(!rc.checkerBoard()) {
rc.clearDepthBuffer();
}
#if TEST == STARFIELD
starfield.updateAndDraw(deltaTime);
#endif
#if TEST == RENDERCONTEXT
mat4 mat;
if(inputs.isMouseHit(0)) ShowCursor(FALSE);
if(inputs.isMouseUp(0)) ShowCursor(TRUE);
if(inputs.isMouseDown(0)) {
RECT rct;
GetClientRect(window.handle(), &rct);
POINT p;
p.x = (rct.right - rct.left) / 2;
p.y = (rct.bottom - rct.top) / 2;
float mx = (p.x - inputs.mouseX());
float my = (p.y - inputs.mouseY());
cameraPitch += mx * deltaTime;
cameraYaw += my * deltaTime;
ClientToScreen(window.handle(), &p);
SetCursorPos(p.x, p.y);
}
mat4 rotation = mat4::Rotation(cameraYaw, 1.0f, 0.0f, 0.0f)*mat4::Rotation(cameraPitch, 0.0f, 1.0f, 0.0f);
vec3 dir = rotation.transposed() * vec3(0.f, 0.f, 1.f);
vec3 right = cross(dir, vec3(0.f, 1.f, 0.f));
right = reorthogonalize(right, dir);
if(inputs.isKeyHit('C')) rc.setTextureWrapingMode(Texture::Wraping::Clamp);
if(inputs.isKeyHit('R')) rc.setTextureWrapingMode(Texture::Wraping::Repeat);
if(inputs.isKeyHit(0x31)) rc.setSamplingMode(Texture::Sampling::None);
if(inputs.isKeyHit(0x32)) rc.setSamplingMode(Texture::Sampling::Linear);
if(inputs.isKeyHit(0x33)) rc.setSamplingMode(Texture::Sampling::CubicHermite);
if(inputs.isKeyDown('W')) cameraPosition += dir*5.f * deltaTime;
if(inputs.isKeyDown('S')) cameraPosition -= dir*5.f * deltaTime;
if(inputs.isKeyDown('D')) cameraPosition += right*5.f * deltaTime;
if(inputs.isKeyDown('A')) cameraPosition -= right*5.f * deltaTime;
/*
if(inputs.isKeyHit(VK_SPACE)) {
rc.testMipmap(!rc.isMipMapTesting());
}
if(rc.isMipMapTesting()) {
rc.setMipMapLevel(rc.mipMapLevel() + (inputs.isKeyHit(VK_UP) - inputs.isKeyHit(VK_DOWN)));
}*/
mat4 viewProjection = mat4::Perspective(aRatio, 90.0f, .01f, 100.f) * rotation * mat4::Translate(cameraPosition);
z -= (float)(inputs.isKeyDown(VK_UP) - inputs.isKeyDown(VK_DOWN)) * deltaTime;
mat4 suzanneRotation = mat4::Rotation(QMod(suzanneAngle, 360.0f), 0.f, 1.f, 0.f);
mat4 model = mat4::Translate(0.0f, 0.0f, -2.0f) * suzanneRotation;
mat = viewProjection * model;
rc.drawMesh(mesh1, mat, texture1, suzanneRotation);
suzanneAngle += deltaTime*20.f;
model = mat4::Translate(0.0f, -4.0f, 0.0f);
mat = viewProjection * model;
rc.drawMesh(mesh2, mat, texture2);
model = mat4::Translate(0.0f, -2.0f, -2.0f);
mat = viewProjection * model;
rc.drawMesh(mesh3, mat);
#endif
#ifdef NDEBUG
std::cout << inputs.mouseX() << ", " << inputs.mouseY() << '\r';
#endif
canvas.swapBuffers();
rc.advanceCheckerboard();
#ifdef TEXT_INPUT_TEST
RECT rct = { 0, 0, 800, 300 };
unsigned int ch;
if(inputs.isTextInput(ch)) {
if(isprint(ch)) {
input += ((char)ch);
}
}
if((inputs.isKeyHit(8) || (inputs.isKeyDown(8) && eraseTime > 1000)) && !input.empty()) {
eraseTime = Timer()/10 - eraseTime;
input.pop_back();
}
rct.top += 20;
DrawTextA(window.dc(), input.c_str(), -1, &rct, 0);
#endif
auto tp = Timer();
deltaTime = (double)(tp - prevtime) / (double)TIMER_PRECISION;
//Cap the FPS, so movement won't become too slow.
if(deltaTime < (1.0 / 120.0)) {
Sleep((int)1000.0*(1.0 / 120.0));
}
//Calculate FPS
prevtime = tp;
frames++;
fpsTime += (double)deltaTime;
if(fpsTime > 1.0) {
fps = frames;
frames = 0;
fpsTime = 0;
}
window.setTitle("Software Rendering | FPS: " + std::to_string(fps) + " | Triangles: "+std::to_string(rc.renderedTriangles()) /*+ (rc.isMipMapTesting() ? " | MipMap testing! " + std::to_string(rc.mipMapLevel()) : "")*/);
inputs.update();
}
return 0;
}
| 9,367 | 4,192 |