text
stringlengths 5
1.04M
|
|---|
/*
Copyright (c) by respective owners including Yahoo!, Microsoft, and
individual contributors. All rights reserved. Released under a BSD (revised)
license as described in the file LICENSE.
*/
#include "vowpalwabbit.h"
#include "vw_example.h"
#include "vw_prediction.h"
#include "gd.h"
namespace VW
{
using namespace Labels;
VowpalWabbitExample::VowpalWabbitExample(IVowpalWabbitExamplePool^ owner, example* example) :
m_owner(owner), m_example(example), m_innerExample(nullptr)
{
}
VowpalWabbitExample::VowpalWabbitExample(IVowpalWabbitExamplePool^ owner, VowpalWabbitExample^ example) :
m_owner(owner), m_example(example->m_example), m_innerExample(example), m_string(example->m_string)
{
}
VowpalWabbitExample::!VowpalWabbitExample()
{
if (m_owner != nullptr)
m_owner->ReturnExampleToPool(this);
}
VowpalWabbitExample::~VowpalWabbitExample()
{
this->!VowpalWabbitExample();
}
VowpalWabbitExample^ VowpalWabbitExample::InnerExample::get()
{
return m_innerExample;
}
IVowpalWabbitExamplePool^ VowpalWabbitExample::Owner::get()
{
return m_owner;
}
size_t VowpalWabbitExample::NumberOfFeatures::get()
{
return m_example->num_features;
}
generic<typename T> T VowpalWabbitExample::GetPrediction(VowpalWabbit^ vw, IVowpalWabbitPredictionFactory<T>^ factory)
{
#ifdef _DEBUG
if (vw == nullptr)
throw gcnew ArgumentNullException("vw");
#endif
return factory->Create(vw->m_vw, m_example);
}
String^ VowpalWabbitExample::VowpalWabbitString::get()
{
return m_string;
}
void VowpalWabbitExample::VowpalWabbitString::set(String^ value)
{
m_string = value;
}
bool VowpalWabbitExample::IsNewLine::get()
{
return example_is_newline(*m_example) != 0;
}
ILabel^ VowpalWabbitExample::Label::get()
{
ILabel^ label;
auto lp = m_owner->Native->m_vw->p->lp;
if (!memcmp(&lp, &simple_label, sizeof(lp)))
label = gcnew SimpleLabel();
else if (!memcmp(&lp, &CB::cb_label, sizeof(lp)))
label = gcnew ContextualBanditLabel();
else if (!memcmp(&lp, &CB_EVAL::cb_eval, sizeof(lp)))
label = gcnew SimpleLabel();
else if (!memcmp(&lp, &COST_SENSITIVE::cs_label, sizeof(lp)))
label = gcnew SimpleLabel();
else
return nullptr;
// TODO:
//else if (!memcmp(&lp, &MULTICLASS::multilabel, sizeof(lp)))
// label = gcnew MulticlassLabel;
//else if (!memcmp(&lp, &MC::multilabel, sizeof(lp)))
label->ReadFromExample(this->m_example);
return label;
}
void VowpalWabbitExample::MakeEmpty(VowpalWabbit^ vw)
{
char empty = '\0';
VW::read_line(*vw->m_vw, m_example, &empty);
VW::parse_atomic_example(*vw->m_vw, m_example, false);
VW::setup_example(*vw->m_vw, m_example);
}
void FormatIndices(example* a, System::Text::StringBuilder^ sb)
{
for (auto ns : a->indices)
{
if (ns == 0)
sb->Append("NULL:0,");
else
sb->AppendFormat("'{0}':{1},", gcnew System::Char(ns), (int)ns);
}
}
System::String^ FormatIndices(example* a, example *b)
{
auto sb = gcnew System::Text::StringBuilder();
sb->AppendFormat("Namespace indicies differ: {0} vs {1}. this.indices: [",
a->indices.size(),
b->indices.size());
FormatIndices(a, sb);
sb->Append("] other.indices: [");
FormatIndices(b, sb);
sb->Append("]");
return sb->ToString();
}
System::String^ FormatFeature(vw* vw, feature_value& f1, feature_index& i1)
{
uint64_t masked_weight_index1 = i1 & vw->reg.weight_mask;
return System::String::Format(
"weight_index = {0}/{1}, x = {2}",
masked_weight_index1,
i1,
gcnew System::Single(f1));
}
System::String^ FormatFeature(vw* vw, feature_value& f1, feature_index& i1, feature_value& f2, feature_index& i2)
{
return System::String::Format(
"Feature differ: this({0}) vs other({1})",
FormatFeature(vw, f1, i1),
FormatFeature(vw, f2, i2));
}
bool FloatEqual(float a, float b)
{
if ((abs(a) < 1e-20 && abs(b) < 1e-20) ||
(isinf(a) && isinf(b)))
{
return true;
}
return abs(a - b) / max(a, b) < 1e-6;
}
System::String^ FormatFeatures(vw* vw, features& arr)
{
auto sb = gcnew System::Text::StringBuilder();
for (size_t i = 0; i < arr.values.size(); i++)
{
sb->Append(FormatFeature(vw, arr.values[i], arr.indicies[i]))->Append(" ");
}
return sb->ToString();
}
System::String^ CompareFeatures(vw* vw, features& fa, features& fb)
{
vector<size_t> fa_missing;
for (size_t ia = 0, ib = 0; ia < fa.values.size(); ia++)
{
auto masked_weight_index = fa.indicies[ia] & vw->reg.weight_mask;
auto other_masked_weight_index = fb.indicies[ib] & vw->reg.weight_mask;
/*System::Diagnostics::Debug::WriteLine(System::String::Format("{0} -> {1} vs {2} -> {3}",
fa.indicies[ia], masked_weight_index,
fb.indicies[ib], other_masked_weight_index
));*/
if (masked_weight_index == other_masked_weight_index && FloatEqual(fa.values[ia], fb.values[ib]))
ib++;
else
{
// fallback to search
size_t ib_old = ib;
bool found = false;
for (ib = 0; ib < fb.values.size(); ib++)
{
auto other_masked_weight_index = fb.indicies[ib] & vw->reg.weight_mask;
if (masked_weight_index == other_masked_weight_index)
{
if (!FloatEqual(fa.values[ia], fb.values[ib]))
{
return FormatFeature(vw, fa.values[ia], fa.indicies[ia], fb.values[ib], fb.indicies[ib]);
}
else
{
found = true;
break;
}
}
}
if (!found)
{
fa_missing.push_back(ia);
}
ib = ib_old + 1;
}
}
if (!fa_missing.empty())
{
auto diff = gcnew System::Text::StringBuilder("missing: ");
for (size_t& ia : fa_missing)
{
diff->AppendFormat("this.weight_index = {0}, x = {1}, ",
fa.indicies[ia] & vw->reg.weight_mask,
fa.values[ia]);
}
return diff->ToString();
}
return nullptr;
}
System::String^ VowpalWabbitExample::Diff(VowpalWabbit^ vw, VowpalWabbitExample^ other, IVowpalWabbitLabelComparator^ labelComparator)
{
auto a = this->m_example;
auto b = other->m_example;
if (a->indices.size() != b->indices.size())
{
return FormatIndices(a, b);
}
for (auto i = a->indices.begin(), j = b->indices.begin(); i != a->indices.end(); i++)
{
if (*i == *j)
j++;
else
{
// fall back on search
auto j_old = j;
j = b->indices.begin();
bool found = false;
for (; j != b->indices.end(); j++)
{
if (*i == *j)
{
found = true;
break;
}
}
if (!found)
return FormatIndices(a, b);
j = j_old + 1;
}
// compare features
features& fa = a->feature_space[*i];
features& fb = b->feature_space[*i];
if (fa.size() != fb.size())
return System::String::Format("Feature length differ {0} vs {1}. this({2}) vs other({3})",
fa.size(), fb.size(), FormatFeatures(vw->m_vw, fa), FormatFeatures(vw->m_vw, fb));
auto diff = CompareFeatures(vw->m_vw, fa, fb);
if (diff != nullptr)
return diff;
diff = CompareFeatures(vw->m_vw, fb, fa);
if (diff != nullptr)
return diff;
}
if (labelComparator != nullptr)
{
// Compare the label
auto diff = labelComparator->Diff(this, other);
if (diff != nullptr)
return diff;
}
return nullptr;
}
String^ VowpalWabbitSimpleLabelComparator::Diff(VowpalWabbitExample^ ex1, VowpalWabbitExample^ ex2)
{
auto s1 = ex1->m_example->l.simple;
auto s2 = ex2->m_example->l.simple;
if (!(FloatEqual(s1.initial, s2.initial) &&
FloatEqual(s1.label, s2.label) &&
FloatEqual(s1.weight, s2.weight)))
{
return System::String::Format("Label differ. label {0} vs {1}. initial {2} vs {3}. weight {4} vs {5}",
s1.label, s2.label,
s1.initial, s2.initial,
s1.weight, s2.weight);
}
return nullptr;
}
String^ VowpalWabbitContextualBanditLabelComparator::Diff(VowpalWabbitExample^ ex1, VowpalWabbitExample^ ex2)
{
auto s1 = ex1->m_example->l.cb;
auto s2 = ex2->m_example->l.cb;
if (s1.costs.size() != s2.costs.size())
{
return System::String::Format("Cost size differ: {0} vs {1}", s1.costs.size(), s2.costs.size());
}
for (size_t i = 0; i < s1.costs.size(); i++)
{
auto c1 = s1.costs[i];
auto c2 = s2.costs[i];
if (c1.action != c2.action)
{
return System::String::Format("Action differ: {0} vs {1}", c1.action, c2.action);
}
if (c1.cost != c2.cost)
{
return System::String::Format("Cost differ: {0} vs {1}", c1.cost, c2.cost);
}
if (abs(c1.probability - c2.probability) / max(c1.probability, c2.probability) > 0.01)
{
return System::String::Format("Probability differ: {0} vs {1}", c1.probability, c2.probability);
}
}
return nullptr;
}
System::Collections::IEnumerator^ VowpalWabbitExample::EnumerableGetEnumerator::get()
{
return GetEnumerator();
}
IEnumerator<VowpalWabbitNamespace^>^ VowpalWabbitExample::GetEnumerator()
{
return gcnew NamespaceEnumerator(this);
}
VowpalWabbitExample::NamespaceEnumerator::NamespaceEnumerator(VowpalWabbitExample^ example)
: m_example(example)
{
Reset();
}
VowpalWabbitExample::NamespaceEnumerator::~NamespaceEnumerator()
{ }
bool VowpalWabbitExample::NamespaceEnumerator::MoveNext()
{
m_current++;
return m_current < m_example->m_example->indices.end();
}
void VowpalWabbitExample::NamespaceEnumerator::Reset()
{
// position before the beginning.
m_current = m_example->m_example->indices.begin() - 1;
}
VowpalWabbitNamespace^ VowpalWabbitExample::NamespaceEnumerator::Current::get()
{
if (m_current < m_example->m_example->indices.begin() || m_current >= m_example->m_example->indices.end())
throw gcnew InvalidOperationException();
return gcnew VowpalWabbitNamespace(m_example, *m_current, &m_example->m_example->feature_space[*m_current]);
}
System::Object^ VowpalWabbitExample::NamespaceEnumerator::IEnumeratorCurrent::get()
{
return Current;
}
VowpalWabbitFeature::VowpalWabbitFeature(VowpalWabbitExample^ example, feature_value x, uint64_t weight_index)
: m_example(example), m_x(x), m_weight_index(weight_index)
{ }
float VowpalWabbitFeature::X::get()
{
return m_x;
}
uint64_t VowpalWabbitFeature::FeatureIndex::get()
{
return m_weight_index;
}
uint64_t VowpalWabbitFeature::WeightIndex::get()
{
vw* vw = m_example->Owner->Native->m_vw;
return ((m_weight_index + m_example->m_example->ft_offset) >> vw->reg.stride_shift) & vw->parse_mask;
}
float VowpalWabbitFeature::Weight::get()
{
vw* vw = m_example->Owner->Native->m_vw;
uint64_t weightIndex = (m_weight_index + m_example->m_example->ft_offset) & vw->reg.weight_mask;
return vw->reg.weight_vector[weightIndex];
}
float VowpalWabbitFeature::AuditWeight::get()
{
vw* vw = m_example->Owner->Native->m_vw;
return GD::trunc_weight(Weight, (float)vw->sd->gravity) * (float)vw->sd->contraction;
}
bool VowpalWabbitFeature::Equals(Object^ o)
{
VowpalWabbitFeature^ other = dynamic_cast<VowpalWabbitFeature^>(o);
return other != nullptr &&
other->m_x == m_x &&
other->m_weight_index == m_weight_index;
}
int VowpalWabbitFeature::GetHashCode()
{
return (int)(m_x + m_weight_index);
}
VowpalWabbitNamespace::VowpalWabbitNamespace(VowpalWabbitExample^ example, namespace_index ns, features* features)
: m_example(example), m_ns(ns), m_features(features)
{ }
VowpalWabbitNamespace::~VowpalWabbitNamespace()
{ }
namespace_index VowpalWabbitNamespace::Index::get()
{
return m_ns;
}
System::Collections::IEnumerator^ VowpalWabbitNamespace::EnumerableGetEnumerator::get()
{
return GetEnumerator();
}
IEnumerator<VowpalWabbitFeature^>^ VowpalWabbitNamespace::GetEnumerator()
{
return gcnew FeatureEnumerator(m_example, m_features);
}
VowpalWabbitNamespace::FeatureEnumerator::FeatureEnumerator(VowpalWabbitExample^ example, features* features)
: m_example(example), m_features(features), m_iterator(nullptr)
{
m_end = new Holder<features::iterator>{ features->end() };
}
VowpalWabbitNamespace::FeatureEnumerator::~FeatureEnumerator()
{
delete m_end;
delete m_iterator;
}
void VowpalWabbitNamespace::FeatureEnumerator::Reset()
{
delete m_iterator;
m_iterator = nullptr;
}
bool VowpalWabbitNamespace::FeatureEnumerator::MoveNext()
{
if (m_iterator)
++m_iterator->value;
else
m_iterator = new Holder<features::iterator>{ m_features->begin() };
return m_iterator->value != m_end->value;
}
System::Object^ VowpalWabbitNamespace::FeatureEnumerator::IEnumeratorCurrent::get()
{
return Current;
}
VowpalWabbitFeature^ VowpalWabbitNamespace::FeatureEnumerator::Current::get()
{
if (!m_iterator || m_iterator->value == m_end->value)
throw gcnew InvalidOperationException();
return gcnew VowpalWabbitFeature(m_example, m_iterator->value.value(), m_iterator->value.index());
}
}
|
/*+**************************************************************************/
/*** ***/
/*** This file is distributed under a BSD license. ***/
/*** See LICENSE.txt for details. ***/
/*** ***/
/**************************************************************************+*/
#ifndef FILE_PLANPAD_PDF_HPP
#define FILE_PLANPAD_PDF_HPP
#include "base/types2.hpp"
/****************************************************************************/
class sPDF
{
// the document
sArray<sU8> Data;
void Print(const sChar *);
// xref
sArray<sInt> Objects; // object 0 = dummy, 1 = pages, 2 = catalog
sInt AddObject(); // "x 0 obj\n"
sArray<sInt> Pages; // all page objects
sArray<sInt> PageFonts; // resources used by current page
void PageFont(sInt font);
// stream assembly
sArray<sU8> StreamData;
void Stream(const sChar *);
void Stream(const sChar *,sInt len);
void StreamString(const sChar *text,sInt len);
sInt AddStream(); // add stream as object, returns object id
// formatted printing
sPRINTING0(PrintF,sFormatStringBuffer buf; sFormatStringBaseCtx(buf,format);buf,Print(buf.Get());)
sPRINTING0(StreamF,sFormatStringBuffer buf; sFormatStringBaseCtx(buf,format);buf,Stream(buf.Get());)
sInt cache_Tf_font;
sF32 cache_Tf_scale;
sU32 cache_rg;
public:
sPDF();
~sPDF();
// general preparation
void BeginDoc(sF32 xs=597.6f,sInt ys=842.4f); // start with A4 page size
sInt RegisterFont(sInt flags,class sFont2D *font); // returns font object #
void EndDoc(const sChar *filename); // write header and save file
// cache
void InvalidateCache();
void _Tf(sInt font,sF32 scale);
void _rg(sU32 col);
// printing commands
sInt BeginPage(); // return page number, starting with 0
void EndPage();
void Text(sInt font,sF32 s,sF32 x,sF32 y,sU32 col,const sChar *text,sInt len=-1);
void Text(sInt font,sF32 matrix[6],sU32 col,const sChar *text,sInt len=-1);
void Rect(const sFRect &r,sU32 col);
void RectFrame(const sFRect &r,sU32 col,sF32 w);
// quick stats;
sF32 SizeX,SizeY; // page size
sInt Page; // starts with 0!
};
enum sPDFEnum
{
sPDF_Times = 0x1,
sPDF_Courier = 0x2,
sPDF_Helvetica = 0x3,
sPDF_Symbol = 0x4,
sPDF_Dingbats = 0x5,
sPDF_Regular = 0x00,
sPDF_Italic = 0x10,
sPDF_Bold = 0x20,
sPDF_BoldItalic = 0x30,
};
/****************************************************************************/
#endif // FILE_PLANPAD_PDF_HPP
|
// (C) Copyright 2008-10 Anthony Williams
//
// 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)
#include <utility>
#include <memory>
#include <stdexcept>
#include <string>
#include <thread>
#include <boost/fiber/all.hpp>
#include <boost/test/unit_test.hpp>
int fn( int i) {
return i;
}
void test_async() {
for ( int i = 0; i < 10; ++i) {
int n = 3;
boost::fibers::packaged_task< int( int) > pt( fn);
boost::fibers::future< int > f( pt.get_future() );
std::thread t(
std::bind(
[n](boost::fibers::packaged_task< int( int) > & pt) mutable -> void {
boost::fibers::fiber( boost::fibers::launch::post, std::move( pt), n).join();
},
std::move( pt) ) );
int result = f.get();
BOOST_CHECK_EQUAL( n, result);
t.join();
}
}
void test_dummy() {}
boost::unit_test_framework::test_suite* init_unit_test_suite(int, char*[]) {
boost::unit_test_framework::test_suite* test =
BOOST_TEST_SUITE("Boost.Fiber: futures-mt test suite");
#if ! defined(BOOST_FIBERS_NO_ATOMICS)
test->add(BOOST_TEST_CASE(test_async));
#else
test->add(BOOST_TEST_CASE(test_dummy));
#endif
return test;
}
|
/*
Copyright (c) 2018-2019, tevador <tevador@gmail.com>
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 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.
*/
#include <new>
#include "crypto/randomx/allocator.hpp"
#include "crypto/randomx/intrin_portable.h"
#include "crypto/randomx/virtual_memory.hpp"
#include "crypto/randomx/common.hpp"
namespace randomx {
template<size_t alignment>
void* AlignedAllocator<alignment>::allocMemory(size_t count) {
void *mem = rx_aligned_alloc(count, alignment);
if (mem == nullptr)
throw std::bad_alloc();
return mem;
}
template<size_t alignment>
void AlignedAllocator<alignment>::freeMemory(void* ptr, size_t count) {
rx_aligned_free(ptr);
}
template struct AlignedAllocator<CacheLineSize>;
void* LargePageAllocator::allocMemory(size_t count) {
return allocLargePagesMemory(count);
}
void LargePageAllocator::freeMemory(void* ptr, size_t count) {
freePagedMemory(ptr, count);
};
}
|
/*
* Copyright (c) 2010, Google Inc. 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 Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#if USE(ACCELERATED_COMPOSITING) || ENABLE(ACCELERATED_2D_CANVAS)
#include "TilingData.h"
#include "FloatRect.h"
#include "IntRect.h"
#include <algorithm>
using namespace std;
namespace WebCore {
static int computeNumTiles(int maxTextureSize, int totalSize, int borderTexels)
{
if (maxTextureSize - 2 * borderTexels <= 0)
return totalSize > 0 && maxTextureSize >= totalSize ? 1 : 0;
int numTiles = max(1, 1 + (totalSize - 1 - 2 * borderTexels) / (maxTextureSize - 2 * borderTexels));
return totalSize > 0 ? numTiles : 0;
}
TilingData::TilingData(int maxTextureSize, int totalSizeX, int totalSizeY, bool hasBorderTexels)
: m_maxTextureSize(maxTextureSize)
, m_totalSizeX(totalSizeX)
, m_totalSizeY(totalSizeY)
, m_borderTexels(hasBorderTexels ? 1 : 0)
{
recomputeNumTiles();
}
void TilingData::setTotalSize(int totalSizeX, int totalSizeY)
{
m_totalSizeX = totalSizeX;
m_totalSizeY = totalSizeY;
recomputeNumTiles();
}
void TilingData::setMaxTextureSize(int maxTextureSize)
{
m_maxTextureSize = maxTextureSize;
recomputeNumTiles();
}
int TilingData::tileXIndexFromSrcCoord(int srcPos) const
{
if (numTilesX() <= 1)
return 0;
ASSERT(m_maxTextureSize - 2 * m_borderTexels);
int x = (srcPos - m_borderTexels) / (m_maxTextureSize - 2 * m_borderTexels);
return min(max(x, 0), numTilesX() - 1);
}
int TilingData::tileYIndexFromSrcCoord(int srcPos) const
{
if (numTilesY() <= 1)
return 0;
ASSERT(m_maxTextureSize - 2 * m_borderTexels);
int y = (srcPos - m_borderTexels) / (m_maxTextureSize - 2 * m_borderTexels);
return min(max(y, 0), numTilesY() - 1);
}
IntRect TilingData::tileBounds(int tile) const
{
assertTile(tile);
int ix = tileXIndex(tile);
int iy = tileYIndex(tile);
int x = tilePositionX(ix);
int y = tilePositionY(iy);
int width = tileSizeX(ix);
int height = tileSizeY(iy);
ASSERT(x >= 0 && y >= 0 && width >= 0 && height >= 0);
ASSERT(x <= totalSizeX() && y <= totalSizeY());
return IntRect(x, y, width, height);
}
IntRect TilingData::tileBoundsWithBorder(int tile) const
{
IntRect bounds = tileBounds(tile);
if (m_borderTexels) {
int x1 = bounds.x();
int x2 = bounds.maxX();
int y1 = bounds.y();
int y2 = bounds.maxY();
if (tileXIndex(tile) > 0)
x1--;
if (tileXIndex(tile) < (numTilesX() - 1))
x2++;
if (tileYIndex(tile) > 0)
y1--;
if (tileYIndex(tile) < (numTilesY() - 1))
y2++;
bounds = IntRect(x1, y1, x2 - x1, y2 - y1);
}
return bounds;
}
FloatRect TilingData::tileBoundsNormalized(int tile) const
{
assertTile(tile);
FloatRect bounds(tileBounds(tile));
bounds.scale(1.0f / m_totalSizeX, 1.0f / m_totalSizeY);
return bounds;
}
int TilingData::tilePositionX(int xIndex) const
{
ASSERT(xIndex >= 0 && xIndex < numTilesX());
int pos = 0;
for (int i = 0; i < xIndex; i++)
pos += tileSizeX(i);
return pos;
}
int TilingData::tilePositionY(int yIndex) const
{
ASSERT(yIndex >= 0 && yIndex < numTilesY());
int pos = 0;
for (int i = 0; i < yIndex; i++)
pos += tileSizeY(i);
return pos;
}
int TilingData::tileSizeX(int xIndex) const
{
ASSERT(xIndex >= 0 && xIndex < numTilesX());
if (!xIndex && m_numTilesX == 1)
return m_totalSizeX;
if (!xIndex && m_numTilesX > 1)
return m_maxTextureSize - m_borderTexels;
if (xIndex < numTilesX() - 1)
return m_maxTextureSize - 2 * m_borderTexels;
if (xIndex == numTilesX() - 1)
return m_totalSizeX - tilePositionX(xIndex);
ASSERT_NOT_REACHED();
return 0;
}
int TilingData::tileSizeY(int yIndex) const
{
ASSERT(yIndex >= 0 && yIndex < numTilesY());
if (!yIndex && m_numTilesY == 1)
return m_totalSizeY;
if (!yIndex && m_numTilesY > 1)
return m_maxTextureSize - m_borderTexels;
if (yIndex < numTilesY() - 1)
return m_maxTextureSize - 2 * m_borderTexels;
if (yIndex == numTilesY() - 1)
return m_totalSizeY - tilePositionY(yIndex);
ASSERT_NOT_REACHED();
return 0;
}
IntRect TilingData::overlappedTileIndices(const WebCore::IntRect &srcRect) const
{
int x = tileXIndexFromSrcCoord(srcRect.x());
int y = tileYIndexFromSrcCoord(srcRect.y());
int r = tileXIndexFromSrcCoord(srcRect.maxX());
int b = tileYIndexFromSrcCoord(srcRect.maxY());
return IntRect(x, y, r - x, b - y);
}
IntRect TilingData::overlappedTileIndices(const WebCore::FloatRect &srcRect) const
{
return overlappedTileIndices(enclosingIntRect(srcRect));
}
void TilingData::intersectDrawQuad(const FloatRect& srcRect, const FloatRect& dstRect, int tile,
FloatRect* newSrc, FloatRect* newDst) const
{
// Intersect with tile
FloatRect tileBounds = this->tileBounds(tile);
FloatRect srcRectIntersected = srcRect;
srcRectIntersected.intersect(tileBounds);
if (srcRectIntersected.isEmpty()) {
*newSrc = *newDst = FloatRect(0, 0, 0, 0);
return;
}
float srcRectIntersectedNormX = (srcRectIntersected.x() - srcRect.x()) / srcRect.width();
float srcRectIntersectedNormY = (srcRectIntersected.y() - srcRect.y()) / srcRect.height();
float srcRectIntersectedNormW = srcRectIntersected.width() / srcRect.width();
float srcRectIntersectedNormH = srcRectIntersected.height() / srcRect.height();
*newSrc = srcRectIntersected;
newSrc->move(
-tileBounds.x() + ((tileXIndex(tile) > 0) ? m_borderTexels : 0),
-tileBounds.y() + ((tileYIndex(tile) > 0) ? m_borderTexels : 0));
*newDst = FloatRect(
srcRectIntersectedNormX * dstRect.width() + dstRect.x(),
srcRectIntersectedNormY * dstRect.height() + dstRect.y(),
srcRectIntersectedNormW * dstRect.width(),
srcRectIntersectedNormH * dstRect.height());
}
IntPoint TilingData::textureOffset(int xIndex, int yIndex) const
{
int left = (!xIndex || m_numTilesX == 1) ? 0 : m_borderTexels;
int top = (!yIndex || m_numTilesY == 1) ? 0 : m_borderTexels;
return IntPoint(left, top);
}
void TilingData::recomputeNumTiles()
{
m_numTilesX = computeNumTiles(m_maxTextureSize, m_totalSizeX, m_borderTexels);
m_numTilesY = computeNumTiles(m_maxTextureSize, m_totalSizeY, m_borderTexels);
}
}
#endif
|
#include "Shotgun.h"
#include <math.h>
Shotgun::Shotgun(unsigned int clipSize, unsigned int minDamage, unsigned int maxDamage, int aimModifier, int critModifier)
: GunBase(clipSize, minDamage, maxDamage, aimModifier, critModifier) {
m_gunType = 1;
}
Shotgun::~Shotgun()
{
}
int Shotgun::GetRangeBonus(const float distance) const
{
float distSq = distance * distance;
return 56 - (int)( 4 * floor( sqrt(2 * distSq) ) );
}
|
#include "portsorch.h"
#include "neighorch.h"
#include <cassert>
#include <fstream>
#include <sstream>
#include <set>
#include <algorithm>
#include <tuple>
#include <sstream>
#include <netinet/if_ether.h>
#include "net/if.h"
#include "logger.h"
#include "schema.h"
#include "converter.h"
#include "sai_serialize.h"
#include "crmorch.h"
#include "countercheckorch.h"
#include "bufferorch.h"
#include "notifier.h"
extern sai_switch_api_t *sai_switch_api;
extern sai_bridge_api_t *sai_bridge_api;
extern sai_port_api_t *sai_port_api;
extern sai_vlan_api_t *sai_vlan_api;
extern sai_lag_api_t *sai_lag_api;
extern sai_hostif_api_t* sai_hostif_api;
extern sai_acl_api_t* sai_acl_api;
extern sai_queue_api_t *sai_queue_api;
extern sai_object_id_t gSwitchId;
extern NeighOrch *gNeighOrch;
extern CrmOrch *gCrmOrch;
extern BufferOrch *gBufferOrch;
#define VLAN_PREFIX "Vlan"
#define DEFAULT_VLAN_ID 1
#define PORT_FLEX_STAT_COUNTER_POLL_MSECS "1000"
#define QUEUE_FLEX_STAT_COUNTER_POLL_MSECS "10000"
static map<string, sai_port_fec_mode_t> fec_mode_map =
{
{ "none", SAI_PORT_FEC_MODE_NONE },
{ "rs", SAI_PORT_FEC_MODE_RS },
{ "fc", SAI_PORT_FEC_MODE_FC }
};
const vector<sai_port_stat_t> portStatIds =
{
SAI_PORT_STAT_IF_IN_OCTETS,
SAI_PORT_STAT_IF_IN_UCAST_PKTS,
SAI_PORT_STAT_IF_IN_NON_UCAST_PKTS,
SAI_PORT_STAT_IF_IN_DISCARDS,
SAI_PORT_STAT_IF_IN_ERRORS,
SAI_PORT_STAT_IF_IN_UNKNOWN_PROTOS,
SAI_PORT_STAT_IF_OUT_OCTETS,
SAI_PORT_STAT_IF_OUT_UCAST_PKTS,
SAI_PORT_STAT_IF_OUT_NON_UCAST_PKTS,
SAI_PORT_STAT_IF_OUT_DISCARDS,
SAI_PORT_STAT_IF_OUT_ERRORS,
SAI_PORT_STAT_IF_OUT_QLEN,
SAI_PORT_STAT_IF_IN_MULTICAST_PKTS,
SAI_PORT_STAT_IF_IN_BROADCAST_PKTS,
SAI_PORT_STAT_IF_OUT_MULTICAST_PKTS,
SAI_PORT_STAT_IF_OUT_BROADCAST_PKTS,
SAI_PORT_STAT_ETHER_RX_OVERSIZE_PKTS,
SAI_PORT_STAT_ETHER_TX_OVERSIZE_PKTS,
SAI_PORT_STAT_PFC_0_TX_PKTS,
SAI_PORT_STAT_PFC_1_TX_PKTS,
SAI_PORT_STAT_PFC_2_TX_PKTS,
SAI_PORT_STAT_PFC_3_TX_PKTS,
SAI_PORT_STAT_PFC_4_TX_PKTS,
SAI_PORT_STAT_PFC_5_TX_PKTS,
SAI_PORT_STAT_PFC_6_TX_PKTS,
SAI_PORT_STAT_PFC_7_TX_PKTS,
SAI_PORT_STAT_PFC_0_RX_PKTS,
SAI_PORT_STAT_PFC_1_RX_PKTS,
SAI_PORT_STAT_PFC_2_RX_PKTS,
SAI_PORT_STAT_PFC_3_RX_PKTS,
SAI_PORT_STAT_PFC_4_RX_PKTS,
SAI_PORT_STAT_PFC_5_RX_PKTS,
SAI_PORT_STAT_PFC_6_RX_PKTS,
SAI_PORT_STAT_PFC_7_RX_PKTS,
SAI_PORT_STAT_PAUSE_RX_PKTS,
SAI_PORT_STAT_PAUSE_TX_PKTS,
SAI_PORT_STAT_ETHER_STATS_TX_NO_ERRORS,
SAI_PORT_STAT_IP_IN_UCAST_PKTS,
SAI_PORT_STAT_ETHER_IN_PKTS_128_TO_255_OCTETS,
};
static const vector<sai_queue_stat_t> queueStatIds =
{
SAI_QUEUE_STAT_PACKETS,
SAI_QUEUE_STAT_BYTES,
SAI_QUEUE_STAT_DROPPED_PACKETS,
SAI_QUEUE_STAT_DROPPED_BYTES,
};
static char* hostif_vlan_tag[] = {
[SAI_HOSTIF_VLAN_TAG_STRIP] = "SAI_HOSTIF_VLAN_TAG_STRIP",
[SAI_HOSTIF_VLAN_TAG_KEEP] = "SAI_HOSTIF_VLAN_TAG_KEEP",
[SAI_HOSTIF_VLAN_TAG_ORIGINAL] = "SAI_HOSTIF_VLAN_TAG_ORIGINAL"
};
/*
* Initialize PortsOrch
* 0) By default, a switch has one CPU port, one 802.1Q bridge, and one default
* VLAN. All ports are in .1Q bridge as bridge ports, and all bridge ports
* are in default VLAN as VLAN members.
* 1) Query switch CPU port.
* 2) Query ports associated with lane mappings
* 3) Query switch .1Q bridge and all its bridge ports.
* 4) Query switch default VLAN and all its VLAN members.
* 5) Remove each VLAN member from default VLAN and each bridge port from .1Q
* bridge. By design, SONiC switch starts with all bridge ports removed from
* default VLAN and all ports removed from .1Q bridge.
*/
PortsOrch::PortsOrch(DBConnector *db, vector<table_name_with_pri_t> &tableNames) :
Orch(db, tableNames)
{
SWSS_LOG_ENTER();
/* Initialize counter table */
m_counter_db = shared_ptr<DBConnector>(new DBConnector(COUNTERS_DB, DBConnector::DEFAULT_UNIXSOCKET, 0));
m_counterTable = unique_ptr<Table>(new Table(m_counter_db.get(), COUNTERS_PORT_NAME_MAP));
/* Initialize port table */
m_portTable = unique_ptr<Table>(new Table(db, APP_PORT_TABLE_NAME));
/* Initialize queue tables */
m_queueTable = unique_ptr<Table>(new Table(m_counter_db.get(), COUNTERS_QUEUE_NAME_MAP));
m_queuePortTable = unique_ptr<Table>(new Table(m_counter_db.get(), COUNTERS_QUEUE_PORT_MAP));
m_queueIndexTable = unique_ptr<Table>(new Table(m_counter_db.get(), COUNTERS_QUEUE_INDEX_MAP));
m_queueTypeTable = unique_ptr<Table>(new Table(m_counter_db.get(), COUNTERS_QUEUE_TYPE_MAP));
m_flex_db = shared_ptr<DBConnector>(new DBConnector(FLEX_COUNTER_DB, DBConnector::DEFAULT_UNIXSOCKET, 0));
m_flexCounterTable = unique_ptr<ProducerTable>(new ProducerTable(m_flex_db.get(), FLEX_COUNTER_TABLE));
m_flexCounterGroupTable = unique_ptr<ProducerTable>(new ProducerTable(m_flex_db.get(), FLEX_COUNTER_GROUP_TABLE));
vector<FieldValueTuple> fields;
fields.emplace_back(POLL_INTERVAL_FIELD, PORT_FLEX_STAT_COUNTER_POLL_MSECS);
m_flexCounterGroupTable->set(PORT_STAT_COUNTER_FLEX_COUNTER_GROUP, fields);
fields.emplace_back(POLL_INTERVAL_FIELD, QUEUE_FLEX_STAT_COUNTER_POLL_MSECS);
m_flexCounterGroupTable->set(QUEUE_STAT_COUNTER_FLEX_COUNTER_GROUP, fields);
uint32_t i, j;
sai_status_t status;
sai_attribute_t attr;
/* Get CPU port */
attr.id = SAI_SWITCH_ATTR_CPU_PORT;
status = sai_switch_api->get_switch_attribute(gSwitchId, 1, &attr);
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Failed to get CPU port, rv:%d", status);
throw "PortsOrch initialization failure";
}
m_cpuPort = Port("CPU", Port::CPU);
m_cpuPort.m_port_id = attr.value.oid;
m_portList[m_cpuPort.m_alias] = m_cpuPort;
/* Get port number */
attr.id = SAI_SWITCH_ATTR_PORT_NUMBER;
status = sai_switch_api->get_switch_attribute(gSwitchId, 1, &attr);
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Failed to get port number, rv:%d", status);
throw "PortsOrch initialization failure";
}
m_portCount = attr.value.u32;
SWSS_LOG_NOTICE("Get %d ports", m_portCount);
/* Get port list */
vector<sai_object_id_t> port_list;
port_list.resize(m_portCount);
attr.id = SAI_SWITCH_ATTR_PORT_LIST;
attr.value.objlist.count = (uint32_t)port_list.size();
attr.value.objlist.list = port_list.data();
status = sai_switch_api->get_switch_attribute(gSwitchId, 1, &attr);
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Failed to get port list, rv:%d", status);
throw "PortsOrch initialization failure";
}
/* Get port hardware lane info */
for (i = 0; i < m_portCount; i++)
{
sai_uint32_t lanes[4] = { 0,0,0,0 };
attr.id = SAI_PORT_ATTR_HW_LANE_LIST;
attr.value.u32list.count = 4;
attr.value.u32list.list = lanes;
status = sai_port_api->get_port_attribute(port_list[i], 1, &attr);
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Failed to get hardware lane list pid:%lx", port_list[i]);
throw "PortsOrch initialization failure";
}
set<int> tmp_lane_set;
for (j = 0; j < attr.value.u32list.count; j++)
tmp_lane_set.insert(attr.value.u32list.list[j]);
string tmp_lane_str = "";
for (auto s : tmp_lane_set)
{
tmp_lane_str += to_string(s) + " ";
}
tmp_lane_str = tmp_lane_str.substr(0, tmp_lane_str.size()-1);
SWSS_LOG_NOTICE("Get port with lanes pid:%lx lanes:%s", port_list[i], tmp_lane_str.c_str());
m_portListLaneMap[tmp_lane_set] = port_list[i];
}
/* Get default 1Q bridge and default VLAN */
vector<sai_attribute_t> attrs;
attr.id = SAI_SWITCH_ATTR_DEFAULT_1Q_BRIDGE_ID;
attrs.push_back(attr);
attr.id = SAI_SWITCH_ATTR_DEFAULT_VLAN_ID;
attrs.push_back(attr);
status = sai_switch_api->get_switch_attribute(gSwitchId, (uint32_t)attrs.size(), attrs.data());
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Failed to get default 1Q bridge and/or default VLAN, rv:%d", status);
throw "PortsOrch initialization failure";
}
m_default1QBridge = attrs[0].value.oid;
m_defaultVlan = attrs[1].value.oid;
removeDefaultVlanMembers();
removeDefaultBridgePorts();
/* Add port oper status notification support */
DBConnector *notificationsDb = new DBConnector(ASIC_DB, DBConnector::DEFAULT_UNIXSOCKET, 0);
m_portStatusNotificationConsumer = new swss::NotificationConsumer(notificationsDb, "NOTIFICATIONS");
auto portStatusNotificatier = new Notifier(m_portStatusNotificationConsumer, this);
Orch::addExecutor("PORT_STATUS_NOTIFICATIONS", portStatusNotificatier);
}
void PortsOrch::removeDefaultVlanMembers()
{
/* Get VLAN members in default VLAN */
vector<sai_object_id_t> vlan_member_list(m_portCount);
sai_attribute_t attr;
attr.id = SAI_VLAN_ATTR_MEMBER_LIST;
attr.value.objlist.count = (uint32_t)vlan_member_list.size();
attr.value.objlist.list = vlan_member_list.data();
sai_status_t status = sai_vlan_api->get_vlan_attribute(m_defaultVlan, 1, &attr);
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Failed to get VLAN member list in default VLAN, rv:%d", status);
throw "PortsOrch initialization failure";
}
/* Remove VLAN members in default VLAN */
for (uint32_t i = 0; i < attr.value.objlist.count; i++)
{
status = sai_vlan_api->remove_vlan_member(vlan_member_list[i]);
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Failed to remove VLAN member, rv:%d", status);
throw "PortsOrch initialization failure";
}
}
SWSS_LOG_NOTICE("Remove %d VLAN members from default VLAN", attr.value.objlist.count);
}
void PortsOrch::removeDefaultBridgePorts()
{
/* Get bridge ports in default 1Q bridge
* By default, there will be m_portCount number of SAI_BRIDGE_PORT_TYPE_PORT
* ports and one SAI_BRIDGE_PORT_TYPE_1Q_ROUTER port. The former type of
* ports will be removed. */
vector<sai_object_id_t> bridge_port_list(m_portCount + 1);
sai_attribute_t attr;
attr.id = SAI_BRIDGE_ATTR_PORT_LIST;
attr.value.objlist.count = (uint32_t)bridge_port_list.size();
attr.value.objlist.list = bridge_port_list.data();
sai_status_t status = sai_bridge_api->get_bridge_attribute(m_default1QBridge, 1, &attr);
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Failed to get bridge port list in default 1Q bridge, rv:%d", status);
throw "PortsOrch initialization failure";
}
auto bridge_port_count = attr.value.objlist.count;
/* Remove SAI_BRIDGE_PORT_TYPE_PORT bridge ports in default 1Q bridge */
for (uint32_t i = 0; i < bridge_port_count; i++)
{
attr.id = SAI_BRIDGE_PORT_ATTR_TYPE;
attr.value.s32 = SAI_NULL_OBJECT_ID;
status = sai_bridge_api->get_bridge_port_attribute(bridge_port_list[i], 1, &attr);
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Failed to get bridge port type, rv:%d", status);
throw "PortsOrch initialization failure";
}
if (attr.value.s32 == SAI_BRIDGE_PORT_TYPE_PORT)
{
status = sai_bridge_api->remove_bridge_port(bridge_port_list[i]);
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Failed to remove bridge port, rv:%d", status);
throw "PortsOrch initialization failure";
}
}
}
SWSS_LOG_NOTICE("Remove bridge ports from default 1Q bridge");
}
bool PortsOrch::isInitDone()
{
return m_initDone;
}
map<string, Port>& PortsOrch::getAllPorts()
{
return m_portList;
}
bool PortsOrch::getPort(string alias, Port &p)
{
SWSS_LOG_ENTER();
if (m_portList.find(alias) == m_portList.end())
{
return false;
}
else
{
p = m_portList[alias];
return true;
}
}
bool PortsOrch::getPort(sai_object_id_t id, Port &port)
{
SWSS_LOG_ENTER();
for (const auto& portIter: m_portList)
{
switch (portIter.second.m_type)
{
case Port::PHY:
if(portIter.second.m_port_id == id)
{
port = portIter.second;
return true;
}
break;
case Port::LAG:
if(portIter.second.m_lag_id == id)
{
port = portIter.second;
return true;
}
break;
case Port::VLAN:
if (portIter.second.m_vlan_info.vlan_oid == id)
{
port = portIter.second;
return true;
}
break;
default:
continue;
}
}
return false;
}
bool PortsOrch::getPortByBridgePortId(sai_object_id_t bridge_port_id, Port &port)
{
SWSS_LOG_ENTER();
for (auto &it: m_portList)
{
if (it.second.m_bridge_port_id == bridge_port_id)
{
port = it.second;
return true;
}
}
return false;
}
bool PortsOrch::getAclBindPortId(string alias, sai_object_id_t &port_id)
{
SWSS_LOG_ENTER();
Port port;
if (getPort(alias, port))
{
switch (port.m_type)
{
case Port::PHY:
if (port.m_lag_member_id != SAI_NULL_OBJECT_ID)
{
SWSS_LOG_WARN("Invalid configuration. Bind table to LAG member %s is not allowed", alias.c_str());
return false;
}
else
{
port_id = port.m_port_id;
}
break;
case Port::LAG:
port_id = port.m_lag_id;
break;
case Port::VLAN:
port_id = port.m_vlan_info.vlan_oid;
break;
default:
SWSS_LOG_ERROR("Failed to process port. Incorrect port %s type %d", alias.c_str(), port.m_type);
return false;
}
return true;
}
else
{
return false;
}
}
void PortsOrch::setPort(string alias, Port p)
{
m_portList[alias] = p;
}
void PortsOrch::getCpuPort(Port &port)
{
port = m_cpuPort;
}
bool PortsOrch::setPortAdminStatus(sai_object_id_t id, bool up)
{
SWSS_LOG_ENTER();
sai_attribute_t attr;
attr.id = SAI_PORT_ATTR_ADMIN_STATE;
attr.value.booldata = up;
sai_status_t status = sai_port_api->set_port_attribute(id, &attr);
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Failed to set admin status %s to port pid:%lx",
up ? "UP" : "DOWN", id);
return false;
}
SWSS_LOG_INFO("Set admin status %s to port pid:%lx",
up ? "UP" : "DOWN", id);
return true;
}
bool PortsOrch::setPortMtu(sai_object_id_t id, sai_uint32_t mtu)
{
SWSS_LOG_ENTER();
sai_attribute_t attr;
attr.id = SAI_PORT_ATTR_MTU;
/* mtu + 14 + 4 + 4 = 22 bytes */
attr.value.u32 = (uint32_t)(mtu + sizeof(struct ether_header) + FCS_LEN + VLAN_TAG_LEN);
sai_status_t status = sai_port_api->set_port_attribute(id, &attr);
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Failed to set MTU %u to port pid:%lx", attr.value.u32, id);
return false;
}
SWSS_LOG_INFO("Set MTU %u to port pid:%lx", attr.value.u32, id);
return true;
}
bool PortsOrch::setPortFec(sai_object_id_t id, sai_port_fec_mode_t mode)
{
SWSS_LOG_ENTER();
sai_attribute_t attr;
attr.id = SAI_PORT_ATTR_FEC_MODE;
attr.value.s32 = mode;
sai_status_t status = sai_port_api->set_port_attribute(id, &attr);
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Failed to set fec mode %d to port pid:%lx",
mode, id);
return false;
}
SWSS_LOG_INFO("Set fec mode %d to port pid:%lx",
mode, id);
return true;
}
bool PortsOrch::bindAclTable(sai_object_id_t id, sai_object_id_t table_oid, sai_object_id_t &group_member_oid, acl_stage_type_t acl_stage)
{
SWSS_LOG_ENTER();
if (acl_stage == ACL_STAGE_UNKNOWN)
{
SWSS_LOG_ERROR("Unknown Acl stage for Acl table %lx", table_oid);
return false;
}
sai_status_t status;
sai_object_id_t groupOid;
Port p;
if (!getPort(id, p))
{
return false;
}
auto &port = m_portList.find(p.m_alias)->second;
if (acl_stage == ACL_STAGE_INGRESS && port.m_ingress_acl_table_group_id != 0)
{
groupOid = port.m_ingress_acl_table_group_id;
}
else if (acl_stage == ACL_STAGE_EGRESS && port.m_egress_acl_table_group_id != 0)
{
groupOid = port.m_egress_acl_table_group_id;
}
else if (acl_stage == ACL_STAGE_INGRESS or acl_stage == ACL_STAGE_EGRESS)
{
bool ingress = acl_stage == ACL_STAGE_INGRESS ? true : false;
// If port ACL table group does not exist, create one
Port p;
if (!getPort(id, p))
{
return false;
}
sai_acl_bind_point_type_t bind_type;
switch (p.m_type) {
case Port::PHY:
bind_type = SAI_ACL_BIND_POINT_TYPE_PORT;
break;
case Port::LAG:
bind_type = SAI_ACL_BIND_POINT_TYPE_LAG;
break;
case Port::VLAN:
bind_type = SAI_ACL_BIND_POINT_TYPE_VLAN;
break;
default:
SWSS_LOG_ERROR("Failed to bind ACL table to port %s with unknown type %d", p.m_alias.c_str(), p.m_type);
return false;
}
sai_object_id_t bp_list[] = { bind_type };
vector<sai_attribute_t> group_attrs;
sai_attribute_t group_attr;
group_attr.id = SAI_ACL_TABLE_GROUP_ATTR_ACL_STAGE;
group_attr.value.s32 = ingress ? SAI_ACL_STAGE_INGRESS : SAI_ACL_STAGE_EGRESS;
group_attrs.push_back(group_attr);
group_attr.id = SAI_ACL_TABLE_GROUP_ATTR_ACL_BIND_POINT_TYPE_LIST;
group_attr.value.objlist.count = 1;
group_attr.value.objlist.list = bp_list;
group_attrs.push_back(group_attr);
group_attr.id = SAI_ACL_TABLE_GROUP_ATTR_TYPE;
group_attr.value.s32 = SAI_ACL_TABLE_GROUP_TYPE_PARALLEL;
group_attrs.push_back(group_attr);
status = sai_acl_api->create_acl_table_group(&groupOid, gSwitchId, (uint32_t)group_attrs.size(), group_attrs.data());
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Failed to create ACL table group, rv:%d", status);
return false;
}
if (ingress)
{
port.m_ingress_acl_table_group_id = groupOid;
}
else
{
port.m_egress_acl_table_group_id = groupOid;
}
gCrmOrch->incCrmAclUsedCounter(CrmResourceType::CRM_ACL_GROUP, ingress ? SAI_ACL_STAGE_INGRESS : SAI_ACL_STAGE_EGRESS, SAI_ACL_BIND_POINT_TYPE_PORT);
switch (port.m_type)
{
case Port::PHY:
{
// Bind this ACL group to physical port
sai_attribute_t port_attr;
port_attr.id = ingress ? SAI_PORT_ATTR_INGRESS_ACL : SAI_PORT_ATTR_EGRESS_ACL;
port_attr.value.oid = groupOid;
status = sai_port_api->set_port_attribute(port.m_port_id, &port_attr);
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Failed to bind port %s to ACL table group %lx, rv:%d",
port.m_alias.c_str(), groupOid, status);
return status;
}
break;
}
case Port::LAG:
{
// Bind this ACL group to LAG
sai_attribute_t lag_attr;
lag_attr.id = ingress ? SAI_LAG_ATTR_INGRESS_ACL : SAI_LAG_ATTR_EGRESS_ACL;
lag_attr.value.oid = groupOid;
status = sai_lag_api->set_lag_attribute(port.m_lag_id, &lag_attr);
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Failed to bind LAG %s to ACL table group %lx, rv:%d",
port.m_alias.c_str(), groupOid, status);
return status;
}
break;
}
case Port::VLAN:
// Bind this ACL group to VLAN
sai_attribute_t vlan_attr;
vlan_attr.id = ingress ? SAI_VLAN_ATTR_INGRESS_ACL : SAI_VLAN_ATTR_EGRESS_ACL;
vlan_attr.value.oid = groupOid;
status = sai_vlan_api->set_vlan_attribute(port.m_vlan_info.vlan_oid, &vlan_attr);
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Failed to bind VLAN %s to ACL table group %lx, rv:%d",
port.m_alias.c_str(), groupOid, status);
return status;
}
break;
default:
SWSS_LOG_ERROR("Failed to bind %s port with type %d", port.m_alias.c_str(), port.m_type);
return SAI_STATUS_FAILURE;
}
SWSS_LOG_NOTICE("Create ACL table group and bind port %s to it", port.m_alias.c_str());
}
// Create an ACL group member with table_oid and groupOid
vector<sai_attribute_t> member_attrs;
sai_attribute_t member_attr;
member_attr.id = SAI_ACL_TABLE_GROUP_MEMBER_ATTR_ACL_TABLE_GROUP_ID;
member_attr.value.oid = groupOid;
member_attrs.push_back(member_attr);
member_attr.id = SAI_ACL_TABLE_GROUP_MEMBER_ATTR_ACL_TABLE_ID;
member_attr.value.oid = table_oid;
member_attrs.push_back(member_attr);
member_attr.id = SAI_ACL_TABLE_GROUP_MEMBER_ATTR_PRIORITY;
member_attr.value.u32 = 100; // TODO: double check!
member_attrs.push_back(member_attr);
status = sai_acl_api->create_acl_table_group_member(&group_member_oid, gSwitchId, (uint32_t)member_attrs.size(), member_attrs.data());
if (status != SAI_STATUS_SUCCESS) {
SWSS_LOG_ERROR("Failed to create member in ACL table group %lx for ACL table group %lx, rv:%d",
table_oid, groupOid, status);
return false;
}
return true;
}
bool PortsOrch::setPortPvid(Port &port, sai_uint32_t pvid)
{
SWSS_LOG_ENTER();
if (port.m_rif_id)
{
SWSS_LOG_ERROR("pvid setting for router interface is not allowed");
return false;
}
vector<Port> portv;
if (port.m_type == Port::PHY)
{
sai_attribute_t attr;
attr.id = SAI_PORT_ATTR_PORT_VLAN_ID;
attr.value.u32 = pvid;
sai_status_t status = sai_port_api->set_port_attribute(port.m_port_id, &attr);
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Failed to set pvid %u to port: %s", attr.value.u32, port.m_alias.c_str());
return false;
}
SWSS_LOG_NOTICE("Set pvid %u to port: %s", attr.value.u32, port.m_alias.c_str());
}
else if (port.m_type == Port::LAG)
{
sai_attribute_t attr;
attr.id = SAI_LAG_ATTR_PORT_VLAN_ID;
attr.value.u32 = pvid;
sai_status_t status = sai_lag_api->set_lag_attribute(port.m_lag_id, &attr);
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Failed to set pvid %u to lag: %s", attr.value.u32, port.m_alias.c_str());
return false;
}
SWSS_LOG_NOTICE("Set pvid %u to lag: %s", attr.value.u32, port.m_alias.c_str());
}
else
{
SWSS_LOG_ERROR("PortsOrch::setPortPvid port type %d not supported", port.m_type);
return false;
}
port.m_port_vlan_id = (sai_vlan_id_t)pvid;
return true;
}
bool PortsOrch::getPortPvid(Port &port, sai_uint32_t &pvid)
{
/* Just return false if the router interface exists */
if (port.m_rif_id)
{
SWSS_LOG_DEBUG("Router interface exists on %s, don't set pvid",
port.m_alias.c_str());
return false;
}
pvid = port.m_port_vlan_id;
return true;
}
bool PortsOrch::setHostIntfsStripTag(Port &port, sai_hostif_vlan_tag_t strip)
{
SWSS_LOG_ENTER();
vector<Port> portv;
/*
* Before SAI_HOSTIF_VLAN_TAG_ORIGINAL is supported by libsai from all asic vendors,
* the VLAN tag on hostif is explicitly controlled with SAI_HOSTIF_VLAN_TAG_STRIP &
* SAI_HOSTIF_VLAN_TAG_KEEP attributes.
*/
if (port.m_type == Port::PHY)
{
portv.push_back(port);
}
else if (port.m_type == Port::LAG)
{
getLagMember(port, portv);
}
else
{
SWSS_LOG_ERROR("port type %d not supported", port.m_type);
return false;
}
for (const auto p: portv)
{
sai_attribute_t attr;
attr.id = SAI_HOSTIF_ATTR_VLAN_TAG;
attr.value.s32 = strip;
sai_status_t status = sai_hostif_api->set_hostif_attribute(p.m_hif_id, &attr);
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Failed to set %s to host interface %s",
hostif_vlan_tag[strip], p.m_alias.c_str());
return false;
}
SWSS_LOG_NOTICE("Set %s to host interface: %s",
hostif_vlan_tag[strip], p.m_alias.c_str());
}
return true;
}
bool PortsOrch::isSpeedSupported(const std::string& alias, sai_object_id_t port_id, sai_uint32_t speed)
{
// This method will return false iff we get a list of supported speeds and the requested speed
// is not supported
// Otherwise the method will return true (even if we received errors)
sai_attribute_t attr;
sai_status_t status;
// "Lazy" query of supported speeds for given port
// Once received the list will be stored in m_portSupportedSpeeds
if (!m_portSupportedSpeeds.count(port_id))
{
const auto size_guess = 25; // Guess the size which could be enough
std::vector<sai_uint32_t> speeds(size_guess);
for (int attempt = 0; attempt < 2; ++attempt) // two attempts to get our value
{ // first with the guess,
// other with the returned value
attr.id = SAI_PORT_ATTR_SUPPORTED_SPEED;
attr.value.u32list.count = static_cast<uint32_t>(speeds.size());
attr.value.u32list.list = speeds.data();
status = sai_port_api->get_port_attribute(port_id, 1, &attr);
if (status != SAI_STATUS_BUFFER_OVERFLOW)
{
break;
}
speeds.resize(attr.value.u32list.count); // if our guess was wrong
// retry with the correct value
}
if (status == SAI_STATUS_SUCCESS)
{
speeds.resize(attr.value.u32list.count);
m_portSupportedSpeeds[port_id] = speeds;
}
else
{
if (status == SAI_STATUS_BUFFER_OVERFLOW)
{
// something went wrong in SAI implementation
SWSS_LOG_ERROR("Failed to get supported speed list for port %s id=%lx. Not enough container size",
alias.c_str(), port_id);
}
else if (SAI_STATUS_IS_ATTR_NOT_SUPPORTED(status) ||
SAI_STATUS_IS_ATTR_NOT_IMPLEMENTED(status) ||
status == SAI_STATUS_NOT_IMPLEMENTED)
{
// unable to validate speed if attribute is not supported on platform
// assuming input value is correct
SWSS_LOG_WARN("Unable to validate speed for port %s id=%lx. Not supported by platform",
alias.c_str(), port_id);
}
else
{
SWSS_LOG_ERROR("Failed to get a list of supported speeds for port %s id=%lx. Error=%d",
alias.c_str(), port_id, status);
}
m_portSupportedSpeeds[port_id] = {}; // use an empty list,
// we don't want to get the port speed for this port again
return true; // we can't check if the speed is valid, so return true to change the speed
}
}
const PortSupportedSpeeds &supp_speeds = m_portSupportedSpeeds[port_id];
if (supp_speeds.size() == 0)
{
// we don't have the list for this port, so return true to change speed anyway
return true;
}
return std::find(supp_speeds.begin(), supp_speeds.end(), speed) != supp_speeds.end();
}
bool PortsOrch::setPortSpeed(sai_object_id_t port_id, sai_uint32_t speed)
{
SWSS_LOG_ENTER();
sai_attribute_t attr;
sai_status_t status;
attr.id = SAI_PORT_ATTR_SPEED;
attr.value.u32 = speed;
status = sai_port_api->set_port_attribute(port_id, &attr);
return status == SAI_STATUS_SUCCESS;
}
bool PortsOrch::getPortSpeed(sai_object_id_t port_id, sai_uint32_t &speed)
{
SWSS_LOG_ENTER();
sai_attribute_t attr;
sai_status_t status;
attr.id = SAI_PORT_ATTR_SPEED;
attr.value.u32 = 0;
status = sai_port_api->get_port_attribute(port_id, 1, &attr);
if (status == SAI_STATUS_SUCCESS)
speed = attr.value.u32;
return status == SAI_STATUS_SUCCESS;
}
bool PortsOrch::setPortAdvSpeed(sai_object_id_t port_id, sai_uint32_t speed)
{
SWSS_LOG_ENTER();
sai_attribute_t attr;
sai_status_t status;
vector<sai_uint32_t> speeds;
speeds.push_back(speed);
attr.id = SAI_PORT_ATTR_ADVERTISED_SPEED;
attr.value.u32list.list = speeds.data();
attr.value.u32list.count = static_cast<uint32_t>(speeds.size());
status = sai_port_api->set_port_attribute(port_id, &attr);
return status == SAI_STATUS_SUCCESS;
}
bool PortsOrch::getQueueType(sai_object_id_t queue_id, string &type)
{
SWSS_LOG_ENTER();
sai_attribute_t attr;
attr.id = SAI_QUEUE_ATTR_TYPE;
sai_status_t status = sai_queue_api->get_queue_attribute(queue_id, 1, &attr);
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Failed to get queue type for queue %lu rv:%d", queue_id, status);
return false;
}
switch (attr.value.s32)
{
case SAI_QUEUE_TYPE_ALL:
type = "SAI_QUEUE_TYPE_ALL";
break;
case SAI_QUEUE_TYPE_UNICAST:
type = "SAI_QUEUE_TYPE_UNICAST";
break;
case SAI_QUEUE_TYPE_MULTICAST:
type = "SAI_QUEUE_TYPE_MULTICAST";
break;
default:
SWSS_LOG_ERROR("Got unsupported queue type %d for %lu queue", attr.value.s32, queue_id);
throw runtime_error("Got unsupported queue type");
}
return true;
}
bool PortsOrch::setPortAutoNeg(sai_object_id_t id, int an)
{
SWSS_LOG_ENTER();
sai_attribute_t attr;
attr.id = SAI_PORT_ATTR_AUTO_NEG_MODE;
switch(an) {
case 1:
attr.value.booldata = true;
break;
default:
attr.value.booldata = false;
break;
}
sai_status_t status = sai_port_api->set_port_attribute(id, &attr);
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Failed to set AutoNeg %u to port pid:%lx", attr.value.booldata, id);
return false;
}
SWSS_LOG_INFO("Set AutoNeg %u to port pid:%lx", attr.value.booldata, id);
return true;
}
bool PortsOrch::setHostIntfsOperStatus(sai_object_id_t port_id, bool up)
{
SWSS_LOG_ENTER();
for (auto it = m_portList.begin(); it != m_portList.end(); it++)
{
if (it->second.m_port_id != port_id)
{
continue;
}
sai_attribute_t attr;
attr.id = SAI_HOSTIF_ATTR_OPER_STATUS;
attr.value.booldata = up;
sai_status_t status = sai_hostif_api->set_hostif_attribute(it->second.m_hif_id, &attr);
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_WARN("Failed to set operation status %s to host interface %s",
up ? "UP" : "DOWN", it->second.m_alias.c_str());
return false;
}
SWSS_LOG_NOTICE("Set operation status %s to host interface %s",
up ? "UP" : "DOWN", it->second.m_alias.c_str());
if (gNeighOrch->ifChangeInformNextHop(it->second.m_alias, up) == false)
{
SWSS_LOG_WARN("Inform nexthop operation failed for interface %s",
it->second.m_alias.c_str());
}
return true;
}
return false;
}
void PortsOrch::updateDbPortOperStatus(sai_object_id_t id, sai_port_oper_status_t status)
{
SWSS_LOG_ENTER();
for (auto it = m_portList.begin(); it != m_portList.end(); it++)
{
if (it->second.m_port_id == id)
{
vector<FieldValueTuple> tuples;
FieldValueTuple tuple("oper_status", oper_status_strings.at(status));
tuples.push_back(tuple);
m_portTable->set(it->first, tuples);
}
}
}
bool PortsOrch::addPort(const set<int> &lane_set, uint32_t speed, int an, string fec_mode)
{
SWSS_LOG_ENTER();
vector<uint32_t> lanes(lane_set.begin(), lane_set.end());
sai_attribute_t attr;
vector<sai_attribute_t> attrs;
attr.id = SAI_PORT_ATTR_SPEED;
attr.value.u32 = speed;
attrs.push_back(attr);
attr.id = SAI_PORT_ATTR_HW_LANE_LIST;
attr.value.u32list.list = lanes.data();
attr.value.u32list.count = static_cast<uint32_t>(lanes.size());
attrs.push_back(attr);
if (an == true)
{
attr.id = SAI_PORT_ATTR_AUTO_NEG_MODE;
attr.value.booldata = true;
attrs.push_back(attr);
}
if (!fec_mode.empty())
{
attr.id = SAI_PORT_ATTR_FEC_MODE;
attr.value.u32 = fec_mode_map[fec_mode];
attrs.push_back(attr);
}
sai_object_id_t port_id;
sai_status_t status = sai_port_api->create_port(&port_id, gSwitchId, static_cast<uint32_t>(attrs.size()), attrs.data());
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Failed to create port with the speed %u, rv:%d", speed, status);
return false;
}
m_portListLaneMap[lane_set] = port_id;
SWSS_LOG_NOTICE("Create port %lx with the speed %u", port_id, speed);
return true;
}
bool PortsOrch::removePort(sai_object_id_t port_id)
{
SWSS_LOG_ENTER();
Port p;
if (getPort(port_id, p))
{
PortUpdate update = {p, false };
notify(SUBJECT_TYPE_PORT_CHANGE, static_cast<void *>(&update));
}
sai_status_t status = sai_port_api->remove_port(port_id);
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Failed to remove port %lx, rv:%d", port_id, status);
return false;
}
SWSS_LOG_NOTICE("Remove port %lx", port_id);
return true;
}
string PortsOrch::getPortFlexCounterTableKey(string key)
{
return string(PORT_STAT_COUNTER_FLEX_COUNTER_GROUP) + ":" + key;
}
string PortsOrch::getQueueFlexCounterTableKey(string key)
{
return string(QUEUE_STAT_COUNTER_FLEX_COUNTER_GROUP) + ":" + key;
}
bool PortsOrch::initPort(const string &alias, const set<int> &lane_set)
{
SWSS_LOG_ENTER();
/* Determine if the lane combination exists in switch */
if (m_portListLaneMap.find(lane_set) != m_portListLaneMap.end())
{
sai_object_id_t id = m_portListLaneMap[lane_set];
/* Determine if the port has already been initialized before */
if (m_portList.find(alias) != m_portList.end() && m_portList[alias].m_port_id == id)
{
SWSS_LOG_INFO("Port has already been initialized before alias:%s", alias.c_str());
}
else
{
Port p(alias, Port::PHY);
p.m_index = static_cast<int32_t>(m_portList.size()); // TODO: Assume no deletion of physical port
p.m_port_id = id;
/* Initialize the port and create corresponding host interface */
if (initializePort(p))
{
/* Add port to port list */
m_portList[alias] = p;
/* Add port name map to counter table */
FieldValueTuple tuple(p.m_alias, sai_serialize_object_id(p.m_port_id));
vector<FieldValueTuple> fields;
fields.push_back(tuple);
m_counterTable->set("", fields);
/* Add port to flex_counter for updating stat counters */
string key = getPortFlexCounterTableKey(sai_serialize_object_id(p.m_port_id));
std::string delimiter = "";
std::ostringstream counters_stream;
for (const auto &id: portStatIds)
{
counters_stream << delimiter << sai_serialize_port_stat(id);
delimiter = ",";
}
fields.clear();
fields.emplace_back(PORT_COUNTER_ID_LIST, counters_stream.str());
m_flexCounterTable->set(key, fields);
PortUpdate update = {p, true };
notify(SUBJECT_TYPE_PORT_CHANGE, static_cast<void *>(&update));
SWSS_LOG_NOTICE("Initialized port %s", alias.c_str());
}
else
{
SWSS_LOG_ERROR("Failed to initialize port %s", alias.c_str());
return false;
}
}
}
else
{
SWSS_LOG_ERROR("Failed to locate port lane combination alias:%s", alias.c_str());
return false;
}
return true;
}
void PortsOrch::doPortTask(Consumer &consumer)
{
SWSS_LOG_ENTER();
auto it = consumer.m_toSync.begin();
while (it != consumer.m_toSync.end())
{
auto &t = it->second;
string alias = kfvKey(t);
string op = kfvOp(t);
if (alias == "PortConfigDone")
{
m_portConfigDone = true;
for (auto i : kfvFieldsValues(t))
{
if (fvField(i) == "count")
{
m_portCount = to_uint<uint32_t>(fvValue(i));
}
}
}
/* Get notification from application */
/* portsyncd application:
* When portsorch receives 'PortInitDone' message, it indicates port initialization
* procedure is done. Before port initialization procedure, none of other tasks
* are executed.
*/
if (alias == "PortInitDone")
{
/* portsyncd restarting case:
* When portsyncd restarts, duplicate notifications may be received.
*/
if (!m_initDone)
{
m_initDone = true;
SWSS_LOG_INFO("Get PortInitDone notification from portsyncd.");
}
it = consumer.m_toSync.erase(it);
return;
}
if (op == "SET")
{
set<int> lane_set;
string admin_status;
string fec_mode;
uint32_t mtu = 0;
uint32_t speed = 0;
int an = -1;
for (auto i : kfvFieldsValues(t))
{
/* Get lane information of a physical port and initialize the port */
if (fvField(i) == "lanes")
{
string lane_str;
istringstream iss(fvValue(i));
while (getline(iss, lane_str, ','))
{
int lane = stoi(lane_str);
lane_set.insert(lane);
}
}
/* Set port admin status */
if (fvField(i) == "admin_status")
admin_status = fvValue(i);
/* Set port MTU */
if (fvField(i) == "mtu")
mtu = (uint32_t)stoul(fvValue(i));
/* Set port speed */
if (fvField(i) == "speed")
{
speed = (uint32_t)stoul(fvValue(i));
}
/* Set port fec */
if (fvField(i) == "fec")
fec_mode = fvValue(i);
/* Set autoneg and ignore the port speed setting */
if (fvField(i) == "autoneg")
{
an = (int)stoul(fvValue(i));
}
}
/* Collect information about all received ports */
if (lane_set.size())
{
m_lanesAliasSpeedMap[lane_set] = make_tuple(alias, speed, an, fec_mode);
}
/* Once all ports received, go through the each port and perform appropriate actions:
* 1. Remove ports which don't exist anymore
* 2. Create new ports
* 3. Initialize all ports
*/
if (m_portConfigDone && (m_lanesAliasSpeedMap.size() == m_portCount))
{
for (auto it = m_portListLaneMap.begin(); it != m_portListLaneMap.end();)
{
if (m_lanesAliasSpeedMap.find(it->first) == m_lanesAliasSpeedMap.end())
{
char *platform = getenv("platform");
if (platform && (strstr(platform, BFN_PLATFORM_SUBSTRING) || strstr(platform, MLNX_PLATFORM_SUBSTRING)))
{
if (!removePort(it->second))
{
throw runtime_error("PortsOrch initialization failure.");
}
}
else
{
SWSS_LOG_NOTICE("Failed to remove Port %lx due to missing SAI remove_port API.", it->second);
}
it = m_portListLaneMap.erase(it);
}
else
{
it++;
}
}
for (auto it = m_lanesAliasSpeedMap.begin(); it != m_lanesAliasSpeedMap.end();)
{
bool port_created = false;
if (m_portListLaneMap.find(it->first) == m_portListLaneMap.end())
{
// work around to avoid syncd termination on SAI error due missing create_port SAI API
// can be removed when SAI redis return NotImplemented error
char *platform = getenv("platform");
if (platform && (strstr(platform, BFN_PLATFORM_SUBSTRING) || strstr(platform, MLNX_PLATFORM_SUBSTRING)))
{
if (!addPort(it->first, get<1>(it->second), get<2>(it->second), get<3>(it->second)))
{
throw runtime_error("PortsOrch initialization failure.");
}
port_created = true;
}
else
{
SWSS_LOG_NOTICE("Failed to create Port %s due to missing SAI create_port API.", get<0>(it->second).c_str());
}
}
else
{
port_created = true;
}
if (port_created)
{
if (!initPort(get<0>(it->second), it->first))
{
throw runtime_error("PortsOrch initialization failure.");
}
}
it = m_lanesAliasSpeedMap.erase(it);
}
}
if (!m_portConfigDone)
{
it = consumer.m_toSync.erase(it);
continue;
}
if (alias != "PortConfigDone" && !gBufferOrch->isPortReady(alias))
{
// buffer configuration hasn't been applied yet. save it for future retry
it++;
continue;
}
Port p;
if (!getPort(alias, p) && alias != "PortConfigDone")
{
SWSS_LOG_ERROR("Failed to get port id by alias:%s", alias.c_str());
}
else
{
if (an != -1 && an != p.m_autoneg)
{
if (setPortAutoNeg(p.m_port_id, an))
{
SWSS_LOG_NOTICE("Set port %s AutoNeg to %u", alias.c_str(), an);
p.m_autoneg = an;
m_portList[alias] = p;
/* Once AN is changed, need to reset the port speed or
port adv speed accordingly */
if (speed == 0 && p.m_speed != 0)
{
speed = p.m_speed;
}
}
else
{
SWSS_LOG_ERROR("Failed to set port %s AN to %u", alias.c_str(), an);
it++;
continue;
}
}
/*
* When AN is enabled, set the port adv speed, otherwise change the port speed.
*
* 1. Get supported speed list and validate if the target speed is within the list
* 2. Get the current port speed and check if it is the same as the target speed
* 3. Set port admin status to DOWN before changing the speed
* 4. Set port speed
*/
if (speed != 0)
{
p.m_speed = speed;
m_portList[alias] = p;
if (p.m_autoneg)
{
if (setPortAdvSpeed(p.m_port_id, speed))
{
SWSS_LOG_NOTICE("Set port %s advertised speed to %u", alias.c_str(), speed);
}
else
{
SWSS_LOG_ERROR("Failed to set port %s advertised speed to %u", alias.c_str(), speed);
it++;
continue;
}
}
else
{
sai_uint32_t current_speed;
if (!isSpeedSupported(alias, p.m_port_id, speed))
{
it++;
continue;
}
if (getPortSpeed(p.m_port_id, current_speed))
{
if (speed != current_speed)
{
if (setPortAdminStatus(p.m_port_id, false))
{
if (setPortSpeed(p.m_port_id, speed))
{
SWSS_LOG_NOTICE("Set port %s speed to %u", alias.c_str(), speed);
}
else
{
SWSS_LOG_ERROR("Failed to set port %s speed to %u", alias.c_str(), speed);
it++;
continue;
}
}
else
{
SWSS_LOG_ERROR("Failed to set port admin status DOWN to set speed");
}
}
}
else
{
SWSS_LOG_ERROR("Failed to get current speed for port %s", alias.c_str());
}
}
}
if (mtu != 0)
{
if (setPortMtu(p.m_port_id, mtu))
{
p.m_mtu = mtu;
m_portList[alias] = p;
SWSS_LOG_NOTICE("Set port %s MTU to %u", alias.c_str(), mtu);
}
else
{
SWSS_LOG_ERROR("Failed to set port %s MTU to %u", alias.c_str(), mtu);
it++;
continue;
}
}
if (!admin_status.empty())
{
if (setPortAdminStatus(p.m_port_id, admin_status == "up"))
{
SWSS_LOG_NOTICE("Set port %s admin status to %s", alias.c_str(), admin_status.c_str());
}
else
{
SWSS_LOG_ERROR("Failed to set port %s admin status to %s", alias.c_str(), admin_status.c_str());
it++;
continue;
}
}
if (!fec_mode.empty())
{
if (fec_mode_map.find(fec_mode) != fec_mode_map.end())
{
/* reset fec mode upon mode change */
if (p.m_fec_mode != fec_mode_map[fec_mode])
{
p.m_fec_mode = fec_mode_map[fec_mode];
if (setPortFec(p.m_port_id, p.m_fec_mode))
{
m_portList[alias] = p;
SWSS_LOG_NOTICE("Set port %s fec to %s", alias.c_str(), fec_mode.c_str());
}
else
{
SWSS_LOG_ERROR("Failed to set port %s fec to %s", alias.c_str(), fec_mode.c_str());
it++;
continue;
}
}
}
else
{
SWSS_LOG_ERROR("Unknown fec mode %s", fec_mode.c_str());
}
}
}
}
else
{
SWSS_LOG_ERROR("Unknown operation type %s", op.c_str());
}
it = consumer.m_toSync.erase(it);
}
}
void PortsOrch::doVlanTask(Consumer &consumer)
{
SWSS_LOG_ENTER();
auto it = consumer.m_toSync.begin();
while (it != consumer.m_toSync.end())
{
auto &t = it->second;
string key = kfvKey(t);
/* Ensure the key starts with "Vlan" otherwise ignore */
if (strncmp(key.c_str(), VLAN_PREFIX, 4))
{
SWSS_LOG_ERROR("Invalid key format. No 'Vlan' prefix: %s", key.c_str());
it = consumer.m_toSync.erase(it);
continue;
}
int vlan_id;
vlan_id = stoi(key.substr(4)); // FIXME: might raise exception
string vlan_alias, port_alias;
vlan_alias = VLAN_PREFIX + to_string(vlan_id);
string op = kfvOp(t);
if (op == SET_COMMAND)
{
/*
* Only creation is supported for now.
* We may add support for VLAN mac learning enable/disable,
* VLAN flooding control setting and etc. in the future.
*/
if (m_portList.find(vlan_alias) == m_portList.end())
{
if (!addVlan(vlan_alias))
{
it++;
continue;
}
}
it = consumer.m_toSync.erase(it);
}
else if (op == DEL_COMMAND)
{
Port vlan;
getPort(vlan_alias, vlan);
if (removeVlan(vlan))
it = consumer.m_toSync.erase(it);
else
it++;
}
else
{
SWSS_LOG_ERROR("Unknown operation type %s", op.c_str());
it = consumer.m_toSync.erase(it);
}
}
}
void PortsOrch::doVlanMemberTask(Consumer &consumer)
{
SWSS_LOG_ENTER();
auto it = consumer.m_toSync.begin();
while (it != consumer.m_toSync.end())
{
auto &t = it->second;
string key = kfvKey(t);
/* Ensure the key starts with "Vlan" otherwise ignore */
if (strncmp(key.c_str(), VLAN_PREFIX, 4))
{
SWSS_LOG_ERROR("Invalid key format. No 'Vlan' prefix: %s", key.c_str());
it = consumer.m_toSync.erase(it);
continue;
}
key = key.substr(4);
size_t found = key.find(':');
int vlan_id;
string vlan_alias, port_alias;
if (found != string::npos)
{
vlan_id = stoi(key.substr(0, found)); // FIXME: might raise exception
port_alias = key.substr(found+1);
}
else
{
SWSS_LOG_ERROR("Invalid key format. No member port is presented: %s",
kfvKey(t).c_str());
it = consumer.m_toSync.erase(it);
continue;
}
vlan_alias = VLAN_PREFIX + to_string(vlan_id);
string op = kfvOp(t);
assert(m_portList.find(vlan_alias) != m_portList.end());
Port vlan, port;
/* When VLAN member is to be created before VLAN is created */
if (!getPort(vlan_alias, vlan))
{
SWSS_LOG_INFO("Failed to locate VLAN %s", vlan_alias.c_str());
it++;
continue;
}
if (!getPort(port_alias, port))
{
SWSS_LOG_ERROR("Failed to locate port %s", port_alias.c_str());
it = consumer.m_toSync.erase(it);
continue;
}
if (op == SET_COMMAND)
{
string tagging_mode = "untagged";
for (auto i : kfvFieldsValues(t))
{
if (fvField(i) == "tagging_mode")
tagging_mode = fvValue(i);
}
if (tagging_mode != "untagged" &&
tagging_mode != "tagged" &&
tagging_mode != "priority_tagged")
{
SWSS_LOG_ERROR("Wrong tagging_mode '%s' for key: %s", tagging_mode.c_str(), kfvKey(t).c_str());
it = consumer.m_toSync.erase(it);
continue;
}
/* Duplicate entry */
if (vlan.m_members.find(port_alias) != vlan.m_members.end())
{
it = consumer.m_toSync.erase(it);
continue;
}
if (addBridgePort(port) && addVlanMember(vlan, port, tagging_mode))
it = consumer.m_toSync.erase(it);
else
it++;
}
else if (op == DEL_COMMAND)
{
if (vlan.m_members.find(port_alias) != vlan.m_members.end())
{
if (removeVlanMember(vlan, port))
{
if (port.m_vlan_members.empty())
{
removeBridgePort(port);
}
it = consumer.m_toSync.erase(it);
}
else
{
it++;
}
}
else
/* Cannot locate the VLAN */
it = consumer.m_toSync.erase(it);
}
else
{
SWSS_LOG_ERROR("Unknown operation type %s", op.c_str());
it = consumer.m_toSync.erase(it);
}
}
}
void PortsOrch::doLagTask(Consumer &consumer)
{
SWSS_LOG_ENTER();
auto it = consumer.m_toSync.begin();
while (it != consumer.m_toSync.end())
{
auto &t = it->second;
string lag_alias = kfvKey(t);
string op = kfvOp(t);
if (op == SET_COMMAND)
{
/* Duplicate entry */
if (m_portList.find(lag_alias) != m_portList.end())
{
it = consumer.m_toSync.erase(it);
continue;
}
if (addLag(lag_alias))
it = consumer.m_toSync.erase(it);
else
it++;
}
else if (op == DEL_COMMAND)
{
Port lag;
/* Cannot locate LAG */
if (!getPort(lag_alias, lag))
{
it = consumer.m_toSync.erase(it);
continue;
}
if (removeLag(lag))
it = consumer.m_toSync.erase(it);
else
it++;
}
else
{
SWSS_LOG_ERROR("Unknown operation type %s", op.c_str());
it = consumer.m_toSync.erase(it);
}
}
}
void PortsOrch::doLagMemberTask(Consumer &consumer)
{
SWSS_LOG_ENTER();
auto it = consumer.m_toSync.begin();
while (it != consumer.m_toSync.end())
{
auto &t = it->second;
/* Retrieve LAG alias and LAG member alias from key */
string key = kfvKey(t);
size_t found = key.find(':');
/* Return if the format of key is wrong */
if (found == string::npos)
{
SWSS_LOG_ERROR("Failed to parse %s", key.c_str());
return;
}
string lag_alias = key.substr(0, found);
string port_alias = key.substr(found+1);
string op = kfvOp(t);
Port lag, port;
if (!getPort(lag_alias, lag))
{
SWSS_LOG_INFO("Failed to locate LAG %s", lag_alias.c_str());
it++;
continue;
}
if (!getPort(port_alias, port))
{
SWSS_LOG_ERROR("Failed to locate port %s", port_alias.c_str());
it = consumer.m_toSync.erase(it);
continue;
}
/* Update a LAG member */
if (op == SET_COMMAND)
{
string status;
for (auto i : kfvFieldsValues(t))
{
if (fvField(i) == "status")
status = fvValue(i);
}
/* Sync an enabled member */
if (status == "enabled")
{
/* Duplicate entry */
if (lag.m_members.find(port_alias) != lag.m_members.end())
{
it = consumer.m_toSync.erase(it);
continue;
}
/* Assert the port doesn't belong to any LAG */
assert(!port.m_lag_id && !port.m_lag_member_id);
if (addLagMember(lag, port))
it = consumer.m_toSync.erase(it);
else
it++;
}
/* Sync an disabled member */
else /* status == "disabled" */
{
/* "status" is "disabled" at start when m_lag_id and
* m_lag_member_id are absent */
if (!port.m_lag_id || !port.m_lag_member_id)
{
it = consumer.m_toSync.erase(it);
continue;
}
if (removeLagMember(lag, port))
it = consumer.m_toSync.erase(it);
else
it++;
}
}
/* Remove a LAG member */
else if (op == DEL_COMMAND)
{
/* Assert the LAG member exists */
assert(lag.m_members.find(port_alias) != lag.m_members.end());
if (!port.m_lag_id || !port.m_lag_member_id)
{
SWSS_LOG_WARN("Member %s not found in LAG %s lid:%lx lmid:%lx,",
port.m_alias.c_str(), lag.m_alias.c_str(), lag.m_lag_id, port.m_lag_member_id);
it = consumer.m_toSync.erase(it);
continue;
}
if (removeLagMember(lag, port))
it = consumer.m_toSync.erase(it);
else
it++;
}
else
{
SWSS_LOG_ERROR("Unknown operation type %s", op.c_str());
it = consumer.m_toSync.erase(it);
}
}
}
void PortsOrch::doTask(Consumer &consumer)
{
SWSS_LOG_ENTER();
string table_name = consumer.getTableName();
if (table_name == APP_PORT_TABLE_NAME)
{
doPortTask(consumer);
}
else
{
/* Wait for all ports to be initialized */
if (!isInitDone())
{
return;
}
if (table_name == APP_VLAN_TABLE_NAME)
{
doVlanTask(consumer);
}
else if (table_name == APP_VLAN_MEMBER_TABLE_NAME)
{
doVlanMemberTask(consumer);
}
else if (table_name == APP_LAG_TABLE_NAME)
{
doLagTask(consumer);
}
else if (table_name == APP_LAG_MEMBER_TABLE_NAME)
{
doLagMemberTask(consumer);
}
}
}
void PortsOrch::initializeQueues(Port &port)
{
SWSS_LOG_ENTER();
sai_attribute_t attr;
attr.id = SAI_PORT_ATTR_QOS_NUMBER_OF_QUEUES;
sai_status_t status = sai_port_api->get_port_attribute(port.m_port_id, 1, &attr);
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Failed to get number of queues for port %s rv:%d", port.m_alias.c_str(), status);
throw runtime_error("PortsOrch initialization failure.");
}
SWSS_LOG_INFO("Get %d queues for port %s", attr.value.u32, port.m_alias.c_str());
port.m_queue_ids.resize(attr.value.u32);
if (attr.value.u32 == 0)
{
return;
}
attr.id = SAI_PORT_ATTR_QOS_QUEUE_LIST;
attr.value.objlist.count = (uint32_t)port.m_queue_ids.size();
attr.value.objlist.list = port.m_queue_ids.data();
status = sai_port_api->get_port_attribute(port.m_port_id, 1, &attr);
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Failed to get queue list for port %s rv:%d", port.m_alias.c_str(), status);
throw runtime_error("PortsOrch initialization failure.");
}
SWSS_LOG_INFO("Get queues for port %s", port.m_alias.c_str());
}
void PortsOrch::initializePriorityGroups(Port &port)
{
SWSS_LOG_ENTER();
sai_attribute_t attr;
attr.id = SAI_PORT_ATTR_NUMBER_OF_INGRESS_PRIORITY_GROUPS;
sai_status_t status = sai_port_api->get_port_attribute(port.m_port_id, 1, &attr);
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Failed to get number of priority groups for port %s rv:%d", port.m_alias.c_str(), status);
throw runtime_error("PortsOrch initialization failure.");
}
SWSS_LOG_INFO("Get %d priority groups for port %s", attr.value.u32, port.m_alias.c_str());
port.m_priority_group_ids.resize(attr.value.u32);
if (attr.value.u32 == 0)
{
return;
}
attr.id = SAI_PORT_ATTR_INGRESS_PRIORITY_GROUP_LIST;
attr.value.objlist.count = (uint32_t)port.m_priority_group_ids.size();
attr.value.objlist.list = port.m_priority_group_ids.data();
status = sai_port_api->get_port_attribute(port.m_port_id, 1, &attr);
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Fail to get priority group list for port %s rv:%d", port.m_alias.c_str(), status);
throw runtime_error("PortsOrch initialization failure.");
}
SWSS_LOG_INFO("Get priority groups for port %s", port.m_alias.c_str());
}
bool PortsOrch::initializePort(Port &p)
{
SWSS_LOG_ENTER();
SWSS_LOG_NOTICE("Initializing port alias:%s pid:%lx", p.m_alias.c_str(), p.m_port_id);
initializePriorityGroups(p);
initializeQueues(p);
/* Create host interface */
addHostIntfs(p, p.m_alias, p.m_hif_id);
#if 0
// TODO: Assure if_nametoindex(p.m_alias.c_str()) != 0
p.m_ifindex = if_nametoindex(p.m_alias.c_str());
if (p.m_ifindex == 0)
{
SWSS_LOG_ERROR("Failed to get netdev index alias:%s", p.m_alias.c_str());
return false;
}
#endif
/* Set default port admin status to DOWN */
/* FIXME: Do we need this? The default port admin status is false */
setPortAdminStatus(p.m_port_id, false);
/**
* Create default database port oper status as DOWN
* This status will be updated when receiving port_oper_status_notification.
*/
vector<FieldValueTuple> vector;
FieldValueTuple tuple("oper_status", "down");
vector.push_back(tuple);
m_portTable->set(p.m_alias, vector);
return true;
}
bool PortsOrch::addHostIntfs(Port &port, string alias, sai_object_id_t &host_intfs_id)
{
SWSS_LOG_ENTER();
sai_attribute_t attr;
vector<sai_attribute_t> attrs;
attr.id = SAI_HOSTIF_ATTR_TYPE;
attr.value.s32 = SAI_HOSTIF_TYPE_NETDEV;
attrs.push_back(attr);
attr.id = SAI_HOSTIF_ATTR_OBJ_ID;
attr.value.oid = port.m_port_id;
attrs.push_back(attr);
attr.id = SAI_HOSTIF_ATTR_NAME;
strncpy((char *)&attr.value.chardata, alias.c_str(), SAI_HOSTIF_NAME_SIZE);
attrs.push_back(attr);
sai_status_t status = sai_hostif_api->create_hostif(&host_intfs_id, gSwitchId, (uint32_t)attrs.size(), attrs.data());
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Failed to create host interface for port %s", alias.c_str());
return false;
}
SWSS_LOG_NOTICE("Create host interface for port %s", alias.c_str());
return true;
}
bool PortsOrch::addBridgePort(Port &port)
{
SWSS_LOG_ENTER();
if (port.m_bridge_port_id != SAI_NULL_OBJECT_ID)
{
return true;
}
sai_attribute_t attr;
vector<sai_attribute_t> attrs;
attr.id = SAI_BRIDGE_PORT_ATTR_TYPE;
attr.value.s32 = SAI_BRIDGE_PORT_TYPE_PORT;
attrs.push_back(attr);
attr.id = SAI_BRIDGE_PORT_ATTR_PORT_ID;
if (port.m_type == Port::PHY)
{
attr.value.oid = port.m_port_id;
}
else if (port.m_type == Port::LAG)
{
attr.value.oid = port.m_lag_id;
}
else
{
SWSS_LOG_ERROR("Failed to add bridge port %s to default 1Q bridge, invalid porty type %d",
port.m_alias.c_str(), port.m_type);
return false;
}
attrs.push_back(attr);
/* Create a bridge port with admin status set to UP */
attr.id = SAI_BRIDGE_PORT_ATTR_ADMIN_STATE;
attr.value.booldata = true;
attrs.push_back(attr);
sai_status_t status = sai_bridge_api->create_bridge_port(&port.m_bridge_port_id, gSwitchId, (uint32_t)attrs.size(), attrs.data());
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Failed to add bridge port %s to default 1Q bridge, rv:%d",
port.m_alias.c_str(), status);
return false;
}
if (!setHostIntfsStripTag(port, SAI_HOSTIF_VLAN_TAG_KEEP))
{
SWSS_LOG_ERROR("Failed to set %s for hostif of port %s",
hostif_vlan_tag[SAI_HOSTIF_VLAN_TAG_KEEP], port.m_alias.c_str());
return false;
}
m_portList[port.m_alias] = port;
SWSS_LOG_NOTICE("Add bridge port %s to default 1Q bridge", port.m_alias.c_str());
return true;
}
bool PortsOrch::removeBridgePort(Port &port)
{
SWSS_LOG_ENTER();
if (port.m_bridge_port_id == SAI_NULL_OBJECT_ID)
{
return true;
}
/* Set bridge port admin status to DOWN */
sai_attribute_t attr;
attr.id = SAI_BRIDGE_PORT_ATTR_ADMIN_STATE;
attr.value.booldata = false;
sai_status_t status = sai_bridge_api->set_bridge_port_attribute(port.m_bridge_port_id, &attr);
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Failed to set bridge port %s admin status to DOWN, rv:%d",
port.m_alias.c_str(), status);
return false;
}
if (!setHostIntfsStripTag(port, SAI_HOSTIF_VLAN_TAG_STRIP))
{
SWSS_LOG_ERROR("Failed to set %s for hostif of port %s",
hostif_vlan_tag[SAI_HOSTIF_VLAN_TAG_STRIP], port.m_alias.c_str());
return false;
}
/* Flush FDB entries pointing to this bridge port */
// TODO: Remove all FDB entries associated with this bridge port before
// removing the bridge port itself
/* Remove bridge port */
status = sai_bridge_api->remove_bridge_port(port.m_bridge_port_id);
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Failed to remove bridge port %s from default 1Q bridge, rv:%d",
port.m_alias.c_str(), status);
return false;
}
port.m_bridge_port_id = SAI_NULL_OBJECT_ID;
SWSS_LOG_NOTICE("Remove bridge port %s from default 1Q bridge", port.m_alias.c_str());
m_portList[port.m_alias] = port;
return true;
}
bool PortsOrch::addVlan(string vlan_alias)
{
SWSS_LOG_ENTER();
sai_object_id_t vlan_oid;
sai_vlan_id_t vlan_id = (uint16_t)stoi(vlan_alias.substr(4));
sai_attribute_t attr;
attr.id = SAI_VLAN_ATTR_VLAN_ID;
attr.value.u16 = vlan_id;
sai_status_t status = sai_vlan_api->create_vlan(&vlan_oid, gSwitchId, 1, &attr);
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Failed to create VLAN %s vid:%hu", vlan_alias.c_str(), vlan_id);
return false;
}
SWSS_LOG_NOTICE("Create an empty VLAN %s vid:%hu", vlan_alias.c_str(), vlan_id);
Port vlan(vlan_alias, Port::VLAN);
vlan.m_vlan_info.vlan_oid = vlan_oid;
vlan.m_vlan_info.vlan_id = vlan_id;
vlan.m_members = set<string>();
m_portList[vlan_alias] = vlan;
return true;
}
bool PortsOrch::removeVlan(Port vlan)
{
SWSS_LOG_ENTER();
/* Vlan removing is not allowed when the VLAN still has members */
if (vlan.m_members.size() > 0)
{
SWSS_LOG_ERROR("Failed to remove non-empty VLAN %s", vlan.m_alias.c_str());
return false;
}
sai_status_t status = sai_vlan_api->remove_vlan(vlan.m_vlan_info.vlan_oid);
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Failed to remove VLAN %s vid:%hu",
vlan.m_alias.c_str(), vlan.m_vlan_info.vlan_id);
return false;
}
SWSS_LOG_NOTICE("Remove VLAN %s vid:%hu", vlan.m_alias.c_str(),
vlan.m_vlan_info.vlan_id);
m_portList.erase(vlan.m_alias);
return true;
}
bool PortsOrch::getVlanByVlanId(sai_vlan_id_t vlan_id, Port &vlan)
{
SWSS_LOG_ENTER();
for (auto &it: m_portList)
{
if (it.second.m_type == Port::VLAN && it.second.m_vlan_info.vlan_id == vlan_id)
{
vlan = it.second;
return true;
}
}
return false;
}
bool PortsOrch::addVlanMember(Port &vlan, Port &port, string &tagging_mode)
{
SWSS_LOG_ENTER();
sai_attribute_t attr;
vector<sai_attribute_t> attrs;
attr.id = SAI_VLAN_MEMBER_ATTR_VLAN_ID;
attr.value.oid = vlan.m_vlan_info.vlan_oid;
attrs.push_back(attr);
attr.id = SAI_VLAN_MEMBER_ATTR_BRIDGE_PORT_ID;
attr.value.oid = port.m_bridge_port_id;
attrs.push_back(attr);
sai_vlan_tagging_mode_t sai_tagging_mode = SAI_VLAN_TAGGING_MODE_TAGGED;
attr.id = SAI_VLAN_MEMBER_ATTR_VLAN_TAGGING_MODE;
if (tagging_mode == "untagged")
sai_tagging_mode = SAI_VLAN_TAGGING_MODE_UNTAGGED;
else if (tagging_mode == "tagged")
sai_tagging_mode = SAI_VLAN_TAGGING_MODE_TAGGED;
else if (tagging_mode == "priority_tagged")
sai_tagging_mode = SAI_VLAN_TAGGING_MODE_PRIORITY_TAGGED;
else assert(false);
attr.value.s32 = sai_tagging_mode;
attrs.push_back(attr);
sai_object_id_t vlan_member_id;
sai_status_t status = sai_vlan_api->create_vlan_member(&vlan_member_id, gSwitchId, (uint32_t)attrs.size(), attrs.data());
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Failed to add member %s to VLAN %s vid:%hu pid:%lx",
port.m_alias.c_str(), vlan.m_alias.c_str(), vlan.m_vlan_info.vlan_id, port.m_port_id);
return false;
}
SWSS_LOG_NOTICE("Add member %s to VLAN %s vid:%hu pid%lx",
port.m_alias.c_str(), vlan.m_alias.c_str(), vlan.m_vlan_info.vlan_id, port.m_port_id);
/* Use untagged VLAN as pvid of the member port */
if (sai_tagging_mode == SAI_VLAN_TAGGING_MODE_UNTAGGED)
{
if(!setPortPvid(port, vlan.m_vlan_info.vlan_id))
{
return false;
}
}
/* a physical port may join multiple vlans */
VlanMemberEntry vme = {vlan_member_id, sai_tagging_mode};
port.m_vlan_members[vlan.m_vlan_info.vlan_id] = vme;
m_portList[port.m_alias] = port;
vlan.m_members.insert(port.m_alias);
m_portList[vlan.m_alias] = vlan;
VlanMemberUpdate update = { vlan, port, true };
notify(SUBJECT_TYPE_VLAN_MEMBER_CHANGE, static_cast<void *>(&update));
return true;
}
bool PortsOrch::removeVlanMember(Port &vlan, Port &port)
{
SWSS_LOG_ENTER();
sai_object_id_t vlan_member_id;
sai_vlan_tagging_mode_t sai_tagging_mode;
auto vlan_member = port.m_vlan_members.find(vlan.m_vlan_info.vlan_id);
/* Assert the port belongs to this VLAN */
assert (vlan_member != port.m_vlan_members.end());
sai_tagging_mode = vlan_member->second.vlan_mode;
vlan_member_id = vlan_member->second.vlan_member_id;
sai_status_t status = sai_vlan_api->remove_vlan_member(vlan_member_id);
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Failed to remove member %s from VLAN %s vid:%hx vmid:%lx",
port.m_alias.c_str(), vlan.m_alias.c_str(), vlan.m_vlan_info.vlan_id, vlan_member_id);
return false;
}
port.m_vlan_members.erase(vlan_member);
SWSS_LOG_NOTICE("Remove member %s from VLAN %s lid:%hx vmid:%lx",
port.m_alias.c_str(), vlan.m_alias.c_str(), vlan.m_vlan_info.vlan_id, vlan_member_id);
/* Restore to default pvid if this port joined this VLAN in untagged mode previously */
if (sai_tagging_mode == SAI_VLAN_TAGGING_MODE_UNTAGGED)
{
if (!setPortPvid(port, DEFAULT_PORT_VLAN_ID))
{
return false;
}
}
m_portList[port.m_alias] = port;
vlan.m_members.erase(port.m_alias);
m_portList[vlan.m_alias] = vlan;
VlanMemberUpdate update = { vlan, port, false };
notify(SUBJECT_TYPE_VLAN_MEMBER_CHANGE, static_cast<void *>(&update));
return true;
}
bool PortsOrch::addLag(string lag_alias)
{
SWSS_LOG_ENTER();
sai_object_id_t lag_id;
sai_status_t status = sai_lag_api->create_lag(&lag_id, gSwitchId, 0, NULL);
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Failed to create LAG %s lid:%lx", lag_alias.c_str(), lag_id);
return false;
}
SWSS_LOG_NOTICE("Create an empty LAG %s lid:%lx", lag_alias.c_str(), lag_id);
Port lag(lag_alias, Port::LAG);
lag.m_lag_id = lag_id;
lag.m_members = set<string>();
m_portList[lag_alias] = lag;
return true;
}
bool PortsOrch::removeLag(Port lag)
{
SWSS_LOG_ENTER();
/* Retry when the LAG still has members */
if (lag.m_members.size() > 0)
{
SWSS_LOG_ERROR("Failed to remove non-empty LAG %s", lag.m_alias.c_str());
return false;
}
if (lag.m_vlan_members.size() > 0)
{
SWSS_LOG_ERROR("Failed to remove LAG %s, it is still in VLAN", lag.m_alias.c_str());
return false;
}
sai_status_t status = sai_lag_api->remove_lag(lag.m_lag_id);
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Failed to remove LAG %s lid:%lx", lag.m_alias.c_str(), lag.m_lag_id);
return false;
}
SWSS_LOG_NOTICE("Remove LAG %s lid:%lx", lag.m_alias.c_str(), lag.m_lag_id);
m_portList.erase(lag.m_alias);
return true;
}
void PortsOrch::getLagMember(Port &lag, vector<Port> &portv)
{
Port member;
for (auto &name: lag.m_members)
{
if (!getPort(name, member))
{
SWSS_LOG_ERROR("Failed to get port for %s alias", name.c_str());
return;
}
portv.push_back(member);
}
}
bool PortsOrch::addLagMember(Port &lag, Port &port)
{
SWSS_LOG_ENTER();
sai_uint32_t pvid;
if (getPortPvid(lag, pvid))
{
setPortPvid (port, pvid);
}
sai_attribute_t attr;
vector<sai_attribute_t> attrs;
attr.id = SAI_LAG_MEMBER_ATTR_LAG_ID;
attr.value.oid = lag.m_lag_id;
attrs.push_back(attr);
attr.id = SAI_LAG_MEMBER_ATTR_PORT_ID;
attr.value.oid = port.m_port_id;
attrs.push_back(attr);
sai_object_id_t lag_member_id;
sai_status_t status = sai_lag_api->create_lag_member(&lag_member_id, gSwitchId, (uint32_t)attrs.size(), attrs.data());
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Failed to add member %s to LAG %s lid:%lx pid:%lx",
port.m_alias.c_str(), lag.m_alias.c_str(), lag.m_lag_id, port.m_port_id);
return false;
}
SWSS_LOG_NOTICE("Add member %s to LAG %s lid:%lx pid:%lx",
port.m_alias.c_str(), lag.m_alias.c_str(), lag.m_lag_id, port.m_port_id);
port.m_lag_id = lag.m_lag_id;
port.m_lag_member_id = lag_member_id;
m_portList[port.m_alias] = port;
lag.m_members.insert(port.m_alias);
m_portList[lag.m_alias] = lag;
if (lag.m_bridge_port_id > 0)
{
if (!setHostIntfsStripTag(port, SAI_HOSTIF_VLAN_TAG_KEEP))
{
SWSS_LOG_ERROR("Failed to set %s for hostif of port %s which is in LAG %s",
hostif_vlan_tag[SAI_HOSTIF_VLAN_TAG_KEEP], port.m_alias.c_str(), lag.m_alias.c_str());
return false;
}
}
LagMemberUpdate update = { lag, port, true };
notify(SUBJECT_TYPE_LAG_MEMBER_CHANGE, static_cast<void *>(&update));
return true;
}
bool PortsOrch::removeLagMember(Port &lag, Port &port)
{
sai_status_t status = sai_lag_api->remove_lag_member(port.m_lag_member_id);
if (status != SAI_STATUS_SUCCESS)
{
SWSS_LOG_ERROR("Failed to remove member %s from LAG %s lid:%lx lmid:%lx",
port.m_alias.c_str(), lag.m_alias.c_str(), lag.m_lag_id, port.m_lag_member_id);
return false;
}
SWSS_LOG_NOTICE("Remove member %s from LAG %s lid:%lx lmid:%lx",
port.m_alias.c_str(), lag.m_alias.c_str(), lag.m_lag_id, port.m_lag_member_id);
port.m_lag_id = 0;
port.m_lag_member_id = 0;
m_portList[port.m_alias] = port;
lag.m_members.erase(port.m_alias);
m_portList[lag.m_alias] = lag;
if (lag.m_bridge_port_id > 0)
{
if (!setHostIntfsStripTag(port, SAI_HOSTIF_VLAN_TAG_STRIP))
{
SWSS_LOG_ERROR("Failed to set %s for hostif of port %s which is leaving LAG %s",
hostif_vlan_tag[SAI_HOSTIF_VLAN_TAG_STRIP], port.m_alias.c_str(), lag.m_alias.c_str());
return false;
}
}
LagMemberUpdate update = { lag, port, false };
notify(SUBJECT_TYPE_LAG_MEMBER_CHANGE, static_cast<void *>(&update));
return true;
}
void PortsOrch::generateQueueMap()
{
if (m_isQueueMapGenerated)
{
return;
}
for (const auto& it: m_portList)
{
if (it.second.m_type == Port::PHY)
{
generateQueueMapPerPort(it.second);
}
}
m_isQueueMapGenerated = true;
}
void PortsOrch::generateQueueMapPerPort(const Port& port)
{
/* Create the Queue map in the Counter DB */
/* Add stat counters to flex_counter */
vector<FieldValueTuple> queueVector;
vector<FieldValueTuple> queuePortVector;
vector<FieldValueTuple> queueIndexVector;
vector<FieldValueTuple> queueTypeVector;
for (size_t queueIndex = 0; queueIndex < port.m_queue_ids.size(); ++queueIndex)
{
std::ostringstream name;
name << port.m_alias << ":" << queueIndex;
const auto id = sai_serialize_object_id(port.m_queue_ids[queueIndex]);
queueVector.emplace_back(name.str(), id);
queuePortVector.emplace_back(id, sai_serialize_object_id(port.m_port_id));
queueIndexVector.emplace_back(id, to_string(queueIndex));
string queueType;
if (getQueueType(port.m_queue_ids[queueIndex], queueType))
{
queueTypeVector.emplace_back(id, queueType);
}
string key = getQueueFlexCounterTableKey(id);
std::string delimiter = "";
std::ostringstream counters_stream;
for (const auto& it: queueStatIds)
{
counters_stream << delimiter << sai_serialize_queue_stat(it);
delimiter = ",";
}
vector<FieldValueTuple> fieldValues;
fieldValues.emplace_back(QUEUE_COUNTER_ID_LIST, counters_stream.str());
m_flexCounterTable->set(key, fieldValues);
}
m_queueTable->set("", queueVector);
m_queuePortTable->set("", queuePortVector);
m_queueIndexTable->set("", queueIndexVector);
m_queueTypeTable->set("", queueTypeVector);
CounterCheckOrch::getInstance().addPort(port);
}
void PortsOrch::doTask(NotificationConsumer &consumer)
{
SWSS_LOG_ENTER();
/* Wait for all ports to be initialized */
if (!isInitDone())
{
return;
}
std::string op;
std::string data;
std::vector<swss::FieldValueTuple> values;
consumer.pop(op, data, values);
if (&consumer != m_portStatusNotificationConsumer)
{
return;
}
if (op == "port_state_change")
{
uint32_t count;
sai_port_oper_status_notification_t *portoperstatus = nullptr;
sai_deserialize_port_oper_status_ntf(data, count, &portoperstatus);
for (uint32_t i = 0; i < count; i++)
{
sai_object_id_t id = portoperstatus[i].port_id;
sai_port_oper_status_t status = portoperstatus[i].port_state;
SWSS_LOG_NOTICE("Get port state change notification id:%lx status:%d", id, status);
this->updateDbPortOperStatus(id, status);
this->setHostIntfsOperStatus(id, status == SAI_PORT_OPER_STATUS_UP);
}
sai_deserialize_free_port_oper_status_ntf(count, portoperstatus);
}
}
|
/*************************************************************************/
/* settings_config_dialog.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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 "settings_config_dialog.h"
#include "core/os/keyboard.h"
#include "core/project_settings.h"
#include "editor/debugger/editor_debugger_node.h"
#include "editor_file_system.h"
#include "editor_log.h"
#include "editor_node.h"
#include "editor_scale.h"
#include "editor_settings.h"
#include "scene/gui/margin_container.h"
void EditorSettingsDialog::ok_pressed() {
if (!EditorSettings::get_singleton())
return;
_settings_save();
timer->stop();
}
void EditorSettingsDialog::_settings_changed() {
timer->start();
}
void EditorSettingsDialog::_settings_property_edited(const String &p_name) {
String full_name = inspector->get_full_item_path(p_name);
if (full_name == "interface/theme/accent_color" || full_name == "interface/theme/base_color" || full_name == "interface/theme/contrast") {
EditorSettings::get_singleton()->set_manually("interface/theme/preset", "Custom"); // set preset to Custom
} else if (full_name.begins_with("text_editor/highlighting")) {
EditorSettings::get_singleton()->set_manually("text_editor/theme/color_theme", "Custom");
}
}
void EditorSettingsDialog::_settings_save() {
EditorSettings::get_singleton()->notify_changes();
EditorSettings::get_singleton()->save();
}
void EditorSettingsDialog::cancel_pressed() {
if (!EditorSettings::get_singleton())
return;
EditorSettings::get_singleton()->notify_changes();
}
void EditorSettingsDialog::popup_edit_settings() {
if (!EditorSettings::get_singleton())
return;
EditorSettings::get_singleton()->list_text_editor_themes(); // make sure we have an up to date list of themes
inspector->edit(EditorSettings::get_singleton());
inspector->get_inspector()->update_tree();
search_box->select_all();
search_box->grab_focus();
_update_shortcuts();
set_process_unhandled_input(true);
// Restore valid window bounds or pop up at default size.
Rect2 saved_size = EditorSettings::get_singleton()->get_project_metadata("dialog_bounds", "editor_settings", Rect2());
if (saved_size != Rect2()) {
popup(saved_size);
} else {
popup_centered_clamped(Size2(900, 700) * EDSCALE, 0.8);
}
_focus_current_search_box();
}
void EditorSettingsDialog::_filter_shortcuts(const String &p_filter) {
shortcut_filter = p_filter;
_update_shortcuts();
}
void EditorSettingsDialog::_undo_redo_callback(void *p_self, const String &p_name) {
EditorNode::get_log()->add_message(p_name, EditorLog::MSG_TYPE_EDITOR);
}
void EditorSettingsDialog::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_READY: {
undo_redo->set_method_notify_callback(EditorDebuggerNode::_method_changeds, NULL);
undo_redo->set_property_notify_callback(EditorDebuggerNode::_property_changeds, NULL);
undo_redo->set_commit_notify_callback(_undo_redo_callback, this);
} break;
case NOTIFICATION_ENTER_TREE: {
_update_icons();
} break;
case NOTIFICATION_POPUP_HIDE: {
EditorSettings::get_singleton()->set_project_metadata("dialog_bounds", "editor_settings", get_rect());
set_process_unhandled_input(false);
} break;
case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: {
_update_icons();
// Update theme colors.
inspector->update_category_list();
_update_shortcuts();
} break;
}
}
void EditorSettingsDialog::_unhandled_input(const Ref<InputEvent> &p_event) {
const Ref<InputEventKey> k = p_event;
if (k.is_valid() && is_window_modal_on_top() && k->is_pressed()) {
bool handled = false;
if (ED_IS_SHORTCUT("editor/undo", p_event)) {
String action = undo_redo->get_current_action_name();
if (action != "")
EditorNode::get_log()->add_message("Undo: " + action, EditorLog::MSG_TYPE_EDITOR);
undo_redo->undo();
handled = true;
}
if (ED_IS_SHORTCUT("editor/redo", p_event)) {
undo_redo->redo();
String action = undo_redo->get_current_action_name();
if (action != "")
EditorNode::get_log()->add_message("Redo: " + action, EditorLog::MSG_TYPE_EDITOR);
handled = true;
}
if (k->get_scancode_with_modifiers() == (KEY_MASK_CMD | KEY_F)) {
_focus_current_search_box();
handled = true;
}
if (handled) {
accept_event();
}
}
}
void EditorSettingsDialog::_update_icons() {
search_box->set_right_icon(get_icon("Search", "EditorIcons"));
search_box->set_clear_button_enabled(true);
shortcut_search_box->set_right_icon(get_icon("Search", "EditorIcons"));
shortcut_search_box->set_clear_button_enabled(true);
restart_close_button->set_icon(get_icon("Close", "EditorIcons"));
restart_container->add_style_override("panel", get_stylebox("bg", "Tree"));
restart_icon->set_texture(get_icon("StatusWarning", "EditorIcons"));
restart_label->add_color_override("font_color", get_color("warning_color", "Editor"));
}
void EditorSettingsDialog::_update_shortcuts() {
Map<String, bool> collapsed;
if (shortcuts->get_root() && shortcuts->get_root()->get_children()) {
for (TreeItem *item = shortcuts->get_root()->get_children(); item; item = item->get_next()) {
collapsed[item->get_text(0)] = item->is_collapsed();
}
}
shortcuts->clear();
List<String> slist;
EditorSettings::get_singleton()->get_shortcut_list(&slist);
TreeItem *root = shortcuts->create_item();
Map<String, TreeItem *> sections;
for (List<String>::Element *E = slist.front(); E; E = E->next()) {
Ref<ShortCut> sc = EditorSettings::get_singleton()->get_shortcut(E->get());
if (!sc->has_meta("original"))
continue;
Ref<InputEvent> original = sc->get_meta("original");
String section_name = E->get().get_slice("/", 0);
TreeItem *section;
if (sections.has(section_name)) {
section = sections[section_name];
} else {
section = shortcuts->create_item(root);
String item_name = section_name.capitalize();
section->set_text(0, item_name);
if (collapsed.has(item_name)) {
section->set_collapsed(collapsed[item_name]);
}
sections[section_name] = section;
section->set_custom_bg_color(0, get_color("prop_subsection", "Editor"));
section->set_custom_bg_color(1, get_color("prop_subsection", "Editor"));
}
// Don't match unassigned shortcuts when searching for assigned keys in search results.
// This prevents all unassigned shortcuts from appearing when searching a string like "no".
if (shortcut_filter.is_subsequence_ofi(sc->get_name()) || (sc->get_as_text() != "None" && shortcut_filter.is_subsequence_ofi(sc->get_as_text()))) {
TreeItem *item = shortcuts->create_item(section);
item->set_text(0, sc->get_name());
item->set_text(1, sc->get_as_text());
if (!sc->is_shortcut(original) && !(sc->get_shortcut().is_null() && original.is_null())) {
item->add_button(1, get_icon("Reload", "EditorIcons"), 2);
}
if (sc->get_as_text() == "None") {
// Fade out unassigned shortcut labels for easier visual grepping.
item->set_custom_color(1, get_color("font_color", "Label") * Color(1, 1, 1, 0.5));
}
item->add_button(1, get_icon("Edit", "EditorIcons"), 0);
item->add_button(1, get_icon("Close", "EditorIcons"), 1);
item->set_tooltip(0, E->get());
item->set_metadata(0, E->get());
}
}
// remove sections with no shortcuts
for (Map<String, TreeItem *>::Element *E = sections.front(); E; E = E->next()) {
TreeItem *section = E->get();
if (section->get_children() == NULL) {
root->remove_child(section);
}
}
}
void EditorSettingsDialog::_shortcut_button_pressed(Object *p_item, int p_column, int p_idx) {
TreeItem *ti = Object::cast_to<TreeItem>(p_item);
ERR_FAIL_COND(!ti);
String item = ti->get_metadata(0);
Ref<ShortCut> sc = EditorSettings::get_singleton()->get_shortcut(item);
if (p_idx == 0) {
press_a_key_label->set_text(TTR("Press a Key..."));
last_wait_for_key = Ref<InputEventKey>();
press_a_key->popup_centered(Size2(250, 80) * EDSCALE);
press_a_key->grab_focus();
press_a_key->get_ok()->set_focus_mode(FOCUS_NONE);
press_a_key->get_cancel()->set_focus_mode(FOCUS_NONE);
shortcut_configured = item;
} else if (p_idx == 1) { //erase
if (!sc.is_valid())
return; //pointless, there is nothing
undo_redo->create_action(TTR("Erase Shortcut"));
undo_redo->add_do_method(sc.ptr(), "set_shortcut", Ref<InputEvent>());
undo_redo->add_undo_method(sc.ptr(), "set_shortcut", sc->get_shortcut());
undo_redo->add_do_method(this, "_update_shortcuts");
undo_redo->add_undo_method(this, "_update_shortcuts");
undo_redo->add_do_method(this, "_settings_changed");
undo_redo->add_undo_method(this, "_settings_changed");
undo_redo->commit_action();
} else if (p_idx == 2) { //revert to original
if (!sc.is_valid())
return; //pointless, there is nothing
Ref<InputEvent> original = sc->get_meta("original");
undo_redo->create_action(TTR("Restore Shortcut"));
undo_redo->add_do_method(sc.ptr(), "set_shortcut", original);
undo_redo->add_undo_method(sc.ptr(), "set_shortcut", sc->get_shortcut());
undo_redo->add_do_method(this, "_update_shortcuts");
undo_redo->add_undo_method(this, "_update_shortcuts");
undo_redo->add_do_method(this, "_settings_changed");
undo_redo->add_undo_method(this, "_settings_changed");
undo_redo->commit_action();
}
}
void EditorSettingsDialog::_wait_for_key(const Ref<InputEvent> &p_event) {
Ref<InputEventKey> k = p_event;
if (k.is_valid() && k->is_pressed() && k->get_scancode() != 0) {
last_wait_for_key = k;
const String str = keycode_get_string(k->get_scancode_with_modifiers());
press_a_key_label->set_text(str);
press_a_key->accept_event();
}
}
void EditorSettingsDialog::_press_a_key_confirm() {
if (last_wait_for_key.is_null())
return;
Ref<InputEventKey> ie;
ie.instance();
ie->set_scancode(last_wait_for_key->get_scancode());
ie->set_shift(last_wait_for_key->get_shift());
ie->set_control(last_wait_for_key->get_control());
ie->set_alt(last_wait_for_key->get_alt());
ie->set_metakey(last_wait_for_key->get_metakey());
Ref<ShortCut> sc = EditorSettings::get_singleton()->get_shortcut(shortcut_configured);
undo_redo->create_action(TTR("Change Shortcut") + " '" + shortcut_configured + "'");
undo_redo->add_do_method(sc.ptr(), "set_shortcut", ie);
undo_redo->add_undo_method(sc.ptr(), "set_shortcut", sc->get_shortcut());
undo_redo->add_do_method(this, "_update_shortcuts");
undo_redo->add_undo_method(this, "_update_shortcuts");
undo_redo->add_do_method(this, "_settings_changed");
undo_redo->add_undo_method(this, "_settings_changed");
undo_redo->commit_action();
}
void EditorSettingsDialog::_tabs_tab_changed(int p_tab) {
_focus_current_search_box();
}
void EditorSettingsDialog::_focus_current_search_box() {
Control *tab = tabs->get_current_tab_control();
LineEdit *current_search_box = NULL;
if (tab == tab_general)
current_search_box = search_box;
else if (tab == tab_shortcuts)
current_search_box = shortcut_search_box;
if (current_search_box) {
current_search_box->grab_focus();
current_search_box->select_all();
}
}
void EditorSettingsDialog::_editor_restart() {
EditorNode::get_singleton()->save_all_scenes();
EditorNode::get_singleton()->restart_editor();
}
void EditorSettingsDialog::_editor_restart_request() {
restart_container->show();
}
void EditorSettingsDialog::_editor_restart_close() {
restart_container->hide();
}
void EditorSettingsDialog::_bind_methods() {
ClassDB::bind_method(D_METHOD("_unhandled_input"), &EditorSettingsDialog::_unhandled_input);
ClassDB::bind_method(D_METHOD("_update_shortcuts"), &EditorSettingsDialog::_update_shortcuts);
}
EditorSettingsDialog::EditorSettingsDialog() {
set_title(TTR("Editor Settings"));
set_resizable(true);
undo_redo = memnew(UndoRedo);
tabs = memnew(TabContainer);
tabs->set_tab_align(TabContainer::ALIGN_LEFT);
tabs->connect("tab_changed", callable_mp(this, &EditorSettingsDialog::_tabs_tab_changed));
add_child(tabs);
// General Tab
tab_general = memnew(VBoxContainer);
tabs->add_child(tab_general);
tab_general->set_name(TTR("General"));
HBoxContainer *hbc = memnew(HBoxContainer);
hbc->set_h_size_flags(Control::SIZE_EXPAND_FILL);
tab_general->add_child(hbc);
search_box = memnew(LineEdit);
search_box->set_h_size_flags(Control::SIZE_EXPAND_FILL);
hbc->add_child(search_box);
inspector = memnew(SectionedInspector);
inspector->get_inspector()->set_use_filter(true);
inspector->register_search_box(search_box);
inspector->set_v_size_flags(Control::SIZE_EXPAND_FILL);
inspector->get_inspector()->set_undo_redo(undo_redo);
tab_general->add_child(inspector);
inspector->get_inspector()->connect("property_edited", callable_mp(this, &EditorSettingsDialog::_settings_property_edited));
inspector->get_inspector()->connect("restart_requested", callable_mp(this, &EditorSettingsDialog::_editor_restart_request));
restart_container = memnew(PanelContainer);
tab_general->add_child(restart_container);
HBoxContainer *restart_hb = memnew(HBoxContainer);
restart_container->add_child(restart_hb);
restart_icon = memnew(TextureRect);
restart_icon->set_v_size_flags(SIZE_SHRINK_CENTER);
restart_hb->add_child(restart_icon);
restart_label = memnew(Label);
restart_label->set_text(TTR("The editor must be restarted for changes to take effect."));
restart_hb->add_child(restart_label);
restart_hb->add_spacer();
Button *restart_button = memnew(Button);
restart_button->connect("pressed", callable_mp(this, &EditorSettingsDialog::_editor_restart));
restart_hb->add_child(restart_button);
restart_button->set_text(TTR("Save & Restart"));
restart_close_button = memnew(ToolButton);
restart_close_button->connect("pressed", callable_mp(this, &EditorSettingsDialog::_editor_restart_close));
restart_hb->add_child(restart_close_button);
restart_container->hide();
// Shortcuts Tab
tab_shortcuts = memnew(VBoxContainer);
tabs->add_child(tab_shortcuts);
tab_shortcuts->set_name(TTR("Shortcuts"));
hbc = memnew(HBoxContainer);
hbc->set_h_size_flags(Control::SIZE_EXPAND_FILL);
tab_shortcuts->add_child(hbc);
shortcut_search_box = memnew(LineEdit);
shortcut_search_box->set_h_size_flags(Control::SIZE_EXPAND_FILL);
hbc->add_child(shortcut_search_box);
shortcut_search_box->connect("text_changed", callable_mp(this, &EditorSettingsDialog::_filter_shortcuts));
shortcuts = memnew(Tree);
tab_shortcuts->add_child(shortcuts, true);
shortcuts->set_v_size_flags(SIZE_EXPAND_FILL);
shortcuts->set_columns(2);
shortcuts->set_hide_root(true);
shortcuts->set_column_titles_visible(true);
shortcuts->set_column_title(0, TTR("Name"));
shortcuts->set_column_title(1, TTR("Binding"));
shortcuts->connect("button_pressed", callable_mp(this, &EditorSettingsDialog::_shortcut_button_pressed));
press_a_key = memnew(ConfirmationDialog);
press_a_key->set_focus_mode(FOCUS_ALL);
add_child(press_a_key);
Label *l = memnew(Label);
l->set_text(TTR("Press a Key..."));
l->set_anchors_and_margins_preset(Control::PRESET_WIDE);
l->set_align(Label::ALIGN_CENTER);
l->set_margin(MARGIN_TOP, 20);
l->set_anchor_and_margin(MARGIN_BOTTOM, ANCHOR_BEGIN, 30);
press_a_key_label = l;
press_a_key->add_child(l);
press_a_key->connect("gui_input", callable_mp(this, &EditorSettingsDialog::_wait_for_key));
press_a_key->connect("confirmed", callable_mp(this, &EditorSettingsDialog::_press_a_key_confirm));
set_hide_on_ok(true);
timer = memnew(Timer);
timer->set_wait_time(1.5);
timer->connect("timeout", callable_mp(this, &EditorSettingsDialog::_settings_save));
timer->set_one_shot(true);
add_child(timer);
EditorSettings::get_singleton()->connect("settings_changed", callable_mp(this, &EditorSettingsDialog::_settings_changed));
get_ok()->set_text(TTR("Close"));
updating = false;
}
EditorSettingsDialog::~EditorSettingsDialog() {
memdelete(undo_redo);
}
|
#include <gtest/gtest.h>
#include <pointing.h>
TEST(pointing, initialization)
{
Pointing p;
}
|
// This file is part of SWGANH which is released under the MIT license.
// See file LICENSE or go to http://swganh.com/LICENSE
#include "swganh/object/manufacture_schematic/manufacture_schematic.h"
#include "swganh/messages/deltas_message.h"
#include "anh/crc.h"
using namespace std;
using namespace swganh::object::manufacture_schematic;
using namespace swganh::messages;
uint32_t ManufactureSchematic::GetType() const
{
return ManufactureSchematic::type;
}
uint32_t ManufactureSchematic::GetSchematicQuantity() const
{
return schematic_quantity_;
}
void ManufactureSchematic::SetSchematicQuantity(uint32_t quantity)
{
schematic_quantity_ = (quantity > 1000) ? 1000 : quantity;
/*if (HasObservers())
{
DeltasMessage message = CreateDeltasMessage(VIEW_3, 4);
message.data.write(schematic_quantity_);
AddDeltasUpdate(message);
}*/
}
void ManufactureSchematic::IncrementSchematicQuantity(int32_t increment_by)
{
uint32_t tmp = schematic_quantity_ + increment_by;
schematic_quantity_ = (tmp > 1000) ? 1000 : tmp;
/*if (HasObservers())
{
DeltasMessage message = CreateDeltasMessage(VIEW_3, 4);
message.data.write(schematic_quantity_);
AddDeltasUpdate(message);
}*/
}
std::vector<ManufactureSchematic::Property> ManufactureSchematic::GetProperties() const
{
return properties_;
}
void ManufactureSchematic::AddProperty(
std::string property_stf_file,
std::string property_stf_name,
float value)
{
auto find_iter = find_if(
properties_.begin(),
properties_.end(),
[&property_stf_name] (const Property& stored_property)
{
return stored_property.property_stf_name.compare(property_stf_name) == 0;
});
if (find_iter != properties_.end())
{
// Already in the list.
return;
}
/*if (HasObservers())
{
DeltasMessage message = CreateDeltasMessage(VIEW_3, 0);
message.data.write(properties_.size());
message.data.write(property_counter_++);
message.data.write(property_stf_file);
message.data.write(0);
message.data.write(property_stf_name);
message.data.write(value);
AddDeltasUpdate(message);
}*/
// now push it back
Property new_property;
new_property.property_stf_file = move(property_stf_file);
new_property.property_stf_name = move(property_stf_name);
new_property.value = value;
properties_.push_back(move(new_property));
}
void ManufactureSchematic::RemoveProperty(
std::string property_stf_file,
std::string property_stf_name,
float value)
{
auto find_iter = find_if(
properties_.begin(),
properties_.end(),
[&property_stf_name] (const Property& stored_property)
{
return stored_property.property_stf_name.compare(property_stf_name) == 0;
});
if (find_iter == properties_.end())
{
// Not in the list.
return;
}
/*if (HasObservers())
{
DeltasMessage message = CreateDeltasMessage(VIEW_3, 5);
message.data.write(properties_.size());
message.data.write(property_counter_);
message.data.write<uint8_t>(1);
message.data.write(property_stf_file);
message.data.write(0);
message.data.write(property_stf_name);
message.data.write(value);
AddDeltasUpdate(message);
}*/
properties_.erase(find_iter);
}
void ManufactureSchematic::UpdateProperty(
std::string property_stf_file,
std::string property_stf_name,
float value)
{
auto find_iter = find_if(
properties_.begin(),
properties_.end(),
[&property_stf_name] (const Property& stored_property)
{
return stored_property.property_stf_name.compare(property_stf_name) == 0;
});
if (find_iter == properties_.end())
{
// Not in the list.
return;
}
/*if (HasObservers())
{
DeltasMessage message = CreateDeltasMessage(VIEW_3, 2);
message.data.write(properties_.size());
message.data.write(property_counter_);
message.data.write(property_stf_file);
message.data.write(0);
message.data.write(property_stf_name);
message.data.write(value);
AddDeltasUpdate(message);
}*/
find_iter->property_stf_file = move(property_stf_file);
find_iter->property_stf_name = move(property_stf_name);
find_iter->value = value;
}
std::wstring ManufactureSchematic::GetCreatorName() const
{
return creator_;
}
void ManufactureSchematic::SetCreatorName(std::wstring creator)
{
creator_ = move(creator);
/*if (HasObservers())
{
DeltasMessage message = CreateDeltasMessage(VIEW_3, 6);
message.data.write(creator_);
AddDeltasUpdate(message);
}*/
}
uint32_t ManufactureSchematic::GetSchematicComplexity() const
{
return complexity_;
}
void ManufactureSchematic::SetSchematicComplexity(uint32_t complexity)
{
complexity_ = complexity;
/*if (HasObservers())
{
DeltasMessage message = CreateDeltasMessage(VIEW_3, 7);
message.data.write(creator_);
AddDeltasUpdate(message);
}*/
}
float ManufactureSchematic::GetSchematicDataSize() const
{
return schematic_data_size_;
}
void ManufactureSchematic::SetSchematicDataSize(float schematic_data_size)
{
schematic_data_size_ = schematic_data_size;
/*if (HasObservers())
{
DeltasMessage message = CreateDeltasMessage(VIEW_3, 8);
message.data.write(schematic_data_size_);
AddDeltasUpdate(message);
}*/
}
std::vector<uint8_t> ManufactureSchematic::GetCustomizationString() const
{
return customization_;
}
void ManufactureSchematic::SetCustomizationString(std::vector<uint8_t> customization_string)
{
customization_ = move(customization_string);
/*if (HasObservers())
{
DeltasMessage message = CreateDeltasMessage(VIEW_6, 1);
message.data.write(customization_);
AddDeltasUpdate(message);
}*/
}
std::string ManufactureSchematic::GetCustomizationModel() const
{
return customization_model_;
}
void ManufactureSchematic::SetCustomizationModel(std::string customization_model)
{
customization_model_ = customization_model;
/*if (HasObservers())
{
DeltasMessage message = CreateDeltasMessage(VIEW_6, 2);
message.data.write(customization_model_);
AddDeltasUpdate(message);
}*/
}
std::string ManufactureSchematic::GetPrototypeModel() const
{
return prototype_model_;
}
uint32_t ManufactureSchematic::GetPrototypeCrc() const
{
return anh::memcrc(prototype_model_);
}
void ManufactureSchematic::SetPrototypeModel(std::string prototype_model)
{
prototype_model_ = move(prototype_model);
/*if (HasObservers())
{
DeltasMessage message = CreateDeltasMessage(VIEW_6, 3);
message.data.write(GetPrototypeCrc());
AddDeltasUpdate(message);
}*/
}
bool ManufactureSchematic::IsActive() const
{
return is_active_;
}
void ManufactureSchematic::Activate()
{
if (!IsActive())
{
ToggleActive();
}
}
void ManufactureSchematic::Deactive()
{
if (IsActive())
{
ToggleActive();
}
}
void ManufactureSchematic::ToggleActive()
{
//is_active_ = !is_active_;
//uint8_t flag = is_active_ ? 1 : 0;
/*if (HasObservers())
{
DeltasMessage message = CreateDeltasMessage(VIEW_6, 4);
message.data.write(flag);
AddDeltasUpdate(message);
}*/
}
uint8_t ManufactureSchematic::GetSlotCount() const
{
return slot_count_;
}
void ManufactureSchematic::IncreaseSlotCount()
{
++slot_count_;
/*if (HasObservers())
{
DeltasMessage message = CreateDeltasMessage(VIEW_6, 5);
message.data.write(slot_count_);
AddDeltasUpdate(message);
}*/
}
void ManufactureSchematic::DecreaseSlotCount()
{
--slot_count_;
/*if (HasObservers())
{
DeltasMessage message = CreateDeltasMessage(VIEW_6, 5);
message.data.write(slot_count_);
AddDeltasUpdate(message);
}*/
}
void ManufactureSchematic::ResetSlotCount(uint8_t slot_count)
{
slot_count_ = slot_count;
/*if (HasObservers())
{
DeltasMessage message = CreateDeltasMessage(VIEW_6, 5);
message.data.write(slot_count_);
AddDeltasUpdate(message);
}*/
}
std::vector<ManufactureSchematic::Slot> ManufactureSchematic::GetSlots() const
{
return slots_;
}
void ManufactureSchematic::BuildSlotDelta_(
uint8_t update_type, uint8_t sub_type,
std::vector<Slot>::iterator slot_iterator)
{
//// no observers, don't bother
//if (!HasObservers())
//{
// return;
//}
//// don't handle reset all here
//if (sub_type == 3)
// return;
//
//DeltasMessage message = CreateDeltasMessage(VIEW_7, 0);
//message.data.write(slots_.size());
//message.data.write(slot_counter_);
//message.data.write<uint8_t>(sub_type);
//// clear
//if (sub_type == 4)
//{
// return;
//}
//// everything needs the index, but 3,4
//message.data.write(slot_iterator - slots_.begin());
//// remove just needs index so return here
//if (sub_type == 0)
//{
// return;
//}
//switch (update_type)
//{
// case 0:
// message.data.write(slot_iterator->slot_stf_file);
// message.data.write(0);
// message.data.write(slot_iterator->slot_stf_name);
// break;
// case 1:
// message.data.write(slot_iterator->type);
// break;
// case 2:
// message.data.write(slot_iterator->ingredient);
// break;
// case 3:
// message.data.write(slot_iterator->ingredient_quantity);
// break;
// case 5:
// message.data.write(slot_iterator->clean);
// break;
// case 6:
// message.data.write(slot_iterator->index);
// break;
//}
//AddDeltasUpdate(message);
}
void ManufactureSchematic::RemoveSlot(uint16_t index)
{
auto find_iter = find_if(
slots_.begin(),
slots_.end(),
[index] (const Slot& slot)
{
return index == slot.index;
});
if (find_iter == slots_.end())
{
// Not in the list.
return;
}
// loop through all the types
for (int update_type = 0; update_type < 7; ++update_type)
{
BuildSlotDelta_(update_type, 0, find_iter);
}
slots_.erase(find_iter);
}
/**
* @return The index the slot was added into.
*/
uint16_t ManufactureSchematic::AddSlot(
std::string slot_stf_file,
std::string slot_stf_name,
uint32_t type,
uint64_t ingredient,
uint32_t ingredient_quantity,
uint32_t clean)
{
auto find_iter = find_if(
slots_.begin(),
slots_.end(),
[&slot_stf_name] (const Slot& slot)
{
return slot.slot_stf_name.compare(slot_stf_name) == 0;
});
if (find_iter != slots_.end())
{
// Already in the list.
return 0;
}
Slot slot;
slot.index = customizations_.back().index + 1;
slot.slot_stf_file = move(slot_stf_file);
slot.slot_stf_name = move(slot_stf_name);
slot.type = type;
slot.ingredient = ingredient;
slot.ingredient_quantity = ingredient_quantity;
slot.clean = clean;
slots_.push_back(slot);
// loop through all the types
for (int update_type = 0; update_type < 7; ++update_type)
{
BuildSlotDelta_(update_type, 1, find_iter);
}
return slot.index;
}
void ManufactureSchematic::UpdateSlot(
uint16_t index,
std::string slot_stf_file,
std::string slot_stf_name,
uint32_t type,
uint64_t ingredient,
uint32_t ingredient_quantity,
uint32_t clean)
{
auto find_iter = find_if(
slots_.begin(),
slots_.end(),
[index] (const Slot& slot)
{
return index == slot.index;
});
if (find_iter == slots_.end())
{
// Not in the list.
return;
}
find_iter->slot_stf_file = move(slot_stf_file);
find_iter->slot_stf_name = move(slot_stf_name);
find_iter->type = type;
find_iter->ingredient = ingredient;
find_iter->ingredient_quantity = ingredient_quantity;
find_iter->clean = clean;
// loop through all the types
for (int update_type = 0; update_type < 7; ++update_type)
{
BuildSlotDelta_(update_type, 2, find_iter);
}
}
void ManufactureSchematic::ResetSlots(std::vector<ManufactureSchematic::Slot> slots)
{
slots_ = move(slots);
/*if (HasObservers())
{
DeltasMessage message = CreateDeltasMessage(VIEW_7, 3);;
message.data.write(slots_.size());
message.data.write(slot_counter_);
for_each(begin(slots_), end(slots_), [&message](Slot slot){
message.data.write(slot.slot_stf_file);
message.data.write(0);
message.data.write(slot.slot_stf_name);
});
AddDeltasUpdate(message);
}*/
}
void ManufactureSchematic::ClearAllSlots()
{
slots_.clear();
// loop through all the types
for (int type = 0; type < 7; ++type)
{
BuildSlotDelta_(type, 0, slots_.begin());
}
}
std::vector<ManufactureSchematic::Experiment> ManufactureSchematic::GetExperiments() const
{
return experiments_;
}
void ManufactureSchematic::RemoveExperiment(uint16_t index)
{
auto find_iter = find_if(
experiments_.begin(),
experiments_.end(),
[index] (const Experiment& experiment)
{
return index == experiment.index;
});
if (find_iter == experiments_.end())
{
// Not in the list.
return;
}
experiments_.erase(find_iter);
}
/**
* @return The index the experiment was added into.
*/
uint16_t ManufactureSchematic::AddExperiment(
std::string experiment_stf_file,
std::string experiment_stf_name,
float value,
float offset,
float size,
float max_value)
{
auto find_iter = find_if(
experiments_.begin(),
experiments_.end(),
[&experiment_stf_name] (const Experiment& experiment)
{
return experiment.experiment_stf_name.compare(experiment_stf_name) == 0;
});
if (find_iter != experiments_.end())
{
// Already in the list.
return 0;
}
Experiment experiment;
experiment.index = customizations_.back().index + 1;
experiment.experiment_stf_file = move(experiment_stf_file);
experiment.experiment_stf_name = move(experiment_stf_name);
experiment.value = value;
experiment.offset = offset;
experiment.size = size;
experiment.max_value = max_value;
experiments_.push_back(experiment);
return experiment.index;
}
void ManufactureSchematic::UpdateExperiment(
uint16_t index,
std::string experiment_stf_file,
std::string experiment_stf_name,
float value,
float offset,
float size,
float max_value)
{
auto find_iter = find_if(
experiments_.begin(),
experiments_.end(),
[index] (const Experiment& experiment)
{
return index == experiment.index;
});
if (find_iter == experiments_.end())
{
// Not in the list.
return;
}
find_iter->experiment_stf_file = move(experiment_stf_file);
find_iter->experiment_stf_name = move(experiment_stf_name);
find_iter->value = value;
find_iter->offset = offset;
find_iter->size = size;
find_iter->max_value = max_value;
}
void ManufactureSchematic::ResetExperiments(std::vector<ManufactureSchematic::Experiment> experiments)
{
experiments_ = move(experiments);
}
void ManufactureSchematic::ClearAllExperiments()
{
experiments_.clear();
}
std::vector<ManufactureSchematic::Customization> ManufactureSchematic::GetCustomizations() const
{
return customizations_;
}
void ManufactureSchematic::RemoveCustomization(uint16_t index)
{
auto find_iter = find_if(
customizations_.begin(),
customizations_.end(),
[index] (const Customization& customization)
{
return index == customization.index;
});
if (find_iter == customizations_.end())
{
// Not in the list.
return;
}
customizations_.erase(find_iter);
}
/**
* @return The index the slot was added into.
*/
uint16_t ManufactureSchematic::AddCustomization(
std::string name,
uint32_t pallet_selection,
uint32_t pallet_start_index,
uint32_t pallet_end_index)
{
auto find_iter = find_if(
customizations_.begin(),
customizations_.end(),
[name] (const Customization& customization)
{
return customization.name.compare(name) == 0;
});
if (find_iter != customizations_.end())
{
// Already in the list.
return 0;
}
Customization customization;
customization.index = customizations_.back().index + 1;
customization.name = move(name);
customization.pallet_selection = pallet_selection;
customization.pallet_start_index = pallet_start_index;
customization.pallet_end_index = pallet_end_index;
customizations_.push_back(customization);
return customization.index;
}
void ManufactureSchematic::UpdateCustomization(
uint16_t index,
std::string name,
uint32_t pallet_selection,
uint32_t pallet_start_index,
uint32_t pallet_end_index)
{
auto find_iter = find_if(
customizations_.begin(),
customizations_.end(),
[index] (const Customization& customization)
{
return index == customization.index;
});
if (find_iter == customizations_.end())
{
// Not in the list.
return;
}
find_iter->name = move(name);
find_iter->pallet_selection = pallet_selection;
find_iter->pallet_start_index = pallet_start_index;
find_iter->pallet_end_index = pallet_end_index;
}
void ManufactureSchematic::ResetCustomizations(std::vector<Customization> customizations)
{
customizations_ = move(customizations);
}
void ManufactureSchematic::ClearAllCustomizations()
{
customizations_.clear();
}
bool ManufactureSchematic::IsReady() const
{
return is_ready_;
}
void ManufactureSchematic::ToggleReady()
{
is_ready_ = !is_ready_;
}
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "ItemCrate.h"
#include "Components/StaticMeshComponent.h"
#include "Components/BoxComponent.h"
#include "Components/WidgetComponent.h"
#include "Engine/CollisionProfile.h"
#include "Interactable/BaseClasses/InteractableComponent.h"
#include "Components/InventoryComponent.h"
#include "Characters/PlayerCharacter/PlayerCharacter.h"
#include "Characters/PlayerCharacter/UtilitySacks/ItemSack.h"
// Sets default values
AItemCrate::AItemCrate()
{
PrimaryActorTick.bCanEverTick = false;
ItemMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("ItemMesh"));
ItemMesh->SetGenerateOverlapEvents(false);
ItemMesh->SetCollisionProfileName(UCollisionProfile::BlockAll_ProfileName);
RootComponent = ItemMesh;
// OutlineMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("OutlineMesh"));
// OutlineMesh->SetGenerateOverlapEvents(false);
// OutlineMesh->SetCollisionProfileName(UCollisionProfile::BlockAll_ProfileName);
// OutlineMesh->SetupAttachment(ItemMesh);
TriggerVolume = CreateDefaultSubobject<UBoxComponent>(TEXT("TriggerVolume"));
TriggerVolume->SetGenerateOverlapEvents(true);
TriggerVolume->SetCollisionProfileName(TEXT("Trigger"));
TriggerVolume->SetupAttachment(RootComponent);
InteractableComponent = CreateDefaultSubobject<UInteractableComponent>(TEXT("InteractableComponent"));
InteractableComponent->bOneTimeUse = false;
InteractableComponent->RegisterTriggerVolume(TriggerVolume);
}
// Called when the game starts or when spawned
void AItemCrate::BeginPlay()
{
Super::BeginPlay();
// TODO: Move to constructor when able to (not working atm)
InteractableComponent->OnInteractSuccess.AddDynamic(this, &AItemCrate::PickupItem);
}
void AItemCrate::PickupItem(class APlayerCharacter* _playerCharacter)
{
_playerCharacter->Receive_PlayGrabAnim();
Receive_PickupItem();
UInventoryComponent* inventoryComp = _playerCharacter->GetInventoryComponent();
// Adds item type to inventory
if (ItemSackType)
{
inventoryComp->PickupItem(ItemSackType);
}
}
|
/*
* Copyright (c) 2021 pongasoft
*
* 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.
*
* @author Yan Pujante
*/
#include <re/mock/Errors.h>
#include <re/mock/Motherboard.h>
#include "RealtimeController.h"
//------------------------------------------------------------------------
// Defining the C-API to invoke from lua as jbox.xxx
//------------------------------------------------------------------------
extern "C" {
using namespace re::mock::lua;
static int lua_load_property(lua_State *L)
{
return RealtimeController::loadFromRegistry(L)->luaLoadProperty();
}
static int lua_store_property(lua_State *L)
{
return RealtimeController::loadFromRegistry(L)->luaStoreProperty();
}
static int lua_make_native_object_rw(lua_State *L)
{
return RealtimeController::loadFromRegistry(L)->luaMakeNativeObject(false);
}
static int lua_make_native_object_ro(lua_State *L)
{
return RealtimeController::loadFromRegistry(L)->luaMakeNativeObject(true);
}
static int lua_is_native_object(lua_State *L)
{
return RealtimeController::loadFromRegistry(L)->luaIsNativeObject();
}
static int lua_is_blob(lua_State *L)
{
return RealtimeController::loadFromRegistry(L)->luaIsBlob();
}
static int lua_make_empty_native_object(lua_State *L)
{
return RealtimeController::loadFromRegistry(L)->luaMakeNil();
}
static int lua_make_empty_blob(lua_State *L)
{
return RealtimeController::loadFromRegistry(L)->luaMakeEmptyBlob();
}
static int lua_load_blob_async(lua_State *L)
{
return RealtimeController::loadFromRegistry(L)->luaLoadBlobAsync();
}
static int lua_get_blob_info(lua_State *L)
{
return RealtimeController::loadFromRegistry(L)->luaGetBlobInfo();
}
static int lua_is_sample(lua_State *L)
{
return RealtimeController::loadFromRegistry(L)->luaIsSample();
}
static int lua_make_empty_sample(lua_State *L)
{
return RealtimeController::loadFromRegistry(L)->luaMakeEmptySample();
}
static int lua_get_sample_meta_data(lua_State *L)
{
return RealtimeController::loadFromRegistry(L)->luaGetSampleMetaData();
}
static int lua_get_sample_info(lua_State *L)
{
return RealtimeController::loadFromRegistry(L)->luaGetSampleInfo();
}
static int lua_load_sample_async(lua_State *L)
{
return RealtimeController::loadFromRegistry(L)->luaLoadSampleAsync();
}
static int lua_trace(lua_State *L)
{
return RealtimeController::loadFromRegistry(L)->luaTrace();
}
}
namespace re::mock::lua {
//------------------------------------------------------------------------
// RealtimeController::RealtimeController
//------------------------------------------------------------------------
RealtimeController::RealtimeController()
{
static const struct luaL_Reg jboxLib[] = {
{"get_blob_info", lua_get_blob_info},
{"get_sample_info", lua_get_sample_info},
{"get_sample_meta_data", lua_get_sample_meta_data},
{"is_blob", lua_is_blob},
{"is_native_object", lua_is_native_object},
{"is_sample", lua_is_sample},
{"load_blob_async", lua_load_blob_async},
{"load_property", lua_load_property},
{"load_sample_async", lua_load_sample_async},
{"make_empty_blob", lua_make_empty_blob},
{"make_empty_native_object", lua_make_empty_native_object},
{"make_empty_sample", lua_make_empty_sample},
{"make_native_object_rw", lua_make_native_object_rw},
{"make_native_object_ro", lua_make_native_object_ro},
{"store_property", lua_store_property},
{"trace", lua_trace},
{nullptr, nullptr}
};
luaL_newlib(L, jboxLib);
lua_setglobal(L, "jbox"); // will be available in realtime_controller.lua as jbox
}
//------------------------------------------------------------------------
// RealtimeController::loadFromRegistry
//------------------------------------------------------------------------
RealtimeController *RealtimeController::loadFromRegistry(lua_State *L)
{
auto res = dynamic_cast<RealtimeController *>(MockJBox::loadFromRegistry(L));
RE_MOCK_ASSERT(res != nullptr);
return res;
}
//------------------------------------------------------------------------
// RealtimeController::fromFile
//------------------------------------------------------------------------
std::unique_ptr<RealtimeController> RealtimeController::fromFile(std::string const &iLuaFilename)
{
auto res = std::make_unique<RealtimeController>();
res->loadFile(iLuaFilename);
return res;
}
//------------------------------------------------------------------------
// RealtimeController::fromString
//------------------------------------------------------------------------
std::unique_ptr<RealtimeController> RealtimeController::fromString(std::string const &iLuaCode)
{
auto res = std::make_unique<RealtimeController>();
res->loadString(iLuaCode);
return res;
}
//------------------------------------------------------------------------
// RealtimeController::luaTrace
//------------------------------------------------------------------------
int RealtimeController::luaTrace()
{
RE_MOCK_ASSERT(lua_gettop(L) == 1, "jbox.trace() is expecting 1 argument");
int t = lua_type(L, 1);
luaL_argexpected(L, t == LUA_TSTRING, 1, "jbox.trace() is expecting a string argument");
lua_Debug ar;
lua_getstack(L, 1, &ar);
lua_getinfo(L, "nSl", &ar);
auto s = lua_tostring(L, -1);
if(s != nullptr)
getCurrentMotherboard()->trace("realtime_controller.lua", ar.currentline, s);
return 0;
}
//------------------------------------------------------------------------
// RealtimeController::luaLoadProperty
//------------------------------------------------------------------------
int RealtimeController::luaLoadProperty()
{
luaL_checktype(L, 1, LUA_TSTRING);
auto const propertyPath = lua_tostring(L, 1);
RE_MOCK_ASSERT(stl::contains_key(fReverseBindings.at(fCurrentBindingName), propertyPath),
"Load property failed while executing binding [/global_rtc/%s]. Can only read property [%s] in rtc_bindings function with this property as source.",
propertyPath, fCurrentBindingName);
auto value = getCurrentMotherboard()->getJboxValue(propertyPath);
pushJBoxValue(value);
return 1;
}
//------------------------------------------------------------------------
// RealtimeController::luaStoreProperty
//------------------------------------------------------------------------
int RealtimeController::luaStoreProperty()
{
luaL_checktype(L, 1, LUA_TSTRING);
auto const propertyPath = lua_tostring(L, 1);
RE_MOCK_ASSERT(getCurrentMotherboard()->getPropertyOwner(propertyPath) == PropertyOwner::kRTCOwner);
getCurrentMotherboard()->setValue(propertyPath, toJBoxValue(2));
return 0;
}
//------------------------------------------------------------------------
// RealtimeController::luaMakeNativeObject
//------------------------------------------------------------------------
int RealtimeController::luaMakeNativeObject(bool iReadOnly)
{
int numArguments = lua_gettop(L);
// Operation
luaL_checktype(L, 1, LUA_TSTRING);
auto operation = lua_tostring(L, 1);
std::vector<std::shared_ptr<const JboxValue>> params{};
// params
if(numArguments > 1)
{
auto paramsTableIdx = 2;
auto numParams = L.getTableSize(paramsTableIdx);
for(int i = 1; i <= numParams; i++)
{
lua_geti(L, paramsTableIdx, i);
params.emplace_back(toJBoxValue());
lua_pop(L, 1);
}
}
pushJBoxValue(iReadOnly ?
getCurrentMotherboard()->makeNativeObjectRO(operation, params) :
getCurrentMotherboard()->makeNativeObjectRW(operation, params));
return 1;
}
//------------------------------------------------------------------------
// RealtimeController::luaMakeNil
//------------------------------------------------------------------------
int RealtimeController::luaMakeNil()
{
pushJBoxValue(getCurrentMotherboard()->makeNil());
return 1;
}
//------------------------------------------------------------------------
// RealtimeController::luaIsNativeObject
//------------------------------------------------------------------------
int RealtimeController::luaIsNativeObject()
{
RE_MOCK_ASSERT(lua_gettop(L) == 1, "jbox.is_native_object() expects 1 argument");
auto type = toJBoxValue()->getValueType();
lua_pushboolean(L, type == kJBox_NativeObject || type == kJBox_Nil);
return 1;
}
//------------------------------------------------------------------------
// RealtimeController::luaMakeEmptyBlob
//------------------------------------------------------------------------
int RealtimeController::luaMakeEmptyBlob()
{
pushJBoxValue(getCurrentMotherboard()->makeEmptyBlob());
return 1;
}
//------------------------------------------------------------------------
// RealtimeController::luaIsBlob
//------------------------------------------------------------------------
int RealtimeController::luaIsBlob()
{
RE_MOCK_ASSERT(lua_gettop(L) == 1, "jbox.is_blob() expects 1 argument");
auto type = toJBoxValue()->getValueType();
lua_pushboolean(L, type == kJBox_BLOB);
return 1;
}
//------------------------------------------------------------------------
// RealtimeController::luaLoadBlobAsync
//------------------------------------------------------------------------
int RealtimeController::luaLoadBlobAsync()
{
luaL_checktype(L, 1, LUA_TSTRING);
pushJBoxValue(getCurrentMotherboard()->loadBlobAsync(lua_tostring(L, 1)));
return 1;
}
//------------------------------------------------------------------------
// RealtimeController::luaGetBlobInfo
//------------------------------------------------------------------------
int RealtimeController::luaGetBlobInfo()
{
RE_MOCK_ASSERT(lua_gettop(L) == 1, "jbox.get_blob_info() expects 1 argument");
auto blobValue = toJBoxValue();
lua_newtable(L);
if(blobValue->getValueType() == kJBox_Nil)
L.setTableValue("state", 0);
else
{
auto info = getCurrentMotherboard()->getBLOBInfo(*blobValue);
L.setTableValue("size", info.getSize());
L.setTableValue("resident_size", info.getResidentSize());
L.setTableValue("state", info.fLoadingContext.getStatusAsInt());
}
return 1;
}
//------------------------------------------------------------------------
// RealtimeController::luaIsSample
//------------------------------------------------------------------------
int RealtimeController::luaIsSample()
{
RE_MOCK_ASSERT(lua_gettop(L) == 1, "jbox.is_sample() expects 1 argument");
auto type = toJBoxValue()->getValueType();
lua_pushboolean(L, type == kJBox_Sample);
return 1;
}
//------------------------------------------------------------------------
// RealtimeController::luaMakeEmptySample
//------------------------------------------------------------------------
int RealtimeController::luaMakeEmptySample()
{
pushJBoxValue(getCurrentMotherboard()->makeEmptySample());
return 1;
}
//------------------------------------------------------------------------
// RealtimeController::luaLoadSampleAsync
//------------------------------------------------------------------------
int RealtimeController::luaLoadSampleAsync()
{
luaL_checktype(L, 1, LUA_TSTRING);
pushJBoxValue(getCurrentMotherboard()->loadSampleAsync(lua_tostring(L, 1)));
return 1;
}
//------------------------------------------------------------------------
// RealtimeController::luaGetSampleMetaData
//------------------------------------------------------------------------
int RealtimeController::luaGetSampleInfo()
{
RE_MOCK_ASSERT(lua_gettop(L) == 1, "jbox.get_sample_info() expects 1 argument");
auto sampleValue = toJBoxValue();
lua_newtable(L);
if(sampleValue->getValueType() == kJBox_Nil)
L.setTableValue("state", 0);
else
{
auto metadata = getCurrentMotherboard()->getSampleMetadata(*sampleValue);
auto &md = metadata.fMain;
L.setTableValue("state", metadata.fLoadingContext.getStatusAsInt());
L.setTableValue("frame_count", md.fSpec.fFrameCount);
L.setTableValue("resident_count", md.fResidentFrameCount);
L.setTableValue("channels", md.fSpec.fChannels);
L.setTableValue("sample_rate", md.fSpec.fSampleRate);
}
return 1;
}
//------------------------------------------------------------------------
// RealtimeController::luaGetSampleMetaData
//------------------------------------------------------------------------
int RealtimeController::luaGetSampleMetaData()
{
RE_MOCK_ASSERT(lua_gettop(L) == 1, "jbox.get_sample_metadata() expects 1 argument");
auto sampleValue = toJBoxValue();
lua_newtable(L);
if(sampleValue->getValueType() == kJBox_Nil)
L.setTableValue("load_status", "nil");
else
{
auto metadata = getCurrentMotherboard()->getSampleMetadata(*sampleValue);
auto &md = metadata.fMain;
L.setTableValue("load_status", metadata.fLoadingContext.getStatusAsString());
L.setTableValue("frame_count", md.fSpec.fFrameCount);
L.setTableValue("resident_frame_count", md.fResidentFrameCount);
L.setTableValue("channels", md.fSpec.fChannels);
L.setTableValue("sample_rate", md.fSpec.fSampleRate);
L.setTableValue("sample_name", metadata.getSampleName());
auto ¶ms = metadata.fMain.fParameters;
L.setTableValue("root_key", params.fRootNote);
L.setTableValue("tune_cents", params.fTuneCents);
L.setTableValue("play_range_start", params.fPlayRangeStart);
L.setTableValue("play_range_end", params.fPlayRangeEnd);
L.setTableValue("loop_range_start", params.fLoopRangeStart);
L.setTableValue("loop_range_end", params.fLoopRangeEnd);
L.setTableValue("preview_volume_level", params.fVolumeLevel);
L.setTableValue("loop_mode", metadata.getLoopModeAsString());
}
return 1;
}
//------------------------------------------------------------------------
// RealtimeController::getCurrentMotherboard
//------------------------------------------------------------------------
Motherboard *RealtimeController::getCurrentMotherboard() const
{
RE_MOCK_ASSERT(fMotherboard != nullptr, "Must be called from within a binding only!");
return fMotherboard;
}
//------------------------------------------------------------------------
// RealtimeController::invokeBinding
//------------------------------------------------------------------------
void RealtimeController::invokeBinding(Motherboard *iMotherboard,
std::string const &iBindingName,
std::string const &iSourcePropertyPath,
std::shared_ptr<const JboxValue> const &iNewValue)
{
RE_MOCK_ASSERT(fMotherboard == nullptr, "calling binding from a binding"); // sanity check
RE_MOCK_ASSERT(stl::contains_key(getBindings(), iSourcePropertyPath), "No rtc binding found for property [%s]", iSourcePropertyPath);
RE_MOCK_ASSERT(stl::contains_key(fReverseBindings, iBindingName), "No rtc binding named [%s] found", iBindingName);
RE_MOCK_ASSERT(stl::contains_key(fReverseBindings.at(iBindingName), iSourcePropertyPath), "Property [%s] is not a source for rtc binding [%s]", iSourcePropertyPath, iBindingName);
fMotherboard = iMotherboard;
fCurrentBindingName = iBindingName;
putBindingOnTopOfStack(iBindingName);
lua_pushstring(L, iSourcePropertyPath.c_str());
pushJBoxValue(iNewValue);
auto const res = lua_pcall(L, 2, 0, 0);
if(res != LUA_OK)
{
std::string errorMsg{lua_tostring(L, -1)};
lua_pop(L, 1);
RE_MOCK_ASSERT(res == LUA_OK, "Error executing binding %s(%s, %s) | %s",
iBindingName.c_str(),
iSourcePropertyPath.c_str(),
fMotherboard->toString(*iNewValue).c_str(),
errorMsg.c_str());
}
fCurrentBindingName = "";
fMotherboard = nullptr;
fJboxValues.reset();
}
//------------------------------------------------------------------------
// RealtimeController::getBindings
//------------------------------------------------------------------------
std::map<std::string, std::string> const &RealtimeController::getBindings()
{
if(!fBindings)
{
std::map<std::string, std::string> bindings{};
if(lua_getglobal(L, "rtc_bindings") != LUA_TNIL)
{
auto mapIndex = lua_gettop(L);
luaL_checktype(L, mapIndex, LUA_TTABLE);
auto n = L.getTableSize(mapIndex);
for(int i = 1; i <= n; i++)
{
lua_geti(L, mapIndex, i);
auto source = L.getTableValueAsString("source");
auto dest = L.getTableValueAsString("dest");
RE_MOCK_ASSERT(dest.find("/global_rtc/") == 0, "invalid rtc_binding [%s]", dest);
dest = dest.substr(12); // skip /global_rtc/
putBindingOnTopOfStack(dest); // this will check that the binding exists
lua_pop(L, 1);
bindings[source] = dest;
// also add it to reverse bindings
if(!stl::contains_key(fReverseBindings, dest))
fReverseBindings[dest] = {};
fReverseBindings[dest].emplace(source);
lua_pop(L, 1);
}
}
lua_pop(L, 1);
fBindings = std::move(bindings);
}
return *fBindings;
}
//------------------------------------------------------------------------
// RealtimeController::getRTInputSetupNotify
//------------------------------------------------------------------------
std::set<std::string> RealtimeController::getRTInputSetupNotify()
{
std::set<std::string> res{};
if(lua_getglobal(L, "rt_input_setup") != LUA_TNIL)
{
if(lua_getfield(L, -1, "notify") != LUA_TNIL)
{
auto n = L.getTableSize();
for(int i = 1; i <= n; i++)
{
lua_geti(L, -1, i);
res.emplace(lua_tostring(L, -1));
lua_pop(L, 1);
}
}
lua_pop(L, 1);
}
lua_pop(L, 1);
return res;
}
//------------------------------------------------------------------------
// RealtimeController::putBindingOnTopOfStack
//------------------------------------------------------------------------
void RealtimeController::putBindingOnTopOfStack(std::string const &iBindingName)
{
lua_getglobal(L, "global_rtc");
auto mapIndex = lua_gettop(L);
luaL_checktype(L, mapIndex, LUA_TTABLE);
lua_getfield(L, mapIndex, iBindingName.c_str());
luaL_argexpected(L, lua_type(L, -1) == LUA_TFUNCTION, -1, fmt::printf("/global_rtc/%s", iBindingName).c_str());
lua_remove(L, -2); // remove global_rtc from stack
}
//------------------------------------------------------------------------
// RealtimeController::toJBoxValue
//------------------------------------------------------------------------
std::shared_ptr<const JboxValue> RealtimeController::toJBoxValue(int idx)
{
int t = lua_type(L, idx);
switch(t)
{
case LUA_TBOOLEAN:
return getCurrentMotherboard()->makeBoolean(lua_toboolean(L, idx));
case LUA_TNUMBER:
return getCurrentMotherboard()->makeNumber(lua_tonumber(L, idx));
case LUA_TSTRING:
return getCurrentMotherboard()->makeString(lua_tostring(L, idx));
case LUA_TUSERDATA:
return fJboxValues.get(*reinterpret_cast<int *>(lua_touserdata(L, idx)));
default: /* other values */
return getCurrentMotherboard()->makeNil();
}
}
//------------------------------------------------------------------------
// RealtimeController::pushJBoxValue
//------------------------------------------------------------------------
void RealtimeController::pushJBoxValue(std::shared_ptr<const JboxValue> iJBoxValue)
{
switch(iJBoxValue->getValueType())
{
case kJBox_Nil:
lua_pushnil(L);
break;
case kJBox_Boolean:
lua_pushboolean(L, iJBoxValue->getBoolean());
break;
case kJBox_Number:
lua_pushnumber(L, iJBoxValue->getNumber());
break;
case kJBox_String:
{
lua_pushstring(L, iJBoxValue->getString().fValue.c_str());
break;
}
default:
auto jboxValueUserData = reinterpret_cast<int *>(lua_newuserdata(L, sizeof(int)));
*jboxValueUserData = fJboxValues.add(std::move(iJBoxValue));
break;
}
}
}
|
class TrieNode{
public:
static const int ALPHABET_SIZE = 26;
static const char FIRST_LETTER = 'a';
bool is_terminal_node;
vector<TrieNode*> children;
TrieNode(){
this->is_terminal_node = false;
this->children.resize(ALPHABET_SIZE, NULL);
}
void insert(const string& word){
TrieNode* node = this;
for(char c: word){
short int edge_id = c - FIRST_LETTER;
if(node->children[edge_id] == NULL){
node->children[edge_id] = new TrieNode();
}
node = node->children[edge_id];
}
node->is_terminal_node = true;
}
string extract_root_word(const string& word){
TrieNode* node = this;
for(int i = 0; i < word.length(); ++i){
char c = word[i];
short int edge_id = c - FIRST_LETTER;
if(node->children[edge_id] == NULL){
return word;
}
if(node->children[edge_id]->is_terminal_node){
return word.substr(0, i + 1);
}
node = node->children[edge_id];
}
return word;
}
};
class Solution {
public:
string replaceWords(vector<string>& dict, string sentence) {
TrieNode* trie = new TrieNode();
for(const string& word: dict){
trie->insert(word);
}
string answer;
string word;
for(int prev_pos = 0, pos = 0; pos <= sentence.length(); ++pos){
if(pos == sentence.length() || sentence[pos] == ' '){
word = sentence.substr(prev_pos, pos - prev_pos);
answer += trie->extract_root_word(word) + " ";
prev_pos = pos + 1;
}
}
answer.pop_back(); // remove last space
return answer;
}
};
|
// Copyright (C) 2020 T. Zachary Laine
//
// 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)
// Warning! This file is autogenerated.
#include <boost/text/normalize_string.hpp>
#include <boost/text/transcode_view.hpp>
#include <boost/text/string_utility.hpp>
#include <gtest/gtest.h>
#include <algorithm>
TEST(normalization, nfc_080_000)
{
// 1D76A;1D76A;1D76A;03A5;03A5;
// (𝝪; 𝝪; 𝝪; Υ; Υ; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL UPSILON
{
std::array<uint32_t, 1> const c1 = {{ 0x1D76A }};
std::array<uint32_t, 1> const c2 = {{ 0x1D76A }};
std::array<uint32_t, 1> const c3 = {{ 0x1D76A }};
std::array<uint32_t, 1> const c4 = {{ 0x03A5 }};
std::array<uint32_t, 1> const c5 = {{ 0x03A5 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_001)
{
// 1D76B;1D76B;1D76B;03A6;03A6;
// (𝝫; 𝝫; 𝝫; Φ; Φ; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL PHI
{
std::array<uint32_t, 1> const c1 = {{ 0x1D76B }};
std::array<uint32_t, 1> const c2 = {{ 0x1D76B }};
std::array<uint32_t, 1> const c3 = {{ 0x1D76B }};
std::array<uint32_t, 1> const c4 = {{ 0x03A6 }};
std::array<uint32_t, 1> const c5 = {{ 0x03A6 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_002)
{
// 1D76C;1D76C;1D76C;03A7;03A7;
// (𝝬; 𝝬; 𝝬; Χ; Χ; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL CHI
{
std::array<uint32_t, 1> const c1 = {{ 0x1D76C }};
std::array<uint32_t, 1> const c2 = {{ 0x1D76C }};
std::array<uint32_t, 1> const c3 = {{ 0x1D76C }};
std::array<uint32_t, 1> const c4 = {{ 0x03A7 }};
std::array<uint32_t, 1> const c5 = {{ 0x03A7 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_003)
{
// 1D76D;1D76D;1D76D;03A8;03A8;
// (𝝭; 𝝭; 𝝭; Ψ; Ψ; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL PSI
{
std::array<uint32_t, 1> const c1 = {{ 0x1D76D }};
std::array<uint32_t, 1> const c2 = {{ 0x1D76D }};
std::array<uint32_t, 1> const c3 = {{ 0x1D76D }};
std::array<uint32_t, 1> const c4 = {{ 0x03A8 }};
std::array<uint32_t, 1> const c5 = {{ 0x03A8 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_004)
{
// 1D76E;1D76E;1D76E;03A9;03A9;
// (𝝮; 𝝮; 𝝮; Ω; Ω; ) MATHEMATICAL SANS-SERIF BOLD CAPITAL OMEGA
{
std::array<uint32_t, 1> const c1 = {{ 0x1D76E }};
std::array<uint32_t, 1> const c2 = {{ 0x1D76E }};
std::array<uint32_t, 1> const c3 = {{ 0x1D76E }};
std::array<uint32_t, 1> const c4 = {{ 0x03A9 }};
std::array<uint32_t, 1> const c5 = {{ 0x03A9 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_005)
{
// 1D76F;1D76F;1D76F;2207;2207;
// (𝝯; 𝝯; 𝝯; ∇; ∇; ) MATHEMATICAL SANS-SERIF BOLD NABLA
{
std::array<uint32_t, 1> const c1 = {{ 0x1D76F }};
std::array<uint32_t, 1> const c2 = {{ 0x1D76F }};
std::array<uint32_t, 1> const c3 = {{ 0x1D76F }};
std::array<uint32_t, 1> const c4 = {{ 0x2207 }};
std::array<uint32_t, 1> const c5 = {{ 0x2207 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_006)
{
// 1D770;1D770;1D770;03B1;03B1;
// (𝝰; 𝝰; 𝝰; α; α; ) MATHEMATICAL SANS-SERIF BOLD SMALL ALPHA
{
std::array<uint32_t, 1> const c1 = {{ 0x1D770 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D770 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D770 }};
std::array<uint32_t, 1> const c4 = {{ 0x03B1 }};
std::array<uint32_t, 1> const c5 = {{ 0x03B1 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_007)
{
// 1D771;1D771;1D771;03B2;03B2;
// (𝝱; 𝝱; 𝝱; β; β; ) MATHEMATICAL SANS-SERIF BOLD SMALL BETA
{
std::array<uint32_t, 1> const c1 = {{ 0x1D771 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D771 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D771 }};
std::array<uint32_t, 1> const c4 = {{ 0x03B2 }};
std::array<uint32_t, 1> const c5 = {{ 0x03B2 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_008)
{
// 1D772;1D772;1D772;03B3;03B3;
// (𝝲; 𝝲; 𝝲; γ; γ; ) MATHEMATICAL SANS-SERIF BOLD SMALL GAMMA
{
std::array<uint32_t, 1> const c1 = {{ 0x1D772 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D772 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D772 }};
std::array<uint32_t, 1> const c4 = {{ 0x03B3 }};
std::array<uint32_t, 1> const c5 = {{ 0x03B3 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_009)
{
// 1D773;1D773;1D773;03B4;03B4;
// (𝝳; 𝝳; 𝝳; δ; δ; ) MATHEMATICAL SANS-SERIF BOLD SMALL DELTA
{
std::array<uint32_t, 1> const c1 = {{ 0x1D773 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D773 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D773 }};
std::array<uint32_t, 1> const c4 = {{ 0x03B4 }};
std::array<uint32_t, 1> const c5 = {{ 0x03B4 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_010)
{
// 1D774;1D774;1D774;03B5;03B5;
// (𝝴; 𝝴; 𝝴; ε; ε; ) MATHEMATICAL SANS-SERIF BOLD SMALL EPSILON
{
std::array<uint32_t, 1> const c1 = {{ 0x1D774 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D774 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D774 }};
std::array<uint32_t, 1> const c4 = {{ 0x03B5 }};
std::array<uint32_t, 1> const c5 = {{ 0x03B5 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_011)
{
// 1D775;1D775;1D775;03B6;03B6;
// (𝝵; 𝝵; 𝝵; ζ; ζ; ) MATHEMATICAL SANS-SERIF BOLD SMALL ZETA
{
std::array<uint32_t, 1> const c1 = {{ 0x1D775 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D775 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D775 }};
std::array<uint32_t, 1> const c4 = {{ 0x03B6 }};
std::array<uint32_t, 1> const c5 = {{ 0x03B6 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_012)
{
// 1D776;1D776;1D776;03B7;03B7;
// (𝝶; 𝝶; 𝝶; η; η; ) MATHEMATICAL SANS-SERIF BOLD SMALL ETA
{
std::array<uint32_t, 1> const c1 = {{ 0x1D776 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D776 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D776 }};
std::array<uint32_t, 1> const c4 = {{ 0x03B7 }};
std::array<uint32_t, 1> const c5 = {{ 0x03B7 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_013)
{
// 1D777;1D777;1D777;03B8;03B8;
// (𝝷; 𝝷; 𝝷; θ; θ; ) MATHEMATICAL SANS-SERIF BOLD SMALL THETA
{
std::array<uint32_t, 1> const c1 = {{ 0x1D777 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D777 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D777 }};
std::array<uint32_t, 1> const c4 = {{ 0x03B8 }};
std::array<uint32_t, 1> const c5 = {{ 0x03B8 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_014)
{
// 1D778;1D778;1D778;03B9;03B9;
// (𝝸; 𝝸; 𝝸; ι; ι; ) MATHEMATICAL SANS-SERIF BOLD SMALL IOTA
{
std::array<uint32_t, 1> const c1 = {{ 0x1D778 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D778 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D778 }};
std::array<uint32_t, 1> const c4 = {{ 0x03B9 }};
std::array<uint32_t, 1> const c5 = {{ 0x03B9 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_015)
{
// 1D779;1D779;1D779;03BA;03BA;
// (𝝹; 𝝹; 𝝹; κ; κ; ) MATHEMATICAL SANS-SERIF BOLD SMALL KAPPA
{
std::array<uint32_t, 1> const c1 = {{ 0x1D779 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D779 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D779 }};
std::array<uint32_t, 1> const c4 = {{ 0x03BA }};
std::array<uint32_t, 1> const c5 = {{ 0x03BA }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_016)
{
// 1D77A;1D77A;1D77A;03BB;03BB;
// (𝝺; 𝝺; 𝝺; λ; λ; ) MATHEMATICAL SANS-SERIF BOLD SMALL LAMDA
{
std::array<uint32_t, 1> const c1 = {{ 0x1D77A }};
std::array<uint32_t, 1> const c2 = {{ 0x1D77A }};
std::array<uint32_t, 1> const c3 = {{ 0x1D77A }};
std::array<uint32_t, 1> const c4 = {{ 0x03BB }};
std::array<uint32_t, 1> const c5 = {{ 0x03BB }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_017)
{
// 1D77B;1D77B;1D77B;03BC;03BC;
// (𝝻; 𝝻; 𝝻; μ; μ; ) MATHEMATICAL SANS-SERIF BOLD SMALL MU
{
std::array<uint32_t, 1> const c1 = {{ 0x1D77B }};
std::array<uint32_t, 1> const c2 = {{ 0x1D77B }};
std::array<uint32_t, 1> const c3 = {{ 0x1D77B }};
std::array<uint32_t, 1> const c4 = {{ 0x03BC }};
std::array<uint32_t, 1> const c5 = {{ 0x03BC }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_018)
{
// 1D77C;1D77C;1D77C;03BD;03BD;
// (𝝼; 𝝼; 𝝼; ν; ν; ) MATHEMATICAL SANS-SERIF BOLD SMALL NU
{
std::array<uint32_t, 1> const c1 = {{ 0x1D77C }};
std::array<uint32_t, 1> const c2 = {{ 0x1D77C }};
std::array<uint32_t, 1> const c3 = {{ 0x1D77C }};
std::array<uint32_t, 1> const c4 = {{ 0x03BD }};
std::array<uint32_t, 1> const c5 = {{ 0x03BD }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_019)
{
// 1D77D;1D77D;1D77D;03BE;03BE;
// (𝝽; 𝝽; 𝝽; ξ; ξ; ) MATHEMATICAL SANS-SERIF BOLD SMALL XI
{
std::array<uint32_t, 1> const c1 = {{ 0x1D77D }};
std::array<uint32_t, 1> const c2 = {{ 0x1D77D }};
std::array<uint32_t, 1> const c3 = {{ 0x1D77D }};
std::array<uint32_t, 1> const c4 = {{ 0x03BE }};
std::array<uint32_t, 1> const c5 = {{ 0x03BE }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_020)
{
// 1D77E;1D77E;1D77E;03BF;03BF;
// (𝝾; 𝝾; 𝝾; ο; ο; ) MATHEMATICAL SANS-SERIF BOLD SMALL OMICRON
{
std::array<uint32_t, 1> const c1 = {{ 0x1D77E }};
std::array<uint32_t, 1> const c2 = {{ 0x1D77E }};
std::array<uint32_t, 1> const c3 = {{ 0x1D77E }};
std::array<uint32_t, 1> const c4 = {{ 0x03BF }};
std::array<uint32_t, 1> const c5 = {{ 0x03BF }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_021)
{
// 1D77F;1D77F;1D77F;03C0;03C0;
// (𝝿; 𝝿; 𝝿; π; π; ) MATHEMATICAL SANS-SERIF BOLD SMALL PI
{
std::array<uint32_t, 1> const c1 = {{ 0x1D77F }};
std::array<uint32_t, 1> const c2 = {{ 0x1D77F }};
std::array<uint32_t, 1> const c3 = {{ 0x1D77F }};
std::array<uint32_t, 1> const c4 = {{ 0x03C0 }};
std::array<uint32_t, 1> const c5 = {{ 0x03C0 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_022)
{
// 1D780;1D780;1D780;03C1;03C1;
// (𝞀; 𝞀; 𝞀; ρ; ρ; ) MATHEMATICAL SANS-SERIF BOLD SMALL RHO
{
std::array<uint32_t, 1> const c1 = {{ 0x1D780 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D780 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D780 }};
std::array<uint32_t, 1> const c4 = {{ 0x03C1 }};
std::array<uint32_t, 1> const c5 = {{ 0x03C1 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_023)
{
// 1D781;1D781;1D781;03C2;03C2;
// (𝞁; 𝞁; 𝞁; ς; ς; ) MATHEMATICAL SANS-SERIF BOLD SMALL FINAL SIGMA
{
std::array<uint32_t, 1> const c1 = {{ 0x1D781 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D781 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D781 }};
std::array<uint32_t, 1> const c4 = {{ 0x03C2 }};
std::array<uint32_t, 1> const c5 = {{ 0x03C2 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_024)
{
// 1D782;1D782;1D782;03C3;03C3;
// (𝞂; 𝞂; 𝞂; σ; σ; ) MATHEMATICAL SANS-SERIF BOLD SMALL SIGMA
{
std::array<uint32_t, 1> const c1 = {{ 0x1D782 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D782 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D782 }};
std::array<uint32_t, 1> const c4 = {{ 0x03C3 }};
std::array<uint32_t, 1> const c5 = {{ 0x03C3 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_025)
{
// 1D783;1D783;1D783;03C4;03C4;
// (𝞃; 𝞃; 𝞃; τ; τ; ) MATHEMATICAL SANS-SERIF BOLD SMALL TAU
{
std::array<uint32_t, 1> const c1 = {{ 0x1D783 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D783 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D783 }};
std::array<uint32_t, 1> const c4 = {{ 0x03C4 }};
std::array<uint32_t, 1> const c5 = {{ 0x03C4 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_026)
{
// 1D784;1D784;1D784;03C5;03C5;
// (𝞄; 𝞄; 𝞄; υ; υ; ) MATHEMATICAL SANS-SERIF BOLD SMALL UPSILON
{
std::array<uint32_t, 1> const c1 = {{ 0x1D784 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D784 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D784 }};
std::array<uint32_t, 1> const c4 = {{ 0x03C5 }};
std::array<uint32_t, 1> const c5 = {{ 0x03C5 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_027)
{
// 1D785;1D785;1D785;03C6;03C6;
// (𝞅; 𝞅; 𝞅; φ; φ; ) MATHEMATICAL SANS-SERIF BOLD SMALL PHI
{
std::array<uint32_t, 1> const c1 = {{ 0x1D785 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D785 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D785 }};
std::array<uint32_t, 1> const c4 = {{ 0x03C6 }};
std::array<uint32_t, 1> const c5 = {{ 0x03C6 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_028)
{
// 1D786;1D786;1D786;03C7;03C7;
// (𝞆; 𝞆; 𝞆; χ; χ; ) MATHEMATICAL SANS-SERIF BOLD SMALL CHI
{
std::array<uint32_t, 1> const c1 = {{ 0x1D786 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D786 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D786 }};
std::array<uint32_t, 1> const c4 = {{ 0x03C7 }};
std::array<uint32_t, 1> const c5 = {{ 0x03C7 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_029)
{
// 1D787;1D787;1D787;03C8;03C8;
// (𝞇; 𝞇; 𝞇; ψ; ψ; ) MATHEMATICAL SANS-SERIF BOLD SMALL PSI
{
std::array<uint32_t, 1> const c1 = {{ 0x1D787 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D787 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D787 }};
std::array<uint32_t, 1> const c4 = {{ 0x03C8 }};
std::array<uint32_t, 1> const c5 = {{ 0x03C8 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_030)
{
// 1D788;1D788;1D788;03C9;03C9;
// (𝞈; 𝞈; 𝞈; ω; ω; ) MATHEMATICAL SANS-SERIF BOLD SMALL OMEGA
{
std::array<uint32_t, 1> const c1 = {{ 0x1D788 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D788 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D788 }};
std::array<uint32_t, 1> const c4 = {{ 0x03C9 }};
std::array<uint32_t, 1> const c5 = {{ 0x03C9 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_031)
{
// 1D789;1D789;1D789;2202;2202;
// (𝞉; 𝞉; 𝞉; ∂; ∂; ) MATHEMATICAL SANS-SERIF BOLD PARTIAL DIFFERENTIAL
{
std::array<uint32_t, 1> const c1 = {{ 0x1D789 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D789 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D789 }};
std::array<uint32_t, 1> const c4 = {{ 0x2202 }};
std::array<uint32_t, 1> const c5 = {{ 0x2202 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_032)
{
// 1D78A;1D78A;1D78A;03B5;03B5;
// (𝞊; 𝞊; 𝞊; ε; ε; ) MATHEMATICAL SANS-SERIF BOLD EPSILON SYMBOL
{
std::array<uint32_t, 1> const c1 = {{ 0x1D78A }};
std::array<uint32_t, 1> const c2 = {{ 0x1D78A }};
std::array<uint32_t, 1> const c3 = {{ 0x1D78A }};
std::array<uint32_t, 1> const c4 = {{ 0x03B5 }};
std::array<uint32_t, 1> const c5 = {{ 0x03B5 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_033)
{
// 1D78B;1D78B;1D78B;03B8;03B8;
// (𝞋; 𝞋; 𝞋; θ; θ; ) MATHEMATICAL SANS-SERIF BOLD THETA SYMBOL
{
std::array<uint32_t, 1> const c1 = {{ 0x1D78B }};
std::array<uint32_t, 1> const c2 = {{ 0x1D78B }};
std::array<uint32_t, 1> const c3 = {{ 0x1D78B }};
std::array<uint32_t, 1> const c4 = {{ 0x03B8 }};
std::array<uint32_t, 1> const c5 = {{ 0x03B8 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_034)
{
// 1D78C;1D78C;1D78C;03BA;03BA;
// (𝞌; 𝞌; 𝞌; κ; κ; ) MATHEMATICAL SANS-SERIF BOLD KAPPA SYMBOL
{
std::array<uint32_t, 1> const c1 = {{ 0x1D78C }};
std::array<uint32_t, 1> const c2 = {{ 0x1D78C }};
std::array<uint32_t, 1> const c3 = {{ 0x1D78C }};
std::array<uint32_t, 1> const c4 = {{ 0x03BA }};
std::array<uint32_t, 1> const c5 = {{ 0x03BA }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_035)
{
// 1D78D;1D78D;1D78D;03C6;03C6;
// (𝞍; 𝞍; 𝞍; φ; φ; ) MATHEMATICAL SANS-SERIF BOLD PHI SYMBOL
{
std::array<uint32_t, 1> const c1 = {{ 0x1D78D }};
std::array<uint32_t, 1> const c2 = {{ 0x1D78D }};
std::array<uint32_t, 1> const c3 = {{ 0x1D78D }};
std::array<uint32_t, 1> const c4 = {{ 0x03C6 }};
std::array<uint32_t, 1> const c5 = {{ 0x03C6 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_036)
{
// 1D78E;1D78E;1D78E;03C1;03C1;
// (𝞎; 𝞎; 𝞎; ρ; ρ; ) MATHEMATICAL SANS-SERIF BOLD RHO SYMBOL
{
std::array<uint32_t, 1> const c1 = {{ 0x1D78E }};
std::array<uint32_t, 1> const c2 = {{ 0x1D78E }};
std::array<uint32_t, 1> const c3 = {{ 0x1D78E }};
std::array<uint32_t, 1> const c4 = {{ 0x03C1 }};
std::array<uint32_t, 1> const c5 = {{ 0x03C1 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_037)
{
// 1D78F;1D78F;1D78F;03C0;03C0;
// (𝞏; 𝞏; 𝞏; π; π; ) MATHEMATICAL SANS-SERIF BOLD PI SYMBOL
{
std::array<uint32_t, 1> const c1 = {{ 0x1D78F }};
std::array<uint32_t, 1> const c2 = {{ 0x1D78F }};
std::array<uint32_t, 1> const c3 = {{ 0x1D78F }};
std::array<uint32_t, 1> const c4 = {{ 0x03C0 }};
std::array<uint32_t, 1> const c5 = {{ 0x03C0 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_038)
{
// 1D790;1D790;1D790;0391;0391;
// (𝞐; 𝞐; 𝞐; Α; Α; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL ALPHA
{
std::array<uint32_t, 1> const c1 = {{ 0x1D790 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D790 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D790 }};
std::array<uint32_t, 1> const c4 = {{ 0x0391 }};
std::array<uint32_t, 1> const c5 = {{ 0x0391 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_039)
{
// 1D791;1D791;1D791;0392;0392;
// (𝞑; 𝞑; 𝞑; Β; Β; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL BETA
{
std::array<uint32_t, 1> const c1 = {{ 0x1D791 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D791 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D791 }};
std::array<uint32_t, 1> const c4 = {{ 0x0392 }};
std::array<uint32_t, 1> const c5 = {{ 0x0392 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_040)
{
// 1D792;1D792;1D792;0393;0393;
// (𝞒; 𝞒; 𝞒; Γ; Γ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL GAMMA
{
std::array<uint32_t, 1> const c1 = {{ 0x1D792 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D792 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D792 }};
std::array<uint32_t, 1> const c4 = {{ 0x0393 }};
std::array<uint32_t, 1> const c5 = {{ 0x0393 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_041)
{
// 1D793;1D793;1D793;0394;0394;
// (𝞓; 𝞓; 𝞓; Δ; Δ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL DELTA
{
std::array<uint32_t, 1> const c1 = {{ 0x1D793 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D793 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D793 }};
std::array<uint32_t, 1> const c4 = {{ 0x0394 }};
std::array<uint32_t, 1> const c5 = {{ 0x0394 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_042)
{
// 1D794;1D794;1D794;0395;0395;
// (𝞔; 𝞔; 𝞔; Ε; Ε; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL EPSILON
{
std::array<uint32_t, 1> const c1 = {{ 0x1D794 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D794 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D794 }};
std::array<uint32_t, 1> const c4 = {{ 0x0395 }};
std::array<uint32_t, 1> const c5 = {{ 0x0395 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_043)
{
// 1D795;1D795;1D795;0396;0396;
// (𝞕; 𝞕; 𝞕; Ζ; Ζ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL ZETA
{
std::array<uint32_t, 1> const c1 = {{ 0x1D795 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D795 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D795 }};
std::array<uint32_t, 1> const c4 = {{ 0x0396 }};
std::array<uint32_t, 1> const c5 = {{ 0x0396 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_044)
{
// 1D796;1D796;1D796;0397;0397;
// (𝞖; 𝞖; 𝞖; Η; Η; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL ETA
{
std::array<uint32_t, 1> const c1 = {{ 0x1D796 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D796 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D796 }};
std::array<uint32_t, 1> const c4 = {{ 0x0397 }};
std::array<uint32_t, 1> const c5 = {{ 0x0397 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_045)
{
// 1D797;1D797;1D797;0398;0398;
// (𝞗; 𝞗; 𝞗; Θ; Θ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL THETA
{
std::array<uint32_t, 1> const c1 = {{ 0x1D797 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D797 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D797 }};
std::array<uint32_t, 1> const c4 = {{ 0x0398 }};
std::array<uint32_t, 1> const c5 = {{ 0x0398 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_046)
{
// 1D798;1D798;1D798;0399;0399;
// (𝞘; 𝞘; 𝞘; Ι; Ι; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL IOTA
{
std::array<uint32_t, 1> const c1 = {{ 0x1D798 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D798 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D798 }};
std::array<uint32_t, 1> const c4 = {{ 0x0399 }};
std::array<uint32_t, 1> const c5 = {{ 0x0399 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_047)
{
// 1D799;1D799;1D799;039A;039A;
// (𝞙; 𝞙; 𝞙; Κ; Κ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL KAPPA
{
std::array<uint32_t, 1> const c1 = {{ 0x1D799 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D799 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D799 }};
std::array<uint32_t, 1> const c4 = {{ 0x039A }};
std::array<uint32_t, 1> const c5 = {{ 0x039A }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_048)
{
// 1D79A;1D79A;1D79A;039B;039B;
// (𝞚; 𝞚; 𝞚; Λ; Λ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL LAMDA
{
std::array<uint32_t, 1> const c1 = {{ 0x1D79A }};
std::array<uint32_t, 1> const c2 = {{ 0x1D79A }};
std::array<uint32_t, 1> const c3 = {{ 0x1D79A }};
std::array<uint32_t, 1> const c4 = {{ 0x039B }};
std::array<uint32_t, 1> const c5 = {{ 0x039B }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_049)
{
// 1D79B;1D79B;1D79B;039C;039C;
// (𝞛; 𝞛; 𝞛; Μ; Μ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL MU
{
std::array<uint32_t, 1> const c1 = {{ 0x1D79B }};
std::array<uint32_t, 1> const c2 = {{ 0x1D79B }};
std::array<uint32_t, 1> const c3 = {{ 0x1D79B }};
std::array<uint32_t, 1> const c4 = {{ 0x039C }};
std::array<uint32_t, 1> const c5 = {{ 0x039C }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_050)
{
// 1D79C;1D79C;1D79C;039D;039D;
// (𝞜; 𝞜; 𝞜; Ν; Ν; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL NU
{
std::array<uint32_t, 1> const c1 = {{ 0x1D79C }};
std::array<uint32_t, 1> const c2 = {{ 0x1D79C }};
std::array<uint32_t, 1> const c3 = {{ 0x1D79C }};
std::array<uint32_t, 1> const c4 = {{ 0x039D }};
std::array<uint32_t, 1> const c5 = {{ 0x039D }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_051)
{
// 1D79D;1D79D;1D79D;039E;039E;
// (𝞝; 𝞝; 𝞝; Ξ; Ξ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL XI
{
std::array<uint32_t, 1> const c1 = {{ 0x1D79D }};
std::array<uint32_t, 1> const c2 = {{ 0x1D79D }};
std::array<uint32_t, 1> const c3 = {{ 0x1D79D }};
std::array<uint32_t, 1> const c4 = {{ 0x039E }};
std::array<uint32_t, 1> const c5 = {{ 0x039E }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_052)
{
// 1D79E;1D79E;1D79E;039F;039F;
// (𝞞; 𝞞; 𝞞; Ο; Ο; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL OMICRON
{
std::array<uint32_t, 1> const c1 = {{ 0x1D79E }};
std::array<uint32_t, 1> const c2 = {{ 0x1D79E }};
std::array<uint32_t, 1> const c3 = {{ 0x1D79E }};
std::array<uint32_t, 1> const c4 = {{ 0x039F }};
std::array<uint32_t, 1> const c5 = {{ 0x039F }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_053)
{
// 1D79F;1D79F;1D79F;03A0;03A0;
// (𝞟; 𝞟; 𝞟; Π; Π; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL PI
{
std::array<uint32_t, 1> const c1 = {{ 0x1D79F }};
std::array<uint32_t, 1> const c2 = {{ 0x1D79F }};
std::array<uint32_t, 1> const c3 = {{ 0x1D79F }};
std::array<uint32_t, 1> const c4 = {{ 0x03A0 }};
std::array<uint32_t, 1> const c5 = {{ 0x03A0 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_054)
{
// 1D7A0;1D7A0;1D7A0;03A1;03A1;
// (𝞠; 𝞠; 𝞠; Ρ; Ρ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL RHO
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7A0 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7A0 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7A0 }};
std::array<uint32_t, 1> const c4 = {{ 0x03A1 }};
std::array<uint32_t, 1> const c5 = {{ 0x03A1 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_055)
{
// 1D7A1;1D7A1;1D7A1;0398;0398;
// (𝞡; 𝞡; 𝞡; Θ; Θ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL THETA SYMBOL
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7A1 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7A1 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7A1 }};
std::array<uint32_t, 1> const c4 = {{ 0x0398 }};
std::array<uint32_t, 1> const c5 = {{ 0x0398 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_056)
{
// 1D7A2;1D7A2;1D7A2;03A3;03A3;
// (𝞢; 𝞢; 𝞢; Σ; Σ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL SIGMA
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7A2 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7A2 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7A2 }};
std::array<uint32_t, 1> const c4 = {{ 0x03A3 }};
std::array<uint32_t, 1> const c5 = {{ 0x03A3 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_057)
{
// 1D7A3;1D7A3;1D7A3;03A4;03A4;
// (𝞣; 𝞣; 𝞣; Τ; Τ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL TAU
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7A3 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7A3 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7A3 }};
std::array<uint32_t, 1> const c4 = {{ 0x03A4 }};
std::array<uint32_t, 1> const c5 = {{ 0x03A4 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_058)
{
// 1D7A4;1D7A4;1D7A4;03A5;03A5;
// (𝞤; 𝞤; 𝞤; Υ; Υ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL UPSILON
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7A4 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7A4 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7A4 }};
std::array<uint32_t, 1> const c4 = {{ 0x03A5 }};
std::array<uint32_t, 1> const c5 = {{ 0x03A5 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_059)
{
// 1D7A5;1D7A5;1D7A5;03A6;03A6;
// (𝞥; 𝞥; 𝞥; Φ; Φ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL PHI
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7A5 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7A5 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7A5 }};
std::array<uint32_t, 1> const c4 = {{ 0x03A6 }};
std::array<uint32_t, 1> const c5 = {{ 0x03A6 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_060)
{
// 1D7A6;1D7A6;1D7A6;03A7;03A7;
// (𝞦; 𝞦; 𝞦; Χ; Χ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL CHI
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7A6 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7A6 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7A6 }};
std::array<uint32_t, 1> const c4 = {{ 0x03A7 }};
std::array<uint32_t, 1> const c5 = {{ 0x03A7 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_061)
{
// 1D7A7;1D7A7;1D7A7;03A8;03A8;
// (𝞧; 𝞧; 𝞧; Ψ; Ψ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL PSI
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7A7 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7A7 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7A7 }};
std::array<uint32_t, 1> const c4 = {{ 0x03A8 }};
std::array<uint32_t, 1> const c5 = {{ 0x03A8 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_062)
{
// 1D7A8;1D7A8;1D7A8;03A9;03A9;
// (𝞨; 𝞨; 𝞨; Ω; Ω; ) MATHEMATICAL SANS-SERIF BOLD ITALIC CAPITAL OMEGA
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7A8 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7A8 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7A8 }};
std::array<uint32_t, 1> const c4 = {{ 0x03A9 }};
std::array<uint32_t, 1> const c5 = {{ 0x03A9 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_063)
{
// 1D7A9;1D7A9;1D7A9;2207;2207;
// (𝞩; 𝞩; 𝞩; ∇; ∇; ) MATHEMATICAL SANS-SERIF BOLD ITALIC NABLA
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7A9 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7A9 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7A9 }};
std::array<uint32_t, 1> const c4 = {{ 0x2207 }};
std::array<uint32_t, 1> const c5 = {{ 0x2207 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_064)
{
// 1D7AA;1D7AA;1D7AA;03B1;03B1;
// (𝞪; 𝞪; 𝞪; α; α; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL ALPHA
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7AA }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7AA }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7AA }};
std::array<uint32_t, 1> const c4 = {{ 0x03B1 }};
std::array<uint32_t, 1> const c5 = {{ 0x03B1 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_065)
{
// 1D7AB;1D7AB;1D7AB;03B2;03B2;
// (𝞫; 𝞫; 𝞫; β; β; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL BETA
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7AB }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7AB }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7AB }};
std::array<uint32_t, 1> const c4 = {{ 0x03B2 }};
std::array<uint32_t, 1> const c5 = {{ 0x03B2 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_066)
{
// 1D7AC;1D7AC;1D7AC;03B3;03B3;
// (𝞬; 𝞬; 𝞬; γ; γ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL GAMMA
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7AC }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7AC }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7AC }};
std::array<uint32_t, 1> const c4 = {{ 0x03B3 }};
std::array<uint32_t, 1> const c5 = {{ 0x03B3 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_067)
{
// 1D7AD;1D7AD;1D7AD;03B4;03B4;
// (𝞭; 𝞭; 𝞭; δ; δ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL DELTA
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7AD }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7AD }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7AD }};
std::array<uint32_t, 1> const c4 = {{ 0x03B4 }};
std::array<uint32_t, 1> const c5 = {{ 0x03B4 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_068)
{
// 1D7AE;1D7AE;1D7AE;03B5;03B5;
// (𝞮; 𝞮; 𝞮; ε; ε; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL EPSILON
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7AE }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7AE }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7AE }};
std::array<uint32_t, 1> const c4 = {{ 0x03B5 }};
std::array<uint32_t, 1> const c5 = {{ 0x03B5 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_069)
{
// 1D7AF;1D7AF;1D7AF;03B6;03B6;
// (𝞯; 𝞯; 𝞯; ζ; ζ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL ZETA
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7AF }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7AF }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7AF }};
std::array<uint32_t, 1> const c4 = {{ 0x03B6 }};
std::array<uint32_t, 1> const c5 = {{ 0x03B6 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_070)
{
// 1D7B0;1D7B0;1D7B0;03B7;03B7;
// (𝞰; 𝞰; 𝞰; η; η; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL ETA
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7B0 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7B0 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7B0 }};
std::array<uint32_t, 1> const c4 = {{ 0x03B7 }};
std::array<uint32_t, 1> const c5 = {{ 0x03B7 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_071)
{
// 1D7B1;1D7B1;1D7B1;03B8;03B8;
// (𝞱; 𝞱; 𝞱; θ; θ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL THETA
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7B1 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7B1 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7B1 }};
std::array<uint32_t, 1> const c4 = {{ 0x03B8 }};
std::array<uint32_t, 1> const c5 = {{ 0x03B8 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_072)
{
// 1D7B2;1D7B2;1D7B2;03B9;03B9;
// (𝞲; 𝞲; 𝞲; ι; ι; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL IOTA
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7B2 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7B2 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7B2 }};
std::array<uint32_t, 1> const c4 = {{ 0x03B9 }};
std::array<uint32_t, 1> const c5 = {{ 0x03B9 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_073)
{
// 1D7B3;1D7B3;1D7B3;03BA;03BA;
// (𝞳; 𝞳; 𝞳; κ; κ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL KAPPA
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7B3 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7B3 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7B3 }};
std::array<uint32_t, 1> const c4 = {{ 0x03BA }};
std::array<uint32_t, 1> const c5 = {{ 0x03BA }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_074)
{
// 1D7B4;1D7B4;1D7B4;03BB;03BB;
// (𝞴; 𝞴; 𝞴; λ; λ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL LAMDA
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7B4 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7B4 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7B4 }};
std::array<uint32_t, 1> const c4 = {{ 0x03BB }};
std::array<uint32_t, 1> const c5 = {{ 0x03BB }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_075)
{
// 1D7B5;1D7B5;1D7B5;03BC;03BC;
// (𝞵; 𝞵; 𝞵; μ; μ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL MU
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7B5 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7B5 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7B5 }};
std::array<uint32_t, 1> const c4 = {{ 0x03BC }};
std::array<uint32_t, 1> const c5 = {{ 0x03BC }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_076)
{
// 1D7B6;1D7B6;1D7B6;03BD;03BD;
// (𝞶; 𝞶; 𝞶; ν; ν; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL NU
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7B6 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7B6 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7B6 }};
std::array<uint32_t, 1> const c4 = {{ 0x03BD }};
std::array<uint32_t, 1> const c5 = {{ 0x03BD }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_077)
{
// 1D7B7;1D7B7;1D7B7;03BE;03BE;
// (𝞷; 𝞷; 𝞷; ξ; ξ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL XI
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7B7 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7B7 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7B7 }};
std::array<uint32_t, 1> const c4 = {{ 0x03BE }};
std::array<uint32_t, 1> const c5 = {{ 0x03BE }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_078)
{
// 1D7B8;1D7B8;1D7B8;03BF;03BF;
// (𝞸; 𝞸; 𝞸; ο; ο; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL OMICRON
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7B8 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7B8 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7B8 }};
std::array<uint32_t, 1> const c4 = {{ 0x03BF }};
std::array<uint32_t, 1> const c5 = {{ 0x03BF }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_079)
{
// 1D7B9;1D7B9;1D7B9;03C0;03C0;
// (𝞹; 𝞹; 𝞹; π; π; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL PI
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7B9 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7B9 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7B9 }};
std::array<uint32_t, 1> const c4 = {{ 0x03C0 }};
std::array<uint32_t, 1> const c5 = {{ 0x03C0 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_080)
{
// 1D7BA;1D7BA;1D7BA;03C1;03C1;
// (𝞺; 𝞺; 𝞺; ρ; ρ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL RHO
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7BA }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7BA }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7BA }};
std::array<uint32_t, 1> const c4 = {{ 0x03C1 }};
std::array<uint32_t, 1> const c5 = {{ 0x03C1 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_081)
{
// 1D7BB;1D7BB;1D7BB;03C2;03C2;
// (𝞻; 𝞻; 𝞻; ς; ς; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL FINAL SIGMA
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7BB }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7BB }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7BB }};
std::array<uint32_t, 1> const c4 = {{ 0x03C2 }};
std::array<uint32_t, 1> const c5 = {{ 0x03C2 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_082)
{
// 1D7BC;1D7BC;1D7BC;03C3;03C3;
// (𝞼; 𝞼; 𝞼; σ; σ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL SIGMA
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7BC }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7BC }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7BC }};
std::array<uint32_t, 1> const c4 = {{ 0x03C3 }};
std::array<uint32_t, 1> const c5 = {{ 0x03C3 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_083)
{
// 1D7BD;1D7BD;1D7BD;03C4;03C4;
// (𝞽; 𝞽; 𝞽; τ; τ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL TAU
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7BD }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7BD }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7BD }};
std::array<uint32_t, 1> const c4 = {{ 0x03C4 }};
std::array<uint32_t, 1> const c5 = {{ 0x03C4 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_084)
{
// 1D7BE;1D7BE;1D7BE;03C5;03C5;
// (𝞾; 𝞾; 𝞾; υ; υ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL UPSILON
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7BE }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7BE }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7BE }};
std::array<uint32_t, 1> const c4 = {{ 0x03C5 }};
std::array<uint32_t, 1> const c5 = {{ 0x03C5 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_085)
{
// 1D7BF;1D7BF;1D7BF;03C6;03C6;
// (𝞿; 𝞿; 𝞿; φ; φ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL PHI
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7BF }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7BF }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7BF }};
std::array<uint32_t, 1> const c4 = {{ 0x03C6 }};
std::array<uint32_t, 1> const c5 = {{ 0x03C6 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_086)
{
// 1D7C0;1D7C0;1D7C0;03C7;03C7;
// (𝟀; 𝟀; 𝟀; χ; χ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL CHI
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7C0 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7C0 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7C0 }};
std::array<uint32_t, 1> const c4 = {{ 0x03C7 }};
std::array<uint32_t, 1> const c5 = {{ 0x03C7 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_087)
{
// 1D7C1;1D7C1;1D7C1;03C8;03C8;
// (𝟁; 𝟁; 𝟁; ψ; ψ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL PSI
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7C1 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7C1 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7C1 }};
std::array<uint32_t, 1> const c4 = {{ 0x03C8 }};
std::array<uint32_t, 1> const c5 = {{ 0x03C8 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_088)
{
// 1D7C2;1D7C2;1D7C2;03C9;03C9;
// (𝟂; 𝟂; 𝟂; ω; ω; ) MATHEMATICAL SANS-SERIF BOLD ITALIC SMALL OMEGA
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7C2 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7C2 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7C2 }};
std::array<uint32_t, 1> const c4 = {{ 0x03C9 }};
std::array<uint32_t, 1> const c5 = {{ 0x03C9 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_089)
{
// 1D7C3;1D7C3;1D7C3;2202;2202;
// (𝟃; 𝟃; 𝟃; ∂; ∂; ) MATHEMATICAL SANS-SERIF BOLD ITALIC PARTIAL DIFFERENTIAL
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7C3 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7C3 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7C3 }};
std::array<uint32_t, 1> const c4 = {{ 0x2202 }};
std::array<uint32_t, 1> const c5 = {{ 0x2202 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_090)
{
// 1D7C4;1D7C4;1D7C4;03B5;03B5;
// (𝟄; 𝟄; 𝟄; ε; ε; ) MATHEMATICAL SANS-SERIF BOLD ITALIC EPSILON SYMBOL
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7C4 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7C4 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7C4 }};
std::array<uint32_t, 1> const c4 = {{ 0x03B5 }};
std::array<uint32_t, 1> const c5 = {{ 0x03B5 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_091)
{
// 1D7C5;1D7C5;1D7C5;03B8;03B8;
// (𝟅; 𝟅; 𝟅; θ; θ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC THETA SYMBOL
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7C5 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7C5 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7C5 }};
std::array<uint32_t, 1> const c4 = {{ 0x03B8 }};
std::array<uint32_t, 1> const c5 = {{ 0x03B8 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_092)
{
// 1D7C6;1D7C6;1D7C6;03BA;03BA;
// (𝟆; 𝟆; 𝟆; κ; κ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC KAPPA SYMBOL
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7C6 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7C6 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7C6 }};
std::array<uint32_t, 1> const c4 = {{ 0x03BA }};
std::array<uint32_t, 1> const c5 = {{ 0x03BA }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_093)
{
// 1D7C7;1D7C7;1D7C7;03C6;03C6;
// (𝟇; 𝟇; 𝟇; φ; φ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC PHI SYMBOL
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7C7 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7C7 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7C7 }};
std::array<uint32_t, 1> const c4 = {{ 0x03C6 }};
std::array<uint32_t, 1> const c5 = {{ 0x03C6 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_094)
{
// 1D7C8;1D7C8;1D7C8;03C1;03C1;
// (𝟈; 𝟈; 𝟈; ρ; ρ; ) MATHEMATICAL SANS-SERIF BOLD ITALIC RHO SYMBOL
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7C8 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7C8 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7C8 }};
std::array<uint32_t, 1> const c4 = {{ 0x03C1 }};
std::array<uint32_t, 1> const c5 = {{ 0x03C1 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_095)
{
// 1D7C9;1D7C9;1D7C9;03C0;03C0;
// (𝟉; 𝟉; 𝟉; π; π; ) MATHEMATICAL SANS-SERIF BOLD ITALIC PI SYMBOL
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7C9 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7C9 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7C9 }};
std::array<uint32_t, 1> const c4 = {{ 0x03C0 }};
std::array<uint32_t, 1> const c5 = {{ 0x03C0 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_096)
{
// 1D7CA;1D7CA;1D7CA;03DC;03DC;
// (𝟊; 𝟊; 𝟊; Ϝ; Ϝ; ) MATHEMATICAL BOLD CAPITAL DIGAMMA
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7CA }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7CA }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7CA }};
std::array<uint32_t, 1> const c4 = {{ 0x03DC }};
std::array<uint32_t, 1> const c5 = {{ 0x03DC }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_097)
{
// 1D7CB;1D7CB;1D7CB;03DD;03DD;
// (𝟋; 𝟋; 𝟋; ϝ; ϝ; ) MATHEMATICAL BOLD SMALL DIGAMMA
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7CB }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7CB }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7CB }};
std::array<uint32_t, 1> const c4 = {{ 0x03DD }};
std::array<uint32_t, 1> const c5 = {{ 0x03DD }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_098)
{
// 1D7CE;1D7CE;1D7CE;0030;0030;
// (𝟎; 𝟎; 𝟎; 0; 0; ) MATHEMATICAL BOLD DIGIT ZERO
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7CE }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7CE }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7CE }};
std::array<uint32_t, 1> const c4 = {{ 0x0030 }};
std::array<uint32_t, 1> const c5 = {{ 0x0030 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_099)
{
// 1D7CF;1D7CF;1D7CF;0031;0031;
// (𝟏; 𝟏; 𝟏; 1; 1; ) MATHEMATICAL BOLD DIGIT ONE
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7CF }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7CF }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7CF }};
std::array<uint32_t, 1> const c4 = {{ 0x0031 }};
std::array<uint32_t, 1> const c5 = {{ 0x0031 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_100)
{
// 1D7D0;1D7D0;1D7D0;0032;0032;
// (𝟐; 𝟐; 𝟐; 2; 2; ) MATHEMATICAL BOLD DIGIT TWO
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7D0 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7D0 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7D0 }};
std::array<uint32_t, 1> const c4 = {{ 0x0032 }};
std::array<uint32_t, 1> const c5 = {{ 0x0032 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_101)
{
// 1D7D1;1D7D1;1D7D1;0033;0033;
// (𝟑; 𝟑; 𝟑; 3; 3; ) MATHEMATICAL BOLD DIGIT THREE
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7D1 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7D1 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7D1 }};
std::array<uint32_t, 1> const c4 = {{ 0x0033 }};
std::array<uint32_t, 1> const c5 = {{ 0x0033 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_102)
{
// 1D7D2;1D7D2;1D7D2;0034;0034;
// (𝟒; 𝟒; 𝟒; 4; 4; ) MATHEMATICAL BOLD DIGIT FOUR
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7D2 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7D2 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7D2 }};
std::array<uint32_t, 1> const c4 = {{ 0x0034 }};
std::array<uint32_t, 1> const c5 = {{ 0x0034 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_103)
{
// 1D7D3;1D7D3;1D7D3;0035;0035;
// (𝟓; 𝟓; 𝟓; 5; 5; ) MATHEMATICAL BOLD DIGIT FIVE
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7D3 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7D3 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7D3 }};
std::array<uint32_t, 1> const c4 = {{ 0x0035 }};
std::array<uint32_t, 1> const c5 = {{ 0x0035 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_104)
{
// 1D7D4;1D7D4;1D7D4;0036;0036;
// (𝟔; 𝟔; 𝟔; 6; 6; ) MATHEMATICAL BOLD DIGIT SIX
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7D4 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7D4 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7D4 }};
std::array<uint32_t, 1> const c4 = {{ 0x0036 }};
std::array<uint32_t, 1> const c5 = {{ 0x0036 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_105)
{
// 1D7D5;1D7D5;1D7D5;0037;0037;
// (𝟕; 𝟕; 𝟕; 7; 7; ) MATHEMATICAL BOLD DIGIT SEVEN
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7D5 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7D5 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7D5 }};
std::array<uint32_t, 1> const c4 = {{ 0x0037 }};
std::array<uint32_t, 1> const c5 = {{ 0x0037 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_106)
{
// 1D7D6;1D7D6;1D7D6;0038;0038;
// (𝟖; 𝟖; 𝟖; 8; 8; ) MATHEMATICAL BOLD DIGIT EIGHT
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7D6 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7D6 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7D6 }};
std::array<uint32_t, 1> const c4 = {{ 0x0038 }};
std::array<uint32_t, 1> const c5 = {{ 0x0038 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_107)
{
// 1D7D7;1D7D7;1D7D7;0039;0039;
// (𝟗; 𝟗; 𝟗; 9; 9; ) MATHEMATICAL BOLD DIGIT NINE
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7D7 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7D7 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7D7 }};
std::array<uint32_t, 1> const c4 = {{ 0x0039 }};
std::array<uint32_t, 1> const c5 = {{ 0x0039 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_108)
{
// 1D7D8;1D7D8;1D7D8;0030;0030;
// (𝟘; 𝟘; 𝟘; 0; 0; ) MATHEMATICAL DOUBLE-STRUCK DIGIT ZERO
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7D8 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7D8 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7D8 }};
std::array<uint32_t, 1> const c4 = {{ 0x0030 }};
std::array<uint32_t, 1> const c5 = {{ 0x0030 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_109)
{
// 1D7D9;1D7D9;1D7D9;0031;0031;
// (𝟙; 𝟙; 𝟙; 1; 1; ) MATHEMATICAL DOUBLE-STRUCK DIGIT ONE
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7D9 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7D9 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7D9 }};
std::array<uint32_t, 1> const c4 = {{ 0x0031 }};
std::array<uint32_t, 1> const c5 = {{ 0x0031 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_110)
{
// 1D7DA;1D7DA;1D7DA;0032;0032;
// (𝟚; 𝟚; 𝟚; 2; 2; ) MATHEMATICAL DOUBLE-STRUCK DIGIT TWO
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7DA }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7DA }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7DA }};
std::array<uint32_t, 1> const c4 = {{ 0x0032 }};
std::array<uint32_t, 1> const c5 = {{ 0x0032 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_111)
{
// 1D7DB;1D7DB;1D7DB;0033;0033;
// (𝟛; 𝟛; 𝟛; 3; 3; ) MATHEMATICAL DOUBLE-STRUCK DIGIT THREE
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7DB }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7DB }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7DB }};
std::array<uint32_t, 1> const c4 = {{ 0x0033 }};
std::array<uint32_t, 1> const c5 = {{ 0x0033 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_112)
{
// 1D7DC;1D7DC;1D7DC;0034;0034;
// (𝟜; 𝟜; 𝟜; 4; 4; ) MATHEMATICAL DOUBLE-STRUCK DIGIT FOUR
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7DC }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7DC }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7DC }};
std::array<uint32_t, 1> const c4 = {{ 0x0034 }};
std::array<uint32_t, 1> const c5 = {{ 0x0034 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_113)
{
// 1D7DD;1D7DD;1D7DD;0035;0035;
// (𝟝; 𝟝; 𝟝; 5; 5; ) MATHEMATICAL DOUBLE-STRUCK DIGIT FIVE
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7DD }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7DD }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7DD }};
std::array<uint32_t, 1> const c4 = {{ 0x0035 }};
std::array<uint32_t, 1> const c5 = {{ 0x0035 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_114)
{
// 1D7DE;1D7DE;1D7DE;0036;0036;
// (𝟞; 𝟞; 𝟞; 6; 6; ) MATHEMATICAL DOUBLE-STRUCK DIGIT SIX
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7DE }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7DE }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7DE }};
std::array<uint32_t, 1> const c4 = {{ 0x0036 }};
std::array<uint32_t, 1> const c5 = {{ 0x0036 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_115)
{
// 1D7DF;1D7DF;1D7DF;0037;0037;
// (𝟟; 𝟟; 𝟟; 7; 7; ) MATHEMATICAL DOUBLE-STRUCK DIGIT SEVEN
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7DF }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7DF }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7DF }};
std::array<uint32_t, 1> const c4 = {{ 0x0037 }};
std::array<uint32_t, 1> const c5 = {{ 0x0037 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_116)
{
// 1D7E0;1D7E0;1D7E0;0038;0038;
// (𝟠; 𝟠; 𝟠; 8; 8; ) MATHEMATICAL DOUBLE-STRUCK DIGIT EIGHT
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7E0 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7E0 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7E0 }};
std::array<uint32_t, 1> const c4 = {{ 0x0038 }};
std::array<uint32_t, 1> const c5 = {{ 0x0038 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_117)
{
// 1D7E1;1D7E1;1D7E1;0039;0039;
// (𝟡; 𝟡; 𝟡; 9; 9; ) MATHEMATICAL DOUBLE-STRUCK DIGIT NINE
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7E1 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7E1 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7E1 }};
std::array<uint32_t, 1> const c4 = {{ 0x0039 }};
std::array<uint32_t, 1> const c5 = {{ 0x0039 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_118)
{
// 1D7E2;1D7E2;1D7E2;0030;0030;
// (𝟢; 𝟢; 𝟢; 0; 0; ) MATHEMATICAL SANS-SERIF DIGIT ZERO
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7E2 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7E2 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7E2 }};
std::array<uint32_t, 1> const c4 = {{ 0x0030 }};
std::array<uint32_t, 1> const c5 = {{ 0x0030 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_119)
{
// 1D7E3;1D7E3;1D7E3;0031;0031;
// (𝟣; 𝟣; 𝟣; 1; 1; ) MATHEMATICAL SANS-SERIF DIGIT ONE
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7E3 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7E3 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7E3 }};
std::array<uint32_t, 1> const c4 = {{ 0x0031 }};
std::array<uint32_t, 1> const c5 = {{ 0x0031 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_120)
{
// 1D7E4;1D7E4;1D7E4;0032;0032;
// (𝟤; 𝟤; 𝟤; 2; 2; ) MATHEMATICAL SANS-SERIF DIGIT TWO
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7E4 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7E4 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7E4 }};
std::array<uint32_t, 1> const c4 = {{ 0x0032 }};
std::array<uint32_t, 1> const c5 = {{ 0x0032 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_121)
{
// 1D7E5;1D7E5;1D7E5;0033;0033;
// (𝟥; 𝟥; 𝟥; 3; 3; ) MATHEMATICAL SANS-SERIF DIGIT THREE
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7E5 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7E5 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7E5 }};
std::array<uint32_t, 1> const c4 = {{ 0x0033 }};
std::array<uint32_t, 1> const c5 = {{ 0x0033 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_122)
{
// 1D7E6;1D7E6;1D7E6;0034;0034;
// (𝟦; 𝟦; 𝟦; 4; 4; ) MATHEMATICAL SANS-SERIF DIGIT FOUR
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7E6 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7E6 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7E6 }};
std::array<uint32_t, 1> const c4 = {{ 0x0034 }};
std::array<uint32_t, 1> const c5 = {{ 0x0034 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_123)
{
// 1D7E7;1D7E7;1D7E7;0035;0035;
// (𝟧; 𝟧; 𝟧; 5; 5; ) MATHEMATICAL SANS-SERIF DIGIT FIVE
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7E7 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7E7 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7E7 }};
std::array<uint32_t, 1> const c4 = {{ 0x0035 }};
std::array<uint32_t, 1> const c5 = {{ 0x0035 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_124)
{
// 1D7E8;1D7E8;1D7E8;0036;0036;
// (𝟨; 𝟨; 𝟨; 6; 6; ) MATHEMATICAL SANS-SERIF DIGIT SIX
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7E8 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7E8 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7E8 }};
std::array<uint32_t, 1> const c4 = {{ 0x0036 }};
std::array<uint32_t, 1> const c5 = {{ 0x0036 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_125)
{
// 1D7E9;1D7E9;1D7E9;0037;0037;
// (𝟩; 𝟩; 𝟩; 7; 7; ) MATHEMATICAL SANS-SERIF DIGIT SEVEN
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7E9 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7E9 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7E9 }};
std::array<uint32_t, 1> const c4 = {{ 0x0037 }};
std::array<uint32_t, 1> const c5 = {{ 0x0037 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_126)
{
// 1D7EA;1D7EA;1D7EA;0038;0038;
// (𝟪; 𝟪; 𝟪; 8; 8; ) MATHEMATICAL SANS-SERIF DIGIT EIGHT
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7EA }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7EA }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7EA }};
std::array<uint32_t, 1> const c4 = {{ 0x0038 }};
std::array<uint32_t, 1> const c5 = {{ 0x0038 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_127)
{
// 1D7EB;1D7EB;1D7EB;0039;0039;
// (𝟫; 𝟫; 𝟫; 9; 9; ) MATHEMATICAL SANS-SERIF DIGIT NINE
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7EB }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7EB }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7EB }};
std::array<uint32_t, 1> const c4 = {{ 0x0039 }};
std::array<uint32_t, 1> const c5 = {{ 0x0039 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_128)
{
// 1D7EC;1D7EC;1D7EC;0030;0030;
// (𝟬; 𝟬; 𝟬; 0; 0; ) MATHEMATICAL SANS-SERIF BOLD DIGIT ZERO
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7EC }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7EC }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7EC }};
std::array<uint32_t, 1> const c4 = {{ 0x0030 }};
std::array<uint32_t, 1> const c5 = {{ 0x0030 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_129)
{
// 1D7ED;1D7ED;1D7ED;0031;0031;
// (𝟭; 𝟭; 𝟭; 1; 1; ) MATHEMATICAL SANS-SERIF BOLD DIGIT ONE
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7ED }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7ED }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7ED }};
std::array<uint32_t, 1> const c4 = {{ 0x0031 }};
std::array<uint32_t, 1> const c5 = {{ 0x0031 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_130)
{
// 1D7EE;1D7EE;1D7EE;0032;0032;
// (𝟮; 𝟮; 𝟮; 2; 2; ) MATHEMATICAL SANS-SERIF BOLD DIGIT TWO
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7EE }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7EE }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7EE }};
std::array<uint32_t, 1> const c4 = {{ 0x0032 }};
std::array<uint32_t, 1> const c5 = {{ 0x0032 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_131)
{
// 1D7EF;1D7EF;1D7EF;0033;0033;
// (𝟯; 𝟯; 𝟯; 3; 3; ) MATHEMATICAL SANS-SERIF BOLD DIGIT THREE
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7EF }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7EF }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7EF }};
std::array<uint32_t, 1> const c4 = {{ 0x0033 }};
std::array<uint32_t, 1> const c5 = {{ 0x0033 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_132)
{
// 1D7F0;1D7F0;1D7F0;0034;0034;
// (𝟰; 𝟰; 𝟰; 4; 4; ) MATHEMATICAL SANS-SERIF BOLD DIGIT FOUR
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7F0 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7F0 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7F0 }};
std::array<uint32_t, 1> const c4 = {{ 0x0034 }};
std::array<uint32_t, 1> const c5 = {{ 0x0034 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_133)
{
// 1D7F1;1D7F1;1D7F1;0035;0035;
// (𝟱; 𝟱; 𝟱; 5; 5; ) MATHEMATICAL SANS-SERIF BOLD DIGIT FIVE
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7F1 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7F1 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7F1 }};
std::array<uint32_t, 1> const c4 = {{ 0x0035 }};
std::array<uint32_t, 1> const c5 = {{ 0x0035 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_134)
{
// 1D7F2;1D7F2;1D7F2;0036;0036;
// (𝟲; 𝟲; 𝟲; 6; 6; ) MATHEMATICAL SANS-SERIF BOLD DIGIT SIX
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7F2 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7F2 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7F2 }};
std::array<uint32_t, 1> const c4 = {{ 0x0036 }};
std::array<uint32_t, 1> const c5 = {{ 0x0036 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_135)
{
// 1D7F3;1D7F3;1D7F3;0037;0037;
// (𝟳; 𝟳; 𝟳; 7; 7; ) MATHEMATICAL SANS-SERIF BOLD DIGIT SEVEN
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7F3 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7F3 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7F3 }};
std::array<uint32_t, 1> const c4 = {{ 0x0037 }};
std::array<uint32_t, 1> const c5 = {{ 0x0037 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_136)
{
// 1D7F4;1D7F4;1D7F4;0038;0038;
// (𝟴; 𝟴; 𝟴; 8; 8; ) MATHEMATICAL SANS-SERIF BOLD DIGIT EIGHT
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7F4 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7F4 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7F4 }};
std::array<uint32_t, 1> const c4 = {{ 0x0038 }};
std::array<uint32_t, 1> const c5 = {{ 0x0038 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_137)
{
// 1D7F5;1D7F5;1D7F5;0039;0039;
// (𝟵; 𝟵; 𝟵; 9; 9; ) MATHEMATICAL SANS-SERIF BOLD DIGIT NINE
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7F5 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7F5 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7F5 }};
std::array<uint32_t, 1> const c4 = {{ 0x0039 }};
std::array<uint32_t, 1> const c5 = {{ 0x0039 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_138)
{
// 1D7F6;1D7F6;1D7F6;0030;0030;
// (𝟶; 𝟶; 𝟶; 0; 0; ) MATHEMATICAL MONOSPACE DIGIT ZERO
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7F6 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7F6 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7F6 }};
std::array<uint32_t, 1> const c4 = {{ 0x0030 }};
std::array<uint32_t, 1> const c5 = {{ 0x0030 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_139)
{
// 1D7F7;1D7F7;1D7F7;0031;0031;
// (𝟷; 𝟷; 𝟷; 1; 1; ) MATHEMATICAL MONOSPACE DIGIT ONE
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7F7 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7F7 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7F7 }};
std::array<uint32_t, 1> const c4 = {{ 0x0031 }};
std::array<uint32_t, 1> const c5 = {{ 0x0031 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_140)
{
// 1D7F8;1D7F8;1D7F8;0032;0032;
// (𝟸; 𝟸; 𝟸; 2; 2; ) MATHEMATICAL MONOSPACE DIGIT TWO
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7F8 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7F8 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7F8 }};
std::array<uint32_t, 1> const c4 = {{ 0x0032 }};
std::array<uint32_t, 1> const c5 = {{ 0x0032 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_141)
{
// 1D7F9;1D7F9;1D7F9;0033;0033;
// (𝟹; 𝟹; 𝟹; 3; 3; ) MATHEMATICAL MONOSPACE DIGIT THREE
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7F9 }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7F9 }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7F9 }};
std::array<uint32_t, 1> const c4 = {{ 0x0033 }};
std::array<uint32_t, 1> const c5 = {{ 0x0033 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_142)
{
// 1D7FA;1D7FA;1D7FA;0034;0034;
// (𝟺; 𝟺; 𝟺; 4; 4; ) MATHEMATICAL MONOSPACE DIGIT FOUR
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7FA }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7FA }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7FA }};
std::array<uint32_t, 1> const c4 = {{ 0x0034 }};
std::array<uint32_t, 1> const c5 = {{ 0x0034 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_143)
{
// 1D7FB;1D7FB;1D7FB;0035;0035;
// (𝟻; 𝟻; 𝟻; 5; 5; ) MATHEMATICAL MONOSPACE DIGIT FIVE
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7FB }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7FB }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7FB }};
std::array<uint32_t, 1> const c4 = {{ 0x0035 }};
std::array<uint32_t, 1> const c5 = {{ 0x0035 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_144)
{
// 1D7FC;1D7FC;1D7FC;0036;0036;
// (𝟼; 𝟼; 𝟼; 6; 6; ) MATHEMATICAL MONOSPACE DIGIT SIX
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7FC }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7FC }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7FC }};
std::array<uint32_t, 1> const c4 = {{ 0x0036 }};
std::array<uint32_t, 1> const c5 = {{ 0x0036 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_145)
{
// 1D7FD;1D7FD;1D7FD;0037;0037;
// (𝟽; 𝟽; 𝟽; 7; 7; ) MATHEMATICAL MONOSPACE DIGIT SEVEN
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7FD }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7FD }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7FD }};
std::array<uint32_t, 1> const c4 = {{ 0x0037 }};
std::array<uint32_t, 1> const c5 = {{ 0x0037 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_146)
{
// 1D7FE;1D7FE;1D7FE;0038;0038;
// (𝟾; 𝟾; 𝟾; 8; 8; ) MATHEMATICAL MONOSPACE DIGIT EIGHT
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7FE }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7FE }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7FE }};
std::array<uint32_t, 1> const c4 = {{ 0x0038 }};
std::array<uint32_t, 1> const c5 = {{ 0x0038 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_147)
{
// 1D7FF;1D7FF;1D7FF;0039;0039;
// (𝟿; 𝟿; 𝟿; 9; 9; ) MATHEMATICAL MONOSPACE DIGIT NINE
{
std::array<uint32_t, 1> const c1 = {{ 0x1D7FF }};
std::array<uint32_t, 1> const c2 = {{ 0x1D7FF }};
std::array<uint32_t, 1> const c3 = {{ 0x1D7FF }};
std::array<uint32_t, 1> const c4 = {{ 0x0039 }};
std::array<uint32_t, 1> const c5 = {{ 0x0039 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_148)
{
// 1EE00;1EE00;1EE00;0627;0627;
// (𞸀; 𞸀; 𞸀; ا; ا; ) ARABIC MATHEMATICAL ALEF
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE00 }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE00 }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE00 }};
std::array<uint32_t, 1> const c4 = {{ 0x0627 }};
std::array<uint32_t, 1> const c5 = {{ 0x0627 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_149)
{
// 1EE01;1EE01;1EE01;0628;0628;
// (𞸁; 𞸁; 𞸁; ب; ب; ) ARABIC MATHEMATICAL BEH
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE01 }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE01 }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE01 }};
std::array<uint32_t, 1> const c4 = {{ 0x0628 }};
std::array<uint32_t, 1> const c5 = {{ 0x0628 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_150)
{
// 1EE02;1EE02;1EE02;062C;062C;
// (𞸂; 𞸂; 𞸂; ج; ج; ) ARABIC MATHEMATICAL JEEM
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE02 }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE02 }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE02 }};
std::array<uint32_t, 1> const c4 = {{ 0x062C }};
std::array<uint32_t, 1> const c5 = {{ 0x062C }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_151)
{
// 1EE03;1EE03;1EE03;062F;062F;
// (𞸃; 𞸃; 𞸃; د; د; ) ARABIC MATHEMATICAL DAL
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE03 }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE03 }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE03 }};
std::array<uint32_t, 1> const c4 = {{ 0x062F }};
std::array<uint32_t, 1> const c5 = {{ 0x062F }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_152)
{
// 1EE05;1EE05;1EE05;0648;0648;
// (𞸅; 𞸅; 𞸅; و; و; ) ARABIC MATHEMATICAL WAW
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE05 }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE05 }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE05 }};
std::array<uint32_t, 1> const c4 = {{ 0x0648 }};
std::array<uint32_t, 1> const c5 = {{ 0x0648 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_153)
{
// 1EE06;1EE06;1EE06;0632;0632;
// (𞸆; 𞸆; 𞸆; ز; ز; ) ARABIC MATHEMATICAL ZAIN
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE06 }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE06 }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE06 }};
std::array<uint32_t, 1> const c4 = {{ 0x0632 }};
std::array<uint32_t, 1> const c5 = {{ 0x0632 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_154)
{
// 1EE07;1EE07;1EE07;062D;062D;
// (𞸇; 𞸇; 𞸇; ح; ح; ) ARABIC MATHEMATICAL HAH
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE07 }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE07 }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE07 }};
std::array<uint32_t, 1> const c4 = {{ 0x062D }};
std::array<uint32_t, 1> const c5 = {{ 0x062D }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_155)
{
// 1EE08;1EE08;1EE08;0637;0637;
// (𞸈; 𞸈; 𞸈; ط; ط; ) ARABIC MATHEMATICAL TAH
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE08 }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE08 }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE08 }};
std::array<uint32_t, 1> const c4 = {{ 0x0637 }};
std::array<uint32_t, 1> const c5 = {{ 0x0637 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_156)
{
// 1EE09;1EE09;1EE09;064A;064A;
// (𞸉; 𞸉; 𞸉; ي; ي; ) ARABIC MATHEMATICAL YEH
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE09 }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE09 }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE09 }};
std::array<uint32_t, 1> const c4 = {{ 0x064A }};
std::array<uint32_t, 1> const c5 = {{ 0x064A }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_157)
{
// 1EE0A;1EE0A;1EE0A;0643;0643;
// (𞸊; 𞸊; 𞸊; ك; ك; ) ARABIC MATHEMATICAL KAF
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE0A }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE0A }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE0A }};
std::array<uint32_t, 1> const c4 = {{ 0x0643 }};
std::array<uint32_t, 1> const c5 = {{ 0x0643 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_158)
{
// 1EE0B;1EE0B;1EE0B;0644;0644;
// (𞸋; 𞸋; 𞸋; ل; ل; ) ARABIC MATHEMATICAL LAM
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE0B }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE0B }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE0B }};
std::array<uint32_t, 1> const c4 = {{ 0x0644 }};
std::array<uint32_t, 1> const c5 = {{ 0x0644 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_159)
{
// 1EE0C;1EE0C;1EE0C;0645;0645;
// (𞸌; 𞸌; 𞸌; م; م; ) ARABIC MATHEMATICAL MEEM
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE0C }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE0C }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE0C }};
std::array<uint32_t, 1> const c4 = {{ 0x0645 }};
std::array<uint32_t, 1> const c5 = {{ 0x0645 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_160)
{
// 1EE0D;1EE0D;1EE0D;0646;0646;
// (𞸍; 𞸍; 𞸍; ن; ن; ) ARABIC MATHEMATICAL NOON
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE0D }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE0D }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE0D }};
std::array<uint32_t, 1> const c4 = {{ 0x0646 }};
std::array<uint32_t, 1> const c5 = {{ 0x0646 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_161)
{
// 1EE0E;1EE0E;1EE0E;0633;0633;
// (𞸎; 𞸎; 𞸎; س; س; ) ARABIC MATHEMATICAL SEEN
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE0E }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE0E }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE0E }};
std::array<uint32_t, 1> const c4 = {{ 0x0633 }};
std::array<uint32_t, 1> const c5 = {{ 0x0633 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_162)
{
// 1EE0F;1EE0F;1EE0F;0639;0639;
// (𞸏; 𞸏; 𞸏; ع; ع; ) ARABIC MATHEMATICAL AIN
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE0F }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE0F }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE0F }};
std::array<uint32_t, 1> const c4 = {{ 0x0639 }};
std::array<uint32_t, 1> const c5 = {{ 0x0639 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_163)
{
// 1EE10;1EE10;1EE10;0641;0641;
// (𞸐; 𞸐; 𞸐; ف; ف; ) ARABIC MATHEMATICAL FEH
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE10 }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE10 }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE10 }};
std::array<uint32_t, 1> const c4 = {{ 0x0641 }};
std::array<uint32_t, 1> const c5 = {{ 0x0641 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_164)
{
// 1EE11;1EE11;1EE11;0635;0635;
// (𞸑; 𞸑; 𞸑; ص; ص; ) ARABIC MATHEMATICAL SAD
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE11 }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE11 }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE11 }};
std::array<uint32_t, 1> const c4 = {{ 0x0635 }};
std::array<uint32_t, 1> const c5 = {{ 0x0635 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_165)
{
// 1EE12;1EE12;1EE12;0642;0642;
// (𞸒; 𞸒; 𞸒; ق; ق; ) ARABIC MATHEMATICAL QAF
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE12 }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE12 }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE12 }};
std::array<uint32_t, 1> const c4 = {{ 0x0642 }};
std::array<uint32_t, 1> const c5 = {{ 0x0642 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_166)
{
// 1EE13;1EE13;1EE13;0631;0631;
// (𞸓; 𞸓; 𞸓; ر; ر; ) ARABIC MATHEMATICAL REH
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE13 }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE13 }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE13 }};
std::array<uint32_t, 1> const c4 = {{ 0x0631 }};
std::array<uint32_t, 1> const c5 = {{ 0x0631 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_167)
{
// 1EE14;1EE14;1EE14;0634;0634;
// (𞸔; 𞸔; 𞸔; ش; ش; ) ARABIC MATHEMATICAL SHEEN
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE14 }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE14 }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE14 }};
std::array<uint32_t, 1> const c4 = {{ 0x0634 }};
std::array<uint32_t, 1> const c5 = {{ 0x0634 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_168)
{
// 1EE15;1EE15;1EE15;062A;062A;
// (𞸕; 𞸕; 𞸕; ت; ت; ) ARABIC MATHEMATICAL TEH
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE15 }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE15 }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE15 }};
std::array<uint32_t, 1> const c4 = {{ 0x062A }};
std::array<uint32_t, 1> const c5 = {{ 0x062A }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_169)
{
// 1EE16;1EE16;1EE16;062B;062B;
// (𞸖; 𞸖; 𞸖; ث; ث; ) ARABIC MATHEMATICAL THEH
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE16 }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE16 }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE16 }};
std::array<uint32_t, 1> const c4 = {{ 0x062B }};
std::array<uint32_t, 1> const c5 = {{ 0x062B }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_170)
{
// 1EE17;1EE17;1EE17;062E;062E;
// (𞸗; 𞸗; 𞸗; خ; خ; ) ARABIC MATHEMATICAL KHAH
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE17 }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE17 }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE17 }};
std::array<uint32_t, 1> const c4 = {{ 0x062E }};
std::array<uint32_t, 1> const c5 = {{ 0x062E }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_171)
{
// 1EE18;1EE18;1EE18;0630;0630;
// (𞸘; 𞸘; 𞸘; ذ; ذ; ) ARABIC MATHEMATICAL THAL
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE18 }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE18 }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE18 }};
std::array<uint32_t, 1> const c4 = {{ 0x0630 }};
std::array<uint32_t, 1> const c5 = {{ 0x0630 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_172)
{
// 1EE19;1EE19;1EE19;0636;0636;
// (𞸙; 𞸙; 𞸙; ض; ض; ) ARABIC MATHEMATICAL DAD
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE19 }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE19 }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE19 }};
std::array<uint32_t, 1> const c4 = {{ 0x0636 }};
std::array<uint32_t, 1> const c5 = {{ 0x0636 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_173)
{
// 1EE1A;1EE1A;1EE1A;0638;0638;
// (𞸚; 𞸚; 𞸚; ظ; ظ; ) ARABIC MATHEMATICAL ZAH
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE1A }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE1A }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE1A }};
std::array<uint32_t, 1> const c4 = {{ 0x0638 }};
std::array<uint32_t, 1> const c5 = {{ 0x0638 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_174)
{
// 1EE1B;1EE1B;1EE1B;063A;063A;
// (𞸛; 𞸛; 𞸛; غ; غ; ) ARABIC MATHEMATICAL GHAIN
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE1B }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE1B }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE1B }};
std::array<uint32_t, 1> const c4 = {{ 0x063A }};
std::array<uint32_t, 1> const c5 = {{ 0x063A }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_175)
{
// 1EE1C;1EE1C;1EE1C;066E;066E;
// (𞸜; 𞸜; 𞸜; ٮ; ٮ; ) ARABIC MATHEMATICAL DOTLESS BEH
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE1C }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE1C }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE1C }};
std::array<uint32_t, 1> const c4 = {{ 0x066E }};
std::array<uint32_t, 1> const c5 = {{ 0x066E }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_176)
{
// 1EE1D;1EE1D;1EE1D;06BA;06BA;
// (𞸝; 𞸝; 𞸝; ں; ں; ) ARABIC MATHEMATICAL DOTLESS NOON
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE1D }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE1D }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE1D }};
std::array<uint32_t, 1> const c4 = {{ 0x06BA }};
std::array<uint32_t, 1> const c5 = {{ 0x06BA }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_177)
{
// 1EE1E;1EE1E;1EE1E;06A1;06A1;
// (𞸞; 𞸞; 𞸞; ڡ; ڡ; ) ARABIC MATHEMATICAL DOTLESS FEH
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE1E }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE1E }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE1E }};
std::array<uint32_t, 1> const c4 = {{ 0x06A1 }};
std::array<uint32_t, 1> const c5 = {{ 0x06A1 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_178)
{
// 1EE1F;1EE1F;1EE1F;066F;066F;
// (𞸟; 𞸟; 𞸟; ٯ; ٯ; ) ARABIC MATHEMATICAL DOTLESS QAF
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE1F }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE1F }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE1F }};
std::array<uint32_t, 1> const c4 = {{ 0x066F }};
std::array<uint32_t, 1> const c5 = {{ 0x066F }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_179)
{
// 1EE21;1EE21;1EE21;0628;0628;
// (𞸡; 𞸡; 𞸡; ب; ب; ) ARABIC MATHEMATICAL INITIAL BEH
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE21 }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE21 }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE21 }};
std::array<uint32_t, 1> const c4 = {{ 0x0628 }};
std::array<uint32_t, 1> const c5 = {{ 0x0628 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_180)
{
// 1EE22;1EE22;1EE22;062C;062C;
// (𞸢; 𞸢; 𞸢; ج; ج; ) ARABIC MATHEMATICAL INITIAL JEEM
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE22 }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE22 }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE22 }};
std::array<uint32_t, 1> const c4 = {{ 0x062C }};
std::array<uint32_t, 1> const c5 = {{ 0x062C }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_181)
{
// 1EE24;1EE24;1EE24;0647;0647;
// (𞸤; 𞸤; 𞸤; ه; ه; ) ARABIC MATHEMATICAL INITIAL HEH
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE24 }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE24 }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE24 }};
std::array<uint32_t, 1> const c4 = {{ 0x0647 }};
std::array<uint32_t, 1> const c5 = {{ 0x0647 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_182)
{
// 1EE27;1EE27;1EE27;062D;062D;
// (𞸧; 𞸧; 𞸧; ح; ح; ) ARABIC MATHEMATICAL INITIAL HAH
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE27 }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE27 }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE27 }};
std::array<uint32_t, 1> const c4 = {{ 0x062D }};
std::array<uint32_t, 1> const c5 = {{ 0x062D }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_183)
{
// 1EE29;1EE29;1EE29;064A;064A;
// (𞸩; 𞸩; 𞸩; ي; ي; ) ARABIC MATHEMATICAL INITIAL YEH
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE29 }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE29 }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE29 }};
std::array<uint32_t, 1> const c4 = {{ 0x064A }};
std::array<uint32_t, 1> const c5 = {{ 0x064A }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_184)
{
// 1EE2A;1EE2A;1EE2A;0643;0643;
// (𞸪; 𞸪; 𞸪; ك; ك; ) ARABIC MATHEMATICAL INITIAL KAF
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE2A }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE2A }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE2A }};
std::array<uint32_t, 1> const c4 = {{ 0x0643 }};
std::array<uint32_t, 1> const c5 = {{ 0x0643 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_185)
{
// 1EE2B;1EE2B;1EE2B;0644;0644;
// (𞸫; 𞸫; 𞸫; ل; ل; ) ARABIC MATHEMATICAL INITIAL LAM
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE2B }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE2B }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE2B }};
std::array<uint32_t, 1> const c4 = {{ 0x0644 }};
std::array<uint32_t, 1> const c5 = {{ 0x0644 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_186)
{
// 1EE2C;1EE2C;1EE2C;0645;0645;
// (𞸬; 𞸬; 𞸬; م; م; ) ARABIC MATHEMATICAL INITIAL MEEM
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE2C }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE2C }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE2C }};
std::array<uint32_t, 1> const c4 = {{ 0x0645 }};
std::array<uint32_t, 1> const c5 = {{ 0x0645 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_187)
{
// 1EE2D;1EE2D;1EE2D;0646;0646;
// (𞸭; 𞸭; 𞸭; ن; ن; ) ARABIC MATHEMATICAL INITIAL NOON
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE2D }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE2D }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE2D }};
std::array<uint32_t, 1> const c4 = {{ 0x0646 }};
std::array<uint32_t, 1> const c5 = {{ 0x0646 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_188)
{
// 1EE2E;1EE2E;1EE2E;0633;0633;
// (𞸮; 𞸮; 𞸮; س; س; ) ARABIC MATHEMATICAL INITIAL SEEN
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE2E }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE2E }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE2E }};
std::array<uint32_t, 1> const c4 = {{ 0x0633 }};
std::array<uint32_t, 1> const c5 = {{ 0x0633 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_189)
{
// 1EE2F;1EE2F;1EE2F;0639;0639;
// (𞸯; 𞸯; 𞸯; ع; ع; ) ARABIC MATHEMATICAL INITIAL AIN
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE2F }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE2F }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE2F }};
std::array<uint32_t, 1> const c4 = {{ 0x0639 }};
std::array<uint32_t, 1> const c5 = {{ 0x0639 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_190)
{
// 1EE30;1EE30;1EE30;0641;0641;
// (𞸰; 𞸰; 𞸰; ف; ف; ) ARABIC MATHEMATICAL INITIAL FEH
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE30 }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE30 }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE30 }};
std::array<uint32_t, 1> const c4 = {{ 0x0641 }};
std::array<uint32_t, 1> const c5 = {{ 0x0641 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_191)
{
// 1EE31;1EE31;1EE31;0635;0635;
// (𞸱; 𞸱; 𞸱; ص; ص; ) ARABIC MATHEMATICAL INITIAL SAD
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE31 }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE31 }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE31 }};
std::array<uint32_t, 1> const c4 = {{ 0x0635 }};
std::array<uint32_t, 1> const c5 = {{ 0x0635 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_192)
{
// 1EE32;1EE32;1EE32;0642;0642;
// (𞸲; 𞸲; 𞸲; ق; ق; ) ARABIC MATHEMATICAL INITIAL QAF
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE32 }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE32 }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE32 }};
std::array<uint32_t, 1> const c4 = {{ 0x0642 }};
std::array<uint32_t, 1> const c5 = {{ 0x0642 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_193)
{
// 1EE34;1EE34;1EE34;0634;0634;
// (𞸴; 𞸴; 𞸴; ش; ش; ) ARABIC MATHEMATICAL INITIAL SHEEN
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE34 }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE34 }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE34 }};
std::array<uint32_t, 1> const c4 = {{ 0x0634 }};
std::array<uint32_t, 1> const c5 = {{ 0x0634 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_194)
{
// 1EE35;1EE35;1EE35;062A;062A;
// (𞸵; 𞸵; 𞸵; ت; ت; ) ARABIC MATHEMATICAL INITIAL TEH
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE35 }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE35 }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE35 }};
std::array<uint32_t, 1> const c4 = {{ 0x062A }};
std::array<uint32_t, 1> const c5 = {{ 0x062A }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_195)
{
// 1EE36;1EE36;1EE36;062B;062B;
// (𞸶; 𞸶; 𞸶; ث; ث; ) ARABIC MATHEMATICAL INITIAL THEH
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE36 }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE36 }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE36 }};
std::array<uint32_t, 1> const c4 = {{ 0x062B }};
std::array<uint32_t, 1> const c5 = {{ 0x062B }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_196)
{
// 1EE37;1EE37;1EE37;062E;062E;
// (𞸷; 𞸷; 𞸷; خ; خ; ) ARABIC MATHEMATICAL INITIAL KHAH
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE37 }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE37 }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE37 }};
std::array<uint32_t, 1> const c4 = {{ 0x062E }};
std::array<uint32_t, 1> const c5 = {{ 0x062E }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_197)
{
// 1EE39;1EE39;1EE39;0636;0636;
// (𞸹; 𞸹; 𞸹; ض; ض; ) ARABIC MATHEMATICAL INITIAL DAD
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE39 }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE39 }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE39 }};
std::array<uint32_t, 1> const c4 = {{ 0x0636 }};
std::array<uint32_t, 1> const c5 = {{ 0x0636 }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_198)
{
// 1EE3B;1EE3B;1EE3B;063A;063A;
// (𞸻; 𞸻; 𞸻; غ; غ; ) ARABIC MATHEMATICAL INITIAL GHAIN
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE3B }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE3B }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE3B }};
std::array<uint32_t, 1> const c4 = {{ 0x063A }};
std::array<uint32_t, 1> const c5 = {{ 0x063A }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
TEST(normalization, nfc_080_199)
{
// 1EE42;1EE42;1EE42;062C;062C;
// (𞹂; 𞹂; 𞹂; ج; ج; ) ARABIC MATHEMATICAL TAILED JEEM
{
std::array<uint32_t, 1> const c1 = {{ 0x1EE42 }};
std::array<uint32_t, 1> const c2 = {{ 0x1EE42 }};
std::array<uint32_t, 1> const c3 = {{ 0x1EE42 }};
std::array<uint32_t, 1> const c4 = {{ 0x062C }};
std::array<uint32_t, 1> const c5 = {{ 0x062C }};
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c2.begin(), c2.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::c>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::d>(c3.begin(), c3.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c4.begin(), c4.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kc>(c5.begin(), c5.end()));
EXPECT_TRUE(boost::text::normalized<boost::text::nf::kd>(c5.begin(), c5.end()));
{
std::string str = boost::text::to_string(c1.begin(), c1.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c2.begin(), c2.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c3.begin(), c3.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c2.size());
auto c2_it = c2.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c2_it) << "iteration " << i;
++c2_it;
++i;
}
}
{
std::string str = boost::text::to_string(c4.begin(), c4.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
{
std::string str = boost::text::to_string(c5.begin(), c5.end());
boost::text::normalize<boost::text::nf::c>(str);
auto const r = boost::text::as_utf32(str);
EXPECT_EQ(std::distance(r.begin(), r.end()), (std::ptrdiff_t)c4.size());
auto c4_it = c4.begin();
int i = 0;
for (auto x : r) {
EXPECT_EQ(x, *c4_it) << "iteration " << i;
++c4_it;
++i;
}
}
}
}
|
//
// Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2021
//
// 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)
//
#include "td/net/Socks5.h"
#include "td/utils/common.h"
#include "td/utils/logging.h"
#include "td/utils/misc.h"
#include "td/utils/Slice.h"
#include "td/utils/SliceBuilder.h"
namespace td {
void Socks5::send_greeting() {
VLOG(proxy) << "Send greeting to proxy";
CHECK(state_ == State::SendGreeting);
state_ = State::WaitGreetingResponse;
string greeting;
greeting += '\x05';
bool use_username = !username_.empty();
char authentication_count = use_username ? '\x02' : '\x01';
greeting += authentication_count;
greeting += '\0';
if (use_username) {
greeting += '\x02';
}
fd_.output_buffer().append(greeting);
}
Status Socks5::wait_greeting_response() {
auto &buf = fd_.input_buffer();
VLOG(proxy) << "Receive greeting response of size " << buf.size();
if (buf.size() < 2) {
return Status::OK();
}
auto buffer_slice = buf.read_as_buffer_slice(2);
auto slice = buffer_slice.as_slice();
if (slice[0] != '\x05') {
return Status::Error(PSLICE() << "Unsupported socks protocol version " << static_cast<int>(slice[0]));
}
auto authentication_method = slice[1];
if (authentication_method == '\0') {
send_ip_address();
return Status::OK();
}
if (authentication_method == '\x02') {
return send_username_password();
}
return Status::Error("Unsupported authentication mode");
}
Status Socks5::send_username_password() {
VLOG(proxy) << "Send username and password";
if (username_.size() >= 128) {
return Status::Error("Username is too long");
}
if (password_.size() >= 128) {
return Status::Error("Password is too long");
}
string request;
request += '\x01';
request += narrow_cast<char>(username_.size());
request += username_;
request += narrow_cast<char>(password_.size());
request += password_;
fd_.output_buffer().append(request);
state_ = State::WaitPasswordResponse;
return Status::OK();
}
Status Socks5::wait_password_response() {
auto &buf = fd_.input_buffer();
VLOG(proxy) << "Receive password response of size " << buf.size();
if (buf.size() < 2) {
return Status::OK();
}
auto buffer_slice = buf.read_as_buffer_slice(2);
auto slice = buffer_slice.as_slice();
if (slice[0] != '\x01') {
return Status::Error(PSLICE() << "Unsupported socks subnegotiation protocol version "
<< static_cast<int>(slice[0]));
}
if (slice[1] != '\x00') {
return Status::Error("Wrong username or password");
}
send_ip_address();
return Status::OK();
}
void Socks5::send_ip_address() {
VLOG(proxy) << "Send IP address";
callback_->on_connected();
string request;
request += '\x05';
request += '\x01';
request += '\x00';
if (ip_address_.is_ipv4()) {
request += '\x01';
auto ipv4 = ntohl(ip_address_.get_ipv4());
request += static_cast<char>(ipv4 & 255);
request += static_cast<char>((ipv4 >> 8) & 255);
request += static_cast<char>((ipv4 >> 16) & 255);
request += static_cast<char>((ipv4 >> 24) & 255);
} else {
request += '\x04';
request += ip_address_.get_ipv6();
}
auto port = ip_address_.get_port();
request += static_cast<char>((port >> 8) & 255);
request += static_cast<char>(port & 255);
fd_.output_buffer().append(request);
state_ = State::WaitIpAddressResponse;
}
Status Socks5::wait_ip_address_response() {
CHECK(state_ == State::WaitIpAddressResponse);
auto it = fd_.input_buffer().clone();
VLOG(proxy) << "Receive IP address response of size " << it.size();
if (it.size() < 4) {
return Status::OK();
}
char c;
MutableSlice c_slice(&c, 1);
it.advance(1, c_slice);
if (c != '\x05') {
return Status::Error("Invalid response");
}
it.advance(1, c_slice);
if (c != '\0') {
return Status::Error(PSLICE() << "Receive error code " << static_cast<int32>(c) << " from server");
}
it.advance(1, c_slice);
if (c != '\0') {
return Status::Error("Byte must be zero");
}
it.advance(1, c_slice);
size_t total_size = 6;
if (c == '\x01') {
if (it.size() < 4) {
return Status::OK();
}
it.advance(4);
total_size += 4;
} else if (c == '\x04') {
if (it.size() < 16) {
return Status::OK();
}
it.advance(16);
total_size += 16;
} else {
return Status::Error("Invalid response");
}
if (it.size() < 2) {
return Status::OK();
}
it.advance(2);
fd_.input_buffer().advance(total_size);
stop();
return Status::OK();
}
Status Socks5::loop_impl() {
switch (state_) {
case State::SendGreeting:
send_greeting();
break;
case State::WaitGreetingResponse:
TRY_STATUS(wait_greeting_response());
break;
case State::WaitPasswordResponse:
TRY_STATUS(wait_password_response());
break;
case State::WaitIpAddressResponse:
TRY_STATUS(wait_ip_address_response());
break;
default:
UNREACHABLE();
}
return Status::OK();
}
} // namespace td
|
#ifndef CTCI_6TH_EDITION_CPP_04_TREES_AND_GRAPHS_06_SUCCESSOR_GETNEXT_HPP_
#define CTCI_6TH_EDITION_CPP_04_TREES_AND_GRAPHS_06_SUCCESSOR_GETNEXT_HPP_
#include "DoubleBinaryTree.hpp"
DoubleBinaryTreeNode* getNext(const p_node_t& node);
#endif // CTCI_6TH_EDITION_CPP_04_TREES_AND_GRAPHS_06_SUCCESSOR_GETNEXT_HPP_
|
// -*- C++ -*-
//===-- test_reverse.cpp --------------------------------------------------===//
//
// Copyright (C) 2017-2019 Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
// This file incorporates work covered by the following copyright and permission
// notice:
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
//
//===----------------------------------------------------------------------===//
#include "pstl_test_config.h"
#include <iterator>
#include "pstl/execution"
#include "pstl/algorithm"
#include "utils.h"
using namespace TestUtils;
struct test_one_policy
{
#if __PSTL_ICC_18_VC141_TEST_SIMD_LAMBDA_RELEASE_BROKEN || __PSTL_ICC_17_VC141_TEST_SIMD_LAMBDA_DEBUG_32_BROKEN || \
__PSTL_ICC_16_VC14_TEST_SIMD_LAMBDA_DEBUG_32_BROKEN // dummy specialization by policy type, in case of broken configuration
template <typename Iterator1, typename Iterator2>
typename std::enable_if<is_same_iterator_category<Iterator1, std::random_access_iterator_tag>::value, void>::type
operator()(pstl::execution::unsequenced_policy, Iterator1 data_b, Iterator1 data_e, Iterator2 actual_b,
Iterator2 actual_e)
{
}
template <typename Iterator1, typename Iterator2>
typename std::enable_if<is_same_iterator_category<Iterator1, std::random_access_iterator_tag>::value, void>::type
operator()(pstl::execution::parallel_unsequenced_policy, Iterator1 data_b, Iterator1 data_e, Iterator2 actual_b,
Iterator2 actual_e)
{
}
#endif
template <typename ExecutionPolicy, typename Iterator1, typename Iterator2>
typename std::enable_if<!is_same_iterator_category<Iterator1, std::forward_iterator_tag>::value>::type
operator()(ExecutionPolicy&& exec, Iterator1 data_b, Iterator1 data_e, Iterator2 actual_b, Iterator2 actual_e)
{
using namespace std;
copy(data_b, data_e, actual_b);
reverse(exec, actual_b, actual_e);
bool check = equal(data_b, data_e, reverse_iterator<Iterator2>(actual_e));
EXPECT_TRUE(check, "wrong result of reverse");
}
template <typename ExecutionPolicy, typename Iterator1, typename Iterator2>
typename std::enable_if<is_same_iterator_category<Iterator1, std::forward_iterator_tag>::value>::type
operator()(ExecutionPolicy&& exec, Iterator1 data_b, Iterator1 data_e, Iterator2 actual_b, Iterator2 actual_e)
{
}
};
template <typename T>
void
test()
{
const std::size_t max_len = 100000;
Sequence<T> actual(max_len);
Sequence<T> data(max_len, [](std::size_t i) { return T(i); });
for (std::size_t len = 0; len < max_len; len = len <= 16 ? len + 1 : std::size_t(3.1415 * len))
{
invoke_on_all_policies(test_one_policy(), data.begin(), data.begin() + len, actual.begin(),
actual.begin() + len);
}
}
template <typename T>
struct wrapper
{
T t;
wrapper() {}
explicit wrapper(T t_) : t(t_) {}
bool
operator==(const wrapper<T>& a) const
{
return t == a.t;
}
};
int32_t
main()
{
test<int32_t>();
test<uint16_t>();
test<float64_t>();
#if !__PSTL_ICC_17_TEST_MAC_RELEASE_32_BROKEN
test<wrapper<float64_t>>();
#endif
std::cout << done() << std::endl;
return 0;
}
|
// Copyright 2014 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.
// This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY!
#include "config.h"
#include "V8HTMLSpanElement.h"
#include "bindings/v8/ExceptionState.h"
#include "bindings/v8/V8DOMConfiguration.h"
#include "bindings/v8/V8HiddenValue.h"
#include "bindings/v8/V8ObjectConstructor.h"
#include "core/dom/ContextFeatures.h"
#include "core/dom/Document.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/TraceEvent.h"
#include "wtf/GetPtr.h"
#include "wtf/RefPtr.h"
namespace WebCore {
static void initializeScriptWrappableForInterface(HTMLSpanElement* object)
{
if (ScriptWrappable::wrapperCanBeStoredInObject(object))
ScriptWrappable::fromObject(object)->setTypeInfo(&V8HTMLSpanElement::wrapperTypeInfo);
else
ASSERT_NOT_REACHED();
}
} // namespace WebCore
void webCoreInitializeScriptWrappableForInterface(WebCore::HTMLSpanElement* object)
{
WebCore::initializeScriptWrappableForInterface(object);
}
namespace WebCore {
const WrapperTypeInfo V8HTMLSpanElement::wrapperTypeInfo = { gin::kEmbedderBlink, V8HTMLSpanElement::domTemplate, V8HTMLSpanElement::derefObject, 0, V8HTMLSpanElement::toEventTarget, 0, V8HTMLSpanElement::installPerContextEnabledMethods, &V8HTMLElement::wrapperTypeInfo, WrapperTypeObjectPrototype, WillBeGarbageCollectedObject };
namespace HTMLSpanElementV8Internal {
template <typename T> void V8_USE(T) { }
} // namespace HTMLSpanElementV8Internal
static void configureV8HTMLSpanElementTemplate(v8::Handle<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate)
{
functionTemplate->ReadOnlyPrototype();
v8::Local<v8::Signature> defaultSignature;
defaultSignature = V8DOMConfiguration::installDOMClassTemplate(functionTemplate, "HTMLSpanElement", V8HTMLElement::domTemplate(isolate), V8HTMLSpanElement::internalFieldCount,
0, 0,
0, 0,
0, 0,
isolate);
v8::Local<v8::ObjectTemplate> instanceTemplate ALLOW_UNUSED = functionTemplate->InstanceTemplate();
v8::Local<v8::ObjectTemplate> prototypeTemplate ALLOW_UNUSED = functionTemplate->PrototypeTemplate();
// Custom toString template
functionTemplate->Set(v8AtomicString(isolate, "toString"), V8PerIsolateData::from(isolate)->toStringTemplate());
}
v8::Handle<v8::FunctionTemplate> V8HTMLSpanElement::domTemplate(v8::Isolate* isolate)
{
return V8DOMConfiguration::domClassTemplate(isolate, const_cast<WrapperTypeInfo*>(&wrapperTypeInfo), configureV8HTMLSpanElementTemplate);
}
bool V8HTMLSpanElement::hasInstance(v8::Handle<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->hasInstance(&wrapperTypeInfo, v8Value);
}
v8::Handle<v8::Object> V8HTMLSpanElement::findInstanceInPrototypeChain(v8::Handle<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->findInstanceInPrototypeChain(&wrapperTypeInfo, v8Value);
}
HTMLSpanElement* V8HTMLSpanElement::toNativeWithTypeCheck(v8::Isolate* isolate, v8::Handle<v8::Value> value)
{
return hasInstance(value, isolate) ? fromInternalPointer(v8::Handle<v8::Object>::Cast(value)->GetAlignedPointerFromInternalField(v8DOMWrapperObjectIndex)) : 0;
}
EventTarget* V8HTMLSpanElement::toEventTarget(v8::Handle<v8::Object> object)
{
return toNative(object);
}
v8::Handle<v8::Object> wrap(HTMLSpanElement* impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
{
ASSERT(impl);
ASSERT(!DOMDataStore::containsWrapper<V8HTMLSpanElement>(impl, isolate));
return V8HTMLSpanElement::createWrapper(impl, creationContext, isolate);
}
v8::Handle<v8::Object> V8HTMLSpanElement::createWrapper(PassRefPtrWillBeRawPtr<HTMLSpanElement> impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
{
ASSERT(impl);
ASSERT(!DOMDataStore::containsWrapper<V8HTMLSpanElement>(impl.get(), isolate));
if (ScriptWrappable::wrapperCanBeStoredInObject(impl.get())) {
const WrapperTypeInfo* actualInfo = ScriptWrappable::fromObject(impl.get())->typeInfo();
// Might be a XXXConstructor::wrapperTypeInfo instead of an XXX::wrapperTypeInfo. These will both have
// the same object de-ref functions, though, so use that as the basis of the check.
RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(actualInfo->derefObjectFunction == wrapperTypeInfo.derefObjectFunction);
}
v8::Handle<v8::Object> wrapper = V8DOMWrapper::createWrapper(creationContext, &wrapperTypeInfo, toInternalPointer(impl.get()), isolate);
if (UNLIKELY(wrapper.IsEmpty()))
return wrapper;
installPerContextEnabledProperties(wrapper, impl.get(), isolate);
V8DOMWrapper::associateObjectWithWrapper<V8HTMLSpanElement>(impl, &wrapperTypeInfo, wrapper, isolate, WrapperConfiguration::Dependent);
return wrapper;
}
void V8HTMLSpanElement::derefObject(void* object)
{
#if !ENABLE(OILPAN)
fromInternalPointer(object)->deref();
#endif // !ENABLE(OILPAN)
}
template<>
v8::Handle<v8::Value> toV8NoInline(HTMLSpanElement* impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
{
return toV8(impl, creationContext, isolate);
}
} // namespace WebCore
|
/*
* Copyright (c) 2012-2020, Intel Corporation
*
* 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.
*/
//!
//! \file codechal_decode_hevc.cpp
//! \brief Implements the decode interface extension for HEVC.
//! \details Implements all functions required by CodecHal for HEVC decoding.
//!
#include "codechal_decoder.h"
#include "codechal_secure_decode_interface.h"
#include "codechal_decode_hevc.h"
#include "codechal_mmc_decode_hevc.h"
#include "codechal_decode_nv12top010.h"
#include "media_interfaces_nv12top010.h"
#include "hal_oca_interface.h"
#if USE_CODECHAL_DEBUG_TOOL
#include "codechal_debug.h"
#endif
//==<Functions>=======================================================
uint8_t CodechalDecodeHevc::GetMvBufferIndex(
uint8_t frameIdx)
{
PCODECHAL_DECODE_HEVC_MV_LIST hevcMVBufList = &m_hevcMvList[0];
uint8_t i;
for (i = 0; i < CODEC_NUM_HEVC_MV_BUFFERS; i++)
{
if (!hevcMVBufList[i].bInUse)
{
hevcMVBufList[i].bInUse = true;
hevcMVBufList[i].u8FrameId = frameIdx;
break;
}
}
if (i == CODEC_NUM_HEVC_MV_BUFFERS)
{
// Should never happen, something must be wrong
CODECHAL_DECODE_ASSERTMESSAGE("Failed to get avaiable MV buffer.");
}
return i;
}
MOS_STATUS CodechalDecodeHevc::AllocateResourcesFixedSizes()
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
CODECHAL_DECODE_FUNCTION_ENTER;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_osInterface->pfnCreateSyncResource(
m_osInterface,
&m_resSyncObjectWaContextInUse));
CODECHAL_DECODE_CHK_STATUS_RETURN(CodecHalAllocateDataList(
m_hevcRefList,
CODECHAL_NUM_UNCOMPRESSED_SURFACE_HEVC));
MOS_ZeroMemory(&m_secondLevelBatchBuffer, CODEC_HEVC_NUM_SECOND_BB * sizeof(MHW_BATCH_BUFFER));
if (m_shortFormatInUse)
{
// Second level batch buffer for HuC FW to use
uint32_t u32Size = MOS_ALIGN_CEIL(CODECHAL_HEVC_MAX_NUM_SLICES_LVL_6 * m_standardDecodeSizeNeeded,
CODECHAL_PAGE_SIZE);
for (int i = 0; i < CODEC_HEVC_NUM_SECOND_BB; i++)
{
CODECHAL_DECODE_CHK_STATUS_RETURN(Mhw_AllocateBb(
m_osInterface,
&m_secondLevelBatchBuffer[i],
nullptr,
u32Size));
m_secondLevelBatchBuffer[i].bSecondLevel = true;
}
// DMEM buffer send to HuC FW
m_dmemBufferSize = GetDmemBufferSize();
for (uint32_t i = 0; i < CODECHAL_HEVC_NUM_DMEM_BUFFERS; i++)
{
CODECHAL_DECODE_CHK_STATUS_MESSAGE_RETURN(AllocateBuffer(
&m_resDmemBuffer[i],
m_dmemBufferSize,
"DmemBuffer"),
"Failed to allocate Dmem Buffer.");
}
}
return eStatus;
}
MOS_STATUS CodechalDecodeHevc::AllocateResourcesVariableSizes()
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
CODECHAL_DECODE_FUNCTION_ENTER;
uint32_t widthMax = MOS_MAX(m_width, m_widthLastMaxAlloced);
uint32_t heightMax = MOS_MAX(m_height, m_heightLastMaxAlloced);
CODECHAL_DECODE_VERBOSEMESSAGE("m_width = %d, Max Width = %d, m_height %d, Max Height = %d",
m_width, widthMax, m_height, heightMax);
uint8_t maxBitDepth = (m_is12BitHevc) ? 12 :((m_is10BitHevc) ? 10 : 8);
uint8_t chromaFormatPic = m_hevcPicParams->chroma_format_idc;
uint8_t chromaFormat = m_chromaFormatinProfile;
CODECHAL_DECODE_ASSERT(chromaFormat >= chromaFormatPic);
uint32_t u32CtbLog2SizeYPic = m_hevcPicParams->log2_diff_max_min_luma_coding_block_size +
m_hevcPicParams->log2_min_luma_coding_block_size_minus3 + 3;
uint32_t ctbLog2SizeY = MOS_MAX(u32CtbLog2SizeYPic, m_ctbLog2SizeYMax);
MHW_VDBOX_HCP_BUFFER_SIZE_PARAMS hcpBufSizeParam;
MOS_ZeroMemory(&hcpBufSizeParam, sizeof(hcpBufSizeParam));
hcpBufSizeParam.ucMaxBitDepth = maxBitDepth;
hcpBufSizeParam.ucChromaFormat = chromaFormat;
hcpBufSizeParam.dwCtbLog2SizeY = ctbLog2SizeY;
MHW_VDBOX_HCP_BUFFER_REALLOC_PARAMS reallocParam;
MOS_ZeroMemory(&reallocParam, sizeof(reallocParam));
reallocParam.ucMaxBitDepth = maxBitDepth;
reallocParam.ucChromaFormat = chromaFormat;
reallocParam.dwCtbLog2SizeY = ctbLog2SizeY;
reallocParam.dwCtbLog2SizeYMax = m_ctbLog2SizeYMax;
if (m_is8BitFrameIn10BitHevc)
{
uint32_t i;
// Init 8bitRTIndexMap array, 0xff means doesn't map to any InternalNV12RTSurface.
if (!m_internalNv12RtIndexMapInitilized)
{
for (i = 0; i < CODECHAL_NUM_UNCOMPRESSED_SURFACE_HEVC; i++)
{
m_internalNv12RtIndexMap[i] = 0xff;
}
m_internalNv12RtIndexMapInitilized = true;
}
if (m_internalNv12RtIndexMap[m_currPic.FrameIdx] != 0xff)
{
if (!Mos_ResourceIsNull(&m_internalNv12RtSurfaces[m_internalNv12RtIndexMap[m_currPic.FrameIdx]].OsResource))
{
m_osInterface->pfnFreeResource(m_osInterface,
&m_internalNv12RtSurfaces[m_internalNv12RtIndexMap[m_currPic.FrameIdx]].OsResource);
}
}
// Seek an available surface in InternalNV12RTSurface array.
for (i = 0; i < CODECHAL_NUM_INTERNAL_NV12_RT_HEVC; i++)
{
if (Mos_ResourceIsNull(&m_internalNv12RtSurfaces[i].OsResource))
{
m_internalNv12RtIndexMap[m_currPic.FrameIdx] = i;
break;
}
}
// If there is no available InternalNV12RTSurface in the array.
if (i == CODECHAL_NUM_INTERNAL_NV12_RT_HEVC)
{
// Search an InternalNV12RTSurface to reuse.
for (uint32_t j = 0; j < CODECHAL_NUM_UNCOMPRESSED_SURFACE_HEVC; j++)
{
if (m_internalNv12RtIndexMap[j] != 0xff && j != m_currPic.FrameIdx)
{
uint32_t k;
// Check if InternalNV12RTSurface in reference list.
for (k = 0; k < CODEC_MAX_NUM_REF_FRAME_HEVC; k++)
{
if (j == m_hevcPicParams->RefFrameList[k].FrameIdx)
{
break;
}
}
// If InternalNV12RTSurface is not in reference list, reuse it.
if (k == CODEC_MAX_NUM_REF_FRAME_HEVC)
{
m_internalNv12RtIndexMap[m_currPic.FrameIdx] = m_internalNv12RtIndexMap[j];
m_internalNv12RtIndexMap[j] = 0xff;
break;
}
}
}
}
uint32_t internalNV12RTIndex = m_internalNv12RtIndexMap[m_currPic.FrameIdx];
if (Mos_ResourceIsNull(&m_internalNv12RtSurfaces[internalNV12RTIndex].OsResource) ||
m_destSurface.dwWidth != m_internalNv12RtSurfaces[internalNV12RTIndex].dwWidth ||
m_destSurface.dwHeight != m_internalNv12RtSurfaces[internalNV12RTIndex].dwHeight)
{
if (!Mos_ResourceIsNull(&m_internalNv12RtSurfaces[internalNV12RTIndex].OsResource))
{
m_osInterface->pfnFreeResource(m_osInterface, &m_internalNv12RtSurfaces[internalNV12RTIndex].OsResource);
}
CODECHAL_DECODE_CHK_STATUS_MESSAGE_RETURN(AllocateSurface(
&m_internalNv12RtSurfaces[internalNV12RTIndex],
m_destSurface.dwWidth,
m_destSurface.dwHeight,
"HevcInternalNV12RTSurfaces"),
"Failed to allocate Hevc Internal NV12 dest surface data buffer.");
}
}
if (!m_hcpInterface->IsHevcDfRowstoreCacheEnabled())
{
uint32_t mfdDeblockingFilterRowStoreScratchBufferPicWidthMax =
MOS_MAX(m_width, m_mfdDeblockingFilterRowStoreScratchBufferPicWidth);
reallocParam.dwPicWidth = mfdDeblockingFilterRowStoreScratchBufferPicWidthMax;
reallocParam.dwPicWidthAlloced = m_mfdDeblockingFilterRowStoreScratchBufferPicWidth;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hcpInterface->IsHevcBufferReallocNeeded(
MHW_VDBOX_HCP_INTERNAL_BUFFER_DBLK_LINE,
&reallocParam));
if (reallocParam.bNeedBiggerSize || Mos_ResourceIsNull(&m_resMfdDeblockingFilterRowStoreScratchBuffer))
{
if (!Mos_ResourceIsNull(&m_resMfdDeblockingFilterRowStoreScratchBuffer))
{
m_osInterface->pfnFreeResource(
m_osInterface,
&m_resMfdDeblockingFilterRowStoreScratchBuffer);
}
// Deblocking Filter Row Store Scratch buffer
hcpBufSizeParam.dwPicWidth = mfdDeblockingFilterRowStoreScratchBufferPicWidthMax;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hcpInterface->GetHevcBufferSize(
MHW_VDBOX_HCP_INTERNAL_BUFFER_DBLK_LINE,
&hcpBufSizeParam));
CODECHAL_DECODE_CHK_STATUS_MESSAGE_RETURN(AllocateBuffer(
&m_resMfdDeblockingFilterRowStoreScratchBuffer,
hcpBufSizeParam.dwBufferSize,
"DeblockingScratchBuffer"),
"Failed to allocate Deblocking Filter Row Store Scratch Buffer.");
}
//record the width and height used for allocation internal resources.
m_mfdDeblockingFilterRowStoreScratchBufferPicWidth = mfdDeblockingFilterRowStoreScratchBufferPicWidthMax;
}
reallocParam.dwPicWidth = widthMax;
reallocParam.dwPicWidthAlloced = m_widthLastMaxAlloced;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hcpInterface->IsHevcBufferReallocNeeded(
MHW_VDBOX_HCP_INTERNAL_BUFFER_DBLK_TILE_LINE,
&reallocParam));
if (reallocParam.bNeedBiggerSize || Mos_ResourceIsNull(&m_resDeblockingFilterTileRowStoreScratchBuffer))
{
if (!Mos_ResourceIsNull(&m_resDeblockingFilterTileRowStoreScratchBuffer))
{
m_osInterface->pfnFreeResource(
m_osInterface,
&m_resDeblockingFilterTileRowStoreScratchBuffer);
}
// Deblocking Filter Tile Row Store Scratch data surface
hcpBufSizeParam.dwPicWidth = widthMax;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hcpInterface->GetHevcBufferSize(
MHW_VDBOX_HCP_INTERNAL_BUFFER_DBLK_TILE_LINE,
&hcpBufSizeParam));
CODECHAL_DECODE_CHK_STATUS_MESSAGE_RETURN(AllocateBuffer(
&m_resDeblockingFilterTileRowStoreScratchBuffer,
hcpBufSizeParam.dwBufferSize,
"DeblockingTileScratchBuffer"),
"Failed to allocate Deblocking Filter Tile Row Store Scratch Buffer.");
}
reallocParam.dwPicHeight = heightMax;
reallocParam.dwPicHeightAlloced = m_heightLastMaxAlloced;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hcpInterface->IsHevcBufferReallocNeeded(
MHW_VDBOX_HCP_INTERNAL_BUFFER_DBLK_TILE_COL,
&reallocParam));
if (reallocParam.bNeedBiggerSize || Mos_ResourceIsNull(&m_resDeblockingFilterColumnRowStoreScratchBuffer))
{
if (!Mos_ResourceIsNull(&m_resDeblockingFilterColumnRowStoreScratchBuffer))
{
m_osInterface->pfnFreeResource(
m_osInterface,
&m_resDeblockingFilterColumnRowStoreScratchBuffer);
}
// Deblocking Filter Column Row Store Scratch data surface
hcpBufSizeParam.dwPicHeight = heightMax;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hcpInterface->GetHevcBufferSize(
MHW_VDBOX_HCP_INTERNAL_BUFFER_DBLK_TILE_COL,
&hcpBufSizeParam));
CODECHAL_DECODE_CHK_STATUS_MESSAGE_RETURN(AllocateBuffer(
&m_resDeblockingFilterColumnRowStoreScratchBuffer,
hcpBufSizeParam.dwBufferSize,
"DeblockingColumnScratchBuffer"),
"Failed to allocate Deblocking Filter Column Row Store Scratch Buffer.");
}
if (!m_hcpInterface->IsHevcDatRowstoreCacheEnabled())
{
uint32_t metadataLineBufferPicWidthMax =
MOS_MAX(m_width, m_metadataLineBufferPicWidth);
reallocParam.dwPicWidth = metadataLineBufferPicWidthMax;
reallocParam.dwPicWidthAlloced = m_metadataLineBufferPicWidth;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hcpInterface->IsHevcBufferReallocNeeded(
MHW_VDBOX_HCP_INTERNAL_BUFFER_META_LINE,
&reallocParam));
if (reallocParam.bNeedBiggerSize || Mos_ResourceIsNull(&m_resMetadataLineBuffer))
{
if (!Mos_ResourceIsNull(&m_resMetadataLineBuffer))
{
m_osInterface->pfnFreeResource(
m_osInterface,
&m_resMetadataLineBuffer);
}
// Metadata Line buffer
hcpBufSizeParam.dwPicWidth = metadataLineBufferPicWidthMax;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hcpInterface->GetHevcBufferSize(
MHW_VDBOX_HCP_INTERNAL_BUFFER_META_LINE,
&hcpBufSizeParam));
CODECHAL_DECODE_CHK_STATUS_MESSAGE_RETURN(AllocateBuffer(
&m_resMetadataLineBuffer,
hcpBufSizeParam.dwBufferSize,
"MetadataLineBuffer"),
"Failed to allocate Metadata Line Buffer.");
}
//record the width and height used for allocation internal resources.
m_metadataLineBufferPicWidth = metadataLineBufferPicWidthMax;
}
reallocParam.dwPicWidth = widthMax;
reallocParam.dwPicWidthAlloced = m_widthLastMaxAlloced;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hcpInterface->IsHevcBufferReallocNeeded(
MHW_VDBOX_HCP_INTERNAL_BUFFER_META_TILE_LINE,
&reallocParam));
if (reallocParam.bNeedBiggerSize || Mos_ResourceIsNull(&m_resMetadataTileLineBuffer))
{
if (!Mos_ResourceIsNull(&m_resMetadataTileLineBuffer))
{
m_osInterface->pfnFreeResource(
m_osInterface,
&m_resMetadataTileLineBuffer);
}
// Metadata Tile Line buffer
hcpBufSizeParam.dwPicWidth = widthMax;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hcpInterface->GetHevcBufferSize(
MHW_VDBOX_HCP_INTERNAL_BUFFER_META_TILE_LINE,
&hcpBufSizeParam));
CODECHAL_DECODE_CHK_STATUS_MESSAGE_RETURN(AllocateBuffer(
&m_resMetadataTileLineBuffer,
hcpBufSizeParam.dwBufferSize,
"MetadataTileLineBuffer"),
"Failed to allocate Metadata Tile Line Buffer.");
}
reallocParam.dwPicHeight = heightMax;
reallocParam.dwPicHeightAlloced = m_heightLastMaxAlloced;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hcpInterface->IsHevcBufferReallocNeeded(
MHW_VDBOX_HCP_INTERNAL_BUFFER_META_TILE_COL,
&reallocParam));
if (reallocParam.bNeedBiggerSize || Mos_ResourceIsNull(&m_resMetadataTileColumnBuffer))
{
if (!Mos_ResourceIsNull(&m_resMetadataTileColumnBuffer))
{
m_osInterface->pfnFreeResource(
m_osInterface,
&m_resMetadataTileColumnBuffer);
}
// Metadata Tile Column buffer
hcpBufSizeParam.dwPicHeight = heightMax;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hcpInterface->GetHevcBufferSize(
MHW_VDBOX_HCP_INTERNAL_BUFFER_META_TILE_COL,
&hcpBufSizeParam));
CODECHAL_DECODE_CHK_STATUS_MESSAGE_RETURN(AllocateBuffer(
&m_resMetadataTileColumnBuffer,
hcpBufSizeParam.dwBufferSize,
"MetadataTileColumnBuffer"),
"Failed to allocate Metadata Tile Column Buffer.");
}
if (!m_hcpInterface->IsHevcSaoRowstoreCacheEnabled())
{
uint32_t saoLineBufferPicWidthMax =
MOS_MAX(m_width, m_saoLineBufferPicWidth);
reallocParam.dwPicWidth = saoLineBufferPicWidthMax;
reallocParam.dwPicWidthAlloced = m_saoLineBufferPicWidth;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hcpInterface->IsHevcBufferReallocNeeded(
MHW_VDBOX_HCP_INTERNAL_BUFFER_SAO_LINE,
&reallocParam));
if (reallocParam.bNeedBiggerSize || Mos_ResourceIsNull(&m_resSaoLineBuffer))
{
if (!Mos_ResourceIsNull(&m_resSaoLineBuffer))
{
m_osInterface->pfnFreeResource(
m_osInterface,
&m_resSaoLineBuffer);
}
// SAO Line buffer
hcpBufSizeParam.dwPicWidth = saoLineBufferPicWidthMax;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hcpInterface->GetHevcBufferSize(
MHW_VDBOX_HCP_INTERNAL_BUFFER_SAO_LINE,
&hcpBufSizeParam));
CODECHAL_DECODE_CHK_STATUS_MESSAGE_RETURN(AllocateBuffer(
&m_resSaoLineBuffer,
hcpBufSizeParam.dwBufferSize,
"SaoLineBuffer"),
"Failed to allocate SAO Line Buffer.");
}
//record the width and height used for allocation internal resources.
m_saoLineBufferPicWidth = saoLineBufferPicWidthMax;
}
reallocParam.dwPicWidth = widthMax;
reallocParam.dwPicWidthAlloced = m_widthLastMaxAlloced;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hcpInterface->IsHevcBufferReallocNeeded(
MHW_VDBOX_HCP_INTERNAL_BUFFER_SAO_TILE_LINE,
&reallocParam));
if (reallocParam.bNeedBiggerSize || Mos_ResourceIsNull(&m_resSaoTileLineBuffer))
{
if (!Mos_ResourceIsNull(&m_resSaoTileLineBuffer))
{
m_osInterface->pfnFreeResource(
m_osInterface,
&m_resSaoTileLineBuffer);
}
// SAO Tile Line buffer
hcpBufSizeParam.dwPicWidth = widthMax;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hcpInterface->GetHevcBufferSize(
MHW_VDBOX_HCP_INTERNAL_BUFFER_SAO_TILE_LINE,
&hcpBufSizeParam));
CODECHAL_DECODE_CHK_STATUS_MESSAGE_RETURN(AllocateBuffer(
&m_resSaoTileLineBuffer,
hcpBufSizeParam.dwBufferSize,
"SaoTileLineBuffer"),
"Failed to allocate SAO Tile Line Buffer.");
}
reallocParam.dwPicHeight = heightMax;
reallocParam.dwPicHeightAlloced = m_heightLastMaxAlloced;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hcpInterface->IsHevcBufferReallocNeeded(
MHW_VDBOX_HCP_INTERNAL_BUFFER_SAO_TILE_COL,
&reallocParam));
if (reallocParam.bNeedBiggerSize || Mos_ResourceIsNull(&m_resSaoTileColumnBuffer))
{
if (!Mos_ResourceIsNull(&m_resSaoTileColumnBuffer))
{
m_osInterface->pfnFreeResource(
m_osInterface,
&m_resSaoTileColumnBuffer);
}
// SAO Tile Column buffer
hcpBufSizeParam.dwPicHeight = heightMax;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hcpInterface->GetHevcBufferSize(
MHW_VDBOX_HCP_INTERNAL_BUFFER_SAO_TILE_COL,
&hcpBufSizeParam));
CODECHAL_DECODE_CHK_STATUS_MESSAGE_RETURN(AllocateBuffer(
&m_resSaoTileColumnBuffer,
hcpBufSizeParam.dwBufferSize,
"SaoTileColumnBuffer"),
"Failed to allocate SAO Tile Column Buffer.");
}
for (uint8_t i = 0; i < CODEC_NUM_HEVC_INITIAL_MV_BUFFERS; i++)
{
AllocateMvTemporalBuffer(i);
}
m_mvBufferProgrammed = true;
if (m_secureDecoder)
{
CODECHAL_DECODE_CHK_STATUS_RETURN(m_secureDecoder->AllocateResource(this));
}
m_widthLastMaxAlloced = widthMax;
m_heightLastMaxAlloced = heightMax;
m_ctbLog2SizeYMax = ctbLog2SizeY;
return eStatus;
}
MOS_STATUS CodechalDecodeHevc::AllocateMvTemporalBuffer(
uint8_t hevcMvBuffIndex)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
CODECHAL_DECODE_FUNCTION_ENTER;
if (hevcMvBuffIndex == CODEC_NUM_HEVC_MV_BUFFERS)
{
// Should never happen, something must be wrong
CODECHAL_DECODE_ASSERTMESSAGE("Failed to get avaiable MV buffer.");
return MOS_STATUS_INVALID_PARAMETER;
}
uint32_t widthMax = MOS_MAX(m_width, m_widthLastMaxAlloced);
uint32_t heightMax = MOS_MAX(m_height, m_heightLastMaxAlloced);
MHW_VDBOX_HCP_BUFFER_REALLOC_PARAMS reallocParam;
MOS_ZeroMemory(&reallocParam, sizeof(reallocParam));
reallocParam.dwPicWidth = widthMax;
reallocParam.dwPicWidthAlloced = m_widthLastMaxAlloced;
reallocParam.dwPicHeight = heightMax;
reallocParam.dwPicHeightAlloced = m_heightLastMaxAlloced;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hcpInterface->IsHevcBufferReallocNeeded(
MHW_VDBOX_HCP_INTERNAL_BUFFER_CURR_MV_TEMPORAL,
&reallocParam));
int32_t isResMvTemporalBufferNull = Mos_ResourceIsNull(&m_resMvTemporalBuffer[hevcMvBuffIndex]);
if (reallocParam.bNeedBiggerSize || isResMvTemporalBufferNull)
{
MHW_VDBOX_HCP_BUFFER_SIZE_PARAMS hcpBufSizeParam;
MOS_ZeroMemory(&hcpBufSizeParam, sizeof(hcpBufSizeParam));
if (!isResMvTemporalBufferNull)
{
m_osInterface->pfnFreeResource(
m_osInterface,
&m_resMvTemporalBuffer[hevcMvBuffIndex]);
}
// MV Temporal buffers
hcpBufSizeParam.dwPicWidth = widthMax;
hcpBufSizeParam.dwPicHeight = heightMax;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hcpInterface->GetHevcBufferSize(
MHW_VDBOX_HCP_INTERNAL_BUFFER_CURR_MV_TEMPORAL,
&hcpBufSizeParam));
m_mvBufferSize = hcpBufSizeParam.dwBufferSize;
CODECHAL_DECODE_CHK_STATUS_MESSAGE_RETURN(AllocateBuffer(
&m_resMvTemporalBuffer[hevcMvBuffIndex],
hcpBufSizeParam.dwBufferSize,
"CurrentMvTemporalBuffer"),
"Failed to allocate MV Temporal Buffer.");
}
return eStatus;
}
CodechalDecodeHevc::~CodechalDecodeHevc ()
{
CODECHAL_DECODE_FUNCTION_ENTER;
CODECHAL_DECODE_CHK_NULL_NO_STATUS_RETURN(m_osInterface);
CODECHAL_DECODE_CHK_NULL_NO_STATUS_RETURN(m_hwInterface);
m_osInterface->pfnDestroySyncResource(m_osInterface, &m_resSyncObjectWaContextInUse);
CodecHalFreeDataList(m_hevcRefList, CODECHAL_NUM_UNCOMPRESSED_SURFACE_HEVC);
if (!Mos_ResourceIsNull(&m_resMfdDeblockingFilterRowStoreScratchBuffer))
{
m_osInterface->pfnFreeResource(
m_osInterface,
&m_resMfdDeblockingFilterRowStoreScratchBuffer);
}
m_osInterface->pfnFreeResource(
m_osInterface,
&m_resDeblockingFilterTileRowStoreScratchBuffer);
m_osInterface->pfnFreeResource(
m_osInterface,
&m_resDeblockingFilterColumnRowStoreScratchBuffer);
if (!Mos_ResourceIsNull(&m_resMetadataLineBuffer))
{
m_osInterface->pfnFreeResource(
m_osInterface,
&m_resMetadataLineBuffer);
}
m_osInterface->pfnFreeResource(
m_osInterface,
&m_resMetadataTileLineBuffer);
m_osInterface->pfnFreeResource(
m_osInterface,
&m_resMetadataTileColumnBuffer);
if (!Mos_ResourceIsNull(&m_resSaoLineBuffer))
{
m_osInterface->pfnFreeResource(
m_osInterface,
&m_resSaoLineBuffer);
}
m_osInterface->pfnFreeResource(
m_osInterface,
&m_resSaoTileLineBuffer);
m_osInterface->pfnFreeResource(
m_osInterface,
&m_resSaoTileColumnBuffer);
for (uint32_t i = 0; i < CODEC_NUM_HEVC_MV_BUFFERS; i++)
{
m_osInterface->pfnFreeResource(
m_osInterface,
&m_resMvTemporalBuffer[i]);
}
if (m_shortFormatInUse)
{
for (uint32_t i = 0; i < CODEC_HEVC_NUM_SECOND_BB; i++)
{
Mhw_FreeBb(m_osInterface, &m_secondLevelBatchBuffer[i], nullptr);
}
for (uint32_t i = 0; i < CODECHAL_HEVC_NUM_DMEM_BUFFERS; i++)
{
m_osInterface->pfnFreeResource(m_osInterface, &m_resDmemBuffer[i]);
}
}
if (!Mos_ResourceIsNull(&m_resCopyDataBuffer))
{
m_osInterface->pfnFreeResource(
m_osInterface,
&m_resCopyDataBuffer);
}
for (uint32_t i = 0; i < CODECHAL_NUM_INTERNAL_NV12_RT_HEVC; i++)
{
m_osInterface->pfnFreeResource(
m_osInterface,
&m_internalNv12RtSurfaces[i].OsResource);
}
if (m_decodeNV12ToP010 != nullptr)
{
MOS_Delete(m_decodeNV12ToP010);
}
#ifdef _DECODE_PROCESSING_SUPPORTED
if (m_sfcState)
{
MOS_Delete(m_sfcState);
m_sfcState = nullptr;
}
#endif
if (m_picMhwParams.PipeModeSelectParams)
{
MOS_Delete(m_picMhwParams.PipeModeSelectParams);
m_picMhwParams.PipeModeSelectParams = nullptr;
}
if (m_picMhwParams.SurfaceParams)
{
MOS_Delete(m_picMhwParams.SurfaceParams);
m_picMhwParams.SurfaceParams = nullptr;
}
if (m_picMhwParams.PipeBufAddrParams)
{
MOS_Delete(m_picMhwParams.PipeBufAddrParams);
m_picMhwParams.PipeBufAddrParams = nullptr;
}
if (m_picMhwParams.IndObjBaseAddrParams)
{
MOS_Delete(m_picMhwParams.IndObjBaseAddrParams);
m_picMhwParams.IndObjBaseAddrParams = nullptr;
}
if (m_picMhwParams.QmParams)
{
MOS_Delete(m_picMhwParams.QmParams);
m_picMhwParams.QmParams = nullptr;
}
if (m_picMhwParams.HevcPicState)
{
MOS_Delete(m_picMhwParams.HevcPicState);
m_picMhwParams.HevcPicState = nullptr;
}
if (m_picMhwParams.HevcTileState)
{
MOS_Delete(m_picMhwParams.HevcTileState);
m_picMhwParams.HevcTileState = nullptr;
}
return;
}
uint32_t CodechalDecodeHevc::GetDmemBufferSize()
{
return MOS_ALIGN_CEIL(sizeof(HUC_HEVC_S2L_BSS), CODECHAL_CACHELINE_SIZE);
}
MOS_STATUS CodechalDecodeHevc::SetHucDmemS2LPictureBss(
PHUC_HEVC_S2L_PIC_BSS hucHevcS2LPicBss)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
CODECHAL_DECODE_FUNCTION_ENTER;
CODECHAL_DECODE_CHK_NULL_RETURN(hucHevcS2LPicBss);
hucHevcS2LPicBss->pic_width_in_min_cbs_y = m_hevcPicParams->PicWidthInMinCbsY;
hucHevcS2LPicBss->pic_height_in_min_cbs_y = m_hevcPicParams->PicHeightInMinCbsY;
hucHevcS2LPicBss->log2_min_luma_coding_block_size_minus3 = m_hevcPicParams->log2_min_luma_coding_block_size_minus3;
hucHevcS2LPicBss->log2_diff_max_min_luma_coding_block_size = m_hevcPicParams->log2_diff_max_min_luma_coding_block_size;
hucHevcS2LPicBss->chroma_format_idc = m_hevcPicParams->chroma_format_idc;
hucHevcS2LPicBss->separate_colour_plane_flag = m_hevcPicParams->separate_colour_plane_flag;
hucHevcS2LPicBss->bit_depth_luma_minus8 = m_hevcPicParams->bit_depth_luma_minus8;
hucHevcS2LPicBss->bit_depth_chroma_minus8 = m_hevcPicParams->bit_depth_chroma_minus8;
hucHevcS2LPicBss->log2_max_pic_order_cnt_lsb_minus4 = m_hevcPicParams->log2_max_pic_order_cnt_lsb_minus4;
hucHevcS2LPicBss->sample_adaptive_offset_enabled_flag = m_hevcPicParams->sample_adaptive_offset_enabled_flag;
hucHevcS2LPicBss->num_short_term_ref_pic_sets = m_hevcPicParams->num_short_term_ref_pic_sets;
hucHevcS2LPicBss->long_term_ref_pics_present_flag = m_hevcPicParams->long_term_ref_pics_present_flag;
hucHevcS2LPicBss->num_long_term_ref_pics_sps = m_hevcPicParams->num_long_term_ref_pic_sps;
hucHevcS2LPicBss->sps_temporal_mvp_enable_flag = m_hevcPicParams->sps_temporal_mvp_enabled_flag;
hucHevcS2LPicBss->num_ref_idx_l0_default_active_minus1 = m_hevcPicParams->num_ref_idx_l0_default_active_minus1;
hucHevcS2LPicBss->num_ref_idx_l1_default_active_minus1 = m_hevcPicParams->num_ref_idx_l1_default_active_minus1;
hucHevcS2LPicBss->pic_init_qp_minus26 = m_hevcPicParams->init_qp_minus26;
hucHevcS2LPicBss->dependent_slice_segments_enabled_flag = m_hevcPicParams->dependent_slice_segments_enabled_flag;
hucHevcS2LPicBss->cabac_init_present_flag = m_hevcPicParams->cabac_init_present_flag;
hucHevcS2LPicBss->pps_slice_chroma_qp_offsets_present_flag = m_hevcPicParams->pps_slice_chroma_qp_offsets_present_flag;
hucHevcS2LPicBss->weighted_pred_flag = m_hevcPicParams->weighted_pred_flag;
hucHevcS2LPicBss->weighted_bipred_flag = m_hevcPicParams->weighted_bipred_flag;
hucHevcS2LPicBss->output_flag_present_flag = m_hevcPicParams->output_flag_present_flag;
hucHevcS2LPicBss->tiles_enabled_flag = m_hevcPicParams->tiles_enabled_flag;
hucHevcS2LPicBss->entropy_coding_sync_enabled_flag = m_hevcPicParams->entropy_coding_sync_enabled_flag;
hucHevcS2LPicBss->loop_filter_across_slices_enabled_flag = m_hevcPicParams->pps_loop_filter_across_slices_enabled_flag;
hucHevcS2LPicBss->deblocking_filter_override_enabled_flag = m_hevcPicParams->deblocking_filter_override_enabled_flag;
hucHevcS2LPicBss->pic_disable_deblocking_filter_flag = m_hevcPicParams->pps_deblocking_filter_disabled_flag;
hucHevcS2LPicBss->lists_modification_present_flag = m_hevcPicParams->lists_modification_present_flag;
hucHevcS2LPicBss->slice_segment_header_extension_present_flag = m_hevcPicParams->slice_segment_header_extension_present_flag;
hucHevcS2LPicBss->high_precision_offsets_enabled_flag = 0;
hucHevcS2LPicBss->chroma_qp_offset_list_enabled_flag = 0;
uint32_t i;
hucHevcS2LPicBss->CurrPicOrderCntVal = m_hevcPicParams->CurrPicOrderCntVal;
for (i = 0; i < CODEC_MAX_NUM_REF_FRAME_HEVC; i++)
{
hucHevcS2LPicBss->PicOrderCntValList[i] = m_hevcPicParams->PicOrderCntValList[i];
}
for (i = 0; i < 8; i++)
{
hucHevcS2LPicBss->RefPicSetStCurrBefore[i] = m_hevcPicParams->RefPicSetStCurrBefore[i];
hucHevcS2LPicBss->RefPicSetStCurrAfter[i] = m_hevcPicParams->RefPicSetStCurrAfter[i];
hucHevcS2LPicBss->RefPicSetLtCurr[i] = m_hevcPicParams->RefPicSetLtCurr[i];
}
hucHevcS2LPicBss->RefFieldPicFlag = m_hevcPicParams->RefFieldPicFlag;
hucHevcS2LPicBss->RefBottomFieldFlag = (uint8_t)m_hevcPicParams->RefBottomFieldFlag;
hucHevcS2LPicBss->pps_beta_offset_div2 = m_hevcPicParams->pps_beta_offset_div2;
hucHevcS2LPicBss->pps_tc_offset_div2 = m_hevcPicParams->pps_tc_offset_div2;
hucHevcS2LPicBss->StRPSBits = m_hevcPicParams->wNumBitsForShortTermRPSInSlice;
if (m_hevcPicParams->tiles_enabled_flag)
{
hucHevcS2LPicBss->num_tile_columns_minus1 = m_hevcPicParams->num_tile_columns_minus1;
hucHevcS2LPicBss->num_tile_rows_minus1 = m_hevcPicParams->num_tile_rows_minus1;
for (i = 0; i < HEVC_NUM_MAX_TILE_COLUMN; i++)
{
hucHevcS2LPicBss->column_width[i] = m_tileColWidth[i];
}
for (i = 0; i < HEVC_NUM_MAX_TILE_ROW; i++)
{
hucHevcS2LPicBss->row_height[i] = m_tileRowHeight[i];
}
}
hucHevcS2LPicBss->NumSlices = (uint16_t)m_numSlices;
hucHevcS2LPicBss->num_extra_slice_header_bits = m_hevcPicParams->num_extra_slice_header_bits;
for (i = 0; i < CODEC_MAX_NUM_REF_FRAME_HEVC; i++)
{
hucHevcS2LPicBss->RefIdxMapping[i] = m_refIdxMapping[i];
}
return eStatus;
}
MOS_STATUS CodechalDecodeHevc::SetHucDmemS2LSliceBss(
PHUC_HEVC_S2L_SLICE_BSS hucHevcS2LSliceBss)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
CODECHAL_DECODE_FUNCTION_ENTER;
CODECHAL_DECODE_CHK_NULL_RETURN(hucHevcS2LSliceBss);
for (uint32_t i = 0; i < m_numSlices; i++)
{
hucHevcS2LSliceBss->BSNALunitDataLocation = m_hevcSliceParams[i].slice_data_offset;
hucHevcS2LSliceBss->SliceBytesInBuffer = m_hevcSliceParams[i].slice_data_size;
hucHevcS2LSliceBss++;
}
return eStatus;
}
MOS_STATUS CodechalDecodeHevc::SetHucDmemParams(
PMOS_RESOURCE dmemBuffer)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
CODECHAL_DECODE_FUNCTION_ENTER;
CODECHAL_DECODE_CHK_NULL_RETURN(dmemBuffer);
CodechalResLock DmemLock(m_osInterface, dmemBuffer);
auto hucHevcS2LBss = (PHUC_HEVC_S2L_BSS)DmemLock.Lock(CodechalResLock::writeOnly);
CODECHAL_DECODE_CHK_NULL_RETURN(hucHevcS2LBss);
hucHevcS2LBss->ProductFamily = m_hucInterface->GetHucProductFamily();
hucHevcS2LBss->RevId = m_hwInterface->GetPlatform().usRevId;
hucHevcS2LBss->DummyRefIdxState =
MEDIA_IS_WA(m_waTable, WaDummyReference) && !m_osInterface->bSimIsActive;
CODECHAL_DECODE_CHK_STATUS_RETURN(SetHucDmemS2LPictureBss(&hucHevcS2LBss->PictureBss));
CODECHAL_DECODE_CHK_STATUS_RETURN(SetHucDmemS2LSliceBss(&hucHevcS2LBss->SliceBss[0]));
if (m_secureDecoder)
{
CODECHAL_DECODE_CHK_STATUS_RETURN(m_secureDecoder->SetHevcHucDmemS2LBss(this, &hucHevcS2LBss->PictureBss, &hucHevcS2LBss->SliceBss[0]));
}
if (m_numSlices < CODECHAL_HEVC_MAX_NUM_SLICES_LVL_6)
{
m_dmemTransferSize = (uint32_t)((uint8_t *)&(hucHevcS2LBss->SliceBss[m_numSlices]) - (uint8_t *)hucHevcS2LBss);
m_dmemTransferSize = MOS_ALIGN_CEIL(m_dmemTransferSize, CODECHAL_CACHELINE_SIZE);
}
else
{
m_dmemTransferSize = m_dmemBufferSize;
}
return eStatus;
}
MOS_STATUS CodechalDecodeHevc::GetAllTileInfo()
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
CODECHAL_DECODE_FUNCTION_ENTER;
if ((m_hevcPicParams->num_tile_columns_minus1 >= HEVC_NUM_MAX_TILE_COLUMN) ||
(m_hevcPicParams->num_tile_rows_minus1 >= HEVC_NUM_MAX_TILE_ROW))
{
CODECHAL_DECODE_ASSERTMESSAGE("num_tile_columns_minus1 or num_tile_rows_minus1 is out of range!");
return MOS_STATUS_INVALID_PARAMETER;
}
uint32_t ctbSize = 1 << (m_hevcPicParams->log2_diff_max_min_luma_coding_block_size + m_hevcPicParams->log2_min_luma_coding_block_size_minus3 + 3);
uint32_t widthInPix = (1 << (m_hevcPicParams->log2_min_luma_coding_block_size_minus3 + 3)) *
(m_hevcPicParams->PicWidthInMinCbsY);
uint32_t heightInPix = (1 << (m_hevcPicParams->log2_min_luma_coding_block_size_minus3 + 3)) *
(m_hevcPicParams->PicHeightInMinCbsY);
uint32_t widthInCtb = MOS_ROUNDUP_DIVIDE(widthInPix, ctbSize);
uint32_t heightInCtb = MOS_ROUNDUP_DIVIDE(heightInPix, ctbSize);
uint16_t *tileColWidth, *tileRowHeight;
tileColWidth = &m_tileColWidth[0];
tileRowHeight = &m_tileRowHeight[0];
if (m_hevcPicParams->uniform_spacing_flag == 1)
{
uint8_t i;
for (i = 0; i <= m_hevcPicParams->num_tile_columns_minus1; i++)
{
tileColWidth[i] = ((i + 1) * widthInCtb) / (m_hevcPicParams->num_tile_columns_minus1 + 1) -
(i * widthInCtb) / (m_hevcPicParams->num_tile_columns_minus1 + 1);
}
for (i = 0; i <= m_hevcPicParams->num_tile_rows_minus1; i++)
{
tileRowHeight[i] = ((i + 1) * heightInCtb) / (m_hevcPicParams->num_tile_rows_minus1 + 1) -
(i * heightInCtb) / (m_hevcPicParams->num_tile_rows_minus1 + 1);
}
}
else
{
uint8_t i;
tileColWidth[m_hevcPicParams->num_tile_columns_minus1] = widthInCtb & 0xffff;
for (i = 0; i < m_hevcPicParams->num_tile_columns_minus1; i++)
{
tileColWidth[i] = m_hevcPicParams->column_width_minus1[i] + 1;
tileColWidth[m_hevcPicParams->num_tile_columns_minus1] -= tileColWidth[i];
}
tileRowHeight[m_hevcPicParams->num_tile_rows_minus1] = heightInCtb & 0xffff;
for (i = 0; i < m_hevcPicParams->num_tile_rows_minus1; i++)
{
tileRowHeight[i] = m_hevcPicParams->row_height_minus1[i] + 1;
tileRowHeight[m_hevcPicParams->num_tile_rows_minus1] -= tileRowHeight[i];
}
}
return eStatus;
}
MOS_STATUS CodechalDecodeHevc::InitializeBitstreamCat ()
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
CODECHAL_DECODE_FUNCTION_ENTER;
if (m_cencBuf)
{
return eStatus;
}
m_incompletePicture = false;
m_copyDataBufferInUse = false;
m_copyDataOffset = 0;
// For multiple execution case, each execution for one frame will increase pDecoderInterface->dwFrameNum in CodecHalDecode_Decode.
// This will lead to dump index error.
// Need to make sure that pDecoderInterface->CurrPic won't update until all bitstream is copied.
m_crrPic.PicFlags = PICTURE_INVALID;
// Estimate Bytes in Bitstream per frame
PCODEC_HEVC_SLICE_PARAMS hevcLastSliceParamsInFrame = m_hevcSliceParams + (m_numSlices - 1);
m_estiBytesInBitstream = MOS_ALIGN_CEIL(hevcLastSliceParamsInFrame->slice_data_offset + hevcLastSliceParamsInFrame->slice_data_size, 64);
CODECHAL_DECODE_NORMALMESSAGE("Estimate bitstream size in this Frame: %u", m_estiBytesInBitstream);
return eStatus;
}
MOS_STATUS CodechalDecodeHevc::CopyDataSurface()
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
CODECHAL_DECODE_FUNCTION_ENTER;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_osInterface->pfnSetGpuContext(
m_osInterface,
m_videoContextForWa));
m_osInterface->pfnResetOsStates(m_osInterface);
m_osInterface->pfnSetPerfTag(
m_osInterface,
(uint16_t)(((m_mode << 4) & 0xF0) | COPY_TYPE));
m_osInterface->pfnResetPerfBufferID(m_osInterface);
MOS_COMMAND_BUFFER cmdBuffer;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_osInterface->pfnGetCommandBuffer(
m_osInterface,
&cmdBuffer,
0));
CODECHAL_DECODE_CHK_STATUS_RETURN(SendPrologWithFrameTracking(
&cmdBuffer,
false));
CODECHAL_DECODE_CHK_STATUS_RETURN(HucCopy(
&cmdBuffer, // pCmdBuffer
&m_resDataBuffer, // presSrc
&m_resCopyDataBuffer, // presDst
m_dataSize, // u32CopyLength
m_dataOffset, // u32CopyInputOffset
m_copyDataOffset)); // u32CopyOutputOffset
m_copyDataOffset += MOS_ALIGN_CEIL(m_dataSize, MHW_CACHELINE_SIZE);
MHW_MI_FLUSH_DW_PARAMS flushDwParams;
MOS_ZeroMemory(&flushDwParams, sizeof(flushDwParams));
CODECHAL_DECODE_CHK_STATUS_RETURN(m_miInterface->AddMiFlushDwCmd(
&cmdBuffer,
&flushDwParams));
CODECHAL_DECODE_CHK_STATUS_RETURN(m_miInterface->AddMiBatchBufferEnd(
&cmdBuffer,
nullptr));
m_osInterface->pfnReturnCommandBuffer(m_osInterface, &cmdBuffer, 0);
// sync resource
if (!m_incompletePicture)
{
MOS_SYNC_PARAMS syncParams = g_cInitSyncParams;
syncParams.GpuContext = m_videoContext;
syncParams.presSyncResource = &m_resSyncObjectWaContextInUse;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_osInterface->pfnEngineSignal(m_osInterface, &syncParams));
syncParams = g_cInitSyncParams;
syncParams.GpuContext = m_videoContextForWa;
syncParams.presSyncResource = &m_resSyncObjectWaContextInUse;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_osInterface->pfnEngineWait(m_osInterface, &syncParams));
}
CODECHAL_DECODE_CHK_STATUS_RETURN(m_osInterface->pfnSubmitCommandBuffer(
m_osInterface,
&cmdBuffer,
m_videoContextForWaUsesNullHw));
CODECHAL_DECODE_CHK_STATUS_RETURN(m_osInterface->pfnSetGpuContext(
m_osInterface,
m_videoContext));
return eStatus;
}
MOS_STATUS CodechalDecodeHevc::CheckAndCopyBitstream()
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
CODECHAL_DECODE_FUNCTION_ENTER;
if (m_cencBuf)
{
return eStatus;
}
if (IsFirstExecuteCall()) // first exec to decide allocate a larger buf or not
{
if (m_estiBytesInBitstream > MOS_ALIGN_CEIL(m_dataOffset + m_dataSize, 64)) // bitstream contains more bytes than current data.
{
CODECHAL_DECODE_NORMALMESSAGE("Multiple Execution Call for HEVC triggered!");
if (m_copyDataBufferSize < m_estiBytesInBitstream) // allocate an appropriate buffer
{
if (!Mos_ResourceIsNull(&m_resCopyDataBuffer))
{
m_osInterface->pfnFreeResource(
m_osInterface,
&m_resCopyDataBuffer);
}
CODECHAL_DECODE_CHK_STATUS_MESSAGE_RETURN(AllocateBuffer(
&m_resCopyDataBuffer,
m_estiBytesInBitstream,
"HevcCopyDataBuffer"),
"Failed to allocate Hevc copy data buffer.");
m_copyDataBufferSize = m_estiBytesInBitstream;
CODECHAL_DECODE_NORMALMESSAGE("Create buffersize %d for MEC.", m_copyDataBufferSize);
}
if (m_dataSize)
{
CODECHAL_DECODE_CHK_STATUS_RETURN(CopyDataSurface());
m_copyDataBufferInUse = true;
}
m_incompletePicture = true;
}
}
else
{
if (m_copyDataOffset + m_dataSize > m_copyDataBufferSize)
{
CODECHAL_DECODE_ASSERTMESSAGE("Bitstream size exceeds copy data buffer size!");
return MOS_STATUS_UNKNOWN;
}
if (m_dataSize)
{
CODECHAL_DECODE_CHK_STATUS_RETURN(CopyDataSurface());
m_frameIdx--; // to keep u32FrameIdx as normal logic meaning.
}
if (m_copyDataOffset >= m_estiBytesInBitstream)
{
m_incompletePicture = false;
}
}
return eStatus;
}
MOS_STATUS CodechalDecodeHevc::SetFrameStates ()
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
PERF_UTILITY_AUTO(__FUNCTION__, PERF_DECODE, PERF_LEVEL_HAL);
CODECHAL_DECODE_FUNCTION_ENTER;
CODECHAL_DECODE_CHK_NULL_RETURN(m_decodeParams.m_destSurface);
CODECHAL_DECODE_CHK_NULL_RETURN(m_decodeParams.m_dataBuffer);
m_frameIdx++;
// Check HuC_status2 Imem loaded bit, if 0,return error
// As driver doesn't know when can get reg value afer storing HuC_Status2 register,
// Check the reg value here at the beginning of next frame
// Check twice, first entry and second entry
if (m_shortFormatInUse &&
m_frameIdx < 3 &&
m_statusQueryReportingEnabled &&
(((m_decodeStatusBuf.m_decodeStatus->m_hucErrorStatus2 >> 32) & m_hucInterface->GetHucStatus2ImemLoadedMask()) == 0))
{
CODECHAL_DECODE_ASSERTMESSAGE("HuC IMEM Loaded fails");
return MOS_STATUS_UNKNOWN;
}
m_cencBuf = m_decodeParams.m_cencBuf;
if (IsFirstExecuteCall()) // For DRC Multiple Execution Call, no need to update every value in pHevcState except first execute
{
m_dataSize = m_decodeParams.m_dataSize;
m_dataOffset = m_decodeParams.m_dataOffset;
m_numSlices = m_decodeParams.m_numSlices;
if (m_numSlices > CODECHAL_HEVC_MAX_NUM_SLICES_LVL_6)
{
CODECHAL_DECODE_ASSERTMESSAGE("Slice number doesn't support!");
return MOS_STATUS_INVALID_PARAMETER;
}
m_hevcPicParams = (PCODEC_HEVC_PIC_PARAMS)m_decodeParams.m_picParams;
CODECHAL_DECODE_CHK_NULL_RETURN(m_decodeParams.m_sliceParams);
m_hevcSliceParams = (PCODEC_HEVC_SLICE_PARAMS)m_decodeParams.m_sliceParams;
m_hevcIqMatrixParams = (PCODECHAL_HEVC_IQ_MATRIX_PARAMS)m_decodeParams.m_iqMatrixBuffer;
m_destSurface = *(m_decodeParams.m_destSurface);
m_resDataBuffer = *(m_decodeParams.m_dataBuffer);
CODECHAL_DECODE_CHK_STATUS_RETURN(InitializeBitstreamCat());
}
else
{
m_dataSize = m_decodeParams.m_dataSize;
m_dataOffset = 0;
m_resDataBuffer = *(m_decodeParams.m_dataBuffer);
}
CODECHAL_DECODE_CHK_STATUS_RETURN(CheckAndCopyBitstream());
//For CENC case, the Entry has been initialized with value in SetParamsForDecode
PCODEC_REF_LIST destEntry = m_hevcRefList[m_hevcPicParams->CurrPic.FrameIdx];
MOS_ZeroMemory(destEntry, sizeof(CODEC_REF_LIST));
if (m_incompletePicture)
{
return MOS_STATUS_SUCCESS;
}
CODECHAL_DECODE_CHK_NULL_RETURN(m_hevcPicParams);
CODECHAL_DECODE_CHK_NULL_RETURN(m_hevcIqMatrixParams);
// Calculate bIs8bitFrameIn10bitHevc
if (MEDIA_IS_WA(m_waTable, Wa8BitFrameIn10BitHevc) &&
m_is10BitHevc &&
m_hevcPicParams->bit_depth_luma_minus8 == 0 &&
m_hevcPicParams->bit_depth_chroma_minus8 == 0 &&
m_decodeParams.m_destSurface->Format == Format_P010)
{
m_is8BitFrameIn10BitHevc = true;
}
else
{
m_is8BitFrameIn10BitHevc = false;
}
// InitNV12ToP010Context
if (m_is8BitFrameIn10BitHevc && m_decodeNV12ToP010 == nullptr)
{
m_decodeNV12ToP010 = Nv12ToP010Device::CreateFactory(m_osInterface);
CODECHAL_DECODE_CHK_NULL_RETURN(m_decodeNV12ToP010);
}
// Calculate bCurPicIntra
m_curPicIntra = true;
if (m_hevcPicParams->IntraPicFlag == 0)
{
for (uint32_t i = 0; i < CODECHAL_MAX_CUR_NUM_REF_FRAME_HEVC; i++)
{
uint8_t frameIdx = m_hevcPicParams->RefPicSetStCurrBefore[i];
if (frameIdx < 15)
{
m_curPicIntra = false;
break;
}
frameIdx = m_hevcPicParams->RefPicSetStCurrAfter[i];
if (frameIdx < 15)
{
m_curPicIntra = false;
break;
}
frameIdx = m_hevcPicParams->RefPicSetLtCurr[i];
if (frameIdx < 15)
{
m_curPicIntra = false;
break;
}
}
}
CODECHAL_DECODE_CHK_STATUS_RETURN(SetPictureStructs());
uint32_t i;
for (i = 0; i < CODEC_MAX_NUM_REF_FRAME_HEVC; i++)
{
m_frameUsedAsCurRef[i] = false;
m_refIdxMapping[i] = -1;
}
// Calculate RefIdxMapping
for (i = 0; i < CODECHAL_MAX_CUR_NUM_REF_FRAME_HEVC; i++)
{
uint8_t frameIdx = m_hevcPicParams->RefPicSetStCurrBefore[i];
if (frameIdx < CODEC_MAX_NUM_REF_FRAME_HEVC)
{
m_frameUsedAsCurRef[frameIdx] = true;
}
frameIdx = m_hevcPicParams->RefPicSetStCurrAfter[i];
if (frameIdx < CODEC_MAX_NUM_REF_FRAME_HEVC)
{
m_frameUsedAsCurRef[frameIdx] = true;
}
frameIdx = m_hevcPicParams->RefPicSetLtCurr[i];
if (frameIdx < CODEC_MAX_NUM_REF_FRAME_HEVC)
{
m_frameUsedAsCurRef[frameIdx] = true;
}
}
uint8_t curRefIdx = 0;
for (i = 0; i < CODEC_MAX_NUM_REF_FRAME_HEVC; i++)
{
if (m_frameUsedAsCurRef[i])
{
m_refIdxMapping[i] = curRefIdx++;
}
}
CODECHAL_DECODE_CHK_COND_RETURN(curRefIdx > 8,"bitstream has more than 8 references");
m_minCtbSize = 1 << (m_hevcPicParams->log2_min_luma_coding_block_size_minus3 + 3);
m_width = m_hevcPicParams->PicWidthInMinCbsY * m_minCtbSize;
m_height = m_hevcPicParams->PicHeightInMinCbsY * m_minCtbSize;
if (m_hcpInterface->IsRowStoreCachingSupported())
{
MHW_VDBOX_ROWSTORE_PARAMS rowstoreParams;
rowstoreParams.Mode = CODECHAL_DECODE_MODE_HEVCVLD;
rowstoreParams.dwPicWidth = m_width;
rowstoreParams.bMbaff = false;
rowstoreParams.ucBitDepthMinus8 = (uint8_t)MOS_MAX(m_hevcPicParams->bit_depth_luma_minus8, m_hevcPicParams->bit_depth_chroma_minus8);
rowstoreParams.ucChromaFormat = m_hevcPicParams->chroma_format_idc;
rowstoreParams.ucLCUSize = 1 << (m_hevcPicParams->log2_min_luma_coding_block_size_minus3 + 3 +
m_hevcPicParams->log2_diff_max_min_luma_coding_block_size);
m_hwInterface->SetRowstoreCachingOffsets(&rowstoreParams);
}
CODECHAL_DECODE_CHK_STATUS_RETURN(AllocateResourcesVariableSizes());
// Calculate Tile info
if (m_hevcPicParams->tiles_enabled_flag)
{
CODECHAL_DECODE_CHK_STATUS_RETURN(GetAllTileInfo());
}
m_hcpDecPhase = CodechalHcpDecodePhaseInitialized;
if (m_curPicIntra)
{
m_perfType = I_TYPE;
}
else
{
// Not possible to determine whether P or B is used for short format.
// For long format iterating through all of the slices to determine P vs
// B, so in order to avoid this, declare all other pictures MIXED_TYPE.
m_perfType = MIXED_TYPE;
}
m_crrPic = m_hevcPicParams->CurrPic;
m_secondField =
CodecHal_PictureIsBottomField(m_hevcPicParams->CurrPic);
CODECHAL_DEBUG_TOOL(
m_debugInterface->m_currPic = m_crrPic;
m_debugInterface->m_secondField = m_secondField;
m_debugInterface->m_frameType = m_perfType;
CODECHAL_DECODE_CHK_STATUS_RETURN(DumpPicParams(
m_hevcPicParams,
nullptr));
if (m_hevcIqMatrixParams) {
CODECHAL_DECODE_CHK_STATUS_RETURN(DumpIQParams(m_hevcIqMatrixParams));
}
if (m_hevcSliceParams) {
CODECHAL_DECODE_CHK_STATUS_RETURN(DumpSliceParams(
m_hevcSliceParams,
nullptr,
m_numSlices,
m_shortFormatInUse));
})
// Clear DMEM buffer program flag and increase the Dmem buffer index to program
if (m_shortFormatInUse)
{
m_dmemBufferProgrammed = false;
m_dmemBufferIdx++;
m_dmemBufferIdx %= CODECHAL_HEVC_NUM_DMEM_BUFFERS;
}
#ifdef _DECODE_PROCESSING_SUPPORTED
// Check if SFC can be supported
CODECHAL_DECODE_CHK_STATUS_RETURN(m_sfcState->CheckAndInitialize((CODECHAL_DECODE_PROCESSING_PARAMS *)m_decodeParams.m_procParams, m_hevcPicParams));
#endif
CODECHAL_DEBUG_TOOL(
if (!m_incompletePicture && !IsFirstExecuteCall()) {
CODECHAL_DECODE_CHK_STATUS_RETURN(m_debugInterface->DumpBuffer(
&m_resCopyDataBuffer,
CodechalDbgAttr::attrBitstream,
"_DEC",
m_estiBytesInBitstream,
0,
CODECHAL_NUM_MEDIA_STATES));
})
return eStatus;
}
MOS_STATUS CodechalDecodeHevc::SetPictureStructs()
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
CODECHAL_DECODE_FUNCTION_ENTER;
PCODEC_HEVC_PIC_PARAMS picParams = m_hevcPicParams;
PCODEC_REF_LIST * hevcRefList = &m_hevcRefList[0];
PCODECHAL_DECODE_HEVC_MV_LIST hevcMVBufferList = &m_hevcMvList[0];
CODEC_PICTURE prevPic = m_currPic;
m_currPic = picParams->CurrPic;
m_statusReportFeedbackNumber = picParams->StatusReportFeedbackNumber;
if (m_currPic.FrameIdx >= CODECHAL_NUM_UNCOMPRESSED_SURFACE_HEVC)
{
CODECHAL_DECODE_ASSERTMESSAGE("currPic.FrameIdx is out of range!");
return MOS_STATUS_INVALID_PARAMETER;
}
hevcRefList[m_currPic.FrameIdx]->RefPic = m_currPic;
hevcRefList[m_currPic.FrameIdx]->sFrameNumber = (int16_t)picParams->CurrPicOrderCntVal;
hevcRefList[m_currPic.FrameIdx]->iFieldOrderCnt[0] = picParams->CurrPicOrderCntVal;
hevcRefList[m_currPic.FrameIdx]->bIsIntra = m_curPicIntra;
hevcRefList[m_currPic.FrameIdx]->resRefPic = m_destSurface.OsResource;
uint8_t i;
for(i = 0; i < CODEC_MAX_NUM_REF_FRAME_HEVC; i++)
{
hevcRefList[m_currPic.FrameIdx]->RefList[i] = picParams->RefFrameList[i];
}
if(!CodecHal_PictureIsInvalid(prevPic))
{
for(i = 0; i < CODEC_NUM_HEVC_MV_BUFFERS; i++)
{
hevcMVBufferList[i].bInUse = false;
hevcMVBufferList[i].u8FrameId = 0;
}
//Mark Referenced frame's MV buffer as used
for(i = 0; i < CODEC_MAX_NUM_REF_FRAME_HEVC; i++)
{
uint8_t index = picParams->RefFrameList[i].FrameIdx;
if(!CodecHal_PictureIsInvalid(picParams->RefFrameList[i])
&& index != picParams->CurrPic.FrameIdx)
{
if (index < CODECHAL_NUM_UNCOMPRESSED_SURFACE_HEVC)
{
hevcMVBufferList[hevcRefList[index]->ucDMVIdx[0]].bInUse = true;
hevcMVBufferList[hevcRefList[index]->ucDMVIdx[0]].u8FrameId = index;
}
}
}
}
//Find out an unused MvBuffer for current frame
m_hevcMvBufferIndex = GetMvBufferIndex(
m_currPic.FrameIdx);
if (m_mvBufferProgrammed)
{
AllocateMvTemporalBuffer(m_hevcMvBufferIndex);
}
hevcRefList[m_currPic.FrameIdx]->ucDMVIdx[0] = m_hevcMvBufferIndex;
return eStatus;
}
MOS_STATUS CodechalDecodeHevc::DetermineDecodePhase()
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
CODECHAL_DECODE_FUNCTION_ENTER;
uint32_t curPhase = m_hcpDecPhase;
switch (curPhase)
{
case CodechalHcpDecodePhaseInitialized:
if (m_shortFormatInUse)
{
m_hcpDecPhase = CodechalHcpDecodePhaseLegacyS2L;
}
else
{
m_hcpDecPhase = CodechalHcpDecodePhaseLegacyLong;
}
break;
case CodechalHcpDecodePhaseLegacyS2L:
if (!m_shortFormatInUse)
{
CODECHAL_DECODE_ASSERTMESSAGE("invalid decode phase.");
return MOS_STATUS_INVALID_PARAMETER;
}
m_hcpDecPhase = CodechalHcpDecodePhaseLegacyLong;
break;
default:
CODECHAL_DECODE_ASSERTMESSAGE("invalid decode phase.");
return MOS_STATUS_INVALID_PARAMETER;
}
return eStatus;
}
MOS_STATUS CodechalDecodeHevc::DecodeStateLevel()
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
PERF_UTILITY_AUTO(__FUNCTION__, PERF_DECODE, PERF_LEVEL_HAL);
CODECHAL_DECODE_FUNCTION_ENTER;
//HEVC Decode Phase State Machine
CODECHAL_DECODE_CHK_STATUS_RETURN(DetermineDecodePhase());
// Set HEVC Decode Phase, and execute it.
if (m_shortFormatInUse && m_hcpDecPhase == CodechalHcpDecodePhaseLegacyS2L)
{
if (m_secureDecoder)
{
CODECHAL_DECODE_CHK_STATUS_RETURN(m_secureDecoder->Execute(this));
}
CODECHAL_DECODE_CHK_STATUS_RETURN(SendPictureS2L());
}
else
{
CODECHAL_DECODE_CHK_STATUS_RETURN(SendPictureLongFormat());
}
return eStatus;
}
MOS_STATUS CodechalDecodeHevc::AddPictureS2LCmds(
PMOS_COMMAND_BUFFER cmdBufferInUse)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
CODECHAL_DECODE_FUNCTION_ENTER;
CODECHAL_DECODE_CHK_NULL_RETURN(cmdBufferInUse);
if (m_statusQueryReportingEnabled)
{
CODECHAL_DECODE_CHK_STATUS_RETURN(StartStatusReport(cmdBufferInUse));
}
// Load HuC FW Kernel from WOPCM.
MHW_VDBOX_HUC_IMEM_STATE_PARAMS hucImemStateParams;
MOS_ZeroMemory(&hucImemStateParams, sizeof(hucImemStateParams));
hucImemStateParams.dwKernelDescriptor = m_hucS2lKernelId;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hucInterface->AddHucImemStateCmd(
cmdBufferInUse,
&hucImemStateParams));
// Pipe mode select
MHW_VDBOX_PIPE_MODE_SELECT_PARAMS pipeModeSelectParams;
pipeModeSelectParams.Mode = m_mode;
pipeModeSelectParams.bStreamOutEnabled = m_streamOutEnabled;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hucInterface->AddHucPipeModeSelectCmd(
cmdBufferInUse,
&pipeModeSelectParams));
// Indirect object base addr
MHW_VDBOX_IND_OBJ_BASE_ADDR_PARAMS indObjBaseAddrParams;
MOS_ZeroMemory(&indObjBaseAddrParams, sizeof(indObjBaseAddrParams));
indObjBaseAddrParams.Mode = m_mode;
indObjBaseAddrParams.dwDataSize = m_copyDataBufferInUse ? m_copyDataBufferSize : m_dataSize;
indObjBaseAddrParams.dwDataOffset = m_copyDataBufferInUse ? 0 : m_dataOffset;
indObjBaseAddrParams.presDataBuffer = m_copyDataBufferInUse ? &m_resCopyDataBuffer : &m_resDataBuffer;
if (m_secureDecoder)
{
CODECHAL_DECODE_CHK_STATUS_RETURN(m_secureDecoder->SetBitstreamBuffer(&indObjBaseAddrParams));
}
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hucInterface->AddHucIndObjBaseAddrStateCmd(
cmdBufferInUse,
&indObjBaseAddrParams));
// Virtual addr state
MHW_VDBOX_HUC_VIRTUAL_ADDR_PARAMS hucVirtualStateParams;
MOS_ZeroMemory(&hucVirtualStateParams, sizeof(hucVirtualStateParams));
hucVirtualStateParams.regionParams[0].presRegion = &m_secondLevelBatchBuffer[m_secondLevelBatchBufferIndex].OsResource;
hucVirtualStateParams.regionParams[0].isWritable = true;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hucInterface->AddHucVirtualAddrStateCmd(
cmdBufferInUse,
&hucVirtualStateParams));
// DMEM state. Pass data from driver to HuC FW.
MHW_VDBOX_HUC_DMEM_STATE_PARAMS hucDmemStateParams;
MOS_ZeroMemory(&hucDmemStateParams, sizeof(hucDmemStateParams));
hucDmemStateParams.presHucDataSource = &m_resDmemBuffer[m_dmemBufferIdx];
hucDmemStateParams.dwDmemOffset = HUC_DMEM_OFFSET_RTOS_GEMS; // If RTOS is GEMS, offset is 0x2000.
if (!m_dmemBufferProgrammed)
{
CODECHAL_DECODE_CHK_STATUS_RETURN(SetHucDmemParams(&m_resDmemBuffer[m_dmemBufferIdx]));
m_dmemBufferProgrammed = true;
}
hucDmemStateParams.dwDataLength = m_dmemTransferSize;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hucInterface->AddHucDmemStateCmd(
cmdBufferInUse,
&hucDmemStateParams));
return eStatus;
}
MOS_STATUS CodechalDecodeHevc::SendPictureS2L()
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
CODECHAL_DECODE_FUNCTION_ENTER;
if (m_enableSf2DmaSubmits)
{
m_osInterface->pfnSetPerfTag(
m_osInterface,
(uint16_t)(((CODECHAL_DECODE_MODE_HUC << 4) & 0xF0) | (m_perfType & 0xF)));
}
MOS_COMMAND_BUFFER cmdBuffer;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_osInterface->pfnGetCommandBuffer(m_osInterface, &cmdBuffer, 0));
CODECHAL_DECODE_CHK_STATUS_RETURN(SendPrologWithFrameTracking(
&cmdBuffer, true));
PMOS_COMMAND_BUFFER cmdBufferInUse = &cmdBuffer;
CODECHAL_DECODE_CHK_STATUS_RETURN(AddPictureS2LCmds(cmdBufferInUse));
m_osInterface->pfnReturnCommandBuffer(m_osInterface, &cmdBuffer, 0);
return eStatus;
}
MOS_STATUS CodechalDecodeHevc::InitPicLongFormatMhwParams()
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
CODECHAL_DECODE_FUNCTION_ENTER;
// Reset all pic Mhw Params
*m_picMhwParams.PipeModeSelectParams = {};
*m_picMhwParams.PipeBufAddrParams = {};
*m_picMhwParams.HevcPicState = {};
MOS_ZeroMemory(m_picMhwParams.SurfaceParams, sizeof(MHW_VDBOX_SURFACE_PARAMS ));
MOS_ZeroMemory(m_picMhwParams.IndObjBaseAddrParams, sizeof(MHW_VDBOX_IND_OBJ_BASE_ADDR_PARAMS));
MOS_ZeroMemory(m_picMhwParams.QmParams, sizeof(MHW_VDBOX_QM_PARAMS ));
MOS_ZeroMemory(m_picMhwParams.HevcTileState, sizeof(MHW_VDBOX_HEVC_TILE_STATE ));
PMOS_SURFACE destSurface = nullptr;
if (m_is8BitFrameIn10BitHevc)
{
destSurface = &m_internalNv12RtSurfaces[m_internalNv12RtIndexMap[m_hevcPicParams->CurrPic.FrameIdx]];
}
else
{
destSurface = &m_destSurface;
}
m_picMhwParams.PipeModeSelectParams->Mode = m_mode;
m_picMhwParams.PipeModeSelectParams->bStreamOutEnabled = m_streamOutEnabled;
m_picMhwParams.PipeModeSelectParams->bShortFormatInUse = m_shortFormatInUse;
m_picMhwParams.SurfaceParams->Mode = CODECHAL_DECODE_MODE_HEVCVLD;
m_picMhwParams.SurfaceParams->psSurface = destSurface;
m_picMhwParams.SurfaceParams->ucSurfaceStateId = CODECHAL_HCP_DECODED_SURFACE_ID;
m_picMhwParams.SurfaceParams->ChromaType = m_hevcPicParams->chroma_format_idc;
m_picMhwParams.SurfaceParams->ucBitDepthLumaMinus8 = m_hevcPicParams->bit_depth_luma_minus8;
m_picMhwParams.SurfaceParams->ucBitDepthChromaMinus8 = m_hevcPicParams->bit_depth_chroma_minus8;
m_picMhwParams.SurfaceParams->dwUVPlaneAlignment = 1 << (m_hevcPicParams->log2_min_luma_coding_block_size_minus3 + 3);
m_picMhwParams.PipeBufAddrParams->Mode = m_mode;
m_picMhwParams.PipeBufAddrParams->psPreDeblockSurface = destSurface;
if (m_is8BitFrameIn10BitHevc)
{
m_picMhwParams.PipeBufAddrParams->presP010RTSurface = &m_destSurface;
}
#ifdef _MMC_SUPPORTED
CODECHAL_DECODE_CHK_STATUS_RETURN(m_mmc->SetPipeBufAddr(m_picMhwParams.PipeBufAddrParams));
#endif
m_picMhwParams.PipeBufAddrParams->presMfdDeblockingFilterRowStoreScratchBuffer =
&m_resMfdDeblockingFilterRowStoreScratchBuffer;
m_picMhwParams.PipeBufAddrParams->presDeblockingFilterTileRowStoreScratchBuffer =
&m_resDeblockingFilterTileRowStoreScratchBuffer;
m_picMhwParams.PipeBufAddrParams->presDeblockingFilterColumnRowStoreScratchBuffer =
&m_resDeblockingFilterColumnRowStoreScratchBuffer;
m_picMhwParams.PipeBufAddrParams->presMetadataLineBuffer = &m_resMetadataLineBuffer;
m_picMhwParams.PipeBufAddrParams->presMetadataTileLineBuffer = &m_resMetadataTileLineBuffer;
m_picMhwParams.PipeBufAddrParams->presMetadataTileColumnBuffer = &m_resMetadataTileColumnBuffer;
m_picMhwParams.PipeBufAddrParams->presSaoLineBuffer = &m_resSaoLineBuffer;
m_picMhwParams.PipeBufAddrParams->presSaoTileLineBuffer = &m_resSaoTileLineBuffer;
m_picMhwParams.PipeBufAddrParams->presSaoTileColumnBuffer = &m_resSaoTileColumnBuffer;
m_picMhwParams.PipeBufAddrParams->presCurMvTempBuffer = &m_resMvTemporalBuffer[m_hevcMvBufferIndex];
MOS_ZeroMemory(m_presReferences, sizeof(PMOS_RESOURCE) * CODEC_MAX_NUM_REF_FRAME_HEVC);
MOS_ZeroMemory(m_dummyReferenceSlot, sizeof(m_dummyReferenceSlot));
if (!m_curPicIntra)
{
uint8_t i, k = 0, m = 0;
PMOS_RESOURCE firstValidFrame = nullptr;
PMOS_RESOURCE firstValidMvBuf = nullptr;
for (i = 0; i < CODEC_MAX_NUM_REF_FRAME_HEVC; i++)
{
if (m_frameUsedAsCurRef[i])
{
uint8_t refFrameValue = m_hevcPicParams->RefFrameList[i].FrameIdx;
if (refFrameValue < CODECHAL_NUM_UNCOMPRESSED_SURFACE_HEVC)
{
m_presReferences[k] = &(m_hevcRefList[refFrameValue]->resRefPic);
for (uint8_t j = 0; j < CODEC_NUM_HEVC_MV_BUFFERS; j++)
{
if ((m_hevcMvList[j].bInUse) &&
(m_hevcMvList[j].u8FrameId == refFrameValue) &&
!Mos_ResourceIsNull(&m_resMvTemporalBuffer[j]))
{
m_picMhwParams.PipeBufAddrParams->presColMvTempBuffer[m++] = &m_resMvTemporalBuffer[j];
if (firstValidMvBuf == nullptr)
{
firstValidMvBuf = &m_resMvTemporalBuffer[j];
}
break;
}
}
if (firstValidFrame == nullptr)
{
firstValidFrame = m_presReferences[k];
}
k++;
}
}
}
CODECHAL_DECODE_CHK_STATUS_RETURN(MOS_SecureMemcpy(
m_picMhwParams.PipeBufAddrParams->presReferences,
sizeof(PMOS_RESOURCE) * CODECHAL_MAX_CUR_NUM_REF_FRAME_HEVC,
m_presReferences,
sizeof(PMOS_RESOURCE) * CODECHAL_MAX_CUR_NUM_REF_FRAME_HEVC));
CODECHAL_DECODE_ASSERT(k <= 8);
CODECHAL_DECODE_ASSERT(m <= 8);
// Return error if reference surface's pitch * height is less than dest surface.
MOS_SURFACE destSurfaceDetails;
MOS_SURFACE refSurfaceDetails;
MOS_ZeroMemory(&destSurfaceDetails, sizeof(destSurfaceDetails));
destSurfaceDetails.Format = Format_Invalid;
MOS_ZeroMemory(&refSurfaceDetails, sizeof(refSurfaceDetails));
refSurfaceDetails.Format = Format_Invalid;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_osInterface->pfnGetResourceInfo(
m_osInterface,
&destSurface->OsResource,
&destSurfaceDetails));
for (uint8_t i = 0; i < CODECHAL_MAX_CUR_NUM_REF_FRAME_HEVC; i++)
{
if (m_picMhwParams.PipeBufAddrParams->presReferences[i] != nullptr)
{
CODECHAL_DECODE_CHK_STATUS_RETURN(m_osInterface->pfnGetResourceInfo(
m_osInterface,
m_picMhwParams.PipeBufAddrParams->presReferences[i],
&refSurfaceDetails));
if ((refSurfaceDetails.dwPitch * refSurfaceDetails.dwHeight) <
(destSurfaceDetails.dwPitch * destSurfaceDetails.dwHeight))
{
CODECHAL_DECODE_ASSERTMESSAGE("Reference surface's pitch * height is less than Dest surface.");
return MOS_STATUS_INVALID_PARAMETER;
}
}
}
if (firstValidFrame == nullptr)
{
firstValidFrame = &destSurface->OsResource;
}
if (firstValidMvBuf == nullptr &&
!Mos_ResourceIsNull(&m_resMvTemporalBuffer[m_hevcMvBufferIndex]))
{
firstValidMvBuf = &m_resMvTemporalBuffer[m_hevcMvBufferIndex];
}
for (uint8_t i = 0; i < CODECHAL_MAX_CUR_NUM_REF_FRAME_HEVC; i++)
{
// error concealment for the unset reference addresses and unset mv buffers
if (m_picMhwParams.PipeBufAddrParams->presReferences[i] == nullptr)
{
m_picMhwParams.PipeBufAddrParams->presReferences[i] = firstValidFrame;
}
}
for (uint32_t n = 0; n < CODEC_NUM_HEVC_MV_BUFFERS; n++)
{
if (m_picMhwParams.PipeBufAddrParams->presColMvTempBuffer[n] == nullptr &&
!Mos_ResourceIsNull(&m_resMvTemporalBuffer[n]))
{
m_picMhwParams.PipeBufAddrParams->presColMvTempBuffer[n] = &m_resMvTemporalBuffer[n];
}
}
}
// set all ref pic addresses to valid addresses for error concealment purpose
for (uint32_t i = 0; i < CODECHAL_MAX_CUR_NUM_REF_FRAME_HEVC; i++)
{
if (m_picMhwParams.PipeBufAddrParams->presReferences[i] == nullptr &&
MEDIA_IS_WA(m_waTable, WaDummyReference) &&
!Mos_ResourceIsNull(&m_dummyReference.OsResource))
{
m_picMhwParams.PipeBufAddrParams->presReferences[i] = &m_dummyReference.OsResource;
m_dummyReferenceSlot[i] = true;
}
}
#ifdef _MMC_SUPPORTED
CODECHAL_DECODE_CHK_STATUS_RETURN(m_mmc->CheckReferenceList(m_picMhwParams.PipeBufAddrParams));
CODECHAL_DECODE_CHK_STATUS_RETURN(m_mmc->SetRefrenceSync(m_disableDecodeSyncLock, m_disableLockForTranscode));
#endif
m_picMhwParams.IndObjBaseAddrParams->Mode = m_mode;
m_picMhwParams.IndObjBaseAddrParams->dwDataSize = m_copyDataBufferInUse ? m_copyDataBufferSize : m_dataSize;
m_picMhwParams.IndObjBaseAddrParams->dwDataOffset = m_copyDataBufferInUse ? 0 : m_dataOffset;
m_picMhwParams.IndObjBaseAddrParams->presDataBuffer = m_copyDataBufferInUse ? &m_resCopyDataBuffer : &m_resDataBuffer;
if (m_secureDecoder)
{
CODECHAL_DECODE_CHK_STATUS_RETURN(m_secureDecoder->SetBitstreamBuffer(m_picMhwParams.IndObjBaseAddrParams));
}
m_picMhwParams.QmParams->Standard = CODECHAL_HEVC;
m_picMhwParams.QmParams->pHevcIqMatrix = (PMHW_VDBOX_HEVC_QM_PARAMS)m_hevcIqMatrixParams;
m_picMhwParams.HevcPicState->pHevcPicParams = m_hevcPicParams;
m_picMhwParams.HevcTileState->pHevcPicParams = m_hevcPicParams;
m_picMhwParams.HevcTileState->pTileColWidth = m_tileColWidth;
m_picMhwParams.HevcTileState->pTileRowHeight = m_tileRowHeight;
return eStatus;
}
MOS_STATUS CodechalDecodeHevc::AddPictureLongFormatCmds(
PMOS_COMMAND_BUFFER cmdBufferInUse,
PIC_LONG_FORMAT_MHW_PARAMS *picMhwParams)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
CODECHAL_DECODE_FUNCTION_ENTER;
CODECHAL_DECODE_CHK_NULL_RETURN(cmdBufferInUse);
CODECHAL_DECODE_CHK_NULL_RETURN(picMhwParams);
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hcpInterface->AddHcpPipeModeSelectCmd(
cmdBufferInUse,
picMhwParams->PipeModeSelectParams));
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hcpInterface->AddHcpSurfaceCmd(
cmdBufferInUse,
picMhwParams->SurfaceParams));
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hcpInterface->AddHcpPipeBufAddrCmd(
cmdBufferInUse,
picMhwParams->PipeBufAddrParams));
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hcpInterface->AddHcpIndObjBaseAddrCmd(
cmdBufferInUse,
picMhwParams->IndObjBaseAddrParams));
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hcpInterface->AddHcpQmStateCmd(
cmdBufferInUse,
picMhwParams->QmParams));
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hcpInterface->AddHcpPicStateCmd(
cmdBufferInUse,
picMhwParams->HevcPicState));
if (m_hevcPicParams->tiles_enabled_flag)
{
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hcpInterface->AddHcpTileStateCmd(
cmdBufferInUse,
picMhwParams->HevcTileState));
}
return eStatus;
}
MOS_STATUS CodechalDecodeHevc::SendPictureLongFormat()
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
CODECHAL_DECODE_FUNCTION_ENTER;
if (m_enableSf2DmaSubmits)
{
m_osInterface->pfnSetPerfTag(
m_osInterface,
(uint16_t)(((CODECHAL_DECODE_MODE_HEVCVLD << 4) & 0xF0) | (m_perfType & 0xF)));
}
MOS_COMMAND_BUFFER cmdBuffer;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_osInterface->pfnGetCommandBuffer(m_osInterface, &cmdBuffer, 0));
auto mmioRegisters = m_hwInterface->GetMfxInterface()->GetMmioRegisters(m_vdboxIndex);
HalOcaInterface::On1stLevelBBStart(cmdBuffer, *m_osInterface->pOsContext, m_osInterface->CurrentGpuContextHandle, *m_miInterface, *mmioRegisters);
bool sendPrologWithFrameTracking = false;
if (m_shortFormatInUse)
{
sendPrologWithFrameTracking = m_enableSf2DmaSubmits;
}
else
{
sendPrologWithFrameTracking = true;
}
CODECHAL_DECODE_CHK_STATUS_RETURN(SendPrologWithFrameTracking(
&cmdBuffer,
sendPrologWithFrameTracking));
CODECHAL_DECODE_CHK_STATUS_RETURN(InitPicLongFormatMhwParams());
CODECHAL_DEBUG_TOOL(
for (uint16_t n = 0; n < CODECHAL_MAX_CUR_NUM_REF_FRAME_HEVC; n++)
{
if (m_picMhwParams.PipeBufAddrParams->presReferences[n])
{
MOS_SURFACE dstSurface;
MOS_ZeroMemory(&dstSurface, sizeof(MOS_SURFACE));
dstSurface.OsResource = *(m_picMhwParams.PipeBufAddrParams->presReferences[n]);
CODECHAL_DECODE_CHK_STATUS_RETURN(CodecHalGetResourceInfo(
m_osInterface,
&dstSurface));
m_debugInterface->m_refIndex = n;
std::string refSurfName = "RefSurf[" + std::to_string(static_cast<uint32_t>(m_debugInterface->m_refIndex)) + "]";
CODECHAL_DECODE_CHK_STATUS_RETURN(m_debugInterface->DumpYUVSurface(
&dstSurface,
CodechalDbgAttr::attrReferenceSurfaces,
refSurfName.c_str()));
}
if (m_picMhwParams.PipeBufAddrParams->presColMvTempBuffer[n])
{
m_debugInterface->m_refIndex = n;
// dump mvdata
CODECHAL_DECODE_CHK_STATUS_RETURN(m_debugInterface->DumpBuffer(
m_picMhwParams.PipeBufAddrParams->presColMvTempBuffer[n],
CodechalDbgAttr::attrMvData,
"DEC",
m_mvBufferSize));
}
}
);
PMOS_COMMAND_BUFFER cmdBufferInUse = &cmdBuffer;
//Send status report Start
if (m_statusQueryReportingEnabled)
{
CODECHAL_DECODE_CHK_STATUS_RETURN(StartStatusReport(cmdBufferInUse));
}
if (m_statusQueryReportingEnabled && m_shortFormatInUse &&
m_hcpDecPhase == CodechalHcpDecodePhaseLegacyLong)
{
uint32_t statusBufferOffset = (m_decodeStatusBuf.m_currIndex * sizeof(CodechalDecodeStatus)) +
m_decodeStatusBuf.m_storeDataOffset +
sizeof(uint32_t) * 2;
// Check HuC_STATUS bit15, HW continue if bit15 > 0, otherwise send COND BB END cmd.
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hwInterface->SendCondBbEndCmd(
&m_decodeStatusBuf.m_statusBuffer,
statusBufferOffset + m_decodeStatusBuf.m_hucErrorStatusMaskOffset,
0,
false,
cmdBufferInUse));
}
CODECHAL_DECODE_CHK_STATUS_RETURN(AddPictureLongFormatCmds(cmdBufferInUse, &m_picMhwParams));
m_osInterface->pfnReturnCommandBuffer(m_osInterface, &cmdBuffer, 0);
return eStatus;
}
MOS_STATUS CodechalDecodeHevc::SendSliceS2L(
PMOS_COMMAND_BUFFER cmdBuffer,
PMHW_VDBOX_HEVC_SLICE_STATE hevcSliceState)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
CODECHAL_DECODE_CHK_NULL_RETURN(cmdBuffer);
CODECHAL_DECODE_CHK_NULL_RETURN(hevcSliceState);
CODECHAL_DECODE_CHK_NULL_RETURN(hevcSliceState->pHevcSliceParams);
CODECHAL_DECODE_CHK_COND_RETURN(
(m_vdboxIndex > m_mfxInterface->GetMaxVdboxIndex()),
"ERROR - vdbox index exceed the maximum");
auto mmioRegisters = m_hucInterface->GetMmioRegisters(m_vdboxIndex);
if (m_secureDecoder)
{
CODECHAL_DECODE_CHK_STATUS_RETURN(m_secureDecoder->AddHucSecureState(
this,
hevcSliceState,
cmdBuffer));
}
// Send HuC Stream Obj cmd
PCODEC_HEVC_SLICE_PARAMS slc = hevcSliceState->pHevcSliceParams;
MHW_VDBOX_HUC_STREAM_OBJ_PARAMS hucStreamObjParams;
MOS_ZeroMemory(&hucStreamObjParams, sizeof(hucStreamObjParams));
hucStreamObjParams.dwIndStreamInLength = hevcSliceState->dwLength;
hucStreamObjParams.bStreamOutEnable = hevcSliceState->bHucStreamOut ? 1 : 0;
hucStreamObjParams.dwIndStreamInStartAddrOffset = slc->slice_data_offset;
hucStreamObjParams.bHucProcessing = true;
if (m_secureDecoder)
{
CODECHAL_DECODE_CHK_STATUS_RETURN(m_secureDecoder->SetHucStreamObj(
&hucStreamObjParams));
}
hucStreamObjParams.bStreamInEnable = 1;
hucStreamObjParams.bEmulPreventionByteRemoval = 1;
hucStreamObjParams.bStartCodeSearchEngine = 1;
hucStreamObjParams.ucStartCodeByte0 = 0;
hucStreamObjParams.ucStartCodeByte1 = 0;
hucStreamObjParams.ucStartCodeByte2 = 1;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hucInterface->AddHucStreamObjectCmd(
cmdBuffer,
&hucStreamObjParams));
if (m_statusQueryReportingEnabled &&
hevcSliceState->bLastSlice &&
!hevcSliceState->bHucStreamOut)
{
uint32_t statusBufferOffset = (m_decodeStatusBuf.m_currIndex * sizeof(CodechalDecodeStatus)) +
m_decodeStatusBuf.m_storeDataOffset +
sizeof(uint32_t) * 2;
// Write HUC_STATUS2 mask
MHW_MI_STORE_DATA_PARAMS storeDataParams;
MOS_ZeroMemory(&storeDataParams, sizeof(storeDataParams));
storeDataParams.pOsResource = &m_decodeStatusBuf.m_statusBuffer;
storeDataParams.dwResourceOffset = statusBufferOffset + m_decodeStatusBuf.m_hucErrorStatus2MaskOffset;
storeDataParams.dwValue = m_hucInterface->GetHucStatus2ImemLoadedMask();
CODECHAL_DECODE_CHK_STATUS_RETURN(m_miInterface->AddMiStoreDataImmCmd(
cmdBuffer,
&storeDataParams));
// store HUC_STATUS2 register
MHW_MI_STORE_REGISTER_MEM_PARAMS storeRegParams;
MOS_ZeroMemory(&storeRegParams, sizeof(storeRegParams));
storeRegParams.presStoreBuffer = &m_decodeStatusBuf.m_statusBuffer;
storeRegParams.dwOffset = statusBufferOffset + m_decodeStatusBuf.m_hucErrorStatus2RegOffset;
storeRegParams.dwRegister = mmioRegisters->hucStatus2RegOffset;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_miInterface->AddMiStoreRegisterMemCmd(
cmdBuffer,
&storeRegParams));
}
// Send HuC Start
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hucInterface->AddHucStartCmd(
cmdBuffer,
hevcSliceState->bLastSlice ? true : false));
return eStatus;
}
MOS_STATUS CodechalDecodeHevc::SendSliceLongFormat(
PMOS_COMMAND_BUFFER cmdBuffer,
PMHW_VDBOX_HEVC_SLICE_STATE hevcSliceState)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
CODECHAL_DECODE_CHK_NULL_RETURN(cmdBuffer);
CODECHAL_DECODE_CHK_NULL_RETURN(hevcSliceState);
CODECHAL_DECODE_CHK_NULL_RETURN(hevcSliceState->pHevcSliceParams);
PCODEC_HEVC_SLICE_PARAMS slc = hevcSliceState->pHevcSliceParams;
// Disable the flag when ref list is empty for P/B slices to avoid the GPU hang
if (m_curPicIntra &&
!m_hcpInterface->IsHevcISlice(slc->LongSliceFlags.fields.slice_type))
{
slc->LongSliceFlags.fields.slice_temporal_mvp_enabled_flag = 0;
}
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hcpInterface->AddHcpSliceStateCmd(
cmdBuffer,
hevcSliceState));
if (! m_hcpInterface->IsHevcISlice(slc->LongSliceFlags.fields.slice_type))
{
MHW_VDBOX_HEVC_REF_IDX_PARAMS refIdxParams;
refIdxParams.CurrPic = m_hevcPicParams->CurrPic;
refIdxParams.ucList = 0;
refIdxParams.ucNumRefForList = slc->num_ref_idx_l0_active_minus1 + 1;
eStatus = MOS_SecureMemcpy(&refIdxParams.RefPicList, sizeof(refIdxParams.RefPicList), &slc->RefPicList, sizeof(slc->RefPicList));
CODECHAL_DECODE_CHK_STATUS_MESSAGE_RETURN(eStatus, "Failed to copy memory.");
refIdxParams.hevcRefList = (void**)m_hevcRefList;
refIdxParams.poc_curr_pic = m_hevcPicParams->CurrPicOrderCntVal;
for (uint8_t i = 0; i < CODEC_MAX_NUM_REF_FRAME_HEVC; i++)
{
refIdxParams.poc_list[i] = m_hevcPicParams->PicOrderCntValList[i];
}
refIdxParams.pRefIdxMapping = hevcSliceState->pRefIdxMapping;
refIdxParams.RefFieldPicFlag = m_hevcPicParams->RefFieldPicFlag;
refIdxParams.RefBottomFieldFlag = m_hevcPicParams->RefBottomFieldFlag;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hcpInterface->AddHcpRefIdxStateCmd(
cmdBuffer,
nullptr,
&refIdxParams));
if (m_hcpInterface->IsHevcBSlice(slc->LongSliceFlags.fields.slice_type))
{
refIdxParams.ucList = 1;
refIdxParams.ucNumRefForList = slc->num_ref_idx_l1_active_minus1 + 1;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hcpInterface->AddHcpRefIdxStateCmd(
cmdBuffer,
nullptr,
&refIdxParams));
}
}
else if (MEDIA_IS_WA(m_waTable, WaDummyReference) && !m_osInterface->bSimIsActive)
{
MHW_VDBOX_HEVC_REF_IDX_PARAMS refIdxParams;
MOS_ZeroMemory(&refIdxParams, sizeof(MHW_VDBOX_HEVC_REF_IDX_PARAMS));
refIdxParams.bDummyReference = true;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hcpInterface->AddHcpRefIdxStateCmd(
cmdBuffer,
nullptr,
&refIdxParams));
}
if ((m_hevcPicParams->weighted_pred_flag &&
m_hcpInterface->IsHevcPSlice(slc->LongSliceFlags.fields.slice_type)) ||
(m_hevcPicParams->weighted_bipred_flag &&
m_hcpInterface->IsHevcBSlice(slc->LongSliceFlags.fields.slice_type)))
{
MHW_VDBOX_HEVC_WEIGHTOFFSET_PARAMS weightOffsetParams;
weightOffsetParams.ucList = 0;
eStatus = MOS_SecureMemcpy(
&weightOffsetParams.LumaWeights[0],
sizeof(weightOffsetParams.LumaWeights[0]),
&slc->delta_luma_weight_l0,
sizeof(slc->delta_luma_weight_l0));
CODECHAL_DECODE_CHK_STATUS_MESSAGE_RETURN(eStatus, "Failed to copy memory.");
eStatus = MOS_SecureMemcpy(
&weightOffsetParams.LumaWeights[1],
sizeof(weightOffsetParams.LumaWeights[1]),
&slc->delta_luma_weight_l1,
sizeof(slc->delta_luma_weight_l1));
CODECHAL_DECODE_CHK_STATUS_MESSAGE_RETURN(eStatus, "Failed to copy memory.");
for (int32_t i = 0; i < 15; i++)
{
weightOffsetParams.LumaOffsets[0][i] = (int16_t)slc->luma_offset_l0[i];
weightOffsetParams.LumaOffsets[1][i] = (int16_t)slc->luma_offset_l1[i];
for (int32_t j = 0; j < 2; j++)
{
weightOffsetParams.ChromaOffsets[0][i][j] = (int16_t)slc->ChromaOffsetL0[i][j];
weightOffsetParams.ChromaOffsets[1][i][j] = (int16_t)slc->ChromaOffsetL1[i][j];
}
}
eStatus = MOS_SecureMemcpy(
&weightOffsetParams.ChromaWeights[0],
sizeof(weightOffsetParams.ChromaWeights[0]),
&slc->delta_chroma_weight_l0,
sizeof(slc->delta_chroma_weight_l0));
CODECHAL_DECODE_CHK_STATUS_MESSAGE_RETURN(eStatus, "Failed to copy memory.");
eStatus = MOS_SecureMemcpy(
&weightOffsetParams.ChromaWeights[1],
sizeof(weightOffsetParams.ChromaWeights[1]),
&slc->delta_chroma_weight_l1,
sizeof(slc->delta_chroma_weight_l1));
CODECHAL_DECODE_CHK_STATUS_MESSAGE_RETURN(eStatus, "Failed to copy memory.");
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hcpInterface->AddHcpWeightOffsetStateCmd(
cmdBuffer,
nullptr,
&weightOffsetParams));
if (m_hcpInterface->IsHevcBSlice(slc->LongSliceFlags.fields.slice_type))
{
weightOffsetParams.ucList = 1;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hcpInterface->AddHcpWeightOffsetStateCmd(
cmdBuffer,
nullptr,
&weightOffsetParams));
}
}
if (m_secureDecoder)
{
CODECHAL_DECODE_CHK_STATUS_RETURN(m_secureDecoder->AddHcpSecureState(
cmdBuffer,
hevcSliceState));
}
MHW_VDBOX_HCP_BSD_PARAMS bsdParams;
MOS_ZeroMemory(&bsdParams, sizeof(bsdParams));
bsdParams.dwBsdDataLength = hevcSliceState->dwLength;
bsdParams.dwBsdDataStartOffset = slc->slice_data_offset + hevcSliceState->dwOffset;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hcpInterface->AddHcpBsdObjectCmd(
cmdBuffer,
&bsdParams));
return eStatus;
}
MOS_STATUS CodechalDecodeHevc::DecodePrimitiveLevel()
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
CODECHAL_DECODE_FUNCTION_ENTER;
// Bitstream is incomplete, don't do any decoding work.
if (m_incompletePicture)
{
return MOS_STATUS_SUCCESS;
}
CODECHAL_DECODE_CHK_COND_RETURN(
(m_vdboxIndex > m_mfxInterface->GetMaxVdboxIndex()),
"ERROR - vdbox index exceed the maximum");
auto mmioRegisters = m_hucInterface->GetMmioRegisters(m_vdboxIndex);
uint32_t statusBufferOffset = (m_decodeStatusBuf.m_currIndex * sizeof(CodechalDecodeStatus)) +
m_decodeStatusBuf.m_storeDataOffset +
sizeof(uint32_t) * 2;
uint32_t renderingFlags = m_videoContextUsesNullHw;
MOS_COMMAND_BUFFER cmdBuffer;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_osInterface->pfnGetCommandBuffer(m_osInterface, &cmdBuffer, 0));
PMOS_COMMAND_BUFFER cmdBufferInUse = &cmdBuffer;
// If S2L and 2nd pass, ...
// ... jump to 2nd level batch buffer.
if ((m_shortFormatInUse &&
m_hcpDecPhase == CodechalHcpDecodePhaseLegacyLong) ||
m_cencBuf)
{
if (m_enableSf2DmaSubmits)
{
#if (_DEBUG || _RELEASE_INTERNAL)
m_secondLevelBatchBuffer[m_secondLevelBatchBufferIndex].iLastCurrent = m_secondLevelBatchBuffer[m_secondLevelBatchBufferIndex].iSize;
#endif
CODECHAL_DEBUG_TOOL(
CODECHAL_DECODE_CHK_STATUS_RETURN(m_debugInterface->Dump2ndLvlBatch(
&m_secondLevelBatchBuffer[m_secondLevelBatchBufferIndex],
CODECHAL_NUM_MEDIA_STATES,
"DEC"));)
}
if (m_cencBuf)
{
CODECHAL_DECODE_CHK_STATUS_RETURN(SetCencBatchBuffer(cmdBufferInUse));
}
else
{
// this is S2L conversion
CODECHAL_DECODE_CHK_STATUS_RETURN(m_miInterface->AddMiBatchBufferStartCmd(
cmdBufferInUse,
&m_secondLevelBatchBuffer[m_secondLevelBatchBufferIndex]));
}
}
else
{
// Setup static slice state parameters
MHW_VDBOX_HEVC_SLICE_STATE hevcSliceState;
hevcSliceState.presDataBuffer = m_copyDataBufferInUse ? &m_resCopyDataBuffer : &m_resDataBuffer;
hevcSliceState.pHevcPicParams = m_hevcPicParams;
hevcSliceState.pRefIdxMapping = &m_refIdxMapping[0];
PCODEC_HEVC_SLICE_PARAMS slc = m_hevcSliceParams;
for (uint32_t slcCount = 0; slcCount < m_numSlices; slcCount++)
{
hevcSliceState.pHevcSliceParams = slc;
hevcSliceState.dwLength = slc->slice_data_size;
hevcSliceState.dwSliceIndex = slcCount;
hevcSliceState.bLastSlice = (slcCount == (m_numSlices - 1));
// If S2L and 1st pass, send HuC commands.
if (m_shortFormatInUse)
{
CODECHAL_DECODE_CHK_STATUS_RETURN(SendSliceS2L(cmdBufferInUse, &hevcSliceState));
}
else
{
CODECHAL_DECODE_CHK_STATUS_RETURN(SendSliceLongFormat(cmdBufferInUse, &hevcSliceState));
}
slc++;
}
// If S2L and 1st pass
if (m_shortFormatInUse && m_hcpDecPhase == CodechalHcpDecodePhaseLegacyS2L)
{
// Send VD Pipe Flush command for SKL+
MHW_VDBOX_VD_PIPE_FLUSH_PARAMS vdpipeFlushParams;
MOS_ZeroMemory(&vdpipeFlushParams , sizeof(vdpipeFlushParams));
vdpipeFlushParams.Flags.bWaitDoneHEVC = 1;
vdpipeFlushParams.Flags.bFlushHEVC = 1;
vdpipeFlushParams.Flags.bWaitDoneVDCmdMsgParser = 1;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_vdencInterface->AddVdPipelineFlushCmd(
cmdBufferInUse,
&vdpipeFlushParams));
MHW_MI_FLUSH_DW_PARAMS flushDwParams;
MOS_ZeroMemory(&flushDwParams, sizeof(flushDwParams));
CODECHAL_DECODE_CHK_STATUS_RETURN(m_miInterface->AddMiFlushDwCmd(
cmdBufferInUse,
&flushDwParams));
if (m_statusQueryReportingEnabled)
{
// Check HuC_STATUS2 bit6, if bit6 > 0 HW continue execution following cmd, otherwise it send a COND BB END cmd.
eStatus = m_hwInterface->SendCondBbEndCmd(
&m_decodeStatusBuf.m_statusBuffer,
statusBufferOffset + m_decodeStatusBuf.m_hucErrorStatus2MaskOffset,
0,
false,
cmdBufferInUse);
CODECHAL_DECODE_CHK_STATUS_RETURN(eStatus);
// Write HUC_STATUS mask
MHW_MI_STORE_DATA_PARAMS storeDataParams;
MOS_ZeroMemory(&storeDataParams, sizeof(storeDataParams));
storeDataParams.pOsResource = &m_decodeStatusBuf.m_statusBuffer;
storeDataParams.dwResourceOffset = statusBufferOffset + m_decodeStatusBuf.m_hucErrorStatusMaskOffset;
storeDataParams.dwValue = m_hucInterface->GetHucStatusHevcS2lFailureMask();
CODECHAL_DECODE_CHK_STATUS_RETURN(m_miInterface->AddMiStoreDataImmCmd(
cmdBufferInUse,
&storeDataParams));
// store HUC_STATUS register
MHW_MI_STORE_REGISTER_MEM_PARAMS storeRegParams;
MOS_ZeroMemory(&storeRegParams, sizeof(storeRegParams));
storeRegParams.presStoreBuffer = &m_decodeStatusBuf.m_statusBuffer;
storeRegParams.dwOffset = statusBufferOffset + m_decodeStatusBuf.m_hucErrorStatusRegOffset;
storeRegParams.dwRegister = mmioRegisters->hucStatusRegOffset;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_miInterface->AddMiStoreRegisterMemCmd(
cmdBufferInUse,
&storeRegParams));
}
if (m_enableSf2DmaSubmits)
{
CODECHAL_DECODE_CHK_STATUS_RETURN(m_miInterface->AddMiBatchBufferEnd(
cmdBufferInUse,
nullptr));
}
m_osInterface->pfnReturnCommandBuffer(m_osInterface, &cmdBuffer, 0);
if (m_enableSf2DmaSubmits)
{
CODECHAL_DEBUG_TOOL(
CODECHAL_DECODE_CHK_STATUS_RETURN(m_debugInterface->DumpCmdBuffer(
cmdBufferInUse,
CODECHAL_NUM_MEDIA_STATES,
"DEC"));
//CODECHAL_DECODE_CHK_STATUS_RETURN(CodecHal_DbgReplaceAllCommands(
// m_debugInterface,
// cmdBufferInUse));
);
//CODECHAL_DECODE_CHK_STATUS_RETURN(m_osInterface->pfnSubmitCommandBuffer(
// m_osInterface,
// cmdBufferInUse,
// renderingFlags));
}
return eStatus;
}
}
// Send VD Pipe Flush command for SKL+
MHW_VDBOX_VD_PIPE_FLUSH_PARAMS vdpipeFlushParams;
MOS_ZeroMemory(&vdpipeFlushParams , sizeof(vdpipeFlushParams));
vdpipeFlushParams.Flags.bWaitDoneHEVC = 1;
vdpipeFlushParams.Flags.bFlushHEVC = 1;
vdpipeFlushParams.Flags.bWaitDoneVDCmdMsgParser = 1;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_vdencInterface->AddVdPipelineFlushCmd(
cmdBufferInUse,
&vdpipeFlushParams));
MHW_MI_FLUSH_DW_PARAMS flushDwParams;
MOS_ZeroMemory(&flushDwParams, sizeof(flushDwParams));
CODECHAL_DECODE_CHK_STATUS_RETURN(m_miInterface->AddMiFlushDwCmd(
cmdBufferInUse,
&flushDwParams));
MOS_SYNC_PARAMS syncParams = g_cInitSyncParams;
syncParams.GpuContext = m_videoContext;
if (m_is8BitFrameIn10BitHevc)
{
syncParams.presSyncResource =
&m_internalNv12RtSurfaces[m_internalNv12RtIndexMap[m_hevcPicParams->CurrPic.FrameIdx]].OsResource;
}
else
{
syncParams.presSyncResource = &m_destSurface.OsResource;
}
syncParams.bReadOnly = false;
syncParams.bDisableDecodeSyncLock = m_disableDecodeSyncLock;
syncParams.bDisableLockForTranscode = m_disableLockForTranscode;
if (!CodecHal_PictureIsField(m_hevcPicParams->CurrPic))
{
CODECHAL_DECODE_CHK_STATUS_RETURN(m_osInterface->pfnPerformOverlaySync(m_osInterface, &syncParams));
CODECHAL_DECODE_CHK_STATUS_RETURN(m_osInterface->pfnResourceWait(m_osInterface, &syncParams));
// Update the resource tag (s/w tag) for On-Demand Sync
m_osInterface->pfnSetResourceSyncTag(m_osInterface, &syncParams);
}
// Update the tag in GPU Sync eStatus buffer (H/W Tag) to match the current S/W tag
if (m_osInterface->bTagResourceSync)
{
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hwInterface->WriteSyncTagToResource(
cmdBufferInUse,
&syncParams));
}
if (m_statusQueryReportingEnabled)
{
CodechalDecodeStatusReport decodeStatusReport;
decodeStatusReport.m_statusReportNumber = m_statusReportFeedbackNumber;
decodeStatusReport.m_currDecodedPic = m_hevcPicParams->CurrPic;
decodeStatusReport.m_currDeblockedPic = m_hevcPicParams->CurrPic;
decodeStatusReport.m_codecStatus = CODECHAL_STATUS_UNAVAILABLE;
if (m_is8BitFrameIn10BitHevc)
{
decodeStatusReport.m_currDecodedPicRes = m_destSurface.OsResource;
}
else
{
decodeStatusReport.m_currDecodedPicRes = m_hevcRefList[m_hevcPicParams->CurrPic.FrameIdx]->resRefPic;
}
#ifdef _DECODE_PROCESSING_SUPPORTED
CODECHAL_DEBUG_TOOL(
if (m_downsampledSurfaces && m_sfcState && m_sfcState->m_sfcOutputSurface) {
m_downsampledSurfaces[m_hevcPicParams->CurrPic.FrameIdx].OsResource =
m_sfcState->m_sfcOutputSurface->OsResource;
decodeStatusReport.m_currSfcOutputPicRes =
&m_downsampledSurfaces[m_hevcPicParams->CurrPic.FrameIdx].OsResource;
})
#endif
CODECHAL_DEBUG_TOOL(
decodeStatusReport.m_secondField = CodecHal_PictureIsBottomField(m_hevcPicParams->CurrPic);
decodeStatusReport.m_frameType = m_perfType;);
CODECHAL_DECODE_CHK_STATUS_RETURN(EndStatusReport(
decodeStatusReport,
cmdBufferInUse));
}
MOS_ZeroMemory(&flushDwParams, sizeof(flushDwParams));
CODECHAL_DECODE_CHK_STATUS_RETURN(m_miInterface->AddMiFlushDwCmd(
cmdBufferInUse,
&flushDwParams));
CODECHAL_DECODE_CHK_STATUS_RETURN(m_miInterface->AddMiBatchBufferEnd(
cmdBufferInUse,
nullptr));
m_osInterface->pfnReturnCommandBuffer(m_osInterface, &cmdBuffer, 0);
bool syncCompleteFrame = m_copyDataBufferInUse;
if (syncCompleteFrame)
{
//Sync up complete frame
MOS_SYNC_PARAMS copyDataSyncParams = g_cInitSyncParams;
copyDataSyncParams.GpuContext = m_videoContextForWa;
copyDataSyncParams.presSyncResource = &m_resSyncObjectWaContextInUse;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_osInterface->pfnEngineSignal(m_osInterface, ©DataSyncParams));
copyDataSyncParams = g_cInitSyncParams;
copyDataSyncParams.GpuContext = m_videoContext;
copyDataSyncParams.presSyncResource = &m_resSyncObjectWaContextInUse;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_osInterface->pfnEngineWait(m_osInterface, ©DataSyncParams));
}
CODECHAL_DEBUG_TOOL(
{
CODECHAL_DECODE_CHK_STATUS_RETURN(m_debugInterface->DumpCmdBuffer(
cmdBufferInUse,
CODECHAL_NUM_MEDIA_STATES,
"DEC"));
//CODECHAL_DECODE_CHK_STATUS_RETURN(CodecHal_DbgReplaceAllCommands(
// m_debugInterface,
// cmdBufferInUse));
}
);
HalOcaInterface::On1stLevelBBEnd(cmdBuffer, *m_osInterface);
CODECHAL_DECODE_CHK_STATUS_RETURN(m_osInterface->pfnSubmitCommandBuffer(
m_osInterface,
cmdBufferInUse,
renderingFlags));
CODECHAL_DEBUG_TOOL(
m_mmc->UpdateUserFeatureKey(&m_destSurface);)
// Reset status report
if (m_statusQueryReportingEnabled)
{
bool resetStatusReport = true;
if (resetStatusReport)
{
CODECHAL_DECODE_CHK_STATUS_RETURN(ResetStatusReport(
m_videoContextUsesNullHw));
}
}
if (m_is8BitFrameIn10BitHevc)
{
CODECHAL_DECODE_CHK_NULL_RETURN(m_decodeNV12ToP010);
CODECHAL_DECODE_CHK_STATUS_RETURN(m_decodeNV12ToP010->Execute(
&m_internalNv12RtSurfaces[m_internalNv12RtIndexMap[m_hevcPicParams->CurrPic.FrameIdx]].OsResource,
&m_destSurface.OsResource));
}
// Needs to be re-set for Linux buffer re-use scenarios
if (m_is8BitFrameIn10BitHevc)
{
m_hevcRefList[m_hevcPicParams->CurrPic.FrameIdx]->resRefPic =
m_internalNv12RtSurfaces[m_internalNv12RtIndexMap[m_hevcPicParams->CurrPic.FrameIdx]].OsResource;
}
else
{
m_hevcRefList[m_hevcPicParams->CurrPic.FrameIdx]->resRefPic =
m_destSurface.OsResource;
}
// Send the signal to indicate decode completion, in case On-Demand Sync is not present
if (!CodecHal_PictureIsField(m_hevcPicParams->CurrPic))
{
MOS_SYNC_PARAMS syncParams = g_cInitSyncParams;
syncParams.GpuContext = m_videoContext;
syncParams.presSyncResource = &m_destSurface.OsResource;
CODECHAL_DECODE_CHK_STATUS_RETURN(m_osInterface->pfnResourceSignal(m_osInterface, &syncParams));
}
#ifdef _DECODE_PROCESSING_SUPPORTED
// Send Vebox and SFC cmds
if (m_sfcState->m_sfcPipeOut)
{
CODECHAL_DECODE_CHK_STATUS_RETURN(m_sfcState->RenderStart());
}
#endif
return eStatus;
}
MOS_STATUS CodechalDecodeHevc::CalcDownsamplingParams(
void *picParams,
uint32_t *refSurfWidth,
uint32_t *refSurfHeight,
MOS_FORMAT *format,
uint8_t *frameIdx)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
CODECHAL_DECODE_CHK_NULL_RETURN(picParams);
CODECHAL_DECODE_CHK_NULL_RETURN(refSurfWidth);
CODECHAL_DECODE_CHK_NULL_RETURN(refSurfHeight);
CODECHAL_DECODE_CHK_NULL_RETURN(format);
CODECHAL_DECODE_CHK_NULL_RETURN(frameIdx);
PCODEC_HEVC_PIC_PARAMS hevcPicParams = (PCODEC_HEVC_PIC_PARAMS)picParams;
*refSurfWidth = 0;
*refSurfHeight = 0;
*format = Format_NV12;
*frameIdx = hevcPicParams->CurrPic.FrameIdx;
uint32_t widthInPix, heightInPix;
widthInPix = (1 << (hevcPicParams->log2_min_luma_coding_block_size_minus3 + 3)) * (hevcPicParams->PicWidthInMinCbsY);
heightInPix = (1 << (hevcPicParams->log2_min_luma_coding_block_size_minus3 + 3)) * (hevcPicParams->PicHeightInMinCbsY);
*refSurfWidth = MOS_ALIGN_CEIL(widthInPix, 64);
*refSurfHeight = MOS_ALIGN_CEIL(heightInPix, 64);
if (m_is10BitHevc)
{
*format = Format_P010;
}
return eStatus;
}
MOS_STATUS CodechalDecodeHevc::InitMmcState()
{
#ifdef _MMC_SUPPORTED
m_mmc = MOS_New(CodechalMmcDecodeHevc, m_hwInterface, this);
CODECHAL_DECODE_CHK_NULL_RETURN(m_mmc);
#endif
return MOS_STATUS_SUCCESS;
}
MOS_STATUS CodechalDecodeHevc::AllocateStandard (
CodechalSetting *settings)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
CODECHAL_DECODE_FUNCTION_ENTER;
CODECHAL_DECODE_CHK_NULL_RETURN(settings);
CODECHAL_DECODE_CHK_STATUS_RETURN(InitMmcState());
m_width = settings->width;
m_height = settings->height;
m_is10BitHevc = (settings->lumaChromaDepth & CODECHAL_LUMA_CHROMA_DEPTH_10_BITS) ? true : false;
m_is12BitHevc = (settings->lumaChromaDepth & CODECHAL_LUMA_CHROMA_DEPTH_12_BITS) ? true : false;
m_chromaFormatinProfile = settings->chromaFormat;
m_shortFormatInUse = settings->shortFormatInUse;
#ifdef _DECODE_PROCESSING_SUPPORTED
m_sfcState = MOS_New(CodechalHevcSfcState);
CODECHAL_DECODE_CHK_NULL_RETURN(m_sfcState);
CODECHAL_DECODE_CHK_STATUS_RETURN(m_sfcState->InitializeSfcState(
this,
m_hwInterface,
m_osInterface));
#endif
MOS_ZeroMemory(&m_currPic, sizeof(m_currPic));
m_frameIdx = 0;
if (m_shortFormatInUse)
{
// Legacy SF has 2 passes, 1st pass is S2L, 2nd pass is HEVC Long decode.
m_decodePassNum = 2;
MOS_USER_FEATURE_VALUE_DATA userFeatureData;
MOS_ZeroMemory(&userFeatureData, sizeof(userFeatureData));
MOS_UserFeature_ReadValue_ID(
nullptr,
__MEDIA_USER_FEATURE_VALUE_HEVC_SF_2_DMA_SUBMITS_ENABLE_ID,
&userFeatureData);
m_enableSf2DmaSubmits = userFeatureData.u32Data ? true : false;
}
MHW_VDBOX_STATE_CMDSIZE_PARAMS stateCmdSizeParams;
stateCmdSizeParams.bShortFormat = m_shortFormatInUse;
stateCmdSizeParams.bHucDummyStream = (m_secureDecoder ? m_secureDecoder->IsDummyStreamEnabled() : false);
// Picture Level Commands
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hwInterface->GetHxxStateCommandSize(
m_mode,
&m_commandBufferSizeNeeded,
&m_commandPatchListSizeNeeded,
&stateCmdSizeParams));
// Primitive Level Commands
CODECHAL_DECODE_CHK_STATUS_RETURN(m_hwInterface->GetHxxPrimitiveCommandSize(
m_mode,
&m_standardDecodeSizeNeeded,
&m_standardDecodePatchListSizeNeeded,
m_shortFormatInUse));
CODECHAL_DECODE_CHK_STATUS_RETURN(AllocateResourcesFixedSizes());
// Prepare Pic Params
m_picMhwParams.PipeModeSelectParams = MOS_New(MHW_VDBOX_PIPE_MODE_SELECT_PARAMS);
m_picMhwParams.SurfaceParams = MOS_New(MHW_VDBOX_SURFACE_PARAMS);
m_picMhwParams.PipeBufAddrParams = MOS_New(MHW_VDBOX_PIPE_BUF_ADDR_PARAMS);
m_picMhwParams.IndObjBaseAddrParams = MOS_New(MHW_VDBOX_IND_OBJ_BASE_ADDR_PARAMS);
m_picMhwParams.QmParams = MOS_New(MHW_VDBOX_QM_PARAMS);
m_picMhwParams.HevcPicState = MOS_New(MHW_VDBOX_HEVC_PIC_STATE);
m_picMhwParams.HevcTileState = MOS_New(MHW_VDBOX_HEVC_TILE_STATE);
MOS_ZeroMemory(m_picMhwParams.SurfaceParams, sizeof(MHW_VDBOX_SURFACE_PARAMS));
MOS_ZeroMemory(m_picMhwParams.IndObjBaseAddrParams, sizeof(MHW_VDBOX_IND_OBJ_BASE_ADDR_PARAMS));
MOS_ZeroMemory(m_picMhwParams.QmParams, sizeof(MHW_VDBOX_QM_PARAMS));
MOS_ZeroMemory(m_picMhwParams.HevcTileState, sizeof(MHW_VDBOX_HEVC_TILE_STATE));
return eStatus;
}
CodechalDecodeHevc::CodechalDecodeHevc(
CodechalHwInterface * hwInterface,
CodechalDebugInterface *debugInterface,
PCODECHAL_STANDARD_INFO standardInfo) : CodechalDecode(hwInterface, debugInterface, standardInfo),
m_minCtbSize(0),
m_is10BitHevc(false),
m_is12BitHevc(false),
m_chromaFormatinProfile(0),
m_shortFormatInUse(false),
m_dataSize(0),
m_dataOffset(0),
m_numSlices(0),
m_is8BitFrameIn10BitHevc(false),
m_internalNv12RtIndexMapInitilized(false),
m_mfdDeblockingFilterRowStoreScratchBufferPicWidth(0),
m_metadataLineBufferPicWidth(0),
m_saoLineBufferPicWidth(0),
m_mvBufferProgrammed(false),
m_secondLevelBatchBufferIndex(0),
m_dmemBufferIdx(0),
m_dmemBufferSize(0),
m_dmemTransferSize(0),
m_dmemBufferProgrammed(false),
m_copyDataBufferSize(0),
m_copyDataOffset(0),
m_copyDataBufferInUse(false),
m_estiBytesInBitstream(0),
m_curPicIntra(false),
m_mvBufferSize(0),
m_hevcMvBufferIndex(0),
m_frameIdx(0),
m_enableSf2DmaSubmits(false),
m_widthLastMaxAlloced(0),
m_heightLastMaxAlloced(0),
m_ctbLog2SizeYMax(0),
m_hcpDecPhase(0)
{
CODECHAL_DECODE_FUNCTION_ENTER;
MOS_ZeroMemory(m_internalNv12RtSurfaces, sizeof(m_internalNv12RtSurfaces));
MOS_ZeroMemory(&m_resDataBuffer, sizeof(m_resDataBuffer));
MOS_ZeroMemory(&m_resMfdDeblockingFilterRowStoreScratchBuffer, sizeof(m_resMfdDeblockingFilterRowStoreScratchBuffer));
MOS_ZeroMemory(&m_resDeblockingFilterTileRowStoreScratchBuffer, sizeof(m_resDeblockingFilterTileRowStoreScratchBuffer));
MOS_ZeroMemory(&m_resDeblockingFilterColumnRowStoreScratchBuffer, sizeof(m_resDeblockingFilterColumnRowStoreScratchBuffer));
MOS_ZeroMemory(&m_resMetadataLineBuffer, sizeof(m_resMetadataLineBuffer));
MOS_ZeroMemory(&m_resMetadataTileLineBuffer, sizeof(m_resMetadataTileLineBuffer));
MOS_ZeroMemory(&m_resMetadataTileColumnBuffer, sizeof(m_resMetadataTileColumnBuffer));
MOS_ZeroMemory(&m_resSaoLineBuffer, sizeof(m_resSaoLineBuffer));
MOS_ZeroMemory(&m_resSaoTileLineBuffer, sizeof(m_resSaoTileLineBuffer));
MOS_ZeroMemory(&m_resSaoTileColumnBuffer, sizeof(m_resSaoTileColumnBuffer));
MOS_ZeroMemory(m_resMvTemporalBuffer, sizeof(m_resMvTemporalBuffer));
MOS_ZeroMemory(m_resDmemBuffer, sizeof(m_resDmemBuffer));
MOS_ZeroMemory(&m_resCopyDataBuffer, sizeof(m_resCopyDataBuffer));
MOS_ZeroMemory(&m_resSyncObjectWaContextInUse, sizeof(m_resSyncObjectWaContextInUse));
MOS_ZeroMemory(&m_picMhwParams,sizeof(m_picMhwParams));
MOS_ZeroMemory(&m_hevcPicParams,sizeof(m_hevcPicParams));
MOS_ZeroMemory(&m_hevcSliceParams,sizeof(m_hevcSliceParams));
MOS_ZeroMemory(&m_hevcIqMatrixParams,sizeof(m_hevcIqMatrixParams));
MOS_ZeroMemory(&m_destSurface,sizeof(m_destSurface));
MOS_ZeroMemory(&m_currPic,sizeof(m_currPic));
m_hcpInUse = true;
}
#if USE_CODECHAL_DEBUG_TOOL
MOS_STATUS CodechalDecodeHevc::DumpPicParams(
PCODEC_HEVC_PIC_PARAMS picParams,
void* extPicParams)
{
CODECHAL_DEBUG_FUNCTION_ENTER;
if (!m_debugInterface->DumpIsEnabled(CodechalDbgAttr::attrPicParams))
{
return MOS_STATUS_SUCCESS;
}
CODECHAL_DEBUG_CHK_NULL(picParams);
std::ostringstream oss;
oss.setf(std::ios::showbase | std::ios::uppercase);
oss.setf(std::ios::hex, std::ios::basefield);
oss << "PicWidthInMinCbsY: " << +picParams->PicWidthInMinCbsY << std::endl;
oss << "PicHeightInMinCbsY: " << +picParams->PicHeightInMinCbsY << std::endl;
//wFormatAndSequenceInfoFlags
oss << "chroma_format_idc: " << +picParams->chroma_format_idc << std::endl;
oss << "separate_colour_plane_flag: " << +picParams->separate_colour_plane_flag << std::endl;
oss << "bit_depth_luma_minus8: " << +picParams->bit_depth_luma_minus8 << std::endl;
oss << "bit_depth_chroma_minus8: " << +picParams->bit_depth_chroma_minus8 << std::endl;
oss << "log2_max_pic_order_cnt_lsb_minus4: " << +picParams->log2_max_pic_order_cnt_lsb_minus4 << std::endl;
oss << "NoPicReorderingFlag: " << +picParams->NoPicReorderingFlag << std::endl;
oss << "ReservedBits1: " << +picParams->ReservedBits1 << std::endl;
oss << "wFormatAndSequenceInfoFlags: " << +picParams->wFormatAndSequenceInfoFlags << std::endl;
oss << "CurrPic FrameIdx: " << +picParams->CurrPic.FrameIdx << std::endl;
oss << "CurrPic PicFlags: " << +picParams->CurrPic.PicFlags << std::endl;
oss << "sps_max_dec_pic_buffering_minus1: " << +picParams->sps_max_dec_pic_buffering_minus1 << std::endl;
oss << "log2_min_luma_coding_block_size_minus3: " << +picParams->log2_min_luma_coding_block_size_minus3 << std::endl;
oss << "log2_diff_max_min_luma_coding_block_size: " << +picParams->log2_diff_max_min_luma_coding_block_size << std::endl;
oss << "log2_min_transform_block_size_minus2: " << +picParams->log2_min_transform_block_size_minus2 << std::endl;
oss << "log2_diff_max_min_transform_block_size: " << +picParams->log2_diff_max_min_transform_block_size << std::endl;
oss << "max_transform_hierarchy_depth_intra: " << +picParams->max_transform_hierarchy_depth_intra << std::endl;
oss << "max_transform_hierarchy_depth_inter: " << +picParams->max_transform_hierarchy_depth_inter << std::endl;
oss << "num_short_term_ref_pic_sets: " << +picParams->num_short_term_ref_pic_sets << std::endl;
oss << "num_long_term_ref_pic_sps: " << +picParams->num_long_term_ref_pic_sps << std::endl;
oss << "num_ref_idx_l0_default_active_minus1: " << +picParams->num_ref_idx_l0_default_active_minus1 << std::endl;
oss << "num_ref_idx_l1_default_active_minus1: " << +picParams->num_ref_idx_l1_default_active_minus1 << std::endl;
oss << "init_qp_minus26: " << +picParams->init_qp_minus26 << std::endl;
oss << "ucNumDeltaPocsOfRefRpsIdx: " << +picParams->ucNumDeltaPocsOfRefRpsIdx << std::endl;
oss << "wNumBitsForShortTermRPSInSlice: " << +picParams->wNumBitsForShortTermRPSInSlice << std::endl;
oss << "ReservedBits2: " << +picParams->ReservedBits2 << std::endl;
//dwCodingParamToolFlags
oss << "scaling_list_enabled_flag: " << +picParams->scaling_list_enabled_flag << std::endl;
oss << "amp_enabled_flag: " << +picParams->amp_enabled_flag << std::endl;
oss << "sample_adaptive_offset_enabled_flag: " << +picParams->sample_adaptive_offset_enabled_flag << std::endl;
oss << "pcm_enabled_flag: " << +picParams->pcm_enabled_flag << std::endl;
oss << "pcm_sample_bit_depth_luma_minus1: " << +picParams->pcm_sample_bit_depth_luma_minus1 << std::endl;
oss << "pcm_sample_bit_depth_chroma_minus1: " << +picParams->pcm_sample_bit_depth_chroma_minus1 << std::endl;
oss << "log2_min_pcm_luma_coding_block_size_minus3: " << +picParams->log2_min_pcm_luma_coding_block_size_minus3 << std::endl;
oss << "log2_diff_max_min_pcm_luma_coding_block_size: " << +picParams->log2_diff_max_min_pcm_luma_coding_block_size << std::endl;
oss << "pcm_loop_filter_disabled_flag: " << +picParams->pcm_loop_filter_disabled_flag << std::endl;
oss << "long_term_ref_pics_present_flag: " << +picParams->long_term_ref_pics_present_flag << std::endl;
oss << "sps_temporal_mvp_enabled_flag: " << +picParams->sps_temporal_mvp_enabled_flag << std::endl;
oss << "strong_intra_smoothing_enabled_flag: " << +picParams->strong_intra_smoothing_enabled_flag << std::endl;
oss << "dependent_slice_segments_enabled_flag: " << +picParams->dependent_slice_segments_enabled_flag << std::endl;
oss << "output_flag_present_flag: " << +picParams->output_flag_present_flag << std::endl;
oss << "num_extra_slice_header_bits: " << +picParams->num_extra_slice_header_bits << std::endl;
oss << "sign_data_hiding_enabled_flag: " << +picParams->sign_data_hiding_enabled_flag << std::endl;
oss << "cabac_init_present_flag: " << +picParams->cabac_init_present_flag << std::endl;
oss << "ReservedBits3: " << +picParams->ReservedBits3 << std::endl;
oss << "dwCodingParamToolFlags: " << +picParams->dwCodingParamToolFlags << std::endl;
//dwCodingSettingPicturePropertyFlags
oss << "constrained_intra_pred_flag: " << +picParams->constrained_intra_pred_flag << std::endl;
oss << "transform_skip_enabled_flag: " << +picParams->transform_skip_enabled_flag << std::endl;
oss << "cu_qp_delta_enabled_flag: " << +picParams->cu_qp_delta_enabled_flag << std::endl;
oss << "diff_cu_qp_delta_depth: " << +picParams->diff_cu_qp_delta_depth << std::endl;
oss << "pps_slice_chroma_qp_offsets_present_flag: " << +picParams->pps_slice_chroma_qp_offsets_present_flag << std::endl;
oss << "weighted_pred_flag: " << +picParams->weighted_pred_flag << std::endl;
oss << "weighted_bipred_flag: " << +picParams->weighted_bipred_flag << std::endl;
oss << "transquant_bypass_enabled_flag: " << +picParams->transquant_bypass_enabled_flag << std::endl;
oss << "tiles_enabled_flag: " << +picParams->tiles_enabled_flag << std::endl;
oss << "entropy_coding_sync_enabled_flag: " << +picParams->entropy_coding_sync_enabled_flag << std::endl;
oss << "uniform_spacing_flag: " << +picParams->uniform_spacing_flag << std::endl;
oss << "loop_filter_across_tiles_enabled_flag: " << +picParams->loop_filter_across_tiles_enabled_flag << std::endl;
oss << "pps_loop_filter_across_slices_enabled_flag: " << +picParams->pps_loop_filter_across_slices_enabled_flag << std::endl;
oss << "deblocking_filter_override_enabled_flag: " << +picParams->deblocking_filter_override_enabled_flag << std::endl;
oss << "pps_deblocking_filter_disabled_flag: " << +picParams->pps_deblocking_filter_disabled_flag << std::endl;
oss << "lists_modification_present_flag: " << +picParams->lists_modification_present_flag << std::endl;
oss << "slice_segment_header_extension_present_flag: " << +picParams->slice_segment_header_extension_present_flag << std::endl;
oss << "IrapPicFlag: " << +picParams->IrapPicFlag << std::endl;
oss << "IdrPicFlag: " << +picParams->IdrPicFlag << std::endl;
oss << "IntraPicFlag: " << +picParams->IntraPicFlag << std::endl;
oss << "ReservedBits4: " << +picParams->ReservedBits4 << std::endl;
oss << "dwCodingSettingPicturePropertyFlags: " << +picParams->dwCodingSettingPicturePropertyFlags << std::endl;
oss << "pps_cb_qp_offset: " << +picParams->pps_cb_qp_offset << std::endl;
oss << "pps_cr_qp_offset: " << +picParams->pps_cr_qp_offset << std::endl;
oss << "num_tile_columns_minus1: " << +picParams->num_tile_columns_minus1 << std::endl;
oss << "num_tile_rows_minus1: " << +picParams->num_tile_rows_minus1 << std::endl;
//Dump column width
oss << "column_width_minus1[19]:";
for (uint8_t i = 0; i < 19; i++)
oss << picParams->column_width_minus1[i] << " ";
oss << std::endl;
//Dump row height
oss << "row_height_minus1[21]:";
for (uint8_t i = 0; i < 21; i++)
oss << picParams->row_height_minus1[i] << " ";
oss << std::endl;
oss << "pps_beta_offset_div2: " << +picParams->pps_beta_offset_div2 << std::endl;
oss << "pps_tc_offset_div2: " << +picParams->pps_tc_offset_div2 << std::endl;
oss << "log2_parallel_merge_level_minus2: " << +picParams->log2_parallel_merge_level_minus2 << std::endl;
oss << "CurrPicOrderCntVal: " << +picParams->CurrPicOrderCntVal << std::endl;
oss.setf(std::ios::dec, std::ios::basefield);
//Dump RefFrameList[15]
for (uint8_t i = 0; i < 15; ++i)
{
oss << "RefFrameList[" << +i << "] FrameIdx:" << +picParams->RefFrameList[i].FrameIdx << std::endl;
oss << "RefFrameList[" << +i << "] PicFlags:" << +picParams->RefFrameList[i].PicFlags << std::endl;
}
//Dump POC List
oss << "PicOrderCntValList[15]:";
for (uint8_t i = 0; i < 15; i++)
oss << std::hex << picParams->PicOrderCntValList[i] << " ";
oss << std::endl;
//Dump Ref RefPicSetStCurrBefore List
oss << "RefPicSetStCurrBefore[8]:";
for (uint8_t i = 0; i < 8; i++)
oss << picParams->RefPicSetStCurrBefore[i] << " ";
oss << std::endl;
//Dump Ref RefPicSetStCurrAfter List
oss << "RefPicSetStCurrAfter[16]:";
for (uint8_t i = 0; i < 8; i++)
oss << picParams->RefPicSetStCurrAfter[i] << " ";
oss << std::endl;
//Dump Ref PicSetStCurr List
oss << "RefPicSetLtCurr[16]:";
for (uint8_t i = 0; i < 8; i++)
oss << picParams->RefPicSetLtCurr[i] << " ";
oss << std::endl;
//Dump Ref RefPicSetStCurrBefore List with POC
oss << "RefPicSetStCurrBefore[8] (POC): ";
for (uint8_t i = 0; i < 8; i++)
oss << picParams->PicOrderCntValList[picParams->RefPicSetStCurrBefore[i]] << " ";
oss << std::endl;
//Dump Ref RefPicSetStCurrAfter List with POC
oss << "RefPicSetStCurrAfter[16] (POC):";
for (uint8_t i = 0; i < 8; i++)
oss << picParams->PicOrderCntValList[picParams->RefPicSetStCurrAfter[i]] << " ";
oss << std::endl;
//Dump Ref PicSetStCurr List with POC
oss << "RefPicSetLtCurr[16] (POC): ";
for (uint8_t i = 0; i < 8; i++)
oss << picParams->PicOrderCntValList[picParams->RefPicSetLtCurr[i]] << " ";
oss << std::endl;
oss << "RefFieldPicFlag: " << +picParams->RefFieldPicFlag << std::endl;
oss << "RefBottomFieldFlag: " << +picParams->RefBottomFieldFlag << std::endl;
oss << "StatusReportFeedbackNumber: " << +picParams->StatusReportFeedbackNumber << std::endl;
const char *fileName = m_debugInterface->CreateFileName(
"_DEC",
CodechalDbgBufferType::bufPicParams,
CodechalDbgExtType::txt);
std::ofstream ofs(fileName, std::ios::out);
ofs << oss.str();
ofs.close();
return MOS_STATUS_SUCCESS;
}
MOS_STATUS CodechalDecodeHevc::DumpSliceParams(
PCODEC_HEVC_SLICE_PARAMS sliceParams,
void* extSliceParams,
uint32_t numSlices,
bool shortFormatInUse)
{
CODECHAL_DEBUG_FUNCTION_ENTER;
if (!m_debugInterface->DumpIsEnabled(CodechalDbgAttr::attrSlcParams))
{
return MOS_STATUS_SUCCESS;
}
CODECHAL_DEBUG_CHK_NULL(sliceParams);
PCODEC_HEVC_SLICE_PARAMS hevcSliceControl = nullptr;
std::ostringstream oss;
oss.setf(std::ios::showbase | std::ios::uppercase);
for (uint16_t j = 0; j < numSlices; j++)
{
hevcSliceControl = &sliceParams[j];
oss << "====================================================================================================" << std::endl;
oss << "Data for Slice number = " << +j << std::endl;
oss << "slice_data_size: " << +hevcSliceControl->slice_data_size << std::endl;
oss << "slice_data_offset: " << +hevcSliceControl->slice_data_offset << std::endl;
if (!shortFormatInUse)
{
//Dump Long format specific
oss << "ByteOffsetToSliceData: " << +hevcSliceControl->ByteOffsetToSliceData << std::endl;
oss << "slice_segment_address: " << +hevcSliceControl->slice_segment_address << std::endl;
//Dump RefPicList[2][15]
for (uint8_t i = 0; i < 15; ++i)
{
oss << "RefPicList[0][" << +i << "]";
oss << "FrameIdx: " << +hevcSliceControl->RefPicList[0][i].FrameIdx;
oss << ", PicFlags: " << +hevcSliceControl->RefPicList[0][i].PicFlags;
oss << std::endl;
}
for (uint8_t i = 0; i < 15; ++i)
{
oss << "RefPicList[1][" << +i << "]";
oss << "FrameIdx: " << +hevcSliceControl->RefPicList[1][i].FrameIdx;
oss << ", PicFlags: " << +hevcSliceControl->RefPicList[1][i].PicFlags;
oss << std::endl;
}
oss << "last_slice_of_pic: " << +hevcSliceControl->LongSliceFlags.fields.LastSliceOfPic << std::endl;
oss << "dependent_slice_segment_flag: " << +hevcSliceControl->LongSliceFlags.fields.dependent_slice_segment_flag << std::endl;
oss << "slice_type: " << +hevcSliceControl->LongSliceFlags.fields.slice_type << std::endl;
oss << "color_plane_id: " << +hevcSliceControl->LongSliceFlags.fields.color_plane_id << std::endl;
oss << "slice_sao_luma_flag: " << +hevcSliceControl->LongSliceFlags.fields.slice_sao_luma_flag << std::endl;
oss << "slice_sao_chroma_flag: " << +hevcSliceControl->LongSliceFlags.fields.slice_sao_chroma_flag << std::endl;
oss << "mvd_l1_zero_flag: " << +hevcSliceControl->LongSliceFlags.fields.mvd_l1_zero_flag << std::endl;
oss << "cabac_init_flag: " << +hevcSliceControl->LongSliceFlags.fields.cabac_init_flag << std::endl;
oss << "slice_temporal_mvp_enabled_flag: " << +hevcSliceControl->LongSliceFlags.fields.slice_temporal_mvp_enabled_flag << std::endl;
oss << "slice_deblocking_filter_disabled_flag: " << +hevcSliceControl->LongSliceFlags.fields.slice_deblocking_filter_disabled_flag << std::endl;
oss << "collocated_from_l0_flag: " << +hevcSliceControl->LongSliceFlags.fields.collocated_from_l0_flag << std::endl;
oss << "slice_loop_filter_across_slices_enabled_flag: " << +hevcSliceControl->LongSliceFlags.fields.slice_loop_filter_across_slices_enabled_flag << std::endl;
oss << "reserved: " << +hevcSliceControl->LongSliceFlags.fields.reserved << std::endl;
oss << "collocated_ref_idx: " << +hevcSliceControl->collocated_ref_idx << std::endl;
oss << "num_ref_idx_l0_active_minus1: " << +hevcSliceControl->num_ref_idx_l0_active_minus1 << std::endl;
oss << "num_ref_idx_l1_active_minus1: " << +hevcSliceControl->num_ref_idx_l1_active_minus1 << std::endl;
oss << "slice_qp_delta: " << +hevcSliceControl->slice_qp_delta << std::endl;
oss << "slice_cb_qp_offset: " << +hevcSliceControl->slice_cb_qp_offset << std::endl;
oss << "slice_cr_qp_offset: " << +hevcSliceControl->slice_cr_qp_offset << std::endl;
oss << "slice_beta_offset_div2: " << +hevcSliceControl->slice_beta_offset_div2 << std::endl;
oss << "slice_tc_offset_div2: " << +hevcSliceControl->slice_tc_offset_div2 << std::endl;
oss << "luma_log2_weight_denom: " << +hevcSliceControl->luma_log2_weight_denom << std::endl;
oss << "delta_chroma_log2_weight_denom: " << +hevcSliceControl->delta_chroma_log2_weight_denom << std::endl;
//Dump luma_offset[2][15]
for (uint8_t i = 0; i < 15; i++)
{
oss << "luma_offset_l0[" << +i << "]: " << (+hevcSliceControl->luma_offset_l0[i]) << std::endl;
oss << "luma_offset_l1[" << +i << "]: " << (+hevcSliceControl->luma_offset_l1[i]) << std::endl;
}
//Dump delta_luma_weight[2][15]
for (uint8_t i = 0; i < 15; i++)
{
oss << "delta_luma_weight_l0[" << +i << "]: " << +hevcSliceControl->delta_luma_weight_l0[i] << std::endl;
oss << "delta_luma_weight_l1[" << +i << "]: " << +hevcSliceControl->delta_luma_weight_l0[i] << std::endl;
}
//Dump chroma_offset[2][15][2]
for (uint8_t i = 0; i < 15; i++)
{
oss << "ChromaOffsetL0[" << +i << "][0]: " << (+hevcSliceControl->ChromaOffsetL0[i][0]) << std::endl;
oss << "ChromaOffsetL0[" << +i << "][1]: " << (+hevcSliceControl->ChromaOffsetL0[i][1]) << std::endl;
oss << "ChromaOffsetL1[" << +i << "][0]: " << (+hevcSliceControl->ChromaOffsetL1[i][0]) << std::endl;
oss << "ChromaOffsetL1[" << +i << "][1]: " << (+hevcSliceControl->ChromaOffsetL1[i][1]) << std::endl;
}
//Dump delta_chroma_weight[2][15][2]
for (uint8_t i = 0; i < 15; i++)
{
oss << "delta_chroma_weight_l0[" << +i << "][0]: " << +hevcSliceControl->delta_chroma_weight_l0[i][0] << std::endl;
oss << "delta_chroma_weight_l0[" << +i << "][1]: " << +hevcSliceControl->delta_chroma_weight_l0[i][1] << std::endl;
oss << "delta_chroma_weight_l1[" << +i << "][0]: " << +hevcSliceControl->delta_chroma_weight_l1[i][0] << std::endl;
oss << "delta_chroma_weight_l1[" << +i << "][1]: " << +hevcSliceControl->delta_chroma_weight_l1[i][1] << std::endl;
}
oss << "five_minus_max_num_merge_cand: " << +hevcSliceControl->five_minus_max_num_merge_cand << std::endl;
}
const char *fileName = m_debugInterface->CreateFileName(
"_DEC",
CodechalDbgBufferType::bufSlcParams,
CodechalDbgExtType::txt);
std::ofstream ofs;
if (j == 0)
{
ofs.open(fileName, std::ios::out);
}
else
{
ofs.open(fileName, std::ios::app);
}
ofs << oss.str();
ofs.close();
}
return MOS_STATUS_SUCCESS;
}
MOS_STATUS CodechalDecodeHevc::DumpIQParams(
PCODECHAL_HEVC_IQ_MATRIX_PARAMS matrixData)
{
CODECHAL_DEBUG_FUNCTION_ENTER;
if (!m_debugInterface->DumpIsEnabled(CodechalDbgAttr::attrIqParams))
{
return MOS_STATUS_SUCCESS;
}
CODECHAL_DEBUG_CHK_NULL(matrixData);
std::ostringstream oss;
oss.setf(std::ios::showbase | std::ios::uppercase);
uint32_t idx;
uint32_t idx2;
// 4x4 block
for (idx2 = 0; idx2 < 6; idx2++)
{
oss << "Qmatrix_HEVC_ucScalingLists0[" << std::dec << +idx2 << "]:" << std::endl;
oss << "ucScalingLists0[" << +idx2 << "]:";
for (uint8_t i = 0; i < 16; i++)
oss << std::hex << +matrixData->ucScalingLists0[idx2][i] << " ";
oss << std::endl;
}
// 8x8 block
for (idx2 = 0; idx2 < 6; idx2++)
{
oss << "ucScalingLists1[" << std::dec << +idx2 << "]:" << std::endl;
for (idx = 0; idx < 56; idx += 8)
{
oss << "ucScalingLists1[" << std::dec << +idx / 8 << "]:" << std::endl;
for (uint8_t i = 0; i < 8; i++)
oss << std::hex << +matrixData->ucScalingLists1[idx2][idx + i] << " ";
oss << std::endl;
}
}
// 16x16 block
for (idx2 = 0; idx2 < 6; idx2++)
{
oss << "ucScalingLists2[" << std::dec << +idx2 << "]:" << std::endl;
for (idx = 0; idx < 56; idx += 8)
{
oss << "ucScalingLists2[" << std::dec << +idx / 8 << "]:" << std::endl;
for (uint8_t i = 0; i < 8; i++)
oss << std::hex << +matrixData->ucScalingLists2[idx2][idx + i] << " ";
oss << std::endl;
}
}
// 32x32 block
for (idx2 = 0; idx2 < 2; idx2++)
{
oss << "ucScalingLists3[" << std::dec << +idx2 << "]:" << std::endl;
for (idx = 0; idx < 56; idx += 8)
{
oss << "ucScalingLists3[" << std::dec << +idx / 8 << "]:" << std::endl;
for (uint8_t i = 0; i < 8; i++)
oss << std::hex << +matrixData->ucScalingLists3[idx2][idx + i] << " ";
oss << std::endl;
}
}
//DC16x16 block
oss << "ucScalingListDCCoefSizeID2: ";
for (uint8_t i = 0; i < 6; i++)
oss << std::hex << +matrixData->ucScalingListDCCoefSizeID2[i] << " ";
oss << std::endl;
//DC32x32 block
oss << "ucScalingListDCCoefSizeID3: ";
oss << +matrixData->ucScalingListDCCoefSizeID3[0] << " " << +matrixData->ucScalingListDCCoefSizeID3[1] << std::endl;
const char *fileName = m_debugInterface->CreateFileName(
"_DEC",
CodechalDbgBufferType::bufIqParams,
CodechalDbgExtType::txt);
std::ofstream ofs(fileName, std::ios::out);
ofs << oss.str();
ofs.close();
return MOS_STATUS_SUCCESS;
}
#endif
|
#include <iostream>
using namespace std;
int main(){
int N, torre = 0, i, j, soma = 0, soma1 = 0, soma2 = 0;
cin >> N;
int somalinhas[N], somacolunas[N], matriz[N][N];
for(i=0; i<N; i++){
for(j=0; j<N; j++){
cin >> matriz[i][j];
}
}
for(i=0; i<N; i++){
soma1 = 0;
soma2 = 0;
for(j=0; j<N; j++){
soma1 += matriz[i][j];
soma2 += matriz[j][i];
}
somalinhas[i] = soma1;
somacolunas[i] = soma2;
}
for(i=0; i<N; i++){
for(j=0; j<N; j++){
soma = somalinhas[i] + somacolunas[j] - (matriz[i][j] * 2);
if(soma > torre){
torre = soma;
}
}
}
cout << torre << endl;
}
|
#include "duckdb/parser/expression/function_expression.hpp"
#include <utility>
#include "duckdb/common/string_util.hpp"
#include "duckdb/common/exception.hpp"
#include "duckdb/common/serializer.hpp"
#include "duckdb/common/types/hash.hpp"
namespace duckdb {
FunctionExpression::FunctionExpression(string schema, const string &function_name,
vector<unique_ptr<ParsedExpression>> &children,
unique_ptr<ParsedExpression> filter, bool distinct, bool is_operator)
: ParsedExpression(ExpressionType::FUNCTION, ExpressionClass::FUNCTION), schema(std::move(schema)),
function_name(StringUtil::Lower(function_name)), is_operator(is_operator), distinct(distinct),
filter(move(filter)) {
for (auto &child : children) {
this->children.push_back(move(child));
}
}
FunctionExpression::FunctionExpression(const string &function_name, vector<unique_ptr<ParsedExpression>> &children,
unique_ptr<ParsedExpression> filter, bool distinct, bool is_operator)
: FunctionExpression(INVALID_SCHEMA, function_name, children, move(filter), distinct, is_operator) {
}
string FunctionExpression::ToString() const {
if (is_operator) {
// built-in operator
if (children.size() == 1) {
return function_name + children[0]->ToString();
} else if (children.size() == 2) {
return children[0]->ToString() + " " + function_name + " " + children[1]->ToString();
}
}
// standard function call
string result = function_name + "(";
result += StringUtil::Join(children, children.size(), ", ",
[](const unique_ptr<ParsedExpression> &child) { return child->ToString(); });
return result + ")";
}
bool FunctionExpression::Equals(const FunctionExpression *a, const FunctionExpression *b) {
if (a->schema != b->schema || a->function_name != b->function_name || b->distinct != a->distinct) {
return false;
}
if (b->children.size() != a->children.size()) {
return false;
}
for (idx_t i = 0; i < a->children.size(); i++) {
if (!a->children[i]->Equals(b->children[i].get())) {
return false;
}
}
if (!BaseExpression::Equals(a->filter.get(), b->filter.get())) {
return false;
}
return true;
}
hash_t FunctionExpression::Hash() const {
hash_t result = ParsedExpression::Hash();
result = CombineHash(result, duckdb::Hash<const char *>(schema.c_str()));
result = CombineHash(result, duckdb::Hash<const char *>(function_name.c_str()));
result = CombineHash(result, duckdb::Hash<bool>(distinct));
return result;
}
unique_ptr<ParsedExpression> FunctionExpression::Copy() const {
vector<unique_ptr<ParsedExpression>> copy_children;
unique_ptr<ParsedExpression> filter_copy;
for (auto &child : children) {
copy_children.push_back(child->Copy());
}
if (filter) {
filter_copy = filter->Copy();
}
auto copy = make_unique<FunctionExpression>(function_name, copy_children, move(filter_copy), distinct, is_operator);
copy->schema = schema;
copy->CopyProperties(*this);
return move(copy);
}
void FunctionExpression::Serialize(Serializer &serializer) {
ParsedExpression::Serialize(serializer);
serializer.WriteString(function_name);
serializer.WriteString(schema);
serializer.WriteList(children);
serializer.WriteOptional(filter);
serializer.Write<bool>(distinct);
serializer.Write<bool>(is_operator);
}
unique_ptr<ParsedExpression> FunctionExpression::Deserialize(ExpressionType type, Deserializer &source) {
vector<unique_ptr<ParsedExpression>> children;
auto function_name = source.Read<string>();
auto schema = source.Read<string>();
source.ReadList<ParsedExpression>(children);
auto filter = source.ReadOptional<ParsedExpression>();
auto distinct = source.Read<bool>();
auto is_operator = source.Read<bool>();
unique_ptr<FunctionExpression> function;
function = make_unique<FunctionExpression>(function_name, children, move(filter), distinct, is_operator);
function->schema = schema;
return move(function);
}
} // namespace duckdb
|
#include <iostream>
#include <linux/input.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "VE450.hpp"
#include <errno.h>
using namespace DJI::OSDK;
using namespace DJI::OSDK::Telemetry;
int main(int argc, char** argv) {
// Initialize server variables
int sock_fd;
struct sockaddr_in serv_addr;
int client_fd;
struct sockaddr_in client_add;
char buff[101];
char command[101];
socklen_t len;
int n;
int reuse=1;
// Initialize onboard variables
int functionTimeout = 1;
// Setup OSDK.
std::cout << "VE450 program starts!\n";
LinuxSetup linuxEnvironment(argc, argv);
Vehicle* vehicle = linuxEnvironment.getVehicle();
if (vehicle == NULL) {
std::cout << "Vehicle not initialized, exiting.\n";
return -1;
}
// Obtain Control Authority
vehicle->obtainCtrlAuthority(functionTimeout);
// get gps information
Telemetry::GPSInfo gpsData;
gpsData = vehicle->broadcast->getGPSInfo();
std::cout << "latitude=" << gpsData.latitude << std::endl;
std::cout << "longtitude=" << gpsData.longitude << std::endl;
// open server
// 创建socket连接
sock_fd=socket(AF_INET,SOCK_STREAM,0);
if(sock_fd==-1)
{
perror("create socket error!");
return 0;
}
else
{
printf("Success to create socket %d\n",sock_fd);
}
//设置server地址结构
bzero(&serv_addr,sizeof(serv_addr)); //初始化结构占用内存
serv_addr.sin_family=AF_INET; //设置传输层类型IPv4
serv_addr.sin_port=htons(EHCO_PORT); //设置端口号
serv_addr.sin_addr.s_addr=htons(INADDR_ANY); //设置服务器IP地址
bzero(&(serv_addr.sin_zero),8);
//reuseaddr
setsockopt(sock_fd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse));
//绑定端口
if(bind(sock_fd,(struct sockaddr*)&serv_addr,sizeof(serv_addr))!=0)
{
printf("bind address fail %d\n",errno);
close(sock_fd);
return 0;
}
else
{
printf("Success to bind address!\n");
}
//监听端口
if(listen(sock_fd,MAX_CLIENT_NUM!=0))
{
perror("listen socket error!\n");
close(sock_fd);
return 0;
}
else
{
printf("Success to listen\n");
}
//创建连接客户端的对应套接字
len=sizeof(client_add);
client_fd=accept(sock_fd,(struct sockaddr*)&client_add,&len);
if(client_fd<=0)
{
perror("accept error!");
close(sock_fd);
return 0;
}
//接收客户端发来的数据
while(1)
{
n=recv(client_fd,buff,100,0);
if(n<=0){
fflush(stdout);
std::cout<<"disconnected, reconnecting"<<std::endl;
sleep(10);
client_fd=accept(sock_fd,(struct sockaddr*)&client_add,&len);
}
else{
buff[n]=='\0';
command[n]='\0';
strncpy(command,buff,n);
printf("receive bytes = %d data=%s\n",n,command);
fflush(stdout);
send(client_fd,command,n,0);
if(strncmp(command,"Take Off",8)==0){
TakeoffAnyway(vehicle);
}
else if(strncmp(command,"land",4)==0){
LandingAnyway(vehicle);
}
else if(strncmp(command,"forward",7)==0){
moveByPositionOffset(vehicle,5,0,0,0);
}
else if(strncmp(command,"quit",4)==0)
break;
}
}
std::cout << "Automatic takeoff and landing test for VE450 starts..." << std::endl;
/*TakeoffAnyway(vehicle);
moveByPositionOffset(vehicle,0,0,0,0);
moveByPositionOffset(vehicle,0,0,0,0);
moveByPositionOffset(vehicle,0,0,0,0);
LandingAnyway(vehicle);
std::cout
<< "Test over."
<<std::endl;
// Display interactive prompt
/*std::cout
<< "| Available commands: |"
<< std::endl;
std::cout
<< "| [a] Takeoff + Landing |"
<< std::endl;
std::cout
<< "| [b] Takeoff + Position Control + Landing |"
<< std::endl;
char inputChar;
std::cin >> inputChar;
switch (inputChar) {
case 'a':
monitoredTakeoff(vehicle);
monitoredLanding(vehicle);
break;
case 'b':
monitoredTakeoff(vehicle);
moveByPositionOffset(vehicle, 0, 6, 6, 30);
moveByPositionOffset(vehicle, 6, 0, -3, -30);
moveByPositionOffset(vehicle, -6, -6, 0, 0);
monitoredLanding(vehicle);
break;
default:
break;
}*/
// close server
close(client_fd);
close(sock_fd);
return 0;
}
|
/**
* particle_filter.cpp
*
* Created on: Dec 12, 2016
* Author: Tiffany Huang
*/
#include "particle_filter.h"
#include <math.h>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <numeric>
#include <random>
#include <string>
#include <vector>
#include "helper_functions.h"
//using std::string;
//using std::vector;
using namespace std;
void ParticleFilter::init(double x, double y, double theta, double std[]) {
/**
* TODO: Set the number of particles. Initialize all particles to
* first position (based on estimates of x, y, theta and their uncertainties
* from GPS) and all weights to 1.
* TODO: Add random Gaussian noise to each particle.
* NOTE: Consult particle_filter.h for more information about this method
* (and others in this file).
*/
num_particles = 100; // TODO: Set the number of particles
// Declare a random engine generates pseudo-random numbers
default_random_engine gen;
// Creating normal distributions
normal_distribution<double> dist_x(x, std[0]);
normal_distribution<double> dist_y(y, std[1]);
normal_distribution<double> dist_theta(theta, std[2]);
// Generate particles with normal distribution with mean on GPS values.
for (int i = 0; i < num_particles; i++) {
Particle particle;
particle.id = i;
particle.x = dist_x(gen);
particle.y = dist_y(gen);
particle.theta = dist_theta(gen);
particle.weight = 1.0;
particles.push_back(particle);
}
// The filter is now initialized.
is_initialized = true;
}
void ParticleFilter::prediction(double delta_t, double std_pos[],
double velocity, double yaw_rate) {
/**
* TODO: Add measurements to each particle and add random Gaussian noise.
* NOTE: When adding noise you may find std::normal_distribution
* and std::default_random_engine useful.
* http://en.cppreference.com/w/cpp/numeric/random/normal_distribution
* http://www.cplusplus.com/reference/random/default_random_engine/
*/
// Declare a random engine generates pseudo-random numbers
default_random_engine gen;
//Normal distributions for sensor noise
normal_distribution<double> dist_x(0, std_pos[0]);
normal_distribution<double> dist_y(0, std_pos[1]);
normal_distribution<double> dist_theta(0, std_pos[2]);
// Calculate new state.
for (int i = 0; i < num_particles; i++) {
if ( fabs(yaw_rate) < 0.0001 ) { // When yaw is not changing.
particles[i].x += velocity * delta_t * cos(particles[i].theta);
particles[i].y += velocity * delta_t * sin(particles[i].theta);
} else {
particles[i].x += velocity/yaw_rate * (sin(particles[i].theta + yaw_rate*delta_t) - sin(particles[i].theta));
particles[i].y += velocity/yaw_rate * (cos(particles[i].theta) - cos(particles[i].theta + yaw_rate*delta_t));
particles[i].theta += yaw_rate * delta_t;
}
// Adding noise.
particles[i].x += dist_x(gen);
particles[i].y += dist_y(gen);
particles[i].theta += dist_theta(gen);
}
}
void ParticleFilter::dataAssociation(vector<LandmarkObs> predicted,
vector<LandmarkObs>& observations) {
/**
* TODO: Find the predicted measurement that is closest to each
* observed measurement and assign the observed measurement to this
* particular landmark.
* NOTE: this method will NOT be called by the grading code. But you will
* probably find it useful to implement this method and use it as a helper
* during the updateWeights phase.
*/
unsigned int nObservations = observations.size();
unsigned int nPredictions = predicted.size();
for (unsigned int i = 0; i < nObservations; i++) { // For each observation
double minDistance = numeric_limits<double>::max(); // init min distance
// Initialize the found map in something not possible.
int mapId = -1;
double obs_x = observations[i].x;
double obs_y = observations[i].y;
for (unsigned int j = 0; j < nPredictions; j++ ) { // For each
double pred_x = predicted[j].x;
double pred_y = predicted[j].y;
double distance = dist(obs_x, obs_y, pred_x, pred_y);
// If the "distance" is less than min, stored the id and update min.
if ( distance < minDistance ) {
minDistance = distance;
mapId = predicted[j].id;
}
}
// Update the observation identifier.
observations[i].id = mapId;
}
}
void ParticleFilter::updateWeights(double sensor_range, double std_landmark[],
const vector<LandmarkObs> &observations,
const Map &map_landmarks) {
/**
* TODO: Update the weights of each particle using a mult-variate Gaussian
* distribution. You can read more about this distribution here:
* https://en.wikipedia.org/wiki/Multivariate_normal_distribution
* NOTE: The observations are given in the VEHICLE'S coordinate system.
* Your particles are located according to the MAP'S coordinate system.
* You will need to transform between the two systems. Keep in mind that
* this transformation requires both rotation AND translation (but no scaling).
* The following is a good resource for the theory:
* https://www.willamette.edu/~gorr/classes/GeneralGraphics/Transforms/transforms2d.htm
* and the following is a good resource for the actual equation to implement
* (look at equation 3.33) http://planning.cs.uiuc.edu/node99.html
*/
for (int i = 0; i < num_particles; i++) {
double paricle_x = particles[i].x;
double paricle_y = particles[i].y;
double paricle_theta = particles[i].theta;
// Step 1: Get landmarks in particle's range.
vector<LandmarkObs> inRangeLandmarks;
for(unsigned int j = 0; j < map_landmarks.landmark_list.size(); j++) {
float landmarkX = map_landmarks.landmark_list[j].x_f;
float landmarkY = map_landmarks.landmark_list[j].y_f;
int landmarkID = map_landmarks.landmark_list[j].id_i;
double dX = fabs(landmarkX - paricle_x);
double dY = fabs(landmarkY - paricle_y);
if ( dX <= sensor_range && dY <= sensor_range ) {
inRangeLandmarks.push_back(LandmarkObs{ landmarkID, landmarkX, landmarkY });
}
}
// Step 2: Transform the coordinates
vector<LandmarkObs> mapped_obs;
unsigned int nObservations = observations.size();
for(unsigned int j = 0; j < nObservations; j++) {
double mapped_x = cos(paricle_theta)*observations[j].x - sin(paricle_theta)*observations[j].y + paricle_x;
double mapped_y = sin(paricle_theta)*observations[j].x + cos(paricle_theta)*observations[j].y + paricle_y;
mapped_obs.push_back(LandmarkObs{ observations[j].id, mapped_x, mapped_y });
}
// Step 3: Observation association to landmark.
dataAssociation(inRangeLandmarks, mapped_obs);
// Step 4: Calculate weights.
// Iterate each measurement "taken" by the particle
for (unsigned int j = 0; j < mapped_obs.size(); j++) {
double obs_X = mapped_obs[j].x;
double obs_Y = mapped_obs[j].y;
double x_l,y_l;
unsigned int nLandmarks = inRangeLandmarks.size();
for (unsigned int k = 0; k < nLandmarks; k++) {
if (inRangeLandmarks[k].id == mapped_obs[j].id) {
x_l = inRangeLandmarks[k].x;
y_l = inRangeLandmarks[k].y;
}
}
//calculate measurement weight
particles[i].weight = 1.0; // reseting the weight
double s_x = std_landmark[0];
double s_y = std_landmark[1];
double normalizer = (1/(2 * M_PI * s_x * s_y));
double gaussian_term1 = pow(obs_X - x_l,2)/(2*pow(s_x, 2));
double gaussian_term2 = pow(obs_Y - y_l,2)/(2*pow(s_y, 2));
double meas_w = normalizer * exp( -( gaussian_term1 + gaussian_term2 ) );
if (meas_w == 0) {
particles[i].weight *= 0.0001;
} else {
particles[i].weight *= meas_w;
}
}
}
}
void ParticleFilter::resample() {
/**
* TODO: Resample particles with replacement with probability proportional
* to their weight.
* NOTE: You may find std::discrete_distribution helpful here.
* http://en.cppreference.com/w/cpp/numeric/random/discrete_distribution
*/
// Create a generator to be used for generating random particle index and beta value
default_random_engine gen;
//Get weights and max weight.
vector<double> weights;
double maxWeight = numeric_limits<double>::min();
for(int i = 0; i < num_particles; i++) {
weights.push_back(particles[i].weight);
if(particles[i].weight > maxWeight) {
maxWeight = particles[i].weight;
}
}
uniform_real_distribution<double> distDouble(0.0, maxWeight);
uniform_int_distribution<int> distInt(0, num_particles - 1);
int index = distInt(gen);
double beta = 0.0;
vector<Particle> resampledParticles;
for(int i = 0; i < num_particles; i++) {
beta += distDouble(gen) * 2.0;
while(beta > weights[index]) {
beta -= weights[index];
index = (index + 1) % num_particles;
}
resampledParticles.push_back(particles[index]);
}
particles = resampledParticles;
}
Particle ParticleFilter::SetAssociations(Particle& particle,
const vector<int>& associations,
const vector<double>& sense_x,
const vector<double>& sense_y) {
// particle: the particle to which assign each listed association,
// and association's (x,y) world coordinates mapping
// associations: The landmark id that goes along with each listed association
// sense_x: the associations x mapping already converted to world coordinates
// sense_y: the associations y mapping already converted to world coordinates
particle.associations = associations;
particle.sense_x = sense_x;
particle.sense_y = sense_y;
return particle;
}
string ParticleFilter::getAssociations(Particle best) {
vector<int> v = best.associations;
stringstream ss;
copy(v.begin(), v.end(), ostream_iterator<int>(ss, " "));
string s = ss.str();
s = s.substr(0, s.length()-1); // get rid of the trailing space
return s;
}
string ParticleFilter::getSenseCoord(Particle best, string coord) {
vector<double> v;
if (coord == "X") {
v = best.sense_x;
} else {
v = best.sense_y;
}
stringstream ss;
copy(v.begin(), v.end(), ostream_iterator<float>(ss, " "));
string s = ss.str();
s = s.substr(0, s.length()-1); // get rid of the trailing space
return s;
}
|
/*
* cgeVideoPlayer.cpp
*
* Created on: 2015-12-9
*/
#ifdef _CGE_USE_FFMPEG_
#include "cgeVideoPlayer.h"
#include "cgeGlobal.h"
#include <cmath>
static const char* const s_vshYUV420p = CGE_SHADER_STRING
(
attribute vec4 vPosition;
varying vec2 vTexCoord;
uniform mat2 rotation;
uniform vec2 flipScale;
void main()
{
gl_Position = vPosition;
// vTexCoord = vec2(1.0 + vPosition.x, 1.0 - vPosition.y) / 2.0;
vTexCoord = flipScale * (vPosition.xy / 2.0 * rotation) + 0.5;
}
);
static CGEConstString s_fshYUV420p = CGE_SHADER_STRING_PRECISION_M
(
varying vec2 vTexCoord;
uniform sampler2D textureY;
uniform sampler2D textureU;
uniform sampler2D textureV;
uniform mat3 m3ColorConversion;
void main()
{
vec3 yuv;
yuv.x = texture2D(textureY, vTexCoord).r; //fix: use full range
yuv.y = texture2D(textureU, vTexCoord).r - 0.5;
yuv.z = texture2D(textureV, vTexCoord).r - 0.5;
vec3 videoColor = m3ColorConversion * yuv;
gl_FragColor = vec4(videoColor, 1.0);
}
);
//The two matrix is from: https://developer.apple.com/library/content/samplecode/GLCameraRipple/Listings/GLCameraRipple_Shaders_Shader_fsh.html#//apple_ref/doc/uid/DTS40011222-GLCameraRipple_Shaders_Shader_fsh-DontLinkElementID_9
// BT.601, which is the standard for SDTV.
static const GLfloat s_colorConversion601[] = {
1, 1, 1,
0, -0.34413, 1.772,
1.402, -.71414, 0
};
// BT.709, which is the standard for HDTV.
static const GLfloat s_colorConversion709[] = {
1, 1, 1,
0, -0.18732, 1.8556,
1.57481, -0.46813, 0.0,
};
namespace CGE
{
CGEVideoPlayerYUV420P::CGEVideoPlayerYUV420P() : m_posAttribLocation(0), m_decodeHandler(nullptr), m_vertexBuffer(0)
{
m_program.bindAttribLocation(CGEImageFilterInterface::paramPositionIndexName, m_posAttribLocation);
if(!m_program.initWithShaderStrings(s_vshYUV420p, s_fshYUV420p))
{
CGE_LOG_ERROR("cgeVideoPlayerYUV420P program init failed!");
return;
}
m_program.bind();
m_program.sendUniformMat3("m3ColorConversion", 1, GL_FALSE, s_colorConversion601);
//textureY
m_texYLoc = m_program.uniformLocation("textureY");
m_texULoc = m_program.uniformLocation("textureU");
m_texVLoc = m_program.uniformLocation("textureV");
glUniform1i(m_texYLoc, 1);
glUniform1i(m_texULoc, 2);
glUniform1i(m_texVLoc, 3);
if(m_texYLoc < 0 || m_texULoc < 0 || m_texVLoc < 0)
{
CGE_LOG_ERROR("Invalid YUV Texture Uniforms\n");
}
memset(m_texYUV, 0, sizeof(m_texYUV));
m_rotLoc = m_program.uniformLocation("rotation");
m_flipScaleLoc = m_program.uniformLocation("flipScale");
setRotation(0.0f);
setFlipScale(1.0f, 1.0f);
cgeCheckGLError("cgeVideoPlayerYUV420P");
}
CGEVideoPlayerYUV420P::~CGEVideoPlayerYUV420P()
{
close();
}
bool CGEVideoPlayerYUV420P::open(const char* filename, CGEVideoDecodeHandler::SamplingStyle s)
{
if(m_decodeHandler != nullptr)
close();
m_decodeHandler = new CGEVideoDecodeHandler();
if(!m_decodeHandler->open(filename))
{
CGE_LOG_ERROR("Open %s failed!\n", filename);
return false;
}
m_decodeHandler->setSamplingStyle(s);
return initWithDecodeHandler(m_decodeHandler);
}
bool CGEVideoPlayerYUV420P::initWithDecodeHandler(CGEVideoDecodeHandler* handler)
{
assert(handler != nullptr); //handler == nullptr
if(m_decodeHandler != handler && m_decodeHandler != nullptr)
delete m_decodeHandler;
m_decodeHandler = handler;
m_linesize[0] = m_videoWidth = m_decodeHandler->getWidth();
m_linesize[2] = m_linesize[1] = m_linesize[0] / 2;
m_videoHeight = m_decodeHandler->getHeight();
m_texYUV[0] = cgeGenTextureWithBuffer(nullptr, m_linesize[0], m_videoHeight, GL_LUMINANCE, GL_UNSIGNED_BYTE, 1, 1);
m_texYUV[1] = cgeGenTextureWithBuffer(nullptr, m_linesize[1], m_videoHeight / 2, GL_LUMINANCE, GL_UNSIGNED_BYTE, 1, 2);
m_texYUV[2] = cgeGenTextureWithBuffer(nullptr, m_linesize[2], m_videoHeight / 2, GL_LUMINANCE, GL_UNSIGNED_BYTE, 1, 3);
if(m_vertexBuffer == 0)
m_vertexBuffer = cgeGenCommonQuadArrayBuffer();
CGE_LOG_INFO("CGEVideoPlayerYUV420P vertex buffer id: %d", m_vertexBuffer);
return m_vertexBuffer != 0;
}
void CGEVideoPlayerYUV420P::close()
{
glDeleteTextures(3, m_texYUV);
memset(m_texYUV, 0, sizeof(m_texYUV));
delete m_decodeHandler;
m_decodeHandler = nullptr;
glDeleteBuffers(1, &m_vertexBuffer);
m_vertexBuffer = 0;
}
void CGEVideoPlayerYUV420P::play()
{
}
void CGEVideoPlayerYUV420P::stop()
{
}
void CGEVideoPlayerYUV420P::pause()
{
}
void CGEVideoPlayerYUV420P::resume()
{
}
bool CGEVideoPlayerYUV420P::seek(float position)
{
return true;
}
void CGEVideoPlayerYUV420P::render()
{
CGE_LOG_CODE(
if(m_texYUV[0] == 0)
{
CGE_LOG_ERROR("You should get a frame first!\n");
return ;
}
);
m_program.bind();
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, m_texYUV[0]);
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, m_texYUV[1]);
glActiveTexture(GL_TEXTURE3);
glBindTexture(GL_TEXTURE_2D, m_texYUV[2]);
glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer);
glEnableVertexAttribArray(m_posAttribLocation);
glVertexAttribPointer(m_posAttribLocation, 2, GL_FLOAT, GL_FALSE, 0, 0);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
}
void CGEVideoPlayerYUV420P::setRotation(float rad)
{
float cosRad = cosf(rad);
float sinRad = sinf(rad);
float mat2[] = {
cosRad, sinRad,
-sinRad, cosRad
};
m_program.bind();
glUniformMatrix2fv(m_rotLoc, 1, GL_FALSE, mat2);
}
void CGEVideoPlayerYUV420P::setFlipScale(float x, float y)
{
m_program.bind();
glUniform2f(m_flipScaleLoc, x, y);
}
bool CGEVideoPlayerYUV420P::updateVideoFrame(const CGEVideoFrameBufferData* data)
{
const CGEVideoFrameBufferData* pFramebuffer = data == nullptr ? m_decodeHandler->getCurrentVideoFrame() : data;
if(pFramebuffer == nullptr)
{
return false;
}
const CGEVideoFrameBufferData& framebuffer = *pFramebuffer;
m_program.bind();
if(m_linesize[0] != framebuffer.linesize[0])
{
m_linesize[0] = framebuffer.linesize[0];
m_linesize[1] = framebuffer.linesize[1];
m_linesize[2] = framebuffer.linesize[2];
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, m_texYUV[0]);
glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, m_linesize[0], m_videoHeight, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, framebuffer.data[0]);
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, m_texYUV[1]);
glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, m_linesize[1], m_videoHeight / 2, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, framebuffer.data[1]);
glActiveTexture(GL_TEXTURE3);
glBindTexture(GL_TEXTURE_2D, m_texYUV[2]);
glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, m_linesize[2], m_videoHeight / 2, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, framebuffer.data[2]);
}
else
{
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, m_texYUV[0]);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, m_linesize[0], m_videoHeight, GL_LUMINANCE, GL_UNSIGNED_BYTE, framebuffer.data[0]);
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, m_texYUV[1]);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, m_linesize[1], m_videoHeight / 2, GL_LUMINANCE, GL_UNSIGNED_BYTE, framebuffer.data[1]);
glActiveTexture(GL_TEXTURE3);
glBindTexture(GL_TEXTURE_2D, m_texYUV[2]);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, m_linesize[2], m_videoHeight / 2, GL_LUMINANCE, GL_UNSIGNED_BYTE, framebuffer.data[2]);
}
cgeCheckGLError("cgeVideoPlayerYUV420P::updateVideoFrame");
return true;
}
bool CGEVideoPlayerYUV420P::nextVideoFrame()
{
const CGEVideoFrameBufferData* data = m_decodeHandler->getNextVideoFrame();
if(data == nullptr)
return false;
return CGEVideoPlayerYUV420P::updateVideoFrame(data);
}
bool CGEVideoPlayerYUV420P::update(double time)
{
double ts = m_decodeHandler->getCurrentTimestamp();
if(time < ts)
return true;
// else if(time > m_decodeHandler->getTotalTime())
// return false;
return nextVideoFrame();
}
}
#endif
|
#pragma once
#include "SDL/SDL.h"
#include "stdio.h"
#include <list>
//--------------------------------
//Macro definition
//--------------------------------
//--------------------------------
//Type definition
//--------------------------------
struct Vector2{
Vector2(float, float);
Vector2 operator + (const Vector2&) const;
Vector2 operator * (float d) const;
bool operator == (const Vector2&) const;
float x, y;
};
typedef Vector2 Point2;
struct Color{
bool operator == (const Color&) const;
Color(short int, short int, short int, short int);
short int R, G, B, A;
};
//class for dynamic object
class PongObject{
public:
PongObject();
PongObject(Point2, float, float, Vector2, Color);
bool operator == (const PongObject&) const;
//Coordinatee of the centeer of object
Point2 coordinate;
float width, height;
//vellocity
Vector2 vell;
Color color;
};
bool IsColliedRectangle(PongObject, PongObject);
//
SDL_Rect PongObect_To_SDLRect(const PongObject&);
//PongObjectをWindowに描画する
void DrawPongObject(SDL_Renderer , PongObject);
//Class that controlls the game
class Game{
public:
Game();
bool Initialize();
void RunLoop();
void Shutdown();
private:
//Helper functions for RunLoop
void ProcessInput();
void UpdateGame();
void GenerateOutput();
//SDL window
SDL_Window* mWindow;
//SDL Renderer for 2D drawing
SDL_Renderer* mRenderer;
//Should we continue the game?
bool mIsRunning;
//now Paused?
bool mIsPaused;
//Ticks Count
Uint32 mTicksCount;
//ticks while paused
Uint32 mPausingTicks;
//specific for Shooting
PongObject mShooter;
//List of bullets
std::list<PongObject> mBullets;
//List of enemy
std::list<PongObject> mEnemies;
//Last time a bullet was shooted
Uint32 mLastShootTime_ms;
//Last time an enemy went out
Uint32 mLastEnemyTime_ms;
};
//--------------------------------
//Prototype definition
//--------------------------------
|
#include "D3DDevice.h"
#include <extension.h>
#include "DX.h"
#include <stdafx.h>
#include "D3DDeviceContext.h"
#ifdef _DEBUG
#define D3D_DEVICE_CREATE_FLAG D3D11_CREATE_DEVICE_DEBUG
#else
#define D3D_DEVICE_CREATE_FLAG 0
#endif
void D3DDevice::Initialize(D3D_DRIVER_TYPE tp = D3D_DRIVER_TYPE_HARDWARE) {
if(tp > 5)throw std::invalid_argument("Invalid D3DDevice type");
HRESULT hr;
if (FAILED(hr = D3D11CreateDevice(0, tp, 0, D3D_DEVICE_CREATE_FLAG, 0, 0,
D3D11_SDK_VERSION,
&native_device, 0, 0))) {
MAKE_ERRMSG<std::runtime_error>("Fail to create D3DDevice, Error code:", hr);
}
ID3D11Device *d = native_device.Get();
d->QueryInterface(__uuidof(IDXGIDevice), &native_dxgi_device);
native_dxgi_device->GetParent(__uuidof(IDXGIAdapter), &native_dxgi_adapter);
native_dxgi_adapter->GetParent(__uuidof(IDXGIFactory), &native_dxgi_factory);
immcontext = Utility::ReferPtr<::D3DDeviceImmdiateContext>::New(this);
}
void D3DDevice::QueryAdapterInfo(DXGI_ADAPTER_DESC *d) {
native_dxgi_adapter->GetDesc(d);
}
namespace Ext { namespace DX {
namespace D3DDevice {
VALUE klass;
void Delete(::D3DDevice *d) {
d->SubRefer();
}
VALUE New(VALUE klass){
auto d = new ::D3DDevice;
d->AddRefer();
return Data_Wrap_Struct(klass, nullptr, Delete, d);
}
static VALUE initialize(int argc, VALUE *argv, VALUE self) {
if (argc > 1) {
rb_raise(rb_eArgError, "D3DDevice#intialize:Wrong number of arguments, expecting (0..1), but given %d", argc);
}
D3D_DRIVER_TYPE t;
if(argc == 0)t = D3D_DRIVER_TYPE_HARDWARE;
if(argc == 1)t = (D3D_DRIVER_TYPE)FIX2INT(argv[0]);
auto d = GetNativeObject<::D3DDevice>(self);
try{
d->Initialize(t);
}
catch (std::runtime_error err) {
rb_raise(rb_eRuntimeError, err.what());
}
catch (std::invalid_argument err) {
rb_raise(rb_eArgError, err.what());
}
rb_iv_set(self, "@immcontext",
Data_Wrap_Struct(Ext::DX::D3DDeviceContext::klass_immcontext, nullptr, nullptr, d->immcontext.Get()));
return self;
}
static VALUE query_adapter_info(VALUE self) {
auto sc = GetNativeObject<::D3DDevice>(self);
DXGI_ADAPTER_DESC d;
sc->QueryAdapterInfo(&d);
VALUE info = rb_hash_new();
std::string s;
U16ToU8(d.Description, s, CP_UTF8);
rb_hash_aset(info, ID2SYM(rb_intern("description")),rb_str_new(s.c_str(), (int)s.length()));
rb_hash_aset(info, ID2SYM(rb_intern("dedicated_vide_memory")), LONG2NUM((long)(d.DedicatedVideoMemory / 1024 / 1024)));
rb_hash_aset(info, ID2SYM(rb_intern("delicated_system_memory")), LONG2NUM((long)(d.DedicatedSystemMemory / 1024 / 1024)));
rb_hash_aset(info, ID2SYM(rb_intern("shared_system_memory")), LONG2NUM((long)(d.SharedSystemMemory / 1024 / 1024)));
return info;
}
VALUE immcontext(VALUE self) {
return rb_iv_get(self, "@immcontext");
}
void Init() {
klass = rb_define_class_under(module, "D3DDevice", rb_cObject);
rb_define_alloc_func(klass, New);
rb_define_const(module, "HARDWARE_DEVICE", INT2FIX(D3D_DRIVER_TYPE_HARDWARE));
rb_define_const(module, "SIMULATED_DEVICE", INT2FIX(D3D_DRIVER_TYPE_WARP));
rb_define_method(klass, "initialize", (rubyfunc)initialize, -1);
rb_define_method(klass, "query_adapter_info", (rubyfunc)query_adapter_info, 0);
rb_define_method(klass, "immcontext", (rubyfunc)immcontext, 0);
}
}
} }
|
/*
** Copyright (c) 2018-2019 Valve Corporation
** Copyright (c) 2018-2019 LunarG, 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 "decode/compression_converter.h"
#include "format/format_util.h"
#include "util/logging.h"
#include <cassert>
GFXRECON_BEGIN_NAMESPACE(gfxrecon)
GFXRECON_BEGIN_NAMESPACE(decode)
CompressionConverter::CompressionConverter() : bytes_written_(0), compressor_(nullptr), decompressing_(false) {}
CompressionConverter::~CompressionConverter()
{
Destroy();
}
bool CompressionConverter::Initialize(std::string filename,
const format::FileHeader& file_header,
const std::vector<format::FileOptionPair>& option_list,
format::CompressionType target_compression_type)
{
bool success = false;
// Modify compression setting and write file header to a new file.
filename_ = filename;
file_stream_ = std::make_unique<util::FileOutputStream>(filename_);
if (format::CompressionType::kNone == target_compression_type)
{
decompressing_ = true;
compressor_ = nullptr;
}
else
{
decompressing_ = false;
compressor_ = format::CreateCompressor(target_compression_type);
if (nullptr == compressor_)
{
GFXRECON_LOG_WARNING("Failed to initialized file compression module (type = %u)", target_compression_type);
return false;
}
}
std::vector<format::FileOptionPair> new_option_list = option_list;
for (auto& option : new_option_list)
{
switch (option.key)
{
case format::FileOption::kCompressionType:
// Change the file option to the new compression type
option.value = static_cast<uint32_t>(target_compression_type);
break;
default:
GFXRECON_LOG_WARNING("Ignoring unrecognized file header option %u", option.key);
break;
}
}
if (file_stream_->IsValid())
{
bytes_written_ = 0;
bytes_written_ += file_stream_->Write(&file_header, sizeof(file_header));
bytes_written_ +=
file_stream_->Write(new_option_list.data(), new_option_list.size() * sizeof(format::FileOptionPair));
success = true;
}
else
{
GFXRECON_LOG_ERROR("Failed to open file %s", filename_.c_str());
}
return success;
}
void CompressionConverter::Destroy()
{
if (nullptr != compressor_)
{
delete compressor_;
compressor_ = nullptr;
}
}
void CompressionConverter::DecodeFunctionCall(format::ApiCallId call_id,
const ApiCallInfo& call_info,
const uint8_t* buffer,
size_t buffer_size)
{
bool write_uncompressed = decompressing_;
if (!decompressing_)
{
// Compress the buffer with the new compression format and write to the new file.
format::CompressedFunctionCallHeader compressed_func_call_header = {};
size_t packet_size = 0;
size_t compressed_size = compressor_->Compress(buffer_size, buffer, &compressed_buffer_);
if (0 < compressed_size && compressed_size < buffer_size)
{
compressed_func_call_header.block_header.type = format::BlockType::kCompressedFunctionCallBlock;
compressed_func_call_header.api_call_id = call_id;
compressed_func_call_header.thread_id = call_info.thread_id;
compressed_func_call_header.uncompressed_size = buffer_size;
packet_size += sizeof(compressed_func_call_header.api_call_id) +
sizeof(compressed_func_call_header.thread_id) +
sizeof(compressed_func_call_header.uncompressed_size) + compressed_size;
compressed_func_call_header.block_header.size = packet_size;
// Write compressed function call block header.
bytes_written_ += file_stream_->Write(&compressed_func_call_header, sizeof(compressed_func_call_header));
// Write parameter data.
bytes_written_ += file_stream_->Write(compressed_buffer_.data(), compressed_size);
}
else
{
// It's bigger compressed than uncompressed, so only write the uncompressed data.
write_uncompressed = true;
}
}
if (write_uncompressed)
{
// Buffer is currently not compressed; it was decompressed prior to this call.
format::FunctionCallHeader func_call_header = {};
size_t packet_size = 0;
func_call_header.block_header.type = format::BlockType::kFunctionCallBlock;
func_call_header.api_call_id = call_id;
func_call_header.thread_id = call_info.thread_id;
packet_size += sizeof(func_call_header.api_call_id) + sizeof(func_call_header.thread_id) + buffer_size;
func_call_header.block_header.size = packet_size;
// Write compressed function call block header.
bytes_written_ += file_stream_->Write(&func_call_header, sizeof(func_call_header));
// Write parameter data.
bytes_written_ += file_stream_->Write(buffer, buffer_size);
}
}
void CompressionConverter::DispatchStateBeginMarker(uint64_t frame_number)
{
format::Marker marker;
marker.header.size = sizeof(marker.marker_type) + sizeof(marker.frame_number);
marker.header.type = format::kStateMarkerBlock;
marker.marker_type = format::kBeginMarker;
marker.frame_number = frame_number;
bytes_written_ += file_stream_->Write(&marker, sizeof(marker));
}
void CompressionConverter::DispatchStateEndMarker(uint64_t frame_number)
{
format::Marker marker;
marker.header.size = sizeof(marker.marker_type) + sizeof(marker.frame_number);
marker.header.type = format::kStateMarkerBlock;
marker.marker_type = format::kEndMarker;
marker.frame_number = frame_number;
bytes_written_ += file_stream_->Write(&marker, sizeof(marker));
}
void CompressionConverter::DispatchDisplayMessageCommand(format::ThreadId thread_id, const std::string& message)
{
size_t message_length = message.size();
format::DisplayMessageCommandHeader message_cmd;
message_cmd.meta_header.block_header.type = format::BlockType::kMetaDataBlock;
message_cmd.meta_header.block_header.size =
sizeof(message_cmd.meta_header.meta_data_type) + sizeof(message_cmd.thread_id) + message_length;
message_cmd.meta_header.meta_data_type = format::MetaDataType::kDisplayMessageCommand;
message_cmd.thread_id = thread_id;
bytes_written_ += file_stream_->Write(&message_cmd, sizeof(message_cmd));
bytes_written_ += file_stream_->Write(message.c_str(), message_length);
}
void CompressionConverter::DispatchFillMemoryCommand(
format::ThreadId thread_id, uint64_t memory_id, uint64_t offset, uint64_t size, const uint8_t* data)
{
// NOTE: Don't apply the offset to the write_address here since it's coming from the file_processor
// at the start of the stream. We only need to record the writing offset for future info.
format::FillMemoryCommandHeader fill_cmd;
const uint8_t* write_address = data;
GFXRECON_CHECK_CONVERSION_DATA_LOSS(size_t, size);
size_t write_size = static_cast<size_t>(size);
fill_cmd.meta_header.block_header.type = format::BlockType::kMetaDataBlock;
fill_cmd.meta_header.meta_data_type = format::MetaDataType::kFillMemoryCommand;
fill_cmd.thread_id = thread_id;
fill_cmd.memory_id = memory_id;
fill_cmd.memory_offset = offset;
fill_cmd.memory_size = write_size;
if ((!decompressing_) && (compressor_ != nullptr))
{
size_t compressed_size = compressor_->Compress(write_size, write_address, &compressed_buffer_);
if ((compressed_size > 0) && (compressed_size < write_size))
{
// We don't have a special header for compressed fill commands because the header always includes
// the uncompressed size, so we just change the type to indicate the data is compressed.
fill_cmd.meta_header.block_header.type = format::BlockType::kCompressedMetaDataBlock;
write_address = compressed_buffer_.data();
write_size = compressed_size;
}
}
// Calculate size of packet with compressed or uncompressed data size.
fill_cmd.meta_header.block_header.size = sizeof(fill_cmd.meta_header.meta_data_type) + sizeof(fill_cmd.thread_id) +
sizeof(fill_cmd.memory_id) + sizeof(fill_cmd.memory_offset) +
sizeof(fill_cmd.memory_size) + write_size;
bytes_written_ += file_stream_->Write(&fill_cmd, sizeof(fill_cmd));
bytes_written_ += file_stream_->Write(write_address, write_size);
}
void CompressionConverter::DispatchResizeWindowCommand(format::ThreadId thread_id,
format::HandleId surface_id,
uint32_t width,
uint32_t height)
{
format::ResizeWindowCommand resize_cmd;
resize_cmd.meta_header.block_header.type = format::BlockType::kMetaDataBlock;
resize_cmd.meta_header.block_header.size = sizeof(resize_cmd.meta_header.meta_data_type) +
sizeof(resize_cmd.thread_id) + sizeof(resize_cmd.surface_id) +
sizeof(resize_cmd.width) + sizeof(resize_cmd.height);
resize_cmd.meta_header.meta_data_type = format::MetaDataType::kResizeWindowCommand;
resize_cmd.thread_id = thread_id;
resize_cmd.surface_id = surface_id;
resize_cmd.width = width;
resize_cmd.height = height;
bytes_written_ += file_stream_->Write(&resize_cmd, sizeof(resize_cmd));
}
void CompressionConverter::DispatchSetSwapchainImageStateCommand(
format::ThreadId thread_id,
format::HandleId device_id,
format::HandleId swapchain_id,
uint32_t last_presented_image,
const std::vector<format::SwapchainImageStateInfo>& image_state)
{
format::SetSwapchainImageStateCommandHeader header;
size_t image_count = image_state.size();
size_t image_state_size = 0;
// Initialize standard block header.
header.meta_header.block_header.size = sizeof(header.meta_header.meta_data_type) + sizeof(header.thread_id) +
sizeof(header.device_id) + sizeof(header.swapchain_id) +
sizeof(header.last_presented_image) + sizeof(header.image_info_count);
header.meta_header.block_header.type = format::kMetaDataBlock;
if (image_count > 0)
{
image_state_size = image_count * sizeof(image_state[0]);
header.meta_header.block_header.size += image_state_size;
}
// Initialize block data for set-swapchain-image-state meta-data command.
header.meta_header.meta_data_type = format::kSetSwapchainImageStateCommand;
header.thread_id = thread_id;
header.device_id = device_id;
header.swapchain_id = swapchain_id;
header.last_presented_image = last_presented_image;
header.image_info_count = static_cast<uint32_t>(image_count);
bytes_written_ += file_stream_->Write(&header, sizeof(header));
bytes_written_ += file_stream_->Write(image_state.data(), image_state_size);
}
void CompressionConverter::DispatchBeginResourceInitCommand(format::ThreadId thread_id,
format::HandleId device_id,
uint64_t max_resource_size,
uint64_t max_copy_size)
{
format::BeginResourceInitCommand begin_cmd;
begin_cmd.meta_header.block_header.size = sizeof(begin_cmd) - sizeof(begin_cmd.meta_header.block_header);
begin_cmd.meta_header.block_header.type = format::kMetaDataBlock;
begin_cmd.meta_header.meta_data_type = format::kBeginResourceInitCommand;
begin_cmd.thread_id = thread_id;
begin_cmd.device_id = device_id;
begin_cmd.max_resource_size = max_resource_size;
begin_cmd.max_copy_size = max_copy_size;
bytes_written_ += file_stream_->Write(&begin_cmd, sizeof(begin_cmd));
}
void CompressionConverter::DispatchEndResourceInitCommand(format::ThreadId thread_id, format::HandleId device_id)
{
format::EndResourceInitCommand end_cmd;
end_cmd.meta_header.block_header.size = sizeof(end_cmd) - sizeof(end_cmd.meta_header.block_header);
end_cmd.meta_header.block_header.type = format::kMetaDataBlock;
end_cmd.meta_header.meta_data_type = format::kEndResourceInitCommand;
end_cmd.thread_id = thread_id;
end_cmd.device_id = device_id;
bytes_written_ += file_stream_->Write(&end_cmd, sizeof(end_cmd));
}
void CompressionConverter::DispatchInitBufferCommand(format::ThreadId thread_id,
format::HandleId device_id,
format::HandleId buffer_id,
uint64_t data_size,
const uint8_t* data)
{
const uint8_t* write_address = data;
GFXRECON_CHECK_CONVERSION_DATA_LOSS(size_t, data_size);
size_t write_size = static_cast<size_t>(data_size);
format::InitBufferCommandHeader init_cmd;
init_cmd.meta_header.block_header.type = format::kMetaDataBlock;
init_cmd.meta_header.meta_data_type = format::kInitBufferCommand;
init_cmd.thread_id = thread_id;
init_cmd.device_id = device_id;
init_cmd.buffer_id = buffer_id;
init_cmd.data_size = write_size; // Uncompressed data size.
if (compressor_ != nullptr)
{
size_t compressed_size = compressor_->Compress(write_size, write_address, &compressed_buffer_);
if ((compressed_size > 0) && (compressed_size < write_size))
{
init_cmd.meta_header.block_header.type = format::BlockType::kCompressedMetaDataBlock;
write_address = compressed_buffer_.data();
write_size = compressed_size;
}
}
// Calculate size of packet with compressed or uncompressed data size.
init_cmd.meta_header.block_header.size =
(sizeof(init_cmd) - sizeof(init_cmd.meta_header.block_header)) + write_size;
bytes_written_ += file_stream_->Write(&init_cmd, sizeof(init_cmd));
bytes_written_ += file_stream_->Write(write_address, write_size);
}
void CompressionConverter::DispatchInitImageCommand(format::ThreadId thread_id,
format::HandleId device_id,
format::HandleId image_id,
uint64_t data_size,
uint32_t aspect,
uint32_t layout,
const std::vector<uint64_t>& level_sizes,
const uint8_t* data)
{
format::InitImageCommandHeader init_cmd;
// Packet size without the resource data.
init_cmd.meta_header.block_header.size = sizeof(init_cmd) - sizeof(init_cmd.meta_header.block_header);
init_cmd.meta_header.block_header.type = format::kMetaDataBlock;
init_cmd.meta_header.meta_data_type = format::kInitImageCommand;
init_cmd.thread_id = thread_id;
init_cmd.device_id = device_id;
init_cmd.image_id = image_id;
init_cmd.aspect = aspect;
init_cmd.layout = layout;
if (data_size > 0)
{
assert(!level_sizes.empty());
const uint8_t* write_address = data;
GFXRECON_CHECK_CONVERSION_DATA_LOSS(size_t, data_size);
size_t write_size = static_cast<size_t>(data_size);
// Store uncompressed data size in packet.
init_cmd.data_size = write_size;
init_cmd.level_count = static_cast<uint32_t>(level_sizes.size());
if (compressor_ != nullptr)
{
size_t compressed_size = compressor_->Compress(write_size, write_address, &compressed_buffer_);
if ((compressed_size > 0) && (compressed_size < write_size))
{
init_cmd.meta_header.block_header.type = format::BlockType::kCompressedMetaDataBlock;
write_address = compressed_buffer_.data();
write_size = compressed_size;
}
}
// Calculate size of packet with compressed or uncompressed data size.
size_t levels_size = level_sizes.size() * sizeof(level_sizes[0]);
init_cmd.meta_header.block_header.size += levels_size + write_size;
bytes_written_ += file_stream_->Write(&init_cmd, sizeof(init_cmd));
bytes_written_ += file_stream_->Write(level_sizes.data(), levels_size);
bytes_written_ += file_stream_->Write(write_address, write_size);
}
else
{
// Write a packet without resource data; replay must still perform a layout transition at image
// initialization.
init_cmd.data_size = 0;
init_cmd.level_count = 0;
bytes_written_ += file_stream_->Write(&init_cmd, sizeof(init_cmd));
}
}
GFXRECON_END_NAMESPACE(decode)
GFXRECON_END_NAMESPACE(gfxrecon)
|
/**
@file
@author Shin'ichiro Nakaoka
*/
#include "GRobotControllerItem.h"
#include "GRobotBar.h"
#include "GRobotController.h"
#include <cnoid/ItemList>
#include <cnoid/MessageView>
#include <cnoid/TimeBar>
#include <cnoid/PutPropertyFunction>
#include <cnoid/Archive>
#include <cnoid/BodyItem>
#include <cnoid/BodyMotionItem>
#include "gettext.h"
using namespace std;
using namespace cnoid;
GRobotControllerItem::GRobotControllerItem()
: mv(MessageView::mainInstance())
{
controller = new GRobotController();
}
GRobotControllerItem::GRobotControllerItem(const GRobotControllerItem& org)
: Item(org),
mv(MessageView::mainInstance())
{
controller = new GRobotController(*org.controller);
}
GRobotControllerItem::~GRobotControllerItem()
{
delete controller;
}
Item* GRobotControllerItem::doDuplicate() const
{
return new GRobotControllerItem(*this);
}
void GRobotControllerItem::onConnectedToRoot()
{
checkToggledConnection =
sigCheckToggled(PrimaryCheck).connect(
[&](bool on){ onCheckToggled(on); });
}
void GRobotControllerItem::onDisconnectedFromRoot()
{
connections.disconnect();
checkToggledConnection.disconnect();
setSyncMode(false);
}
void GRobotControllerItem::onCheckToggled(bool on)
{
if(connections.empty() && on){
GRobotBar* bar = GRobotBar::instance();
connections.add(
bar->sigServoSwitchRequest().connect(
[&](bool on){ controller->switchServos(on); }));
connections.add(
bar->sigPoseSendRequest().connect(
[&](){ requestToSendPose(1.0); }));
connections.add(
bar->sigSyncModeToggled().connect(
[&](bool on){ setSyncMode(on); }));
if(bar->isSyncMode()){
setSyncMode(true);
}
} else {
connections.disconnect();
setSyncMode(false);
}
}
void GRobotControllerItem::onPositionChanged()
{
bodyItem = findOwnerItem<BodyItem>();
}
void GRobotControllerItem::setSyncMode(bool on)
{
kinematicStateChangeConnection.disconnect();
playbackInitilizeConnection.disconnect();
if(on && bodyItem){
kinematicStateChangeConnection =
bodyItem->sigKinematicStateChanged().connect(
[&](){ requestToSendPose(0.1); });
requestToSendPose(1.0);
playbackInitilizeConnection =
TimeBar::instance()->sigPlaybackInitialized().connect(
[&](double time){ return onPlaybackInitialized(time); });
}
}
void GRobotControllerItem::requestToSendPose(double transitionTime)
{
if(bodyItem){
const BodyPtr& body = bodyItem->body();
for(int i=0; i < body->numJoints(); ++i){
controller->setJointAngle(i, body->joint(i)->q());
}
controller->requestToSendPose(transitionTime);
}
}
bool GRobotControllerItem::onPlaybackInitialized(double time)
{
if(controller->isPlayingMotion()){
controller->stopMotion();
}
playbackConnections.disconnect();
if(bodyItem){
auto motionItem = bodyItem->selectedDescendantItems<BodyMotionItem>().toSingle();
if(motionItem){
auto qseq = motionItem->jointPosSeq();
if(qseq->numFrames() > 0 && qseq->numParts() == controller->numJoints()){
if(controller->setMotion(&qseq->at(0, 0), qseq->numFrames(), qseq->getTimeStep())){
TimeBar* timeBar = TimeBar::instance();
playbackConnections.add(
timeBar->sigPlaybackStarted().connect(
[&](double time){ onPlaybackStarted(time);}));
playbackConnections.add(
timeBar->sigPlaybackStopped().connect(
[&](double, bool){ onPlaybackStopped(); }));
}
}
}
}
return true;
}
void GRobotControllerItem::onPlaybackStarted(double time)
{
controller->startMotion(time);
}
void GRobotControllerItem::onPlaybackStopped()
{
controller->stopMotion();
playbackConnections.disconnect();
}
void GRobotControllerItem::doPutProperties(PutPropertyFunction& putProperty)
{
putProperty(_("Port"), controller->portDevice(),
[&](const std::string& port){ return onPortPropertyChanged(port); });
}
bool GRobotControllerItem::onPortPropertyChanged(const std::string& port)
{
controller->setPortDevice(port);
return true;
}
bool GRobotControllerItem::store(Archive& archive)
{
archive.write("port", controller->portDevice());
return true;
}
bool GRobotControllerItem::restore(const Archive& archive)
{
controller->setPortDevice(archive.get("port", controller->portDevice()));
return true;
}
|
/*
* Copyright 2020 OmniSci, 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 "TestProcessSignalHandler.h"
#include <csignal>
#include <cstdlib>
#include <iostream>
#include "Logger/Logger.h"
void TestProcessSignalHandler::registerSignalHandler() {
if (!has_registered_signal_handler_) {
std::signal(SIGTERM, shutdownSubsystemsAndExit);
std::signal(SIGSEGV, shutdownSubsystemsAndExit);
std::signal(SIGABRT, shutdownSubsystemsAndExit);
has_registered_signal_handler_ = true;
}
}
void TestProcessSignalHandler::addShutdownCallback(
std::function<void()> shutdown_callback) {
shutdown_callbacks_.emplace_back(shutdown_callback);
}
void TestProcessSignalHandler::shutdownSubsystemsAndExit(int signal_number) {
std::cerr << __func__ << ": Interrupt signal (" << signal_number << ") received."
<< std::endl;
// Perform additional shutdowns
for (auto& callback : shutdown_callbacks_) {
callback();
}
// Shutdown logging force a flush
logger::shutdown();
// Terminate program
// TODO: Why convert SIGTERM to EXIT_SUCCESS?
int const exit_code = signal_number == SIGTERM ? EXIT_SUCCESS : signal_number;
#ifdef __APPLE__
std::exit(exit_code);
#else
std::quick_exit(exit_code);
#endif
}
bool TestProcessSignalHandler::has_registered_signal_handler_{false};
std::vector<std::function<void()>> TestProcessSignalHandler::shutdown_callbacks_{};
|
#include "data_provider_builders.h"
#include "cat_feature_perfect_hash.h"
#include "columns.h"
#include "data_provider.h"
#include "feature_index.h"
#include "lazy_columns.h"
#include "sparse_columns.h"
#include "objects.h"
#include "sparse_columns.h"
#include "target.h"
#include "util.h"
#include "visitor.h"
#include <catboost/libs/cat_feature/cat_feature.h>
#include <catboost/libs/helpers/compression.h>
#include <catboost/libs/helpers/exception.h>
#include <catboost/libs/helpers/resource_holder.h>
#include <catboost/libs/logging/logging.h>
#include <catboost/private/libs/labels/helpers.h>
#include <catboost/private/libs/options/restrictions.h>
#include <catboost/private/libs/quantization/utils.h>
#include <library/cpp/threading/local_executor/local_executor.h>
#include <util/generic/algorithm.h>
#include <util/generic/cast.h>
#include <util/generic/ptr.h>
#include <util/generic/string.h>
#include <util/generic/xrange.h>
#include <util/generic/ylimits.h>
#include <util/generic/ymath.h>
#include <util/stream/labeled.h>
#include <util/string/join.h>
#include <util/system/yassert.h>
#include <algorithm>
#include <array>
namespace NCB {
class TRawObjectsOrderDataProviderBuilder : public IDataProviderBuilder,
public IRawObjectsOrderDataVisitor
{
public:
TRawObjectsOrderDataProviderBuilder(
const TDataProviderBuilderOptions& options,
NPar::ILocalExecutor* localExecutor
)
: InBlock(false)
, ObjectCount(0)
, CatFeatureCount(0)
, Cursor(NotSet)
, NextCursor(0)
, Options(options)
, LocalExecutor(localExecutor)
, InProcess(false)
, ResultTaken(false)
{}
void Start(
bool inBlock,
const TDataMetaInfo& metaInfo,
bool haveUnknownNumberOfSparseFeatures,
ui32 objectCount,
EObjectsOrder objectsOrder,
// keep necessary resources for data to be available (memory mapping for a file for example)
TVector<TIntrusivePtr<IResourceHolder>> resourceHolders
) override {
CB_ENSURE(!InProcess, "Attempt to start new processing without finishing the last");
InProcess = true;
ResultTaken = false;
InBlock = inBlock;
ui32 prevTailSize = 0;
if (InBlock) {
CB_ENSURE(!metaInfo.HasPairs, "Pairs are not supported in block processing");
prevTailSize = (NextCursor < ObjectCount) ? (ObjectCount - NextCursor) : 0;
NextCursor = prevTailSize;
} else {
NextCursor = 0;
}
ObjectCount = objectCount + prevTailSize;
CatFeatureCount = metaInfo.FeaturesLayout->GetCatFeatureCount();
Cursor = NotSet;
Data.MetaInfo = metaInfo;
if (haveUnknownNumberOfSparseFeatures) {
// make a copy because it can be updated
Data.MetaInfo.FeaturesLayout = MakeIntrusive<TFeaturesLayout>(*metaInfo.FeaturesLayout);
}
Data.TargetData.PrepareForInitialization(Data.MetaInfo, ObjectCount, prevTailSize);
Data.CommonObjectsData.PrepareForInitialization(Data.MetaInfo, ObjectCount, prevTailSize);
Data.ObjectsData.PrepareForInitialization(Data.MetaInfo);
Data.CommonObjectsData.ResourceHolders = std::move(resourceHolders);
Data.CommonObjectsData.Order = objectsOrder;
auto prepareFeaturesStorage = [&] (auto& featuresStorage) {
featuresStorage.PrepareForInitialization(
*Data.MetaInfo.FeaturesLayout,
haveUnknownNumberOfSparseFeatures,
ObjectCount,
prevTailSize,
/*dataCanBeReusedForNextBlock*/ InBlock && Data.MetaInfo.HasGroupId,
LocalExecutor
);
};
prepareFeaturesStorage(FloatFeaturesStorage);
prepareFeaturesStorage(CatFeaturesStorage);
prepareFeaturesStorage(TextFeaturesStorage);
prepareFeaturesStorage(EmbeddingFeaturesStorage);
switch (Data.MetaInfo.TargetType) {
case ERawTargetType::Float:
case ERawTargetType::Integer:
PrepareForInitialization(
Data.MetaInfo.TargetCount,
ObjectCount,
prevTailSize,
&FloatTarget
);
break;
case ERawTargetType::String:
PrepareForInitialization(
Data.MetaInfo.TargetCount,
ObjectCount,
prevTailSize,
&StringTarget
);
break;
default:
;
}
if (metaInfo.HasWeights) {
PrepareForInitialization(ObjectCount, prevTailSize, &WeightsBuffer);
}
if (metaInfo.HasGroupWeight) {
PrepareForInitialization(ObjectCount, prevTailSize, &GroupWeightsBuffer);
}
}
void StartNextBlock(ui32 blockSize) override {
Cursor = NextCursor;
NextCursor = Cursor + blockSize;
}
// TCommonObjectsData
void AddGroupId(ui32 localObjectIdx, TGroupId value) override {
(*Data.CommonObjectsData.GroupIds)[Cursor + localObjectIdx] = value;
}
void AddSubgroupId(ui32 localObjectIdx, TSubgroupId value) override {
(*Data.CommonObjectsData.SubgroupIds)[Cursor + localObjectIdx] = value;
}
void AddTimestamp(ui32 localObjectIdx, ui64 value) override {
(*Data.CommonObjectsData.Timestamp)[Cursor + localObjectIdx] = value;
}
// TRawObjectsData
void AddFloatFeature(ui32 localObjectIdx, ui32 flatFeatureIdx, float feature) override {
FloatFeaturesStorage.Set(
GetInternalFeatureIdx<EFeatureType::Float>(flatFeatureIdx),
Cursor + localObjectIdx,
feature
);
}
void AddAllFloatFeatures(ui32 localObjectIdx, TConstArrayRef<float> features) override {
auto objectIdx = Cursor + localObjectIdx;
for (auto perTypeFeatureIdx : xrange(features.size())) {
FloatFeaturesStorage.Set(
TFloatFeatureIdx(perTypeFeatureIdx),
objectIdx,
features[perTypeFeatureIdx]
);
}
}
void AddAllFloatFeatures(ui32 localObjectIdx, TConstPolymorphicValuesSparseArray<float, ui32> features) override {
ui32 sparseFeatureCount = 0;
features.ForEachNonDefault(
[&] (ui32 perTypeFeatureIdx, float /*value*/) {
sparseFeatureCount += FloatFeaturesStorage.IsSparse(TFloatFeatureIdx(perTypeFeatureIdx));
}
);
auto objectIdx = Cursor + localObjectIdx;
if (features.GetNonDefaultSize() == sparseFeatureCount) {
features.ForBlockNonDefault(
[&] (auto indexBlock, auto valueBlock) {
FloatFeaturesStorage.SetSparseFeatureBlock(objectIdx, indexBlock, valueBlock, &FloatFeaturesStorage);
},
/*blockSize*/ 1024
);
return;
}
features.ForEachNonDefault(
[&] (ui32 perTypeFeatureIdx, float value) {
FloatFeaturesStorage.Set(TFloatFeatureIdx(perTypeFeatureIdx), objectIdx, value);
}
);
}
ui32 GetCatFeatureValue(ui32 flatFeatureIdx, TStringBuf feature) override {
auto catFeatureIdx = GetInternalFeatureIdx<EFeatureType::Categorical>(flatFeatureIdx);
ui32 hashVal = CalcCatFeatureHash(feature);
int hashPartIdx = LocalExecutor->GetWorkerThreadId();
CB_ENSURE(hashPartIdx < CB_THREAD_LIMIT, "Internal error: thread ID exceeds CB_THREAD_LIMIT");
auto& catFeatureHashes = HashMapParts[hashPartIdx].CatFeatureHashes;
catFeatureHashes.resize(CatFeatureCount);
auto& catFeatureHash = catFeatureHashes[*catFeatureIdx];
THashMap<ui32, TString>::insert_ctx insertCtx;
if (!catFeatureHash.contains(hashVal, insertCtx)) {
catFeatureHash.emplace_direct(insertCtx, hashVal, feature);
}
return hashVal;
}
void AddCatFeature(ui32 localObjectIdx, ui32 flatFeatureIdx, TStringBuf feature) override {
auto catFeatureIdx = GetInternalFeatureIdx<EFeatureType::Categorical>(flatFeatureIdx);
CatFeaturesStorage.Set(
catFeatureIdx,
Cursor + localObjectIdx,
GetCatFeatureValue(flatFeatureIdx, feature)
);
}
void AddAllCatFeatures(ui32 localObjectIdx, TConstArrayRef<ui32> features) override {
auto objectIdx = Cursor + localObjectIdx;
for (auto perTypeFeatureIdx : xrange(features.size())) {
CatFeaturesStorage.Set(
TCatFeatureIdx(perTypeFeatureIdx),
objectIdx,
features[perTypeFeatureIdx]
);
}
}
void AddAllCatFeatures(ui32 localObjectIdx, TConstPolymorphicValuesSparseArray<ui32, ui32> features) override {
auto objectIdx = Cursor + localObjectIdx;
features.ForEachNonDefault(
[&] (ui32 perTypeFeatureIdx, ui32 value) {
CatFeaturesStorage.Set(TCatFeatureIdx(perTypeFeatureIdx), objectIdx, value);
}
);
}
void AddCatFeatureDefaultValue(ui32 flatFeatureIdx, TStringBuf feature) override {
auto catFeatureIdx = GetInternalFeatureIdx<EFeatureType::Categorical>(flatFeatureIdx);
CatFeaturesStorage.SetDefaultValue(catFeatureIdx, GetCatFeatureValue(flatFeatureIdx, feature));
}
void AddTextFeature(ui32 localObjectIdx, ui32 flatFeatureIdx, TStringBuf feature) override {
auto textFeatureIdx = GetInternalFeatureIdx<EFeatureType::Text>(flatFeatureIdx);
TextFeaturesStorage.Set(
textFeatureIdx,
Cursor + localObjectIdx,
TString(feature)
);
}
void AddTextFeature(ui32 localObjectIdx, ui32 flatFeatureIdx, const TString& feature) override {
auto textFeatureIdx = GetInternalFeatureIdx<EFeatureType::Text>(flatFeatureIdx);
TextFeaturesStorage.Set(
textFeatureIdx,
Cursor + localObjectIdx,
feature
);
}
void AddAllTextFeatures(ui32 localObjectIdx, TConstArrayRef<TString> features) override {
auto objectIdx = Cursor + localObjectIdx;
for (auto perTypeFeatureIdx : xrange(features.size())) {
TextFeaturesStorage.Set(
TTextFeatureIdx(perTypeFeatureIdx),
objectIdx,
features[perTypeFeatureIdx]
);
}
}
void AddAllTextFeatures(ui32 localObjectIdx, TConstPolymorphicValuesSparseArray<TString, ui32> features) override {
auto objectIdx = Cursor + localObjectIdx;
features.ForEachNonDefault(
[&] (ui32 perTypeFeatureIdx, TString value) {
TextFeaturesStorage.Set(TTextFeatureIdx(perTypeFeatureIdx), objectIdx, std::move(value));
}
);
}
void AddEmbeddingFeature(
ui32 localObjectIdx,
ui32 flatFeatureIdx,
TMaybeOwningConstArrayHolder<float> feature
) override {
auto embeddingFeatureIdx = GetInternalFeatureIdx<EFeatureType::Embedding>(flatFeatureIdx);
EmbeddingFeaturesStorage.Set(
embeddingFeatureIdx,
Cursor + localObjectIdx,
std::move(feature)
);
}
// TRawTargetData
void AddTarget(ui32 localObjectIdx, const TString& value) override {
AddTarget(0, localObjectIdx, value);
}
void AddTarget(ui32 localObjectIdx, float value) override {
AddTarget(0, localObjectIdx, value);
}
void AddTarget(ui32 flatTargetIdx, ui32 localObjectIdx, const TString& value) override {
Y_ASSERT(Data.MetaInfo.TargetType == ERawTargetType::String);
StringTarget[flatTargetIdx][Cursor + localObjectIdx] = value;
}
void AddTarget(ui32 flatTargetIdx, ui32 localObjectIdx, float value) override {
Y_ASSERT(
(Data.MetaInfo.TargetType == ERawTargetType::Float) ||
(Data.MetaInfo.TargetType == ERawTargetType::Integer)
);
FloatTarget[flatTargetIdx][Cursor + localObjectIdx] = value;
}
void AddBaseline(ui32 localObjectIdx, ui32 baselineIdx, float value) override {
Data.TargetData.Baseline[baselineIdx][Cursor + localObjectIdx] = value;
}
void AddWeight(ui32 localObjectIdx, float value) override {
WeightsBuffer[Cursor + localObjectIdx] = value;
}
void AddGroupWeight(ui32 localObjectIdx, float value) override {
GroupWeightsBuffer[Cursor + localObjectIdx] = value;
}
// separate method because they can be loaded from a separate data source
void SetGroupWeights(TVector<float>&& groupWeights) override {
CheckDataSize(groupWeights.size(), (size_t)ObjectCount, "groupWeights");
GroupWeightsBuffer = std::move(groupWeights);
}
// separate method because they can be loaded from a separate data source
void SetBaseline(TVector<TVector<float>>&& baseline) override {
Data.TargetData.Baseline = std::move(baseline);
}
void SetPairs(TRawPairsData&& pairs) override {
Data.TargetData.Pairs = std::move(pairs);
}
void SetTimestamps(TVector<ui64>&& timestamps) override {
CheckDataSize(timestamps.size(), (size_t)ObjectCount, "timestamps");
Data.CommonObjectsData.Timestamp = std::move(timestamps);
}
// needed for checking groupWeights consistency while loading from separate file
TMaybeData<TConstArrayRef<TGroupId>> GetGroupIds() const override {
return Data.CommonObjectsData.GroupIds;
}
void Finish() override {
CB_ENSURE(InProcess, "Attempt to Finish without starting processing");
CB_ENSURE(
NextCursor >= ObjectCount,
"processed object count is less than than specified in metadata"
);
if (ObjectCount != 0) {
CATBOOST_INFO_LOG << "Object info sizes: " << ObjectCount << " "
<< Data.MetaInfo.FeaturesLayout->GetExternalFeatureCount() << Endl;
} else {
// should this be an error?
CATBOOST_ERROR_LOG << "No objects info loaded" << Endl;
}
// if data has groups and we're in block mode, skip last group data
if (InBlock && Data.MetaInfo.HasGroupId) {
RollbackNextCursorToLastGroupStart();
}
InProcess = false;
}
TDataProviderPtr GetResult() override {
CB_ENSURE_INTERNAL(!InProcess, "Attempt to GetResult before finishing processing");
CB_ENSURE_INTERNAL(!ResultTaken, "Attempt to GetResult several times");
if (InBlock && Data.MetaInfo.HasGroupId) {
// copy, not move target & weights buffers
if (Data.MetaInfo.TargetType == ERawTargetType::String) {
for (auto targetIdx : xrange(Data.MetaInfo.TargetCount)) {
Data.TargetData.Target[targetIdx] = StringTarget[targetIdx];
}
} else {
for (auto targetIdx : xrange(Data.MetaInfo.TargetCount)) {
Data.TargetData.Target[targetIdx] =
(ITypedSequencePtr<float>)MakeIntrusive<TTypeCastArrayHolder<float, float>>(
TVector<float>(FloatTarget[targetIdx])
);
}
}
if (Data.MetaInfo.HasWeights) {
Data.TargetData.Weights = TWeights<float>(
TVector<float>(WeightsBuffer),
AsStringBuf("Weights"),
/*allWeightsCanBeZero*/ true
);
}
if (Data.MetaInfo.HasGroupWeight) {
Data.TargetData.GroupWeights = TWeights<float>(
TVector<float>(GroupWeightsBuffer),
AsStringBuf("GroupWeights"),
/*allWeightsCanBeZero*/ true
);
}
} else {
if (Data.MetaInfo.TargetType == ERawTargetType::String) {
for (auto targetIdx : xrange(Data.MetaInfo.TargetCount)) {
Data.TargetData.Target[targetIdx] = std::move(StringTarget[targetIdx]);
}
} else {
for (auto targetIdx : xrange(Data.MetaInfo.TargetCount)) {
Data.TargetData.Target[targetIdx] =
(ITypedSequencePtr<float>)MakeIntrusive<TTypeCastArrayHolder<float, float>>(
std::move(FloatTarget[targetIdx])
);
}
}
if (Data.MetaInfo.HasWeights) {
Data.TargetData.Weights = TWeights<float>(
std::move(WeightsBuffer),
AsStringBuf("Weights"),
/*allWeightsCanBeZero*/ InBlock
);
}
if (Data.MetaInfo.HasGroupWeight) {
Data.TargetData.GroupWeights = TWeights<float>(
std::move(GroupWeightsBuffer),
AsStringBuf("GroupWeights"),
/*allWeightsCanBeZero*/ InBlock
);
}
}
Data.CommonObjectsData.SubsetIndexing = MakeAtomicShared<TArraySubsetIndexing<ui32>>(
TFullSubset<ui32>(ObjectCount)
);
auto getFeaturesResult = [&] (auto& featuresStorage, auto* dstFeatures) {
featuresStorage.GetResult(
Data.CommonObjectsData.SubsetIndexing.Get(),
Options.SparseArrayIndexingType,
Data.MetaInfo.FeaturesLayout.Get(),
dstFeatures
);
};
getFeaturesResult(FloatFeaturesStorage, &Data.ObjectsData.FloatFeatures);
getFeaturesResult(CatFeaturesStorage, &Data.ObjectsData.CatFeatures);
if (CatFeatureCount) {
auto& catFeaturesHashToString = *Data.CommonObjectsData.CatFeaturesHashToString;
catFeaturesHashToString.resize(CatFeatureCount);
for (const auto& part : HashMapParts) {
if (part.CatFeatureHashes.empty()) {
continue;
}
for (auto catFeatureIdx : xrange(CatFeatureCount)) {
catFeaturesHashToString[catFeatureIdx].insert(
part.CatFeatureHashes[catFeatureIdx].begin(),
part.CatFeatureHashes[catFeatureIdx].end()
);
}
}
}
getFeaturesResult(TextFeaturesStorage, &Data.ObjectsData.TextFeatures);
getFeaturesResult(EmbeddingFeaturesStorage, &Data.ObjectsData.EmbeddingFeatures);
ResultTaken = true;
if (InBlock && Data.MetaInfo.HasGroupId) {
auto fullData = MakeDataProvider<TRawObjectsDataProvider>(
/*objectsGrouping*/ Nothing(), // will init from data
std::move(Data),
Options.SkipCheck,
LocalExecutor
);
TDataProviderPtr result;
ui32 groupCount = fullData->ObjectsGrouping->GetGroupCount();
if (groupCount != 1) {
TVector<TSubsetBlock<ui32>> subsetBlocks = {
TSubsetBlock<ui32>{{ui32(0), groupCount - 1}, 0}
};
result = fullData->GetSubset(
GetSubset(
fullData->ObjectsGrouping,
TArraySubsetIndexing<ui32>(
TRangesSubset<ui32>(groupCount - 1, std::move(subsetBlocks))
),
EObjectsOrder::Ordered
),
Options.MaxCpuRamUsage,
LocalExecutor
)->CastMoveTo<TObjectsDataProvider>();
}
// save Data parts - it still contains last group data
Data = TRawBuilderDataHelper::Extract(std::move(*fullData));
return result;
} else {
return MakeDataProvider<TRawObjectsDataProvider>(
/*objectsGrouping*/ Nothing(), // will init from data
std::move(Data),
Options.SkipCheck,
LocalExecutor
)->CastMoveTo<TObjectsDataProvider>();
}
}
TDataProviderPtr GetLastResult() override {
CB_ENSURE_INTERNAL(!InProcess, "Attempt to GetLastResult before finishing processing");
CB_ENSURE_INTERNAL(ResultTaken, "Attempt to call GetLastResult before GetResult");
if (!InBlock || !Data.MetaInfo.HasGroupId) {
return nullptr;
}
auto fullData = MakeDataProvider<TRawObjectsDataProvider>(
/*objectsGrouping*/ Nothing(), // will init from data
std::move(Data),
Options.SkipCheck,
LocalExecutor
);
ui32 groupCount = fullData->ObjectsGrouping->GetGroupCount();
if (groupCount == 1) {
return fullData->CastMoveTo<TObjectsDataProvider>();
} else {
TVector<TSubsetBlock<ui32>> subsetBlocks = {
TSubsetBlock<ui32>{{groupCount - 1, groupCount}, 0}
};
return fullData->GetSubset(
GetSubset(
fullData->ObjectsGrouping,
TArraySubsetIndexing<ui32>(TRangesSubset<ui32>(1, std::move(subsetBlocks))),
EObjectsOrder::Ordered
),
Options.MaxCpuRamUsage,
LocalExecutor
)->CastMoveTo<TObjectsDataProvider>();
}
}
private:
void RollbackNextCursorToLastGroupStart() {
const auto& groupIds = *Data.CommonObjectsData.GroupIds;
if (ObjectCount == 0) {
return;
}
auto rit = groupIds.rbegin();
TGroupId lastGroupId = *rit;
for (++rit; rit != groupIds.rend(); ++rit) {
if (*rit != lastGroupId) {
break;
}
}
NextCursor = ObjectCount - (rit - groupIds.rbegin());
}
template <EFeatureType FeatureType>
TFeatureIdx<FeatureType> GetInternalFeatureIdx(ui32 flatFeatureIdx) const {
return Data.MetaInfo.FeaturesLayout->GetExpandingInternalFeatureIdx<FeatureType>(flatFeatureIdx);
}
private:
struct THashPart {
TVector<THashMap<ui32, TString>> CatFeatureHashes;
};
template <EFeatureType FeatureType, class T>
class TFeaturesStorage {
struct TSparseIndex2d {
ui32 PerTypeFeatureIdx;
ui32 ObjectIdx;
};
struct TSparsePart {
TVector<TSparseIndex2d> Indices;
TVector<T> Values;
};
struct TSparseDataForBuider {
TVector<ui32> ObjectIndices;
TVector<T> Values;
};
struct TPerFeatureData {
/* shared between this builder and created data provider for efficiency
* (can be reused for cache here if there's no more references to data
* (data provider was freed))
*/
TIntrusivePtr<TVectorHolder<T>> DenseDataStorage;
TArrayRef<T> DenseDstView;
T DefaultValue; // used only for sparse
TFeatureMetaInfo MetaInfo;
public:
TPerFeatureData() = default;
TPerFeatureData(TFeatureMetaInfo&& metaInfo)
: MetaInfo(std::move(metaInfo))
{}
};
typedef void (*TSetCallback)(
TFeatureIdx<FeatureType> perTypeFeatureIdx,
ui32 objectIdx,
T value,
TFeaturesStorage* storage
);
private:
ui32 ObjectCount = 0;
bool HasSparseData = false;
bool DataCanBeReusedForNextBlock = false;
NPar::ILocalExecutor* LocalExecutor = nullptr;
TVector<TPerFeatureData> PerFeatureData; // [perTypeFeatureIdx]
std::array<TSparsePart, CB_THREAD_LIMIT> SparseDataParts; // [threadId]
// [perTypeFeaturesIdx] + extra element for adding new features
TVector<TSetCallback> PerFeatureCallbacks;
private:
// set callbacks
static void SetDenseFeature(
TFeatureIdx<FeatureType> perTypeFeatureIdx,
ui32 objectIdx,
T value,
TFeaturesStorage* storage
) {
storage->PerFeatureData[*perTypeFeatureIdx].DenseDstView[objectIdx] = std::move(value);
}
static void SetSparseFeature(
TFeatureIdx<FeatureType> perTypeFeatureIdx,
ui32 objectIdx,
T value,
TFeaturesStorage* storage
) {
const auto featureIdx = *perTypeFeatureIdx;
SetSparseFeatureBlock(objectIdx, MakeArrayRef(&featureIdx, 1), MakeArrayRef(&value, 1), storage);
}
static void IgnoreFeature(
TFeatureIdx<FeatureType> perTypeFeatureIdx,
ui32 objectIdx,
T value,
TFeaturesStorage* storage
) {
Y_UNUSED(perTypeFeatureIdx, objectIdx, value, storage);
}
void PrepareForInitializationSparseParts(ui32 prevObjectCount, ui32 prevTailSize) {
ui32 objectIdxShift = prevObjectCount - prevTailSize;
LocalExecutor->ExecRangeWithThrow(
[&, objectIdxShift, prevTailSize] (int partIdx) {
auto& sparseDataPart = SparseDataParts[partIdx];
size_t dstIdx = 0;
if (prevTailSize) {
for (auto i : xrange(sparseDataPart.Indices.size())) {
auto index2d = sparseDataPart.Indices[i];
if (index2d.ObjectIdx >= objectIdxShift) {
sparseDataPart.Indices[dstIdx].PerTypeFeatureIdx
= index2d.PerTypeFeatureIdx;
sparseDataPart.Indices[dstIdx].ObjectIdx
= index2d.ObjectIdx - objectIdxShift;
sparseDataPart.Values[dstIdx] = std::move(sparseDataPart.Values[i]);
++dstIdx;
}
}
}
sparseDataPart.Indices.resize(dstIdx);
sparseDataPart.Values.resize(dstIdx);
},
0,
SafeIntegerCast<int>(SparseDataParts.size()),
NPar::TLocalExecutor::WAIT_COMPLETE
);
}
TVector<TMaybe<TConstPolymorphicValuesSparseArray<T, ui32>>> CreateSparseArrays(
ui32 objectCount,
ESparseArrayIndexingType sparseArrayIndexingType,
NPar::ILocalExecutor* localExecutor
) {
TVector<size_t> sizesForBuilders(PerFeatureData.size());
auto builderCount = PerFeatureData.size();
for (auto& sparseDataPart : SparseDataParts) {
for (auto index2d : sparseDataPart.Indices) {
if (index2d.PerTypeFeatureIdx >= builderCount) {
// add previously unknown features
builderCount = index2d.PerTypeFeatureIdx + 1;
sizesForBuilders.resize(builderCount);
}
sizesForBuilders[index2d.PerTypeFeatureIdx] += 1;
}
}
if (builderCount == 0) {
return TVector<TMaybe<TConstPolymorphicValuesSparseArray<T, ui32>>>{0};
}
TVector<TSparseDataForBuider> sparseDataForBuilders(builderCount); // [perTypeFeatureIdx]
for (auto idx : xrange(sparseDataForBuilders.size())) {
sparseDataForBuilders[idx].ObjectIndices.yresize(sizesForBuilders[idx]);
sparseDataForBuilders[idx].Values.yresize(sizesForBuilders[idx]);
}
const auto valueCount = Accumulate(sizesForBuilders, ui64(0));
const auto valueCountPerRange = CeilDiv<ui64>(valueCount, localExecutor->GetThreadCount() + 1);
TVector<NCB::TIndexRange<ui32>> builderRanges;
ui32 rangeSize = 0;
ui32 rangeOffset = 0;
for (ui32 featureIdx : xrange(sizesForBuilders.size())) {
if (rangeSize >= valueCountPerRange) {
builderRanges.push_back({rangeOffset, featureIdx});
rangeOffset = featureIdx;
rangeSize = 0;
}
rangeSize += sizesForBuilders[featureIdx];
}
if (rangeSize > 0) {
builderRanges.push_back({rangeOffset, ui32(sizesForBuilders.size())});
}
TVector<size_t> idxForBuilders(sparseDataForBuilders.size());
const auto rangeCount = builderRanges.size();
NPar::ParallelFor(
*localExecutor,
0,
rangeCount,
[&] (ui32 rangeIdx) {
for (auto& sparseDataPart : SparseDataParts) {
if (sparseDataPart.Indices.empty()) {
continue;
}
const auto indicesRef = MakeArrayRef(sparseDataPart.Indices);
const auto valuesRef = MakeArrayRef(sparseDataPart.Values);
const auto idxRef = MakeArrayRef(idxForBuilders);
const auto buildersRef = MakeArrayRef(sparseDataForBuilders);
const auto rangeBegin = builderRanges[rangeIdx].Begin;
const auto rangeEnd = builderRanges[rangeIdx].End;
for (auto i : xrange(indicesRef.size())) {
const auto index2d = indicesRef[i];
const auto featureIdx = index2d.PerTypeFeatureIdx;
if (featureIdx >= rangeBegin && featureIdx < rangeEnd) {
auto& dataForBuilder = buildersRef[featureIdx];
dataForBuilder.ObjectIndices[idxRef[featureIdx]] = index2d.ObjectIdx;
dataForBuilder.Values[idxRef[featureIdx]] = valuesRef[i];
++idxRef[featureIdx];
}
}
}
}
);
if (!DataCanBeReusedForNextBlock) {
for (auto& sparseDataPart : SparseDataParts) {
sparseDataPart = TSparsePart();
}
}
TVector<TMaybe<TConstPolymorphicValuesSparseArray<T, ui32>>> result(
sparseDataForBuilders.size()
);
localExecutor->ExecRangeWithThrow(
[&] (int perTypeFeatureIdx) {
T defaultValue = T();
if ((size_t)perTypeFeatureIdx < PerFeatureData.size()) {
if (!PerFeatureData[perTypeFeatureIdx].MetaInfo.IsSparse) {
return;
}
defaultValue = PerFeatureData[perTypeFeatureIdx].DefaultValue;
}
std::function<TTypedSequenceContainer<T>(TVector<T>&&)> createNonDefaultValues
= [&] (TVector<T>&& values) {
return TTypedSequenceContainer<T>(
MakeIntrusive<TTypeCastArrayHolder<T, T>>(
TMaybeOwningConstArrayHolder<T>::CreateOwning(std::move(values))
)
);
};
result[perTypeFeatureIdx].ConstructInPlace(
MakeSparseArrayBase<const T, TTypedSequenceContainer<T>, ui32>(
objectCount,
std::move(sparseDataForBuilders[perTypeFeatureIdx].ObjectIndices),
std::move(sparseDataForBuilders[perTypeFeatureIdx].Values),
std::move(createNonDefaultValues),
sparseArrayIndexingType,
/*ordered*/ false,
std::move(defaultValue)
)
);
},
0,
SafeIntegerCast<int>(sparseDataForBuilders.size()),
NPar::TLocalExecutor::WAIT_COMPLETE
);
return result;
}
public:
void PrepareForInitialization(
const TFeaturesLayout& featuresLayout,
bool haveUnknownNumberOfSparseFeatures,
ui32 objectCount,
ui32 prevTailSize,
bool dataCanBeReusedForNextBlock,
NPar::ILocalExecutor* localExecutor
) {
ui32 prevObjectCount = ObjectCount;
ObjectCount = objectCount;
DataCanBeReusedForNextBlock = dataCanBeReusedForNextBlock;
LocalExecutor = localExecutor;
HasSparseData = haveUnknownNumberOfSparseFeatures;
const size_t featureCount = (size_t) featuresLayout.GetFeatureCount(FeatureType);
PerFeatureData.resize(featureCount);
PerFeatureCallbacks.resize(featureCount + 1);
for (auto perTypeFeatureIdx : xrange(featureCount)) {
auto& perFeatureData = PerFeatureData[perTypeFeatureIdx];
perFeatureData.MetaInfo
= featuresLayout.GetInternalFeatureMetaInfo(perTypeFeatureIdx, FeatureType);
if (perFeatureData.MetaInfo.IsAvailable) {
if (perFeatureData.MetaInfo.IsSparse) {
HasSparseData = true;
PerFeatureCallbacks[perTypeFeatureIdx] = SetSparseFeature;
} else {
auto& maybeSharedStoragePtr = perFeatureData.DenseDataStorage;
if (!maybeSharedStoragePtr) {
Y_VERIFY(!prevTailSize);
maybeSharedStoragePtr = MakeIntrusive<TVectorHolder<T>>();
maybeSharedStoragePtr->Data.yresize(objectCount);
} else {
Y_VERIFY(prevTailSize <= maybeSharedStoragePtr->Data.size());
auto newMaybeSharedStoragePtr = MakeIntrusive<TVectorHolder<T>>();
newMaybeSharedStoragePtr->Data.yresize(objectCount);
if (prevTailSize) {
std::copy(
maybeSharedStoragePtr->Data.end() - prevTailSize,
maybeSharedStoragePtr->Data.end(),
newMaybeSharedStoragePtr->Data.begin()
);
}
maybeSharedStoragePtr = std::move(newMaybeSharedStoragePtr);
}
perFeatureData.DenseDstView = maybeSharedStoragePtr->Data;
PerFeatureCallbacks[perTypeFeatureIdx] = SetDenseFeature;
}
} else {
PerFeatureCallbacks[perTypeFeatureIdx] = IgnoreFeature;
}
}
// for new sparse features
PerFeatureCallbacks.back() = SetSparseFeature;
if (HasSparseData) {
PrepareForInitializationSparseParts(prevObjectCount, prevTailSize);
}
}
inline void Set(TFeatureIdx<FeatureType> perTypeFeatureIdx, ui32 objectIdx, T value) {
PerFeatureCallbacks[Min(size_t(*perTypeFeatureIdx), PerFeatureCallbacks.size() - 1)](
perTypeFeatureIdx,
objectIdx,
value,
this
);
}
inline bool IsSparse(TFeatureIdx<FeatureType> perTypeFeatureIdx) const {
const auto idx = *perTypeFeatureIdx;
return idx + 1 < PerFeatureCallbacks.size() && PerFeatureCallbacks[idx] == SetSparseFeature;
}
Y_FORCE_INLINE static void SetSparseFeatureBlock(
ui32 objectIdx,
TConstArrayRef<ui32> indices,
TConstArrayRef<T> values,
TFeaturesStorage* storage
) {
Y_POD_STATIC_THREAD(int) threadId(-1);
if (Y_UNLIKELY(threadId == -1)) {
threadId = storage->LocalExecutor->GetWorkerThreadId();
}
auto& sparseDataPart = storage->SparseDataParts[threadId];
for (auto idx : indices) {
sparseDataPart.Indices.emplace_back(TSparseIndex2d{idx, objectIdx});
}
if (values.size() == 1) {
sparseDataPart.Values.push_back(values[0]);
} else {
sparseDataPart.Values.insert(sparseDataPart.Values.end(), values.begin(), values.end());
}
}
void SetDefaultValue(TFeatureIdx<FeatureType> perTypeFeatureIdx, T value) {
if (*perTypeFeatureIdx >= PerFeatureData.size()) {
for (auto perTypeFeatureIdx : xrange(PerFeatureData.size(), size_t(*perTypeFeatureIdx + 1))) {
Y_UNUSED(perTypeFeatureIdx);
PerFeatureData.emplace_back(
TFeatureMetaInfo(FeatureType, /*name*/ "", /*isSparse*/ true)
);
}
}
PerFeatureData[*perTypeFeatureIdx].DefaultValue = value;
}
template <class TColumn>
void GetResult(
const TFeaturesArraySubsetIndexing* subsetIndexing,
ESparseArrayIndexingType sparseArrayIndexingType,
TFeaturesLayout* featuresLayout,
TVector<THolder<TColumn>>* result
) {
size_t featureCount = (size_t)featuresLayout->GetFeatureCount(FeatureType);
CB_ENSURE_INTERNAL(
PerFeatureData.size() >= featureCount,
"PerFeatureData is inconsistent with feature Layout"
);
TVector<TMaybe<TConstPolymorphicValuesSparseArray<T, ui32>>> sparseData = CreateSparseArrays(
subsetIndexing->Size(),
sparseArrayIndexingType,
LocalExecutor
);
// there are some new sparse features
for (auto perTypeFeatureIdx : xrange(featureCount, sparseData.size())) {
Y_UNUSED(perTypeFeatureIdx);
featuresLayout->AddFeature(TFeatureMetaInfo(FeatureType, /*name*/ "", /*isSparse*/ true));
}
featureCount = (size_t)featuresLayout->GetFeatureCount(FeatureType);
result->clear();
result->reserve(featureCount);
for (auto perTypeFeatureIdx : xrange(featureCount)) {
const ui32 flatFeatureIdx = (ui32)featuresLayout->GetExternalFeatureIdx(
perTypeFeatureIdx,
FeatureType
);
const auto& metaInfo = featuresLayout->GetExternalFeatureMetaInfo(flatFeatureIdx);
if (metaInfo.IsAvailable) {
if (metaInfo.IsSparse) {
result->push_back(
MakeHolder<TSparsePolymorphicArrayValuesHolder<TColumn>>(
/* featureId */ flatFeatureIdx,
std::move(*(sparseData[perTypeFeatureIdx]))
)
);
} else {
result->push_back(
MakeHolder<TPolymorphicArrayValuesHolder<TColumn>>(
/* featureId */ flatFeatureIdx,
TMaybeOwningConstArrayHolder<T>::CreateOwning(
PerFeatureData[perTypeFeatureIdx].DenseDstView,
PerFeatureData[perTypeFeatureIdx].DenseDataStorage
),
subsetIndexing
)
);
}
} else {
result->push_back(nullptr);
}
}
}
};
private:
bool InBlock;
ui32 ObjectCount;
ui32 CatFeatureCount;
TRawBuilderData Data;
// will be moved to Data.RawTargetData at GetResult
TVector<TVector<TString>> StringTarget;
TVector<TVector<float>> FloatTarget;
// will be moved to Data.RawTargetData at GetResult
TVector<float> WeightsBuffer;
TVector<float> GroupWeightsBuffer;
TFeaturesStorage<EFeatureType::Float, float> FloatFeaturesStorage;
TFeaturesStorage<EFeatureType::Categorical, ui32> CatFeaturesStorage;
TFeaturesStorage<EFeatureType::Text, TString> TextFeaturesStorage;
TFeaturesStorage<EFeatureType::Embedding, TConstEmbedding> EmbeddingFeaturesStorage;
std::array<THashPart, CB_THREAD_LIMIT> HashMapParts;
static constexpr const ui32 NotSet = Max<ui32>();
ui32 Cursor;
ui32 NextCursor;
TDataProviderBuilderOptions Options;
NPar::ILocalExecutor* LocalExecutor;
bool InProcess;
bool ResultTaken;
};
class TRawFeaturesOrderDataProviderBuilder : public IDataProviderBuilder,
public IRawFeaturesOrderDataVisitor
{
public:
static constexpr int OBJECT_CALC_BLOCK_SIZE = 10000;
TRawFeaturesOrderDataProviderBuilder(
const TDataProviderBuilderOptions& options,
NPar::ILocalExecutor* localExecutor
)
: ObjectCount(0)
, Options(options)
, LocalExecutor(localExecutor)
, InProcess(false)
, ResultTaken(false)
{}
void Start(
const TDataMetaInfo& metaInfo,
ui32 objectCount,
EObjectsOrder objectsOrder,
// keep necessary resources for data to be available (memory mapping for a file for example)
TVector<TIntrusivePtr<IResourceHolder>> resourceHolders
) override {
CB_ENSURE(!InProcess, "Attempt to start new processing without finishing the last");
InProcess = true;
ResultTaken = false;
ObjectCount = objectCount;
ObjectCalcParams.Reset(
new NPar::ILocalExecutor::TExecRangeParams(0, SafeIntegerCast<int>(ObjectCount))
);
ObjectCalcParams->SetBlockSize(OBJECT_CALC_BLOCK_SIZE);
Data.MetaInfo = metaInfo;
Data.TargetData.PrepareForInitialization(metaInfo, ObjectCount, 0);
Data.CommonObjectsData.PrepareForInitialization(metaInfo, ObjectCount, 0);
Data.ObjectsData.PrepareForInitialization(metaInfo);
Data.CommonObjectsData.ResourceHolders = std::move(resourceHolders);
Data.CommonObjectsData.Order = objectsOrder;
Data.CommonObjectsData.SubsetIndexing = MakeAtomicShared<TArraySubsetIndexing<ui32>>(
TFullSubset<ui32>(ObjectCount)
);
}
// TCommonObjectsData
void AddGroupId(ui32 objectIdx, TGroupId value) override {
(*Data.CommonObjectsData.GroupIds)[objectIdx] = value;
}
void AddSubgroupId(ui32 objectIdx, TSubgroupId value) override {
(*Data.CommonObjectsData.SubgroupIds)[objectIdx] = value;
}
void AddTimestamp(ui32 objectIdx, ui64 value) override {
(*Data.CommonObjectsData.Timestamp)[objectIdx] = value;
}
// TRawObjectsData
void AddFloatFeature(ui32 flatFeatureIdx, ITypedSequencePtr<float> features) override {
auto floatFeatureIdx = GetInternalFeatureIdx<EFeatureType::Float>(flatFeatureIdx);
Data.ObjectsData.FloatFeatures[*floatFeatureIdx] = MakeHolder<TFloatArrayValuesHolder>(
flatFeatureIdx,
features->GetSubset(Data.CommonObjectsData.SubsetIndexing.Get())
);
}
void AddFloatFeature(ui32 flatFeatureIdx, TConstPolymorphicValuesSparseArray<float, ui32> features) override {
auto floatFeatureIdx = GetInternalFeatureIdx<EFeatureType::Float>(flatFeatureIdx);
Data.ObjectsData.FloatFeatures[*floatFeatureIdx] = MakeHolder<TFloatSparseValuesHolder>(
flatFeatureIdx,
std::move(features)
);
}
ui32 GetCatFeatureValue(ui32 flatFeatureIdx, TStringBuf feature) override {
auto catFeatureIdx = GetInternalFeatureIdx<EFeatureType::Categorical>(flatFeatureIdx);
auto& catFeatureHash = (*Data.CommonObjectsData.CatFeaturesHashToString)[*catFeatureIdx];
ui32 hashedValue = CalcCatFeatureHash(feature);
THashMap<ui32, TString>::insert_ctx insertCtx;
if (!catFeatureHash.contains(hashedValue, insertCtx)) {
catFeatureHash.emplace_direct(insertCtx, hashedValue, TString(feature));
}
return hashedValue;
}
void AddCatFeature(ui32 flatFeatureIdx, TConstArrayRef<TString> feature) override {
AddCatFeatureImpl(flatFeatureIdx, feature);
}
void AddCatFeature(ui32 flatFeatureIdx, TConstArrayRef<TStringBuf> feature) override {
AddCatFeatureImpl(flatFeatureIdx, feature);
}
void AddCatFeature(ui32 flatFeatureIdx, TMaybeOwningConstArrayHolder<ui32> features) override {
auto catFeatureIdx = GetInternalFeatureIdx<EFeatureType::Categorical>(flatFeatureIdx);
Data.ObjectsData.CatFeatures[*catFeatureIdx] = MakeHolder<THashedCatArrayValuesHolder>(
flatFeatureIdx,
std::move(features),
Data.CommonObjectsData.SubsetIndexing.Get()
);
}
void AddCatFeature(ui32 flatFeatureIdx, TConstPolymorphicValuesSparseArray<TString, ui32> features) override {
auto catFeatureIdx = GetInternalFeatureIdx<EFeatureType::Categorical>(flatFeatureIdx);
Data.ObjectsData.CatFeatures[*catFeatureIdx] = MakeHolder<THashedCatSparseValuesHolder>(
flatFeatureIdx,
MakeConstPolymorphicValuesSparseArray(
features.GetIndexing(),
TMaybeOwningConstArrayHolder<ui32>::CreateOwning(
CreateHashedCatValues(catFeatureIdx, features.GetNonDefaultValues().GetImpl())
),
GetCatFeatureValue(flatFeatureIdx, features.GetDefaultValue())
)
);
}
void AddTextFeature(ui32 flatFeatureIdx, TConstArrayRef<TString> features) override {
auto textFeatureIdx = GetInternalFeatureIdx<EFeatureType::Text>(flatFeatureIdx);
TVector<TString> featuresCopy(features.begin(), features.end());
Data.ObjectsData.TextFeatures[*textFeatureIdx] = MakeHolder<TStringTextArrayValuesHolder>(
flatFeatureIdx,
TMaybeOwningConstArrayHolder<TString>::CreateOwning(std::move(featuresCopy)),
Data.CommonObjectsData.SubsetIndexing.Get()
);
}
void AddTextFeature(ui32 flatFeatureIdx, TMaybeOwningConstArrayHolder<TString> features) override {
auto textFeatureIdx = GetInternalFeatureIdx<EFeatureType::Text>(flatFeatureIdx);
Data.ObjectsData.TextFeatures[*textFeatureIdx] = MakeHolder<TStringTextArrayValuesHolder>(
flatFeatureIdx,
std::move(features),
Data.CommonObjectsData.SubsetIndexing.Get()
);
}
void AddTextFeature(ui32 flatFeatureIdx, TConstPolymorphicValuesSparseArray<TString, ui32> features) override {
auto textFeatureIdx = GetInternalFeatureIdx<EFeatureType::Text>(flatFeatureIdx);
Data.ObjectsData.TextFeatures[*textFeatureIdx] = MakeHolder<TStringTextSparseValuesHolder>(
flatFeatureIdx,
std::move(features)
);
}
void AddEmbeddingFeature(ui32 flatFeatureIdx, ITypedSequencePtr<TMaybeOwningConstArrayHolder<float>> features) override {
auto embeddingFeatureIdx = GetInternalFeatureIdx<EFeatureType::Embedding>(flatFeatureIdx);
Data.ObjectsData.EmbeddingFeatures[*embeddingFeatureIdx]
= MakeHolder<TEmbeddingArrayValuesHolder>(
flatFeatureIdx,
features->GetSubset(Data.CommonObjectsData.SubsetIndexing.Get())
);
}
// TRawTargetData
void AddTarget(TConstArrayRef<TString> value) override {
AddTarget(0, value);
}
void AddTarget(ITypedSequencePtr<float> value) override {
AddTarget(0, std::move(value));
}
void AddTarget(ui32 flatTargetIdx, TConstArrayRef<TString> value) override {
Data.TargetData.Target[flatTargetIdx] = TVector<TString>(value.begin(), value.end());
}
void AddTarget(ui32 flatTargetIdx, ITypedSequencePtr<float> value) override {
Data.TargetData.Target[flatTargetIdx] = std::move(value);
}
void AddBaseline(ui32 baselineIdx, TConstArrayRef<float> value) override {
Data.TargetData.Baseline[baselineIdx].assign(value.begin(), value.end());
}
void AddWeights(TConstArrayRef<float> value) override {
Data.TargetData.Weights = TWeights<float>(TVector<float>(value.begin(), value.end()));
}
void AddGroupWeights(TConstArrayRef<float> value) override {
Data.TargetData.GroupWeights = TWeights<float>(
TVector<float>(value.begin(), value.end()),
"GroupWeights"
);
}
// separate method because they can be loaded from a separate data source
void SetGroupWeights(TVector<float>&& groupWeights) override {
CheckDataSize(groupWeights.size(), (size_t)ObjectCount, "groupWeights");
Data.TargetData.GroupWeights = TWeights<float>(std::move(groupWeights), "GroupWeights");
}
// separate method because they can be loaded from a separate data source
void SetBaseline(TVector<TVector<float>>&& baseline) override {
Data.TargetData.Baseline = std::move(baseline);
}
void SetPairs(TRawPairsData&& pairs) override {
Data.TargetData.Pairs = std::move(pairs);
}
void SetTimestamps(TVector<ui64>&& timestamps) override {
CheckDataSize(timestamps.size(), (size_t)ObjectCount, "timestamps");
Data.CommonObjectsData.Timestamp = timestamps;
}
// needed for checking groupWeights consistency while loading from separate file
TMaybeData<TConstArrayRef<TGroupId>> GetGroupIds() const override {
return Data.CommonObjectsData.GroupIds;
}
void Finish() override {
CB_ENSURE(InProcess, "Attempt to Finish without starting processing");
InProcess = false;
if (ObjectCount != 0) {
CATBOOST_INFO_LOG << "Object info sizes: " << ObjectCount << " "
<< Data.MetaInfo.FeaturesLayout->GetExternalFeatureCount() << Endl;
} else {
// should this be an error?
CATBOOST_ERROR_LOG << "No objects info loaded" << Endl;
}
}
TDataProviderPtr GetResult() override {
CB_ENSURE_INTERNAL(!InProcess, "Attempt to GetResult before finishing processing");
CB_ENSURE_INTERNAL(!ResultTaken, "Attempt to GetResult several times");
ResultTaken = true;
return MakeDataProvider<TRawObjectsDataProvider>(
/*objectsGrouping*/ Nothing(), // will init from data
std::move(Data),
Options.SkipCheck,
LocalExecutor
)->CastMoveTo<TObjectsDataProvider>();
}
private:
template <EFeatureType FeatureType>
TFeatureIdx<FeatureType> GetInternalFeatureIdx(ui32 flatFeatureIdx) const {
return TFeatureIdx<FeatureType>(
Data.MetaInfo.FeaturesLayout->GetInternalFeatureIdx(flatFeatureIdx)
);
}
template <class TStringLike>
TVector<ui32> CreateHashedCatValues(
TCatFeatureIdx catFeatureIdx,
const ITypedSequence<TStringLike>& stringValues
) {
TVector<ui32> hashedCatValues;
hashedCatValues.yresize(stringValues.GetSize());
TArrayRef<ui32> hashedCatValuesRef = hashedCatValues;
TSimpleIndexRangesGenerator<ui32> indexRanges(
TIndexRange<ui32>(stringValues.GetSize()),
(ui32)OBJECT_CALC_BLOCK_SIZE
);
LocalExecutor->ExecRange(
[&, hashedCatValuesRef](int subRangeIdx) {
TIndexRange<ui32> subRange = indexRanges.GetRange((ui32)subRangeIdx);
auto blockIterator = stringValues.GetBlockIterator(subRange);
ui32 objectIdx = subRange.Begin;
while (auto block = blockIterator->Next()) {
for (auto stringValue : block) {
hashedCatValuesRef[objectIdx++] = CalcCatFeatureHash(stringValue);
}
}
},
0,
SafeIntegerCast<int>(indexRanges.RangesCount()),
NPar::TLocalExecutor::WAIT_COMPLETE
);
auto& catFeatureHash = (*Data.CommonObjectsData.CatFeaturesHashToString)[*catFeatureIdx];
auto blockIterator = stringValues.GetBlockIterator();
ui32 objectIdx = 0;
while (auto block = blockIterator->Next()) {
for (auto stringValue : block) {
const ui32 hashedValue = hashedCatValues[objectIdx];
THashMap<ui32, TString>::insert_ctx insertCtx;
if (!catFeatureHash.contains(hashedValue, insertCtx)) {
catFeatureHash.emplace_direct(insertCtx, hashedValue, stringValue);
}
++objectIdx;
}
}
return hashedCatValues;
}
template <class TStringLike>
void AddCatFeatureImpl(ui32 flatFeatureIdx, TConstArrayRef<TStringLike> feature) {
auto catFeatureIdx = GetInternalFeatureIdx<EFeatureType::Categorical>(flatFeatureIdx);
TVector<ui32> hashedCatValues = CreateHashedCatValues(
catFeatureIdx,
TTypeCastArrayHolder<TStringLike, TStringLike>(
TMaybeOwningConstArrayHolder<TStringLike>::CreateNonOwning(feature)
)
);
Data.ObjectsData.CatFeatures[*catFeatureIdx] = MakeHolder<THashedCatArrayValuesHolder>(
flatFeatureIdx,
TMaybeOwningConstArrayHolder<ui32>::CreateOwning(std::move(hashedCatValues)),
Data.CommonObjectsData.SubsetIndexing.Get()
);
}
private:
ui32 ObjectCount;
TRawBuilderData Data;
TDataProviderBuilderOptions Options;
NPar::ILocalExecutor* LocalExecutor;
// have to make it THolder because NPar::ILocalExecutor::TExecRangeParams is unassignable/unmoveable
THolder<NPar::ILocalExecutor::TExecRangeParams> ObjectCalcParams;
bool InProcess;
bool ResultTaken;
};
class TQuantizedFeaturesDataProviderBuilder : public IDataProviderBuilder,
public IQuantizedFeaturesDataVisitor
{
public:
TQuantizedFeaturesDataProviderBuilder(
const TDataProviderBuilderOptions& options,
TDatasetSubset loadSubset,
NPar::ILocalExecutor* localExecutor
)
: ObjectCount(0)
, Options(options)
, DatasetSubset(loadSubset)
, LocalExecutor(localExecutor)
, InProcess(false)
, ResultTaken(false)
{}
void Start(
const TDataMetaInfo& metaInfo,
ui32 objectCount,
EObjectsOrder objectsOrder,
// keep necessary resources for data to be available (memory mapping for a file for example)
TVector<TIntrusivePtr<IResourceHolder>> resourceHolders,
const NCB::TPoolQuantizationSchema& poolQuantizationSchema,
bool wholeColumns
) override {
CB_ENSURE(!InProcess, "Attempt to start new processing without finishing the last");
CB_ENSURE(poolQuantizationSchema.HasAvailableFeatures(), "No features in quantized pool!");
TConstArrayRef<NJson::TJsonValue> schemaClassLabels = poolQuantizationSchema.ClassLabels;
if (metaInfo.TargetType == ERawTargetType::String && !schemaClassLabels.empty()) {
CB_ENSURE(
schemaClassLabels[0].GetType() == NJson::JSON_STRING,
"poolQuantizationSchema must have string class labels when target data type is String"
);
StringClassLabels.reserve(schemaClassLabels.size());
for (const NJson::TJsonValue& classLabel : schemaClassLabels) {
StringClassLabels.push_back(classLabel.GetString());
}
} else if ((metaInfo.TargetType != ERawTargetType::None) && !schemaClassLabels.empty()) {
FloatClassLabels.reserve(schemaClassLabels.size());
switch (schemaClassLabels[0].GetType()) {
case NJson::JSON_INTEGER:
CB_ENSURE_INTERNAL(
metaInfo.TargetType == ERawTargetType::Integer,
"metaInfo.TargetType (" << metaInfo.TargetType
<< ") is inconsistent with schemaClassLabels type ("
<< schemaClassLabels[0].GetType() << ')'
);
for (const NJson::TJsonValue& classLabel : schemaClassLabels) {
FloatClassLabels.push_back(static_cast<float>(classLabel.GetInteger()));
}
break;
case NJson::JSON_DOUBLE:
CB_ENSURE_INTERNAL(
metaInfo.TargetType == ERawTargetType::Float,
"metaInfo.TargetType (" << metaInfo.TargetType
<< ") is inconsistent with schemaClassLabels type ("
<< schemaClassLabels[0].GetType() << ')'
);
for (const NJson::TJsonValue& classLabel : schemaClassLabels) {
FloatClassLabels.push_back(static_cast<float>(classLabel.GetDouble()));
}
break;
default:
CB_ENSURE_INTERNAL(
false,
"Unexpected JSON label type for numeric target type : "
<< schemaClassLabels[0].GetType()
);
}
}
InProcess = true;
ResultTaken = false;
ObjectCount = objectCount;
Data.MetaInfo = metaInfo;
if (Data.MetaInfo.ClassLabels.empty()) {
Data.MetaInfo.ClassLabels.assign(schemaClassLabels.begin(), schemaClassLabels.end());
} else {
size_t prefixLength = Min(Data.MetaInfo.ClassLabels.size(), schemaClassLabels.size());
auto firstGivenLabels = TConstArrayRef<NJson::TJsonValue>(
Data.MetaInfo.ClassLabels.begin(),
Data.MetaInfo.ClassLabels.begin() + prefixLength
);
CB_ENSURE(firstGivenLabels == schemaClassLabels,
"Class-names incompatible with quantized pool, expected: " << JoinSeq(",", schemaClassLabels));
}
Data.TargetData.PrepareForInitialization(metaInfo, objectCount, 0);
Data.CommonObjectsData.PrepareForInitialization(metaInfo, objectCount, 0);
Data.ObjectsData.Data.PrepareForInitialization(
metaInfo,
// TODO(akhropov): get from quantized pool meta info when it will be available: MLTOOLS-2392.
NCatboostOptions::TBinarizationOptions(
EBorderSelectionType::GreedyLogSum, // default value
(poolQuantizationSchema.Borders.size() > 0) ?
SafeIntegerCast<ui32>(poolQuantizationSchema.Borders[0].size())
: 32,
ENanMode::Forbidden // default value
),
TMap<ui32, NCatboostOptions::TBinarizationOptions>()
);
FillQuantizedFeaturesInfo(
poolQuantizationSchema,
Data.ObjectsData.Data.QuantizedFeaturesInfo.Get()
);
Data.ObjectsData.ExclusiveFeatureBundlesData = TExclusiveFeatureBundlesData(
*metaInfo.FeaturesLayout,
TVector<TExclusiveFeaturesBundle>() // TODO(akhropov): bundle quantized data
);
Data.ObjectsData.PackedBinaryFeaturesData = TPackedBinaryFeaturesData(
*metaInfo.FeaturesLayout,
*Data.ObjectsData.Data.QuantizedFeaturesInfo,
Data.ObjectsData.ExclusiveFeatureBundlesData,
/*dontPack*/ Options.GpuDistributedFormat
);
Data.ObjectsData.FeaturesGroupsData = TFeatureGroupsData(
*metaInfo.FeaturesLayout,
TVector<TFeaturesGroup>() // TODO(ilyzhin): group quantized data
);
Data.CommonObjectsData.ResourceHolders = std::move(resourceHolders);
Data.CommonObjectsData.Order = objectsOrder;
PrepareBinaryFeaturesStorage();
if (DatasetSubset.HasFeatures) {
FloatFeaturesStorage.PrepareForInitialization(
*metaInfo.FeaturesLayout,
objectCount,
Data.ObjectsData.Data.QuantizedFeaturesInfo,
BinaryFeaturesStorage,
Data.ObjectsData.PackedBinaryFeaturesData.FlatFeatureIndexToPackedBinaryIndex,
wholeColumns
);
CategoricalFeaturesStorage.PrepareForInitialization(
*metaInfo.FeaturesLayout,
objectCount,
Data.ObjectsData.Data.QuantizedFeaturesInfo,
BinaryFeaturesStorage,
Data.ObjectsData.PackedBinaryFeaturesData.FlatFeatureIndexToPackedBinaryIndex,
wholeColumns
);
}
if (Data.MetaInfo.TargetType == ERawTargetType::String) {
PrepareForInitialization(
Data.MetaInfo.TargetCount,
ObjectCount,
/*prevTailSize*/ 0,
&StringTarget
);
} else {
PrepareForInitialization(
Data.MetaInfo.TargetCount,
ObjectCount,
/*prevTailSize*/ 0,
&FloatTarget
);
}
if (metaInfo.HasWeights) {
WeightsBuffer.yresize(objectCount);
}
if (metaInfo.HasGroupWeight) {
GroupWeightsBuffer.yresize(objectCount);
}
}
template <class T>
static void CopyPart(ui32 objectOffset, TUnalignedArrayBuf<T> srcPart, TVector<T>* dstData) {
CB_ENSURE_INTERNAL(
objectOffset < dstData->size(),
LabeledOutput(objectOffset, srcPart.GetSize(), dstData->size()));
CB_ENSURE_INTERNAL(
objectOffset + srcPart.GetSize() <= dstData->size(),
LabeledOutput(objectOffset, srcPart.GetSize(), dstData->size()));
TArrayRef<T> dstArrayRef(dstData->data() + objectOffset, srcPart.GetSize());
srcPart.WriteTo(&dstArrayRef);
}
// TCommonObjectsData
void AddGroupIdPart(ui32 objectOffset, TUnalignedArrayBuf<TGroupId> groupIdPart) override {
CopyPart(objectOffset, groupIdPart, &(*Data.CommonObjectsData.GroupIds));
}
void AddSubgroupIdPart(ui32 objectOffset, TUnalignedArrayBuf<TSubgroupId> subgroupIdPart) override {
CopyPart(objectOffset, subgroupIdPart, &(*Data.CommonObjectsData.SubgroupIds));
}
void AddTimestampPart(ui32 objectOffset, TUnalignedArrayBuf<ui64> timestampPart) override {
CopyPart(objectOffset, timestampPart, &(*Data.CommonObjectsData.Timestamp));
}
void AddFloatFeaturePart(
ui32 flatFeatureIdx,
ui32 objectOffset,
ui8 bitsPerDocumentFeature,
TMaybeOwningConstArrayHolder<ui8> featuresPart // per-feature data size depends on BitsPerKey
) override {
FloatFeaturesStorage.Set(
GetInternalFeatureIdx<EFeatureType::Float>(flatFeatureIdx),
objectOffset,
bitsPerDocumentFeature,
std::move(featuresPart),
LocalExecutor
);
}
void AddCatFeaturePart(
ui32 flatFeatureIdx,
ui32 objectOffset,
ui8 bitsPerDocumentFeature,
TMaybeOwningConstArrayHolder<ui8> featuresPart // per-feature data size depends on BitsPerKey
) override {
CategoricalFeaturesStorage.Set(
GetInternalFeatureIdx<EFeatureType::Categorical>(flatFeatureIdx),
objectOffset,
bitsPerDocumentFeature,
std::move(featuresPart),
LocalExecutor
);
}
// TRawTargetData
void AddTargetPart(ui32 objectOffset, TUnalignedArrayBuf<float> targetPart) override {
AddTargetPart(0, objectOffset, targetPart);
}
void AddTargetPart(ui32 objectOffset, TMaybeOwningConstArrayHolder<TString> targetPart) override {
AddTargetPart(0, objectOffset, targetPart);
}
void AddTargetPart(ui32 flatTargetIdx, ui32 objectOffset, TMaybeOwningConstArrayHolder<TString> targetPart) override {
Y_ASSERT(Data.MetaInfo.TargetType == ERawTargetType::String);
Copy(
(*targetPart).begin(),
(*targetPart).end(),
std::next(StringTarget[flatTargetIdx].begin(), objectOffset)
);
}
void AddTargetPart(ui32 flatTargetIdx, ui32 objectOffset, TUnalignedArrayBuf<float> targetPart) override {
if (!StringClassLabels.empty()) {
Y_ASSERT(Data.MetaInfo.TargetType == ERawTargetType::String);
AddTargetPartWithClassLabels<TString>(
objectOffset,
targetPart,
StringClassLabels,
StringTarget[flatTargetIdx]
);
} else {
Y_ASSERT(
(Data.MetaInfo.TargetType == ERawTargetType::Integer) ||
(Data.MetaInfo.TargetType == ERawTargetType::Float)
);
if (!FloatClassLabels.empty()) {
AddTargetPartWithClassLabels<float>(
objectOffset,
targetPart,
FloatClassLabels,
FloatTarget[flatTargetIdx]
);
} else {
TArrayRef<float> dstPart(
FloatTarget[flatTargetIdx].data() + objectOffset,
targetPart.GetSize()
);
targetPart.WriteTo(&dstPart);
}
}
}
void AddBaselinePart(
ui32 objectOffset,
ui32 baselineIdx,
TUnalignedArrayBuf<float> baselinePart
) override {
CopyPart(objectOffset, baselinePart, &Data.TargetData.Baseline[baselineIdx]);
}
void AddWeightPart(ui32 objectOffset, TUnalignedArrayBuf<float> weightPart) override {
CopyPart(objectOffset, weightPart, &WeightsBuffer);
}
void AddGroupWeightPart(ui32 objectOffset, TUnalignedArrayBuf<float> groupWeightPart) override {
CopyPart(objectOffset, groupWeightPart, &GroupWeightsBuffer);
}
// separate method because they can be loaded from a separate data source
void SetGroupWeights(TVector<float>&& groupWeights) override {
CheckDataSize(groupWeights.size(), (size_t)ObjectCount, "groupWeights");
GroupWeightsBuffer = std::move(groupWeights);
}
// separate method because they can be loaded from a separate data source
void SetBaseline(TVector<TVector<float>>&& baseline) override {
Data.TargetData.Baseline = std::move(baseline);
}
void SetPairs(TRawPairsData&& pairs) override {
Data.TargetData.Pairs = std::move(pairs);
}
void SetTimestamps(TVector<ui64>&& timestamps) override {
CheckDataSize(timestamps.size(), (size_t)ObjectCount, "timestamps");
Data.CommonObjectsData.Timestamp = std::move(timestamps);
}
// needed for checking groupWeights consistency while loading from separate file
TMaybeData<TConstArrayRef<TGroupId>> GetGroupIds() const override {
return Data.CommonObjectsData.GroupIds;
}
void Finish() override {
CB_ENSURE(InProcess, "Attempt to Finish without starting processing");
if (ObjectCount != 0) {
CATBOOST_INFO_LOG << "Object info sizes: " << ObjectCount << " "
<< Data.MetaInfo.FeaturesLayout->GetExternalFeatureCount() << Endl;
} else {
// should this be an error?
CATBOOST_ERROR_LOG << "No objects info loaded" << Endl;
}
InProcess = false;
}
TDataProviderPtr GetResult() override {
GetTargetAndBinaryFeaturesData();
if (DatasetSubset.HasFeatures) {
FloatFeaturesStorage.GetResult(
ObjectCount,
*Data.MetaInfo.FeaturesLayout,
Data.CommonObjectsData.SubsetIndexing.Get(),
Data.ObjectsData.PackedBinaryFeaturesData.SrcData,
&Data.ObjectsData.Data.FloatFeatures
);
CategoricalFeaturesStorage.GetResult(
ObjectCount,
*Data.MetaInfo.FeaturesLayout,
Data.CommonObjectsData.SubsetIndexing.Get(),
Data.ObjectsData.PackedBinaryFeaturesData.SrcData,
&Data.ObjectsData.Data.CatFeatures
);
}
SetResultsTaken();
return MakeDataProvider<TQuantizedForCPUObjectsDataProvider>(
/*objectsGrouping*/ Nothing(), // will init from data
std::move(Data),
// without HasFeatures dataprovider self-test fails on distributed train
// on quantized pool
Options.SkipCheck || !DatasetSubset.HasFeatures,
LocalExecutor
)->CastMoveTo<TObjectsDataProvider>();
}
void GetTargetAndBinaryFeaturesData() {
CB_ENSURE_INTERNAL(!InProcess, "Attempt to GetResult before finishing processing");
CB_ENSURE_INTERNAL(!ResultTaken, "Attempt to GetResult several times");
if (Data.MetaInfo.TargetType == ERawTargetType::String) {
for (auto targetIdx : xrange(Data.MetaInfo.TargetCount)) {
Data.TargetData.Target[targetIdx] = std::move(StringTarget[targetIdx]);
}
} else {
for (auto targetIdx : xrange(Data.MetaInfo.TargetCount)) {
Data.TargetData.Target[targetIdx] =
(ITypedSequencePtr<float>)MakeIntrusive<TTypeCastArrayHolder<float, float>>(
std::move(FloatTarget[targetIdx])
);
}
}
if (Data.MetaInfo.HasWeights) {
Data.TargetData.Weights = TWeights<float>(std::move(WeightsBuffer));
}
if (Data.MetaInfo.HasGroupWeight) {
Data.TargetData.GroupWeights = TWeights<float>(std::move(GroupWeightsBuffer));
}
Data.CommonObjectsData.SubsetIndexing = MakeAtomicShared<TArraySubsetIndexing<ui32>>(
TFullSubset<ui32>(ObjectCount)
);
GetBinaryFeaturesDataResult();
}
TQuantizedForCPUBuilderData& GetDataRef() {
return Data;
}
ui32 GetObjectCount() const {
return ObjectCount;
}
void SetResultsTaken() {
ResultTaken = true;
}
template <EFeatureType FeatureType>
static TVector<bool> MakeIsAvailable(const TFeaturesLayout& featuresLayout) {
const size_t perTypeFeatureCount = (size_t)featuresLayout.GetFeatureCount(FeatureType);
TVector<bool> isAvailable(perTypeFeatureCount, false);
const auto& metaInfos = featuresLayout.GetExternalFeaturesMetaInfo();
for (auto perTypeFeatureIdx : xrange(perTypeFeatureCount)) {
const auto flatFeatureIdx = featuresLayout.GetExternalFeatureIdx(perTypeFeatureIdx, FeatureType);
if (!metaInfos[flatFeatureIdx].IsAvailable) {
continue;
}
isAvailable[perTypeFeatureIdx] = true;
}
return isAvailable;
}
private:
template <EFeatureType FeatureType>
TFeatureIdx<FeatureType> GetInternalFeatureIdx(ui32 flatFeatureIdx) const {
return TFeatureIdx<FeatureType>(
Data.MetaInfo.FeaturesLayout->GetInternalFeatureIdx(flatFeatureIdx)
);
}
static TVector<float> Slice(
const TVector<float>& v,
const size_t offset,
const size_t size)
{
CB_ENSURE_INTERNAL(offset < v.size(), LabeledOutput(v.size(), offset));
TVector<float> slice;
slice.reserve(size);
for (size_t i = 0; i < size && offset + i < v.size(); ++i) {
slice.push_back(v[offset + i]);
}
return slice;
}
static void FillQuantizedFeaturesInfo(
const NCB::TPoolQuantizationSchema& schema,
TQuantizedFeaturesInfo* info
) {
const auto& featuresLayout = *info->GetFeaturesLayout();
const auto metaInfos = featuresLayout.GetExternalFeaturesMetaInfo();
for (size_t i = 0, iEnd = schema.FloatFeatureIndices.size(); i < iEnd; ++i) {
const auto flatFeatureIdx = schema.FloatFeatureIndices[i];
const auto nanMode = schema.NanModes[i];
const auto& metaInfo = metaInfos[flatFeatureIdx];
CB_ENSURE(
metaInfo.Type == EFeatureType::Float,
"quantization schema's feature type for feature " LabeledOutput(flatFeatureIdx)
<< " (float) is inconsistent with features layout");
if (!metaInfo.IsAvailable) {
continue;
}
const auto typedFeatureIdx = featuresLayout.GetInternalFeatureIdx<EFeatureType::Float>(
flatFeatureIdx);
info->SetBorders(typedFeatureIdx, TVector<float>(schema.Borders[i]));
info->SetNanMode(typedFeatureIdx, nanMode);
}
for (size_t i = 0, iEnd = schema.CatFeatureIndices.size(); i < iEnd; ++i) {
const auto flatFeatureIdx = schema.CatFeatureIndices[i];
const auto& metaInfo = metaInfos[flatFeatureIdx];
CB_ENSURE(
metaInfo.Type == EFeatureType::Categorical,
"quantization schema's feature type for feature " LabeledOutput(flatFeatureIdx)
<< " (categorical) is inconsistent with features layout");
if (!metaInfo.IsAvailable) {
continue;
}
const auto typedFeatureIdx = featuresLayout.GetInternalFeatureIdx<EFeatureType::Categorical>(
flatFeatureIdx);
TCatFeaturePerfectHash perfectHash{
Nothing(),
schema.FeaturesPerfectHash[i]
};
info->UpdateCategoricalFeaturesPerfectHash(typedFeatureIdx, std::move(perfectHash));
}
}
void PrepareBinaryFeaturesStorage() {
auto binaryFeaturesStorageSize = CeilDiv(
Data.ObjectsData.PackedBinaryFeaturesData.PackedBinaryToSrcIndex.size(),
sizeof(TBinaryFeaturesPack) * CHAR_BIT
);
BinaryFeaturesStorage.resize(binaryFeaturesStorageSize);
if (!binaryFeaturesStorageSize) {
return;
}
TIndexHelper<ui64> indexHelper(sizeof(TBinaryFeaturesPack) * CHAR_BIT);
const ui64 storageVectorSize = indexHelper.CompressedSize(ObjectCount);
LocalExecutor->ExecRangeWithThrow(
[&] (int i) {
auto& binaryFeaturesStorageElement = BinaryFeaturesStorage[i];
if (!binaryFeaturesStorageElement || (binaryFeaturesStorageElement->RefCount() > 1)) {
/* storage is either uninited or shared with some other references
* so it has to be reset to be reused
*/
binaryFeaturesStorageElement = MakeIntrusive<TVectorHolder<ui64>>();
}
auto& data = binaryFeaturesStorageElement->Data;
data.yresize(storageVectorSize);
Fill(data.begin(), data.end(), ui64(0));
},
0,
SafeIntegerCast<int>(binaryFeaturesStorageSize),
NPar::TLocalExecutor::WAIT_COMPLETE
);
}
void GetBinaryFeaturesDataResult() {
auto& dst = Data.ObjectsData.PackedBinaryFeaturesData.SrcData;
dst.clear();
for (auto& binaryFeaturesStorageElement : BinaryFeaturesStorage) {
dst.push_back(
MakeHolder<TBinaryPacksArrayHolder>(
0,
TCompressedArray(
ObjectCount,
sizeof(TBinaryFeaturesPack) * CHAR_BIT,
TMaybeOwningArrayHolder<ui64>::CreateOwning(
binaryFeaturesStorageElement->Data,
binaryFeaturesStorageElement
)
),
Data.CommonObjectsData.SubsetIndexing.Get()
)
);
}
}
template <class T>
static void AddTargetPartWithClassLabels(
ui32 objectOffset,
TUnalignedArrayBuf<float> targetPart,
TConstArrayRef<T> classLabels,
TArrayRef<T> target
) {
for (auto it = targetPart.GetIterator(); !it.AtEnd(); it.Next(), ++objectOffset) {
target[objectOffset] = classLabels[int(it.Cur())];
}
}
private:
// ui64 because passed to TCompressedArray later
using TBinaryFeaturesStorage = TVector<TIntrusivePtr<TVectorHolder<ui64>>>;
template <EFeatureType FeatureType>
class TFeaturesStorage {
private:
static_assert(FeatureType == EFeatureType::Float || FeatureType == EFeatureType::Categorical,
"Only float and categorical features are currently supported");
bool WholeColumns = false;
size_t ObjectCount = 0;
/******************************************************************************************/
// non-binary features
/* shared between this builder and created data provider for efficiency
* (can be reused for cache here if there's no more references to data
* (data provider was freed))
*
* Used if WholeColumns == false
*/
TVector<TIntrusivePtr<TVectorHolder<ui64>>> DenseDataStorage; // [perTypeFeatureIdx]
// view into storage for faster access
TVector<TArrayRef<ui64>> DenseDstView; // [perTypeFeatureIdx]
// whole columns
/*
* Used if WholeColumns == true
* if src array data is properly aligned (as ui64, because it is used in TCompressedArray)
* just copy TMaybeOwningArrayHolder as, make a copy otherwise
* but const cast is used because TCompressedArray accepts only TMaybeOwningArrayHolder
* whereas in fact it is used only as read-only data later in data provider
* TODO(akhropov): Propagate const-correctness here
*/
TVector<TMaybeOwningArrayHolder<ui64>> DenseWholeColumns; // [perTypeFeatureIdx]
TVector<TIndexHelper<ui64>> IndexHelpers; // [perTypeFeatureIdx]
/******************************************************************************************/
// binary features
// view into BinaryStorage for faster access
// BinaryStorage is not owned by TFeaturesStorage but common for all FeatureTypes
TVector<TArrayRef<TBinaryFeaturesPack>> DstBinaryView; // [packIdx][objectIdx][bitIdx]
TVector<TMaybe<TPackedBinaryIndex>> FeatureIdxToPackedBinaryIndex; // [perTypeFeatureIdx]
/******************************************************************************************/
// copy from Data.MetaInfo.FeaturesLayout for fast access
TVector<bool> IsAvailable; // [perTypeFeatureIdx]
public:
void PrepareForInitialization(
const TFeaturesLayout& featuresLayout,
ui32 objectCount,
const TQuantizedFeaturesInfoPtr& quantizedFeaturesInfoPtr,
TBinaryFeaturesStorage& binaryStorage,
TConstArrayRef<TMaybe<TPackedBinaryIndex>> flatFeatureIndexToPackedBinaryIndex,
bool wholeColumns
) {
ObjectCount = objectCount;
WholeColumns = wholeColumns;
const size_t perTypeFeatureCount = (size_t)featuresLayout.GetFeatureCount(FeatureType);
if (WholeColumns) {
DenseWholeColumns.resize(perTypeFeatureCount);
DenseDataStorage.clear();
DenseDstView.clear();
} else {
DenseWholeColumns.clear();
DenseDataStorage.resize(perTypeFeatureCount);
DenseDstView.resize(perTypeFeatureCount);
}
IndexHelpers.resize(perTypeFeatureCount, TIndexHelper<ui64>(8));
FeatureIdxToPackedBinaryIndex.resize(perTypeFeatureCount);
IsAvailable = MakeIsAvailable<FeatureType>(featuresLayout);
const auto metaInfos = featuresLayout.GetExternalFeaturesMetaInfo();
const bool isFloatType = (FeatureType == EFeatureType::Float);
for (auto perTypeFeatureIdx : xrange(perTypeFeatureCount)) {
const auto flatFeatureIdx = featuresLayout.GetExternalFeatureIdx(perTypeFeatureIdx, FeatureType);
if (!metaInfos[flatFeatureIdx].IsAvailable) {
continue;
}
ui8 bitsPerFeature;
if (isFloatType) {
bitsPerFeature = CalcHistogramWidthForBorders(
quantizedFeaturesInfoPtr->GetBorders(TFloatFeatureIdx(perTypeFeatureIdx)).size());
} else {
bitsPerFeature = CalcHistogramWidthForUniqueValuesCount(
quantizedFeaturesInfoPtr->GetUniqueValuesCounts(TCatFeatureIdx(perTypeFeatureIdx)).OnAll);
}
IndexHelpers[perTypeFeatureIdx] = TIndexHelper<ui64>(bitsPerFeature);
FeatureIdxToPackedBinaryIndex[perTypeFeatureIdx]
= flatFeatureIndexToPackedBinaryIndex[flatFeatureIdx];
}
if (!WholeColumns) {
for (auto perTypeFeatureIdx : xrange(perTypeFeatureCount)) {
if (featuresLayout.GetInternalFeatureMetaInfo(
perTypeFeatureIdx,
FeatureType
).IsAvailable &&
!FeatureIdxToPackedBinaryIndex[perTypeFeatureIdx])
{
CB_ENSURE(
IsAvailable[perTypeFeatureIdx],
FeatureType << " feature #" << perTypeFeatureIdx
<< " has no data in quantized pool"
);
auto& maybeSharedStoragePtr = DenseDataStorage[perTypeFeatureIdx];
if (!maybeSharedStoragePtr || (maybeSharedStoragePtr->RefCount() > 1)) {
/* storage is either uninited or shared with some other references
* so it has to be reset to be reused
*/
DenseDataStorage[perTypeFeatureIdx] = MakeIntrusive<TVectorHolder<ui64>>();
}
maybeSharedStoragePtr->Data.yresize(
IndexHelpers[perTypeFeatureIdx].CompressedSize(objectCount)
);
DenseDstView[perTypeFeatureIdx] = maybeSharedStoragePtr->Data;
} else {
DenseDataStorage[perTypeFeatureIdx] = nullptr;
DenseDstView[perTypeFeatureIdx] = TArrayRef<ui64>();
}
}
}
for (auto& binaryStorageElement : binaryStorage) {
DstBinaryView.push_back(
TArrayRef<ui8>((ui8*)binaryStorageElement->Data.data(), objectCount)
);
}
}
void Set(
TFeatureIdx<FeatureType> perTypeFeatureIdx,
ui32 objectOffset,
ui8 bitsPerDocumentFeature,
TMaybeOwningConstArrayHolder<ui8> featuresPart,
NPar::ILocalExecutor* localExecutor
) {
if (!IsAvailable[*perTypeFeatureIdx]) {
return;
}
if (FeatureIdxToPackedBinaryIndex[*perTypeFeatureIdx]) {
auto packedBinaryIndex = *FeatureIdxToPackedBinaryIndex[*perTypeFeatureIdx];
auto dstSlice = DstBinaryView[packedBinaryIndex.PackIdx].Slice(
objectOffset,
featuresPart.GetSize()
);
ParallelSetBinaryFeatureInPackArray(
*featuresPart,
packedBinaryIndex.BitIdx,
/*needToClearDstBits*/ false,
localExecutor,
&dstSlice
);
} else {
CB_ENSURE_INTERNAL(
bitsPerDocumentFeature == 8 || bitsPerDocumentFeature == 16 || bitsPerDocumentFeature == 32,
"Only 8, 16 or 32 bits per document supported, got: " << bitsPerDocumentFeature);
CB_ENSURE_INTERNAL(IndexHelpers[*perTypeFeatureIdx].GetBitsPerKey() == bitsPerDocumentFeature,
"BitsPerKey should be equal to bitsPerDocumentFeature");
const auto bytesPerDocument = bitsPerDocumentFeature / (sizeof(ui8) * CHAR_BIT);
if (WholeColumns) {
CB_ENSURE(objectOffset == 0, "objectOffset must be 0 for WholeColumns");
const ui8* dataPtr = featuresPart.data();
if (reinterpret_cast<ui64>(dataPtr) % alignof(ui64)) {
// fallback to data copying if it is unaligned
TVector<ui64> dataCopy;
dataCopy.yresize(IndexHelpers[*perTypeFeatureIdx].CompressedSize(ObjectCount));
Copy(featuresPart.begin(), featuresPart.end(), (ui8*)dataCopy.data());
DenseWholeColumns[*perTypeFeatureIdx] =
TMaybeOwningArrayHolder<ui64>::CreateOwning(std::move(dataCopy));
} else {
DenseWholeColumns[*perTypeFeatureIdx] =
TMaybeOwningArrayHolder<ui64>::CreateOwning(
TArrayRef<ui64>(
(ui64*)const_cast<ui8*>(dataPtr),
CeilDiv(featuresPart.GetSize(), sizeof(ui64))
),
featuresPart.GetResourceHolder()
);
}
} else {
const auto dstCapacityInBytes =
DenseDstView[*perTypeFeatureIdx].size() *
sizeof(decltype(*DenseDstView[*perTypeFeatureIdx].data()));
const auto objectOffsetInBytes = objectOffset * bytesPerDocument;
CB_ENSURE_INTERNAL(
objectOffsetInBytes < dstCapacityInBytes,
LabeledOutput(perTypeFeatureIdx, objectOffset, objectOffsetInBytes, featuresPart.GetSize(), dstCapacityInBytes));
CB_ENSURE_INTERNAL(
objectOffsetInBytes + featuresPart.GetSize() <= dstCapacityInBytes,
LabeledOutput(perTypeFeatureIdx, objectOffset, objectOffsetInBytes, featuresPart.GetSize(), dstCapacityInBytes));
memcpy(
((ui8*)DenseDstView[*perTypeFeatureIdx].data()) + objectOffsetInBytes,
featuresPart.data(),
featuresPart.GetSize());
}
}
}
template <class TColumn>
void GetResult(
ui32 objectCount,
const TFeaturesLayout& featuresLayout,
const TFeaturesArraySubsetIndexing* subsetIndexing,
const TVector<THolder<IBinaryPacksArray>>& binaryFeaturesData,
TVector<THolder<TColumn>>* result
) {
const size_t featureCount = (size_t)featuresLayout.GetFeatureCount(FeatureType);
if (WholeColumns) {
CB_ENSURE_INTERNAL(
DenseWholeColumns.size() == featureCount,
"DenseWholeColumns is inconsistent with feature Layout; "
LabeledOutput(DenseWholeColumns.size(), featureCount));
} else {
CB_ENSURE_INTERNAL(
DenseDataStorage.size() == featureCount,
"DenseDataStorage is inconsistent with feature Layout; "
LabeledOutput(DenseDataStorage.size(), featureCount));
CB_ENSURE_INTERNAL(
DenseDataStorage.size() == DenseDstView.size(),
"DenseDataStorage is inconsistent with DenseDstView; "
LabeledOutput(DenseDataStorage.size(), DenseDstView.size()));
}
result->clear();
result->reserve(featureCount);
for (auto perTypeFeatureIdx : xrange(featureCount)) {
if (IsAvailable[perTypeFeatureIdx]) {
auto featureId = featuresLayout.GetExternalFeatureIdx(perTypeFeatureIdx, FeatureType);
if (FeatureIdxToPackedBinaryIndex[perTypeFeatureIdx]) {
auto packedBinaryIndex = *FeatureIdxToPackedBinaryIndex[perTypeFeatureIdx];
result->push_back(
MakeHolder<TPackedBinaryValuesHolderImpl<TColumn>>(
featureId,
binaryFeaturesData[packedBinaryIndex.PackIdx].Get(),
packedBinaryIndex.BitIdx
)
);
} else {
result->push_back(
MakeHolder<TCompressedValuesHolderImpl<TColumn>>(
featureId,
TCompressedArray(
objectCount,
IndexHelpers[perTypeFeatureIdx].GetBitsPerKey(),
WholeColumns ?
std::move(DenseWholeColumns[perTypeFeatureIdx])
: TMaybeOwningArrayHolder<ui64>::CreateOwning(
DenseDstView[perTypeFeatureIdx],
DenseDataStorage[perTypeFeatureIdx]
)
),
subsetIndexing
)
);
}
} else {
result->push_back(nullptr);
}
}
}
};
private:
ui32 ObjectCount;
/* ForCPU because TQuantizedForCPUObjectsData is more generic than TQuantizedObjectsData -
* it contains it as a subset
*/
TQuantizedForCPUBuilderData Data;
TVector<TString> StringClassLabels; // if poolQuantizationSchema.ClassLabels has Strings
TVector<float> FloatClassLabels; // if poolQuantizationSchema.ClassLabels has Integer or Float
// will be moved to Data.RawTargetData at GetResult
TVector<TVector<TString>> StringTarget;
TVector<TVector<float>> FloatTarget;
// will be moved to Data.RawTargetData at GetResult
TVector<float> WeightsBuffer;
TVector<float> GroupWeightsBuffer;
TFeaturesStorage<EFeatureType::Float> FloatFeaturesStorage;
TFeaturesStorage<EFeatureType::Categorical> CategoricalFeaturesStorage;
TBinaryFeaturesStorage BinaryFeaturesStorage;
TDataProviderBuilderOptions Options;
TDatasetSubset DatasetSubset;
NPar::ILocalExecutor* LocalExecutor;
bool InProcess;
bool ResultTaken;
};
class TLazyQuantizedFeaturesDataProviderBuilder : public TQuantizedFeaturesDataProviderBuilder
{
public:
TLazyQuantizedFeaturesDataProviderBuilder(
const TDataProviderBuilderOptions& options,
NPar::ILocalExecutor* localExecutor
)
: TQuantizedFeaturesDataProviderBuilder(options, TDatasetSubset::MakeColumns(/*hasFeatures*/false), localExecutor)
, Options(options)
, PoolLoader(GetProcessor<IQuantizedPoolLoader, const TPathWithScheme&>(options.PoolPath, options.PoolPath))
, LocalExecutor(localExecutor)
{
CB_ENSURE(PoolLoader, "Cannot load dataset because scheme " << options.PoolPath.Scheme << " is unsupported");
CB_ENSURE(Options.GpuDistributedFormat, "Lazy columns are supported only in distributed GPU mode");
}
TDataProviderPtr GetResult() override {
GetTargetAndBinaryFeaturesData();
auto& dataRef = GetDataRef();
const auto& subsetIndexing = *dataRef.CommonObjectsData.SubsetIndexing;
const auto& featuresLayout = *dataRef.MetaInfo.FeaturesLayout;
CB_ENSURE(featuresLayout.GetFeatureCount(EFeatureType::Categorical) == 0, "Categorical Lazy columns are not supported");
dataRef.ObjectsData.Data.CatFeatures.clear();
const size_t featureCount = (size_t)featuresLayout.GetFeatureCount(EFeatureType::Float);
const auto& flatFeatureIdxToPackedBinaryIdx =
dataRef.ObjectsData.PackedBinaryFeaturesData.FlatFeatureIndexToPackedBinaryIndex;
const auto& isAvailable = MakeIsAvailable<EFeatureType::Float>(featuresLayout);
TVector<THolder<IQuantizedFloatValuesHolder>>& lazyQuantizedColumns =
dataRef.ObjectsData.Data.FloatFeatures;
lazyQuantizedColumns.clear();
lazyQuantizedColumns.reserve(featureCount);
for (auto perTypeFeatureIdx : xrange(featureCount)) {
if (isAvailable[perTypeFeatureIdx]) {
auto flatFeatureIdx = featuresLayout.GetExternalFeatureIdx(perTypeFeatureIdx, EFeatureType::Float);
CB_ENSURE(!flatFeatureIdxToPackedBinaryIdx[flatFeatureIdx], "Packed lazy columns are not supported");
lazyQuantizedColumns.push_back(
MakeHolder<TLazyCompressedValuesHolderImpl<IQuantizedFloatValuesHolder>>(
flatFeatureIdx,
&subsetIndexing,
PoolLoader)
);
} else {
lazyQuantizedColumns.push_back(nullptr);
}
}
SetResultsTaken();
return MakeDataProvider<TQuantizedForCPUObjectsDataProvider>(
/*objectsGrouping*/ Nothing(), // will init from data
std::move(dataRef),
Options.SkipCheck,
LocalExecutor
)->CastMoveTo<TObjectsDataProvider>();
}
private:
TDataProviderBuilderOptions Options;
TAtomicSharedPtr<IQuantizedPoolLoader> PoolLoader;
NPar::ILocalExecutor* const LocalExecutor;
};
THolder<IDataProviderBuilder> CreateDataProviderBuilder(
EDatasetVisitorType visitorType,
const TDataProviderBuilderOptions& options,
TDatasetSubset loadSubset,
NPar::ILocalExecutor* localExecutor
) {
switch (visitorType) {
case EDatasetVisitorType::RawObjectsOrder:
return MakeHolder<TRawObjectsOrderDataProviderBuilder>(options, localExecutor);
case EDatasetVisitorType::RawFeaturesOrder:
return MakeHolder<TRawFeaturesOrderDataProviderBuilder>(options, localExecutor);
case EDatasetVisitorType::QuantizedFeatures:
if (options.GpuDistributedFormat) {
return MakeHolder<TLazyQuantizedFeaturesDataProviderBuilder>(options, localExecutor);
} else {
return MakeHolder<TQuantizedFeaturesDataProviderBuilder>(options, loadSubset, localExecutor);
}
default:
return nullptr;
}
}
}
|
/*** Copyright (c), The Regents of the University of California ***
*** For more information please refer to files in the COPYRIGHT directory ***/
/* fileSyncToArch.h - This file may be generated by a program or script
*/
#ifndef FILE_SYNC_TO_ARCH_HPP
#define FILE_SYNC_TO_ARCH_HPP
/* This is a Object File I/O call */
#include "rods.hpp"
#include "rcMisc.hpp"
#include "procApiRequest.hpp"
#include "apiNumber.hpp"
#include "initServer.hpp"
#include "fileDriver.hpp"
#include "fileStageToCache.hpp"
#if defined(RODS_SERVER)
#define RS_FILE_SYNC_TO_ARCH rsFileSyncToArch
/* prototype for the server handler */
int
rsFileSyncToArch( rsComm_t *rsComm, fileStageSyncInp_t *fileSyncToArchInp, fileSyncOut_t** );
int
rsFileSyncToArchByHost( rsComm_t *rsComm, fileStageSyncInp_t *fileSyncToArchInp, fileSyncOut_t**,
rodsServerHost_t *rodsServerHost );
int
_rsFileSyncToArch( rsComm_t *rsComm, fileStageSyncInp_t *fileSyncToArchInp, fileSyncOut_t** );
int
remoteFileSyncToArch( rsComm_t *rsComm, fileStageSyncInp_t *fileSyncToArchInp, fileSyncOut_t**,
rodsServerHost_t *rodsServerHost );
#else
#define RS_FILE_SYNC_TO_ARCH NULL
#endif
/* prototype for the client call */
int
rcFileSyncToArch( rcComm_t *conn, fileStageSyncInp_t *fileSyncToArchInp, fileSyncOut_t** );
#endif /* FILE_SYNC_TO_ARCH_H */
|
/**
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
*/
/***********************************************************************************************************/
/* Declarations, macros, parser functions */
/***********************************************************************************************************/
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <bitset>
using namespace std;
#define FOR(i,m,n) for((i)=(m);(i)<(n);(i)++)
#define FORE(i,m,n) for((i)=(m);(i)<=(n);(i)++)
#define ROF(i,m,n) for((i)=(m);(i)>=(n);(i)--)
#define _FORIT(it, b, e) for (__typeof(b) it = (b); it != (e); it++)
#define FORIT(x...) _FORIT(x)
#define ALL(v) (v).begin(), (v).end()
#define RALL(v) (v).rbegin(), (v).rend()
#define SI(a) ((a).size())
#define PB push_back
#define MP make_pair
#define CLR(a,v) memset((a),(v),sizeof(a))
#define SORT(v) sort(ALL(v))
#define UNIQUE(v) SORT(v),(v).resize(unique(ALL(v))-(v).begin())
inline string ITOA(int a) {
char c[500]; sprintf(c, "%d", (a)); return string(c);
}
typedef vector<int> VI;
typedef vector<double> VD;
typedef vector<string> VS;
typedef vector<VI> VVI;
typedef vector<VD> VVD;
typedef vector<VS> VVS;
typedef pair<int,int> PII;
typedef signed long long i64;
typedef unsigned long long u64;
#define EPS 1E-9
#define INF 0x3F3F3F3F
#define DINF 1E16
#define NULO -1
#define PI 3.1415926535897932384626433832795
inline int cmp(double x, double y = 0, double tol = EPS) {
return (x <= y + tol) ? (x + tol < y) ? -1 : 0 : 1;
}
int main() {
char code[1001];
int dif[1001], n, i, j, k, m, ret;
for(; gets(code), strcmp(code,"*");) {
n = strlen(code); ret = 0;
dif[0] = code[0]-'a';
FOR(i,1,n) dif[i] = (code[i]-code[i-1]+26)%26;
dif[i] = ('a'-code[i-1]+26)%26;
while (1) {
m = INF; FORE(i,0,n) if (dif[i]>0 && dif[i]<m) m=dif[i], j = i;
if (m==INF) break;
m = -1; FORE(i,0,n) if (i!=j && dif[i]>m) m=dif[i], k = i;
ret++; dif[j]--; dif[k]=(dif[k]+1)%26;
}
printf("%d\n", ret);
}
return 0;
}
|
// Copyright (c) 2012-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "dbwrapper.h"
#include "uint256.h"
#include "random.h"
#include "test/test_safepe.h"
#include <boost/assign/std/vector.hpp> // for 'operator+=()'
#include <boost/assert.hpp>
#include <boost/test/unit_test.hpp>
// Test if a string consists entirely of null characters
bool is_null_key(const std::vector<unsigned char>& key) {
bool isnull = true;
for (unsigned int i = 0; i < key.size(); i++)
isnull &= (key[i] == '\x00');
return isnull;
}
BOOST_FIXTURE_TEST_SUITE(dbwrapper_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(dbwrapper)
{
// Perform tests both obfuscated and non-obfuscated.
for (int i = 0; i < 2; i++) {
bool obfuscate = (bool)i;
boost::filesystem::path ph = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path();
CDBWrapper dbw(ph, (1 << 20), true, false, obfuscate);
char key = 'k';
uint256 in = GetRandHash();
uint256 res;
// Ensure that we're doing real obfuscation when obfuscate=true
BOOST_CHECK(obfuscate != is_null_key(dbwrapper_private::GetObfuscateKey(dbw)));
BOOST_CHECK(dbw.Write(key, in));
BOOST_CHECK(dbw.Read(key, res));
BOOST_CHECK_EQUAL(res.ToString(), in.ToString());
}
}
// Test batch operations
BOOST_AUTO_TEST_CASE(dbwrapper_batch)
{
// Perform tests both obfuscated and non-obfuscated.
for (int i = 0; i < 2; i++) {
bool obfuscate = (bool)i;
boost::filesystem::path ph = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path();
CDBWrapper dbw(ph, (1 << 20), true, false, obfuscate);
char key = 'i';
uint256 in = GetRandHash();
char key2 = 'j';
uint256 in2 = GetRandHash();
char key3 = 'k';
uint256 in3 = GetRandHash();
uint256 res;
CDBBatch batch(dbw);
batch.Write(key, in);
batch.Write(key2, in2);
batch.Write(key3, in3);
// Remove key3 before it's even been written
batch.Erase(key3);
dbw.WriteBatch(batch);
BOOST_CHECK(dbw.Read(key, res));
BOOST_CHECK_EQUAL(res.ToString(), in.ToString());
BOOST_CHECK(dbw.Read(key2, res));
BOOST_CHECK_EQUAL(res.ToString(), in2.ToString());
// key3 should've never been written
BOOST_CHECK(dbw.Read(key3, res) == false);
}
}
BOOST_AUTO_TEST_CASE(dbwrapper_iterator)
{
// Perform tests both obfuscated and non-obfuscated.
for (int i = 0; i < 2; i++) {
bool obfuscate = (bool)i;
boost::filesystem::path ph = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path();
CDBWrapper dbw(ph, (1 << 20), true, false, obfuscate);
// The two keys are intentionally chosen for ordering
char key = 'j';
uint256 in = GetRandHash();
BOOST_CHECK(dbw.Write(key, in));
char key2 = 'k';
uint256 in2 = GetRandHash();
BOOST_CHECK(dbw.Write(key2, in2));
std::unique_ptr<CDBIterator> it(const_cast<CDBWrapper*>(&dbw)->NewIterator());
// Be sure to seek past the obfuscation key (if it exists)
it->Seek(key);
char key_res;
uint256 val_res;
it->GetKey(key_res);
it->GetValue(val_res);
BOOST_CHECK_EQUAL(key_res, key);
BOOST_CHECK_EQUAL(val_res.ToString(), in.ToString());
it->Next();
it->GetKey(key_res);
it->GetValue(val_res);
BOOST_CHECK_EQUAL(key_res, key2);
BOOST_CHECK_EQUAL(val_res.ToString(), in2.ToString());
it->Next();
BOOST_CHECK_EQUAL(it->Valid(), false);
}
}
// Test that we do not obfuscation if there is existing data.
BOOST_AUTO_TEST_CASE(existing_data_no_obfuscate)
{
// We're going to share this boost::filesystem::path between two wrappers
boost::filesystem::path ph = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path();
create_directories(ph);
// Set up a non-obfuscated wrapper to write some initial data.
CDBWrapper* dbw = new CDBWrapper(ph, (1 << 10), false, false, false);
char key = 'k';
uint256 in = GetRandHash();
uint256 res;
BOOST_CHECK(dbw->Write(key, in));
BOOST_CHECK(dbw->Read(key, res));
BOOST_CHECK_EQUAL(res.ToString(), in.ToString());
// Call the destructor to free leveldb LOCK
delete dbw;
// Now, set up another wrapper that wants to obfuscate the same directory
CDBWrapper odbw(ph, (1 << 10), false, false, true);
// Check that the key/val we wrote with unobfuscated wrapper exists and
// is readable.
uint256 res2;
BOOST_CHECK(odbw.Read(key, res2));
BOOST_CHECK_EQUAL(res2.ToString(), in.ToString());
BOOST_CHECK(!odbw.IsEmpty()); // There should be existing data
BOOST_CHECK(is_null_key(dbwrapper_private::GetObfuscateKey(odbw))); // The key should be an empty string
uint256 in2 = GetRandHash();
uint256 res3;
// Check that we can write successfully
BOOST_CHECK(odbw.Write(key, in2));
BOOST_CHECK(odbw.Read(key, res3));
BOOST_CHECK_EQUAL(res3.ToString(), in2.ToString());
}
// Ensure that we start obfuscating during a reindex.
BOOST_AUTO_TEST_CASE(existing_data_reindex)
{
// We're going to share this boost::filesystem::path between two wrappers
boost::filesystem::path ph = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path();
create_directories(ph);
// Set up a non-obfuscated wrapper to write some initial data.
CDBWrapper* dbw = new CDBWrapper(ph, (1 << 10), false, false, false);
char key = 'k';
uint256 in = GetRandHash();
uint256 res;
BOOST_CHECK(dbw->Write(key, in));
BOOST_CHECK(dbw->Read(key, res));
BOOST_CHECK_EQUAL(res.ToString(), in.ToString());
// Call the destructor to free leveldb LOCK
delete dbw;
// Simulate a -reindex by wiping the existing data store
CDBWrapper odbw(ph, (1 << 10), false, true, true);
// Check that the key/val we wrote with unobfuscated wrapper doesn't exist
uint256 res2;
BOOST_CHECK(!odbw.Read(key, res2));
BOOST_CHECK(!is_null_key(dbwrapper_private::GetObfuscateKey(odbw)));
uint256 in2 = GetRandHash();
uint256 res3;
// Check that we can write successfully
BOOST_CHECK(odbw.Write(key, in2));
BOOST_CHECK(odbw.Read(key, res3));
BOOST_CHECK_EQUAL(res3.ToString(), in2.ToString());
}
BOOST_AUTO_TEST_CASE(iterator_ordering)
{
boost::filesystem::path ph = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path();
CDBWrapper dbw(ph, (1 << 20), true, false, false);
for (int x=0x00; x<256; ++x) {
uint8_t key = x;
uint32_t value = x*x;
BOOST_CHECK(dbw.Write(key, value));
}
std::unique_ptr<CDBIterator> it(const_cast<CDBWrapper*>(&dbw)->NewIterator());
for (int c=0; c<2; ++c) {
int seek_start;
if (c == 0)
seek_start = 0x00;
else
seek_start = 0x80;
it->Seek((uint8_t)seek_start);
for (int x=seek_start; x<256; ++x) {
uint8_t key;
uint32_t value;
BOOST_CHECK(it->Valid());
if (!it->Valid()) // Avoid spurious errors about invalid iterator's key and value in case of failure
break;
BOOST_CHECK(it->GetKey(key));
BOOST_CHECK(it->GetValue(value));
BOOST_CHECK_EQUAL(key, x);
BOOST_CHECK_EQUAL(value, x*x);
it->Next();
}
BOOST_CHECK(!it->Valid());
}
}
struct StringContentsSerializer {
// Used to make two serialized objects the same while letting them have a different lengths
// This is a terrible idea
std::string str;
StringContentsSerializer() {}
StringContentsSerializer(const std::string& inp) : str(inp) {}
StringContentsSerializer& operator+=(const std::string& s) {
str += s;
return *this;
}
StringContentsSerializer& operator+=(const StringContentsSerializer& s) { return *this += s.str; }
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
if (ser_action.ForRead()) {
str.clear();
char c = 0;
while (true) {
try {
READWRITE(c);
str.push_back(c);
} catch (const std::ios_base::failure& e) {
break;
}
}
} else {
for (size_t i = 0; i < str.size(); i++)
READWRITE(str[i]);
}
}
};
BOOST_AUTO_TEST_CASE(iterator_string_ordering)
{
char buf[10];
boost::filesystem::path ph = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path();
CDBWrapper dbw(ph, (1 << 20), true, false, false);
for (int x=0x00; x<10; ++x) {
for (int y = 0; y < 10; y++) {
snprintf(buf, sizeof(buf), "%d", x);
StringContentsSerializer key(buf);
for (int z = 0; z < y; z++)
key += key;
uint32_t value = x*x;
BOOST_CHECK(dbw.Write(key, value));
}
}
std::unique_ptr<CDBIterator> it(const_cast<CDBWrapper*>(&dbw)->NewIterator());
for (int c=0; c<2; ++c) {
int seek_start;
if (c == 0)
seek_start = 0;
else
seek_start = 5;
snprintf(buf, sizeof(buf), "%d", seek_start);
StringContentsSerializer seek_key(buf);
it->Seek(seek_key);
for (int x=seek_start; x<10; ++x) {
for (int y = 0; y < 10; y++) {
snprintf(buf, sizeof(buf), "%d", x);
std::string exp_key(buf);
for (int z = 0; z < y; z++)
exp_key += exp_key;
StringContentsSerializer key;
uint32_t value;
BOOST_CHECK(it->Valid());
if (!it->Valid()) // Avoid spurious errors about invalid iterator's key and value in case of failure
break;
BOOST_CHECK(it->GetKey(key));
BOOST_CHECK(it->GetValue(value));
BOOST_CHECK_EQUAL(key.str, exp_key);
BOOST_CHECK_EQUAL(value, x*x);
it->Next();
}
}
BOOST_CHECK(!it->Valid());
}
}
BOOST_AUTO_TEST_SUITE_END()
|
#include "compat.h"
#include <QDateTime>
#include <cstdlib>
#include "types/camount.h"
#include "transactionfilterproxy.h"
#include "transactiontablemodel.h"
#include "transactionrecord.h"
// Earliest date that can be represented (far in the past)
const QDateTime TransactionFilterProxy::MIN_DATE = QDateTime::fromTime_t(0);
// Last date that can be represented (far in the future)
const QDateTime TransactionFilterProxy::MAX_DATE = QDateTime::fromTime_t(0xFFFFFFFF);
TransactionFilterProxy::TransactionFilterProxy(QObject *parent) :
QSortFilterProxyModel(parent),
dateFrom(MIN_DATE),
dateTo(MAX_DATE),
addrPrefix(),
typeFilter(COMMON_TYPES),
watchOnlyFilter(WatchOnlyFilter_All),
minAmount(0),
limitRows(-1),
showInactive(true)
{
}
bool TransactionFilterProxy::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
{
QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);
int type = index.data(TransactionTableModel::TypeRole).toInt();
QDateTime datetime = index.data(TransactionTableModel::DateRole).toDateTime();
bool involvesWatchAddress = index.data(TransactionTableModel::WatchonlyRole).toBool();
QString address = index.data(TransactionTableModel::AddressRole).toString();
QString label = index.data(TransactionTableModel::LabelRole).toString();
qint64 amount = llabs(index.data(TransactionTableModel::AmountRole).toLongLong());
int status = index.data(TransactionTableModel::StatusRole).toInt();
if(!showInactive && (status == TransactionStatus::Conflicted || status == TransactionStatus::NotAccepted))
return false;
if(!(TYPE(type) & typeFilter))
return false;
if (involvesWatchAddress && watchOnlyFilter == WatchOnlyFilter_No)
return false;
if (!involvesWatchAddress && watchOnlyFilter == WatchOnlyFilter_Yes)
return false;
if(datetime < dateFrom || datetime > dateTo)
return false;
if (!address.contains(addrPrefix, Qt::CaseInsensitive) && !label.contains(addrPrefix, Qt::CaseInsensitive))
return false;
if(amount < minAmount)
return false;
return true;
}
void TransactionFilterProxy::setDateRange(const QDateTime &from, const QDateTime &to)
{
this->dateFrom = from;
this->dateTo = to;
invalidateFilter();
}
void TransactionFilterProxy::setAddressPrefix(const QString &addrPrefix)
{
this->addrPrefix = addrPrefix;
invalidateFilter();
}
void TransactionFilterProxy::setTypeFilter(quint32 modes)
{
this->typeFilter = modes;
invalidateFilter();
}
void TransactionFilterProxy::setMinAmount(const CAmount& minimum)
{
this->minAmount = minimum;
invalidateFilter();
}
void TransactionFilterProxy::setWatchOnlyFilter(WatchOnlyFilter filter)
{
this->watchOnlyFilter = filter;
invalidateFilter();
}
void TransactionFilterProxy::setLimit(int limit)
{
this->limitRows = limit;
}
void TransactionFilterProxy::setShowInactive(bool showInactive)
{
this->showInactive = showInactive;
invalidateFilter();
}
int TransactionFilterProxy::rowCount(const QModelIndex &parent) const
{
if(limitRows != -1)
{
return std::min(QSortFilterProxyModel::rowCount(parent), limitRows);
}
else
{
return QSortFilterProxyModel::rowCount(parent);
}
}
|
#ifndef FW_TIME_HPP
#define FW_TIME_HPP
#include <Fw/Types/BasicTypes.hpp>
#include <Fw/Types/Assert.hpp>
#include <Fw/Types/Serializable.hpp>
#include <FpConfig.hpp>
namespace Fw {
class Time: public Serializable {
public:
enum {
SERIALIZED_SIZE = sizeof(FwTimeBaseStoreType)
+ sizeof(FwTimeContextStoreType)
+ sizeof(U32) + sizeof(U32)
};
Time(void); // !< Default constructor
Time(const Time& other); // !< Copy constructor
Time(U32 seconds, U32 useconds); // !< Constructor with member values as arguments
Time(TimeBase timeBase, U32 seconds, U32 useconds); // !< Constructor with member values as arguments
Time(TimeBase timeBase, FwTimeContextStoreType context, U32 seconds, U32 useconds); // !< Constructor with member values as arguments
virtual ~Time(void); // !< Destructor
void set(U32 seconds, U32 useconds); // !< Sets value of time stored
void set(TimeBase timeBase, U32 seconds, U32 useconds); // !< Sets value of time stored
void set(TimeBase timeBase, FwTimeContextStoreType context, U32 seconds, U32 useconds); // !< Sets value of time stored
void setTimeBase(TimeBase timeBase);
void setTimeContext(FwTimeContextStoreType context);
U32 getSeconds(void) const; // !< Gets seconds part of time
U32 getUSeconds(void) const; // !< Gets microseconds part of time
TimeBase getTimeBase(void) const; // !< Time base of time. This is project specific and is meant for indicating different sources of time
FwTimeContextStoreType getContext(void) const; // !< get the context value
SerializeStatus serialize(SerializeBufferBase& buffer) const; // !< Serialize method
SerializeStatus deserialize(SerializeBufferBase& buffer); // !< Deserialize method
bool operator==(const Time& other) const;
bool operator!=(const Time& other) const;
bool operator>(const Time& other) const;
bool operator<(const Time& other) const;
bool operator>=(const Time& other) const;
bool operator<=(const Time& other) const;
const Time& operator=(const Time& other);
// Static methods:
//! The type of a comparison result
typedef enum {
LT = -1,
EQ = 0,
GT = 1,
INCOMPARABLE = 2
} Comparison;
//! \return time zero
static Time zero(TimeBase timeBase=TB_NONE);
//! Compare two times
//! \return The result
static Comparison compare(
const Time &time1, //!< Time 1
const Time &time2 //!< Time 2
);
//! Add two times
//! \return The result
static Time add(
const Time& a, //!< Time a
const Time& b //!< Time b
);
//! Subtract subtrahend from minuend
//! \return The result
static Time sub(
const Time& minuend, //!< Value being subtracted from
const Time& subtrahend //!< Value being subtracted
);
// add seconds and microseconds to existing time
void add(U32 seconds, U32 mseconds);
#ifdef BUILD_UT // Stream operators to support Googletest
friend std::ostream& operator<<(std::ostream& os, const Time& val);
#endif
PRIVATE:
U32 m_seconds; // !< seconds portion
U32 m_useconds; // !< microseconds portion
TimeBase m_timeBase; // !< basis of time (defined by system)
FwTimeContextStoreType m_timeContext; // !< user settable value. Could be reboot count, node, etc
};
const static Time ZERO_TIME = Time();
}
#endif
|
/*
* Copyright (c) 2021, NVIDIA CORPORATION.
*
* 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 <base/debug/logger.hpp>
#include <random>
#include <resource_managers/resource_manager_ext.hpp>
#include <utils.hpp>
namespace HugeCTR {
std::shared_ptr<ResourceManager> ResourceManagerExt::create(
const std::vector<std::vector<int>>& visible_devices, unsigned long long seed,
DeviceMap::Layout layout) {
int size = 1, rank = 0;
#ifdef ENABLE_MPI
HCTR_MPI_THROW(MPI_Comm_size(MPI_COMM_WORLD, &size));
HCTR_MPI_THROW(MPI_Comm_rank(MPI_COMM_WORLD, &rank));
#endif
DeviceMap device_map(visible_devices, rank, layout);
std::random_device rd;
if (seed == 0) {
seed = rd();
}
#ifdef ENABLE_MPI
HCTR_MPI_THROW(MPI_Bcast(&seed, 1, MPI_UNSIGNED_LONG_LONG, 0, MPI_COMM_WORLD));
#endif
HCTR_LOG(INFO, ROOT, "Global seed is %llu\n", seed);
std::shared_ptr<ResourceManager> core(
new ResourceManagerCore(size, rank, std::move(device_map), seed));
return std::shared_ptr<ResourceManager>(new ResourceManagerExt(core));
}
#ifdef ENABLE_MPI
void ResourceManagerExt::init_ib_comm() {
int num_process = get_num_process();
if (num_process > 1) {
int process_id = get_process_id();
ib_comm_ = std::make_unique<IbComm>();
ib_comm_->init(num_process, get_local_gpu_count(), process_id, get_local_gpu_device_id_list());
}
}
#endif
void ResourceManagerExt::set_ar_comm(AllReduceAlgo algo, bool use_mixed_precision) {
int num_process = get_num_process();
#ifdef ENABLE_MPI
IbComm* ib_comm_ptr = nullptr;
if (algo == AllReduceAlgo::ONESHOT) {
init_ib_comm();
ib_comm_ptr = ib_comm_.get();
}
ar_comm_ = AllReduceInPlaceComm::create(num_process, algo, use_mixed_precision, get_local_gpus(),
ib_comm_ptr);
#else
ar_comm_ = AllReduceInPlaceComm::create(num_process, algo, use_mixed_precision, get_local_gpus());
#endif
}
} // namespace HugeCTR
|
/*
* Copyright (C) Volition, Inc. 1999. All rights reserved.
*
* All source code herein is the property of Volition, Inc. You may not sell
* or otherwise commercially exploit the source or things you created based on the
* source.
*
*/
#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#else
#include <arpa/inet.h>
#include <netdb.h>
#endif
#include "pcp.h"
#include "cmdline/cmdline.h"
#include "io/timer.h"
#include "network/multi_log.h"
#include "network/multi_portfwd.h"
#include "network/psnet2.h"
// from "default_config.h" in libpcp
#ifndef PCP_SERVER_PORT
#define PCP_SERVER_PORT 5351
#endif
#ifndef PCP_MAX_SUPPORTED_VERSION
#define PCP_MAX_SUPPORTED_VERSION 2
#endif
static bool PF_initted = false;
static pcp_flow_t *PF_pcp_flow = nullptr;
static pcp_ctx_t *PF_pcp_ctx = nullptr;
static int PF_wait_timestamp = 0;
static const uint32_t PF_lifetime = 7200; // 2 hrs
static void PF_log_init();
void multi_port_forward_init()
{
SOCKADDR_STORAGE gateway_addr;
SOCKADDR_STORAGE local_addr;
int wait_ms;
bool auto_discover = true;
if (PF_initted) {
return;
}
if (Cmdline_gateway_ip) {
if ( psnet_get_addr(Cmdline_gateway_ip, PCP_SERVER_PORT, &gateway_addr) ) {
auto_discover = false;
}
}
PF_log_init(); // must call before pcp_init() to fix logging
PF_pcp_ctx = pcp_init(auto_discover ? ENABLE_AUTODISCOVERY : DISABLE_AUTODISCOVERY, nullptr);
if (PF_pcp_ctx == nullptr) {
ml_string("Port forward => Initialization failed!");
return;
}
// this needs to be after successful pcp_init() so we'll know to shutdown
PF_initted = true;
if ( !auto_discover ) {
pcp_add_server(PF_pcp_ctx, reinterpret_cast<LPSOCKADDR>(&gateway_addr), PCP_MAX_SUPPORTED_VERSION);
}
psnet_get_addr(nullptr, Psnet_default_port, &local_addr);
PF_pcp_flow = pcp_new_flow(PF_pcp_ctx, reinterpret_cast<LPSOCKADDR>(&local_addr),
nullptr, nullptr, IPPROTO_UDP, PF_lifetime, nullptr);
if (PF_pcp_flow == nullptr) {
ml_string("Port forward => Failed to init mapping!");
multi_port_forward_close();
return;
}
ml_string("Port forward => Initialized successfully");
// let's start this ball rolling...
wait_ms = pcp_pulse(PF_pcp_ctx, nullptr);
PF_wait_timestamp = timer_get_milliseconds() + wait_ms;
}
void multi_port_forward_do()
{
pcp_fstate_e state;
size_t info_count = 0;
int wait_ms;
if ( !PF_initted ) {
return;
}
if ( PF_wait_timestamp > timer_get_milliseconds() ) {
return;
}
// this ultimately does everything to maintain the connection
wait_ms = pcp_pulse(PF_pcp_ctx, nullptr);
PF_wait_timestamp = timer_get_milliseconds() + wait_ms;
// check progress and log if needed
if ( pcp_eval_flow_state(PF_pcp_flow, &state) ) {
if (state == pcp_state_failed) {
ml_string("Port forward => Mapping failed!");
} else if (state == pcp_state_succeeded) {
pcp_flow_info_t *flow_info = pcp_flow_get_info(PF_pcp_flow, &info_count);
for (size_t idx = 0; idx < info_count; ++idx) {
pcp_flow_info_t *info = &flow_info[idx];
char time_str[16];
char int_ip[INET6_ADDRSTRLEN];
char ext_ip[INET6_ADDRSTRLEN];
memset(&int_ip, 0, sizeof(int_ip));
memset(&ext_ip, 0, sizeof(ext_ip));
inet_ntop(AF_INET6, psnet_mask_addr(&info->int_ip), int_ip, sizeof(int_ip));
inet_ntop(AF_INET6, psnet_mask_addr(&info->ext_ip), ext_ip, sizeof(ext_ip));
ml_printf("Port forward => Mapping successful [%s]:%u <-> [%s]:%u",
int_ip, ntohs(info->int_port),
ext_ip, ntohs(info->ext_port));
// formatted to match what multi_log uses
strftime(time_str, sizeof(time_str), "%m/%d %H:%M:%S", localtime(&info->recv_lifetime_end));
ml_printf("Port forward => Mapping valid until %s", time_str);
}
if (flow_info) {
free(flow_info); // system call, allocated in lib ** don't change! **
}
}
}
}
void multi_port_forward_close()
{
if ( !PF_initted ) {
return;
}
pcp_terminate(PF_pcp_ctx, 1);
if (PF_pcp_flow) {
ml_string("Port forward => Mapping removed");
} else {
ml_string("Port forward => Shutdown");
}
PF_pcp_ctx = nullptr;
PF_pcp_flow = nullptr;
PF_initted = false;
PF_wait_timestamp = 0;
}
#ifndef NDEBUG
static void PF_logger_fn(pcp_loglvl_e /* lvl */, const char *msg)
{
nprintf(("portfwd", "Port forward => %s", msg));
}
#endif
static void PF_log_init()
{
#ifdef NDEBUG
// log spew for libpcp is set with this
pcp_log_level = PCP_LOGLVL_NONE;
#else
pcp_log_level = PCP_LOGLVL_INFO;
pcp_set_loggerfn(PF_logger_fn);
#endif
}
|
// Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <algorithm>
#include <cinttypes>
#include <cmath>
#include <cstdlib>
#include <iterator>
#include <limits>
#include <numeric>
#include <random>
#include <string>
// clang-format off
#ifdef ${BACKEND_NAME}_FLOAT_TOLERANCE_BITS
#define DEFAULT_FLOAT_TOLERANCE_BITS ${BACKEND_NAME}_FLOAT_TOLERANCE_BITS
#endif
// clang-format on
#include "gtest/gtest.h"
#include "ngraph/check.hpp"
#include "ngraph/ngraph.hpp"
#include "ngraph/opsets/opset4.hpp"
#include "ngraph/op/util/attr_types.hpp"
#include "util/all_close.hpp"
#include "util/all_close_f.hpp"
#include "util/engine/test_engines.hpp"
#include "util/ndarray.hpp"
#include "util/random.hpp"
#include "util/test_case.hpp"
#include "util/test_control.hpp"
#include "util/test_tools.hpp"
NGRAPH_SUPPRESS_DEPRECATED_START
using namespace std;
using namespace ngraph;
static string s_manifest = "${MANIFEST}";
using TestEngine = test::ENGINE_CLASS_NAME(${BACKEND_NAME});
NGRAPH_TEST(${BACKEND_NAME}, elu)
{
auto A = make_shared<op::Parameter>(element::f32, Shape{3, 2});
auto elu = make_shared<op::Elu>(A, 0.5f);
auto function = make_shared<Function>(NodeVector{elu}, ParameterVector{A});
auto test_case = test::TestCase<TestEngine>(function);
test_case.add_input(vector<float>{-2.f, 3.f, -2.f, 1.f, -1.f, 0.f});
test_case.add_expected_output(
vector<float>{-0.432332358f, 3.f, -0.432332358f, 1.f, -0.316060279f, 0.f});
test_case.run();
}
NGRAPH_TEST(${BACKEND_NAME}, elu_negative_alpha)
{
auto A = make_shared<op::Parameter>(element::f32, Shape{3, 2});
auto elu = make_shared<op::Elu>(A, -1.f);
auto function = make_shared<Function>(NodeVector{elu}, ParameterVector{A});
auto test_case = test::TestCase<TestEngine>(function);
test_case.add_input(vector<float>{-2.f, 3.f, -2.f, 1.f, -1.f, 0.f});
test_case.add_expected_output(
vector<float>{0.864664717f, 3.f, 0.864664717f, 1.f, 0.632120559f, 0.f});
test_case.run();
}
NGRAPH_TEST(${BACKEND_NAME}, prelu)
{
Shape shape{3, 2};
Shape rshape{3};
auto A = make_shared<op::Parameter>(element::f32, shape);
auto B = make_shared<op::Parameter>(element::f32, rshape);
auto prelu = make_shared<op::PRelu>(A, B);
auto f = make_shared<Function>(NodeVector{prelu}, ParameterVector{A, B});
std::vector<float> a{-2, 3, -2, 1, -1, 0};
std::vector<float> b{0, 0.5, 1};
auto test_case = test::TestCase<TestEngine>(f);
test_case.add_multiple_inputs<float>({a, b});
test_case.add_expected_output<float>(vector<float>{0, 3, -1, 1, -1, 0});
test_case.run();
}
NGRAPH_TEST(${BACKEND_NAME}, hardsigmoid)
{
const Shape shape{2, 7};
const float alpha_f = 0.125f;
const float beta_f = 0.642f;
const auto A = make_shared<op::Parameter>(element::f32, shape);
const auto alpha = op::Constant::create<float>(A->get_element_type(), Shape{}, {alpha_f});
const auto beta = op::Constant::create<float>(A->get_element_type(), Shape{}, {beta_f});
auto hardsigmoid = make_shared<op::HardSigmoid>(A, alpha, beta);
auto f = make_shared<Function>(NodeVector{hardsigmoid}, ParameterVector{A});
vector<float> input{-1.f,
0.f,
1.f,
-100.f,
100.f,
-3.1234567f,
5.876543f,
7.13245364f,
numeric_limits<float>::max(),
numeric_limits<float>::lowest(),
numeric_limits<float>::min(),
numeric_limits<float>::infinity(),
numeric_limits<float>::min() / 16.f,
-numeric_limits<float>::min() / 16.f};
// Prepare expected output data
auto impl = [alpha_f, beta_f](float val) { return min(max(alpha_f * val + beta_f, 0.f), 1.f); };
vector<float> expected_output;
transform(begin(input), end(input), back_inserter(expected_output), impl);
auto test_case = test::TestCase<TestEngine>(f);
test_case.add_input<float>(input);
test_case.add_expected_output<float>(expected_output);
test_case.run();
}
NGRAPH_TEST(${BACKEND_NAME}, prelu_shared_slope)
{
Shape shape{3, 2};
Shape rshape{};
auto A = make_shared<op::Parameter>(element::f32, shape);
auto B = make_shared<op::Parameter>(element::f32, rshape);
auto prelu = make_shared<op::PRelu>(A, B);
auto f = make_shared<Function>(NodeVector{prelu}, ParameterVector{A, B});
std::vector<float> a{-2, 3, -2, 1, -1, 0};
std::vector<float> b{0.5};
auto test_case = test::TestCase<TestEngine>(f);
test_case.add_multiple_inputs<float>({a, b});
test_case.add_expected_output<float>(vector<float>{-1, 3, -1, 1, -0.5, 0});
test_case.run();
}
NGRAPH_TEST(${BACKEND_NAME}, prelu_negative_slope)
{
Shape shape{3, 2};
Shape rshape{};
auto A = make_shared<op::Parameter>(element::f32, shape);
auto B = make_shared<op::Parameter>(element::f32, rshape);
auto prelu = make_shared<op::PRelu>(A, B);
auto f = make_shared<Function>(NodeVector{prelu}, ParameterVector{A, B});
std::vector<float> a{-2, 3, -2, 1, -1, 0};
std::vector<float> b{-0.5};
auto test_case = test::TestCase<TestEngine>(f);
test_case.add_multiple_inputs<float>({a, b});
test_case.add_expected_output<float>(vector<float>{1, 3, 1, 1, 0.5, 0});
test_case.run();
}
NGRAPH_TEST(${BACKEND_NAME}, space_to_depth_block_first)
{
auto A = make_shared<op::Parameter>(element::f32, Shape{1, 2, 4, 4});
const auto mode = ngraph::op::SpaceToDepth::SpaceToDepthMode::BLOCKS_FIRST;
auto space_to_depth = make_shared<op::SpaceToDepth>(A, mode, 2);
auto function = make_shared<Function>(NodeVector{space_to_depth}, ParameterVector{A});
auto test_case = test::TestCase<TestEngine>(function);
test_case.add_input<float>({0.f, 1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f, 8.f, 9.f, 10.f,
11.f, 12.f, 13.f, 14.f, 15.f, 16.f, 17.f, 18.f, 19.f, 20.f, 21.f,
22.f, 23.f, 24.f, 25.f, 26.f, 27.f, 28.f, 29.f, 30.f, 31.f});
test_case.add_expected_output<float>(Shape{1, 8, 2, 2},
{
0.f, 2.f, 8.f, 10.f, 16.f, 18.f, 24.f, 26.f,
1.f, 3.f, 9.f, 11.f, 17.f, 19.f, 25.f, 27.f,
4.f, 6.f, 12.f, 14.f, 20.f, 22.f, 28.f, 30.f,
5.f, 7.f, 13.f, 15.f, 21.f, 23.f, 29.f, 31.f,
});
test_case.run();
}
NGRAPH_TEST(${BACKEND_NAME}, space_to_depth_depth_first)
{
auto A = make_shared<op::Parameter>(element::f32, Shape{1, 2, 4, 4});
const auto mode = ngraph::op::SpaceToDepth::SpaceToDepthMode::DEPTH_FIRST;
auto space_to_depth = make_shared<op::SpaceToDepth>(A, mode, 2);
auto function = make_shared<Function>(NodeVector{space_to_depth}, ParameterVector{A});
auto test_case = test::TestCase<TestEngine>(function);
test_case.add_input<float>({0.f, 16.f, 2.f, 18.f, 1.f, 17.f, 3.f, 19.f, 8.f, 24.f, 10.f,
26.f, 9.f, 25.f, 11.f, 27.f, 4.f, 20.f, 6.f, 22.f, 5.f, 21.f,
7.f, 23.f, 12.f, 28.f, 14.f, 30.f, 13.f, 29.f, 15.f, 31.f});
test_case.add_expected_output<float>(
Shape{1, 8, 2, 2}, {0.f, 2.f, 8.f, 10.f, 16.f, 18.f, 24.f, 26.f, 1.f, 3.f, 9.f,
11.f, 17.f, 19.f, 25.f, 27.f, 4.f, 6.f, 12.f, 14.f, 20.f, 22.f,
28.f, 30.f, 5.f, 7.f, 13.f, 15.f, 21.f, 23.f, 29.f, 31.f});
test_case.run();
}
NGRAPH_TEST(${BACKEND_NAME}, depth_to_space_block_first)
{
auto A = make_shared<op::Parameter>(element::f32, Shape{1, 8, 2, 2});
auto depth_to_space =
make_shared<op::DepthToSpace>(A, op::DepthToSpace::DepthToSpaceMode::BLOCKS_FIRST, 2);
auto function = make_shared<Function>(NodeVector{depth_to_space}, ParameterVector{A});
auto test_case = test::TestCase<TestEngine>(function);
test_case.add_input<float>({
0.f, 2.f, 8.f, 10.f, 16.f, 18.f, 24.f, 26.f, 1.f, 3.f, 9.f, 11.f, 17.f, 19.f, 25.f, 27.f,
4.f, 6.f, 12.f, 14.f, 20.f, 22.f, 28.f, 30.f, 5.f, 7.f, 13.f, 15.f, 21.f, 23.f, 29.f, 31.f,
});
test_case.add_expected_output<float>(
Shape{1, 2, 4, 4}, {0.f, 1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f, 8.f, 9.f, 10.f,
11.f, 12.f, 13.f, 14.f, 15.f, 16.f, 17.f, 18.f, 19.f, 20.f, 21.f,
22.f, 23.f, 24.f, 25.f, 26.f, 27.f, 28.f, 29.f, 30.f, 31.f});
test_case.run();
}
NGRAPH_TEST(${BACKEND_NAME}, depth_to_space_depth_first)
{
auto A = make_shared<op::Parameter>(element::f32, Shape{1, 8, 2, 2});
auto depth_to_space =
make_shared<op::DepthToSpace>(A, op::DepthToSpace::DepthToSpaceMode::DEPTH_FIRST, 2);
auto function = make_shared<Function>(NodeVector{depth_to_space}, ParameterVector{A});
auto test_case = test::TestCase<TestEngine>(function);
test_case.add_input<float>({
0.f, 2.f, 8.f, 10.f, 16.f, 18.f, 24.f, 26.f, 1.f, 3.f, 9.f, 11.f, 17.f, 19.f, 25.f, 27.f,
4.f, 6.f, 12.f, 14.f, 20.f, 22.f, 28.f, 30.f, 5.f, 7.f, 13.f, 15.f, 21.f, 23.f, 29.f, 31.f,
});
test_case.add_expected_output<float>(
Shape{1, 2, 4, 4}, {0.f, 16.f, 2.f, 18.f, 1.f, 17.f, 3.f, 19.f, 8.f, 24.f, 10.f,
26.f, 9.f, 25.f, 11.f, 27.f, 4.f, 20.f, 6.f, 22.f, 5.f, 21.f,
7.f, 23.f, 12.f, 28.f, 14.f, 30.f, 13.f, 29.f, 15.f, 31.f});
test_case.run();
}
// TODO: Issue: 37521
NGRAPH_TEST(${BACKEND_NAME}, DISABLED_normalize_across_chw_4d)
{
Shape data_shape{1, 2, 3, 4};
auto data = make_shared<op::Parameter>(element::f32, data_shape);
const auto axes = make_shared<op::Constant>(element::i64, Shape{3}, vector<int64_t>{1, 2, 3});
float eps{1e-6f};
auto eps_mode = op::EpsMode::ADD;
auto normalize = make_shared<op::NormalizeL2>(data, axes, eps, eps_mode);
auto function = make_shared<Function>(NodeVector{normalize}, ParameterVector{data});
auto test_case = test::TestCase<TestEngine>(function);
vector<float> input_data(shape_size(data_shape));
iota(begin(input_data), end(input_data), 1);
test_case.add_input<float>(input_data);
test_case.add_expected_output<float>(
data_shape, {0.01428571f, 0.02857143f, 0.04285714f, 0.05714286f, 0.07142857f, 0.08571429f,
0.1f, 0.11428571f, 0.12857144f, 0.14285715f, 0.15714286f, 0.17142858f,
0.18571429f, 0.2f, 0.21428572f, 0.22857143f, 0.24285714f, 0.25714287f,
0.27142859f, 0.2857143f, 0.30000001f, 0.31428573f, 0.32857144f, 0.34285715f});
test_case.run(DEFAULT_FLOAT_TOLERANCE_BITS + 1);
}
NGRAPH_TEST(${BACKEND_NAME}, DISABLED_normalize_across_empty_axes_input)
{
Shape data_shape{1, 2, 3, 4};
auto data = make_shared<op::Parameter>(element::f32, data_shape);
const auto axes = make_shared<op::Constant>(element::i64, Shape{0}, vector<int64_t>{});
float eps{1e-6f};
auto eps_mode = op::EpsMode::ADD;
auto normalize = make_shared<op::NormalizeL2>(data, axes, eps, eps_mode);
auto function = make_shared<Function>(NodeVector{normalize}, ParameterVector{data});
auto test_case = test::TestCase<TestEngine>(function);
vector<float> input_data(shape_size(data_shape));
iota(begin(input_data), end(input_data), 1);
test_case.add_input<float>(input_data);
test_case.add_expected_output<float>(
data_shape,
vector<float>{0.01428571, 0.02857143, 0.04285714, 0.05714286, 0.07142857, 0.08571429,
0.1, 0.11428571, 0.12857144, 0.14285715, 0.15714286, 0.17142858,
0.18571429, 0.2, 0.21428572, 0.22857143, 0.24285714, 0.25714287,
0.27142859, 0.2857143, 0.3, 0.31428573, 0.32857144, 0.34285715});
test_case.run(DEFAULT_FLOAT_TOLERANCE_BITS + 1);
}
NGRAPH_TEST(${BACKEND_NAME}, DISABLED_normalize_across_h_4d)
{
Shape data_shape{1, 2, 3, 4};
auto data = make_shared<op::Parameter>(element::f32, data_shape);
const auto axes = make_shared<op::Constant>(element::i64, Shape{1}, vector<int64_t>{1});
float eps{1e-6f};
auto eps_mode = op::EpsMode::ADD;
auto normalize = make_shared<op::NormalizeL2>(data, axes, eps, eps_mode);
auto function = make_shared<Function>(NodeVector{normalize}, ParameterVector{data});
auto test_case = test::TestCase<TestEngine>(function);
vector<float> input_data(shape_size(data_shape));
iota(begin(input_data), end(input_data), 1);
test_case.add_input<float>(input_data);
test_case.add_expected_output<float>(
data_shape, {0.0766965f, 0.14142136f, 0.19611613f, 0.24253564f, 0.28216633f, 0.31622776f,
0.34570536f, 0.37139067f, 0.39391932f, 0.41380295f, 0.43145549f, 0.44721359f,
0.99705452f, 0.98994946f, 0.98058069f, 0.97014254f, 0.95936549f, 0.94868332f,
0.93834311f, 0.92847669f, 0.91914505f, 0.91036648f, 0.90213418f, 0.89442718f});
test_case.run(DEFAULT_FLOAT_TOLERANCE_BITS + 1);
}
NGRAPH_TEST(${BACKEND_NAME}, DISABLED_normalize_across_1axis_5d)
{
Shape data_shape{1, 2, 2, 2, 3};
auto data = make_shared<op::Parameter>(element::f32, data_shape);
const auto axes = make_shared<op::Constant>(element::i64, Shape{1}, vector<int64_t>{1});
float eps{1e-6f};
auto eps_mode = op::EpsMode::ADD;
auto normalize = make_shared<op::NormalizeL2>(data, axes, eps, eps_mode);
auto function = make_shared<Function>(NodeVector{normalize}, ParameterVector{data});
auto test_case = test::TestCase<TestEngine>(function);
vector<float> input_data(shape_size(data_shape));
iota(begin(input_data), end(input_data), 1);
test_case.add_input<float>(input_data);
test_case.add_expected_output<float>(
data_shape, {0.0766965f, 0.14142136f, 0.19611613f, 0.24253564f, 0.28216633f, 0.31622776f,
0.34570536f, 0.37139067f, 0.39391932f, 0.41380295f, 0.43145549f, 0.44721359f,
0.99705452f, 0.98994946f, 0.98058069f, 0.97014254f, 0.95936549f, 0.94868332f,
0.93834311f, 0.92847669f, 0.91914505f, 0.91036648f, 0.90213418f, 0.89442718f});
test_case.run(DEFAULT_FLOAT_TOLERANCE_BITS + 1);
}
NGRAPH_TEST(${BACKEND_NAME}, DISABLED_normalize_across_123axes_5d)
{
Shape data_shape{1, 2, 2, 2, 3};
auto data = make_shared<op::Parameter>(element::f32, data_shape);
const auto axes = make_shared<op::Constant>(element::i64, Shape{3}, vector<int64_t>{1, 2, 3});
float eps{1e-6f};
auto eps_mode = op::EpsMode::ADD;
auto normalize = make_shared<op::NormalizeL2>(data, axes, eps, eps_mode);
auto function = make_shared<Function>(NodeVector{normalize}, ParameterVector{data});
auto test_case = test::TestCase<TestEngine>(function);
vector<float> input_data(shape_size(data_shape));
iota(begin(input_data), end(input_data), 1);
test_case.add_input<float>(input_data);
test_case.add_expected_output<float>(
data_shape, {0.02638899f, 0.04956816f, 0.070014f, 0.10555596f, 0.1239204f, 0.140028f,
0.18472293f, 0.19827265f, 0.210042f, 0.26388991f, 0.27262488f, 0.280056f,
0.34305686f, 0.34697714f, 0.35007f, 0.42222384f, 0.42132938f, 0.420084f,
0.50139081f, 0.49568161f, 0.49009803f, 0.58055776f, 0.57003385f, 0.560112f});
test_case.run(DEFAULT_FLOAT_TOLERANCE_BITS + 1);
}
NGRAPH_TEST(${BACKEND_NAME}, DISABLED_normalize_across_c_2x2_shape)
{
Shape data_shape{2, 2};
auto data = make_shared<op::Parameter>(element::f32, data_shape);
const auto axes = make_shared<op::Constant>(element::i64, Shape{}, vector<int64_t>{1});
float eps{1e-6f};
auto eps_mode = op::EpsMode::ADD;
auto normalize = make_shared<op::NormalizeL2>(data, axes, eps, eps_mode);
auto function = make_shared<Function>(NodeVector{normalize}, ParameterVector{data});
auto test_case = test::TestCase<TestEngine>(function);
vector<float> input_data(shape_size(data_shape));
iota(begin(input_data), end(input_data), 1);
test_case.add_input<float>(input_data);
test_case.add_expected_output<float>(data_shape,
{0.44721353f, 0.89442706f, 0.60000002f, 0.80000001f});
test_case.run(DEFAULT_FLOAT_TOLERANCE_BITS + 1);
}
NGRAPH_TEST(${BACKEND_NAME}, DISABLED_normalize_across_c_2x4_shape)
{
Shape data_shape{2, 4};
auto data = make_shared<op::Parameter>(element::f32, data_shape);
const auto axes = make_shared<op::Constant>(element::i64, Shape{}, vector<int64_t>{1});
float eps{1e-6f};
auto eps_mode = op::EpsMode::ADD;
auto normalize = make_shared<op::NormalizeL2>(data, axes, eps, eps_mode);
auto function = make_shared<Function>(NodeVector{normalize}, ParameterVector{data});
auto test_case = test::TestCase<TestEngine>(function);
vector<float> input_data(shape_size(data_shape));
iota(begin(input_data), end(input_data), 1);
test_case.add_input<float>(input_data);
test_case.add_expected_output<float>(data_shape,
{0.18257418f,
0.36514837f,
0.54772252f,
0.73029673f,
0.37904903f,
0.45485884f,
0.53066862f,
0.60647845f});
test_case.run(DEFAULT_FLOAT_TOLERANCE_BITS + 1);
}
NGRAPH_TEST(${BACKEND_NAME}, DISABLED_normalize_across_chw_4d_max_bias)
{
Shape data_shape{1, 2, 3, 4};
auto data = make_shared<op::Parameter>(element::f32, data_shape);
const auto axes = make_shared<op::Constant>(element::i64, Shape{3}, vector<int64_t>{1, 2, 3});
float eps{5000};
auto eps_mode = op::EpsMode::MAX;
auto normalize = make_shared<op::NormalizeL2>(data, axes, eps, eps_mode);
auto function = make_shared<Function>(NodeVector{normalize}, ParameterVector{data});
auto test_case = test::TestCase<TestEngine>(function);
vector<float> input_data(shape_size(data_shape));
iota(begin(input_data), end(input_data), 1);
test_case.add_input<float>(input_data);
test_case.add_expected_output<float>(
data_shape, {0.01414214f, 0.02828427f, 0.04242641f, 0.05656854f, 0.07071068f, 0.08485281f,
0.09899495f, 0.11313709f, 0.12727922f, 0.14142136f, 0.15556349f, 0.16970563f,
0.18384777f, 0.1979899f, 0.21213204f, 0.22627418f, 0.2404163f, 0.25455844f,
0.26870057f, 0.28284273f, 0.29698485f, 0.31112698f, 0.32526913f, 0.33941126f});
test_case.run(DEFAULT_FLOAT_TOLERANCE_BITS + 1);
}
NGRAPH_TEST(${BACKEND_NAME}, mvn_mean_normalization)
{
Shape data_shape{1, 2, 5};
auto data = make_shared<op::Parameter>(element::f32, data_shape);
auto mvn_func = make_shared<op::MVN>(data, true, false);
auto function = make_shared<Function>(NodeVector{mvn_func}, ParameterVector{data});
auto test_case = test::TestCase<TestEngine>(function);
// data
vector<float> data_vector(shape_size(data_shape));
iota(begin(data_vector), end(data_vector), 0);
test_case.add_input<float>(data_vector);
// expected result
test_case.add_expected_output<float>(
data_shape, vector<float>{-4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5});
test_case.run();
}
NGRAPH_TEST(${BACKEND_NAME}, mvn_mean_normalization_split_channels)
{
Shape data_shape{1, 2, 5, 1};
auto data = make_shared<op::Parameter>(element::f32, data_shape);
auto mvn_func = make_shared<op::MVN>(data, false, false);
auto function = make_shared<Function>(NodeVector{mvn_func}, ParameterVector{data});
auto test_case = test::TestCase<TestEngine>(function);
// data
vector<float> data_vector(shape_size(data_shape));
iota(begin(data_vector), end(data_vector), 0);
test_case.add_input<float>(data_vector);
// expected result
test_case.add_expected_output<float>({1, 2, 5, 1},
vector<float>{-2, -1, 0, 1, 2, -2, -1, 0, 1, 2});
test_case.run();
}
NGRAPH_TEST(${BACKEND_NAME}, mvn_mean_variance_normalization)
{
Shape data_shape{1, 2, 5};
auto data = make_shared<op::Parameter>(element::f32, data_shape);
auto mvn_func = make_shared<op::MVN>(data);
auto function = make_shared<Function>(NodeVector{mvn_func}, ParameterVector{data});
auto test_case = test::TestCase<TestEngine>(function);
// data
vector<float> data_vector(shape_size(data_shape));
iota(begin(data_vector), end(data_vector), 0);
test_case.add_input<float>(data_vector);
// expected result
test_case.add_expected_output<float>(data_shape,
vector<float>{-1.566698903055826,
-1.2185435912656424,
-0.87038827947545883,
-0.52223296768527527,
-0.17407765589509178,
0.17407765589509178,
0.52223296768527527,
0.87038827947545883,
1.2185435912656424,
1.566698903055826});
test_case.run();
}
NGRAPH_TEST(${BACKEND_NAME}, mvn_mean_variance_normalization_split_channels)
{
Shape data_shape{1, 2, 5};
auto data = make_shared<op::Parameter>(element::f32, data_shape);
auto mvn_func = make_shared<op::MVN>(data, false);
auto function = make_shared<Function>(NodeVector{mvn_func}, ParameterVector{data});
auto test_case = test::TestCase<TestEngine>(function);
// data
vector<float> data_vector(shape_size(data_shape));
iota(begin(data_vector), end(data_vector), 0);
test_case.add_input<float>(data_vector);
// expected result
test_case.add_expected_output<float>(data_shape,
vector<float>{-1.4142135613730948,
-0.70710678068654742,
0.000000000000000,
0.70710678068654742,
1.4142135613730948,
-1.4142135613730948,
-0.70710678068654742,
0.000000000000000,
0.70710678068654742,
1.4142135613730948});
test_case.run();
}
NGRAPH_TEST(${BACKEND_NAME}, mvn_mean_variance_normalization_shared_across_channel_batch_size_2)
{
Shape data_shape{2, 2, 5};
auto data = make_shared<op::Parameter>(element::f32, data_shape);
auto mvn_func = make_shared<op::MVN>(data, true);
auto function = make_shared<Function>(NodeVector{mvn_func}, ParameterVector{data});
auto test_case = test::TestCase<TestEngine>(function);
// data
vector<float> data_vector(shape_size(data_shape));
iota(begin(data_vector), end(data_vector), 0);
test_case.add_input<float>(data_vector);
// expected result
test_case.add_expected_output<float>(
data_shape,
{-1.5666989f, -1.2185436f, -0.8703883f, -0.5222329f, -0.1740777f, 0.1740777f, 0.5222329f,
0.8703883f, 1.2185436f, 1.5666989f, -1.5666989f, -1.2185436f, -0.8703883f, -0.5222329f,
-0.1740777f, 0.1740777f, 0.5222329f, 0.8703883f, 1.2185436f, 1.5666989f});
test_case.run();
}
NGRAPH_TEST(${BACKEND_NAME}, mvn_mean_variance_normalization_not_shared_across_channel_batch_size_2)
{
Shape data_shape{2, 2, 5};
auto data = make_shared<op::Parameter>(element::f32, data_shape);
auto mvn_func = make_shared<op::MVN>(data, false);
auto function = make_shared<Function>(NodeVector{mvn_func}, ParameterVector{data});
auto test_case = test::TestCase<TestEngine>(function);
// data
vector<float> data_vector(shape_size(data_shape));
iota(begin(data_vector), end(data_vector), 0);
test_case.add_input<float>(data_vector);
// expected result
test_case.add_expected_output<float>(
data_shape,
{-1.4142135f, -0.7071068f, 0.0000000f, 0.7071068f, 1.4142135f, -1.4142135f, -0.7071068f,
0.0000000f, 0.7071068f, 1.4142135f, -1.4142135f, -0.7071068f, 0.0000000f, 0.7071068f,
1.4142135f, -1.4142135f, -0.7071068f, 0.0000000f, 0.7071068f, 1.4142135f});
test_case.run();
}
NGRAPH_TEST(${BACKEND_NAME}, grn_4d)
{
const Shape data_shape{1, 2, 3, 4};
const auto data = make_shared<op::Parameter>(element::f32, data_shape);
float bias{1e-6f};
const auto grn = make_shared<op::GRN>(data, bias);
const auto function = make_shared<Function>(NodeVector{grn}, ParameterVector{data});
auto test_case = test::TestCase<TestEngine>(function);
vector<float> input_data(shape_size(data_shape));
iota(begin(input_data), end(input_data), 1);
test_case.add_input<float>(input_data);
test_case.add_expected_output<float>(
data_shape, {0.0766965f, 0.14142136f, 0.19611613f, 0.24253564f, 0.28216633f, 0.31622776f,
0.34570536f, 0.37139067f, 0.39391932f, 0.41380295f, 0.4314555f, 0.4472136f,
0.9970545f, 0.98994946f, 0.9805807f, 0.97014254f, 0.9593655f, 0.9486833f,
0.9383431f, 0.9284767f, 0.91914505f, 0.9103665f, 0.9021342f, 0.8944272f});
test_case.run();
}
NGRAPH_TEST(${BACKEND_NAME}, DISABLED_grn_2d_with_bias)
{
const Shape data_shape{3, 4};
const auto data = make_shared<op::Parameter>(element::f32, data_shape);
float bias{2.25f};
const auto grn = make_shared<op::GRN>(data, bias);
const auto function = make_shared<Function>(NodeVector{grn}, ParameterVector{data});
auto test_case = test::TestCase<TestEngine>(function);
vector<float> input_data(shape_size(data_shape));
iota(begin(input_data), end(input_data), 1);
test_case.add_input<float>(input_data);
test_case.add_expected_output<float>(data_shape,
{0.5547002f,
0.8f,
0.8944272f,
0.9363292f,
0.95782626f,
0.9701425f,
0.9778024f,
0.98287225f,
0.9863939f,
0.9889363f,
0.9908301f,
0.99227786f});
test_case.run();
}
NGRAPH_TEST(${BACKEND_NAME}, unsqueeze)
{
auto data_node = make_shared<op::Parameter>(element::f32, Shape{4, 2});
auto axes_node =
make_shared<ngraph::op::Constant>(element::i64, Shape{2}, vector<int64_t>{1, 2});
auto squeeze = make_shared<op::v0::Unsqueeze>(data_node, axes_node);
auto function = make_shared<Function>(NodeVector{squeeze}, ParameterVector{data_node});
auto test_case = test::TestCase<TestEngine>(function);
auto data = vector<float>{1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f};
test_case.add_input(data);
test_case.add_expected_output<float>(Shape{4, 1, 1, 2}, data);
}
NGRAPH_TEST(${BACKEND_NAME}, shuffle_channels_simple)
{
const auto data = make_shared<op::Parameter>(element::i32, Shape{1, 15, 2, 2});
auto tested_op = make_shared<op::ShuffleChannels>(data, 1, 5);
auto function = make_shared<Function>(tested_op, ParameterVector{data});
auto test_case = test::TestCase<TestEngine>(function);
std::vector<int32_t> input_data(60);
std::iota(std::begin(input_data), std::end(input_data), 0);
test_case.add_input(input_data);
test_case.add_expected_output<int32_t>(
Shape{1, 15, 2, 2},
{0, 1, 2, 3, 12, 13, 14, 15, 24, 25, 26, 27, 36, 37, 38, 39, 48, 49, 50, 51,
4, 5, 6, 7, 16, 17, 18, 19, 28, 29, 30, 31, 40, 41, 42, 43, 52, 53, 54, 55,
8, 9, 10, 11, 20, 21, 22, 23, 32, 33, 34, 35, 44, 45, 46, 47, 56, 57, 58, 59});
test_case.run();
}
NGRAPH_TEST(${BACKEND_NAME}, shuffle_channels_negative_axis)
{
// in this test the output is the same as in shuffle_channels_simple but
// the axis value is negative and the C(channels) value is in a different dimension(0) of the
// shape
const auto data = make_shared<op::Parameter>(element::i32, Shape{15, 2, 1, 2});
auto tested_op = make_shared<op::ShuffleChannels>(data, -4, 5);
auto function = make_shared<Function>(tested_op, ParameterVector{data});
auto test_case = test::TestCase<TestEngine>(function);
std::vector<int32_t> input_data(60);
std::iota(std::begin(input_data), std::end(input_data), 0);
test_case.add_input(input_data);
test_case.add_expected_output<int32_t>(
Shape{15, 2, 1, 2},
{0, 1, 2, 3, 12, 13, 14, 15, 24, 25, 26, 27, 36, 37, 38, 39, 48, 49, 50, 51,
4, 5, 6, 7, 16, 17, 18, 19, 28, 29, 30, 31, 40, 41, 42, 43, 52, 53, 54, 55,
8, 9, 10, 11, 20, 21, 22, 23, 32, 33, 34, 35, 44, 45, 46, 47, 56, 57, 58, 59});
test_case.run();
}
NGRAPH_TEST(${BACKEND_NAME}, shuffle_channels_float)
{
const auto data = make_shared<op::Parameter>(element::f32, Shape{6, 1, 1, 1});
auto tested_op = make_shared<op::ShuffleChannels>(data, 0, 2);
auto function = make_shared<Function>(tested_op, ParameterVector{data});
auto test_case = test::TestCase<TestEngine>(function);
test_case.add_input<float>({0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f});
test_case.add_expected_output<float>(Shape{6, 1, 1, 1}, {0.0f, 3.0f, 1.0f, 4.0f, 2.0f, 5.0f});
test_case.run();
}
NGRAPH_TEST(${BACKEND_NAME}, squeeze)
{
const auto data_node = make_shared<op::Parameter>(element::f32, Shape{1, 4, 1, 1, 2});
const auto axes_node =
make_shared<ngraph::op::Constant>(element::i64, Shape{2}, vector<int64_t>{0, 2});
const auto squeeze = make_shared<op::Squeeze>(data_node, axes_node);
const auto function = make_shared<Function>(NodeVector{squeeze}, ParameterVector{data_node});
auto test_case = test::TestCase<TestEngine>(function);
const auto data = vector<float>{1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f};
test_case.add_input(data);
test_case.add_expected_output<float>(Shape{4, 1, 2}, data);
test_case.run();
}
NGRAPH_TEST(${BACKEND_NAME}, squeeze_default_axes)
{
const auto data_node = make_shared<op::Parameter>(element::f32, Shape{1, 4, 1, 1, 2});
const auto axes_node =
make_shared<ngraph::op::Constant>(element::i64, Shape{0}, vector<int64_t>{});
const auto squeeze = make_shared<op::Squeeze>(data_node, axes_node);
const auto function = make_shared<Function>(NodeVector{squeeze}, ParameterVector{data_node});
auto test_case = test::TestCase<TestEngine>(function);
const auto data = vector<float>{1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f};
test_case.add_input(data);
test_case.add_expected_output<float>(Shape{4, 2}, data);
test_case.run();
}
NGRAPH_TEST(${BACKEND_NAME}, squeeze_dynamic)
{
const auto data_param = make_shared<op::Parameter>(element::f32, Shape{1, 4, 1, 1, 2});
const auto axes_param = make_shared<op::Parameter>(element::i64, Shape{2});
const auto squeeze = make_shared<op::Squeeze>(data_param, axes_param);
const auto function = make_shared<Function>(NodeVector{squeeze}, ParameterVector{data_param, axes_param});
auto test_case = test::TestCase<TestEngine>(function);
const auto data = vector<float>{1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f};
test_case.add_input(data);
test_case.add_input(vector<int64_t>{0, 2});
test_case.add_expected_output<float>(Shape{4, 1, 2}, data);
test_case.run();
}
// TODO: Issue: 37534
NGRAPH_TEST(${BACKEND_NAME}, DISABLED_squared_difference)
{
const auto x1 = make_shared<op::Parameter>(element::f32, Shape{2, 2});
const auto x2 = make_shared<op::Parameter>(element::f32, Shape{2, 2});
auto tested_op = make_shared<op::SquaredDifference>(x1, x2);
auto function = make_shared<Function>(tested_op, ParameterVector{x1, x2});
auto test_case = test::TestCase<TestEngine>(function);
test_case.add_input<float>({1.0, 16.0, 0.0, 1.234567});
test_case.add_input<float>({1.0, 8.0, -3.0, 3.456789});
test_case.add_expected_output<float>(Shape{2, 2}, {0.0, 64.0, 9.0, 4.938270617284});
test_case.run();
}
NGRAPH_TEST(${BACKEND_NAME}, DISABLED_squared_difference_broadcast)
{
const auto x1 = make_shared<op::Parameter>(element::i32, Shape{2, 2});
const auto x2 = make_shared<op::Parameter>(element::i32, Shape{});
auto tested_op = make_shared<op::SquaredDifference>(x1, x2);
auto function = make_shared<Function>(tested_op, ParameterVector{x1, x2});
auto test_case = test::TestCase<TestEngine>(function);
test_case.add_input<int32_t>({1, 1, 1, 1});
test_case.add_input<int32_t>({1});
test_case.add_expected_output<int32_t>(Shape{2, 2}, {0, 0, 0, 0});
test_case.run();
}
// TODO: Issue: 37511
NGRAPH_TEST(${BACKEND_NAME}, DISABLED_fake_quantize)
{
const Shape data_shape{1, 2, 3, 4};
const size_t levels = 4;
const auto data = make_shared<op::Parameter>(element::f32, data_shape);
const auto input_low = make_shared<op::Parameter>(element::f32, Shape{});
const auto input_high = make_shared<op::Parameter>(element::f32, Shape{});
const auto output_low = make_shared<op::Parameter>(element::f32, Shape{});
const auto output_high = make_shared<op::Parameter>(element::f32, Shape{});
const auto quantize =
make_shared<op::FakeQuantize>(data, input_low, input_high, output_low, output_high, levels);
const auto function = make_shared<Function>(
NodeVector{quantize},
ParameterVector{data, input_low, input_high, output_low, output_high});
auto test_case = test::TestCase<TestEngine>(function);
const size_t n_elements = shape_size(data_shape);
vector<float> input_data(n_elements);
iota(begin(input_data), end(input_data), 0);
test_case.add_input<float>(input_data);
// input_low
test_case.add_input<float>({0.0f});
// input_high
test_case.add_input<float>({23.f});
// output_low
test_case.add_input<float>({2.f});
// output_high
test_case.add_input<float>({16.f});
// expected result
test_case.add_expected_output<float>(
data_shape,
vector<float>{2.f, 2.f, 2.f, 2.f, 6.6666669f,
6.6666669f, 6.6666669f, 6.6666669f, 6.6666669f, 6.6666669f,
6.6666669f, 6.6666669f, 11.33333301f, 11.33333301f, 11.33333301f,
11.33333301f, 11.33333301f, 11.33333301f, 11.33333301f, 11.33333301f,
16.f, 16.f, 16.f, 16.f});
test_case.run();
}
NGRAPH_TEST(${BACKEND_NAME}, DISABLED_fake_quantize_with_clip)
{
const Shape data_shape{1, 2, 3, 4};
const size_t levels = 5;
const auto data = make_shared<op::Parameter>(element::f32, data_shape);
const auto input_low = make_shared<op::Parameter>(element::f32, Shape{});
const auto input_high = make_shared<op::Parameter>(element::f32, Shape{});
const auto output_low = make_shared<op::Parameter>(element::f32, Shape{});
const auto output_high = make_shared<op::Parameter>(element::f32, Shape{});
const auto quantize =
make_shared<op::FakeQuantize>(data, input_low, input_high, output_low, output_high, levels);
const auto function = make_shared<Function>(
NodeVector{quantize},
ParameterVector{data, input_low, input_high, output_low, output_high});
auto test_case = test::TestCase<TestEngine>(function);
const size_t n_elements = shape_size(data_shape);
vector<float> input_data(n_elements);
iota(begin(input_data), end(input_data), 0);
test_case.add_input<float>(input_data);
// input_low
test_case.add_input<float>({3.f});
// input_high
test_case.add_input<float>({17.f});
// output_low
test_case.add_input<float>({2.f});
// output_high
test_case.add_input<float>({16.f});
// expected result
test_case.add_expected_output<float>(
data_shape,
vector<float>{2.f, 2.f, 2.f, 2.f, 2.f, 5.5f, 5.5f, 5.5f, 5.5f, 9.f, 9.f, 9.f,
12.5f, 12.5f, 12.5f, 12.5f, 16.f, 16.f, 16.f, 16.f, 16.f, 16.f, 16.f, 16.f});
test_case.run();
}
NGRAPH_TEST(${BACKEND_NAME}, DISABLED_fake_quantize_with_clip_across_channels)
{
Shape data_shape{1, 2, 5, 5};
size_t levels = 5;
auto data = make_shared<op::Parameter>(element::f32, data_shape);
auto input_low = make_shared<op::Parameter>(element::f32, Shape{2, 1, 1});
auto input_high = make_shared<op::Parameter>(element::f32, Shape{2, 1, 1});
auto output_low = make_shared<op::Parameter>(element::f32, Shape{2, 1, 1});
auto output_high = make_shared<op::Parameter>(element::f32, Shape{2, 1, 1});
auto quantize =
make_shared<op::FakeQuantize>(data, input_low, input_high, output_low, output_high, levels);
auto function = make_shared<Function>(
NodeVector{quantize},
ParameterVector{data, input_low, input_high, output_low, output_high});
auto test_case = test::TestCase<TestEngine>(function);
size_t n_elements = shape_size(data_shape);
vector<float> input_data(n_elements);
iota(begin(input_data), end(input_data), 0);
test_case.add_input<float>(input_data);
// input_low
test_case.add_input<float>(vector<float>{5.f, 30.f});
// input_high
test_case.add_input<float>(vector<float>{10.f, 40.f});
// output_low
test_case.add_input<float>(vector<float>{0.f, 50.f});
// output_high
test_case.add_input<float>(vector<float>{20.f, 70.f});
// expected result
test_case.add_expected_output<float>(
data_shape,
vector<float>{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 5.0f, 10.0f, 10.0f, 15.0f,
20.0f, 20.0f, 20.0f, 20.0f, 20.0f, 20.0f, 20.0f, 20.0f, 20.0f, 20.0f,
20.0f, 20.0f, 20.0f, 20.0f, 20.0f, 50.0f, 50.0f, 50.0f, 50.0f, 50.0f,
50.0f, 50.0f, 55.0f, 55.0f, 60.0f, 60.0f, 60.0f, 65.0f, 65.0f, 70.0f,
70.0f, 70.0f, 70.0f, 70.0f, 70.0f, 70.0f, 70.0f, 70.0f, 70.0f, 70.0f});
test_case.run();
}
NGRAPH_TEST(${BACKEND_NAME}, DISABLED_fake_quantize_pdpd)
{
Shape data_shape{1, 2, 5, 5};
size_t levels = 5;
auto data = make_shared<op::Parameter>(element::f32, data_shape);
auto input_low = make_shared<op::Parameter>(element::f32, Shape{2});
auto input_high = make_shared<op::Parameter>(element::f32, Shape{2});
auto output_low = make_shared<op::Parameter>(element::f32, Shape{2});
auto output_high = make_shared<op::Parameter>(element::f32, Shape{2});
auto quantize =
make_shared<op::FakeQuantize>(data,
input_low,
input_high,
output_low,
output_high,
levels,
op::AutoBroadcastSpec(op::AutoBroadcastType::PDPD, 1));
auto function = make_shared<Function>(
NodeVector{quantize},
ParameterVector{data, input_low, input_high, output_low, output_high});
auto test_case = test::TestCase<TestEngine>(function);
size_t n_elements = shape_size(data_shape);
vector<float> input_data(n_elements);
iota(begin(input_data), end(input_data), 0);
test_case.add_input<float>(input_data);
// input_low
test_case.add_input<float>(vector<float>{5.f, 30.f});
// input_high
test_case.add_input<float>(vector<float>{10.f, 40.f});
// output_low
test_case.add_input<float>(vector<float>{0.f, 50.f});
// output_high
test_case.add_input<float>(vector<float>{20.f, 70.f});
// expected result
test_case.add_expected_output<float>(
data_shape,
vector<float>{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 5.0f, 10.0f, 10.0f, 15.0f,
20.0f, 20.0f, 20.0f, 20.0f, 20.0f, 20.0f, 20.0f, 20.0f, 20.0f, 20.0f,
20.0f, 20.0f, 20.0f, 20.0f, 20.0f, 50.0f, 50.0f, 50.0f, 50.0f, 50.0f,
50.0f, 50.0f, 55.0f, 55.0f, 60.0f, 60.0f, 60.0f, 65.0f, 65.0f, 70.0f,
70.0f, 70.0f, 70.0f, 70.0f, 70.0f, 70.0f, 70.0f, 70.0f, 70.0f, 70.0f});
test_case.run();
}
NGRAPH_TEST(${BACKEND_NAME}, depth_to_space_space_to_depth_block_first)
{
auto backend = runtime::Backend::create("${BACKEND_NAME}");
Shape dts_input_shape{2, 32, 2, 4, 2, 4};
size_t block_size = 2;
auto dts_input = make_shared<op::Parameter>(element::f32, dts_input_shape);
auto depth_to_space = make_shared<op::DepthToSpace>(
dts_input, op::DepthToSpace::DepthToSpaceMode::BLOCKS_FIRST, block_size);
auto dts_func = make_shared<Function>(NodeVector{depth_to_space}, ParameterVector{dts_input});
auto dts_input_tensor = backend->create_tensor(element::f32, dts_input_shape);
const auto data_size = shape_size(dts_input_shape);
vector<float> data(data_size);
std::iota(data.begin(), data.end(), 0);
copy_data(dts_input_tensor, data);
const auto dts_output_shape = depth_to_space->get_output_shape(0);
auto dts_output_tensor = backend->create_tensor(element::f32, dts_output_shape);
auto handle = backend->compile(dts_func);
handle->call_with_validate({dts_output_tensor}, {dts_input_tensor});
auto dts_result = read_vector<float>(dts_output_tensor);
// use depth_to_space output as space_to_depth input
auto std_input = make_shared<op::Parameter>(element::f32, dts_output_shape);
auto space_to_depth = make_shared<op::SpaceToDepth>(
std_input, op::SpaceToDepth::SpaceToDepthMode::BLOCKS_FIRST, block_size);
auto std_func = make_shared<Function>(NodeVector{space_to_depth}, ParameterVector{std_input});
auto std_input_tensor = backend->create_tensor(element::f32, dts_output_shape);
copy_data(std_input_tensor, dts_result);
auto std_output_tensor = backend->create_tensor(element::f32, dts_input_shape);
handle = backend->compile(std_func);
handle->call_with_validate({std_output_tensor}, {std_input_tensor});
auto std_result = read_vector<float>(std_output_tensor);
// expected output of space_to_depth is input of depth_to_space
ASSERT_EQ(dts_input_shape, space_to_depth->get_output_shape(0));
EXPECT_TRUE(test::all_close_f(std_result, data, data_size));
}
NGRAPH_TEST(${BACKEND_NAME}, depth_to_space_space_to_depth_depth_first)
{
auto backend = runtime::Backend::create("${BACKEND_NAME}");
Shape dts_input_shape{2, 32, 2, 4, 2, 4};
size_t block_size = 2;
auto dts_input = make_shared<op::Parameter>(element::f32, dts_input_shape);
auto depth_to_space = make_shared<op::DepthToSpace>(
dts_input, op::DepthToSpace::DepthToSpaceMode::DEPTH_FIRST, block_size);
auto dts_func = make_shared<Function>(NodeVector{depth_to_space}, ParameterVector{dts_input});
auto dts_input_tensor = backend->create_tensor(element::f32, dts_input_shape);
const auto data_size = shape_size(dts_input_shape);
vector<float> data(data_size);
std::iota(data.begin(), data.end(), 0);
copy_data(dts_input_tensor, data);
const auto dts_output_shape = depth_to_space->get_output_shape(0);
auto dts_output_tensor = backend->create_tensor(element::f32, dts_output_shape);
auto handle = backend->compile(dts_func);
handle->call_with_validate({dts_output_tensor}, {dts_input_tensor});
auto dts_result = read_vector<float>(dts_output_tensor);
// use depth_to_space output as space_to_depth input
auto std_input = make_shared<op::Parameter>(element::f32, dts_output_shape);
auto space_to_depth = make_shared<op::SpaceToDepth>(
std_input, op::SpaceToDepth::SpaceToDepthMode::DEPTH_FIRST, block_size);
auto std_func = make_shared<Function>(NodeVector{space_to_depth}, ParameterVector{std_input});
auto std_input_tensor = backend->create_tensor(element::f32, dts_output_shape);
copy_data(std_input_tensor, dts_result);
auto std_output_tensor = backend->create_tensor(element::f32, dts_input_shape);
handle = backend->compile(std_func);
handle->call_with_validate({std_output_tensor}, {std_input_tensor});
auto std_result = read_vector<float>(std_output_tensor);
// expected output of space_to_depth is input of depth_to_space
ASSERT_EQ(dts_input_shape, space_to_depth->get_output_shape(0));
EXPECT_TRUE(test::all_close_f(std_result, data, data_size));
}
|
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/topological_sort.hpp>
#include <boost/range.hpp>
#include <boost/range/adaptor/indexed.hpp>
#include <deque>
#include <iostream>
#include <list>
#include <string>
#include <type_traits>
#include <vector>
// From the docs, An adjacency_list has the following generic parameters:
// * OutEdgeList: The selector for the container used to
// represent the edge-list for each of the vertices. vecS
// * VertexList: The selector for the container used to represent
// the vertex-list of the graph. vecS
// * Directed: A selector to choose whether the graph is directed,
// undirected, or directed with bidirectional edge access
// (access to both out-edges and in-edges). The options are directedS,
// undirectedS, and bidirectionalS. directedS
// * VertexProperties: for specifying internal property storage. no_property
// * EdgeProperties: for specifying internal property storage. no_property
// * GraphProperties: for specifying property storage for the graph object. no_property
// * EdgeList: The selector for the container used to represent the edge-list for the graph.
namespace boost{
enum vertex_compile_cost_t {vertex_compile_cost = 111}; // a unique #
BOOST_INSTALL_PROPERTY(vertex, compile_cost);
}
using graph_type = boost::adjacency_list<
boost::listS, // by using a list,
// we get linear removal time!,
// but vertices are not int's any more.
boost::listS,
boost::directedS,
// Vertex properties:
boost::property<boost::vertex_name_t, std::string,
boost::property<boost::vertex_compile_cost_t, float,
boost::property<boost::vertex_distance_t, float,
boost::property<boost::vertex_color_t, boost::default_color_type> > > >,
boost::property<boost::edge_weight_t, float>
>;
using name_map_t = boost::property_map<graph_type, boost::vertex_name_t>::type;
using compile_cost_map_t = boost::property_map<graph_type, boost::vertex_compile_cost_t>::type;
using distance_map_t = boost::property_map<graph_type, boost::vertex_distance_t>::type;
using color_map_t = boost::property_map<graph_type, boost::vertex_color_t>::type;
int main()
{
graph_type g;
name_map_t name_map = get(boost::vertex_name, g);
compile_cost_map_t compile_cost_map = get(boost::vertex_compile_cost, g);
// -> get the property through compile_cost_map[vertex_element]
// -> there is a set method to set the vertex/edge...
return 0;
}
|
/*
* Copyright (C) 2004-2018 ZNC, see the NOTICE file for details.
*
* 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 <znc/znc.h>
#include <signal.h>
#include <time.h>
#include <thread>
#if defined(HAVE_LIBSSL) && defined(HAVE_PTHREAD) && \
(!defined(OPENSSL_VERSION_NUMBER) || OPENSSL_VERSION_NUMBER < 0x10100004)
/* Starting with version 1.1.0-pre4, OpenSSL has a new threading implementation
that doesn't need locking callbacks.
"OpenSSL now uses a new threading API. It is no longer necessary to set
locking callbacks to use OpenSSL in a multi-threaded environment. There are
two supported threading models: pthreads and windows threads. It is also
possible to configure OpenSSL at compile time for "no-threads". The old
threading API should no longer be used. The functions have been replaced
with "no-op" compatibility macros."
See openssl/openssl@2e52e7df518d80188c865ea3f7bb3526d14b0c08. */
#include <znc/Threads.h>
#include <openssl/crypto.h>
#include <memory>
static std::vector<std::unique_ptr<CMutex>> lock_cs;
static void locking_callback(int mode, int type, const char* file, int line) {
if (mode & CRYPTO_LOCK) {
lock_cs[type]->lock();
} else {
lock_cs[type]->unlock();
}
}
static unsigned long thread_id_callback() {
return (unsigned long)pthread_self();
}
static CRYPTO_dynlock_value* dyn_create_callback(const char* file, int line) {
return (CRYPTO_dynlock_value*)new CMutex;
}
static void dyn_lock_callback(int mode, CRYPTO_dynlock_value* dlock,
const char* file, int line) {
CMutex* mtx = (CMutex*)dlock;
if (mode & CRYPTO_LOCK) {
mtx->lock();
} else {
mtx->unlock();
}
}
static void dyn_destroy_callback(CRYPTO_dynlock_value* dlock, const char* file,
int line) {
CMutex* mtx = (CMutex*)dlock;
delete mtx;
}
static void thread_setup() {
lock_cs.resize(CRYPTO_num_locks());
for (std::unique_ptr<CMutex>& mtx : lock_cs)
mtx = std::unique_ptr<CMutex>(new CMutex());
CRYPTO_set_id_callback(&thread_id_callback);
CRYPTO_set_locking_callback(&locking_callback);
CRYPTO_set_dynlock_create_callback(&dyn_create_callback);
CRYPTO_set_dynlock_lock_callback(&dyn_lock_callback);
CRYPTO_set_dynlock_destroy_callback(&dyn_destroy_callback);
}
#else
#define thread_setup()
#endif
using std::cout;
using std::endl;
using std::set;
#ifdef HAVE_GETOPT_LONG
#include <getopt.h>
#else
#define no_argument 0
#define required_argument 1
#define optional_argument 2
struct option {
const char* a;
int opt;
int* flag;
int val;
};
static inline int getopt_long(int argc, char* const argv[],
const char* optstring, const struct option*,
int*) {
return getopt(argc, argv, optstring);
}
#endif
static const struct option g_LongOpts[] = {
{"help", no_argument, nullptr, 'h'},
{"version", no_argument, nullptr, 'v'},
{"debug", no_argument, nullptr, 'D'},
{"foreground", no_argument, nullptr, 'f'},
{"no-color", no_argument, nullptr, 'n'},
{"allow-root", no_argument, nullptr, 'r'},
{"makeconf", no_argument, nullptr, 'c'},
{"makepass", no_argument, nullptr, 's'},
{"makepem", no_argument, nullptr, 'p'},
{"datadir", required_argument, nullptr, 'd'},
{nullptr, 0, nullptr, 0}};
static void GenerateHelp(const char* appname) {
CUtils::PrintMessage("USAGE: " + CString(appname) + " [options]");
CUtils::PrintMessage("Options are:");
CUtils::PrintMessage(
"\t-h, --help List available command line options (this page)");
CUtils::PrintMessage(
"\t-v, --version Output version information and exit");
CUtils::PrintMessage(
"\t-c, --makeconf Interactively create a new config");
CUtils::PrintMessage(
"\t-d, --datadir Set a different ZNC repository (default is "
"~/.znc)");
CUtils::PrintMessage(
"\t-D, --debug Output debugging information (Implies -f)");
CUtils::PrintMessage("\t-f, --foreground Don't fork into the background");
CUtils::PrintMessage(
"\t-n, --no-color Don't use escape sequences in the output");
#ifdef HAVE_LIBSSL
CUtils::PrintMessage(
"\t-p, --makepem Generates a pemfile for use with SSL");
#endif /* HAVE_LIBSSL */
CUtils::PrintMessage(
"\t-r, --allow-root Don't complain if ZNC is run as root");
CUtils::PrintMessage(
"\t-s, --makepass Generates a password for use in config");
}
class CSignalHandler {
public:
CSignalHandler(CZNC* pZNC) {
if (pipe(m_iPipe)) {
DEBUG("Ouch, can't open pipe for signal handler: "
<< strerror(errno));
exit(1);
}
pZNC->GetManager().MonitorFD(new CSignalHandlerMonitorFD(m_iPipe[0]));
sigset_t signals;
sigfillset(&signals);
pthread_sigmask(SIG_SETMASK, &signals, nullptr);
m_thread = std::thread([=]() { HandleSignals(pZNC); });
}
~CSignalHandler() {
pthread_cancel(m_thread.native_handle());
m_thread.join();
}
private:
class CSignalHandlerMonitorFD : public CSMonitorFD {
// This class just prevents the pipe buffer from filling by clearing it
public:
CSignalHandlerMonitorFD(int fd) { Add(fd, CSockManager::ECT_Read); }
bool FDsThatTriggered(
const std::map<int, short>& miiReadyFds) override {
for (const auto& it : miiReadyFds) {
if (it.second) {
int sig;
read(it.first, &sig, sizeof(sig));
}
}
return true;
}
};
void HandleSignals(CZNC* pZNC) {
sigset_t signals;
sigemptyset(&signals);
sigaddset(&signals, SIGHUP);
sigaddset(&signals, SIGUSR1);
sigaddset(&signals, SIGINT);
sigaddset(&signals, SIGQUIT);
sigaddset(&signals, SIGTERM);
sigaddset(&signals, SIGPIPE);
sigaddset(&signals, SIGSEGV);
// Handle only these signals specially; the rest will have their default
// action, but in this thread
pthread_sigmask(SIG_SETMASK, &signals, nullptr);
while (true) {
int sig;
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, nullptr);
// This thread can be cancelled, but only during this function.
// Such cancel will be the only way to finish this thread.
if (sigwait(&signals, &sig) == -1) continue;
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, nullptr);
// TODO probably move switch() to CSignalHandlerMonitorFD?
switch (sig) {
case SIGHUP:
pZNC->SetConfigState(CZNC::ECONFIG_NEED_REHASH);
break;
case SIGUSR1:
pZNC->SetConfigState(CZNC::ECONFIG_NEED_VERBOSE_WRITE);
break;
case SIGINT:
case SIGQUIT:
case SIGTERM:
pZNC->SetConfigState(CZNC::ECONFIG_NEED_QUIT);
// Reset handler to default by:
// * not blocking it
// * not waiting for it
// So, if ^C is pressed, but for some reason it didn't work,
// second ^C will kill the process for sure.
sigdelset(&signals, sig);
pthread_sigmask(SIG_SETMASK, &signals, nullptr);
break;
case SIGPIPE:
case SIGSEGV:
kill(0, SIGSTOP);
break;
default:
break;
}
// This write() must succeed because POSIX guarantees that writes of
// less than PIPE_BUF are atomic (and PIPE_BUF is at least 512).
size_t w = write(m_iPipe[1], &sig, sizeof(sig));
if (w != sizeof(sig)) {
DEBUG(
"Something bad happened during write() to a pipe for "
"signal handler, wrote "
<< w << " bytes: " << strerror(errno));
exit(1);
}
}
}
std::thread m_thread;
// pipe for waking up the main thread
int m_iPipe[2];
};
static bool isRoot() {
// User root? If one of these were root, we could switch the others to root,
// too
return (geteuid() == 0 || getuid() == 0);
}
static void seedPRNG() {
struct timeval tv;
unsigned int seed;
// Try to find a seed which can't be as easily guessed as only time()
if (gettimeofday(&tv, nullptr) == 0) {
seed = (unsigned int)tv.tv_sec;
// This is in [0:1e6], which means that roughly 20 bits are
// actually used, let's try to shuffle the high bits.
seed ^= uint32_t((tv.tv_usec << 10) | tv.tv_usec);
} else
seed = (unsigned int)time(nullptr);
seed ^= rand();
seed ^= getpid();
srand(seed);
}
int main(int argc, char** argv) {
CString sConfig;
CString sDataDir = "";
thread_setup();
seedPRNG();
CDebug::SetStdoutIsTTY(isatty(1));
int iArg, iOptIndex = -1;
bool bMakeConf = false;
bool bMakePass = false;
bool bAllowRoot = false;
bool bForeground = false;
#ifdef ALWAYS_RUN_IN_FOREGROUND
bForeground = true;
#endif
#ifdef HAVE_LIBSSL
bool bMakePem = false;
#endif
CZNC::CreateInstance();
while ((iArg = getopt_long(argc, argv, "hvnrcspd:Df", g_LongOpts,
&iOptIndex)) != -1) {
switch (iArg) {
case 'h':
GenerateHelp(argv[0]);
return 0;
case 'v':
cout << CZNC::GetTag() << endl;
cout << CZNC::GetCompileOptionsString() << endl;
return 0;
case 'n':
CDebug::SetStdoutIsTTY(false);
break;
case 'r':
bAllowRoot = true;
break;
case 'c':
bMakeConf = true;
break;
case 's':
bMakePass = true;
break;
case 'p':
#ifdef HAVE_LIBSSL
bMakePem = true;
break;
#else
CUtils::PrintError("ZNC is compiled without SSL support.");
return 1;
#endif /* HAVE_LIBSSL */
case 'd':
sDataDir = CString(optarg);
break;
case 'f':
bForeground = true;
break;
case 'D':
bForeground = true;
CDebug::SetDebug(true);
break;
case '?':
default:
GenerateHelp(argv[0]);
return 1;
}
}
if (optind < argc) {
CUtils::PrintError("Unrecognized command line arguments.");
CUtils::PrintError("Did you mean to run `/znc " +
CString(argv[optind]) + "' in IRC client instead?");
CUtils::PrintError("Hint: `/znc " + CString(argv[optind]) +
"' is an alias for `/msg *status " +
CString(argv[optind]) + "'");
return 1;
}
CZNC* pZNC = &CZNC::Get();
pZNC->InitDirs(((argc) ? argv[0] : ""), sDataDir);
#ifdef HAVE_LIBSSL
if (bMakePem) {
pZNC->WritePemFile();
CZNC::DestroyInstance();
return 0;
}
#endif /* HAVE_LIBSSL */
if (bMakePass) {
CString sSalt;
CUtils::PrintMessage("Type your new password.");
CString sHash = CUtils::GetSaltedHashPass(sSalt);
CUtils::PrintMessage("Kill ZNC process, if it's running.");
CUtils::PrintMessage(
"Then replace password in the <User> section of your config with "
"this:");
// Not PrintMessage(), to remove [**] from the beginning, to ease
// copypasting
std::cout << "<Pass password>" << std::endl;
std::cout << "\tMethod = " << CUtils::sDefaultHash << std::endl;
std::cout << "\tHash = " << sHash << std::endl;
std::cout << "\tSalt = " << sSalt << std::endl;
std::cout << "</Pass>" << std::endl;
CUtils::PrintMessage(
"After that start ZNC again, and you should be able to login with "
"the new password.");
CZNC::DestroyInstance();
return 0;
}
{
set<CModInfo> ssGlobalMods;
set<CModInfo> ssUserMods;
set<CModInfo> ssNetworkMods;
CUtils::PrintAction("Checking for list of available modules");
pZNC->GetModules().GetAvailableMods(ssGlobalMods,
CModInfo::GlobalModule);
pZNC->GetModules().GetAvailableMods(ssUserMods, CModInfo::UserModule);
pZNC->GetModules().GetAvailableMods(ssNetworkMods,
CModInfo::NetworkModule);
if (ssGlobalMods.empty() && ssUserMods.empty() &&
ssNetworkMods.empty()) {
CUtils::PrintStatus(false, "");
CUtils::PrintError(
"No modules found. Perhaps you didn't install ZNC properly?");
CUtils::PrintError(
"Read https://wiki.znc.in/Installation for instructions.");
if (!CUtils::GetBoolInput(
"Do you really want to run ZNC without any modules?",
false)) {
CZNC::DestroyInstance();
return 1;
}
}
CUtils::PrintStatus(true, "");
}
if (isRoot()) {
CUtils::PrintError(
"You are running ZNC as root! Don't do that! There are not many "
"valid");
CUtils::PrintError(
"reasons for this and it can, in theory, cause great damage!");
if (!bAllowRoot) {
CZNC::DestroyInstance();
return 1;
}
CUtils::PrintError("You have been warned.");
CUtils::PrintError(
"Hit CTRL+C now if you don't want to run ZNC as root.");
CUtils::PrintError("ZNC will start in 30 seconds.");
sleep(30);
}
if (bMakeConf) {
if (!pZNC->WriteNewConfig(sConfig)) {
CZNC::DestroyInstance();
return 0;
}
/* Fall through to normal bootup */
}
CString sConfigError;
if (!pZNC->ParseConfig(sConfig, sConfigError)) {
CUtils::PrintError("Unrecoverable config error.");
CZNC::DestroyInstance();
return 1;
}
if (!pZNC->OnBoot()) {
CUtils::PrintError("Exiting due to module boot errors.");
CZNC::DestroyInstance();
return 1;
}
if (bForeground) {
int iPid = getpid();
CUtils::PrintMessage("Staying open for debugging [pid: " +
CString(iPid) + "]");
pZNC->WritePidFile(iPid);
CUtils::PrintMessage(CZNC::GetTag());
} else {
CUtils::PrintAction("Forking into the background");
int iPid = fork();
if (iPid == -1) {
CUtils::PrintStatus(false, strerror(errno));
CZNC::DestroyInstance();
return 1;
}
if (iPid > 0) {
// We are the parent. We are done and will go to bed.
CUtils::PrintStatus(true, "[pid: " + CString(iPid) + "]");
pZNC->WritePidFile(iPid);
CUtils::PrintMessage(CZNC::GetTag());
/* Don't destroy pZNC here or it will delete the pid file. */
return 0;
}
/* fcntl() locks don't necessarily propagate to forked()
* children. Reacquire the lock here. Use the blocking
* call to avoid race condition with parent exiting.
*/
if (!pZNC->WaitForChildLock()) {
CUtils::PrintError(
"Child was unable to obtain lock on config file.");
CZNC::DestroyInstance();
return 1;
}
// Redirect std in/out/err to /dev/null
close(0);
open("/dev/null", O_RDONLY);
close(1);
open("/dev/null", O_WRONLY);
close(2);
open("/dev/null", O_WRONLY);
CDebug::SetStdoutIsTTY(false);
// We are the child. There is no way we can be a process group
// leader, thus setsid() must succeed.
setsid();
// Now we are in our own process group and session (no
// controlling terminal). We are independent!
}
// Handle all signals in separate thread
std::unique_ptr<CSignalHandler> SignalHandler(new CSignalHandler(pZNC));
int iRet = 0;
try {
pZNC->Loop();
} catch (const CException& e) {
switch (e.GetType()) {
case CException::EX_Shutdown:
iRet = 0;
break;
case CException::EX_Restart: {
// strdup() because GCC is stupid
char* args[] = {
strdup(argv[0]), strdup("--datadir"),
strdup(pZNC->GetZNCPath().c_str()), nullptr,
nullptr, nullptr,
nullptr};
int pos = 3;
if (CDebug::Debug())
args[pos++] = strdup("--debug");
else if (bForeground)
args[pos++] = strdup("--foreground");
if (!CDebug::StdoutIsTTY()) args[pos++] = strdup("--no-color");
if (bAllowRoot) args[pos++] = strdup("--allow-root");
// The above code adds 3 entries to args tops
// which means the array should be big enough
SignalHandler.reset();
CZNC::DestroyInstance();
execvp(args[0], args);
CUtils::PrintError("Unable to restart ZNC [" +
CString(strerror(errno)) + "]");
} /* Fall through */
default:
iRet = 1;
}
}
SignalHandler.reset();
CZNC::DestroyInstance();
CUtils::PrintMessage("Exiting");
return iRet;
}
|
/*
Copyright (C) 2003-2014 by David White <davewx7@gmail.com>
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 acknowledgement 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.
*/
#pragma once
#include <boost/tuple/tuple.hpp>
#include <deque>
#include <list>
#include "formula_callable.hpp"
#include "shared_memory_pipe.hpp"
#include "tbs_server_base.hpp"
#include "variant.hpp"
namespace tbs
{
struct internal_server_manager {
explicit internal_server_manager(bool use_internal_server);
~internal_server_manager();
};
//create a server in an external process and return the port
int spawn_server_on_localhost(SharedMemoryPipePtr* ipc_pipe);
//if there is a server in an external process available return
//the port, otherwise return 0.
int get_server_on_localhost(SharedMemoryPipePtr* ipc_pipe);
class internal_server : public server_base
{
public:
internal_server();
virtual ~internal_server();
void handle_process();
static void send_request(const variant& request,
int session_id,
game_logic::MapFormulaCallablePtr callable,
std::function<void(const std::string&)> handler);
static void process();
static boost::asio::io_service& get_io_service() { return io_service_; }
static int requests_in_flight(int session_id);
protected:
virtual void heartbeat_internal(int send_heartbeat, std::map<int, client_info>& clients) override;
private:
int connection_timeout_ticks() const override;
void send_msg(const variant& resp,
int session_id,
std::function<void(const std::string&)> handler,
game_logic::MapFormulaCallablePtr callable);
static boost::asio::io_service io_service_;
void write_queue(send_function send_fn, const variant& v, int session_id);
bool read_queue(send_function* send_fn, variant* v, int *session_id);
void finish_socket(send_function send_fn, client_info& cli_info);
socket_info& create_socket_info(send_function send_fn);
void disconnect(int session_id);
void queue_msg(int session_id, const std::string& msg, bool has_priority) override;
std::list<std::pair<send_function, socket_info> > connections_;
std::deque<boost::tuple<send_function,variant,int> > msg_queue_;
};
typedef std::shared_ptr<internal_server> internal_server_ptr;
}
|
// boost\math\distributions\binomial.hpp
// Copyright John Maddock 2006.
// Copyright Paul A. Bristow 2007.
// Use, modification and distribution are subject to 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)
// http://en.wikipedia.org/wiki/binomial_distribution
// Binomial distribution is the discrete probability distribution of
// the number (k) of successes, in a sequence of
// n independent (yes or no, success or failure) Bernoulli trials.
// It expresses the probability of a number of events occurring in a fixed time
// if these events occur with a known average rate (probability of success),
// and are independent of the time since the last event.
// The number of cars that pass through a certain point on a road during a given period of time.
// The number of spelling mistakes a secretary makes while typing a single page.
// The number of phone calls at a call center per minute.
// The number of times a web server is accessed per minute.
// The number of light bulbs that burn out in a certain amount of time.
// The number of roadkill found per unit length of road
// http://en.wikipedia.org/wiki/binomial_distribution
// Given a sample of N measured values k[i],
// we wish to estimate the value of the parameter x (mean)
// of the binomial population from which the sample was drawn.
// To calculate the maximum likelihood value = 1/N sum i = 1 to N of k[i]
// Also may want a function for EXACTLY k.
// And probability that there are EXACTLY k occurrences is
// exp(-x) * pow(x, k) / factorial(k)
// where x is expected occurrences (mean) during the given interval.
// For example, if events occur, on average, every 4 min,
// and we are interested in number of events occurring in 10 min,
// then x = 10/4 = 2.5
// http://www.itl.nist.gov/div898/handbook/eda/section3/eda366i.htm
// The binomial distribution is used when there are
// exactly two mutually exclusive outcomes of a trial.
// These outcomes are appropriately labeled "success" and "failure".
// The binomial distribution is used to obtain
// the probability of observing x successes in N trials,
// with the probability of success on a single trial denoted by p.
// The binomial distribution assumes that p is fixed for all trials.
// P(x, p, n) = n!/(x! * (n-x)!) * p^x * (1-p)^(n-x)
// http://mathworld.wolfram.com/BinomialCoefficient.html
// The binomial coefficient (n; k) is the number of ways of picking
// k unordered outcomes from n possibilities,
// also known as a combination or combinatorial number.
// The symbols _nC_k and (n; k) are used to denote a binomial coefficient,
// and are sometimes read as "n choose k."
// (n; k) therefore gives the number of k-subsets possible out of a set of n distinct items.
// For example:
// The 2-subsets of {1,2,3,4} are the six pairs {1,2}, {1,3}, {1,4}, {2,3}, {2,4}, and {3,4}, so (4; 2)==6.
// http://functions.wolfram.com/GammaBetaErf/Binomial/ for evaluation.
// But note that the binomial distribution
// (like others including the poisson, negative binomial & Bernoulli)
// is strictly defined as a discrete function: only integral values of k are envisaged.
// However because of the method of calculation using a continuous gamma function,
// it is convenient to treat it as if a continous function,
// and permit non-integral values of k.
// To enforce the strict mathematical model, users should use floor or ceil functions
// on k outside this function to ensure that k is integral.
#ifndef BOOST_MATH_SPECIAL_BINOMIAL_HPP
#define BOOST_MATH_SPECIAL_BINOMIAL_HPP
#include <boost/math/distributions/fwd.hpp>
#include <boost/math/special_functions/beta.hpp> // for incomplete beta.
#include <boost/math/distributions/complement.hpp> // complements
#include <boost/math/distributions/detail/common_error_handling.hpp> // error checks
#include <boost/math/distributions/detail/inv_discrete_quantile.hpp> // error checks
#include <boost/math/special_functions/fpclassify.hpp> // isnan.
#include <boost/math/tools/roots.hpp> // for root finding.
#include <utility>
namespace boost
{
namespace math
{
template <class RealType, class Policy>
class binomial_distribution;
namespace binomial_detail{
// common error checking routines for binomial distribution functions:
template <class RealType, class Policy>
inline bool check_N(const char* function, const RealType& N, RealType* result, const Policy& pol)
{
if((N < 0) || !(boost::math::isfinite)(N))
{
*result = policies::raise_domain_error<RealType>(
function,
"Number of Trials argument is %1%, but must be >= 0 !", N, pol);
return false;
}
return true;
}
template <class RealType, class Policy>
inline bool check_success_fraction(const char* function, const RealType& p, RealType* result, const Policy& pol)
{
if((p < 0) || (p > 1) || !(boost::math::isfinite)(p))
{
*result = policies::raise_domain_error<RealType>(
function,
"Success fraction argument is %1%, but must be >= 0 and <= 1 !", p, pol);
return false;
}
return true;
}
template <class RealType, class Policy>
inline bool check_dist(const char* function, const RealType& N, const RealType& p, RealType* result, const Policy& pol)
{
return check_success_fraction(
function, p, result, pol)
&& check_N(
function, N, result, pol);
}
template <class RealType, class Policy>
inline bool check_dist_and_k(const char* function, const RealType& N, const RealType& p, RealType k, RealType* result, const Policy& pol)
{
if(check_dist(function, N, p, result, pol) == false)
return false;
if((k < 0) || !(boost::math::isfinite)(k))
{
*result = policies::raise_domain_error<RealType>(
function,
"Number of Successes argument is %1%, but must be >= 0 !", k, pol);
return false;
}
if(k > N)
{
*result = policies::raise_domain_error<RealType>(
function,
"Number of Successes argument is %1%, but must be <= Number of Trials !", k, pol);
return false;
}
return true;
}
template <class RealType, class Policy>
inline bool check_dist_and_prob(const char* function, const RealType& N, RealType p, RealType prob, RealType* result, const Policy& pol)
{
if(check_dist(function, N, p, result, pol) && detail::check_probability(function, prob, result, pol) == false)
return false;
return true;
}
template <class T, class Policy>
T inverse_binomial_cornish_fisher(T n, T sf, T p, T q, const Policy& pol)
{
BOOST_MATH_STD_USING
// mean:
T m = n * sf;
// standard deviation:
T sigma = sqrt(n * sf * (1 - sf));
// skewness
T sk = (1 - 2 * sf) / sigma;
// kurtosis:
// T k = (1 - 6 * sf * (1 - sf) ) / (n * sf * (1 - sf));
// Get the inverse of a std normal distribution:
T x = boost::math::erfc_inv(p > q ? 2 * q : 2 * p, pol) * constants::root_two<T>();
// Set the sign:
if(p < 0.5)
x = -x;
T x2 = x * x;
// w is correction term due to skewness
T w = x + sk * (x2 - 1) / 6;
/*
// Add on correction due to kurtosis.
// Disabled for now, seems to make things worse?
//
if(n >= 10)
w += k * x * (x2 - 3) / 24 + sk * sk * x * (2 * x2 - 5) / -36;
*/
w = m + sigma * w;
if(w < tools::min_value<T>())
return sqrt(tools::min_value<T>());
if(w > n)
return n;
return w;
}
template <class RealType, class Policy>
RealType quantile_imp(const binomial_distribution<RealType, Policy>& dist, const RealType& p, const RealType& q)
{ // Quantile or Percent Point Binomial function.
// Return the number of expected successes k,
// for a given probability p.
//
// Error checks:
BOOST_MATH_STD_USING // ADL of std names
RealType result;
RealType trials = dist.trials();
RealType success_fraction = dist.success_fraction();
if(false == binomial_detail::check_dist_and_prob(
"boost::math::quantile(binomial_distribution<%1%> const&, %1%)",
trials,
success_fraction,
p,
&result, Policy()))
{
return result;
}
// Special cases:
//
if(p == 0)
{ // There may actually be no answer to this question,
// since the probability of zero successes may be non-zero,
// but zero is the best we can do:
return 0;
}
if(p == 1)
{ // Probability of n or fewer successes is always one,
// so n is the most sensible answer here:
return trials;
}
if (p <= pow(1 - success_fraction, trials))
{ // p <= pdf(dist, 0) == cdf(dist, 0)
return 0; // So the only reasonable result is zero.
} // And root finder would fail otherwise.
// Solve for quantile numerically:
//
RealType guess = binomial_detail::inverse_binomial_cornish_fisher(trials, success_fraction, p, q, Policy());
RealType factor = 8;
if(trials > 100)
factor = 1.01f; // guess is pretty accurate
else if((trials > 10) && (trials - 1 > guess) && (guess > 3))
factor = 1.15f; // less accurate but OK.
else if(trials < 10)
{
// pretty inaccurate guess in this area:
if(guess > trials / 64)
{
guess = trials / 4;
factor = 2;
}
else
guess = trials / 1024;
}
else
factor = 2; // trials largish, but in far tails.
typedef typename Policy::discrete_quantile_type discrete_quantile_type;
boost::uintmax_t max_iter = policies::get_max_root_iterations<Policy>();
return detail::inverse_discrete_quantile(
dist,
p,
q,
guess,
factor,
RealType(1),
discrete_quantile_type(),
max_iter);
} // quantile
}
template <class RealType = double, class Policy = policies::policy<> >
class binomial_distribution
{
public:
typedef RealType value_type;
typedef Policy policy_type;
binomial_distribution(RealType n = 1, RealType p = 0.5) : m_n(n), m_p(p)
{ // Default n = 1 is the Bernoulli distribution
// with equal probability of 'heads' or 'tails.
RealType r;
binomial_detail::check_dist(
"boost::math::binomial_distribution<%1%>::binomial_distribution",
m_n,
m_p,
&r, Policy());
} // binomial_distribution constructor.
RealType success_fraction() const
{ // Probability.
return m_p;
}
RealType trials() const
{ // Total number of trials.
return m_n;
}
enum interval_type{
clopper_pearson_exact_interval,
jeffreys_prior_interval
};
//
// Estimation of the success fraction parameter.
// The best estimate is actually simply successes/trials,
// these functions are used
// to obtain confidence intervals for the success fraction.
//
static RealType find_lower_bound_on_p(
RealType trials,
RealType successes,
RealType probability,
interval_type t = clopper_pearson_exact_interval)
{
static const char* function = "boost::math::binomial_distribution<%1%>::find_lower_bound_on_p";
// Error checks:
RealType result;
if(false == binomial_detail::check_dist_and_k(
function, trials, RealType(0), successes, &result, Policy())
&&
binomial_detail::check_dist_and_prob(
function, trials, RealType(0), probability, &result, Policy()))
{ return result; }
if(successes == 0)
return 0;
// NOTE!!! The Clopper Pearson formula uses "successes" not
// "successes+1" as usual to get the lower bound,
// see http://www.itl.nist.gov/div898/handbook/prc/section2/prc241.htm
return (t == clopper_pearson_exact_interval) ? ibeta_inv(successes, trials - successes + 1, probability, static_cast<RealType*>(0), Policy())
: ibeta_inv(successes + 0.5f, trials - successes + 0.5f, probability, static_cast<RealType*>(0), Policy());
}
static RealType find_upper_bound_on_p(
RealType trials,
RealType successes,
RealType probability,
interval_type t = clopper_pearson_exact_interval)
{
static const char* function = "boost::math::binomial_distribution<%1%>::find_upper_bound_on_p";
// Error checks:
RealType result;
if(false == binomial_detail::check_dist_and_k(
function, trials, RealType(0), successes, &result, Policy())
&&
binomial_detail::check_dist_and_prob(
function, trials, RealType(0), probability, &result, Policy()))
{ return result; }
if(trials == successes)
return 1;
return (t == clopper_pearson_exact_interval) ? ibetac_inv(successes + 1, trials - successes, probability, static_cast<RealType*>(0), Policy())
: ibetac_inv(successes + 0.5f, trials - successes + 0.5f, probability, static_cast<RealType*>(0), Policy());
}
// Estimate number of trials parameter:
//
// "How many trials do I need to be P% sure of seeing k events?"
// or
// "How many trials can I have to be P% sure of seeing fewer than k events?"
//
static RealType find_minimum_number_of_trials(
RealType k, // number of events
RealType p, // success fraction
RealType alpha) // risk level
{
static const char* function = "boost::math::binomial_distribution<%1%>::find_minimum_number_of_trials";
// Error checks:
RealType result;
if(false == binomial_detail::check_dist_and_k(
function, k, p, k, &result, Policy())
&&
binomial_detail::check_dist_and_prob(
function, k, p, alpha, &result, Policy()))
{ return result; }
result = ibetac_invb(k + 1, p, alpha, Policy()); // returns n - k
return result + k;
}
static RealType find_maximum_number_of_trials(
RealType k, // number of events
RealType p, // success fraction
RealType alpha) // risk level
{
static const char* function = "boost::math::binomial_distribution<%1%>::find_maximum_number_of_trials";
// Error checks:
RealType result;
if(false == binomial_detail::check_dist_and_k(
function, k, p, k, &result, Policy())
&&
binomial_detail::check_dist_and_prob(
function, k, p, alpha, &result, Policy()))
{ return result; }
result = ibeta_invb(k + 1, p, alpha, Policy()); // returns n - k
return result + k;
}
private:
RealType m_n; // Not sure if this shouldn't be an int?
RealType m_p; // success_fraction
}; // template <class RealType, class Policy> class binomial_distribution
typedef binomial_distribution<> binomial;
// typedef binomial_distribution<double> binomial;
// IS now included since no longer a name clash with function binomial.
//typedef binomial_distribution<double> binomial; // Reserved name of type double.
template <class RealType, class Policy>
const std::pair<RealType, RealType> range(const binomial_distribution<RealType, Policy>& dist)
{ // Range of permissible values for random variable k.
using boost::math::tools::max_value;
return std::pair<RealType, RealType>(static_cast<RealType>(0), dist.trials());
}
template <class RealType, class Policy>
const std::pair<RealType, RealType> support(const binomial_distribution<RealType, Policy>& dist)
{ // Range of supported values for random variable k.
// This is range where cdf rises from 0 to 1, and outside it, the pdf is zero.
return std::pair<RealType, RealType>(static_cast<RealType>(0), dist.trials());
}
template <class RealType, class Policy>
inline RealType mean(const binomial_distribution<RealType, Policy>& dist)
{ // Mean of Binomial distribution = np.
return dist.trials() * dist.success_fraction();
} // mean
template <class RealType, class Policy>
inline RealType variance(const binomial_distribution<RealType, Policy>& dist)
{ // Variance of Binomial distribution = np(1-p).
return dist.trials() * dist.success_fraction() * (1 - dist.success_fraction());
} // variance
template <class RealType, class Policy>
RealType pdf(const binomial_distribution<RealType, Policy>& dist, const RealType& k)
{ // Probability Density/Mass Function.
BOOST_FPU_EXCEPTION_GUARD
BOOST_MATH_STD_USING // for ADL of std functions
RealType n = dist.trials();
// Error check:
RealType result;
if(false == binomial_detail::check_dist_and_k(
"boost::math::pdf(binomial_distribution<%1%> const&, %1%)",
n,
dist.success_fraction(),
k,
&result, Policy()))
{
return result;
}
// Special cases of success_fraction, regardless of k successes and regardless of n trials.
if (dist.success_fraction() == 0)
{ // probability of zero successes is 1:
return static_cast<RealType>(k == 0 ? 1 : 0);
}
if (dist.success_fraction() == 1)
{ // probability of n successes is 1:
return static_cast<RealType>(k == n ? 1 : 0);
}
// k argument may be integral, signed, or unsigned, or floating point.
// If necessary, it has already been promoted from an integral type.
if (n == 0)
{
return 1; // Probability = 1 = certainty.
}
if (k == 0)
{ // binomial coeffic (n 0) = 1,
// n ^ 0 = 1
return pow(1 - dist.success_fraction(), n);
}
if (k == n)
{ // binomial coeffic (n n) = 1,
// n ^ 0 = 1
return pow(dist.success_fraction(), k); // * pow((1 - dist.success_fraction()), (n - k)) = 1
}
// Probability of getting exactly k successes
// if C(n, k) is the binomial coefficient then:
//
// f(k; n,p) = C(n, k) * p^k * (1-p)^(n-k)
// = (n!/(k!(n-k)!)) * p^k * (1-p)^(n-k)
// = (tgamma(n+1) / (tgamma(k+1)*tgamma(n-k+1))) * p^k * (1-p)^(n-k)
// = p^k (1-p)^(n-k) / (beta(k+1, n-k+1) * (n+1))
// = ibeta_derivative(k+1, n-k+1, p) / (n+1)
//
using boost::math::ibeta_derivative; // a, b, x
return ibeta_derivative(k+1, n-k+1, dist.success_fraction(), Policy()) / (n+1);
} // pdf
template <class RealType, class Policy>
inline RealType cdf(const binomial_distribution<RealType, Policy>& dist, const RealType& k)
{ // Cumulative Distribution Function Binomial.
// The random variate k is the number of successes in n trials.
// k argument may be integral, signed, or unsigned, or floating point.
// If necessary, it has already been promoted from an integral type.
// Returns the sum of the terms 0 through k of the Binomial Probability Density/Mass:
//
// i=k
// -- ( n ) i n-i
// > | | p (1-p)
// -- ( i )
// i=0
// The terms are not summed directly instead
// the incomplete beta integral is employed,
// according to the formula:
// P = I[1-p]( n-k, k+1).
// = 1 - I[p](k + 1, n - k)
BOOST_MATH_STD_USING // for ADL of std functions
RealType n = dist.trials();
RealType p = dist.success_fraction();
// Error check:
RealType result;
if(false == binomial_detail::check_dist_and_k(
"boost::math::cdf(binomial_distribution<%1%> const&, %1%)",
n,
p,
k,
&result, Policy()))
{
return result;
}
if (k == n)
{
return 1;
}
// Special cases, regardless of k.
if (p == 0)
{ // This need explanation:
// the pdf is zero for all cases except when k == 0.
// For zero p the probability of zero successes is one.
// Therefore the cdf is always 1:
// the probability of k or *fewer* successes is always 1
// if there are never any successes!
return 1;
}
if (p == 1)
{ // This is correct but needs explanation:
// when k = 1
// all the cdf and pdf values are zero *except* when k == n,
// and that case has been handled above already.
return 0;
}
//
// P = I[1-p](n - k, k + 1)
// = 1 - I[p](k + 1, n - k)
// Use of ibetac here prevents cancellation errors in calculating
// 1-p if p is very small, perhaps smaller than machine epsilon.
//
// Note that we do not use a finite sum here, since the incomplete
// beta uses a finite sum internally for integer arguments, so
// we'll just let it take care of the necessary logic.
//
return ibetac(k + 1, n - k, p, Policy());
} // binomial cdf
template <class RealType, class Policy>
inline RealType cdf(const complemented2_type<binomial_distribution<RealType, Policy>, RealType>& c)
{ // Complemented Cumulative Distribution Function Binomial.
// The random variate k is the number of successes in n trials.
// k argument may be integral, signed, or unsigned, or floating point.
// If necessary, it has already been promoted from an integral type.
// Returns the sum of the terms k+1 through n of the Binomial Probability Density/Mass:
//
// i=n
// -- ( n ) i n-i
// > | | p (1-p)
// -- ( i )
// i=k+1
// The terms are not summed directly instead
// the incomplete beta integral is employed,
// according to the formula:
// Q = 1 -I[1-p]( n-k, k+1).
// = I[p](k + 1, n - k)
BOOST_MATH_STD_USING // for ADL of std functions
RealType const& k = c.param;
binomial_distribution<RealType, Policy> const& dist = c.dist;
RealType n = dist.trials();
RealType p = dist.success_fraction();
// Error checks:
RealType result;
if(false == binomial_detail::check_dist_and_k(
"boost::math::cdf(binomial_distribution<%1%> const&, %1%)",
n,
p,
k,
&result, Policy()))
{
return result;
}
if (k == n)
{ // Probability of greater than n successes is necessarily zero:
return 0;
}
// Special cases, regardless of k.
if (p == 0)
{
// This need explanation: the pdf is zero for all
// cases except when k == 0. For zero p the probability
// of zero successes is one. Therefore the cdf is always
// 1: the probability of *more than* k successes is always 0
// if there are never any successes!
return 0;
}
if (p == 1)
{
// This needs explanation, when p = 1
// we always have n successes, so the probability
// of more than k successes is 1 as long as k < n.
// The k == n case has already been handled above.
return 1;
}
//
// Calculate cdf binomial using the incomplete beta function.
// Q = 1 -I[1-p](n - k, k + 1)
// = I[p](k + 1, n - k)
// Use of ibeta here prevents cancellation errors in calculating
// 1-p if p is very small, perhaps smaller than machine epsilon.
//
// Note that we do not use a finite sum here, since the incomplete
// beta uses a finite sum internally for integer arguments, so
// we'll just let it take care of the necessary logic.
//
return ibeta(k + 1, n - k, p, Policy());
} // binomial cdf
template <class RealType, class Policy>
inline RealType quantile(const binomial_distribution<RealType, Policy>& dist, const RealType& p)
{
return binomial_detail::quantile_imp(dist, p, RealType(1-p));
} // quantile
template <class RealType, class Policy>
RealType quantile(const complemented2_type<binomial_distribution<RealType, Policy>, RealType>& c)
{
return binomial_detail::quantile_imp(c.dist, RealType(1-c.param), c.param);
} // quantile
template <class RealType, class Policy>
inline RealType mode(const binomial_distribution<RealType, Policy>& dist)
{
BOOST_MATH_STD_USING // ADL of std functions.
RealType p = dist.success_fraction();
RealType n = dist.trials();
return floor(p * (n + 1));
}
template <class RealType, class Policy>
inline RealType median(const binomial_distribution<RealType, Policy>& dist)
{ // Bounds for the median of the negative binomial distribution
// VAN DE VEN R. ; WEBER N. C. ;
// Univ. Sydney, school mathematics statistics, Sydney N.S.W. 2006, AUSTRALIE
// Metrika (Metrika) ISSN 0026-1335 CODEN MTRKA8
// 1993, vol. 40, no3-4, pp. 185-189 (4 ref.)
// Bounds for median and 50 percetage point of binomial and negative binomial distribution
// Metrika, ISSN 0026-1335 (Print) 1435-926X (Online)
// Volume 41, Number 1 / December, 1994, DOI 10.1007/BF01895303
BOOST_MATH_STD_USING // ADL of std functions.
RealType p = dist.success_fraction();
RealType n = dist.trials();
// Wikipedia says one of floor(np) -1, floor (np), floor(np) +1
return floor(p * n); // Chose the middle value.
}
template <class RealType, class Policy>
inline RealType skewness(const binomial_distribution<RealType, Policy>& dist)
{
BOOST_MATH_STD_USING // ADL of std functions.
RealType p = dist.success_fraction();
RealType n = dist.trials();
return (1 - 2 * p) / sqrt(n * p * (1 - p));
}
template <class RealType, class Policy>
inline RealType kurtosis(const binomial_distribution<RealType, Policy>& dist)
{
RealType p = dist.success_fraction();
RealType n = dist.trials();
return 3 - 6 / n + 1 / (n * p * (1 - p));
}
template <class RealType, class Policy>
inline RealType kurtosis_excess(const binomial_distribution<RealType, Policy>& dist)
{
RealType p = dist.success_fraction();
RealType q = 1 - p;
RealType n = dist.trials();
return (1 - 6 * p * q) / (n * p * q);
}
} // namespace math
} // namespace boost
// This include must be at the end, *after* the accessors
// for this distribution have been defined, in order to
// keep compilers that support two-phase lookup happy.
#include <boost/math/distributions/detail/derived_accessors.hpp>
#endif // BOOST_MATH_SPECIAL_BINOMIAL_HPP
|
/*
Copyright 2012 Rogier van Dalen.
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 a parser wrapper that makes compiler errors more meaningful.
*/
#ifndef PARSE_LL_BASE_NAMED_HPP_INCLUDED
#define PARSE_LL_BASE_NAMED_HPP_INCLUDED
#include "utility/returns.hpp"
#include "core.hpp"
#include <type_traits>
#include <boost/utility/enable_if.hpp>
namespace parse_ll {
/**
Base class for producing parsers that wrap other parsers.
Using named_parser is never necessary, but it is convenient for debugging.
For example, the predefined parser for "float" would have a five-line type if it
were not a named parser "float_parser".
A class deriving from this should have a member "implementation()" which is the
actual parser to be used, and a member "description()" which returns a short
description of the parser.
*/
struct named_parser {};
struct named_parser_tag;
template <class Parser> struct decayed_parser_tag <Parser,
typename boost::enable_if <std::is_base_of <named_parser, Parser>>::type>
{ typedef named_parser_tag type; };
namespace operation {
template <> struct parse <named_parser_tag> {
template <class Policy, class Parser, class Input>
auto operator() (Policy const & policy,
Parser const & parser, Input const & input) const
RETURNS (parse_ll::parse (policy, parser.implementation(), input));
};
template <> struct describe <named_parser_tag> {
template <class Parser> auto operator() (Parser const & parser) const
RETURNS (parser.description());
};
}
} // namespace parse_ll
/**
\todo Test separately.
Define a named parser type that wraps the parser expression in the dots.
*/
#define PARSE_LL_DEFINE_NAMED_PARSER_TYPE(name, type_name, ...) \
struct type_name \
: ::parse_ll::parser_base <type_name>, ::parse_ll::named_parser { \
typedef decltype (__VA_ARGS__) implementation_type; \
implementation_type implementation_; \
type_name() : implementation_ (__VA_ARGS__) {} \
implementation_type const & implementation() const { \
return implementation_; \
} \
const char * description() const { return name; } \
}
/**
Define a named parser type "name_parser" that wraps the parser expression in the
dots, and a static const variable "name" of type "name_parser".
*/
#define PARSE_LL_DEFINE_NAMED_PARSER(name, ...) \
PARSE_LL_DEFINE_NAMED_PARSER_TYPE (#name, name##_parser, __VA_ARGS__); \
static name##_parser const name = name##_parser();
/**
Define a named parser type that wraps the parser expression in the dots and has
one template parameter "template_parameter".
*/
#define PARSE_LL_DEFINE_NAMED_PARSER_TEMPLATE( \
name, type_name, template_parameter, ...) \
template <typename template_parameter> struct type_name \
: ::parse_ll::parser_base <type_name <template_parameter>>, \
::parse_ll::named_parser \
{ \
typedef decltype (__VA_ARGS__) implementation_type; \
implementation_type implementation_; \
type_name() : implementation_ (__VA_ARGS__) {} \
implementation_type const & implementation() const { \
return implementation_; \
} \
const char * description() const { return #name; } \
}
#endif // PARSE_LL_BASE_NAMED_HPP_INCLUDED
|
/* ========================= eCAL LICENSE =================================
*
* Copyright (C) 2016 - 2019 Continental Corporation
*
* 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.
*
* ========================= eCAL LICENSE =================================
*/
#include <ecal/ecal.h>
#include <atomic>
#include <chrono>
#include <iostream>
#include <memory>
#define TEST_RELIABLE 0
#define TEST_BEST_EFFORT 1
#define TEST_UDP 0
#define TEST_SHM 1
#define TEST_TCP 0
#define TEST_INPROC 0
auto g_snd_size (1000 * 1024);
auto g_pre_loops(100);
auto g_snd_loops( 1000 * 1000);
// subscriber callback function
std::atomic<size_t> g_callback_received;
void OnReceive(const char* /*topic_name_*/, const struct eCAL::SReceiveCallbackData* data_)
{
g_callback_received += data_->size;
}
static std::string CreatePayLoad(size_t payload_size_)
{
std::string s = "Hello World ";
while (s.size() < payload_size_) s += s;
s.resize(payload_size_);
return(s);
}
bool test_throughput(int snd_size, int snd_loops, eCAL::TLayer::eTransportLayer layer, bool reliable)
{
// internal timings for registration and data flow delay
const int reg_time (2000);
const int data_time(200);
// create publisher for topic "ThroughPut"
std::shared_ptr<eCAL::CPublisher> pub = std::make_shared<eCAL::CPublisher>();
// set qos
eCAL::QOS::SWriterQOS wqos;
if (reliable) wqos.reliability = eCAL::QOS::reliable_reliability_qos;
else wqos.reliability = eCAL::QOS::best_effort_reliability_qos;
pub->SetQOS(wqos);
// set transport layer
pub->SetLayerMode(eCAL::TLayer::tlayer_all, eCAL::TLayer::smode_off);
pub->SetLayerMode(layer, eCAL::TLayer::smode_on);
// create it
pub->Create("ThroughPut");
// create subscriber for topic "ThroughPut"
std::shared_ptr<eCAL::CSubscriber> sub = std::make_shared<eCAL::CSubscriber>();
// set qos
eCAL::QOS::SReaderQOS rqos;
if (reliable) rqos.reliability = eCAL::QOS::reliable_reliability_qos;
else rqos.reliability = eCAL::QOS::best_effort_reliability_qos;
sub->SetQOS(rqos);
// create it
sub->Create("ThroughPut");
// add callback
sub->AddReceiveCallback(std::bind(OnReceive, std::placeholders::_1, std::placeholders::_2));
// let's match them
eCAL::Process::SleepMS(reg_time);
// default send string
std::string send_s = CreatePayLoad(snd_size);
// start time
auto start = std::chrono::high_resolution_clock::now();
// we send a few dummy loops to establish all connections
for (auto i = 0; i < g_pre_loops; ++i)
{
pub->Send(send_s);
}
// let's finalize receive
eCAL::Process::SleepMS(data_time);
// reset received bytes counter
g_callback_received = 0;
// do some work
for (auto i = 0; i < snd_loops; ++i)
{
pub->Send(send_s);
}
// end time
auto finish = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed = finish - start;
std::cout << "Elapsed time : " << elapsed.count() << " s" << std::endl;
// let's match them
eCAL::Process::SleepMS(data_time);
size_t sum_snd_bytes = send_s.size() * snd_loops;
size_t sum_rcv_bytes = g_callback_received;
std::cout << "Sent : " << sum_snd_bytes << " bytes";
std::cout << " (" << sum_snd_bytes / (1024 * 1024) << " MB)" << std::endl;
std::cout << "Received : " << sum_rcv_bytes << " bytes";
std::cout << " (" << sum_rcv_bytes / (1024 * 1024) << " MB)" << std::endl;
std::cout << "Lost : " << sum_snd_bytes - sum_rcv_bytes << " bytes";
std::cout << " (" << (sum_snd_bytes - sum_rcv_bytes) / (1024 * 1024) << " MB, ";
std::cout << (sum_snd_bytes - sum_rcv_bytes) * 100.0f / sum_snd_bytes << " %)" << std::endl;
std::cout << "Throughput : " << int((sum_snd_bytes / (1024.0 * 1024.0)) / elapsed.count()) << " MB/s " << std::endl;
// check receive and send bytes
bool ret_state(false);
if (reliable) ret_state = sum_snd_bytes == sum_rcv_bytes;
else ret_state = (sum_snd_bytes * 3/4) <= sum_rcv_bytes;
// destroy pub/sub
pub->Destroy();
sub->Destroy();
return(ret_state);
}
// main entry
int main(int argc, char **argv)
{
// initialize eCAL API
eCAL::Initialize(argc, argv, "pubsub_throughput");
// publish / subscribe match in the same process
eCAL::Util::EnableLoopback(true);
bool success(false);
#if TEST_RELIABLE
#if TEST_UDP
std::cout << "RELIABLE : UDP" << std::endl;
success = test_throughput(g_snd_size, g_snd_loops, eCAL::TLayer::tlayer_udp_mc, true);
std::cout << "RESULT : " << success << std::endl << std::endl;
#endif
#if TEST_SHM
std::cout << "RELIABLE : SHM" << std::endl;
success = test_throughput(g_snd_size, g_snd_loops, eCAL::TLayer::tlayer_shm, true);
std::cout << "RESULT : " << success << std::endl << std::endl;
#endif
#if TEST_TCP
std::cout << "RELIABLE : TCP" << std::endl;
success = test_throughput(4000, g_snd_loops, eCAL::TLayer::tlayer_tcp, true);
std::cout << "RESULT : " << success << std::endl << std::endl;
#endif
#if TEST_INPROC
std::cout << "RELIABLE : INPROC" << std::endl;
success = test_throughput(4000, g_snd_loops, eCAL::TLayer::tlayer_inproc, true);
std::cout << "RESULT : " << success << std::endl << std::endl;
#endif
#endif // TEST_RELIABLE
#if TEST_BEST_EFFORT
#if TEST_UDP
std::cout << "BEST EFFORT : UDP" << std::endl;
success = test_throughput(g_snd_size, g_snd_loops, eCAL::TLayer::tlayer_udp_mc, false);
std::cout << "RESULT : " << success << std::endl << std::endl;
#endif
#if TEST_SHM
std::cout << "BEST EFFORT : SHM" << std::endl;
success = test_throughput(g_snd_size, g_snd_loops, eCAL::TLayer::tlayer_shm, false);
std::cout << "RESULT : " << success << std::endl << std::endl;
#endif
#if TEST_TCP
std::cout << "BEST EFFORT : TCP" << std::endl;
success = test_throughput(g_snd_size, g_snd_loops, eCAL::TLayer::tlayer_tcp, false);
std::cout << "RESULT : " << success << std::endl << std::endl;
#endif
#if TEST_INPROC
std::cout << "BEST EFFORT : INPROC" << std::endl;
success = test_throughput(4000, g_snd_loops, eCAL::TLayer::tlayer_inproc, false);
std::cout << "RESULT : " << success << std::endl << std::endl;
#endif
#endif // TEST_BEST_EFFORT
// finalize eCAL API
eCAL::Finalize();
return(0);
}
|
/*
* Copyright 2014 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "api/statstypes.h"
#include <string.h>
#include "rtc_base/checks.h"
#include "rtc_base/refcountedobject.h"
// TODO(tommi): Could we have a static map of value name -> expected type
// and use this to RTC_DCHECK on correct usage (somewhat strongly typed values)?
// Alternatively, we could define the names+type in a separate document and
// generate strongly typed inline C++ code that forces the correct type to be
// used for a given name at compile time.
using rtc::RefCountedObject;
namespace webrtc {
namespace {
// The id of StatsReport of type kStatsReportTypeBwe.
const char kStatsReportVideoBweId[] = "bweforvideo";
// NOTE: These names need to be consistent with an external
// specification (W3C Stats Identifiers).
const char* InternalTypeToString(StatsReport::StatsType type) {
switch (type) {
case StatsReport::kStatsReportTypeSession:
return "googLibjingleSession";
case StatsReport::kStatsReportTypeBwe:
return "VideoBwe";
case StatsReport::kStatsReportTypeRemoteSsrc:
return "remoteSsrc";
case StatsReport::kStatsReportTypeSsrc:
return "ssrc";
case StatsReport::kStatsReportTypeTrack:
return "googTrack";
case StatsReport::kStatsReportTypeIceLocalCandidate:
return "localcandidate";
case StatsReport::kStatsReportTypeIceRemoteCandidate:
return "remotecandidate";
case StatsReport::kStatsReportTypeTransport:
return "transport";
case StatsReport::kStatsReportTypeComponent:
return "googComponent";
case StatsReport::kStatsReportTypeCandidatePair:
return "googCandidatePair";
case StatsReport::kStatsReportTypeCertificate:
return "googCertificate";
case StatsReport::kStatsReportTypeDataChannel:
return "datachannel";
}
RTC_NOTREACHED();
return nullptr;
}
class BandwidthEstimationId : public StatsReport::IdBase {
public:
BandwidthEstimationId()
: StatsReport::IdBase(StatsReport::kStatsReportTypeBwe) {}
std::string ToString() const override { return kStatsReportVideoBweId; }
};
class TypedId : public StatsReport::IdBase {
public:
TypedId(StatsReport::StatsType type, const std::string& id)
: StatsReport::IdBase(type), id_(id) {}
bool Equals(const IdBase& other) const override {
return IdBase::Equals(other) &&
static_cast<const TypedId&>(other).id_ == id_;
}
std::string ToString() const override {
return std::string(InternalTypeToString(type_)) + kSeparator + id_;
}
protected:
const std::string id_;
};
class TypedIntId : public StatsReport::IdBase {
public:
TypedIntId(StatsReport::StatsType type, int id)
: StatsReport::IdBase(type), id_(id) {}
bool Equals(const IdBase& other) const override {
return IdBase::Equals(other) &&
static_cast<const TypedIntId&>(other).id_ == id_;
}
std::string ToString() const override {
return std::string(InternalTypeToString(type_)) +
kSeparator +
rtc::ToString<int>(id_);
}
protected:
const int id_;
};
class IdWithDirection : public TypedId {
public:
IdWithDirection(StatsReport::StatsType type, const std::string& id,
StatsReport::Direction direction)
: TypedId(type, id), direction_(direction) {}
bool Equals(const IdBase& other) const override {
return TypedId::Equals(other) &&
static_cast<const IdWithDirection&>(other).direction_ == direction_;
}
std::string ToString() const override {
std::string ret(TypedId::ToString());
ret += kSeparator;
ret += direction_ == StatsReport::kSend ? "send" : "recv";
return ret;
}
private:
const StatsReport::Direction direction_;
};
class CandidateId : public TypedId {
public:
CandidateId(bool local, const std::string& id)
: TypedId(local ?
StatsReport::kStatsReportTypeIceLocalCandidate :
StatsReport::kStatsReportTypeIceRemoteCandidate,
id) {
}
std::string ToString() const override {
return "Cand-" + id_;
}
};
class ComponentId : public StatsReport::IdBase {
public:
ComponentId(const std::string& content_name, int component)
: ComponentId(StatsReport::kStatsReportTypeComponent, content_name,
component) {}
bool Equals(const IdBase& other) const override {
return IdBase::Equals(other) &&
static_cast<const ComponentId&>(other).component_ == component_ &&
static_cast<const ComponentId&>(other).content_name_ == content_name_;
}
std::string ToString() const override {
return ToString("Channel-");
}
protected:
ComponentId(StatsReport::StatsType type, const std::string& content_name,
int component)
: IdBase(type),
content_name_(content_name),
component_(component) {}
std::string ToString(const char* prefix) const {
std::string ret(prefix);
ret += content_name_;
ret += '-';
ret += rtc::ToString<>(component_);
return ret;
}
private:
const std::string content_name_;
const int component_;
};
class CandidatePairId : public ComponentId {
public:
CandidatePairId(const std::string& content_name, int component, int index)
: ComponentId(StatsReport::kStatsReportTypeCandidatePair, content_name,
component),
index_(index) {}
bool Equals(const IdBase& other) const override {
return ComponentId::Equals(other) &&
static_cast<const CandidatePairId&>(other).index_ == index_;
}
std::string ToString() const override {
std::string ret(ComponentId::ToString("Conn-"));
ret += '-';
ret += rtc::ToString<>(index_);
return ret;
}
private:
const int index_;
};
} // namespace
StatsReport::IdBase::IdBase(StatsType type) : type_(type) {}
StatsReport::IdBase::~IdBase() {}
StatsReport::StatsType StatsReport::IdBase::type() const { return type_; }
bool StatsReport::IdBase::Equals(const IdBase& other) const {
return other.type_ == type_;
}
StatsReport::Value::Value(StatsValueName name, int64_t value, Type int_type)
: name(name), type_(int_type) {
RTC_DCHECK(type_ == kInt || type_ == kInt64);
type_ == kInt ? value_.int_ = static_cast<int>(value) : value_.int64_ = value;
}
StatsReport::Value::Value(StatsValueName name, float f)
: name(name), type_(kFloat) {
value_.float_ = f;
}
StatsReport::Value::Value(StatsValueName name, const std::string& value)
: name(name), type_(kString) {
value_.string_ = new std::string(value);
}
StatsReport::Value::Value(StatsValueName name, const char* value)
: name(name), type_(kStaticString) {
value_.static_string_ = value;
}
StatsReport::Value::Value(StatsValueName name, bool b)
: name(name), type_(kBool) {
value_.bool_ = b;
}
StatsReport::Value::Value(StatsValueName name, const Id& value)
: name(name), type_(kId) {
value_.id_ = new Id(value);
}
StatsReport::Value::~Value() {
switch (type_) {
case kInt:
case kInt64:
case kFloat:
case kBool:
case kStaticString:
break;
case kString:
delete value_.string_;
break;
case kId:
delete value_.id_;
break;
}
}
bool StatsReport::Value::Equals(const Value& other) const {
if (name != other.name)
return false;
// There's a 1:1 relation between a name and a type, so we don't have to
// check that.
RTC_DCHECK_EQ(type_, other.type_);
switch (type_) {
case kInt:
return value_.int_ == other.value_.int_;
case kInt64:
return value_.int64_ == other.value_.int64_;
case kFloat:
return value_.float_ == other.value_.float_;
case kStaticString: {
#if RTC_DCHECK_IS_ON
if (value_.static_string_ != other.value_.static_string_) {
RTC_DCHECK(strcmp(value_.static_string_, other.value_.static_string_) !=
0)
<< "Duplicate global?";
}
#endif
return value_.static_string_ == other.value_.static_string_;
}
case kString:
return *value_.string_ == *other.value_.string_;
case kBool:
return value_.bool_ == other.value_.bool_;
case kId:
return (*value_.id_)->Equals(*other.value_.id_);
}
RTC_NOTREACHED();
return false;
}
bool StatsReport::Value::operator==(const std::string& value) const {
return (type_ == kString && value_.string_->compare(value) == 0) ||
(type_ == kStaticString && value.compare(value_.static_string_) == 0);
}
bool StatsReport::Value::operator==(const char* value) const {
if (type_ == kString)
return value_.string_->compare(value) == 0;
if (type_ != kStaticString)
return false;
#if RTC_DCHECK_IS_ON
if (value_.static_string_ != value)
RTC_DCHECK(strcmp(value_.static_string_, value) != 0)
<< "Duplicate global?";
#endif
return value == value_.static_string_;
}
bool StatsReport::Value::operator==(int64_t value) const {
return type_ == kInt ? value_.int_ == static_cast<int>(value) :
(type_ == kInt64 ? value_.int64_ == value : false);
}
bool StatsReport::Value::operator==(bool value) const {
return type_ == kBool && value_.bool_ == value;
}
bool StatsReport::Value::operator==(float value) const {
return type_ == kFloat && value_.float_ == value;
}
bool StatsReport::Value::operator==(const Id& value) const {
return type_ == kId && (*value_.id_)->Equals(value);
}
int StatsReport::Value::int_val() const {
RTC_DCHECK(type_ == kInt);
return value_.int_;
}
int64_t StatsReport::Value::int64_val() const {
RTC_DCHECK(type_ == kInt64);
return value_.int64_;
}
float StatsReport::Value::float_val() const {
RTC_DCHECK(type_ == kFloat);
return value_.float_;
}
const char* StatsReport::Value::static_string_val() const {
RTC_DCHECK(type_ == kStaticString);
return value_.static_string_;
}
const std::string& StatsReport::Value::string_val() const {
RTC_DCHECK(type_ == kString);
return *value_.string_;
}
bool StatsReport::Value::bool_val() const {
RTC_DCHECK(type_ == kBool);
return value_.bool_;
}
const char* StatsReport::Value::display_name() const {
switch (name) {
case kStatsValueNameAecDivergentFilterFraction:
return "aecDivergentFilterFraction";
case kStatsValueNameAudioOutputLevel:
return "audioOutputLevel";
case kStatsValueNameAudioInputLevel:
return "audioInputLevel";
case kStatsValueNameBytesSent:
return "bytesSent";
case kStatsValueNameConcealedSamples:
return "concealedSamples";
case kStatsValueNameConcealmentEvents:
return "concealmentEvents";
case kStatsValueNamePacketsSent:
return "packetsSent";
case kStatsValueNameBytesReceived:
return "bytesReceived";
case kStatsValueNameLabel:
return "label";
case kStatsValueNamePacketsReceived:
return "packetsReceived";
case kStatsValueNamePacketsLost:
return "packetsLost";
case kStatsValueNameProtocol:
return "protocol";
case kStatsValueNameTotalSamplesReceived:
return "totalSamplesReceived";
case kStatsValueNameTransportId:
return "transportId";
case kStatsValueNameSelectedCandidatePairId:
return "selectedCandidatePairId";
case kStatsValueNameSsrc:
return "ssrc";
case kStatsValueNameState:
return "state";
case kStatsValueNameDataChannelId:
return "datachannelid";
case kStatsValueNameFramesDecoded:
return "framesDecoded";
case kStatsValueNameFramesEncoded:
return "framesEncoded";
case kStatsValueNameJitterBufferDelay:
return "jitterBufferDelay";
case kStatsValueNameCodecImplementationName:
return "codecImplementationName";
case kStatsValueNameMediaType:
return "mediaType";
case kStatsValueNameQpSum:
return "qpSum";
// 'goog' prefixed constants.
case kStatsValueNameAccelerateRate:
return "googAccelerateRate";
case kStatsValueNameActiveConnection:
return "googActiveConnection";
case kStatsValueNameActualEncBitrate:
return "googActualEncBitrate";
case kStatsValueNameAvailableReceiveBandwidth:
return "googAvailableReceiveBandwidth";
case kStatsValueNameAvailableSendBandwidth:
return "googAvailableSendBandwidth";
case kStatsValueNameAvgEncodeMs:
return "googAvgEncodeMs";
case kStatsValueNameBucketDelay:
return "googBucketDelay";
case kStatsValueNameBandwidthLimitedResolution:
return "googBandwidthLimitedResolution";
// STUN ping related attributes.
// TODO(zhihuang) Rename these stats to follow the standards.
case kStatsValueNameSentPingRequestsTotal:
return "requestsSent";
case kStatsValueNameSentPingRequestsBeforeFirstResponse:
return "consentRequestsSent";
case kStatsValueNameSentPingResponses:
return "responsesSent";
case kStatsValueNameRecvPingRequests:
return "requestsReceived";
case kStatsValueNameRecvPingResponses:
return "responsesReceived";
// Candidate related attributes. Values are taken from
// http://w3c.github.io/webrtc-stats/#rtcstatstype-enum*.
case kStatsValueNameCandidateIPAddress:
return "ipAddress";
case kStatsValueNameCandidateNetworkType:
return "networkType";
case kStatsValueNameCandidatePortNumber:
return "portNumber";
case kStatsValueNameCandidatePriority:
return "priority";
case kStatsValueNameCandidateTransportType:
return "transport";
case kStatsValueNameCandidateType:
return "candidateType";
case kStatsValueNameChannelId:
return "googChannelId";
case kStatsValueNameCodecName:
return "googCodecName";
case kStatsValueNameComponent:
return "googComponent";
case kStatsValueNameContentName:
return "googContentName";
case kStatsValueNameContentType:
return "googContentType";
case kStatsValueNameCpuLimitedResolution:
return "googCpuLimitedResolution";
case kStatsValueNameDecodingCTSG:
return "googDecodingCTSG";
case kStatsValueNameDecodingCTN:
return "googDecodingCTN";
case kStatsValueNameDecodingMutedOutput:
return "googDecodingMuted";
case kStatsValueNameDecodingNormal:
return "googDecodingNormal";
case kStatsValueNameDecodingPLC:
return "googDecodingPLC";
case kStatsValueNameDecodingCNG:
return "googDecodingCNG";
case kStatsValueNameDecodingPLCCNG:
return "googDecodingPLCCNG";
case kStatsValueNameDer:
return "googDerBase64";
case kStatsValueNameDtlsCipher:
return "dtlsCipher";
case kStatsValueNameEchoCancellationQualityMin:
return "googEchoCancellationQualityMin";
case kStatsValueNameEchoDelayMedian:
return "googEchoCancellationEchoDelayMedian";
case kStatsValueNameEchoDelayStdDev:
return "googEchoCancellationEchoDelayStdDev";
case kStatsValueNameEchoReturnLoss:
return "googEchoCancellationReturnLoss";
case kStatsValueNameEchoReturnLossEnhancement:
return "googEchoCancellationReturnLossEnhancement";
case kStatsValueNameEncodeUsagePercent:
return "googEncodeUsagePercent";
case kStatsValueNameExpandRate:
return "googExpandRate";
case kStatsValueNameFingerprint:
return "googFingerprint";
case kStatsValueNameFingerprintAlgorithm:
return "googFingerprintAlgorithm";
case kStatsValueNameFirsReceived:
return "googFirsReceived";
case kStatsValueNameFirsSent:
return "googFirsSent";
case kStatsValueNameFrameHeightInput:
return "googFrameHeightInput";
case kStatsValueNameFrameHeightReceived:
return "googFrameHeightReceived";
case kStatsValueNameFrameHeightSent:
return "googFrameHeightSent";
case kStatsValueNameFrameRateReceived:
return "googFrameRateReceived";
case kStatsValueNameFrameRateDecoded:
return "googFrameRateDecoded";
case kStatsValueNameFrameRateOutput:
return "googFrameRateOutput";
case kStatsValueNameDecodeMs:
return "googDecodeMs";
case kStatsValueNameMaxDecodeMs:
return "googMaxDecodeMs";
case kStatsValueNameCurrentDelayMs:
return "googCurrentDelayMs";
case kStatsValueNameTargetDelayMs:
return "googTargetDelayMs";
case kStatsValueNameJitterBufferMs:
return "googJitterBufferMs";
case kStatsValueNameMinPlayoutDelayMs:
return "googMinPlayoutDelayMs";
case kStatsValueNameRenderDelayMs:
return "googRenderDelayMs";
case kStatsValueNameCaptureStartNtpTimeMs:
return "googCaptureStartNtpTimeMs";
case kStatsValueNameFrameRateInput:
return "googFrameRateInput";
case kStatsValueNameFrameRateSent:
return "googFrameRateSent";
case kStatsValueNameFrameWidthInput:
return "googFrameWidthInput";
case kStatsValueNameFrameWidthReceived:
return "googFrameWidthReceived";
case kStatsValueNameFrameWidthSent:
return "googFrameWidthSent";
case kStatsValueNameHasEnteredLowResolution:
return "googHasEnteredLowResolution";
case kStatsValueNameInitiator:
return "googInitiator";
case kStatsValueNameInterframeDelayMaxMs:
return "googInterframeDelayMax";
case kStatsValueNameIssuerId:
return "googIssuerId";
case kStatsValueNameJitterReceived:
return "googJitterReceived";
case kStatsValueNameLocalAddress:
return "googLocalAddress";
case kStatsValueNameLocalCandidateId:
return "localCandidateId";
case kStatsValueNameLocalCandidateType:
return "googLocalCandidateType";
case kStatsValueNameLocalCertificateId:
return "localCertificateId";
case kStatsValueNameAdaptationChanges:
return "googAdaptationChanges";
case kStatsValueNameNacksReceived:
return "googNacksReceived";
case kStatsValueNameNacksSent:
return "googNacksSent";
case kStatsValueNamePreemptiveExpandRate:
return "googPreemptiveExpandRate";
case kStatsValueNamePlisReceived:
return "googPlisReceived";
case kStatsValueNamePlisSent:
return "googPlisSent";
case kStatsValueNamePreferredJitterBufferMs:
return "googPreferredJitterBufferMs";
case kStatsValueNameReceiving:
return "googReadable";
case kStatsValueNameRemoteAddress:
return "googRemoteAddress";
case kStatsValueNameRemoteCandidateId:
return "remoteCandidateId";
case kStatsValueNameRemoteCandidateType:
return "googRemoteCandidateType";
case kStatsValueNameRemoteCertificateId:
return "remoteCertificateId";
case kStatsValueNameResidualEchoLikelihood:
return "googResidualEchoLikelihood";
case kStatsValueNameResidualEchoLikelihoodRecentMax:
return "googResidualEchoLikelihoodRecentMax";
case kStatsValueNameAnaBitrateActionCounter:
return "googAnaBitrateActionCounter";
case kStatsValueNameAnaChannelActionCounter:
return "googAnaChannelActionCounter";
case kStatsValueNameAnaDtxActionCounter:
return "googAnaDtxActionCounter";
case kStatsValueNameAnaFecActionCounter:
return "googAnaFecActionCounter";
case kStatsValueNameAnaFrameLengthIncreaseCounter:
return "googAnaFrameLengthIncreaseCounter";
case kStatsValueNameAnaFrameLengthDecreaseCounter:
return "googAnaFrameLengthDecreaseCounter";
case kStatsValueNameAnaUplinkPacketLossFraction:
return "googAnaUplinkPacketLossFraction";
case kStatsValueNameRetransmitBitrate:
return "googRetransmitBitrate";
case kStatsValueNameRtt:
return "googRtt";
case kStatsValueNameSecondaryDecodedRate:
return "googSecondaryDecodedRate";
case kStatsValueNameSecondaryDiscardedRate:
return "googSecondaryDiscardedRate";
case kStatsValueNameSendPacketsDiscarded:
return "packetsDiscardedOnSend";
case kStatsValueNameSpeechExpandRate:
return "googSpeechExpandRate";
case kStatsValueNameSrtpCipher:
return "srtpCipher";
case kStatsValueNameTargetEncBitrate:
return "googTargetEncBitrate";
case kStatsValueNameTotalAudioEnergy:
return "totalAudioEnergy";
case kStatsValueNameTotalSamplesDuration:
return "totalSamplesDuration";
case kStatsValueNameTransmitBitrate:
return "googTransmitBitrate";
case kStatsValueNameTransportType:
return "googTransportType";
case kStatsValueNameTrackId:
return "googTrackId";
case kStatsValueNameTimingFrameInfo:
return "googTimingFrameInfo";
case kStatsValueNameTypingNoiseState:
return "googTypingNoiseState";
case kStatsValueNameWritable:
return "googWritable";
}
return nullptr;
}
std::string StatsReport::Value::ToString() const {
switch (type_) {
case kInt:
return rtc::ToString(value_.int_);
case kInt64:
return rtc::ToString(value_.int64_);
case kFloat:
return rtc::ToString(value_.float_);
case kStaticString:
return std::string(value_.static_string_);
case kString:
return *value_.string_;
case kBool:
return value_.bool_ ? "true" : "false";
case kId:
return (*value_.id_)->ToString();
}
RTC_NOTREACHED();
return std::string();
}
StatsReport::StatsReport(const Id& id) : id_(id), timestamp_(0.0) {
RTC_DCHECK(id_.get());
}
StatsReport::~StatsReport() = default;
// static
StatsReport::Id StatsReport::NewBandwidthEstimationId() {
return Id(new RefCountedObject<BandwidthEstimationId>());
}
// static
StatsReport::Id StatsReport::NewTypedId(StatsType type, const std::string& id) {
return Id(new RefCountedObject<TypedId>(type, id));
}
// static
StatsReport::Id StatsReport::NewTypedIntId(StatsType type, int id) {
return Id(new RefCountedObject<TypedIntId>(type, id));
}
// static
StatsReport::Id StatsReport::NewIdWithDirection(
StatsType type, const std::string& id, StatsReport::Direction direction) {
return Id(new RefCountedObject<IdWithDirection>(type, id, direction));
}
// static
StatsReport::Id StatsReport::NewCandidateId(bool local, const std::string& id) {
return Id(new RefCountedObject<CandidateId>(local, id));
}
// static
StatsReport::Id StatsReport::NewComponentId(
const std::string& content_name, int component) {
return Id(new RefCountedObject<ComponentId>(content_name, component));
}
// static
StatsReport::Id StatsReport::NewCandidatePairId(
const std::string& content_name, int component, int index) {
return Id(new RefCountedObject<CandidatePairId>(
content_name, component, index));
}
const char* StatsReport::TypeToString() const {
return InternalTypeToString(id_->type());
}
void StatsReport::AddString(StatsReport::StatsValueName name,
const std::string& value) {
const Value* found = FindValue(name);
if (!found || !(*found == value))
values_[name] = ValuePtr(new Value(name, value));
}
void StatsReport::AddString(StatsReport::StatsValueName name,
const char* value) {
const Value* found = FindValue(name);
if (!found || !(*found == value))
values_[name] = ValuePtr(new Value(name, value));
}
void StatsReport::AddInt64(StatsReport::StatsValueName name, int64_t value) {
const Value* found = FindValue(name);
if (!found || !(*found == value))
values_[name] = ValuePtr(new Value(name, value, Value::kInt64));
}
void StatsReport::AddInt(StatsReport::StatsValueName name, int value) {
const Value* found = FindValue(name);
if (!found || !(*found == static_cast<int64_t>(value)))
values_[name] = ValuePtr(new Value(name, value, Value::kInt));
}
void StatsReport::AddFloat(StatsReport::StatsValueName name, float value) {
const Value* found = FindValue(name);
if (!found || !(*found == value))
values_[name] = ValuePtr(new Value(name, value));
}
void StatsReport::AddBoolean(StatsReport::StatsValueName name, bool value) {
const Value* found = FindValue(name);
if (!found || !(*found == value))
values_[name] = ValuePtr(new Value(name, value));
}
void StatsReport::AddId(StatsReport::StatsValueName name,
const Id& value) {
const Value* found = FindValue(name);
if (!found || !(*found == value))
values_[name] = ValuePtr(new Value(name, value));
}
const StatsReport::Value* StatsReport::FindValue(StatsValueName name) const {
Values::const_iterator it = values_.find(name);
return it == values_.end() ? nullptr : it->second.get();
}
StatsCollection::StatsCollection() {
}
StatsCollection::~StatsCollection() {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
for (auto* r : list_)
delete r;
}
StatsCollection::const_iterator StatsCollection::begin() const {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
return list_.begin();
}
StatsCollection::const_iterator StatsCollection::end() const {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
return list_.end();
}
size_t StatsCollection::size() const {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
return list_.size();
}
StatsReport* StatsCollection::InsertNew(const StatsReport::Id& id) {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
RTC_DCHECK(Find(id) == nullptr);
StatsReport* report = new StatsReport(id);
list_.push_back(report);
return report;
}
StatsReport* StatsCollection::FindOrAddNew(const StatsReport::Id& id) {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
StatsReport* ret = Find(id);
return ret ? ret : InsertNew(id);
}
StatsReport* StatsCollection::ReplaceOrAddNew(const StatsReport::Id& id) {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
RTC_DCHECK(id.get());
Container::iterator it = std::find_if(list_.begin(), list_.end(),
[&id](const StatsReport* r)->bool { return r->id()->Equals(id); });
if (it != end()) {
StatsReport* report = new StatsReport((*it)->id());
delete *it;
*it = report;
return report;
}
return InsertNew(id);
}
// Looks for a report with the given |id|. If one is not found, null
// will be returned.
StatsReport* StatsCollection::Find(const StatsReport::Id& id) {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
Container::iterator it = std::find_if(list_.begin(), list_.end(),
[&id](const StatsReport* r)->bool { return r->id()->Equals(id); });
return it == list_.end() ? nullptr : *it;
}
} // namespace webrtc
|
/*
* nextpnr -- Next Generation Place and Route
*
* Copyright (C) 2018 David Shah <david@symbioticeda.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "cells.h"
#include "log.h"
#include "nextpnr.h"
#include "util.h"
NEXTPNR_NAMESPACE_BEGIN
inline NetInfo *port_or_nullptr(const CellInfo *cell, IdString name)
{
auto found = cell->ports.find(name);
if (found == cell->ports.end())
return nullptr;
return found->second.net;
}
bool Arch::slicesCompatible(const std::vector<const CellInfo *> &cells) const
{
// TODO: allow different LSR/CLK and MUX/SRMODE settings once
// routing details are worked out
IdString clk_sig, lsr_sig;
IdString CLKMUX, LSRMUX, SRMODE;
bool first = true;
for (auto cell : cells) {
if (cell->sliceInfo.using_dff) {
if (first) {
clk_sig = cell->sliceInfo.clk_sig;
lsr_sig = cell->sliceInfo.lsr_sig;
CLKMUX = cell->sliceInfo.clkmux;
LSRMUX = cell->sliceInfo.lsrmux;
SRMODE = cell->sliceInfo.srmode;
} else {
if (cell->sliceInfo.clk_sig != clk_sig)
return false;
if (cell->sliceInfo.lsr_sig != lsr_sig)
return false;
if (cell->sliceInfo.clkmux != CLKMUX)
return false;
if (cell->sliceInfo.lsrmux != LSRMUX)
return false;
if (cell->sliceInfo.srmode != SRMODE)
return false;
}
first = false;
}
}
return true;
}
bool Arch::isBelLocationValid(BelId bel) const
{
if (getBelType(bel) == id_TRELLIS_SLICE) {
std::vector<const CellInfo *> bel_cells;
Loc bel_loc = getBelLocation(bel);
for (auto bel_other : getBelsByTile(bel_loc.x, bel_loc.y)) {
CellInfo *cell_other = getBoundBelCell(bel_other);
if (cell_other != nullptr) {
bel_cells.push_back(cell_other);
}
}
if (getBoundBelCell(bel) != nullptr && getBoundBelCell(bel)->sliceInfo.has_l6mux && ((bel_loc.z % 2) == 1))
return false;
return slicesCompatible(bel_cells);
} else {
CellInfo *cell = getBoundBelCell(bel);
if (cell == nullptr)
return true;
else
return isValidBelForCell(cell, bel);
}
}
bool Arch::isValidBelForCell(CellInfo *cell, BelId bel) const
{
if (cell->type == id_TRELLIS_SLICE) {
NPNR_ASSERT(getBelType(bel) == id_TRELLIS_SLICE);
std::vector<const CellInfo *> bel_cells;
Loc bel_loc = getBelLocation(bel);
if (cell->sliceInfo.has_l6mux && ((bel_loc.z % 2) == 1))
return false;
for (auto bel_other : getBelsByTile(bel_loc.x, bel_loc.y)) {
CellInfo *cell_other = getBoundBelCell(bel_other);
if (cell_other != nullptr && bel_other != bel) {
bel_cells.push_back(cell_other);
}
}
bel_cells.push_back(cell);
return slicesCompatible(bel_cells);
} else if (cell->type == id_DCUA || cell->type == id_EXTREFB || cell->type == id_PCSCLKDIV) {
return args.type != ArchArgs::LFE5U_25F && args.type != ArchArgs::LFE5U_45F && args.type != ArchArgs::LFE5U_85F;
} else {
// other checks
return true;
}
}
NEXTPNR_NAMESPACE_END
|
#include <torch/csrc/jit/python/module_python.h>
#include <torch/csrc/jit/python/pybind_utils.h>
#include <torch/csrc/jit/python/python_dict.h>
#include <torch/csrc/jit/python/python_ivalue.h>
#include <c10/util/irange.h>
namespace torch {
namespace jit {
// This is a hack to remove instances deleted in C++ from the PyBind cache
// C++->Python. We need this because otherwise we may get the old Python object
// if C++ creates a new object at the memory location of the deleted object.
void clear_registered_instances(void* ptr) {
auto& registered_instances =
pybind11::detail::get_internals().registered_instances;
auto range = registered_instances.equal_range(ptr);
for (auto it = range.first; it != range.second; ++it) {
auto vh = it->second->get_value_and_holder();
vh.set_instance_registered(false);
}
registered_instances.erase(ptr);
}
IValue toIValue(py::handle obj, const TypePtr& type, c10::optional<int32_t> N) {
switch (type->kind()) {
case TypeKind::TensorType: {
auto var = py::cast<autograd::Variable>(obj);
if (var.is_sparse()) {
TORCH_WARN_ONCE(
"Using sparse tensors in TorchScript is experimental. Many optimization "
"pathways have not been thoroughly tested with sparse tensors. Please "
"include the fact that the network is running sparse tensors in any bug "
"reports submitted.");
}
guardAgainstNamedTensor<autograd::Variable>(var);
return var;
}
case TypeKind::FloatType:
return py::cast<double>(obj);
case TypeKind::ComplexType: {
auto c_obj = py::cast<std::complex<double>>(obj.ptr());
return static_cast<c10::complex<double>>(c_obj);
}
case TypeKind::IntType:
// TODO(xintchen): Handling LayoutType and ScalarTypeType correctly.
case TypeKind::LayoutType:
case TypeKind::ScalarTypeType:
if (THPDtype_Check(obj.ptr())) {
auto dtype = reinterpret_cast<THPDtype*>(obj.ptr());
return static_cast<int64_t>(dtype->scalar_type);
}
if (THPQScheme_Check(obj.ptr())) {
auto qscheme = reinterpret_cast<THPQScheme*>(obj.ptr());
return static_cast<uint8_t>(qscheme->qscheme);
}
if (THPLayout_Check(obj.ptr())) {
auto layout = reinterpret_cast<THPLayout*>(obj.ptr());
return static_cast<int8_t>(layout->layout);
}
return py::cast<int64_t>(obj);
case TypeKind::NoneType:
if (!obj.is_none()) {
throw py::cast_error(
c10::str("Cannot cast ", py::str(obj), " to None"));
}
return {};
case TypeKind::BoolType:
return py::cast<bool>(obj);
case TypeKind::TupleType: {
py::tuple tuple = py::cast<py::tuple>(obj);
size_t tuple_size = tuple.size();
auto tuple_type = type->cast<TupleType>();
const auto& elem_types = tuple_type->elements();
if (elem_types.size() != tuple_size) {
throw py::cast_error(c10::str(
"Object ",
py::str(obj),
" had a different number of elements than type ",
type->repr_str()));
}
std::vector<IValue> values;
values.reserve(tuple_size);
for (size_t i = 0; i < tuple_size; ++i) {
values.push_back(toIValue(tuple[i], elem_types[i]));
}
return tuple_type->name()
? c10::ivalue::Tuple::createNamed(std::move(values), tuple_type)
: c10::ivalue::Tuple::create(std::move(values));
}
case TypeKind::StringType:
return ConstantString::create(py::cast<std::string>(obj));
case TypeKind::DeviceObjType: {
if (THPDevice_Check(obj.ptr())) {
auto device = reinterpret_cast<THPDevice*>(obj.ptr());
return device->device;
}
return c10::Device(py::cast<std::string>(obj.ptr()));
}
case TypeKind::StreamObjType: {
auto stream = reinterpret_cast<THPStream*>(obj.ptr());
return static_cast<int64_t>(stream->cdata);
}
case TypeKind::ListType: {
const auto& elem_type = type->expectRef<ListType>().getElementType();
switch (elem_type->kind()) {
// allows single int/float to be broadcasted to a fixed size list
case TypeKind::IntType:
if (!N || !py::isinstance<py::int_>(obj)) {
return IValue(py::cast<std::vector<int64_t>>(obj));
} else {
int64_t value = py::cast<int64_t>(obj);
c10::List<int64_t> repeated;
repeated.reserve(*N);
for (int i = 0; i < *N; ++i) {
repeated.push_back(value);
}
return repeated;
}
case TypeKind::FloatType:
if (!N || !py::isinstance<py::float_>(obj)) {
return IValue(py::cast<std::vector<double>>(obj));
} else {
double value = py::cast<double>(obj);
c10::List<double> repeated;
repeated.reserve(*N);
for (int i = 0; i < *N; ++i) {
repeated.push_back(value);
}
return repeated;
}
case TypeKind::BoolType:
return IValue(py::cast<std::vector<bool>>(obj));
case TypeKind::TensorType:
return IValue(py::cast<std::vector<at::Tensor>>(obj));
default:
return createGenericList(obj, elem_type);
}
}
case TypeKind::DictType: {
const auto& dict_type = type->expect<DictType>();
// If the object is a ScriptDict, retrieve the c10::Dict
// instance inside it.
try {
auto script_dict = py::cast<ScriptDict>(obj);
return script_dict.dict_;
} catch (py::cast_error& e) {
}
// If not (i.e. it is a regular Python dictionary), make a new
// c10::Dict.
return createGenericDict(
py::cast<py::dict>(obj),
dict_type->getKeyType(),
dict_type->getValueType());
}
case TypeKind::OptionalType: {
// check if it's a none obj since optional accepts NoneType
if (obj.is_none()) {
// check if it's a none obj since optional accepts NoneType
// return an IValue() to denote a NoneType
return {};
}
return toIValue(obj, type->expectRef<OptionalType>().getElementType());
}
case TypeKind::ClassType: {
auto classType = type->expect<ClassType>();
auto object = py::cast<py::object>(obj);
if (auto mod = as_module(object)) {
// if obj is already a ScriptModule, just return its ivalue
return mod.value()._ivalue();
}
// Check if the obj is a ScriptObject.
if (auto script_obj = as_object(object)) {
return script_obj.value()._ivalue();
}
// otherwise is a normal class object, we create a fresh
// ivalue::Object to use from the py object.
// 1. create a bare ivalue
const size_t numAttrs = classType->numAttributes();
auto cu = classType->compilation_unit();
auto userObj = c10::ivalue::Object::create(
c10::StrongTypePtr(cu, classType), numAttrs);
// 2. copy all the contained types
for (const auto slot : c10::irange(numAttrs)) {
const auto& attrType = classType->getAttribute(slot);
const auto& attrName = classType->getAttributeName(slot);
if (!py::hasattr(obj, attrName.c_str())) {
throw py::cast_error(c10::str(
"Tried to cast object to type ",
type->repr_str(),
" but object",
" was missing attribute ",
attrName));
}
try {
const auto& contained = py::getattr(obj, attrName.c_str());
userObj->setSlot(slot, toIValue(contained, attrType));
} catch (std::exception& e) {
throw py::cast_error(c10::str(
"Could not cast attribute '",
attrName,
"' to type ",
attrType->repr_str(),
": ",
e.what()));
}
}
return userObj;
}
case TypeKind::InterfaceType: {
auto interfaceType = type->expect<InterfaceType>();
// When converting an pyobj to an interface, we check if rhs
// is module or normal torchscript class, get the type and ivalue
// from them correspondingly.
c10::ClassTypePtr classType = nullptr;
IValue res;
if (auto mod = as_module(py::cast<py::object>(obj))) {
classType = mod.value().type();
res = mod.value()._ivalue();
} else if (auto object = as_object(py::cast<py::object>(obj))) {
classType = object.value().type();
res = object.value()._ivalue();
} else {
// We inspect the value to found the compiled TorchScript class
// and then create a ivalue::Object from that class type.
py::str qualified_name = py::module::import("torch._jit_internal")
.attr("_qualified_name")(obj.get_type());
auto pyCu = get_python_cu();
classType = pyCu->get_class(c10::QualifiedName(qualified_name));
if (!classType) {
throw std::runtime_error(c10::str(
"Assigning the object ",
py::str(obj),
" to an interface fails because the value is not "
"a TorchScript compatible type, did you forget to",
"turn it into a user defined TorchScript class?"));
}
res = toIValue(obj, classType);
}
// check if the classType conform with the interface or not
std::stringstream why_not;
if (!classType->isSubtypeOfExt(interfaceType, &why_not)) {
throw py::cast_error(c10::str(
"Object of type ",
classType->repr_str(),
" is not compatible with interface ",
interfaceType->repr_str(),
"\n",
why_not.str()));
}
return res;
}
case TypeKind::NumberType: {
if (THPDtype_Check(obj.ptr())) {
auto dtype = reinterpret_cast<THPDtype*>(obj.ptr());
return static_cast<int64_t>(dtype->scalar_type);
}
if (THPQScheme_Check(obj.ptr())) {
auto qscheme = reinterpret_cast<THPQScheme*>(obj.ptr());
return static_cast<uint8_t>(qscheme->qscheme);
}
if (THPLayout_Check(obj.ptr())) {
auto layout = reinterpret_cast<THPLayout*>(obj.ptr());
return static_cast<int8_t>(layout->layout);
}
if (py::isinstance<py::int_>(obj)) {
return py::cast<int64_t>(obj);
} else if (py::isinstance<py::float_>(obj)) {
return py::cast<double>(obj);
} else if (PyComplex_CheckExact(obj.ptr())) {
auto c_obj = py::cast<std::complex<double>>(obj.ptr());
return static_cast<c10::complex<double>>(c_obj);
} else {
throw py::cast_error(
c10::str("Cannot cast ", py::str(obj), " to ", type->repr_str()));
}
}
case TypeKind::RRefType: {
#ifdef USE_RPC
return obj.cast<torch::distributed::rpc::PyRRef>().toIValue();
#else
AT_ERROR("RRef is only supported with the distributed package");
#endif
} break;
case TypeKind::PyObjectType: {
return c10::ivalue::ConcretePyObjectHolder::create(obj);
}
case TypeKind::CapsuleType: {
return IValue::make_capsule(py::cast<c10::Capsule>(obj).obj_ptr);
}
case TypeKind::FutureType: {
return obj.cast<std::shared_ptr<PythonFutureWrapper>>()->fut;
}
case TypeKind::AnyType:
return toTypeInferredIValue(obj);
case TypeKind::FunctionType:
case TypeKind::GeneratorType:
case TypeKind::StorageType:
case TypeKind::QuantizerType:
case TypeKind::VarType:
case TypeKind::QSchemeType:
case TypeKind::AnyListType:
case TypeKind::AnyTupleType:
case TypeKind::AnyClassType:
case TypeKind::AnyEnumType:
break;
case TypeKind::EnumType:
EnumTypePtr enum_type = type->expect<EnumType>();
py::object py_obj = py::reinterpret_borrow<py::object>(obj);
std::string name = py::cast<std::string>(obj.attr("name"));
IValue value = toIValue(obj.attr("value"), enum_type->getValueType(), {});
auto enum_holder =
c10::make_intrusive<c10::ivalue::EnumHolder>(enum_type, name, value);
return IValue(enum_holder);
}
throw py::cast_error(c10::str(
"toIValue() cannot handle converting to type: ", type->repr_str()));
}
} // namespace jit
} // namespace torch
|
//--------------------------------------------------------------------------------
// NVIDIA(R) GVDB VOXELS
// Copyright 2016-2018, NVIDIA Corporation.
//
// 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.
//
// Version 1.0: Rama Hoetzlein, 5/1/2017
// Version 1.1: Rama Hoetzlein, 3/25/2018
//----------------------------------------------------------------------------------
#include "gvdb_allocator.h"
#include "gvdb_volume_3D.h"
#include "gvdb_volume_gvdb.h"
#include "gvdb_render.h"
#include "gvdb_node.h"
#include "app_perf.h"
#include "string_helper.h"
#include "gvdb_cutils.cuh"
#include <algorithm>
#include <iostream>
#include <fstream>
#if !defined(_WIN32)
# include <GL/glx.h>
#endif
using namespace nvdb;
#define MAJOR_VERSION 1
#define MINOR_VERSION 11
// Version history
// GVDB 1.0 - First release. GTC'2017
// GVDB 1.0 - Incremental fixes, Beta pre-release.
// GVDB 1.1 - Second release. GTC'2018
// GVDB 1.1.1 - Bug Fixes
#define PUSH_CTX cuCtxPushCurrent(mContext);
#define POP_CTX CUcontext pctx; cuCtxPopCurrent(&pctx);
#define MRES 2048
#ifndef GVDB_CPU_VERSION
#define GVDB_CPU_VERSION 0
#endif
#ifdef BUILD_OPENVDB
#include <openvdb/tools/ValueTransformer.h>
#endif
Vector3DI VolumeGVDB::getVersion() {
return Vector3DI(MAJOR_VERSION, MINOR_VERSION, 0);
}
void VolumeGVDB::TimerStart () { PERF_START(); }
float VolumeGVDB::TimerStop () { return PERF_STOP(); }
VolumeGVDB::VolumeGVDB ()
{
TimeX start;
mDevice = NULL;
mContext = NULL;
mStream = NULL;
mPool = nullptr;
mScene = nullptr;
mV3D = 0x0;
mAtlasResize.Set ( 0, 20, 0 );
mEpsilon = 0.001f; // default epsilon
mMaxIter = 256; // default max iter
mApron = 1; // default apron
mbDebug = false;
// identity transform
SetTransform(Vector3DF(0, 0, 0), Vector3DF(1, 1, 1), Vector3DF(0, 0, 0), Vector3DF(0, 0, 0));
mRoot = ID_UNDEFL;
mbUseGLAtlas = false;
mVDBInfo.update = true;
mVDBInfo.clr_chan = CHAN_UNDEF;
mbProfile = false;
mbVerbose = false;
mDummyFrameBuffer = -1;
for (int n=0; n < 5; n++ ) cuModule[n] = (CUmodule) -1;
for (int n=0; n < MAX_FUNC; n++ ) cuFunc[n] = (CUfunction) -1;
for (int n=0; n < MAX_CHANNEL; n++ ) { mVDBInfo.volIn[n] = ID_UNDEFL; mVDBInfo.volOut[n] = ID_UNDEFL; }
for (int n=0; n < MAX_AUX; n++) {
mAux[n].lastEle = 0; mAux[n].usedNum = 0; mAux[n].max = 0; mAux[n].size = 0; mAux[n].stride = 0;
mAux[n].cpu = 0; mAux[n].gpu = 0;
}
mRendName[SHADE_VOXEL] = "SHADE_VOXEL";
mRendName[SHADE_SECTION2D] = "SHADE_SECTION2D";
mRendName[SHADE_SECTION3D] = "SHADE_SECTION3D";
mRendName[SHADE_EMPTYSKIP] = "SHADE_EMPTYSKIP";
mRendName[SHADE_TRILINEAR] = "SHADE_TRILINEAR";
mRendName[SHADE_TRICUBIC] = "SHADE_TRICUBIC";
mRendName[SHADE_LEVELSET] = "SHADE_LEVELSET";
mRendName[SHADE_VOLUME] = "SHADE_VOLUME";
mAuxName[AUX_PNTPOS] = "PNTPOS";
mAuxName[AUX_PNTCLR] = "PNTCLR";
mAuxName[AUX_PNODE] = "PNODE";
mAuxName[AUX_PNDX] = "PNDX";
mAuxName[AUX_GRIDCNT] = "GRIDCNT";
mAuxName[AUX_GRIDOFF] = "GRIDOFF";
mAuxName[AUX_ARRAY1] = "ARRAY1";
mAuxName[AUX_SCAN1] = "SCAN1";
mAuxName[AUX_ARRAY2] = "ARRAY2";
mAuxName[AUX_SCAN2] = "SCAN2";
mAuxName[AUX_COLAVG] = "COLAVG";
mAuxName[AUX_VOXELIZE] = "VOXELIZE";
mAuxName[AUX_VERTEX_BUF] = "VERTEX_BUF";
mAuxName[AUX_ELEM_BUF] = "ELEM_BUF";
mAuxName[AUX_TRI_BUF] = "TRI_BUF";
mAuxName[AUX_PNTSORT] = "PNTSORT";
mAuxName[AUX_PNTDIR] = "PNTDIR";
mAuxName[AUX_DATA2D] = "DATA2D";
mAuxName[AUX_DATA3D] = "DATA3D";
mAuxName[AUX_MATRIX4F] = "MATRIX4F";
mAuxName[AUX_PBRICKDX] = "PBRICKDX";
mAuxName[AUX_ACTIVBRICKCNT] = "ACTIVEBRICKCNT";
mAuxName[AUX_BRICK_LEVXYZ] = "BRICK_LEVXYZ";
mAuxName[AUX_RANGE_RES] = "RANGE_RES";
mAuxName[AUX_MARKER] = "MARKER";
mAuxName[AUX_RADIX_PRESCAN] = "RADIX_PRESCAN";
mAuxName[AUX_SORTED_LEVXYZ] = "SORTED_LEVXYZ";
mAuxName[AUX_TMP] = "TMP";
mAuxName[AUX_UNIQUE_CNT] = "UNIQUE_CNT";
mAuxName[AUX_MARKER_PRESUM] = "MARKER_PRESUM";
mAuxName[AUX_UNIQUE_LEVXYZ] = "UNIQUE_LEVXYZ";
mAuxName[AUX_LEVEL_CNT] = "LEVEL_CNT";
mAuxName[AUX_EXTRA_BRICK_CNT] = "EXTRA_BRICK_CNT";
mAuxName[AUX_NODE_MARKER] = "NODE_MARKER";
mAuxName[AUX_PNTVEL] = "PNTVEL";
mAuxName[AUX_DIV] = "DIV";
mAuxName[AUX_SUBCELL_CNT] = "SUBCELL_CNT";
mAuxName[AUX_SUBCELL_PREFIXSUM] = "SUBCELL_PREFIXSUM";
mAuxName[AUX_SUBCELL_PNTS] = "SUBCELL_PNTS";
mAuxName[AUX_SUBCELL_POS] = "SUBCELL_POS";
mAuxName[AUX_SUBCELL_PNT_POS] = "SUBCELL_PNT_POS";
mAuxName[AUX_SUBCELL_PNT_VEL] = "SUBCELL_PNT_VEL";
mAuxName[AUX_SUBCELL_PNT_CLR] = "SUBCELL_PNT_CLR";
mAuxName[AUX_BOUNDING_BOX] = "BOUNDING_BOX";
mAuxName[AUX_WORLD_POS_X] = "WORLD_POS_X";
mAuxName[AUX_WORLD_POS_Y] = "WORLD_POS_Y";
mAuxName[AUX_WORLD_POS_Z] = "WORLD_POS_Z";
mAuxName[AUX_VOLUME] = "VOLUME";
mAuxName[AUX_CG] = "CG";
mAuxName[AUX_INNER_PRODUCT] = "INNER_PRODUCT";
mAuxName[AUX_TEXTURE_MAX] = "TEXTURE_MAX";
mAuxName[AUX_TEXTURE_MAX_TMP] = "TEXTURE_MAX_TMP";
mAuxName[AUX_TEST] = "TEST";
mAuxName[AUX_TEST_1] = "TEST_1";
mAuxName[AUX_OUT1] = "OUT1";
mAuxName[AUX_OUT2] = "OUT2";
mAuxName[AUX_SUBCELL_MAPPING] = "SUBCELL_MAPPING";
mAuxName[AUX_SUBCELL_FLAG] = "SUBCELL_FLAG";
mAuxName[AUX_SUBCELL_NID] = "SUBCELL_NID";
mAuxName[AUX_SUBCELL_OBS_NID] = "SUBCELL_OBS_ND";
}
VolumeGVDB::~VolumeGVDB()
{
// Free the atlas
DestroyChannels();
// Free all auxiliary memory
CleanAux();
// Delete CUDA objects
if (cuVDBInfo != 0) {
cudaCheck(cuMemFree(cuVDBInfo), "VolumeGVDB", "~VolumeGVDB", "cuMemFree", "cuVDBInfo", mbDebug);
}
for (int n = 0; n < sizeof(cuModule)/sizeof(cuModule[0]); n++) {
if (cuModule[n] != (CUmodule)(-1)) {
cudaCheck(cuModuleUnload(cuModule[n]), "VolumeGVDB", "~VolumeGVDB", "cuModuleUnload", "cuModule[n]", mbDebug);
}
}
if (mV3D != 0) {
delete mV3D;
mV3D = 0;
}
// Free mTransferPtr
if (mPool != nullptr) {
mPool->FreeMemLinear(mTransferPtr);
// Tell mScene that its transfer function has been destroyed to avoid
// free-after-free
if (mScene != nullptr) {
mScene->mTransferFunc = nullptr;
}
}
if (mScene != nullptr) {
delete mScene;
mScene = 0;
}
// VolumeBase destructor called here
}
void VolumeGVDB::SetProfile ( bool bCPU, bool bGPU )
{
mbProfile = bCPU;
PERF_INIT ( 64, bCPU, bGPU, bCPU, 0, "" );
}
void VolumeGVDB::SetDebug ( bool d )
{
mbDebug = d;
if (mPool != 0x0) mPool->SetDebug(d);
}
// Loads a CUDA function into memory from ptx file
void VolumeGVDB::LoadFunction ( int fid, std::string func, int mid, std::string ptx )
{
char cptx[512]; strcpy ( cptx, ptx.c_str() );
char cfn[512]; strcpy ( cfn, func.c_str() );
if ( cuModule[mid] == (CUmodule) -1 )
cudaCheck ( cuModuleLoad ( &cuModule[mid], cptx ), "VolumeGVDB", "LoadFunction", "cuModuleLoad", cptx, mbDebug);
if ( cuFunc[fid] == (CUfunction) -1 )
cudaCheck ( cuModuleGetFunction ( &cuFunc[fid], cuModule[mid], cfn ), "VolumeGVDB", "LoadFunction", "cuModuleGetFunction", cfn, mbDebug);
}
// Set the current CUDA device, load all GVDB kernels
void VolumeGVDB::SetCudaDevice ( int devid, CUcontext ctx )
{
size_t len = 0;
mDevSelect = devid;
StartCuda(devid, ctx, mDevice, mContext, &mStream, mbVerbose );
PUSH_CTX
//--- Load cuda kernels
// Raytracing
LoadFunction ( FUNC_RAYDEEP, "gvdbRayDeep", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_RAYVOXEL, "gvdbRaySurfaceVoxel", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_RAYTRILINEAR, "gvdbRaySurfaceTrilinear", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_RAYTRICUBIC, "gvdbRaySurfaceTricubic", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_RAYSURFACE_DEPTH, "gvdbRaySurfaceDepth", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_RAYLEVELSET, "gvdbRayLevelSet", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_EMPTYSKIP, "gvdbRayEmptySkip", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_SECTION2D, "gvdbSection2D", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_SECTION3D, "gvdbSection3D", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_RAYTRACE, "gvdbRaytrace", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
// Sorting / Points / Triangles
LoadFunction ( FUNC_PREFIXSUM, "prefixSum", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_PREFIXFIXUP, "prefixFixup", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_INSERT_POINTS, "gvdbInsertPoints", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_SORT_POINTS, "gvdbSortPoints", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_SCATTER_DENSITY, "gvdbScatterPointDensity", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_SCATTER_AVG_COL, "gvdbScatterPointAvgCol", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_INSERT_TRIS, "gvdbInsertTriangles", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_SORT_TRIS, "gvdbSortTriangles", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_VOXELIZE, "gvdbVoxelize", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_RESAMPLE, "gvdbResample", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_REDUCTION, "gvdbReduction", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_DOWNSAMPLE, "gvdbDownsample", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_SCALE_PNT_POS, "gvdbScalePntPos", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_CONV_AND_XFORM, "gvdbConvAndTransform", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_ADD_SUPPORT_VOXEL, "gvdbAddSupportVoxel", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_INSERT_SUPPORT_POINTS, "gvdbInsertSupportPoints", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
// Topology
LoadFunction ( FUNC_FIND_ACTIV_BRICKS, "gvdbFindActivBricks", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_BITONIC_SORT, "gvdbBitonicSort", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_CALC_BRICK_ID, "gvdbCalcBrickId", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_RADIX_SUM, "RadixSum", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_RADIX_PREFIXSUM, "RadixPrefixSum", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_RADIX_SHUFFLE, "RadixAddOffsetsAndShuffle", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_FIND_UNIQUE, "gvdbFindUnique", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_COMPACT_UNIQUE, "gvdbCompactUnique", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_LINK_BRICKS, "gvdbLinkBricks", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
// Incremental Topology
LoadFunction ( FUNC_CALC_EXTRA_BRICK_ID,"gvdbCalcExtraBrickId", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_CALC_INCRE_BRICK_ID,"gvdbCalcIncreBrickId", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_CALC_INCRE_EXTRA_BRICK_ID,"gvdbCalcIncreExtraBrickId", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_DELINK_LEAF_BRICKS, "gvdbDelinkLeafBricks", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_DELINK_BRICKS, "gvdbDelinkBricks", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_MARK_LEAF_NODE, "gvdbMarkLeafNode", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
// Gathering
LoadFunction ( FUNC_COUNT_SUBCELL, "gvdbCountSubcell", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_INSERT_SUBCELL, "gvdbInsertSubcell", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_INSERT_SUBCELL_FP16,"gvdbInsertSubcell_fp16", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX);
LoadFunction ( FUNC_GATHER_DENSITY, "gvdbGatherDensity", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_GATHER_LEVELSET, "gvdbGatherLevelSet", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX);
LoadFunction ( FUNC_GATHER_LEVELSET_FP16, "gvdbGatherLevelSet_fp16", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX);
LoadFunction ( FUNC_CALC_SUBCELL_POS, "gvdbCalcSubcellPos", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_MAP_EXTRA_GVDB, "gvdbMapExtraGVDB", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_SPLIT_POS, "gvdbSplitPos", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_SET_FLAG_SUBCELL, "gvdbSetFlagSubcell", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_READ_GRID_VEL, "gvdbReadGridVel", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_CHECK_VAL, "gvdbCheckVal", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
// Apron Updates
LoadFunction ( FUNC_UPDATEAPRON_F, "gvdbUpdateApronF", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_UPDATEAPRON_F4, "gvdbUpdateApronF4", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_UPDATEAPRON_C, "gvdbUpdateApronC", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_UPDATEAPRON_C4, "gvdbUpdateApronC4", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_UPDATEAPRONFACES_F, "gvdbUpdateApronFacesF", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
// Operators
LoadFunction ( FUNC_FILL_F, "gvdbOpFillF", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_FILL_C, "gvdbOpFillC", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_FILL_C4, "gvdbOpFillC4", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_SMOOTH, "gvdbOpSmooth", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_NOISE, "gvdbOpNoise", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_CLR_EXPAND, "gvdbOpClrExpand", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
LoadFunction ( FUNC_EXPANDC, "gvdbOpExpandC", MODL_PRIMARY, CUDA_GVDB_MODULE_PTX );
SetModule ( cuModule[MODL_PRIMARY] );
POP_CTX
}
// Reset to default module
void VolumeGVDB::SetModule ()
{
SetModule ( cuModule[MODL_PRIMARY] );
}
// Set to a user-defined module (application)
void VolumeGVDB::SetModule ( CUmodule module )
{
PUSH_CTX
cudaCheck ( cuCtxSynchronize (), "VolumeGVDB", "SetModule", "cuCtxSynchronize", "", mbDebug);
ClearAtlasAccess ();
size_t len = 0;
cudaCheck ( cuModuleGetGlobal ( &cuScnInfo, &len, module, "scn" ), "VolumeGVDB", "SetModule", "cuModuleGetGlobal", "cuScnInfo", mbDebug);
cudaCheck ( cuModuleGetGlobal ( &cuXform, &len, module, "cxform" ), "VolumeGVDB", "SetModule", "cuModuleGetGlobal", "cuXform", mbDebug);
cudaCheck ( cuModuleGetGlobal ( &cuDebug, &len, module, "cdebug" ), "VolumeGVDB", "SetModule", "cuModuleGetGlobal", "cuDebug", mbDebug);
SetupAtlasAccess ();
POP_CTX
}
// Takes `inbuf`, a buffer of `cnt` Vector3DF objects (i.e. `3*cnt` floats),
// and writes the length of each vector into `outbuf`, a buffer of `cnt` floats.
// Sets vmin and vmax to the minimum and maximum lengths.
float* ConvertToScalar ( int cnt, float* inbuf, float* outbuf, float& vmin, float& vmax )
{
float* outv = outbuf;
Vector3DF* vec = (Vector3DF*) inbuf;
float val;
for ( int n=0; n < cnt; n++ ) {
val = static_cast<float>(vec->Length());
if ( val < vmin ) vmin = val;
if ( val > vmax ) vmax = val;
*outv++ = val;
vec++;
}
return outbuf;
}
// Simple Importer for ASCII VTK files
// - Only supports STRUCTURED_POINTS
bool VolumeGVDB::ImportVTK ( std::string fname, std::string field, Vector3DI& res )
{
PUSH_CTX
char buf[2048];
strcpy (buf, fname.c_str() );
FILE* fp = fopen ( buf, "rt" );
std::string lin, word;
bool bAscii = false;
float f;
float* vox = 0x0;
uint64 cnt = 0, max_cnt = 0;
char status = 'X';
verbosef ( "Loading VTK: %s\n", buf );
while ( !feof(fp) && status!='D' ) {
if ( fgets ( buf, 2048, fp ) == NULL ) break;
lin = std::string(buf);
word = strSplit ( lin, " \n" );
if ( word.compare("vtk")==0 ) continue;
if ( word.compare("ASCII")==0 ) {bAscii=true; continue;}
if ( word.compare("DATASET")==0 ) {
word = strSplit ( lin, " \n" );
if (word.compare("STRUCTURED_POINTS")==0) continue;
gprintf ( "ERROR: ImportVTK currently only supports STRUCTURED_POINTS\n" );
return false;
}
if ( word.compare("DIMENSIONS")==0 ) {
word = strSplit ( lin, " \n" ); strIsNum(word, f ); res.x = static_cast<int>(f-1);
word = strSplit ( lin, " \n" ); strIsNum(word, f ); res.y = static_cast<int>(f-1);
word = strSplit ( lin, " \n" ); strIsNum(word, f ); res.z = static_cast<int>(f-1);
verbosef ( " Res: %d, %d, %d\n", res.x, res.y, res.z );
PrepareAux ( AUX_DATA3D, res.x*res.y*res.z, sizeof(float), false, true );
vox = (float*) mAux[AUX_DATA3D].cpu;
continue;
}
if ( word.compare("FIELD")==0 ) {
// get next line
if ( fgets ( buf, 2048, fp ) == NULL ) break;
lin = std::string(buf);
word = strSplit ( lin, " \n" );
// if desired field is found, start reading
if ( word.compare ( field ) == 0 ) status = 'R';
word = strSplit ( lin, " \n" );
word = strSplit ( lin, " \n" ); strIsNum(word, f); max_cnt = static_cast<int>(f);
verbosef ( " Reading: %s, %ld\n", field.c_str(), max_cnt );
continue;
}
if ( word.compare("SPACING")==0 ) continue;
if ( word.compare("ORIGIN")==0 ) continue;
if ( word.compare("CELL_DATA")==0 ) continue;
if ( word.compare("SCALARS")==0 ) continue;
if ( word.compare("LOOKUP_TABLE")==0 ) continue;
if ( status=='R' ) {
while ( strIsNum(word, f) && !lin.empty() ) {
*vox++ = f;
word = strSplit( lin, " \n" );
}
cnt = static_cast<uint64>(vox - (float*) mAux[AUX_DATA3D].cpu);
if ( cnt >= max_cnt) status = 'D'; // done
}
}
verbosef ( " Values Read: %d\n", cnt );
// Commit data to GPU
CommitData ( mAux[AUX_DATA3D] );
POP_CTX
return true;
}
void VolumeGVDB::ConvertBitmaskToNonBitmask( int levs )
{
Node* node;
uint64* clist;
uint64 childid;
// uint32 cnt;
uint32 ndx;
uint64 ccnt, cmax, btchk;
// Activate all bricks (assuming earlier file did not use flags)
for (int n = 0; n < getNumTotalNodes(0); n++) {
node = getNode(0, 0, n);
node->mFlags = 1;
}
// Convert upper nodes to non-bitmask
for (int lv = 1; lv < levs; lv++) {
for (int n = 0; n < getNumTotalNodes(lv); n++) {
node = getNode(0, lv, n);
if (node->mChildList == ID_UNDEFL) {
gprintf("ERROR: ConvertBitmaskToNonBitmask, child list is null.\n");
gerror();
}
// number of children
ccnt = getNumChild( node );
cmax = getVoxCnt( node->mLev );
clist = mPool->PoolData64( node->mChildList );
// pad remainder of child list with ID_UNDEFL
memset(clist + ccnt, 0xFF, sizeof(uint64)*(cmax - ccnt));
// move children into index locations
for (int64_t j = static_cast<int64_t>(ccnt-1); j >=0; j--) {
ndx = countToIndex(node, j);
btchk = countOn(node, ndx);
if (btchk != j) {
gprintf("ERROR: countToIndex error.\n");
gerror();
}
childid = *(clist + j); // get child
*(clist + ndx) = childid; // put child
*(clist + j) = ID_UNDEF64;
}
}
}
}
// Load a VBX file
bool VolumeGVDB::LoadVBX(const std::string fname, int force_maj, int force_min)
{
// See GVDB_FILESPEC.txt for the specification of the VBX file format.
PUSH_CTX
FILE* fp = fopen(fname.c_str(), "rb");
if (fp == 0x0) {
gprintf("Error: Unable to open file %s\n", fname.c_str());
return false;
}
PERF_PUSH("Read VBX");
// Read VBX config
uchar major, minor;
int num_grids;
const int grid_name_len = 256; // Length of grid_name
char grid_name[grid_name_len];
char grid_components;
char grid_dtype;
char grid_compress;
char grid_topotype;
int grid_reuse;
char grid_layout;
int leafcnt;
int num_chan;
Vector3DI leafdim;
int apron;
Vector3DI axiscnt;
Vector3DI axisres;
Vector3DF voxelsize_deprecated;
slong atlas_sz;
int levels;
uint64 root;
Vector3DI range[MAXLEV];
int ld[MAXLEV], res[MAXLEV];
int cnt0[MAXLEV], cnt1[MAXLEV];
int width0[MAXLEV]{}, width1[MAXLEV];
std::vector<uint64> grid_offs;
//--- VBX file header
fread (&major, sizeof(uchar), 1, fp); // major version
fread (&minor, sizeof(uchar), 1, fp); // minor version
if (force_maj > 0 || force_min > 0) {
major = force_maj;
minor = force_min;
}
verbosef("LoadVBX: %s (ver %d.%d)\n", fname.c_str(), major, minor );
verbosef("Sizes: char %d, int %d, u64 %d, float %d\n", sizeof(char), sizeof(int), sizeof(uint64), sizeof(float));
if ((major == 1 && minor >= 11) || major > 1) {
// GVDB >=1.11+ saves grid transforms (GVDB 1.1 and earlier do not)
fread( &mPretrans, sizeof(float), 3, fp);
fread( &mAngs, sizeof(float), 3, fp);
fread( &mScale, sizeof(float), 3, fp);
fread( &mTrans, sizeof(float), 3, fp);
SetTransform(mPretrans, mScale, mAngs, mTrans); // set grid transform
}
fread ( &num_grids, sizeof(int), 1, fp ); // number of grids
// bitmask info
uchar use_masks = 0; // Whether the read volume should use bitmasks
#ifdef USE_BITMASKS
use_masks = 1;
#endif
uchar read_masks = 0; // Whether the VBX file uses bitmasks
if (major >= 2) {
// GVDB >= 2, bitmasks optional
fread(&read_masks, sizeof(uchar), 1, fp);
}
else if (major == 1 && minor == 0) {
// GVDB 1.0 always uses bitmasks
read_masks = 1;
}
//--- grid offset table
for (int n=0; n < num_grids; n++ ) {
grid_offs.push_back(0);
fread ( &grid_offs[n], sizeof(uint64), 1, fp ); // grid offsets
}
for (int n = 0; n < num_grids; n++) {
//---- grid header
fread(&grid_name, 256, 1, fp); // grid name
fread(&grid_dtype, sizeof(uchar), 1, fp); // grid data type
fread(&grid_components, sizeof(uchar), 1, fp); // grid components
fread(&grid_compress, sizeof(uchar), 1, fp); // grid compression (0=none, 1=blosc, 2=..)
fread(&voxelsize_deprecated, sizeof(float), 3, fp); // voxel size
fread(&leafcnt, sizeof(int), 1, fp); // total brick count
fread(&leafdim.x, sizeof(int), 3, fp); // brick dimensions
fread(&apron, sizeof(int), 1, fp); // brick apron
fread(&num_chan, sizeof(int), 1, fp); // number of channels
fread(&atlas_sz, sizeof(uint64), 1, fp); // total atlas size (all channels)
fread(&grid_topotype, sizeof(uchar), 1, fp); // topology type? (0=none, 1=reuse, 2=gvdb, 3=..)
fread(&grid_reuse, sizeof(int), 1, fp); // topology reuse
fread(&grid_layout, sizeof(uchar), 1, fp); // brick layout? (0=atlas, 1=brick)
fread(&axiscnt.x, sizeof(int), 3, fp); // atlas brick count
fread(&axisres.x, sizeof(int), 3, fp); // atlas res
//---- topology section
fread(&levels, sizeof(int), 1, fp); // num levels
fread(&root, sizeof(uint64), 1, fp); // root id
for (int n = 0; n < levels; n++) {
fread(&ld[n], sizeof(int), 1, fp);
fread(&res[n], sizeof(int), 1, fp);
fread(&range[n].x, sizeof(int), 1, fp);
fread(&range[n].y, sizeof(int), 1, fp);
fread(&range[n].z, sizeof(int), 1, fp);
fread(&cnt0[n], sizeof(int), 1, fp);
fread(&width0[n], sizeof(int), 1, fp);
fread(&cnt1[n], sizeof(int), 1, fp);
fread(&width1[n], sizeof(int), 1, fp);
}
if (width0[0] != sizeof(nvdb::Node)) {
gprintf("ERROR: VBX file contains nodes incompatible with current gvdb_library.\n");
gprintf(" Size in file: %d, Size in library: %d\n", width0[0], sizeof(nvdb::Node));
gerror();
}
// Initialize GVDB
Configure ( levels, ld, cnt0, (read_masks==1) );
mRoot = root; // must be set after initialize
// Read topology
for (int n=0; n < levels; n++ ) {
mPool->PoolRead(fp, 0, n, cnt0[n], width0[n]);
}
for (int n = 0; n < levels; n++) {
mPool->PoolRead(fp, 1, n, cnt1[n], width1[n]);
}
if (read_masks==1 && use_masks==0) {
// Convert bitmasks to non-bitmasks
ConvertBitmaskToNonBitmask( levels );
}
FinishTopology ();
// Atlas section
DestroyChannels ();
// Read atlas into GPU slice-by-slice to conserve CPU and GPU mem
for (int chan = 0 ; chan < num_chan; chan++ ) {
int chan_type, chan_stride;
fread ( &chan_type, sizeof(int), 1, fp );
fread ( &chan_stride, sizeof(int), 1, fp );
AddChannel ( chan, chan_type, apron, F_LINEAR, F_BORDER, axiscnt ); // provide axiscnt
mPool->AtlasSetNum ( chan, cnt0[0] ); // assumes atlas contains all bricks (all are resident)
DataPtr slice;
mPool->CreateMemLinear ( slice, 0x0, chan_stride, axisres.x*axisres.y, true );
for (int z = 0; z < axisres.z; z++ ) {
fread ( slice.cpu, slice.size, 1, fp );
mPool->AtlasWriteSlice ( chan, z, static_cast<int>(slice.size),
slice.gpu, (uchar*) slice.cpu ); // transfer from GPU, directly into CPU atlas
}
mPool->FreeMemLinear ( slice );
}
UpdateAtlas ();
}
PERF_POP ();
POP_CTX
return true;
}
// Set the current color channel for rendering
void VolumeGVDB::SetColorChannel ( uchar chan )
{
mVDBInfo.clr_chan = chan;
mVDBInfo.update = true;
}
void VolumeGVDB::AtlasRetrieveBrickXYZ(uchar channel, Vector3DI minimumCorner, DataPtr& dest) {
mPool->AtlasRetrieveTexXYZ(channel, minimumCorner, dest);
}
// Clear device access to atlases
void VolumeGVDB::ClearAtlasAccess ()
{
if ( mPool==0x0 ) return;
PUSH_CTX
int num_chan = mPool->getNumAtlas();
for (int chan=0; chan < num_chan; chan++ ) {
if ( mVDBInfo.volIn[chan] != ID_UNDEFL ) {
cudaCheck ( cuTexObjectDestroy (mVDBInfo.volIn[chan] ), "VolumeGVDB", "ClearAtlasAccess", "cuTexObjectDestroy", "volIn", mbDebug);
mVDBInfo.volIn[chan] = ID_UNDEFL;
}
if (mVDBInfo.volOut[chan] != ID_UNDEFL ) {
cudaCheck ( cuSurfObjectDestroy (mVDBInfo.volOut[chan] ), "VolumeGVDB", "ClearAtlasAccess", "cuSurfObjectDestroy", "volOut", mbDebug);
mVDBInfo.volIn[chan] = ID_UNDEFL;
}
}
cudaCheck ( cuCtxSynchronize (), "VolumeGVDB", "ClearAtlasAccess", "cuCtxSynchronize", "", mbDebug);
POP_CTX
}
// Setup device access to atlases
void VolumeGVDB::SetupAtlasAccess ()
{
if ( mPool == 0x0 ) return;
if ( mPool->getNumAtlas() == 0 ) return;
PUSH_CTX
DataPtr atlas;
//-- Texture Access using CUDA Bindless
int num_chan = mPool->getNumAtlas();
char chanmsg[256];
for (int chan=0; chan < num_chan; chan++ ) {
atlas = mPool->getAtlas(chan );
sprintf( chanmsg, "chan %d", chan);
CUDA_RESOURCE_DESC resDesc;
memset ( &resDesc, 0, sizeof(resDesc) );
resDesc.resType = CU_RESOURCE_TYPE_ARRAY;
if ( atlas.grsc != 0x0 ) {
cudaCheck ( cuGraphicsMapResources(1, &atlas.grsc, mStream), "VolumeGVDB", "SetupAtlasAccess", "cuGraphicsMapResource", chanmsg, mbDebug);
cudaCheck ( cuGraphicsSubResourceGetMappedArray ( &atlas.garray, atlas.grsc, 0, 0 ), "VolumeGVDB", "SetupAtlasAccess", "cuGraphicsSubResourceGetMappedArray", chanmsg, mbDebug);
}
resDesc.res.array.hArray = atlas.garray;
resDesc.flags = 0;
CUDA_TEXTURE_DESC texDesc;
memset ( &texDesc, 0, sizeof(texDesc) );
// filter mode
switch ( atlas.filter ) {
case F_POINT: texDesc.filterMode = CU_TR_FILTER_MODE_POINT;break;
case F_LINEAR: texDesc.filterMode = CU_TR_FILTER_MODE_LINEAR; break;
};
// read mode
switch ( atlas.type ) {
case T_FLOAT: case T_FLOAT3: case T_FLOAT4:
texDesc.flags = 0;
break;
case T_UCHAR: case T_UCHAR3: case T_UCHAR4: case T_INT: case T_INT3: case T_INT4:
texDesc.flags = CU_TRSF_READ_AS_INTEGER;
break;
};
// border mode
switch ( atlas.border ) {
case F_BORDER:
texDesc.addressMode[0] = CU_TR_ADDRESS_MODE_BORDER;
texDesc.addressMode[1] = CU_TR_ADDRESS_MODE_BORDER;
texDesc.addressMode[2] = CU_TR_ADDRESS_MODE_BORDER;
break;
case F_CLAMP:
texDesc.addressMode[0] = CU_TR_ADDRESS_MODE_CLAMP;
texDesc.addressMode[1] = CU_TR_ADDRESS_MODE_CLAMP;
texDesc.addressMode[2] = CU_TR_ADDRESS_MODE_CLAMP;
break;
case F_WRAP:
texDesc.addressMode[0] = CU_TR_ADDRESS_MODE_WRAP;
texDesc.addressMode[1] = CU_TR_ADDRESS_MODE_WRAP;
texDesc.addressMode[2] = CU_TR_ADDRESS_MODE_WRAP;
break;
};
if ( mVDBInfo.volIn[chan] != ID_UNDEFL ) {
cudaCheck ( cuTexObjectDestroy ( mVDBInfo.volIn[chan] ), "VolumeGVDB", "SetupAtlasAccess", "cuTexObjectDestroy", chanmsg, mbDebug);
mVDBInfo.volIn[ chan ] = ID_UNDEFL;
}
if ( mVDBInfo.volOut[chan] != ID_UNDEFL ) {
cudaCheck ( cuSurfObjectDestroy ( mVDBInfo.volOut[chan] ), "VolumeGVDB", "SetupAtlasAccess", "cuSurfObjectDestroy", chanmsg, mbDebug);
mVDBInfo.volOut[ chan ] = ID_UNDEFL;
}
cudaCheck ( cuTexObjectCreate ( &mVDBInfo.volIn[chan], &resDesc, &texDesc, NULL ), "VolumeGVDB", "SetupAtlasAccess", "cuTexObjectCreate", chanmsg, mbDebug);
cudaCheck ( cuSurfObjectCreate ( &mVDBInfo.volOut[chan], &resDesc ), "VolumeGVDB", "SetupAtlasAccess", "cuSurfObjectCreate", chanmsg, mbDebug);
if ( atlas.grsc != 0x0 )
cudaCheck ( cuGraphicsUnmapResources(1, &atlas.grsc, mStream), "VolumeGVDB", "SetupAtlasAccess", "cuGraphicsUnmapResources", chanmsg, mbDebug);
}
// Require VDBInfo update
mVDBInfo.update = true;
POP_CTX
}
//////////////////////////////////////////////////////////////////////////
void VolumeGVDB::ClearPoolCPU()
{
PUSH_CTX
mPool->PoolClearCPU();
POP_CTX
}
void VolumeGVDB::FetchPoolCPU()
{
PUSH_CTX
mPool->PoolFetchAll();
POP_CTX
}
int VolumeGVDB::DetermineDepth( Vector3DI& pos)
{
// looking for certain level that one brick can contain the bounding box
Vector3DI range, posMin, posMax;
for (int lev = 0; lev < MAXLEV; lev++)
{
posMin = GetCoveringNode ( lev, mPosMin, range );
posMax = GetCoveringNode ( lev, mPosMax, range );
if (posMin.x == posMax.x && posMin.y == posMax.y && posMin.z == posMax.z) {
pos = posMin;
return lev;
}
}
return -1;
}
bool pairCompare(std::pair<int, int> firstElem, std::pair<int, int> secondElem) {
return firstElem.first < secondElem.first;
}
void VolumeGVDB::FindUniqueBrick(int pNumPnts, int pLevDepth, int& pNumUniqueBrick)
{
PERF_PUSH ("Find unique");
int numPnts = pNumPnts;
int threads = 512;
int pblks = int(numPnts / threads)+1;
PrepareAux ( AUX_MARKER, numPnts, sizeof(int), true);
PrepareAux ( AUX_MARKER_PRESUM, numPnts, sizeof(int), true);
PrepareAux ( AUX_UNIQUE_CNT, 1, sizeof(int), true);
PrepareAux ( AUX_LEVEL_CNT, pLevDepth, sizeof(int), true);
PUSH_CTX
void* argsFindUnique[5] = { &numPnts, &mAux[AUX_SORTED_LEVXYZ].gpu, &mAux[AUX_MARKER].gpu, &mAux[AUX_UNIQUE_CNT].gpu, &mAux[AUX_LEVEL_CNT].gpu};
cudaCheck ( cuLaunchKernel ( cuFunc[FUNC_FIND_UNIQUE],
pblks, 1, 1, threads, 1, 1, 0, NULL, argsFindUnique, NULL ), "VolumeGVDB", "FindUniqueBrick", "cuLaunch", "FUNC_FIND_UNIQUE", mbDebug);
cudaCheck ( cuMemcpyDtoH ( &pNumUniqueBrick, mAux[AUX_UNIQUE_CNT].gpu, sizeof(int) ), "VolumeGVDB", "FindUniqueBrick", "cuMemcpyDtoH", "AUX_UNIQUE_CNT", mbDebug);
PrefixSum(mAux[AUX_MARKER].gpu, mAux[AUX_MARKER_PRESUM].gpu, numPnts);
PrepareAux ( AUX_UNIQUE_LEVXYZ, pNumUniqueBrick, sizeof(long long), false);
void* argsCompactUnique[5] = { &numPnts, &mAux[AUX_SORTED_LEVXYZ].gpu, &mAux[AUX_MARKER].gpu, &mAux[AUX_MARKER_PRESUM].gpu, &mAux[AUX_UNIQUE_LEVXYZ].gpu};
cudaCheck ( cuLaunchKernel ( cuFunc[FUNC_COMPACT_UNIQUE],
pblks, 1, 1, threads, 1, 1, 0, NULL, argsCompactUnique, NULL ), "VolumeGVDB", "FindUniqueBrick", "cuLaunch", "FUNC_COMPACT_UNIQUE", mbDebug );
PERF_POP ();
POP_CTX
}
static const int NUM_SMS = 16;
static const int NUM_THREADS_PER_SM = 192;
static const int NUM_THREADS_PER_BLOCK = 64;
//static const int NUM_THREADS = NUM_THREADS_PER_SM * NUM_SMS;
static const int NUM_BLOCKS = (NUM_THREADS_PER_SM / NUM_THREADS_PER_BLOCK) * NUM_SMS;
static const int RADIX = 8; // Number of bits per radix sort pass
static const int RADICES = 1 << RADIX; // Number of radices
static const int RADIXMASK = RADICES - 1; // Mask for each radix sort pass
static const int RADIXBITS = 64; // Number of bits to sort over
static const int RADIXTHREADS = 16; // Number of threads sharing each radix counter
static const int RADIXGROUPS = NUM_THREADS_PER_BLOCK / RADIXTHREADS; // Number of radix groups per CTA
static const int TOTALRADIXGROUPS = NUM_BLOCKS * RADIXGROUPS; // Number of radix groups for each radix
static const int SORTRADIXGROUPS = TOTALRADIXGROUPS * RADICES; // Total radix count
static const int GRFELEMENTS = (NUM_THREADS_PER_BLOCK / RADIXTHREADS) * RADICES;
static const int GRFSIZE = GRFELEMENTS * sizeof(uint);
// Prefix sum variables
static const int PREFIX_NUM_THREADS_PER_SM = NUM_THREADS_PER_SM;
static const int PREFIX_NUM_THREADS_PER_BLOCK = PREFIX_NUM_THREADS_PER_SM;
static const int PREFIX_NUM_BLOCKS = (PREFIX_NUM_THREADS_PER_SM / PREFIX_NUM_THREADS_PER_BLOCK) * NUM_SMS;
static const int PREFIX_BLOCKSIZE = SORTRADIXGROUPS / PREFIX_NUM_BLOCKS;
static const int PREFIX_GRFELEMENTS = PREFIX_BLOCKSIZE + 2 * PREFIX_NUM_THREADS_PER_BLOCK;
static const int PREFIX_GRFSIZE = PREFIX_GRFELEMENTS * sizeof(uint);
// Shuffle variables
static const int SHUFFLE_GRFOFFSET = RADIXGROUPS * RADICES;
static const int SHUFFLE_GRFELEMENTS = SHUFFLE_GRFOFFSET + PREFIX_NUM_BLOCKS;
static const int SHUFFLE_GRFSIZE = SHUFFLE_GRFELEMENTS * sizeof(uint);
void VolumeGVDB::RadixSortByByte(int pNumPnts, int pLevDepth)
{
PUSH_CTX
PERF_PUSH("Radix sort");
int numPnts = pNumPnts;
int threads = 512;
int pblks = int(numPnts / threads)+1;
int length = pNumPnts * 4;
PrepareAux ( AUX_SORTED_LEVXYZ, pNumPnts * 4, sizeof(unsigned short), false);
cudaCheck ( cuMemcpyDtoD (mAux[AUX_SORTED_LEVXYZ].gpu, mAux[AUX_BRICK_LEVXYZ].gpu, length * sizeof(unsigned short) ),
"VolumeGVDB", "RadixSortByByte", "cuMemcpyDtoD", "AUX_SORTED_LEVXYZ", mbDebug);
// gvdbDeviceRadixSort takes a pointer to memory interpreted as 64-bit
// integers, and the number of 64-bit integers in the array.
gvdbDeviceRadixSort(mAux[AUX_SORTED_LEVXYZ].gpu, pNumPnts);
PERF_POP();
POP_CTX
}
void VolumeGVDB::ActivateExtraBricksGPU(int pNumPnts, float pRadius, Vector3DF pOrig, int pRootLev, Vector3DI pRootPos)
{
PERF_PUSH("Extra node");
int threads = 512;
int pblks = int(pNumPnts / threads)+1;
PrepareAux ( AUX_BRICK_LEVXYZ, pNumPnts * pRootLev * 4, sizeof(unsigned short), true );
PrepareAux ( AUX_EXTRA_BRICK_CNT, 1, sizeof(int), true, true);
PUSH_CTX
void* argsCalcExtraLevXYZ[11] = { &cuVDBInfo, &pRadius,
&pNumPnts, &pRootLev, &mAux[AUX_RANGE_RES].gpu,
&mAux[AUX_PNTPOS].gpu, &mAux[AUX_PNTPOS].subdim.x, &mAux[AUX_PNTPOS].stride,
&pOrig.x, &mAux[AUX_BRICK_LEVXYZ].gpu, &mAux[AUX_EXTRA_BRICK_CNT].gpu};
cudaCheck ( cuLaunchKernel ( cuFunc[FUNC_CALC_EXTRA_BRICK_ID],
pblks, 1, 1, threads, 1, 1, 0, NULL, argsCalcExtraLevXYZ, NULL ), "VolumeGVDB", "ActivateExtraBricksGPU", "cuLaunch", "FUNC_CALC_EXTRA_BRICK_ID", mbDebug);
RetrieveData(mAux[AUX_EXTRA_BRICK_CNT]);
int* extraNodeNum = (int *)mAux[AUX_EXTRA_BRICK_CNT].cpu;
int numUniqueExtraBrick = 0;
RadixSortByByte(extraNodeNum[0], pRootLev);
FindUniqueBrick(extraNodeNum[0], pRootLev, numUniqueExtraBrick);
PERF_PUSH ( "Create pool (CPU)");
int* extraLevCnt = (int*) malloc ( pRootLev * sizeof(int) );
cudaCheck ( cuMemcpyDtoH ( extraLevCnt, mAux[AUX_LEVEL_CNT].gpu, pRootLev * sizeof(int) ), "VolumeGVDB", "ActivateExtraBricksGPU", "cuMemcpyDtoH", "AUX_LEVEL_CNT", mbDebug);
unsigned short* extraUniBricks = (unsigned short*) malloc ( numUniqueExtraBrick * 4 * sizeof(unsigned short) );
cudaCheck ( cuMemcpyDtoH ( extraUniBricks, mAux[AUX_UNIQUE_LEVXYZ].gpu, numUniqueExtraBrick * 4 * sizeof(unsigned short) ), "VolumeGVDB", "ActivateExtraBricksGPU", "cuMemcpyDtoH", "AUX_UNIQUE_LEVXYZ", mbDebug);
int extraLevPrefixSum = 0;
for (int lev = 0; lev < pRootLev; lev++)
{
int r = getRes(lev);
uint64 childlistLen = ((uint64) r*r*r);
Vector3DI brickRange = getRange(lev);
for (int n = extraLevPrefixSum; n < extraLevCnt[lev]+extraLevPrefixSum; n++)
{
uint64 nodeID = mPool->PoolAlloc ( 0, lev, true );
SetupNode ( nodeID, lev, Vector3DI( extraUniBricks[n * 4 + 2] * brickRange.x,
extraUniBricks[n * 4 + 1] * brickRange.y,
extraUniBricks[n * 4 + 0] * brickRange.z));
if (lev > 0)
{
Node* nd = getNode(nodeID);
nd->mChildList = mPool->PoolAlloc ( 1, lev, true );
uint64* clist = mPool->PoolData64 ( nd->mChildList );
memset(clist, 0xFF, sizeof(uint64) * childlistLen);
}
}
extraLevPrefixSum += extraLevCnt[lev];
}
PERF_POP();
PERF_PUSH ( "Commit");
mPool->PoolCommitAll();
PERF_POP ();
PERF_PUSH ( "PrepPartial");
PrepareVDBPartially();
PERF_POP ();
PERF_PUSH ( "Link node");
for (int lev = pRootLev-1; lev >= 0; lev--)
{
//std::cout << "link " << lev << std::endl;
pblks = int(mPool->getPoolTotalCnt(0,lev)/ threads)+1;
void* argsLink[2] = { &cuVDBInfo, &lev};
cudaCheck ( cuLaunchKernel ( cuFunc[FUNC_LINK_BRICKS],
pblks, 1, 1, threads, 1, 1, 0, NULL, argsLink, NULL ), "VolumeGVDB", "ActivateExtraBricksGPU", "cuLaunch", "FUNC_LINK_BRICKS", mbDebug);
}
PERF_POP();
PERF_PUSH ( "FetchAll");
mPool->PoolFetchAll();
PERF_POP();
POP_CTX
PERF_POP();
}
int Incre_ratio = 1; // assume only 10% new points need to be sorted
void VolumeGVDB::ActivateIncreBricksGPU(int pNumPnts, float pRadius, Vector3DF pOrig, int pRootLev, Vector3DI pRootPos, bool bAccum)
{
if (getNumTotalNodes(0) == 0) return;
PUSH_CTX
PERF_PUSH("Incremental node");
// mark all leaf node deactivated
int totalLeafNodeCnt = static_cast<int>(getNumTotalNodes(0));
PrepareAux ( AUX_NODE_MARKER, totalLeafNodeCnt, sizeof(int), false, true);
//--- Accumulate topology (OPTIONAL)
int* marker = (int*) mAux[AUX_NODE_MARKER].cpu;
if ( bAccum ) {
// mark existing nodes active, preserves previous brick topology
for (int ni=0; ni < totalLeafNodeCnt; ni++ ) {
*marker++ = getNode(0,0, ni)->mFlags;
}
} else {
// mark all deactivated (default behavior)
memset ( marker, 0, totalLeafNodeCnt*sizeof(int) );
}
CommitData ( mAux[AUX_NODE_MARKER] );
//---
int threads = 512;
int pblks = int(pNumPnts / threads)+1;
PrepareAux ( AUX_BRICK_LEVXYZ, pNumPnts * pRootLev * 4 / Incre_ratio, sizeof(unsigned short), true );
PrepareAux ( AUX_EXTRA_BRICK_CNT, 1, sizeof(int), true, true);
void* argsCalcExtraLevXYZ[12] = { &cuVDBInfo, &pRadius,
&pNumPnts, &pRootLev, &mAux[AUX_RANGE_RES].gpu,
&mAux[AUX_PNTPOS].gpu, &mAux[AUX_PNTPOS].subdim.x, &mAux[AUX_PNTPOS].stride,
&pOrig.x, &mAux[AUX_BRICK_LEVXYZ].gpu, &mAux[AUX_EXTRA_BRICK_CNT].gpu,
&mAux[AUX_NODE_MARKER].gpu,
};
cudaCheck ( cuLaunchKernel ( cuFunc[FUNC_CALC_INCRE_EXTRA_BRICK_ID], pblks, 1, 1, threads, 1, 1, 0, NULL, argsCalcExtraLevXYZ, NULL ),
"VolumeGVDB", "ActivateIncreBricksGPU", "cuLaunch", "FUNC_CALC_INCRE_EXTRA_BRICK_ID", mbDebug);
RetrieveData(mAux[AUX_EXTRA_BRICK_CNT]);
int* extraNodeNum = (int *)mAux[AUX_EXTRA_BRICK_CNT].cpu;
if (extraNodeNum[0] == 0) { POP_CTX; PERF_POP(); return; } // no new node, then return
int numUniqueExtraBrick = 0;
RadixSortByByte(extraNodeNum[0], pRootLev);
FindUniqueBrick(extraNodeNum[0], pRootLev, numUniqueExtraBrick);
int* extraLevCnt = new int[pRootLev];
cudaCheck ( cuMemcpyDtoH ( extraLevCnt, mAux[AUX_LEVEL_CNT].gpu, pRootLev * sizeof(int) ), "VolumeGVDB", "ActivateIncreBricksGPU", "cuMemcpyDtoH", "AUX_LEVEL_CNT", mbDebug);
unsigned short* extraUniBricks = new unsigned short[numUniqueExtraBrick * 4];
cudaCheck ( cuMemcpyDtoH ( extraUniBricks, mAux[AUX_UNIQUE_LEVXYZ].gpu, numUniqueExtraBrick * 4 * sizeof(unsigned short) ), "VolumeGVDB", "ActivateIncreBricksGPU", "cuMemcpyDtoH", "AUX_UNIQUE_LEVXYZ", mbDebug);
PERF_PUSH ( "Update markers (CPU)");
RetrieveData ( mAux[AUX_NODE_MARKER] );
marker = (int*) mAux[AUX_NODE_MARKER].cpu;
for (int ni = 0; ni < totalLeafNodeCnt; ni++) {
getNode(0,0,ni)->mFlags = *marker++;
}
PERF_POP ();
PERF_PUSH ( "Allocate pool (CPU)");
int extraLevPrefixSum = 0;
for (int lev = 0; lev < pRootLev; lev++)
{
int r = getRes(lev);
uint64 childlistLen = ((uint64) r*r*r);
Vector3DI brickRange = getRange(lev);
for (int n = extraLevPrefixSum; n < extraLevCnt[lev]+extraLevPrefixSum; n++)
{
// Allocate new node
// - preserve existing on expand
// - marker is set to 1 (active)
uint64 nodeID = mPool->PoolAlloc ( 0, lev, true );
SetupNode ( nodeID, lev, Vector3DI( extraUniBricks[n * 4 + 2] * brickRange.x, extraUniBricks[n * 4 + 1] * brickRange.y, extraUniBricks[n * 4 + 0] * brickRange.z));
if (lev > 0) // alloc childlist for nodes except leaf nodes
{
Node* nd = getNode(nodeID);
nd->mChildList = mPool->PoolAlloc ( 1, lev, true );
uint64* clist = mPool->PoolData64 ( nd->mChildList );
memset(clist, 0xFF, sizeof(uint64) * childlistLen);
}
}
extraLevPrefixSum += extraLevCnt[lev];
}
PERF_POP ();
mPool->PoolCommitAll();
// Commit all existing and new nodes, including marker data
PERF_PUSH ( "PrepPartial");
PrepareVDBPartially();
PERF_POP ();
// link - top down
pblks = int(getNumTotalNodes(0) / threads)+1;
PERF_PUSH ( "Link node");
for (int lev = pRootLev - 1; lev >= 0; lev--)
{
void* argsLink[2] = { &cuVDBInfo, &lev};
cudaCheck ( cuLaunchKernel ( cuFunc[FUNC_LINK_BRICKS], pblks, 1, 1, threads, 1, 1, 0, NULL, argsLink, NULL ), "VolumeGVDB", "ActivateIncreBricksGPU", "cuLaunch", "FUNC_LINK_BRICKS", mbDebug);
}
PERF_POP();
// delink - bottom up
PERF_PUSH ( "Delink node");
void* argsDelinkLeaf[1] = { &cuVDBInfo};
cudaCheck ( cuLaunchKernel ( cuFunc[FUNC_DELINK_LEAF_BRICKS], pblks, 1, 1, threads, 1, 1, 0, NULL, argsDelinkLeaf, NULL ), "VolumeGVDB", "ActivateIncreBricksGPU", "cuLaunch", "FUNC_DELINK_LEAF_BRICKS", mbDebug);
for (int lev = 1; lev < pRootLev; lev++)
{
void* argsDelink[2] = { &cuVDBInfo, &lev};
cudaCheck ( cuLaunchKernel ( cuFunc[FUNC_DELINK_BRICKS], pblks, 1, 1, threads, 1, 1, 0, NULL, argsDelink, NULL ), "VolumeGVDB", "ActivateIncreBricksGPU", "cuLaunch", "FUNC_DELINK_BRICKS", mbDebug);
}
PERF_POP();
mPool->PoolFetchAll();
PERF_PUSH ( "UpdateUsed");
uint64 usedNum = mPool->getPoolTotalCnt(0,0);
for (int ni = 0; ni < mPool->getPoolTotalCnt(0,0); ni++) if(!getNode(0,0,ni)->mFlags) usedNum--;
mPool->SetPoolUsedCnt(0,0,usedNum);
PERF_POP();
delete[] extraLevCnt;
delete[] extraUniBricks;
PERF_POP();
POP_CTX
}
void VolumeGVDB::AccumulateTopology(int pNumPnts, float pRadius, Vector3DF pOrig, int iDepth )
{
GetBoundingBox(pNumPnts, pOrig);
Vector3DI rootPos;
int depth = DetermineDepth(rootPos);
if ( depth < iDepth ) depth = iDepth; // min depth
if ( depth == 0 ) {
gprintf("ERROR: Points extents smaller than 1 brick. Not yet supported.\n");
return;
}
if (depth > 5) {
gprintf("ERROR: Point extents exceed 5 levels.\n");
return;
}
if (mRebuildTopo) {
RebuildTopology ( pNumPnts, pRadius, pOrig );
return;
}
ActivateIncreBricksGPU(pNumPnts, pRadius, pOrig, depth, rootPos, true );
}
void VolumeGVDB::RebuildTopology(int pNumPnts, float pRadius, Vector3DF pOrig )
{
GetBoundingBox(pNumPnts, pOrig);
Vector3DI rootPos;
int depth = DetermineDepth(rootPos);
if (depth == 0) {
gprintf("ERROR: Points extents smaller than 1 brick. Not yet supported.\n");
return;
}
if (depth > 5) {
gprintf("ERROR: Point extents exceed 5 levels.\n");
return;
}
if (mRebuildTopo) {
Clear();
} else {
if (depth != mCurrDepth) { // in case the depth is changing
gprintf("Warning: Depth change in rebuild.\n");
Clear();
mRebuildTopo = true;
mCurrDepth = depth;
}
}
if (mRebuildTopo) {
ActivateBricksGPU(pNumPnts, pRadius, pOrig, depth, rootPos);
if (pRadius >= 1)
ActivateExtraBricksGPU(pNumPnts, pRadius, pOrig, depth, rootPos); // for radius > 1 and staggered grid
mRebuildTopo = false;
CleanAux(AUX_BRICK_LEVXYZ);
CleanAux(AUX_MARKER);
CleanAux(AUX_SORTED_LEVXYZ);
CleanAux(AUX_MARKER_PRESUM);
} else {
ActivateIncreBricksGPU(pNumPnts, pRadius, pOrig, depth, rootPos);
}
}
void VolumeGVDB::RebuildTopologyCPU(int pNumPnts, Vector3DF pOrig, Vector3DF* pPos)
{
Vector3DF p;
for (int n=0; n < pNumPnts; n++) {
p = (*pPos++) + pOrig;
ActivateSpace ( p );
}
}
void VolumeGVDB::ActivateBricksGPU(int pNumPnts, float pRadius, Vector3DF pOrig, int pRootLev, Vector3DI pRootPos)
{
PUSH_CTX
//////////////////////////////////////////////////////////////////////////
// Prepare
//////////////////////////////////////////////////////////////////////////
PrepareAux ( AUX_RANGE_RES, pRootLev, sizeof(int), true, true );
int* range_res = (int*) mAux[AUX_RANGE_RES].cpu;
for (int lev = 0; lev < pRootLev; lev++)
range_res[lev] = getRange(lev).x;
CommitData ( mAux[AUX_RANGE_RES] );
PrepareAux ( AUX_BRICK_LEVXYZ, pNumPnts * pRootLev * 4, sizeof(unsigned short), false ); // 4 - lev, x, y, z
void* argsCalcLevXYZ[8] = { &pNumPnts, &pRootLev, &mAux[AUX_RANGE_RES].gpu,
&mAux[AUX_PNTPOS].gpu, &mAux[AUX_PNTPOS].subdim.x, &mAux[AUX_PNTPOS].stride,
&pOrig.x, &mAux[AUX_BRICK_LEVXYZ].gpu};
int threads = 512;
int pblks = int(pNumPnts / threads)+1;
//////////////////////////////////////////////////////////////////////////
// calculate brick id for each level
//////////////////////////////////////////////////////////////////////////
cudaCheck ( cuLaunchKernel ( cuFunc[FUNC_CALC_BRICK_ID],
pblks, 1, 1, threads, 1, 1, 0, NULL, argsCalcLevXYZ, NULL ), "VolumeGVDB", "ActivateBricksGPU", "cuLaunch", "FUNC_CALC_BRICK_ID", mbDebug);
#if 0
//////////////////////////////////////////////////////////////////////////
// checking data
//////////////////////////////////////////////////////////////////////////
int length = pNumPnts * pRootLev * 4;
unsigned short* dat1 = (unsigned short*) malloc ( length * sizeof(unsigned short) );
cudaCheck ( cuMemcpyDtoH ( dat1, mAux[AUX_BRICK_LEVXYZ].gpu, length * sizeof(unsigned short) ), "Memcpy dat1", "ActivateBricksGPU" );
for (int i = 0; i < pNumPnts; i++)
{
std::cout << "Point " << i << std::endl;
for (int lev = 0; lev < pRootLev; lev++)
{
std::cout << " level " << lev;
std::cout << ": " << dat1[ i * pRootLev * 4 + lev * 4 + 0];
std::cout << " " << dat1[ i * pRootLev * 4 + lev * 4 + 1];
std::cout << " " << dat1[ i * pRootLev * 4 + lev * 4 + 2];
std::cout << " " << dat1[ i * pRootLev * 4 + lev * 4 + 3] << std::endl;
}
}
#endif
int numUniqueBrick = 0;
RadixSortByByte(pNumPnts * pRootLev, pRootLev);
FindUniqueBrick(pNumPnts * pRootLev, pRootLev, numUniqueBrick);
//////////////////////////////////////////////////////////////////////////
// create pool for each level
// set lev, pos, and childlist
//////////////////////////////////////////////////////////////////////////
PERF_PUSH("Create pool (CPU)");
{
mRoot = mPool->PoolAlloc ( 0, pRootLev, true );
uint64 childlistId = mPool->PoolAlloc ( 1, pRootLev, true );
SetupNode ( mRoot, pRootLev, pRootPos);
Node* rootnd = getNode(mRoot);
rootnd->mFlags = true;
rootnd->mChildList = childlistId;
uint64* clist = mPool->PoolData64 ( rootnd->mChildList );
int r = getRes(pRootLev);
uint64 childlistLen = ((uint64) r*r*r);
memset(clist, 0xFF, sizeof(uint64) * childlistLen);
}
int* levCnt = new int[pRootLev];
cudaCheck ( cuMemcpyDtoH ( levCnt, mAux[AUX_LEVEL_CNT].gpu, pRootLev * sizeof(int) ), "VolumeGVDB", "ActivateBricksGPU", "cuMemcpyDtoH", "AUX_LEVEL_CNT", mbDebug);
unsigned short* uniBricks = new unsigned short[numUniqueBrick * 4];
cudaCheck ( cuMemcpyDtoH ( uniBricks, mAux[AUX_UNIQUE_LEVXYZ].gpu, numUniqueBrick * 4 * sizeof(unsigned short) ), "VolumeGVDB", "ActivateBricksGPU", "cuMemcpyDtoH", "AUX_UNIQUE_LEVXYZ", mbDebug);
int levPrefixSum = 0;
for (int lev = 0; lev < pRootLev; lev++)
{
int r = getRes(lev);
uint64 childlistLen = ((uint64) r*r*r);
Vector3DI brickRange = getRange(lev);
for (int n = levPrefixSum; n < levCnt[lev]+levPrefixSum; n++)
{
uint64 nodeID = mPool->PoolAlloc ( 0, lev, true );
SetupNode ( nodeID, lev, Vector3DI( uniBricks[n * 4 + 2] * brickRange.x,
uniBricks[n * 4 + 1] * brickRange.y,
uniBricks[n * 4 + 0] * brickRange.z));
if (lev > 0)
{
Node* nd = getNode(nodeID);
nd->mChildList = mPool->PoolAlloc ( 1, lev, true );
uint64* clist = mPool->PoolData64 ( nd->mChildList );
memset(clist, 0xFF, sizeof(uint64) * childlistLen);
}
}
levPrefixSum += levCnt[lev];
}
PERF_POP();
//////////////////////////////////////////////////////////////////////////
// set bit mask and link between parent and children
//////////////////////////////////////////////////////////////////////////
#if GVDB_CPU_VERSION // CPU version
Vector3DF posInNode;
uint32 bitMaskPos;
for (int lev = pRootLev-1; lev >= 0; lev--)
{
Vector3DI res = getRes3DI(lev+1);
Vector3DI range = getRange(lev+1);
for (int n = 0; n < levCnt[lev]; n++)
{
uint64 nodeID = Elem(0, lev, n);
Node* nd = getNode(nodeID);
uint64 parentNodeID = FindParent(lev+1, nd->mPos) ;
Node* parentNd = getNode(parentNodeID);
posInNode = nd->mPos - parentNd->mPos;
posInNode *= res;
posInNode /= range;
posInNode.x = floor(posInNode.x); // IMPORTANT!!! truncate decimal
posInNode.y = floor(posInNode.y);
posInNode.z = floor(posInNode.z);
bitMaskPos = (posInNode.z*res.x + posInNode.y)*res.x+ posInNode.x;
// parent in node
nd->mParent = parentNodeID; // set parent of child
#ifdef USE_BITMASKS
// determine child bit position
uint64 p = parentNd->countOn ( bitMaskPos );
uint64 cnum = parentNd->getNumChild(); // existing children count
parentNd->setOn ( bitMaskPos );
// insert into child list in parent node
uint64* clist = mPool->PoolData64 ( parentNd->mChildList );
if ( p < cnum ) {
memmove ( clist + p+1, clist + p, (cnum-p)*sizeof(uint64) );
*(clist + p) = nodeID;
} else {
*(clist + cnum) = nodeID;
}
#else
uint64* clist = mPool->PoolData64 ( parentNd->mChildList );
*(clist + bitMaskPos) = nodeID;
#endif
}
mPool->PoolCommitAll();
}
#else // GPU version
PERF_PUSH ( "Commit");
mPool->PoolCommitAll();
PERF_POP ();
PERF_PUSH ( "PrepPartial");
PrepareVDBPartially();
PERF_POP ();
PERF_PUSH("Link Levels");
for (int lev = pRootLev-1; lev >= 0; lev--)
{
pblks = int(mPool->getPoolTotalCnt(0,lev) / threads)+1;
void* argsLink[3] = { &cuVDBInfo, &lev};
cudaCheck ( cuLaunchKernel ( cuFunc[FUNC_LINK_BRICKS],
pblks, 1, 1, threads, 1, 1, 0, NULL, argsLink, NULL ), "VolumeGVDB", "ActivateBricksGPU", "cuLaunch", "FUNC_LINK_BRICKS", mbDebug);
}
PERF_POP();
PERF_PUSH ( "FetchAll");
mPool->PoolFetchAll();
PERF_POP();
#endif
POP_CTX
delete[] levCnt;
delete[] uniBricks;
}
void VolumeGVDB::FindActivBricks(int pLev, int pRootlev, int pNumPnts, Vector3DF pOrig, Vector3DI pRootPos)
{
PUSH_CTX
std::cout << "======================" << pLev << "======================\n";
//////////////////////////////////////////////////////////////////////////
// create root node
//////////////////////////////////////////////////////////////////////////
if (pLev == pRootlev)
{
mRoot = mPool->PoolAlloc ( 0, pLev, true );
uint64 childlistId = mPool->PoolAlloc ( 1, pLev, true );
SetupNode ( mRoot, pLev, pRootPos);
Node* rootnd = getNode(mRoot);
rootnd->mChildList = childlistId;
}
//////////////////////////////////////////////////////////////////////////
// find activated bricks per points
//////////////////////////////////////////////////////////////////////////
PERF_PUSH ("Find brick idx for points");
int nxtLev = pLev - 1;
int dim = getRange(pRootlev).x / getRange(nxtLev).x;
int d2 = dim * dim;
PrepareAux ( AUX_PBRICKDX, pNumPnts, sizeof(int), false );
int threads = 512;
int pblks = int(pNumPnts / threads)+1;
Vector3DI brickRange = getRange(nxtLev);
Vector3DI orig_shift = GetCoveringNode ( nxtLev, pOrig, brickRange );
void* args[11] = { &pNumPnts, &nxtLev, &brickRange, &dim,
&mAux[AUX_PNTPOS].gpu, &mAux[AUX_PNTPOS].subdim.x, &mAux[AUX_PNTPOS].stride,
&pOrig.x, &orig_shift, &mAux[AUX_PBRICKDX].gpu};
cudaCheck ( cuLaunchKernel ( cuFunc[FUNC_FIND_ACTIV_BRICKS], pblks, 1, 1, threads, 1, 1, 0, NULL, args, NULL ),
"VolumeGVDB", "ActivateBricksGPU", "cuLaunch", "FUNC_FIND_ACTIV_BRICKS", mbDebug);
// retrieve data
int* brickIdx = new int[pNumPnts];
cudaCheck ( cuMemcpyDtoH ( brickIdx, mAux[AUX_PBRICKDX].gpu, pNumPnts*sizeof(int) ), "VolumeGVDB", "ActivateBricksGPU", "cuMemcpyDtoH", "AUX_PBRICKDX", mbDebug);
Vector3DF* sortedPos = new Vector3DF[pNumPnts];
Vector3DF* pos = new Vector3DF[pNumPnts];
cudaCheck ( cuMemcpyDtoH ( pos, mAux[AUX_PNTPOS].gpu, pNumPnts*sizeof(Vector3DF) ), "VolumeGVDB", "ActivateBricksGPU", "cuMemcpyDtoH", "AUX_PNTPOS", mbDebug);
PERF_POP ();
//////////////////////////////////////////////////////////////////////////
// sort points based on brick idx
// TODO: CUDA implementation
//////////////////////////////////////////////////////////////////////////
PERF_PUSH ("Sort points");
std::vector< std::pair<int, int> > pntList;
for (int n = 0; n < pNumPnts; n++) {
std::pair<int, int> tmp(brickIdx[n], n);
pntList.push_back(tmp);
}
std::sort(pntList.begin(), pntList.end(), pairCompare);
// write back to pPos and pBrickIdx
for (int n = 0; n < pNumPnts; n++) {
brickIdx[n] = pntList[n].first;
sortedPos[n] = pos[pntList[n].second];
}
PERF_POP ();
//////////////////////////////////////////////////////////////////////////
// determine activated bricks number
// TODO: CUDA implementation
//////////////////////////////////////////////////////////////////////////
PERF_PUSH ("Determine brick number");
std::vector<int> activatingBrickIdx;
int numActivatingBrick = 1;
int prevBrickIdx = brickIdx[0];
activatingBrickIdx.push_back(brickIdx[0]);
for (int n = 1; n < pNumPnts; n++)
{
if (brickIdx[n] != prevBrickIdx) {
activatingBrickIdx.push_back(brickIdx[n]);
numActivatingBrick++;
}
prevBrickIdx = brickIdx[n];
}
PERF_POP ();
//////////////////////////////////////////////////////////////////////////
// create pool 0 and pool 1 for next level
//////////////////////////////////////////////////////////////////////////
PERF_PUSH ("Create pool");
for (int n = 0; n < numActivatingBrick; n++)
{
uint64 nodeID = mPool->PoolAlloc ( 0, pLev - 1, true );
SetupNode ( nodeID, pLev - 1, Vector3DI( activatingBrickIdx[n] % dim * brickRange.x,
activatingBrickIdx[n] / dim % dim * brickRange.y,
activatingBrickIdx[n] / d2 % dim * brickRange.z));
if ((pLev - 1) > 0)
{
Node* nd = getNode(nodeID);
nd->mChildList = mPool->PoolAlloc ( 1, pLev - 1, true );
}
}
PERF_POP ();
//////////////////////////////////////////////////////////////////////////
// set bit mask and parent for current level
// set childlist for parent node
// TODO: CUDA implementation
//////////////////////////////////////////////////////////////////////////
PERF_PUSH ("Setup child and parent");
Vector3DI res = getRes3DI ( nxtLev + 1 );
Vector3DI range = getRange ( nxtLev + 1);
Vector3DF posInNode;
uint32 bitMaskPos;
Vector3DI tmpRange;
for (int n = 0; n < numActivatingBrick; n++)
{
uint64 nodeID = Elem(0, pLev - 1, n);
Node* nd = getNode(nodeID);
uint64 parentNodeID = FindParent(pLev, nd->mPos) ;
Node* parentNd = getNode(parentNodeID);
posInNode = nd->mPos - parentNd->mPos;
posInNode *= res;
posInNode /= range;
int posInNodeX = int(floor(posInNode.x)); // IMPORTANT!!! truncate decimal
int posInNodeY = int(floor(posInNode.y));
int posInNodeZ = int(floor(posInNode.z));
bitMaskPos = (posInNodeZ*res.x + posInNodeY)*res.x+ posInNodeX;
// parent in node
nd->mParent = parentNodeID; // set parent of child
// determine child bit position
#ifdef USE_BITMASKS
uint64 p = parentNd->countOn ( bitMaskPos );
uint64 cnum = parentNd->getNumChild(); // existing children count
parentNd->setOn ( bitMaskPos );
// insert into child list in parent node
uint64* clist = mPool->PoolData64 ( parentNd->mChildList );
if ( p < cnum ) {
memmove ( clist + p+1, clist + p, (cnum-p)*sizeof(uint64) );
*(clist + p) = nodeID;
} else {
*(clist + cnum) = nodeID;
}
#else
uint64* clist = mPool->PoolData64 ( parentNd->mChildList );
*(clist + bitMaskPos) = nodeID;
#endif
}
PERF_POP ();
//////////////////////////////////////////////////////////////////////////
// clear data
//////////////////////////////////////////////////////////////////////////
delete brickIdx;
delete sortedPos;
delete pos;
POP_CTX
}
//////////////////////////////////////////////////////////////////////////
void VolumeGVDB::FinishTopology (bool pCommitPool, bool pComputeBounds)
{
PUSH_CTX
// compute bounds
if (pComputeBounds) ComputeBounds ();
// commit topology
if (pCommitPool) mPool->PoolCommitAll();
// update VDB data on gpu
mVDBInfo.update = true;
POP_CTX
}
// Clear all channels
void VolumeGVDB::ClearChannel (uchar chan)
{
// This launches a kernel to clear the CUarray.
// (there is no MemsetD8 for cuda arrays)
PUSH_CTX
mPool->AtlasFill(chan);
POP_CTX
}
uchar VolumeGVDB::GetChannelType(uchar channel) {
return mPool->getAtlas(channel).type;
}
// Clear all channels
void VolumeGVDB::ClearAllChannels ()
{
PUSH_CTX
PERF_PUSH ( "Clear All" );
for (int n = 0; n < mPool->getNumAtlas(); n++)
ClearChannel(n);
PERF_POP ();
POP_CTX
}
// Save a VBX file
void VolumeGVDB::SaveVBX ( const std::string fname )
{
// See GVDB_FILESPEC.txt for the specification of the VBX file format.
PUSH_CTX
FILE* fp = fopen ( fname.c_str(), "wb" );
const uchar major = MAJOR_VERSION;
const uchar minor = MINOR_VERSION;
PERF_PUSH ( "Saving VBX" );
verbosef ( " Saving VBX (ver %d.%d)\n", major, minor );
const int levels = mPool->getNumLevels();
const int num_grids = 1;
const int grid_name_len = 256; // Length of grid_name
char grid_name[grid_name_len];
const char grid_components = 1; // one component
const char grid_dtype = 'f'; // float
const char grid_compress = 0; // no compression
const char grid_topotype = 2; // gvdb topology
const int grid_reuse = 0;
const char grid_layout = 0; // atlas layout
const int leafcnt = static_cast<int>(mPool->getPoolTotalCnt(0,0)); // brick count
const int num_chan = mPool->getNumAtlas(); // number of channels
const int leafdimX = getRes(0);
const Vector3DI leafdim = Vector3DI(leafdimX, leafdimX, leafdimX); // brick resolution
const int apron = mPool->getAtlas(0).apron; // brick apron
const Vector3DI axiscnt = mPool->getAtlas(0).subdim; // atlas count
const Vector3DI axisres = mPool->getAtlasRes(0); // atlas res
const Vector3DF voxelsize_deprecated(1, 1, 1); // world units per voxel
const uint64 atlas_sz = mPool->getAtlas(0).size; // atlas size
std::vector<uint64> grid_offs(num_grids, 0); // All values are initially 0
//--- VBX file header
fwrite ( &major, sizeof(uchar), 1, fp ); // major version
fwrite ( &minor, sizeof(uchar), 1, fp ); // minor version
if ((major == 1 && minor >= 11) || major > 1) {
// GVDB 1.11+ saves grid transforms (GVDB 1.1 and earlier do not)
fwrite( &mPretrans.x, sizeof(float), 3, fp);
fwrite( &mAngs.x, sizeof(float), 3, fp);
fwrite( &mScale.x, sizeof(float), 3, fp);
fwrite( &mTrans.x, sizeof(float), 3, fp);
}
fwrite ( &num_grids, sizeof(int), 1, fp ); // number of grids - future expansion
// bitmask info
uchar use_bitmask = 0;
#ifdef USE_BITMASK
use_bitmask = 1;
#endif
if (major >= 2) {
fwrite( &use_bitmask, sizeof(uchar), 1, fp ); // bitmask usage (GVDB 2.0 or higher)
}
//--- grid offset table
const long grid_table = ftell ( fp ); // position of grid table in file
fwrite(grid_offs.data(), sizeof(uint64), grid_offs.size(), fp); // grid offsets (populated later)
for (int n=0; n < num_grids; n++ ) {
grid_offs[n] = ftell ( fp ); // record grid offset
//---- grid header
fwrite ( &grid_name, 256, 1, fp ); // grid name
fwrite ( &grid_dtype, sizeof(uchar), 1, fp ); // grid data type
fwrite ( &grid_components, sizeof(uchar), 1, fp ); // grid components
fwrite ( &grid_compress, sizeof(uchar), 1, fp ); // grid compression (0=none, 1=blosc, 2=..)
fwrite ( &voxelsize_deprecated.x, sizeof(float), 3, fp ); // voxel size
fwrite ( &leafcnt, sizeof(int), 1, fp ); // total brick count
fwrite ( &leafdim.x, sizeof(int), 3, fp ); // brick dimensions
fwrite ( &apron, sizeof(int), 1, fp ); // brick apron
fwrite ( &num_chan, sizeof(int), 1, fp ); // number of channels
fwrite ( &atlas_sz, sizeof(uint64), 1, fp ); // total atlas size (all channels)
fwrite ( &grid_topotype, sizeof(uchar), 1, fp ); // topology type? (0=none, 1=reuse, 2=gvdb, 3=..)
fwrite ( &grid_reuse, sizeof(int), 1, fp); // topology reuse
fwrite ( &grid_layout, sizeof(uchar), 1, fp); // brick layout? (0=atlas, 1=brick)
fwrite ( &axiscnt.x, sizeof(int), 3, fp ); // atlas axis count
fwrite ( &axisres.x, sizeof(int), 3, fp ); // atlas res
//---- topology section
fwrite ( &levels, sizeof(int), 1, fp ); // num levels
fwrite ( &mRoot, sizeof(uint64), 1, fp ); // root id
for (int n=0; n < levels; n++ ) {
const int res = getRes(n);
const Vector3DI range = getRange(n);
const int width0 = static_cast<int>(mPool->getPoolWidth(0, n));
const int width1 = static_cast<int>(mPool->getPoolWidth(1, n));
const int cnt0 = static_cast<int>(mPool->getPoolTotalCnt(0, n));
const int cnt1 = static_cast<int>(mPool->getPoolTotalCnt(1, n));
fwrite ( &mLogDim[n], sizeof(int), 1, fp );
fwrite ( &res, sizeof(int), 1, fp );
fwrite ( &range.x, sizeof(int), 3, fp );
fwrite ( &cnt0, sizeof(int), 1, fp );
fwrite ( &width0, sizeof(int), 1, fp );
fwrite ( &cnt1, sizeof(int), 1, fp );
fwrite ( &width1, sizeof(int), 1, fp );
}
// Write topology
for (int n = 0; n < levels; n++) {
mPool->PoolWrite(fp, 0, n); // write pool 0
}
for (int n = 0; n < levels; n++) {
mPool->PoolWrite(fp, 1, n); // write pool 1
}
//---- atlas section
// readback slice-by-slice from gpu to conserve CPU and GPU mem
for (int chan = 0 ; chan < num_chan; chan++ ) {
DataPtr slice;
const int chan_type = mPool->getAtlas(chan).type ;
const int chan_stride = mPool->getSize ( chan_type );
fwrite ( &chan_type, sizeof(int), 1, fp );
fwrite ( &chan_stride, sizeof(int), 1, fp );
mPool->CreateMemLinear ( slice, 0x0, chan_stride, axisres.x*axisres.y, true );
for (int z = 0; z < axisres.z; z++ ) {
mPool->AtlasRetrieveSlice ( chan, z, static_cast<int>(slice.size),
slice.gpu, (uchar*) slice.cpu ); // transfer from GPU, directly into CPU atlas
fwrite ( slice.cpu, slice.size, 1, fp );
}
mPool->FreeMemLinear ( slice );
}
}
// update grid offsets table
fseek(fp, grid_table, SEEK_SET);
fwrite(grid_offs.data(), sizeof(uint64), grid_offs.size(), fp); // grid offsets
fclose ( fp );
PERF_POP ();
POP_CTX
}
void VolumeGVDB::SetBounds(Vector3DF pMin, Vector3DF pMax)
{
Vector3DI range = getRange(0);
mVoxMin.x = float(int(pMin.x / range.x) * range.x - range.x);
mVoxMin.y = float(int(pMin.y / range.y) * range.y - range.y);
mVoxMin.z = float(int(pMin.z / range.z) * range.z - range.z);
mVoxMax.x = float(int(pMax.x / range.x) * range.x + 2 * range.x);
mVoxMax.y = float(int(pMax.y / range.y) * range.y + 2 * range.y);
mVoxMax.z = float(int(pMax.z / range.z) * range.z + 2 * range.z);
mObjMin = mVoxMin;
mObjMax = mVoxMax;
mVoxRes = mVoxMax; mVoxRes -= mVoxMin;
if ( mVoxRes.x > mVoxResMax.x ) mVoxResMax.x = mVoxRes.x;
if ( mVoxRes.y > mVoxResMax.y ) mVoxResMax.y = mVoxRes.y;
if ( mVoxRes.z > mVoxResMax.z ) mVoxResMax.z = mVoxRes.z;
}
// Compute bounding box of entire volume.
// - This is done by finding the min/max of all bricks
void VolumeGVDB::ComputeBounds ()
{
Vector3DI range = getRange(0);
Node* curr = getNode ( 0, 0, 0 );
mVoxMin = curr->mPos;
mVoxMax = mVoxMin;
for (int n=0; n < mPool->getPoolTotalCnt(0,0); n++ ) {
curr = getNode ( 0, 0, n );
if (!curr->mFlags) continue; // inactivated, skip
if ( curr->mPos.x < mVoxMin.x ) mVoxMin.x = static_cast<float>(curr->mPos.x);
if ( curr->mPos.y < mVoxMin.y ) mVoxMin.y = static_cast<float>(curr->mPos.y);
if ( curr->mPos.z < mVoxMin.z ) mVoxMin.z = static_cast<float>(curr->mPos.z);
if ( curr->mPos.x + range.x > mVoxMax.x ) mVoxMax.x = static_cast<float>(curr->mPos.x + range.x);
if ( curr->mPos.y + range.y > mVoxMax.y ) mVoxMax.y = static_cast<float>(curr->mPos.y + range.y);
if ( curr->mPos.z + range.z > mVoxMax.z ) mVoxMax.z = static_cast<float>(curr->mPos.z + range.z);
}
mObjMin = mVoxMin;
mObjMax = mVoxMax;
mVoxRes = mVoxMax; mVoxRes -= mVoxMin;
if ( mVoxRes.x > mVoxResMax.x ) mVoxResMax.x = mVoxRes.x;
if ( mVoxRes.y > mVoxResMax.y ) mVoxResMax.y = mVoxRes.y;
if ( mVoxRes.z > mVoxResMax.z ) mVoxResMax.z = mVoxRes.z;
}
#ifdef BUILD_OPENVDB
// Skips to the `leaf_start`th leaf in the file.
template<class GridType>
void vdbSkip(typename GridType::Ptr& grid, typename GridType::TreeType::LeafCIter& iter, int leaf_start) {
iter = grid->tree().cbeginLeaf();
for (int j = 0; iter && j < leaf_start; j++) {
++iter;
}
}
#endif
// Load a raw BRK file
bool VolumeGVDB::LoadBRK ( std::string fname )
{
PUSH_CTX
char fn[1024], buf[1024];
strcpy ( fn, fname.c_str() );
FILE* fp = fopen ( fn, "rb" );
slong leaf;
int leaf_cnt = 0;
Vector3DF bmin, bmax;
Vector3DI bres, bndx, bcurr;
int brkcnt;
float* brick = 0x0;
bcurr.Set ( 0, 0, 0 );
Volume3D vtemp ( mScene );
sprintf ( buf, "Reading BRK %s", fname.c_str() );
verbosef ( " %s\n", buf );
PERF_PUSH ( buf );
fread ( &brkcnt, sizeof(int), 1, fp );
verbosef ( " Number of bricks: %d\n", brkcnt );
// Read first brick for res
fread ( &bndx, sizeof(Vector3DI), 1, fp );
fread ( &bmin, sizeof(Vector3DF), 1, fp );
fread ( &bmax, sizeof(Vector3DF), 1, fp );
fread ( &bres, sizeof(Vector3DI), 1, fp ); // needed to create atlas
bcurr = bres;
if ( brick != 0x0 ) free ( brick );
brick = (float*) malloc ( bres.x*bres.y*bres.z * sizeof(float) ); // allocate brick memory
vtemp.Resize ( T_FLOAT, bres, 0x0, false );
fseek ( fp, 0, SEEK_SET );
fread ( &brkcnt, sizeof(int), 1, fp );
// Adjust VDB config if necessary
int res = bres.x;
mVCFG[4] = 0;
while ( res >>= 1 ) ++mVCFG[4];
verbosef ( " Leaf res: %d (leaf log2=%d)\n", bres.x, mVCFG[4] );
// Initialize VDB
Configure ( mVCFG[0], mVCFG[1], mVCFG[2], mVCFG[3], mVCFG[4] );
SetApron ( 1 );
// Create atlas
mPool->AtlasReleaseAll ();
PERF_PUSH ( "Create Atlas" );
int side = int(ceil(pow(brkcnt, 1 / 3.0f))); // number of leaves along one axis
Vector3DI axiscnt (side, side, side);
mPool->AtlasCreate ( 0, T_FLOAT, bres, axiscnt, mApron, sizeof(AtlasNode), false, mbUseGLAtlas );
PERF_POP ();
float vmin = FLT_MAX, vmax = -FLT_MAX;
// Read all bricks
Vector3DF t;
PERF_PUSH ( "Load Bricks" );
for (int n=0; n < brkcnt; n++ ) {
// Read brick dimensions
PERF_START ();
fread ( &bndx, sizeof(Vector3DI), 1, fp );
fread ( &bmin, sizeof(Vector3DF), 1, fp );
fread ( &bmax, sizeof(Vector3DF), 1, fp );
fread ( &bres, sizeof(Vector3DI), 1, fp );
if ( bcurr.x != bres.x || bcurr.y != bres.y || bcurr.z != bres.z ) {
gprintf ( "ERROR: Bricks do not have same resolution.\n" );
exit (-1);
}
// Read brick
fread ( brick, sizeof(float), bres.x*bres.y*bres.z, fp );
t.x += PERF_STOP ();
// Activate space
PERF_START ();
bool bnew = false;
leaf = ActivateSpace ( mRoot, bndx, bnew );
t.y += PERF_STOP ();
if ( leaf != ID_UNDEFL ) {
PERF_START ();
// Copy data from CPU into 3D Texture
vtemp.SetDomain ( bmin, bmax );
vtemp.CommitFromCPU ( brick );
// Create VDB Atlas value and sub-copy 3D texture into it
Vector3DI brickpos;
Node* node;
if ( mPool->AtlasAlloc ( 0, brickpos ) ) {
node = getNode ( leaf );
node->mValue = brickpos;
mPool->AtlasCopyTex ( 0, brickpos, vtemp.getPtr() );
}
leaf_cnt++;
t.z += PERF_STOP ();
}
}
PERF_POP ();
verbosef( " Read Brk: %f ms\n", t.x );
verbosef( " Activate: %f ms\n", t.y );
verbosef( " To Atlas: %f ms\n", t.z );
ComputeBounds ();
// Commit all node pools to gpu
PERF_PUSH ( "Commit" );
mPool->PoolCommitAll ();
PERF_POP ();
PERF_POP ();
FinishTopology ();
UpdateApron ();
POP_CTX
return true;
}
#ifdef BUILD_OPENVDB
template<class GridType>
bool VolumeGVDB::LoadVDBInternal(openvdb::GridBase::Ptr& baseGrid) {
// isFloat is true iff the OpenVDB grid contains floating-point values. If it
// contains vector values instead, for instance, it will be false.
const bool isFloat = std::is_same<GridType::ValueType, float>::value;
// Sanity check
if (!baseGrid->isType<GridType>()) {
gprintf("ERROR: Base grid type did not match template in LoadVDBInternal.\n");
return false;
}
GridType::Ptr grid = openvdb::gridPtrCast<GridType>(baseGrid);
const Vector3DF voxelsize = Vector3DF(
static_cast<float>(grid->voxelSize().x()),
static_cast<float>(grid->voxelSize().y()),
static_cast<float>(grid->voxelSize().z()));
SetTransform(Vector3DF(0, 0, 0), voxelsize, Vector3DF(0, 0, 0), Vector3DF(0, 0, 0));
SetApron(1);
const float poolUsed = MeasurePools();
verbosef(" Topology Used: %6.2f MB\n", poolUsed);
int leaf_start = 0;
int leaf_max = 0;
Vector3DF vclipmin, vclipmax, voffset;
vclipmin = getScene()->mVClipMin;
vclipmax = getScene()->mVClipMax;
// Determine volume bounds
verbosef(" Compute volume bounds.\n");
GridType::TreeType::LeafCIter iterator;
vdbSkip<GridType>(grid, iterator, leaf_start);
for (leaf_max = 0; iterator.test(); ) {
openvdb::Coord origin;
iterator->getOrigin(origin);
Vector3DF p0 = Vector3DI(origin.x(), origin.y(), origin.z());
// Only accept origins within the vclip bounding box
if (p0.x > vclipmin.x && p0.y > vclipmin.y && p0.z > vclipmin.z && p0.x < vclipmax.x && p0.y < vclipmax.y && p0.z < vclipmax.z) {
if (leaf_max == 0) {
mVoxMin = p0; mVoxMax = p0;
}
else {
if (p0.x < mVoxMin.x) mVoxMin.x = p0.x;
if (p0.y < mVoxMin.y) mVoxMin.y = p0.y;
if (p0.z < mVoxMin.z) mVoxMin.z = p0.z;
if (p0.x > mVoxMax.x) mVoxMax.x = p0.x;
if (p0.y > mVoxMax.y) mVoxMax.y = p0.y;
if (p0.z > mVoxMax.z) mVoxMax.z = p0.z;
}
leaf_max++;
}
iterator.next();
}
voffset = mVoxMin * -1; // offset to positive space (hack)
// Activate Space
PERF_PUSH("Activate");
verbosef(" Activating space.\n");
vdbSkip<GridType>(grid, iterator, leaf_start);
for (int n = leaf_max = 0; iterator.test(); n++) {
// Read leaf position
openvdb::Coord origin;
iterator->getOrigin(origin);
Vector3DF p0 = Vector3DI(origin.x(), origin.y(), origin.z());
p0 += voffset;
// only accept those in clip volume
if (p0.x > vclipmin.x && p0.y > vclipmin.y && p0.z > vclipmin.z && p0.x < vclipmax.x && p0.y < vclipmax.y && p0.z < vclipmax.z) { // accept condition
bool bnew = false;
slong leaf = ActivateSpace(mRoot, p0, bnew);
leaf_ptr.push_back(leaf);
leaf_pos.push_back(p0);
if (leaf_max == 0) {
mVoxMin = p0; mVoxMax = p0;
verbosef(" First leaf: %d (%f %f %f)\n", leaf_start + n, p0.x, p0.y, p0.z);
}
leaf_max++;
}
iterator.next();
}
// Finish Topology
FinishTopology();
PERF_POP();
// Resize Atlas
//verbosef ( " Create Atlas. Free before: %6.2f MB\n", cudaGetFreeMem() );
PERF_PUSH("Atlas");
DestroyChannels();
AddChannel(0, T_FLOAT, mApron, F_LINEAR);
UpdateAtlas();
PERF_POP();
//verbosef ( " Create Atlas. Free after: %6.2f MB, # Leaf: %d\n", cudaGetFreeMem(), leaf_max );
// Resize temp 3D texture to match leaf res
int res0 = getRes(0);
Vector3DI vres0(res0, res0, res0); // leaf resolution
Vector3DF vrange0 = getRange(0);
Volume3D vtemp(mScene);
vtemp.Resize(T_FLOAT, vres0, 0x0, false);
// Read brick data
PERF_PUSH("Read bricks");
// Advance to starting leaf
vdbSkip<GridType>(grid, iterator, leaf_start);
// Tempoary buffer for velocity fields
const int64_t res0_64 = static_cast<int64_t>(res0);
float* srcLengths = new float[res0_64 * res0_64 * res0_64];
float mValMin, mValMax;
mValMin = FLT_MAX; mValMax = FLT_MIN;
// Fill atlas from leaf data
int percentLast = 0, percent = 0;
verbosef(" Loading bricks.\n");
for (int leaf_cnt = 0; iterator.test(); ) {
// Read leaf position
openvdb::Coord origin;
iterator->getOrigin(origin);
Vector3DF p0 = Vector3DI(origin.x(), origin.y(), origin.z());
p0 += voffset;
// Only process nodes whose origins are within the bounding box
if (p0.x > vclipmin.x && p0.y > vclipmin.y && p0.z > vclipmin.z && p0.x < vclipmax.x && p0.y < vclipmax.y && p0.z < vclipmax.z) {
// get leaf
GridType::TreeType::LeafNodeType::Buffer leafBuffer = iterator->buffer();
float* src;
if (isFloat) {
src = leafBuffer.data();
}
else {
src = ConvertToScalar(res0 * res0 * res0, (float*)leafBuffer.data(), srcLengths, mValMin, mValMax);
}
// Copy data from CPU into temporary 3D texture
vtemp.SetDomain(leaf_pos[leaf_cnt], leaf_pos[leaf_cnt] + vrange0);
vtemp.CommitFromCPU(src);
// Copy from 3D texture into Atlas brick
Node* node = getNode(leaf_ptr[leaf_cnt]);
mPool->AtlasCopyTexZYX(0, node->mValue, vtemp.getPtr());
// Progress percent
leaf_cnt++; percent = int(leaf_cnt * 100 / leaf_max);
if (percent != percentLast) {
verbosef("%d%%%% ", percent);
percentLast = percent;
}
}
iterator.next();
}
PERF_POP();
if (mValMin != FLT_MAX || mValMax != FLT_MIN)
verbosef("\n Value Range: %f %f\n", mValMin, mValMax);
UpdateApron();
delete[] srcLengths;
return true;
}
#endif // BUILD_OPENVDB
bool VolumeGVDB::LoadVDB ( std::string fname )
{
#ifdef BUILD_OPENVDB
// Only initialize OpenVDB once
static bool openVDBInitialized = false;
if (!openVDBInitialized) {
openvdb::initialize();
FloatGrid34::registerGrid();
// We don't need to register FloatGrid543, as it is part of OpenVDB
openVDBInitialized = true;
}
PERF_PUSH ( "Load VDB" );
// Read .vdb file
verbosef ( " Reading OpenVDB file.\n" );
openvdb::io::File* vdbfile = new openvdb::io::File ( fname );
vdbfile->open();
// Read grid
openvdb::GridBase::Ptr baseGrid;
openvdb::io::File::NameIterator nameIter = vdbfile->beginName();
std::string name = vdbfile->beginName().gridName();
for ( openvdb::io::File::NameIterator nameIter = vdbfile->beginName(); nameIter != vdbfile->endName(); ++nameIter ) {
verbosef ( " Grid: %s\n", nameIter.gridName().c_str() );
if ( nameIter.gridName().compare( getScene()->mVName ) == 0 ) name = getScene()->mVName;
}
verbosef ( " Loading Grid: %s\n", name.c_str() );
baseGrid = vdbfile->readGrid ( name );
PERF_POP ();
// Switch based on the type of the grid
bool success = false;
if (baseGrid->isType<FloatGrid543>()) {
Configure(5, 5, 5, 4, 3);
success = LoadVDBInternal<FloatGrid543>(baseGrid);
}
else if (baseGrid->isType<Vec3fGrid543>()) {
Configure(5, 5, 5, 4, 3);
success = LoadVDBInternal<FloatGrid543>(baseGrid);
}
else if (baseGrid->isType<FloatGrid34>()) {
Configure(3, 3, 3, 3, 4);
success = LoadVDBInternal<FloatGrid34>(baseGrid);
}
else if (baseGrid->isType<Vec3fGrid34>()) {
Configure(3, 3, 3, 3, 4);
success = LoadVDBInternal<FloatGrid34>(baseGrid);
}
vdbfile->close();
delete vdbfile;
return success;
#else
gprintf ( "ERROR: Unable to load .vdb file. OpenVDB library not linked.\n");
return false;
#endif
}
#ifdef BUILD_OPENVDB
// Activates all voxels whose value is nonzero.
// GridValueAllIter is e.g. FloatGrid34::ValueAllIter
struct Activator {
template<class GridValueAllIter>
static inline void op(const GridValueAllIter& iter) {
if ( iter.getValue() != 0.0 )
iter.setActiveState ( true );
}
};
template<class TreeType>
void VolumeGVDB::SaveVDBInternal(std::string& fname) {
// Raw pointer to tree
TreeType* treePtr = new TreeType(0.0);
TreeType::Ptr tree(treePtr);
// `typename` here doesn't change the type - it just lets the
// compiler know that these are types, and not values:
using GridType = typename openvdb::Grid<TreeType>;
using IterType = typename GridType::ValueAllIter;
using RootType = typename TreeType::RootNodeType;
using LeafType = typename TreeType::LeafNodeType;
using ValueType = typename LeafType::ValueType;
LeafType* leaf;
const int res = getRes(0);
const uint64 bytesPerLeaf = getVoxCnt(0) * sizeof(float); // = (res^3) floats
DataPtr p;
mPool->CreateMemLinear(p, 0x0, 1, bytesPerLeaf, true);
const uint64 leafcnt = mPool->getPoolTotalCnt(0, 0); // Leaf count
Node* node;
float minValue = FLT_MAX;
float maxValue = FLT_MIN;
for (uint64 n = 0; n < leafcnt; n++) {
node = getNode(0, 0, n);
Vector3DI pos = node->mPos;
// Get a pointer to this node
leaf = tree->touchLeaf(openvdb::Coord(pos.x, pos.y, pos.z));
leaf->setValuesOff();
ValueType* leafBuffer = leaf->buffer().data();
// Get the brick from the GPU
mPool->AtlasRetrieveTexXYZ(0, node->mValue, p);
// Set the leaf voxels
memcpy(leafBuffer, p.cpu, bytesPerLeaf);
}
verbosef(" Leaf count: %d\n", tree->leafCount());
// Now, create the grid from the tree and activate it
PERF_PUSH("Creating grid");
GridType::Ptr grid = GridType::create(tree);
grid->setGridClass(openvdb::GRID_FOG_VOLUME);
grid->setName("density");
grid->setTransform(openvdb::math::Transform::createLinearTransform(1.0));
grid->addStatsMetadata();
// VS2019: Ignore warning about OpenVDB using const in a template argument
#pragma warning(push)
#pragma warning(disable:4180)
openvdb::tools::foreach(grid->beginValueAll(), Activator::op<IterType>);
#pragma warning(pop)
verbosef(" Leaf count: %d\n", grid->tree().leafCount());
PERF_POP();
PERF_PUSH("Writing grids");
openvdb::io::File* vdbfile = new openvdb::io::File(fname);
vdbfile->setGridStatsMetadataEnabled(true);
vdbfile->setCompression(openvdb::io::COMPRESS_NONE);
openvdb::GridPtrVec grids;
grids.push_back(grid);
vdbfile->write(grids);
vdbfile->close();
PERF_POP();
}
#endif
void VolumeGVDB::SaveVDB ( std::string fname )
{
#ifdef BUILD_OPENVDB
// Verify that the atlas's datatype is T_FLOAT
if (mPool->getAtlas(0).type != T_FLOAT) {
gprintf("ERROR: Unable to save .vdb file. Atlas channel 0 must have "
"type T_FLOAT in order to export correctly.\n");
return;
}
const int logRes = getLD(0);
if (logRes == 3) {
SaveVDBInternal<TreeType543F>(fname);
}
else if (logRes == 4) {
SaveVDBInternal<TreeType34F>(fname);
}
else {
gprintf("ERROR: Unable to save .vdb file. No configurations available for given log res.\n");
}
return;
#else
gprintf("ERROR: Unable to save .vdb file. OpenVDB library not linked.\n");
return;
#endif
}
// Add a search path for assets
void VolumeGVDB::AddPath ( const char* path )
{
mScene->AddPath ( path );
}
bool VolumeGVDB::FindFile ( std::string fname, char* path )
{
return mScene->FindFile ( fname, path );
}
// Initialize GVDB
// - Creates a scene object and a memory pool allocator
// - Default transfer function and settings
void VolumeGVDB::Initialize ()
{
PUSH_CTX
// Create Pool Allocator
verbosef("Starting GVDB Voxels. ver %d.%d\n", MAJOR_VERSION, MINOR_VERSION );
verbosef(" Creating Allocator..\n");
mPool = new Allocator;
mPool->SetStream(mStream);
mPool->SetDebug(mbDebug);
// Create Scene object
verbosef(" Creating Scene..\n");
mScene = new Scene;
// Create VDB object
cudaCheck(cuMemAlloc(&cuVDBInfo, sizeof(VDBInfo)), "VolumeGVDB", "Initialize", "cuMemAlloc", "cuVDBInfo", mbDebug);
// Default Camera & Light
mScene->SetCamera ( new Camera3D ); // Default camera
mScene->SetLight ( 0, new Light ); // Default light
mScene->SetVolumeRange ( 0.1f, 0, 1 ); // Default transfer range
mScene->LinearTransferFunc ( 0, 1, Vector4DF(0,0,0,0), Vector4DF(1,1,1,0.1f) ); // Default transfer function
// Default transfer function
CommitTransferFunc ();
// Default channel config
SetChannelDefault ( 16, 16, 1 );
// Default paths
AddPath ( "../source/shared_assets/" );
AddPath ( "../shared_assets/" );
mRebuildTopo = true;
mCurrDepth = -1;
mHasObstacle = false;
POP_CTX
}
// Configure VDB tree (5-level)
void VolumeGVDB::Configure ( int q4, int q3, int q2, int q1, int q0 )
{
int r[5], n[5];
r[0] = q0; r[1] = q1; r[2] = q2; r[3] = q3; r[4] = q4;
n[0] = 4; // leaf max
int cnt = 4;
n[1] = cnt; cnt >>= 1;
n[2] = cnt; cnt >>= 1;
n[3] = cnt; cnt >>= 1;
n[4] = cnt;
Configure ( 5, r, n );
}
// Configure VDB tree (N-level)
void VolumeGVDB::Configure ( int levs, int* r, int* numcnt, bool use_masks )
{
PUSH_CTX
if ( mPool == 0 || mScene == 0 ) {
gprintf ( "ERROR: Initialize not called.\n" );
gerror ();
}
// This vector defines the VDB configuration
int* maxcnt = (int*) malloc ( levs * sizeof(int) );
for (int n=0; n < levs; n++) {
mLogDim[n] = (r[n]==0) ? 1 : r[n];
maxcnt[n] = (numcnt[n]==0) ? 1 : numcnt[n];
}
mClrDim[0] = Vector3DF(0,0,1); // blue
mClrDim[1] = Vector3DF(0,1,0); // green
mClrDim[2] = Vector3DF(1,0,0); // red
mClrDim[3] = Vector3DF(1,1,0); // yellow
mClrDim[4] = Vector3DF(1,0,1); // purple
mClrDim[5] = Vector3DF(0,1,1); // aqua
mClrDim[6] = Vector3DF(1,0.5,0); // orange
mClrDim[7] = Vector3DF(0,0.5,1); // green-blue
mClrDim[8] = Vector3DF(0.7f,0.7f,0.7f); // grey
// Initialize memory pools
uint64 hdr = sizeof(Node);
mPool->PoolReleaseAll();
#ifdef USE_BITMASKS
use_masks = true;
#endif
// node & mask list
uint64 nodesz;
for (int n = 0; n < levs; n++) {
nodesz = hdr;
if ( use_masks ) nodesz += getMaskSize(n);
mPool->PoolCreate(0, n, nodesz, maxcnt[n], true);
}
// child lists
mPool->PoolCreate ( 1, 0, 0, 0, true );
for (int n=1; n < levs; n++ )
mPool->PoolCreate ( 1, n, sizeof(uint64)*getVoxCnt(n), maxcnt[n], true );
mVoxResMax.Set ( 0, 0, 0 );
// Clear tree and create default root
Clear ();
POP_CTX
}
// Add a data channel (voxel attribute)
void VolumeGVDB::AddChannel ( uchar chan, int dt, int apron, int filter, int border, Vector3DI axiscnt )
{
PUSH_CTX
if (axiscnt.x==0 && axiscnt.y==0 && axiscnt.z==0) {
if ( chan == 0 ) axiscnt = mDefaultAxiscnt;
else axiscnt = mPool->getAtlas(0).subdim;
}
mApron = apron;
mPool->AtlasCreate ( chan, dt, getRes3DI(0), axiscnt, apron, sizeof(AtlasNode), false, mbUseGLAtlas );
mPool->AtlasSetFilter ( chan, filter, border );
SetupAtlasAccess ();
POP_CTX
}
// Fill data channel
void VolumeGVDB::FillChannel ( uchar chan, Vector4DF val )
{
PUSH_CTX
if (val.x == 0 && val.y==0 && val.z==0 && val.w==0) {
ClearChannel(chan);
} else {
switch (mPool->getAtlas(chan).type) {
case T_FLOAT: Compute(FUNC_FILL_F, chan, 1, val, false, false); break;
case T_UCHAR: Compute(FUNC_FILL_C, chan, 1, val, false, false); break;
case T_UCHAR4: Compute(FUNC_FILL_C4, chan, 1, val, false, false); break;
};
}
POP_CTX
}
// Destroy all channels
void VolumeGVDB::DestroyChannels ()
{
PUSH_CTX
if (mPool) {
mPool->AtlasReleaseAll();
}
SetColorChannel ( -1 );
POP_CTX
}
// Clear GVDB without changing config
void VolumeGVDB::Clear ()
{
PUSH_CTX
// Empty VDB data (keep pools)
mPool->PoolEmptyAll (); // does not free pool mem
mRoot = ID_UNDEFL;
// Empty atlas & atlas map
mPool->AtlasEmptyAll (); // does not free atlas
mPnt.Set ( 0, 0, 0 );
mRebuildTopo = true; // full rebuild required
POP_CTX
}
// Allocate a new VDB node
slong VolumeGVDB::AllocateNode ( int lev )
{
return mPool->PoolAlloc ( 0, lev, true );
}
// Setup a VDB node
void VolumeGVDB::SetupNode ( slong nodeid, int lev, Vector3DF pos, bool marker)
{
Node* node = getNode ( nodeid );
node->mLev = lev;
node->mPos = pos;
node->mChildList = ID_UNDEFL;
node->mParent = ID_UNDEFL;
node->mValue = Vector3DI(-1,-1,-1);
node->mFlags = marker;
#ifdef USE_BITMASKS
if ( lev > 0 ) node->clearMask ();
#endif
}
void VolumeGVDB::UpdateNeighbors()
{
PUSH_CTX
uint64 brks = mPool->getPoolTotalCnt(0, 0);
mPool->AllocateNeighbors( brks );
Vector3DF ct;
float d = static_cast<float>(mPool->getAtlasBrickwid(0));
DataPtr* ntable = mPool->getNeighborTable();
int* nbr = (int*) ntable->cpu;
Node* node;
for (uint64 n = 0; n < brks; n++) {
node = getNode(0, 0, n);
ct = node->mPos + Vector3DF(d / 2, d / 2, d / 2);
*nbr++ = static_cast<int>(ElemNdx(getNodeAtPoint(mRoot, ct - Vector3DF(d, 0, 0))));
*nbr++ = static_cast<int>(ElemNdx(getNodeAtPoint(mRoot, ct - Vector3DF(0, d, 0))));
*nbr++ = static_cast<int>(ElemNdx(getNodeAtPoint(mRoot, ct - Vector3DF(0, 0, d))));
*nbr++ = static_cast<int>(ElemNdx(getNodeAtPoint(mRoot, ct + Vector3DF(d, 0, 0))));
*nbr++ = static_cast<int>(ElemNdx(getNodeAtPoint(mRoot, ct + Vector3DF(0, d, 0))));
*nbr++ = static_cast<int>(ElemNdx(getNodeAtPoint(mRoot, ct + Vector3DF(0, 0, d))));
}
mPool->CommitNeighbors();
POP_CTX
}
// Clear atlas mapping
void VolumeGVDB::ClearMapping ()
{
// This function ensures that the atlas mapping, for unused bricks in the atlas,
// maps to an undefined value which is checked by kernels.
DataPtr a = mPool->getAtlas ( 0 ); // atlas
Vector3DI axiscnt = a.subdim; // number of leaves along atlas axis
AtlasNode* an;
Vector3DI b; // 3D brick index 0 < b < atlas_cnt
Vector3DI brickpos; // pos of brick in atlas 0 < brickpos < atlas res
for (b.z=0; b.z < axiscnt.z; b.z++ ) {
for (b.y=0; b.y < axiscnt.y; b.y++ ) {
for (b.x=0; b.x < axiscnt.x; b.x++ ) {
brickpos = b * int(a.stride + a.apron*2) + a.apron;
an = (AtlasNode*) mPool->getAtlasMapNode ( 0, brickpos );
an->mLeafNode = ID_UNDEFL;
an->mPos.Set ( ID_UNDEFL, ID_UNDEFL, ID_UNDEFL );
}
}
}
}
// Assign an atlas mapping
void VolumeGVDB::AssignMapping ( Vector3DI brickpos, Vector3DI pos, int leafid )
{
AtlasNode* an = (AtlasNode*) mPool->getAtlasMapNode ( 0, brickpos );
an->mPos = pos;
an->mLeafNode = leafid;
}
// Mandelbulb! (3D fractal)
float Mandelbulb ( Vector3DF s )
{
const int iter = 24;
const float bail = 8.0;
float pwr = 8.0;
float theta, phi, zr;
Vector3DF z = s;
float dr = 1.0;
float r = 0.0;
for (int i = 0; i < iter; i++ ) {
r = static_cast<float>(z.Length());
if ( r > bail ) break;
theta = asin(z.z/r) * pwr;
phi = atan2(z.y, z.x) * pwr;
zr = powf(r, pwr - 1.0f );
dr = zr*pwr*dr + 1.0f;
zr *= r;
z = Vector3DF( cos(theta)*cos(phi), cos(theta)*sin(phi), sin(theta) );
z *= zr;
z += s;
}
return -0.5f*log(r)*r / dr;
}
void VolumeGVDB::CopyChannel(int chanDst, int chanSrc)
{
PUSH_CTX
mPool->CopyChannel(chanDst, chanSrc);
POP_CTX
}
// Update the atlas
// - Resize atlas if needed
// - Assign new nodes to atlas
// - Update atlas mapping and pools
void VolumeGVDB::UpdateAtlas ()
{
PUSH_CTX
PERF_PUSH ( "Update Atlas" );
Vector3DI brickpos;
Node* node;
uint64 totalLeafcnt = mPool->getPoolTotalCnt(0,0);
uint64 usedLeafcnt = mPool->getPoolUsedCnt(0,0);
mPool->AtlasEmptyAll ();
// Resize atlas
uint64 amax = mPool->getAtlas(0).max;
if ( usedLeafcnt > amax ) {
PERF_PUSH ( "Resize Atlas" );
for (int n=0; n < mPool->getNumAtlas(); n++ )
mPool->AtlasResize ( n, usedLeafcnt );
SetupAtlasAccess (); // must reassign surf/obj access objects to new glids
PERF_POP ();
}
// Assign new nodes to atlas
PERF_PUSH ( "Assign Atlas" );
for (uint64 n=0; n < totalLeafcnt; n++ ) {
node = getNode ( 0, 0, n );
if (!node->mFlags) continue;
if ( mPool->AtlasAlloc ( 0, brickpos ) ) // assign to atlas brick
node->mValue = brickpos;
}
PERF_POP ();
// Reallocate Atlas Map (if needed)
// -- Note: subdim = full size of atlas including unused bricks
PERF_PUSH ( "Allocate Atlas" );
mPool->AllocateAtlasMap ( sizeof(AtlasNode), mPool->getAtlas(0).subdim );
PERF_POP ();
// ensure mapping for unused bricks
PERF_PUSH ( "Clear mapping" );
ClearMapping ();
PERF_POP ();
// Build Atlas Mapping
PERF_PUSH ( "Atlas Mapping" );
//int brickcnt = totalLeafcnt;//mPool->getAtlas(0).lastEle;
int brickres = mPool->getAtlasBrickres(0);
Vector3DI atlasres = mPool->getAtlasRes(0);
Vector3DI atlasmax = atlasres - brickres + mPool->getAtlas(0).apron;
for (uint64 n=0; n < totalLeafcnt; n++ ) {
Node* node = getNode ( 0, 0, n );
if (!node->mFlags) continue;
if ( node->mValue.x > atlasmax.x || node->mValue.y > atlasmax.y || node->mValue.z > atlasmax.z ) {
gprintf ( "ERROR: Node value exceeds atlas res. node: %d, val: %d %d %d, atlas: %d %d %d\n", n, node->mValue.x, node->mValue.y, node->mValue.z, atlasres.x, atlasres.y, atlasres.z );
gerror ();
}
AssignMapping ( node->mValue, node->mPos, static_cast<int>(n) );
}
PERF_POP ();
// Commit to GPU
PERF_PUSH ( "Commit Atlas Map" );
mPool->PoolCommitAtlasMap (); // Commit Atlas Map (HtoD)
mPool->PoolCommit ( 0, 0 ); // Commit brick nodes *with new values* (HtoD)
PERF_POP ();
PERF_POP ();
POP_CTX
}
// Add a child to a node
slong VolumeGVDB::AddChildNode(slong nodeid, Vector3DF ppos, int plev, uint32 i, Vector3DI pos)
{
// allocate new internal or leaf node
slong child = AllocateNode(plev - 1);
// determine absolute node pos at correct level
Vector3DI range = getRange(plev - 1);
Vector3DI p = getPosFromBit(plev, i);
p *= range;
p += ppos;
// position child
SetupNode(child, plev - 1, p);
// add to list of own children
return InsertChild(nodeid, child, i);
}
// Reparent the VDB tree
slong VolumeGVDB::Reparent(int lev, slong prevroot_id, Vector3DI pos, bool& bNew)
{
Node* prevroot = getNode(prevroot_id);
Vector3DI prevroot_pos = prevroot->mPos;
Vector3DI p, pos1, pos2, range;
bool bCover = false;
// find a level node which covers both the child (former root)
// and the new position
while (!bCover && lev < MAXLEV)
{
lev++;
pos1 = GetCoveringNode(lev, pos, range);
pos2 = GetCoveringNode(lev, prevroot_pos, range);
bCover = (pos1.x == pos2.x && pos1.y == pos2.y && pos1.z == pos2.z);
}
if (lev >= MAXLEV) {
return ID_UNDEFL; // level limit exceeded, return existing root
}
// create new covering root
uint64 newroot_id = AllocateNode(lev);
if (newroot_id == ID_UNDEFL)
return ID_UNDEFL;
SetupNode(newroot_id, lev, pos1);
// insert prevroot into new root
bool bn = false; // prev path does not create new leaf, so ignore bnew
ActivateSpace(newroot_id, prevroot_pos, bn, prevroot_id); // use stopnode to connect paths
// insert new pos into new root
uint64 leaf_id = ActivateSpace(newroot_id, pos, bNew ); // new path may create new leaf (return bNew)
// update root
mRoot = newroot_id;
return getNode(leaf_id)->mParent; // return parent of the new pos
}
// Activate region of space at 3D position
slong VolumeGVDB::ActivateSpace ( Vector3DF pos )
{
Vector3DI brickpos;
bool bnew = false;
slong node_id = ActivateSpace ( mRoot, pos, bnew, ID_UNDEFL, 0 );
if ( node_id == ID_UNDEFL ) return ID_UNDEFL;
if ( !bnew ) return node_id; // exiting node. return
return ID_UNDEFL;
}
// Activate region of space at 3D position down to a given level
slong VolumeGVDB::ActivateSpaceAtLevel ( int lev, Vector3DI pos )
{
Vector3DI brickpos;
bool bnew = false;
slong node_id = ActivateSpace ( mRoot, pos, bnew, ID_UNDEFL, lev ); // specify level to stop
if ( node_id == ID_UNDEFL ) return ID_UNDEFL;
if ( !bnew ) return node_id; // exiting node. return
return ID_UNDEFL;
}
bool VolumeGVDB::isOn (slong nodeid, uint32 b )
{
#ifdef USE_BITMASKS
Node* node = getNode(noideid);
return node->isOn( b );
#else
uint64 cid = getChildNode ( nodeid, b );
return (cid != ID_UNDEF64 );
#endif
}
// Activate space
// - 'nodeid' Starting sub-tree for activation
// - 'pos' Index-space position to activate
// - 'bNew' Returns true if the brick was added
// - 'stopnode' Specific node to stop activation
// - 'stoplev' Specific level to stop activation
slong VolumeGVDB::ActivateSpace ( slong nodeid, Vector3DI pos, bool& bNew, slong stopnode, int stoplev )
{
Vector3DI p;
Vector3DI range;
slong childid;
uint32 b;
if ( mRoot == ID_UNDEFL && nodeid == mRoot ) {
// Create new root
p = GetCoveringNode ( stoplev, pos, range );
mRoot = AllocateNode ( stoplev );
SetupNode ( mRoot, stoplev, p );
nodeid = mRoot;
}
// Activate recursively to leaf
Node* curr = getNode ( nodeid );
if ( getPosInNode ( nodeid, pos, b ) ) {
// check stop node
if (stopnode != ID_UNDEFL) {
Node* stopn = getNode(stopnode);
Vector3DI sp = stopn->mPos;
if (pos.x == sp.x && pos.y == sp.y && pos.z == sp.z && !isOn(nodeid, b) && curr->mLev == stopn->mLev + 1) {
// if same position as stopnode, bit is not on,
return InsertChild( nodeid, stopnode, b);
}
}
// check stop level
if ( curr->mLev == stoplev ) return nodeid;
// point is inside this node, add children
if ( !isOn (nodeid, b ) ) { // not on yet - create new child
childid = AddChildNode ( nodeid, curr->mPos, curr->mLev, b, pos );
if ( curr->mLev==1 ) bNew = true;
} else { // already on - insert into existing child
childid = getChildNode ( nodeid, b );
}
if ( isLeaf ( childid ) ) return childid;
return ActivateSpace ( childid, pos, bNew, stopnode, stoplev );
} else {
// point is outside this node
uint64 parent = curr->mParent;
if ( parent == ID_UNDEFL ) {
parent = Reparent ( curr->mLev, nodeid, pos, bNew ); // make make new lev0 nodes
if ( parent == ID_UNDEFL ) return ID_UNDEFL;
}
// active point inside the (possibly new) parent
return ActivateSpace ( parent, pos, bNew, stopnode, stoplev );
}
}
// Get bit position in node given 3D local brick-space index
bool VolumeGVDB::getPosInNode ( slong curr_id, Vector3DI pos, uint32& bit )
{
Node* curr = getNode ( curr_id );
Vector3DI res = getRes3DI ( curr->mLev );
Vector3DI p = pos; p -= curr->mPos;
Vector3DI range = getRange ( curr->mLev );
if (p.x >= 0 && p.y >=0 && p.z >=0 && p.x < range.x && p.y < range.y && p.z < range.z ) {
// point is inside this node
p *= res;
p /= range;
bit = getBitPos ( curr->mLev, p );
return true;
} else {
bit = 0;
return false;
}
}
const char* binaryStr (uint64 x)
{
static char b[65];
int p = 0;
for (uint64 z = uint64(1) << 63; z > 0; z >>= 1) {
b[p++] = ((x & z) == z) ? '1' : '0';
}
b[64] = '\0';
return b;
}
// Debug a node
void VolumeGVDB::DebugNode ( slong nodeid )
{
Node* curr = getNode ( nodeid );
int b = -1;
int ndx = static_cast<int>(ElemNdx(nodeid));
if ( curr->mLev < 4 && curr->mParent != ID_UNDEFL ) {
Vector3DF range = getRange ( curr->mLev+1 );
Vector3DI p = curr->mPos; p -= getNode(curr->mParent)->mPos; p *= getRes3DI ( curr->mLev+1 ); p /= range;
b = getBitPos ( curr->mLev+1, p );
}
#ifdef USE_BITMASKS
if ( curr->mLev > 0 ) {
gprintf ( "%*s L%d #%d, Bit: %d, Pos: %d %d %d, Mask: %s\n", (5-curr->mLev)*2, "", (int) curr->mLev, ndx, b, curr->mPos.x, curr->mPos.y, curr->mPos.z, binaryStr( *curr->getMask() ) );
for (int n=0; n < curr->getNumChild(); n++ ) {
slong childid = getChildNode ( nodeid, n );
DebugNode ( childid );
}
} else {
gprintf ( "%*s L%d #%d, Bit: %d, Pos: %d %d %d, Atlas: %d %d %d\n", (5-curr->mLev)*2, "", (int) curr->mLev, ndx, b, curr->mPos.x, curr->mPos.y, curr->mPos.z, curr->mValue.x, curr->mValue.y, curr->mValue.z);
}
#endif
}
// Get the index-space position of the corner of a node covering the given 'pos'
Vector3DI VolumeGVDB::GetCoveringNode ( int lev, Vector3DI pos, Vector3DI& range )
{
Vector3DI nodepos;
range = getRange( lev ); // range of node
if ( lev == MAXLEV-1 ) {
nodepos = Vector3DI(0,0,0);
} else {
nodepos = pos;
nodepos /= range;
nodepos = Vector3DI(nodepos) * range; // determine nearest next-level block
if ( pos.x < nodepos.x ) nodepos.x -= range.x;
if ( pos.y < nodepos.y ) nodepos.y -= range.y;
if ( pos.z < nodepos.z ) nodepos.z -= range.z;
}
return nodepos;
}
slong VolumeGVDB::FindParent(int lev, Vector3DI pos)
{
if(mRoot == ID_UNDEFL) return ID_UNDEFL;
Node* nd = getNode(mRoot);
int l = nd->mLev;
if (l == lev) return mRoot;
Vector3DI range, res;
Vector3DF posInNode;
uint32 bitMaskPos;
while (l > lev)
{
res = getRes3DI(l);
range = getRange(l);
posInNode = pos - nd->mPos;
posInNode *= res;
posInNode /= range;
int posInNodeX = static_cast<int>(floor(posInNode.x)); // IMPORTANT!!! truncate decimal
int posInNodeY = static_cast<int>(floor(posInNode.y)); // IMPORTANT!!! truncate decimal
int posInNodeZ = static_cast<int>(floor(posInNode.z)); // IMPORTANT!!! truncate decimal
bitMaskPos = (posInNodeZ*res.x + posInNodeY)*res.x+ posInNodeX;
#ifdef USE_BITMASKS
uint64 p = nd->countOn ( bitMaskPos );
l--;
uint64* clist = mPool->PoolData64(nd->mChildList);
if (l == lev) return clist[p];
nd = getNode(clist[p]);
#else
l--;
uint64* clist = mPool->PoolData64(nd->mChildList);
if (l == lev) return clist[bitMaskPos];
nd = getNode(clist[bitMaskPos]);
#endif
}
return ID_UNDEFL;
}
// Insert child into a child list
slong VolumeGVDB::InsertChild ( slong nodeid, slong childid, uint32 i )
{
Node* curr = getNode ( nodeid );
Node* child = getNode ( childid );
child->mParent = nodeid; // set parent of child
#ifdef USE_BITMASKS
// determine child bit position
assert ( ! curr->isOn ( i ) ); // check if child already exists
uint64 p = curr->countOn ( i );
uint64 cnum = curr->getNumChild(); // existing children count
curr->setOn ( i );
// add child list if doesn't exist
if ( curr->mChildList == ID_UNDEFL ) {
curr->mChildList = mPool->PoolAlloc ( 1, curr->mLev, true );
}
uint64 max_child = mPool->getPoolWidth( 1, curr->mLev ) / sizeof(uint64);
if ( cnum + 1 > max_child ) {
gprintf ( "ERROR: Number of children exceed max of %d (lev %d)\n", max_child, curr->mLev );
gerror ();
}
// insert into child list
uint64* clist = mPool->PoolData64 ( curr->mChildList );
if ( p < cnum ) {
//for (uint64* j = clist + cnum; j > clist + p; j-- )
// *j = *(j-1);
memmove ( clist + p+1, clist + p, (cnum-p)*sizeof(uint64) );
*(clist + p) = childid;
} else {
*(clist + cnum) = childid;
}
int cnt = curr->countOn(); // count children again
#else
if ( curr->mChildList == ID_UNDEFL ) {
curr->mChildList = mPool->PoolAlloc ( 1, curr->mLev, true );
uint64* clist = mPool->PoolData64 ( curr->mChildList );
memset(clist, 0xFF, sizeof(uint64) * getVoxCnt(curr->mLev));
}
// insert into child list
uint64* clist = mPool->PoolData64 ( curr->mChildList );
clist[i] = childid;
#endif
return childid;
}
// Get child node at index
Node* VolumeGVDB::getChild(Node* curr, uint ndx)
{
if (curr->mChildList == ID_UNDEFL) return 0x0;
uint64* clist = mPool->PoolData64(curr->mChildList);
uint64* cnext = (uint64*) mPool->PoolData ( ElemGrp(curr->mChildList), ElemLev(curr->mChildList), ElemNdx(curr->mChildList)+1 );
uint64 ch;
#ifdef USE_BITMASKS
ch = *(clist + ndx);
#else
int vox = 0;
uint sum = 0;
ndx++;
for (; sum < ndx && vox < getVoxCnt(curr->mLev); vox++ ) {
if ( *(clist + vox) != ID_UNDEF64) sum++;
}
if (vox >= getVoxCnt(curr->mLev)) return 0x0;
ch = *(clist + (vox-1) );
#endif
return getNode(ch);
}
// Get child node at bit position
Node* VolumeGVDB::getChildAtBit (Node* curr, uint b)
{
if (curr->mChildList == ID_UNDEFL) return 0x0;
uint64* clist = mPool->PoolData64(curr->mChildList);
#ifdef USE_BITMASKS
uint32 ndx = curr->countOn(b);
uint64 ch = *(clist + ndx);
#else
uint64 ch = *(clist + b);
#endif
if (ch == ID_UNDEF64) return 0x0;
return getNode(ch);
}
uint64 VolumeGVDB::getChildRefAtBit(Node* curr, uint b)
{
if (curr->mChildList == ID_UNDEFL) return ID_UNDEF64;
uint64* clist = mPool->PoolData64(curr->mChildList);
#ifdef USE_BITMASKS
uint32 ndx = curr->countOn(b);
return *(clist + ndx);
#else
return *(clist + b);
#endif
}
// Get child node at bit position
uint64 VolumeGVDB::getChildNode ( slong nodeid, uint b )
{
Node* curr = getNode ( nodeid );
if (curr->mChildList == ID_UNDEFL) return ID_UNDEF64;
uint64* clist = mPool->PoolData64 ( curr->mChildList );
#ifdef USE_BITMASKS
uint32 ndx = curr->countOn ( b );
return *(clist + ndx);
#else
return *(clist + b);
#endif
}
// Get child a given local 3D brick position
uint32 VolumeGVDB::getChildOffset ( slong nodeid, slong childid, Vector3DI& pos )
{
Node* curr = getNode ( nodeid );
Node* child = getNode ( childid );
pos = child->mPos;
pos -= curr->mPos;
pos *= getRes3DI ( curr->mLev );
pos /= getRange ( curr->mLev );
return getBitPos ( curr->mLev, pos );
}
void VolumeGVDB::writeCube ( FILE* fp, unsigned char vpix[], slong& numfaces, int gv[], int*& vgToVert, slong vbase )
{
// find absolute vert indices for this cube
// * map from local grid index to local vertex id, then add base index for this leaf
slong v[8];
vbase++; // * .obj file indices are base 1;
v[0] = vbase + vgToVert[ gv[0] ];
v[1] = vbase + vgToVert[ gv[1] ];
v[2] = vbase + vgToVert[ gv[2] ];
v[3] = vbase + vgToVert[ gv[3] ];
v[4] = vbase + vgToVert[ gv[4] ];
v[5] = vbase + vgToVert[ gv[5] ];
v[6] = vbase + vgToVert[ gv[6] ];
v[7] = vbase + vgToVert[ gv[7] ];
if ( vpix[1] == 0 ) {fprintf(fp, "f %lld//0 %lld//0 %lld//0 %lld//0\n", v[1], v[2], v[6], v[5] ); numfaces++; } // x+
if ( vpix[2] == 0 ) {fprintf(fp, "f %lld//1 %lld//1 %lld//1 %lld//1\n", v[0], v[3], v[7], v[4] ); numfaces++; } // x-
if ( vpix[3] == 0 ) {fprintf(fp, "f %lld//2 %lld//2 %lld//2 %lld//2\n", v[2], v[3], v[7], v[6] ); numfaces++; } // y+
if ( vpix[4] == 0 ) {fprintf(fp, "f %lld//3 %lld//3 %lld//3 %lld//3\n", v[1], v[0], v[4], v[5] ); numfaces++; } // y-
if ( vpix[5] == 0 ) {fprintf(fp, "f %lld//4 %lld//4 %lld//4 %lld//4\n", v[4], v[5], v[6], v[7] ); numfaces++; } // z+
if ( vpix[6] == 0 ) {fprintf(fp, "f %lld//5 %lld//5 %lld//5 %lld//5\n", v[0], v[1], v[2], v[3] ); numfaces++; } // z-
}
void VolumeGVDB::enableVerts ( int*& vgToVert, std::vector<Vector3DF>& verts, Vector3DF vm, int gv[] )
{
if ( vgToVert[ gv[0] ] == -1) { vgToVert[ gv[0] ] = (int) verts.size (); verts.push_back ( vm ); }
if ( vgToVert[ gv[1] ] == -1) { vgToVert[ gv[1] ] = (int) verts.size (); verts.push_back ( vm+Vector3DF(1,0,0) ); }
if ( vgToVert[ gv[2] ] == -1) { vgToVert[ gv[2] ] = (int) verts.size (); verts.push_back ( vm+Vector3DF(1,1,0) ); }
if ( vgToVert[ gv[3] ] == -1) { vgToVert[ gv[3] ] = (int) verts.size (); verts.push_back ( vm+Vector3DF(0,1,0) ); }
if ( vgToVert[ gv[4] ] == -1) { vgToVert[ gv[4] ] = (int) verts.size (); verts.push_back ( vm+Vector3DF(0,0,1) ); }
if ( vgToVert[ gv[5] ] == -1) { vgToVert[ gv[5] ] = (int) verts.size (); verts.push_back ( vm+Vector3DF(1,0,1) ); }
if ( vgToVert[ gv[6] ] == -1) { vgToVert[ gv[6] ] = (int) verts.size (); verts.push_back ( vm+Vector3DF(1,1,1) ); }
if ( vgToVert[ gv[7] ] == -1) { vgToVert[ gv[7] ] = (int) verts.size (); verts.push_back ( vm+Vector3DF(0,1,1) ); }
}
void VolumeGVDB::setupVerts ( int gv[], Vector3DI g, int r1, int r2 )
{
int g0 = (g.z*r1 + g.y)*r1 + g.x ; // local index of first vertex
gv[0] = g0;
gv[1] = g0 + 1;
gv[2] = g0 + r1+1;
gv[3] = g0 + r1;
gv[4] = g0 + r2;
gv[5] = g0 + r2+1;
gv[6] = g0 + r2+r1+1;
gv[7] = g0 + r2+r1;
}
void VolumeGVDB::WriteObj ( char* fname )
{
//NOT IMPLEMENTED
//TODO - IMPLEMENT OR RAISE EXCEPTION
}
// Validate OpenGL
// - Set the current OpenGL context for GL operations
void VolumeGVDB::ValidateOpenGL ()
{
#ifdef BUILD_OPENGL
if ( !mbGlew ) {
mbGlew = true;
glewExperimental = GL_TRUE;
glewInit ();
}
#if defined(_WIN32)
HGLRC ctx = wglGetCurrentContext ();
#else
void* ctx = glXGetCurrentContext();
#endif
if ( ctx == NULL ) {
gprintf ( "ERROR: Cannot validate OpenGL. No context active.\n" );
return;
}
#endif
}
// Start Raster GL
// - Enable the GL rasterization pipeline.
// - Load GLSL shaders
void VolumeGVDB::StartRasterGL ()
{
#ifdef BUILD_OPENGL
ValidateOpenGL ();
makeSimpleShaderGL (mScene, "simple.vert.glsl", "simple.frag.glsl");
makeVoxelizeShader ( mScene, "voxelize.vert.glsl", "voxelize.frag.glsl", "voxelize.geom.glsl" );
#endif
}
// Create OpenGL atlases (optional)
void VolumeGVDB::UseOpenGLAtlas ( bool tf )
{
mbUseGLAtlas = tf;
#ifdef BUILD_OPENGL
if ( mbUseGLAtlas ) ValidateOpenGL();
#endif
}
// Prepare 3D texture for intermediate sub-volume
void VolumeGVDB::PrepareV3D ( Vector3DI ires, uchar dtype )
{
PUSH_CTX
if ( mV3D == 0x0 ) {
mV3D = new Volume3D ( mScene ) ;
mV3D->Resize ( dtype, ires, 0x0, true );
mV3D->PrepareRasterGL ( true );
} else {
if ( !mV3D->hasSize( ires, dtype ) ) {
mV3D->Resize ( dtype, ires, 0x0, true );
mV3D->PrepareRasterGL ( (ires.x==0) ? false : true );
}
}
POP_CTX
}
Vector3DI VolumeGVDB::getNearestAbsVox ( int lev, Vector3DF pnt )
{
Vector3DF cover = getCover(lev);
return pnt / cover;
}
// Compute index-space extents given world bounding box
Extents VolumeGVDB::ComputeExtents ( int lev, Vector3DF obj_min, Vector3DF obj_max )
{
// Compute index extents given world extents
Extents e;
e.lev = lev;
e.vmin = obj_min; // world-space bounds
e.vmax = obj_max;
e.cover = getCover(lev-1);
e.imin = e.vmin / e.cover; // absolute index-space extents of children
e.imax = (e.vmax / e.cover) - Vector3DI(1,1,1);
e.ires = e.imax; e.ires -= e.imin; e.ires += Vector3DI(1, 1, 1);
e.icnt = e.ires.x * e.ires.y * e.ires.z;
return e;
}
// Compute index-space extents given a node
Extents VolumeGVDB::ComputeExtents ( Node* node )
{
// Compute index and world extent given node
Extents e;
e.lev = node->mLev;
Vector3DI range = getRange(e.lev-1);
e.cover = getCover(e.lev-1);
e.imin = node->mPos / range; // absolute index-space extents of children
e.imax = (node->mPos / range) + getRes3DI(e.lev) - Vector3DI(1,1,1);
e.vmin = Vector3DF(e.imin) * e.cover; // world-space bounds of children
e.vmax = Vector3DF(e.imax + Vector3DI(1,1,1)) * e.cover;
e.ires = e.imax; e.ires -= e.imin; e.ires += Vector3DI(1, 1, 1);
e.icnt = e.ires.x * e.ires.y * e.ires.z;
return e;
}
// Map an OpenGL VBO to auxiliary geometry
void VolumeGVDB::AuxGeometryMap ( Model* model, int vertaux, int elemaux )
{
PUSH_CTX
DataPtr* vaux = &mAux[vertaux];
DataPtr* eaux = &mAux[elemaux];
size_t vsize, esize;
cudaCheck(cuGraphicsGLRegisterBuffer( &vaux->grsc, model->vertBufferID, CU_GRAPHICS_MAP_RESOURCE_FLAGS_READ_ONLY), "VolumeGVDB", "AuxGeometryMap", "cuGraphicsGLRegisterBuffer", "vaux", mbDebug);
cudaCheck(cuGraphicsMapResources(1, &vaux->grsc, 0), "VolumeGVDB", "AuxGeometryMap", "cuGraphicsMapResources", "vaux", mbDebug );
cudaCheck(cuGraphicsResourceGetMappedPointer ( &vaux->gpu, &vsize, vaux->grsc ), "VolumeGVDB", "AuxGeometryMap", "cuGraphicsResourceGetMappedPointer ", "vaux", mbDebug );
vaux->lastEle = model->vertCount;
vaux->usedNum = model->vertCount;
vaux->stride = model->vertStride;
vaux->size = vsize;
cudaCheck(cuGraphicsGLRegisterBuffer( &eaux->grsc, model->elemBufferID, CU_GRAPHICS_MAP_RESOURCE_FLAGS_READ_ONLY), "VolumeGVDB", "AuxGeometryMap", "cuGraphicsGLRegisterBuffer", "eaux", mbDebug);
cudaCheck(cuGraphicsMapResources(1, &eaux->grsc, 0), "VolumeGVDB", "AuxGeometryMap", "cuGraphicsMapResources", "eaux", mbDebug );
cudaCheck(cuGraphicsResourceGetMappedPointer ( &eaux->gpu, &esize, eaux->grsc ), "VolumeGVDB", "AuxGeometryMap", "cuGraphicsResourceGetMappedPointer", "eaux", mbDebug);
eaux->lastEle = model->elemCount;
eaux->usedNum = model->elemCount;
eaux->stride = model->elemStride;
eaux->size = esize;
POP_CTX
}
// Unmap an OpenGL VBO
void VolumeGVDB::AuxGeometryUnmap ( Model* model, int vertaux, int elemaux )
{
PUSH_CTX
DataPtr* vaux = &mAux[vertaux];
DataPtr* eaux = &mAux[elemaux];
cudaCheck(cuGraphicsUnmapResources(1, &vaux->grsc, 0), "VolumeGVDB", "AuxGeometryUnmap", "cuGraphicsUnmapResources", "vaux", mbDebug);
cudaCheck(cuGraphicsUnmapResources(1, &eaux->grsc, 0), "VolumeGVDB", "AuxGeometryUnmap", "cuGraphicsUnmapResources", "eaux", mbDebug);
POP_CTX
}
void VolumeGVDB::Synchronize() {
PUSH_CTX
cuCtxSynchronize();
POP_CTX
}
// Activate a region of space
int VolumeGVDB::ActivateRegion ( int lev, Extents& e )
{
Vector3DI pos;
uint64 leaf;
int cnt = 0;
assert ( lev == e.lev-1 ); // make sure extens match desired level
for (int z=e.imin.z; z <= e.imax.z; z++ )
for (int y=e.imin.y; y <= e.imax.y; y++ )
for (int x=e.imin.x; x <= e.imax.x; x++ ) {
pos.Set(x, y, z); pos *= e.cover;
leaf = ActivateSpaceAtLevel ( e.lev-1, pos );
cnt++;
}
return cnt;
}
int VolumeGVDB::ActivateHalo(Extents& e)
{
Vector3DI pos, nbr;
int cnt, actv;
// tag buffer
int sz = e.ires.x*e.ires.y*e.ires.z * sizeof(uchar);
uchar* tagbuf = (uchar*) malloc( sz );
memset(tagbuf, 0, sz);
// Tag halo regions
cnt = 0;
for (int z = e.imin.z; z <= e.imax.z; z++)
for (int y = e.imin.y; y <= e.imax.y; y++)
for (int x = e.imin.x; x <= e.imax.x; x++) {
pos.Set(x, y, z); pos *= e.cover;
if (!isActive(pos)) {
actv = 0;
nbr = pos + Vector3DF(-1, 0, 0)*e.cover; if (isActive(nbr)) actv++;
nbr = pos + Vector3DF(1, 0, 0)*e.cover; if (isActive(nbr)) actv++;
nbr = pos + Vector3DF(0, -1, 0)*e.cover; if (isActive(nbr)) actv++;
nbr = pos + Vector3DF(0, 1, 0)*e.cover; if (isActive(nbr)) actv++;
nbr = pos + Vector3DF(0, 0, -1)*e.cover; if (isActive(nbr)) actv++;
nbr = pos + Vector3DF(0, 0, 1)*e.cover; if (isActive(nbr)) actv++;
if (actv > 0) {
tagbuf[( (z - e.imin.z)*e.ires.y + (y - e.imin.y) )*e.ires.x + (x - e.imin.x)] = 1;
}
}
}
// Activate space at tags
for (int z = e.imin.z; z <= e.imax.z; z++)
for (int y = e.imin.y; y <= e.imax.y; y++)
for (int x = e.imin.x; x <= e.imax.x; x++) {
pos.Set(x, y, z); pos *= e.cover;
if (tagbuf[((z - e.imin.z)*e.ires.y + (y - e.imin.y))*e.ires.x + (x - e.imin.x)] > 0) {
ActivateSpaceAtLevel(e.lev - 1, pos);
cnt++;
}
}
free(tagbuf);
return cnt;
}
// Activate a region of space from an auxiliary byte buffer
int VolumeGVDB::ActivateRegionFromAux (Extents& e, int auxid, uchar dt, float vthresh)
{
Vector3DI pos;
uint64 leaf;
char* vdat = mAux[auxid].cpu; // Get AUX data
int cnt = 0;
switch (dt) {
case T_UCHAR: {
for (int z = e.imin.z; z <= e.imax.z; z++)
for (int y = e.imin.y; y <= e.imax.y; y++)
for (int x = e.imin.x; x <= e.imax.x; x++) {
uchar vset = *(vdat + ((z - e.imin.z)*e.ires.y + (y - e.imin.y))*e.ires.x + (x - e.imin.x));
if (vset > vthresh) {
pos.Set(x, y, z); pos *= e.cover;
leaf = ActivateSpaceAtLevel(e.lev - 1, pos); cnt++;
}
}
} break;
case T_FLOAT: {
for (int z = e.imin.z; z <= e.imax.z; z++)
for (int y = e.imin.y; y <= e.imax.y; y++)
for (int x = e.imin.x; x <= e.imax.x; x++) {
float vset = *(((float*)vdat) + ((z - e.imin.z)*e.ires.y + (y - e.imin.y))*e.ires.x + (x - e.imin.x));
if (vset > vthresh) {
pos.Set(x, y, z); pos *= e.cover;
leaf = ActivateSpaceAtLevel(e.lev - 1, pos); cnt++;
}
}
} break;
};
return cnt;
}
// Check data returned from GPU
void VolumeGVDB::CheckData ( std::string msg, CUdeviceptr ptr, int dt, int stride, int cnt )
{
PUSH_CTX
char* dat = (char*) malloc ( stride*cnt );
cudaCheck ( cuMemcpyDtoH ( dat, ptr, stride*cnt ), "VolumeGVDB", "CheckData", "cuMemcpyDtoH", "", mbDebug);
gprintf ( "%s\n", msg.c_str() );
char* p = dat;
for (int n=0; n < cnt; n++ ) {
switch ( dt ) {
case T_FLOAT: gprintf ( "%d: %f\n", n, *(float*) dat ); break;
case T_INT: gprintf ( "%d: %d\n", n, *(int*) dat ); break;
case T_FLOAT3:
float3 v = *(float3*) dat;
gprintf ( "%d: %f %f %f\n", n, v.x, v.y, v.z ); break;
};
dat += stride;
}
POP_CTX
}
// Voxelize a node from polygons
int VolumeGVDB::VoxelizeNode ( Node* node, uchar chan, Matrix4F* xform, float bdiv, float val_surf, float val_inside, float vthresh )
{
int cnt = 0;
Extents e = ComputeExtents ( node );
// CUDA voxelize
uchar dt = mPool->getAtlas(chan).type;
PrepareAux ( AUX_VOXELIZE, e.icnt, mPool->getSize(dt), true, true ); // Prepare buffer for data retrieve
Vector3DI block ( 8, 8, 8 );
Vector3DI grid ( int(e.ires.x/block.x) + 1, int(e.ires.y/block.y) + 1, int(e.ires.z/block.z) + 1 );
int bmax = static_cast<int>(mAux[AUX_GRIDOFF].lastEle);
void* args[12] = { &e.vmin, &e.vmax, &e.ires, &mAux[AUX_VOXELIZE].gpu, &dt, &val_surf, &val_inside,
&bdiv, &bmax, &mAux[AUX_GRIDCNT].gpu, &mAux[AUX_GRIDOFF].gpu, &mAux[AUX_TRI_BUF].gpu };
cudaCheck(cuLaunchKernel(cuFunc[FUNC_VOXELIZE], grid.x, grid.y, grid.z, block.x, block.y, block.z, 0, NULL, args, NULL),
"VolumeGVDB", "VoxelizeNode", "cuLaunch", "FUNC_VOXELIZE", mbDebug );
if ( node->mLev==0 ) {
mPool->AtlasCopyLinear ( chan, node->mValue, mAux[AUX_VOXELIZE].gpu );
} else {
RetrieveData ( mAux[AUX_VOXELIZE] );
cnt = ActivateRegionFromAux ( e, AUX_VOXELIZE, dt, vthresh);
}
#ifdef VOX_GL
// OpenGL voxelize
uchar dt = mPool->getAtlas(chan).type;
PrepareV3D ( e.ires, dt ); // Preapre 3D Texture for hardware raster
mV3D->SurfaceVoxelizeFastGL ( e.vmin, e.vmax, xform ); // Voxelize with graphics pipeline
if ( node->mLev==0 ) { // Generate voxels in a brick..
mPool->AtlasCopyTex ( chan, node->mValue, mV3D->getPtr() ); // Copy voxels into GVDB atlas
cudaCheck ( cuCtxSynchronize(), "sync(AtlasCopyData)" ); // Must sync after CUDA copy
} else { // OR Generate children..
PrepareAux ( AUX_VOXELIZE, e.icnt, mPool->getSize(dt), true, true );// Prepare CPU buffer for data retrieve
mV3D->RetrieveGL ( mAux[AUX_VOXELIZE].cpu ); // Retrieve into CPU buffer
cnt = ActivateRegionFromAux ( e, AUX_VOXELIZE, dt ); // Activate nodes at next level down
}
#endif
return cnt;
}
// SolidVoxelize - Voxelize a polygonal mesh to a sparse volume
void VolumeGVDB::SolidVoxelize ( uchar chan, Model* model, Matrix4F* xform, float val_surf, float val_inside, float vthresh )
{
PUSH_CTX
//TimerStart();
AuxGeometryMap ( model, AUX_VERTEX_BUF, AUX_ELEM_BUF ); // Setup VBO for CUDA (interop)
// Prepare model geometry for use by CUDA
cudaCheck ( cuMemcpyHtoD ( cuXform, xform->GetDataF(), sizeof(float)*16), "VolumeGVDB", "SolidVoxelize", "cuMemcpyHtoD", "cuXform", mbDebug ); // Send transform
// Identify model bounding box
model->ComputeBounds ( *xform, 0.1f );
mObjMin = model->objMin; mObjMax = model->objMax;
mVoxMin = mObjMin;
mVoxMax = mObjMax;
mVoxRes = mVoxMax; mVoxRes -= mVoxMin;
// VDB Hierarchical Rasterization
Clear (); // creates a new root
// Voxelize all nodes in bounding box at starting level
int N = mPool->getNumLevels ();
Extents e = ComputeExtents ( N, mObjMin, mObjMax ); // start - level N
ActivateRegion ( N-1, e ); // activate - level N-1
#ifdef VOX_GL
PrepareV3D ( Vector3DI(8,8,8), 0 );
#endif
// Voxelize at each level
int node_cnt, cnt;
Node* node;
for (int lev = N-1; lev >= 0; lev-- ) { // scan - level N-1 down to 0
node_cnt = static_cast<int>(getNumUsedNodes(lev));
cnt = 0;
// Insert triangles into bins
float ydiv = getCover(lev).y; // use brick boundaries for triangle sorting
Vector3DI tcnts = InsertTriangles ( model, xform, ydiv );
// Voxelize each node at this level
for (int n = 0; n < node_cnt; n++ ) { // get each node at current
node = getNodeAtLevel ( n, lev );
cnt += VoxelizeNode ( node, chan, xform, ydiv, val_surf, val_inside, vthresh); // Voxelize each node
}
if ( lev==1 ) { // Finish and Update atlas before doing bricks
FinishTopology( true, true );
UpdateAtlas();
}
verbosef("Voxelized.. lev: %d, nodes: %d, new: %d\n", lev, node_cnt, cnt );
}
// Update apron
UpdateApron ();
#ifdef VOX_GL
PrepareV3D ( Vector3DI(0,0,0), 0 );
#endif
AuxGeometryUnmap ( model, AUX_VERTEX_BUF, AUX_ELEM_BUF );
POP_CTX
//float msec = TimerStop();
//verbosef( "Voxelize Complete: %4.2f\n", msec );
}
// Insert triangles into auxiliary bins
Vector3DI VolumeGVDB::InsertTriangles ( Model* model, Matrix4F* xform, float& ydiv )
{
PUSH_CTX
// Identify model bounding box
model->ComputeBounds ( *xform, 0.1f );
int ybins = int(model->objMax.y / ydiv)+1; // y divisions align with lev0 brick boundaries
PrepareAux ( AUX_GRIDCNT, ybins, sizeof(uint), true, true ); // allow return to cpu
PrepareAux ( AUX_GRIDOFF, ybins, sizeof(uint), false, false );
int vcnt = static_cast<int>(mAux[AUX_VERTEX_BUF].lastEle); // input
int ecnt = static_cast<int>(mAux[AUX_ELEM_BUF].lastEle);
int tri_cnt = 0; // output
Vector3DI block ( 512, 1, 1 );
Vector3DI grid ( int(ecnt/block.x)+1, 1, 1 );
void* args[7] = { &ydiv, &ybins, &mAux[AUX_GRIDCNT].gpu, &vcnt, &ecnt, &mAux[AUX_VERTEX_BUF].gpu, &mAux[AUX_ELEM_BUF].gpu };
cudaCheck( cuLaunchKernel(cuFunc[FUNC_INSERT_TRIS], grid.x, 1, 1, block.x, 1, 1, 0, NULL, args, NULL),
"VolumeGVDB", "InsertTriangles", "cuLaunch", "FUNC_INSERT_TRIS", mbDebug);
// Prefix sum for bin offsets
PrefixSum ( mAux[AUX_GRIDCNT].gpu, mAux[AUX_GRIDOFF].gpu, ybins );
// Sort triangles into bins (deep copy)
RetrieveData ( mAux[AUX_GRIDCNT] );
uint* cnt = (uint*) mAux[AUX_GRIDCNT].cpu;
for (int n=0; n < ybins; n++ ) tri_cnt += cnt[n]; // get total - should return from prefixsum
// Reset grid counts
cudaCheck ( cuMemsetD8 ( mAux[AUX_GRIDCNT].gpu, 0, sizeof(uint)*ybins ), "VolumeGVDB", "InsertTriangles", "cuMemsetD8", "AUX_GRIDCNT", mbDebug);
// Prepare output triangle buffer
PrepareAux ( AUX_TRI_BUF, tri_cnt, sizeof(Vector3DF)*3, false, false );
// Deep copy sorted tris into output buffer
block.Set ( 512, 1, 1 );
grid.Set ( int(tri_cnt/block.x)+1, 1, 1 );
void* args2[10] = { &ydiv, &ybins, &mAux[AUX_GRIDCNT].gpu, &mAux[AUX_GRIDOFF].gpu, &tri_cnt, &mAux[AUX_TRI_BUF].gpu, &vcnt, &ecnt, &mAux[AUX_VERTEX_BUF].gpu, &mAux[AUX_ELEM_BUF].gpu };
cudaCheck ( cuLaunchKernel ( cuFunc[FUNC_SORT_TRIS], grid.x, 1, 1, block.x, 1, 1, 0, NULL, args2, NULL ),
"VolumeGVDB", "InsertTriangles", "cuLaunch", "FUNC_SORT_TRIS", mbDebug );
POP_CTX
return Vector3DI( ybins, tri_cnt, ecnt); // return: number of bins, total inserted tris, original tri count
}
// Voxelize a mesh as surface voxels using OpenGL hardware rasterizer
void VolumeGVDB::SurfaceVoxelizeGL ( uchar chan, Model* model, Matrix4F* xform )
{
PUSH_CTX
#ifdef BUILD_OPENGL
Volume3D vtemp ( mScene ) ;
std::vector< Vector3DF > leaf_pos;
std::vector< uint64 > leaf_ptr;
slong leaf;
int res0 = getRes ( 0 );
Vector3DI vres0 ( res0, res0, res0 ); // leaf resolution
Vector3DF vrange0 = getRange(0);
// VDB Hierarchical Rasterization
PERF_PUSH ( "clear" );
Clear (); // creates a new root
PERF_POP ();
// Configure model
model->ComputeBounds ( *xform, 0.1f );
mObjMin = model->objMin; mObjMax = model->objMax;
mVoxMin = mObjMin;
mVoxMax = mObjMax;
mVoxRes = mVoxMax; mVoxRes -= mVoxMin;
// Determine which leaf voxels to activate
PERF_PUSH ( "activate" );
int res1 = getRes ( 1 );
Vector3DI vres1 ( res1, res1, res1 ); // large-scale resolution = level 1
Vector3DF vmin0, vmin1, vmax1;
Vector3DF vrange1 = getRange(1);
Vector3DI vstart, vstop;
float* vdat = (float*) malloc ( res1*res1*res1*sizeof(float) );
unsigned char vpix[8], c[8];
vstart = mVoxMin; vstart /= vrange1;
vstop = mVoxMax; vstop /= vrange1;
// Resize temporary volume to level 1
vtemp.Resize ( T_FLOAT, vres1, 0x0, true ); // use opengl
verbosef( " L1 range: %d %d %d, %d %d %d\n", vstart.x, vstart.y, vstart.z, vstop.x, vstop.y, vstop.z);
vtemp.PrepareRasterGL ( true );
// Scan over domain with level-1 rasterize
bool bnew = false;
for ( int z1 = vstart.z; z1 <= vstop.z; z1++ ) {
for ( int y1 = vstart.y; y1 <= vstop.y; y1++ ) {
for ( int x1 = vstart.x; x1 <= vstop.x; x1++ ) {
// Rasterize at level 1 (green)
vmin1 = Vector3DI(x1+0, y1+0, z1+0); vmin1 *= vrange1;
vmax1 = Vector3DI(x1+1, y1+1, z1+1); vmax1 *= vrange1;
vtemp.SurfaceVoxelizeFastGL ( vmin1, vmax1, xform );
// Readback the voxels
vtemp.RetrieveGL ( (char*) vdat );
// Identify leaf nodes at level-1
for ( int z0=0; z0 < res1; z0++ ) {
for ( int y0=0; y0 < res1; y0++ ) {
for ( int x0=0; x0 < res1; x0++ ) {
vpix[0] = static_cast<uchar>(*(vdat + (z0*res1 + y0)*res1 + x0));
if ( vpix[0] > 0 ) {
vmin0.x = vmin1.x + x0 * vrange1.x / res1;
vmin0.y = vmin1.y + y0 * vrange1.y / res1;
vmin0.z = vmin1.z + z0 * vrange1.z / res1;
leaf = ActivateSpace ( mRoot, vmin0, bnew );
if ( leaf != ID_UNDEFL ) {
leaf_pos.push_back ( vmin0 );
leaf_ptr.push_back ( leaf );
}
} else {
// correction when not using conservative raster
c[1]=c[2]=c[3]=c[4]=c[5]=c[6] = 0;
vpix[1] = static_cast<uchar>((x0 == res1 - 1) ? 0 : *(vdat + (z0 * res1 + y0) * res1 + (x0 + 1)));
vpix[2] = static_cast<uchar>((y0 == res1 - 1) ? 0 : *(vdat + (z0 * res1 + (y0 + 1)) * res1 + x0));
vpix[3] = static_cast<uchar>((z0 == res1 - 1) ? 0 : *(vdat + ((z0 + 1) * res1 + y0) * res1 + x0));
vpix[4] = static_cast<uchar>((x0 == 0) ? 0 : *(vdat + (z0 * res1 + y0) * res1 + (x0 - 1)));
vpix[5] = static_cast<uchar>((y0 == 0) ? 0 : *(vdat + (z0 * res1 + (y0 - 1)) * res1 + x0));
vpix[6] = static_cast<uchar>((z0 == 0) ? 0 : *(vdat + ((z0 - 1) * res1 + y0) * res1 + x0));
vpix[7] = (vpix[1] > 0) + (vpix[2] > 0) + (vpix[3] > 0) + (vpix[4] > 0) + (vpix[5] > 0 ) + (vpix[6] > 0 );
if ( vpix[7] > 0 ) {
vmin0.x = vmin1.x + x0 * vrange1.x / res1;
vmin0.y = vmin1.y + y0 * vrange1.y / res1;
vmin0.z = vmin1.z + z0 * vrange1.z / res1;
leaf = ActivateSpace ( mRoot, vmin0, bnew );
if ( leaf != ID_UNDEFL ) {
leaf_pos.push_back ( vmin0 );
leaf_ptr.push_back ( leaf );
}
}
c[1]=c[2]=c[3]=c[4]=c[5]=c[6] = 0;
vpix[1] = static_cast<uchar>((x0 == res1 - 1) ? (++c[1] == 1) : *(vdat + (z0 * res1 + y0) * res1 + (x0 + 1)));
vpix[2] = static_cast<uchar>((y0 == res1 - 1) ? (++c[2] == 1) : *(vdat + (z0 * res1 + (y0 + 1)) * res1 + x0));
vpix[3] = static_cast<uchar>((z0 == res1 - 1) ? (++c[3] == 1) : *(vdat + ((z0 + 1) * res1 + y0) * res1 + x0));
vpix[4] = static_cast<uchar>((x0 == 0) ? (++c[4] == 1) : *(vdat + (z0 * res1 + y0) * res1 + (x0 - 1)));
vpix[5] = static_cast<uchar>((y0 == 0) ? (++c[5] == 1) : *(vdat + (z0 * res1 + (y0 - 1)) * res1 + x0));
vpix[6] = static_cast<uchar>((z0 == 0) ? (++c[6] == 1) : *(vdat + ((z0 - 1) * res1 + y0) * res1 + x0));
vpix[7] = (vpix[1] > 0) + (vpix[2] > 0) + (vpix[3] > 0) + (vpix[4] > 0) + (vpix[5] > 0 ) + (vpix[6] > 0 );
c[7] = (c[1]+c[2]+c[3]+c[4]+c[5]+c[6] == 3) ? 1 : 0;
if ( vpix[7] >= 3 + c[7] ) {
vmin0.x = vmin1.x + x0 * vrange1.x / res1;
vmin0.y = vmin1.y + y0 * vrange1.y / res1;
vmin0.z = vmin1.z + z0 * vrange1.z / res1;
leaf = ActivateSpace ( mRoot, vmin0, bnew );
if ( leaf != ID_UNDEFL ) {
leaf_pos.push_back ( vmin0 );
leaf_ptr.push_back ( leaf );
}
}
}
}
}
}
}
}
}
PERF_POP ();
FinishTopology ();
UpdateAtlas ();
cudaCheck ( cuCtxSynchronize(), "VolumeGVDB", "SurfaceVoxelizeGL", "cuCtxSynchronize", "", mbDebug );
vtemp.PrepareRasterGL ( false );
verbosef( " # of leaves: %d\n", leaf_ptr.size() );
if ( leaf_ptr.size()==0 ) {
gprintf ( " ERROR: No data generated.\n" );
free ( vdat );
return;
}
// Create atlas if none exists
if ( chan >= mPool->getNumAtlas() ) {
gprintf ( " ERROR: Channel %d not defined for SurfaceVoxelizeGL. Call AddChannel first.\n", (int) chan );
free ( vdat );
return;
}
// Resize temp 3D texture to match leaf res
vtemp.Resize ( T_FLOAT, vres0, 0x0, true );
if ( leaf_ptr.size() > 0 ) {
// Rasterize each leaf node
PERF_PUSH ( "rasterize" );
vtemp.PrepareRasterGL ( true );
for (int n=0; n < leaf_ptr.size(); n++ ) {
// Rasterize into temporary 3D texture
vtemp.SurfaceVoxelizeFastGL ( leaf_pos[n], leaf_pos[n] + vrange0, xform );
// Copy 3D texture in VDB atlas
Node* node = getNode ( leaf_ptr[n] );
if ( node == 0x0 || node->mValue.x == -1 ) {
gprintf ( "WARNING: Node or value is empty in SurfaceVoxelizeGL.\n" );
} else {
mPool->AtlasCopyTex ( chan, node->mValue, vtemp.getPtr() );
}
}
vtemp.PrepareRasterGL ( false );
PERF_POP ();
}
glFinish ();
cudaCheck ( cuCtxSynchronize(), "VolumeGVDB", "SurfaceVoxelizeGL", "cuCtxSynchronize", "", mbDebug );
free ( vdat );
POP_CTX
#endif
}
Vector3DF VolumeGVDB::MemoryUsage(std::string name, std::vector<std::string>& outlist )
{
PUSH_CTX
float vol_total=0, vol_dense = 0;
float MB = (1024.f*1024.f);
char str[1024];
int bpv;
float curr;
Vector3DF mem = cudaGetMemUsage();
for (int n = 0; n < mPool->getNumAtlas(); n++) {
bpv = mPool->getSize(mPool->getAtlas(n).type);
curr = float(mPool->getAtlas(n).size) / MB;
sprintf ( str, "%s, Voxel Channel %d: %6.2f MB (%4.2f%%)\n", name.c_str(), n, curr, float(curr*100.0/mem.x) );
outlist.push_back(str);
vol_total += curr;
vol_dense += (mVoxResMax.x * mVoxResMax.y * mVoxResMax.z) * bpv;
}
sprintf(str, "%s, Volume Total: %6.2f MB (%4.2f%%)\n", name.c_str(), vol_total, float(vol_total*100.0 / mem.x));
outlist.push_back(str);
float aux_total = 0;
for (int n = 0; n < MAX_AUX; n++) {
if (mAux[n].size > 0) {
curr = float(mAux[n].size) / MB;
sprintf(str, "%s, Aux %02d: %6.2f MB (%4.2f%%) - %s\n", name.c_str(), n, curr, float(curr*100.0 / mem.x), mAuxName[n].c_str() );
outlist.push_back(str);
aux_total += curr;
}
}
sprintf(str, "%s, Aux Total: %6.2f MB (%4.2f%%)\n", name.c_str(), aux_total, float(aux_total*100.0 / mem.x));
outlist.push_back(str);
POP_CTX
return mem;
}
// Measure pools
float VolumeGVDB::MeasurePools ()
{
uint64 pool0_total=0, pool1_total=0;
int levs = mPool->getNumLevels ();
float MB = 1024.0*1024.0;
for (int n=0; n < levs; n++ ) {
pool0_total += mPool->getPoolSize ( 0, n );
pool1_total += mPool->getPoolSize ( 1, n );
}
return (pool0_total + pool1_total) / MB;
}
// getUsage - Quickly report memory info
// - ext = Extents of volume in voxels
// - vox = # Bricks, # Voxels(M), Occupancy (%)
// - used = Topology total (MB), Atlas total (MB), Aux total (MB)
// - free = GPU mem free (MB), GPU total mem (MB)
//
void VolumeGVDB::getUsage( Vector3DF& ext, Vector3DF& vox, Vector3DF& used, Vector3DF& free )
{
float MB = 1024.0*1024.0; // convert to MB
// extents
RetrieveVDB();
ext = mVoxResMax;
// brick/voxel count
if (mPool->getNumAtlas() > 0) {
int leafdim = static_cast<int>(mPool->getAtlas(0).stride);
Vector3DI vb = mVoxResMax; vb /= Vector3DI(leafdim, leafdim, leafdim);
long vbrk = vb.x*vb.y*vb.z; // number of bricks covering bounded world domain
float abrk = static_cast<float>(mPool->getPoolUsedCnt(0, 0)); // active bricks
vox = Vector3DF(abrk, abrk*leafdim*leafdim*leafdim / 1000000.0f, abrk*100.0f / vbrk); // # bricks, # voxels(M), occupancy(%)
} else {
vox = Vector3DF(0, 0, 0);
}
// memory used
float topo_total = MeasurePools();
float vol_total = 0;
for (int n = 0; n < mPool->getNumAtlas(); n++) {
vol_total += mPool->getAtlas(n).size / MB;
}
float aux_total = 0;
for (int ai = 0; ai < MAX_AUX; ai++) {
if (mAux[ai].gpu != 0x0) aux_total += float(mAux[ai].size) / MB;
}
used = Vector3DF(topo_total, vol_total, aux_total );
// memory free
free = Vector3DF(cudaGetMemUsage().y, cudaGetMemUsage().z, 0);
}
// Measure GVDB topology & data
void VolumeGVDB::Measure ( bool bPrint )
{
PUSH_CTX
uint64 numnodes_at_lev, maxnodes_at_lev;
uint64 numnodes_total = 0, maxnodes_total = 0;
Vector3DI axisres, axiscnt;
int leafdim;
uint64 atlas_sz = 0;
int levs = mPool->getNumLevels ();
//--- Print
if (bPrint) {
gprintf(" EXTENTS:\n");
gprintf(" Volume Res: %.0f x %.0f x %.0f\n", mVoxRes.x, mVoxRes.y, mVoxRes.z);
gprintf(" Volume Max: %.0f x %.0f x %.0f\n", mVoxResMax.x, mVoxResMax.y, mVoxResMax.z);
gprintf(" Bound Min: %f x %f x %f\n", mObjMin.x, mObjMin.y, mObjMin.z);
gprintf(" Bound Max: %f x %f x %f\n", mObjMax.x, mObjMax.y, mObjMax.z);
gprintf(" VDB CONFIG: <%d, %d, %d, %d, %d>:\n", getLD(4), getLD(3), getLD(2), getLD(1), getLD(0));
gprintf(" # Nodes / # Pool Pool Size\n");
for (int n=0; n < levs; n++ ) {
// node counts
numnodes_at_lev = mPool->getPoolUsedCnt(0, n);
maxnodes_at_lev = mPool->getPoolTotalCnt(0, n);
numnodes_total += numnodes_at_lev;
maxnodes_total += maxnodes_at_lev;
gprintf ( " Level %d: %8d %8d %8d MB\n", n, numnodes_at_lev, maxnodes_at_lev );
}
float MB = 1024.0*1024.0; // convert to MB
gprintf ( " Percent Pool Used: %4.2f%%%%\n", float(numnodes_total)*100.0f / maxnodes_total );
// Atlas info
if ( mPool->getNumAtlas() > 0 ) {
leafdim = static_cast<int>(mPool->getAtlas(0).stride); // voxel res of one brick
axiscnt = mPool->getAtlas(0).subdim; // number of bricks in atlas
axisres = axiscnt * (leafdim + mApron*2); // number of voxels in atlas
atlas_sz = mPool->getAtlas(0).size;
gprintf ( " ATLAS STORAGE\n" );
gprintf ( " Atlas Res: %d x %d x %d LeafCnt: %d x %d x %d LeafDim: %d^3\n", axisres.x, axisres.y, axisres.z, axiscnt.x, axiscnt.y, axiscnt.z, leafdim );
Vector3DI vb = mVoxResMax;
vb /= Vector3DI(leafdim, leafdim, leafdim);
long vbrk = vb.x*vb.y*vb.z; // number of bricks covering bounded world domain
int sbrk = axiscnt.x*axiscnt.y*axiscnt.z; // number of bricks stored in atlas
uint64 abrk = mPool->getPoolUsedCnt(0, 0);
gprintf ( " Vol Extents: %d bricks, %5.2f million voxels\n", vbrk, float(vbrk)*leafdim*leafdim*leafdim / 1000000.0f );
gprintf ( " Atlas Storage: %d bricks, %5.2f million voxels\n", sbrk, float(sbrk)*leafdim*leafdim*leafdim / 1000000.0f );
gprintf ( " Atlas Active: %d bricks, %5.2f million voxels\n", abrk, float(abrk)*leafdim*leafdim*leafdim / 1000000.0f );
gprintf ( " Occupancy: %6.2f%%%% \n", float(abrk)*100.0f / vbrk );
}
float pool_total = MeasurePools();
float vol_total, vol_dense;
vol_total = 0; vol_dense = 0;
gprintf ( " MEMORY USAGE:\n");
gprintf ( " Topology Total: %6.2f MB\n", pool_total);
gprintf ( " Atlas:\n" );
int bpv;
for (int n=0; n < mPool->getNumAtlas(); n++ ) {
bpv = mPool->getSize(mPool->getAtlas(n).type) ;
gprintf ( " Channel %d: %6.2f MB (%d bytes/vox)\n", n, float(mPool->getAtlas(n).size) / MB, bpv );
vol_total += mPool->getAtlas(n).size;
vol_dense += (mVoxResMax.x * mVoxResMax.y * mVoxResMax.z) * bpv;
}
gprintf ( " Atlas Total: %6.2f MB (Dense: %10.2f MB)\n", vol_total / MB, vol_dense / MB );
}
POP_CTX
}
// Prepare VDB data on GPU before kernel launch
void VolumeGVDB::PrepareVDB ()
{
if ( mPool->getNumAtlas() == 0 ) {
gprintf ( "ERROR: No atlas created.\n" );
}
// Send VDB info
if ( mVDBInfo.update ) {
mVDBInfo.update = false;
int tlev = 1;
int levs = mPool->getNumLevels ();
for (int n = levs-1; n >= 0; n-- ) {
mVDBInfo.dim[n] = mLogDim[n];
mVDBInfo.res[n] = getRes(n);
mVDBInfo.vdel[n] = Vector3DF(getRange(n)); mVDBInfo.vdel[n] /= Vector3DF( getRes3DI(n) );
mVDBInfo.noderange[n] = getRange(n); // integer (cannot send cover)
mVDBInfo.nodecnt[n] = static_cast<int>(mPool->getPoolTotalCnt(0, n));
mVDBInfo.nodewid[n] = static_cast<int>(mPool->getPoolWidth(0, n));
mVDBInfo.childwid[n] = static_cast<int>(mPool->getPoolWidth(1, n));
mVDBInfo.nodelist[n] = mPool->getPoolGPU(0, n);
mVDBInfo.childlist[n] = mPool->getPoolGPU(1, n);
if ( mVDBInfo.nodecnt[n] == 1 ) tlev = n; // get top level for rendering
}
mVDBInfo.atlas_map = mPool->getAtlasMapGPU(0);
mVDBInfo.atlas_apron = mPool->getAtlas(0).apron;
mVDBInfo.atlas_cnt = mPool->getAtlas(0).subdim; // number of bricks on each axis of atlas
mVDBInfo.atlas_res = mPool->getAtlasRes(0); // total resolution of atlas
mVDBInfo.brick_res = mPool->getAtlasBrickres(0); // resolution of single brick (sides are all same)
int blkres = mPool->getAtlasBrickres(0);
for (int n=0; n < mApron; n++ ) {
mVDBInfo.apron_table[ n ] = n;
mVDBInfo.apron_table[ (mApron*2-1)-n ] = (blkres-1) - n;
}
mVDBInfo.top_lev = tlev;
mVDBInfo.epsilon = mEpsilon;
mVDBInfo.max_iter = mMaxIter;
mVDBInfo.bmin = mObjMin;
mVDBInfo.bmax = mObjMax;
PUSH_CTX
cudaCheck ( cuMemcpyHtoD ( cuVDBInfo, &mVDBInfo, sizeof(VDBInfo) ), "VolumeGVDB", "PrepareVDB", "cuMemcpyHtoD", "cuVDBInfo", mbDebug);
POP_CTX
}
}
void VolumeGVDB::RetrieveVDB()
{
PUSH_CTX
cudaCheck(cuMemcpyDtoH( &mVDBInfo, cuVDBInfo, sizeof(VDBInfo)), "VolumeGVDB", "RetrieveVDB", "cuMemcpyDtoH", "cuVDBInfo", mbDebug);
POP_CTX
}
void VolumeGVDB::PrepareVDBPartially ()
{
mVDBInfo.update = false;
int tlev = 1;
int levs = mPool->getNumLevels ();
for (int n = levs-1; n >= 0; n-- ) {
mVDBInfo.dim[n] = mLogDim[n];
mVDBInfo.res[n] = getRes(n);
mVDBInfo.vdel[n] = Vector3DF(getRange(n)); mVDBInfo.vdel[n] /= Vector3DF( getRes3DI(n) );
mVDBInfo.noderange[n] = getRange(n); // integer (cannot send cover)
mVDBInfo.nodecnt[n] = static_cast<int>(mPool->getPoolTotalCnt(0, n));
mVDBInfo.nodewid[n] = static_cast<int>(mPool->getPoolWidth(0, n));
mVDBInfo.childwid[n] = static_cast<int>(mPool->getPoolWidth(1, n));
mVDBInfo.nodelist[n] = mPool->getPoolGPU(0, n);
mVDBInfo.childlist[n] = mPool->getPoolGPU(1, n);
if ( mVDBInfo.nodecnt[n] == 1 ) tlev = n; // get top level for rendering
}
mVDBInfo.top_lev = tlev;
mVDBInfo.bmin = mObjMin;
mVDBInfo.bmax = mObjMax;
PUSH_CTX
cudaCheck ( cuMemcpyHtoD ( cuVDBInfo, &mVDBInfo, sizeof(VDBInfo) ), "VolumeGVDB", "PrepareVDBPartially", "cuMemcpyHtoD", "cuVDBInfo", mbDebug);
POP_CTX
}
bool glCheck()
{
GLenum error = glGetError();
if (error != GL_NO_ERROR) {
gprintf("GL ERROR\n");
gerror();
return false;
}
return true;
}
void VolumeGVDB::WriteDepthTexGL(int chan, int glid)
{
PUSH_CTX
PERF_PUSH("WriteDepthGL");
if (mDummyFrameBuffer == -1) {
glGenFramebuffers(1, (GLuint*)&mDummyFrameBuffer);
}
// Set current framebuffer to input buffer:
glBindFramebuffer(GL_FRAMEBUFFER, mDummyFrameBuffer);
// Setup frame buffer so that we can copy depth info from the depth target bound
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, glid, 0);
// Copy contents of depth target into _depthBuffer for use in CUDA rendering:
glBindBuffer(GL_PIXEL_PACK_BUFFER, mRenderBuf[chan].glid);
glReadPixels(0, 0,
static_cast<GLsizei>(mRenderBuf[chan].stride),
static_cast<GLsizei>(mRenderBuf[chan].max / mRenderBuf[chan].stride),
GL_DEPTH_COMPONENT, GL_FLOAT, 0);
glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
glCheck();
// Clear render target:
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glFinish();
PERF_POP();
POP_CTX
}
void VolumeGVDB::WriteRenderTexGL ( int chan, int glid )
{
PUSH_CTX
PERF_PUSH ( "ReadTexGL" );
if (mRenderBuf[chan].garray == 0) {
// Prepare render target
mRenderBuf[chan].glid = glid;
// Cuda-GL interop to get target CUarray
cudaCheck(cuGraphicsGLRegisterImage(&mRenderBuf[chan].grsc, glid, GL_TEXTURE_2D, CU_GRAPHICS_REGISTER_FLAGS_SURFACE_LDST), "VolumeGVDB", "WriteRenderTexGL", "cuGraphicsGLRegisterImage", "mRenderBuf", mbDebug );
cudaCheck(cuGraphicsMapResources(1, &mRenderBuf[chan].grsc, 0), "VolumeGVDB", "WriteRenderTexGL", "cuGraphicsMapResources", "mRenderBuf", mbDebug);
cudaCheck(cuGraphicsSubResourceGetMappedArray(&mRenderBuf[chan].garray, mRenderBuf[chan].grsc, 0, 0), "VolumeGVDB", "WriteRenderTexGL", "cuGraphicsSubResourceGetMappedArray", "mRenderBuf", mbDebug);
cudaCheck(cuGraphicsUnmapResources(1, &mRenderBuf[chan].grsc, 0), "VolumeGVDB", "WriteRenderTexGL", "cuGraphicsUnmapResources", "mRenderBuf", mbDebug);
}
size_t bpp = mRenderBuf[chan].size / mRenderBuf[chan].max;
size_t width = mRenderBuf[chan].stride * bpp;
size_t height = mRenderBuf[chan].max / mRenderBuf[chan].stride;
// Cuda Memcpy2D to transfer cuda output buffer
// into opengl texture as a CUarray
CUDA_MEMCPY2D cp = { 0 };
cp.dstMemoryType = CU_MEMORYTYPE_DEVICE; // from cuda buffer
cp.dstDevice = mRenderBuf[chan].gpu;
cp.srcMemoryType = CU_MEMORYTYPE_ARRAY; // to CUarray (opengl texture)
cp.srcArray = mRenderBuf[chan].garray;
cp.WidthInBytes = width;
cp.Height = height;
cudaCheck(cuMemcpy2D(&cp), "VolumeGVDB", "WriteRenderTexGL", "cuMemcpy2D", "", mbDebug );
cuCtxSynchronize();
PERF_POP ();
POP_CTX
}
void VolumeGVDB::ReadRenderTexGL ( int chan, int glid )
{
PUSH_CTX
PERF_PUSH ( "ReadTexGL" );
if ( mRenderBuf[chan].garray == 0 ) {
// Prepare render target
mRenderBuf[chan].glid = glid;
// Cuda-GL interop to get target CUarray
cudaCheck ( cuGraphicsGLRegisterImage ( &mRenderBuf[chan].grsc, glid, GL_TEXTURE_2D, CU_GRAPHICS_REGISTER_FLAGS_SURFACE_LDST ), "VolumeGVDB", "ReadRenderTexGL", "cuGraphicsGLRegisterImage ", "mRenderBuf", mbDebug);
cudaCheck ( cuGraphicsMapResources(1, &mRenderBuf[chan].grsc, 0), "VolumeGVDB", "ReadRenderTexGL", "cuGraphicsMapResources", "mRenderBuf", mbDebug);
cudaCheck ( cuGraphicsSubResourceGetMappedArray ( &mRenderBuf[chan].garray, mRenderBuf[chan].grsc, 0, 0 ), "VolumeGVDB", "ReadRenderTexGL", "cuGraphicsSubResourcesGetMappedArray", "mRenderBuf", mbDebug);
cudaCheck ( cuGraphicsUnmapResources(1, &mRenderBuf[chan].grsc, 0), "VolumeGVDB", "ReadRenderTexGL", "cuGraphicsUnmapResources", "mRenderBuf", mbDebug);
}
size_t bpp = mRenderBuf[chan].size / mRenderBuf[chan].max;
size_t width = mRenderBuf[chan].stride * bpp;
size_t height = mRenderBuf[chan].max / mRenderBuf[chan].stride;
// Cuda Memcpy2D to transfer cuda output buffer
// into opengl texture as a CUarray
CUDA_MEMCPY2D cp = {0};
cp.srcMemoryType = CU_MEMORYTYPE_DEVICE; // from cuda buffer
cp.srcDevice = mRenderBuf[chan].gpu;
cp.dstMemoryType = CU_MEMORYTYPE_ARRAY; // to CUarray (opengl texture)
cp.dstArray = mRenderBuf[chan].garray;
cp.WidthInBytes = width;
cp.Height = height;
cudaCheck ( cuMemcpy2D ( &cp ), "VolumeGVDB", "ReadRenderTexGL", "cuMemcpy2D", "", mbDebug );
cuCtxSynchronize ();
PERF_POP ();
POP_CTX
}
// Add a depth buffer
void VolumeGVDB::AddDepthBuf(int chan, int width, int height)
{
mRenderBuf.resize(chan + 1);
mRenderBuf[chan].alloc = mPool;
mRenderBuf[chan].cpu = 0x0; // no cpu residence yet
mRenderBuf[chan].lastEle = 0;
mRenderBuf[chan].usedNum = 0;
mRenderBuf[chan].garray = 0;
mRenderBuf[chan].grsc = 0;
mRenderBuf[chan].glid = -1;
mRenderBuf[chan].gpu = 0x0;
ResizeDepthBuf( chan, width, height );
}
// Add a render buffer
void VolumeGVDB::AddRenderBuf ( int chan, int width, int height, int byteperpix )
{
mRenderBuf.resize ( chan+1 );
mRenderBuf[chan].alloc = mPool;
mRenderBuf[chan].cpu = 0x0; // no cpu residence yet
mRenderBuf[chan].usedNum = 0;
mRenderBuf[chan].lastEle = 0;
mRenderBuf[chan].garray = 0;
mRenderBuf[chan].grsc = 0;
mRenderBuf[chan].glid = -1;
mRenderBuf[chan].gpu = 0x0;
ResizeRenderBuf ( chan, width, height, byteperpix );
}
// Resize a depth buffer
void VolumeGVDB::ResizeDepthBuf( int chan, int width, int height )
{
PUSH_CTX
if (chan >= mRenderBuf.size()) {
gprintf("ERROR: Attempt to resize depth buf that doesn't exist.");
}
if (mRenderBuf[chan].glid != -1)
{
glDeleteBuffers(1, (GLuint*)&mRenderBuf[chan].glid);
mRenderBuf[chan].glid = -1;
}
glGenBuffers(1, (GLuint*)&mRenderBuf[chan].glid);
glBindBuffer(GL_PIXEL_PACK_BUFFER, mRenderBuf[chan].glid);
glBufferData(GL_PIXEL_PACK_BUFFER, width * height * sizeof(GLuint), NULL, GL_DYNAMIC_DRAW);
glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
mRenderBuf[chan].max = width * height;
mRenderBuf[chan].size = width * height * sizeof(GLuint);
mRenderBuf[chan].stride = width;
cudaCheck(cuGraphicsGLRegisterBuffer(&mRenderBuf[chan].grsc, mRenderBuf[chan].glid, 0), "VolumeGVDB", "ResizeDepthBuf", "cuGraphicsGLRegisterBuffer", "", mbDebug);
cudaCheck(cuGraphicsMapResources(1, &mRenderBuf[chan].grsc, 0), "VolumeGVDB", "ResizeDepthBuf", "cuGraphicsMapResources", "", mbDebug);
cudaCheck(cuGraphicsResourceGetMappedPointer(&mRenderBuf[chan].gpu, &mRenderBuf[chan].size, mRenderBuf[chan].grsc), "VolumeGVDB", "ResizeDepthBuf", "cuGraphicsResourcesGetMappedPointer", "", mbDebug);
cudaCheck(cuGraphicsUnmapResources(1, &mRenderBuf[chan].grsc, 0), "VolumeGVDB", "ResizeDepthBuf", "cuGraphicsUnmapResources", "", mbDebug);
POP_CTX
}
// Resize a render buffer
void VolumeGVDB::ResizeRenderBuf ( int chan, int width, int height, int byteperpix )
{
PUSH_CTX
if ( chan >= mRenderBuf.size() ) {
gprintf ( "ERROR: Attempt to resize render buf that doesn't exist." );
}
mRenderBuf[chan].max = width * height;
mRenderBuf[chan].size = width * height * byteperpix;
mRenderBuf[chan].stride = width;
if ( chan == 0 ) getScene()->SetRes ( width, height );
size_t sz = mRenderBuf[chan].size;
if ( mRenderBuf[chan].gpu != 0x0 ) {
cudaCheck ( cuMemFree ( mRenderBuf[chan].gpu ), "VolumeGVDB", "ResizeRenderBuf", "cuMemFree", "", mbDebug);
}
cudaCheck ( cuMemAlloc ( &mRenderBuf[chan].gpu, sz ), "VolumeGVDB", "ResizeRenderBuf", "cuMemAlloc", "", mbDebug);
if ( mRenderBuf[chan].garray != 0x0 ) {
cudaCheck ( cuGraphicsUnregisterResource ( mRenderBuf[chan].grsc ), "VolumeGVDB", "ResizeRenderBuf", "cuGraphicsUnregisterResource", "", mbDebug);
mRenderBuf[chan].grsc = 0x0;
mRenderBuf[chan].garray = 0x0;
}
cuCtxSynchronize ();
POP_CTX
}
// Read render buffer to CPU
void VolumeGVDB::ReadRenderBuf ( int chan, unsigned char* outptr )
{
PUSH_CTX
if ( mbVerbose ) PERF_PUSH ( "ReadBuf" );
mRenderBuf[chan].cpu = (char*) outptr;
mPool->RetrieveMem ( mRenderBuf[chan] ); // transfer dev to host
if ( mbVerbose ) PERF_POP ();
POP_CTX
}
// Prepare scene data for rendering kernel
void VolumeGVDB::PrepareRender ( int w, int h, char shading )
{
PUSH_CTX
// Send scene data
Camera3D* cam = getScene()->getCamera();
mScnInfo.width = w;
mScnInfo.height = h;
mScnInfo.camnear = cam->getNear ();
mScnInfo.camfar = cam->getFar();
mScnInfo.campos = cam->origRayWorld;
mScnInfo.cams = cam->tlRayWorld;
mScnInfo.camu = cam->trRayWorld; mScnInfo.camu -= mScnInfo.cams;
mScnInfo.camv = cam->blRayWorld; mScnInfo.camv -= mScnInfo.cams;
mScnInfo.bias = m_bias;
// Transform the light position from application space to voxel space,
// like getViewPos:
nvdb::Vector4DF lightPos4 = getScene()->getLight()->getPos();
lightPos4.w = 1.0f; // Since it's a position, not a direction
lightPos4 *= mInvXform;
mScnInfo.light_pos = Vector3DF(lightPos4.x, lightPos4.y, lightPos4.z);
Vector3DF crs = Vector3DF(0,0,0);
mScnInfo.slice_pnt = getScene()->getSectionPnt();
mScnInfo.slice_norm = getScene()->getSectionNorm();
mScnInfo.shading = shading; // getScene()->getShading();
mScnInfo.filtering = getScene()->getFilterMode();
mScnInfo.frame = getScene()->getFrame();
mScnInfo.samples = getScene()->getSample();
mScnInfo.shadow_params = getScene()->getShadowParams();
mScnInfo.backclr = getScene()->getBackClr ();
mScnInfo.extinct = getScene()->getExtinct ();
mScnInfo.steps = getScene()->getSteps ();
mScnInfo.cutoff = getScene()->getCutoff ();
mScnInfo.thresh = getScene()->mVThreshold;
// Grid transform
memcpy(mScnInfo.xform, mXform.GetDataF(), sizeof(float)*16);
memcpy(mScnInfo.invxform, mInvXform.GetDataF(), sizeof(float)*16);
memcpy(mScnInfo.invxrot, mInvXrot.GetDataF(), sizeof(float) * 16);
// Transfer function
mScnInfo.transfer = getTransferFuncGPU();
if (mScnInfo.transfer == 0) {
gprintf("Error: Transfer function not on GPU. Must call CommitTransferFunc.\n");
gerror();
}
// Depth buffer
mScnInfo.outbuf = -1; // NOT USED (was mRenderBuf[0].gpu;)
int dbuf = getScene()->getDepthBuf();
mScnInfo.dbuf = (dbuf == 255 ? NULL : mRenderBuf[dbuf].gpu);
cudaCheck ( cuMemcpyHtoD ( cuScnInfo, &mScnInfo, sizeof(ScnInfo) ), "VolumeGVDB", "PrepareRender", "cuMemcpyHtoD", "cuScnInfo", mbDebug);
POP_CTX
}
// Render using custom user kernel
void VolumeGVDB::RenderKernel ( CUfunction user_kernel, uchar chan, uchar rbuf )
{
PUSH_CTX
if (mbProfile) PERF_PUSH ( "Render" );
int width = static_cast<int>(mRenderBuf[rbuf].stride);
int height = static_cast<int>(mRenderBuf[rbuf].max / mRenderBuf[rbuf].stride);
// Send Scene info (camera, lights)
PrepareRender ( width, height, getScene()->getShading() );
// Send VDB Info & Atlas
PrepareVDB ();
// Run CUDA User-Kernel
Vector3DI block ( 8, 8, 1 );
Vector3DI grid ( (int(width) + block.x - 1)/block.x, (int(height) + block.y - 1)/block.y, 1);
void* args[3] = { &cuVDBInfo, &chan, &mRenderBuf[rbuf].gpu };
cudaCheck ( cuLaunchKernel ( user_kernel, grid.x, grid.y, 1, block.x, block.y, 1, 0, NULL, args, NULL ), "VolumeGVDB", "RenderKernel", "cuLaunch", "(user kernel)", mbDebug);
if (mbProfile) PERF_POP ();
POP_CTX
}
// Render using native kernel
void VolumeGVDB::Render ( char shading, uchar chan, uchar rbuf )
{
int width = static_cast<int>(mRenderBuf[rbuf].stride);
int height = static_cast<int>(mRenderBuf[rbuf].max / mRenderBuf[rbuf].stride);
if ( shading==SHADE_OFF ) {
PUSH_CTX
cudaCheck ( cuMemsetD8 ( mRenderBuf[rbuf].gpu, 0, static_cast<uint64>(width)*static_cast<uint64>(height)*4 ),
"VolumeGVDB", "Render", "cuMemsetD8", "(no shading)", mbDebug);
POP_CTX
return;
}
PUSH_CTX
if (mbProfile) PERF_PUSH ( "Render" );
// Send Scene info (camera, lights)
PrepareRender ( width, height, shading );
// Send VDB Info & Atlas
PrepareVDB ();
// Prepare kernel
Vector3DI block ( 16, 16, 1);
Vector3DI grid((int(width) + block.x - 1) / block.x, (int(height) + block.y - 1) / block.y, 1);
void* args[3] = { &cuVDBInfo, &chan, &mRenderBuf[rbuf].gpu };
int kern;
switch ( shading ) {
case SHADE_VOXEL: kern = FUNC_RAYVOXEL; break;
case SHADE_TRILINEAR: kern = FUNC_RAYTRILINEAR; break;
case SHADE_TRICUBIC: kern = FUNC_RAYTRICUBIC; break;
case SHADE_EMPTYSKIP: kern = FUNC_EMPTYSKIP; break;
case SHADE_SECTION2D: kern = FUNC_SECTION2D; break;
case SHADE_SECTION3D: kern = FUNC_SECTION3D; break;
case SHADE_LEVELSET: kern = FUNC_RAYLEVELSET; break;
case SHADE_VOLUME: kern = FUNC_RAYDEEP; break;
}
// Run Raytracing kernel
cudaCheck(cuLaunchKernel(cuFunc[kern], grid.x, grid.y, 1, block.x, block.y, 1, 0, NULL, args, NULL),
"VolumeGVDB", "Render", "cuLaunch", mRendName[shading], mbDebug);
if (mbProfile) PERF_POP ();
POP_CTX
}
// Explicit raytracing
void VolumeGVDB::Raytrace ( DataPtr rays, uchar chan, char shading, int frame, float bias )
{
PUSH_CTX
if (mbProfile) PERF_PUSH ( "Raytrace" );
// Send scene data
PrepareRender ( 1, 1, 0 );
// Send VDB Info & Atlas
PrepareVDB ();
// Run CUDA GVDB Raytracer
int cnt = static_cast<int>(rays.lastEle);
Vector3DI block ( 64, 1, 1);
Vector3DI grid ( (cnt + block.x - 1)/block.x, 1, 1);
void* args[5] = { &cuVDBInfo, &chan, &cnt, &rays.gpu, &bias };
cudaCheck ( cuLaunchKernel ( cuFunc[FUNC_RAYTRACE], grid.x, 1, 1, block.x, 1, 1, 0, NULL, args, NULL ),
"VolumeGVDB", "Raytrace", "cuLaunch", "FUNC_RAYTRACE", mbDebug );
if (mbProfile) PERF_POP ();
POP_CTX
}
// Update apron (for all channels)
void VolumeGVDB::UpdateApron ()
{
for (int n=0; n < mPool->getNumAtlas(); n++ )
UpdateApron ( n ); // only update marker channel
}
// Update apron (one channel)
void VolumeGVDB::UpdateApron ( uchar chan, float boundval, bool changeCtx)
{
if ( mApron == 0 ) return;
// Send VDB Info
PrepareVDB ();
if(changeCtx) PUSH_CTX
// Channel type
int kern;
char typ[3]; typ[2] = '\0';
switch ( mPool->getAtlas(chan).type ) {
case T_FLOAT: kern = FUNC_UPDATEAPRON_F; typ[0] = 'F'; typ[1] = '1'; break;
case T_FLOAT3: kern = FUNC_UPDATEAPRON_F4; typ[0] = 'F'; typ[1] = '3'; break; // F3 is implemented as F4
case T_FLOAT4: kern = FUNC_UPDATEAPRON_F4; typ[0] = 'F'; typ[1] = '4'; break;
case T_UCHAR: kern = FUNC_UPDATEAPRON_C; typ[0] = 'U'; typ[1] = '1'; break;
case T_UCHAR4: kern = FUNC_UPDATEAPRON_C4; typ[0] = 'U'; typ[1] = '4'; break;
}
// Dimensions
int bricks = static_cast<int>(mPool->getPoolTotalCnt(0,0)); // number of bricks
int brickres = mPool->getAtlasBrickres(chan); // dimension of brick (including apron)
int brickwid = mPool->getAtlasBrickwid(chan); // dimension of brick (without apron)
if (bricks == 0) return;
Vector3DI threadcnt(bricks, brickres, brickres); // First component is passed directly to grid
Vector3DI block(6 * mApron, 8, 8);
Vector3DI grid(threadcnt.x, (threadcnt.y + block.y - 1) / block.y, (threadcnt.y + block.z - 1) / block.z);
// Note: Kernels currently assume apron size of 1.
void* args[6] = { &cuVDBInfo, &chan, &bricks, &brickres, &brickwid, &boundval };
cudaCheck(cuLaunchKernel(cuFunc[kern], grid.x, grid.y, grid.z, block.x, block.y, block.z, 0, NULL, args, NULL),
"VolumeGVDB", "UpdateApron", "cuLaunch", typ, mbDebug);
if (changeCtx) { POP_CTX }
}
// Update apron (one channel)
void VolumeGVDB::UpdateApronFaces (uchar chan)
{
if (mApron == 0) return;
if (mbProfile) PERF_PUSH("UpdateApron");
// Send VDB Info
PrepareVDB();
// Channel type
int kern;
switch (mPool->getAtlas(chan).type) {
case T_FLOAT: kern = FUNC_UPDATEAPRONFACES_F; break;
}
PUSH_CTX
// Dimensions
int bricks = static_cast<int>(mPool->getPoolTotalCnt(0, 0)); // number of bricks
int brickres = mPool->getAtlasBrickres(chan); // dimension of brick (including apron)
int brickwid = mPool->getAtlasBrickwid(chan); // dimension of brick (without apron)
Vector3DI threadcnt(bricks, brickwid, brickwid); // First component is passed directly to grid
Vector3DI block(3 * mApron, 8, 8);
Vector3DI grid(threadcnt.x, (threadcnt.y + block.y - 1) / block.y, (threadcnt.z + block.z - 1) / block.z);
DataPtr* ntable = mPool->getNeighborTable(); // get neighbor table
void* args[6] = { &cuVDBInfo, &chan, &bricks, &brickres, &brickwid, &ntable->gpu };
cudaCheck(cuLaunchKernel(cuFunc[kern], grid.x, grid.y, grid.z, block.x, block.y, block.z, 0, NULL, args, NULL),
"VolumeGVDB", "UpdateApronFaces", "cuLaunch", "F1 (only)", mbDebug);
POP_CTX
if (mbProfile) PERF_POP();
}
void VolumeGVDB::ComputeKernel (CUmodule user_module, CUfunction user_kernel, uchar channel, bool bUpdateApron, bool skipOverAprons)
{
PERF_PUSH ("ComputeKernel");
SetModule ( user_module );
// Send VDB Info (*to user module*)
PrepareVDB ();
PUSH_CTX
// Determine grid and block dims (must match atlas bricks)
Vector3DI block ( 8, 8, 8 );
Vector3DI atlasRes = mPool->getAtlasRes(channel);
Vector3DI threadCount = (skipOverAprons ? mPool->getAtlasPackres(channel) : atlasRes);
Vector3DI grid = (threadCount + block - 1) / block;
void* args[3] = { &cuVDBInfo, &atlasRes, &channel };
cudaCheck ( cuLaunchKernel ( user_kernel, grid.x, grid.y, grid.z, block.x, block.y, block.z, 0, NULL, args, NULL ),
"VolumeGVDB", "ComputeKernel", "cuLaunch", "(user kernel)", mbDebug);
if ( bUpdateApron ) {
cudaCheck ( cuCtxSynchronize(), "VolumeGVDB", "ComputeKernel", "cuCtxSyncronize", "", mbDebug);
SetModule (); // Update apron must be called from default module
UpdateApron ();
}
POP_CTX
PERF_POP();
}
void VolumeGVDB::Compute (int effect, uchar channel, int num_iterations, Vector3DF parameters, bool bUpdateApron, bool skipOverAprons, float boundval)
{
PERF_PUSH ("Compute");
// Send VDB Info
PrepareVDB ();
PUSH_CTX
// Determine grid and block dims (must match atlas bricks)
Vector3DI block ( 8, 8, 8 );
Vector3DI atlasRes = mPool->getAtlasRes(channel);
Vector3DI threadCount = (skipOverAprons ? mPool->getAtlasPackres(channel) : atlasRes);
Vector3DI grid = (threadCount + block - 1) / block;
void* args[6] = { &cuVDBInfo, &atlasRes, &channel, ¶meters.x, ¶meters.y, ¶meters.z };
for (int n=0; n < num_iterations; n++ ) {
cudaCheck ( cuLaunchKernel ( cuFunc[effect], grid.x, grid.y, grid.z, block.x, block.y, block.z, 0, mStream, args, NULL ),
"VolumeGVDB", "Compute", "cuLaunch", "", mbDebug);
if (bUpdateApron) UpdateApron(channel, boundval); // update the apron
}
POP_CTX
PERF_POP();
}
void VolumeGVDB::DownsampleCPU(Matrix4F xform, Vector3DI in_res, char in_aux, Vector3DI out_res, Vector3DF out_max, char out_aux, Vector3DF inr, Vector3DF outr)
{
PUSH_CTX
PrepareAux(out_aux, out_res.x*out_res.y*out_res.z, sizeof(float), true, true);
// Determine grid and block dims
Vector3DI block(8, 8, 8);
Vector3DI grid(int(out_res.x / block.x) + 1, int(out_res.y / block.y) + 1, int(out_res.z / block.z) + 1);
// Send transform matrix to cuda
PrepareAux(AUX_MATRIX4F, 16, sizeof(float), true, true);
memcpy(mAux[AUX_MATRIX4F].cpu, xform.GetDataF(), 16 * sizeof(float));
CommitData(mAux[AUX_MATRIX4F]);
void* args[8] = { &in_res, &mAux[in_aux].gpu, &out_res, &out_max, &mAux[out_aux].gpu, &mAux[AUX_MATRIX4F].gpu, &inr, &outr };
cudaCheck(cuLaunchKernel(cuFunc[FUNC_DOWNSAMPLE], grid.x, grid.y, grid.z, block.x, block.y, block.z, 0, NULL, args, NULL),
"VolumeGVDB", "DownsampleCPU", "cuLaunch", "FUNC_DOWNSAMPLE", mbDebug);
// Retrieve data back to CPU
RetrieveData(mAux[out_aux]);
POP_CTX
}
Vector3DF VolumeGVDB::Reduction(uchar chan)
{
if (mbProfile) PERF_PUSH("Reduction");
PrepareVDB();
PUSH_CTX
// Launch 2D grid of voxels
// (x/y plane, not including apron)
Vector3DI packres = mPool->getAtlasPackres(chan); // exclude apron voxels
Vector3DI res = mPool->getAtlasRes(chan);
Vector3DI block(8, 8, 1);
Vector3DI grid(int(packres.x / block.x) + 1, int(packres.y / block.y) + 1, 1);
// Prepare accumulation buffer
PrepareAux(AUX_DATA2D, packres.x*packres.y, sizeof(float), false, true);
void* args[5] = { &cuVDBInfo, &res, &chan, &packres, &mAux[AUX_DATA2D].gpu };
cudaCheck(cuLaunchKernel(cuFunc[FUNC_REDUCTION], grid.x, grid.y, grid.z, block.x, block.y, block.z, 0, NULL, args, NULL),
"VolumeGVDB", "Reduction", "cuLaunch", "FUNC_REDUCTION", mbDebug);
RetrieveData(mAux[AUX_DATA2D]);
float sum = 0.0;
float* dat = (float*)mAux[AUX_DATA2D].cpu;
for (int y = 0; y < packres.y; y++) {
for (int x = 0; x < packres.x; x++) {
sum += *dat;
dat++;
}
}
POP_CTX
if (mbProfile) PERF_POP();
return Vector3DF(sum, 0, 0);
}
void VolumeGVDB::Resample ( uchar chan, Matrix4F xform, Vector3DI in_res, char in_aux, Vector3DF inr, Vector3DF outr )
{
PrepareVDB ();
PUSH_CTX
// Determine grid and block dims (must match atlas bricks)
Vector3DI block ( 8, 8, 8 );
Vector3DI res = mPool->getAtlasRes( chan );
Vector3DI grid = (res + block - 1) / block;
// Send transform matrix to cuda
PrepareAux ( AUX_MATRIX4F, 16, sizeof(float), true, true );
memcpy ( mAux[AUX_MATRIX4F].cpu, xform.GetDataF(), 16*sizeof(float) );
CommitData ( mAux[AUX_MATRIX4F] );
void* args[8] = { &cuVDBInfo, &res, &chan, &in_res, &mAux[in_aux].gpu, &mAux[AUX_MATRIX4F].gpu, &inr, &outr };
cudaCheck ( cuLaunchKernel ( cuFunc[FUNC_RESAMPLE], grid.x, grid.y, grid.z, block.x, block.y, block.z, 0, NULL, args, NULL ),
"VolumeGVDB", "Resample", "cuLaunch", "FUNC_RESAMPLE", mbDebug);
POP_CTX
}
uint64 VolumeGVDB::getNodeAtPoint (uint64 nodeid, Vector3DF pos)
{
// Recurse to find node
Node* curr = getNode( nodeid );
Vector3DF p = pos; p -= curr->mPos;
Vector3DF range = getRange(curr->mLev);
if (p.x >= 0 && p.y >= 0 && p.z >= 0 && p.x < range.x && p.y < range.y && p.z < range.z) {
// point is inside this node
p *= getRes(curr->mLev);
p /= range;
if (isLeaf(nodeid)) {
return nodeid;
} else {
#ifdef USE_BITMASKS
uint32 i = getBitPos(curr->mLev, p);
uint32 b = curr->countOn(i);
slong childid;
if (curr->isOn(i)) {
childid = getChildNode(nodeid, b);
return getNodeAtPoint( childid, pos);
}
#else
uint32 i = getBitPos(curr->mLev, p);
slong childid;
if (isOn(nodeid, i)) {
childid = getChildNode(nodeid, i);
return getNodeAtPoint( childid, pos);
}
#endif
}
}
return ID_UNDEFL;
}
bool VolumeGVDB::isActive(Vector3DI wpos)
{
return isActive(wpos, mRoot);
}
bool VolumeGVDB::isActive( Vector3DI pos, slong nodeid)
{
// Recurse to leaf
unsigned int b;
if (getPosInNode(nodeid, pos, b)) {
// point is inside
if (isLeaf(nodeid)) {
return true; // found leaf. is active.
} else {
slong childid;
if (isOn(nodeid, b)) {
childid = getChildNode(nodeid, b);
return isActive(pos, childid);
}
}
}
return false;
}
float VolumeGVDB::getValue ( slong nodeid, Vector3DF pos, float* atlas )
{
// Recurse to find value
Node* curr = getNode ( nodeid );
Vector3DF p = pos; p -= curr->mPos;
Vector3DF range = getRange ( curr->mLev );
if (p.x >= 0 && p.y >=0 && p.z >=0 && p.x < range.x && p.y < range.y && p.z < range.z ) {
// point is inside this node
p *= getRes ( curr->mLev );
p /= range;
if ( isLeaf ( nodeid ) ) {
Vector3DF atlaspos = curr->mValue;
Vector3DI atlasres = mPool->getAtlasRes( 0 );
p += atlaspos;
return atlas [ (int(p.z)*atlasres.y + int(p.y) )*atlasres.x + int(p.x) ];
} else {
#ifdef USE_BITMASKS
uint32 i = getBitPos ( curr->mLev, p );
uint32 b = curr->countOn ( i );
slong childid;
if ( curr->isOn ( i ) ) {
childid = getChildNode ( nodeid, b );
return getValue ( childid, pos, atlas );
}
#else
uint32 i = getBitPos ( curr->mLev, p );
slong childid;
if ( isOn (nodeid, i ) ) {
childid = getChildNode ( nodeid, i );
return getValue ( childid, pos, atlas );
}
#endif
}
}
return 0.0;
}
#define SCAN_BLOCKSIZE 512 // <--- must match cuda_gvdb_particles.cuh header
#define ONE_LEVEL 0
void VolumeGVDB::PrefixSum ( CUdeviceptr inArray, CUdeviceptr outArray, int numElem )
{
int naux = SCAN_BLOCKSIZE << 1; // 1024
int len1 = numElem / naux; // (1024^2+1024) = 1,049,600, len1 = 1025
int blks1 = int( numElem / naux )+1; // 1026
int blks2 = int( blks1 / naux )+1; // 2
int threads = SCAN_BLOCKSIZE;
int zon = 1;
CUdeviceptr nptr = {0};
PUSH_CTX
if ( blks1 <= 1024 ) {
PrepareAux ( AUX_ARRAY1, SCAN_BLOCKSIZE << 1, sizeof(uint), false);
PrepareAux ( AUX_SCAN1, SCAN_BLOCKSIZE << 1, sizeof(uint), false);
} else {
PrepareAux ( AUX_ARRAY1, blks2*(SCAN_BLOCKSIZE << 1), sizeof(uint), false);
PrepareAux ( AUX_SCAN1, blks2*(SCAN_BLOCKSIZE << 1), sizeof(uint), false);
}
PrepareAux ( AUX_ARRAY2, SCAN_BLOCKSIZE << 1, sizeof(uint), false );
PrepareAux ( AUX_SCAN2, SCAN_BLOCKSIZE << 1, sizeof(uint), false );
void* argsA[5] = {&inArray, &outArray, &mAux[AUX_ARRAY1].gpu, &numElem, &zon };
cudaCheck ( cuLaunchKernel ( cuFunc[FUNC_PREFIXSUM], blks1, 1, 1, threads, 1, 1, 0, NULL, argsA, NULL ),
"VolumeGVDB", "PrefixSum", "cuLaunch", "FUNC_PREFIXSUM (in,out->A1)", mbDebug);
#if ONE_LEVEL
void* argsB[5] = { &mAux[AUX_ARRAY1].gpu, &mAux[AUX_SCAN1].gpu, &nptr, &blks1, &zon };
cudaCheck ( cuLaunchKernel ( cuFunc[FUNC_PREFIXSUM], blks2, 1, 1, threads, 1, 1, 0, NULL, argsB, NULL ), "cuPrefixSumB", "PrefixSum" );
RetrieveData ( mAux[AUX_SCAN1] );
uint* dat = (uint*) getDataPtr ( 0, mAux[AUX_SCAN1] );
gprintf ( "----\n" );
for (int n=0; n < 10; n++ ) {
gprintf ( "%d: %d\n", n, *dat++ );
}
gprintf ( "----\n" );
#else
//int blen1 = blks1 * naux;
void* argsB[5] = { &mAux[AUX_ARRAY1].gpu, &mAux[AUX_SCAN1].gpu, &mAux[AUX_ARRAY2].gpu, &blks1, &zon };
cudaCheck ( cuLaunchKernel ( cuFunc[FUNC_PREFIXSUM], blks2, 1, 1, threads, 1, 1, 0, NULL, argsB, NULL ),
"VolumeGVDB", "PrefixSum", "cuLaunch", "FUNC_PREFIXSUM (A1,S1->A2)", mbDebug);
//int blen2 = blks2 * naux;
void* argsC[5] = { &mAux[AUX_ARRAY2].gpu, &mAux[AUX_SCAN2].gpu, &nptr, &blks2, &zon };
cudaCheck ( cuLaunchKernel ( cuFunc[FUNC_PREFIXSUM], 1, 1, 1, threads, 1, 1, 0, NULL, argsC, NULL ),
"VolumeGVDB", "PrefixSum", "cuLaunch", "FUNC_PREFIXSUM (A2,S2->null)", mbDebug);
void* argsD[3] = { &mAux[AUX_SCAN1].gpu, &mAux[AUX_SCAN2].gpu, &blks1 };
cudaCheck ( cuLaunchKernel ( cuFunc[FUNC_PREFIXFIXUP], blks2, 1, 1, threads, 1, 1, 0, NULL, argsD, NULL ),
"VolumeGVDB", "PrefixSum", "cuLaunch", "FUNC_PREFIXFIXUP (S2->S1)", mbDebug);
#endif
void* argsE[3] = { &outArray, &mAux[AUX_SCAN1].gpu, &numElem };
cudaCheck ( cuLaunchKernel ( cuFunc[FUNC_PREFIXFIXUP], blks1, 1, 1, threads, 1, 1, 0, NULL, argsE, NULL ),
"VolumeGVDB", "PrefixSum", "cuLaunch", "FUNC_PREFIXFIXUP (S1->out)", mbDebug);
POP_CTX
}
void VolumeGVDB::AllocData ( DataPtr& ptr, int cnt, int stride, bool bCPU )
{
PUSH_CTX
if ( (ptr.cpu == 0 && bCPU) || ptr.gpu==0 || cnt > ptr.max || stride != ptr.stride )
mPool->CreateMemLinear ( ptr, 0x0, stride, cnt, bCPU ); // always reallocates
POP_CTX
}
void VolumeGVDB::FreeData( DataPtr& ptr )
{
PUSH_CTX
mPool->FreeMemLinear(ptr);
POP_CTX
}
void VolumeGVDB::CommitData ( DataPtr ptr )
{
PUSH_CTX
PERF_PUSH ( "Commit Data" );
mPool->CommitMem ( ptr );
PERF_POP ();
POP_CTX
}
void VolumeGVDB::CommitData ( DataPtr& dat, int cnt, char* cpubuf, int offs, int stride )
{
dat.cpu = cpubuf;
dat.usedNum = cnt;
dat.lastEle = cnt;
dat.max = cnt;
dat.stride = stride;
dat.subdim.Set ( offs, stride, 0 );
if (dat.gpu == 0x0) {
gprintf( "ERROR: Buffer not allocated on GPU. May be missing call to AllocData.\n");
gerror();
return;
}
PUSH_CTX
PERF_PUSH ( "Commit Data" );
mPool->CommitMem ( dat );
PERF_POP ();
POP_CTX
}
void VolumeGVDB::SetDataCPU ( DataPtr& dat, int cnt, char* cptr, int offs, int stride )
{
dat.usedNum = cnt;
dat.lastEle = cnt;
dat.max = cnt;
dat.cpu = cptr;
dat.stride = stride;
dat.subdim.Set ( offs, stride, 0 );
}
void VolumeGVDB::SetDataGPU ( DataPtr& dat, int cnt, CUdeviceptr gptr, int offs, int stride )
{
dat.lastEle = cnt;
dat.usedNum = cnt;
dat.max = cnt;
dat.gpu = gptr;
dat.stride = stride;
dat.subdim.Set ( offs, stride, 0 );
}
void VolumeGVDB::RetrieveData ( DataPtr ptr )
{
PUSH_CTX
mPool->RetrieveMem ( ptr );
POP_CTX
}
char* VolumeGVDB::getDataCPU ( DataPtr ptr, int n, int stride )
{
return (ptr.cpu + n*stride);
}
void VolumeGVDB::CommitTransferFunc ()
{
PUSH_CTX
mPool->CreateMemLinear ( mTransferPtr, (char*) mScene->getTransferFunc(), 16384*sizeof(Vector4DF) );
mVDBInfo.update = true; // tranfer func pointer may have changed for next render
POP_CTX
}
void VolumeGVDB::SetPoints ( DataPtr& pntpos, DataPtr& pntvel, DataPtr& pntclr )
{
mAux[AUX_PNTPOS] = pntpos;
mAux[AUX_PNTVEL] = pntvel;
mAux[AUX_PNTCLR] = pntclr;
if ( pntvel.gpu==0 ) CleanAux ( AUX_SUBCELL_PNT_VEL );
if ( pntclr.gpu==0 ) CleanAux ( AUX_SUBCELL_PNT_CLR );
}
void VolumeGVDB::SetDiv ( DataPtr div )
{
mAux[AUX_DIV] = div;
}
void VolumeGVDB::SetSupportPoints ( DataPtr& pntpos, DataPtr& dirpos )
{
mAux[AUX_PNTPOS] = pntpos;
mAux[AUX_PNTDIR] = dirpos;
}
void VolumeGVDB::CleanAux()
{
PUSH_CTX
for (int id = 0; id < MAX_AUX; id++) {
mAux[id].lastEle = 0; mAux[id].usedNum = 0;
mAux[id].max = 0; mAux[id].size = 0; mAux[id].stride = 0;
if (mAux[id].cpu != 0x0) { free(mAux[id].cpu); mAux[id].cpu = 0x0;}
if (mAux[id].gpu != 0x0) { (cuMemFree(mAux[id].gpu), "cuMemFree", "CleanAux"); mAux[id].gpu = 0x0; }
}
POP_CTX
}
void VolumeGVDB::CleanAux(int id)
{
PUSH_CTX
//std::cout << "clean aux " << id << std::endl;
mAux[id].lastEle = 0;
mAux[id].usedNum = 0;
mAux[id].max = 0;
mAux[id].size = 0;
mAux[id].stride = 0;
if (mAux[id].cpu != 0x0)
{
free(mAux[id].cpu);
mAux[id].cpu = 0x0;
}
if (mAux[id].gpu != 0x0)
{
(cuMemFree(mAux[id].gpu), "cuMemFree", "CleanAux");
mAux[id].gpu = 0x0;
}
POP_CTX
}
void VolumeGVDB::PrepareAux ( int id, int cnt, int stride, bool bZero, bool bCPU )
{
PUSH_CTX
if ( mAux[id].lastEle < cnt || mAux[id].stride != stride ) {
mPool->CreateMemLinear ( mAux[id], 0x0, stride, cnt, bCPU );
}
if ( bZero ) {
cudaCheck ( cuMemsetD8 ( mAux[id].gpu, 0, mAux[id].size ), "VolumeGVDB", "PrepareAux", "cuMemsetD8", "", mbDebug);
}
POP_CTX
}
void VolumeGVDB::InsertPointsSubcell( int subcell_size, int num_pnts, float pRadius, Vector3DF trans, int& pSCPntsLength)
{
int numBrick = static_cast<int>(mPool->getPoolUsedCnt(0, 0));
if (numBrick == 0) {
gprintf("Warning: InsertPointsSubcell yet no bricks exist.\n");
return;
}
PrepareVDB();
PUSH_CTX
PERF_PUSH("Insert pnt sc");
int numSCellPerBrick = static_cast<int>(pow(getRes(0) / subcell_size, 3));
int numSCell = numSCellPerBrick * numBrick;
int SCDim = getRes(0) / subcell_size;
Vector3DI range = getRange(0) / (getRes(0) / subcell_size);
int numSCellMapping = static_cast<int>(mPool->getPoolTotalCnt(0, 0));
int threads = 512;
int pblks = int(numSCellMapping / threads)+1;
PrepareAux( AUX_SUBCELL_FLAG, numSCellMapping, sizeof(int), false, true);
PrepareAux( AUX_SUBCELL_MAPPING, numSCellMapping, sizeof(int), false);
void* argsSetFlag[3] = { &cuVDBInfo, &numSCellMapping, &mAux[AUX_SUBCELL_FLAG].gpu};
cudaCheck(cuLaunchKernel(cuFunc[FUNC_SET_FLAG_SUBCELL], pblks, 1, 1, threads, 1, 1, 0, NULL, argsSetFlag, NULL),
"VolumeGVDB", "InsertPointsSubcell", "cuLaunch", "FUNC_SET_FLAG_SUBCELL", mbDebug);
PrefixSum ( mAux[AUX_SUBCELL_FLAG].gpu, mAux[AUX_SUBCELL_MAPPING].gpu, numSCellMapping);
//////////////////////////////////////////////////////////////////////////
PERF_PUSH("SC counting");
// subcell count
pblks = int(num_pnts / threads)+1;
PrepareAux ( AUX_SUBCELL_CNT, numSCell, sizeof(int), true );
void* argsCounting[14] = { &cuVDBInfo, &subcell_size, &numSCellPerBrick,
&num_pnts, &mAux[AUX_PNTPOS].gpu, &mAux[AUX_PNTPOS].subdim.x, &mAux[AUX_PNTPOS].stride,
&mAux[AUX_SUBCELL_CNT].gpu, &range.x, &trans.x, &SCDim, &pRadius, &numSCell, &mAux[AUX_SUBCELL_MAPPING].gpu};
cudaCheck ( cuLaunchKernel ( cuFunc[FUNC_COUNT_SUBCELL], pblks, 1, 1, threads, 1, 1, 0, NULL, argsCounting, NULL ),
"VolumeGVDB", "InsertPointsSubcell", "cuLaunch", "FUNC_COUNT_SUBCELL", mbDebug);
PERF_POP();
#if 0
int* sc_cnt = (int*) malloc(numSCell * sizeof(int));
cudaCheck ( cuMemcpyDtoH ( sc_cnt, mAux[AUX_SUBCELL_CNT].gpu, numSCell * sizeof(int) ), "InsertPointsSubcell","","","",false );
int maxSCCnt = 0;
int minSCCnt = 1000000;
int totalCnt = 0;
for (int i = 0; i < numSCell; i++)
{
if(sc_cnt[i] > maxSCCnt) maxSCCnt = sc_cnt[i];
if(sc_cnt[i] < minSCCnt) minSCCnt = sc_cnt[i];
totalCnt += sc_cnt[i];
}
std::cout << "# Subcells: " << numSCell << std::endl;
std::cout << "Pnt/Subcell (Max): " << maxSCCnt << std::endl;
std::cout << "Pnt/Subcell (Min): " << minSCCnt << std::endl;
std::cout << "Pnt/Subcell (Ave): " << totalCnt/float(numSCell) << std::endl;
std::cout << "Total Subcell Pnt: " << totalCnt << std::endl;
delete sc_cnt;
#endif
//////////////////////////////////////////////////////////////////////////
// prefixsum
PERF_PUSH("PrefixSum");
PrepareAux ( AUX_SUBCELL_PREFIXSUM, numSCell, sizeof(int), true );
PrefixSum ( mAux[AUX_SUBCELL_CNT].gpu, mAux[AUX_SUBCELL_PREFIXSUM].gpu, numSCell);
PERF_POP();
//////////////////////////////////////////////////////////////////////////
PERF_PUSH("Fetching");
int offset_last, cnt_last;
cudaCheck ( cuMemcpyDtoH ( &offset_last, mAux[AUX_SUBCELL_PREFIXSUM].gpu + (numSCell - 1) * sizeof(int), sizeof(int) ),
"VolumeGVDB", "InsertPointsSubcell", "cuMemcpyDtoH", "AUX_SUBCELL_PREFIXSUM", mbDebug);
cudaCheck ( cuMemcpyDtoH ( &cnt_last, mAux[AUX_SUBCELL_CNT].gpu + (numSCell - 1) * sizeof(int), sizeof(int) ),
"VolumeGVDB", "InsertPointsSubcell", "cuMemcpyDtoH", "AUX_SUBCELL_CNT", mbDebug);
pSCPntsLength = offset_last + cnt_last; // total number of subcell points
if (pSCPntsLength == 0 ) return;
PrepareAux ( AUX_SUBCELL_CNT, numSCell, sizeof(int), true );
PrepareAux ( AUX_SUBCELL_PNT_POS, pSCPntsLength, sizeof(float3), false );
if (mAux[AUX_PNTVEL].gpu != 0x0) PrepareAux ( AUX_SUBCELL_PNT_VEL, pSCPntsLength, sizeof(float3), false );
if (mAux[AUX_PNTCLR].gpu != 0x0) PrepareAux ( AUX_SUBCELL_PNT_CLR, pSCPntsLength, sizeof(uint), false);
PERF_POP();
//////////////////////////////////////////////////////////////////////////
PERF_PUSH("SC insert");
void* argsInsert[23] = { &cuVDBInfo, &subcell_size, &numSCellPerBrick, &num_pnts,
&mAux[AUX_SUBCELL_CNT].gpu, &mAux[AUX_SUBCELL_PREFIXSUM].gpu, &mAux[AUX_SUBCELL_MAPPING].gpu,
&range.x, &trans.x, &SCDim, &pRadius,
&mAux[AUX_PNTPOS].gpu, &mAux[AUX_PNTPOS].subdim.x, &mAux[AUX_PNTPOS].stride, &mAux[AUX_SUBCELL_PNT_POS].gpu,
&mAux[AUX_PNTVEL].gpu, &mAux[AUX_PNTVEL].subdim.x, &mAux[AUX_PNTVEL].stride, &mAux[AUX_SUBCELL_PNT_VEL].gpu,
&mAux[AUX_PNTCLR].gpu, &mAux[AUX_PNTCLR].subdim.x, &mAux[AUX_PNTCLR].stride, &mAux[AUX_SUBCELL_PNT_CLR].gpu
};
cudaCheck ( cuLaunchKernel ( cuFunc[FUNC_INSERT_SUBCELL], pblks, 1, 1, threads, 1, 1, 0, NULL, argsInsert, NULL ),
"VolumeGVDB", "InsertPointsSubcell", "cuLaunch", "FUNC_INSERT_SUBCELL", mbDebug);
PERF_POP();
//////////////////////////////////////////////////////////////////////////
PERF_PUSH("SC pos");
PrepareAux ( AUX_SUBCELL_POS, numSCell, sizeof(int3), false );
PrepareAux ( AUX_SUBCELL_NID, numSCell, sizeof(int), false );
void* argsSCPos[10] = { &cuVDBInfo, &mAux[AUX_SUBCELL_NID].gpu, &mAux[AUX_SUBCELL_POS].gpu, &numSCellMapping, &SCDim, &numSCellPerBrick, &subcell_size, &mAux[AUX_SUBCELL_MAPPING].gpu};
pblks = int(numSCellMapping / threads)+1;
cudaCheck ( cuLaunchKernel ( cuFunc[FUNC_CALC_SUBCELL_POS], pblks, 1, 1, threads, 1, 1, 0, NULL, argsSCPos, NULL ),
"VolumeGVDB", "InsertPointsSubcell", "cuLaunch", "FUNC_CALC_SUBCELL_POS", mbDebug);
PERF_POP();
PERF_POP();
POP_CTX
}
void VolumeGVDB::InsertPointsSubcell_FP16(int subcell_size, int num_pnts, float pRadius, Vector3DF trans, int& pSCPntsLength)
{
PrepareVDB();
PUSH_CTX
PERF_PUSH("Insert pnt sc");
int numSCellPerBrick = static_cast<int>(pow(getRes(0) / subcell_size, 3));
int numBrick = static_cast<int>(mPool->getPoolUsedCnt(0, 0));
int numSCell = numSCellPerBrick * numBrick;
int SCDim = getRes(0) / subcell_size;
Vector3DI range = getRange(0) / (getRes(0) / subcell_size);
int numSCellMapping = static_cast<int>(mPool->getPoolTotalCnt(0, 0));
int threads = 512;
int pblks = int(numSCellMapping / threads) + 1;
PrepareAux(AUX_SUBCELL_FLAG, numSCellMapping, sizeof(int), false);
PrepareAux(AUX_SUBCELL_MAPPING, numSCellMapping, sizeof(int), false);
void* argsSetFlag[3] = { &cuVDBInfo, &numSCellMapping, &mAux[AUX_SUBCELL_FLAG].gpu };
cudaCheck(cuLaunchKernel(cuFunc[FUNC_SET_FLAG_SUBCELL], pblks, 1, 1, threads, 1, 1, 0, NULL, argsSetFlag, NULL),
"VolumeGVDB", "InsertPointsSubcell_FP16", "cuLaunch", "FUNC_SET_FLAG_SUBCELL", mbDebug);
PrefixSum(mAux[AUX_SUBCELL_FLAG].gpu, mAux[AUX_SUBCELL_MAPPING].gpu, numSCellMapping);
//////////////////////////////////////////////////////////////////////////
PERF_PUSH("SC counting");
// subcell count
pblks = int(num_pnts / threads) + 1;
PrepareAux(AUX_SUBCELL_CNT, numSCell, sizeof(int), true);
void* argsCounting[14] = { &cuVDBInfo, &subcell_size, &numSCellPerBrick, &num_pnts, &mAux[AUX_PNTPOS].gpu, &mAux[AUX_PNTPOS].subdim.x, &mAux[AUX_PNTPOS].stride,
&mAux[AUX_SUBCELL_CNT].gpu, &range.x, &trans.x, &SCDim, &pRadius, &numSCell, &mAux[AUX_SUBCELL_MAPPING].gpu };
cudaCheck(cuLaunchKernel(cuFunc[FUNC_COUNT_SUBCELL], pblks, 1, 1, threads, 1, 1, 0, NULL, argsCounting, NULL),
"VolumeGVDB", "InsertPointsSubcell_FP16", "cuLaunch", "FUNC_COUNT_SUBCELL", mbDebug);
PERF_POP();
//////////////////////////////////////////////////////////////////////////
// prefixsum
PERF_PUSH("PrefixSum");
PrepareAux(AUX_SUBCELL_PREFIXSUM, numSCell, sizeof(int), true);
PrefixSum(mAux[AUX_SUBCELL_CNT].gpu, mAux[AUX_SUBCELL_PREFIXSUM].gpu, numSCell);
PERF_POP();
//////////////////////////////////////////////////////////////////////////
PERF_PUSH("Fetching");
int tmpa, tmpb;
cudaCheck(cuMemcpyDtoH(&tmpa, mAux[AUX_SUBCELL_PREFIXSUM].gpu + (numSCell - 1) * sizeof(int), sizeof(int)),
"VolumeGVDB", "InsertPointsSubcell_FP16", "cuMemcpyDtoH", "AUX_SUBCELL_PREFIXSUM", mbDebug);
cudaCheck(cuMemcpyDtoH(&tmpb, mAux[AUX_SUBCELL_CNT].gpu + (numSCell - 1) * sizeof(int), sizeof(int)),
"VolumeGVDB", "InsertPointsSubcell_FP16", "cuMemcpyDtoH", "AUX_SUBCELL_CNT", mbDebug);
pSCPntsLength = tmpa + tmpb;
PrepareAux(AUX_SUBCELL_CNT, numSCell, sizeof(int), true);
PrepareAux(AUX_SUBCELL_PNT_POS, pSCPntsLength, sizeof(ushort3), false);
if (mAux[AUX_PNTVEL].gpu != 0x0) PrepareAux(AUX_SUBCELL_PNT_VEL, pSCPntsLength, sizeof(ushort3), false);
if (mAux[AUX_PNTCLR].gpu != 0x0) PrepareAux(AUX_SUBCELL_PNT_CLR, pSCPntsLength, sizeof(uint), false);
PERF_POP();
//////////////////////////////////////////////////////////////////////////
PERF_PUSH("SC insert");
void* argsInsert[27] = { &cuVDBInfo, &subcell_size, &numSCellPerBrick, &num_pnts,
&mAux[AUX_SUBCELL_CNT].gpu, &mAux[AUX_SUBCELL_PREFIXSUM].gpu, &mAux[AUX_SUBCELL_MAPPING].gpu,
&mPosMin.x, &mPosRange.x, &mVelMin.x, &mVelRange.x,
&range.x, &trans.x, &SCDim, &pRadius,
&mAux[AUX_PNTPOS].gpu, &mAux[AUX_PNTPOS].subdim.x, &mAux[AUX_PNTPOS].stride, &mAux[AUX_SUBCELL_PNT_POS].gpu,
&mAux[AUX_PNTVEL].gpu, &mAux[AUX_PNTVEL].subdim.x, &mAux[AUX_PNTVEL].stride, &mAux[AUX_SUBCELL_PNT_VEL].gpu,
&mAux[AUX_PNTCLR].gpu, &mAux[AUX_PNTCLR].subdim.x, &mAux[AUX_PNTCLR].stride, &mAux[AUX_SUBCELL_PNT_CLR].gpu
};
cudaCheck(cuLaunchKernel(cuFunc[FUNC_INSERT_SUBCELL_FP16], pblks, 1, 1, threads, 1, 1, 0, NULL, argsInsert, NULL),
"VolumeGVDB", "InsertPointsSubcell_FP16", "cuLaunch", "FUNC_INSERT_SUBCELL_FP16", mbDebug);
PERF_POP();
//////////////////////////////////////////////////////////////////////////
PERF_PUSH("SC pos");
PrepareAux(AUX_SUBCELL_POS, numSCell, sizeof(int3), false);
PrepareAux(AUX_SUBCELL_NID, numSCell, sizeof(int), false);
void* argsSCPos[10] = { &cuVDBInfo, &mAux[AUX_SUBCELL_NID].gpu, &mAux[AUX_SUBCELL_POS].gpu, &numSCellMapping, &SCDim, &numSCellPerBrick, &subcell_size, &mAux[AUX_SUBCELL_MAPPING].gpu };
pblks = int(numSCellMapping / threads) + 1;
cudaCheck(cuLaunchKernel(cuFunc[FUNC_CALC_SUBCELL_POS], pblks, 1, 1, threads, 1, 1, 0, NULL, argsSCPos, NULL),
"VolumeGVDB", "InsertPointsSubcell_FP16", "cuLaunch", "FUNC_CALC_SUBCELL_POS", mbDebug);
PERF_POP();
PERF_POP();
POP_CTX
}
void VolumeGVDB::MapExtraGVDB (int subcell_size)
{
if (!mHasObstacle) return;
PUSH_CTX
PERF_PUSH("SC extra");
int numSCellPerBrick = static_cast<int>(pow(getRes(0) / subcell_size, 3));
int numBrick = static_cast<int>(mPool->getPoolUsedCnt(0, 0));
int numSCell = numSCellPerBrick * numBrick;
int SCDim = getRes(0) / subcell_size;
Vector3DI range = getRange(0) / (getRes(0) / subcell_size);
int numSCellMapping = static_cast<int>(mPool->getPoolTotalCnt(0, 0));
int threads = 512;
PrepareAux(AUX_SUBCELL_OBS_NID, numSCell, sizeof(int), false);
void* argsSCPos[10] = { &cuVDBInfo, &numSCellMapping, &SCDim, &numSCellPerBrick, &subcell_size, &mAux[AUX_SUBCELL_MAPPING].gpu, &cuOBSVDBInfo, &mAux[AUX_SUBCELL_OBS_NID].gpu };
int pblks = int(numSCellMapping / threads) + 1;
cudaCheck(cuLaunchKernel(cuFunc[FUNC_MAP_EXTRA_GVDB], pblks, 1, 1, threads, 1, 1, 0, NULL, argsSCPos, NULL),
"VolumeGVDB", "MapExtraGVDB", "cuLaunch", "FUNC_MAP_EXTRA_GVDB", mbDebug);
PERF_POP();
POP_CTX
}
void VolumeGVDB::InsertPoints ( int num_pnts, Vector3DF trans, bool bPrefix )
{
PrepareVDB ();
PUSH_CTX
PERF_PUSH("InsertPoints");
// Prepare aux arrays
PERF_PUSH ( "Prepare Aux");
int bricks = static_cast<int>(mPool->getAtlas(0).lastEle);
PrepareAux ( AUX_PNODE, num_pnts, sizeof(int), false ); // node which each point falls into
PrepareAux ( AUX_PNDX, num_pnts, sizeof(int), false ); // index of the point inside that node
PrepareAux ( AUX_GRIDCNT, bricks, sizeof(int), true ); // number of points in each brick cell
PERF_POP();
// Insert particles
PERF_PUSH ( "Insert kernel");
int threads = 512;
int pblks = int(num_pnts / threads)+1;
void* args[9] = { &cuVDBInfo, &num_pnts, &mAux[AUX_PNTPOS].gpu, &mAux[AUX_PNTPOS].subdim.x, &mAux[AUX_PNTPOS].stride, &mAux[AUX_PNODE].gpu, &mAux[AUX_PNDX].gpu, &mAux[AUX_GRIDCNT].gpu, &trans.x };
cudaCheck ( cuLaunchKernel ( cuFunc[FUNC_INSERT_POINTS], pblks, 1, 1, threads, 1, 1, 0, NULL, args, NULL ),
"VolumeGVDB", "InsertPoints", "cuLaunch", "FUNC_INSERT_POINTS", mbDebug);
PERF_POP();
if ( bPrefix ) {
// Prefix sum for brick offsets
PERF_PUSH ( " Prefix sum");
PrepareAux ( AUX_GRIDOFF, bricks, sizeof(int), false );
PrefixSum ( mAux[AUX_GRIDCNT].gpu, mAux[AUX_GRIDOFF].gpu, bricks );
PERF_POP();
PERF_PUSH ( " Sort points");
PrepareAux ( AUX_PNTSORT, num_pnts, sizeof(Vector3DF), false );
void* args[13] = { &cuVDBInfo, &num_pnts, &mAux[AUX_PNTPOS].gpu, &mAux[AUX_PNTPOS].subdim.x, &mAux[AUX_PNTPOS].stride, &mAux[AUX_PNODE].gpu, &mAux[AUX_PNDX].gpu,
&bricks, &mAux[AUX_GRIDCNT].gpu, &mAux[AUX_GRIDOFF].gpu, &mAux[AUX_PNTSORT].gpu, &trans.x };
cudaCheck ( cuLaunchKernel ( cuFunc[FUNC_SORT_POINTS], pblks, 1, 1, threads, 1, 1, 0, NULL, args, NULL ),
"VolumeGVDB", "InsertPoints", "cuLaunch", "FUNC_SORT_POINTS", mbDebug);
PERF_POP();
}
PERF_POP(); // InsertParticles
POP_CTX
}
void VolumeGVDB::InsertSupportPoints ( int num_pnts, float offset, Vector3DF trans, bool bPrefix )
{
PrepareVDB ();
PUSH_CTX
PERF_PUSH("InsertPoints");
// Prepare aux arrays
PERF_PUSH ( "Prepare Aux");
int bricks = static_cast<int>(mPool->getAtlas(0).usedNum);
PrepareAux ( AUX_PNODE, num_pnts, sizeof(int), false ); // node which each point falls into
PrepareAux ( AUX_PNDX, num_pnts, sizeof(int), false ); // index of the point inside that node
PrepareAux ( AUX_GRIDCNT, bricks, sizeof(int), true ); // number of points in each brick cell
PERF_POP();
// Insert particles
PERF_PUSH ( "Insert kernel");
int threads = 512;
int pblks = int(num_pnts / threads)+1;
void* args[12] = { &num_pnts, &offset,
&mAux[AUX_PNTPOS].gpu, &mAux[AUX_PNTPOS].subdim.x, &mAux[AUX_PNTPOS].stride,
&mAux[AUX_PNODE].gpu, &mAux[AUX_PNDX].gpu, &mAux[AUX_GRIDCNT].gpu,
&mAux[AUX_PNTDIR].gpu, &mAux[AUX_PNTDIR].subdim.x, &mAux[AUX_PNTDIR].stride,
&trans.x };
cudaCheck ( cuLaunchKernel ( cuFunc[FUNC_INSERT_SUPPORT_POINTS], pblks, 1, 1, threads, 1, 1, 0, NULL, args, NULL ),
"VolumeGVDB", "InsertSupportPoints", "cuLaunch", "FUNC_INSERT_SUPPORT_POINTS", mbDebug);
PERF_POP();
PERF_POP(); // InsertParticles
POP_CTX
}
void VolumeGVDB::ScalePntPos (int num_pnts, float scale)
{
PUSH_CTX
int threads = 512;
int pblks = int(num_pnts / threads)+1;
void* args[5] = { &num_pnts, &mAux[AUX_PNTPOS].gpu, &mAux[AUX_PNTPOS].subdim.x, &mAux[AUX_PNTPOS].stride, &scale };
cudaCheck ( cuLaunchKernel ( cuFunc[FUNC_SCALE_PNT_POS], pblks, 1, 1, threads, 1, 1, 0, NULL, args, NULL ),
"VolumeGVDB", "ScalePntPos", "cuLaunch", "FUNC_SCALE_PNT_POS", mbDebug);
POP_CTX
}
void VolumeGVDB::GatherDensity ( int subcell_size, int num_pnts, float radius, Vector3DF trans, int& pSCPntsLength, int chanDensity, int chanClr, bool bAccum )
{
int num_brick = static_cast<int>(mPool->getPoolUsedCnt(0, 0));
if (pSCPntsLength==0) return;
if (num_brick == 0) return;
PrepareVDB();
PERF_PUSH("Gather Density");
int numSCell = static_cast<int>(pow(getRes(0) / subcell_size, 3)) * num_brick;
void* args[14] =
{
&cuVDBInfo, &num_pnts, &numSCell, &radius,
&mAux[AUX_SUBCELL_NID].gpu, &mAux[AUX_SUBCELL_CNT].gpu, &mAux[AUX_SUBCELL_PREFIXSUM].gpu, &mAux[AUX_SUBCELL_POS].gpu,
&mAux[AUX_SUBCELL_PNT_POS].gpu, &mAux[AUX_SUBCELL_PNT_VEL].gpu, &mAux[AUX_SUBCELL_PNT_CLR].gpu,
&chanDensity, &chanClr, &bAccum
};
PUSH_CTX
cudaCheck(cuLaunchKernel(cuFunc[FUNC_GATHER_DENSITY], numSCell, 1, 1, subcell_size, subcell_size, subcell_size, 0, NULL, args, NULL),
"VolumeGVDB", "GatherDensity", "cuLaunch", "FUNC_GATHER_DENSITY", mbDebug);
POP_CTX
PERF_POP();
}
void VolumeGVDB::GatherLevelSet (int subcell_size, int num_pnts, float radius, Vector3DF trans, int& pSCPntsLength, int chanDensity, int chanClr, bool bAccum )
{
int num_brick = static_cast<int>(mPool->getPoolUsedCnt(0, 0));
if (num_brick == 0) return;
PrepareVDB();
PERF_PUSH("Gather LevelSet");
int numSCell = static_cast<int>(pow(getRes(0) / subcell_size, 3)) * num_brick;
void* args[14] =
{
&cuVDBInfo, &num_pnts, &numSCell, &radius,
&mAux[AUX_SUBCELL_NID].gpu, &mAux[AUX_SUBCELL_CNT].gpu, &mAux[AUX_SUBCELL_PREFIXSUM].gpu, &mAux[AUX_SUBCELL_POS].gpu,
&mAux[AUX_SUBCELL_PNT_POS].gpu, &mAux[AUX_SUBCELL_PNT_VEL].gpu, &mAux[AUX_SUBCELL_PNT_CLR].gpu,
&chanDensity, &chanClr, &bAccum
};
PUSH_CTX
cudaCheck(cuLaunchKernel(cuFunc[FUNC_GATHER_LEVELSET], numSCell, 1, 1, subcell_size, subcell_size, subcell_size, 0, NULL, args, NULL),
"VolumeGVDB", "GatherLevelSet", "cuLaunch", "FUNC_GATHER_LEVELSET", mbDebug);
POP_CTX
PERF_POP();
}
void VolumeGVDB::GatherLevelSet_FP16(int subcell_size, int num_pnts, float radius, Vector3DF trans, int& pSCPntsLength, int chanDensity, int chanClr)
{
int num_brick = static_cast<int>(mPool->getPoolUsedCnt(0, 0));
if (num_brick == 0) return;
PrepareVDB();
PERF_PUSH("Gather LevelSet");
int numSCell = static_cast<int>(pow(getRes(0) / subcell_size, 3)) * num_brick;
void* args[23] =
{
&cuVDBInfo, &num_pnts, &numSCell, &radius,
&mPosMin.x, &mPosRange.x, &mVelMin.x, &mVelRange.x,
&mAux[AUX_SUBCELL_NID].gpu, &mAux[AUX_SUBCELL_CNT].gpu, &mAux[AUX_SUBCELL_PREFIXSUM].gpu, &mAux[AUX_SUBCELL_POS].gpu,
&mAux[AUX_SUBCELL_PNT_POS].gpu, &mAux[AUX_SUBCELL_PNT_VEL].gpu, &mAux[AUX_SUBCELL_PNT_CLR].gpu,
&chanDensity, &chanClr
};
PUSH_CTX
cudaCheck(cuLaunchKernel(cuFunc[FUNC_GATHER_LEVELSET_FP16], numSCell, 1, 1, subcell_size, subcell_size, subcell_size, 0, NULL, args, NULL),
"VolumeGVDB", "GatherLevelSet_FP16", "cuLaunch", "FUNC_GATHER_LEVELSET_FP16", mbDebug);
POP_CTX
PERF_POP();
}
void VolumeGVDB::GetBoundingBox(int num_pnts, Vector3DF pTrans)
{
PUSH_CTX
PERF_PUSH("GPU bounding box");
PERF_PUSH("Split pos");
PrepareAux(AUX_WORLD_POS_X, num_pnts, sizeof(float), false);
PrepareAux(AUX_WORLD_POS_Y, num_pnts, sizeof(float), false);
PrepareAux(AUX_WORLD_POS_Z, num_pnts, sizeof(float), false);
int threads = 256;
int pblks = int(num_pnts / threads) + 1;
void* args[8] =
{
&num_pnts, &pTrans.x,
&mAux[AUX_PNTPOS].gpu, &mAux[AUX_PNTPOS].subdim.x, &mAux[AUX_PNTPOS].stride,
&mAux[AUX_WORLD_POS_X].gpu, &mAux[AUX_WORLD_POS_Y].gpu, &mAux[AUX_WORLD_POS_Z].gpu
};
cudaCheck(cuLaunchKernel(cuFunc[FUNC_SPLIT_POS], pblks, 1, 1, threads, 1, 1, 0, NULL, args, NULL),
"VolumeGVDB", "GetBoundingBox", "cuLaunch", "FUNC_SPLIT_POS", mbDebug);
PERF_POP();
PERF_PUSH("Reduce");
PrepareAux(AUX_BOUNDING_BOX, 6, sizeof(float), false, true);
const int axes[] = {
AUX_WORLD_POS_X,
AUX_WORLD_POS_Y,
AUX_WORLD_POS_Z
};
for (uint32_t i = 0; i < 6; ++i) {
if (i < 3) {
gvdbDeviceMinElementF((mAux[AUX_BOUNDING_BOX].gpu + i * sizeof(float)),mAux[axes[i%3]].gpu,num_pnts);
}
else {
gvdbDeviceMaxElementF((mAux[AUX_BOUNDING_BOX].gpu + i * sizeof(float)), mAux[axes[i % 3]].gpu, num_pnts);
}
}
PERF_POP();
RetrieveData(mAux[AUX_BOUNDING_BOX]);
float* dat = (float*)getDataPtr(0, mAux[AUX_BOUNDING_BOX]);
mPosMin.x = dat[0] - 1; mPosMin.y = dat[1] - 1; mPosMin.z = dat[2] - 1;
mPosMax.x = dat[3] + 2; mPosMax.y = dat[4] + 2; mPosMax.z = dat[5] + 2;
mPosMin.x = 0 > mPosMin.x ? 0 : mPosMin.x;
mPosMin.y = 0 > mPosMin.y ? 0 : mPosMin.y;
mPosMin.z = 0 > mPosMin.z ? 0 : mPosMin.z;
mPosMax.x = 0 > mPosMax.x ? 0 : mPosMax.x;
mPosMax.y = 0 > mPosMax.y ? 0 : mPosMax.y;
mPosMax.z = 0 > mPosMax.z ? 0 : mPosMax.z;
mPosRange = mPosMax - mPosMin;
PERF_POP();
POP_CTX
}
void VolumeGVDB::GetMinMaxVel(int num_pnts)
{
Vector3DF pTrans(0, 0, 0);
PUSH_CTX
PERF_PUSH("Vel bounding box");
PERF_PUSH("Split pos");
PrepareAux(AUX_WORLD_VEL_X, num_pnts, sizeof(float), false);
PrepareAux(AUX_WORLD_VEL_Y, num_pnts, sizeof(float), false);
PrepareAux(AUX_WORLD_VEL_Z, num_pnts, sizeof(float), false);
int threads = 256;
int pblks = int(num_pnts / threads) + 1;
void* args[8] =
{
&num_pnts, &pTrans.x,
&mAux[AUX_PNTVEL].gpu, &mAux[AUX_PNTVEL].subdim.x, &mAux[AUX_PNTVEL].stride,
&mAux[AUX_WORLD_VEL_X].gpu, &mAux[AUX_WORLD_VEL_Y].gpu, &mAux[AUX_WORLD_VEL_Z].gpu
};
cudaCheck(cuLaunchKernel(cuFunc[FUNC_SPLIT_POS], pblks, 1, 1, threads, 1, 1, 0, NULL, args, NULL), "VolumeGVDB", "GetMinMaxVel", "cuLaunch", "FUNC_SPLIT_POS", mbDebug);
PERF_POP();
PERF_PUSH("Reduce");
PrepareAux(AUX_VEL_BOUNDING_BOX, 6, sizeof(float), false, true);
const int axes[] = {
AUX_WORLD_VEL_X,
AUX_WORLD_VEL_Y,
AUX_WORLD_VEL_Z
};
for (uint32_t i = 0; i < 6; ++i) {
if (i < 3) {
gvdbDeviceMinElementF((mAux[AUX_VEL_BOUNDING_BOX].gpu + i * sizeof(float)), mAux[axes[i % 3]].gpu, num_pnts);
}
else {
gvdbDeviceMaxElementF((mAux[AUX_VEL_BOUNDING_BOX].gpu + i * sizeof(float)), mAux[axes[i % 3]].gpu, num_pnts);
}
}
PERF_POP();
RetrieveData(mAux[AUX_VEL_BOUNDING_BOX]);
float* dat = (float*)getDataPtr(0, mAux[AUX_VEL_BOUNDING_BOX]);
mVelMin.x = dat[0]; mVelMin.y = dat[1]; mVelMin.z = dat[2];
mVelMax.x = dat[3]; mVelMax.y = dat[4]; mVelMax.z = dat[5];
mVelRange = mVelMax - mVelMin;
PERF_POP();
POP_CTX
}
char* VolumeGVDB::GetTestPtr()
{
return mAux[AUX_TEST].cpu;
}
void VolumeGVDB::ReadGridVel(int N)
{
PUSH_CTX
int cellNum = N * N * N;
PrepareAux(AUX_TEST, cellNum, sizeof(float), true, true); // cell_vel
PrepareAux(AUX_TEST_1, cellNum, sizeof(int) * 3, true, true); // cell_pos
int3* cell_pos = (int3*)mAux[AUX_TEST_1].cpu;
int index = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
for (int k = 0; k < N; k++) {
cell_pos[index].x = i;
cell_pos[index].y = j;
cell_pos[index++].z = k;
}
}
}
CommitData(mAux[AUX_TEST_1]);
int threads = 256;
int pblks = int(cellNum / threads) + 1;
void* args[4] = { &cuVDBInfo, &cellNum, &mAux[AUX_TEST_1].gpu, &mAux[AUX_TEST].gpu };
cudaCheck(cuLaunchKernel(cuFunc[FUNC_READ_GRID_VEL], pblks, 1, 1, threads, 1, 1, 0, NULL, args, NULL), "VolumeGVDB", "ReadGridVel", "cuLaunch", "FUNC_READ_GRID_VEL", mbDebug);
RetrieveData(mAux[AUX_TEST]);
float* cell_vel = (float *)mAux[AUX_TEST].cpu;
index = 0;
std::ofstream myfile;
myfile.open("G_matrix_free.txt");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
myfile << "C " << i << " " << j << " : ";
for (int k = 0; k < N; k++) {
myfile << cell_vel[index] << " ";
index++;
}
myfile << std::endl;
}
}
//std::cout << "----------------\n";
myfile.close();
POP_CTX
}
void VolumeGVDB::CheckVal(float slice, int chanVx, int chanVy, int chanVz, int chanVxOld, int chanVyOld, int chanVzOld)
{
PUSH_CTX
Vector3DI res = Vector3DI(30, 30, 30);
Vector3DI block(8, 1, 8);
Vector3DI grid(int(res.x / block.x) + 1, 1, int(res.z / block.z) + 1);
PrepareAux(AUX_OUT1, res.x*res.z, sizeof(float), true, true);
PrepareAux(AUX_OUT2, res.x*res.z, sizeof(float), true, true);
float* out1 = (float*)mAux[AUX_OUT1].cpu;
float* out2 = (float*)mAux[AUX_OUT2].cpu;
for (int z = 0; z < res.z; z++)
for (int x = 0; x < res.x; x++) {
out1[z*res.x + x] = -1.0;
out2[z*res.x + x] = -1.0;
}
CommitData(mAux[AUX_OUT1]);
CommitData(mAux[AUX_OUT2]);
void* args[11] = { &cuVDBInfo, &slice, &res, &chanVx, &chanVy, &chanVz, &chanVxOld, &chanVyOld, &chanVzOld, &mAux[AUX_OUT1].gpu, &mAux[AUX_OUT2].gpu };
cudaCheck(cuLaunchKernel(cuFunc[FUNC_CHECK_VAL], grid.x, grid.y, grid.z, block.x, block.y, block.z, 0, NULL, args, NULL), "VolumeGVDB", "CheckVal", "cuLaunch", "FUNC_CHECK_VAL", mbDebug);
RetrieveData(mAux[AUX_OUT1]);
RetrieveData(mAux[AUX_OUT2]);
cudaCheck(cuCtxSynchronize(), "VolumeGVDB", "CheckVal", "cuCtxSynchronize", "", mbDebug);
for (int z = 0; z < 10; z++) {
for (int x = 0; x < 10; x++) {
gprintf("%4.3f/%4.3f ", out1[z*res.x + x], out2[z*res.x + x]);
}
gprintf("\n");
}
POP_CTX
}
void VolumeGVDB::ScatterDensity ( int num_pnts, float radius, float amp, Vector3DF trans, bool expand, bool avgColor )
{
uint num_voxels;
PrepareVDB ();
PUSH_CTX
// Splat particles
PERF_PUSH ( "ScatterPointDensity");
int threads = 256;
int pblks = int(num_pnts / threads)+1;
if (mAux[AUX_PNTCLR].gpu != NULL && avgColor) {
Vector3DI brickResVec = getRes3DI(0);
num_voxels = brickResVec.x * brickResVec.y * brickResVec.z * static_cast<uint>(getNumUsedNodes(0));
if (mbProfile) PERF_PUSH("Prepare Aux");
PrepareAux(AUX_COLAVG, 4 * num_voxels, sizeof(uint), true); // node which each point falls into
if (mbProfile) PERF_POP();
}
void* args[13] = { &num_pnts, &radius, &, &mAux[AUX_PNTPOS].gpu, &mAux[AUX_PNTPOS].subdim.x, &mAux[AUX_PNTPOS].stride, &mAux[AUX_PNTCLR].gpu, &mAux[AUX_PNTCLR].subdim.x, &mAux[AUX_PNTCLR].stride, &mAux[AUX_PNODE].gpu, &trans.x, &expand, &mAux[AUX_COLAVG].gpu };
cudaCheck ( cuLaunchKernel ( cuFunc[FUNC_SCATTER_DENSITY], pblks, 1, 1, threads, 1, 1, 0, NULL, args, NULL ),
"VolumeGVDB", "ScatterPointDensity", "cuLaunch", "FUNC_SCATTER_DENSITY", mbDebug);
if (mAux[AUX_PNTCLR].gpu != NULL && avgColor) {
int threads_avgcol = 256;
int pblks_avgcol = int(num_voxels / threads_avgcol) + 1;
void* args_avgcol[2] = { &num_voxels, &mAux[AUX_COLAVG].gpu };
cudaCheck( cuLaunchKernel (cuFunc[FUNC_SCATTER_AVG_COL], pblks_avgcol, 1, 1, threads_avgcol, 1, 1, 0, NULL, args_avgcol, NULL),
"VolumeGVDB", "ScatterPointDensity", "cuLaunch", "FUNC_SCATTER_AVG_COL", mbDebug);
}
PERF_POP ();
POP_CTX
}
// psrcbits / pdestbits are:
// 1 = byte components, 3 bytes/point
// 2 = ushort components 6 bytes/point
// 4 = float components, 12 bytes/point
// 8 = double components, 24 bytes/point
//
void VolumeGVDB::ConvertAndTransform(DataPtr& psrc, char psrcbits, DataPtr& pdest, char pdestbits, int num_pnts, Vector3DF wMin, Vector3DF wDelta, Vector3DF trans, Vector3DF scal)
{
PUSH_CTX
int threads = 512;
int pblks = int(num_pnts / threads) + 1;
void* args[9] = { &num_pnts,
&psrc.gpu, &psrcbits, &pdest.gpu, &pdestbits,
&wMin, &wDelta, &trans, &scal };
cudaCheck(cuLaunchKernel(cuFunc[FUNC_CONV_AND_XFORM], pblks, 1, 1, threads, 1, 1, 0, NULL, args, NULL),
"VolumeGVDB", "ConvertAndTransform", "cuLaunch", "FUNC_CONV_AND_XFORM", mbDebug);
POP_CTX
}
void VolumeGVDB::AddSupportVoxel ( int num_pnts, float radius, float offset, float amp, Vector3DF trans, bool expand, bool avgColor )
{
PrepareVDB ();
PUSH_CTX
// Splat particles
PERF_PUSH ( "AddSupportVoxel");
int threads = 256;
int pblks = int(num_pnts / threads)+1;
void* args[14] = { &num_pnts, &radius, &offset, &,
&mAux[AUX_PNTPOS].gpu, &mAux[AUX_PNTPOS].subdim.x, &mAux[AUX_PNTPOS].stride,
&mAux[AUX_PNTDIR].gpu, &mAux[AUX_PNTDIR].subdim.x, &mAux[AUX_PNTDIR].stride,
&mAux[AUX_PNODE].gpu, &trans.x, &expand, &mAux[AUX_COLAVG].gpu };
cudaCheck ( cuLaunchKernel ( cuFunc[FUNC_ADD_SUPPORT_VOXEL], pblks, 1, 1, threads, 1, 1, 0, NULL, args, NULL ),
"VolumeGVDB", "AddSupportVoxel", "cuLaunch", "FUNC_ADD_SUPPORT_VOXEL", mbDebug);
PERF_POP ();
POP_CTX
}
void VolumeGVDB::PrintPool(uchar grp, uchar lev)
{
DataPtr* p = mPool->getPool(grp, lev);
std::cout << "Pool " << (int)grp << " at level " << (int)lev << std::endl;
std::cout << " num: " << p->lastEle << std::endl;
for (int i = 0; i < p->lastEle; i++)
{
char* pool = p->cpu;
nvdb::Node* nd = (nvdb::Node*) (pool + p->stride * i);
std::cout << " Node " << i << ":\n";
#ifdef USE_BITMASKS
if ((int)lev > 0) {
std::cout << " mMask: " << nd->countOn() << std::endl;
uint64* w1 = (uint64*) &nd->mMask;
uint64* we = (uint64*) &nd->mMask + nd->getMaskWords();
}
std::cout << " Parent ID:" << nd->mParent << std::endl;
std::cout << " Childlist address:" << (int)nd->mChildList << std::endl;
std::cout << " Child ID:" << std::endl;
if ((int)nd->mChildList > 0) {
int numChild = nd->countOn();
uint64* clist = mPool->PoolData64 ( nd->mChildList );
std::cout << " ";
for (int i = 0; i < numChild; i++)
{
std::cout << clist[i] << " ";
}
std::cout << std::endl;
}
std::cout << "------------------------------------\n";
#else
std::cout << " Parent ID:" << nd->mParent << std::endl;
std::cout << " Childlist address:" << (int)nd->mChildList << std::endl;
int r = getRes(lev);
int childlistLen = ((uint64) r*r*r);
std::cout << " Childlist length:" << childlistLen << std::endl;
std::cout << " Child ID:" << std::endl;
if ((int)nd->mChildList > 0) {
uint64* clist = mPool->PoolData64 ( nd->mChildList );
for (int i = 0; i < childlistLen; i++)
{
if ( clist[i] != ID_UNDEF64)
{
std::cout << i << " " << clist[i] << " ";
}
}
std::cout << std::endl;
}
std::cout << "------------------------------------\n";
#endif
}
std::cout << "====================================\n";
}
void VolumeGVDB::SetTransform(Vector3DF pretrans, Vector3DF scal, Vector3DF angs, Vector3DF trans )
{
mPretrans = pretrans;
mScale = scal;
mAngs = angs;
mTrans = trans;
// Compute the rotation-only part of the matrix, mXrot = R
Matrix4F mXrot;
mXrot.RotateZYX(mAngs);
// Compute mInvXrot = (S R)^-1 = R^-1 S^-1
mInvXrot.Identity();
mInvXrot.InvScaleInPlace(mScale); // scale here supports non-uniform voxels
mInvXrot.InvLeftMultiplyInPlace(mXrot);
// Compute mXform = T R S PT (pretranslate, then scale, then rotate, then translate)
mXform.Identity();
mXform.RotateTZYXS(mAngs, mTrans, mScale); // T R S
mXform.PreTranslate(mPretrans); // T R S PT
// Compute mInvXform = mXform^-1
mInvXform = mXform;
mInvXform.InvertTRS();
}
// Node queries
uint64 VolumeGVDB::getNumUsedNodes ( int lev ) { return mPool->getPoolUsedCnt(0, lev); }
uint64 VolumeGVDB::getNumTotalNodes ( int lev ) { return mPool->getPoolTotalCnt(0, lev); }
Node* VolumeGVDB::getNodeAtLevel ( int n, int lev ) { return (Node*) (mPool->PoolData( 0, lev, n )); }
Vector3DF VolumeGVDB::getWorldMin ( Node* node ) { return Vector3DF(node->mPos); }
Vector3DF VolumeGVDB::getWorldMax ( Node* node ) { return Vector3DF(node->mPos) + getCover(node->mLev); }
Vector3DF VolumeGVDB::getWorldMin() {
return mObjMin;
}
Vector3DF VolumeGVDB::getWorldMax()
{
return mObjMax;
}
|
/**
* @file Graph/DepthFirstSearch/test2.cxx Test Case for Depth-First Search
* @brief
* A test case
*
* @author George Heineman
* @date 6/15/08
*/
#include <cassert>
#include <iostream>
#include "Graph.h"
#include "dfs.h"
/** cormen example, p. 481, first edition */
int main (int argc, char **argv) {
int n = 8;
int i;
Graph g(n,true);
g.addEdge (0, 4);
g.addEdge (1, 5);
g.addEdge (1, 0);
g.addEdge (4, 1);
g.addEdge (5, 4);
g.addEdge (2, 5);
g.addEdge (2, 1);
g.addEdge (6, 2);
g.addEdge (6, 5);
g.addEdge (3, 7);
g.addEdge (3, 6);
g.addEdge (7, 6);
g.addEdge (7, 3);
vector<int> d(g.numVertices());
vector<int> f(g.numVertices());
vector<int> pred(g.numVertices());
list<EdgeLabel> labels;
dfs_search (g, 2, d, f, pred, labels);
for (i = 0; i < n; i++) {
cout << i << ": " << d[i] << "-" << f[i] << " " << pred[i] << "\n";
}
for (list<EdgeLabel>::const_iterator it = labels.begin();
it != labels.end(); ++it) {
EdgeLabel ei = (*it);
cout << ei.describe() << "\n";
}
// spot check some (hardly sufficient! but just a quick check).
assert (d[1] == 2);
assert (f[1] == 9);
assert (pred[1] == 2);
// some edge types known from graph. These are a better test case
for (list<EdgeLabel>::const_iterator it = labels.begin();
it != labels.end(); ++it) {
EdgeLabel ei = (*it);
// a cross
if (ei.src() == 6 && ei.target() == 2) {
assert (ei.type() == Cross);
}
// a tree
if (ei.src() == 2 && ei.target() == 1) {
assert (ei.type() == Tree);
}
// a back
if (ei.src() == 4 && ei.target() == 1) {
assert (ei.type() == Backward);
}
// a cross
if (ei.src() == 6 && ei.target() == 2) {
assert (ei.type() == Cross);
}
}
cout << "Passed test\n";
}
|
//$Id:$
//------------------------------------------------------------------------------
// SpiceKernelWriter
//------------------------------------------------------------------------------
// GMAT: General Mission Analysis Tool.
//
// Copyright (c) 2002 - 2015 United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration.
// All Other 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.
//
// Developed jointly by NASA/GSFC and Thinking Systems, Inc. under
// FDSS Task order 28.
//
// Author: Wendy C. Shoan
// Created: 2009.12.07
//
/**
* Implementation of the SpiceKernelWriter, which writes SPICE data (kernel) files.
*
* This code creates a temporary text file, required in order to include META-Data
* (commentary) in the SPK file. The file is deleted from the system after the
* commentary is added to the SPK file. The name of this temporary text file
* takes the form
* GMATtmpSPKcmmnt<objName>.txt
* where <objName> is the name of the object for whom the SPK file is created
*
* If the code is unable to create the temporary file (e.g., because of a permission
* problem), the SPK file will still be generated but will contain no META-data.
*
*/
//------------------------------------------------------------------------------
#include <stdio.h>
#include <sstream>
#include "SpiceKernelWriter.hpp"
#include "MessageInterface.hpp"
#include "StringUtil.hpp"
#include "TimeTypes.hpp"
#include "TimeSystemConverter.hpp"
#include "UtilityException.hpp"
#include "RealUtilities.hpp"
//#define DEBUG_SPICE_KERNEL_WRITER
//---------------------------------
// static data
//---------------------------------
// none
//---------------------------------
// public methods
//---------------------------------
//------------------------------------------------------------------------------
// SpiceKernelWriter()
//------------------------------------------------------------------------------
/**
* This method creates an object of the SpiceKernelWriter class
* (default constructor).
*
*/
//------------------------------------------------------------------------------
SpiceKernelWriter::SpiceKernelWriter() :
SpiceInterface()
{
}
//------------------------------------------------------------------------------
// SpiceKernelWriter(const SpiceKernelWriter ©)
//------------------------------------------------------------------------------
/**
* This method creates an object of the SpiceKernelWriter class, with data
* copied from the input instance.
* (copy constructor).
*
*/
//------------------------------------------------------------------------------
SpiceKernelWriter::SpiceKernelWriter(const SpiceKernelWriter ©) :
SpiceInterface(copy)
{
}
//------------------------------------------------------------------------------
// SpiceKernelWriter& operator=(const SpiceKernelWriter ©)
//------------------------------------------------------------------------------
/**
* This method sets data on "this" SpiceKernelWriter instance, copying data
* from the input instance.
*
*/
//------------------------------------------------------------------------------
SpiceKernelWriter& SpiceKernelWriter::operator=(const SpiceKernelWriter ©)
{
if (© != this)
{
SpiceInterface::operator=(copy);
}
return *this;
}
//------------------------------------------------------------------------------
// ~SpiceKernelWriter()
//------------------------------------------------------------------------------
/**
* This method deletes "this" SpiceKernelWriter instance.
* (destructor)
*
*/
//------------------------------------------------------------------------------
SpiceKernelWriter::~SpiceKernelWriter()
{
}
|
/* -------------------------------------------------------------------
* @doc
* @notice Template file wizards/projects/qtquickapplication/main.cpp
*
* @copyright Arboreus (http://arboreus.systems)
* @author Alexandr Kirilov (http://alexandr.kirilov.me)
* @created 11/06/2021 at 19:45:31
* */// --------------------------------------------------------------
// System includes
#include <QGuiApplication>
#include <QQmlApplicationEngine>
// Application includes
// Constants
// Qt Quick Application
int main(int inCounter, char *inArguments[]) {
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
QGuiApplication oApplication(inCounter, inArguments);
QQmlApplicationEngine oEngine;
const QUrl oURL(QStringLiteral("qrc:/main.qml"));
QObject::connect(
&oEngine, &QQmlApplicationEngine::objectCreated,
&oApplication, [oURL](QObject *obj, const QUrl &objUrl) {
if (!obj && oURL == objUrl) {
QCoreApplication::exit(-1);
}
}, Qt::QueuedConnection
);
oEngine.load(oURL);
return oApplication.exec();
}
|
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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 "platformX86UNIX/platformGL.h"
#include "platformX86UNIX/platformX86UNIX.h"
#include "console/console.h"
#include <dlfcn.h>
#include <SDL/SDL.h>
// declare stub functions
#define GL_FUNCTION(fn_return, fn_name, fn_args, fn_value) fn_return stub_##fn_name fn_args{ fn_value }
#include "platform/GLCoreFunc.h"
#include "platform/GLExtFunc.h"
#undef GL_FUNCTION
// point gl function pointers at stub functions
#define GL_FUNCTION(fn_return,fn_name,fn_args, fn_value) fn_return (*fn_name)fn_args = stub_##fn_name;
#include "platform/GLCoreFunc.h"
#include "platform/GLExtFunc.h"
#undef GL_FUNCTION
static void* dlHandle = NULL;
//------------------------------------------------------------------
//bind functions for each function prototype
//------------------------------------------------------------------
//GL_EXT/ARB
enum {
ARB_multitexture = BIT(0),
ARB_texture_compression = BIT(1),
EXT_compiled_vertex_array = BIT(2),
EXT_fog_coord = BIT(3),
EXT_paletted_texture = BIT(4),
NV_vertex_array_range = BIT(5),
EXT_blend_color = BIT(6),
EXT_blend_minmax = BIT(7)
};
//WGL_ARB
enum {
WGL_ARB_extensions_string = BIT(0),
WGL_EXT_swap_control = BIT(1),
WGL_3DFX_gamma_control = BIT(2)
};
static bool isFnOk( const char *name)
{
bool ok = false;
// JMQ: these are specific to torque's d3d->gl wrapper. They are not used under linux.
if (dStrcmp(name, "glAvailableVertexBufferEXT")==0)
ok = true;
else if (dStrcmp(name, "glAllocateVertexBufferEXT")==0)
ok = true;
else if (dStrcmp(name, "glLockVertexBufferEXT")==0)
ok = true;
else if (dStrcmp(name, "glUnlockVertexBufferEXT")==0)
ok = true;
else if (dStrcmp(name, "glSetVertexBufferEXT")==0)
ok = true;
else if (dStrcmp(name, "glOffsetVertexBufferEXT")==0)
ok = true;
else if (dStrcmp(name, "glFillVertexBufferEXT")==0)
ok = true;
else if (dStrcmp(name, "glFreeVertexBufferEXT")==0)
ok = true;
return ok;
}
//------------------------------------------------------------------
//bind functions for each function prototype
//------------------------------------------------------------------
static bool bindGLFunction( void *&fnAddress, const char *name )
{
void* addr = (void*)SDL_GL_GetProcAddress(name);
bool ok = (bool)addr;
if( !ok )
{
if (!isFnOk(name))
Con::errorf(ConsoleLogEntry::General, " Missing OpenGL function '%s'", name);
else
ok = true;
}
else
fnAddress = addr;
return ok;
}
static bool bindEXTFunction( void *&fnAddress, const char *name )
{
void* addr = (void*)SDL_GL_GetProcAddress(name);
if( !addr )
Con::errorf(ConsoleLogEntry::General, " Missing OpenGL extension '%s'", name);
else
fnAddress = addr;
return (addr != NULL);
}
//------------------------------------------------------------------
//binds for each function group
//------------------------------------------------------------------
static bool bindGLFunctions()
{
bool result = true;
#define GL_FUNCTION(fn_return, fn_name, fn_args, fn_value) \
result &= bindGLFunction( *(void**)&fn_name, #fn_name);
#include "platform/GLCoreFunc.h"
#undef GL_FUNCTION
return result;
}
static bool bindEXTFunctions(U32 extMask)
{
bool result = true;
#define GL_GROUP_BEGIN( flag ) \
if( extMask & flag ) {
#define GL_GROUP_END() }
#define GL_FUNCTION(fn_return, fn_name, fn_args, fn_value) \
result &= bindEXTFunction( *(void**)&fn_name, #fn_name);
#include "platform/GLExtFunc.h"
#undef GL_FUNCTION
#undef GL_GROUP_BEGIN
#undef GL_GROUP_END
return result;
}
static void unbindGLFunctions()
{
// point gl function pointers at stub functions
#define GL_FUNCTION(fn_return, fn_name, fn_args, fn_value) fn_name = stub_##fn_name;
#include "platform/GLCoreFunc.h"
#include "platform/GLExtFunc.h"
#undef GL_FUNCTION
}
namespace GLLoader
{
bool OpenGLInit()
{
return OpenGLDLLInit();
}
void OpenGLShutdown()
{
OpenGLDLLShutdown();
}
bool OpenGLDLLInit()
{
OpenGLDLLShutdown();
// load libGL.so
if (SDL_GL_LoadLibrary("libGL.so") == -1 &&
SDL_GL_LoadLibrary("libGL.so.1") == -1)
{
Con::errorf("Error loading GL library: %s", SDL_GetError());
return false;
}
// bind functions
if (!bindGLFunctions())
{
Con::errorf("Error binding GL functions");
OpenGLDLLShutdown();
return false;
}
return true;
}
void OpenGLDLLShutdown()
{
// there is no way to tell SDL to unload the library
if (dlHandle != NULL)
{
dlclose(dlHandle);
dlHandle = NULL;
}
unbindGLFunctions();
}
}
GLState gGLState;
bool gOpenGLDisablePT = false;
bool gOpenGLDisableCVA = false;
bool gOpenGLDisableTEC = false;
bool gOpenGLDisableARBMT = false;
bool gOpenGLDisableFC = false;
bool gOpenGLDisableTCompress = false;
bool gOpenGLNoEnvColor = false;
float gOpenGLGammaCorrection = 0.5;
bool gOpenGLNoDrawArraysAlpha = false;
// JMQTODO: really need a platform-shared version of this nastiness
bool GL_EXT_Init( )
{
// Load extensions...
//
const char* pExtString = reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS));
gGLState.primMode = 0;
U32 extBitMask = 0;
// GL_EXT_paletted_texture
if (pExtString && dStrstr(pExtString, (const char*)"GL_EXT_paletted_texture") != NULL)
{
extBitMask |= EXT_paletted_texture;
gGLState.suppPalettedTexture = true;
}
else
gGLState.suppPalettedTexture = false;
// EXT_compiled_vertex_array
if (pExtString && dStrstr(pExtString, (const char*)"GL_EXT_compiled_vertex_array") != NULL)
{
extBitMask |= EXT_compiled_vertex_array;
gGLState.suppLockedArrays = true;
}
else
{
gGLState.suppLockedArrays = false;
}
// ARB_multitexture
if (pExtString && dStrstr(pExtString, (const char*)"GL_ARB_multitexture") != NULL)
{
extBitMask |= ARB_multitexture;
gGLState.suppARBMultitexture = true;
} else {
gGLState.suppARBMultitexture = false;
}
// EXT_blend_color
if(pExtString && dStrstr(pExtString, (const char*)"GL_EXT_blend_color") != NULL)
{
extBitMask |= EXT_blend_color;
gGLState.suppEXTblendcolor = true;
} else {
gGLState.suppEXTblendcolor = false;
}
// EXT_blend_minmax
if(pExtString && dStrstr(pExtString, (const char*)"GL_EXT_blend_minmax") != NULL)
{
extBitMask |= EXT_blend_color;
gGLState.suppEXTblendminmax = true;
} else {
gGLState.suppEXTblendminmax = false;
}
// EXT_fog_coord
if (pExtString && dStrstr(pExtString, (const char*)"GL_EXT_fog_coord") != NULL)
{
extBitMask |= EXT_fog_coord;
gGLState.suppFogCoord = true;
} else {
gGLState.suppFogCoord = false;
}
// EXT_texture_compression_s3tc
if (pExtString && dStrstr(pExtString, (const char*)"GL_EXT_texture_compression_s3tc") != NULL)
gGLState.suppS3TC = true;
else
gGLState.suppS3TC = false;
// ARB_texture_compression
if (pExtString && dStrstr(pExtString, (const char*)"GL_ARB_texture_compression") != NULL)
{
extBitMask |= ARB_texture_compression;
gGLState.suppTextureCompression = true;
} else {
gGLState.suppTextureCompression = false;
}
// NV_vertex_array_range (not on *nix)
gGLState.suppVertexArrayRange = false;
// 3DFX_texture_compression_FXT1
if (pExtString && dStrstr(pExtString, (const char*)"3DFX_texture_compression_FXT1") != NULL)
gGLState.suppFXT1 = true;
else
gGLState.suppFXT1 = false;
if (!bindEXTFunctions(extBitMask))
Con::warnf("You are missing some OpenGL Extensions. You may experience rendering problems.");
// Binary states, i.e., no supporting functions
// EXT_packed_pixels
// EXT_texture_env_combine
//
// dhc note: a number of these can have multiple matching 'versions', private, ext, and arb.
gGLState.suppPackedPixels = pExtString? (dStrstr(pExtString, (const char*)"GL_EXT_packed_pixels") != NULL) : false;
gGLState.suppTextureEnvCombine = pExtString? (dStrstr(pExtString, (const char*)"GL_EXT_texture_env_combine") != NULL) : false;
gGLState.suppEdgeClamp = pExtString? (dStrstr(pExtString, (const char*)"GL_EXT_texture_edge_clamp") != NULL) : false;
gGLState.suppEdgeClamp |= pExtString? (dStrstr(pExtString, (const char*)"GL_SGIS_texture_edge_clamp") != NULL) : false;
gGLState.suppTexEnvAdd = pExtString? (dStrstr(pExtString, (const char*)"GL_ARB_texture_env_add") != NULL) : false;
gGLState.suppTexEnvAdd |= pExtString? (dStrstr(pExtString, (const char*)"GL_EXT_texture_env_add") != NULL) : false;
// Anisotropic filtering
gGLState.suppTexAnisotropic = pExtString? (dStrstr(pExtString, (const char*)"GL_EXT_texture_filter_anisotropic") != NULL) : false;
if (gGLState.suppTexAnisotropic)
glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &gGLState.maxAnisotropy);
if (gGLState.suppARBMultitexture)
glGetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, &gGLState.maxTextureUnits);
else
gGLState.maxTextureUnits = 1;
// JMQ: vsync/swap interval skipped
gGLState.suppSwapInterval = false;
Con::printf("OpenGL Init: Enabled Extensions");
if (gGLState.suppARBMultitexture) Con::printf(" ARB_multitexture (Max Texture Units: %d)", gGLState.maxTextureUnits);
if (gGLState.suppEXTblendcolor) Con::printf(" EXT_blend_color");
if (gGLState.suppEXTblendminmax) Con::printf(" EXT_blend_minmax");
if (gGLState.suppPalettedTexture) Con::printf(" EXT_paletted_texture");
if (gGLState.suppLockedArrays) Con::printf(" EXT_compiled_vertex_array");
if (gGLState.suppVertexArrayRange) Con::printf(" NV_vertex_array_range");
if (gGLState.suppTextureEnvCombine) Con::printf(" EXT_texture_env_combine");
if (gGLState.suppPackedPixels) Con::printf(" EXT_packed_pixels");
if (gGLState.suppFogCoord) Con::printf(" EXT_fog_coord");
if (gGLState.suppTextureCompression) Con::printf(" ARB_texture_compression");
if (gGLState.suppS3TC) Con::printf(" EXT_texture_compression_s3tc");
if (gGLState.suppFXT1) Con::printf(" 3DFX_texture_compression_FXT1");
if (gGLState.suppTexEnvAdd) Con::printf(" (ARB|EXT)_texture_env_add");
if (gGLState.suppTexAnisotropic) Con::printf(" EXT_texture_filter_anisotropic (Max anisotropy: %f)", gGLState.maxAnisotropy);
if (gGLState.suppSwapInterval) Con::printf(" WGL_EXT_swap_control");
Con::warnf("OpenGL Init: Disabled Extensions");
if (!gGLState.suppARBMultitexture) Con::warnf(" ARB_multitexture");
if (!gGLState.suppEXTblendcolor) Con::warnf(" EXT_blend_color");
if (!gGLState.suppEXTblendminmax) Con::warnf(" EXT_blend_minmax");
if (!gGLState.suppPalettedTexture) Con::warnf(" EXT_paletted_texture");
if (!gGLState.suppLockedArrays) Con::warnf(" EXT_compiled_vertex_array");
if (!gGLState.suppVertexArrayRange) Con::warnf(" NV_vertex_array_range");
if (!gGLState.suppTextureEnvCombine) Con::warnf(" EXT_texture_env_combine");
if (!gGLState.suppPackedPixels) Con::warnf(" EXT_packed_pixels");
if (!gGLState.suppFogCoord) Con::warnf(" EXT_fog_coord");
if (!gGLState.suppTextureCompression) Con::warnf(" ARB_texture_compression");
if (!gGLState.suppS3TC) Con::warnf(" EXT_texture_compression_s3tc");
if (!gGLState.suppFXT1) Con::warnf(" 3DFX_texture_compression_FXT1");
if (!gGLState.suppTexEnvAdd) Con::warnf(" (ARB|EXT)_texture_env_add");
if (!gGLState.suppTexAnisotropic) Con::warnf(" EXT_texture_filter_anisotropic");
if (!gGLState.suppSwapInterval) Con::warnf(" WGL_EXT_swap_control");
Con::printf(" ");
// Set some console variables:
Con::setBoolVariable( "$FogCoordSupported", gGLState.suppFogCoord );
Con::setBoolVariable( "$TextureCompressionSupported", gGLState.suppTextureCompression );
Con::setBoolVariable( "$AnisotropySupported", gGLState.suppTexAnisotropic );
Con::setBoolVariable( "$PalettedTextureSupported", gGLState.suppPalettedTexture );
Con::setBoolVariable( "$SwapIntervalSupported", gGLState.suppSwapInterval );
if (!gGLState.suppPalettedTexture && Con::getBoolVariable("$pref::OpenGL::forcePalettedTexture",false))
{
Con::setBoolVariable("$pref::OpenGL::forcePalettedTexture", false);
Con::setBoolVariable("$pref::OpenGL::force16BitTexture", true);
}
return true;
}
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/history/history_service_factory.h"
#include "base/prefs/pref_service.h"
#include "chrome/browser/bookmarks/bookmark_model_factory.h"
#include "chrome/browser/history/chrome_history_client.h"
#include "chrome/browser/history/chrome_history_client_factory.h"
#include "chrome/browser/history/history_service.h"
#include "chrome/browser/profiles/incognito_helpers.h"
#include "chrome/common/pref_names.h"
#include "components/bookmarks/browser/bookmark_model.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
// static
HistoryService* HistoryServiceFactory::GetForProfile(
Profile* profile, Profile::ServiceAccessType sat) {
// If saving history is disabled, only allow explicit access.
if (profile->GetPrefs()->GetBoolean(prefs::kSavingBrowserHistoryDisabled) &&
sat != Profile::EXPLICIT_ACCESS)
return NULL;
return static_cast<HistoryService*>(
GetInstance()->GetServiceForBrowserContext(profile, true));
}
// static
HistoryService*
HistoryServiceFactory::GetForProfileIfExists(
Profile* profile, Profile::ServiceAccessType sat) {
// If saving history is disabled, only allow explicit access.
if (profile->GetPrefs()->GetBoolean(prefs::kSavingBrowserHistoryDisabled) &&
sat != Profile::EXPLICIT_ACCESS)
return NULL;
return static_cast<HistoryService*>(
GetInstance()->GetServiceForBrowserContext(profile, false));
}
// static
HistoryService*
HistoryServiceFactory::GetForProfileWithoutCreating(Profile* profile) {
return static_cast<HistoryService*>(
GetInstance()->GetServiceForBrowserContext(profile, false));
}
// static
HistoryServiceFactory* HistoryServiceFactory::GetInstance() {
return Singleton<HistoryServiceFactory>::get();
}
// static
void HistoryServiceFactory::ShutdownForProfile(Profile* profile) {
HistoryServiceFactory* factory = GetInstance();
factory->BrowserContextDestroyed(profile);
}
HistoryServiceFactory::HistoryServiceFactory()
: BrowserContextKeyedServiceFactory(
"HistoryService", BrowserContextDependencyManager::GetInstance()) {
DependsOn(ChromeHistoryClientFactory::GetInstance());
}
HistoryServiceFactory::~HistoryServiceFactory() {
}
KeyedService* HistoryServiceFactory::BuildServiceInstanceFor(
content::BrowserContext* context) const {
Profile* profile = static_cast<Profile*>(context);
scoped_ptr<HistoryService> history_service(new HistoryService(
ChromeHistoryClientFactory::GetForProfile(profile), profile));
if (!history_service->Init(profile->GetPath()))
return NULL;
return history_service.release();
}
content::BrowserContext* HistoryServiceFactory::GetBrowserContextToUse(
content::BrowserContext* context) const {
return chrome::GetBrowserContextRedirectedInIncognito(context);
}
bool HistoryServiceFactory::ServiceIsNULLWhileTesting() const {
return true;
}
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Helveticum Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "miner.h"
#include "amount.h"
#include "chain.h"
#include "chainparams.h"
#include "coins.h"
#include "consensus/consensus.h"
#include "consensus/tx_verify.h"
#include "consensus/merkle.h"
#include "consensus/validation.h"
#include "hash.h"
#include "validation.h"
#include "net.h"
#include "policy/feerate.h"
#include "policy/policy.h"
#include "pow.h"
#include "primitives/transaction.h"
#include "script/standard.h"
#include "timedata.h"
#include "txmempool.h"
#include "util.h"
#include "utilmoneystr.h"
#include "validationinterface.h"
#include <algorithm>
#include <queue>
#include <utility>
//////////////////////////////////////////////////////////////////////////////
//
// HelveticumMiner
//
//
// Unconfirmed transactions in the memory pool often depend on other
// transactions in the memory pool. When we select transactions from the
// pool, we select by highest fee rate of a transaction combined with all
// its ancestors.
uint64_t nLastBlockTx = 0;
uint64_t nLastBlockSize = 0;
uint64_t nLastBlockWeight = 0;
int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
{
int64_t nOldTime = pblock->nTime;
int64_t nNewTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
if (nOldTime < nNewTime)
pblock->nTime = nNewTime;
// Updating time can change work required on testnet:
if (consensusParams.fPowAllowMinDifficultyBlocks)
pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);
return nNewTime - nOldTime;
}
BlockAssembler::Options::Options() {
blockMinFeeRate = CFeeRate(DEFAULT_BLOCK_MIN_TX_FEE);
nBlockMaxWeight = DEFAULT_BLOCK_MAX_WEIGHT;
nBlockMaxSize = DEFAULT_BLOCK_MAX_SIZE;
}
BlockAssembler::BlockAssembler(const CChainParams& params, const Options& options) : chainparams(params)
{
blockMinFeeRate = options.blockMinFeeRate;
// Limit weight to between 4K and MAX_BLOCK_WEIGHT-4K for sanity:
nBlockMaxWeight = std::max<size_t>(4000, std::min<size_t>(MAX_BLOCK_WEIGHT - 4000, options.nBlockMaxWeight));
// Limit size to between 1K and MAX_BLOCK_SERIALIZED_SIZE-1K for sanity:
nBlockMaxSize = std::max<size_t>(1000, std::min<size_t>(MAX_BLOCK_SERIALIZED_SIZE - 1000, options.nBlockMaxSize));
// Whether we need to account for byte usage (in addition to weight usage)
fNeedSizeAccounting = (nBlockMaxSize < MAX_BLOCK_SERIALIZED_SIZE - 1000);
}
static BlockAssembler::Options DefaultOptions(const CChainParams& params)
{
// Block resource limits
// If neither -blockmaxsize or -blockmaxweight is given, limit to DEFAULT_BLOCK_MAX_*
// If only one is given, only restrict the specified resource.
// If both are given, restrict both.
BlockAssembler::Options options;
options.nBlockMaxWeight = DEFAULT_BLOCK_MAX_WEIGHT;
options.nBlockMaxSize = DEFAULT_BLOCK_MAX_SIZE;
bool fWeightSet = false;
if (IsArgSet("-blockmaxweight")) {
options.nBlockMaxWeight = GetArg("-blockmaxweight", DEFAULT_BLOCK_MAX_WEIGHT);
options.nBlockMaxSize = MAX_BLOCK_SERIALIZED_SIZE;
fWeightSet = true;
}
if (IsArgSet("-blockmaxsize")) {
options.nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
if (!fWeightSet) {
options.nBlockMaxWeight = options.nBlockMaxSize * WITNESS_SCALE_FACTOR;
}
}
if (IsArgSet("-blockmintxfee")) {
CAmount n = 0;
ParseMoney(GetArg("-blockmintxfee", ""), n);
options.blockMinFeeRate = CFeeRate(n);
} else {
options.blockMinFeeRate = CFeeRate(DEFAULT_BLOCK_MIN_TX_FEE);
}
return options;
}
BlockAssembler::BlockAssembler(const CChainParams& params) : BlockAssembler(params, DefaultOptions(params)) {}
void BlockAssembler::resetBlock()
{
inBlock.clear();
// Reserve space for coinbase tx
nBlockSize = 1000;
nBlockWeight = 4000;
nBlockSigOpsCost = 400;
fIncludeWitness = false;
// These counters do not include coinbase tx
nBlockTx = 0;
nFees = 0;
}
std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock(const CScript& scriptPubKeyIn, bool fMineWitnessTx)
{
int64_t nTimeStart = GetTimeMicros();
resetBlock();
pblocktemplate.reset(new CBlockTemplate());
if(!pblocktemplate.get())
return nullptr;
pblock = &pblocktemplate->block; // pointer for convenience
// Add dummy coinbase tx as first transaction
pblock->vtx.emplace_back();
pblocktemplate->vTxFees.push_back(-1); // updated at end
pblocktemplate->vTxSigOpsCost.push_back(-1); // updated at end
LOCK2(cs_main, mempool.cs);
CBlockIndex* pindexPrev = chainActive.Tip();
nHeight = pindexPrev->nHeight + 1;
pblock->nVersion = ComputeBlockVersion(pindexPrev, chainparams.GetConsensus());
// -regtest only: allow overriding block.nVersion with
// -blockversion=N to test forking scenarios
if (chainparams.MineBlocksOnDemand())
pblock->nVersion = GetArg("-blockversion", pblock->nVersion);
pblock->nTime = GetAdjustedTime();
const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
? nMedianTimePast
: pblock->GetBlockTime();
// Decide whether to include witness transactions
// This is only needed in case the witness softfork activation is reverted
// (which would require a very deep reorganization) or when
// -promiscuousmempoolflags is used.
// TODO: replace this with a call to main to assess validity of a mempool
// transaction (which in most cases can be a no-op).
fIncludeWitness = IsWitnessEnabled(pindexPrev, chainparams.GetConsensus()) && fMineWitnessTx;
int nPackagesSelected = 0;
int nDescendantsUpdated = 0;
addPackageTxs(nPackagesSelected, nDescendantsUpdated);
int64_t nTime1 = GetTimeMicros();
nLastBlockTx = nBlockTx;
nLastBlockSize = nBlockSize;
nLastBlockWeight = nBlockWeight;
// Create coinbase transaction.
CMutableTransaction coinbaseTx;
coinbaseTx.vin.resize(1);
coinbaseTx.vin[0].prevout.SetNull();
coinbaseTx.vout.resize(1);
coinbaseTx.vout[0].scriptPubKey = scriptPubKeyIn;
coinbaseTx.vout[0].nValue = nFees + GetBlockSubsidy(nHeight, chainparams.GetConsensus());
coinbaseTx.vin[0].scriptSig = CScript() << nHeight << OP_0;
pblock->vtx[0] = MakeTransactionRef(std::move(coinbaseTx));
pblocktemplate->vchCoinbaseCommitment = GenerateCoinbaseCommitment(*pblock, pindexPrev, chainparams.GetConsensus());
pblocktemplate->vTxFees[0] = -nFees;
uint64_t nSerializeSize = GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION);
LogPrintf("CreateNewBlock(): total size: %u block weight: %u txs: %u fees: %ld sigops %d\n", nSerializeSize, GetBlockWeight(*pblock), nBlockTx, nFees, nBlockSigOpsCost);
// Fill in header
pblock->hashPrevBlock = pindexPrev->GetBlockHash();
UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, chainparams.GetConsensus());
pblock->nNonce = 0;
pblocktemplate->vTxSigOpsCost[0] = WITNESS_SCALE_FACTOR * GetLegacySigOpCount(*pblock->vtx[0]);
CValidationState state;
if (!TestBlockValidity(state, chainparams, *pblock, pindexPrev, false, false)) {
throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s", __func__, FormatStateMessage(state)));
}
int64_t nTime2 = GetTimeMicros();
LogPrint(BCLog::BENCH, "CreateNewBlock() packages: %.2fms (%d packages, %d updated descendants), validity: %.2fms (total %.2fms)\n", 0.001 * (nTime1 - nTimeStart), nPackagesSelected, nDescendantsUpdated, 0.001 * (nTime2 - nTime1), 0.001 * (nTime2 - nTimeStart));
return std::move(pblocktemplate);
}
void BlockAssembler::onlyUnconfirmed(CTxMemPool::setEntries& testSet)
{
for (CTxMemPool::setEntries::iterator iit = testSet.begin(); iit != testSet.end(); ) {
// Only test txs not already in the block
if (inBlock.count(*iit)) {
testSet.erase(iit++);
}
else {
iit++;
}
}
}
bool BlockAssembler::TestPackage(uint64_t packageSize, int64_t packageSigOpsCost)
{
// TODO: switch to weight-based accounting for packages instead of vsize-based accounting.
if (nBlockWeight + WITNESS_SCALE_FACTOR * packageSize >= nBlockMaxWeight)
return false;
if (nBlockSigOpsCost + packageSigOpsCost >= MAX_BLOCK_SIGOPS_COST)
return false;
return true;
}
// Perform transaction-level checks before adding to block:
// - transaction finality (locktime)
// - premature witness (in case segwit transactions are added to mempool before
// segwit activation)
// - serialized size (in case -blockmaxsize is in use)
bool BlockAssembler::TestPackageTransactions(const CTxMemPool::setEntries& package)
{
uint64_t nPotentialBlockSize = nBlockSize; // only used with fNeedSizeAccounting
for (const CTxMemPool::txiter it : package) {
if (!IsFinalTx(it->GetTx(), nHeight, nLockTimeCutoff))
return false;
if (!fIncludeWitness && it->GetTx().HasWitness())
return false;
if (fNeedSizeAccounting) {
uint64_t nTxSize = ::GetSerializeSize(it->GetTx(), SER_NETWORK, PROTOCOL_VERSION);
if (nPotentialBlockSize + nTxSize >= nBlockMaxSize) {
return false;
}
nPotentialBlockSize += nTxSize;
}
}
return true;
}
void BlockAssembler::AddToBlock(CTxMemPool::txiter iter)
{
pblock->vtx.emplace_back(iter->GetSharedTx());
pblocktemplate->vTxFees.push_back(iter->GetFee());
pblocktemplate->vTxSigOpsCost.push_back(iter->GetSigOpCost());
if (fNeedSizeAccounting) {
nBlockSize += ::GetSerializeSize(iter->GetTx(), SER_NETWORK, PROTOCOL_VERSION);
}
nBlockWeight += iter->GetTxWeight();
++nBlockTx;
nBlockSigOpsCost += iter->GetSigOpCost();
nFees += iter->GetFee();
inBlock.insert(iter);
bool fPrintPriority = GetBoolArg("-printpriority", DEFAULT_PRINTPRIORITY);
if (fPrintPriority) {
LogPrintf("fee %s txid %s\n",
CFeeRate(iter->GetModifiedFee(), iter->GetTxSize()).ToString(),
iter->GetTx().GetHash().ToString());
}
}
int BlockAssembler::UpdatePackagesForAdded(const CTxMemPool::setEntries& alreadyAdded,
indexed_modified_transaction_set &mapModifiedTx)
{
int nDescendantsUpdated = 0;
for (const CTxMemPool::txiter it : alreadyAdded) {
CTxMemPool::setEntries descendants;
mempool.CalculateDescendants(it, descendants);
// Insert all descendants (not yet in block) into the modified set
for (CTxMemPool::txiter desc : descendants) {
if (alreadyAdded.count(desc))
continue;
++nDescendantsUpdated;
modtxiter mit = mapModifiedTx.find(desc);
if (mit == mapModifiedTx.end()) {
CTxMemPoolModifiedEntry modEntry(desc);
modEntry.nSizeWithAncestors -= it->GetTxSize();
modEntry.nModFeesWithAncestors -= it->GetModifiedFee();
modEntry.nSigOpCostWithAncestors -= it->GetSigOpCost();
mapModifiedTx.insert(modEntry);
} else {
mapModifiedTx.modify(mit, update_for_parent_inclusion(it));
}
}
}
return nDescendantsUpdated;
}
// Skip entries in mapTx that are already in a block or are present
// in mapModifiedTx (which implies that the mapTx ancestor state is
// stale due to ancestor inclusion in the block)
// Also skip transactions that we've already failed to add. This can happen if
// we consider a transaction in mapModifiedTx and it fails: we can then
// potentially consider it again while walking mapTx. It's currently
// guaranteed to fail again, but as a belt-and-suspenders check we put it in
// failedTx and avoid re-evaluation, since the re-evaluation would be using
// cached size/sigops/fee values that are not actually correct.
bool BlockAssembler::SkipMapTxEntry(CTxMemPool::txiter it, indexed_modified_transaction_set &mapModifiedTx, CTxMemPool::setEntries &failedTx)
{
assert (it != mempool.mapTx.end());
return mapModifiedTx.count(it) || inBlock.count(it) || failedTx.count(it);
}
void BlockAssembler::SortForBlock(const CTxMemPool::setEntries& package, CTxMemPool::txiter entry, std::vector<CTxMemPool::txiter>& sortedEntries)
{
// Sort package by ancestor count
// If a transaction A depends on transaction B, then A's ancestor count
// must be greater than B's. So this is sufficient to validly order the
// transactions for block inclusion.
sortedEntries.clear();
sortedEntries.insert(sortedEntries.begin(), package.begin(), package.end());
std::sort(sortedEntries.begin(), sortedEntries.end(), CompareTxIterByAncestorCount());
}
// This transaction selection algorithm orders the mempool based
// on feerate of a transaction including all unconfirmed ancestors.
// Since we don't remove transactions from the mempool as we select them
// for block inclusion, we need an alternate method of updating the feerate
// of a transaction with its not-yet-selected ancestors as we go.
// This is accomplished by walking the in-mempool descendants of selected
// transactions and storing a temporary modified state in mapModifiedTxs.
// Each time through the loop, we compare the best transaction in
// mapModifiedTxs with the next transaction in the mempool to decide what
// transaction package to work on next.
void BlockAssembler::addPackageTxs(int &nPackagesSelected, int &nDescendantsUpdated)
{
// mapModifiedTx will store sorted packages after they are modified
// because some of their txs are already in the block
indexed_modified_transaction_set mapModifiedTx;
// Keep track of entries that failed inclusion, to avoid duplicate work
CTxMemPool::setEntries failedTx;
// Start by adding all descendants of previously added txs to mapModifiedTx
// and modifying them for their already included ancestors
UpdatePackagesForAdded(inBlock, mapModifiedTx);
CTxMemPool::indexed_transaction_set::index<ancestor_score>::type::iterator mi = mempool.mapTx.get<ancestor_score>().begin();
CTxMemPool::txiter iter;
// Limit the number of attempts to add transactions to the block when it is
// close to full; this is just a simple heuristic to finish quickly if the
// mempool has a lot of entries.
const int64_t MAX_CONSECUTIVE_FAILURES = 1000;
int64_t nConsecutiveFailed = 0;
while (mi != mempool.mapTx.get<ancestor_score>().end() || !mapModifiedTx.empty())
{
// First try to find a new transaction in mapTx to evaluate.
if (mi != mempool.mapTx.get<ancestor_score>().end() &&
SkipMapTxEntry(mempool.mapTx.project<0>(mi), mapModifiedTx, failedTx)) {
++mi;
continue;
}
// Now that mi is not stale, determine which transaction to evaluate:
// the next entry from mapTx, or the best from mapModifiedTx?
bool fUsingModified = false;
modtxscoreiter modit = mapModifiedTx.get<ancestor_score>().begin();
if (mi == mempool.mapTx.get<ancestor_score>().end()) {
// We're out of entries in mapTx; use the entry from mapModifiedTx
iter = modit->iter;
fUsingModified = true;
} else {
// Try to compare the mapTx entry to the mapModifiedTx entry
iter = mempool.mapTx.project<0>(mi);
if (modit != mapModifiedTx.get<ancestor_score>().end() &&
CompareModifiedEntry()(*modit, CTxMemPoolModifiedEntry(iter))) {
// The best entry in mapModifiedTx has higher score
// than the one from mapTx.
// Switch which transaction (package) to consider
iter = modit->iter;
fUsingModified = true;
} else {
// Either no entry in mapModifiedTx, or it's worse than mapTx.
// Increment mi for the next loop iteration.
++mi;
}
}
// We skip mapTx entries that are inBlock, and mapModifiedTx shouldn't
// contain anything that is inBlock.
assert(!inBlock.count(iter));
uint64_t packageSize = iter->GetSizeWithAncestors();
CAmount packageFees = iter->GetModFeesWithAncestors();
int64_t packageSigOpsCost = iter->GetSigOpCostWithAncestors();
if (fUsingModified) {
packageSize = modit->nSizeWithAncestors;
packageFees = modit->nModFeesWithAncestors;
packageSigOpsCost = modit->nSigOpCostWithAncestors;
}
if (packageFees < blockMinFeeRate.GetFee(packageSize)) {
// Everything else we might consider has a lower fee rate
return;
}
if (!TestPackage(packageSize, packageSigOpsCost)) {
if (fUsingModified) {
// Since we always look at the best entry in mapModifiedTx,
// we must erase failed entries so that we can consider the
// next best entry on the next loop iteration
mapModifiedTx.get<ancestor_score>().erase(modit);
failedTx.insert(iter);
}
++nConsecutiveFailed;
if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES && nBlockWeight >
nBlockMaxWeight - 4000) {
// Give up if we're close to full and haven't succeeded in a while
break;
}
continue;
}
CTxMemPool::setEntries ancestors;
uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
std::string dummy;
mempool.CalculateMemPoolAncestors(*iter, ancestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy, false);
onlyUnconfirmed(ancestors);
ancestors.insert(iter);
// Test if all tx's are Final
if (!TestPackageTransactions(ancestors)) {
if (fUsingModified) {
mapModifiedTx.get<ancestor_score>().erase(modit);
failedTx.insert(iter);
}
continue;
}
// This transaction will make it in; reset the failed counter.
nConsecutiveFailed = 0;
// Package can be added. Sort the entries in a valid order.
std::vector<CTxMemPool::txiter> sortedEntries;
SortForBlock(ancestors, iter, sortedEntries);
for (size_t i=0; i<sortedEntries.size(); ++i) {
AddToBlock(sortedEntries[i]);
// Erase from the modified set, if present
mapModifiedTx.erase(sortedEntries[i]);
}
++nPackagesSelected;
// Update transactions that depend on each of these
nDescendantsUpdated += UpdatePackagesForAdded(ancestors, mapModifiedTx);
}
}
void IncrementExtraNonce(CBlock* pblock, const CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
{
// Update nExtraNonce
static uint256 hashPrevBlock;
if (hashPrevBlock != pblock->hashPrevBlock)
{
nExtraNonce = 0;
hashPrevBlock = pblock->hashPrevBlock;
}
++nExtraNonce;
unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
CMutableTransaction txCoinbase(*pblock->vtx[0]);
txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
assert(txCoinbase.vin[0].scriptSig.size() <= 100);
pblock->vtx[0] = MakeTransactionRef(std::move(txCoinbase));
pblock->hashMerkleRoot = BlockMerkleRoot(*pblock);
}
|
// Copyright (c) 2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <test/util.h>
#include <chainparams.h>
#include <consensus/merkle.h>
#include <miner.h>
#include <outputtype.h>
#include <pos.h>
#include <script/standard.h>
#include <validation.h>
#include <validationinterface.h>
#ifdef ENABLE_WALLET
#include <wallet/wallet.h>
#endif
const std::string ADDRESS_BCRT1_UNSPENDABLE = "bcrt1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq3xueyj";
#ifdef ENABLE_WALLET
std::string getnewaddress(CWallet& w)
{
constexpr auto output_type = OutputType::BECH32;
CTxDestination dest;
std::string error;
if (!w.GetNewDestination(output_type, "", dest, error)) assert(false);
return EncodeDestination(dest);
}
void importaddress(CWallet& wallet, const std::string& address)
{
LOCK(wallet.cs_wallet);
const auto dest = DecodeDestination(address);
assert(IsValidDestination(dest));
const auto script = GetScriptForDestination(dest);
wallet.MarkDirty();
assert(!wallet.HaveWatchOnly(script));
if (!wallet.AddWatchOnly(script, 0 /* nCreateTime */)) assert(false);
wallet.SetAddressBook(dest, /* label */ "", "receive");
}
#endif // ENABLE_WALLET
CTxIn generatetoaddress(const std::string& address)
{
const auto dest = DecodeDestination(address);
assert(IsValidDestination(dest));
const auto coinbase_script = GetScriptForDestination(dest);
return MineBlock(coinbase_script);
}
CTxIn MineBlock(const CScript& coinbase_scriptPubKey)
{
auto block = PrepareBlock(coinbase_scriptPubKey);
// while (!CheckProofOfWork(block->GetHash(), block->nBits, Params().GetConsensus())) { // TODO: SS I broke this
// ++block->nNonce;
// assert(block->nNonce);
// }
bool processed{ProcessNewBlock(Params(), block, true, nullptr)};
assert(processed);
return CTxIn{block->vtx[0]->GetHash(), 0};
}
std::shared_ptr<CBlock> PrepareBlock(const CScript& coinbase_scriptPubKey)
{
auto block = std::make_shared<CBlock>(
BlockAssembler{Params()}
.CreateNewBlock(coinbase_scriptPubKey)
->block);
LOCK(cs_main);
block->nTime = ::ChainActive().Tip()->GetMedianTimePast() + 1;
block->hashMerkleRoot = BlockMerkleRoot(*block);
return block;
}
|
// Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "transactionrecord.h"
#include "base58.h"
#include "obfuscation.h"
#include "swifttx.h"
#include "timedata.h"
#include "wallet.h"
#include <stdint.h>
/* Return positive answer if transaction should be shown in list.
*/
bool TransactionRecord::showTransaction(const CWalletTx& wtx)
{
if (wtx.IsCoinBase()) {
// Ensures we show generated coins / mined transactions at depth 1
if (!wtx.IsInMainChain()) {
return false;
}
}
return true;
}
/*
* Decompose CWallet transaction to model transaction records.
*/
QList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet* wallet, const CWalletTx& wtx)
{
QList<TransactionRecord> parts;
int64_t nTime = wtx.GetComputedTxTime();
CAmount nCredit = wtx.GetCredit(ISMINE_ALL);
CAmount nDebit = wtx.GetDebit(ISMINE_ALL);
CAmount nNet = nCredit - nDebit;
uint256 hash = wtx.GetHash();
std::map<std::string, std::string> mapValue = wtx.mapValue;
if (wtx.IsCoinStake()) {
TransactionRecord sub(hash, nTime);
CTxDestination address;
if (!ExtractDestination(wtx.vout[1].scriptPubKey, address))
return parts;
if (!IsMine(*wallet, address)) {
//if the address is not yours then it means you have a tx sent to you in someone elses coinstake tx
for (unsigned int i = 1; i < wtx.vout.size(); i++) {
CTxDestination outAddress;
if (ExtractDestination(wtx.vout[i].scriptPubKey, outAddress)) {
if (IsMine(*wallet, outAddress)) {
isminetype mine = wallet->IsMine(wtx.vout[i]);
sub.involvesWatchAddress = mine & ISMINE_WATCH_ONLY;
sub.type = TransactionRecord::MNReward;
sub.address = CBitcoinAddress(outAddress).ToString();
sub.credit = wtx.vout[i].nValue;
}
}
}
} else {
//stake reward
isminetype mine = wallet->IsMine(wtx.vout[1]);
sub.involvesWatchAddress = mine & ISMINE_WATCH_ONLY;
sub.type = TransactionRecord::StakeMint;
sub.address = CBitcoinAddress(address).ToString();
sub.credit = nNet;
}
parts.append(sub);
} else if (wtx.IsZerocoinSpend()) {
// a zerocoin spend that was created by this wallet
libzerocoin::CoinSpend zcspend = TxInToZerocoinSpend(wtx.vin[0]);
bool fSpendFromMe = wallet->IsMyZerocoinSpend(zcspend.getCoinSerialNumber());
//zerocoin spend outputs
bool fFeeAssigned = false;
for (const CTxOut txout : wtx.vout) {
// change that was reminted as zerocoins
if (txout.IsZerocoinMint()) {
// do not display record if this isn't from our wallet
if (!fSpendFromMe)
continue;
TransactionRecord sub(hash, nTime);
sub.type = TransactionRecord::ZerocoinSpend_Change_zVYI;
sub.address = mapValue["zerocoinmint"];
sub.debit = -txout.nValue;
if (!fFeeAssigned) {
sub.debit -= (wtx.GetZerocoinSpent() - wtx.GetValueOut());
fFeeAssigned = true;
}
sub.idx = parts.size();
parts.append(sub);
continue;
}
string strAddress = "";
CTxDestination address;
if (ExtractDestination(txout.scriptPubKey, address))
strAddress = CBitcoinAddress(address).ToString();
// a zerocoinspend that was sent to an address held by this wallet
isminetype mine = wallet->IsMine(txout);
if (mine) {
TransactionRecord sub(hash, nTime);
sub.type = (fSpendFromMe ? TransactionRecord::ZerocoinSpend_FromMe : TransactionRecord::RecvFromZerocoinSpend);
sub.debit = txout.nValue;
sub.address = mapValue["recvzerocoinspend"];
if (strAddress != "")
sub.address = strAddress;
sub.idx = parts.size();
parts.append(sub);
continue;
}
// spend is not from us, so do not display the spend side of the record
if (!fSpendFromMe)
continue;
// zerocoin spend that was sent to someone else
TransactionRecord sub(hash, nTime);
sub.debit = -txout.nValue;
sub.type = TransactionRecord::ZerocoinSpend;
sub.address = mapValue["zerocoinspend"];
if (strAddress != "")
sub.address = strAddress;
sub.idx = parts.size();
parts.append(sub);
}
} else if (nNet > 0 || wtx.IsCoinBase()) {
//
// Credit
//
BOOST_FOREACH (const CTxOut& txout, wtx.vout) {
isminetype mine = wallet->IsMine(txout);
if (mine) {
TransactionRecord sub(hash, nTime);
CTxDestination address;
sub.idx = parts.size(); // sequence number
sub.credit = txout.nValue;
sub.involvesWatchAddress = mine & ISMINE_WATCH_ONLY;
if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*wallet, address)) {
// Received by Vyigrat Address
sub.type = TransactionRecord::RecvWithAddress;
sub.address = CBitcoinAddress(address).ToString();
} else {
// Received by IP connection (deprecated features), or a multisignature or other non-simple transaction
sub.type = TransactionRecord::RecvFromOther;
sub.address = mapValue["from"];
}
if (wtx.IsCoinBase()) {
// Generated
sub.type = TransactionRecord::Generated;
}
parts.append(sub);
}
}
} else {
bool fAllFromMeDenom = true;
int nFromMe = 0;
bool involvesWatchAddress = false;
isminetype fAllFromMe = ISMINE_SPENDABLE;
BOOST_FOREACH (const CTxIn& txin, wtx.vin) {
if (wallet->IsMine(txin)) {
fAllFromMeDenom = fAllFromMeDenom && wallet->IsDenominated(txin);
nFromMe++;
}
isminetype mine = wallet->IsMine(txin);
if (mine & ISMINE_WATCH_ONLY) involvesWatchAddress = true;
if (fAllFromMe > mine) fAllFromMe = mine;
}
isminetype fAllToMe = ISMINE_SPENDABLE;
bool fAllToMeDenom = true;
int nToMe = 0;
BOOST_FOREACH (const CTxOut& txout, wtx.vout) {
if (wallet->IsMine(txout)) {
fAllToMeDenom = fAllToMeDenom && wallet->IsDenominatedAmount(txout.nValue);
nToMe++;
}
isminetype mine = wallet->IsMine(txout);
if (mine & ISMINE_WATCH_ONLY) involvesWatchAddress = true;
if (fAllToMe > mine) fAllToMe = mine;
}
if (fAllFromMeDenom && fAllToMeDenom && nFromMe * nToMe) {
parts.append(TransactionRecord(hash, nTime, TransactionRecord::ObfuscationDenominate, "", -nDebit, nCredit));
parts.last().involvesWatchAddress = false; // maybe pass to TransactionRecord as constructor argument
} else if (fAllFromMe && fAllToMe) {
// Payment to self
// TODO: this section still not accurate but covers most cases,
// might need some additional work however
TransactionRecord sub(hash, nTime);
// Payment to self by default
sub.type = TransactionRecord::SendToSelf;
sub.address = "";
if (mapValue["DS"] == "1") {
sub.type = TransactionRecord::Obfuscated;
CTxDestination address;
if (ExtractDestination(wtx.vout[0].scriptPubKey, address)) {
// Sent to Vyigrat Address
sub.address = CBitcoinAddress(address).ToString();
} else {
// Sent to IP, or other non-address transaction like OP_EVAL
sub.address = mapValue["to"];
}
} else {
for (unsigned int nOut = 0; nOut < wtx.vout.size(); nOut++) {
const CTxOut& txout = wtx.vout[nOut];
sub.idx = parts.size();
if (wallet->IsCollateralAmount(txout.nValue)) sub.type = TransactionRecord::ObfuscationMakeCollaterals;
if (wallet->IsDenominatedAmount(txout.nValue)) sub.type = TransactionRecord::ObfuscationCreateDenominations;
if (nDebit - wtx.GetValueOut() == OBFUSCATION_COLLATERAL) sub.type = TransactionRecord::ObfuscationCollateralPayment;
}
}
CAmount nChange = wtx.GetChange();
sub.debit = -(nDebit - nChange);
sub.credit = nCredit - nChange;
parts.append(sub);
parts.last().involvesWatchAddress = involvesWatchAddress; // maybe pass to TransactionRecord as constructor argument
} else if (fAllFromMe) {
//
// Debit
//
CAmount nTxFee = nDebit - wtx.GetValueOut();
for (unsigned int nOut = 0; nOut < wtx.vout.size(); nOut++) {
const CTxOut& txout = wtx.vout[nOut];
TransactionRecord sub(hash, nTime);
sub.idx = parts.size();
sub.involvesWatchAddress = involvesWatchAddress;
if (wallet->IsMine(txout)) {
// Ignore parts sent to self, as this is usually the change
// from a transaction sent back to our own address.
continue;
}
CTxDestination address;
if (ExtractDestination(txout.scriptPubKey, address)) {
// Sent to Vyigrat Address
sub.type = TransactionRecord::SendToAddress;
sub.address = CBitcoinAddress(address).ToString();
} else if (txout.IsZerocoinMint()){
sub.type = TransactionRecord::ZerocoinMint;
sub.address = mapValue["zerocoinmint"];
} else {
// Sent to IP, or other non-address transaction like OP_EVAL
sub.type = TransactionRecord::SendToOther;
sub.address = mapValue["to"];
}
if (mapValue["DS"] == "1") {
sub.type = TransactionRecord::Obfuscated;
}
CAmount nValue = txout.nValue;
/* Add fee to first output */
if (nTxFee > 0) {
nValue += nTxFee;
nTxFee = 0;
}
sub.debit = -nValue;
parts.append(sub);
}
} else {
//
// Mixed debit transaction, can't break down payees
//
parts.append(TransactionRecord(hash, nTime, TransactionRecord::Other, "", nNet, 0));
parts.last().involvesWatchAddress = involvesWatchAddress;
}
}
return parts;
}
void TransactionRecord::updateStatus(const CWalletTx& wtx)
{
AssertLockHeld(cs_main);
// Determine transaction status
// Find the block the tx is in
CBlockIndex* pindex = NULL;
BlockMap::iterator mi = mapBlockIndex.find(wtx.hashBlock);
if (mi != mapBlockIndex.end())
pindex = (*mi).second;
// Sort order, unrecorded transactions sort to the top
status.sortKey = strprintf("%010d-%01d-%010u-%03d",
(pindex ? pindex->nHeight : std::numeric_limits<int>::max()),
(wtx.IsCoinBase() ? 1 : 0),
wtx.nTimeReceived,
idx);
status.countsForBalance = wtx.IsTrusted() && !(wtx.GetBlocksToMaturity() > 0);
status.depth = wtx.GetDepthInMainChain();
status.cur_num_blocks = chainActive.Height();
status.cur_num_ix_locks = nCompleteTXLocks;
if (!IsFinalTx(wtx, chainActive.Height() + 1)) {
if (wtx.nLockTime < LOCKTIME_THRESHOLD) {
status.status = TransactionStatus::OpenUntilBlock;
status.open_for = wtx.nLockTime - chainActive.Height();
} else {
status.status = TransactionStatus::OpenUntilDate;
status.open_for = wtx.nLockTime;
}
}
// For generated transactions, determine maturity
else if (type == TransactionRecord::Generated || type == TransactionRecord::StakeMint || type == TransactionRecord::MNReward) {
if (wtx.GetBlocksToMaturity() > 0) {
status.status = TransactionStatus::Immature;
if (wtx.IsInMainChain()) {
status.matures_in = wtx.GetBlocksToMaturity();
// Check if the block was requested by anyone
if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)
status.status = TransactionStatus::MaturesWarning;
} else {
status.status = TransactionStatus::NotAccepted;
}
} else {
status.status = TransactionStatus::Confirmed;
}
} else {
if (status.depth < 0) {
status.status = TransactionStatus::Conflicted;
} else if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0) {
status.status = TransactionStatus::Offline;
} else if (status.depth == 0) {
status.status = TransactionStatus::Unconfirmed;
} else if (status.depth < RecommendedNumConfirmations) {
status.status = TransactionStatus::Confirming;
} else {
status.status = TransactionStatus::Confirmed;
}
}
}
bool TransactionRecord::statusUpdateNeeded()
{
AssertLockHeld(cs_main);
return status.cur_num_blocks != chainActive.Height() || status.cur_num_ix_locks != nCompleteTXLocks;
}
QString TransactionRecord::getTxID() const
{
return QString::fromStdString(hash.ToString());
}
int TransactionRecord::getOutputIndex() const
{
return idx;
}
|
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "BlastMeshEditorDialogs.h"
#include "BlastFractureSettings.h"
#include "BlastFracture.h"
#include "BlastMeshFactory.h"
#include "BlastMesh.h"
#include "Framework/MultiBox/MultiBoxBuilder.h"
//#include "Engine/StaticMesh.h"
//#include "Widgets/Input/SSlider.h"
#include "EditorReimportHandler.h"
#include "SUniformGridPanel.h"
#include "PropertyEditorModule.h"
#include "EditorStyleSet.h"
#include "Widgets/Images/SImage.h"
#include "WidgetLayoutLibrary.h"
#include <Developer/DesktopPlatform/Public/IDesktopPlatform.h>
#include <Developer/DesktopPlatform/Public/DesktopPlatformModule.h>
#include "BlastMeshExporter.h"
#include <NvBlastExtAuthoring.h>
#include <NvBlastExtSerialization.h>
#include <NvBlastExtLlSerialization.h>
#include <PlatformFilemanager.h>
//////////////////////////////////////////////////////////////////////////
// SSelectStaticMeshDialog
//////////////////////////////////////////////////////////////////////////
// Constructs this widget with InArgs
void SSelectStaticMeshDialog::Construct(const FArguments& InArgs)
{
FDetailsViewArgs Args;
Args.bLockable = false;
Args.bHideSelectionTip = true;
FPropertyEditorModule& PropertyModule = FModuleManager::LoadModuleChecked<FPropertyEditorModule>("PropertyEditor");
StaticMeshHolder = NewObject<UBlastStaticMeshHolder>();
StaticMeshHolder->OnStaticMeshSelected.BindSP(this, &SSelectStaticMeshDialog::MeshSelected);
MeshView = PropertyModule.CreateDetailView(Args);
MeshView->SetObject(StaticMeshHolder);
ChildSlot
[
SNew(SBorder)
.Padding(FMargin(0.0f, 3.0f, 1.0f, 0.0f))
[
SNew(SVerticalBox)
+ SVerticalBox::Slot()
.Padding(2.0f)
.AutoHeight()
[
MeshView->AsShared()
]
+ SVerticalBox::Slot()
.Padding(2.0f)
.HAlign(HAlign_Right)
.AutoHeight()
[
SNew(SUniformGridPanel)
.SlotPadding(2)
+ SUniformGridPanel::Slot(0, 0)
[
SAssignNew(LoadButton, SButton)
.Text(FText::FromString("Load"))
.IsEnabled(false)
.OnClicked(this, &SSelectStaticMeshDialog::LoadClicked)
]
+ SUniformGridPanel::Slot(1, 0)
[
SNew(SButton)
.Text(FText::FromString("Cancel"))
.OnClicked(this, &SSelectStaticMeshDialog::CancelClicked)
]
]
]
];
}
void SSelectStaticMeshDialog::MeshSelected()
{
LoadButton->SetEnabled(StaticMeshHolder->StaticMesh != nullptr);
}
FReply SSelectStaticMeshDialog::LoadClicked()
{
IsLoad = true;
CloseContainingWindow();
return FReply::Handled();
}
FReply SSelectStaticMeshDialog::CancelClicked()
{
CloseContainingWindow();
return FReply::Handled();
}
void SSelectStaticMeshDialog::CloseContainingWindow()
{
FWidgetPath WidgetPath;
TSharedPtr<SWindow> ContainingWindow = FSlateApplication::Get().FindWidgetWindow(AsShared(), WidgetPath);
if (ContainingWindow.IsValid())
{
ContainingWindow->RequestDestroyWindow();
}
}
UStaticMesh* SSelectStaticMeshDialog::ShowWindow()
{
const FText TitleText = NSLOCTEXT("BlastMeshEditor", "BlastMeshEditor_SelectStaticMesh", "Select static mesh");
// Create the window to pick the class
TSharedRef<SWindow> SelectStaticMeshWindow = SNew(SWindow)
.Title(TitleText)
.SizingRule(ESizingRule::Autosized)
.AutoCenter(EAutoCenter::PreferredWorkArea)
.SupportsMinimize(false);
TSharedRef<SSelectStaticMeshDialog> SelectStaticMeshDialog = SNew(SSelectStaticMeshDialog);
SelectStaticMeshWindow->SetContent(SelectStaticMeshDialog);
TSharedPtr<SWindow> RootWindow = FGlobalTabmanager::Get()->GetRootWindow();
if (RootWindow.IsValid())
{
FSlateApplication::Get().AddModalWindow(SelectStaticMeshWindow, RootWindow.ToSharedRef());
}
else
{
//assert here?
}
return SelectStaticMeshDialog->IsLoad ? SelectStaticMeshDialog->StaticMeshHolder->StaticMesh : nullptr;
}
//////////////////////////////////////////////////////////////////////////
// SFixChunkHierarchyDialog
//////////////////////////////////////////////////////////////////////////
// Constructs this widget with InArgs
void SFixChunkHierarchyDialog::Construct(const FArguments& InArgs)
{
FDetailsViewArgs Args;
Args.bLockable = false;
Args.bHideSelectionTip = true;
FPropertyEditorModule& PropertyModule = FModuleManager::LoadModuleChecked<FPropertyEditorModule>("PropertyEditor");
Properties = NewObject<UBlastFixChunkHierarchyProperties>();
PropertyView = PropertyModule.CreateDetailView(Args);
PropertyView->SetObject(Properties);
ChildSlot
[
SNew(SBorder)
.Padding(FMargin(0.0f, 3.0f, 1.0f, 0.0f))
[
SNew(SVerticalBox)
+ SVerticalBox::Slot()
.Padding(2.0f)
.AutoHeight()
[
PropertyView->AsShared()
]
+ SVerticalBox::Slot()
.Padding(2.0f)
.HAlign(HAlign_Right)
.AutoHeight()
[
SNew(SUniformGridPanel)
.SlotPadding(2)
+ SUniformGridPanel::Slot(0, 0)
[
SNew(SButton)
.Text(FText::FromString("Fix"))
.OnClicked(this, &SFixChunkHierarchyDialog::OnClicked, true)
]
+ SUniformGridPanel::Slot(1, 0)
[
SNew(SButton)
.Text(FText::FromString("Cancel"))
.OnClicked(this, &SFixChunkHierarchyDialog::OnClicked, false)
]
]
]
];
}
FReply SFixChunkHierarchyDialog::OnClicked(bool isFix)
{
IsFix = isFix;
CloseContainingWindow();
return FReply::Handled();
}
void SFixChunkHierarchyDialog::CloseContainingWindow()
{
FWidgetPath WidgetPath;
TSharedPtr<SWindow> ContainingWindow = FSlateApplication::Get().FindWidgetWindow(AsShared(), WidgetPath);
if (ContainingWindow.IsValid())
{
ContainingWindow->RequestDestroyWindow();
}
}
bool SFixChunkHierarchyDialog::ShowWindow(TSharedPtr<FBlastFracture> Fracturer, UBlastFractureSettings* FractureSettings)
{
const FText TitleText = NSLOCTEXT("BlastMeshEditor", "BlastMeshEditor_FixChunkHierarchy", "Fix chunk hierarchy");
// Create the window to pick the class
TSharedRef<SWindow> FixChunkHierarchyWindow = SNew(SWindow)
.Title(TitleText)
.SizingRule(ESizingRule::Autosized)
.AutoCenter(EAutoCenter::PreferredWorkArea)
.SupportsMinimize(false);
TSharedRef<SFixChunkHierarchyDialog> FixChunkHierarchyDialog = SNew(SFixChunkHierarchyDialog);
FixChunkHierarchyWindow->SetContent(FixChunkHierarchyDialog);
TSharedPtr<SWindow> RootWindow = FGlobalTabmanager::Get()->GetRootWindow();
if (RootWindow.IsValid())
{
FSlateApplication::Get().AddModalWindow(FixChunkHierarchyWindow, RootWindow.ToSharedRef());
}
else
{
//assert here?
}
if (FixChunkHierarchyDialog->IsFix)
{
Fracturer->BuildChunkHierarchy(FractureSettings, FixChunkHierarchyDialog->Properties->Threshold,
FixChunkHierarchyDialog->Properties->TargetedClusterSize);
}
return FixChunkHierarchyDialog->IsFix;
}
bool SExportAssetToFileDialog::ShowWindow(TSharedPtr<FBlastFracture> Fracturer, UBlastFractureSettings* FractureSettings)
{
IDesktopPlatform* platform = FDesktopPlatformModule::Get();
if (platform)
{
const FText TitleText = NSLOCTEXT("BlastMeshEditor", "BlastMeshEditor_ExportAsset", "Export asset to a file");
TArray<FString> path;
if (platform->SaveFileDialog(FSlateApplication::Get().FindBestParentWindowHandleForDialogs(nullptr), TitleText.ToString(), "C:/", L"asset.obj", "Wavefront OBJ|*.obj|Autodesk FBX|*.fbx", 0, path))
{
int32 dotPs1;
int32 dotPs2;
path[0].FindLastChar('/', dotPs1);
path[0].FindLastChar('\\', dotPs2);
dotPs1 = FMath::Max(dotPs1, dotPs2);
path[0].FindLastChar('.', dotPs2);
FString folderPath = path[0].Left(dotPs1);
FString extension = path[0].RightChop(dotPs2);
FString name = path[0].Mid(dotPs1 + 1, dotPs2 - dotPs1 - 1);
FString blastFile = folderPath;
blastFile.Append("/").Append(name).Append(".blast");
auto* bmesh = FractureSettings->FractureSession->BlastMesh;
TArray<const char*> matNames;
for (int32 i = 0; i < bmesh->Mesh->Materials.Num(); ++i)
{
int32_t elemCount = bmesh->Mesh->Materials[i].MaterialSlotName.ToString().Len() + 1;
char* data = new char[elemCount];
memcpy(data, TCHAR_TO_UTF8(bmesh->Mesh->Materials[i].MaterialSlotName.ToString().GetCharArray().GetData()), sizeof(char) * (elemCount - 1));
data[elemCount - 1] = 0; // set terminating character
matNames.Add(data);
}
FractureSettings->FractureSession->FractureData->materialCount = matNames.Num();
FractureSettings->FractureSession->FractureData->materialNames = matNames.GetData();
FString assetName = FractureSettings->FractureSession->BlastMesh->GetName();
if (extension == L".fbx")
{
Nv::Blast::IMeshFileWriter* writer = NvBlastExtExporterCreateFbxFileWriter();
writer->appendMesh(*FractureSettings->FractureSession->FractureData.Get(), TCHAR_TO_UTF8(assetName.GetCharArray().GetData()));
writer->saveToFile(TCHAR_TO_UTF8(name.GetCharArray().GetData()), TCHAR_TO_UTF8(folderPath.GetCharArray().GetData()));
}
if (extension == L".obj")
{
Nv::Blast::IMeshFileWriter* writer = NvBlastExtExporterCreateObjFileWriter();
writer->appendMesh(*FractureSettings->FractureSession->FractureData.Get(), TCHAR_TO_UTF8(assetName.GetCharArray().GetData()));
writer->saveToFile(TCHAR_TO_UTF8(name.GetCharArray().GetData()), TCHAR_TO_UTF8(folderPath.GetCharArray().GetData()));
}
UBlastMeshFactory::TransformBlastAssetFromUE4ToBlastCoordinateSystem(FractureSettings->FractureSession->FractureData->asset, nullptr);
for (int32_t i = 0; i < matNames.Num(); ++i)
{
delete[] matNames[i];
}
void* buffer;
Nv::Blast::ExtSerialization* serializer = NvBlastExtSerializationCreate();
serializer->setSerializationEncoding(Nv::Blast::ExtSerialization::EncodingID::CapnProtoBinary);
uint64_t bsize = serializer->serializeIntoBuffer(buffer, FractureSettings->FractureSession->FractureData->asset, Nv::Blast::LlObjectTypeID::Asset);
if (bsize)
{
IPlatformFile& platformFile = FPlatformFileManager::Get().GetPlatformFile();
IFileHandle* file = platformFile.OpenWrite(*blastFile);
if (file)
{
file->Write((uint8*)buffer, bsize);
}
delete file;
}
UBlastMeshFactory::TransformBlastAssetToUE4CoordinateSystem(FractureSettings->FractureSession->FractureData->asset, nullptr);
NVBLAST_FREE(buffer);
buffer = nullptr;
serializer->release();
}
}
return false;
}
//////////////////////////////////////////////////////////////////////////
// SUVCoordinatesDialog
//////////////////////////////////////////////////////////////////////////
void SFitUvCoordinatesDialog::Construct(const FArguments& InArgs)
{
mSquareSize = 1.f;
isOnlySelectedToggle = ECheckBoxState::Unchecked;
ChildSlot
[
SNew(SBorder)
.Padding(FMargin(0.0f, 3.0f, 1.0f, 0.0f))
[
SNew(SVerticalBox)
+ SVerticalBox::Slot()
.Padding(2.0f)
.AutoHeight()
+ SVerticalBox::Slot()
.Padding(2.0f)
.HAlign(HAlign_Left)
.AutoHeight()
[
SNew(SUniformGridPanel)
.SlotPadding(2)
+ SUniformGridPanel::Slot(0, 0)
[
SNew(STextBlock).Text(FText::FromString("Square size")).Font(FEditorStyle::GetFontStyle(TEXT("MenuItem.Font")))
]
+ SUniformGridPanel::Slot(1, 0)
[
SNew(SNumericEntryBox<float>).MinValue(0).OnValueChanged(this, &SFitUvCoordinatesDialog::OnSquareSizeChanged).Value(this, &SFitUvCoordinatesDialog::getSquareSize)
]
]
+ SVerticalBox::Slot()
.Padding(2.0f)
.HAlign(HAlign_Left)
.AutoHeight()
[
SNew(SCheckBox).OnCheckStateChanged(this, &SFitUvCoordinatesDialog::OnIsSelectedToggleChanged).IsChecked(this, &SFitUvCoordinatesDialog::getIsOnlySelectedToggle).ToolTipText(NSLOCTEXT("BlastMeshEditor", "UVFITTOOL_ONLYSELC", "Fit only selected chunks"))
[
SNew(STextBlock)
.Text(NSLOCTEXT("BlastMeshEditor", "OnlySelLabel", "Fit UV for only selected chunks."))
]
]
+ SVerticalBox::Slot()
.Padding(2.0f)
.HAlign(HAlign_Right)
.AutoHeight()
[
SNew(SUniformGridPanel)
.SlotPadding(2)
+ SUniformGridPanel::Slot(0, 0)
[
SNew(SButton)
.Text(FText::FromString("Fit UV"))
.OnClicked(this, &SFitUvCoordinatesDialog::OnClicked, true)
]
+ SUniformGridPanel::Slot(1, 0)
[
SNew(SButton)
.Text(FText::FromString("Cancel"))
.OnClicked(this, &SFitUvCoordinatesDialog::OnClicked, false)
]
]
]
];
}
FReply SFitUvCoordinatesDialog::OnClicked(bool isFix)
{
shouldFix = isFix;
CloseContainingWindow();
return FReply::Handled();
}
void SFitUvCoordinatesDialog::CloseContainingWindow()
{
FWidgetPath WidgetPath;
TSharedPtr<SWindow> ContainingWindow = FSlateApplication::Get().FindWidgetWindow(AsShared(), WidgetPath);
if (ContainingWindow.IsValid())
{
ContainingWindow->RequestDestroyWindow();
}
}
bool SFitUvCoordinatesDialog::ShowWindow(TSharedPtr<FBlastFracture> Fracturer, UBlastFractureSettings* FractureSettings, TSet<int32>& ChunkIndices)
{
const FText TitleText = NSLOCTEXT("FitUVDialog", "FitUVDialog", "Fit UV");
// Create the window to pick the class
TSharedRef<SWindow> FitUV = SNew(SWindow)
.Title(TitleText)
.SizingRule(ESizingRule::Autosized)
.AutoCenter(EAutoCenter::PreferredWorkArea)
.SupportsMinimize(false);
TSharedRef<SFitUvCoordinatesDialog> FitUVDialog = SNew(SFitUvCoordinatesDialog);
FitUV->SetContent(FitUVDialog);
TSharedPtr<SWindow> RootWindow = FGlobalTabmanager::Get()->GetRootWindow();
if (RootWindow.IsValid())
{
FSlateApplication::Get().AddModalWindow(FitUV, RootWindow.ToSharedRef());
}
else
{
//assert here?
}
if (FitUVDialog->shouldFix)
{
Fracturer->FitUvs(FractureSettings, FitUVDialog->mSquareSize, FitUVDialog->isOnlySelectedToggle == ECheckBoxState::Checked, ChunkIndices);
}
return true;
}
//////////////////////////////////////////////////////////////////////////
// SRebuildCollisionMeshDialog
//////////////////////////////////////////////////////////////////////////
// Constructs this widget with InArgs
void SRebuildCollisionMeshDialog::Construct(const FArguments& InArgs)
{
FDetailsViewArgs Args;
Args.bLockable = false;
Args.bHideSelectionTip = true;
FPropertyEditorModule& PropertyModule = FModuleManager::LoadModuleChecked<FPropertyEditorModule>("PropertyEditor");
Properties = NewObject<UBlastRebuildCollisionMeshProperties>();
PropertyView = PropertyModule.CreateDetailView(Args);
PropertyView->SetObject(Properties);
ChildSlot
[
SNew(SBorder)
.Padding(FMargin(0.0f, 3.0f, 1.0f, 0.0f))
[
SNew(SVerticalBox)
+ SVerticalBox::Slot()
.Padding(2.0f)
.AutoHeight()
[
PropertyView->AsShared()
]
+ SVerticalBox::Slot()
.Padding(2.0f)
.HAlign(HAlign_Right)
.AutoHeight()
[
SNew(SUniformGridPanel)
.SlotPadding(2)
+ SUniformGridPanel::Slot(0, 0)
[
SNew(SButton)
.Text(FText::FromString("Build"))
.OnClicked(this, &SRebuildCollisionMeshDialog::OnClicked, true)
]
+ SUniformGridPanel::Slot(1, 0)
[
SNew(SButton)
.Text(FText::FromString("Cancel"))
.OnClicked(this, &SRebuildCollisionMeshDialog::OnClicked, false)
]
]
]
];
}
FReply SRebuildCollisionMeshDialog::OnClicked(bool InIsRebuild)
{
IsRebuild = InIsRebuild;
CloseContainingWindow();
return FReply::Handled();
}
void SRebuildCollisionMeshDialog::CloseContainingWindow()
{
FWidgetPath WidgetPath;
TSharedPtr<SWindow> ContainingWindow = FSlateApplication::Get().FindWidgetWindow(AsShared(), WidgetPath);
if (ContainingWindow.IsValid())
{
ContainingWindow->RequestDestroyWindow();
}
}
bool SRebuildCollisionMeshDialog::ShowWindow(TSharedPtr<FBlastFracture> Fracturer, UBlastFractureSettings* FractureSettings, TSet<int32>& ChunkIndices)
{
const FText TitleText = NSLOCTEXT("BlastMeshEditor", "BlastMeshEditor_RebuildCollisionMesh", "Rebuild collision mesh");
// Create the window to pick the class
TSharedRef<SWindow> RebuildCollisionMeshWindow = SNew(SWindow)
.Title(TitleText)
.SizingRule(ESizingRule::Autosized)
.AutoCenter(EAutoCenter::PreferredWorkArea)
.SupportsMinimize(false);
TSharedRef<SRebuildCollisionMeshDialog> RebuildCollisionMeshDialog = SNew(SRebuildCollisionMeshDialog);
RebuildCollisionMeshWindow->SetContent(RebuildCollisionMeshDialog);
TSharedPtr<SWindow> RootWindow = FGlobalTabmanager::Get()->GetRootWindow();
if (RootWindow.IsValid())
{
FSlateApplication::Get().AddModalWindow(RebuildCollisionMeshWindow, RootWindow.ToSharedRef());
}
else
{
//assert here?
}
if (RebuildCollisionMeshDialog->IsRebuild)
{
Fracturer->RebuildCollisionMesh(FractureSettings, RebuildCollisionMeshDialog->Properties->MaximumNumberOfHulls,
RebuildCollisionMeshDialog->Properties->VoxelGridResolution,
RebuildCollisionMeshDialog->Properties->Concavity,
RebuildCollisionMeshDialog->Properties->IsOnlyForSelectedChunks ? ChunkIndices : TSet<int32>());
}
return RebuildCollisionMeshDialog->IsRebuild;
}
|
// Copyright 2020 The Chromium Authors. All rights reserved.
// Copyright 2014 Blake Embrey (hello@blakeembrey.com)
// Use of this source code is governed by an MIT-style license that can be
// found in the LICENSE file or at https://opensource.org/licenses/MIT.
#include "third_party/liburlpattern/tokenize.h"
#include "third_party/abseil-cpp/absl/strings/str_format.h"
#include "third_party/icu/source/common/unicode/uchar.h"
#include "third_party/icu/source/common/unicode/utf8.h"
// The following code is a translation from the path-to-regexp typescript at:
//
// https://github.com/pillarjs/path-to-regexp/blob/125c43e6481f68cc771a5af22b914acdb8c5ba1f/src/index.ts#L4-L124
namespace liburlpattern {
namespace {
bool IsASCII(UChar32 c) {
// Characters should be valid ASCII code points:
// https://infra.spec.whatwg.org/#ascii-code-point
return c >= 0x00 && c <= 0x7f;
}
bool IsNameCodepoint(UChar32 c, bool first_codepoint) {
// Require group names to follow the same character restrictions as
// javascript identifiers. This code originates from v8 at:
//
// https://source.chromium.org/chromium/chromium/src/+/master:v8/src/strings/char-predicates.cc;l=17-34;drc=be014256adea1552d4a044ef80616cdab6a7d549
//
// We deviate from js identifiers, however, in not support the backslash
// character. This is mainly used in js identifiers to allow escaped
// unicode sequences to be written in ascii. The js engine, however,
// should take care of this long before we reach this level of code. So
// we don't need to handle it here.
if (first_codepoint) {
return u_hasBinaryProperty(c, UCHAR_ID_START) || c == '$' || c == '_';
}
return u_hasBinaryProperty(c, UCHAR_ID_CONTINUE) || c == '$' || c == '_' ||
c == 0x200c || c == 0x200d;
}
class Tokenizer {
public:
Tokenizer(absl::string_view pattern, TokenizePolicy policy)
: pattern_(std::move(pattern)), policy_(policy) {
token_list_.reserve(pattern_.size());
}
absl::StatusOr<std::vector<Token>> Tokenize() {
while (index_ < pattern_.size()) {
if (!status_.ok())
return std::move(status_);
NextAt(index_);
if (codepoint_ == '*') {
AddToken(TokenType::kAsterisk);
continue;
}
if (codepoint_ == '+' || codepoint_ == '?') {
AddToken(TokenType::kOtherModifier);
continue;
}
// Escape sequences always escape a single following character at the
// level of the pattern.
if (codepoint_ == '\\') {
if (index_ == (pattern_.size() - 1)) {
Error(absl::StrFormat("Trailing escape character at index %d.",
index_));
continue;
}
size_t escaped_i = next_index_;
Next();
AddToken(TokenType::kEscapedChar, next_index_, escaped_i);
continue;
}
if (codepoint_ == '{') {
AddToken(TokenType::kOpen);
continue;
}
if (codepoint_ == '}') {
AddToken(TokenType::kClose);
continue;
}
if (codepoint_ == ':') {
size_t pos = next_index_;
size_t name_start = pos;
// Iterate over codepoints until we find the first non-name codepoint.
while (pos < pattern_.size()) {
NextAt(pos);
if (!IsNameCodepoint(codepoint_, pos == name_start))
break;
pos = next_index_;
}
if (pos <= name_start) {
Error(absl::StrFormat("Missing parameter name at index %d.", index_),
name_start, index_);
continue;
}
AddToken(TokenType::kName, pos, name_start);
continue;
}
if (codepoint_ == '(') {
size_t paren_nesting = 1;
size_t j = next_index_;
const size_t regex_start = next_index_;
bool error = false;
while (j < pattern_.size()) {
NextAt(j);
if (!IsASCII(codepoint_)) {
Error(absl::StrFormat(
"Invalid non-ASCII character 0x%02x at index %d.",
codepoint_, j),
regex_start, index_);
error = true;
break;
}
if (j == regex_start && codepoint_ == '?') {
Error(absl::StrFormat("Regex cannot start with '?' at index %d", j),
regex_start, index_);
error = true;
break;
}
// This escape processing only handles single character escapes since
// we only need to understand escaped paren characters for our state
// processing. The escape `\` character is propagated to the embedded
// regex expression. This permits authors to write longer escape
// sequences such as `\x22` since the later characters will be
// propagated on subsequent loop iterations.
if (codepoint_ == '\\') {
if (j == (pattern_.size() - 1)) {
Error(
absl::StrFormat("Trailing escape character at index %d.", j),
regex_start, index_);
error = true;
break;
}
size_t escaped_j = next_index_;
Next();
if (!IsASCII(codepoint_)) {
Error(absl::StrFormat(
"Invalid non-ASCII character 0x%02x at index %d.",
codepoint_, escaped_j),
regex_start, index_);
error = true;
break;
}
j = next_index_;
continue;
}
if (codepoint_ == ')') {
paren_nesting -= 1;
if (paren_nesting == 0) {
j = next_index_;
break;
}
} else if (codepoint_ == '(') {
paren_nesting += 1;
if (j == (pattern_.size() - 1)) {
Error(absl::StrFormat("Unbalanced regex at index %d.", j),
regex_start, index_);
error = true;
break;
}
size_t tmp_j = next_index_;
Next();
// Require the the first character after an open paren is `?`. This
// permits assertions, named capture groups, and non-capturing
// groups. It blocks, however, unnamed capture groups.
if (codepoint_ != '?') {
Error(absl::StrFormat(
"Unnamed capturing groups are not allowed at index %d.",
tmp_j),
regex_start, index_);
error = true;
break;
}
next_index_ = tmp_j;
}
j = next_index_;
}
if (error)
continue;
if (paren_nesting) {
Error(absl::StrFormat("Unbalanced regex at index %d.", index_),
regex_start, index_);
continue;
}
const size_t regex_length = j - regex_start - 1;
if (regex_length == 0) {
Error(absl::StrFormat("Missing regex at index %d.", index_),
regex_start, index_);
continue;
}
AddToken(TokenType::kRegex, j, regex_start, regex_length);
continue;
}
AddToken(TokenType::kChar);
}
if (!status_.ok())
return std::move(status_);
AddToken(TokenType::kEnd, index_, index_);
return std::move(token_list_);
}
private:
// Read the codepoint at `next_index_` in `pattern_` and store it in
// `codepoint_`. In addition, `next_index_` is updated to the codepoint to be
// read next.
void Next() {
U8_NEXT(pattern_.data(), next_index_, pattern_.size(), codepoint_);
}
// Read the codepoint at the specified `index` in `pattern_` and store it in
// `codepoint_`. In addition, `next_index_` is updated to the codepoint to be
// read next.
void NextAt(size_t index) {
next_index_ = index;
Next();
}
// Append a Token to our list of the given `type` and with a value consisting
// of the codepoints in `pattern_` starting at `value_pos` with
// `value_length`. Update `index_` to `next_pos` automatically.
void AddToken(TokenType type,
size_t next_pos,
size_t value_pos,
size_t value_length) {
token_list_.emplace_back(type, index_,
pattern_.substr(value_pos, value_length));
index_ = next_pos;
}
// Append a Token to our list of the given `type` and with a value consisting
// of the codepoints in `pattern_` starting at `value_pos`. The value length
// is automatically computed as the difference between `next_pos` and
// `value_pos`. Update `index_` to `next_pos` automatically.
void AddToken(TokenType type, size_t next_pos, size_t value_pos) {
AddToken(type, next_pos, value_pos, next_pos - value_pos);
}
// Append a Token to our list of the given `type` and with a value consisting
// of the codepoints in `pattern_` starting at `index_`. The value length
// is automatically computed as the difference between `next_index_` and
// `index_`. Update `index_` to `next_index_` automatically.
void AddToken(TokenType type) { AddToken(type, next_index_, index_); }
void Error(absl::string_view message, size_t next_pos, size_t value_pos) {
if (policy_ == TokenizePolicy::kLenient)
AddToken(TokenType::kInvalidChar, next_pos, value_pos);
else
status_ = absl::InvalidArgumentError(message);
}
void Error(absl::string_view message) { Error(message, next_index_, index_); }
const absl::string_view pattern_;
const TokenizePolicy policy_;
std::vector<Token> token_list_;
absl::Status status_;
// `index_` tracks our "current" byte index in the input string. Typically
// this will be updated every time we commit a token to `token_list_`. It may
// stay frozen in place if we have a sub-loop consuming a larger token like
// a named group or regex group.
size_t index_ = 0;
// The `next_index_` member is used to find the next UTF8 codepoint in the
// string. This is used as both an input and output from the U8_NEXT()
// function. We keep this separate from `index_` because there are many
// cases where we need to read ahead of the last token consumed.
size_t next_index_ = 0;
UChar32 codepoint_ = U_SENTINEL;
};
} // namespace
const char* TokenTypeToString(TokenType type) {
switch (type) {
case TokenType::kOpen:
return "'{'";
case TokenType::kClose:
return "'}'";
case TokenType::kRegex:
return "regex group";
case TokenType::kName:
return "named group";
case TokenType::kChar:
return "character";
case TokenType::kEscapedChar:
return "escaped character";
case TokenType::kOtherModifier:
return "modifier";
case TokenType::kAsterisk:
return "asterisk";
case TokenType::kEnd:
return "end of pattern";
case TokenType::kInvalidChar:
return "invalid character";
}
}
std::ostream& operator<<(std::ostream& o, Token token) {
o << "{ type:" << static_cast<int>(token.type) << ", index:" << token.index
<< ", value:" << token.value << " }";
return o;
}
// Split the input pattern into a list of tokens.
absl::StatusOr<std::vector<Token>> Tokenize(absl::string_view pattern,
TokenizePolicy policy) {
Tokenizer tokenizer(std::move(pattern), policy);
return tokenizer.Tokenize();
}
} // namespace liburlpattern
|
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
const char VOWEL[] = "AUEOI";
const char CONSONANT[] = "JSBKTCLDMVNWFXGPYHQZR";
int n;
int main()
{
int T;
cin >> T;
for (int t = 1; t <= T; t++)
{
// Input.
cin >> n;
// Solve.
string vowel, consonant;
for (int i = 1, idx = 0; i <= (n + 1) / 2; i++)
{
vowel += VOWEL[idx];
if (i % 21 == 0) idx++;
}
for (int i = 1, idx = 0; i <= n / 2; i++)
{
consonant += CONSONANT[idx];
if (i % 5 == 0) idx++;
}
sort(vowel.begin(), vowel.end());
sort(consonant.begin(), consonant.end());
// Output.
cout << "Case " << t << ": ";
for (int i = 1; i <= n; i++)
cout << (i % 2 ? vowel[i / 2] : consonant[i / 2 - 1]);
cout << endl;
}
return 0;
}
|
/*
// Copyright (c) 2019-2020 Intel Corporation
//
// 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 "gather_kernel_ref.h"
#include "kernel_selector_utils.h"
#include <string>
#include <vector>
namespace kernel_selector {
static size_t GetGatherChannelIndex(const gather_params& params) {
Tensor::DataChannelName name = Tensor::DataChannelName::X;
size_t inputSize = params.inputs[0].GetDims().size();
switch (params.axis) {
case GatherAxis::X:
return inputSize - 1;
case GatherAxis::Y:
return inputSize - 2;
case GatherAxis::Z:
return inputSize - 3;
case GatherAxis::W:
return 2;
case GatherAxis::FEATURE:
return 1;
case GatherAxis::BATCH:
return 0;
default:
break;
}
return DataTensor::Channelndex(params.output.GetLayout(), name);
}
ParamsKey GatherKernelRef::GetSupportedKey() const {
ParamsKey k;
k.EnableInputDataType(Datatype::F16);
k.EnableInputDataType(Datatype::F32);
k.EnableInputDataType(Datatype::INT32);
k.EnableOutputDataType(Datatype::F16);
k.EnableOutputDataType(Datatype::F32);
k.EnableOutputDataType(Datatype::INT32);
k.EnableOutputDataType(Datatype::INT8);
k.EnableOutputDataType(Datatype::UINT8);
k.EnableInputLayout(DataLayout::bfyx);
k.EnableOutputLayout(DataLayout::bfyx);
k.EnableInputLayout(DataLayout::bfzyx);
k.EnableOutputLayout(DataLayout::bfzyx);
k.EnableInputLayout(DataLayout::bfwzyx);
k.EnableOutputLayout(DataLayout::bfwzyx);
k.EnableTensorOffset();
k.EnableTensorPitches();
k.EnableBatching();
k.EnableDifferentTypes();
return k;
}
static size_t GetNonEmptyDimsNumber(const DataTensor& data_tensor) {
if (data_tensor.LogicalSize() != 1) {
// Count the number of "one size" dimensions starting with X to Batch
size_t one_size_dims = 0;
for (auto& i : data_tensor.GetDims()) {
if (i.v == 1)
one_size_dims++;
else
break;
}
return data_tensor.Dimentions() - one_size_dims;
} else {
return 1;
}
}
static inline std::string GetOrderString(std::vector<std::string>& order) {
std::string order_str = order[0];
for (size_t i = 1; i < order.size(); i++)
order_str += ", " + order[i];
return order_str;
}
static inline std::vector<std::string> GetOrder(size_t size) {
std::vector<std::string> idx_order;
if (size <= 4) {
idx_order = {"b", "f", "y", "x"};
} else if (size == 5) {
idx_order = {"b", "f", "z", "y", "x"};
} else if (size == 6) {
idx_order = {"b", "f", "w", "z", "y", "x"};
}
return idx_order;
}
static std::string GetDictionaryIndexOrder(const gather_params& params, size_t axis) {
std::vector<std::string> idx_order = GetOrder(params.output.GetDims().size());
const std::string input_axis_index_macro = "INPUT_AXIS_INDEX";
const std::string zeroVal = "0";
size_t dictionary_dims_num = GetNonEmptyDimsNumber(params.inputs[0]);
size_t indices_dims_num = GetNonEmptyDimsNumber(params.output) - dictionary_dims_num + 1;
// Shift indices of Gather dictionary input related to output dims
for (size_t i = axis + 1; i < dictionary_dims_num; i++)
idx_order[i] = idx_order[i + indices_dims_num - 1];
for (size_t i = dictionary_dims_num; i < idx_order.size(); i++)
idx_order[i] = zeroVal;
// Fix size to inputs[0] dims size
for (size_t i = 0; i < params.output.GetDims().size() - params.inputs[0].GetDims().size(); i++)
idx_order.pop_back();
idx_order[axis] = input_axis_index_macro;
return GetOrderString(idx_order);
}
static std::string GetIndecesIdxOrder(const gather_params& params, size_t axis) {
std::vector<std::string> idx_order = GetOrder(params.output.GetDims().size());
const std::string zero_val = "0";
size_t indices_dims_num = GetNonEmptyDimsNumber(params.inputs[1]);
// Shift indices of Gather indices input related to output dims
for (size_t i = 0; i < indices_dims_num; i++)
idx_order[i] = idx_order[axis + i];
for (size_t i = indices_dims_num; i < idx_order.size(); i++)
idx_order[i] = zero_val;
// Fix size to inputs[1] dims size
for (size_t i = 0; i < params.output.GetDims().size() - params.inputs[1].GetDims().size(); i++)
idx_order.pop_back();
return GetOrderString(idx_order);
}
CommonDispatchData GatherKernelRef::SetDefault(const gather_params& params, const optional_params&) const {
CommonDispatchData dispatchData;
const auto& output = params.output;
if (output.GetLayout() == DataLayout::bfyx) {
dispatchData.gws = {output.X().v, output.Y().v, output.Feature().v * output.Batch().v};
} else if (output.GetLayout() == DataLayout::bfzyx) {
dispatchData.gws = {output.X().v, output.Y().v * output.Z().v, output.Feature().v * output.Batch().v};
} else {
dispatchData.gws = {output.X().v * output.Y().v, output.Z().v * output.W().v, output.Feature().v * output.Batch().v};
}
dispatchData.lws = GetOptimalLocalWorkGroupSizes(dispatchData.gws, params.engineInfo);
return dispatchData;
}
JitConstants GatherKernelRef::GetJitConstants(const gather_params& params) const {
JitConstants jit = MakeBaseParamsJitConstants(params);
jit.AddConstant(MakeJitConstant("DICTIONARY_INDEX_ORDER", GetDictionaryIndexOrder(params, GetGatherChannelIndex(params))));
jit.AddConstant(MakeJitConstant("INDICES_INDEX_ORDER", GetIndecesIdxOrder(params, GetGatherChannelIndex(params))));
if (!params.fused_ops.empty()) {
std::vector<std::string> idx_order = GetOrder(params.inputs[0].GetDims().size());
FusedOpsConfiguration conf = { "", idx_order, "val", params.inputs[0].GetDType() };
jit.Merge(MakeFusedOpsJitConstants(params, {conf}));
}
return jit;
}
bool GatherKernelRef::Validate(const Params& p, const optional_params& o) const {
if (p.GetType() != KernelType::GATHER || o.GetType() != KernelType::GATHER) {
return false;
}
const gather_params& params = static_cast<const gather_params&>(p);
for (auto& fused_op : params.fused_ops) {
if (!IsFusedPrimitiveSupported(fused_op))
return false;
}
return true;
}
KernelsData GatherKernelRef::GetKernelsData(const Params& params, const optional_params& options) const {
if (!Validate(params, options)) {
return {};
}
KernelData kd = KernelData::Default<gather_params>(params);
gather_params& newParams = *static_cast<gather_params*>(kd.params.get());
auto dispatchData = SetDefault(newParams, options);
auto entry_point = GetEntryPoint(kernelName, newParams.layerID, options);
auto cldnn_jit = GetJitConstants(newParams);
std::string jit = CreateJit(kernelName, cldnn_jit, entry_point);
auto& kernel = kd.kernels[0];
FillCLKernelData(kernel, dispatchData, params.engineInfo, kernelName, jit, entry_point, "", false, false, 2, GetFusedPrimitiveInputsCount(params));
return {kd};
}
KernelsPriority GatherKernelRef::GetKernelsPriority(const Params& /*params*/, const optional_params& /*options*/) const {
return DONT_USE_IF_HAVE_SOMETHING_ELSE;
}
} // namespace kernel_selector
|
// Copyright (c) 2015-2019 The Khronos Group 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.
//
// ---- Exceptions to the Apache 2.0 License: ----
//
// As an exception, if you use this Software to generate code and portions of
// this Software are embedded into the generated code as a result, you may
// redistribute such product without providing attribution as would otherwise
// be required by Sections 4(a), 4(b) and 4(d) of the License.
//
// In addition, if you combine or link code generated by this Software with
// software that is licensed under the GPLv2 or the LGPL v2.0 or 2.1
// ("`Combined Software`") and if a court of competent jurisdiction determines
// that the patent provision (Section 3), the indemnity provision (Section 9)
// or other Section of the License conflicts with the conditions of the
// applicable GPL or LGPL license, you may retroactively and prospectively
// choose to deem waived or otherwise exclude such Section(s) of the License,
// but only in their entirety and only with respect to the Combined Software.
//
// This header is generated from the Khronos Vulkan XML API Registry.
#pragma once
#include "../handles.hpp"
#include "VkAcquire.hpp"
#include "VkAcceleration.hpp"
#include "VkApplication.hpp"
#include "VkInitialize.hpp"
#include "VkAllocation.hpp"
#include "VkExternal.hpp"
#include "VkBind.hpp"
#include "VkObject.hpp"
#include "VkCooperative.hpp"
#include "VkAndroid.hpp"
#include "VkImport.hpp"
#include "VkImage.hpp"
#include "VkDescriptor.hpp"
#include "VkBase.hpp"
#include "VkAttachment.hpp"
#include "VkBuffer.hpp"
#include "VkFramebuffer.hpp"
#include "VkCalibrated.hpp"
#include "VkDevice.hpp"
#include "VkCheckpoint.hpp"
#include "VkConformance.hpp"
#include "VkClear.hpp"
#include "VkCmd.hpp"
#include "VkExtension.hpp"
#include "VkCoarse.hpp"
#include "VkCommand.hpp"
#include "VkMetal.hpp"
#include "VkFormat.hpp"
#include "VkComponent.hpp"
#include "VkCopy.hpp"
#include "VkCompute.hpp"
#include "VkPast.hpp"
#include "VkConditional.hpp"
#include "VkMapped.hpp"
#include "VkD3D.hpp"
#include "VkDebug.hpp"
#include "VkFence.hpp"
#include "VkDedicated.hpp"
#include "VkPipeline.hpp"
#include "VkDraw.hpp"
#include "VkDispatch.hpp"
#include "VkDisplay.hpp"
#include "VkDrm.hpp"
#include "VkEvent.hpp"
#include "VkExport.hpp"
#include "VkExtent.hpp"
#include "VkPerformance.hpp"
#include "VkFilter.hpp"
#include "VkGeometry.hpp"
#include "VkGraphics.hpp"
#include "VkHdr.hpp"
#include "VkHeadless.hpp"
#include "VkMultisample.hpp"
#include "VkI.hpp"
#include "VkIndirect.hpp"
#include "VkInput.hpp"
#include "VkOffset.hpp"
#include "VkMemory.hpp"
#include "VkInstance.hpp"
#include "VkLayer.hpp"
#include "VkMac.hpp"
#include "VkPhysical.hpp"
#include "VkPresent.hpp"
namespace VULKAN_HPP_NAMESPACE
{
struct ProtectedSubmitInfo
{
VULKAN_HPP_CONSTEXPR ProtectedSubmitInfo( VULKAN_HPP_NAMESPACE::Bool32 protectedSubmit_ = {} ) VULKAN_HPP_NOEXCEPT
: protectedSubmit( protectedSubmit_ )
{}
VULKAN_HPP_CONSTEXPR ProtectedSubmitInfo( ProtectedSubmitInfo const& rhs ) VULKAN_HPP_NOEXCEPT
: pNext( rhs.pNext )
, protectedSubmit( rhs.protectedSubmit )
{}
ProtectedSubmitInfo & operator=( ProtectedSubmitInfo const & rhs ) VULKAN_HPP_NOEXCEPT
{
memcpy( &pNext, &rhs.pNext, sizeof( ProtectedSubmitInfo ) - offsetof( ProtectedSubmitInfo, pNext ) );
return *this;
}
ProtectedSubmitInfo( VkProtectedSubmitInfo const & rhs ) VULKAN_HPP_NOEXCEPT
{
*this = rhs;
}
ProtectedSubmitInfo& operator=( VkProtectedSubmitInfo const & rhs ) VULKAN_HPP_NOEXCEPT
{
*this = *reinterpret_cast<VULKAN_HPP_NAMESPACE::ProtectedSubmitInfo const *>(&rhs);
return *this;
}
ProtectedSubmitInfo & setPNext( const void* pNext_ ) VULKAN_HPP_NOEXCEPT
{
pNext = pNext_;
return *this;
}
ProtectedSubmitInfo & setProtectedSubmit( VULKAN_HPP_NAMESPACE::Bool32 protectedSubmit_ ) VULKAN_HPP_NOEXCEPT
{
protectedSubmit = protectedSubmit_;
return *this;
}
operator VkProtectedSubmitInfo const&() const VULKAN_HPP_NOEXCEPT
{
return *reinterpret_cast<const VkProtectedSubmitInfo*>( this );
}
operator VkProtectedSubmitInfo &() VULKAN_HPP_NOEXCEPT
{
return *reinterpret_cast<VkProtectedSubmitInfo*>( this );
}
#if defined(VULKAN_HPP_HAS_SPACESHIP_OPERATOR)
auto operator<=>( ProtectedSubmitInfo const& ) const = default;
#else
bool operator==( ProtectedSubmitInfo const& rhs ) const VULKAN_HPP_NOEXCEPT
{
return ( sType == rhs.sType )
&& ( pNext == rhs.pNext )
&& ( protectedSubmit == rhs.protectedSubmit );
}
bool operator!=( ProtectedSubmitInfo const& rhs ) const VULKAN_HPP_NOEXCEPT
{
return !operator==( rhs );
}
#endif
public:
const VULKAN_HPP_NAMESPACE::StructureType sType = StructureType::eProtectedSubmitInfo;
const void* pNext = {};
VULKAN_HPP_NAMESPACE::Bool32 protectedSubmit = {};
};
static_assert( sizeof( ProtectedSubmitInfo ) == sizeof( VkProtectedSubmitInfo ), "struct and wrapper have different size!" );
static_assert( std::is_standard_layout<ProtectedSubmitInfo>::value, "struct wrapper is not a standard layout!" );
} // namespace VULKAN_HPP_NAMESPACE
|
// C++2a concepts experiment
// g++-2a -std=c++2a -fconcepts
// wikipedia example
#ifdef FAILTEST // for cleaner asm
class NotComp
{
}; // class lacking in equality/inequality operator
#endif
template <class T>
concept bool EqualityComparable = requires(T a, T b)
{
{
a == b
}
->bool;
{
a != b
}
->bool;
};
// Templated for EqualityComparable types
void f(const EqualityComparable &) {} // do nothing
int main()
{
f(122); // compiles, comparable type
#ifdef FAILTEST // control method use -DFAILTEST w/ gcc
f(NotComp());
#endif
}
|
#include "jtil/ui/rocket_file_interface.h"
#include <stdio.h>
using Rocket::Core::String;
namespace jtil {
namespace ui {
RocketFileInterface::RocketFileInterface(const std::string& root) :
root(root.c_str()) {
}
RocketFileInterface::~RocketFileInterface() {
}
// Opens a file.
Rocket::Core::FileHandle RocketFileInterface::Open(const String& path) {
// Attempt to open the file relative to the application's root.
FILE* fp = fopen((root + path).CString(), "rb");
if (fp != NULL)
return (Rocket::Core::FileHandle) fp;
// Attempt to open the file relative to the current working directory.
fp = fopen(path.CString(), "rb");
return (Rocket::Core::FileHandle) fp;
}
// Closes a previously opened file.
void RocketFileInterface::Close(Rocket::Core::FileHandle file) {
fclose((FILE*) file);
}
// Reads data from a previously opened file.
size_t RocketFileInterface::Read(void* buffer, size_t size,
Rocket::Core::FileHandle file) {
return fread(buffer, 1, size, (FILE*) file);
}
// Seeks to a point in a previously opened file.
bool RocketFileInterface::Seek(Rocket::Core::FileHandle file,
long offset, int origin) {
return fseek((FILE*) file, offset, origin) == 0;
}
// Returns the current position of the file pointer.
size_t RocketFileInterface::Tell(Rocket::Core::FileHandle file) {
return ftell((FILE*) file);
}
} // namespace ui
} // namespace jtil
|
#include "guiutil.h"
#include "bitcoinaddressvalidator.h"
#include "walletmodel.h"
#include "bitcoinunits.h"
#include "util.h"
#include "init.h"
#include <QString>
#include <QDateTime>
#include <QDoubleValidator>
#include <QFont>
#include <QLineEdit>
#include <QUrl>
#include <QTextDocument> // For Qt::escape
#include <QAbstractItemView>
#include <QApplication>
#include <QClipboard>
#include <QFileDialog>
#include <QDesktopServices>
#include <QThread>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#ifdef WIN32
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include "shlwapi.h"
#include "shlobj.h"
#include "shellapi.h"
#endif
namespace GUIUtil {
QString dateTimeStr(const QDateTime &date)
{
return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm");
}
QString dateTimeStr(qint64 nTime)
{
return dateTimeStr(QDateTime::fromTime_t((qint32)nTime));
}
QFont bitcoinAddressFont()
{
QFont font("Monospace");
font.setStyleHint(QFont::TypeWriter);
return font;
}
void setupAddressWidget(QLineEdit *widget, QWidget *parent)
{
widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength);
widget->setValidator(new BitcoinAddressValidator(parent));
widget->setFont(bitcoinAddressFont());
}
void setupAmountWidget(QLineEdit *widget, QWidget *parent)
{
QDoubleValidator *amountValidator = new QDoubleValidator(parent);
amountValidator->setDecimals(8);
amountValidator->setBottom(0.0);
widget->setValidator(amountValidator);
widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
}
bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
{
if(uri.scheme() != QString("bitcoin"))
return false;
SendCoinsRecipient rv;
rv.address = uri.path();
rv.amount = 0;
QList<QPair<QString, QString> > items = uri.queryItems();
for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++)
{
bool fShouldReturnFalse = false;
if (i->first.startsWith("req-"))
{
i->first.remove(0, 4);
fShouldReturnFalse = true;
}
if (i->first == "label")
{
rv.label = i->second;
fShouldReturnFalse = false;
}
else if (i->first == "amount")
{
if(!i->second.isEmpty())
{
if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount))
{
return false;
}
}
fShouldReturnFalse = false;
}
if (fShouldReturnFalse)
return false;
}
if(out)
{
*out = rv;
}
return true;
}
bool parseBitcoinURI(QString uri, SendCoinsRecipient *out)
{
// Convert bitcoin:// to bitcoin:
//
// Cannot handle this later, because bitcoin:// will cause Qt to see the part after // as host,
// which will lower-case it (and thus invalidate the address).
if(uri.startsWith("bitcoin://"))
{
uri.replace(0, 10, "bitcoin:");
}
QUrl uriInstance(uri);
return parseBitcoinURI(uriInstance, out);
}
QString HtmlEscape(const QString& str, bool fMultiLine)
{
QString escaped = Qt::escape(str);
if(fMultiLine)
{
escaped = escaped.replace("\n", "<br>\n");
}
return escaped;
}
QString HtmlEscape(const std::string& str, bool fMultiLine)
{
return HtmlEscape(QString::fromStdString(str), fMultiLine);
}
void copyEntryData(QAbstractItemView *view, int column, int role)
{
if(!view || !view->selectionModel())
return;
QModelIndexList selection = view->selectionModel()->selectedRows(column);
if(!selection.isEmpty())
{
// Copy first item
QApplication::clipboard()->setText(selection.at(0).data(role).toString());
}
}
QString getSaveFileName(QWidget *parent, const QString &caption,
const QString &dir,
const QString &filter,
QString *selectedSuffixOut)
{
QString selectedFilter;
QString myDir;
if(dir.isEmpty()) // Default to user documents location
{
myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
}
else
{
myDir = dir;
}
QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter);
/* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
QString selectedSuffix;
if(filter_re.exactMatch(selectedFilter))
{
selectedSuffix = filter_re.cap(1);
}
/* Add suffix if needed */
QFileInfo info(result);
if(!result.isEmpty())
{
if(info.suffix().isEmpty() && !selectedSuffix.isEmpty())
{
/* No suffix specified, add selected suffix */
if(!result.endsWith("."))
result.append(".");
result.append(selectedSuffix);
}
}
/* Return selected suffix if asked to */
if(selectedSuffixOut)
{
*selectedSuffixOut = selectedSuffix;
}
return result;
}
Qt::ConnectionType blockingGUIThreadConnection()
{
if(QThread::currentThread() != QCoreApplication::instance()->thread())
{
return Qt::BlockingQueuedConnection;
}
else
{
return Qt::DirectConnection;
}
}
bool checkPoint(const QPoint &p, const QWidget *w)
{
QWidget *atW = qApp->widgetAt(w->mapToGlobal(p));
if (!atW) return false;
return atW->topLevelWidget() == w;
}
bool isObscured(QWidget *w)
{
return !(checkPoint(QPoint(0, 0), w)
&& checkPoint(QPoint(w->width() - 1, 0), w)
&& checkPoint(QPoint(0, w->height() - 1), w)
&& checkPoint(QPoint(w->width() - 1, w->height() - 1), w)
&& checkPoint(QPoint(w->width() / 2, w->height() / 2), w));
}
void openDebugLogfile()
{
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
/* Open debug.log with the associated application */
if (boost::filesystem::exists(pathDebug))
QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string())));
}
ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) :
QObject(parent), size_threshold(size_threshold)
{
}
bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt)
{
if(evt->type() == QEvent::ToolTipChange)
{
QWidget *widget = static_cast<QWidget*>(obj);
QString tooltip = widget->toolTip();
if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt/>") && !Qt::mightBeRichText(tooltip))
{
// Prefix <qt/> to make sure Qt detects this as rich text
// Escape the current message as HTML and replace \n by <br>
tooltip = "<qt/>" + HtmlEscape(tooltip, true);
widget->setToolTip(tooltip);
return true;
}
}
return QObject::eventFilter(obj, evt);
}
#ifdef WIN32
boost::filesystem::path static StartupShortcutPath()
{
return GetSpecialFolderPath(CSIDL_STARTUP) / "Bitcoin.lnk";
}
bool GetStartOnSystemStartup()
{
// check for Bitcoin.lnk
return boost::filesystem::exists(StartupShortcutPath());
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
// If the shortcut exists already, remove it for updating
boost::filesystem::remove(StartupShortcutPath());
if (fAutoStart)
{
CoInitialize(NULL);
// Get a pointer to the IShellLink interface.
IShellLink* psl = NULL;
HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
CLSCTX_INPROC_SERVER, IID_IShellLink,
reinterpret_cast<void**>(&psl));
if (SUCCEEDED(hres))
{
// Get the current executable path
TCHAR pszExePath[MAX_PATH];
GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
TCHAR pszArgs[5] = TEXT("-min");
// Set the path to the shortcut target
psl->SetPath(pszExePath);
PathRemoveFileSpec(pszExePath);
psl->SetWorkingDirectory(pszExePath);
psl->SetShowCmd(SW_SHOWMINNOACTIVE);
psl->SetArguments(pszArgs);
// Query IShellLink for the IPersistFile interface for
// saving the shortcut in persistent storage.
IPersistFile* ppf = NULL;
hres = psl->QueryInterface(IID_IPersistFile,
reinterpret_cast<void**>(&ppf));
if (SUCCEEDED(hres))
{
WCHAR pwsz[MAX_PATH];
// Ensure that the string is ANSI.
MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH);
// Save the link by calling IPersistFile::Save.
hres = ppf->Save(pwsz, TRUE);
ppf->Release();
psl->Release();
CoUninitialize();
return true;
}
psl->Release();
}
CoUninitialize();
return false;
}
return true;
}
#elif defined(LINUX)
// Follow the Desktop Application Autostart Spec:
// http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
boost::filesystem::path static GetAutostartDir()
{
namespace fs = boost::filesystem;
char* pszConfigHome = getenv("XDG_CONFIG_HOME");
if (pszConfigHome) return fs::path(pszConfigHome) / "autostart";
char* pszHome = getenv("HOME");
if (pszHome) return fs::path(pszHome) / ".config" / "autostart";
return fs::path();
}
boost::filesystem::path static GetAutostartFilePath()
{
return GetAutostartDir() / "bitcoin.desktop";
}
bool GetStartOnSystemStartup()
{
boost::filesystem::ifstream optionFile(GetAutostartFilePath());
if (!optionFile.good())
return false;
// Scan through file for "Hidden=true":
std::string line;
while (!optionFile.eof())
{
getline(optionFile, line);
if (line.find("Hidden") != std::string::npos &&
line.find("true") != std::string::npos)
return false;
}
optionFile.close();
return true;
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
if (!fAutoStart)
boost::filesystem::remove(GetAutostartFilePath());
else
{
char pszExePath[MAX_PATH+1];
memset(pszExePath, 0, sizeof(pszExePath));
if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
return false;
boost::filesystem::create_directories(GetAutostartDir());
boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc);
if (!optionFile.good())
return false;
// Write a bitcoin.desktop file to the autostart directory:
optionFile << "[Desktop Entry]\n";
optionFile << "Type=Application\n";
optionFile << "Name=Bitcoin\n";
optionFile << "Exec=" << pszExePath << " -min\n";
optionFile << "Terminal=false\n";
optionFile << "Hidden=false\n";
optionFile.close();
}
return true;
}
#else
// TODO: OSX startup stuff; see:
// https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html
bool GetStartOnSystemStartup() { return false; }
bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
#endif
HelpMessageBox::HelpMessageBox(QWidget *parent) :
QMessageBox(parent)
{
header = tr("Bitcoin-Qt") + " " + tr("version") + " " +
QString::fromStdString(FormatFullVersion()) + "\n\n" +
tr("Usage:") + "\n" +
" bitcoin-qt [" + tr("command-line options") + "] " + "\n";
coreOptions = QString::fromStdString(HelpMessage());
uiOptions = tr("UI options") + ":\n" +
" -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" +
" -min " + tr("Start minimized") + "\n" +
" -splash " + tr("Show splash screen on startup (default: 1)") + "\n";
setWindowTitle(tr("Bitcoin-Qt"));
setTextFormat(Qt::PlainText);
// setMinimumWidth is ignored for QMessageBox so put in non-breaking spaces to make it wider.
setText(header + QString(QChar(0x2003)).repeated(50));
setDetailedText(coreOptions + "\n" + uiOptions);
}
void HelpMessageBox::printToConsole()
{
// On other operating systems, the expected action is to print the message to the console.
QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions;
fprintf(stdout, "%s", strUsage.toStdString().c_str());
}
void HelpMessageBox::showOrPrint()
{
#if defined(WIN32)
// On Windows, show a message box, as there is no stderr/stdout in windowed applications
exec();
#else
// On other operating systems, print help text to console
printToConsole();
#endif
}
} // namespace GUIUtil
|
#include "PeakRankModel.h"
extern const int num_RKH_combos = 6;
extern const int num_RKH_pairs = num_RKH_combos * num_RKH_combos;
extern const string combos[]={"NB","H","K","HK","R","RR"};
int calc_RKH_combo_idx (int r, int k, int h)
{
const int sum = r + k + h;
if (sum==0)
return 0; // no basics
if (sum == 1)
{
if (h)
return 1; // H only
if (k)
return 2; // K only
}
if (r==0) // KH, HH, KK ...
return 3;
if (r==1) // R, RK , RH ...
return 4;
return 5; // RR, RRK, RRR....
}
extern const float RKH_pair_matrix[6][6]={
{ 0.0, 1.0, 2.0, 3.0, 4.0, 5.0},
{ -1.0, 0.0, 2.0, 3.0, 4.0, 5.0},
{ -2.0, -2.0, 0.0, 2.0, 4.0, 5.0},
{ -3.0, -3.0, -2.0, 0.0, 3.0, 4.0},
{ -4.0, -4.0, -4.0, -3.0, 0.0, 4.0},
{ -5.0, -5.0, -5.0, -4.0, -4.0, 0.0} };
/**********************************************************************
This fills in all possible sequence features that can be used in any
of the models (these features are good for all fragments/mobility/
size/charge). The models can later choose to ignore some of these
features by asigning the weight 0. All features are derived directly
from the peptide sequence and concern the specified cut idx.
***********************************************************************/
void PeakRankModel::fill_advanced_peak_features(
const vector<int>& org_amino_acids,
int cut_idx,
mass_t cut_mass,
mass_t pm_with_19,
int spec_charge,
const FragmentType& fragment,
RankBoostSample& sample) const
{
const int length = org_amino_acids.size();
const int num_aas = model_aa_labels.size();
int r_idx=0;
int i;
vector<int> amino_acids;
convert_aas_to_model_aas(org_amino_acids, amino_acids);
if (amino_acids.size() != org_amino_acids.size())
{
cout << "Error: aa size mismatch!" << endl;
exit(1);
}
if (cut_idx<=0 || cut_idx>=amino_acids.size())
{
cout << "Error: cut_idx is bad!" << endl;
exit(1);
}
// need to use the special Idx variables and not the regular enumerations
const int HisIdx = session_aas_to_model_aas[His];
const int LysIdx = session_aas_to_model_aas[Lys];
const int ArgIdx = session_aas_to_model_aas[Arg];
const int SerIdx = session_aas_to_model_aas[Ser];
const int ThrIdx = session_aas_to_model_aas[Thr];
const int ProIdx = session_aas_to_model_aas[Pro];
const int GlyIdx = session_aas_to_model_aas[Gly];
const int AlaIdx = session_aas_to_model_aas[Ala];
const int LeuIdx = session_aas_to_model_aas[Leu];
const int AsnIdx = session_aas_to_model_aas[Asn];
const int AspIdx = session_aas_to_model_aas[Asp];
const int GluIdx = session_aas_to_model_aas[Glu];
sample.clear();
// special N C side aa indicators
int num_nH=0, num_cH=0;
int num_nK=0, num_cK=0;
int num_nR=0, num_cR=0;
for (i=0; i<cut_idx; i++)
{
if (amino_acids[i] == HisIdx)
num_nH++;
if (amino_acids[i] == LysIdx)
num_nK++;
if (amino_acids[i] == ArgIdx)
num_nR++;
}
for (i=cut_idx; i<length; i++)
{
if (amino_acids[i] == HisIdx)
num_cH++;
if (amino_acids[i] == LysIdx)
num_cK++;
if (amino_acids[i] == ArgIdx)
num_cR++;
}
// MASS / LOCATION FEATURES (REAL + BINARY)
const mass_t exp_peak_mass = fragment.calc_expected_mass(cut_mass,pm_with_19);
const mass_t min_obs_mass = calc_min_detected_mass(pm_with_19,spec_charge);
const mass_t max_obs_mass = (pm_with_19>max_detected_mass ? max_detected_mass : pm_with_19);
const float peak_mass_prop = ((exp_peak_mass - min_obs_mass)/(max_obs_mass - min_obs_mass));
const float rounded_peak_prop = 0.1*floor(peak_mass_prop * 10.0);
// give values within a resolution of 20 Da
const mass_t dis_from_min = 25.0*floor((exp_peak_mass - min_obs_mass)*0.04);
const mass_t dis_from_max = 25.0*floor((max_obs_mass - exp_peak_mass)*0.04);
const int RKH_n_combo_idx = calc_RKH_combo_idx(num_nR,num_nK,num_nH);
const int RKH_c_combo_idx = calc_RKH_combo_idx(num_cR,num_cK,num_cH);
const int RKH_pair_idx = (RKH_n_combo_idx * num_RKH_combos) + RKH_c_combo_idx;
const float RKH_liniar_pair_idx = RKH_pair_matrix[RKH_n_combo_idx][RKH_c_combo_idx];
const int n_aa = amino_acids[cut_idx-1];
const int c_aa = amino_acids[cut_idx];
// proportion of mass of the N/C fragments (special values are given to the first 3
// cuts on each side. If the cut is not in those regions, prop is assigned the
// index of the fifth in which it falls
int side_length=3;
if (length>=12) side_length=4;
if (length>=15) side_length=5;
float cut_prop;
if (cut_idx<=side_length)
{
cut_prop=(float)cut_idx;
}
else if (cut_idx>=length-side_length)
{
cut_prop=(float)(11+cut_idx-length);
}
else
{
cut_prop = 5.1+floor(3.0*(cut_mass/pm_with_19))*0.1;
}
// fill N RKH and C RKH
sample.add_real_feature(r_idx++,RKH_n_combo_idx);
sample.add_real_feature(r_idx++,RKH_c_combo_idx);
// peak prop
sample.add_real_feature(r_idx++,rounded_peak_prop);
sample.add_real_feature(r_idx+RKH_pair_idx,rounded_peak_prop);
r_idx+=num_RKH_pairs;
// fill dis features
if (dis_from_min<dis_from_max)
{
sample.add_real_feature(r_idx,dis_from_min);
r_idx++;
sample.add_real_feature(r_idx+RKH_pair_idx,dis_from_min);
r_idx+=(2*num_RKH_pairs+1);
}
else
{
r_idx+=(num_RKH_pairs+1);
sample.add_real_feature(r_idx,dis_from_max);
r_idx++;
sample.add_real_feature(r_idx+RKH_pair_idx,dis_from_max);
r_idx+=num_RKH_pairs;
}
// fill prop features
sample.add_real_feature(r_idx++,cut_prop);
sample.add_real_feature(r_idx+RKH_pair_idx,cut_prop);
r_idx+=num_RKH_pairs;
// fill prop X dis features
if (dis_from_min<dis_from_max)
{
if (dis_from_min<75.0)
sample.add_real_feature(r_idx,cut_prop);
r_idx++;
if (dis_from_min<150.0)
sample.add_real_feature(r_idx,cut_prop);
r_idx++;
if (dis_from_min<250.0)
sample.add_real_feature(r_idx,cut_prop);
r_idx++;
if (dis_from_min<=400.0)
sample.add_real_feature(r_idx,cut_prop);
r_idx++;
r_idx+=4;
}
else
{
r_idx+=4;
if (dis_from_max<75.0)
sample.add_real_feature(r_idx,cut_prop);
r_idx++;
if (dis_from_max<150.0)
sample.add_real_feature(r_idx,cut_prop);
r_idx++;
if (dis_from_max<250.0)
sample.add_real_feature(r_idx,cut_prop);
r_idx++;
if (dis_from_max<=400.0)
sample.add_real_feature(r_idx,cut_prop);
r_idx++;
}
// fill aa count features (up top 3 aa's away from cut)
vector<int> n_aa_counts, c_aa_counts;
n_aa_counts.resize(num_aas+1,0);
c_aa_counts.resize(num_aas+1,0);
for (i=0; i<cut_idx-3; i++)
n_aa_counts[amino_acids[i]]++;
for (i=cut_idx+3; i<length; i++)
c_aa_counts[amino_acids[i]]++;
int a;
for (a=0; a<num_aas; a++)
sample.add_real_feature(r_idx++,n_aa_counts[a]);
for (a=0; a<num_aas; a++)
sample.add_real_feature(r_idx++,c_aa_counts[a]);
// including the aas up top the count
int start_cut = cut_idx-3;
if (start_cut<0)
start_cut=0;
for (i=start_cut; i<cut_idx; i++)
n_aa_counts[amino_acids[i]]++;
int end_cut = cut_idx+3;
if (end_cut>length)
end_cut = length;
for (i=cut_idx; i<end_cut; i++)
c_aa_counts[amino_acids[i]]++;
for (a=0; a<num_aas; a++)
sample.add_real_feature(r_idx++,n_aa_counts[a]);
for (a=0; a<num_aas; a++)
sample.add_real_feature(r_idx++,c_aa_counts[a]);
// fill aa flanking features N side
if (cut_idx>0)
sample.add_real_feature(r_idx+amino_acids[cut_idx-1],cut_prop);
r_idx+=num_aas;
if (cut_idx>1)
sample.add_real_feature(r_idx+amino_acids[cut_idx-2],cut_prop);
r_idx+=num_aas;
if (cut_idx>2)
sample.add_real_feature(r_idx+amino_acids[cut_idx-3],cut_prop);
r_idx+=num_aas;
// fill aa flanking features C side
if (cut_idx<length)
sample.add_real_feature(r_idx+amino_acids[cut_idx],cut_prop);
r_idx+=num_aas;
if (cut_idx<length-1)
sample.add_real_feature(r_idx+amino_acids[cut_idx+1],cut_prop);
r_idx+=num_aas;
if (cut_idx<length-2)
sample.add_real_feature(r_idx+amino_acids[cut_idx+2],cut_prop);
r_idx+=num_aas;
// fill cut pair features X-Y
sample.add_real_feature(r_idx+(n_aa*num_aas+c_aa),cut_prop);
r_idx+=(num_aas*num_aas);
// fill cut pair features X-Y
sample.add_real_feature(r_idx+(n_aa*num_aas+c_aa),rounded_peak_prop);
r_idx+=(num_aas*num_aas);
// fill flanking aa info with RKH_pair data
// fill aa flanking features N side
if (cut_idx>0)
sample.add_real_feature(r_idx+amino_acids[cut_idx-1],RKH_liniar_pair_idx);
r_idx+=num_aas;
if (cut_idx>1)
sample.add_real_feature(r_idx+amino_acids[cut_idx-2],RKH_liniar_pair_idx);
r_idx+=num_aas;
if (cut_idx>2)
sample.add_real_feature(r_idx+amino_acids[cut_idx-3],RKH_liniar_pair_idx);
r_idx+=num_aas;
// fill aa flanking features C side
if (cut_idx<length)
sample.add_real_feature(r_idx+amino_acids[cut_idx],RKH_liniar_pair_idx);
r_idx+=num_aas;
if (cut_idx<length-1)
sample.add_real_feature(r_idx+amino_acids[cut_idx+1],RKH_liniar_pair_idx);
r_idx+=num_aas;
if (cut_idx<length-2)
sample.add_real_feature(r_idx+amino_acids[cut_idx+2],RKH_liniar_pair_idx);
r_idx+=num_aas;
// fill flanking aa info with peak prop data
// fill aa flanking features N side
if (cut_idx>0)
sample.add_real_feature(r_idx+amino_acids[cut_idx-1],rounded_peak_prop);
r_idx+=num_aas;
if (cut_idx>1)
sample.add_real_feature(r_idx+amino_acids[cut_idx-2],rounded_peak_prop);
r_idx+=num_aas;
if (cut_idx>2)
sample.add_real_feature(r_idx+amino_acids[cut_idx-3],rounded_peak_prop);
r_idx+=num_aas;
// fill aa flanking features C side
if (cut_idx<length)
sample.add_real_feature(r_idx+amino_acids[cut_idx],rounded_peak_prop);
r_idx+=num_aas;
if (cut_idx<length-1)
sample.add_real_feature(r_idx+amino_acids[cut_idx+1],rounded_peak_prop);
r_idx+=num_aas;
if (cut_idx<length-2)
sample.add_real_feature(r_idx+amino_acids[cut_idx+2],rounded_peak_prop);
r_idx+=num_aas;
// add features for flanking pairs of amino acids
if (cut_idx>1)
sample.add_real_feature(r_idx+amino_acids[cut_idx-2]*num_aas+amino_acids[cut_idx-1],cut_prop);
r_idx+=num_aas*num_aas;
if (cut_idx<length-2)
sample.add_real_feature(r_idx+amino_acids[cut_idx]*num_aas+amino_acids[cut_idx+1],cut_prop);
r_idx+=num_aas*num_aas;
// X != R
// features of the form |LXK |LXXK |LXXXK |LXXXXK
if (cut_idx < length-2 &&
amino_acids[cut_idx+2]==LysIdx &&
amino_acids[cut_idx] != LysIdx && amino_acids[cut_idx] != ArgIdx &&
amino_acids[cut_idx+1] != ArgIdx)
sample.add_real_feature(r_idx+amino_acids[cut_idx],cut_prop);
r_idx+=num_aas;
if (cut_idx < length-3 &&
amino_acids[cut_idx+3]==LysIdx &&
amino_acids[cut_idx] != LysIdx && amino_acids[cut_idx] != ArgIdx &&
amino_acids[cut_idx+1] != ArgIdx && amino_acids[cut_idx+2] != ArgIdx)
sample.add_real_feature(r_idx+amino_acids[cut_idx],cut_prop);
r_idx+=num_aas;
if (cut_idx < length-4 &&
amino_acids[cut_idx+4]==LysIdx &&
amino_acids[cut_idx] != LysIdx && amino_acids[cut_idx] != ArgIdx &&
amino_acids[cut_idx+1] != ArgIdx && amino_acids[cut_idx+2] != ArgIdx &&
amino_acids[cut_idx+3] != ArgIdx)
sample.add_real_feature(r_idx+amino_acids[cut_idx],cut_prop);
r_idx+=num_aas;
if (cut_idx < length-5 &&
amino_acids[cut_idx+5]==LysIdx &&
amino_acids[cut_idx] != LysIdx && amino_acids[cut_idx] != ArgIdx &&
amino_acids[cut_idx+1] != ArgIdx && amino_acids[cut_idx+2] != ArgIdx &&
amino_acids[cut_idx+3] != ArgIdx && amino_acids[cut_idx+4] != ArgIdx )
sample.add_real_feature(r_idx+amino_acids[cut_idx],cut_prop);
r_idx+=num_aas;
// features of the form |XLXK |XLXXK |XLXXXK |XLXXXXK
if (cut_idx < length-3 &&
amino_acids[cut_idx+3]==LysIdx &&
amino_acids[cut_idx+1] != LysIdx && amino_acids[cut_idx+1] != ArgIdx &&
amino_acids[cut_idx] != ArgIdx && amino_acids[cut_idx+2] != ArgIdx
&& amino_acids[cut_idx] != LysIdx )
sample.add_real_feature(r_idx+amino_acids[cut_idx+1],cut_prop);
r_idx+=num_aas;
if (cut_idx < length-4 &&
amino_acids[cut_idx+4]==LysIdx &&
amino_acids[cut_idx+1] != LysIdx && amino_acids[cut_idx+1] != ArgIdx &&
amino_acids[cut_idx] != ArgIdx && amino_acids[cut_idx+2] != ArgIdx &&
amino_acids[cut_idx+3] != ArgIdx && amino_acids[cut_idx] != LysIdx )
sample.add_real_feature(r_idx+amino_acids[cut_idx+1],cut_prop);
r_idx+=num_aas;
if (cut_idx < length-5 &&
amino_acids[cut_idx+5]==LysIdx &&
amino_acids[cut_idx+1] != LysIdx && amino_acids[cut_idx+1] != ArgIdx &&
amino_acids[cut_idx] != ArgIdx && amino_acids[cut_idx+2] != ArgIdx &&
amino_acids[cut_idx+3] != ArgIdx && amino_acids[cut_idx+4] != ArgIdx
&& amino_acids[cut_idx] != LysIdx )
sample.add_real_feature(r_idx+amino_acids[cut_idx+1],cut_prop);
r_idx+=num_aas;
if (cut_idx < length-6 &&
amino_acids[cut_idx+6]==LysIdx &&
amino_acids[cut_idx+1] != LysIdx && amino_acids[cut_idx+1] != ArgIdx &&
amino_acids[cut_idx] != ArgIdx && amino_acids[cut_idx+2] != ArgIdx &&
amino_acids[cut_idx+3] != ArgIdx && amino_acids[cut_idx+4] != ArgIdx &&
amino_acids[cut_idx+5] != ArgIdx && amino_acids[cut_idx] != LysIdx )
sample.add_real_feature(r_idx+amino_acids[cut_idx+1],cut_prop);
r_idx+=num_aas;
// features of the form L|XK L|XXK L|XXXK L|XXXXK
if (cut_idx>0 &&cut_idx < length-1 &&
amino_acids[cut_idx+1]==LysIdx &&
amino_acids[cut_idx-1] != LysIdx && amino_acids[cut_idx-1] != ArgIdx &&
amino_acids[cut_idx] != ArgIdx)
sample.add_real_feature(r_idx+amino_acids[cut_idx-1],cut_prop);
r_idx+=num_aas;
if (cut_idx>0 &&cut_idx < length-2 &&
amino_acids[cut_idx+2]==LysIdx &&
amino_acids[cut_idx-1] != LysIdx && amino_acids[cut_idx-1] != ArgIdx &&
amino_acids[cut_idx] != ArgIdx && amino_acids[cut_idx+1] != ArgIdx)
sample.add_real_feature(r_idx+amino_acids[cut_idx-1],cut_prop);
r_idx+=num_aas;
if (cut_idx>0 &&cut_idx < length-3 &&
amino_acids[cut_idx+3]==LysIdx &&
amino_acids[cut_idx-1] != LysIdx && amino_acids[cut_idx-1] != ArgIdx &&
amino_acids[cut_idx+1] != ArgIdx && amino_acids[cut_idx+2] != ArgIdx &&
amino_acids[cut_idx] != ArgIdx)
sample.add_real_feature(r_idx+amino_acids[cut_idx-1],cut_prop);
r_idx+=num_aas;
if (cut_idx>0 && cut_idx < length-4 &&
amino_acids[cut_idx+4]==LysIdx &&
amino_acids[cut_idx-1] != LysIdx && amino_acids[cut_idx-1] != ArgIdx &&
amino_acids[cut_idx+1] != ArgIdx && amino_acids[cut_idx+2] != ArgIdx &&
amino_acids[cut_idx+3] != ArgIdx && amino_acids[cut_idx] != ArgIdx )
sample.add_real_feature(r_idx+amino_acids[cut_idx-1],cut_prop);
r_idx+=num_aas;
// features of the form |LXR |LXXR |LXXXR |LXXXXR
if (cut_idx < length-2 &&
amino_acids[cut_idx+2]==ArgIdx &&
amino_acids[cut_idx] != LysIdx && amino_acids[cut_idx] != ArgIdx &&
amino_acids[cut_idx+1] != ArgIdx)
sample.add_real_feature(r_idx+amino_acids[cut_idx],cut_prop);
r_idx+=num_aas;
if (cut_idx < length-3 &&
amino_acids[cut_idx+3]==ArgIdx &&
amino_acids[cut_idx] != LysIdx && amino_acids[cut_idx] != ArgIdx &&
amino_acids[cut_idx+1] != ArgIdx && amino_acids[cut_idx+2] != ArgIdx)
sample.add_real_feature(r_idx+amino_acids[cut_idx],cut_prop);
r_idx+=num_aas;
if (cut_idx < length-4 &&
amino_acids[cut_idx+4]==ArgIdx &&
amino_acids[cut_idx] != LysIdx && amino_acids[cut_idx] != ArgIdx &&
amino_acids[cut_idx+1] != ArgIdx && amino_acids[cut_idx+2] != ArgIdx &&
amino_acids[cut_idx+3] != ArgIdx)
sample.add_real_feature(r_idx+amino_acids[cut_idx],cut_prop);
r_idx+=num_aas;
if (cut_idx < length-5 &&
amino_acids[cut_idx+5]==ArgIdx &&
amino_acids[cut_idx] != LysIdx && amino_acids[cut_idx] != ArgIdx &&
amino_acids[cut_idx+1] != ArgIdx && amino_acids[cut_idx+2] != ArgIdx &&
amino_acids[cut_idx+3] != ArgIdx && amino_acids[cut_idx+4] != ArgIdx )
sample.add_real_feature(r_idx+amino_acids[cut_idx],cut_prop);
r_idx+=num_aas;
// features of the form |XLXR |XLXXR |XLXXXR |XLXXXXR
if (cut_idx < length-3 &&
amino_acids[cut_idx+3]==ArgIdx &&
amino_acids[cut_idx+1] != LysIdx && amino_acids[cut_idx+1] != ArgIdx &&
amino_acids[cut_idx] != ArgIdx && amino_acids[cut_idx] != LysIdx &&
amino_acids[cut_idx+2] != ArgIdx)
sample.add_real_feature(r_idx+amino_acids[cut_idx+1],cut_prop);
r_idx+=num_aas;
if (cut_idx < length-4 &&
amino_acids[cut_idx+4]==ArgIdx &&
amino_acids[cut_idx+1] != LysIdx && amino_acids[cut_idx+1] != ArgIdx &&
amino_acids[cut_idx] != ArgIdx && amino_acids[cut_idx+2] != ArgIdx &&
amino_acids[cut_idx+3] != ArgIdx && amino_acids[cut_idx] != LysIdx )
sample.add_real_feature(r_idx+amino_acids[cut_idx+1],cut_prop);
r_idx+=num_aas;
if (cut_idx < length-5 &&
amino_acids[cut_idx+5]==ArgIdx &&
amino_acids[cut_idx+1] != LysIdx && amino_acids[cut_idx+1] != ArgIdx &&
amino_acids[cut_idx] != ArgIdx && amino_acids[cut_idx+2] != ArgIdx &&
amino_acids[cut_idx+3] != ArgIdx && amino_acids[cut_idx+4] != ArgIdx &&
amino_acids[cut_idx] != LysIdx )
sample.add_real_feature(r_idx+amino_acids[cut_idx+1],cut_prop);
r_idx+=num_aas;
if (cut_idx < length-6 &&
amino_acids[cut_idx+6]==ArgIdx &&
amino_acids[cut_idx+1] != LysIdx && amino_acids[cut_idx+1] != ArgIdx &&
amino_acids[cut_idx] != ArgIdx && amino_acids[cut_idx+2] != ArgIdx &&
amino_acids[cut_idx+3] != ArgIdx && amino_acids[cut_idx+4] != ArgIdx &&
amino_acids[cut_idx+5] != ArgIdx && amino_acids[cut_idx] != LysIdx )
sample.add_real_feature(r_idx+amino_acids[cut_idx+1],cut_prop);
r_idx+=num_aas;
// features of the form L|XR L|XXR L|XXXR L|XXXXR
if (cut_idx>0 &&cut_idx < length-1 &&
amino_acids[cut_idx+1]==ArgIdx &&
amino_acids[cut_idx-1] != LysIdx && amino_acids[cut_idx-1] != ArgIdx &&
amino_acids[cut_idx] != ArgIdx)
sample.add_real_feature(r_idx+amino_acids[cut_idx-1],cut_prop);
r_idx+=num_aas;
if (cut_idx>0 &&cut_idx < length-2 &&
amino_acids[cut_idx+2]==ArgIdx &&
amino_acids[cut_idx-1] != LysIdx && amino_acids[cut_idx-1] != ArgIdx &&
amino_acids[cut_idx] != ArgIdx && amino_acids[cut_idx+1] != ArgIdx)
sample.add_real_feature(r_idx+amino_acids[cut_idx-1],cut_prop);
r_idx+=num_aas;
if (cut_idx>0 &&cut_idx < length-3 &&
amino_acids[cut_idx+3]==ArgIdx &&
amino_acids[cut_idx-1] != LysIdx && amino_acids[cut_idx-1] != ArgIdx &&
amino_acids[cut_idx+1] != ArgIdx && amino_acids[cut_idx+2] != ArgIdx &&
amino_acids[cut_idx] != ArgIdx)
sample.add_real_feature(r_idx+amino_acids[cut_idx-1],cut_prop);
r_idx+=num_aas;
if (cut_idx>0 && cut_idx < length-4 &&
amino_acids[cut_idx+4]==ArgIdx &&
amino_acids[cut_idx-1] != LysIdx && amino_acids[cut_idx-1] != ArgIdx &&
amino_acids[cut_idx+1] != ArgIdx && amino_acids[cut_idx+2] != ArgIdx &&
amino_acids[cut_idx+3] != ArgIdx && amino_acids[cut_idx] != ArgIdx )
sample.add_real_feature(r_idx+amino_acids[cut_idx-1],cut_prop);
r_idx+=num_aas;
// features of the form KXF KXXF KXXXF KXXXXF
if (cut_idx>2 && amino_acids[cut_idx-3] == LysIdx &&amino_acids[cut_idx-2] != ArgIdx)
sample.add_real_feature(r_idx+amino_acids[cut_idx-1],cut_prop);
r_idx+=num_aas;
if (cut_idx>3 && amino_acids[cut_idx-4] == LysIdx && amino_acids[cut_idx-3] != ArgIdx &&
amino_acids[cut_idx-2] != ArgIdx)
sample.add_real_feature(r_idx+amino_acids[cut_idx-1],cut_prop);
r_idx+=num_aas;
if (cut_idx>4 && amino_acids[cut_idx-5] == LysIdx && amino_acids[cut_idx-4] != ArgIdx &&
amino_acids[cut_idx-3] != ArgIdx && amino_acids[cut_idx-2] != ArgIdx)
sample.add_real_feature(r_idx+amino_acids[cut_idx-1],cut_prop);
r_idx+=num_aas;
if (cut_idx>5 && amino_acids[cut_idx-6] == LysIdx && amino_acids[cut_idx-5] != ArgIdx &&
amino_acids[cut_idx-4] != ArgIdx && amino_acids[cut_idx-3] != ArgIdx &&
amino_acids[cut_idx-2] != ArgIdx)
sample.add_real_feature(r_idx+amino_acids[cut_idx-1],cut_prop);
r_idx+=num_aas;
// features of the form KXFX KXXFX KXXXFX KXXXXFX
if (cut_idx>3 && amino_acids[cut_idx-4] == LysIdx && amino_acids[cut_idx-3] != ArgIdx &&
amino_acids[cut_idx-1] != ArgIdx)
sample.add_real_feature(r_idx+amino_acids[cut_idx-2],cut_prop);
r_idx+=num_aas;
if (cut_idx>4 && amino_acids[cut_idx-5] == LysIdx && amino_acids[cut_idx-4] != ArgIdx &&
amino_acids[cut_idx-3] != ArgIdx && amino_acids[cut_idx-1] != ArgIdx)
sample.add_real_feature(r_idx+amino_acids[cut_idx-2],cut_prop);
r_idx+=num_aas;
if (cut_idx>5 && amino_acids[cut_idx-6] == LysIdx && amino_acids[cut_idx-5] != ArgIdx &&
amino_acids[cut_idx-4] != ArgIdx && amino_acids[cut_idx-3] != ArgIdx &&
amino_acids[cut_idx-1] != ArgIdx)
sample.add_real_feature(r_idx+amino_acids[cut_idx-2],cut_prop);
r_idx+=num_aas;
if (cut_idx>6 && amino_acids[cut_idx-7] == LysIdx && amino_acids[cut_idx-6] != ArgIdx &&
amino_acids[cut_idx-5] != ArgIdx && amino_acids[cut_idx-4] != ArgIdx &&
amino_acids[cut_idx-3] != ArgIdx && amino_acids[cut_idx-1] != ArgIdx)
sample.add_real_feature(r_idx+amino_acids[cut_idx-2],cut_prop);
r_idx+=num_aas;
// features of the form KX|F KXX|F KXXX|F KXXXX|F
if (cut_idx>1 && cut_idx<length && amino_acids[cut_idx-2] == LysIdx &&
amino_acids[cut_idx-1] != ArgIdx)
sample.add_real_feature(r_idx+amino_acids[cut_idx],cut_prop);
r_idx+=num_aas;
if (cut_idx>2 && cut_idx<length && amino_acids[cut_idx-3] == LysIdx &&
amino_acids[cut_idx-2] != ArgIdx && amino_acids[cut_idx-1] != ArgIdx)
sample.add_real_feature(r_idx+amino_acids[cut_idx],cut_prop);
r_idx+=num_aas;
if (cut_idx>3 && cut_idx<length && amino_acids[cut_idx-4] == LysIdx &&
amino_acids[cut_idx-3] != ArgIdx && amino_acids[cut_idx-2] != ArgIdx &&
amino_acids[cut_idx-1] != ArgIdx)
sample.add_real_feature(r_idx+amino_acids[cut_idx],cut_prop);
r_idx+=num_aas;
if (cut_idx>4 && cut_idx<length && amino_acids[cut_idx-5] == LysIdx &&
amino_acids[cut_idx-4] != ArgIdx && amino_acids[cut_idx-3] != ArgIdx &&
amino_acids[cut_idx-2] != ArgIdx && amino_acids[cut_idx-1] != ArgIdx)
sample.add_real_feature(r_idx+amino_acids[cut_idx],cut_prop);
r_idx+=num_aas;
// features of the form RXF RXXF RXXXF RXXXXF
if (cut_idx>2 && amino_acids[cut_idx-3] == ArgIdx &&amino_acids[cut_idx-2] != ArgIdx)
sample.add_real_feature(r_idx+amino_acids[cut_idx-1],cut_prop);
r_idx+=num_aas;
if (cut_idx>3 && amino_acids[cut_idx-4] == ArgIdx && amino_acids[cut_idx-3] != ArgIdx &&
amino_acids[cut_idx-2] != ArgIdx)
sample.add_real_feature(r_idx+amino_acids[cut_idx-1],cut_prop);
r_idx+=num_aas;
if (cut_idx>4 && amino_acids[cut_idx-5] == ArgIdx && amino_acids[cut_idx-4] != ArgIdx &&
amino_acids[cut_idx-3] != ArgIdx && amino_acids[cut_idx-2] != ArgIdx)
sample.add_real_feature(r_idx+amino_acids[cut_idx-1],cut_prop);
r_idx+=num_aas;
if (cut_idx>5 && amino_acids[cut_idx-6] == ArgIdx && amino_acids[cut_idx-5] != ArgIdx &&
amino_acids[cut_idx-4] != ArgIdx && amino_acids[cut_idx-3] != ArgIdx &&
amino_acids[cut_idx-2] != ArgIdx)
sample.add_real_feature(r_idx+amino_acids[cut_idx-1],cut_prop);
r_idx+=num_aas;
// features of the form RXFX RXXFX RXXXFX RXXXXFX
if (cut_idx>3 && amino_acids[cut_idx-4] == ArgIdx && amino_acids[cut_idx-3] != ArgIdx &&
amino_acids[cut_idx-1] != ArgIdx)
sample.add_real_feature(r_idx+amino_acids[cut_idx-2],cut_prop);
r_idx+=num_aas;
if (cut_idx>4 && amino_acids[cut_idx-5] == ArgIdx && amino_acids[cut_idx-4] != ArgIdx &&
amino_acids[cut_idx-3] != ArgIdx && amino_acids[cut_idx-1] != ArgIdx)
sample.add_real_feature(r_idx+amino_acids[cut_idx-2],cut_prop);
r_idx+=num_aas;
if (cut_idx>5 && amino_acids[cut_idx-6] == ArgIdx && amino_acids[cut_idx-5] != ArgIdx &&
amino_acids[cut_idx-4] != ArgIdx && amino_acids[cut_idx-3] != ArgIdx &&
amino_acids[cut_idx-1] != ArgIdx)
sample.add_real_feature(r_idx+amino_acids[cut_idx-2],cut_prop);
r_idx+=num_aas;
if (cut_idx>6 && amino_acids[cut_idx-7] == ArgIdx && amino_acids[cut_idx-6] != ArgIdx &&
amino_acids[cut_idx-5] != ArgIdx && amino_acids[cut_idx-4] != ArgIdx &&
amino_acids[cut_idx-3] != ArgIdx && amino_acids[cut_idx-1] != ArgIdx)
sample.add_real_feature(r_idx+amino_acids[cut_idx-2],cut_prop);
r_idx+=num_aas;
// features of the form RX|F RXX|F RXXX|F RXXXX|F
if (cut_idx>1 && cut_idx<length && amino_acids[cut_idx-2] == ArgIdx &&
amino_acids[cut_idx-1] != ArgIdx)
sample.add_real_feature(r_idx+amino_acids[cut_idx],cut_prop);
r_idx+=num_aas;
if (cut_idx>2 && cut_idx<length && amino_acids[cut_idx-3] == ArgIdx &&
amino_acids[cut_idx-2] != ArgIdx && amino_acids[cut_idx-1] != ArgIdx)
sample.add_real_feature(r_idx+amino_acids[cut_idx],cut_prop);
r_idx+=num_aas;
if (cut_idx>3 && cut_idx<length && amino_acids[cut_idx-4] == ArgIdx &&
amino_acids[cut_idx-3] != ArgIdx && amino_acids[cut_idx-2] != ArgIdx &&
amino_acids[cut_idx-1] != ArgIdx)
sample.add_real_feature(r_idx+amino_acids[cut_idx],cut_prop);
r_idx+=num_aas;
if (cut_idx>4 && cut_idx<length && amino_acids[cut_idx-5] == ArgIdx &&
amino_acids[cut_idx-4] != ArgIdx && amino_acids[cut_idx-3] != ArgIdx &&
amino_acids[cut_idx-2] != ArgIdx && amino_acids[cut_idx-1] != ArgIdx)
sample.add_real_feature(r_idx+amino_acids[cut_idx],cut_prop);
r_idx+=num_aas;
// Add sepcial C-terminal features
const int c_cut_dis = length - cut_idx;
if (c_cut_dis<=5 && amino_acids[length-1]==LysIdx)
{
if (c_aa_counts[LeuIdx]>0 &&
(c_aa_counts[AspIdx]+c_aa_counts[GluIdx]>0 &&
c_aa_counts[LeuIdx] + c_aa_counts[GluIdx] + +c_aa_counts[AspIdx] +
c_aa_counts[LysIdx] == c_cut_dis) )
sample.add_real_feature(r_idx,c_cut_dis);
r_idx++;
if (c_aa_counts[LeuIdx]>0 && c_aa_counts[AlaIdx]>0 &&
c_aa_counts[LeuIdx] + c_aa_counts[AlaIdx] + c_aa_counts[LysIdx] == c_cut_dis)
sample.add_real_feature(r_idx,c_cut_dis);
r_idx++;
if (c_cut_dis>=3 && c_aa_counts[LeuIdx] + c_aa_counts[LysIdx] + c_aa_counts[GluIdx] +
c_aa_counts[AspIdx] == c_cut_dis-1)
sample.add_real_feature(r_idx,c_cut_dis);
r_idx++;
}
else
r_idx+=3;
if (amino_acids[length-1]==ArgIdx && cut_idx<length-1)
{
if (c_aa_counts[LeuIdx] + c_aa_counts[ArgIdx] + c_aa_counts[GluIdx] +
c_aa_counts[AspIdx] == c_cut_dis)
sample.add_real_feature(r_idx,c_cut_dis);
}
r_idx++;
}
void push_back_all_RHK_pairs(vector<string>& real_feature_names, string prefix_label)
{
int n;
for (n=0; n<num_RKH_combos; n++)
{
int c;
for (c=0; c<num_RKH_combos; c++)
{
string label = prefix_label + " " + combos[n] + "/" + combos[c];
real_feature_names.push_back(label);
}
}
}
void PeakRankModel::set_advanced_feature_names()
{
const int num_aas = this->get_num_model_aas();
int i;
real_feature_names.clear();
real_feature_stage_idxs.clear();
real_feature_names.push_back("N RKH LEVEL");
real_feature_names.push_back("C RKH LEVEL");
real_feature_names.push_back("PROP PEAK MASS IN VIS RANGE");
push_back_all_RHK_pairs(real_feature_names,"PROP PEAK MASS IN VIS RANGE");
real_feature_names.push_back("DIS FROM MIN");
push_back_all_RHK_pairs(real_feature_names,"DIS FROM MIN");
real_feature_names.push_back("DIS FROM MAX");
push_back_all_RHK_pairs(real_feature_names,"DIS FROM MAX");
real_feature_names.push_back("CUT POS");
push_back_all_RHK_pairs(real_feature_names,"CUT POS");
real_feature_names.push_back("DIS MIN<75, CUT POS");
real_feature_names.push_back("DIS MIN<150, CUT POS");
real_feature_names.push_back("DIS MIN<250, CUT POS");
real_feature_names.push_back("DIS MIN<=400, CUT POS");
real_feature_names.push_back("DIS MAX<75, CUT POS");
real_feature_names.push_back("DIS MAX<150, CUT POS");
real_feature_names.push_back("DIS MAX<250, CUT POS");
real_feature_names.push_back("DIS MAX<=400, CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back("#N-SIDE " + model_aa_labels[i] + "(without flanking 3)");
for (i=0; i<num_aas; i++)
real_feature_names.push_back("#C-SIDE " + model_aa_labels[i] + "(without flanking 3)");
for (i=0; i<num_aas; i++)
real_feature_names.push_back("#N-SIDE " + model_aa_labels[i]);
for (i=0; i<num_aas; i++)
real_feature_names.push_back("#C-SIDE " + model_aa_labels[i]);
for (i=0; i<num_aas; i++)
real_feature_names.push_back("CUT -1 = " + model_aa_labels[i] + ", CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back("CUT -2 = " + model_aa_labels[i] + ", CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back("CUT -3 = " + model_aa_labels[i] + ", CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back("CUT +1 = " + model_aa_labels[i] + ", CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back("CUT +2 = " + model_aa_labels[i] + ", CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back("CUT +3 = " + model_aa_labels[i] + ", CUT POS");
for (i=0; i<num_aas; i++)
{
int j;
for (j=0; j<num_aas; j++)
real_feature_names.push_back("CUT IS " + model_aa_labels[i] + "-" + model_aa_labels[j] + ", CUT POS");
}
for (i=0; i<num_aas; i++)
{
int j;
for (j=0; j<num_aas; j++)
real_feature_names.push_back("CUT IS " + model_aa_labels[i] + "-" + model_aa_labels[j] + ", PEAK PROP");
}
for (i=0; i<num_aas; i++)
real_feature_names.push_back("CUT -1 = " + model_aa_labels[i] + ", RHK LEVEL");
for (i=0; i<num_aas; i++)
real_feature_names.push_back("CUT -2 = " + model_aa_labels[i] + ", RHK LEVEL");
for (i=0; i<num_aas; i++)
real_feature_names.push_back("CUT -3 = " + model_aa_labels[i] + ", RHK LEVEL");
for (i=0; i<num_aas; i++)
real_feature_names.push_back("CUT +1 = " + model_aa_labels[i] + ", RHK LEVEL");
for (i=0; i<num_aas; i++)
real_feature_names.push_back("CUT +2 = " + model_aa_labels[i] + ", RHK LEVEL");
for (i=0; i<num_aas; i++)
real_feature_names.push_back("CUT +3 = " + model_aa_labels[i] + ", RHK LEVEL");
for (i=0; i<num_aas; i++)
real_feature_names.push_back("CUT -1 = " + model_aa_labels[i] + ", PEAK PROP");
for (i=0; i<num_aas; i++)
real_feature_names.push_back("CUT -2 = " + model_aa_labels[i] + ", PEAK PROP");
for (i=0; i<num_aas; i++)
real_feature_names.push_back("CUT -3 = " + model_aa_labels[i] + ", PEAK PROP");
for (i=0; i<num_aas; i++)
real_feature_names.push_back("CUT +1 = " + model_aa_labels[i] + ", PEAK PROP");
for (i=0; i<num_aas; i++)
real_feature_names.push_back("CUT +2 = " + model_aa_labels[i] + ", PEAK PROP");
for (i=0; i<num_aas; i++)
real_feature_names.push_back("CUT +3 = " + model_aa_labels[i] + ", PEAK PROP");
for (i=0; i<num_aas; i++)
{
int j;
for (j=0; j<num_aas; j++)
real_feature_names.push_back(model_aa_labels[i] + model_aa_labels[j] + " BEFORE CUT, CUT POS");
}
for (i=0; i<num_aas; i++)
{
int j;
for (j=0; j<num_aas; j++)
real_feature_names.push_back(model_aa_labels[i] + model_aa_labels[j] + " AFTER CUT, CUT POS");
}
for (i=0; i<num_aas; i++)
real_feature_names.push_back( "|"+ model_aa_labels[i] + "XK, CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( "|"+ model_aa_labels[i] + "XXK, CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( "|"+ model_aa_labels[i] + "XXXK, CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( "|"+ model_aa_labels[i] + "XXXXK, CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( "|X"+ model_aa_labels[i] + "XK, CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( "|X"+ model_aa_labels[i] + "XXK, CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( "|X"+ model_aa_labels[i] + "XXXK, CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( "|X"+ model_aa_labels[i] + "XXXXK, CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( model_aa_labels[i] + "|XK, CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( model_aa_labels[i] + "|XXK, CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( model_aa_labels[i] + "|XXXK, CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( model_aa_labels[i] + "|XXXXK, CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( "|"+ model_aa_labels[i] + "XR, CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( "|"+ model_aa_labels[i] + "XXR, CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( "|"+ model_aa_labels[i] + "XXXR, CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( "|"+ model_aa_labels[i] + "XXXXR, CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( "|X"+ model_aa_labels[i] + "XR, CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( "|X"+ model_aa_labels[i] + "XXR, CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( "|X"+ model_aa_labels[i] + "XXXR, CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( "|X"+ model_aa_labels[i] + "XXXXR, CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( model_aa_labels[i] + "|XR, CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( model_aa_labels[i] + "|XXR, CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( model_aa_labels[i] + "|XXXR, CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( model_aa_labels[i] + "|XXXXR, CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( "KX" + model_aa_labels[i] + "|, CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( "KXX" + model_aa_labels[i] + "|, CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( "KXXX" + model_aa_labels[i] + "|, CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( "KXXXX" + model_aa_labels[i] + "|, CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( "KX" + model_aa_labels[i] + "X|, CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( "KXX" + model_aa_labels[i] + "X|, CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( "KXXX" + model_aa_labels[i] + "X|, CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( "KXXXX" + model_aa_labels[i] + "X|, CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( "KX|" + model_aa_labels[i] + ", CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( "KXX|" + model_aa_labels[i] + ", CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( "KXXX|" + model_aa_labels[i] + ", CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( "KXXXX|" + model_aa_labels[i] + ", CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( "RX" + model_aa_labels[i] + "|, CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( "RXX" + model_aa_labels[i] + "|, CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( "RXXX" + model_aa_labels[i] + "|, CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( "RXXXX" + model_aa_labels[i] + "|, CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( "RX" + model_aa_labels[i] + "X|, CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( "RXX" + model_aa_labels[i] + "X|, CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( "RXXX" + model_aa_labels[i] + "X|, CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( "RXXXX" + model_aa_labels[i] + "X|, CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( "RX|" + model_aa_labels[i] + ", CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( "RXX|" + model_aa_labels[i] + ", CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( "RXXX|" + model_aa_labels[i] + ", CUT POS");
for (i=0; i<num_aas; i++)
real_feature_names.push_back( "RXXXX|" + model_aa_labels[i] + ", CUT POS");
real_feature_names.push_back("|[LD/EK] - permuted");
real_feature_names.push_back("|[LAK] - permuted");
real_feature_names.push_back("|[LDEK] - permuted with one X");
real_feature_names.push_back("|[LDER] - permuted");
}
|
#include <config.hpp> // for ensure_config
#include <fs.hpp>
#include <getopt.h>
#include <libgen.h>
#include <llarp.h>
#include <logger.hpp>
#include <signal.h>
#include <string>
#include <iostream>
#ifdef _WIN32
#define wmin(x, y) (((x) < (y)) ? (x) : (y))
#define MIN wmin
#endif
struct llarp_main *ctx = 0;
void
handle_signal(int sig)
{
if(ctx)
llarp_main_signal(ctx, sig);
}
int
printHelp(const char *argv0, int code = 1)
{
std::cout << "usage: " << argv0 << " [-h] [-v] [-g|-c] config.ini"
<< std::endl;
return code;
}
#ifdef _WIN32
int
startWinsock()
{
WSADATA wsockd;
int err;
err = ::WSAStartup(MAKEWORD(2, 2), &wsockd);
if(err)
{
perror("Failed to start Windows Sockets");
return err;
}
return 0;
}
extern "C" BOOL FAR PASCAL
handle_signal_win32(DWORD fdwCtrlType)
{
UNREFERENCED_PARAMETER(fdwCtrlType);
handle_signal(SIGINT);
return TRUE; // probably unreachable
}
#endif
int
main(int argc, char *argv[])
{
bool multiThreaded = true;
const char *singleThreadVar = getenv("LLARP_SHADOW");
if(singleThreadVar && std::string(singleThreadVar) == "1")
{
multiThreaded = false;
}
#ifdef _WIN32
if(startWinsock())
return -1;
SetConsoleCtrlHandler(handle_signal_win32, TRUE);
#endif
int opt = 0;
bool genconfigOnly = false;
bool asRouter = false;
bool overWrite = false;
while((opt = getopt(argc, argv, "hgcfrv")) != -1)
{
switch(opt)
{
case 'v':
SetLogLevel(llarp::eLogDebug);
llarp::LogDebug("debug logging activated");
break;
case 'h':
return printHelp(argv[0], 0);
case 'g':
genconfigOnly = true;
break;
case 'c':
genconfigOnly = true;
break;
case 'r':
#ifdef _WIN32
llarp::LogWarn(
"please don't try this at home, the relay feature is untested on "
"windows server --R.");
#endif
asRouter = true;
break;
case 'f':
overWrite = true;
break;
default:
return printHelp(argv[0]);
}
}
std::string conffname;
if(optind < argc)
{
// when we have an explicit filepath
fs::path fname = fs::path(argv[optind]);
fs::path basedir = fname.parent_path();
conffname = fname.string();
if(basedir.string().empty())
{
if(!llarp_ensure_config(fname.string().c_str(), nullptr, overWrite,
asRouter))
return 1;
}
else
{
std::error_code ec;
if(!fs::create_directories(basedir, ec))
{
if(ec)
{
llarp::LogError("failed to create '", basedir.string(),
"': ", ec.message());
return 1;
}
}
if(!llarp_ensure_config(fname.string().c_str(), basedir.string().c_str(),
overWrite, asRouter))
return 1;
}
}
else
{
// no explicit config file provided
#ifdef _WIN32
fs::path homedir = fs::path(getenv("APPDATA"));
#else
fs::path homedir = fs::path(getenv("HOME"));
#endif
fs::path basepath = homedir / fs::path(".lokinet");
fs::path fpath = basepath / "lokinet.ini";
std::error_code ec;
// These paths are guaranteed to exist - $APPDATA or $HOME
// so only create .lokinet/*
if(!fs::create_directory(basepath, ec))
{
if(ec)
{
llarp::LogError("failed to create '", basepath.string(),
"': ", ec.message());
return 1;
}
}
if(!llarp_ensure_config(fpath.string().c_str(), basepath.string().c_str(),
overWrite, asRouter))
return 1;
conffname = fpath.string();
}
if(genconfigOnly)
return 0;
ctx = llarp_main_init(conffname.c_str(), multiThreaded);
int code = 1;
if(ctx)
{
signal(SIGINT, handle_signal);
signal(SIGTERM, handle_signal);
#ifndef _WIN32
signal(SIGHUP, handle_signal);
#endif
code = llarp_main_setup(ctx);
if(code == 0)
code = llarp_main_run(ctx);
llarp_main_free(ctx);
}
#ifdef _WIN32
::WSACleanup();
#endif
exit(code);
return code;
}
|
/**************************************************************************
* CrProtonReentrant.cc
**************************************************************************
* Read comments at the head of CosmicRayGeneratorAction.cc
* and GLAST-LAT Technical Note (LAT-TD-250.1) by T. Mizuno et al.
* for overall flow of cosmic ray generation in BalloonTestV13.
* This program is interfaced to CosmicRayGeneratorAction.cc
* via CrProton, the entry-point class for the cosmic-ray proton
* generation.
**************************************************************************
* This program generates the cosmic-ray secondary proton downward flux
* at satellite altitude with proper angular distribution and energy spectrum.
* The absolute flux and spectrum of downward protons are assumed
* to depend on the geomagnetic cutoff energy.
* The flux is assumed not to depend on the zenith angle since AMS
* didn't detect significant difference between downward and upward
* flux in theta_M<0.6.
* The energy spectrum above 100 MeV is represented by simple analytic
* functions such as a power-low referring to AMS data.
* Below 100 MeV, the spectrum is extrapolated down to 10 MeV
* assuming that the flux is proportional to E^-1.
* A method reentrantCRenergy returns an energy and CrProtonReentrant::dir
* returns a direction in cos(theta) and phi (azimuth angle).
* Please note that we don't have splash nor reentrant component at
* satellite altitude. The class is named "**Reentrant" due to the
* historical reason.
**************************************************************************
* Definitions:
* 1) The z-axis points upward (from Calorimeter to Tracker).
* 2) Partile of theta=0 points for downward (i.e., comes from zenith)
* and that of theta=pi points for upward (comes from nadir).
* 3) Partile of phi=0 comes along x-axis (from x>0 to x=0) and
* that of phi=pi/2 comes along y-axis (from y>0 to y=0).
* 4) Energy means kinetic energy unless defined otherwise.
* 5) Magnetic latitude theta_M is in radian.
* 6) Particle direction is defined by cos(theta) and phi (in radian).
**************************************************************************
* in 2000 Originally written by by M. Ozaki (ISAS)
* and K. Hirano (Hiroshima Univ.)
* 2001-04 Spectrum part is modified by T. Mizuno (Hiroshima Univ.)
* 2001-05 Spectrum part is modified by T. Mizuno (Hiroshima Univ.)
* 2001-05 Comments added and unused codes removed by T. Kamae (SLAC)
* 2001-05 Program checked by T. Kamae and H. Mizushima (Hiroshima)
* 2001-11 Modified by T. Mizuno.
* angular distribution is changed to be uniform
* energy spectrum is extrapolated down to 10 MeV
* 2001-11 Modified by T. Mizuno to construct a `stand-alone' module
* 2003-02 Modified by T. Mizuno to generate flux at any position in orbit.
* 2004-04 Modified by T. Mizuno to simplify the model functions.
* 2005-05 Modified by T. Mizuno to calculate the flux when theta_M<0.
**************************************************************************
*/
//$Header$
#include <cmath>
// CLHEP
//#include <CLHEP/config/CLHEP.h>
#include <CLHEP/Random/RandomEngine.h>
#include <CLHEP/Random/RandGeneral.h>
#include <CLHEP/Random/JamesRandom.h>
#include "CrProtonReentrant.hh"
#include "CrProtonSubReentrant.hh"
typedef double G4double;
// private function definitions.
namespace {
// rest energy (rest mass) of proton in units of GeV
const G4double restE = 0.938;
// gives back v/c as a function of kinetic Energy
inline G4double beta(G4double E /* GeV */){
return sqrt(1 - pow(E/restE+1, -2));
}
// gives back the rigidity (p/Ze where p is the momentum, e means
// electron charge magnitude, and Z is the atomic number) in units of [GV],
// as a function of kinetic energy [GeV].
inline G4double rigidity(G4double E /* GeV */){
return sqrt(pow(E + restE, 2) - pow(restE, 2));
}
// gives back the kinetic energy (GeV) as a function of rigidity (GV)
inline G4double energy(G4double rigidity /* GV */){
return sqrt(pow(rigidity, 2) + pow(restE, 2)) - restE;
}
} // End of noname-namespace: private function definitions.
//
//
//
CrProtonReentrant::CrProtonReentrant():CrSpectrum()
{
crProtonReentrant_0002 = new CrProtonReentrant_0002();
crProtonReentrant_0203 = new CrProtonReentrant_0203();
crProtonReentrant_0304 = new CrProtonReentrant_0304();
crProtonReentrant_0405 = new CrProtonReentrant_0405();
crProtonReentrant_0506 = new CrProtonReentrant_0506();
crProtonReentrant_0607 = new CrProtonReentrant_0607();
crProtonReentrant_0708 = new CrProtonReentrant_0708();
crProtonReentrant_0809 = new CrProtonReentrant_0809();
crProtonReentrant_0910 = new CrProtonReentrant_0910();
}
CrProtonReentrant::~CrProtonReentrant()
{
delete crProtonReentrant_0002;
delete crProtonReentrant_0203;
delete crProtonReentrant_0304;
delete crProtonReentrant_0405;
delete crProtonReentrant_0506;
delete crProtonReentrant_0607;
delete crProtonReentrant_0708;
delete crProtonReentrant_0809;
delete crProtonReentrant_0910;
}
// Gives back particle direction in (cos(theta), phi)
std::pair<G4double,G4double> CrProtonReentrant::dir(G4double /* energy */,
CLHEP::HepRandomEngine* engine) const
// return: cos(theta) and phi [rad]
// The downward direction has plus sign in cos(theta),
// and phi = 0 for the particle comming along x-axis (from x>0 to x=0)
// and phi=pi/2 for that comming along y-axis (from y>0 to y=0)
{
G4double phi = engine->flat() * 2 * M_PI;
G4double theta = acos(engine->flat());
G4double r1, r2;
if (fabs(m_geomagneticLatitude)*M_PI/180.0<0.15){
theta = crProtonReentrant_0002->theta(engine);
} else if (fabs(m_geomagneticLatitude)*M_PI/180.0>=0.15 && fabs(m_geomagneticLatitude)*M_PI/180.0<0.25){
r1 = fabs(m_geomagneticLatitude)*M_PI/180.0-0.15;
r2 = 0.25-fabs(m_geomagneticLatitude)*M_PI/180.0;
if (engine->flat()*(r1+r2)<r2){
theta = crProtonReentrant_0002->theta(engine);
} else {
theta = crProtonReentrant_0203->theta(engine);
}
} else if (fabs(m_geomagneticLatitude)*M_PI/180.0>=0.25 && fabs(m_geomagneticLatitude)*M_PI/180.0<0.35){
r1 = fabs(m_geomagneticLatitude)*M_PI/180.0-0.25;
r2 = 0.35-fabs(m_geomagneticLatitude)*M_PI/180.0;
if (engine->flat()*(r1+r2)<r2){
theta = crProtonReentrant_0203->theta(engine);
} else {
theta = crProtonReentrant_0304->theta(engine);
}
} else if (fabs(m_geomagneticLatitude)*M_PI/180.0>=0.35 && fabs(m_geomagneticLatitude)*M_PI/180.0<0.45){
r1 = fabs(m_geomagneticLatitude)*M_PI/180.0-0.35;
r2 = 0.45-fabs(m_geomagneticLatitude)*M_PI/180.0;
if (engine->flat()*(r1+r2)<r2){
theta = crProtonReentrant_0304->theta(engine);
} else {
theta = crProtonReentrant_0405->theta(engine);
}
} else if (fabs(m_geomagneticLatitude)*M_PI/180.0>=0.45 && fabs(m_geomagneticLatitude)*M_PI/180.0<0.55){
r1 = fabs(m_geomagneticLatitude)*M_PI/180.0-0.45;
r2 = 0.55-fabs(m_geomagneticLatitude)*M_PI/180.0;
if (engine->flat()*(r1+r2)<r2){
theta = crProtonReentrant_0405->theta(engine);
} else {
theta = crProtonReentrant_0506->theta(engine);
}
} else if (fabs(m_geomagneticLatitude)*M_PI/180.0>=0.55 && fabs(m_geomagneticLatitude)*M_PI/180.0<0.65){
r1 = fabs(m_geomagneticLatitude)*M_PI/180.0-0.55;
r2 = 0.65-fabs(m_geomagneticLatitude)*M_PI/180.0;
if (engine->flat()*(r1+r2)<r2){
theta = crProtonReentrant_0506->theta(engine);
} else {
theta = crProtonReentrant_0607->theta(engine);
}
} else if (fabs(m_geomagneticLatitude)*M_PI/180.0>=0.65 && fabs(m_geomagneticLatitude)*M_PI/180.0<0.75){
r1 = fabs(m_geomagneticLatitude)*M_PI/180.0-0.65;
r2 = 0.75-fabs(m_geomagneticLatitude)*M_PI/180.0;
if (engine->flat()*(r1+r2)<r2){
theta = crProtonReentrant_0607->theta(engine);
} else {
theta = crProtonReentrant_0708->theta(engine);
}
} else if (fabs(m_geomagneticLatitude)*M_PI/180.0>=0.75 && fabs(m_geomagneticLatitude)*M_PI/180.0<0.85){
r1 = fabs(m_geomagneticLatitude)*M_PI/180.0-0.75;
r2 = 0.85-fabs(m_geomagneticLatitude)*M_PI/180.0;
if (engine->flat()*(r1+r2)<r2){
theta = crProtonReentrant_0708->theta(engine);
} else {
theta = crProtonReentrant_0809->theta(engine);
}
} else if (fabs(m_geomagneticLatitude)*M_PI/180.0>=0.85 && fabs(m_geomagneticLatitude)*M_PI/180.0<0.95){
r1 = fabs(m_geomagneticLatitude)*M_PI/180.0-0.85;
r2 = 0.95-fabs(m_geomagneticLatitude)*M_PI/180.0;
if (engine->flat()*(r1+r2)<r2){
theta = crProtonReentrant_0809->theta(engine);
} else {
theta = crProtonReentrant_0910->theta(engine);
}
} else {
theta = crProtonReentrant_0910->theta(engine);
}
return std::pair<G4double,G4double>(cos(theta), phi);
}
// Gives back particle energy
G4double CrProtonReentrant::energySrc(CLHEP::HepRandomEngine* engine) const
{
// return crProtonReentrant_0002->energy(engine);
// return crProtonReentrant_0203->energy(engine);
// return crProtonReentrant_0304->energy(engine);
// return crProtonReentrant_0405->energy(engine);
// return crProtonReentrant_0506->energy(engine);
// return crProtonReentrant_0607->energy(engine);
// return crProtonReentrant_0708->energy(engine);
// return crProtonReentrant_0809->energy(engine);
// return crProtonReentrant_0910->energy(engine);
G4double r1, r2;
if (fabs(m_geomagneticLatitude)*M_PI/180.0<0.15){
return crProtonReentrant_0002->energy(engine);
} else if (fabs(m_geomagneticLatitude)*M_PI/180.0>=0.15 && fabs(m_geomagneticLatitude)*M_PI/180.0<0.25){
r1 = fabs(m_geomagneticLatitude)*M_PI/180.0-0.15;
r2 = 0.25-fabs(m_geomagneticLatitude)*M_PI/180.0;
if (engine->flat()*(r1+r2)<r2){
return crProtonReentrant_0002->energy(engine);
} else {
return crProtonReentrant_0203->energy(engine);
}
} else if (fabs(m_geomagneticLatitude)*M_PI/180.0>=0.25 && fabs(m_geomagneticLatitude)*M_PI/180.0<0.35){
r1 = fabs(m_geomagneticLatitude)*M_PI/180.0-0.25;
r2 = 0.35-fabs(m_geomagneticLatitude)*M_PI/180.0;
if (engine->flat()*(r1+r2)<r2){
return crProtonReentrant_0203->energy(engine);
} else {
return crProtonReentrant_0304->energy(engine);
}
} else if (fabs(m_geomagneticLatitude)*M_PI/180.0>=0.35 && fabs(m_geomagneticLatitude)*M_PI/180.0<0.45){
r1 = fabs(m_geomagneticLatitude)*M_PI/180.0-0.35;
r2 = 0.45-fabs(m_geomagneticLatitude)*M_PI/180.0;
if (engine->flat()*(r1+r2)<r2){
return crProtonReentrant_0304->energy(engine);
} else {
return crProtonReentrant_0405->energy(engine);
}
} else if (fabs(m_geomagneticLatitude)*M_PI/180.0>=0.45 && fabs(m_geomagneticLatitude)*M_PI/180.0<0.55){
r1 = fabs(m_geomagneticLatitude)*M_PI/180.0-0.45;
r2 = 0.55-fabs(m_geomagneticLatitude)*M_PI/180.0;
if (engine->flat()*(r1+r2)<r2){
return crProtonReentrant_0405->energy(engine);
} else {
return crProtonReentrant_0506->energy(engine);
}
} else if (fabs(m_geomagneticLatitude)*M_PI/180.0>=0.55 && fabs(m_geomagneticLatitude)*M_PI/180.0<0.65){
r1 = fabs(m_geomagneticLatitude)*M_PI/180.0-0.55;
r2 = 0.65-fabs(m_geomagneticLatitude)*M_PI/180.0;
if (engine->flat()*(r1+r2)<r2){
return crProtonReentrant_0506->energy(engine);
} else {
return crProtonReentrant_0607->energy(engine);
}
} else if (fabs(m_geomagneticLatitude)*M_PI/180.0>=0.65 && fabs(m_geomagneticLatitude)*M_PI/180.0<0.75){
r1 = fabs(m_geomagneticLatitude)*M_PI/180.0-0.65;
r2 = 0.75-fabs(m_geomagneticLatitude)*M_PI/180.0;
if (engine->flat()*(r1+r2)<r2){
return crProtonReentrant_0607->energy(engine);
} else {
return crProtonReentrant_0708->energy(engine);
}
} else if (fabs(m_geomagneticLatitude)*M_PI/180.0>=0.75 && fabs(m_geomagneticLatitude)*M_PI/180.0<0.85){
r1 = fabs(m_geomagneticLatitude)*M_PI/180.0-0.75;
r2 = 0.85-fabs(m_geomagneticLatitude)*M_PI/180.0;
if (engine->flat()*(r1+r2)<r2){
return crProtonReentrant_0708->energy(engine);
} else {
return crProtonReentrant_0809->energy(engine);
}
} else if (fabs(m_geomagneticLatitude)*M_PI/180.0>=0.85 && fabs(m_geomagneticLatitude)*M_PI/180.0<0.95){
r1 = fabs(m_geomagneticLatitude)*M_PI/180.0-0.85;
r2 = 0.95-fabs(m_geomagneticLatitude)*M_PI/180.0;
if (engine->flat()*(r1+r2)<r2){
return crProtonReentrant_0809->energy(engine);
} else {
return crProtonReentrant_0910->energy(engine);
}
} else {
return crProtonReentrant_0910->energy(engine);
}
}
// flux() returns the energy integrated flux averaged over
// the region from which particle is coming from
// and the unit is [c/s/m^2/sr].
// flux()*solidAngle() is used as relative normalization among
// "primary", "reentrant" and "splash".
G4double CrProtonReentrant::flux() const
{
// energy integrated vertically downward flux, [c/s/m^2/sr]
G4double downwardFlux;
G4double r1, r2;
if (fabs(m_geomagneticLatitude)*M_PI/180.0<0.15){
downwardFlux = crProtonReentrant_0002->downwardFlux();
} else if (fabs(m_geomagneticLatitude)*M_PI/180.0>=0.15 && fabs(m_geomagneticLatitude)*M_PI/180.0<0.25){
r1 = fabs(m_geomagneticLatitude)*M_PI/180.0-0.15;
r2 = 0.25-fabs(m_geomagneticLatitude)*M_PI/180.0;
downwardFlux = ( r2*crProtonReentrant_0002->downwardFlux()
+r1*crProtonReentrant_0203->downwardFlux() )/(r1+r2);
} else if (fabs(m_geomagneticLatitude)*M_PI/180.0>=0.25 && fabs(m_geomagneticLatitude)*M_PI/180.0<0.35){
r1 = fabs(m_geomagneticLatitude)*M_PI/180.0-0.25;
r2 = 0.35-fabs(m_geomagneticLatitude)*M_PI/180.0;
downwardFlux = ( r2*crProtonReentrant_0203->downwardFlux()
+r1*crProtonReentrant_0304->downwardFlux() )/(r1+r2);
} else if (fabs(m_geomagneticLatitude)*M_PI/180.0>=0.35 && fabs(m_geomagneticLatitude)*M_PI/180.0<0.45){
r1 = fabs(m_geomagneticLatitude)*M_PI/180.0-0.35;
r2 = 0.45-fabs(m_geomagneticLatitude)*M_PI/180.0;
downwardFlux = ( r2*crProtonReentrant_0304->downwardFlux()
+r1*crProtonReentrant_0405->downwardFlux() )/(r1+r2);
} else if (fabs(m_geomagneticLatitude)*M_PI/180.0>=0.45 && fabs(m_geomagneticLatitude)*M_PI/180.0<0.55){
r1 = fabs(m_geomagneticLatitude)*M_PI/180.0-0.45;
r2 = 0.55-fabs(m_geomagneticLatitude)*M_PI/180.0;
downwardFlux = ( r2*crProtonReentrant_0405->downwardFlux()
+r1*crProtonReentrant_0506->downwardFlux() )/(r1+r2);
} else if (fabs(m_geomagneticLatitude)*M_PI/180.0>=0.55 && fabs(m_geomagneticLatitude)*M_PI/180.0<0.65){
r1 = fabs(m_geomagneticLatitude)*M_PI/180.0-0.55;
r2 = 0.65-fabs(m_geomagneticLatitude)*M_PI/180.0;
downwardFlux = ( r2*crProtonReentrant_0506->downwardFlux()
+r1*crProtonReentrant_0607->downwardFlux() )/(r1+r2);
} else if (fabs(m_geomagneticLatitude)*M_PI/180.0>=0.65 && fabs(m_geomagneticLatitude)*M_PI/180.0<0.75){
r1 = fabs(m_geomagneticLatitude)*M_PI/180.0-0.65;
r2 = 0.75-fabs(m_geomagneticLatitude)*M_PI/180.0;
downwardFlux = ( r2*crProtonReentrant_0607->downwardFlux()
+r1*crProtonReentrant_0708->downwardFlux() )/(r1+r2);
} else if (fabs(m_geomagneticLatitude)*M_PI/180.0>=0.75 && fabs(m_geomagneticLatitude)*M_PI/180.0<0.85){
r1 = fabs(m_geomagneticLatitude)*M_PI/180.0-0.75;
r2 = 0.85-fabs(m_geomagneticLatitude)*M_PI/180.0;
downwardFlux = ( r2*crProtonReentrant_0708->downwardFlux()
+r1*crProtonReentrant_0809->downwardFlux() )/(r1+r2);
} else if (fabs(m_geomagneticLatitude)*M_PI/180.0>=0.85 && fabs(m_geomagneticLatitude)*M_PI/180.0<0.95){
r1 = fabs(m_geomagneticLatitude)*M_PI/180.0-0.85;
r2 = 0.95-fabs(m_geomagneticLatitude)*M_PI/180.0;
downwardFlux = ( r2*crProtonReentrant_0809->downwardFlux()
+r1*crProtonReentrant_0910->downwardFlux() )/(r1+r2);
} else {
downwardFlux = crProtonReentrant_0910->downwardFlux();
}
return m_normalization*downwardFlux; // [c/s/m^2/sr]
}
// Gives back solid angle from which particle comes
G4double CrProtonReentrant::solidAngle() const
{
return 2 * M_PI;
}
// Gives back particle name
const char* CrProtonReentrant::particleName() const
{
return "proton";
}
// Gives back the name of the component
std::string CrProtonReentrant::title() const
{
return "CrProtonReentrant";
}
|
// The MIT License(MIT)
//
// Copyright(c) 2016 Cedric Guillemet
//
// 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 "vierkant/imgui/imgui.h"
#ifndef IMGUI_DEFINE_MATH_OPERATORS
#define IMGUI_DEFINE_MATH_OPERATORS
#endif
#include "imgui_internal.h"
#include "vierkant/imgui/ImGuizmo.h"
// includes patches for multiview from
// https://github.com/CedricGuillemet/ImGuizmo/issues/15
namespace ImGuizmo
{
static const float ZPI = 3.14159265358979323846f;
static const float RAD2DEG = (180.f / ZPI);
static const float DEG2RAD = (ZPI / 180.f);
static const float gGizmoSizeClipSpace = 0.1f;
const float screenRotateSize = 0.06f;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// utility and math
void FPU_MatrixF_x_MatrixF(const float *a, const float *b, float *r)
{
r[0] = a[0] * b[0] + a[1] * b[4] + a[2] * b[8] + a[3] * b[12];
r[1] = a[0] * b[1] + a[1] * b[5] + a[2] * b[9] + a[3] * b[13];
r[2] = a[0] * b[2] + a[1] * b[6] + a[2] * b[10] + a[3] * b[14];
r[3] = a[0] * b[3] + a[1] * b[7] + a[2] * b[11] + a[3] * b[15];
r[4] = a[4] * b[0] + a[5] * b[4] + a[6] * b[8] + a[7] * b[12];
r[5] = a[4] * b[1] + a[5] * b[5] + a[6] * b[9] + a[7] * b[13];
r[6] = a[4] * b[2] + a[5] * b[6] + a[6] * b[10] + a[7] * b[14];
r[7] = a[4] * b[3] + a[5] * b[7] + a[6] * b[11] + a[7] * b[15];
r[8] = a[8] * b[0] + a[9] * b[4] + a[10] * b[8] + a[11] * b[12];
r[9] = a[8] * b[1] + a[9] * b[5] + a[10] * b[9] + a[11] * b[13];
r[10] = a[8] * b[2] + a[9] * b[6] + a[10] * b[10] + a[11] * b[14];
r[11] = a[8] * b[3] + a[9] * b[7] + a[10] * b[11] + a[11] * b[15];
r[12] = a[12] * b[0] + a[13] * b[4] + a[14] * b[8] + a[15] * b[12];
r[13] = a[12] * b[1] + a[13] * b[5] + a[14] * b[9] + a[15] * b[13];
r[14] = a[12] * b[2] + a[13] * b[6] + a[14] * b[10] + a[15] * b[14];
r[15] = a[12] * b[3] + a[13] * b[7] + a[14] * b[11] + a[15] * b[15];
}
//template <typename T> T LERP(T x, T y, float z) { return (x + (y - x)*z); }
template <typename T> T Clamp(T x, T y, T z) { return ((x<y) ? y : ((x>z) ? z : x)); }
template <typename T> T max(T x, T y) { return (x > y) ? x : y; }
template <typename T> T min(T x, T y) { return (x < y) ? x : y; }
template <typename T> bool IsWithin(T x, T y, T z) { return (x>=y) && (x<=z); }
struct matrix_t;
struct vec_t
{
public:
float x, y, z, w;
void Lerp(const vec_t& v, float t)
{
x += (v.x - x) * t;
y += (v.y - y) * t;
z += (v.z - z) * t;
w += (v.w - w) * t;
}
void Set(float v) { x = y = z = w = v; }
void Set(float _x, float _y, float _z = 0.f, float _w = 0.f) { x = _x; y = _y; z = _z; w = _w; }
vec_t& operator -= (const vec_t& v) { x -= v.x; y -= v.y; z -= v.z; w -= v.w; return *this; }
vec_t& operator += (const vec_t& v) { x += v.x; y += v.y; z += v.z; w += v.w; return *this; }
vec_t& operator *= (const vec_t& v) { x *= v.x; y *= v.y; z *= v.z; w *= v.w; return *this; }
vec_t& operator *= (float v) { x *= v; y *= v; z *= v; w *= v; return *this; }
vec_t operator * (float f) const;
vec_t operator - () const;
vec_t operator - (const vec_t& v) const;
vec_t operator + (const vec_t& v) const;
vec_t operator * (const vec_t& v) const;
const vec_t& operator + () const { return (*this); }
float Length() const { return sqrtf(x*x + y*y + z*z); };
float LengthSq() const { return (x*x + y*y + z*z); };
vec_t Normalize() { (*this) *= (1.f / Length()); return (*this); }
vec_t Normalize(const vec_t& v) { this->Set(v.x, v.y, v.z, v.w); this->Normalize(); return (*this); }
vec_t Abs() const;
void Cross(const vec_t& v)
{
vec_t res;
res.x = y * v.z - z * v.y;
res.y = z * v.x - x * v.z;
res.z = x * v.y - y * v.x;
x = res.x;
y = res.y;
z = res.z;
w = 0.f;
}
void Cross(const vec_t& v1, const vec_t& v2)
{
x = v1.y * v2.z - v1.z * v2.y;
y = v1.z * v2.x - v1.x * v2.z;
z = v1.x * v2.y - v1.y * v2.x;
w = 0.f;
}
float Dot(const vec_t &v) const
{
return (x * v.x) + (y * v.y) + (z * v.z) + (w * v.w);
}
float Dot3(const vec_t &v) const
{
return (x * v.x) + (y * v.y) + (z * v.z);
}
void Transform(const matrix_t& matrix);
void Transform(const vec_t & s, const matrix_t& matrix);
void TransformVector(const matrix_t& matrix);
void TransformPoint(const matrix_t& matrix);
void TransformVector(const vec_t& v, const matrix_t& matrix) { (*this) = v; this->TransformVector(matrix); }
void TransformPoint(const vec_t& v, const matrix_t& matrix) { (*this) = v; this->TransformPoint(matrix); }
float& operator [] (size_t index) { return ((float*)&x)[index]; }
const float& operator [] (size_t index) const { return ((float*)&x)[index]; }
};
vec_t makeVect(float _x, float _y, float _z = 0.f, float _w = 0.f) { vec_t res; res.x = _x; res.y = _y; res.z = _z; res.w = _w; return res; }
vec_t makeVect(ImVec2 v) { vec_t res; res.x = v.x; res.y = v.y; res.z = 0.f; res.w = 0.f; return res; }
vec_t vec_t::operator * (float f) const { return makeVect(x * f, y * f, z * f, w *f); }
vec_t vec_t::operator - () const { return makeVect(-x, -y, -z, -w); }
vec_t vec_t::operator - (const vec_t& v) const { return makeVect(x - v.x, y - v.y, z - v.z, w - v.w); }
vec_t vec_t::operator + (const vec_t& v) const { return makeVect(x + v.x, y + v.y, z + v.z, w + v.w); }
vec_t vec_t::operator * (const vec_t& v) const { return makeVect(x * v.x, y * v.y, z * v.z, w * v.w); }
vec_t vec_t::Abs() const { return makeVect(fabsf(x), fabsf(y), fabsf(z)); }
vec_t Normalized(const vec_t& v) { vec_t res; res = v; res.Normalize(); return res; }
vec_t Cross(const vec_t& v1, const vec_t& v2)
{
vec_t res;
res.x = v1.y * v2.z - v1.z * v2.y;
res.y = v1.z * v2.x - v1.x * v2.z;
res.z = v1.x * v2.y - v1.y * v2.x;
res.w = 0.f;
return res;
}
float Dot(const vec_t &v1, const vec_t &v2)
{
return (v1.x * v2.x) + (v1.y * v2.y) + (v1.z * v2.z);
}
vec_t BuildPlan(const vec_t & p_point1, const vec_t & p_normal)
{
vec_t normal, res;
normal.Normalize(p_normal);
res.w = normal.Dot(p_point1);
res.x = normal.x;
res.y = normal.y;
res.z = normal.z;
return res;
}
struct matrix_t
{
public:
union
{
float m[4][4];
float m16[16];
struct
{
vec_t right, up, dir, position;
} v;
vec_t component[4];
};
matrix_t(const matrix_t& other) { memcpy(&m16[0], &other.m16[0], sizeof(float) * 16); }
matrix_t() {}
operator float * () { return m16; }
operator const float* () const { return m16; }
void Translation(float _x, float _y, float _z) { this->Translation(makeVect(_x, _y, _z)); }
void Translation(const vec_t& vt)
{
v.right.Set(1.f, 0.f, 0.f, 0.f);
v.up.Set(0.f, 1.f, 0.f, 0.f);
v.dir.Set(0.f, 0.f, 1.f, 0.f);
v.position.Set(vt.x, vt.y, vt.z, 1.f);
}
void Scale(float _x, float _y, float _z)
{
v.right.Set(_x, 0.f, 0.f, 0.f);
v.up.Set(0.f, _y, 0.f, 0.f);
v.dir.Set(0.f, 0.f, _z, 0.f);
v.position.Set(0.f, 0.f, 0.f, 1.f);
}
void Scale(const vec_t& s) { Scale(s.x, s.y, s.z); }
matrix_t& operator *= (const matrix_t& mat)
{
matrix_t tmpMat;
tmpMat = *this;
tmpMat.Multiply(mat);
*this = tmpMat;
return *this;
}
matrix_t operator * (const matrix_t& mat) const
{
matrix_t matT;
matT.Multiply(*this, mat);
return matT;
}
void Multiply(const matrix_t &matrix)
{
matrix_t tmp;
tmp = *this;
FPU_MatrixF_x_MatrixF((float*)&tmp, (float*)&matrix, (float*)this);
}
void Multiply(const matrix_t &m1, const matrix_t &m2)
{
FPU_MatrixF_x_MatrixF((float*)&m1, (float*)&m2, (float*)this);
}
float GetDeterminant() const
{
return m[0][0] * m[1][1] * m[2][2] + m[0][1] * m[1][2] * m[2][0] + m[0][2] * m[1][0] * m[2][1] -
m[0][2] * m[1][1] * m[2][0] - m[0][1] * m[1][0] * m[2][2] - m[0][0] * m[1][2] * m[2][1];
}
float Inverse(const matrix_t &srcMatrix, bool affine = false);
void SetToIdentity()
{
v.right.Set(1.f, 0.f, 0.f, 0.f);
v.up.Set(0.f, 1.f, 0.f, 0.f);
v.dir.Set(0.f, 0.f, 1.f, 0.f);
v.position.Set(0.f, 0.f, 0.f, 1.f);
}
void Transpose()
{
matrix_t tmpm;
for (int l = 0; l < 4; l++)
{
for (int c = 0; c < 4; c++)
{
tmpm.m[l][c] = m[c][l];
}
}
(*this) = tmpm;
}
void RotationAxis(const vec_t & axis, float angle);
void OrthoNormalize()
{
v.right.Normalize();
v.up.Normalize();
v.dir.Normalize();
}
};
void vec_t::Transform(const matrix_t& matrix)
{
vec_t out;
out.x = x * matrix.m[0][0] + y * matrix.m[1][0] + z * matrix.m[2][0] + w * matrix.m[3][0];
out.y = x * matrix.m[0][1] + y * matrix.m[1][1] + z * matrix.m[2][1] + w * matrix.m[3][1];
out.z = x * matrix.m[0][2] + y * matrix.m[1][2] + z * matrix.m[2][2] + w * matrix.m[3][2];
out.w = x * matrix.m[0][3] + y * matrix.m[1][3] + z * matrix.m[2][3] + w * matrix.m[3][3];
x = out.x;
y = out.y;
z = out.z;
w = out.w;
}
void vec_t::Transform(const vec_t & s, const matrix_t& matrix)
{
*this = s;
Transform(matrix);
}
void vec_t::TransformPoint(const matrix_t& matrix)
{
vec_t out;
out.x = x * matrix.m[0][0] + y * matrix.m[1][0] + z * matrix.m[2][0] + matrix.m[3][0];
out.y = x * matrix.m[0][1] + y * matrix.m[1][1] + z * matrix.m[2][1] + matrix.m[3][1];
out.z = x * matrix.m[0][2] + y * matrix.m[1][2] + z * matrix.m[2][2] + matrix.m[3][2];
out.w = x * matrix.m[0][3] + y * matrix.m[1][3] + z * matrix.m[2][3] + matrix.m[3][3];
x = out.x;
y = out.y;
z = out.z;
w = out.w;
}
void vec_t::TransformVector(const matrix_t& matrix)
{
vec_t out;
out.x = x * matrix.m[0][0] + y * matrix.m[1][0] + z * matrix.m[2][0];
out.y = x * matrix.m[0][1] + y * matrix.m[1][1] + z * matrix.m[2][1];
out.z = x * matrix.m[0][2] + y * matrix.m[1][2] + z * matrix.m[2][2];
out.w = x * matrix.m[0][3] + y * matrix.m[1][3] + z * matrix.m[2][3];
x = out.x;
y = out.y;
z = out.z;
w = out.w;
}
float matrix_t::Inverse(const matrix_t &srcMatrix, bool affine)
{
float det = 0;
if (affine)
{
det = GetDeterminant();
float s = 1 / det;
m[0][0] = (srcMatrix.m[1][1] * srcMatrix.m[2][2] - srcMatrix.m[1][2] * srcMatrix.m[2][1]) * s;
m[0][1] = (srcMatrix.m[2][1] * srcMatrix.m[0][2] - srcMatrix.m[2][2] * srcMatrix.m[0][1]) * s;
m[0][2] = (srcMatrix.m[0][1] * srcMatrix.m[1][2] - srcMatrix.m[0][2] * srcMatrix.m[1][1]) * s;
m[1][0] = (srcMatrix.m[1][2] * srcMatrix.m[2][0] - srcMatrix.m[1][0] * srcMatrix.m[2][2]) * s;
m[1][1] = (srcMatrix.m[2][2] * srcMatrix.m[0][0] - srcMatrix.m[2][0] * srcMatrix.m[0][2]) * s;
m[1][2] = (srcMatrix.m[0][2] * srcMatrix.m[1][0] - srcMatrix.m[0][0] * srcMatrix.m[1][2]) * s;
m[2][0] = (srcMatrix.m[1][0] * srcMatrix.m[2][1] - srcMatrix.m[1][1] * srcMatrix.m[2][0]) * s;
m[2][1] = (srcMatrix.m[2][0] * srcMatrix.m[0][1] - srcMatrix.m[2][1] * srcMatrix.m[0][0]) * s;
m[2][2] = (srcMatrix.m[0][0] * srcMatrix.m[1][1] - srcMatrix.m[0][1] * srcMatrix.m[1][0]) * s;
m[3][0] = -(m[0][0] * srcMatrix.m[3][0] + m[1][0] * srcMatrix.m[3][1] + m[2][0] * srcMatrix.m[3][2]);
m[3][1] = -(m[0][1] * srcMatrix.m[3][0] + m[1][1] * srcMatrix.m[3][1] + m[2][1] * srcMatrix.m[3][2]);
m[3][2] = -(m[0][2] * srcMatrix.m[3][0] + m[1][2] * srcMatrix.m[3][1] + m[2][2] * srcMatrix.m[3][2]);
}
else
{
// transpose matrix
float src[16];
for (int i = 0; i < 4; ++i)
{
src[i] = srcMatrix.m16[i * 4];
src[i + 4] = srcMatrix.m16[i * 4 + 1];
src[i + 8] = srcMatrix.m16[i * 4 + 2];
src[i + 12] = srcMatrix.m16[i * 4 + 3];
}
// calculate pairs for first 8 elements (cofactors)
float tmp[12]; // temp array for pairs
tmp[0] = src[10] * src[15];
tmp[1] = src[11] * src[14];
tmp[2] = src[9] * src[15];
tmp[3] = src[11] * src[13];
tmp[4] = src[9] * src[14];
tmp[5] = src[10] * src[13];
tmp[6] = src[8] * src[15];
tmp[7] = src[11] * src[12];
tmp[8] = src[8] * src[14];
tmp[9] = src[10] * src[12];
tmp[10] = src[8] * src[13];
tmp[11] = src[9] * src[12];
// calculate first 8 elements (cofactors)
m16[0] = (tmp[0] * src[5] + tmp[3] * src[6] + tmp[4] * src[7]) - (tmp[1] * src[5] + tmp[2] * src[6] + tmp[5] * src[7]);
m16[1] = (tmp[1] * src[4] + tmp[6] * src[6] + tmp[9] * src[7]) - (tmp[0] * src[4] + tmp[7] * src[6] + tmp[8] * src[7]);
m16[2] = (tmp[2] * src[4] + tmp[7] * src[5] + tmp[10] * src[7]) - (tmp[3] * src[4] + tmp[6] * src[5] + tmp[11] * src[7]);
m16[3] = (tmp[5] * src[4] + tmp[8] * src[5] + tmp[11] * src[6]) - (tmp[4] * src[4] + tmp[9] * src[5] + tmp[10] * src[6]);
m16[4] = (tmp[1] * src[1] + tmp[2] * src[2] + tmp[5] * src[3]) - (tmp[0] * src[1] + tmp[3] * src[2] + tmp[4] * src[3]);
m16[5] = (tmp[0] * src[0] + tmp[7] * src[2] + tmp[8] * src[3]) - (tmp[1] * src[0] + tmp[6] * src[2] + tmp[9] * src[3]);
m16[6] = (tmp[3] * src[0] + tmp[6] * src[1] + tmp[11] * src[3]) - (tmp[2] * src[0] + tmp[7] * src[1] + tmp[10] * src[3]);
m16[7] = (tmp[4] * src[0] + tmp[9] * src[1] + tmp[10] * src[2]) - (tmp[5] * src[0] + tmp[8] * src[1] + tmp[11] * src[2]);
// calculate pairs for second 8 elements (cofactors)
tmp[0] = src[2] * src[7];
tmp[1] = src[3] * src[6];
tmp[2] = src[1] * src[7];
tmp[3] = src[3] * src[5];
tmp[4] = src[1] * src[6];
tmp[5] = src[2] * src[5];
tmp[6] = src[0] * src[7];
tmp[7] = src[3] * src[4];
tmp[8] = src[0] * src[6];
tmp[9] = src[2] * src[4];
tmp[10] = src[0] * src[5];
tmp[11] = src[1] * src[4];
// calculate second 8 elements (cofactors)
m16[8] = (tmp[0] * src[13] + tmp[3] * src[14] + tmp[4] * src[15]) - (tmp[1] * src[13] + tmp[2] * src[14] + tmp[5] * src[15]);
m16[9] = (tmp[1] * src[12] + tmp[6] * src[14] + tmp[9] * src[15]) - (tmp[0] * src[12] + tmp[7] * src[14] + tmp[8] * src[15]);
m16[10] = (tmp[2] * src[12] + tmp[7] * src[13] + tmp[10] * src[15]) - (tmp[3] * src[12] + tmp[6] * src[13] + tmp[11] * src[15]);
m16[11] = (tmp[5] * src[12] + tmp[8] * src[13] + tmp[11] * src[14]) - (tmp[4] * src[12] + tmp[9] * src[13] + tmp[10] * src[14]);
m16[12] = (tmp[2] * src[10] + tmp[5] * src[11] + tmp[1] * src[9]) - (tmp[4] * src[11] + tmp[0] * src[9] + tmp[3] * src[10]);
m16[13] = (tmp[8] * src[11] + tmp[0] * src[8] + tmp[7] * src[10]) - (tmp[6] * src[10] + tmp[9] * src[11] + tmp[1] * src[8]);
m16[14] = (tmp[6] * src[9] + tmp[11] * src[11] + tmp[3] * src[8]) - (tmp[10] * src[11] + tmp[2] * src[8] + tmp[7] * src[9]);
m16[15] = (tmp[10] * src[10] + tmp[4] * src[8] + tmp[9] * src[9]) - (tmp[8] * src[9] + tmp[11] * src[10] + tmp[5] * src[8]);
// calculate determinant
det = src[0] * m16[0] + src[1] * m16[1] + src[2] * m16[2] + src[3] * m16[3];
// calculate matrix inverse
float invdet = 1 / det;
for (int j = 0; j < 16; ++j)
{
m16[j] *= invdet;
}
}
return det;
}
void matrix_t::RotationAxis(const vec_t & axis, float angle)
{
float length2 = axis.LengthSq();
if (length2 < FLT_EPSILON)
{
SetToIdentity();
return;
}
vec_t n = axis * (1.f / sqrtf(length2));
float s = sinf(angle);
float c = cosf(angle);
float k = 1.f - c;
float xx = n.x * n.x * k + c;
float yy = n.y * n.y * k + c;
float zz = n.z * n.z * k + c;
float xy = n.x * n.y * k;
float yz = n.y * n.z * k;
float zx = n.z * n.x * k;
float xs = n.x * s;
float ys = n.y * s;
float zs = n.z * s;
m[0][0] = xx;
m[0][1] = xy + zs;
m[0][2] = zx - ys;
m[0][3] = 0.f;
m[1][0] = xy - zs;
m[1][1] = yy;
m[1][2] = yz + xs;
m[1][3] = 0.f;
m[2][0] = zx + ys;
m[2][1] = yz - xs;
m[2][2] = zz;
m[2][3] = 0.f;
m[3][0] = 0.f;
m[3][1] = 0.f;
m[3][2] = 0.f;
m[3][3] = 1.f;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
enum MOVETYPE
{
NONE,
MOVE_X,
MOVE_Y,
MOVE_Z,
MOVE_YZ,
MOVE_ZX,
MOVE_XY,
MOVE_SCREEN,
ROTATE_X,
ROTATE_Y,
ROTATE_Z,
ROTATE_SCREEN,
SCALE_X,
SCALE_Y,
SCALE_Z,
SCALE_XYZ
};
struct Context
{
Context() : mbUsing(false), mbEnable(true), mbUsingBounds(false)
{
}
ImDrawList* mDrawList;
MODE mMode;
matrix_t mViewMat;
matrix_t mProjectionMat;
matrix_t mModel;
matrix_t mModelInverse;
matrix_t mModelSource;
matrix_t mModelSourceInverse;
matrix_t mMVP;
matrix_t mViewProjection;
vec_t mModelScaleOrigin;
vec_t mCameraEye;
vec_t mCameraRight;
vec_t mCameraDir;
vec_t mCameraUp;
vec_t mRayOrigin;
vec_t mRayVector;
float mRadiusSquareCenter;
ImVec2 mScreenSquareCenter;
ImVec2 mScreenSquareMin;
ImVec2 mScreenSquareMax;
float mScreenFactor;
vec_t mRelativeOrigin;
bool mbUsing;
bool mbEnable;
// translation
vec_t mTranslationPlan;
vec_t mTranslationPlanOrigin;
vec_t mMatrixOrigin;
// rotation
vec_t mRotationVectorSource;
float mRotationAngle;
float mRotationAngleOrigin;
//vec_t mWorldToLocalAxis;
// scale
vec_t mScale;
vec_t mScaleValueOrigin;
float mSaveMousePosx;
// save axis factor when using gizmo
bool mBelowAxisLimit[3];
bool mBelowPlaneLimit[3];
float mAxisFactor[3];
// bounds stretching
vec_t mBoundsPivot;
vec_t mBoundsAnchor;
vec_t mBoundsPlan;
vec_t mBoundsLocalPivot;
int mBoundsBestAxis;
int mBoundsAxis[2];
bool mbUsingBounds;
matrix_t mBoundsMatrix;
//
int mCurrentOperation;
float mX = 0.f;
float mY = 0.f;
float mWidth = 0.f;
float mHeight = 0.f;
float mXMax = 0.f;
float mYMax = 0.f;
float mDisplayRatio = 1.f;
bool mIsOrthographic = false;
};
static Context gContext;
static const float angleLimit = 0.96f;
static const float planeLimit = 0.2f;
static const vec_t directionUnary[3] = { makeVect(1.f, 0.f, 0.f), makeVect(0.f, 1.f, 0.f), makeVect(0.f, 0.f, 1.f) };
static const ImU32 directionColor[3] = { 0xFF0000AA, 0xFF00AA00, 0xFFAA0000 };
// Alpha: 100%: FF, 87%: DE, 70%: B3, 54%: 8A, 50%: 80, 38%: 61, 12%: 1F
static const ImU32 planeColor[3] = { 0x610000AA, 0x6100AA00, 0x61AA0000 };
static const ImU32 selectionColor = 0x8A1080FF;
static const ImU32 inactiveColor = 0x99999999;
static const ImU32 translationLineColor = 0xAAAAAAAA;
static const char *translationInfoMask[] = { "X : %5.3f", "Y : %5.3f", "Z : %5.3f",
"Y : %5.3f Z : %5.3f", "X : %5.3f Z : %5.3f", "X : %5.3f Y : %5.3f",
"X : %5.3f Y : %5.3f Z : %5.3f" };
static const char *scaleInfoMask[] = { "X : %5.2f", "Y : %5.2f", "Z : %5.2f", "XYZ : %5.2f" };
static const char *rotationInfoMask[] = { "X : %5.2f deg %5.2f rad", "Y : %5.2f deg %5.2f rad", "Z : %5.2f deg %5.2f rad", "Screen : %5.2f deg %5.2f rad" };
static const int translationInfoIndex[] = { 0,0,0, 1,0,0, 2,0,0, 1,2,0, 0,2,0, 0,1,0, 0,1,2 };
static const float quadMin = 0.5f;
static const float quadMax = 0.8f;
static const float quadUV[8] = { quadMin, quadMin, quadMin, quadMax, quadMax, quadMax, quadMax, quadMin };
static const int halfCircleSegmentCount = 64;
static const float snapTension = 0.5f;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
static int GetMoveType(vec_t *gizmoHitProportion);
static int GetRotateType();
static int GetScaleType();
static ImVec2 worldToPos(const vec_t& worldPos, const matrix_t& mat)
{
vec_t trans;
trans.TransformPoint(worldPos, mat);
trans *= 0.5f / trans.w;
trans += makeVect(0.5f, 0.5f);
trans.y = 1.f - trans.y;
trans.x *= gContext.mWidth;
trans.y *= gContext.mHeight;
trans.x += gContext.mX;
trans.y += gContext.mY;
return ImVec2(trans.x, trans.y);
}
static void ComputeCameraRay(vec_t &rayOrigin, vec_t &rayDir)
{
ImGuiIO& io = ImGui::GetIO();
matrix_t mViewProjInverse;
mViewProjInverse.Inverse(gContext.mViewMat * gContext.mProjectionMat);
float mox = ((io.MousePos.x - gContext.mX) / gContext.mWidth) * 2.f - 1.f;
float moy = (1.f - ((io.MousePos.y - gContext.mY) / gContext.mHeight)) * 2.f - 1.f;
rayOrigin.Transform(makeVect(mox, moy, 0.f, 1.f), mViewProjInverse);
rayOrigin *= 1.f / rayOrigin.w;
vec_t rayEnd;
rayEnd.Transform(makeVect(mox, moy, 1.f, 1.f), mViewProjInverse);
rayEnd *= 1.f / rayEnd.w;
rayDir = Normalized(rayEnd - rayOrigin);
}
static float GetSegmentLengthClipSpace(const vec_t& start, const vec_t& end)
{
vec_t startOfSegment = start;
startOfSegment.TransformPoint(gContext.mMVP);
if (fabsf(startOfSegment.w)> FLT_EPSILON) // check for axis aligned with camera direction
startOfSegment *= 1.f / startOfSegment.w;
vec_t endOfSegment = end;
endOfSegment.TransformPoint(gContext.mMVP);
if (fabsf(endOfSegment.w)> FLT_EPSILON) // check for axis aligned with camera direction
endOfSegment *= 1.f / endOfSegment.w;
vec_t clipSpaceAxis = endOfSegment - startOfSegment;
clipSpaceAxis.y /= gContext.mDisplayRatio;
float segmentLengthInClipSpace = sqrtf(clipSpaceAxis.x*clipSpaceAxis.x + clipSpaceAxis.y*clipSpaceAxis.y);
return segmentLengthInClipSpace;
}
static float GetParallelogram(const vec_t& ptO, const vec_t& ptA, const vec_t& ptB)
{
vec_t pts[] = { ptO, ptA, ptB };
for (unsigned int i = 0; i < 3; i++)
{
pts[i].TransformPoint(gContext.mMVP);
if (fabsf(pts[i].w)> FLT_EPSILON) // check for axis aligned with camera direction
pts[i] *= 1.f / pts[i].w;
}
vec_t segA = pts[1] - pts[0];
vec_t segB = pts[2] - pts[0];
segA.y /= gContext.mDisplayRatio;
segB.y /= gContext.mDisplayRatio;
vec_t segAOrtho = makeVect(-segA.y, segA.x);
segAOrtho.Normalize();
float dt = segAOrtho.Dot3(segB);
float surface = sqrtf(segA.x*segA.x + segA.y*segA.y) * fabsf(dt);
return surface;
}
inline vec_t PointOnSegment(const vec_t & point, const vec_t & vertPos1, const vec_t & vertPos2)
{
vec_t c = point - vertPos1;
vec_t V;
V.Normalize(vertPos2 - vertPos1);
float d = (vertPos2 - vertPos1).Length();
float t = V.Dot3(c);
if (t < 0.f)
return vertPos1;
if (t > d)
return vertPos2;
return vertPos1 + V * t;
}
static float IntersectRayPlane(const vec_t & rOrigin, const vec_t& rVector, const vec_t& plan)
{
float numer = plan.Dot3(rOrigin) - plan.w;
float denom = plan.Dot3(rVector);
if (fabsf(denom) < FLT_EPSILON) // normal is orthogonal to vector, cant intersect
return -1.0f;
return -(numer / denom);
}
static bool IsInContextRect( ImVec2 p )
{
return IsWithin( p.x, gContext.mX, gContext.mXMax ) && IsWithin(p.y, gContext.mY, gContext.mYMax );
}
void SetRect(float x, float y, float width, float height)
{
gContext.mX = x;
gContext.mY = y;
gContext.mWidth = width;
gContext.mHeight = height;
gContext.mXMax = gContext.mX + gContext.mWidth;
gContext.mYMax = gContext.mY + gContext.mXMax;
gContext.mDisplayRatio = width / height;
}
IMGUI_API void SetOrthographic(bool isOrthographic)
{
gContext.mIsOrthographic = isOrthographic;
}
void SetDrawlist()
{
gContext.mDrawList = ImGui::GetWindowDrawList();
}
void BeginFrame()
{
ImGuiIO& io = ImGui::GetIO();
const ImU32 flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoBringToFrontOnFocus;
ImGui::SetNextWindowSize(io.DisplaySize);
ImGui::SetNextWindowPos(ImVec2(0, 0));
ImGui::PushStyleColor(ImGuiCol_WindowBg, 0);
ImGui::PushStyleColor(ImGuiCol_Border, 0);
ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
ImGui::Begin("gizmo", NULL, flags);
gContext.mDrawList = ImGui::GetWindowDrawList();
ImGui::End();
ImGui::PopStyleVar();
ImGui::PopStyleColor(2);
}
bool IsUsing()
{
return gContext.mbUsing||gContext.mbUsingBounds;
}
bool IsOver()
{
return (GetMoveType(NULL) != NONE) || GetRotateType() != NONE || GetScaleType() != NONE || IsUsing();
}
void Enable(bool enable)
{
gContext.mbEnable = enable;
if (!enable)
{
gContext.mbUsing = false;
gContext.mbUsingBounds = false;
}
}
// static float GetUniform(const vec_t& position, const matrix_t& mat)
// {
// vec_t trf = makeVect(position.x, position.y, position.z, 1.f);
// trf.Transform(mat);
// return trf.w;
// }
static void ComputeContext(const float *view, const float *projection, float *matrix, MODE mode)
{
gContext.mMode = mode;
gContext.mViewMat = *(matrix_t*)view;
gContext.mProjectionMat = *(matrix_t*)projection;
if (mode == LOCAL)
{
gContext.mModel = *(matrix_t*)matrix;
gContext.mModel.OrthoNormalize();
}
else
{
gContext.mModel.Translation(((matrix_t*)matrix)->v.position);
}
gContext.mModelSource = *(matrix_t*)matrix;
gContext.mModelScaleOrigin.Set(gContext.mModelSource.v.right.Length(), gContext.mModelSource.v.up.Length(), gContext.mModelSource.v.dir.Length());
gContext.mModelInverse.Inverse(gContext.mModel);
gContext.mModelSourceInverse.Inverse(gContext.mModelSource);
gContext.mViewProjection = gContext.mViewMat * gContext.mProjectionMat;
gContext.mMVP = gContext.mModel * gContext.mViewProjection;
matrix_t viewInverse;
viewInverse.Inverse(gContext.mViewMat);
gContext.mCameraDir = viewInverse.v.dir;
gContext.mCameraEye = viewInverse.v.position;
gContext.mCameraRight = viewInverse.v.right;
gContext.mCameraUp = viewInverse.v.up;
// compute scale from the size of camera right vector projected on screen at the matrix position
vec_t pointRight = viewInverse.v.right;
pointRight.TransformPoint(gContext.mViewProjection);
gContext.mScreenFactor = gGizmoSizeClipSpace / (pointRight.x / pointRight.w - gContext.mMVP.v.position.x / gContext.mMVP.v.position.w);
vec_t rightViewInverse = viewInverse.v.right;
rightViewInverse.TransformVector(gContext.mModelInverse);
float rightLength = GetSegmentLengthClipSpace(makeVect(0.f, 0.f), rightViewInverse);
gContext.mScreenFactor = gGizmoSizeClipSpace / rightLength;
ImVec2 centerSSpace = worldToPos(makeVect(0.f, 0.f), gContext.mMVP);
gContext.mScreenSquareCenter = centerSSpace;
gContext.mScreenSquareMin = ImVec2(centerSSpace.x - 10.f, centerSSpace.y - 10.f);
gContext.mScreenSquareMax = ImVec2(centerSSpace.x + 10.f, centerSSpace.y + 10.f);
ComputeCameraRay(gContext.mRayOrigin, gContext.mRayVector);
}
static void ComputeColors(ImU32 *colors, int type, OPERATION operation)
{
if (gContext.mbEnable)
{
switch (operation)
{
case TRANSLATE:
colors[0] = (type == MOVE_SCREEN) ? selectionColor : 0xFFFFFFFF;
for (int i = 0; i < 3; i++)
{
colors[i + 1] = (type == (int)(MOVE_X + i)) ? selectionColor : directionColor[i];
colors[i + 4] = (type == (int)(MOVE_YZ + i)) ? selectionColor : planeColor[i];
colors[i + 4] = (type == MOVE_SCREEN) ? selectionColor : colors[i + 4];
}
break;
case ROTATE:
colors[0] = (type == ROTATE_SCREEN) ? selectionColor : 0xFFFFFFFF;
for (int i = 0; i < 3; i++)
colors[i + 1] = (type == (int)(ROTATE_X + i)) ? selectionColor : directionColor[i];
break;
case SCALE:
colors[0] = (type == SCALE_XYZ) ? selectionColor : 0xFFFFFFFF;
for (int i = 0; i < 3; i++)
colors[i + 1] = (type == (int)(SCALE_X + i)) ? selectionColor : directionColor[i];
break;
case BOUNDS:
break;
}
}
else
{
for (int i = 0; i < 7; i++)
colors[i] = inactiveColor;
}
}
static void ComputeTripodAxisAndVisibility(int axisIndex, vec_t& dirAxis, vec_t& dirPlaneX, vec_t& dirPlaneY, bool& belowAxisLimit, bool& belowPlaneLimit)
{
dirAxis = directionUnary[axisIndex];
dirPlaneX = directionUnary[(axisIndex + 1) % 3];
dirPlaneY = directionUnary[(axisIndex + 2) % 3];
if (gContext.mbUsing)
{
// when using, use stored factors so the gizmo doesn't flip when we translate
belowAxisLimit = gContext.mBelowAxisLimit[axisIndex];
belowPlaneLimit = gContext.mBelowPlaneLimit[axisIndex];
dirAxis *= gContext.mAxisFactor[axisIndex];
dirPlaneX *= gContext.mAxisFactor[(axisIndex + 1) % 3];
dirPlaneY *= gContext.mAxisFactor[(axisIndex + 2) % 3];
}
else
{
// new method
float lenDir = GetSegmentLengthClipSpace(makeVect(0.f, 0.f, 0.f), dirAxis);
float lenDirMinus = GetSegmentLengthClipSpace(makeVect(0.f, 0.f, 0.f), -dirAxis);
float lenDirPlaneX = GetSegmentLengthClipSpace(makeVect(0.f, 0.f, 0.f), dirPlaneX);
float lenDirMinusPlaneX = GetSegmentLengthClipSpace(makeVect(0.f, 0.f, 0.f), -dirPlaneX);
float lenDirPlaneY = GetSegmentLengthClipSpace(makeVect(0.f, 0.f, 0.f), dirPlaneY);
float lenDirMinusPlaneY = GetSegmentLengthClipSpace(makeVect(0.f, 0.f, 0.f), -dirPlaneY);
float mulAxis = (lenDir < lenDirMinus && fabsf(lenDir - lenDirMinus) > FLT_EPSILON) ? -1.f : 1.f;
float mulAxisX = (lenDirPlaneX < lenDirMinusPlaneX && fabsf(lenDirPlaneX - lenDirMinusPlaneX) > FLT_EPSILON) ? -1.f : 1.f;
float mulAxisY = (lenDirPlaneY < lenDirMinusPlaneY && fabsf(lenDirPlaneY - lenDirMinusPlaneY) > FLT_EPSILON) ? -1.f : 1.f;
dirAxis *= mulAxis;
dirPlaneX *= mulAxisX;
dirPlaneY *= mulAxisY;
// for axis
float axisLengthInClipSpace = GetSegmentLengthClipSpace(makeVect(0.f, 0.f, 0.f), dirAxis * gContext.mScreenFactor);
float paraSurf = GetParallelogram(makeVect(0.f, 0.f, 0.f), dirPlaneX * gContext.mScreenFactor, dirPlaneY * gContext.mScreenFactor);
belowPlaneLimit = (paraSurf > 0.0025f);
belowAxisLimit = (axisLengthInClipSpace > 0.02f);
// and store values
gContext.mAxisFactor[axisIndex] = mulAxis;
gContext.mAxisFactor[(axisIndex + 1) % 3] = mulAxisX;
gContext.mAxisFactor[(axisIndex + 2) % 3] = mulAxisY;
gContext.mBelowAxisLimit[axisIndex] = belowAxisLimit;
gContext.mBelowPlaneLimit[axisIndex] = belowPlaneLimit;
}
}
static void ComputeSnap(float*value, float snap)
{
if (snap <= FLT_EPSILON)
return;
float modulo = fmodf(*value, snap);
float moduloRatio = fabsf(modulo) / snap;
if (moduloRatio < snapTension)
*value -= modulo;
else if (moduloRatio >(1.f - snapTension))
*value = *value - modulo + snap * ((*value<0.f) ? -1.f : 1.f);
}
static void ComputeSnap(vec_t& value, float *snap)
{
for (int i = 0; i < 3; i++)
{
ComputeSnap(&value[i], snap[i]);
}
}
static float ComputeAngleOnPlan()
{
const float len = IntersectRayPlane(gContext.mRayOrigin, gContext.mRayVector, gContext.mTranslationPlan);
vec_t localPos = Normalized(gContext.mRayOrigin + gContext.mRayVector * len - gContext.mModel.v.position);
vec_t perpendicularVector;
perpendicularVector.Cross(gContext.mRotationVectorSource, gContext.mTranslationPlan);
perpendicularVector.Normalize();
float acosAngle = Clamp(Dot(localPos, gContext.mRotationVectorSource), -0.9999f, 0.9999f);
float angle = acosf(acosAngle);
angle *= (Dot(localPos, perpendicularVector) < 0.f) ? 1.f : -1.f;
return angle;
}
static void DrawRotationGizmo(int type)
{
ImDrawList* drawList = gContext.mDrawList;
// colors
ImU32 colors[7];
ComputeColors(colors, type, ROTATE);
vec_t cameraToModelNormalized;
if (gContext.mIsOrthographic)
{
matrix_t viewInverse;
viewInverse.Inverse(*(matrix_t*)&gContext.mViewMat);
cameraToModelNormalized = viewInverse.v.dir;
}
else
{
cameraToModelNormalized = Normalized(gContext.mModel.v.position - gContext.mCameraEye);
}
cameraToModelNormalized.TransformVector(gContext.mModelInverse);
gContext.mRadiusSquareCenter = screenRotateSize * gContext.mHeight;
for (int axis = 0; axis < 3; axis++)
{
ImVec2 circlePos[halfCircleSegmentCount];
float angleStart = atan2f(cameraToModelNormalized[(4-axis)%3], cameraToModelNormalized[(3 - axis) % 3]) + ZPI * 0.5f;
for (unsigned int i = 0; i < halfCircleSegmentCount; i++)
{
float ng = angleStart + ZPI * ((float)i / (float)halfCircleSegmentCount);
vec_t axisPos = makeVect(cosf(ng), sinf(ng), 0.f);
vec_t pos = makeVect(axisPos[axis], axisPos[(axis+1)%3], axisPos[(axis+2)%3]) * gContext.mScreenFactor;
circlePos[i] = worldToPos(pos, gContext.mMVP);
}
float radiusAxis = sqrtf( (ImLengthSqr(worldToPos(gContext.mModel.v.position, gContext.mViewProjection) - circlePos[0]) ));
if(radiusAxis > gContext.mRadiusSquareCenter)
gContext.mRadiusSquareCenter = radiusAxis;
drawList->AddPolyline(circlePos, halfCircleSegmentCount, colors[3 - axis], false, 2);
}
drawList->AddCircle(worldToPos(gContext.mModel.v.position, gContext.mViewProjection), gContext.mRadiusSquareCenter, colors[0], 64, 3.f);
if (gContext.mbUsing)
{
ImVec2 circlePos[halfCircleSegmentCount +1];
circlePos[0] = worldToPos(gContext.mModel.v.position, gContext.mViewProjection);
for (unsigned int i = 1; i < halfCircleSegmentCount; i++)
{
float ng = gContext.mRotationAngle * ((float)(i-1) / (float)(halfCircleSegmentCount -1));
matrix_t rotateVectorMatrix;
rotateVectorMatrix.RotationAxis(gContext.mTranslationPlan, ng);
vec_t pos;
pos.TransformPoint(gContext.mRotationVectorSource, rotateVectorMatrix);
pos *= gContext.mScreenFactor;
circlePos[i] = worldToPos(pos + gContext.mModel.v.position, gContext.mViewProjection);
}
drawList->AddConvexPolyFilled(circlePos, halfCircleSegmentCount, 0x801080FF);
drawList->AddPolyline(circlePos, halfCircleSegmentCount, 0xFF1080FF, true, 2);
ImVec2 destinationPosOnScreen = circlePos[1];
char tmps[512];
ImFormatString(tmps, sizeof(tmps), rotationInfoMask[type - ROTATE_X], (gContext.mRotationAngle/ZPI)*180.f, gContext.mRotationAngle);
drawList->AddText(ImVec2(destinationPosOnScreen.x + 15, destinationPosOnScreen.y + 15), 0xFF000000, tmps);
drawList->AddText(ImVec2(destinationPosOnScreen.x + 14, destinationPosOnScreen.y + 14), 0xFFFFFFFF, tmps);
}
}
static void DrawHatchedAxis(const vec_t& axis)
{
for (int j = 1; j < 10; j++)
{
ImVec2 baseSSpace2 = worldToPos(axis * 0.05f * (float)(j * 2) * gContext.mScreenFactor, gContext.mMVP);
ImVec2 worldDirSSpace2 = worldToPos(axis * 0.05f * (float)(j * 2 + 1) * gContext.mScreenFactor, gContext.mMVP);
gContext.mDrawList->AddLine(baseSSpace2, worldDirSSpace2, 0x80000000, 6.f);
}
}
static void DrawScaleGizmo(int type)
{
ImDrawList* drawList = gContext.mDrawList;
// colors
ImU32 colors[7];
ComputeColors(colors, type, SCALE);
// draw
vec_t scaleDisplay = { 1.f, 1.f, 1.f, 1.f };
if (gContext.mbUsing)
scaleDisplay = gContext.mScale;
for (unsigned int i = 0; i < 3; i++)
{
vec_t dirPlaneX, dirPlaneY, dirAxis;
bool belowAxisLimit, belowPlaneLimit;
ComputeTripodAxisAndVisibility(i, dirAxis, dirPlaneX, dirPlaneY, belowAxisLimit, belowPlaneLimit);
// draw axis
if (belowAxisLimit)
{
ImVec2 baseSSpace = worldToPos(dirAxis * 0.1f * gContext.mScreenFactor, gContext.mMVP);
ImVec2 worldDirSSpaceNoScale = worldToPos(dirAxis * gContext.mScreenFactor, gContext.mMVP);
ImVec2 worldDirSSpace = worldToPos((dirAxis * scaleDisplay[i]) * gContext.mScreenFactor, gContext.mMVP);
if (gContext.mbUsing)
{
drawList->AddLine(baseSSpace, worldDirSSpaceNoScale, 0xFF404040, 3.f);
drawList->AddCircleFilled(worldDirSSpaceNoScale, 6.f, 0xFF404040);
}
drawList->AddLine(baseSSpace, worldDirSSpace, colors[i + 1], 3.f);
drawList->AddCircleFilled(worldDirSSpace, 6.f, colors[i + 1]);
if (gContext.mAxisFactor[i] < 0.f)
DrawHatchedAxis(dirAxis * scaleDisplay[i]);
}
}
// draw screen cirle
drawList->AddCircleFilled(gContext.mScreenSquareCenter, 6.f, colors[0], 32);
if (gContext.mbUsing)
{
//ImVec2 sourcePosOnScreen = worldToPos(gContext.mMatrixOrigin, gContext.mViewProjection);
ImVec2 destinationPosOnScreen = worldToPos(gContext.mModel.v.position, gContext.mViewProjection);
/*vec_t dif(destinationPosOnScreen.x - sourcePosOnScreen.x, destinationPosOnScreen.y - sourcePosOnScreen.y);
dif.Normalize();
dif *= 5.f;
drawList->AddCircle(sourcePosOnScreen, 6.f, translationLineColor);
drawList->AddCircle(destinationPosOnScreen, 6.f, translationLineColor);
drawList->AddLine(ImVec2(sourcePosOnScreen.x + dif.x, sourcePosOnScreen.y + dif.y), ImVec2(destinationPosOnScreen.x - dif.x, destinationPosOnScreen.y - dif.y), translationLineColor, 2.f);
*/
char tmps[512];
//vec_t deltaInfo = gContext.mModel.v.position - gContext.mMatrixOrigin;
int componentInfoIndex = (type - SCALE_X) * 3;
ImFormatString(tmps, sizeof(tmps), scaleInfoMask[type - SCALE_X], scaleDisplay[translationInfoIndex[componentInfoIndex]]);
drawList->AddText(ImVec2(destinationPosOnScreen.x + 15, destinationPosOnScreen.y + 15), 0xFF000000, tmps);
drawList->AddText(ImVec2(destinationPosOnScreen.x + 14, destinationPosOnScreen.y + 14), 0xFFFFFFFF, tmps);
}
}
static void DrawTranslationGizmo(int type)
{
ImDrawList* drawList = gContext.mDrawList;
if (!drawList)
return;
// colors
ImU32 colors[7];
ComputeColors(colors, type, TRANSLATE);
const ImVec2 origin = worldToPos(gContext.mModel.v.position, gContext.mViewProjection);
// draw
bool belowAxisLimit = false;
bool belowPlaneLimit = false;
for (unsigned int i = 0; i < 3; ++i)
{
vec_t dirPlaneX, dirPlaneY, dirAxis;
ComputeTripodAxisAndVisibility(i, dirAxis, dirPlaneX, dirPlaneY, belowAxisLimit, belowPlaneLimit);
// draw axis
if (belowAxisLimit)
{
ImVec2 baseSSpace = worldToPos(dirAxis * 0.1f * gContext.mScreenFactor, gContext.mMVP);
ImVec2 worldDirSSpace = worldToPos(dirAxis * gContext.mScreenFactor, gContext.mMVP);
drawList->AddLine(baseSSpace, worldDirSSpace, colors[i + 1], 3.f);
// Arrow head begin
ImVec2 dir(origin - worldDirSSpace);
float d = sqrtf(ImLengthSqr(dir));
dir /= d; // Normalize
dir *= 6.0f;
ImVec2 ortogonalDir(dir.y, -dir.x); // Perpendicular vector
ImVec2 a(worldDirSSpace + dir);
drawList->AddTriangleFilled(worldDirSSpace - dir, a + ortogonalDir, a - ortogonalDir, colors[i + 1]);
// Arrow head end
if (gContext.mAxisFactor[i] < 0.f)
DrawHatchedAxis(dirAxis);
}
// draw plane
if (belowPlaneLimit)
{
ImVec2 screenQuadPts[4];
for (int j = 0; j < 4; ++j)
{
vec_t cornerWorldPos = (dirPlaneX * quadUV[j * 2] + dirPlaneY * quadUV[j * 2 + 1]) * gContext.mScreenFactor;
screenQuadPts[j] = worldToPos(cornerWorldPos, gContext.mMVP);
}
drawList->AddPolyline(screenQuadPts, 4, directionColor[i], true, 1.0f);
drawList->AddConvexPolyFilled(screenQuadPts, 4, colors[i + 4]);
}
}
drawList->AddCircleFilled(gContext.mScreenSquareCenter, 6.f, colors[0], 32);
if (gContext.mbUsing)
{
ImVec2 sourcePosOnScreen = worldToPos(gContext.mMatrixOrigin, gContext.mViewProjection);
ImVec2 destinationPosOnScreen = worldToPos(gContext.mModel.v.position, gContext.mViewProjection);
vec_t dif = { destinationPosOnScreen.x - sourcePosOnScreen.x, destinationPosOnScreen.y - sourcePosOnScreen.y, 0.f, 0.f };
dif.Normalize();
dif *= 5.f;
drawList->AddCircle(sourcePosOnScreen, 6.f, translationLineColor);
drawList->AddCircle(destinationPosOnScreen, 6.f, translationLineColor);
drawList->AddLine(ImVec2(sourcePosOnScreen.x + dif.x, sourcePosOnScreen.y + dif.y), ImVec2(destinationPosOnScreen.x - dif.x, destinationPosOnScreen.y - dif.y), translationLineColor, 2.f);
char tmps[512];
vec_t deltaInfo = gContext.mModel.v.position - gContext.mMatrixOrigin;
int componentInfoIndex = (type - MOVE_X) * 3;
ImFormatString(tmps, sizeof(tmps), translationInfoMask[type - MOVE_X], deltaInfo[translationInfoIndex[componentInfoIndex]], deltaInfo[translationInfoIndex[componentInfoIndex + 1]], deltaInfo[translationInfoIndex[componentInfoIndex + 2]]);
drawList->AddText(ImVec2(destinationPosOnScreen.x + 15, destinationPosOnScreen.y + 15), 0xFF000000, tmps);
drawList->AddText(ImVec2(destinationPosOnScreen.x + 14, destinationPosOnScreen.y + 14), 0xFFFFFFFF, tmps);
}
}
static bool CanActivate()
{
if (ImGui::IsMouseClicked(0) && !ImGui::IsAnyItemHovered() && !ImGui::IsAnyItemActive())
return true;
return false;
}
static void HandleAndDrawLocalBounds(float *bounds, matrix_t *matrix, float *snapValues, OPERATION operation)
{
ImGuiIO& io = ImGui::GetIO();
ImDrawList* drawList = gContext.mDrawList;
// compute best projection axis
vec_t axesWorldDirections[3];
vec_t bestAxisWorldDirection = { 0.0f, 0.0f, 0.0f, 0.0f };
int axes[3];
unsigned int numAxes = 1;
axes[0] = gContext.mBoundsBestAxis;
int bestAxis = axes[0];
if (!gContext.mbUsingBounds)
{
numAxes = 0;
float bestDot = 0.f;
for (unsigned int i = 0; i < 3; i++)
{
vec_t dirPlaneNormalWorld;
dirPlaneNormalWorld.TransformVector(directionUnary[i], gContext.mModelSource);
dirPlaneNormalWorld.Normalize();
float dt = fabsf( Dot(Normalized(gContext.mCameraEye - gContext.mModelSource.v.position), dirPlaneNormalWorld) );
if ( dt >= bestDot )
{
bestDot = dt;
bestAxis = i;
bestAxisWorldDirection = dirPlaneNormalWorld;
}
if( dt >= 0.1f )
{
axes[numAxes] = i;
axesWorldDirections[numAxes] = dirPlaneNormalWorld;
++numAxes;
}
}
}
if( numAxes == 0 )
{
axes[0] = bestAxis;
axesWorldDirections[0] = bestAxisWorldDirection;
numAxes = 1;
}
else if( bestAxis != axes[0] )
{
unsigned int bestIndex = 0;
for (unsigned int i = 0; i < numAxes; i++)
{
if( axes[i] == bestAxis )
{
bestIndex = i;
break;
}
}
int tempAxis = axes[0];
axes[0] = axes[bestIndex];
axes[bestIndex] = tempAxis;
vec_t tempDirection = axesWorldDirections[0];
axesWorldDirections[0] = axesWorldDirections[bestIndex];
axesWorldDirections[bestIndex] = tempDirection;
}
for (unsigned int axisIndex = 0; axisIndex < numAxes; ++axisIndex)
{
bestAxis = axes[axisIndex];
bestAxisWorldDirection = axesWorldDirections[axisIndex];
// corners
vec_t aabb[4];
int secondAxis = (bestAxis + 1) % 3;
int thirdAxis = (bestAxis + 2) % 3;
for (int i = 0; i < 4; i++)
{
aabb[i][3] = aabb[i][bestAxis] = 0.f;
aabb[i][secondAxis] = bounds[secondAxis + 3 * (i >> 1)];
aabb[i][thirdAxis] = bounds[thirdAxis + 3 * ((i >> 1) ^ (i & 1))];
}
// draw bounds
unsigned int anchorAlpha = gContext.mbEnable ? 0xFF000000 : 0x80000000;
matrix_t boundsMVP = gContext.mModelSource * gContext.mViewProjection;
for (int i = 0; i < 4;i++)
{
ImVec2 worldBound1 = worldToPos(aabb[i], boundsMVP);
ImVec2 worldBound2 = worldToPos(aabb[(i+1)%4], boundsMVP);
if( !IsInContextRect( worldBound1 ) || !IsInContextRect( worldBound2 ) )
{
continue;
}
float boundDistance = sqrtf(ImLengthSqr(worldBound1 - worldBound2));
int stepCount = (int)(boundDistance / 10.f);
stepCount = min( stepCount, 1000 );
float stepLength = 1.f / (float)stepCount;
for (int j = 0; j < stepCount; j++)
{
float t1 = (float)j * stepLength;
float t2 = (float)j * stepLength + stepLength * 0.5f;
ImVec2 worldBoundSS1 = ImLerp(worldBound1, worldBound2, ImVec2(t1, t1));
ImVec2 worldBoundSS2 = ImLerp(worldBound1, worldBound2, ImVec2(t2, t2));
//drawList->AddLine(worldBoundSS1, worldBoundSS2, 0x000000 + anchorAlpha, 3.f);
drawList->AddLine(worldBoundSS1, worldBoundSS2, 0xAAAAAA + anchorAlpha, 2.f);
}
vec_t midPoint = (aabb[i] + aabb[(i + 1) % 4] ) * 0.5f;
ImVec2 midBound = worldToPos(midPoint, boundsMVP);
static const float AnchorBigRadius = 8.f;
static const float AnchorSmallRadius = 6.f;
bool overBigAnchor = ImLengthSqr(worldBound1 - io.MousePos) <= (AnchorBigRadius*AnchorBigRadius);
bool overSmallAnchor = ImLengthSqr(midBound - io.MousePos) <= (AnchorBigRadius*AnchorBigRadius);
int type = NONE;
vec_t gizmoHitProportion;
switch (operation)
{
case TRANSLATE: type = GetMoveType(&gizmoHitProportion); break;
case ROTATE: type = GetRotateType(); break;
case SCALE: type = GetScaleType(); break;
case BOUNDS: break;
}
if (type != NONE)
{
overBigAnchor = false;
overSmallAnchor = false;
}
unsigned int bigAnchorColor = overBigAnchor ? selectionColor : (0xAAAAAA + anchorAlpha);
unsigned int smallAnchorColor = overSmallAnchor ? selectionColor : (0xAAAAAA + anchorAlpha);
drawList->AddCircleFilled(worldBound1, AnchorBigRadius, 0xFF000000);
drawList->AddCircleFilled(worldBound1, AnchorBigRadius-1.2f, bigAnchorColor);
drawList->AddCircleFilled(midBound, AnchorSmallRadius, 0xFF000000);
drawList->AddCircleFilled(midBound, AnchorSmallRadius-1.2f, smallAnchorColor);
int oppositeIndex = (i + 2) % 4;
// big anchor on corners
if (!gContext.mbUsingBounds && gContext.mbEnable && overBigAnchor && CanActivate())
{
gContext.mBoundsPivot.TransformPoint(aabb[(i + 2) % 4], gContext.mModelSource);
gContext.mBoundsAnchor.TransformPoint(aabb[i], gContext.mModelSource);
gContext.mBoundsPlan = BuildPlan(gContext.mBoundsAnchor, bestAxisWorldDirection);
gContext.mBoundsBestAxis = bestAxis;
gContext.mBoundsAxis[0] = secondAxis;
gContext.mBoundsAxis[1] = thirdAxis;
gContext.mBoundsLocalPivot.Set(0.f);
gContext.mBoundsLocalPivot[secondAxis] = aabb[oppositeIndex][secondAxis];
gContext.mBoundsLocalPivot[thirdAxis] = aabb[oppositeIndex][thirdAxis];
gContext.mbUsingBounds = true;
gContext.mBoundsMatrix = gContext.mModelSource;
}
// small anchor on middle of segment
if (!gContext.mbUsingBounds && gContext.mbEnable && overSmallAnchor && CanActivate())
{
vec_t midPointOpposite = (aabb[(i + 2) % 4] + aabb[(i + 3) % 4]) * 0.5f;
gContext.mBoundsPivot.TransformPoint(midPointOpposite, gContext.mModelSource);
gContext.mBoundsAnchor.TransformPoint(midPoint, gContext.mModelSource);
gContext.mBoundsPlan = BuildPlan(gContext.mBoundsAnchor, bestAxisWorldDirection);
gContext.mBoundsBestAxis = bestAxis;
int indices[] = { secondAxis , thirdAxis };
gContext.mBoundsAxis[0] = indices[i%2];
gContext.mBoundsAxis[1] = -1;
gContext.mBoundsLocalPivot.Set(0.f);
gContext.mBoundsLocalPivot[gContext.mBoundsAxis[0]] = aabb[oppositeIndex][indices[i % 2]];// bounds[gContext.mBoundsAxis[0]] * (((i + 1) & 2) ? 1.f : -1.f);
gContext.mbUsingBounds = true;
gContext.mBoundsMatrix = gContext.mModelSource;
}
}
if (gContext.mbUsingBounds)
{
matrix_t scale;
scale.SetToIdentity();
// compute projected mouse position on plan
const float len = IntersectRayPlane(gContext.mRayOrigin, gContext.mRayVector, gContext.mBoundsPlan);
vec_t newPos = gContext.mRayOrigin + gContext.mRayVector * len;
// compute a reference and delta vectors base on mouse move
vec_t deltaVector = (newPos - gContext.mBoundsPivot).Abs();
vec_t referenceVector = (gContext.mBoundsAnchor - gContext.mBoundsPivot).Abs();
// for 1 or 2 axes, compute a ratio that's used for scale and snap it based on resulting length
for (int i = 0; i < 2; i++)
{
int axisIndex1 = gContext.mBoundsAxis[i];
if (axisIndex1 == -1)
continue;
float ratioAxis = 1.f;
vec_t axisDir = gContext.mBoundsMatrix.component[axisIndex1].Abs();
float dtAxis = axisDir.Dot(referenceVector);
float boundSize = bounds[axisIndex1 + 3] - bounds[axisIndex1];
if (dtAxis > FLT_EPSILON)
ratioAxis = axisDir.Dot(deltaVector) / dtAxis;
if (snapValues)
{
float length = boundSize * ratioAxis;
ComputeSnap(&length, snapValues[axisIndex1]);
if (boundSize > FLT_EPSILON)
ratioAxis = length / boundSize;
}
scale.component[axisIndex1] *= ratioAxis;
}
// transform matrix
matrix_t preScale, postScale;
preScale.Translation(-gContext.mBoundsLocalPivot);
postScale.Translation(gContext.mBoundsLocalPivot);
matrix_t res = preScale * scale * postScale * gContext.mBoundsMatrix;
*matrix = res;
// info text
char tmps[512];
ImVec2 destinationPosOnScreen = worldToPos(gContext.mModel.v.position, gContext.mViewProjection);
ImFormatString(tmps, sizeof(tmps), "X: %.2f Y: %.2f Z:%.2f"
, (bounds[3] - bounds[0]) * gContext.mBoundsMatrix.component[0].Length() * scale.component[0].Length()
, (bounds[4] - bounds[1]) * gContext.mBoundsMatrix.component[1].Length() * scale.component[1].Length()
, (bounds[5] - bounds[2]) * gContext.mBoundsMatrix.component[2].Length() * scale.component[2].Length()
);
drawList->AddText(ImVec2(destinationPosOnScreen.x + 15, destinationPosOnScreen.y + 15), 0xFF000000, tmps);
drawList->AddText(ImVec2(destinationPosOnScreen.x + 14, destinationPosOnScreen.y + 14), 0xFFFFFFFF, tmps);
}
if (!io.MouseDown[0])
gContext.mbUsingBounds = false;
if( gContext.mbUsingBounds )
break;
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
static int GetScaleType()
{
ImGuiIO& io = ImGui::GetIO();
int type = NONE;
// screen
if (io.MousePos.x >= gContext.mScreenSquareMin.x && io.MousePos.x <= gContext.mScreenSquareMax.x &&
io.MousePos.y >= gContext.mScreenSquareMin.y && io.MousePos.y <= gContext.mScreenSquareMax.y)
type = SCALE_XYZ;
// compute
for (unsigned int i = 0; i < 3 && type == NONE; i++)
{
vec_t dirPlaneX, dirPlaneY, dirAxis;
bool belowAxisLimit, belowPlaneLimit;
ComputeTripodAxisAndVisibility(i, dirAxis, dirPlaneX, dirPlaneY, belowAxisLimit, belowPlaneLimit);
const float len = IntersectRayPlane(gContext.mRayOrigin, gContext.mRayVector, BuildPlan(gContext.mModel.v.position, dirAxis));
vec_t posOnPlan = gContext.mRayOrigin + gContext.mRayVector * len;
const ImVec2 posOnPlanScreen = worldToPos(posOnPlan, gContext.mViewProjection);
const ImVec2 axisStartOnScreen = worldToPos(gContext.mModel.v.position + dirAxis * gContext.mScreenFactor * 0.1f, gContext.mViewProjection);
const ImVec2 axisEndOnScreen = worldToPos(gContext.mModel.v.position + dirAxis * gContext.mScreenFactor, gContext.mViewProjection);
vec_t closestPointOnAxis = PointOnSegment(makeVect(posOnPlanScreen), makeVect(axisStartOnScreen), makeVect(axisEndOnScreen));
if ((closestPointOnAxis - makeVect(posOnPlanScreen)).Length() < 12.f) // pixel size
type = SCALE_X + i;
}
return type;
}
static int GetRotateType()
{
ImGuiIO& io = ImGui::GetIO();
int type = NONE;
vec_t deltaScreen = { io.MousePos.x - gContext.mScreenSquareCenter.x, io.MousePos.y - gContext.mScreenSquareCenter.y, 0.f, 0.f };
float dist = deltaScreen.Length();
if (dist >= (gContext.mRadiusSquareCenter - 1.0f) && dist < (gContext.mRadiusSquareCenter + 1.0f))
type = ROTATE_SCREEN;
const vec_t planNormals[] = { gContext.mModel.v.right, gContext.mModel.v.up, gContext.mModel.v.dir};
for (unsigned int i = 0; i < 3 && type == NONE; i++)
{
// pickup plan
vec_t pickupPlan = BuildPlan(gContext.mModel.v.position, planNormals[i]);
const float len = IntersectRayPlane(gContext.mRayOrigin, gContext.mRayVector, pickupPlan);
vec_t localPos = gContext.mRayOrigin + gContext.mRayVector * len - gContext.mModel.v.position;
if (Dot(Normalized(localPos), gContext.mRayVector) > FLT_EPSILON)
continue;
vec_t idealPosOnCircle = Normalized(localPos);
idealPosOnCircle.TransformVector(gContext.mModelInverse);
ImVec2 idealPosOnCircleScreen = worldToPos(idealPosOnCircle * gContext.mScreenFactor, gContext.mMVP);
//gContext.mDrawList->AddCircle(idealPosOnCircleScreen, 5.f, 0xFFFFFFFF);
ImVec2 distanceOnScreen = idealPosOnCircleScreen - io.MousePos;
float distance = makeVect(distanceOnScreen).Length();
if (distance < 8.f) // pixel size
type = ROTATE_X + i;
}
return type;
}
static int GetMoveType(vec_t *gizmoHitProportion)
{
ImGuiIO& io = ImGui::GetIO();
int type = NONE;
// screen
if (io.MousePos.x >= gContext.mScreenSquareMin.x && io.MousePos.x <= gContext.mScreenSquareMax.x &&
io.MousePos.y >= gContext.mScreenSquareMin.y && io.MousePos.y <= gContext.mScreenSquareMax.y)
type = MOVE_SCREEN;
// compute
for (unsigned int i = 0; i < 3 && type == NONE; i++)
{
vec_t dirPlaneX, dirPlaneY, dirAxis;
bool belowAxisLimit, belowPlaneLimit;
ComputeTripodAxisAndVisibility(i, dirAxis, dirPlaneX, dirPlaneY, belowAxisLimit, belowPlaneLimit);
dirAxis.TransformVector(gContext.mModel);
dirPlaneX.TransformVector(gContext.mModel);
dirPlaneY.TransformVector(gContext.mModel);
const float len = IntersectRayPlane(gContext.mRayOrigin, gContext.mRayVector, BuildPlan(gContext.mModel.v.position, dirAxis));
vec_t posOnPlan = gContext.mRayOrigin + gContext.mRayVector * len;
const ImVec2 posOnPlanScreen = worldToPos(posOnPlan, gContext.mViewProjection);
const ImVec2 axisStartOnScreen = worldToPos(gContext.mModel.v.position + dirAxis * gContext.mScreenFactor * 0.1f, gContext.mViewProjection);
const ImVec2 axisEndOnScreen = worldToPos(gContext.mModel.v.position + dirAxis * gContext.mScreenFactor, gContext.mViewProjection);
vec_t closestPointOnAxis = PointOnSegment(makeVect(posOnPlanScreen), makeVect(axisStartOnScreen), makeVect(axisEndOnScreen));
if ((closestPointOnAxis - makeVect(posOnPlanScreen)).Length() < 12.f) // pixel size
type = MOVE_X + i;
const float dx = dirPlaneX.Dot3((posOnPlan - gContext.mModel.v.position) * (1.f / gContext.mScreenFactor));
const float dy = dirPlaneY.Dot3((posOnPlan - gContext.mModel.v.position) * (1.f / gContext.mScreenFactor));
if (belowPlaneLimit && dx >= quadUV[0] && dx <= quadUV[4] && dy >= quadUV[1] && dy <= quadUV[3])
type = MOVE_YZ + i;
if (gizmoHitProportion)
*gizmoHitProportion = makeVect(dx, dy, 0.f);
}
return type;
}
static void HandleTranslation(float *matrix, float *deltaMatrix, int& type, float *snap)
{
ImGuiIO& io = ImGui::GetIO();
bool applyRotationLocaly = gContext.mMode == LOCAL || type == MOVE_SCREEN;
// move
if (gContext.mbUsing)
{
ImGui::CaptureMouseFromApp();
const float len = fabsf(IntersectRayPlane(gContext.mRayOrigin, gContext.mRayVector, gContext.mTranslationPlan)); // near plan
vec_t newPos = gContext.mRayOrigin + gContext.mRayVector * len;
// compute delta
vec_t newOrigin = newPos - gContext.mRelativeOrigin * gContext.mScreenFactor;
vec_t delta = newOrigin - gContext.mModel.v.position;
// 1 axis constraint
if (gContext.mCurrentOperation >= MOVE_X && gContext.mCurrentOperation <= MOVE_Z)
{
int axisIndex = gContext.mCurrentOperation - MOVE_X;
const vec_t& axisValue = *(vec_t*)&gContext.mModel.m[axisIndex];
float lengthOnAxis = Dot(axisValue, delta);
delta = axisValue * lengthOnAxis;
}
// snap
if (snap)
{
vec_t cumulativeDelta = gContext.mModel.v.position + delta - gContext.mMatrixOrigin;
if (applyRotationLocaly)
{
matrix_t modelSourceNormalized = gContext.mModelSource;
modelSourceNormalized.OrthoNormalize();
matrix_t modelSourceNormalizedInverse;
modelSourceNormalizedInverse.Inverse(modelSourceNormalized);
cumulativeDelta.TransformVector(modelSourceNormalizedInverse);
ComputeSnap(cumulativeDelta, snap);
cumulativeDelta.TransformVector(modelSourceNormalized);
}
else
{
ComputeSnap(cumulativeDelta, snap);
}
delta = gContext.mMatrixOrigin + cumulativeDelta - gContext.mModel.v.position;
}
// compute matrix & delta
matrix_t deltaMatrixTranslation;
deltaMatrixTranslation.Translation(delta);
if (deltaMatrix)
memcpy(deltaMatrix, deltaMatrixTranslation.m16, sizeof(float) * 16);
matrix_t res = gContext.mModelSource * deltaMatrixTranslation;
*(matrix_t*)matrix = res;
if (!io.MouseDown[0])
gContext.mbUsing = false;
type = gContext.mCurrentOperation;
}
else
{
// find new possible way to move
vec_t gizmoHitProportion;
type = GetMoveType(&gizmoHitProportion);
if(type != NONE)
{
ImGui::CaptureMouseFromApp();
}
if (CanActivate() && type != NONE)
{
gContext.mbUsing = true;
gContext.mCurrentOperation = type;
vec_t movePlanNormal[] = { gContext.mModel.v.right, gContext.mModel.v.up, gContext.mModel.v.dir,
gContext.mModel.v.right, gContext.mModel.v.up, gContext.mModel.v.dir,
-gContext.mCameraDir };
vec_t cameraToModelNormalized = Normalized(gContext.mModel.v.position - gContext.mCameraEye);
for (unsigned int i = 0; i < 3; i++)
{
vec_t orthoVector = Cross(movePlanNormal[i], cameraToModelNormalized);
movePlanNormal[i].Cross(orthoVector);
movePlanNormal[i].Normalize();
}
// pickup plan
gContext.mTranslationPlan = BuildPlan(gContext.mModel.v.position, movePlanNormal[type - MOVE_X]);
const float len = IntersectRayPlane(gContext.mRayOrigin, gContext.mRayVector, gContext.mTranslationPlan);
gContext.mTranslationPlanOrigin = gContext.mRayOrigin + gContext.mRayVector * len;
gContext.mMatrixOrigin = gContext.mModel.v.position;
gContext.mRelativeOrigin = (gContext.mTranslationPlanOrigin - gContext.mModel.v.position) * (1.f / gContext.mScreenFactor);
}
}
}
static void HandleScale(float *matrix, float *deltaMatrix, int& type, float *snap)
{
ImGuiIO& io = ImGui::GetIO();
if (!gContext.mbUsing)
{
// find new possible way to scale
type = GetScaleType();
if(type != NONE)
{
ImGui::CaptureMouseFromApp();
}
if (CanActivate() && type != NONE)
{
gContext.mbUsing = true;
gContext.mCurrentOperation = type;
const vec_t movePlanNormal[] = { gContext.mModel.v.up, gContext.mModel.v.dir, gContext.mModel.v.right, gContext.mModel.v.dir, gContext.mModel.v.up, gContext.mModel.v.right, -gContext.mCameraDir };
// pickup plan
gContext.mTranslationPlan = BuildPlan(gContext.mModel.v.position, movePlanNormal[type - SCALE_X]);
const float len = IntersectRayPlane(gContext.mRayOrigin, gContext.mRayVector, gContext.mTranslationPlan);
gContext.mTranslationPlanOrigin = gContext.mRayOrigin + gContext.mRayVector * len;
gContext.mMatrixOrigin = gContext.mModel.v.position;
gContext.mScale.Set(1.f, 1.f, 1.f);
gContext.mRelativeOrigin = (gContext.mTranslationPlanOrigin - gContext.mModel.v.position) * (1.f / gContext.mScreenFactor);
gContext.mScaleValueOrigin = makeVect(gContext.mModelSource.v.right.Length(), gContext.mModelSource.v.up.Length(), gContext.mModelSource.v.dir.Length());
gContext.mSaveMousePosx = io.MousePos.x;
}
}
// scale
if (gContext.mbUsing)
{
ImGui::CaptureMouseFromApp();
const float len = IntersectRayPlane(gContext.mRayOrigin, gContext.mRayVector, gContext.mTranslationPlan);
vec_t newPos = gContext.mRayOrigin + gContext.mRayVector * len;
vec_t newOrigin = newPos - gContext.mRelativeOrigin * gContext.mScreenFactor;
vec_t delta = newOrigin - gContext.mModel.v.position;
// 1 axis constraint
if (gContext.mCurrentOperation >= SCALE_X && gContext.mCurrentOperation <= SCALE_Z)
{
int axisIndex = gContext.mCurrentOperation - SCALE_X;
const vec_t& axisValue = *(vec_t*)&gContext.mModel.m[axisIndex];
float lengthOnAxis = Dot(axisValue, delta);
delta = axisValue * lengthOnAxis;
vec_t baseVector = gContext.mTranslationPlanOrigin - gContext.mModel.v.position;
float ratio = Dot(axisValue, baseVector + delta) / Dot(axisValue, baseVector);
gContext.mScale[axisIndex] = max(ratio, 0.001f);
}
else
{
float scaleDelta = (io.MousePos.x - gContext.mSaveMousePosx) * 0.01f;
gContext.mScale.Set(max(1.f + scaleDelta, 0.001f));
}
// snap
if (snap)
{
float scaleSnap[] = { snap[0], snap[0], snap[0] };
ComputeSnap(gContext.mScale, scaleSnap);
}
// no 0 allowed
for (int i = 0; i < 3;i++)
gContext.mScale[i] = max(gContext.mScale[i], 0.001f);
// compute matrix & delta
matrix_t deltaMatrixScale;
deltaMatrixScale.Scale(gContext.mScale * gContext.mScaleValueOrigin);
matrix_t res = deltaMatrixScale * gContext.mModel;
*(matrix_t*)matrix = res;
if (deltaMatrix)
{
deltaMatrixScale.Scale(gContext.mScale);
memcpy(deltaMatrix, deltaMatrixScale.m16, sizeof(float) * 16);
}
if (!io.MouseDown[0])
gContext.mbUsing = false;
type = gContext.mCurrentOperation;
}
}
static void HandleRotation(float *matrix, float *deltaMatrix, int& type, float *snap)
{
ImGuiIO& io = ImGui::GetIO();
bool applyRotationLocaly = gContext.mMode == LOCAL;
if (!gContext.mbUsing)
{
type = GetRotateType();
if(type != NONE)
{
ImGui::CaptureMouseFromApp();
}
if (type == ROTATE_SCREEN)
{
applyRotationLocaly = true;
}
if (CanActivate() && type != NONE)
{
gContext.mbUsing = true;
gContext.mCurrentOperation = type;
const vec_t rotatePlanNormal[] = { gContext.mModel.v.right, gContext.mModel.v.up, gContext.mModel.v.dir, -gContext.mCameraDir };
// pickup plan
if (applyRotationLocaly)
{
gContext.mTranslationPlan = BuildPlan(gContext.mModel.v.position, rotatePlanNormal[type - ROTATE_X]);
}
else
{
gContext.mTranslationPlan = BuildPlan(gContext.mModelSource.v.position, directionUnary[type - ROTATE_X]);
}
const float len = IntersectRayPlane(gContext.mRayOrigin, gContext.mRayVector, gContext.mTranslationPlan);
vec_t localPos = gContext.mRayOrigin + gContext.mRayVector * len - gContext.mModel.v.position;
gContext.mRotationVectorSource = Normalized(localPos);
gContext.mRotationAngleOrigin = ComputeAngleOnPlan();
}
}
// rotation
if (gContext.mbUsing)
{
ImGui::CaptureMouseFromApp();
gContext.mRotationAngle = ComputeAngleOnPlan();
if (snap)
{
float snapInRadian = snap[0] * DEG2RAD;
ComputeSnap(&gContext.mRotationAngle, snapInRadian);
}
vec_t rotationAxisLocalSpace;
rotationAxisLocalSpace.TransformVector(makeVect(gContext.mTranslationPlan.x, gContext.mTranslationPlan.y, gContext.mTranslationPlan.z, 0.f), gContext.mModelInverse);
rotationAxisLocalSpace.Normalize();
matrix_t deltaRotation;
deltaRotation.RotationAxis(rotationAxisLocalSpace, gContext.mRotationAngle - gContext.mRotationAngleOrigin);
gContext.mRotationAngleOrigin = gContext.mRotationAngle;
matrix_t scaleOrigin;
scaleOrigin.Scale(gContext.mModelScaleOrigin);
if (applyRotationLocaly)
{
*(matrix_t*)matrix = scaleOrigin * deltaRotation * gContext.mModel;
}
else
{
matrix_t res = gContext.mModelSource;
res.v.position.Set(0.f);
*(matrix_t*)matrix = res * deltaRotation;
((matrix_t*)matrix)->v.position = gContext.mModelSource.v.position;
}
if (deltaMatrix)
{
*(matrix_t*)deltaMatrix = gContext.mModelInverse * deltaRotation * gContext.mModel;
}
if (!io.MouseDown[0])
gContext.mbUsing = false;
type = gContext.mCurrentOperation;
}
}
void DecomposeMatrixToComponents(const float *matrix, float *translation, float *rotation, float *scale)
{
matrix_t mat = *(matrix_t*)matrix;
scale[0] = mat.v.right.Length();
scale[1] = mat.v.up.Length();
scale[2] = mat.v.dir.Length();
mat.OrthoNormalize();
rotation[0] = RAD2DEG * atan2f(mat.m[1][2], mat.m[2][2]);
rotation[1] = RAD2DEG * atan2f(-mat.m[0][2], sqrtf(mat.m[1][2] * mat.m[1][2] + mat.m[2][2]* mat.m[2][2]));
rotation[2] = RAD2DEG * atan2f(mat.m[0][1], mat.m[0][0]);
translation[0] = mat.v.position.x;
translation[1] = mat.v.position.y;
translation[2] = mat.v.position.z;
}
void RecomposeMatrixFromComponents(const float *translation, const float *rotation, const float *scale, float *matrix)
{
matrix_t& mat = *(matrix_t*)matrix;
matrix_t rot[3];
for (int i = 0; i < 3;i++)
rot[i].RotationAxis(directionUnary[i], rotation[i] * DEG2RAD);
mat = rot[0] * rot[1] * rot[2];
float validScale[3];
for (int i = 0; i < 3; i++)
{
if (fabsf(scale[i]) < FLT_EPSILON)
validScale[i] = 0.001f;
else
validScale[i] = scale[i];
}
mat.v.right *= validScale[0];
mat.v.up *= validScale[1];
mat.v.dir *= validScale[2];
mat.v.position.Set(translation[0], translation[1], translation[2], 1.f);
}
void Manipulate(const float *view, const float *projection, OPERATION operation, MODE mode, float *matrix, float *deltaMatrix, float *snap, float *localBounds, float *boundsSnap)
{
ComputeContext(view, projection, matrix, mode);
// set delta to identity
if (deltaMatrix)
((matrix_t*)deltaMatrix)->SetToIdentity();
// behind camera
vec_t camSpacePosition;
camSpacePosition.TransformPoint(makeVect(0.f, 0.f, 0.f), gContext.mMVP);
if (!gContext.mIsOrthographic && camSpacePosition.z < 0.001f)
return;
// --
int type = NONE;
if (gContext.mbEnable)
{
if (!gContext.mbUsingBounds)
{
switch (operation)
{
case ROTATE:
HandleRotation(matrix, deltaMatrix, type, snap);
break;
case TRANSLATE:
HandleTranslation(matrix, deltaMatrix, type, snap);
break;
case SCALE:
HandleScale(matrix, deltaMatrix, type, snap);
break;
case BOUNDS:
break;
}
}
}
if (localBounds && !gContext.mbUsing)
HandleAndDrawLocalBounds(localBounds, (matrix_t*)matrix, boundsSnap, operation);
if (!gContext.mbUsingBounds)
{
switch (operation)
{
case ROTATE:
DrawRotationGizmo(type);
break;
case TRANSLATE:
DrawTranslationGizmo(type);
break;
case SCALE:
DrawScaleGizmo(type);
break;
case BOUNDS:
break;
}
}
}
void DrawCube(const float *view, const float *projection, const float *matrix)
{
matrix_t viewInverse;
viewInverse.Inverse(*(matrix_t*)view);
const matrix_t& model = *(matrix_t*)matrix;
matrix_t res = *(matrix_t*)matrix * *(matrix_t*)view * *(matrix_t*)projection;
for (int iFace = 0; iFace < 6; iFace++)
{
const int normalIndex = (iFace % 3);
const int perpXIndex = (normalIndex + 1) % 3;
const int perpYIndex = (normalIndex + 2) % 3;
const float invert = (iFace > 2) ? -1.f : 1.f;
const vec_t faceCoords[4] = { directionUnary[normalIndex] + directionUnary[perpXIndex] + directionUnary[perpYIndex],
directionUnary[normalIndex] + directionUnary[perpXIndex] - directionUnary[perpYIndex],
directionUnary[normalIndex] - directionUnary[perpXIndex] - directionUnary[perpYIndex],
directionUnary[normalIndex] - directionUnary[perpXIndex] + directionUnary[perpYIndex],
};
// clipping
bool skipFace = false;
for (unsigned int iCoord = 0; iCoord < 4; iCoord++)
{
vec_t camSpacePosition;
camSpacePosition.TransformPoint(faceCoords[iCoord] * 0.5f * invert, gContext.mMVP);
if (camSpacePosition.z > 0.001f)
{
skipFace = true;
break;
}
}
if (skipFace)
continue;
// 3D->2D
ImVec2 faceCoordsScreen[4];
for (unsigned int iCoord = 0; iCoord < 4; iCoord++)
faceCoordsScreen[iCoord] = worldToPos(faceCoords[iCoord] * 0.5f * invert, res);
// back face culling
vec_t cullPos, cullNormal;
cullPos.TransformPoint(faceCoords[0] * 0.5f * invert, model);
cullNormal.TransformVector(directionUnary[normalIndex] * invert, model);
float dt = Dot(Normalized(cullPos - viewInverse.v.position), Normalized(cullNormal));
if (dt>0.f)
continue;
// draw face with lighter color
gContext.mDrawList->AddConvexPolyFilled(faceCoordsScreen, 4, directionColor[normalIndex] | 0x808080);
}
}
void DrawGrid(const float *view, const float *projection, const float *matrix, const float gridSize)
{
matrix_t res = *(matrix_t*)matrix * *(matrix_t*)view * *(matrix_t*)projection;
for (float f = -gridSize; f <= gridSize; f += 1.f)
{
gContext.mDrawList->AddLine(worldToPos(makeVect(f, 0.f, -gridSize), res), worldToPos(makeVect(f, 0.f, gridSize), res), 0xFF808080);
gContext.mDrawList->AddLine(worldToPos(makeVect(-gridSize, 0.f, f), res), worldToPos(makeVect(gridSize, 0.f, f), res), 0xFF808080);
}
}
};
|
// Copyright (c) 2014 The Bitcoin Core developers
// Copyright (c) 2014-2015 The Dash developers
//
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "primitives/transaction.h"
#include "main.h"
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_SUITE(main_tests)
CAmount nMoneySupplyPoWEnd = 43199500 * COIN;
BOOST_AUTO_TEST_CASE(subsidy_limit_test)
{
CAmount nSum = 0;
for (int nHeight = 0; nHeight < 1; nHeight += 1) {
/* premine in block 1 (60,001 EGAMES) */
CAmount nSubsidy = GetBlockValue(nHeight);
BOOST_CHECK(nSubsidy <= 60001 * COIN);
nSum += nSubsidy;
}
for (int nHeight = 1; nHeight < 86400; nHeight += 1) {
/* PoW Phase One */
CAmount nSubsidy = GetBlockValue(nHeight);
BOOST_CHECK(nSubsidy <= 250 * COIN);
nSum += nSubsidy;
}
for (int nHeight = 86400; nHeight < 151200; nHeight += 1) {
/* PoW Phase Two */
CAmount nSubsidy = GetBlockValue(nHeight);
BOOST_CHECK(nSubsidy <= 225 * COIN);
nSum += nSubsidy;
}
for (int nHeight = 151200; nHeight < 259200; nHeight += 1) {
/* PoW Phase Two */
CAmount nSubsidy = GetBlockValue(nHeight);
BOOST_CHECK(nSubsidy <= 45 * COIN);
BOOST_CHECK(MoneyRange(nSubsidy));
nSum += nSubsidy;
BOOST_CHECK(nSum > 0 && nSum <= nMoneySupplyPoWEnd);
}
BOOST_CHECK(nSum == 4109975100000000ULL);
}
BOOST_AUTO_TEST_SUITE_END()
|
#include "CodeTree.h"
void CodeTree::buildCodeTree(FrequencyTable& table) {
fillHeap(table);
constructTree();
}
void CodeTree::fillHeap(FrequencyTable& table) {
for (auto& pair : table) {
huffmanMinHeap.push(std::move(make_shared<HuffmanTreeNode>(pair.first, pair.second)));
}
}
void CodeTree::constructTree() {
char symbolForSumOfFrequences = '$';
while (huffmanMinHeap.size() > 1) {
auto minimumFrequencePair = huffmanMinHeap.top();
huffmanMinHeap.pop();
auto secondMinimumFrequencePair = huffmanMinHeap.top();
huffmanMinHeap.pop();
shared_ptr<HuffmanTreeNode> newNode = make_shared<HuffmanTreeNode>();
newNode->leftChild = minimumFrequencePair;
newNode->rightChild = secondMinimumFrequencePair;
newNode->symbol = symbolForSumOfFrequences;
newNode->frequency = minimumFrequencePair->frequency + secondMinimumFrequencePair->frequency;
huffmanMinHeap.push(newNode);
}
root = huffmanMinHeap.top();
}
|
#include "widget.h"
#include <QApplication>
#include <QDesktopWidget>
#include <QRect>
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
Widget w;
w.setWindowState(Qt::WindowMinimized); /* start the application minimized */
w.show();
return a.exec();
}
|
/***********************************************************************************************+
* @brief -- XX -- Library - CPP Source file
* \par
* \par @DETAILS
*
*
* \li LIMITATION-TO-CLASS
* \li LIMITATION-TO-CLASS
*
* @note ANY RELEVANT NOTES
*
* @file esp32_sal.cpp
* @author N.G Pedersen <nikolajgliese@tutanota.com>
* @version 1.0
* @date 2022-01-07
* @copyright --
*
*
***********************************************************************************************/
#include "../include/esp32_http_sal.hpp"
#include "../include/esp32_http_settings.hpp"
//#define DEBUG // default uncommeted
//#ifdef DEBUG
static const char* LOG_TAG = "esp32_sal";
//#endif
static std::string m_recieved_content;
static FreeRTOS::Semaphore m_semaphore_client_handler; // there should only be one
#ifdef __ESP32__
esp_err_t esp32_http_sal::_http_event_handle(esp_http_client_event_t* evt)
{
switch(evt->event_id)
{
case HTTP_EVENT_ERROR:
LOG_PRINT_INFO(LOG_TAG, "HTTP_EVENT_ERROR");
break;
case HTTP_EVENT_ON_CONNECTED:
LOG_PRINT_INFO(LOG_TAG, "HTTP_EVENT_ON_CONNECTED");
break;
case HTTP_EVENT_HEADER_SENT:
LOG_PRINT_INFO(LOG_TAG, "HTTP_EVENT_HEADER_SENT");
break;
case HTTP_EVENT_ON_HEADER:
LOG_PRINT_INFO(LOG_TAG, "HTTP_EVENT_ON_HEADER");
printf("%.*s", evt->data_len, (char*)evt->data);
break;
case HTTP_EVENT_ON_DATA:
LOG_PRINT_INFO(LOG_TAG, "HTTP_EVENT_ON_DATA, len=%d", evt->data_len);
if(!esp_http_client_is_chunked_response(evt->client))
{
std::string str((char*)evt->data, (size_t)evt->data_len);
m_recieved_content = str;
#ifdef DEBUG
std::cout << "recieved data is : <" << m_recieved_content << ">\n";
#endif
}
break;
case HTTP_EVENT_ON_FINISH:
LOG_PRINT_INFO(LOG_TAG, "HTTP_EVENT_ON_FINISH");
break;
case HTTP_EVENT_DISCONNECTED:
LOG_PRINT_INFO(LOG_TAG, "HTTP_EVENT_DISCONNECTED");
break;
}
return ESP_OK;
}
#endif
esp32_http_sal::esp32_http_sal(const std::string& server, const int& port)
: m_server{server}, m_port{port}
{
}
esp32_http_sal::~esp32_http_sal() {}
general_err_t esp32_http_sal::get(const std::string& api_call, std::string& output)
{
#ifdef DEBUG
LOG_PRINT_INFO(LOG_TAG, ">> esp32_sal::get >> ");
#endif
// Executable code:
std::cout << " calling get request : <" << m_server << api_call << "> on port <" << m_port
<< ">\n";
if(!m_semaphore_client_handler.take(5000, m_server + api_call + std::to_string(m_port)))
{
std::cerr << " Not able to take semaphore! \n";
return GE_SEMAPHORE_NOT_TAKEN;
}
general_err_t ge_err = GE_OK;
#ifdef __ESP32__
esp_http_client_config_t config = DEFAULT_HTTP_CONFIG;
config.url = m_server.c_str();
config.host = m_server.c_str();
config.port = m_port;
config.path = api_call.c_str();
config.event_handler = this->_http_event_handle;
#ifdef DEBUG
LOG_PRINT_INFO(LOG_TAG, ">> getting handle ... >> ");
#endif
m_client = esp_http_client_init(&config);
#ifdef DEBUG
LOG_PRINT_INFO(LOG_TAG, ">> handle OK ... >> ");
#endif
#ifdef DEBUG
LOG_PRINT_INFO(LOG_TAG, ">> Perform http request ... >> ");
#endif
// GET
esp_err_t err = esp_http_client_perform(m_client);
if(err == ESP_OK)
{
std::cout << " HTTP Get Status : <" << (int)esp_http_client_get_status_code(m_client)
<< "> , content length : <" << (int)esp_http_client_get_content_length(m_client)
<< ">\n";
output = m_recieved_content;
}
else
{
std::cout << "Error in HTTP request <" << (int)err << ">\n";
ge_err = GE_FAIL;
}
esp_http_client_cleanup(m_client);
// make sure we release the semaphore
m_semaphore_client_handler.give();
#endif
#ifdef DEBUG
LOG_PRINT_INFO(LOG_TAG, "<< esp32_sal::get << ");
#endif
return ge_err;
}
general_err_t esp32_http_sal::get(const std::string& api_call, json& output)
{
#ifdef DEBUG
LOG_PRINT_INFO(LOG_TAG, ">> esp32_http_sal::getJSON >> ");
#endif
// Executable code:
std::string str;
auto err = get(api_call, str);
if(err != GE_OK)
{
Logger::write({err, GR_NO_RESPONSE, "Not able to call get command <" + api_call + ">"});
return err;
}
output = json::parse(str, nullptr, false);
if(output.is_discarded())
{
Logger::write({GE_NO_DATA, GR_NO_RESPONSE,
"Not able to convert string to json: str<" + str + "> : json <" +
output.dump() + ">"});
return GE_NO_DATA;
}
#ifdef DEBUG
LOG_PRINT_INFO(LOG_TAG, "<< esp32_http_sal::getJSON << ");
#endif
return GE_OK;
}
general_err_t esp32_http_sal::post(const std::string& api_call, const std::string& content)
{
#ifdef DEBUG
LOG_PRINT_INFO(LOG_TAG, ">> esp32_sal::post >> ");
#endif
// Executable code:
#ifdef DEBUG
LOG_PRINT_INFO(LOG_TAG, "<< esp32_sal::post << ");
#endif
return GE_OK;
}
|
#ifndef IMAGE_VIEW_HPP_INCLUDED
#define IMAGE_VIEW_HPP_INCLUDED
#include <vector>
#include <fstream>
#include <string>
#include <iostream>
#include <vector>
#include <memory>
#include "vulkan_include.hpp"
#include "logical_device.hpp"
namespace vkBasalt{
std::vector<VkImageView> createImageViews(std::shared_ptr<LogicalDevice> pLogicalDevice, VkFormat format, std::vector<VkImage> images, VkImageViewType viewType = VK_IMAGE_VIEW_TYPE_2D, VkImageAspectFlags aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, uint32_t mipLevels = 1);
}
#endif // IMAGE_VIEW_HPP_INCLUDED
|
#include "config/config.hpp"
#include <json/json.h>
#include <fstream>
namespace taraxa {
std::string getConfigErr(std::vector<string> path) {
std::string res = "Error in processing configuration file on param: ";
for (size_t i = 0; i < path.size(); i++) res += path[i] + ".";
res += " ";
return res;
}
Json::Value getConfigData(Json::Value root, std::vector<string> const &path, bool optional = false) {
for (size_t i = 0; i < path.size(); i++) {
root = root[path[i]];
if (root.isNull() && !optional) {
throw ConfigException(getConfigErr(path) + "Element missing: " + path[i]);
}
}
return root;
}
std::string getConfigDataAsString(Json::Value const &root, std::vector<string> const &path) {
try {
return getConfigData(root, path).asString();
} catch (Json::Exception &e) {
throw ConfigException(getConfigErr(path) + e.what());
}
}
uint32_t getConfigDataAsUInt(Json::Value const &root, std::vector<string> const &path, bool optional = false,
uint32_t value = 0) {
try {
Json::Value ret = getConfigData(root, path, optional);
if (ret.isNull()) {
return value;
} else {
return ret.asUInt();
}
} catch (Json::Exception &e) {
if (optional) {
return value;
}
throw ConfigException(getConfigErr(path) + e.what());
}
}
uint64_t getConfigDataAsUInt64(Json::Value const &root, std::vector<string> const &path) {
try {
return getConfigData(root, path).asUInt64();
} catch (Json::Exception &e) {
throw ConfigException(getConfigErr(path) + e.what());
}
}
bool getConfigDataAsBoolean(Json::Value const &root, std::vector<string> const &path) {
try {
return getConfigData(root, path).asBool();
} catch (Json::Exception &e) {
throw ConfigException(getConfigErr(path) + e.what());
}
}
Json::Value getJsonFromFileOrString(Json::Value const &value) {
if (value.isString()) {
std::string json_file_name = value.asString();
if (!json_file_name.empty()) {
std::ifstream config_doc(json_file_name, std::ifstream::binary);
if (!config_doc.is_open()) {
throw ConfigException(string("Could not open configuration file: ") + json_file_name);
}
try {
Json::Value parsed_from_file;
config_doc >> parsed_from_file;
return parsed_from_file;
} catch (Json::Exception &e) {
throw ConfigException(string("Could not parse json configuration file: ") + json_file_name + e.what());
}
}
}
return value;
}
FullNodeConfig::FullNodeConfig(Json::Value const &string_or_object, Json::Value const &wallet) {
Json::Value parsed_from_file = getJsonFromFileOrString(string_or_object);
if (string_or_object.isString()) {
json_file_name = string_or_object.asString();
}
auto const &root = string_or_object.isString() ? parsed_from_file : string_or_object;
data_path = getConfigDataAsString(root, {"data_path"});
db_path = data_path / "db";
if (auto n = getConfigData(root, {"network_is_boot_node"}, true); !n.isNull()) {
network.network_is_boot_node = n.asBool();
}
network.network_address = getConfigDataAsString(root, {"network_address"});
network.network_tcp_port = getConfigDataAsUInt(root, {"network_tcp_port"});
network.network_simulated_delay = getConfigDataAsUInt(root, {"network_simulated_delay"});
network.network_performance_log_interval =
getConfigDataAsUInt(root, {"network_performance_log_interval"}, true, 30000 /*ms*/);
network.network_transaction_interval = getConfigDataAsUInt(root, {"network_transaction_interval"});
network.network_bandwidth = getConfigDataAsUInt(root, {"network_bandwidth"});
network.network_ideal_peer_count = getConfigDataAsUInt(root, {"network_ideal_peer_count"});
network.network_max_peer_count = getConfigDataAsUInt(root, {"network_max_peer_count"});
network.network_sync_level_size = getConfigDataAsUInt(root, {"network_sync_level_size"});
network.network_packets_processing_threads = getConfigDataAsUInt(root, {"network_packets_processing_threads"});
for (auto &item : root["network_boot_nodes"]) {
NodeConfig node;
node.id = getConfigDataAsString(item, {"id"});
node.ip = getConfigDataAsString(item, {"ip"});
node.tcp_port = getConfigDataAsUInt(item, {"tcp_port"});
network.network_boot_nodes.push_back(node);
}
// Rpc config
if (auto rpc_config = getConfigData(root, {"rpc"}, true); !rpc_config.isNull()) {
rpc = RpcConfig();
// ip address
rpc->address = boost::asio::ip::address::from_string(network.network_address);
// http port
if (auto http_port = getConfigData(rpc_config, {"http_port"}, true); !http_port.isNull()) {
rpc->http_port = http_port.asUInt();
}
// websocket port
if (auto ws_port = getConfigData(rpc_config, {"ws_port"}, true); !ws_port.isNull()) {
rpc->ws_port = ws_port.asUInt();
}
// number of threads processing rpc calls
if (auto threads_num = getConfigData(rpc_config, {"threads_num"}, true); !threads_num.isNull()) {
rpc->threads_num = threads_num.asUInt();
}
}
{ // for test experiments
test_params.max_transactions_pool_warn = getConfigDataAsUInt(root, {"test_params", "max_transactions_pool_warn"});
test_params.max_transactions_pool_drop = getConfigDataAsUInt(root, {"test_params", "max_transactions_pool_drop"});
test_params.max_block_queue_warn = getConfigDataAsUInt(root, {"test_params", "max_block_queue_warn"}, true);
// Create db snapshot each N pbft block
test_params.db_snapshot_each_n_pbft_block =
getConfigDataAsUInt(root, {"test_params", "db_snapshot_each_n_pbft_block"}, true);
test_params.db_max_snapshots = getConfigDataAsUInt(root, {"test_params", "db_max_snapshots"}, true);
// DAG proposal
test_params.block_proposer.shard = getConfigDataAsUInt(root, {"test_params", "block_proposer", "shard"});
test_params.block_proposer.transaction_limit =
getConfigDataAsUInt(root, {"test_params", "block_proposer", "transaction_limit"});
}
// Network logging in p2p library creates performance issues even with
// channel/verbosity off Disable it completely in net channel is not present
if (!root["logging"].isNull()) {
if (auto path = getConfigData(root["logging"], {"log_path"}, true); !path.isNull()) {
log_path = path.asString();
} else {
log_path = data_path / "logs";
}
for (auto &item : root["logging"]["configurations"]) {
auto on = getConfigDataAsBoolean(item, {"on"});
if (on) {
logger::Config logging;
logging.name = getConfigDataAsString(item, {"name"});
logging.verbosity = logger::stringToVerbosity(getConfigDataAsString(item, {"verbosity"}));
for (auto &ch : item["channels"]) {
std::pair<std::string, uint16_t> channel;
channel.first = getConfigDataAsString(ch, {"name"});
if (ch["verbosity"].isNull()) {
channel.second = logging.verbosity;
} else {
channel.second = logger::stringToVerbosity(getConfigDataAsString(ch, {"verbosity"}));
}
logging.channels[channel.first] = channel.second;
}
for (auto &o : item["outputs"]) {
logger::Config::OutputConfig output;
output.type = getConfigDataAsString(o, {"type"});
output.format = getConfigDataAsString(o, {"format"});
if (output.type == "file") {
output.target = log_path;
output.file_name = (log_path / getConfigDataAsString(o, {"file_name"})).string();
output.format = getConfigDataAsString(o, {"format"});
output.max_size = getConfigDataAsUInt64(o, {"max_size"});
output.rotation_size = getConfigDataAsUInt64(o, {"rotation_size"});
output.time_based_rotation = getConfigDataAsString(o, {"time_based_rotation"});
}
logging.outputs.push_back(output);
}
log_configs.push_back(logging);
}
}
}
if (auto const &v = root["chain_config"]; v.isString()) {
chain = ChainConfig::predefined(v.asString());
} else if (v.isObject()) {
dec_json(v, chain);
} else {
chain = ChainConfig::predefined();
}
node_secret = wallet["node_secret"].asString();
vrf_secret = vrf_wrapper::vrf_sk_t(wallet["vrf_secret"].asString());
network.network_id = chain.chain_id;
// TODO configurable
opts_final_chain.expected_max_trx_per_block = 1000;
opts_final_chain.max_trie_full_node_levels_to_cache = 4;
}
void FullNodeConfig::validate() {
// Max enabled number of threads for processing rpc requests
constexpr uint16_t MAX_PACKETS_PROCESSING_THREADS_NUM = 30;
if (network.network_packets_processing_threads < 3 ||
network.network_packets_processing_threads > MAX_PACKETS_PROCESSING_THREADS_NUM) {
throw ConfigException(std::string("network_packets_processing_threads must be in range [3, ") +
std::to_string(MAX_PACKETS_PROCESSING_THREADS_NUM) + "]");
}
// Validates rpc config values
if (rpc) {
if (!rpc->http_port && !rpc->ws_port) {
throw ConfigException("Either rpc::http_port or rpc::ws_port post must be specified for rpc");
}
// Max enabled number of threads for processing rpc requests
constexpr uint16_t MAX_RPC_THREADS_NUM = 10;
if (rpc->threads_num <= 0 || rpc->threads_num > MAX_RPC_THREADS_NUM) {
throw ConfigException(string("rpc::threads_num must be in range (0, ") + std::to_string(MAX_RPC_THREADS_NUM) +
"]");
}
}
// TODO validate that the boot node list doesn't contain self (although it's not critical)
for (auto const &node : network.network_boot_nodes) {
if (node.ip.empty()) {
throw ConfigException(std::string("Boot node ip is empty:") + node.ip + ":" + std::to_string(node.tcp_port));
}
if (node.tcp_port == 0) {
throw ConfigException(std::string("Boot node port invalid: ") + std::to_string(node.tcp_port));
}
}
// TODO: add validation of other config values
}
std::ostream &operator<<(std::ostream &strm, NodeConfig const &conf) {
strm << " [Node Config] " << std::endl;
strm << " node_id: " << conf.id << std::endl;
strm << " node_ip: " << conf.ip << std::endl;
strm << " node_tcp_port: " << conf.tcp_port << std::endl;
return strm;
}
std::ostream &operator<<(std::ostream &strm, NetworkConfig const &conf) {
strm << "[Network Config] " << std::endl;
strm << " json_file_name: " << conf.json_file_name << std::endl;
strm << " network_is_boot_node: " << conf.network_is_boot_node << std::endl;
strm << " network_address: " << conf.network_address << std::endl;
strm << " network_tcp_port: " << conf.network_tcp_port << std::endl;
strm << " network_simulated_delay: " << conf.network_simulated_delay << std::endl;
strm << " network_transaction_interval: " << conf.network_transaction_interval << std::endl;
strm << " network_bandwidth: " << conf.network_bandwidth << std::endl;
strm << " network_ideal_peer_count: " << conf.network_ideal_peer_count << std::endl;
strm << " network_max_peer_count: " << conf.network_max_peer_count << std::endl;
strm << " network_sync_level_size: " << conf.network_sync_level_size << std::endl;
strm << " network_id: " << conf.network_id << std::endl;
strm << " network_performance_log_interval: " << conf.network_performance_log_interval << std::endl;
strm << " network_num_threads: " << conf.network_num_threads << std::endl;
strm << " network_packets_processing_threads: " << conf.network_packets_processing_threads << std::endl;
strm << " --> boot nodes ... " << std::endl;
for (auto const &c : conf.network_boot_nodes) {
strm << c << std::endl;
}
return strm;
}
std::ostream &operator<<(std::ostream &strm, FullNodeConfig const &conf) {
strm << std::ifstream(conf.json_file_name).rdbuf() << std::endl;
return strm;
}
} // namespace taraxa
|
//===- HWAddressSanitizer.cpp - detector of uninitialized reads -------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
/// \file
/// This file is a part of HWAddressSanitizer, an address sanity checker
/// based on tagged addressing.
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/Triple.h"
#include "llvm/BinaryFormat/ELF.h"
#include "llvm/IR/Attributes.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/InlineAsm.h"
#include "llvm/IR/InstVisitor.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/MDBuilder.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Value.h"
#include "llvm/InitializePasses.h"
#include "llvm/Pass.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Instrumentation.h"
#include "llvm/Transforms/Instrumentation/AddressSanitizerCommon.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Utils/ModuleUtils.h"
#include "llvm/Transforms/Utils/PromoteMemToReg.h"
#include <sstream>
using namespace llvm;
#define DEBUG_TYPE "hwasan"
static const char *const kHwasanModuleCtorName = "hwasan.module_ctor";
static const char *const kHwasanNoteName = "hwasan.note";
static const char *const kHwasanInitName = "__hwasan_init";
static const char *const kHwasanPersonalityThunkName =
"__hwasan_personality_thunk";
static const char *const kHwasanShadowMemoryDynamicAddress =
"__hwasan_shadow_memory_dynamic_address";
// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
static const size_t kNumberOfAccessSizes = 5;
static const size_t kDefaultShadowScale = 4;
static const uint64_t kDynamicShadowSentinel =
std::numeric_limits<uint64_t>::max();
static const unsigned kPointerTagShift = 56;
static const unsigned kShadowBaseAlignment = 32;
static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
"hwasan-memory-access-callback-prefix",
cl::desc("Prefix for memory access callbacks"), cl::Hidden,
cl::init("__hwasan_"));
static cl::opt<bool>
ClInstrumentWithCalls("hwasan-instrument-with-calls",
cl::desc("instrument reads and writes with callbacks"),
cl::Hidden, cl::init(false));
static cl::opt<bool> ClInstrumentReads("hwasan-instrument-reads",
cl::desc("instrument read instructions"),
cl::Hidden, cl::init(true));
static cl::opt<bool> ClInstrumentWrites(
"hwasan-instrument-writes", cl::desc("instrument write instructions"),
cl::Hidden, cl::init(true));
static cl::opt<bool> ClInstrumentAtomics(
"hwasan-instrument-atomics",
cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
cl::init(true));
static cl::opt<bool> ClInstrumentByval("hwasan-instrument-byval",
cl::desc("instrument byval arguments"),
cl::Hidden, cl::init(true));
static cl::opt<bool> ClRecover(
"hwasan-recover",
cl::desc("Enable recovery mode (continue-after-error)."),
cl::Hidden, cl::init(false));
static cl::opt<bool> ClInstrumentStack("hwasan-instrument-stack",
cl::desc("instrument stack (allocas)"),
cl::Hidden, cl::init(true));
static cl::opt<bool> ClUARRetagToZero(
"hwasan-uar-retag-to-zero",
cl::desc("Clear alloca tags before returning from the function to allow "
"non-instrumented and instrumented function calls mix. When set "
"to false, allocas are retagged before returning from the "
"function to detect use after return."),
cl::Hidden, cl::init(true));
static cl::opt<bool> ClGenerateTagsWithCalls(
"hwasan-generate-tags-with-calls",
cl::desc("generate new tags with runtime library calls"), cl::Hidden,
cl::init(false));
static cl::opt<bool> ClGlobals("hwasan-globals", cl::desc("Instrument globals"),
cl::Hidden, cl::init(false), cl::ZeroOrMore);
static cl::opt<int> ClMatchAllTag(
"hwasan-match-all-tag",
cl::desc("don't report bad accesses via pointers with this tag"),
cl::Hidden, cl::init(-1));
static cl::opt<bool> ClEnableKhwasan(
"hwasan-kernel",
cl::desc("Enable KernelHWAddressSanitizer instrumentation"),
cl::Hidden, cl::init(false));
// These flags allow to change the shadow mapping and control how shadow memory
// is accessed. The shadow mapping looks like:
// Shadow = (Mem >> scale) + offset
static cl::opt<uint64_t>
ClMappingOffset("hwasan-mapping-offset",
cl::desc("HWASan shadow mapping offset [EXPERIMENTAL]"),
cl::Hidden, cl::init(0));
static cl::opt<bool>
ClWithIfunc("hwasan-with-ifunc",
cl::desc("Access dynamic shadow through an ifunc global on "
"platforms that support this"),
cl::Hidden, cl::init(false));
static cl::opt<bool> ClWithTls(
"hwasan-with-tls",
cl::desc("Access dynamic shadow through an thread-local pointer on "
"platforms that support this"),
cl::Hidden, cl::init(true));
static cl::opt<bool>
ClRecordStackHistory("hwasan-record-stack-history",
cl::desc("Record stack frames with tagged allocations "
"in a thread-local ring buffer"),
cl::Hidden, cl::init(true));
static cl::opt<bool>
ClInstrumentMemIntrinsics("hwasan-instrument-mem-intrinsics",
cl::desc("instrument memory intrinsics"),
cl::Hidden, cl::init(true));
static cl::opt<bool>
ClInstrumentLandingPads("hwasan-instrument-landing-pads",
cl::desc("instrument landing pads"), cl::Hidden,
cl::init(false), cl::ZeroOrMore);
static cl::opt<bool> ClUseShortGranules(
"hwasan-use-short-granules",
cl::desc("use short granules in allocas and outlined checks"), cl::Hidden,
cl::init(false), cl::ZeroOrMore);
static cl::opt<bool> ClInstrumentPersonalityFunctions(
"hwasan-instrument-personality-functions",
cl::desc("instrument personality functions"), cl::Hidden, cl::init(false),
cl::ZeroOrMore);
static cl::opt<bool> ClInlineAllChecks("hwasan-inline-all-checks",
cl::desc("inline all checks"),
cl::Hidden, cl::init(false));
namespace {
/// An instrumentation pass implementing detection of addressability bugs
/// using tagged pointers.
class HWAddressSanitizer {
public:
explicit HWAddressSanitizer(Module &M, bool CompileKernel = false,
bool Recover = false) : M(M) {
this->Recover = ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover;
this->CompileKernel = ClEnableKhwasan.getNumOccurrences() > 0 ?
ClEnableKhwasan : CompileKernel;
initializeModule();
}
bool sanitizeFunction(Function &F);
void initializeModule();
void createHwasanCtorComdat();
void initializeCallbacks(Module &M);
Value *getDynamicShadowIfunc(IRBuilder<> &IRB);
Value *getDynamicShadowNonTls(IRBuilder<> &IRB);
void untagPointerOperand(Instruction *I, Value *Addr);
Value *shadowBase();
Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
void instrumentMemAccessInline(Value *Ptr, bool IsWrite,
unsigned AccessSizeIndex,
Instruction *InsertBefore);
void instrumentMemIntrinsic(MemIntrinsic *MI);
bool instrumentMemAccess(InterestingMemoryOperand &O);
bool ignoreAccess(Value *Ptr);
void getInterestingMemoryOperands(
Instruction *I, SmallVectorImpl<InterestingMemoryOperand> &Interesting);
bool isInterestingAlloca(const AllocaInst &AI);
bool tagAlloca(IRBuilder<> &IRB, AllocaInst *AI, Value *Tag, size_t Size);
Value *tagPointer(IRBuilder<> &IRB, Type *Ty, Value *PtrLong, Value *Tag);
Value *untagPointer(IRBuilder<> &IRB, Value *PtrLong);
bool instrumentStack(
SmallVectorImpl<AllocaInst *> &Allocas,
DenseMap<AllocaInst *, std::vector<DbgVariableIntrinsic *>> &AllocaDbgMap,
SmallVectorImpl<Instruction *> &RetVec, Value *StackTag);
Value *readRegister(IRBuilder<> &IRB, StringRef Name);
bool instrumentLandingPads(SmallVectorImpl<Instruction *> &RetVec);
Value *getNextTagWithCall(IRBuilder<> &IRB);
Value *getStackBaseTag(IRBuilder<> &IRB);
Value *getAllocaTag(IRBuilder<> &IRB, Value *StackTag, AllocaInst *AI,
unsigned AllocaNo);
Value *getUARTag(IRBuilder<> &IRB, Value *StackTag);
Value *getHwasanThreadSlotPtr(IRBuilder<> &IRB, Type *Ty);
void emitPrologue(IRBuilder<> &IRB, bool WithFrameRecord);
void instrumentGlobal(GlobalVariable *GV, uint8_t Tag);
void instrumentGlobals();
void instrumentPersonalityFunctions();
private:
LLVMContext *C;
Module &M;
Triple TargetTriple;
FunctionCallee HWAsanMemmove, HWAsanMemcpy, HWAsanMemset;
FunctionCallee HWAsanHandleVfork;
/// This struct defines the shadow mapping using the rule:
/// shadow = (mem >> Scale) + Offset.
/// If InGlobal is true, then
/// extern char __hwasan_shadow[];
/// shadow = (mem >> Scale) + &__hwasan_shadow
/// If InTls is true, then
/// extern char *__hwasan_tls;
/// shadow = (mem>>Scale) + align_up(__hwasan_shadow, kShadowBaseAlignment)
struct ShadowMapping {
int Scale;
uint64_t Offset;
bool InGlobal;
bool InTls;
void init(Triple &TargetTriple);
unsigned getObjectAlignment() const { return 1U << Scale; }
};
ShadowMapping Mapping;
Type *VoidTy = Type::getVoidTy(M.getContext());
Type *IntptrTy;
Type *Int8PtrTy;
Type *Int8Ty;
Type *Int32Ty;
Type *Int64Ty = Type::getInt64Ty(M.getContext());
bool CompileKernel;
bool Recover;
bool UseShortGranules;
bool InstrumentLandingPads;
Function *HwasanCtorFunction;
FunctionCallee HwasanMemoryAccessCallback[2][kNumberOfAccessSizes];
FunctionCallee HwasanMemoryAccessCallbackSized[2];
FunctionCallee HwasanTagMemoryFunc;
FunctionCallee HwasanGenerateTagFunc;
Constant *ShadowGlobal;
Value *LocalDynamicShadow = nullptr;
Value *StackBaseTag = nullptr;
GlobalValue *ThreadPtrGlobal = nullptr;
};
class HWAddressSanitizerLegacyPass : public FunctionPass {
public:
// Pass identification, replacement for typeid.
static char ID;
explicit HWAddressSanitizerLegacyPass(bool CompileKernel = false,
bool Recover = false)
: FunctionPass(ID), CompileKernel(CompileKernel), Recover(Recover) {
initializeHWAddressSanitizerLegacyPassPass(
*PassRegistry::getPassRegistry());
}
StringRef getPassName() const override { return "HWAddressSanitizer"; }
bool doInitialization(Module &M) override {
HWASan = std::make_unique<HWAddressSanitizer>(M, CompileKernel, Recover);
return true;
}
bool runOnFunction(Function &F) override {
return HWASan->sanitizeFunction(F);
}
bool doFinalization(Module &M) override {
HWASan.reset();
return false;
}
private:
std::unique_ptr<HWAddressSanitizer> HWASan;
bool CompileKernel;
bool Recover;
};
} // end anonymous namespace
char HWAddressSanitizerLegacyPass::ID = 0;
INITIALIZE_PASS_BEGIN(
HWAddressSanitizerLegacyPass, "hwasan",
"HWAddressSanitizer: detect memory bugs using tagged addressing.", false,
false)
INITIALIZE_PASS_END(
HWAddressSanitizerLegacyPass, "hwasan",
"HWAddressSanitizer: detect memory bugs using tagged addressing.", false,
false)
FunctionPass *llvm::createHWAddressSanitizerLegacyPassPass(bool CompileKernel,
bool Recover) {
assert(!CompileKernel || Recover);
return new HWAddressSanitizerLegacyPass(CompileKernel, Recover);
}
HWAddressSanitizerPass::HWAddressSanitizerPass(bool CompileKernel, bool Recover)
: CompileKernel(CompileKernel), Recover(Recover) {}
PreservedAnalyses HWAddressSanitizerPass::run(Module &M,
ModuleAnalysisManager &MAM) {
HWAddressSanitizer HWASan(M, CompileKernel, Recover);
bool Modified = false;
for (Function &F : M)
Modified |= HWASan.sanitizeFunction(F);
if (Modified)
return PreservedAnalyses::none();
return PreservedAnalyses::all();
}
void HWAddressSanitizer::createHwasanCtorComdat() {
std::tie(HwasanCtorFunction, std::ignore) =
getOrCreateSanitizerCtorAndInitFunctions(
M, kHwasanModuleCtorName, kHwasanInitName,
/*InitArgTypes=*/{},
/*InitArgs=*/{},
// This callback is invoked when the functions are created the first
// time. Hook them into the global ctors list in that case:
[&](Function *Ctor, FunctionCallee) {
Comdat *CtorComdat = M.getOrInsertComdat(kHwasanModuleCtorName);
Ctor->setComdat(CtorComdat);
appendToGlobalCtors(M, Ctor, 0, Ctor);
});
// Create a note that contains pointers to the list of global
// descriptors. Adding a note to the output file will cause the linker to
// create a PT_NOTE program header pointing to the note that we can use to
// find the descriptor list starting from the program headers. A function
// provided by the runtime initializes the shadow memory for the globals by
// accessing the descriptor list via the note. The dynamic loader needs to
// call this function whenever a library is loaded.
//
// The reason why we use a note for this instead of a more conventional
// approach of having a global constructor pass a descriptor list pointer to
// the runtime is because of an order of initialization problem. With
// constructors we can encounter the following problematic scenario:
//
// 1) library A depends on library B and also interposes one of B's symbols
// 2) B's constructors are called before A's (as required for correctness)
// 3) during construction, B accesses one of its "own" globals (actually
// interposed by A) and triggers a HWASAN failure due to the initialization
// for A not having happened yet
//
// Even without interposition it is possible to run into similar situations in
// cases where two libraries mutually depend on each other.
//
// We only need one note per binary, so put everything for the note in a
// comdat. This needs to be a comdat with an .init_array section to prevent
// newer versions of lld from discarding the note.
//
// Create the note even if we aren't instrumenting globals. This ensures that
// binaries linked from object files with both instrumented and
// non-instrumented globals will end up with a note, even if a comdat from an
// object file with non-instrumented globals is selected. The note is harmless
// if the runtime doesn't support it, since it will just be ignored.
Comdat *NoteComdat = M.getOrInsertComdat(kHwasanModuleCtorName);
Type *Int8Arr0Ty = ArrayType::get(Int8Ty, 0);
auto Start =
new GlobalVariable(M, Int8Arr0Ty, true, GlobalVariable::ExternalLinkage,
nullptr, "__start_hwasan_globals");
Start->setVisibility(GlobalValue::HiddenVisibility);
Start->setDSOLocal(true);
auto Stop =
new GlobalVariable(M, Int8Arr0Ty, true, GlobalVariable::ExternalLinkage,
nullptr, "__stop_hwasan_globals");
Stop->setVisibility(GlobalValue::HiddenVisibility);
Stop->setDSOLocal(true);
// Null-terminated so actually 8 bytes, which are required in order to align
// the note properly.
auto *Name = ConstantDataArray::get(*C, "LLVM\0\0\0");
auto *NoteTy = StructType::get(Int32Ty, Int32Ty, Int32Ty, Name->getType(),
Int32Ty, Int32Ty);
auto *Note =
new GlobalVariable(M, NoteTy, /*isConstantGlobal=*/true,
GlobalValue::PrivateLinkage, nullptr, kHwasanNoteName);
Note->setSection(".note.hwasan.globals");
Note->setComdat(NoteComdat);
Note->setAlignment(Align(4));
Note->setDSOLocal(true);
// The pointers in the note need to be relative so that the note ends up being
// placed in rodata, which is the standard location for notes.
auto CreateRelPtr = [&](Constant *Ptr) {
return ConstantExpr::getTrunc(
ConstantExpr::getSub(ConstantExpr::getPtrToInt(Ptr, Int64Ty),
ConstantExpr::getPtrToInt(Note, Int64Ty)),
Int32Ty);
};
Note->setInitializer(ConstantStruct::getAnon(
{ConstantInt::get(Int32Ty, 8), // n_namesz
ConstantInt::get(Int32Ty, 8), // n_descsz
ConstantInt::get(Int32Ty, ELF::NT_LLVM_HWASAN_GLOBALS), // n_type
Name, CreateRelPtr(Start), CreateRelPtr(Stop)}));
appendToCompilerUsed(M, Note);
// Create a zero-length global in hwasan_globals so that the linker will
// always create start and stop symbols.
auto Dummy = new GlobalVariable(
M, Int8Arr0Ty, /*isConstantGlobal*/ true, GlobalVariable::PrivateLinkage,
Constant::getNullValue(Int8Arr0Ty), "hwasan.dummy.global");
Dummy->setSection("hwasan_globals");
Dummy->setComdat(NoteComdat);
Dummy->setMetadata(LLVMContext::MD_associated,
MDNode::get(*C, ValueAsMetadata::get(Note)));
appendToCompilerUsed(M, Dummy);
}
/// Module-level initialization.
///
/// inserts a call to __hwasan_init to the module's constructor list.
void HWAddressSanitizer::initializeModule() {
LLVM_DEBUG(dbgs() << "Init " << M.getName() << "\n");
auto &DL = M.getDataLayout();
TargetTriple = Triple(M.getTargetTriple());
Mapping.init(TargetTriple);
C = &(M.getContext());
IRBuilder<> IRB(*C);
IntptrTy = IRB.getIntPtrTy(DL);
Int8PtrTy = IRB.getInt8PtrTy();
Int8Ty = IRB.getInt8Ty();
Int32Ty = IRB.getInt32Ty();
HwasanCtorFunction = nullptr;
// Older versions of Android do not have the required runtime support for
// short granules, global or personality function instrumentation. On other
// platforms we currently require using the latest version of the runtime.
bool NewRuntime =
!TargetTriple.isAndroid() || !TargetTriple.isAndroidVersionLT(30);
UseShortGranules =
ClUseShortGranules.getNumOccurrences() ? ClUseShortGranules : NewRuntime;
// If we don't have personality function support, fall back to landing pads.
InstrumentLandingPads = ClInstrumentLandingPads.getNumOccurrences()
? ClInstrumentLandingPads
: !NewRuntime;
if (!CompileKernel) {
createHwasanCtorComdat();
bool InstrumentGlobals =
ClGlobals.getNumOccurrences() ? ClGlobals : NewRuntime;
if (InstrumentGlobals)
instrumentGlobals();
bool InstrumentPersonalityFunctions =
ClInstrumentPersonalityFunctions.getNumOccurrences()
? ClInstrumentPersonalityFunctions
: NewRuntime;
if (InstrumentPersonalityFunctions)
instrumentPersonalityFunctions();
}
if (!TargetTriple.isAndroid()) {
Constant *C = M.getOrInsertGlobal("__hwasan_tls", IntptrTy, [&] {
auto *GV = new GlobalVariable(M, IntptrTy, /*isConstant=*/false,
GlobalValue::ExternalLinkage, nullptr,
"__hwasan_tls", nullptr,
GlobalVariable::InitialExecTLSModel);
appendToCompilerUsed(M, GV);
return GV;
});
ThreadPtrGlobal = cast<GlobalVariable>(C);
}
}
void HWAddressSanitizer::initializeCallbacks(Module &M) {
IRBuilder<> IRB(*C);
for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
const std::string TypeStr = AccessIsWrite ? "store" : "load";
const std::string EndingStr = Recover ? "_noabort" : "";
HwasanMemoryAccessCallbackSized[AccessIsWrite] = M.getOrInsertFunction(
ClMemoryAccessCallbackPrefix + TypeStr + "N" + EndingStr,
FunctionType::get(IRB.getVoidTy(), {IntptrTy, IntptrTy}, false));
for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
AccessSizeIndex++) {
HwasanMemoryAccessCallback[AccessIsWrite][AccessSizeIndex] =
M.getOrInsertFunction(
ClMemoryAccessCallbackPrefix + TypeStr +
itostr(1ULL << AccessSizeIndex) + EndingStr,
FunctionType::get(IRB.getVoidTy(), {IntptrTy}, false));
}
}
HwasanTagMemoryFunc = M.getOrInsertFunction(
"__hwasan_tag_memory", IRB.getVoidTy(), Int8PtrTy, Int8Ty, IntptrTy);
HwasanGenerateTagFunc =
M.getOrInsertFunction("__hwasan_generate_tag", Int8Ty);
ShadowGlobal = M.getOrInsertGlobal("__hwasan_shadow",
ArrayType::get(IRB.getInt8Ty(), 0));
const std::string MemIntrinCallbackPrefix =
CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
HWAsanMemmove = M.getOrInsertFunction(MemIntrinCallbackPrefix + "memmove",
IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
IRB.getInt8PtrTy(), IntptrTy);
HWAsanMemcpy = M.getOrInsertFunction(MemIntrinCallbackPrefix + "memcpy",
IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
IRB.getInt8PtrTy(), IntptrTy);
HWAsanMemset = M.getOrInsertFunction(MemIntrinCallbackPrefix + "memset",
IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
IRB.getInt32Ty(), IntptrTy);
HWAsanHandleVfork =
M.getOrInsertFunction("__hwasan_handle_vfork", IRB.getVoidTy(), IntptrTy);
}
Value *HWAddressSanitizer::getDynamicShadowIfunc(IRBuilder<> &IRB) {
// An empty inline asm with input reg == output reg.
// An opaque no-op cast, basically.
InlineAsm *Asm = InlineAsm::get(
FunctionType::get(Int8PtrTy, {ShadowGlobal->getType()}, false),
StringRef(""), StringRef("=r,0"),
/*hasSideEffects=*/false);
return IRB.CreateCall(Asm, {ShadowGlobal}, ".hwasan.shadow");
}
Value *HWAddressSanitizer::getDynamicShadowNonTls(IRBuilder<> &IRB) {
// Generate code only when dynamic addressing is needed.
if (Mapping.Offset != kDynamicShadowSentinel)
return nullptr;
if (Mapping.InGlobal) {
return getDynamicShadowIfunc(IRB);
} else {
Value *GlobalDynamicAddress =
IRB.GetInsertBlock()->getParent()->getParent()->getOrInsertGlobal(
kHwasanShadowMemoryDynamicAddress, Int8PtrTy);
return IRB.CreateLoad(Int8PtrTy, GlobalDynamicAddress);
}
}
bool HWAddressSanitizer::ignoreAccess(Value *Ptr) {
// Do not instrument acesses from different address spaces; we cannot deal
// with them.
Type *PtrTy = cast<PointerType>(Ptr->getType()->getScalarType());
if (PtrTy->getPointerAddressSpace() != 0)
return true;
// Ignore swifterror addresses.
// swifterror memory addresses are mem2reg promoted by instruction
// selection. As such they cannot have regular uses like an instrumentation
// function and it makes no sense to track them as memory.
if (Ptr->isSwiftError())
return true;
return false;
}
void HWAddressSanitizer::getInterestingMemoryOperands(
Instruction *I, SmallVectorImpl<InterestingMemoryOperand> &Interesting) {
// Skip memory accesses inserted by another instrumentation.
if (I->hasMetadata("nosanitize"))
return;
// Do not instrument the load fetching the dynamic shadow address.
if (LocalDynamicShadow == I)
return;
if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
if (!ClInstrumentReads || ignoreAccess(LI->getPointerOperand()))
return;
Interesting.emplace_back(I, LI->getPointerOperandIndex(), false,
LI->getType(), LI->getAlign());
} else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
if (!ClInstrumentWrites || ignoreAccess(SI->getPointerOperand()))
return;
Interesting.emplace_back(I, SI->getPointerOperandIndex(), true,
SI->getValueOperand()->getType(), SI->getAlign());
} else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
if (!ClInstrumentAtomics || ignoreAccess(RMW->getPointerOperand()))
return;
Interesting.emplace_back(I, RMW->getPointerOperandIndex(), true,
RMW->getValOperand()->getType(), None);
} else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
if (!ClInstrumentAtomics || ignoreAccess(XCHG->getPointerOperand()))
return;
Interesting.emplace_back(I, XCHG->getPointerOperandIndex(), true,
XCHG->getCompareOperand()->getType(), None);
} else if (auto CI = dyn_cast<CallInst>(I)) {
for (unsigned ArgNo = 0; ArgNo < CI->getNumArgOperands(); ArgNo++) {
if (!ClInstrumentByval || !CI->isByValArgument(ArgNo) ||
ignoreAccess(CI->getArgOperand(ArgNo)))
continue;
Type *Ty = CI->getParamByValType(ArgNo);
Interesting.emplace_back(I, ArgNo, false, Ty, Align(1));
}
}
}
static unsigned getPointerOperandIndex(Instruction *I) {
if (LoadInst *LI = dyn_cast<LoadInst>(I))
return LI->getPointerOperandIndex();
if (StoreInst *SI = dyn_cast<StoreInst>(I))
return SI->getPointerOperandIndex();
if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I))
return RMW->getPointerOperandIndex();
if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I))
return XCHG->getPointerOperandIndex();
report_fatal_error("Unexpected instruction");
return -1;
}
static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
size_t Res = countTrailingZeros(TypeSize / 8);
assert(Res < kNumberOfAccessSizes);
return Res;
}
void HWAddressSanitizer::untagPointerOperand(Instruction *I, Value *Addr) {
if (TargetTriple.isAArch64())
return;
IRBuilder<> IRB(I);
Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Value *UntaggedPtr =
IRB.CreateIntToPtr(untagPointer(IRB, AddrLong), Addr->getType());
I->setOperand(getPointerOperandIndex(I), UntaggedPtr);
}
Value *HWAddressSanitizer::shadowBase() {
if (LocalDynamicShadow)
return LocalDynamicShadow;
return ConstantExpr::getIntToPtr(ConstantInt::get(IntptrTy, Mapping.Offset),
Int8PtrTy);
}
Value *HWAddressSanitizer::memToShadow(Value *Mem, IRBuilder<> &IRB) {
// Mem >> Scale
Value *Shadow = IRB.CreateLShr(Mem, Mapping.Scale);
if (Mapping.Offset == 0)
return IRB.CreateIntToPtr(Shadow, Int8PtrTy);
// (Mem >> Scale) + Offset
return IRB.CreateGEP(Int8Ty, shadowBase(), Shadow);
}
void HWAddressSanitizer::instrumentMemAccessInline(Value *Ptr, bool IsWrite,
unsigned AccessSizeIndex,
Instruction *InsertBefore) {
const int64_t AccessInfo = Recover * 0x20 + IsWrite * 0x10 + AccessSizeIndex;
IRBuilder<> IRB(InsertBefore);
if (!ClInlineAllChecks && TargetTriple.isAArch64() &&
TargetTriple.isOSBinFormatELF() && !Recover) {
Module *M = IRB.GetInsertBlock()->getParent()->getParent();
Ptr = IRB.CreateBitCast(Ptr, Int8PtrTy);
IRB.CreateCall(Intrinsic::getDeclaration(
M, UseShortGranules
? Intrinsic::hwasan_check_memaccess_shortgranules
: Intrinsic::hwasan_check_memaccess),
{shadowBase(), Ptr, ConstantInt::get(Int32Ty, AccessInfo)});
return;
}
Value *PtrLong = IRB.CreatePointerCast(Ptr, IntptrTy);
Value *PtrTag = IRB.CreateTrunc(IRB.CreateLShr(PtrLong, kPointerTagShift),
IRB.getInt8Ty());
Value *AddrLong = untagPointer(IRB, PtrLong);
Value *Shadow = memToShadow(AddrLong, IRB);
Value *MemTag = IRB.CreateLoad(Int8Ty, Shadow);
Value *TagMismatch = IRB.CreateICmpNE(PtrTag, MemTag);
int matchAllTag = ClMatchAllTag.getNumOccurrences() > 0 ?
ClMatchAllTag : (CompileKernel ? 0xFF : -1);
if (matchAllTag != -1) {
Value *TagNotIgnored = IRB.CreateICmpNE(PtrTag,
ConstantInt::get(PtrTag->getType(), matchAllTag));
TagMismatch = IRB.CreateAnd(TagMismatch, TagNotIgnored);
}
Instruction *CheckTerm =
SplitBlockAndInsertIfThen(TagMismatch, InsertBefore, false,
MDBuilder(*C).createBranchWeights(1, 100000));
IRB.SetInsertPoint(CheckTerm);
Value *OutOfShortGranuleTagRange =
IRB.CreateICmpUGT(MemTag, ConstantInt::get(Int8Ty, 15));
Instruction *CheckFailTerm =
SplitBlockAndInsertIfThen(OutOfShortGranuleTagRange, CheckTerm, !Recover,
MDBuilder(*C).createBranchWeights(1, 100000));
IRB.SetInsertPoint(CheckTerm);
Value *PtrLowBits = IRB.CreateTrunc(IRB.CreateAnd(PtrLong, 15), Int8Ty);
PtrLowBits = IRB.CreateAdd(
PtrLowBits, ConstantInt::get(Int8Ty, (1 << AccessSizeIndex) - 1));
Value *PtrLowBitsOOB = IRB.CreateICmpUGE(PtrLowBits, MemTag);
SplitBlockAndInsertIfThen(PtrLowBitsOOB, CheckTerm, false,
MDBuilder(*C).createBranchWeights(1, 100000),
nullptr, nullptr, CheckFailTerm->getParent());
IRB.SetInsertPoint(CheckTerm);
Value *InlineTagAddr = IRB.CreateOr(AddrLong, 15);
InlineTagAddr = IRB.CreateIntToPtr(InlineTagAddr, Int8PtrTy);
Value *InlineTag = IRB.CreateLoad(Int8Ty, InlineTagAddr);
Value *InlineTagMismatch = IRB.CreateICmpNE(PtrTag, InlineTag);
SplitBlockAndInsertIfThen(InlineTagMismatch, CheckTerm, false,
MDBuilder(*C).createBranchWeights(1, 100000),
nullptr, nullptr, CheckFailTerm->getParent());
IRB.SetInsertPoint(CheckFailTerm);
InlineAsm *Asm;
switch (TargetTriple.getArch()) {
case Triple::x86_64:
// The signal handler will find the data address in rdi.
Asm = InlineAsm::get(
FunctionType::get(IRB.getVoidTy(), {PtrLong->getType()}, false),
"int3\nnopl " + itostr(0x40 + AccessInfo) + "(%rax)",
"{rdi}",
/*hasSideEffects=*/true);
break;
case Triple::aarch64:
case Triple::aarch64_be:
// The signal handler will find the data address in x0.
Asm = InlineAsm::get(
FunctionType::get(IRB.getVoidTy(), {PtrLong->getType()}, false),
"brk #" + itostr(0x900 + AccessInfo),
"{x0}",
/*hasSideEffects=*/true);
break;
default:
report_fatal_error("unsupported architecture");
}
IRB.CreateCall(Asm, PtrLong);
if (Recover)
cast<BranchInst>(CheckFailTerm)->setSuccessor(0, CheckTerm->getParent());
}
void HWAddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
IRBuilder<> IRB(MI);
if (isa<MemTransferInst>(MI)) {
IRB.CreateCall(
isa<MemMoveInst>(MI) ? HWAsanMemmove : HWAsanMemcpy,
{IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
} else if (isa<MemSetInst>(MI)) {
IRB.CreateCall(
HWAsanMemset,
{IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
}
MI->eraseFromParent();
}
bool HWAddressSanitizer::instrumentMemAccess(InterestingMemoryOperand &O) {
Value *Addr = O.getPtr();
LLVM_DEBUG(dbgs() << "Instrumenting: " << O.getInsn() << "\n");
if (O.MaybeMask)
return false; //FIXME
IRBuilder<> IRB(O.getInsn());
if (isPowerOf2_64(O.TypeSize) &&
(O.TypeSize / 8 <= (1ULL << (kNumberOfAccessSizes - 1))) &&
(!O.Alignment || *O.Alignment >= (1ULL << Mapping.Scale) ||
*O.Alignment >= O.TypeSize / 8)) {
size_t AccessSizeIndex = TypeSizeToSizeIndex(O.TypeSize);
if (ClInstrumentWithCalls) {
IRB.CreateCall(HwasanMemoryAccessCallback[O.IsWrite][AccessSizeIndex],
IRB.CreatePointerCast(Addr, IntptrTy));
} else {
instrumentMemAccessInline(Addr, O.IsWrite, AccessSizeIndex, O.getInsn());
}
} else {
IRB.CreateCall(HwasanMemoryAccessCallbackSized[O.IsWrite],
{IRB.CreatePointerCast(Addr, IntptrTy),
ConstantInt::get(IntptrTy, O.TypeSize / 8)});
}
untagPointerOperand(O.getInsn(), Addr);
return true;
}
static uint64_t getAllocaSizeInBytes(const AllocaInst &AI) {
uint64_t ArraySize = 1;
if (AI.isArrayAllocation()) {
const ConstantInt *CI = dyn_cast<ConstantInt>(AI.getArraySize());
assert(CI && "non-constant array size");
ArraySize = CI->getZExtValue();
}
Type *Ty = AI.getAllocatedType();
uint64_t SizeInBytes = AI.getModule()->getDataLayout().getTypeAllocSize(Ty);
return SizeInBytes * ArraySize;
}
bool HWAddressSanitizer::tagAlloca(IRBuilder<> &IRB, AllocaInst *AI,
Value *Tag, size_t Size) {
size_t AlignedSize = alignTo(Size, Mapping.getObjectAlignment());
if (!UseShortGranules)
Size = AlignedSize;
Value *JustTag = IRB.CreateTrunc(Tag, IRB.getInt8Ty());
if (ClInstrumentWithCalls) {
IRB.CreateCall(HwasanTagMemoryFunc,
{IRB.CreatePointerCast(AI, Int8PtrTy), JustTag,
ConstantInt::get(IntptrTy, AlignedSize)});
} else {
size_t ShadowSize = Size >> Mapping.Scale;
Value *ShadowPtr = memToShadow(IRB.CreatePointerCast(AI, IntptrTy), IRB);
// If this memset is not inlined, it will be intercepted in the hwasan
// runtime library. That's OK, because the interceptor skips the checks if
// the address is in the shadow region.
// FIXME: the interceptor is not as fast as real memset. Consider lowering
// llvm.memset right here into either a sequence of stores, or a call to
// hwasan_tag_memory.
if (ShadowSize)
IRB.CreateMemSet(ShadowPtr, JustTag, ShadowSize, Align(1));
if (Size != AlignedSize) {
IRB.CreateStore(
ConstantInt::get(Int8Ty, Size % Mapping.getObjectAlignment()),
IRB.CreateConstGEP1_32(Int8Ty, ShadowPtr, ShadowSize));
IRB.CreateStore(JustTag, IRB.CreateConstGEP1_32(
Int8Ty, IRB.CreateBitCast(AI, Int8PtrTy),
AlignedSize - 1));
}
}
return true;
}
static unsigned RetagMask(unsigned AllocaNo) {
// A list of 8-bit numbers that have at most one run of non-zero bits.
// x = x ^ (mask << 56) can be encoded as a single armv8 instruction for these
// masks.
// The list does not include the value 255, which is used for UAR.
//
// Because we are more likely to use earlier elements of this list than later
// ones, it is sorted in increasing order of probability of collision with a
// mask allocated (temporally) nearby. The program that generated this list
// can be found at:
// https://github.com/google/sanitizers/blob/master/hwaddress-sanitizer/sort_masks.py
static unsigned FastMasks[] = {0, 128, 64, 192, 32, 96, 224, 112, 240,
48, 16, 120, 248, 56, 24, 8, 124, 252,
60, 28, 12, 4, 126, 254, 62, 30, 14,
6, 2, 127, 63, 31, 15, 7, 3, 1};
return FastMasks[AllocaNo % (sizeof(FastMasks) / sizeof(FastMasks[0]))];
}
Value *HWAddressSanitizer::getNextTagWithCall(IRBuilder<> &IRB) {
return IRB.CreateZExt(IRB.CreateCall(HwasanGenerateTagFunc), IntptrTy);
}
Value *HWAddressSanitizer::getStackBaseTag(IRBuilder<> &IRB) {
if (ClGenerateTagsWithCalls)
return getNextTagWithCall(IRB);
if (StackBaseTag)
return StackBaseTag;
// FIXME: use addressofreturnaddress (but implement it in aarch64 backend
// first).
Module *M = IRB.GetInsertBlock()->getParent()->getParent();
auto GetStackPointerFn = Intrinsic::getDeclaration(
M, Intrinsic::frameaddress,
IRB.getInt8PtrTy(M->getDataLayout().getAllocaAddrSpace()));
Value *StackPointer = IRB.CreateCall(
GetStackPointerFn, {Constant::getNullValue(IRB.getInt32Ty())});
// Extract some entropy from the stack pointer for the tags.
// Take bits 20..28 (ASLR entropy) and xor with bits 0..8 (these differ
// between functions).
Value *StackPointerLong = IRB.CreatePointerCast(StackPointer, IntptrTy);
Value *StackTag =
IRB.CreateXor(StackPointerLong, IRB.CreateLShr(StackPointerLong, 20),
"hwasan.stack.base.tag");
return StackTag;
}
Value *HWAddressSanitizer::getAllocaTag(IRBuilder<> &IRB, Value *StackTag,
AllocaInst *AI, unsigned AllocaNo) {
if (ClGenerateTagsWithCalls)
return getNextTagWithCall(IRB);
return IRB.CreateXor(StackTag,
ConstantInt::get(IntptrTy, RetagMask(AllocaNo)));
}
Value *HWAddressSanitizer::getUARTag(IRBuilder<> &IRB, Value *StackTag) {
if (ClUARRetagToZero)
return ConstantInt::get(IntptrTy, 0);
if (ClGenerateTagsWithCalls)
return getNextTagWithCall(IRB);
return IRB.CreateXor(StackTag, ConstantInt::get(IntptrTy, 0xFFU));
}
// Add a tag to an address.
Value *HWAddressSanitizer::tagPointer(IRBuilder<> &IRB, Type *Ty,
Value *PtrLong, Value *Tag) {
Value *TaggedPtrLong;
if (CompileKernel) {
// Kernel addresses have 0xFF in the most significant byte.
Value *ShiftedTag = IRB.CreateOr(
IRB.CreateShl(Tag, kPointerTagShift),
ConstantInt::get(IntptrTy, (1ULL << kPointerTagShift) - 1));
TaggedPtrLong = IRB.CreateAnd(PtrLong, ShiftedTag);
} else {
// Userspace can simply do OR (tag << 56);
Value *ShiftedTag = IRB.CreateShl(Tag, kPointerTagShift);
TaggedPtrLong = IRB.CreateOr(PtrLong, ShiftedTag);
}
return IRB.CreateIntToPtr(TaggedPtrLong, Ty);
}
// Remove tag from an address.
Value *HWAddressSanitizer::untagPointer(IRBuilder<> &IRB, Value *PtrLong) {
Value *UntaggedPtrLong;
if (CompileKernel) {
// Kernel addresses have 0xFF in the most significant byte.
UntaggedPtrLong = IRB.CreateOr(PtrLong,
ConstantInt::get(PtrLong->getType(), 0xFFULL << kPointerTagShift));
} else {
// Userspace addresses have 0x00.
UntaggedPtrLong = IRB.CreateAnd(PtrLong,
ConstantInt::get(PtrLong->getType(), ~(0xFFULL << kPointerTagShift)));
}
return UntaggedPtrLong;
}
Value *HWAddressSanitizer::getHwasanThreadSlotPtr(IRBuilder<> &IRB, Type *Ty) {
Module *M = IRB.GetInsertBlock()->getParent()->getParent();
if (TargetTriple.isAArch64() && TargetTriple.isAndroid()) {
// Android provides a fixed TLS slot for sanitizers. See TLS_SLOT_SANITIZER
// in Bionic's libc/private/bionic_tls.h.
Function *ThreadPointerFunc =
Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
Value *SlotPtr = IRB.CreatePointerCast(
IRB.CreateConstGEP1_32(IRB.getInt8Ty(),
IRB.CreateCall(ThreadPointerFunc), 0x30),
Ty->getPointerTo(0));
return SlotPtr;
}
if (ThreadPtrGlobal)
return ThreadPtrGlobal;
return nullptr;
}
void HWAddressSanitizer::emitPrologue(IRBuilder<> &IRB, bool WithFrameRecord) {
if (!Mapping.InTls) {
LocalDynamicShadow = getDynamicShadowNonTls(IRB);
return;
}
if (!WithFrameRecord && TargetTriple.isAndroid()) {
LocalDynamicShadow = getDynamicShadowIfunc(IRB);
return;
}
Value *SlotPtr = getHwasanThreadSlotPtr(IRB, IntptrTy);
assert(SlotPtr);
Value *ThreadLong = IRB.CreateLoad(IntptrTy, SlotPtr);
// Extract the address field from ThreadLong. Unnecessary on AArch64 with TBI.
Value *ThreadLongMaybeUntagged =
TargetTriple.isAArch64() ? ThreadLong : untagPointer(IRB, ThreadLong);
if (WithFrameRecord) {
Function *F = IRB.GetInsertBlock()->getParent();
StackBaseTag = IRB.CreateAShr(ThreadLong, 3);
// Prepare ring buffer data.
Value *PC;
if (TargetTriple.getArch() == Triple::aarch64)
PC = readRegister(IRB, "pc");
else
PC = IRB.CreatePtrToInt(F, IntptrTy);
Module *M = F->getParent();
auto GetStackPointerFn = Intrinsic::getDeclaration(
M, Intrinsic::frameaddress,
IRB.getInt8PtrTy(M->getDataLayout().getAllocaAddrSpace()));
Value *SP = IRB.CreatePtrToInt(
IRB.CreateCall(GetStackPointerFn,
{Constant::getNullValue(IRB.getInt32Ty())}),
IntptrTy);
// Mix SP and PC.
// Assumptions:
// PC is 0x0000PPPPPPPPPPPP (48 bits are meaningful, others are zero)
// SP is 0xsssssssssssSSSS0 (4 lower bits are zero)
// We only really need ~20 lower non-zero bits (SSSS), so we mix like this:
// 0xSSSSPPPPPPPPPPPP
SP = IRB.CreateShl(SP, 44);
// Store data to ring buffer.
Value *RecordPtr =
IRB.CreateIntToPtr(ThreadLongMaybeUntagged, IntptrTy->getPointerTo(0));
IRB.CreateStore(IRB.CreateOr(PC, SP), RecordPtr);
// Update the ring buffer. Top byte of ThreadLong defines the size of the
// buffer in pages, it must be a power of two, and the start of the buffer
// must be aligned by twice that much. Therefore wrap around of the ring
// buffer is simply Addr &= ~((ThreadLong >> 56) << 12).
// The use of AShr instead of LShr is due to
// https://bugs.llvm.org/show_bug.cgi?id=39030
// Runtime library makes sure not to use the highest bit.
Value *WrapMask = IRB.CreateXor(
IRB.CreateShl(IRB.CreateAShr(ThreadLong, 56), 12, "", true, true),
ConstantInt::get(IntptrTy, (uint64_t)-1));
Value *ThreadLongNew = IRB.CreateAnd(
IRB.CreateAdd(ThreadLong, ConstantInt::get(IntptrTy, 8)), WrapMask);
IRB.CreateStore(ThreadLongNew, SlotPtr);
}
// Get shadow base address by aligning RecordPtr up.
// Note: this is not correct if the pointer is already aligned.
// Runtime library will make sure this never happens.
LocalDynamicShadow = IRB.CreateAdd(
IRB.CreateOr(
ThreadLongMaybeUntagged,
ConstantInt::get(IntptrTy, (1ULL << kShadowBaseAlignment) - 1)),
ConstantInt::get(IntptrTy, 1), "hwasan.shadow");
LocalDynamicShadow = IRB.CreateIntToPtr(LocalDynamicShadow, Int8PtrTy);
}
Value *HWAddressSanitizer::readRegister(IRBuilder<> &IRB, StringRef Name) {
Module *M = IRB.GetInsertBlock()->getParent()->getParent();
Function *ReadRegister =
Intrinsic::getDeclaration(M, Intrinsic::read_register, IntptrTy);
MDNode *MD = MDNode::get(*C, {MDString::get(*C, Name)});
Value *Args[] = {MetadataAsValue::get(*C, MD)};
return IRB.CreateCall(ReadRegister, Args);
}
bool HWAddressSanitizer::instrumentLandingPads(
SmallVectorImpl<Instruction *> &LandingPadVec) {
for (auto *LP : LandingPadVec) {
IRBuilder<> IRB(LP->getNextNode());
IRB.CreateCall(
HWAsanHandleVfork,
{readRegister(IRB, (TargetTriple.getArch() == Triple::x86_64) ? "rsp"
: "sp")});
}
return true;
}
bool HWAddressSanitizer::instrumentStack(
SmallVectorImpl<AllocaInst *> &Allocas,
DenseMap<AllocaInst *, std::vector<DbgVariableIntrinsic *>> &AllocaDbgMap,
SmallVectorImpl<Instruction *> &RetVec, Value *StackTag) {
// Ideally, we want to calculate tagged stack base pointer, and rewrite all
// alloca addresses using that. Unfortunately, offsets are not known yet
// (unless we use ASan-style mega-alloca). Instead we keep the base tag in a
// temp, shift-OR it into each alloca address and xor with the retag mask.
// This generates one extra instruction per alloca use.
for (unsigned N = 0; N < Allocas.size(); ++N) {
auto *AI = Allocas[N];
IRBuilder<> IRB(AI->getNextNode());
// Replace uses of the alloca with tagged address.
Value *Tag = getAllocaTag(IRB, StackTag, AI, N);
Value *AILong = IRB.CreatePointerCast(AI, IntptrTy);
Value *Replacement = tagPointer(IRB, AI->getType(), AILong, Tag);
std::string Name =
AI->hasName() ? AI->getName().str() : "alloca." + itostr(N);
Replacement->setName(Name + ".hwasan");
AI->replaceUsesWithIf(Replacement,
[AILong](Use &U) { return U.getUser() != AILong; });
for (auto *DDI : AllocaDbgMap.lookup(AI)) {
// Prepend "tag_offset, N" to the dwarf expression.
// Tag offset logically applies to the alloca pointer, and it makes sense
// to put it at the beginning of the expression.
SmallVector<uint64_t, 8> NewOps = {dwarf::DW_OP_LLVM_tag_offset,
RetagMask(N)};
DDI->setArgOperand(
2, MetadataAsValue::get(*C, DIExpression::prependOpcodes(
DDI->getExpression(), NewOps)));
}
size_t Size = getAllocaSizeInBytes(*AI);
tagAlloca(IRB, AI, Tag, Size);
for (auto RI : RetVec) {
IRB.SetInsertPoint(RI);
// Re-tag alloca memory with the special UAR tag.
Value *Tag = getUARTag(IRB, StackTag);
tagAlloca(IRB, AI, Tag, alignTo(Size, Mapping.getObjectAlignment()));
}
}
return true;
}
bool HWAddressSanitizer::isInterestingAlloca(const AllocaInst &AI) {
return (AI.getAllocatedType()->isSized() &&
// FIXME: instrument dynamic allocas, too
AI.isStaticAlloca() &&
// alloca() may be called with 0 size, ignore it.
getAllocaSizeInBytes(AI) > 0 &&
// We are only interested in allocas not promotable to registers.
// Promotable allocas are common under -O0.
!isAllocaPromotable(&AI) &&
// inalloca allocas are not treated as static, and we don't want
// dynamic alloca instrumentation for them as well.
!AI.isUsedWithInAlloca() &&
// swifterror allocas are register promoted by ISel
!AI.isSwiftError());
}
bool HWAddressSanitizer::sanitizeFunction(Function &F) {
if (&F == HwasanCtorFunction)
return false;
if (!F.hasFnAttribute(Attribute::SanitizeHWAddress))
return false;
LLVM_DEBUG(dbgs() << "Function: " << F.getName() << "\n");
SmallVector<InterestingMemoryOperand, 16> OperandsToInstrument;
SmallVector<MemIntrinsic *, 16> IntrinToInstrument;
SmallVector<AllocaInst*, 8> AllocasToInstrument;
SmallVector<Instruction*, 8> RetVec;
SmallVector<Instruction*, 8> LandingPadVec;
DenseMap<AllocaInst *, std::vector<DbgVariableIntrinsic *>> AllocaDbgMap;
for (auto &BB : F) {
for (auto &Inst : BB) {
if (ClInstrumentStack)
if (AllocaInst *AI = dyn_cast<AllocaInst>(&Inst)) {
if (isInterestingAlloca(*AI))
AllocasToInstrument.push_back(AI);
continue;
}
if (isa<ReturnInst>(Inst) || isa<ResumeInst>(Inst) ||
isa<CleanupReturnInst>(Inst))
RetVec.push_back(&Inst);
if (auto *DDI = dyn_cast<DbgVariableIntrinsic>(&Inst))
if (auto *Alloca =
dyn_cast_or_null<AllocaInst>(DDI->getVariableLocation()))
AllocaDbgMap[Alloca].push_back(DDI);
if (InstrumentLandingPads && isa<LandingPadInst>(Inst))
LandingPadVec.push_back(&Inst);
getInterestingMemoryOperands(&Inst, OperandsToInstrument);
if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&Inst))
IntrinToInstrument.push_back(MI);
}
}
initializeCallbacks(*F.getParent());
bool Changed = false;
if (!LandingPadVec.empty())
Changed |= instrumentLandingPads(LandingPadVec);
if (AllocasToInstrument.empty() && F.hasPersonalityFn() &&
F.getPersonalityFn()->getName() == kHwasanPersonalityThunkName) {
// __hwasan_personality_thunk is a no-op for functions without an
// instrumented stack, so we can drop it.
F.setPersonalityFn(nullptr);
Changed = true;
}
if (AllocasToInstrument.empty() && OperandsToInstrument.empty() &&
IntrinToInstrument.empty())
return Changed;
assert(!LocalDynamicShadow);
Instruction *InsertPt = &*F.getEntryBlock().begin();
IRBuilder<> EntryIRB(InsertPt);
emitPrologue(EntryIRB,
/*WithFrameRecord*/ ClRecordStackHistory &&
!AllocasToInstrument.empty());
if (!AllocasToInstrument.empty()) {
Value *StackTag =
ClGenerateTagsWithCalls ? nullptr : getStackBaseTag(EntryIRB);
instrumentStack(AllocasToInstrument, AllocaDbgMap, RetVec, StackTag);
}
// Pad and align each of the allocas that we instrumented to stop small
// uninteresting allocas from hiding in instrumented alloca's padding and so
// that we have enough space to store real tags for short granules.
DenseMap<AllocaInst *, AllocaInst *> AllocaToPaddedAllocaMap;
for (AllocaInst *AI : AllocasToInstrument) {
uint64_t Size = getAllocaSizeInBytes(*AI);
uint64_t AlignedSize = alignTo(Size, Mapping.getObjectAlignment());
AI->setAlignment(
Align(std::max(AI->getAlignment(), Mapping.getObjectAlignment())));
if (Size != AlignedSize) {
Type *AllocatedType = AI->getAllocatedType();
if (AI->isArrayAllocation()) {
uint64_t ArraySize =
cast<ConstantInt>(AI->getArraySize())->getZExtValue();
AllocatedType = ArrayType::get(AllocatedType, ArraySize);
}
Type *TypeWithPadding = StructType::get(
AllocatedType, ArrayType::get(Int8Ty, AlignedSize - Size));
auto *NewAI = new AllocaInst(
TypeWithPadding, AI->getType()->getAddressSpace(), nullptr, "", AI);
NewAI->takeName(AI);
NewAI->setAlignment(AI->getAlign());
NewAI->setUsedWithInAlloca(AI->isUsedWithInAlloca());
NewAI->setSwiftError(AI->isSwiftError());
NewAI->copyMetadata(*AI);
auto *Bitcast = new BitCastInst(NewAI, AI->getType(), "", AI);
AI->replaceAllUsesWith(Bitcast);
AllocaToPaddedAllocaMap[AI] = NewAI;
}
}
if (!AllocaToPaddedAllocaMap.empty()) {
for (auto &BB : F)
for (auto &Inst : BB)
if (auto *DVI = dyn_cast<DbgVariableIntrinsic>(&Inst))
if (auto *AI =
dyn_cast_or_null<AllocaInst>(DVI->getVariableLocation()))
if (auto *NewAI = AllocaToPaddedAllocaMap.lookup(AI))
DVI->setArgOperand(
0, MetadataAsValue::get(*C, LocalAsMetadata::get(NewAI)));
for (auto &P : AllocaToPaddedAllocaMap)
P.first->eraseFromParent();
}
// If we split the entry block, move any allocas that were originally in the
// entry block back into the entry block so that they aren't treated as
// dynamic allocas.
if (EntryIRB.GetInsertBlock() != &F.getEntryBlock()) {
InsertPt = &*F.getEntryBlock().begin();
for (auto II = EntryIRB.GetInsertBlock()->begin(),
IE = EntryIRB.GetInsertBlock()->end();
II != IE;) {
Instruction *I = &*II++;
if (auto *AI = dyn_cast<AllocaInst>(I))
if (isa<ConstantInt>(AI->getArraySize()))
I->moveBefore(InsertPt);
}
}
for (auto &Operand : OperandsToInstrument)
instrumentMemAccess(Operand);
if (ClInstrumentMemIntrinsics && !IntrinToInstrument.empty()) {
for (auto Inst : IntrinToInstrument)
instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
}
LocalDynamicShadow = nullptr;
StackBaseTag = nullptr;
return true;
}
void HWAddressSanitizer::instrumentGlobal(GlobalVariable *GV, uint8_t Tag) {
Constant *Initializer = GV->getInitializer();
uint64_t SizeInBytes =
M.getDataLayout().getTypeAllocSize(Initializer->getType());
uint64_t NewSize = alignTo(SizeInBytes, Mapping.getObjectAlignment());
if (SizeInBytes != NewSize) {
// Pad the initializer out to the next multiple of 16 bytes and add the
// required short granule tag.
std::vector<uint8_t> Init(NewSize - SizeInBytes, 0);
Init.back() = Tag;
Constant *Padding = ConstantDataArray::get(*C, Init);
Initializer = ConstantStruct::getAnon({Initializer, Padding});
}
auto *NewGV = new GlobalVariable(M, Initializer->getType(), GV->isConstant(),
GlobalValue::ExternalLinkage, Initializer,
GV->getName() + ".hwasan");
NewGV->copyAttributesFrom(GV);
NewGV->setLinkage(GlobalValue::PrivateLinkage);
NewGV->copyMetadata(GV, 0);
NewGV->setAlignment(
MaybeAlign(std::max(GV->getAlignment(), Mapping.getObjectAlignment())));
// It is invalid to ICF two globals that have different tags. In the case
// where the size of the global is a multiple of the tag granularity the
// contents of the globals may be the same but the tags (i.e. symbol values)
// may be different, and the symbols are not considered during ICF. In the
// case where the size is not a multiple of the granularity, the short granule
// tags would discriminate two globals with different tags, but there would
// otherwise be nothing stopping such a global from being incorrectly ICF'd
// with an uninstrumented (i.e. tag 0) global that happened to have the short
// granule tag in the last byte.
NewGV->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
// Descriptor format (assuming little-endian):
// bytes 0-3: relative address of global
// bytes 4-6: size of global (16MB ought to be enough for anyone, but in case
// it isn't, we create multiple descriptors)
// byte 7: tag
auto *DescriptorTy = StructType::get(Int32Ty, Int32Ty);
const uint64_t MaxDescriptorSize = 0xfffff0;
for (uint64_t DescriptorPos = 0; DescriptorPos < SizeInBytes;
DescriptorPos += MaxDescriptorSize) {
auto *Descriptor =
new GlobalVariable(M, DescriptorTy, true, GlobalValue::PrivateLinkage,
nullptr, GV->getName() + ".hwasan.descriptor");
auto *GVRelPtr = ConstantExpr::getTrunc(
ConstantExpr::getAdd(
ConstantExpr::getSub(
ConstantExpr::getPtrToInt(NewGV, Int64Ty),
ConstantExpr::getPtrToInt(Descriptor, Int64Ty)),
ConstantInt::get(Int64Ty, DescriptorPos)),
Int32Ty);
uint32_t Size = std::min(SizeInBytes - DescriptorPos, MaxDescriptorSize);
auto *SizeAndTag = ConstantInt::get(Int32Ty, Size | (uint32_t(Tag) << 24));
Descriptor->setComdat(NewGV->getComdat());
Descriptor->setInitializer(ConstantStruct::getAnon({GVRelPtr, SizeAndTag}));
Descriptor->setSection("hwasan_globals");
Descriptor->setMetadata(LLVMContext::MD_associated,
MDNode::get(*C, ValueAsMetadata::get(NewGV)));
appendToCompilerUsed(M, Descriptor);
}
Constant *Aliasee = ConstantExpr::getIntToPtr(
ConstantExpr::getAdd(
ConstantExpr::getPtrToInt(NewGV, Int64Ty),
ConstantInt::get(Int64Ty, uint64_t(Tag) << kPointerTagShift)),
GV->getType());
auto *Alias = GlobalAlias::create(GV->getValueType(), GV->getAddressSpace(),
GV->getLinkage(), "", Aliasee, &M);
Alias->setVisibility(GV->getVisibility());
Alias->takeName(GV);
GV->replaceAllUsesWith(Alias);
GV->eraseFromParent();
}
void HWAddressSanitizer::instrumentGlobals() {
std::vector<GlobalVariable *> Globals;
for (GlobalVariable &GV : M.globals()) {
if (GV.isDeclarationForLinker() || GV.getName().startswith("llvm.") ||
GV.isThreadLocal())
continue;
// Common symbols can't have aliases point to them, so they can't be tagged.
if (GV.hasCommonLinkage())
continue;
// Globals with custom sections may be used in __start_/__stop_ enumeration,
// which would be broken both by adding tags and potentially by the extra
// padding/alignment that we insert.
if (GV.hasSection())
continue;
Globals.push_back(&GV);
}
MD5 Hasher;
Hasher.update(M.getSourceFileName());
MD5::MD5Result Hash;
Hasher.final(Hash);
uint8_t Tag = Hash[0];
for (GlobalVariable *GV : Globals) {
// Skip tag 0 in order to avoid collisions with untagged memory.
if (Tag == 0)
Tag = 1;
instrumentGlobal(GV, Tag++);
}
}
void HWAddressSanitizer::instrumentPersonalityFunctions() {
// We need to untag stack frames as we unwind past them. That is the job of
// the personality function wrapper, which either wraps an existing
// personality function or acts as a personality function on its own. Each
// function that has a personality function or that can be unwound past has
// its personality function changed to a thunk that calls the personality
// function wrapper in the runtime.
MapVector<Constant *, std::vector<Function *>> PersonalityFns;
for (Function &F : M) {
if (F.isDeclaration() || !F.hasFnAttribute(Attribute::SanitizeHWAddress))
continue;
if (F.hasPersonalityFn()) {
PersonalityFns[F.getPersonalityFn()->stripPointerCasts()].push_back(&F);
} else if (!F.hasFnAttribute(Attribute::NoUnwind)) {
PersonalityFns[nullptr].push_back(&F);
}
}
if (PersonalityFns.empty())
return;
FunctionCallee HwasanPersonalityWrapper = M.getOrInsertFunction(
"__hwasan_personality_wrapper", Int32Ty, Int32Ty, Int32Ty, Int64Ty,
Int8PtrTy, Int8PtrTy, Int8PtrTy, Int8PtrTy, Int8PtrTy);
FunctionCallee UnwindGetGR = M.getOrInsertFunction("_Unwind_GetGR", VoidTy);
FunctionCallee UnwindGetCFA = M.getOrInsertFunction("_Unwind_GetCFA", VoidTy);
for (auto &P : PersonalityFns) {
std::string ThunkName = kHwasanPersonalityThunkName;
if (P.first)
ThunkName += ("." + P.first->getName()).str();
FunctionType *ThunkFnTy = FunctionType::get(
Int32Ty, {Int32Ty, Int32Ty, Int64Ty, Int8PtrTy, Int8PtrTy}, false);
bool IsLocal = P.first && (!isa<GlobalValue>(P.first) ||
cast<GlobalValue>(P.first)->hasLocalLinkage());
auto *ThunkFn = Function::Create(ThunkFnTy,
IsLocal ? GlobalValue::InternalLinkage
: GlobalValue::LinkOnceODRLinkage,
ThunkName, &M);
if (!IsLocal) {
ThunkFn->setVisibility(GlobalValue::HiddenVisibility);
ThunkFn->setComdat(M.getOrInsertComdat(ThunkName));
}
auto *BB = BasicBlock::Create(*C, "entry", ThunkFn);
IRBuilder<> IRB(BB);
CallInst *WrapperCall = IRB.CreateCall(
HwasanPersonalityWrapper,
{ThunkFn->getArg(0), ThunkFn->getArg(1), ThunkFn->getArg(2),
ThunkFn->getArg(3), ThunkFn->getArg(4),
P.first ? IRB.CreateBitCast(P.first, Int8PtrTy)
: Constant::getNullValue(Int8PtrTy),
IRB.CreateBitCast(UnwindGetGR.getCallee(), Int8PtrTy),
IRB.CreateBitCast(UnwindGetCFA.getCallee(), Int8PtrTy)});
WrapperCall->setTailCall();
IRB.CreateRet(WrapperCall);
for (Function *F : P.second)
F->setPersonalityFn(ThunkFn);
}
}
void HWAddressSanitizer::ShadowMapping::init(Triple &TargetTriple) {
Scale = kDefaultShadowScale;
if (ClMappingOffset.getNumOccurrences() > 0) {
InGlobal = false;
InTls = false;
Offset = ClMappingOffset;
} else if (ClEnableKhwasan || ClInstrumentWithCalls) {
InGlobal = false;
InTls = false;
Offset = 0;
} else if (ClWithIfunc) {
InGlobal = true;
InTls = false;
Offset = kDynamicShadowSentinel;
} else if (ClWithTls) {
InGlobal = false;
InTls = true;
Offset = kDynamicShadowSentinel;
} else {
InGlobal = false;
InTls = false;
Offset = kDynamicShadowSentinel;
}
}
|
// C:\diabpsx\PSXSRC\TIMS.CPP
#include "types.h"
// address: 0x8007CF00
// line start: 458
// line end: 486
void TimSwann__Fv() {
}
|
/*************************************************************************/
/* file_access_android.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* http://www.godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */
/* */
/* 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 "file_access_android.h"
#include "print_string.h"
AAssetManager *FileAccessAndroid::asset_manager=NULL;
/*void FileAccessAndroid::make_default() {
create_func=create_android;
}*/
FileAccess* FileAccessAndroid::create_android() {
return memnew(FileAccessAndroid);
}
Error FileAccessAndroid::_open(const String& p_path, int p_mode_flags) {
String path=fix_path(p_path).simplify_path();
if (path.begins_with("/"))
path=path.substr(1,path.length());
else if (path.begins_with("res://"))
path=path.substr(6,path.length());
ERR_FAIL_COND_V(p_mode_flags&FileAccess::WRITE,ERR_UNAVAILABLE); //can't write on android..
a=AAssetManager_open(asset_manager,path.utf8().get_data(),AASSET_MODE_STREAMING);
if (!a)
return ERR_CANT_OPEN;
//ERR_FAIL_COND_V(!a,ERR_FILE_NOT_FOUND);
len=AAsset_getLength(a);
pos=0;
eof=false;
return OK;
}
void FileAccessAndroid::close() {
if (!a)
return;
AAsset_close(a);
a=NULL;
}
bool FileAccessAndroid::is_open() const {
return a!=NULL;
}
void FileAccessAndroid::seek(size_t p_position) {
ERR_FAIL_COND(!a);
AAsset_seek(a,p_position,SEEK_SET);
pos=p_position;
if (pos>len) {
pos=len;
eof=true;
} else {
eof=false;
}
}
void FileAccessAndroid::seek_end(int64_t p_position) {
ERR_FAIL_COND(!a);
AAsset_seek(a,p_position,SEEK_END);
pos=len+p_position;
}
size_t FileAccessAndroid::get_pos() const {
return pos;
}
size_t FileAccessAndroid::get_len() const {
return len;
}
bool FileAccessAndroid::eof_reached() const {
return eof;
}
uint8_t FileAccessAndroid::get_8() const {
if (pos>=len) {
eof=true;
return 0;
}
uint8_t byte;
AAsset_read(a,&byte,1);
pos++;
return byte;
}
int FileAccessAndroid::get_buffer(uint8_t *p_dst, int p_length) const {
off_t r = AAsset_read(a,p_dst,p_length);
if (r>=0) {
pos+=r;
if (pos>len) {
pos=len;
eof=true;
}
}
return r;
}
Error FileAccessAndroid::get_error() const {
return eof?ERR_FILE_EOF:OK; //not sure what else it may happen
}
void FileAccessAndroid::store_8(uint8_t p_dest) {
ERR_FAIL();
}
bool FileAccessAndroid::file_exists(const String& p_path) {
String path=fix_path(p_path).simplify_path();
if (path.begins_with("/"))
path=path.substr(1,path.length());
else if (path.begins_with("res://"))
path=path.substr(6,path.length());
AAsset *at=AAssetManager_open(asset_manager,path.utf8().get_data(),AASSET_MODE_STREAMING);
if (!at)
return false;
AAsset_close(at);
return true;
}
FileAccessAndroid::FileAccessAndroid() {
a=NULL;
eof=false;
}
FileAccessAndroid::~FileAccessAndroid()
{
close();
}
|
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <errno.h>
#include <stdarg.h>
#include <unistd.h>
#include "conformance.pb.h"
#include <google/protobuf/test_messages_proto3.pb.h>
#include <google/protobuf/test_messages_proto2.pb.h>
#include <google/protobuf/message.h>
#include <google/protobuf/text_format.h>
#include <google/protobuf/util/json_util.h>
#include <google/protobuf/util/type_resolver_util.h>
using conformance::ConformanceRequest;
using conformance::ConformanceResponse;
using google::protobuf::Descriptor;
using google::protobuf::DescriptorPool;
using google::protobuf::Message;
using google::protobuf::MessageFactory;
using google::protobuf::TextFormat;
using google::protobuf::util::BinaryToJsonString;
using google::protobuf::util::JsonParseOptions;
using google::protobuf::util::JsonToBinaryString;
using google::protobuf::util::NewTypeResolverForDescriptorPool;
using google::protobuf::util::Status;
using google::protobuf::util::TypeResolver;
using protobuf_test_messages::proto2::TestAllTypesProto2;
using protobuf_test_messages::proto3::TestAllTypesProto3;
using std::string;
static const char kTypeUrlPrefix[] = "type.googleapis.com";
const char* kFailures[] = {
#if !GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER
"Required.Proto2.ProtobufInput."
"PrematureEofInDelimitedDataForKnownNonRepeatedValue.MESSAGE",
"Required.Proto2.ProtobufInput."
"PrematureEofInDelimitedDataForKnownRepeatedValue.MESSAGE",
"Required.Proto2.ProtobufInput.PrematureEofInPackedField.BOOL",
"Required.Proto2.ProtobufInput.PrematureEofInPackedField.ENUM",
"Required.Proto2.ProtobufInput.PrematureEofInPackedField.INT32",
"Required.Proto2.ProtobufInput.PrematureEofInPackedField.INT64",
"Required.Proto2.ProtobufInput.PrematureEofInPackedField.SINT32",
"Required.Proto2.ProtobufInput.PrematureEofInPackedField.SINT64",
"Required.Proto2.ProtobufInput.PrematureEofInPackedField.UINT32",
"Required.Proto2.ProtobufInput.PrematureEofInPackedField.UINT64",
"Required.Proto3.ProtobufInput."
"PrematureEofInDelimitedDataForKnownNonRepeatedValue.MESSAGE",
"Required.Proto3.ProtobufInput."
"PrematureEofInDelimitedDataForKnownRepeatedValue.MESSAGE",
"Required.Proto3.ProtobufInput.PrematureEofInPackedField.BOOL",
"Required.Proto3.ProtobufInput.PrematureEofInPackedField.ENUM",
"Required.Proto3.ProtobufInput.PrematureEofInPackedField.INT32",
"Required.Proto3.ProtobufInput.PrematureEofInPackedField.INT64",
"Required.Proto3.ProtobufInput.PrematureEofInPackedField.SINT32",
"Required.Proto3.ProtobufInput.PrematureEofInPackedField.SINT64",
"Required.Proto3.ProtobufInput.PrematureEofInPackedField.UINT32",
"Required.Proto3.ProtobufInput.PrematureEofInPackedField.UINT64",
#endif
};
static string GetTypeUrl(const Descriptor* message) {
return string(kTypeUrlPrefix) + "/" + message->full_name();
}
int test_count = 0;
bool verbose = false;
TypeResolver* type_resolver;
string* type_url;
bool CheckedRead(int fd, void *buf, size_t len) {
size_t ofs = 0;
while (len > 0) {
ssize_t bytes_read = read(fd, (char*)buf + ofs, len);
if (bytes_read == 0) return false;
if (bytes_read < 0) {
GOOGLE_LOG(FATAL) << "Error reading from test runner: " << strerror(errno);
}
len -= bytes_read;
ofs += bytes_read;
}
return true;
}
void CheckedWrite(int fd, const void *buf, size_t len) {
if (write(fd, buf, len) != len) {
GOOGLE_LOG(FATAL) << "Error writing to test runner: " << strerror(errno);
}
}
void DoTest(const ConformanceRequest& request, ConformanceResponse* response) {
Message *test_message;
const Descriptor *descriptor = DescriptorPool::generated_pool()->FindMessageTypeByName(
request.message_type());
if (!descriptor) {
GOOGLE_LOG(FATAL) << "No such message type: " << request.message_type();
}
test_message = MessageFactory::generated_factory()->GetPrototype(descriptor)->New();
switch (request.payload_case()) {
case ConformanceRequest::kProtobufPayload: {
if (!test_message->ParseFromString(request.protobuf_payload())) {
// Getting parse details would involve something like:
// http://stackoverflow.com/questions/22121922/how-can-i-get-more-details-about-errors-generated-during-protobuf-parsing-c
response->set_parse_error("Parse error (no more details available).");
return;
}
break;
}
case ConformanceRequest::kJsonPayload: {
string proto_binary;
JsonParseOptions options;
options.ignore_unknown_fields =
(request.test_category() ==
conformance::JSON_IGNORE_UNKNOWN_PARSING_TEST);
Status status = JsonToBinaryString(type_resolver, *type_url,
request.json_payload(), &proto_binary,
options);
if (!status.ok()) {
response->set_parse_error(string("Parse error: ") +
status.error_message().as_string());
return;
}
if (!test_message->ParseFromString(proto_binary)) {
response->set_runtime_error(
"Parsing JSON generates invalid proto output.");
return;
}
break;
}
case ConformanceRequest::kTextPayload: {
if (!TextFormat::ParseFromString(request.text_payload(), test_message)) {
response->set_parse_error("Parse error");
return;
}
break;
}
case ConformanceRequest::PAYLOAD_NOT_SET:
GOOGLE_LOG(FATAL) << "Request didn't have payload.";
break;
default:
GOOGLE_LOG(FATAL) << "unknown payload type: "
<< request.payload_case();
break;
}
conformance::FailureSet failures;
if (descriptor == failures.GetDescriptor()) {
for (const char* s : kFailures) failures.add_failure(s);
test_message = &failures;
}
switch (request.requested_output_format()) {
case conformance::UNSPECIFIED:
GOOGLE_LOG(FATAL) << "Unspecified output format";
break;
case conformance::PROTOBUF: {
GOOGLE_CHECK(test_message->SerializeToString(response->mutable_protobuf_payload()));
break;
}
case conformance::JSON: {
string proto_binary;
GOOGLE_CHECK(test_message->SerializeToString(&proto_binary));
Status status = BinaryToJsonString(type_resolver, *type_url, proto_binary,
response->mutable_json_payload());
if (!status.ok()) {
response->set_serialize_error(
string("Failed to serialize JSON output: ") +
status.error_message().as_string());
return;
}
break;
}
case conformance::TEXT_FORMAT: {
GOOGLE_CHECK(TextFormat::PrintToString(*test_message,
response->mutable_text_payload()));
break;
}
default:
GOOGLE_LOG(FATAL) << "Unknown output format: "
<< request.requested_output_format();
}
}
bool DoTestIo() {
string serialized_input;
string serialized_output;
ConformanceRequest request;
ConformanceResponse response;
uint32_t bytes;
if (!CheckedRead(STDIN_FILENO, &bytes, sizeof(uint32_t))) {
// EOF.
return false;
}
serialized_input.resize(bytes);
if (!CheckedRead(STDIN_FILENO, (char*)serialized_input.c_str(), bytes)) {
GOOGLE_LOG(ERROR) << "Unexpected EOF on stdin. " << strerror(errno);
}
if (!request.ParseFromString(serialized_input)) {
GOOGLE_LOG(FATAL) << "Parse of ConformanceRequest proto failed.";
return false;
}
DoTest(request, &response);
response.SerializeToString(&serialized_output);
bytes = serialized_output.size();
CheckedWrite(STDOUT_FILENO, &bytes, sizeof(uint32_t));
CheckedWrite(STDOUT_FILENO, serialized_output.c_str(), bytes);
if (verbose) {
fprintf(stderr, "conformance-cpp: request=%s, response=%s\n",
request.ShortDebugString().c_str(),
response.ShortDebugString().c_str());
}
test_count++;
return true;
}
int main() {
type_resolver = NewTypeResolverForDescriptorPool(
kTypeUrlPrefix, DescriptorPool::generated_pool());
type_url = new string(GetTypeUrl(TestAllTypesProto3::descriptor()));
while (1) {
if (!DoTestIo()) {
fprintf(stderr, "conformance-cpp: received EOF from test runner "
"after %d tests, exiting\n", test_count);
return 0;
}
}
}
|
// 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 "chrome/browser/engagement/site_engagement_service.h"
#include "base/time/clock.h"
#include "base/time/default_clock.h"
#include "chrome/browser/engagement/site_engagement_score.h"
// static
bool SiteEngagementService::IsEnabled() {
return false;
}
// static
SiteEngagementService* SiteEngagementService::Get(Profile* profile) {
return nullptr;
}
// static
double SiteEngagementService::GetScoreFromSettings(
HostContentSettingsMap* settings,
const GURL& origin) {
auto clock = std::make_unique<base::DefaultClock>();
return SiteEngagementScore(clock.get(), origin, settings).GetTotalScore();
}
|
#include "mwoibn/hierarchical_control/actions/merge/end.h"
#include "mwoibn/hierarchical_control/actions/merge/replace.h"
#include "mwoibn/hierarchical_control/actions/merge.h"
#include "mwoibn/hierarchical_control/controllers/default.h"
mwoibn::hierarchical_control::actions::merge::End::End(mwoibn::Matrix& P, mwoibn::VectorN& command, MergeManager& memory, maps::TaskMap& map, actions::Merge& merge, double dt, double mu, mwoibn::hierarchical_control::tasks::Constraints& constraints, mwoibn::robot_class::Robot& robot) : Local(memory, map, merge), _gain(), _this(P, command, _merge_memory, map, _gain), _dt(dt), _mu(mu){
_this_memory.release(_this);
_gain.setZero(command.size());
//
// _hierarchical_controller_ptr.reset(new mwoibn::hierarchical_control::controllers::Default());
// _hierarchical_controller_ptr->addTask(constraints, 1.0, 0.0001);
//
// mwoibn::Matrix jacobian = mwoibn::Matrix::Identity(robot.getDofs(), robot.getDofs());
//
// _joints.reset(new mwoibn::hierarchical_control::tasks::BasicTask(robot.getDofs(), robot.getDofs()));
// _joints->updateJacobian(jacobian);
// _hierarchical_controller_ptr->addTask(*_joints, 1.0, 0.0001);
}
mwoibn::hierarchical_control::actions::merge::End::End(mwoibn::Matrix& P, mwoibn::VectorN& command, MergeManager& memory, maps::TaskMap& map, actions::Merge& merge, double dt, double mu) : Local(memory, map, merge), _gain(), _this(P, command, _merge_memory, map, _gain), _dt(dt), _mu(mu){
_this_memory.release(_this);
_gain.setZero(command.size());
}
mwoibn::hierarchical_control::actions::merge::End::End(const End& other) : Local(other), _gain(other._gain), _t(other._t), _dt(other._dt), _mu(other._mu), _p(other._p), _this_memory(other._this_memory), _this(other._this, _gain) {
// if(other._hierarchical_controller_ptr == nullptr) return;
//
// _hierarchical_controller_ptr.reset(new mwoibn::hierarchical_control::controllers::Default(static_cast<mwoibn::hierarchical_control::controllers::Default&>(*(other._hierarchical_controller_ptr))));
// _hierarchical_controller_ptr->removeTask( 1);
//
// _joints.reset(new mwoibn::hierarchical_control::tasks::BasicTask(*other._joints));
// _hierarchical_controller_ptr->addTask(*_joints, 1.0, 0.0001);
}
mwoibn::hierarchical_control::actions::merge::End::~End(){
}
bool mwoibn::hierarchical_control::actions::merge::End::isParent(actions::Task& task){
return false;
}
const double mwoibn::hierarchical_control::actions::merge::End::getGain(){
return _p;
}
void mwoibn::hierarchical_control::actions::merge::End::updateGain(){
_p = std::tanh(_mu*_t);
// std::cout << "_p " << _p << std::endl;
_gain.setConstant(_p);
}
void mwoibn::hierarchical_control::actions::merge::End::reset(){
_p = 0;
_t = 0;
_gain.setZero();
//std::cout << name() << "\t reset_p " << _p << std::endl;
}
void mwoibn::hierarchical_control::actions::merge::End::progress(){
_t += _dt;
updateGain();
//std::cout << "end_p " << _p << std::endl;
}
void mwoibn::hierarchical_control::actions::merge::End::setProgress(double p){
//if (p == 0) _t = 0;
//else
_t = std::atanh(p)/_mu;
updateGain();
}
void mwoibn::hierarchical_control::actions::merge::End::_setLimit(){
_t = _dt;
progress();
_this.setCondition(1-_p); // set end to the same step as the first one
reset();
}
void mwoibn::hierarchical_control::actions::merge::End::run(){
//std::cout << "end" << std::endl;
progress();
_this.run();
// std::cout << "raw\t" << _this.getCommand().head<12>().transpose() << std::endl;
//_this.getCommand() = _hierarchical_controller_ptr->update();
// std::cout << "swap\t" << _this.getCommand().head<12>().transpose() << std::endl;
}
mwoibn::hierarchical_control::actions::merge::Local& mwoibn::hierarchical_control::actions::merge::End::swapFromFront(Local& old){
actions::merge::Front* _base_1 = _merge_memory.local_front.get();
actions::merge::End* _end_1 = _merge_memory.local_end.get();
_base_1->assign(_this.action(), nullptr, _end_1);
_end_1->assign(old.action(), *_base_1);
_end_1->setProgress(1 - _p);
old.releaseMemory();
releaseMemory();
_map[_base_1->action().baseAction().getTask()] = _base_1;
_map[_end_1->action().baseAction().getTask()] = _end_1;
_merge.setLast(*_end_1);
return *_end_1;
}
mwoibn::hierarchical_control::actions::merge::Local& mwoibn::hierarchical_control::actions::merge::End::swapFromReplace(Local& lower){
return lower.swapToEnd(*this);
}
void mwoibn::hierarchical_control::actions::merge::End::_end(){
//std::cout << name() << "end_p " << _p << std::endl;
// std::cout << "_end" << std::endl;
_this.secondAction().release(); // this should release pointer
//_map.erase(_this.secondAction().baseAction().getTask());
actions::merge::Front* ptr = _merge_memory.local_front.get();
ptr->assign(_this.action().next(), nullptr, nullptr);
_map[_this.baseAction().getTask()] = ptr;
_finish(*ptr);
}
void mwoibn::hierarchical_control::actions::merge::End::releaseMemory(){
_merge_memory.release(*this);
}
void mwoibn::hierarchical_control::actions::merge::End::release(){
if(_this.isDone()) _end();
else
_map[_this.baseAction().getTask()] = _next;
releaseMemory();
}
void mwoibn::hierarchical_control::actions::merge::End::_finish(Local& last){
_merge.setLast(last);
}
void mwoibn::hierarchical_control::actions::merge::End::assign(actions::Task& t_new, actions::Task& t_old){
_this_memory.replace.get();
_this.start(t_new, t_old, *_merge_memory.snap.get());
_map[t_new.baseAction().getTask()] = this;
_setLimit();
reset();
}
void mwoibn::hierarchical_control::actions::merge::End::assign(actions::Task& t_new, actions::Task* t_old, Local* parent){
assign(t_new, *t_old);
/*_this_memory.replace.get();
_this.start(t_new, *t_old, *_memory.snap.get());
_map[baseAction().getTask()] = this;
_setLimit();
reset();*/
}
void mwoibn::hierarchical_control::actions::merge::End::push(Local& parent){
Replace* _ptr = _merge_memory.local_replace.get();
_ptr->assign(action(), &_this.secondAction(), &parent);
_ptr->setProgress(getGain());
release();
_map[baseAction().getTask()] = _ptr;
}
mwoibn::hierarchical_control::actions::Task& mwoibn::hierarchical_control::actions::merge::End::next(){
actions::Task& ptr = _this.next();
if (&ptr != &_this || _this.isDone()) {
release();
return *_map[_this.baseAction().getTask()];
}
return *this;
}
mwoibn::hierarchical_control::actions::Primary& mwoibn::hierarchical_control::actions::merge::End::baseAction(){
return _this.baseAction();
}
mwoibn::hierarchical_control::actions::Task& mwoibn::hierarchical_control::actions::merge::End::action(){
return _this.action();
}
|
/*
*
* Copyright (c) 2004
* John Maddock
*
* Use, modification and distribution are subject to 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)
*
*/
/*
* LOCATION: see http://www.boost.org for most recent version.
* FILE test_regex_search.hpp
* VERSION see <boost/version.hpp>
* DESCRIPTION: Declares tests for regex search and iteration.
*/
#ifndef BOOST_REGEX_REGRESS_REGEX_SEARCH_HPP
#define BOOST_REGEX_REGRESS_REGEX_SEARCH_HPP
#include "info.hpp"
#ifdef TEST_ROPE
#include <rope>
#endif
//
// this file implements a test for a regular expression that should compile,
// followed by a search for that expression:
//
struct test_regex_search_tag{};
template <class BidirectionalIterator>
void test_sub_match(const boost::sub_match<BidirectionalIterator>& sub, BidirectionalIterator base, const int* answer_table, int i, bool recurse = true)
{
#ifdef BOOST_MSVC
#pragma warning(push)
#pragma warning(disable:4244)
#endif
if(recurse)
{
boost::sub_match<BidirectionalIterator> copy(sub);
test_sub_match(copy, base, answer_table, i, false);
}
typedef typename boost::sub_match<BidirectionalIterator>::value_type charT;
if((sub.matched == 0)
&&
!((i == 0)
&& (test_info<charT>::match_options() & boost::match_partial)) )
{
if(answer_table[2*i] >= 0)
{
BOOST_REGEX_TEST_ERROR(
"Sub-expression " << i
<< " was not matched when it should have been.", charT);
}
}
else
{
if(boost::re_detail::distance(base, sub.first) != answer_table[2*i])
{
BOOST_REGEX_TEST_ERROR(
"Error in start location of sub-expression "
<< i << ", found " << boost::re_detail::distance(base, sub.first)
<< ", expected " << answer_table[2*i] << ".", charT);
}
if(boost::re_detail::distance(base, sub.second) != answer_table[1+ 2*i])
{
BOOST_REGEX_TEST_ERROR(
"Error in end location of sub-expression "
<< i << ", found " << boost::re_detail::distance(base, sub.second)
<< ", expected " << answer_table[1 + 2*i] << ".", charT);
}
}
#ifdef BOOST_MSVC
#pragma warning(pop)
#endif
}
template <class BidirectionalIterator, class Allocator>
void test_result(const boost::match_results<BidirectionalIterator, Allocator>& what, BidirectionalIterator base, const int* answer_table, bool recurse = true)
{
if(recurse)
{
boost::match_results<BidirectionalIterator, Allocator> copy(what);
test_result(copy, base, answer_table, false);
boost::match_results<BidirectionalIterator, Allocator> s;
s.swap(copy);
test_result(s, base, answer_table, false);
boost::match_results<BidirectionalIterator, Allocator> s2;
s2 = what;
test_result(s2, base, answer_table, false);
}
for(unsigned i = 0; i < what.size(); ++i)
{
test_sub_match(what[i], base, answer_table, i);
}
}
template<class charT, class traits>
void test_simple_search(boost::basic_regex<charT, traits>& r)
{
typedef typename std::basic_string<charT>::const_iterator const_iterator;
const std::basic_string<charT>& search_text = test_info<charT>::search_text();
boost::regex_constants::match_flag_type opts = test_info<charT>::match_options();
const int* answer_table = test_info<charT>::answer_table();
boost::match_results<const_iterator> what;
if(boost::regex_search(
search_text.begin(),
search_text.end(),
what,
r,
opts))
{
test_result(what, search_text.begin(), answer_table);
// setting match_any should have no effect on the result returned:
if(!boost::regex_search(
search_text.begin(),
search_text.end(),
r,
opts|boost::regex_constants::match_any))
{
BOOST_REGEX_TEST_ERROR("Expected match was not found when using the match_any flag.", charT);
}
}
else
{
if(answer_table[0] >= 0)
{
// we should have had a match but didn't:
BOOST_REGEX_TEST_ERROR("Expected match was not found.", charT);
}
// setting match_any should have no effect on the result returned:
else if(boost::regex_search(
search_text.begin(),
search_text.end(),
r,
opts|boost::regex_constants::match_any))
{
BOOST_REGEX_TEST_ERROR("Unexpected match was found when using the match_any flag.", charT);
}
}
#ifdef TEST_ROPE
std::rope<charT> rsearch_text;
for(unsigned i = 0; i < search_text.size(); ++i)
{
std::rope<charT> c(search_text[i]);
if(++i != search_text.size())
{
c.append(search_text[i]);
if(++i != search_text.size())
{
c.append(search_text[i]);
}
}
rsearch_text.append(c);
}
boost::match_results<std::rope<charT>::const_iterator> rwhat;
if(boost::regex_search(
rsearch_text.begin(),
rsearch_text.end(),
rwhat,
r,
opts))
{
test_result(rwhat, rsearch_text.begin(), answer_table);
}
else
{
if(answer_table[0] >= 0)
{
// we should have had a match but didn't:
BOOST_REGEX_TEST_ERROR("Expected match was not found.", charT);
}
}
#endif
}
template<class charT, class traits>
void test_regex_iterator(boost::basic_regex<charT, traits>& r)
{
typedef typename std::basic_string<charT>::const_iterator const_iterator;
typedef boost::regex_iterator<const_iterator, charT, traits> test_iterator;
const std::basic_string<charT>& search_text = test_info<charT>::search_text();
boost::regex_constants::match_flag_type opts = test_info<charT>::match_options();
const int* answer_table = test_info<charT>::answer_table();
test_iterator start(search_text.begin(), search_text.end(), r, opts), end;
test_iterator copy(start);
const_iterator last_end = search_text.begin();
while(start != end)
{
if(start != copy)
{
BOOST_REGEX_TEST_ERROR("Failed iterator != comparison.", charT);
}
if(!(start == copy))
{
BOOST_REGEX_TEST_ERROR("Failed iterator == comparison.", charT);
}
test_result(*start, search_text.begin(), answer_table);
// test $` and $' :
if(start->prefix().first != last_end)
{
BOOST_REGEX_TEST_ERROR("Incorrect position for start of $`", charT);
}
if(start->prefix().second != (*start)[0].first)
{
BOOST_REGEX_TEST_ERROR("Incorrect position for end of $`", charT);
}
if(start->prefix().matched != (start->prefix().first != start->prefix().second))
{
BOOST_REGEX_TEST_ERROR("Incorrect position for matched member of $`", charT);
}
if(start->suffix().first != (*start)[0].second)
{
BOOST_REGEX_TEST_ERROR("Incorrect position for start of $'", charT);
}
if(start->suffix().second != search_text.end())
{
BOOST_REGEX_TEST_ERROR("Incorrect position for end of $'", charT);
}
if(start->suffix().matched != (start->suffix().first != start->suffix().second))
{
BOOST_REGEX_TEST_ERROR("Incorrect position for matched member of $'", charT);
}
last_end = (*start)[0].second;
++start;
++copy;
// move on the answer table to next set of answers;
if(*answer_table != -2)
while(*answer_table++ != -2){}
}
if(answer_table[0] >= 0)
{
// we should have had a match but didn't:
BOOST_REGEX_TEST_ERROR("Expected match was not found.", charT);
}
}
template<class charT, class traits>
void test_regex_token_iterator(boost::basic_regex<charT, traits>& r)
{
typedef typename std::basic_string<charT>::const_iterator const_iterator;
typedef boost::regex_token_iterator<const_iterator, charT, traits> test_iterator;
const std::basic_string<charT>& search_text = test_info<charT>::search_text();
boost::regex_constants::match_flag_type opts = test_info<charT>::match_options();
const int* answer_table = test_info<charT>::answer_table();
//
// we start by testing sub-expression 0:
//
test_iterator start(search_text.begin(), search_text.end(), r, 0, opts), end;
test_iterator copy(start);
while(start != end)
{
if(start != copy)
{
BOOST_REGEX_TEST_ERROR("Failed iterator != comparison.", charT);
}
if(!(start == copy))
{
BOOST_REGEX_TEST_ERROR("Failed iterator == comparison.", charT);
}
test_sub_match(*start, search_text.begin(), answer_table, 0);
++start;
++copy;
// move on the answer table to next set of answers;
if(*answer_table != -2)
while(*answer_table++ != -2){}
}
if(answer_table[0] >= 0)
{
// we should have had a match but didn't:
BOOST_REGEX_TEST_ERROR("Expected match was not found.", charT);
}
//
// and now field spitting:
//
test_iterator start2(search_text.begin(), search_text.end(), r, -1, opts), end2;
test_iterator copy2(start2);
int last_end2 = 0;
answer_table = test_info<charT>::answer_table();
while(start2 != end2)
{
if(start2 != copy2)
{
BOOST_REGEX_TEST_ERROR("Failed iterator != comparison.", charT);
}
if(!(start2 == copy2))
{
BOOST_REGEX_TEST_ERROR("Failed iterator == comparison.", charT);
}
#ifdef BOOST_MSVC
#pragma warning(push)
#pragma warning(disable:4244)
#endif
if(boost::re_detail::distance(search_text.begin(), start2->first) != last_end2)
{
BOOST_REGEX_TEST_ERROR(
"Error in location of start of field split, found: "
<< boost::re_detail::distance(search_text.begin(), start2->first)
<< ", expected: "
<< last_end2
<< ".", charT);
}
int expected_end = static_cast<int>(answer_table[0] < 0 ? search_text.size() : answer_table[0]);
if(boost::re_detail::distance(search_text.begin(), start2->second) != expected_end)
{
BOOST_REGEX_TEST_ERROR(
"Error in location of end2 of field split, found: "
<< boost::re_detail::distance(search_text.begin(), start2->second)
<< ", expected: "
<< expected_end
<< ".", charT);
}
#ifdef BOOST_MSVC
#pragma warning(pop)
#endif
last_end2 = answer_table[1];
++start2;
++copy2;
// move on the answer table to next set of answers;
if(*answer_table != -2)
while(*answer_table++ != -2){}
}
if(answer_table[0] >= 0)
{
// we should have had a match but didn't:
BOOST_REGEX_TEST_ERROR("Expected match was not found.", charT);
}
#if !BOOST_WORKAROUND(BOOST_MSVC, < 1300)
//
// and now both field splitting and $0:
//
std::vector<int> subs;
subs.push_back(-1);
subs.push_back(0);
start2 = test_iterator(search_text.begin(), search_text.end(), r, subs, opts);
copy2 = start2;
last_end2 = 0;
answer_table = test_info<charT>::answer_table();
while(start2 != end2)
{
if(start2 != copy2)
{
BOOST_REGEX_TEST_ERROR("Failed iterator != comparison.", charT);
}
if(!(start2 == copy2))
{
BOOST_REGEX_TEST_ERROR("Failed iterator == comparison.", charT);
}
#ifdef BOOST_MSVC
#pragma warning(push)
#pragma warning(disable:4244)
#endif
if(boost::re_detail::distance(search_text.begin(), start2->first) != last_end2)
{
BOOST_REGEX_TEST_ERROR(
"Error in location of start of field split, found: "
<< boost::re_detail::distance(search_text.begin(), start2->first)
<< ", expected: "
<< last_end2
<< ".", charT);
}
int expected_end = static_cast<int>(answer_table[0] < 0 ? search_text.size() : answer_table[0]);
if(boost::re_detail::distance(search_text.begin(), start2->second) != expected_end)
{
BOOST_REGEX_TEST_ERROR(
"Error in location of end2 of field split, found: "
<< boost::re_detail::distance(search_text.begin(), start2->second)
<< ", expected: "
<< expected_end
<< ".", charT);
}
#ifdef BOOST_MSVC
#pragma warning(pop)
#endif
last_end2 = answer_table[1];
++start2;
++copy2;
if((start2 == end2) && (answer_table[0] >= 0))
{
BOOST_REGEX_TEST_ERROR(
"Expected $0 match not found", charT);
}
if(start2 != end2)
{
test_sub_match(*start2, search_text.begin(), answer_table, 0);
++start2;
++copy2;
}
// move on the answer table to next set of answers;
if(*answer_table != -2)
while(*answer_table++ != -2){}
}
if(answer_table[0] >= 0)
{
// we should have had a match but didn't:
BOOST_REGEX_TEST_ERROR("Expected match was not found.", charT);
}
#endif
}
template <class charT, class traits>
struct grep_test_predicate
{
typedef typename std::basic_string<charT>::const_iterator test_iter;
grep_test_predicate(test_iter b, const int* a)
: m_base(b), m_table(a)
{}
bool operator()(const boost::match_results<test_iter>& what)
{
test_result(what, m_base, m_table);
// move on the answer table to next set of answers;
if(*m_table != -2)
while(*m_table++ != -2){}
return true;
}
private:
test_iter m_base;
const int* m_table;
};
template<class charT, class traits>
void test_regex_grep(boost::basic_regex<charT, traits>& r)
{
typedef typename std::basic_string<charT>::const_iterator const_iterator;
const std::basic_string<charT>& search_text = test_info<charT>::search_text();
boost::regex_constants::match_flag_type opts = test_info<charT>::match_options();
const int* answer_table = test_info<charT>::answer_table();
grep_test_predicate<charT, traits> pred(search_text.begin(), answer_table);
boost::regex_grep(pred, search_text.begin(), search_text.end(), r, opts);
}
template<class charT, class traits>
void test_regex_match(boost::basic_regex<charT, traits>& r)
{
typedef typename std::basic_string<charT>::const_iterator const_iterator;
const std::basic_string<charT>& search_text = test_info<charT>::search_text();
boost::regex_constants::match_flag_type opts = test_info<charT>::match_options();
const int* answer_table = test_info<charT>::answer_table();
boost::match_results<const_iterator> what;
if(answer_table[0] < 0)
{
if(boost::regex_match(search_text, r, opts))
{
BOOST_REGEX_TEST_ERROR("boost::regex_match found a match when it should not have done so.", charT);
}
}
else
{
if((answer_table[0] > 0) && boost::regex_match(search_text, r, opts))
{
BOOST_REGEX_TEST_ERROR("boost::regex_match found a match when it should not have done so.", charT);
}
else if((answer_table[0] == 0) && (answer_table[1] == static_cast<int>(search_text.size())))
{
if(boost::regex_match(
search_text.begin(),
search_text.end(),
what,
r,
opts))
{
test_result(what, search_text.begin(), answer_table);
}
else if(answer_table[0] >= 0)
{
// we should have had a match but didn't:
BOOST_REGEX_TEST_ERROR("Expected match was not found.", charT);
}
}
}
}
template<class charT, class traits>
void test(boost::basic_regex<charT, traits>& r, const test_regex_search_tag&)
{
const std::basic_string<charT>& expression = test_info<charT>::expression();
boost::regex_constants::syntax_option_type syntax_options = test_info<charT>::syntax_options();
try{
r.assign(expression, syntax_options);
if(r.status())
{
BOOST_REGEX_TEST_ERROR("Expression did not compile when it should have done, error code = " << r.status(), charT);
}
test_simple_search(r);
test_regex_iterator(r);
test_regex_token_iterator(r);
test_regex_grep(r);
test_regex_match(r);
//
// Verify sub-expression locations:
//
if((syntax_options & boost::regbase::save_subexpression_location) == 0)
{
bool have_except = false;
try
{
r.subexpression(1);
}
catch(const std::out_of_range&)
{
have_except = true;
}
if(!have_except)
{
BOOST_REGEX_TEST_ERROR("Expected std::out_of_range error was not found.", charT);
}
}
r.assign(expression, syntax_options | boost::regbase::save_subexpression_location);
for(std::size_t i = 1; i < r.mark_count(); ++i)
{
std::pair<const charT*, const charT*> p = r.subexpression(i);
if(*p.first != '(')
{
BOOST_REGEX_TEST_ERROR("Starting location of sub-expression " << i << " iterator was invalid.", charT);
}
if(*p.second != ')')
{
BOOST_REGEX_TEST_ERROR("Ending location of sub-expression " << i << " iterator was invalid.", charT);
}
}
}
catch(const boost::bad_expression& e)
{
BOOST_REGEX_TEST_ERROR("Expression did not compile when it should have done: " << e.what(), charT);
}
catch(const std::runtime_error& e)
{
BOOST_REGEX_TEST_ERROR("Received an unexpected std::runtime_error: " << e.what(), charT);
}
catch(const std::exception& e)
{
BOOST_REGEX_TEST_ERROR("Received an unexpected std::exception: " << e.what(), charT);
}
catch(...)
{
BOOST_REGEX_TEST_ERROR("Received an unexpected exception of unknown type", charT);
}
}
#endif
|
#include <Audio.h>
#include "settings.h"
#include "speech.h"
#ifdef SDCARD
extern AudioPlaySdWav audioPromptSD;
extern AudioPlayMemory audioPrompt;
extern AudioMixer4 audioOutputMixer;
#else
#include <Talkie.h>
Talkie voice;
extern AudioPlayMemory audioPrompt;
extern AudioMixer4 audioOutputMixer;
/*
* This is the Morse letter to speech lookup table
* it is in the same order as the "mySet[]" array
* ##TEMNAIOGKDWRUS##QZYCXBJP#L#FVH09#8###7#####/-61#######2###3#45
*/
//const uint8_t* speechLookup[] = {
// NULL, NULL, spT, spE, spM,
// spN, spA, spI, spO, spG,
// spK, spD, spW, spR, spU,
// spS, NULL, NULL, spQ, spZ,
// spY, spC, spX, spB, spJ,
// spP, NULL, spL, NULL, spF,
// spV, spH, spZERO, spNINE, NULL,
// spEIGHT, NULL, NULL, NULL, spSEVEN,
// NULL, NULL, NULL, NULL, NULL,
// spOPERATOR, spMINUS, spSIX, spONE, NULL,
// NULL, NULL, NULL, NULL, NULL,
// NULL, spTWO, NULL, NULL, NULL,
// spTHREE, NULL, spFOUR, spFIVE
//};
const uint8_t* ascii2lpc[] = {
NULL, NULL, NULL, NULL, NULL, //0
NULL, NULL, NULL, NULL, NULL, //5
NULL, NULL, NULL, spMINUS,NULL, //10
NULL, NULL, NULL, NULL, NULL, //15
NULL, NULL, NULL, NULL, NULL, //20
NULL, NULL, NULL, NULL, NULL, //25
NULL, NULL, NULL, NULL, NULL, //30
NULL, NULL, NULL, NULL, NULL, //35
NULL, NULL, NULL, NULL, NULL, //40
NULL, NULL, spOPERATOR,spZERO, spONE, //45
spTWO, spTHREE, spFOUR, spFIVE, spSIX, //50
spSEVEN, spEIGHT, spNINE, NULL, NULL, //55
NULL, NULL, NULL, NULL, NULL, //60
spA, spB, spC, spD, spE, //65
spF, spG, spH, spI, spJ, //70
spK, spL, spM, spN, spO, //75
spP, spQ, spR, spS, spT, //80
spU, spV, spW, spX, spY, //85
spZ, NULL, NULL, NULL, NULL, //90
NULL, NULL, spA, spB, spC, //95
spD, spE, spF, spG, spH, //100
spI, spJ, spK, spL, spM, //105
spN, spO, spP, spQ, spR, //110
spS, spT, spU, spV, spW, //115
spX, spY, spZ, NULL, NULL, //120
};
#endif
//---------------------------------------------------------------------------------
void speakChar(char c) {
#ifndef SDCARD // Use LPC to say the character
voice.say(ascii2lpc[(int)c]);
#else // Otherwise we can use WAV files stored on a SD card
char s[15];
if (c == '/') {
strcpy(s,"slash.wav");
} else if (c == '-') {
strcpy(s,"hyphen.wav");
} else {
strcpy(s,"X.wav"); // Setup dummy filename X
s[0] = toupper(c); // Replace X with our actual char
}
speakSD(s);
#endif
}
//---------------------------------------------------------------------------------
void speakChars(const char callsign[]) {
for (unsigned int i = 0; i < strlen(callsign) ; i++) {
speakChar(callsign[i]);
};
}
//---------------------------------------------------------------
void speak(const unsigned int* audioSample) {
lowerRadio();
audioPrompt.play(audioSample);
do {delay(10);} while (audioPrompt.isPlaying());
unMuteRadio();
}
//---------------------------------------------------------------
void speakSD(const char *filename) {
#ifdef SDCARD
#ifdef DEBUG
Serial.println(filename);
#endif
audioPromptSD.play(filename);
delay(3); // This delay is important!
while (audioPromptSD.isPlaying()) {
delay(5);
};
#endif
}
//---------------------------------------------------------------
void muteRadio() {
audioOutputMixer.gain(0, 0.0); // Mute radio audio
}
//---------------------------------------------------------------
void unMuteRadio() {
audioOutputMixer.gain(0, 1.0); // Unmute radio audio
}
//---------------------------------------------------------------
void lowerRadio() {
audioOutputMixer.gain(0, 0.1); // Lower the radio volume to allow speach at same time
}
// Speech FIFO
#define SPEECH_BUF_SZ 8
char speechBuffer[SPEECH_BUF_SZ];
int speechReadPointer = 0;
int speechWritePointer = 0;
int speechCount = 0;
//---------------------------------------------------------------------
void speechBuffer_push(char c) {
if (speechCount >= SPEECH_BUF_SZ - 1) // If we are about to overflow the buffer, drop the char
return;
speechCount++;
speechBuffer[speechWritePointer++] = c;
speechWritePointer &= (SPEECH_BUF_SZ - 1);
}
//---------------------------------------------------------------------
char speechBuffer_pull() {
speechReadPointer &= (SPEECH_BUF_SZ - 1);
speechCount--;
return speechBuffer[speechReadPointer++];
}
//---------------------------------------------------------------------
// Returns TRUE when buffer empty
bool speech_buffer_empty(void) {
if(0 == speechCount) {
return true;
}
return false;
}
//---------------------------------------------------------------------
// Stop all buffered playback
void speech_Buffer_flush(void) {
speechReadPointer = speechWritePointer;
}
//---------------------------------------------------------------------
// If the speech buffer is empty return or the audio system is busy - just return
// else read the next char in the buffer and start playing it.
void serviceSpeech() {
#ifdef SDCARD
if ( speech_buffer_empty() || audioPromptSD.isPlaying())
return;
char c = speechBuffer_pull();
char s[15];
if (c == '/') {
strcpy(s,"slash.wav");
} else if (c == '-') {
strcpy(s,"hyphen.wav");
} else {
strcpy(s,"X.wav"); // Setup dummy filename X.wav
s[0] = tolower(c); // Replace X with our actual char
}
audioPromptSD.play(s);
delay(3); // The delay is important!
#endif
}
|
// Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/MakerBux-config.h"
#endif
#include "optionsdialog.h"
#include "ui_optionsdialog.h"
#include "bitcoinunits.h"
#include "guiutil.h"
#include "obfuscation.h"
#include "optionsmodel.h"
#include "main.h" // for MAX_SCRIPTCHECK_THREADS
#include "netbase.h"
#include "txdb.h" // for -dbcache defaults
#ifdef ENABLE_WALLET
#include "wallet.h" // for CWallet::minTxFee
#endif
#include <boost/thread.hpp>
#include <QDataWidgetMapper>
#include <QDir>
#include <QIntValidator>
#include <QLocale>
#include <QMessageBox>
#include <QTimer>
OptionsDialog::OptionsDialog(QWidget* parent, bool enableWallet) : QDialog(parent),
ui(new Ui::OptionsDialog),
model(0),
mapper(0),
fProxyIpValid(true)
{
ui->setupUi(this);
GUIUtil::restoreWindowGeometry("nOptionsDialogWindow", this->size(), this);
/* Main elements init */
ui->databaseCache->setMinimum(nMinDbCache);
ui->databaseCache->setMaximum(nMaxDbCache);
ui->threadsScriptVerif->setMinimum(-(int)boost::thread::hardware_concurrency());
ui->threadsScriptVerif->setMaximum(MAX_SCRIPTCHECK_THREADS);
/* Network elements init */
#ifndef USE_UPNP
ui->mapPortUpnp->setEnabled(false);
#endif
ui->proxyIp->setEnabled(false);
ui->proxyPort->setEnabled(false);
ui->proxyPort->setValidator(new QIntValidator(1, 65535, this));
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyIp, SLOT(setEnabled(bool)));
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyPort, SLOT(setEnabled(bool)));
ui->proxyIp->installEventFilter(this);
/* Window elements init */
#ifdef Q_OS_MAC
/* remove Window tab on Mac */
ui->tabWidget->removeTab(ui->tabWidget->indexOf(ui->tabWindow));
#endif
/* remove Wallet tab in case of -disablewallet */
if (!enableWallet) {
ui->tabWidget->removeTab(ui->tabWidget->indexOf(ui->tabWallet));
}
/* Display elements init */
/* Number of displayed decimal digits selector */
QString digits;
for (int index = 2; index <= 8; index++) {
digits.setNum(index);
ui->digits->addItem(digits, digits);
}
/* Theme selector static themes */
ui->theme->addItem(QString("Default"), QVariant("default"));
/* Theme selector external themes */
boost::filesystem::path pathAddr = GetDataDir() / "themes";
QDir dir(pathAddr.string().c_str());
dir.setFilter(QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot);
QFileInfoList list = dir.entryInfoList();
for (int i = 0; i < list.size(); ++i) {
QFileInfo fileInfo = list.at(i);
ui->theme->addItem(fileInfo.fileName(), QVariant(fileInfo.fileName()));
}
/* Language selector */
QDir translations(":translations");
ui->lang->addItem(QString("(") + tr("default") + QString(")"), QVariant(""));
foreach (const QString& langStr, translations.entryList()) {
QLocale locale(langStr);
/** check if the locale name consists of 2 parts (language_country) */
if (langStr.contains("_")) {
#if QT_VERSION >= 0x040800
/** display language strings as "native language - native country (locale name)", e.g. "Deutsch - Deutschland (de)" */
ui->lang->addItem(locale.nativeLanguageName() + QString(" - ") + locale.nativeCountryName() + QString(" (") + langStr + QString(")"), QVariant(langStr));
#else
/** display language strings as "language - country (locale name)", e.g. "German - Germany (de)" */
ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" - ") + QLocale::countryToString(locale.country()) + QString(" (") + langStr + QString(")"), QVariant(langStr));
#endif
} else {
#if QT_VERSION >= 0x040800
/** display language strings as "native language (locale name)", e.g. "Deutsch (de)" */
ui->lang->addItem(locale.nativeLanguageName() + QString(" (") + langStr + QString(")"), QVariant(langStr));
#else
/** display language strings as "language (locale name)", e.g. "German (de)" */
ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" (") + langStr + QString(")"), QVariant(langStr));
#endif
}
}
#if QT_VERSION >= 0x040700
ui->thirdPartyTxUrls->setPlaceholderText("https://example.com/tx/%s");
#endif
ui->unit->setModel(new BitcoinUnits(this));
/* Widget-to-option mapper */
mapper = new QDataWidgetMapper(this);
mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
mapper->setOrientation(Qt::Vertical);
/* setup/change UI elements when proxy IP is invalid/valid */
connect(this, SIGNAL(proxyIpChecks(QValidatedLineEdit*, int)), this, SLOT(doProxyIpChecks(QValidatedLineEdit*, int)));
}
OptionsDialog::~OptionsDialog()
{
GUIUtil::saveWindowGeometry("nOptionsDialogWindow", this);
delete ui;
}
void OptionsDialog::setModel(OptionsModel* model)
{
this->model = model;
if (model) {
/* check if client restart is needed and show persistent message */
if (model->isRestartRequired())
showRestartWarning(true);
QString strLabel = model->getOverriddenByCommandLine();
if (strLabel.isEmpty())
strLabel = tr("none");
ui->overriddenByCommandLineLabel->setText(strLabel);
mapper->setModel(model);
setMapper();
mapper->toFirst();
}
/* warn when one of the following settings changes by user action (placed here so init via mapper doesn't trigger them) */
/* Main */
connect(ui->databaseCache, SIGNAL(valueChanged(int)), this, SLOT(showRestartWarning()));
connect(ui->threadsScriptVerif, SIGNAL(valueChanged(int)), this, SLOT(showRestartWarning()));
/* Wallet */
connect(ui->spendZeroConfChange, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning()));
/* Network */
connect(ui->allowIncoming, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning()));
connect(ui->connectSocks, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning()));
/* Display */
connect(ui->digits, SIGNAL(valueChanged()), this, SLOT(showRestartWarning()));
connect(ui->theme, SIGNAL(valueChanged()), this, SLOT(showRestartWarning()));
connect(ui->lang, SIGNAL(valueChanged()), this, SLOT(showRestartWarning()));
connect(ui->thirdPartyTxUrls, SIGNAL(textChanged(const QString&)), this, SLOT(showRestartWarning()));
connect(ui->showMasternodesTab, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning()));
}
void OptionsDialog::setMapper()
{
/* Main */
mapper->addMapping(ui->bitcoinAtStartup, OptionsModel::StartAtStartup);
mapper->addMapping(ui->threadsScriptVerif, OptionsModel::ThreadsScriptVerif);
mapper->addMapping(ui->databaseCache, OptionsModel::DatabaseCache);
/* Wallet */
mapper->addMapping(ui->spendZeroConfChange, OptionsModel::SpendZeroConfChange);
mapper->addMapping(ui->coinControlFeatures, OptionsModel::CoinControlFeatures);
/* Network */
mapper->addMapping(ui->mapPortUpnp, OptionsModel::MapPortUPnP);
mapper->addMapping(ui->allowIncoming, OptionsModel::Listen);
mapper->addMapping(ui->connectSocks, OptionsModel::ProxyUse);
mapper->addMapping(ui->proxyIp, OptionsModel::ProxyIP);
mapper->addMapping(ui->proxyPort, OptionsModel::ProxyPort);
/* Window */
#ifndef Q_OS_MAC
mapper->addMapping(ui->minimizeToTray, OptionsModel::MinimizeToTray);
mapper->addMapping(ui->minimizeOnClose, OptionsModel::MinimizeOnClose);
#endif
/* Display */
mapper->addMapping(ui->digits, OptionsModel::Digits);
mapper->addMapping(ui->theme, OptionsModel::Theme);
mapper->addMapping(ui->theme, OptionsModel::Theme);
mapper->addMapping(ui->lang, OptionsModel::Language);
mapper->addMapping(ui->unit, OptionsModel::DisplayUnit);
mapper->addMapping(ui->thirdPartyTxUrls, OptionsModel::ThirdPartyTxUrls);
/* Obfuscation Rounds */
mapper->addMapping(ui->obfuscationRounds, OptionsModel::ObfuscationRounds);
mapper->addMapping(ui->anonymizeMakerBux, OptionsModel::AnonymizeMakerBuxAmount);
mapper->addMapping(ui->showMasternodesTab, OptionsModel::ShowMasternodesTab);
}
void OptionsDialog::enableOkButton()
{
/* prevent enabling of the OK button when data modified, if there is an invalid proxy address present */
if (fProxyIpValid)
setOkButtonState(true);
}
void OptionsDialog::disableOkButton()
{
setOkButtonState(false);
}
void OptionsDialog::setOkButtonState(bool fState)
{
ui->okButton->setEnabled(fState);
}
void OptionsDialog::on_resetButton_clicked()
{
if (model) {
// confirmation dialog
QMessageBox::StandardButton btnRetVal = QMessageBox::question(this, tr("Confirm options reset"),
tr("Client restart required to activate changes.") + "<br><br>" + tr("Client will be shutdown, do you want to proceed?"),
QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);
if (btnRetVal == QMessageBox::Cancel)
return;
/* reset all options and close GUI */
model->Reset();
QApplication::quit();
}
}
void OptionsDialog::on_okButton_clicked()
{
mapper->submit();
obfuScationPool.cachedNumBlocks = std::numeric_limits<int>::max();
pwalletMain->MarkDirty();
accept();
}
void OptionsDialog::on_cancelButton_clicked()
{
reject();
}
void OptionsDialog::showRestartWarning(bool fPersistent)
{
ui->statusLabel->setStyleSheet("QLabel { color: red; }");
if (fPersistent) {
ui->statusLabel->setText(tr("Client restart required to activate changes."));
} else {
ui->statusLabel->setText(tr("This change would require a client restart."));
// clear non-persistent status label after 10 seconds
// Todo: should perhaps be a class attribute, if we extend the use of statusLabel
QTimer::singleShot(10000, this, SLOT(clearStatusLabel()));
}
}
void OptionsDialog::clearStatusLabel()
{
ui->statusLabel->clear();
}
void OptionsDialog::doProxyIpChecks(QValidatedLineEdit* pUiProxyIp, int nProxyPort)
{
Q_UNUSED(nProxyPort);
const std::string strAddrProxy = pUiProxyIp->text().toStdString();
CService addrProxy;
/* Check for a valid IPv4 / IPv6 address */
if (!(fProxyIpValid = LookupNumeric(strAddrProxy.c_str(), addrProxy))) {
disableOkButton();
pUiProxyIp->setValid(false);
ui->statusLabel->setStyleSheet("QLabel { color: red; }");
ui->statusLabel->setText(tr("The supplied proxy address is invalid."));
} else {
enableOkButton();
ui->statusLabel->clear();
}
}
bool OptionsDialog::eventFilter(QObject* object, QEvent* event)
{
if (event->type() == QEvent::FocusOut) {
if (object == ui->proxyIp) {
emit proxyIpChecks(ui->proxyIp, ui->proxyPort->text().toInt());
}
}
return QDialog::eventFilter(object, event);
}
|
/* mbed Microcontroller Library
* Copyright (c) 2013-2014 ARM Limited
*
* 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 "mbed-drivers/mbed.h"
#include "mbed-drivers/test_env.h"
void ticker_callback_1(void);
void ticker_callback_2(void);
DigitalOut led0(LED1);
DigitalOut led1(LED2);
Ticker ticker;
void print_char(char c = '*')
{
printf("%c", c);
fflush(stdout);
}
void ticker_callback_2(void)
{
ticker.detach();
ticker.attach(ticker_callback_1, 1.0);
led1 = !led1;
print_char();
}
void ticker_callback_1(void)
{
ticker.detach();
ticker.attach(ticker_callback_2, 1.0);
led0 = !led0;
print_char();
}
void app_start(int, char*[])
{
MBED_HOSTTEST_TIMEOUT(15);
MBED_HOSTTEST_SELECT(wait_us_auto);
MBED_HOSTTEST_DESCRIPTION(Ticker Two callbacks);
MBED_HOSTTEST_START("MBED_34");
ticker.attach(ticker_callback_1, 1.0);
}
|
/*
* Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* 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.
*/
// Software Guide : BeginCommandLineArgs
// INPUTS: {StereoFixed.png}, {StereoMoving.png}
// OUTPUTS: {deformationFieldOutput.png}, {resampledMovingOutput.png}
// 5 5 9 7 10 100 0.8
// Software Guide : EndCommandLineArgs
// Software Guide : BeginLatex
//
// This example demonstrates the use of the \doxygen{otb}{DisparityMapEstimationMethod}, along with
// the \doxygen{otb}{NearestPointDisplacementFieldGenerator}. The first filter performs deformation estimation
// according to a given transform, using embedded ITK registration framework. It takes as input a possibly non regular
// point set and produces a point set with associated point data representing the deformation.
//
// The second filter generates a deformation field by using nearest neighbor interpolation on the deformation values from
// the point set. More advanced methods for deformation field interpolation are also available.
//
// The first step toward the use of these filters is to include the proper header files.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "otbDisparityMapEstimationMethod.h"
#include "itkTranslationTransform.h"
#include "itkNormalizedCorrelationImageToImageMetric.h"
#include "itkWindowedSincInterpolateImageFunction.h"
#include "itkGradientDescentOptimizer.h"
#include "otbBSplinesInterpolateDisplacementFieldGenerator.h"
#include "itkWarpImageFilter.h"
// Software Guide : EndCodeSnippet
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "itkUnaryFunctorImageFilter.h"
#include "itkRescaleIntensityImageFilter.h"
#include "otbMultiToMonoChannelExtractROI.h"
int main(int argc, char* argv[])
{
if (argc != 12)
{
std::cerr << "Usage: " << argv[0];
std::cerr << " fixedFileName movingFileName fieldOutName imageOutName ";
std::cerr <<
"pointSetStepX pointSetStepY explorationSize windowSize learningRate ";
std::cerr << "nbIterations metricThreshold";
return EXIT_FAILURE;
}
const unsigned int Dimension = 2;
// Software Guide : BeginLatex
//
// Then we must decide what pixel type to use for the image. We choose to do
// all the computation in floating point precision and rescale the results
// between 0 and 255 in order to export PNG images.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef double PixelType;
typedef unsigned char OutputPixelType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The images are defined using the pixel type and the dimension. Please note that
// the \doxygen{otb}{NearestPointDisplacementFieldGenerator} generates a
// \doxygen{otb}{VectorImage} to represent the deformation field in both
// image directions.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::Image<PixelType, Dimension> ImageType;
typedef otb::Image<OutputPixelType, Dimension> OutputImageType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The next step is to define the transform we have chosen to model the deformation. In this
// example the deformation is modeled as a \doxygen{itk}{TranslationTransform}.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::TranslationTransform<double, Dimension> TransformType;
typedef TransformType::ParametersType ParametersType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Then we define the metric we will use to evaluate the local registration between the fixed and
// the moving image. In this example we chose the \doxygen{itk}{NormalizedCorrelationImageToImageMetric}.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::NormalizedCorrelationImageToImageMetric<ImageType,
ImageType> MetricType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Disparity map estimation implies evaluation of the moving image at non-grid position. Therefore, an
// interpolator is needed. In this example we chose the \doxygen{itk}{WindowedSincInterpolateImageFunction}.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::Function::HammingWindowFunction<3> WindowFunctionType;
typedef itk::ZeroFluxNeumannBoundaryCondition<ImageType> ConditionType;
typedef itk::WindowedSincInterpolateImageFunction<ImageType, 3,
WindowFunctionType,
ConditionType,
double> InterpolatorType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// To perform local registration, an optimizer is needed. In this example we chose the
// \doxygen{itk}{GradientDescentOptimizer}.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::GradientDescentOptimizer OptimizerType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Now we will define the point set to represent the point where to compute local disparity.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::PointSet<ParametersType, Dimension> PointSetType;
// Software Guide : EndCodeSnippet
typedef PointSetType::PointType PointType;
// Software Guide : BeginLatex
//
// Now we define the disparity map estimation filter.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::DisparityMapEstimationMethod<ImageType,
ImageType,
PointSetType> DMEstimationType;
typedef DMEstimationType::SizeType SizeType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The input image reader also has to be defined.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::ImageFileReader<ImageType> ReaderType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Two readers are instantiated : one for the fixed image, and one for the moving image.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
ReaderType::Pointer fixedReader = ReaderType::New();
ReaderType::Pointer movingReader = ReaderType::New();
fixedReader->SetFileName(argv[1]);
movingReader->SetFileName(argv[2]);
fixedReader->UpdateOutputInformation();
movingReader->UpdateOutputInformation();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We will the create a regular point set where to compute the local disparity.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
SizeType fixedSize =
fixedReader->GetOutput()->GetLargestPossibleRegion().GetSize();
unsigned int NumberOfXNodes = (fixedSize[0] - 2 * atoi(argv[7]) - 1)
/ atoi(argv[5]);
unsigned int NumberOfYNodes = (fixedSize[1] - 2 * atoi(argv[7]) - 1)
/ atoi(argv[6]);
ImageType::IndexType firstNodeIndex;
firstNodeIndex[0] = atoi(argv[7]);
firstNodeIndex[1] = atoi(argv[7]);
PointSetType::Pointer nodes = PointSetType::New();
unsigned int nodeCounter = 0;
for (unsigned int x = 0; x < NumberOfXNodes; x++)
{
for (unsigned int y = 0; y < NumberOfYNodes; y++)
{
PointType p;
p[0] = firstNodeIndex[0] + x*atoi(argv[5]);
p[1] = firstNodeIndex[1] + y*atoi(argv[6]);
nodes->SetPoint(nodeCounter++, p);
}
}
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We build the transform, interpolator, metric and optimizer for the disparity map
// estimation filter.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
TransformType::Pointer transform = TransformType::New();
OptimizerType::Pointer optimizer = OptimizerType::New();
optimizer->MinimizeOn();
optimizer->SetLearningRate(atof(argv[9]));
optimizer->SetNumberOfIterations(atoi(argv[10]));
InterpolatorType::Pointer interpolator = InterpolatorType::New();
MetricType::Pointer metric = MetricType::New();
metric->SetSubtractMean(true);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We then set up the disparity map estimation filter. This filter will perform a local registration at each
// point of the given point set using the ITK registration framework. It will produce a point set whose point data
// reflects the disparity locally around the associated point.
//
// Point data will contains the following data :
//
// \begin{enumerate}
// \item{The final metric value found in the registration process, }
// \item{the deformation value in the first image direction, }
// \item{the deformation value in the second image direction, }
// \item{the final parameters of the transform.}
// \end{enumerate}
//
// Please note that in the case of a \doxygen{itk}{TranslationTransform}, the deformation values and
// the transform parameters are the same.
//
// Software Guide : EndLatex
// Software Guide :BeginCodeSnippet
DMEstimationType::Pointer dmestimator = DMEstimationType::New();
dmestimator->SetTransform(transform);
dmestimator->SetOptimizer(optimizer);
dmestimator->SetInterpolator(interpolator);
dmestimator->SetMetric(metric);
SizeType windowSize, explorationSize;
explorationSize.Fill(atoi(argv[7]));
windowSize.Fill(atoi(argv[8]));
dmestimator->SetWinSize(windowSize);
dmestimator->SetExploSize(explorationSize);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The initial transform parameters can be set via the \code{SetInitialTransformParameters()} method.
// In our case, we simply fill the parameter array with null values.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
DMEstimationType::ParametersType
initialParameters(transform->GetNumberOfParameters());
initialParameters[0] = 0.0;
initialParameters[1] = 0.0;
dmestimator->SetInitialTransformParameters(initialParameters);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Now we can set the input for the deformation field estimation filter. Fixed image can be set using the \code{SetFixedImage()}
// method, moving image can be set using the \code{SetMovingImage()}, and input point set can be set using the
// \code{SetPointSet()} method.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
dmestimator->SetFixedImage(fixedReader->GetOutput());
dmestimator->SetMovingImage(movingReader->GetOutput());
dmestimator->SetPointSet(nodes);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Once the estimation has been performed by the \doxygen{otb}{DisparityMapEstimationMethod}, one can generate
// the associated deformation field (that means translation in first and second image direction).
// It will be represented as a \doxygen{otb}{VectorImage}.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::VectorImage<PixelType, Dimension> DisplacementFieldType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// For the deformation field estimation, we will use the \doxygen{otb}{BSplinesInterpolateDisplacementFieldGenerator}.
// This filter will perform a nearest neighbor interpolation on the deformation values in the point set data.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::BSplinesInterpolateDisplacementFieldGenerator<PointSetType,
DisplacementFieldType>
GeneratorType;
// Software GUide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The disparity map estimation filter is instantiated.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
GeneratorType::Pointer generator = GeneratorType::New();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We must then specify the input point set using the \code{SetPointSet()} method.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
generator->SetPointSet(dmestimator->GetOutput());
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// One must also specify the origin, size and spacing of the output deformation field.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
generator->SetOutputOrigin(fixedReader->GetOutput()->GetOrigin());
generator->SetOutputSpacing(fixedReader->GetOutput()->GetSignedSpacing());
generator->SetOutputSize(fixedReader->GetOutput()
->GetLargestPossibleRegion().GetSize());
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The local registration process can lead to wrong deformation values and transform parameters. To Select only
// points in point set for which the registration process was successful, one can set a threshold on the final metric
// value : points for which the absolute final metric value is below this threshold will be discarded. This
// threshold can be set with the \code{SetMetricThreshold()} method.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
generator->SetMetricThreshold(atof(argv[11]));
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// \relatedClasses
// \begin{itemize}
// \item \doxygen{otb}{NNearestPointsLinearInterpolateDisplacementFieldGenerator}
// \item \doxygen{otb}{BSplinesInterpolateDisplacementFieldGenerator}
// \item \doxygen{otb}{NearestTransformDisplacementFieldGenerator}
// \item \doxygen{otb}{NNearestTransformsLinearInterpolateDisplacementFieldGenerator}
// \item \doxygen{otb}{BSplinesInterpolateTransformDisplacementFieldGenerator}
// \end{itemize}
//
// Software Guide : EndLatex
// Software Guide : BeginLatex
//
// Now we can warp our fixed image according to the estimated deformation field. This will be performed by the
// \doxygen{itk}{WarpImageFilter}. First, we define this filter.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::WarpImageFilter<ImageType, ImageType,
DisplacementFieldType> ImageWarperType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Then we instantiate it.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
ImageWarperType::Pointer warper = ImageWarperType::New();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We set the input image to warp using the \code{SetInput()} method, and the deformation field
// using the \code{SetDisplacementField()} method.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
warper->SetInput(movingReader->GetOutput());
warper->SetDisplacementField(generator->GetOutput());
warper->SetOutputOrigin(fixedReader->GetOutput()->GetOrigin());
warper->SetOutputSpacing(fixedReader->GetOutput()->GetSignedSpacing());
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// In order to write the result to a PNG file, we will rescale it on a proper range.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::RescaleIntensityImageFilter<ImageType,
OutputImageType> RescalerType;
RescalerType::Pointer outputRescaler = RescalerType::New();
outputRescaler->SetInput(warper->GetOutput());
outputRescaler->SetOutputMaximum(255);
outputRescaler->SetOutputMinimum(0);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We can now write the image to a file. The filters are executed by invoking
// the \code{Update()} method.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::ImageFileWriter<OutputImageType> WriterType;
WriterType::Pointer outputWriter = WriterType::New();
outputWriter->SetInput(outputRescaler->GetOutput());
outputWriter->SetFileName(argv[4]);
outputWriter->Update();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We also want to write the deformation field along the first direction to a file.
// To achieve this we will use the \doxygen{otb}{MultiToMonoChannelExtractROI} filter.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::MultiToMonoChannelExtractROI<PixelType,
PixelType>
ChannelExtractionFilterType;
ChannelExtractionFilterType::Pointer channelExtractor
= ChannelExtractionFilterType::New();
channelExtractor->SetInput(generator->GetOutput());
channelExtractor->SetChannel(1);
RescalerType::Pointer fieldRescaler = RescalerType::New();
fieldRescaler->SetInput(channelExtractor->GetOutput());
fieldRescaler->SetOutputMaximum(255);
fieldRescaler->SetOutputMinimum(0);
WriterType::Pointer fieldWriter = WriterType::New();
fieldWriter->SetInput(fieldRescaler->GetOutput());
fieldWriter->SetFileName(argv[3]);
fieldWriter->Update();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Figure~\ref{fig:SIMPLEDISPARITYMAPESTIMATIONOUTPUT} shows the result of applying disparity map estimation on a stereo pair
// using a regular point set, followed by deformation field estimation using Splines and fixed image resampling.
//
// \begin{figure}
// \center
// \includegraphics[width=0.20\textwidth]{StereoFixed.eps}
// \includegraphics[width=0.20\textwidth]{StereoMoving.eps}
// \includegraphics[width=0.20\textwidth]{deformationFieldOutput.eps}
// \includegraphics[width=0.20\textwidth]{resampledMovingOutput.eps}
// \itkcaption[Displacement field and resampling from disparity map estimation]{From left
// to right and top to bottom: fixed input image, moving image with a sinusoid deformation,
// estimated deformation field in the horizontal direction, resampled moving image.}
// \label{fig:SIMPLEDISPARITYMAPESTIMATIONOUTPUT}
// \end{figure}
//
// Software Guide : EndLatex
return EXIT_SUCCESS;
}
|
#define PROBLEM "https://onlinejudge.u-aizu.ac.jp/courses/library/3/DSL/all/DSL_2_A"
#include <iostream>
#include "../lib/segment_tree.hpp"
int main() {
int n, q; std::cin >> n >> q;
auto op = [](long long a, long long b) { return std::min(a, b); };
SegmentTree<long long>
seg(std::vector<long long>(n, (1LL << 31) - 1),
op, (1LL << 31) - 1);
for (int i = 0; i < q; i++) {
int com, x, y; std::cin >> com >> x >> y;
if (com) std::cout << seg.getval(x, y + 1) << std::endl;
else seg.update(x, y);
}
return 0;
}
|
// license:GPL-2.0+
// copyright-holders:Raphael Nabet, Brett Wyer
/*
Corvus Concept driver
Raphael Nabet, Brett Wyer, 2003-2005
*/
#include "emu.h"
#include "includes/concept.h"
#define VERBOSE 1
#define LOG(x) do { if (VERBOSE > 0) logerror x; } while (0)
#define VLOG(x) do { if (VERBOSE > 1) logerror x; } while (0)
/* interrupt priority encoder */
enum
{
IOCINT_level = 1, /* serial lines (CTS, DSR & DCD) and I/O ports */
SR1INT_level, /* serial port 1 acia */
OMINT_level, /* omninet */
SR0INT_level, /* serial port 0 acia */
TIMINT_level, /* via */
KEYINT_level, /* keyboard acia */
NMIINT_level /* reserved */
};
/* Clock interface */
/* Omninet */
/*static int ready;*/ /* ready line from monochip, role unknown */
/* Via */
void concept_state::machine_start()
{
/* initialize int state */
m_pending_interrupts = 0;
/* initialize clock interface */
m_clock_enable = false /*true*/;
save_item(NAME(m_pending_interrupts));
save_item(NAME(m_clock_enable));
save_item(NAME(m_clock_address));
}
void concept_state::machine_reset()
{
// OS will not boot if TDRE is clear on ACIA 0; this fixes that
m_acia0->write_cts(CLEAR_LINE);
m_acia1->write_cts(CLEAR_LINE);
}
void concept_state::video_start()
{
}
uint32_t concept_state::screen_update(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect)
{
/* resolution is 720*560 */
for (int y = 0; y < 560; y++)
{
uint16_t *const line = &bitmap.pix(560-1-y);
for (int x = 0; x < 720; x++)
line[720-1-x] = (m_videoram[(x+48+y*768)>>4] & (0x8000 >> ((x+48+y*768) & 0xf))) ? 1 : 0;
}
return 0;
}
WRITE_LINE_MEMBER(concept_state::ioc_interrupt)
{
concept_set_interrupt(IOCINT_level, state);
}
void concept_state::concept_set_interrupt(int level, int state)
{
int interrupt_mask;
int final_level;
if (state)
m_pending_interrupts |= 1 << level;
else
m_pending_interrupts &= ~ (1 << level);
for (final_level = 7, interrupt_mask = m_pending_interrupts; (final_level > 0) && ! (interrupt_mask & 0x80); final_level--, interrupt_mask <<= 1)
;
if (final_level)
/* assert interrupt */
m_maincpu->set_input_line(M68K_IRQ_1 + final_level - 1, ASSERT_LINE);
else
{
/* clear all interrupts */
m_maincpu->set_input_line(M68K_IRQ_1 + level - 1, CLEAR_LINE);
}
}
/*
VIA port A
0: omninet ready (I)
1: CTS0 (I)
2: CTS1 (I)
3: DSR0 (I)
4: DSR1 (I)
5: DCD0 (I)
6: DCD1 (I)
7: IOX (O)
*/
uint8_t concept_state::via_in_a()
{
LOG(("via_in_a: VIA port A (Omninet and COMM port status) read\n"));
return 1; /* omninet ready always 1 */
}
void concept_state::via_out_a(uint8_t data)
{
LOG(("via_out_a: VIA port A status written: data=0x%2.2x\n", data));
/*iox = (data & 0x80) != 0;*/
}
/*
VIA port B
0: video off (O)
1: video address 17 (O)
2: video address 18 (O)
3: monitor orientation (I)
4: CH rate select DC0 (serial port line) (O)
5: CH rate select DC1 (serial port line) (O)
6: boot switch 0 (I)
7: boot switch 1 (I)
*/
uint8_t concept_state::via_in_b()
{
uint8_t status;
status = ((ioport("DSW0")->read() & 0x80) >> 1) | ((ioport("DSW0")->read() & 0x40) << 1);
LOG(("via_in_b: VIA port B (DIP switches, Video, Comm Rate) - status: 0x%2.2x\n", status));
return status;
}
void concept_state::via_out_b(uint8_t data)
{
VLOG(("via_out_b: VIA port B (Video Control and COMM rate select) written: data=0x%2.2x\n", data));
}
/*
VIA CB2: used as sound output
*/
WRITE_LINE_MEMBER(concept_state::via_out_cb2)
{
// LOG(("via_out_cb2: Sound control written: data=0x%2.2x\n", state));
m_speaker->level_w(state);
}
/*
VIA irq -> 68k level 5
*/
WRITE_LINE_MEMBER(concept_state::via_irq_func)
{
concept_set_interrupt(TIMINT_level, state);
}
uint8_t concept_state::io_r(offs_t offset)
{
switch ((offset >> 8) & 7)
{
case 0:
/* I/O slot regs */
switch ((offset >> 4) & 7)
{
case 1: // IO1 registers
case 2: // IO2 registers
case 3: // IO3 registers
case 4: // IO4 registers
{
int slot = ((offset >> 4) & 7);
device_a2bus_card_interface *card = m_a2bus->get_a2bus_card(slot);
if (card)
{
return card->read_c0nx(offset & 0x0f);
}
return 0xff;
}
break;
default: // ???
logerror("concept_io_r: Slot I/O memory accessed for unknown purpose at address 0x03%4.4x\n", offset << 1);
break;
}
break;
case 1: // IO1 ROM
case 2: // IO2 ROM
case 3: // IO3 ROM
case 4: // IO4 ROM
{
int slot = (offset >> 8) & 7;
device_a2bus_card_interface *card = m_a2bus->get_a2bus_card(slot);
if (card)
{
return card->read_cnxx(offset & 0xff);
}
}
break;
case 5:
/* slot status */
LOG(("concept_io_r: Slot status read at address 0x03%4.4x\n", offset << 1));
return (~m_a2bus->get_a2bus_nmi_mask() & 0x0f) | (~m_a2bus->get_a2bus_irq_mask() & 0x0f) << 4;
case 6:
/* calendar R/W */
VLOG(("concept_io_r: Calendar read at address 0x03%4.4x\n", offset << 1));
if (!m_clock_enable)
return m_mm58174->read(m_clock_address);
break;
case 7:
/* I/O ports */
switch ((offset >> 4) & 7)
{
case 0:
/* NKBP keyboard */
return m_kbdacia->read(offset & 3);
case 1:
/* NSR0 data comm port 0 */
return m_acia0->read(offset & 3);
case 2:
/* NSR1 data comm port 1 */
return m_acia1->read(offset & 3);
case 3:
/* NVIA versatile system interface */
// LOG(("concept_io_r: VIA read at address 0x03%4.4x\n", offset << 1));
{
return m_via0->read(offset & 0xf);
}
case 4:
/* NCALM clock calendar address and strobe register */
/* write-only? */
LOG(("concept_io_r: NCALM clock/calendar read at address 0x03%4.4x\n", offset << 1));
break;
case 5:
/* NOMNI omninet strobe */
logerror("concept_io_r: NOMNI Omninet Transporter register read at address 0x03%4.4x\n", offset << 1);
break;
case 6:
/* NOMOFF reset omninet interrupt flip-flop */
logerror("concept_io_r: NOMOFF Omninet interrupt flip-flop read at address 0x03%4.4x\n", offset << 1);
break;
case 7:
/* NIOSTRB external I/O ROM strobe (disables interface RAM) */
logerror("concept_io_r: NIOSTRB External I/O ROM strobe read at address 0x03%4.4x\n", offset << 1);
break;
}
break;
}
return 0;
}
void concept_state::io_w(offs_t offset, uint8_t data)
{
switch ((offset >> 8) & 7)
{
case 0:
/* I/O slot regs */
switch ((offset >> 4) & 7)
{
case 1: // IO1 registers
case 2: // IO2 registers
case 3: // IO3 registers
case 4: // IO4 registers
{
int slot = (offset >> 4) & 7;
device_a2bus_card_interface *card = m_a2bus->get_a2bus_card(slot);
if (card)
{
return card->write_c0nx(offset & 0x0f, data);
}
}
break;
default: // ???
logerror("concept_io_w: Slot I/O memory written for unknown purpose at address 0x03%4.4x, data: 0x%4.4x\n", offset << 1, data);
break;
}
break;
case 1: // IO1 ROM
case 2: // IO2 ROM
case 3: // IO3 ROM
case 4: // IO4 ROM
{
int slot = (offset >> 8) & 7;
device_a2bus_card_interface *card = m_a2bus->get_a2bus_card(slot);
if (card)
{
return card->write_cnxx(offset & 0xff, data);
}
}
break;
case 5:
/* slot status */
logerror("concept_io_w: Slot status written at address 0x03%4.4x, data: 0x%4.4x\n", offset << 1, data);
break;
case 6:
/* calendar R/W */
LOG(("concept_io_w: Calendar written to at address 0x03%4.4x, data: 0x%4.4x\n", offset << 1, data));
if (!m_clock_enable)
m_mm58174->write(m_clock_address, data & 0xf);
break;
case 7:
/* I/O ports */
switch ((offset >> 4) & 7)
{
case 0:
/* NKBP keyboard */
m_kbdacia->write(offset & 3, data);
break;
case 1:
/* NSR0 data comm port 0 */
m_acia0->write(offset & 3, data);
break;
case 2:
/* NSR1 data comm port 1 */
m_acia1->write(offset & 3, data);
break;
case 3:
/* NVIA versatile system interface */
{
m_via0->write(offset & 0xf, data);
}
break;
case 4:
/* NCALM clock calendar address and strobe register */
if (m_clock_enable != ((data & 0x10) != 0))
{
m_clock_enable = ((data & 0x10) != 0);
if (! m_clock_enable)
/* latch address when enable goes low */
m_clock_address = data & 0x0f;
}
/*volume_control = (data & 0x20) != 0;*/
/*alt_map = (data & 0x40) != 0;*/
break;
case 5:
/* NOMNI omninet strobe */
logerror("concept_io_w: NOMNI Omninet Transporter register written at address 0x03%4.4x, data: 0x%4.4x\n", offset << 1, data);
break;
case 6:
/* NOMOFF reset omninet interrupt flip-flop */
logerror("concept_io_w: NOMOFF Omninet flip-flop reset at address 0x03%4.4x, data: 0x%4.4x\n", offset << 1, data);
break;
case 7:
/* NIOSTRB external I/O ROM strobe */
logerror("concept_io_w: NIOSTRB External I/O ROM strobe written at address 0x03%4.4x, data: 0x%4.4x\n", offset << 1, data);
break;
}
break;
}
}
|
#include <fiberchain/dapp_history/dapp_history_plugin.hpp>
#include <fiberchain/dapp_history/dapp_impacted.hpp>
#include <fiberchain/dapp_history/dapp_history_objects.hpp>
#include <fiberchain/dapp_history/dapp_history_api.hpp>
#include <fiberchain/chain/database.hpp>
#include <fiberchain/chain/index.hpp>
#include <fiberchain/chain/history_object.hpp>
namespace fiberchain { namespace dapp_history {
namespace detail {
class dapp_history_plugin_impl
{
public:
dapp_history_plugin_impl( dapp_history_plugin& _plugin ) : _self( _plugin ) {}
fiberchain::chain::database& database() {
return _self.database();
}
void on_pre_operation( const operation_notification& note );
private:
dapp_history_plugin& _self;
}; //class dapp_history_plugin_impl
struct operation_visitor {
operation_visitor( database& db, const operation_notification& note, const operation_object*& n, dapp_name_type _name )
:_db( db ), _note( note ), _new_obj( n ), dapp_name( _name ) {}
typedef void result_type;
database& _db;
const operation_notification& _note;
const operation_object*& _new_obj;
dapp_name_type dapp_name;
template<typename Op>
void operator()( Op&& )const {
if( !_new_obj ) {
const auto& idx = _db.get_index< operation_index >().indices().get< by_location >();
auto itr = idx.lower_bound( boost::make_tuple( _note.block, _note.trx_in_block, _note.op_in_trx, _note.virtual_op ) );
if( itr != idx.end() && itr->block == _note.block
&& itr->trx_in_block == _note.trx_in_block && itr->op_in_trx == _note.op_in_trx
&& itr->virtual_op == _note.virtual_op ) {
_new_obj = &( *itr );
} else {
while( itr != idx.end() && itr->block == _note.block ){
if(itr->trx_in_block == _note.trx_in_block && itr->op_in_trx == _note.op_in_trx && itr->virtual_op == _note.virtual_op) {
_new_obj = &( *itr );
break;
}
itr++;
}
}
if( !_new_obj ) {
_new_obj = &_db.create< operation_object >( [&]( operation_object& object ) {
object.trx_id = _note.trx_id;
object.block = _note.block;
object.trx_in_block = _note.trx_in_block;
object.op_in_trx = _note.op_in_trx;
object.virtual_op = _note.virtual_op;
object.timestamp = _db.head_block_time();
auto size = fc::raw::pack_size( _note.op );
object.serialized_op.resize( size );
fc::datastream< char* > ds( object.serialized_op.data(), size );
fc::raw::pack( ds, _note.op );
});
}
}
const auto& hist_idx = _db.get_index< dapp_history_index >().indices().get< by_dapp_name >();
auto hist_itr = hist_idx.lower_bound( boost::make_tuple( dapp_name, uint32_t(-1) ) );
uint32_t sequence = 0;
if( hist_itr != hist_idx.end() && hist_itr->dapp_name == dapp_name )
sequence = hist_itr->sequence + 1;
_db.create< dapp_history_object >( [&]( dapp_history_object& object ) {
object.dapp_name = dapp_name;
object.sequence = sequence;
object.op = _new_obj->id;
});
}
}; // struct operation_visitor
void dapp_history_plugin_impl::on_pre_operation( const operation_notification& note ){
flat_set< dapp_name_type > impacted;
fiberchain::chain::database& db = database();
const operation_object* new_obj = nullptr;
operation_get_impacted_dapp( note.op, db, impacted );
for( const auto& dapp_name : impacted ) {
note.op.visit( operation_visitor( db, note, new_obj, dapp_name ) );
}
}
} //namespace detail
dapp_history_plugin::dapp_history_plugin( application* app )
: plugin( app ), _my( new detail::dapp_history_plugin_impl( *this ) ) {}
void dapp_history_plugin::plugin_initialize( const boost::program_options::variables_map& options ) {
try {
ilog( "Intializing dapp history plugin" );
chain::database& db = database();
add_plugin_index< dapp_history_index >( db );
db.pre_apply_operation.connect( [&]( const operation_notification& note ){
_my->on_pre_operation(note);
});
} FC_CAPTURE_AND_RETHROW()
}
void dapp_history_plugin::plugin_startup() {
app().register_api_factory< dapp_history_api >( "dapp_history_api" );
}
} } //namespace fiberchain::dapp_history
FIBERCHAIN_DEFINE_PLUGIN( dapp_history, fiberchain::dapp_history::dapp_history_plugin )
|
/*
* 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 "stdafx.h"
#include "dNewtonBody.h"
#include "dNewtonWorld.h"
#include "dNewtonCollision.h"
class DebugCallBack
{
public:
dVector m_eyePoint;
OnDrawFaceCallback m_callback;
};
dMatrix dNewtonCollision::m_primitiveAligment(dVector(0.0f, 1.0f, 0.0f, 0.0f), dVector(-1.0f, 0.0f, 0.0f, 0.0f), dVector(0.0f, 0.0f, 1.0f, 0.0f), dVector(0.0f, 0.0f, 0.0f, 1.0f));
dNewtonCollision::dNewtonCollision(dNewtonWorld* const world, dLong collisionMask)
:dAlloc()
,m_shape(NULL)
,m_myWorld(world)
,m_materialID(0)
{
}
dNewtonCollision::~dNewtonCollision()
{
DeleteShape();
}
bool dNewtonCollision::IsValid()
{
return m_shape ? true : false;
}
void dNewtonCollision::SetAsTrigger(bool mode)
{
if (m_shape) {
NewtonCollisionSetMode(m_shape, mode ? 0 : 1);
}
}
void dNewtonCollision::SetMaterialID(int materialId)
{
m_materialID = materialId;
}
void dNewtonCollision::SetLayer(int layer)
{
m_layer = layer;
}
void dNewtonCollision::DeleteShape()
{
if (m_shape) {
NewtonWaitForUpdateToFinish(m_myWorld->m_world);
NewtonCollisionSetUserData(m_shape, NULL);
NewtonDestroyCollision(m_shape);
m_myWorld->m_collisionCache.Remove(m_collisionCacheNode);
m_shape = NULL;
m_collisionCacheNode = NULL;
}
}
void dNewtonCollision::SetShape(NewtonCollision* const shape)
{
m_shape = shape;
NewtonCollisionSetUserData(m_shape, this);
m_collisionCacheNode = m_myWorld->m_collisionCache.Append(this);
}
void dNewtonCollision::DebugRenderCallback(void* userData, int vertexCount, const dFloat* faceVertec, int id)
{
DebugCallBack* const callbackInfo = (DebugCallBack*)userData;
dVector normal = dVector(0.0f);
dVector p0 (faceVertec[0], faceVertec[1], faceVertec[2], 0.0f);
dVector p1 (faceVertec[3], faceVertec[4], faceVertec[5], 0.0f);
dVector p1p0(p1 - p0);
for (int i = 2; i < vertexCount; i++) {
dVector p2(faceVertec[i * 3 + 0], faceVertec[i * 3 + 1], faceVertec[i * 3 + 2], 0.0f);
dVector p2p0(p2 - p0);
normal += p1p0.CrossProduct(p2p0);
p1p0 = p2p0;
}
dFloat side = normal.DotProduct3 (callbackInfo->m_eyePoint - p0);
if (side > 0.0f) {
callbackInfo->m_callback(faceVertec, vertexCount);
}
}
void dNewtonCollision::DebugRender(OnDrawFaceCallback callback, const dVector eyePoint)
{
DebugCallBack callbackInfo;
callbackInfo.m_eyePoint = eyePoint;
callbackInfo.m_callback = callback;
dMatrix matrix(dGetIdentityMatrix());
NewtonCollisionForEachPolygonDo(m_shape, &matrix[0][0], DebugRenderCallback, &callbackInfo);
}
void dNewtonCollision::SetScale(dFloat scaleX, dFloat scaleY, dFloat scaleZ)
{
scaleX = dMax(0.01f, dAbs(scaleX));
scaleY = dMax(0.01f, dAbs(scaleY));
scaleZ = dMax(0.01f, dAbs(scaleZ));
NewtonCollisionSetScale(m_shape, scaleX, scaleY, scaleZ);
}
void dNewtonCollision::SetMatrix(const dMatrix matrix)
{
NewtonCollisionSetMatrix(m_shape, &matrix[0][0]);
}
dNewtonCollisionNull::dNewtonCollisionNull(dNewtonWorld* const world)
:dNewtonCollision(world, 0)
{
NewtonWaitForUpdateToFinish(m_myWorld->m_world);
SetShape(NewtonCreateNull(m_myWorld->m_world));
}
dNewtonCollisionSphere::dNewtonCollisionSphere(dNewtonWorld* const world, dFloat r)
:dNewtonCollision(world, 0)
{
NewtonWaitForUpdateToFinish(m_myWorld->m_world);
SetShape(NewtonCreateSphere(m_myWorld->m_world, r, 0, NULL));
}
dNewtonCollisionBox::dNewtonCollisionBox(dNewtonWorld* const world, dFloat x, dFloat y, dFloat z)
:dNewtonCollision(world, 0)
{
NewtonWaitForUpdateToFinish(m_myWorld->m_world);
SetShape(NewtonCreateBox(m_myWorld->m_world, x, y, z, 0, NULL));
}
dNewtonAlignedShapes::dNewtonAlignedShapes(dNewtonWorld* const world, dLong collisionMask)
:dNewtonCollision(world, 0)
{
}
void dNewtonAlignedShapes::SetScale(dFloat x, dFloat y, dFloat z)
{
dVector scale(m_primitiveAligment.RotateVector(dVector(x, y, z, 0.0f)));
dNewtonCollision::SetScale(scale.m_x, scale.m_y, scale.m_z);
}
void dNewtonAlignedShapes::SetMatrix(const dMatrix matrix)
{
dNewtonCollision::SetMatrix(m_primitiveAligment * matrix);
}
dNewtonCollisionCapsule::dNewtonCollisionCapsule(dNewtonWorld* const world, dFloat radio0, dFloat radio1, dFloat height)
:dNewtonAlignedShapes(world, 0)
{
NewtonWaitForUpdateToFinish(m_myWorld->m_world);
SetShape(NewtonCreateCapsule(m_myWorld->m_world, radio0, radio1, height, 0, NULL));
}
dNewtonCollisionCylinder::dNewtonCollisionCylinder(dNewtonWorld* const world, dFloat radio0, dFloat radio1, dFloat height)
:dNewtonAlignedShapes(world, 0)
{
NewtonWaitForUpdateToFinish(m_myWorld->m_world);
SetShape(NewtonCreateCylinder(m_myWorld->m_world, radio0, radio1, height, 0, NULL));
}
dNewtonCollisionCone::dNewtonCollisionCone(dNewtonWorld* const world, dFloat radio, dFloat height)
:dNewtonAlignedShapes(world, 0)
{
NewtonWaitForUpdateToFinish(m_myWorld->m_world);
SetShape(NewtonCreateCone(m_myWorld->m_world, radio, height, 0, NULL));
}
dNewtonCollisionChamferedCylinder::dNewtonCollisionChamferedCylinder(dNewtonWorld* const world, dFloat radio, dFloat height)
:dNewtonAlignedShapes(world, 0)
{
NewtonWaitForUpdateToFinish(m_myWorld->m_world);
SetShape(NewtonCreateChamferCylinder(m_myWorld->m_world, radio, height, 0, NULL));
}
dNewtonCollisionConvexHull::dNewtonCollisionConvexHull(dNewtonWorld* const world, int vertexCount, const dFloat* const vertexCloud, dFloat tolerance)
:dNewtonCollision(world, 0)
{
NewtonWaitForUpdateToFinish(m_myWorld->m_world);
SetShape(NewtonCreateConvexHull(m_myWorld->m_world, vertexCount, vertexCloud, 3 * sizeof (dFloat), tolerance, 0, NULL));
}
dNewtonCollisionMesh::dNewtonCollisionMesh(dNewtonWorld* const world)
:dNewtonCollision(world, 0)
{
NewtonWaitForUpdateToFinish(m_myWorld->m_world);
SetShape(NewtonCreateTreeCollision(m_myWorld->m_world, 0));
}
void dNewtonCollisionMesh::BeginFace()
{
NewtonTreeCollisionBeginBuild(m_shape);
}
void dNewtonCollisionMesh::AddFace(int vertexCount, const dFloat* const vertexPtr, int strideInBytes, int faceAttribute)
{
NewtonTreeCollisionAddFace(m_shape, vertexCount, vertexPtr, strideInBytes, faceAttribute);
}
void dNewtonCollisionMesh::EndFace(bool optimize)
{
NewtonTreeCollisionEndBuild(m_shape, optimize ? 1 : 0);
}
dNewtonCollisionCompound::dNewtonCollisionCompound(dNewtonWorld* const world)
:dNewtonCollision(world, 0)
{
NewtonWaitForUpdateToFinish(m_myWorld->m_world);
SetShape(NewtonCreateCompoundCollision(m_myWorld->m_world, 0));
}
void dNewtonCollisionCompound::BeginAddRemoveCollision()
{
NewtonCompoundCollisionBeginAddRemove(m_shape);
}
void* dNewtonCollisionCompound::AddCollision(dNewtonCollision* const collision)
{
return NewtonCompoundCollisionAddSubCollision(m_shape, collision->m_shape);
}
void dNewtonCollisionCompound::RemoveCollision(void* const handle)
{
NewtonCompoundCollisionRemoveSubCollision(m_shape, handle);
}
void dNewtonCollisionCompound::EndAddRemoveCollision()
{
NewtonCompoundCollisionEndAddRemove(m_shape);
}
dNewtonCollisionHeightField::dNewtonCollisionHeightField(dNewtonWorld* const world, const dFloat* const elevations, int resolution, dVector scale)
:dNewtonCollision(world, 0)
{
char* const attibute = new char[resolution * resolution];
memset(attibute, 0, sizeof(char) * resolution * resolution);
dFloat scaleFactor = 1.0f / (resolution - 1);
NewtonCollision* const shape = NewtonCreateHeightFieldCollision(
m_myWorld->m_world, resolution, resolution, 1, 0, elevations, attibute, 1.0f, scale.m_x * scaleFactor, scale.m_z * scaleFactor, 0);
delete[] attibute;
SetShape(shape);
}
dNewtonCollisionScene::dNewtonCollisionScene(dNewtonWorld* const world)
:dNewtonCollision(world, 0)
{
NewtonWaitForUpdateToFinish(m_myWorld->m_world);
SetShape(NewtonCreateSceneCollision(m_myWorld->m_world, 0));
}
void dNewtonCollisionScene::BeginAddRemoveCollision()
{
NewtonSceneCollisionBeginAddRemove(m_shape);
}
void* dNewtonCollisionScene::AddCollision(const dNewtonCollision* const collision)
{
return NewtonSceneCollisionAddSubCollision(m_shape, collision->m_shape);
}
void dNewtonCollisionScene::RemoveCollision(void* const handle)
{
NewtonSceneCollisionRemoveSubCollision(m_shape, handle);
}
void dNewtonCollisionScene::EndAddRemoveCollision()
{
NewtonSceneCollisionEndAddRemove(m_shape);
}
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "ppl/nn/engines/riscv/optimizer/ops/onnx/reshape_op.h"
#include "ppl/nn/engines/riscv/kernels/onnx/reshape_kernel.h"
#include "ppl/nn/oputils/onnx/reshape_reshape.h"
using namespace std;
using namespace ppl::common;
namespace ppl { namespace nn { namespace riscv {
RetCode ReshapeOp::Init(const OptKernelOptions& options) {
infer_dims_func_ = [](InputOutputInfo* info) -> RetCode {
return onnx::ReshapeReshape(info, nullptr);
};
infer_type_func_ = GenericInferType;
return RC_SUCCESS;
}
RetCode ReshapeOp::SelectFormat(const InputOutputInfo& info, vector<dataformat_t>* selected_input_formats,
vector<dataformat_t>* selected_output_formats) {
selected_input_formats->at(0) = DATAFORMAT_NDARRAY;
selected_output_formats->at(0) = DATAFORMAT_NDARRAY;
return RC_SUCCESS;
}
KernelImpl* ReshapeOp::CreateKernelImpl() const {
return CreateKernelImplWithoutParam<ReshapeKernel>();
}
}}} // namespace ppl::nn::riscv
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkSobelGradientMagnitudePass.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkSobelGradientMagnitudePass.h"
#include "vtkObjectFactory.h"
#include <cassert>
#include "vtkRenderState.h"
#include "vtkRenderer.h"
#include "vtkgl.h"
#include "vtkFrameBufferObject.h"
#include "vtkTextureObject.h"
#include "vtkShaderProgram2.h"
#include "vtkShader2.h"
#include "vtkShader2Collection.h"
#include "vtkUniformVariables.h"
#include "vtkOpenGLRenderWindow.h"
#include "vtkOpenGLExtensionManager.h"
#include "vtkOpenGLError.h"
#include "vtkTextureUnitManager.h"
// to be able to dump intermediate passes into png files for debugging.
// only for vtkSobelGradientMagnitudePass developers.
//#define VTK_SOBEL_PASS_DEBUG
#include "vtkPNGWriter.h"
#include "vtkImageImport.h"
#include "vtkPixelBufferObject.h"
#include "vtkPixelBufferObject.h"
#include "vtkImageExtractComponents.h"
vtkStandardNewMacro(vtkSobelGradientMagnitudePass);
extern const char *vtkSobelGradientMagnitudePassShader1_fs;
extern const char *vtkSobelGradientMagnitudePassShader2_fs;
// ----------------------------------------------------------------------------
vtkSobelGradientMagnitudePass::vtkSobelGradientMagnitudePass()
{
this->FrameBufferObject=0;
this->Pass1=0;
this->Gx1=0;
this->Gy1=0;
this->Program1=0;
this->Program2=0;
}
// ----------------------------------------------------------------------------
vtkSobelGradientMagnitudePass::~vtkSobelGradientMagnitudePass()
{
if(this->FrameBufferObject!=0)
{
vtkErrorMacro(<<"FrameBufferObject should have been deleted in ReleaseGraphicsResources().");
}
if(this->Pass1!=0)
{
vtkErrorMacro(<<"Pass1 should have been deleted in ReleaseGraphicsResources().");
}
if(this->Gx1!=0)
{
vtkErrorMacro(<<"Gx1 should have been deleted in ReleaseGraphicsResources().");
}
if(this->Gy1!=0)
{
vtkErrorMacro(<<"Gx1 should have been deleted in ReleaseGraphicsResources().");
}
if(this->Program1!=0)
{
this->Program1->Delete();
}
if(this->Program2!=0)
{
this->Program2->Delete();
}
}
// ----------------------------------------------------------------------------
void vtkSobelGradientMagnitudePass::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
}
// ----------------------------------------------------------------------------
// Description:
// Perform rendering according to a render state \p s.
// \pre s_exists: s!=0
void vtkSobelGradientMagnitudePass::Render(const vtkRenderState *s)
{
assert("pre: s_exists" && s!=0);
this->NumberOfRenderedProps=0;
if(this->DelegatePass!=0)
{
vtkRenderer *renderer = s->GetRenderer();
vtkOpenGLRenderWindow *context
= vtkOpenGLRenderWindow::SafeDownCast(renderer->GetRenderWindow());
// Test for Hardware support. If not supported, just render the delegate.
bool fbo_support = vtkFrameBufferObject::IsSupported(context)!=0;
bool texture_support = vtkTextureObject::IsSupported(context)!=0;
bool shader_support = vtkShaderProgram2::IsSupported(context)!=0;
bool supported
= fbo_support && texture_support && shader_support;
if (!supported)
{
vtkErrorMacro(
<< "The required extensions are not supported."
<< " fbo_support=" << fbo_support
<< " texture_support=" << texture_support
<< " shader_support=" << shader_support);
this->DelegatePass->Render(s);
this->NumberOfRenderedProps
+= this->DelegatePass->GetNumberOfRenderedProps();
return;
}
vtkOpenGLClearErrorMacro();
GLint savedDrawBuffer;
glGetIntegerv(GL_DRAW_BUFFER,&savedDrawBuffer);
// 1. Create a new render state with an FBO.
int width=0;
int height=0;
int size[2];
s->GetWindowSize(size);
width=size[0];
height=size[1];
const int extraPixels=1; // one on each side
int w=width+2*extraPixels;
int h=height+2*extraPixels;
if(this->Pass1==0)
{
this->Pass1=vtkTextureObject::New();
this->Pass1->SetContext(context);
}
if(this->FrameBufferObject==0)
{
this->FrameBufferObject=vtkFrameBufferObject::New();
this->FrameBufferObject->SetContext(context);
}
this->RenderDelegate(s,width,height,w,h,this->FrameBufferObject,
this->Pass1);
#ifdef VTK_SOBEL_PASS_DEBUG
// Save first pass in file for debugging.
vtkPixelBufferObject *pbo=this->Pass1->Download();
unsigned char *openglRawData=new unsigned char[4*w*h];
unsigned int dims[2];
dims[0]=w;
dims[1]=h;
vtkIdType incs[2];
incs[0]=0;
incs[1]=0;
bool status=pbo->Download2D(VTK_UNSIGNED_CHAR,openglRawData,dims,4,incs);
assert("check" && status);
pbo->Delete();
// no pbo
this->Pass1->Bind();
glGetTexImage(GL_TEXTURE_2D,0,GL_RGBA,GL_UNSIGNED_BYTE,openglRawData);
this->Pass1->UnBind();
vtkImageImport *importer=vtkImageImport::New();
importer->CopyImportVoidPointer(openglRawData,4*w*h*sizeof(unsigned char));
importer->SetDataScalarTypeToUnsignedChar();
importer->SetNumberOfScalarComponents(4);
importer->SetWholeExtent(0,w-1,0,h-1,0,0);
importer->SetDataExtentToWholeExtent();
delete[] openglRawData;
vtkImageExtractComponents *rgbaToRgb=vtkImageExtractComponents::New();
rgbaToRgb->SetInputConnection(importer->GetOutputPort());
rgbaToRgb->SetComponents(0,1,2);
vtkPNGWriter *writer=vtkPNGWriter::New();
writer->SetFileName("SobelPass1.png");
writer->SetInputConnection(rgbaToRgb->GetOutputPort());
importer->Delete();
rgbaToRgb->Delete();
writer->Write();
writer->Delete();
#endif
// 3. Same FBO, but two color attachments (new TOs gx1 and gy1).
if(this->Gx1==0)
{
this->Gx1=vtkTextureObject::New();
this->Gx1->SetContext(this->FrameBufferObject->GetContext());
}
if(this->Gx1->GetWidth()!=static_cast<unsigned int>(w) ||
this->Gx1->GetHeight()!=static_cast<unsigned int>(h))
{
this->Gx1->Create2D(w,h,4,VTK_UNSIGNED_CHAR,false);
}
if(this->Gy1==0)
{
this->Gy1=vtkTextureObject::New();
this->Gy1->SetContext(this->FrameBufferObject->GetContext());
}
if(this->Gy1->GetWidth()!=static_cast<unsigned int>(w) ||
this->Gy1->GetHeight()!=static_cast<unsigned int>(h))
{
this->Gy1->Create2D(w,h,4,VTK_UNSIGNED_CHAR,false);
}
#ifdef VTK_SOBEL_PASS_DEBUG
cout << "gx1 TOid=" << this->Gx1->GetHandle() <<endl;
cout << "gy1 TOid=" << this->Gy1->GetHandle() <<endl;
#endif
this->FrameBufferObject->SetNumberOfRenderTargets(2);
this->FrameBufferObject->SetColorBuffer(0,this->Gx1);
this->FrameBufferObject->SetColorBuffer(1,this->Gy1);
unsigned int indices[2]={0,1};
this->FrameBufferObject->SetActiveBuffers(2,indices);
this->FrameBufferObject->Start(w,h,false);
#ifdef VTK_SOBEL_PASS_DEBUG
cout << "sobel finish2" << endl;
glFinish();
#endif
// Use the horizontal shader to compute the first pass of Gx and Gy.
// this->Pass1 is the source
// (this->Gx1 and this->Gy1 are fbo render targets)
if(this->Program1==0)
{
this->Program1=vtkShaderProgram2::New();
this->Program1->SetContext(
static_cast<vtkOpenGLRenderWindow *>(
this->FrameBufferObject->GetContext()));
vtkShader2 *shader=vtkShader2::New();
shader->SetType(VTK_SHADER_TYPE_FRAGMENT);
shader->SetSourceCode(vtkSobelGradientMagnitudePassShader1_fs);
shader->SetContext(this->Program1->GetContext());
this->Program1->GetShaders()->AddItem(shader);
shader->Delete();
}
this->Program1->Build();
#ifdef VTK_SOBEL_PASS_DEBUG
this->Program1->PrintActiveUniformVariablesOnCout();
#endif
#ifdef VTK_SOBEL_PASS_DEBUG
cout << "sobel finish build 1" << endl;
glFinish();
#endif
if(this->Program1->GetLastBuildStatus()
!=VTK_SHADER_PROGRAM2_LINK_SUCCEEDED)
{
vtkErrorMacro("Couldn't build the shader program. At this point , it can be an error in a shader or a driver bug.");
// restore some state.
this->FrameBufferObject->UnBind();
glDrawBuffer(savedDrawBuffer);
return;
}
vtkUniformVariables *var=this->Program1->GetUniformVariables();
vtkTextureUnitManager *tu=context->GetTextureUnitManager();
int sourceId=tu->Allocate();
vtkgl::ActiveTexture(vtkgl::TEXTURE0+sourceId);
this->Pass1->Bind();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
var->SetUniformi("source",1,&sourceId);
float fvalue=static_cast<float>(1.0/w);
var->SetUniformf("stepSize",1,&fvalue);
this->Program1->Use();
#ifdef VTK_SOBEL_PASS_DEBUG
cout << "sobel finish use 1" << endl;
glFinish();
#endif
#ifdef VTK_SOBEL_PASS_DEBUG
this->Program1->PrintActiveUniformVariablesOnCout();
#endif
if(!this->Program1->IsValid())
{
vtkErrorMacro(<<this->Program1->GetLastValidateLog());
}
#ifdef VTK_SOBEL_PASS_DEBUG
cout << "sobel finish3-" << endl;
glFinish();
#endif
this->FrameBufferObject->RenderQuad(0,w-1,0,h-1);
#ifdef VTK_SOBEL_PASS_DEBUG
cout << "sobel finish3" << endl;
glFinish();
#endif
this->Pass1->UnBind();
tu->Free(sourceId);
#ifdef VTK_SOBEL_PASS_DEBUG
// Save second pass in file for debugging.
pbo=this->Gx1->Download();
openglRawData=new unsigned char[4*w*h];
status=pbo->Download2D(VTK_UNSIGNED_CHAR,openglRawData,dims,4,incs);
assert("check2" && status);
pbo->Delete();
importer=vtkImageImport::New();
importer->CopyImportVoidPointer(openglRawData,4*w*h*sizeof(unsigned char));
importer->SetDataScalarTypeToUnsignedChar();
importer->SetNumberOfScalarComponents(4);
importer->SetWholeExtent(0,w-1,0,h-1,0,0);
importer->SetDataExtentToWholeExtent();
delete[] openglRawData;
rgbaToRgb=vtkImageExtractComponents::New();
rgbaToRgb->SetInputConnection(importer->GetOutputPort());
rgbaToRgb->SetComponents(0,1,2);
writer=vtkPNGWriter::New();
writer->SetFileName("SobelPass2Gx1.png");
writer->SetInputConnection(rgbaToRgb->GetOutputPort());
importer->Delete();
rgbaToRgb->Delete();
writer->Write();
writer->Delete();
pbo=this->Gy1->Download();
openglRawData=new unsigned char[4*w*h];
status=pbo->Download2D(VTK_UNSIGNED_CHAR,openglRawData,dims,4,incs);
assert("check3" && status);
pbo->Delete();
importer=vtkImageImport::New();
importer->CopyImportVoidPointer(openglRawData,4*w*h*sizeof(unsigned char));
importer->SetDataScalarTypeToUnsignedChar();
importer->SetNumberOfScalarComponents(4);
importer->SetWholeExtent(0,w-1,0,h-1,0,0);
importer->SetDataExtentToWholeExtent();
delete[] openglRawData;
rgbaToRgb=vtkImageExtractComponents::New();
rgbaToRgb->SetInputConnection(importer->GetOutputPort());
rgbaToRgb->SetComponents(0,1,2);
writer=vtkPNGWriter::New();
writer->SetFileName("SobelPass2Gy1.png");
writer->SetInputConnection(rgbaToRgb->GetOutputPort());
importer->Delete();
rgbaToRgb->Delete();
writer->Write();
writer->Delete();
#endif
// 4. Render in original FB (from renderstate in arg)
this->Program1->Restore();
this->FrameBufferObject->UnBind();
glDrawBuffer(savedDrawBuffer);
if(this->Program2==0)
{
this->Program2=vtkShaderProgram2::New();
this->Program2->SetContext(
static_cast<vtkOpenGLRenderWindow *>(
this->FrameBufferObject->GetContext()));
vtkShader2 *shader=vtkShader2::New();
shader->SetType(VTK_SHADER_TYPE_FRAGMENT);
shader->SetSourceCode(vtkSobelGradientMagnitudePassShader2_fs);
shader->SetContext(this->Program2->GetContext());
this->Program2->GetShaders()->AddItem(shader);
shader->Delete();
}
this->Program2->Build();
#ifdef VTK_SOBEL_PASS_DEBUG
this->Program2->PrintActiveUniformVariablesOnCout();
#endif
#ifdef VTK_SOBEL_PASS_DEBUG
cout << "sobel finish build 2" << endl;
glFinish();
#endif
if(this->Program2->GetLastBuildStatus()
!=VTK_SHADER_PROGRAM2_LINK_SUCCEEDED)
{
vtkErrorMacro("Couldn't build the shader program. At this point , it can be an error in a shader or a driver bug.");
// restore some state.
vtkgl::ActiveTexture(vtkgl::TEXTURE0);
return;
}
// this->Gx1 and this->Gy1 are the sources
int id0=tu->Allocate();
int id1=tu->Allocate();
vtkgl::ActiveTexture(vtkgl::TEXTURE0+id0);
this->Gx1->Bind();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
vtkgl::ActiveTexture(vtkgl::TEXTURE0+id1);
this->Gy1->Bind();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
var=this->Program2->GetUniformVariables();
var->SetUniformi("gx1",1,&id0);
var->SetUniformi("gy1",1,&id1);
fvalue=static_cast<float>(1.0/h);
var->SetUniformf("stepSize",1,&fvalue);
this->Program2->Use();
#ifdef VTK_SOBEL_PASS_DEBUG
cout << "sobel finish use 2" << endl;
glFinish();
#endif
#ifdef VTK_SOBEL_PASS_DEBUG
this->Program2->PrintActiveUniformVariablesOnCout();
#endif
if(!this->Program2->IsValid())
{
vtkErrorMacro(<<this->Program2->GetLastValidateLog());
}
#ifdef VTK_SOBEL_PASS_DEBUG
cout << "sobel finish 4-" << endl;
glFinish();
#endif
// Prepare blitting
glDisable(GL_ALPHA_TEST);
glDisable(GL_BLEND);
glDisable(GL_DEPTH_TEST);
glDisable(GL_LIGHTING);
glDisable(GL_SCISSOR_TEST);
// Trigger a draw on Gy1 (could be called on Gx1).
this->Gy1->CopyToFrameBuffer(extraPixels,extraPixels,
w-1-extraPixels,h-1-extraPixels,
0,0,width,height);
this->Gy1->UnBind();
vtkgl::ActiveTexture(vtkgl::TEXTURE0+id0);
this->Gx1->UnBind();
vtkgl::ActiveTexture(vtkgl::TEXTURE0);
tu->Free(id1);
tu->Free(id0);
#ifdef VTK_SOBEL_PASS_DEBUG
cout << "sobel finish4" << endl;
glFinish();
#endif
this->Program2->Restore();
}
else
{
vtkWarningMacro(<<" no delegate.");
}
vtkOpenGLCheckErrorMacro("failed after Render");
}
// ----------------------------------------------------------------------------
// Description:
// Release graphics resources and ask components to release their own
// resources.
// \pre w_exists: w!=0
void vtkSobelGradientMagnitudePass::ReleaseGraphicsResources(vtkWindow *w)
{
assert("pre: w_exists" && w!=0);
this->Superclass::ReleaseGraphicsResources(w);
if(this->Program1!=0)
{
this->Program1->ReleaseGraphicsResources();
}
if(this->Program2!=0)
{
this->Program2->ReleaseGraphicsResources();
}
if(this->FrameBufferObject!=0)
{
this->FrameBufferObject->Delete();
this->FrameBufferObject=0;
}
if(this->Pass1!=0)
{
this->Pass1->Delete();
this->Pass1=0;
}
if(this->Gx1!=0)
{
this->Gx1->Delete();
this->Gx1=0;
}
if(this->Gy1!=0)
{
this->Gy1->Delete();
this->Gy1=0;
}
}
|
/****************************************************************************
*
* (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
* QGroundControl is licensed according to the terms in the file
* COPYING.md in the root of the source code directory.
*
****************************************************************************/
#include "TaisyncHandler.h"
#include "SettingsManager.h"
#include "QGCApplication.h"
#include "VideoManager.h"
QGC_LOGGING_CATEGORY(TaisyncLog, "TaisyncLog")
QGC_LOGGING_CATEGORY(TaisyncVerbose, "TaisyncVerbose")
//-----------------------------------------------------------------------------
TaisyncHandler::TaisyncHandler(QObject* parent)
: QObject (parent)
{
}
//-----------------------------------------------------------------------------
TaisyncHandler::~TaisyncHandler()
{
close();
}
//-----------------------------------------------------------------------------
bool TaisyncHandler::close()
{
bool res = (_tcpSocket || _tcpServer);
if(_tcpSocket) {
qCDebug(TaisyncLog) << "Close Taisync TCP socket on port" << _tcpSocket->localPort();
_tcpSocket->close();
_tcpSocket->deleteLater();
_tcpSocket = nullptr;
}
if(_tcpServer) {
qCDebug(TaisyncLog) << "Close Taisync TCP server on port" << _tcpServer->serverPort();;
_tcpServer->close();
_tcpServer->deleteLater();
_tcpServer = nullptr;
}
return res;
}
//-----------------------------------------------------------------------------
bool
TaisyncHandler::_start(uint16_t port, QHostAddress addr)
{
close();
_serverMode = addr == QHostAddress::AnyIPv4;
if(_serverMode) {
if(!_tcpServer) {
qCDebug(TaisyncLog) << "Listen for Taisync TCP on port" << port;
_tcpServer = new QTcpServer(this);
QObject::connect(_tcpServer, &QTcpServer::newConnection, this, &TaisyncHandler::_newConnection);
_tcpServer->listen(QHostAddress::AnyIPv4, port);
}
} else {
_tcpSocket = new QTcpSocket();
QObject::connect(_tcpSocket, &QIODevice::readyRead, this, &TaisyncHandler::_readBytes);
qCDebug(TaisyncLog) << "Connecting to" << addr;
_tcpSocket->connectToHost(addr, port);
//-- TODO: This has to be removed. It's blocking the main thread.
if (!_tcpSocket->waitForConnected(1000)) {
close();
return false;
}
emit connected();
}
return true;
}
//-----------------------------------------------------------------------------
void
TaisyncHandler::_newConnection()
{
qCDebug(TaisyncLog) << "New Taisync TCP Connection on port" << _tcpServer->serverPort();
if(_tcpSocket) {
_tcpSocket->close();
_tcpSocket->deleteLater();
}
_tcpSocket = _tcpServer->nextPendingConnection();
if(_tcpSocket) {
QObject::connect(_tcpSocket, &QIODevice::readyRead, this, &TaisyncHandler::_readBytes);
QObject::connect(_tcpSocket, &QAbstractSocket::disconnected, this, &TaisyncHandler::_socketDisconnected);
emit connected();
} else {
qCWarning(TaisyncLog) << "New Taisync TCP Connection provided no socket";
}
}
//-----------------------------------------------------------------------------
void
TaisyncHandler::_socketDisconnected()
{
qCDebug(TaisyncLog) << "Taisync TCP Connection Closed on port" << _tcpSocket->localPort();
if(_tcpSocket) {
_tcpSocket->close();
_tcpSocket->deleteLater();
_tcpSocket = nullptr;
}
emit disconnected();
}
|
/**
* The U Programming Language
*
* Copyright 2018 Joseph Benden
*
* 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.
*
* \author Joseph W. Benden
* \copyright (C) 2018 Joseph Benden
* \license apache2
*/
#ifndef ULANG_U_H
#define ULANG_U_H
#define UC_MAJOR_VERSION 0
#define UC_MINOR_VERSION 0
#define UC_MICRO_VERSION 1
#define UC_VERSION_SEP .
#define PPCAT_NX(A, B) A ## B
#define PPCAT_NX3(A, B, C) A ## B ## C
#define PPCAT_NX4(A,B,C,D) A ## B ## C ## D
#define PPCAT_NX5(A,B,C,D,E) A ## B ## C ## D ## E
#define PPCAT(A, B) PPCAT_NX(A,B)
#define PPCAT3(A, B, C) PPCAT_NX3(A,B,C)
#define PPCAT4(A, B, C, D) PPCAT_NX4(A,B,C,D)
#define PPCAT5(A, B, C, D, E) PPCAT_NX5(A,B,C,D,E)
#define STRINGIZE_NX(A) #A
#define STRINGIZE(A) STRINGIZE_NX(A)
#define UC_VERSION STRINGIZE(PPCAT5(UC_MAJOR_VERSION, \
UC_VERSION_SEP, \
UC_MINOR_VERSION, \
UC_VERSION_SEP, \
UC_MICRO_VERSION))
#if defined(_WIN32) && defined(_DLL)
#if !defined(U_DLL) && !defined(U_STATIC)
#define U_DLL
#endif
#endif
//
// The following block is the standard way of creating macros which make exporting
// from a DLL simpler. All files within this DLL are compiled with the foundation_EXPORTS
// symbol defined on the command line. this symbol should not be defined on any project
// that uses this DLL. This way any other project whose source files include this file see
// foundation_API functions as being imported from a DLL, wheras this DLL sees symbols
// defined with this macro as being exported.
//
#if (defined(_WIN32) || defined(_WIN32_WCE)) && defined(U_DLL)
#if defined(UEXPORTS)
#define UAPI __declspec(dllexport)
#else
#define UAPI __declspec(dllimport)
#endif
#endif
#if !defined(UAPI)
#if !defined(U_NO_GCC_API_ATTRIBUTE) && defined (__GNUC__) && (__GNUC__ >= 4)
#define UAPI __attribute__ ((visibility ("default")))
#else
#define UAPI
#endif
#endif
/* Here we provide G_GNUC_EXTENSION as an alias for __extension__,
* where this is valid. This allows for warningless compilation of
* "long long" types even in the presence of '-ansi -pedantic'.
*/
#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 8)
#define U_GNUC_EXTENSION __extension__
#else
#define U_GNUC_EXTENSION
#endif
/* Provide macros to feature the GCC function attribute.
*/
#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 96)
#define U_GNUC_PURE __attribute__((__pure__))
#define U_GNUC_MALLOC __attribute__((__malloc__))
#else
#define U_GNUC_PURE
#define U_GNUC_MALLOC
#endif
#if __GNUC__ >= 4
#define U_GNUC_NULL_TERMINATED __attribute__((__sentinel__))
#else
#define U_GNUC_NULL_TERMINATED
#endif
/* Guard C code in headers, while including them from C++ */
#ifdef __cplusplus
#define U_BEGIN_DECLS extern "C" {
#define U_END_DECLS }
#else
#define U_BEGIN_DECLS
#define U_END_DECLS
#endif
#undef UMAX
#define UMAX(a, b) (((a) > (b)) ? (a) : (b))
#undef UMIN
#define UMIN(a, b) (((a) < (b)) ? (a) : (b))
#undef UABS
#define UABS(a) (((a) < 0) ? -(a) : (a))
#undef UCLAMP
#define UCLAMP(x, low, high) (((x) > (high)) ? (high) : (((x) < (low)) ? (low) : (x)))
/* Count the number of elements in an array. The array must be defined
* as such; using this with a dynamically allocated array will give
* incorrect results.
*/
#define U_N_ELEMENTS(arr) (sizeof (arr) / sizeof ((arr)[0]))
#if (defined(__GNUC__) && __GNUC__ >= 4) || defined (_MSC_VER)
#define U_STRUCT_OFFSET(struct_type, member) \
((glong) offsetof (struct_type, member))
#else
#define U_STRUCT_OFFSET(struct_type, member) \
((glong) ((guint8*) &((struct_type*) 0)->member))
#endif
#define U_STRUCT_MEMBER_P(struct_p, struct_offset) \
((gpointer) ((guint8*) (struct_p) + (glong) (struct_offset)))
#define U_STRUCT_MEMBER(member_type, struct_p, struct_offset) \
(*(member_type*) U_STRUCT_MEMBER_P ((struct_p), (struct_offset)))
/*
* The U_LIKELY and U_UNLIKELY macros let the programmer give hints to
* the compiler about the expected result of an expression. Some compilers
* can use this information for optimization.
*
* The _U_BOOLEAN_EXPR macro is intended to trigger a gcc warning when
* putting assignments in g_return_if_fail ().
*/
#if defined(__GNUC__) && (__GNUC__ > 2) && defined(__OPTIMIZE__)
#define _U_BOOLEAN_EXPR(expr) \
U_GNUC_EXTENSION ({ \
int _g_boolean_var_; \
if (expr) \
_g_boolean_var_ = 1; \
else \
_g_boolean_var_ = 0; \
_g_boolean_var_; \
})
#define U_LIKELY(expr) (__builtin_expect (_U_BOOLEAN_EXPR((expr)), 1))
#define U_UNLIKELY(expr) (__builtin_expect (_U_BOOLEAN_EXPR((expr)), 0))
#else
#define U_LIKELY(expr) (expr)
#define U_UNLIKELY(expr) (expr)
#endif
#ifdef __cplusplus
#define UINLINE inline
#else
#define UINLINE
#endif
#if __GNUC__ >= 4
#define UINLINE_ALWAYS UINLINE __attribute__((always_inline))
#else
#define UINLINE_ALWAYS UINLINE
#endif
#ifdef __cplusplus
#include <iostream>
#include <system_error>
#include <assert.h>
#undef HAVE_INTTYPES_H
#undef HAVE_STDINT_H
#undef HAVE_UINT64_T
#include <stdtypes.hpp>
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
using size_t = ::std::size_t;
#endif
#define Kilobytes(Value) ((Value)*1024LL)
#define Megabytes(Value) (Kilobytes(Value)*1024LL)
#define Gigabytes(Value) (Megabytes(Value)*1024LL)
#define Terabytes(Value) (Gigabytes(Value)*1024LL)
#define AlignPow2(Value, Alignment) ((Value + ((Alignment) - 1)) & ~((Value - Value) + (Alignment) - 1))
#define Align4(Value) ((Value + 3) & ~3)
#define Align8(Value) ((Value + 7) & ~7)
#define Align16(Value) ((Value + 15) & ~15)
inline uint32_t
SafeTruncateUInt64(uint64_t Value)
{
assert(Value <= 0xFFFFFFFF);
uint32_t Result = (uint32_t)Value;
return(Result);
}
inline uint16_t
SafeTruncateToU16(uint32_t Value)
{
assert(Value <= 0xFFFF);
uint16_t Result = (uint16_t)Value;
return(Result);
}
inline uint8_t
SafeTruncateToU16(uint16_t Value)
{
assert(Value <= 0xFF);
uint8_t Result = (uint8_t)Value;
return(Result);
}
#endif
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <pow.h>
#include <arith_uint256.h>
#include <chain.h>
#include <primitives/block.h>
#include <uint256.h>
unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params)
{
assert(pindexLast != nullptr);
unsigned int nProofOfWorkLimit = UintToArith256(params.powLimit).GetCompact();
// Only change once per difficulty adjustment interval
if ((pindexLast->nHeight+1) % params.DifficultyAdjustmentInterval() != 0)
{
if (params.fPowAllowMinDifficultyBlocks)
{
// Special difficulty rule for testnet:
// If the new block's timestamp is more than 2* 10 minutes
// then allow mining of a min-difficulty block.
if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2)
return nProofOfWorkLimit;
else
{
// Return the last non-special-min-difficulty-rules-block
const CBlockIndex* pindex = pindexLast;
while (pindex->pprev && pindex->nHeight % params.DifficultyAdjustmentInterval() != 0 && pindex->nBits == nProofOfWorkLimit)
pindex = pindex->pprev;
return pindex->nBits;
}
}
return pindexLast->nBits;
}
// Go back by what we want to be 14 days worth of blocks
// Rackcoin: This fixes an issue where a 51% attack can change difficulty at will.
// Go back the full period unless it's the first retarget after genesis. Code courtesy of Art Forz
int blockstogoback = params.DifficultyAdjustmentInterval()-1;
if ((pindexLast->nHeight+1) != params.DifficultyAdjustmentInterval())
blockstogoback = params.DifficultyAdjustmentInterval();
// Go back by what we want to be 14 days worth of blocks
const CBlockIndex* pindexFirst = pindexLast;
for (int i = 0; pindexFirst && i < blockstogoback; i++)
pindexFirst = pindexFirst->pprev;
assert(pindexFirst);
return CalculateNextWorkRequired(pindexLast, pindexFirst->GetBlockTime(), params);
}
unsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params)
{
if (params.fPowNoRetargeting)
return pindexLast->nBits;
// Limit adjustment step
int64_t nActualTimespan = pindexLast->GetBlockTime() - nFirstBlockTime;
if (nActualTimespan < params.nPowTargetTimespan/4)
nActualTimespan = params.nPowTargetTimespan/4;
if (nActualTimespan > params.nPowTargetTimespan*4)
nActualTimespan = params.nPowTargetTimespan*4;
// Retarget
arith_uint256 bnNew;
arith_uint256 bnOld;
bnNew.SetCompact(pindexLast->nBits);
bnOld = bnNew;
// Rackcoin: intermediate uint256 can overflow by 1 bit
const arith_uint256 bnPowLimit = UintToArith256(params.powLimit);
bool fShift = bnNew.bits() > bnPowLimit.bits() - 1;
if (fShift)
bnNew >>= 1;
bnNew *= nActualTimespan;
bnNew /= params.nPowTargetTimespan;
if (fShift)
bnNew <<= 1;
if (bnNew > bnPowLimit)
bnNew = bnPowLimit;
return bnNew.GetCompact();
}
bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params)
{
bool fNegative;
bool fOverflow;
arith_uint256 bnTarget;
bnTarget.SetCompact(nBits, &fNegative, &fOverflow);
// Check range
if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit))
return false;
// Check proof of work matches claimed amount
if (UintToArith256(hash) > bnTarget)
return false;
return true;
}
|
#include "pch.h"
#include "vcpkg_Commands.h"
#include "vcpkg_Input.h"
#include "vcpkg_System.h"
namespace vcpkg::Commands::BuildExternal
{
void perform_and_exit(const VcpkgCmdArguments& args, const VcpkgPaths& paths, const Triplet& default_triplet)
{
static const std::string example =
Commands::Help::create_example_string(R"(build_external zlib2 C:\path\to\dir\with\controlfile\)");
args.check_exact_arg_count(2, example);
const FullPackageSpec spec =
Input::check_and_get_full_package_spec(args.command_arguments.at(0), default_triplet, example);
Input::check_triplet(spec.package_spec.triplet(), paths);
const std::unordered_set<std::string> options = args.check_and_get_optional_command_arguments({});
const fs::path port_dir = args.command_arguments.at(1);
BuildCommand::perform_and_exit(spec, port_dir, options, paths);
}
}
|
#include <stdlib.h>
#include <string>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "Tools.h"
#include <string.h>
#include <libxml/tree.h>
#include <libxml/parser.h>
#include <libxml/xpath.h>
#include <libxml/xpathInternals.h>
int main(int argc,char **argv)
{
std::string url[]=
{
"http://www.france24.com/fr/actualites/rss",
"http://www.france24.com/fr/europe/rss/",
"http://rss.lapresse.ca/179.xml"
};
srand (time(NULL));
std::string news=url[(int) (3.0 * (rand() / (RAND_MAX + 1.0)))];
//std::cout<<news<<std::endl;
std::string xml = getUrl(news);
//channel->item->title
//channel->item->description
// std::cout<<xml<<std::endl;
xmlInitParser();
xmlDocPtr dd= xmlParseMemory(xml.c_str(),xml.size());
xmlXPathContextPtr xpathCtx = xmlXPathNewContext(dd);
std::string path="//item/title";
xmlXPathObjectPtr xpathObj=xmlXPathEvalExpression(BAD_CAST path.c_str(), xpathCtx);
for (int i=0; i < xpathObj->nodesetval->nodeNr; i++) {
xmlChar *keyword = xmlNodeListGetString(dd, xpathObj->nodesetval->nodeTab[i]->xmlChildrenNode, 1);
std::string txt;
txt.append((const char*)keyword,strlen((const char *)keyword));
printf("%s\n", majuscule(txt).c_str());
xmlFree(keyword);
}
xmlCleanupParser();
exit(0);
}
|
#include "config.h"
int main(int argc, char *argv[])
{
//需要修改的数据库信息,登录名,密码,库名
string user = "root";
string passwd = "root";
string databasename = "qgydb";
//命令行解析 后期可以写一个类,读取项目配置文件
Config config;
config.parse_arg(argc, argv);
//栈上构造 初始化 httpconns timers
WebServer server;
//初始化 数据库配置、链接池配置、线程池配置
server.init(config.PORT, user, passwd, databasename, config.LOGWrite,
config.OPT_LINGER, config.TRIGMode, config.sql_num, config.thread_num,
config.close_log, config.actor_model);
/////////////以下服务器的动作 不应该是在init里么?应该是伴随着server的声明周期且不会被单独调用的
//日志
server.log_write();
//数据库
server.sql_pool();
//线程池
server.thread_pool();
//触发模式
server.trig_mode();
//监听
server.eventListen();
/////////////////////////////////////////
//运行启动
server.eventLoop();
return 0;
}
|
#include "UF08.h"
namespace OFEC {
UF08::UF08(param_map & v) : UF08(v.at("problem name"), v.at("number of variables")) { //param_numDim = 30 is suggested
}
UF08::UF08(const std::string & name, size_t size_var) : problem(name, size_var, 3), UF(name, size_var, 3) {
}
void UF08::initialize() {
std::vector<std::pair<Real, Real>> r;
r.push_back(std::make_pair(0., 1.));
r.push_back(std::make_pair(0., 1.));
for (int i = 2; i < m_num_vars; ++i) {
r.push_back(std::make_pair(-2., 2.));
}
setInitialDomain(r);
setDomain(r);
load_PF();
}
EvalTag UF08::evaluateObjective(Real *x, std::vector<Real> &obj) {
int count1, count2, count3;
Real sum1, sum2, sum3, yj;
sum1 = sum2 = sum3 = 0.0;
count1 = count2 = count3 = 0;
for (int j = 3; j <= m_num_vars; j++) {
yj = x[j - 1] - 2.0*x[1] * sin(2.0*OFEC_PI*x[0] + j * OFEC_PI / m_num_vars);
if (j % 3 == 1)
{
sum1 += yj * yj;
count1++;
}
else if (j % 3 == 2)
{
sum2 += yj * yj;
count2++;
}
else
{
sum3 += yj * yj;
count3++;
}
}
if (count1 == 0)
obj[0] = cos(0.5*OFEC_PI*x[0])*cos(0.5*OFEC_PI*x[1]);
else
obj[0] = cos(0.5*OFEC_PI*x[0])*cos(0.5*OFEC_PI*x[1]) + 2.0*sum1 / (Real)count1;
if (count2 == 0)
obj[1] = cos(0.5*OFEC_PI*x[0])*sin(0.5*OFEC_PI*x[1]);
else
obj[1] = cos(0.5*OFEC_PI*x[0])*sin(0.5*OFEC_PI*x[1]) + 2.0*sum2 / (Real)count2;
if (count3 == 0)
obj[2] = sin(0.5*OFEC_PI*x[0]);
else
obj[2] = sin(0.5*OFEC_PI*x[0]) + 2.0*sum3 / (Real)count3;
return EvalTag::Normal;
}
}
|
// Memory-mapped corpus track
// (c) Ulrich Germann. All rights reserved
// Licensed to NRC under special agreement.
#include <sstream>
#include "ug_mm_ttrack.h"
#include "tpt_pickler.h"
namespace ugdiss
{
using namespace std;
#if 0
template<>
id_type
Ttrack<id_type>::
toID(id_type const& t)
{
return t;
}
#endif
/** @return string representation of sentence /sid/ */
template<>
string
Ttrack<id_type>::
str(id_type sid, TokenIndex const& T) const
{
assert(sid < numTokens());
id_type const* stop = sntEnd(sid);
id_type const* strt = sntStart(sid);
ostringstream buf;
if (strt < stop) buf << T[*strt];
while (++strt < stop)
buf << " " << T[*strt];
return buf.str();
}
template<>
string
Ttrack<id_type>::
str(id_type sid, Vocab const& V) const
{
assert(sid < numTokens());
id_type const* stop = sntEnd(sid);
id_type const* strt = sntStart(sid);
ostringstream buf;
if (strt < stop) buf << V[*strt].str;
while (++strt < stop)
buf << " " << V[*strt].str;
return buf.str();
}
}
|
#include "teca_connected_components.h"
#include "teca_mesh.h"
#include "teca_array_collection.h"
#include "teca_variant_array.h"
#include "teca_metadata.h"
#include "teca_cartesian_mesh.h"
#include "teca_array_attributes.h"
#include <algorithm>
#include <iostream>
#include <deque>
#include <cmath>
#include <sstream>
using std::cerr;
using std::endl;
//#define TECA_DEBUG
namespace {
/// hold i,j,k index triplet
struct id3
{
id3() : i(0), j(0), k(0) {}
id3(unsigned long p, unsigned long q, unsigned long r)
: i(p), j(q), k(r) {}
unsigned long i;
unsigned long j;
unsigned long k;
};
/// 2D/3D connected component labeler
/**
given seed(i0,j0,k0) that's in a component to label, the
current component(current_component), a binary segmentation(segments),
and a set of components(components) of dimensions nx,ny,nz,nxy,
walk the segmentation from the seed labeling it as we go.
when this function returns this component is completely
labeled. this is the 1 pass algorithm.
*/
template <typename segment_t, typename component_t>
void non_periodic_labeler(unsigned long i0, unsigned long j0, unsigned long k0,
component_t current_component, unsigned long nx, unsigned long ny,
unsigned long nz, unsigned long nxy, const segment_t *segments,
component_t *components)
{
std::deque<id3> work_queue;
work_queue.push_back(id3(i0,j0,k0));
while (work_queue.size())
{
id3 ijk = work_queue.back();
work_queue.pop_back();
long s0 = ijk.k > 0 ? -1 : 0;
long s1 = ijk.k < nz-1 ? 1 : 0;
for (long s = s0; s <= s1; ++s)
{
unsigned long ss = ijk.k + s;
unsigned long kk = ss*nxy;
long r0 = ijk.j > 0 ? -1 : 0;
long r1 = ijk.j < ny-1 ? 1 : 0;
for (long r = r0; r <= r1; ++r)
{
unsigned long rr = ijk.j + r;
unsigned long jj = rr*nx;
long q0 = ijk.i > 0 ? -1 : 0;
long q1 = ijk.i < nx-1 ? 1 : 0;
long q_inc = (r || s) ? 1 : 2;
for (long q = q0; q <= q1; q += q_inc)
{
unsigned long qq = ijk.i + q;
unsigned long w = qq + jj + kk;
if (segments[w] && !components[w])
{
components[w] = current_component;
work_queue.push_back(id3(qq,rr,ss));
}
}
}
}
}
}
/// 2D/3D connected component labeler, with periodic boundary in x
/**
given seed(i0,j0,k0) that's in a component to label, the
current component(current_component), a binary segmentation(segments),
and a set of components(components) of dimensions nx,ny,nz,nxy,
walk the segmentation from the seed labeling it as we go.
when this function returns this component is completely
labeled. this is the 1 pass algorithm.
notes:
if we have a periodic bc then neighborhood includes cells -1 to 1, relative
to the current index, else the neighborhood is constrained to 0 to 1, or
-1 to 0.
long s0 = periodic_in_z ? -1 : ijk.k > 0 ? -1 : 0;
long s1 = periodic_in_z ? 1 : ijk.k < nz-1 ? 1 : 0;
then when an index goes out of bounds because the neighborhood crosses the
periodic bc
ss = (ss + nz) % nz;
wraps it around
*/
template <typename segment_t, typename component_t>
void periodic_labeler(unsigned long i0, unsigned long j0, unsigned long k0,
component_t current_component, unsigned long nx, unsigned long ny,
unsigned long nz, unsigned long nxy, int periodic_in_x, int periodic_in_y,
int periodic_in_z, const segment_t *segments,
component_t *components)
{
std::deque<id3> work_queue;
work_queue.push_back(id3(i0,j0,k0));
while (work_queue.size())
{
id3 ijk = work_queue.back();
work_queue.pop_back();
long s0 = periodic_in_z ? -1 : ijk.k > 0 ? -1 : 0;
long s1 = periodic_in_z ? 1 : ijk.k < nz-1 ? 1 : 0;
for (long s = s0; s <= s1; ++s)
{
unsigned long ss = ijk.k + s;
ss = (ss + nz) % nz;
unsigned long kk = ss*nxy;
long r0 = periodic_in_y ? -1 : ijk.j > 0 ? -1 : 0;
long r1 = periodic_in_y ? 1 : ijk.j < ny-1 ? 1 : 0;
for (long r = r0; r <= r1; ++r)
{
unsigned long rr = ijk.j + r;
rr = (rr + ny) % ny;
unsigned long jj = rr*nx;
long q0 = periodic_in_x ? -1 : ijk.i > 0 ? -1 : 0;
long q1 = periodic_in_x ? 1 : ijk.i < nx-1 ? 1 : 0;
long q_inc = (r || s) ? 1 : 2;
for (long q = q0; q <= q1; q += q_inc)
{
long qq = ijk.i + q;
qq = (qq + nx) % nx;
unsigned long w = qq + jj + kk;
if (segments[w] && !components[w])
{
components[w] = current_component;
work_queue.push_back(id3(qq,rr,ss));
}
}
}
}
}
}
/// 2D/3D connected component labeler driver
/**
given a binary segmentation(segments) and buffer(components), both
with dimensions described by the given exent(ext), compute
the labeling.
*/
template <typename segment_t, typename component_t>
void label(unsigned long *ext, int periodic_in_x, int periodic_in_y,
int periodic_in_z, const segment_t *segments, component_t *components,
component_t &max_component)
{
unsigned long nx = ext[1] - ext[0] + 1;
unsigned long ny = ext[3] - ext[2] + 1;
unsigned long nz = ext[5] - ext[4] + 1;
unsigned long nxy = nx*ny;
// initialize the components
component_t current_component = 0;
memset(components, 0, nxy*nz*sizeof(component_t));
// visit each element to see if it is a seed
for (unsigned long k = 0; k < nz; ++k)
{
unsigned long kk = k*nxy;
for (unsigned long j = 0; j < ny; ++j)
{
unsigned long jj = j*nx;
for (unsigned long i = 0; i < nx; ++i)
{
unsigned long q = kk + jj + i;
// found seed, label it
if (segments[q] && !components[q])
{
components[q] = ++current_component;
periodic_labeler(i,j,k, current_component,
nx,ny,nz,nxy, periodic_in_x, periodic_in_y,
periodic_in_z, segments, components);
}
}
}
}
max_component = current_component;
}
};
// --------------------------------------------------------------------------
teca_connected_components::teca_connected_components() :
component_variable(""), segmentation_variable("")
{
this->set_number_of_input_connections(1);
this->set_number_of_output_ports(1);
}
// --------------------------------------------------------------------------
teca_connected_components::~teca_connected_components()
{}
// --------------------------------------------------------------------------
std::string teca_connected_components::get_component_variable(
const teca_metadata &request)
{
std::string component_var = this->component_variable;
if (component_var.empty())
{
if (request.has("component_variable"))
request.get("component_variable", component_var);
else if (this->segmentation_variable.empty())
component_var = "components";
else
component_var = this->segmentation_variable + "_components";
}
return component_var;
}
// --------------------------------------------------------------------------
std::string teca_connected_components::get_segmentation_variable(
const teca_metadata &request)
{
std::string segmentation_var = this->segmentation_variable;
if (segmentation_var.empty() &&
request.has("segmentation_variable"))
request.get("segmentation_variable",
segmentation_var);
return segmentation_var;
}
// --------------------------------------------------------------------------
teca_metadata teca_connected_components::get_output_metadata(
unsigned int port,
const std::vector<teca_metadata> &input_md)
{
#ifdef TECA_DEBUG
cerr << teca_parallel_id()
<< "teca_connected_components::get_output_metadata" << endl;
#endif
(void) port;
std::string component_var = this->component_variable;
if (component_var.empty())
{
if (this->segmentation_variable.empty())
component_var = "components";
else
component_var = this->segmentation_variable + "_components";
}
// tell the downstream about the variable we produce
teca_metadata md = input_md[0];
md.append("variables", component_var);
// add metadata for CF I/O
teca_metadata atts;
md.get("attributes", atts);
std::ostringstream oss;
oss << "the connected components of " << this->segmentation_variable;
teca_array_attributes cc_atts(
teca_variant_array_code<short>::get(),
teca_array_attributes::point_centering,
0, "unitless", component_var,
oss.str().c_str());
atts.set(component_var, (teca_metadata)cc_atts);
md.set("attributes", atts);
return md;
}
// --------------------------------------------------------------------------
std::vector<teca_metadata> teca_connected_components::get_upstream_request(
unsigned int port,
const std::vector<teca_metadata> &input_md,
const teca_metadata &request)
{
#ifdef TECA_DEBUG
cerr << teca_parallel_id()
<< "teca_connected_components::get_upstream_request" << endl;
#endif
(void) port;
(void) input_md;
std::vector<teca_metadata> up_reqs;
// get the name of the array to request
std::string segmentation_var = this->get_segmentation_variable(request);
if (segmentation_var.empty())
{
TECA_ERROR("A segmentation variable was not specified")
return up_reqs;
}
// pass the incoming request upstream, and
// add in what we need
teca_metadata req(request);
std::set<std::string> arrays;
if (req.has("arrays"))
req.get("arrays", arrays);
arrays.insert(segmentation_var);
// remove fromt the request what we generate
std::string component_var = this->get_component_variable(request);
arrays.erase(component_var);
req.set("arrays", arrays);
// send up
up_reqs.push_back(req);
return up_reqs;
}
// --------------------------------------------------------------------------
const_p_teca_dataset teca_connected_components::execute(
unsigned int port,
const std::vector<const_p_teca_dataset> &input_data,
const teca_metadata &request)
{
#ifdef TECA_DEBUG
cerr << teca_parallel_id()
<< "teca_connected_components::execute" << endl;
#endif
(void)port;
// get the input
const_p_teca_cartesian_mesh in_mesh =
std::dynamic_pointer_cast<const teca_cartesian_mesh>(
input_data[0]);
if (!in_mesh)
{
TECA_ERROR("empty input, or not a cartesian_mesh")
return nullptr;
}
// create output and copy metadata, coordinates, etc
p_teca_cartesian_mesh out_mesh = teca_cartesian_mesh::New();
out_mesh->shallow_copy(
std::const_pointer_cast<teca_cartesian_mesh>(in_mesh));
// get the input array
std::string segmentation_var = this->get_segmentation_variable(request);
if (segmentation_var.empty())
{
TECA_ERROR("A segmentation variable was not specified")
return nullptr;
}
const_p_teca_variant_array input_array
= out_mesh->get_point_arrays()->get(segmentation_var);
if (!input_array)
{
TECA_ERROR("The segmentation variable \"" << segmentation_var
<< "\" is not in the input")
return nullptr;
}
// get mesh dimension
unsigned long extent[6];
out_mesh->get_extent(extent);
unsigned long whole_extent[6];
out_mesh->get_whole_extent(whole_extent);
// check for periodic bc.
int periodic_in_x = 0;
out_mesh->get_periodic_in_x(periodic_in_x);
if (periodic_in_x &&
(extent[0] == whole_extent[0]) && (extent[1] == whole_extent[1]))
periodic_in_x = 1;
int periodic_in_y = 0;
out_mesh->get_periodic_in_y(periodic_in_y);
if (periodic_in_y &&
(extent[2] == whole_extent[2]) && (extent[3] == whole_extent[3]))
periodic_in_y = 1;
int periodic_in_z = 0;
out_mesh->get_periodic_in_z(periodic_in_z);
if (periodic_in_z &&
(extent[4] == whole_extent[4]) && (extent[5] == whole_extent[5]))
periodic_in_z = 1;
// do segmentation and component
size_t n_elem = input_array->size();
p_teca_short_array components = teca_short_array::New(n_elem);
short *p_components = components->get();
short max_component = 0;
TEMPLATE_DISPATCH(const teca_variant_array_impl,
input_array.get(),
const NT *p_in = static_cast<TT*>(input_array.get())->get();
::label(extent, periodic_in_x, periodic_in_y,
periodic_in_z, p_in, p_components, max_component);
)
// put components in output
std::string component_var = this->get_component_variable(request);
out_mesh->get_point_arrays()->set(component_var, components);
// put the component ids in the metadata
short num_components = max_component + 1;
p_teca_short_array component_id = teca_short_array::New(num_components);
for (short i = 0; i < num_components; ++i)
component_id->set(i, i);
teca_metadata &omd = out_mesh->get_metadata();
omd.set("component_ids", component_id);
omd.set("number_of_components", num_components);
omd.set("background_id", short(0));
return out_mesh;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.