hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
108
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
104a22b0f1934b314928702965216b76141ca16f
| 2,975
|
cpp
|
C++
|
src/third_party/mozjs-45/extract/js/src/jit/x86/Assembler-x86.cpp
|
SunguckLee/real-mongodb
|
fef0e44fafc6d3709a84101327e7d2f54dd18d88
|
[
"Apache-2.0"
] | 4
|
2018-02-06T01:53:12.000Z
|
2018-02-20T01:47:36.000Z
|
src/third_party/mozjs-45/extract/js/src/jit/x86/Assembler-x86.cpp
|
SunguckLee/real-mongodb
|
fef0e44fafc6d3709a84101327e7d2f54dd18d88
|
[
"Apache-2.0"
] | null | null | null |
src/third_party/mozjs-45/extract/js/src/jit/x86/Assembler-x86.cpp
|
SunguckLee/real-mongodb
|
fef0e44fafc6d3709a84101327e7d2f54dd18d88
|
[
"Apache-2.0"
] | 3
|
2018-02-06T01:53:18.000Z
|
2021-07-28T09:48:15.000Z
|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* vim: set ts=8 sts=4 et sw=4 tw=99:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "jit/x86/Assembler-x86.h"
#include "gc/Marking.h"
using namespace js;
using namespace js::jit;
ABIArgGenerator::ABIArgGenerator()
: stackOffset_(0),
current_()
{}
ABIArg
ABIArgGenerator::next(MIRType type)
{
switch (type) {
case MIRType_Int32:
case MIRType_Pointer:
current_ = ABIArg(stackOffset_);
stackOffset_ += sizeof(uint32_t);
break;
case MIRType_Float32: // Float32 moves are actually double moves
case MIRType_Double:
current_ = ABIArg(stackOffset_);
stackOffset_ += sizeof(uint64_t);
break;
case MIRType_Int32x4:
case MIRType_Float32x4:
// SIMD values aren't passed in or out of C++, so we can make up
// whatever internal ABI we like. visitAsmJSPassArg assumes
// SimdMemoryAlignment.
stackOffset_ = AlignBytes(stackOffset_, SimdMemoryAlignment);
current_ = ABIArg(stackOffset_);
stackOffset_ += Simd128DataSize;
break;
default:
MOZ_CRASH("Unexpected argument type");
}
return current_;
}
const Register ABIArgGenerator::NonArgReturnReg0 = ecx;
const Register ABIArgGenerator::NonArgReturnReg1 = edx;
const Register ABIArgGenerator::NonVolatileReg = ebx;
const Register ABIArgGenerator::NonArg_VolatileReg = eax;
const Register ABIArgGenerator::NonReturn_VolatileReg0 = ecx;
void
Assembler::executableCopy(uint8_t* buffer)
{
AssemblerX86Shared::executableCopy(buffer);
for (size_t i = 0; i < jumps_.length(); i++) {
RelativePatch& rp = jumps_[i];
X86Encoding::SetRel32(buffer + rp.offset, rp.target);
}
}
class RelocationIterator
{
CompactBufferReader reader_;
uint32_t offset_;
public:
RelocationIterator(CompactBufferReader& reader)
: reader_(reader)
{ }
bool read() {
if (!reader_.more())
return false;
offset_ = reader_.readUnsigned();
return true;
}
uint32_t offset() const {
return offset_;
}
};
static inline JitCode*
CodeFromJump(uint8_t* jump)
{
uint8_t* target = (uint8_t*)X86Encoding::GetRel32Target(jump);
return JitCode::FromExecutable(target);
}
void
Assembler::TraceJumpRelocations(JSTracer* trc, JitCode* code, CompactBufferReader& reader)
{
RelocationIterator iter(reader);
while (iter.read()) {
JitCode* child = CodeFromJump(code->raw() + iter.offset());
TraceManuallyBarrieredEdge(trc, &child, "rel32");
MOZ_ASSERT(child == CodeFromJump(code->raw() + iter.offset()));
}
}
| 28.605769
| 91
| 0.646723
|
SunguckLee
|
104a327f80da397e5fb8c252289e938fc8389797
| 8,166
|
cpp
|
C++
|
hardware/test/cpu_instruction_set_test.cpp
|
vinders/pandora_toolbox
|
f32e301ebaa2b281a1ffc3d6d0c556091420520a
|
[
"MIT"
] | 2
|
2020-11-19T03:23:35.000Z
|
2021-02-25T03:34:40.000Z
|
hardware/test/cpu_instruction_set_test.cpp
|
vinders/pandora_toolbox
|
f32e301ebaa2b281a1ffc3d6d0c556091420520a
|
[
"MIT"
] | null | null | null |
hardware/test/cpu_instruction_set_test.cpp
|
vinders/pandora_toolbox
|
f32e301ebaa2b281a1ffc3d6d0c556091420520a
|
[
"MIT"
] | null | null | null |
/*******************************************************************************
MIT License
Copyright (c) 2021 Romain Vinders
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 SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO 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 <gtest/gtest.h>
#include <hardware/cpu_instruction_set.h>
using namespace pandora::hardware;
class CpuInstructionSetTest : public testing::Test {
public:
protected:
//static void SetUpTestCase() {}
//static void TearDownTestCase() {}
void SetUp() override {}
void TearDown() override {}
};
// -- enumerations --
TEST_F(CpuInstructionSetTest, instructionFamilySerializer) {
EXPECT_TRUE(*toString(CpuInstructionFamily::assembly));
EXPECT_TRUE(*toString(CpuInstructionFamily::mmx));
EXPECT_TRUE(*toString(CpuInstructionFamily::sse));
EXPECT_TRUE(*toString(CpuInstructionFamily::avx));
EXPECT_TRUE(*toString(CpuInstructionFamily::neon));
EXPECT_TRUE(CpuInstructionFamily_size() > 0);
CpuInstructionFamily converted = CpuInstructionFamily::assembly;
EXPECT_TRUE(fromString(toString(CpuInstructionFamily::assembly), converted));
EXPECT_EQ(CpuInstructionFamily::assembly, converted);
EXPECT_TRUE(fromString(toString(CpuInstructionFamily::mmx), converted));
EXPECT_EQ(CpuInstructionFamily::mmx, converted);
EXPECT_TRUE(fromString(toString(CpuInstructionFamily::sse), converted));
EXPECT_EQ(CpuInstructionFamily::sse, converted);
EXPECT_TRUE(fromString(toString(CpuInstructionFamily::avx), converted));
EXPECT_EQ(CpuInstructionFamily::avx, converted);
EXPECT_TRUE(fromString(toString(CpuInstructionFamily::neon), converted));
EXPECT_EQ(CpuInstructionFamily::neon, converted);
}
TEST_F(CpuInstructionSetTest, instructionFamilyFlagOps) {
CpuInstructionFamily flag1 = CpuInstructionFamily::sse;
CpuInstructionFamily flag2 = CpuInstructionFamily::sse;
EXPECT_TRUE(flag1 == flag2);
EXPECT_FALSE(flag1 != flag2);
EXPECT_FALSE(flag1 < flag2);
EXPECT_TRUE(flag1 <= flag2);
EXPECT_FALSE(flag1 > flag2);
EXPECT_TRUE(flag1 >= flag2);
flag2 = CpuInstructionFamily::avx;
EXPECT_FALSE(flag1 == flag2);
EXPECT_TRUE(flag1 != flag2);
EXPECT_EQ((static_cast<uint32_t>(flag1) < static_cast<uint32_t>(flag2)), (flag1 < flag2));
EXPECT_EQ((static_cast<uint32_t>(flag1) <= static_cast<uint32_t>(flag2)), (flag1 <= flag2));
EXPECT_EQ((static_cast<uint32_t>(flag1) > static_cast<uint32_t>(flag2)), (flag1 > flag2));
EXPECT_EQ((static_cast<uint32_t>(flag1) >= static_cast<uint32_t>(flag2)), (flag1 >= flag2));
EXPECT_EQ(static_cast<CpuInstructionFamily>(static_cast<uint32_t>(flag1) & static_cast<uint32_t>(flag2)), (flag1 & flag2));
EXPECT_EQ(static_cast<CpuInstructionFamily>(static_cast<uint32_t>(flag1) | static_cast<uint32_t>(flag2)), (flag1 | flag2));
EXPECT_EQ(static_cast<CpuInstructionFamily>(static_cast<uint32_t>(flag1) ^ static_cast<uint32_t>(flag2)), (flag1 ^ flag2));
EXPECT_EQ(static_cast<CpuInstructionFamily>(~static_cast<uint32_t>(flag1)), (~flag1));
EXPECT_EQ((CpuInstructionFamily::sse | CpuInstructionFamily::avx), addFlag(flag1, flag2));
EXPECT_EQ((CpuInstructionFamily::sse | CpuInstructionFamily::avx), flag1);
EXPECT_EQ((CpuInstructionFamily::avx), removeFlag(flag1, CpuInstructionFamily::sse));
EXPECT_EQ((CpuInstructionFamily::avx), flag1);
}
TEST_F(CpuInstructionSetTest, instructionSetSerializer) {
CpuInstructionSet converted = CpuInstructionSet::cpp;
EXPECT_TRUE(*toString(CpuInstructionSet::cpp));
EXPECT_TRUE(fromString(toString(CpuInstructionSet::cpp), converted));
EXPECT_EQ(CpuInstructionSet::cpp, converted);
EXPECT_TRUE(CpuInstructionSet_size() > 0);
for (auto instSet : CpuInstructionSet_x86_values()) {
EXPECT_TRUE(*toString(instSet));
EXPECT_TRUE(fromString(toString(instSet), converted));
EXPECT_EQ(instSet, converted);
}
for (auto instSet : CpuInstructionSet_arm_values()) {
EXPECT_TRUE(*toString(instSet));
EXPECT_TRUE(fromString(toString(instSet), converted));
EXPECT_EQ(instSet, converted);
}
}
TEST_F(CpuInstructionSetTest, instructionSetFlagOps) {
CpuInstructionSet flag1 = CpuInstructionSet::sse;
CpuInstructionSet flag2 = CpuInstructionSet::sse;
EXPECT_TRUE(flag1 == flag2);
EXPECT_FALSE(flag1 != flag2);
EXPECT_FALSE(flag1 < flag2);
EXPECT_TRUE(flag1 <= flag2);
EXPECT_FALSE(flag1 > flag2);
EXPECT_TRUE(flag1 >= flag2);
flag2 = CpuInstructionSet::avx;
EXPECT_FALSE(flag1 == flag2);
EXPECT_TRUE(flag1 != flag2);
EXPECT_EQ((static_cast<uint32_t>(flag1) < static_cast<uint32_t>(flag2)), (flag1 < flag2));
EXPECT_EQ((static_cast<uint32_t>(flag1) <= static_cast<uint32_t>(flag2)), (flag1 <= flag2));
EXPECT_EQ((static_cast<uint32_t>(flag1) > static_cast<uint32_t>(flag2)), (flag1 > flag2));
EXPECT_EQ((static_cast<uint32_t>(flag1) >= static_cast<uint32_t>(flag2)), (flag1 >= flag2));
EXPECT_EQ(static_cast<CpuInstructionSet>(static_cast<uint32_t>(flag1) & static_cast<uint32_t>(flag2)), (flag1 & flag2));
EXPECT_EQ(static_cast<CpuInstructionSet>(static_cast<uint32_t>(flag1) | static_cast<uint32_t>(flag2)), (flag1 | flag2));
EXPECT_EQ(static_cast<CpuInstructionSet>(static_cast<uint32_t>(flag1) ^ static_cast<uint32_t>(flag2)), (flag1 ^ flag2));
EXPECT_EQ(static_cast<CpuInstructionSet>(~static_cast<uint32_t>(flag1)), (~flag1));
EXPECT_EQ((CpuInstructionSet::sse | CpuInstructionSet::avx), addFlag(flag1, flag2));
EXPECT_EQ((CpuInstructionSet::sse | CpuInstructionSet::avx), flag1);
}
TEST_F(CpuInstructionSetTest, instructionSetSubEnumValues) {
EXPECT_TRUE(CpuInstructionSet_size() > 0);
EXPECT_FALSE(CpuInstructionSet_x86_values().empty());
EXPECT_FALSE(CpuInstructionSet_x86_rvalues().empty());
EXPECT_FALSE(CpuInstructionSet_arm_values().empty());
EXPECT_FALSE(CpuInstructionSet_arm_rvalues().empty());
EXPECT_EQ(CpuInstructionSet_x86_values().size(), CpuInstructionSet_x86_rvalues().size());
EXPECT_EQ(CpuInstructionSet_arm_values().size(), CpuInstructionSet_arm_rvalues().size());
EXPECT_TRUE(CpuInstructionSet_x86_values().size() + CpuInstructionSet_arm_values().size() <= CpuInstructionSet_size());
}
// -- builder / extractors --
TEST_F(CpuInstructionSetTest, buildInstructionSet) {
EXPECT_EQ(CpuInstructionSet::sse, toCpuInstructionSet(pandora::system::CpuArchitecture::x86, CpuInstructionFamily::sse, 0x2));
}
TEST_F(CpuInstructionSetTest, extractInstructionFamily) {
EXPECT_EQ(CpuInstructionFamily::assembly, toCpuInstructionFamily(CpuInstructionSet::cpp));
for (auto instSet : CpuInstructionSet_x86_values()) {
EXPECT_TRUE(toCpuInstructionFamily(instSet) == CpuInstructionFamily::mmx
|| toCpuInstructionFamily(instSet) == CpuInstructionFamily::sse
|| toCpuInstructionFamily(instSet) == CpuInstructionFamily::avx);
}
for (auto instSet : CpuInstructionSet_arm_values()) {
EXPECT_EQ(CpuInstructionFamily::neon, toCpuInstructionFamily(instSet));
}
}
TEST_F(CpuInstructionSetTest, extractCpuArch) {
EXPECT_EQ(pandora::system::CpuArchitecture::all, toCpuArchitecture(CpuInstructionSet::cpp));
for (auto instSet : CpuInstructionSet_x86_values()) {
EXPECT_EQ(pandora::system::CpuArchitecture::x86, toCpuArchitecture(instSet));
}
for (auto instSet : CpuInstructionSet_arm_values()) {
EXPECT_EQ(pandora::system::CpuArchitecture::arm, toCpuArchitecture(instSet));
}
}
| 48.035294
| 128
| 0.75447
|
vinders
|
104b88ded841f8ea686069bd5c9fc4a560c0315a
| 1,156
|
cpp
|
C++
|
huawei/binarysearch/binarysearch/main.cpp
|
RainChang/My_ACM_Exercises
|
36872bdcb49cbb3eebde4bb9c7d154d057775b72
|
[
"Apache-2.0"
] | 1
|
2017-03-16T09:38:48.000Z
|
2017-03-16T09:38:48.000Z
|
huawei/binarysearch/binarysearch/main.cpp
|
RainChang/My_ACM_Exercises
|
36872bdcb49cbb3eebde4bb9c7d154d057775b72
|
[
"Apache-2.0"
] | null | null | null |
huawei/binarysearch/binarysearch/main.cpp
|
RainChang/My_ACM_Exercises
|
36872bdcb49cbb3eebde4bb9c7d154d057775b72
|
[
"Apache-2.0"
] | null | null | null |
//
// main.cpp
// binarysearch
//
// Created by Rain on 12/04/2017.
// Copyright © 2017 Rain. All rights reserved.
//
#include <iostream>
#include <vector>
using namespace std;
int getPos(vector<int> A, int n, int val) {
// write code here
vector<int>count(10000,0);
for(int i=0;i<n;i++)
{
count[A[i]]++;
}
int low=0;
int high=n-1;
int result=0,mid=0;
while(low<=high)
{
mid=(high-low)/2+low;
if(A[mid]==val)
{
result=A[mid];
break;
}
if(A[mid]<val)
{
low=mid+1;
}
else{
high=mid-1;
}
}
if(count[A[mid]]==1)
return mid;
else
{
for(int i=mid;i>=0;i--)
{
if(A[i]!=A[mid])
return i;
}
}
return 0;
}
int main(int argc, const char * argv[]) {
// insert code here...
vector<int> A={9,13,21,31};
cout<<getPos(A, 4, 9)<<endl;
return 0;
}
| 20.280702
| 47
| 0.390138
|
RainChang
|
104c4a39144277fd702a673cd41acae54291cf78
| 426
|
cpp
|
C++
|
level1/p02_isPrime/_isPrime.cpp
|
KenNN99/c2019
|
a668b7aa67187c8ef44bdefe5e7813d665084ff3
|
[
"MIT"
] | null | null | null |
level1/p02_isPrime/_isPrime.cpp
|
KenNN99/c2019
|
a668b7aa67187c8ef44bdefe5e7813d665084ff3
|
[
"MIT"
] | null | null | null |
level1/p02_isPrime/_isPrime.cpp
|
KenNN99/c2019
|
a668b7aa67187c8ef44bdefe5e7813d665084ff3
|
[
"MIT"
] | null | null | null |
#include <stdio.h>
#include <stdlib.h>
void NotPrime();
int main()
{
int i;
scanf("%d", &i);
if (i == 1)
{
NotPrime();
}
for (int n = 2; n*n <= i; n++)
{
if (i%n == 0)
{
NotPrime();
return 0;
}
}
printf("This is a Prime.");
system("pause");
return 0;
}
void NotPrime()
{
printf("This is not a Prime!!!");
system("pause");
<<<<<<< HEAD
}
=======
}
>>>>>>> 2b6d759c8e10cfe17d315e90703734d5f6ddb2ff
| 11.833333
| 48
| 0.528169
|
KenNN99
|
104c691c27d95e1ba124b9aec6463c2cd4d733d0
| 430
|
hpp
|
C++
|
NWNXLib/API/Mac/API/Schema.hpp
|
Qowyn/unified
|
149d0b7670a9d156e64555fe0bd7715423db4c2a
|
[
"MIT"
] | null | null | null |
NWNXLib/API/Mac/API/Schema.hpp
|
Qowyn/unified
|
149d0b7670a9d156e64555fe0bd7715423db4c2a
|
[
"MIT"
] | null | null | null |
NWNXLib/API/Mac/API/Schema.hpp
|
Qowyn/unified
|
149d0b7670a9d156e64555fe0bd7715423db4c2a
|
[
"MIT"
] | null | null | null |
#pragma once
#include <cstdint>
#include "Hash.hpp"
namespace NWNXLib {
namespace API {
// Forward class declarations (defined in the source file)
struct Table;
struct Schema
{
int32_t schema_cookie;
int32_t iGeneration;
Hash tblHash;
Hash idxHash;
Hash trigHash;
Hash fkeyHash;
Table* pSeqTab;
uint8_t file_format;
uint8_t enc;
uint16_t schemaFlags;
int32_t cache_size;
};
}
}
| 13.4375
| 58
| 0.686047
|
Qowyn
|
104d77282d146d7a6193a61bb24274bc0bd3ca6b
| 5,540
|
cpp
|
C++
|
test/test_pex.cpp
|
svn2github/libtorrent-rasterbar-RC_0_16
|
c2c8dc24c82816c336d7c45c3ae7a3ab3821077a
|
[
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null |
test/test_pex.cpp
|
svn2github/libtorrent-rasterbar-RC_0_16
|
c2c8dc24c82816c336d7c45c3ae7a3ab3821077a
|
[
"BSL-1.0",
"BSD-3-Clause"
] | 1
|
2019-02-03T09:54:54.000Z
|
2019-02-03T09:54:54.000Z
|
test/test_pex.cpp
|
svn2github/libtorrent-rasterbar-RC_0_16
|
c2c8dc24c82816c336d7c45c3ae7a3ab3821077a
|
[
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null |
/*
Copyright (c) 2008, Arvid Norberg
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 author 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 "libtorrent/session.hpp"
#include "libtorrent/session_settings.hpp"
#include "libtorrent/hasher.hpp"
#include "libtorrent/extensions/ut_pex.hpp"
#include "libtorrent/thread.hpp"
#include <boost/tuple/tuple.hpp>
#include "test.hpp"
#include "setup_transfer.hpp"
#include <iostream>
void test_pex()
{
using namespace libtorrent;
session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48200, 49000), "0.0.0.0", 0);
session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49200, 50000), "0.0.0.0", 0);
session ses3(fingerprint("LT", 0, 1, 0, 0), std::make_pair(50200, 51000), "0.0.0.0", 0);
ses1.add_extension(create_ut_pex_plugin);
ses2.add_extension(create_ut_pex_plugin);
torrent_handle tor1;
torrent_handle tor2;
torrent_handle tor3;
boost::tie(tor1, tor2, tor3) = setup_transfer(&ses1, &ses2, &ses3, true, false, false, "_pex");
int mask = alert::all_categories
& ~(alert::progress_notification
| alert::performance_warning
| alert::stats_notification);
ses1.set_alert_mask(mask);
ses2.set_alert_mask(mask);
ses3.set_alert_mask(mask);
// this is to avoid everything finish from a single peer
// immediately. To make the swarm actually connect all
// three peers before finishing.
session_settings set = ses1.settings();
set.download_rate_limit = 0;
set.upload_rate_limit = 0;
ses1.set_settings(set);
// make the peer connecting the two worthless to transfer
// data, to force peer 3 to connect directly to peer 1 through pex
set = ses2.settings();
set.download_rate_limit = 2000;
set.upload_rate_limit = 2000;
set.ignore_limits_on_local_network = false;
set.rate_limit_utp = true;
ses2.set_settings(set);
set = ses3.settings();
set.download_rate_limit = 0;
set.upload_rate_limit = 0;
ses3.set_settings(set);
#ifndef TORRENT_DISABLE_ENCRYPTION
pe_settings pes;
pes.out_enc_policy = pe_settings::forced;
pes.in_enc_policy = pe_settings::forced;
ses1.set_pe_settings(pes);
ses2.set_pe_settings(pes);
ses3.set_pe_settings(pes);
#endif
test_sleep(100);
// in this test, ses1 is a seed, ses2 is connected to ses1 and ses3.
// the expected behavior is that ses2 will introduce ses1 and ses3 to each other
error_code ec;
tor2.connect_peer(tcp::endpoint(address::from_string("127.0.0.1", ec), ses1.listen_port()));
tor2.connect_peer(tcp::endpoint(address::from_string("127.0.0.1", ec), ses3.listen_port()));
torrent_status st1;
torrent_status st2;
torrent_status st3;
for (int i = 0; i < 15; ++i)
{
print_alerts(ses1, "ses1");
print_alerts(ses2, "ses2");
print_alerts(ses3, "ses3");
st1 = tor1.status();
st2 = tor2.status();
st3 = tor3.status();
std::cerr
<< "\033[33m" << int(st1.upload_payload_rate / 1000.f) << "kB/s "
<< st1.num_peers << ": "
<< "\033[32m" << int(st2.download_payload_rate / 1000.f) << "kB/s "
<< "\033[31m" << int(st2.upload_payload_rate / 1000.f) << "kB/s "
<< "\033[0m" << int(st2.progress * 100) << "% "
<< st2.num_peers << " - "
<< "\033[32m" << int(st3.download_payload_rate / 1000.f) << "kB/s "
<< "\033[31m" << int(st3.upload_payload_rate / 1000.f) << "kB/s "
<< "\033[0m" << int(st3.progress * 100) << "% "
<< st3.num_peers
<< std::endl;
// this is the success condition
if (st1.num_peers == 2 && st2.num_peers == 2 && st3.num_peers == 2)
break;
// this suggests that we failed. If session 3 completes without
// actually connecting to session 1, everything was transferred
// through session 2
if (st3.state == torrent_status::seeding) break;
test_sleep(1000);
}
TEST_CHECK(st1.num_peers == 2 && st2.num_peers == 2 && st3.num_peers == 2)
if (!tor2.status().is_seeding && tor3.status().is_seeding) std::cerr << "done\n";
}
int test_main()
{
using namespace libtorrent;
// in case the previous run was terminated
error_code ec;
remove_all("tmp1_pex", ec);
remove_all("tmp2_pex", ec);
remove_all("tmp3_pex", ec);
test_pex();
remove_all("tmp1_pex", ec);
remove_all("tmp2_pex", ec);
remove_all("tmp3_pex", ec);
return 0;
}
| 32.588235
| 96
| 0.718412
|
svn2github
|
104dd44c38c2bb09a043d6c92870c7c210012d1f
| 29,388
|
cpp
|
C++
|
Engine/source/Alux3D/shotgunprojectile.cpp
|
fr1tz/alux3d
|
249a3b51751ce3184d52879b481f83eabe89e7e3
|
[
"MIT"
] | null | null | null |
Engine/source/Alux3D/shotgunprojectile.cpp
|
fr1tz/alux3d
|
249a3b51751ce3184d52879b481f83eabe89e7e3
|
[
"MIT"
] | null | null | null |
Engine/source/Alux3D/shotgunprojectile.cpp
|
fr1tz/alux3d
|
249a3b51751ce3184d52879b481f83eabe89e7e3
|
[
"MIT"
] | 1
|
2018-10-26T03:18:22.000Z
|
2018-10-26T03:18:22.000Z
|
// Copyright information can be found in the file named COPYING
// located in the root directory of this distribution.
#include "platform/platform.h"
#include "Alux3D/shotgunprojectile.h"
#include "scene/sceneRenderState.h"
#include "scene/sceneManager.h"
#include "lighting/lightInfo.h"
#include "lighting/lightManager.h"
#include "console/consoleTypes.h"
#include "console/typeValidators.h"
#include "core/resourceManager.h"
#include "core/stream/bitStream.h"
#include "T3D/fx/explosion.h"
#include "T3D/shapeBase.h"
#include "ts/tsShapeInstance.h"
#include "sfx/sfxTrack.h"
#include "sfx/sfxSource.h"
#include "sfx/sfxSystem.h"
#include "sfx/sfxTypes.h"
#include "math/mathUtils.h"
#include "math/mathIO.h"
#include "sim/netConnection.h"
#include "T3D/fx/particleEmitter.h"
#include "T3D/fx/splash.h"
#include "T3D/physics/physicsPlugin.h"
#include "T3D/physics/physicsWorld.h"
#include "gfx/gfxTransformSaver.h"
#include "T3D/containerQuery.h"
#include "T3D/decal/decalManager.h"
#include "T3D/decal/decalData.h"
#include "T3D/lightDescription.h"
#include "console/engineAPI.h"
#include "T3D/gameBase/gameConnection.h"
static MRandomLCG sRandom(0x1);
//--------------------------------------------------------------------------
IMPLEMENT_CO_CLIENTEVENT_V1(CreateExplosionEvent);
CreateExplosionEvent::CreateExplosionEvent()
{
//mGuaranteeType = Guaranteed;
mData = NULL;
}
CreateExplosionEvent::CreateExplosionEvent(ExplosionData* data,
const Point3F& p, const Point3F &n)
{
mData = data;
mPos = p;
mNorm = n;
}
void CreateExplosionEvent::pack(NetConnection* conn, BitStream* bstream)
{
if(bstream->writeFlag(mData))
{
bstream->writeRangedU32(mData->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast);
mathWrite(*bstream, mPos);
mathWrite(*bstream, mNorm);
}
}
void CreateExplosionEvent::unpack(NetConnection* conn, BitStream* bstream)
{
if(bstream->readFlag())
{
SimObject* ptr = NULL;
U32 id = bstream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
if(id != 0 && (ptr = Sim::findObject(id)))
mData = dynamic_cast<ExplosionData*>(ptr);
mathRead(*bstream, &mPos);
mathRead(*bstream, &mNorm);
}
}
void CreateExplosionEvent::write(NetConnection* conn, BitStream* bstream)
{
this->pack(conn,bstream);
}
void CreateExplosionEvent::process(NetConnection* conn)
{
if(!mData)
return;
Explosion* pExplosion = new Explosion;
pExplosion->onNewDataBlock(mData, false);
if( pExplosion )
{
MatrixF xform(true);
xform.setPosition(mPos);
pExplosion->setTransform(xform);
pExplosion->setInitialState(mPos, mNorm);
if (pExplosion->registerObject() == false)
{
Con::errorf(ConsoleLogEntry::General, "CreateExplosionEvent(): couldn't register explosion (%s)",
mData->getName() );
delete pExplosion;
pExplosion = NULL;
}
}
}
ConsoleFunction( createExplosionOnClient, bool, 5, 5, "(NetConnection conn, DataBlock datablock, Point3F pos, Point3F norm)")
{
NetConnection* nc = NULL;
if(Sim::findObject(argv[1], nc) == false)
{
Con::warnf(ConsoleLogEntry::General, "createExplosionOnClient: couldn't find object: %s", argv[1]);
return false;
}
ExplosionData* datablock = NULL;
if(Sim::findObject(argv[2], datablock) == false)
{
Con::warnf(ConsoleLogEntry::General, "createExplosionOnClient: couldn't find object: %s", argv[2]);
return false;
}
Point3F pos, norm;
dSscanf(argv[3], "%f %f %f", &pos.x, &pos.y, &pos.z);
dSscanf(argv[4], "%f %f %f", &norm.x, &norm.y, &norm.z);
if(datablock)
{
CreateExplosionEvent* event = new CreateExplosionEvent(datablock,pos,norm);
nc->postNetEvent(event);
}
return true;
}
//--------------------------------------------------------------------------
//
IMPLEMENT_CO_DATABLOCK_V1(ShotgunProjectileData);
ShotgunProjectileData::ShotgunProjectileData()
{
noFake = false;
energyDrain = 0;
numBullets = 10;
bulletDistMode = 0;
range = 1000.0f;
muzzleSpreadRadius = 0.0f;
referenceSpreadRadius = 0.0f;
referenceSpreadDistance = 0.0f;
}
//--------------------------------------------------------------------------
void ShotgunProjectileData::initPersistFields()
{
Parent::initPersistFields();
addField("noFake", TypeBool, Offset(noFake, ShotgunProjectileData));
addField("energyDrain", TypeS32, Offset(energyDrain, ShotgunProjectileData));
addField("numBullets", TypeS32, Offset(numBullets, ShotgunProjectileData));
addField("bulletDistMode", TypeS32, Offset(bulletDistMode, ShotgunProjectileData));
addField("range", TypeF32, Offset(range, ShotgunProjectileData));
addField("muzzleSpreadRadius", TypeF32, Offset(muzzleSpreadRadius, ShotgunProjectileData));
addField("referenceSpreadRadius", TypeF32, Offset(referenceSpreadRadius, ShotgunProjectileData));
addField("referenceSpreadDistance", TypeF32, Offset(referenceSpreadDistance, ShotgunProjectileData));
}
//--------------------------------------------------------------------------
bool ShotgunProjectileData::onAdd()
{
if(!Parent::onAdd())
return false;
return true;
}
bool ShotgunProjectileData::preload(bool server, String &errorStr)
{
if (Parent::preload(server, errorStr) == false)
return false;
return true;
}
//--------------------------------------------------------------------------
void ShotgunProjectileData::packData(BitStream* stream)
{
Parent::packData(stream);
stream->writeFlag(noFake);
stream->write(energyDrain);
stream->write(numBullets);
stream->write(bulletDistMode);
stream->write(range);
stream->write(muzzleSpreadRadius);
stream->write(referenceSpreadRadius);
stream->write(referenceSpreadDistance);
}
void ShotgunProjectileData::unpackData(BitStream* stream)
{
Parent::unpackData(stream);
noFake = stream->readFlag();
stream->read(&energyDrain);
stream->read(&numBullets);
stream->read(&bulletDistMode);
stream->read(&range);
stream->read(&muzzleSpreadRadius);
stream->read(&referenceSpreadRadius);
stream->read(&referenceSpreadDistance);
}
//--------------------------------------------------------------------------
IMPLEMENT_CO_NETOBJECT_V1(ShotgunProjectileTracer);
ShotgunProjectileTracer::ShotgunProjectileTracer(const Point3F* impactPos)
{
mNetFlags.clear();
mNetFlags.set(IsGhost);
if(impactPos)
mImpactPos.set(*impactPos);
mAtImpactPos = false;
}
ShotgunProjectileTracer::~ShotgunProjectileTracer()
{
}
bool ShotgunProjectileTracer::onAdd()
{
AssertFatal(isClientObject(), "ShotgunProjectileTracer on the server? - Someone fucked up!");
if(mDataBlock->muzzleVelocity <= 10)
{
mCurrVelocity = (mImpactPos - mCurrPosition) / mDataBlock->muzzleVelocity;
mCurrVelocity *= TickMs;
}
mInitialPosition = mCurrPosition;
mInitialVelocity = mCurrVelocity;
mCurrDeltaBase = mCurrPosition;
mCurrBackDelta = -mCurrVelocity;
if(!Parent::onAdd())
return false;
return true;
}
bool ShotgunProjectileTracer::onNewDataBlock(GameBaseData* dptr, bool reload)
{
mDataBlock = dynamic_cast<ShotgunProjectileData*>(dptr);
if(!mDataBlock || !Parent::onNewDataBlock(dptr, reload))
return false;
return true;
}
void ShotgunProjectileTracer::processTick(const Move* move)
{
AssertFatal(isClientObject(), "ShotgunProjectileTracer on the server? - Someone fucked up!");
#if 0
mNumTicks++;
#endif
mCurrTick++;
if(mAtImpactPos)
this->deleteObject();
return;
// HACK HACK HACK
if(mDataBlock->muzzleVelocity > 9000)
{
#if 0
this->missedEnemiesCheck(mInitialPosition, mImpactPos);
if(mDataBlock->laserTail != NULL)
{
LaserBeam* beam = new LaserBeam();
beam->setSceneObjectColorization(this->getSceneObjectColorization());
beam->onNewDataBlock(mDataBlock->laserTail);
if(!beam->registerObject())
{
Con::warnf( ConsoleLogEntry::General, "Could not register laserTail for class: %s", mDataBlock->getName() );
delete beam;
}
else
{
beam->setRender(true);
F32 r = sRandom.randF();
Point3F v = (mImpactPos - mInitialPosition)*r;
Point3F vel = v; vel.normalize(); vel *= mDataBlock->muzzleVelocity;
beam->makeDisappear(mInitialPosition, mInitialPosition + v,
vel, mDataBlock->laserTailLen);
}
}
addLaserTrailNode(mInitialPosition, false);
addLaserTrailNode(mImpactPos, false);
for(S32 i = 0; i < NUM_LASERTRAILS; i++)
{
if( mLaserTrailList[i] != NULL )
{
mLaserTrailList[i]->setSceneObjectColorization(this->getSceneObjectColorization());
if(mDataBlock->smoothLaserTrail)
mLaserTrailList[i]->smooth();
if(mDataBlock->laserTrailFlagsList[i] & 1)
mLaserTrailList[i]->smoothReverseDist(mDataBlock->range);
if(mDataBlock->laserTrailFlagsList[i] & 2)
mLaserTrailList[i]->smooth();
if(mDataBlock->laserTrailFlagsList[i] & 4)
mLaserTrailList[i]->smoothDist(2);
}
}
#endif
this->deleteObject();
return;
}
if(mCurrTick >= mDataBlock->lifetime)
{
deleteObject();
return;
}
F32 timeLeft;
RayInfo rInfo;
Point3F oldPosition;
Point3F newPosition;
oldPosition = mCurrPosition;
newPosition = oldPosition + mCurrVelocity * TickSec;
F32 oldDist = (oldPosition-mImpactPos).len();
F32 newDist = (newPosition-mImpactPos).len();
if(newDist > oldDist) // going away from target?
newPosition = mImpactPos;
mCurrDeltaBase = newPosition;
mCurrBackDelta = mCurrPosition - newPosition;
this->emitParticles(oldPosition, newPosition, mCurrVelocity, TickMs);
#if 0
this->missedEnemiesCheck(oldPosition, newPosition);
//emitParticles(mCurrPosition, newPosition, mCurrVelocity, TickMs);
// update laser trail...
if( mEmissionCount == 0 )
{
addLaserTrailNode(mInitialPosition,false);
for( U8 i = 0; i < mNumBouncePoints; i++ )
{
//Con::printf("processTick(): (client) adding bouncePoint %u: %f %f %f",i,mBouncePoint[i].x,mBouncePoint[i].y,mBouncePoint[i].z);
addLaserTrailNode(mBouncePoint[i].pos, false);
createBounceExplosion(mBouncePoint[i].pos, mBouncePoint[i].norm, mBouncePoint[i].decal);
}
}
if( mFxLight != NULL )
mFxLight->setPosition(mCurrDeltaBase);
addLaserTrailNode(newPosition,false);
mEmissionCount++;
#endif
if(newPosition == mImpactPos)
{
this->deleteObject();
return;
}
mCurrPosition = newPosition;
MatrixF xform(true);
xform.setColumn(3, mCurrPosition);
setTransform(xform);
}
void ShotgunProjectileTracer::advanceTime(F32 dt)
{
Parent::advanceTime(dt);
if(mAtImpactPos)
return;
this->simulate(dt);
this->updateSound();
}
void ShotgunProjectileTracer::interpolateTick(F32 delta)
{
// ShotgunProjectileTracers use advanceTime() to
// advance their simulation (instead of ticks).
}
void ShotgunProjectileTracer::simulate(F32 dt)
{
F32 timeLeft;
RayInfo rInfo;
Point3F oldPosition;
Point3F newPosition;
oldPosition = mCurrPosition;
newPosition = oldPosition + mCurrVelocity * dt;
F32 oldDist = (oldPosition-mImpactPos).len();
F32 newDist = (newPosition-mImpactPos).len();
if(newDist > oldDist) // going away from target?
{
newPosition = mImpactPos;
mAtImpactPos = true;
}
mCurrDeltaBase = newPosition;
mCurrBackDelta = mCurrPosition - newPosition;
this->emitParticles(oldPosition, newPosition, mCurrVelocity, dt*1000);
mCurrPosition = newPosition;
Point3F dir = mCurrVelocity;
if(dir.isZero())
dir.set(0,0,1);
else
dir.normalize();
MatrixF xform(true);
xform = MathUtils::createOrientFromDir(dir);
xform.setPosition(mCurrPosition);
setTransform(xform);
}
//--------------------------------------------------------------------------
ShotgunHit::ShotgunHit()
{
object = NULL;
numImpacts = 0;
}
ShotgunHit::ShotgunHit(const ShotgunHit& hit)
{
object = hit.object;
objectPos = hit.objectPos;
numImpacts = hit.numImpacts;
impactCenterVec = hit.impactCenterVec;
impactVecs = hit.impactVecs;
impactNormals = hit.impactNormals;
}
ShotgunHit::~ShotgunHit()
{
}
void ShotgunHit::pack(NetConnection* con, BitStream* stream)
{
// send object id or object pos if the object does not exist anymore
if(stream->writeFlag(object.isNull()))
{
mathWrite(*stream, objectPos);
}
else
{
S32 ghostIndex = -1;
if(stream->writeFlag(object->isClientObject()))
ghostIndex = object->getNetIndex();
else
ghostIndex = con->getGhostIndex(object);
if(stream->writeFlag(ghostIndex != -1))
stream->writeRangedU32(U32(ghostIndex), 0, NetConnection::MaxGhostCount);
else
mathWrite(*stream, objectPos);
}
stream->write(numImpacts);
mathWrite(*stream, impactCenterVec);
for(U32 i = 0; i < numImpacts; i ++)
{
mathWrite(*stream, impactVecs[i]);
mathWrite(*stream, impactNormals[i]);
}
}
void ShotgunHit::unpack(NetConnection* con, BitStream* stream)
{
if(stream->readFlag())
{
mathRead(*stream, &objectPos);
}
else
{
bool onServer = stream->readFlag();
if(stream->readFlag())
{
U32 objectId = stream->readRangedU32(0, NetConnection::MaxGhostCount);
if(onServer)
{
NetObject* pObj = con->resolveObjectFromGhostIndex(objectId);
object = dynamic_cast<SceneObject*>(pObj);
}
else
{
NetObject* pObj = con->resolveGhost(objectId);
object = dynamic_cast<SceneObject*>(pObj);
}
if(object)
objectPos = object->getPosition();
}
else
mathRead(*stream, &objectPos);
}
stream->read(&numImpacts);
mathRead(*stream, &impactCenterVec);
for(U32 i = 0; i < numImpacts; i ++)
{
Point3F impactVec, impactNormal;
mathRead(*stream, &impactVec);
mathRead(*stream, &impactNormal);
impactVecs.push_back(impactVec);
impactNormals.push_back(impactNormal);
}
}
//--------------------------------------------------------------------------
IMPLEMENT_CO_NETOBJECT_V1(ShotgunProjectile);
ShotgunProjectile::ShotgunProjectile(bool onClient, bool findHits)
{
mFindHits = findHits;
mHitsSource = NULL;
mNetFlags.clear();
if(onClient)
{
mNetFlags.set(IsGhost);
}
else
{
mNetFlags.set(Ghostable);
}
}
ShotgunProjectile::~ShotgunProjectile()
{
U32 n = mHits.size();
while(n--)
delete mHits[n];
}
void ShotgunProjectile::onDeleteNotify(SimObject* obj)
{
Parent::onDeleteNotify(obj);
}
//--------------------------------------------------------------------------
void ShotgunProjectile::initPersistFields()
{
Parent::initPersistFields();
}
void ShotgunProjectile::consoleInit()
{
Parent::consoleInit();
}
//--------------------------------------------------------------------------
class ObjectDeleteEvent : public SimEvent
{
public:
void process(SimObject *object)
{
object->deleteObject();
}
};
bool ShotgunProjectile::onAdd()
{
if(!Parent::onAdd())
return false;
setProcessTick(false); // no need to process ticks
if(mFindHits)
{
this->findHits();
if(this->isClientObject())
this->transmitHitsToServer();
}
this->processHits();
if(isClientObject())
{
if(mFindHits)
{
this->deleteObject();
return true;
}
else
{
mHasExploded = true;
}
}
else
{
// Need valid transform for scoping.
Point3F dir = mCurrVelocity; dir.normalize();
MatrixF mat = MathUtils::createOrientFromDir(dir);
mat.setPosition(mCurrPosition);
this->setTransform(mat);
// Delete us after we've had some time to ghost.
Sim::postEvent(this, new ObjectDeleteEvent, Sim::getCurrentTime() + DeleteWaitTime);
}
return true;
}
void ShotgunProjectile::onRemove()
{
Parent::onRemove();
}
bool ShotgunProjectile::onNewDataBlock(GameBaseData* dptr, bool reload)
{
mDataBlock = dynamic_cast<ShotgunProjectileData*>( dptr );
if(!mDataBlock || !Parent::onNewDataBlock(dptr, reload))
return false;
return true;
}
//----------------------------------------------------------------------------
void ShotgunProjectile::processTick(const Move* move)
{
AssertFatal(isClientObject(), "ShotgunProjectile::processTick() being called? - Someone fucked up!");
//mNumTicks++;
//mCurrTick++;
//if(isServerObject() && mCurrTick >= mDataBlock->lifetime)
// deleteObject();
}
void ShotgunProjectile::advanceTime(F32 dt)
{
Parent::advanceTime(dt);
}
void ShotgunProjectile::interpolateTick(F32 delta)
{
Parent::interpolateTick(delta);
}
//--------------------------------------------------------------------------
U32 ShotgunProjectile::packUpdate(NetConnection* con, U32 mask, BitStream* stream)
{
U32 retMask = Parent::packUpdate(con, mask, stream);
// Transmit hits...
// Note: Don't send hits back to their source.
if(stream->writeFlag((mask & GameBase::InitialUpdateMask) && con != mHitsSource))
{
U32 n = mHits.size();
stream->write(n);
while(n--)
mHits[n]->pack(con, stream);
}
return retMask;
}
void ShotgunProjectile::unpackUpdate(NetConnection* con, BitStream* stream)
{
Parent::unpackUpdate(con, stream);
// Read hits?
if(stream->readFlag())
{
U32 n; stream->read(&n);
while(n--)
{
ShotgunHit* newHit = new ShotgunHit();
newHit->unpack(con, stream);
mHits.push_back(newHit);
}
}
}
//--------------------------------------------------------------------------
void ShotgunProjectile::addHits(NetConnection* client, const ShotgunHits& hits)
{
mHitsSource = client;
U32 n = hits.size();
while(n--)
mHits.push_back(new ShotgunHit(*hits[n]));
}
void ShotgunProjectile::findHits()
{
mSourceObject->disableCollision();
Point3F muzzlePoint = mCurrPosition;
Point3F dir = mCurrVelocity; dir.normalize();
MatrixF transform = MathUtils::createOrientFromDir(dir);
Point3F zv; transform.getColumn(2, &zv);
zv.normalize();
Point3F startEdge = muzzlePoint
+ zv * mDataBlock->muzzleSpreadRadius;
Point3F refEdge = muzzlePoint + dir * mDataBlock->referenceSpreadDistance
+ zv * mDataBlock->referenceSpreadRadius;
Point3F vec = refEdge - startEdge; vec.normalize();
Point3F endEdge = startEdge + vec * mDataBlock->range;
Point3F startCenter = muzzlePoint;
Point3F endCenter = muzzlePoint + dir * mDataBlock->range;
//
// collect hits...
//
int totalImpacts = 0;
Vector<Point3F> misses;
if(mDataBlock->bulletDistMode == 0)
{
for(int i=0; i < mDataBlock->numBullets; i++)
{
Point3F startClockVec = startEdge - startCenter;
Point3F endClockVec = endEdge - endCenter;
MatrixF rotmat(EulerF(0, 6.28 * sRandom.randF(), 0));
rotmat.mulV(startClockVec);
rotmat.mulV(endClockVec);
Point3F startVec = startClockVec;
transform.mulV(startVec);
Point3F endVec = endClockVec;
transform.mulV(endVec);
F32 r = sRandom.randF();
Point3F start = startCenter + startVec * r;
Point3F end = endCenter + endVec * r;
RayInfo rInfo;
bool collision = getContainer()->castRay(start, end, csmDynamicCollisionMask | csmStaticCollisionMask, &rInfo);
if(collision)
{
ShotgunHit* hit = NULL;
for(int k=0; k<mHits.size(); k++)
{
if(mHits[k]->object == rInfo.object)
{
hit = mHits[k];
break;
}
}
if(hit == NULL)
{
hit = new ShotgunHit();
hit->object = rInfo.object;
hit->objectPos = hit->object->getPosition();
hit->numImpacts = 0;
mHits.push_back(hit);
}
hit->numImpacts++;
Point3F impactVec = rInfo.point - hit->objectPos;
hit->impactCenterVec += impactVec;
hit->impactCenterVec /= 2;
hit->impactVecs.push_back(impactVec);
hit->impactNormals.push_back(rInfo.normal);
totalImpacts++;
}
else
{
misses.push_back(end);
}
}
}
else
{
int numEdges = 40;
int numSegments = 20;
Point3F startClockVec = startEdge - startCenter;
Point3F endClockVec = endEdge - endCenter;
MatrixF rotmat(EulerF(0, 6.28 / numEdges, 0));
for(int i=0; i < numEdges; i++)
{
rotmat.mulV(startClockVec);
rotmat.mulV(endClockVec);
Point3F startVec = startClockVec;
transform.mulV(startVec);
Point3F endVec = endClockVec;
transform.mulV(endVec);
Point3F startVecSeg = startVec / numSegments;
Point3F endVecSeg = endVec / numSegments;
startVec = startVecSeg;
endVec = endVecSeg;
for(int j = 0; j < numSegments; j++)
{
Point3F start = startCenter + startVec;
Point3F end = endCenter + endVec;
RayInfo rInfo;
bool collision = getContainer()->castRay(start, end, csmDynamicCollisionMask | csmStaticCollisionMask, &rInfo);
if(collision)
{
ShotgunHit* hit = NULL;
for(int k=0; k<mHits.size(); k++)
{
if(mHits[k]->object == rInfo.object)
{
hit = mHits[k];
break;
}
}
if(hit == NULL)
{
hit = new ShotgunHit();
hit->object = rInfo.object;
hit->objectPos = hit->object->getPosition();
hit->numImpacts = 0;
mHits.push_back(hit);
}
hit->numImpacts++;
Point3F impactVec = rInfo.point - hit->objectPos;
hit->impactCenterVec += impactVec;
hit->impactCenterVec /= 2;
hit->impactVecs.push_back(impactVec);
hit->impactNormals.push_back(rInfo.normal);
}
else
{
misses.push_back(end);
}
startVec += startVecSeg;
endVec += endVecSeg;
}
}
// reduce number of impacts per hit according to the number
// of bullets that the shotgun is supposed to fire...
int totalBullets = numEdges * numSegments;
int n = mHits.size();
while(n--)
{
ShotgunHit* hit = mHits[n];
//Con::printf("Number of actual impacts: %i of %i", hit->numImpacts, totalBullets);
hit->numImpacts = F32(hit->numImpacts) / (totalBullets / mDataBlock->numBullets);
hit->numImpacts = mClamp(hit->numImpacts + 1, 1, mDataBlock->numBullets);
totalImpacts += hit->numImpacts;
//Con::printf("Number of bullet impacts: %i of %i", hit->numImpacts, mDataBlock->numBullets);
Vector<Point3F> newImpactVecs, newImpactNormals;
for(int i = 0; i < hit->numImpacts; i++)
{
U32 idx = sRandom.randI(0, hit->impactVecs.size()-1);
newImpactVecs.push_back(hit->impactVecs[idx]);
newImpactNormals.push_back(hit->impactNormals[idx]);
}
hit->impactVecs = newImpactVecs;
hit->impactNormals = newImpactNormals;
}
}
// create a hit for the bullets that didn't hit anything
int numMisses = mDataBlock->numBullets - totalImpacts;
if(numMisses > 0)
{
ShotgunHit* newHit = new ShotgunHit();
newHit->object = NULL;
newHit->objectPos.set(0, 0, 0);
newHit->impactCenterVec.set(0, 0, 0);
newHit->numImpacts = numMisses;
while(numMisses--)
{
Point3F impactVec;
if(mDataBlock->bulletDistMode == 0)
impactVec = misses[numMisses];
else
impactVec = misses[sRandom.randI(0, misses.size()-1)];
newHit->impactCenterVec += impactVec;
newHit->impactCenterVec /= 2;
newHit->impactVecs.push_back(impactVec);
newHit->impactNormals.push_back(Point3F(0, 0, 1));
}
mHits.push_back(newHit);
}
mSourceObject->enableCollision();
}
void ShotgunProjectile::processHits()
{
if(isServerObject())
this->serverProcessHits();
else
this->clientProcessHits();
}
void ShotgunProjectile::serverProcessHits()
{
Point3F muzzlePoint = mCurrPosition;
int n = mHits.size();
while(n--)
{
ShotgunHit* hit = mHits[n];
Point3F objectPos;
if(hit->object.isNull())
objectPos = hit->objectPos;
else
objectPos = hit->object->getPosition();
for(int i = 0; i < hit->numImpacts; i++)
{
Point3F impactVec = hit->impactVecs[i];
Point3F impactNormal = hit->impactNormals[i];
Point3F impactPos = objectPos + impactVec;
#if 0
mTraveledDistance = (impactPos-mCurrPosition).len();
#endif
Parent::onCollision(impactPos, impactNormal, hit->object);
}
}
}
void ShotgunProjectile::clientProcessHits()
{
Point3F muzzlePoint = mCurrPosition;
int n = mHits.size();
while(n--)
{
ShotgunHit* hit = mHits[n];
Point3F objectPos;
if(hit->object.isNull())
objectPos = hit->objectPos;
else
objectPos = hit->object->getPosition();
// eyecandy stuff...
for(int i = 0; i < hit->numImpacts; i++)
{
Point3F impactVec = hit->impactVecs[i];
Point3F impactNormal = hit->impactNormals[i];
Point3F impactPos = objectPos + impactVec;
Point3F velocity = impactPos - muzzlePoint;
F32 dist = velocity.len();
velocity.normalize();
//if(mDataBlock->spread == 0.0 && !hit->object.isNull())
// velocity *= dist / (mDataBlock->lifetime * (F32(TickMs) / 1000.0f));
//else
velocity *= mDataBlock->muzzleVelocity;
ShotgunProjectileTracer* prj = new ShotgunProjectileTracer(&impactPos);
prj->mCurrPosition = muzzlePoint;
prj->mCurrVelocity = velocity;
prj->mSourceObject = mSourceObject;
prj->mSourceObjectSlot = mSourceObjectSlot;
#if 0
prj->setSceneObjectColorization(this->getSceneObjectColorization());
#endif
prj->onNewDataBlock(mDataBlock, false);
if(!prj->registerObject())
{
Con::warnf(ConsoleLogEntry::General, "Could not register shotgun tracer projectile for image: %s", mDataBlock->getName());
delete prj;
prj = NULL;
}
if(hit->object.isNull())
{
#if 0
prj->disableLaserTrail(1);
#endif
continue;
}
SceneObject* sObj = hit->object.operator->();
#if 0
if( sObj->getType() & Projectile::csmDynamicCollisionMask )
{
if( ((ShapeBase*)sObj)->getTeamId() == mTeamId )
{
mExplosionType = Projectile::HitTeammateExplosion;
prj->disableLaserTrail(1);
}
else
{
mExplosionType = Projectile::HitEnemyExplosion;
prj->disableLaserTrail(0);
}
}
else
{
mExplosionType = Projectile::StandardExplosion;
prj->disableLaserTrail(1);
}
#endif
ExplosionData* datablock = mDataBlock->explosion;
#if 0
if( mExplosionType == HitEnemyExplosion && mDataBlock->hitEnemyExplosion != NULL )
datablock = mDataBlock->hitEnemyExplosion;
else if( mExplosionType == HitTeammateExplosion && mDataBlock->hitTeammateExplosion != NULL )
datablock = mDataBlock->hitTeammateExplosion;
#endif
if(datablock != NULL)
{
Explosion* pExplosion = new Explosion;
pExplosion->onNewDataBlock(datablock, false);
Point3F expPos = impactPos + impactNormal*0.1;
MatrixF xform(true);
xform.setPosition(expPos);
pExplosion->setTransform(xform);
pExplosion->setInitialState(expPos, impactNormal);
pExplosion->setCollideType(hit->object->getTypeMask());
if (pExplosion->registerObject() == false)
{
Con::errorf(ConsoleLogEntry::General, "ShotgunProjectile(%s)::explode: couldn't register explosion",
mDataBlock->getName() );
delete pExplosion;
pExplosion = NULL;
}
if(mDataBlock->decal
&& !(sObj->getTypeMask() & Projectile::csmDynamicCollisionMask)
&& (hit->object->getTypeMask() & Projectile::csmStaticCollisionMask))
gDecalManager->addDecal(impactPos, impactNormal, 0.0f, mDataBlock->decal );
}
}
}
}
void ShotgunProjectile::transmitHitsToServer()
{
ShotgunFireEvent* event = new ShotgunFireEvent();
event->datablock = mDataBlock;
event->source = mSourceObject;
event->sourceId = mSourceObject->getNetIndex();
event->sourceSlot = mSourceObjectSlot;
event->muzzlePoint = mCurrPosition;
event->muzzleVector = mCurrVelocity;
U32 n = mHits.size();
while(n--)
event->hits.push_back(new ShotgunHit(*mHits[n]));
GameConnection::getConnectionToServer()->postNetEvent(event);
}
//--------------------------------------------------------------------------
IMPLEMENT_CO_SERVEREVENT_V1(ShotgunFireEvent);
ShotgunFireEvent::ShotgunFireEvent()
{
//mGuaranteeType = NetEvent::Guaranteed; // FIXME
datablock = NULL;
source = NULL;
sourceId = -1;
sourceSlot = -1;
}
ShotgunFireEvent::~ShotgunFireEvent()
{
U32 n = hits.size();
while(n--)
delete hits[n];
}
void ShotgunFireEvent::pack(NetConnection* conn, BitStream* bstream)
{
if(!bstream->writeFlag(datablock))
return;
// datablock
bstream->writeRangedU32(datablock->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast);
// source
if(bstream->writeFlag(sourceId != -1))
bstream->writeRangedU32(U32(sourceId), 0, NetConnection::MaxGhostCount);
// source slot
bstream->writeSignedInt(sourceSlot,4);
// muzzle point & vector
mathWrite(*bstream, muzzlePoint);
mathWrite(*bstream, muzzleVector);
// hits
U32 n = hits.size();
bstream->write(n);
while(n--)
hits[n]->pack(conn, bstream);
}
void ShotgunFireEvent::unpack(NetConnection* conn, BitStream* bstream)
{
if(!bstream->readFlag())
return;
// datablock
SimObject* ptr = NULL;
U32 id = bstream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
if(id != 0 && (ptr = Sim::findObject(id)))
datablock = dynamic_cast<ShotgunProjectileData*>(ptr);
// source
if(bstream->readFlag())
{
sourceId = bstream->readRangedU32(0, NetConnection::MaxGhostCount);
if(sourceId != -1)
{
NetObject* pObj = conn->resolveObjectFromGhostIndex(sourceId);
source = dynamic_cast<ShapeBase*>(pObj);
}
}
// source slot
sourceSlot = bstream->readSignedInt(4);
// muzzle point & vector
mathRead(*bstream, &muzzlePoint);
mathRead(*bstream, &muzzleVector);
// hits
U32 n; bstream->read(&n);
while(n--)
{
ShotgunHit* newHit = new ShotgunHit();
newHit->unpack(conn, bstream);
hits.push_back(newHit);
}
}
void ShotgunFireEvent::write(NetConnection* conn, BitStream* bstream)
{
this->pack(conn, bstream);
}
void ShotgunFireEvent::process(NetConnection* conn)
{
if(!datablock)
return;
if(!source)
return;
source->clientFiredShotgun(
conn,
sourceSlot,
hits,
datablock,
muzzlePoint,
muzzleVector
);
}
| 23.757478
| 132
| 0.671124
|
fr1tz
|
104f273a3cd6bfc289799d35170c6753a04d80e8
| 2,026
|
hpp
|
C++
|
src/ME136/SensorCalibration.hpp
|
lassepe/ME292B-UserCode-Group14
|
a6a637340439ca75b129dc9dd6c560558c22e2ff
|
[
"BSD-3-Clause"
] | null | null | null |
src/ME136/SensorCalibration.hpp
|
lassepe/ME292B-UserCode-Group14
|
a6a637340439ca75b129dc9dd6c560558c22e2ff
|
[
"BSD-3-Clause"
] | null | null | null |
src/ME136/SensorCalibration.hpp
|
lassepe/ME292B-UserCode-Group14
|
a6a637340439ca75b129dc9dd6c560558c22e2ff
|
[
"BSD-3-Clause"
] | null | null | null |
#pragma once
#include "MainLoopTypes.hpp"
#include "Vec3f.hpp"
class SensorCalibration {
public:
/**
* @brief SensorCalibration the constructor for this class. This class wraps away
* the calibration routine. The user can specify over how many iterations he
* wants to calibrate;
* @param measurementsToRecord the number of measurements that should be used
* for calibration.
*/
SensorCalibration(const int measurementsToRecord)
: finished_(false),
numMeasurements_(0),
measurementsToRecord_(measurementsToRecord),
rateGyroOffset_(0, 0, 0) {}
/// getters to savely access the internal state
bool isFinished() const { return finished_; }
int getNumMeasurements() const { return numMeasurements_; }
const Vec3f& getRateGyroOffset() const { return rateGyroOffset_; }
/// reset the calibration state back to 0
void reset() {
rateGyroOffset_ = Vec3f(0, 0, 0);
finished_ = false;
numMeasurements_ = 0;
}
/**
* @brief run runs the calibration routine until we recorded enough
* measurements
* @param in the input of the main loop (containing the measurements)
* @return returns true if this method is still running
*/
bool run(const MainLoopInput& in) {
// check if we still need to collect measurements
if (!finished_) {
// accumulate the rateGyroMeasurements
rateGyroOffset_ =
(rateGyroOffset_ * numMeasurements_ + in.imuMeasurement.rateGyro) /
(numMeasurements_ + 1);
numMeasurements_++;
}
// update the finished state
finished_ = !(numMeasurements_ < measurementsToRecord_);
// return if we are still running
return !finished_;
}
private:
/// true if the calibration phase is fished
bool finished_ = false;
/// the number of measurements recorded
int numMeasurements_;
/// the maximum number of measurements that we need to record
const int measurementsToRecord_ = 500;
/// the calibrated values
Vec3f rateGyroOffset_ = Vec3f(0, 0, 0);
};
| 31.169231
| 83
| 0.698914
|
lassepe
|
10506bb2f6449ce70be8d9cd41f032a088a927da
| 1,129
|
hpp
|
C++
|
include/dtc/cell/cell.hpp
|
tsung-wei-huang/DtCraft
|
80cc9e1195adc0026107814243401a1fc47b5be2
|
[
"MIT"
] | 69
|
2019-03-16T20:13:26.000Z
|
2022-03-24T14:12:19.000Z
|
include/dtc/cell/cell.hpp
|
Tsung-Wei/DtCraft
|
80cc9e1195adc0026107814243401a1fc47b5be2
|
[
"MIT"
] | 12
|
2017-12-02T05:38:30.000Z
|
2019-02-08T11:16:12.000Z
|
include/dtc/cell/cell.hpp
|
Tsung-Wei/DtCraft
|
80cc9e1195adc0026107814243401a1fc47b5be2
|
[
"MIT"
] | 12
|
2019-04-13T16:27:29.000Z
|
2022-01-07T14:42:46.000Z
|
/******************************************************************************
* *
* Copyright (c) 2018, Tsung-Wei Huang, Chun-Xun Lin, and Martin D. F. Wong, *
* University of Illinois at Urbana-Champaign (UIUC), IL, USA. *
* *
* All Rights Reserved. *
* *
* This program is free software. You can redistribute and/or modify *
* it in accordance with the terms of the accompanying license agreement. *
* See LICENSE in the top-level directory for details. *
* *
******************************************************************************/
#ifndef DTC_CELL_CELL_HPP_
#define DTC_CELL_CELL_HPP_
#include <dtc/cell/visitor.hpp>
#include <dtc/cell/operator.hpp>
#include <dtc/cell/feeder/feeder.hpp>
#endif
| 49.086957
| 80
| 0.355182
|
tsung-wei-huang
|
10520c36a175ae4aceb9a500270a9bbd45dfafbb
| 170,457
|
cc
|
C++
|
third_party/blink/renderer/core/html/media/html_media_element.cc
|
DamieFC/chromium
|
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1
|
2020-10-18T02:33:40.000Z
|
2020-10-18T02:33:40.000Z
|
third_party/blink/renderer/core/html/media/html_media_element.cc
|
DamieFC/chromium
|
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 3
|
2021-05-17T16:28:52.000Z
|
2021-05-21T22:42:22.000Z
|
third_party/blink/renderer/core/html/media/html_media_element.cc
|
DamieFC/chromium
|
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
/*
* Copyright (C) 2007, 2008, 2009, 2010, 2011, 2012, 2013 Apple 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:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. 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 "third_party/blink/renderer/core/html/media/html_media_element.h"
#include <algorithm>
#include <limits>
#include "base/auto_reset.h"
#include "base/debug/crash_logging.h"
#include "base/feature_list.h"
#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "base/time/time.h"
#include "media/base/logging_override_if_enabled.h"
#include "media/base/media_content_type.h"
#include "media/base/media_switches.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
#include "third_party/blink/public/common/privacy_budget/identifiability_metric_builder.h"
#include "third_party/blink/public/common/privacy_budget/identifiability_study_settings.h"
#include "third_party/blink/public/common/privacy_budget/identifiable_surface.h"
#include "third_party/blink/public/common/widget/screen_info.h"
#include "third_party/blink/public/mojom/frame/user_activation_notification_type.mojom-shared.h"
#include "third_party/blink/public/platform/modules/mediastream/web_media_stream.h"
#include "third_party/blink/public/platform/modules/remoteplayback/web_remote_playback_client.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/public/platform/web_audio_source_provider.h"
#include "third_party/blink/public/platform/web_content_decryption_module.h"
#include "third_party/blink/public/platform/web_inband_text_track.h"
#include "third_party/blink/public/platform/web_media_player.h"
#include "third_party/blink/public/platform/web_media_player_source.h"
#include "third_party/blink/renderer/bindings/core/v8/script_controller.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h"
#include "third_party/blink/renderer/core/core_initializer.h"
#include "third_party/blink/renderer/core/core_probes_inl.h"
#include "third_party/blink/renderer/core/css/media_list.h"
#include "third_party/blink/renderer/core/css/style_change_reason.h"
#include "third_party/blink/renderer/core/css/style_engine.h"
#include "third_party/blink/renderer/core/dom/attribute.h"
#include "third_party/blink/renderer/core/dom/dom_exception.h"
#include "third_party/blink/renderer/core/dom/dom_node_ids.h"
#include "third_party/blink/renderer/core/dom/element_traversal.h"
#include "third_party/blink/renderer/core/dom/events/event.h"
#include "third_party/blink/renderer/core/dom/events/event_queue.h"
#include "third_party/blink/renderer/core/dom/shadow_root.h"
#include "third_party/blink/renderer/core/events/keyboard_event.h"
#include "third_party/blink/renderer/core/fileapi/url_file_api.h"
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/local_frame_client.h"
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
#include "third_party/blink/renderer/core/frame/picture_in_picture_controller.h"
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/fullscreen/fullscreen.h"
#include "third_party/blink/renderer/core/html/html_source_element.h"
#include "third_party/blink/renderer/core/html/media/audio_output_device_controller.h"
#include "third_party/blink/renderer/core/html/media/autoplay_policy.h"
#include "third_party/blink/renderer/core/html/media/html_media_element_controls_list.h"
#include "third_party/blink/renderer/core/html/media/media_controls.h"
#include "third_party/blink/renderer/core/html/media/media_error.h"
#include "third_party/blink/renderer/core/html/media/media_fragment_uri_parser.h"
#include "third_party/blink/renderer/core/html/media/media_source_attachment.h"
#include "third_party/blink/renderer/core/html/media/media_source_tracer.h"
#include "third_party/blink/renderer/core/html/time_ranges.h"
#include "third_party/blink/renderer/core/html/track/audio_track.h"
#include "third_party/blink/renderer/core/html/track/audio_track_list.h"
#include "third_party/blink/renderer/core/html/track/automatic_track_selection.h"
#include "third_party/blink/renderer/core/html/track/cue_timeline.h"
#include "third_party/blink/renderer/core/html/track/html_track_element.h"
#include "third_party/blink/renderer/core/html/track/inband_text_track.h"
#include "third_party/blink/renderer/core/html/track/loadable_text_track.h"
#include "third_party/blink/renderer/core/html/track/text_track_container.h"
#include "third_party/blink/renderer/core/html/track/text_track_list.h"
#include "third_party/blink/renderer/core/html/track/video_track.h"
#include "third_party/blink/renderer/core/html/track/video_track_list.h"
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
#include "third_party/blink/renderer/core/intersection_observer/intersection_observer.h"
#include "third_party/blink/renderer/core/intersection_observer/intersection_observer_entry.h"
#include "third_party/blink/renderer/core/layout/layout_media.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
#include "third_party/blink/renderer/core/loader/mixed_content_checker.h"
#include "third_party/blink/renderer/core/page/chrome_client.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/paint/compositing/paint_layer_compositor.h"
#include "third_party/blink/renderer/platform/audio/audio_bus.h"
#include "third_party/blink/renderer/platform/audio/audio_source_provider_client.h"
#include "third_party/blink/renderer/platform/bindings/exception_messages.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/bindings/microtask.h"
#include "third_party/blink/renderer/platform/graphics/graphics_layer.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
#include "third_party/blink/renderer/platform/mediastream/media_stream_descriptor.h"
#include "third_party/blink/renderer/platform/network/mime/content_type.h"
#include "third_party/blink/renderer/platform/network/mime/mime_type_from_url.h"
#include "third_party/blink/renderer/platform/network/network_state_notifier.h"
#include "third_party/blink/renderer/platform/network/parsed_content_type.h"
#include "third_party/blink/renderer/platform/privacy_budget/identifiability_digest_helpers.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
#include "third_party/blink/renderer/platform/wtf/math_extras.h"
#ifndef LOG_MEDIA_EVENTS
// Default to not logging events because so many are generated they can
// overwhelm the rest of the logging.
#define LOG_MEDIA_EVENTS 0
#endif
#ifndef LOG_OFFICIAL_TIME_STATUS
// Default to not logging status of official time because it adds a fair amount
// of overhead and logging.
#define LOG_OFFICIAL_TIME_STATUS 0
#endif
namespace blink {
using WeakMediaElementSet = HeapHashSet<WeakMember<HTMLMediaElement>>;
using DocumentElementSetMap =
HeapHashMap<WeakMember<Document>, Member<WeakMediaElementSet>>;
namespace {
// This enum is used to record histograms. Do not reorder.
enum class MediaControlsShow {
kAttribute = 0,
kFullscreen,
kNoScript,
kNotShown,
kDisabledSettings,
kUserExplicitlyEnabled,
kUserExplicitlyDisabled,
kMaxValue = kUserExplicitlyDisabled,
};
// These values are used for the Media.MediaElement.ContentTypeResult histogram.
// Do not reorder.
enum class ContentTypeParseableResult {
kIsSupportedParseable = 0,
kMayBeSupportedParseable,
kIsNotSupportedParseable,
kIsSupportedNotParseable,
kMayBeSupportedNotParseable,
kIsNotSupportedNotParseable,
kMaxValue = kIsNotSupportedNotParseable,
};
// This enum is used to record histograms. Do not reorder.
enum class PlayPromiseRejectReason {
kFailedAutoplayPolicy = 0,
kNoSupportedSources,
kInterruptedByPause,
kInterruptedByLoad,
kMaxValue = kInterruptedByLoad,
};
// The state of the HTMLMediaElement when ProgressEventTimerFired is invoked.
// These values are histogrammed, so please only add values to the end.
enum class ProgressEventTimerState {
// networkState is not NETWORK_LOADING.
kNotLoading,
// MediaShouldBeOpaque() is true.
kMediaShouldBeOpaque,
// "progress" event was scheduled.
kProgress,
// No progress. The "stalled" event was scheduled.
kStalled,
// No progress. No "stalled" event scheduled because a Media Source Attachment
// is used.
kHasMediaSourceAttachment,
// No progress. No "stalled" event scheduled because there was recent
// progress.
kRecentProgress,
// No progress. No "stalled" event scheduled because it was already scheduled.
kStalledEventAlreadyScheduled,
kMaxValue = kStalledEventAlreadyScheduled
};
// Records the state of the HTMLMediaElement when its "progress event" timer
// fires.
// TODO(crbug.com/1143317): Remove once the bug is fixed.
void RecordProgressEventTimerState(ProgressEventTimerState state) {
UMA_HISTOGRAM_ENUMERATION("Media.ProgressEventTimerState", state);
}
static const base::TimeDelta kStalledNotificationInterval =
base::TimeDelta::FromSeconds(3);
void ReportContentTypeResultToUMA(String content_type,
MIMETypeRegistry::SupportsType result) {
ParsedContentType parsed_content_type(content_type);
ContentTypeParseableResult uma_result =
ContentTypeParseableResult::kIsNotSupportedNotParseable;
switch (result) {
case MIMETypeRegistry::kIsSupported:
uma_result = parsed_content_type.IsValid()
? ContentTypeParseableResult::kIsSupportedParseable
: ContentTypeParseableResult::kIsSupportedNotParseable;
break;
case MIMETypeRegistry::kMayBeSupported:
uma_result =
parsed_content_type.IsValid()
? ContentTypeParseableResult::kMayBeSupportedParseable
: ContentTypeParseableResult::kMayBeSupportedNotParseable;
break;
case MIMETypeRegistry::kIsNotSupported:
uma_result =
parsed_content_type.IsValid()
? ContentTypeParseableResult::kIsNotSupportedParseable
: ContentTypeParseableResult::kIsNotSupportedNotParseable;
break;
}
base::UmaHistogramEnumeration("Media.MediaElement.ContentTypeParseable",
uma_result);
}
String UrlForLoggingMedia(const KURL& url) {
static const unsigned kMaximumURLLengthForLogging = 128;
if (url.GetString().length() < kMaximumURLLengthForLogging)
return url.GetString();
return url.GetString().Substring(0, kMaximumURLLengthForLogging) + "...";
}
const char* BoolString(bool val) {
return val ? "true" : "false";
}
DocumentElementSetMap& DocumentToElementSetMap() {
DEFINE_STATIC_LOCAL(Persistent<DocumentElementSetMap>, map,
(MakeGarbageCollected<DocumentElementSetMap>()));
return *map;
}
void AddElementToDocumentMap(HTMLMediaElement* element, Document* document) {
DocumentElementSetMap& map = DocumentToElementSetMap();
WeakMediaElementSet* set = nullptr;
auto it = map.find(document);
if (it == map.end()) {
set = MakeGarbageCollected<WeakMediaElementSet>();
map.insert(document, set);
} else {
set = it->value;
}
set->insert(element);
}
void RemoveElementFromDocumentMap(HTMLMediaElement* element,
Document* document) {
DocumentElementSetMap& map = DocumentToElementSetMap();
auto it = map.find(document);
DCHECK(it != map.end());
WeakMediaElementSet* set = it->value;
set->erase(element);
if (set->IsEmpty())
map.erase(it);
}
String BuildElementErrorMessage(const String& error) {
// Prepend a UA-specific-error code before the first ':', to enable better
// collection and aggregation of UA-specific-error codes from
// MediaError.message by web apps. WebMediaPlayer::GetErrorMessage() should
// similarly conform to this format.
DEFINE_STATIC_LOCAL(const String, element_error_prefix,
("MEDIA_ELEMENT_ERROR: "));
StringBuilder builder;
builder.Append(element_error_prefix);
builder.Append(error);
return builder.ToString();
}
class AudioSourceProviderClientLockScope {
STACK_ALLOCATED();
public:
explicit AudioSourceProviderClientLockScope(HTMLMediaElement& element)
: client_(element.AudioSourceNode()) {
if (client_)
client_->lock();
}
~AudioSourceProviderClientLockScope() {
if (client_)
client_->unlock();
}
private:
AudioSourceProviderClient* client_;
};
const AtomicString& AudioKindToString(
WebMediaPlayerClient::AudioTrackKind kind) {
switch (kind) {
case WebMediaPlayerClient::kAudioTrackKindNone:
return g_empty_atom;
case WebMediaPlayerClient::kAudioTrackKindAlternative:
return AudioTrack::AlternativeKeyword();
case WebMediaPlayerClient::kAudioTrackKindDescriptions:
return AudioTrack::DescriptionsKeyword();
case WebMediaPlayerClient::kAudioTrackKindMain:
return AudioTrack::MainKeyword();
case WebMediaPlayerClient::kAudioTrackKindMainDescriptions:
return AudioTrack::MainDescriptionsKeyword();
case WebMediaPlayerClient::kAudioTrackKindTranslation:
return AudioTrack::TranslationKeyword();
case WebMediaPlayerClient::kAudioTrackKindCommentary:
return AudioTrack::CommentaryKeyword();
}
NOTREACHED();
return g_empty_atom;
}
const AtomicString& VideoKindToString(
WebMediaPlayerClient::VideoTrackKind kind) {
switch (kind) {
case WebMediaPlayerClient::kVideoTrackKindNone:
return g_empty_atom;
case WebMediaPlayerClient::kVideoTrackKindAlternative:
return VideoTrack::AlternativeKeyword();
case WebMediaPlayerClient::kVideoTrackKindCaptions:
return VideoTrack::CaptionsKeyword();
case WebMediaPlayerClient::kVideoTrackKindMain:
return VideoTrack::MainKeyword();
case WebMediaPlayerClient::kVideoTrackKindSign:
return VideoTrack::SignKeyword();
case WebMediaPlayerClient::kVideoTrackKindSubtitles:
return VideoTrack::SubtitlesKeyword();
case WebMediaPlayerClient::kVideoTrackKindCommentary:
return VideoTrack::CommentaryKeyword();
}
NOTREACHED();
return g_empty_atom;
}
bool CanLoadURL(const KURL& url, const String& content_type_str) {
DEFINE_STATIC_LOCAL(const String, codecs, ("codecs"));
ContentType content_type(content_type_str);
String content_mime_type = content_type.GetType().DeprecatedLower();
String content_type_codecs = content_type.Parameter(codecs);
// If the MIME type is missing or is not meaningful, try to figure it out from
// the URL.
if (content_mime_type.IsEmpty() ||
content_mime_type == "application/octet-stream" ||
content_mime_type == "text/plain") {
if (url.ProtocolIsData())
content_mime_type = MimeTypeFromDataURL(url.GetString());
}
// If no MIME type is specified, always attempt to load.
if (content_mime_type.IsEmpty())
return true;
// 4.8.12.3 MIME types - In the absence of a specification to the contrary,
// the MIME type "application/octet-stream" when used with parameters, e.g.
// "application/octet-stream;codecs=theora", is a type that the user agent
// knows it cannot render.
if (content_mime_type != "application/octet-stream" ||
content_type_codecs.IsEmpty()) {
return MIMETypeRegistry::SupportsMediaMIMEType(content_mime_type,
content_type_codecs) !=
MIMETypeRegistry::kIsNotSupported;
}
return false;
}
String PreloadTypeToString(WebMediaPlayer::Preload preload_type) {
switch (preload_type) {
case WebMediaPlayer::kPreloadNone:
return "none";
case WebMediaPlayer::kPreloadMetaData:
return "metadata";
case WebMediaPlayer::kPreloadAuto:
return "auto";
}
NOTREACHED();
return String();
}
void RecordPlayPromiseRejected(PlayPromiseRejectReason reason) {
base::UmaHistogramEnumeration("Media.MediaElement.PlayPromiseReject", reason);
}
void RecordShowControlsUsage(const HTMLMediaElement* element,
MediaControlsShow value) {
if (element->IsHTMLVideoElement()) {
base::UmaHistogramEnumeration("Media.Controls.Show.Video", value);
return;
}
base::UmaHistogramEnumeration("Media.Controls.Show.Audio", value);
}
bool IsValidPlaybackRate(double rate) {
return rate == 0.0 || (rate >= HTMLMediaElement::kMinPlaybackRate &&
rate <= HTMLMediaElement::kMaxPlaybackRate);
}
std::ostream& operator<<(std::ostream& stream,
HTMLMediaElement const& media_element) {
return stream << static_cast<void const*>(&media_element);
}
} // anonymous namespace
// TODO(https://crbug.com/752720): Remove this once C++17 is adopted (and hence,
// `inline constexpr` is supported).
constexpr double HTMLMediaElement::kMinPlaybackRate;
constexpr double HTMLMediaElement::kMaxPlaybackRate;
// static
MIMETypeRegistry::SupportsType HTMLMediaElement::GetSupportsType(
const ContentType& content_type) {
// TODO(https://crbug.com/809912): Finding source of mime parsing crash.
static base::debug::CrashKeyString* content_type_crash_key =
base::debug::AllocateCrashKeyString("media_content_type",
base::debug::CrashKeySize::Size256);
base::debug::ScopedCrashKeyString scoped_crash_key(
content_type_crash_key, content_type.Raw().Utf8().c_str());
String type = content_type.GetType().DeprecatedLower();
// The codecs string is not lower-cased because MP4 values are case sensitive
// per http://tools.ietf.org/html/rfc4281#page-7.
String type_codecs = content_type.Parameter("codecs");
if (type.IsEmpty())
return MIMETypeRegistry::kIsNotSupported;
// 4.8.12.3 MIME types - The canPlayType(type) method must return the empty
// string if type is a type that the user agent knows it cannot render or is
// the type "application/octet-stream"
if (type == "application/octet-stream")
return MIMETypeRegistry::kIsNotSupported;
// Check if stricter parsing of |contentType| will cause problems.
// TODO(jrummell): Either switch to ParsedContentType or remove this UMA,
// depending on the results reported.
MIMETypeRegistry::SupportsType result =
MIMETypeRegistry::SupportsMediaMIMEType(type, type_codecs);
ReportContentTypeResultToUMA(content_type.Raw(), result);
return result;
}
bool HTMLMediaElement::IsHLSURL(const KURL& url) {
// Keep the same logic as in media_codec_util.h.
if (url.IsNull() || url.IsEmpty())
return false;
if (!url.IsLocalFile() && !url.ProtocolIs("http") && !url.ProtocolIs("https"))
return false;
return url.GetString().Contains("m3u8");
}
bool HTMLMediaElement::MediaTracksEnabledInternally() {
return RuntimeEnabledFeatures::AudioVideoTracksEnabled() ||
RuntimeEnabledFeatures::BackgroundVideoTrackOptimizationEnabled();
}
// static
void HTMLMediaElement::OnMediaControlsEnabledChange(Document* document) {
auto it = DocumentToElementSetMap().find(document);
if (it == DocumentToElementSetMap().end())
return;
DCHECK(it->value);
WeakMediaElementSet& elements = *it->value;
for (const auto& element : elements) {
element->UpdateControlsVisibility();
if (element->GetMediaControls())
element->GetMediaControls()->OnMediaControlsEnabledChange();
}
}
HTMLMediaElement::HTMLMediaElement(const QualifiedName& tag_name,
Document& document)
: HTMLElement(tag_name, document),
ExecutionContextLifecycleStateObserver(GetExecutionContext()),
load_timer_(document.GetTaskRunner(TaskType::kInternalMedia),
this,
&HTMLMediaElement::LoadTimerFired),
progress_event_timer_(
document.GetTaskRunner(TaskType::kMediaElementEvent),
this,
&HTMLMediaElement::ProgressEventTimerFired),
playback_progress_timer_(document.GetTaskRunner(TaskType::kInternalMedia),
this,
&HTMLMediaElement::PlaybackProgressTimerFired),
audio_tracks_timer_(document.GetTaskRunner(TaskType::kInternalMedia),
this,
&HTMLMediaElement::AudioTracksTimerFired),
removed_from_document_timer_(
document.GetTaskRunner(TaskType::kInternalMedia),
this,
&HTMLMediaElement::OnRemovedFromDocumentTimerFired),
played_time_ranges_(),
async_event_queue_(
MakeGarbageCollected<EventQueue>(GetExecutionContext(),
TaskType::kMediaElementEvent)),
playback_rate_(1.0f),
default_playback_rate_(1.0f),
network_state_(kNetworkEmpty),
ready_state_(kHaveNothing),
ready_state_maximum_(kHaveNothing),
volume_(1.0f),
last_seek_time_(0),
duration_(std::numeric_limits<double>::quiet_NaN()),
last_time_update_event_media_time_(
std::numeric_limits<double>::quiet_NaN()),
default_playback_start_position_(0),
load_state_(kWaitingForSource),
deferred_load_state_(kNotDeferred),
deferred_load_timer_(document.GetTaskRunner(TaskType::kInternalMedia),
this,
&HTMLMediaElement::DeferredLoadTimerFired),
cc_layer_(nullptr),
official_playback_position_(0),
official_playback_position_needs_update_(true),
fragment_end_time_(std::numeric_limits<double>::quiet_NaN()),
pending_action_flags_(0),
playing_(false),
should_delay_load_event_(false),
have_fired_loaded_data_(false),
can_autoplay_(true),
muted_(false),
paused_(true),
seeking_(false),
paused_by_context_paused_(false),
show_poster_flag_(true),
sent_stalled_event_(false),
ignore_preload_none_(false),
text_tracks_visible_(false),
should_perform_automatic_track_selection_(true),
tracks_are_ready_(true),
processing_preference_change_(false),
was_always_muted_(true),
audio_tracks_(MakeGarbageCollected<AudioTrackList>(*this)),
video_tracks_(MakeGarbageCollected<VideoTrackList>(*this)),
audio_source_node_(nullptr),
autoplay_policy_(MakeGarbageCollected<AutoplayPolicy>(this)),
remote_playback_client_(nullptr),
media_controls_(nullptr),
controls_list_(MakeGarbageCollected<HTMLMediaElementControlsList>(this)),
lazy_load_intersection_observer_(nullptr),
media_player_host_remote_(
MakeGarbageCollected<DisallowNewWrapper<
HeapMojoAssociatedRemote<media::mojom::blink::MediaPlayerHost>>>(
GetExecutionContext())),
media_player_observer_remote_set_(
MakeGarbageCollected<DisallowNewWrapper<HeapMojoAssociatedRemoteSet<
media::mojom::blink::MediaPlayerObserver>>>(
GetExecutionContext())),
media_player_receiver_set_(
MakeGarbageCollected<DisallowNewWrapper<
HeapMojoAssociatedReceiverSet<media::mojom::blink::MediaPlayer,
HTMLMediaElement>>>(
this,
GetExecutionContext())) {
DVLOG(1) << "HTMLMediaElement(" << *this << ")";
LocalFrame* frame = document.GetFrame();
if (frame) {
remote_playback_client_ =
frame->Client()->CreateWebRemotePlaybackClient(*this);
}
SetHasCustomStyleCallbacks();
AddElementToDocumentMap(this, &document);
UseCounter::Count(document, WebFeature::kHTMLMediaElement);
}
HTMLMediaElement::~HTMLMediaElement() {
DVLOG(1) << "~HTMLMediaElement(" << *this << ")";
}
void HTMLMediaElement::Dispose() {
// Destroying the player may cause a resource load to be canceled,
// which could result in LocalDOMWindow::dispatchWindowLoadEvent() being
// called via ResourceFetch::didLoadResource(), then
// FrameLoader::checkCompleted(). But it's guaranteed that the load event
// doesn't get dispatched during the object destruction.
// See Document::isDelayingLoadEvent().
// Also see http://crbug.com/275223 for more details.
ClearMediaPlayerAndAudioSourceProviderClientWithoutLocking();
}
void HTMLMediaElement::DidMoveToNewDocument(Document& old_document) {
DVLOG(3) << "didMoveToNewDocument(" << *this << ")";
load_timer_.MoveToNewTaskRunner(
GetDocument().GetTaskRunner(TaskType::kInternalMedia));
progress_event_timer_.MoveToNewTaskRunner(
GetDocument().GetTaskRunner(TaskType::kInternalMedia));
playback_progress_timer_.MoveToNewTaskRunner(
GetDocument().GetTaskRunner(TaskType::kInternalMedia));
audio_tracks_timer_.MoveToNewTaskRunner(
GetDocument().GetTaskRunner(TaskType::kInternalMedia));
deferred_load_timer_.MoveToNewTaskRunner(
GetDocument().GetTaskRunner(TaskType::kInternalMedia));
removed_from_document_timer_.MoveToNewTaskRunner(
GetDocument().GetTaskRunner(TaskType::kInternalMedia));
autoplay_policy_->DidMoveToNewDocument(old_document);
if (cue_timeline_) {
cue_timeline_->DidMoveToNewDocument(old_document);
}
if (should_delay_load_event_) {
GetDocument().IncrementLoadEventDelayCount();
// Note: Keeping the load event delay count increment on oldDocument that
// was added when should_delay_load_event_ was set so that destruction of
// web_media_player_ can not cause load event dispatching in oldDocument.
} else {
// Incrementing the load event delay count so that destruction of
// web_media_player_ can not cause load event dispatching in oldDocument.
old_document.IncrementLoadEventDelayCount();
}
RemoveElementFromDocumentMap(this, &old_document);
AddElementToDocumentMap(this, &GetDocument());
SetExecutionContext(GetExecutionContext());
// Reset mojo state that is coupled to |old_document|'s execution context.
// NOTE: |media_player_host_remote_| is also coupled to |old_document|'s frame
media_player_host_remote_ = MakeGarbageCollected<DisallowNewWrapper<
HeapMojoAssociatedRemote<media::mojom::blink::MediaPlayerHost>>>(
GetExecutionContext());
media_player_observer_remote_set_->Value().Clear();
media_player_observer_remote_set_ = MakeGarbageCollected<DisallowNewWrapper<
HeapMojoAssociatedRemoteSet<media::mojom::blink::MediaPlayerObserver>>>(
GetExecutionContext());
media_player_receiver_set_->Value().Clear();
media_player_receiver_set_ =
MakeGarbageCollected<DisallowNewWrapper<HeapMojoAssociatedReceiverSet<
media::mojom::blink::MediaPlayer, HTMLMediaElement>>>(
this, GetExecutionContext());
// FIXME: This is a temporary fix to prevent this object from causing the
// MediaPlayer to dereference LocalFrame and FrameLoader pointers from the
// previous document. This restarts the load, as if the src attribute had been
// set. A proper fix would provide a mechanism to allow this object to
// refresh the MediaPlayer's LocalFrame and FrameLoader references on document
// changes so that playback can be resumed properly.
ignore_preload_none_ = false;
InvokeLoadAlgorithm();
// Decrement the load event delay count on oldDocument now that
// web_media_player_ has been destroyed and there is no risk of dispatching a
// load event from within the destructor.
old_document.DecrementLoadEventDelayCount();
HTMLElement::DidMoveToNewDocument(old_document);
}
bool HTMLMediaElement::SupportsFocus() const {
// TODO(https://crbug.com/911882): Depending on result of discussion, remove.
if (ownerDocument()->IsMediaDocument())
return false;
// If no controls specified, we should still be able to focus the element if
// it has tabIndex.
return ShouldShowControls() || HTMLElement::SupportsFocus();
}
bool HTMLMediaElement::IsMouseFocusable() const {
return !IsFullscreen() && SupportsFocus();
}
void HTMLMediaElement::ParseAttribute(
const AttributeModificationParams& params) {
const QualifiedName& name = params.name;
if (name == html_names::kSrcAttr) {
DVLOG(2) << "parseAttribute(" << *this
<< ", kSrcAttr, old=" << params.old_value
<< ", new=" << params.new_value << ")";
// A change to the src attribute can affect intrinsic size, which in turn
// requires a style recalc.
SetNeedsStyleRecalc(kLocalStyleChange,
StyleChangeReasonForTracing::FromAttribute(name));
// Trigger a reload, as long as the 'src' attribute is present.
if (!params.new_value.IsNull()) {
ignore_preload_none_ = false;
InvokeLoadAlgorithm();
}
} else if (name == html_names::kControlsAttr) {
UseCounter::Count(GetDocument(),
WebFeature::kHTMLMediaElementControlsAttribute);
UpdateControlsVisibility();
} else if (name == html_names::kControlslistAttr) {
UseCounter::Count(GetDocument(),
WebFeature::kHTMLMediaElementControlsListAttribute);
if (params.old_value != params.new_value) {
controls_list_->DidUpdateAttributeValue(params.old_value,
params.new_value);
if (GetMediaControls())
GetMediaControls()->OnControlsListUpdated();
}
} else if (name == html_names::kPreloadAttr) {
SetPlayerPreload();
} else if (name == html_names::kDisableremoteplaybackAttr) {
// This attribute is an extension described in the Remote Playback API spec.
// Please see: https://w3c.github.io/remote-playback
UseCounter::Count(GetDocument(),
WebFeature::kDisableRemotePlaybackAttribute);
if (params.old_value != params.new_value) {
if (web_media_player_) {
web_media_player_->RequestRemotePlaybackDisabled(
!params.new_value.IsNull());
}
}
} else if (name == html_names::kLatencyhintAttr &&
RuntimeEnabledFeatures::MediaLatencyHintEnabled()) {
if (GetWebMediaPlayer())
GetWebMediaPlayer()->SetLatencyHint(latencyHint());
} else {
HTMLElement::ParseAttribute(params);
}
}
void HTMLMediaElement::ParserDidSetAttributes() {
HTMLElement::ParserDidSetAttributes();
if (FastHasAttribute(html_names::kMutedAttr))
muted_ = true;
}
// This method is being used as a way to know that cloneNode finished cloning
// attribute as there is no callback notifying about the end of a cloning
// operation. Indeed, it is required per spec to set the muted state based on
// the content attribute when the object is created.
void HTMLMediaElement::CloneNonAttributePropertiesFrom(const Element& other,
CloneChildrenFlag flag) {
HTMLElement::CloneNonAttributePropertiesFrom(other, flag);
if (FastHasAttribute(html_names::kMutedAttr))
muted_ = true;
}
void HTMLMediaElement::FinishParsingChildren() {
HTMLElement::FinishParsingChildren();
if (Traversal<HTMLTrackElement>::FirstChild(*this))
ScheduleTextTrackResourceLoad();
}
bool HTMLMediaElement::LayoutObjectIsNeeded(const ComputedStyle& style) const {
return ShouldShowControls() && HTMLElement::LayoutObjectIsNeeded(style);
}
LayoutObject* HTMLMediaElement::CreateLayoutObject(const ComputedStyle&,
LegacyLayout) {
return new LayoutMedia(this);
}
Node::InsertionNotificationRequest HTMLMediaElement::InsertedInto(
ContainerNode& insertion_point) {
DVLOG(3) << "insertedInto(" << *this << ", " << insertion_point << ")";
HTMLElement::InsertedInto(insertion_point);
if (insertion_point.isConnected()) {
UseCounter::Count(GetDocument(), WebFeature::kHTMLMediaElementInDocument);
if ((!FastGetAttribute(html_names::kSrcAttr).IsEmpty() || src_object_) &&
network_state_ == kNetworkEmpty) {
ignore_preload_none_ = false;
InvokeLoadAlgorithm();
}
}
return kInsertionShouldCallDidNotifySubtreeInsertions;
}
void HTMLMediaElement::DidNotifySubtreeInsertionsToDocument() {
UpdateControlsVisibility();
}
void HTMLMediaElement::RemovedFrom(ContainerNode& insertion_point) {
DVLOG(3) << "removedFrom(" << *this << ", " << insertion_point << ")";
removed_from_document_timer_.StartOneShot(base::TimeDelta(), FROM_HERE);
HTMLElement::RemovedFrom(insertion_point);
}
void HTMLMediaElement::AttachLayoutTree(AttachContext& context) {
HTMLElement::AttachLayoutTree(context);
UpdateLayoutObject();
}
void HTMLMediaElement::DidRecalcStyle(const StyleRecalcChange change) {
if (!change.ReattachLayoutTree())
UpdateLayoutObject();
}
void HTMLMediaElement::ScheduleTextTrackResourceLoad() {
DVLOG(3) << "scheduleTextTrackResourceLoad(" << *this << ")";
pending_action_flags_ |= kLoadTextTrackResource;
if (!load_timer_.IsActive())
load_timer_.StartOneShot(base::TimeDelta(), FROM_HERE);
}
void HTMLMediaElement::ScheduleNextSourceChild() {
// Schedule the timer to try the next <source> element WITHOUT resetting state
// ala invokeLoadAlgorithm.
pending_action_flags_ |= kLoadMediaResource;
load_timer_.StartOneShot(base::TimeDelta(), FROM_HERE);
}
void HTMLMediaElement::ScheduleEvent(const AtomicString& event_name) {
Event* event = Event::CreateCancelable(event_name);
event->SetTarget(this);
ScheduleEvent(event);
}
void HTMLMediaElement::ScheduleEvent(Event* event) {
#if LOG_MEDIA_EVENTS
DVLOG(3) << "ScheduleEvent(" << (void*)this << ")"
<< " - scheduling '" << event->type() << "'";
#endif
async_event_queue_->EnqueueEvent(FROM_HERE, *event);
}
void HTMLMediaElement::LoadTimerFired(TimerBase*) {
if (pending_action_flags_ & kLoadTextTrackResource)
HonorUserPreferencesForAutomaticTextTrackSelection();
if (pending_action_flags_ & kLoadMediaResource) {
if (load_state_ == kLoadingFromSourceElement)
LoadNextSourceChild();
else
LoadInternal();
}
pending_action_flags_ = 0;
}
MediaError* HTMLMediaElement::error() const {
return error_;
}
void HTMLMediaElement::SetSrc(const AtomicString& url) {
setAttribute(html_names::kSrcAttr, url);
}
void HTMLMediaElement::SetSrcObject(MediaStreamDescriptor* src_object) {
DVLOG(1) << "setSrcObject(" << *this << ")";
src_object_ = src_object;
InvokeLoadAlgorithm();
}
HTMLMediaElement::NetworkState HTMLMediaElement::getNetworkState() const {
return network_state_;
}
String HTMLMediaElement::canPlayType(ExecutionContext* context,
const String& mime_type) const {
MIMETypeRegistry::SupportsType support =
GetSupportsType(ContentType(mime_type));
if (IdentifiabilityStudySettings::Get()->ShouldSample(
blink::IdentifiableSurface::Type::kHTMLMediaElement_CanPlayType)) {
blink::IdentifiabilityMetricBuilder(context->UkmSourceID())
.Set(
blink::IdentifiableSurface::FromTypeAndToken(
blink::IdentifiableSurface::Type::kHTMLMediaElement_CanPlayType,
IdentifiabilityBenignStringToken(mime_type)),
static_cast<uint64_t>(support))
.Record(context->UkmRecorder());
}
String can_play;
// 4.8.12.3
switch (support) {
case MIMETypeRegistry::kIsNotSupported:
can_play = g_empty_string;
break;
case MIMETypeRegistry::kMayBeSupported:
can_play = "maybe";
break;
case MIMETypeRegistry::kIsSupported:
can_play = "probably";
break;
}
DVLOG(2) << "canPlayType(" << *this << ", " << mime_type << ") -> "
<< can_play;
return can_play;
}
void HTMLMediaElement::load() {
DVLOG(1) << "load(" << *this << ")";
autoplay_policy_->TryUnlockingUserGesture();
ignore_preload_none_ = true;
InvokeLoadAlgorithm();
}
// Implements the "media element load algorithm" as defined by
// https://html.spec.whatwg.org/multipage/media.html#media-element-load-algorithm
// TODO(srirama.m): Currently ignore_preload_none_ is reset before calling
// invokeLoadAlgorithm() in all places except load(). Move it inside here
// once microtask is implemented for "Await a stable state" step
// in resource selection algorithm.
void HTMLMediaElement::InvokeLoadAlgorithm() {
DVLOG(3) << "invokeLoadAlgorithm(" << *this << ")";
// Perform the cleanup required for the resource load algorithm to run.
StopPeriodicTimers();
load_timer_.Stop();
CancelDeferredLoad();
// FIXME: Figure out appropriate place to reset LoadTextTrackResource if
// necessary and set pending_action_flags_ to 0 here.
pending_action_flags_ &= ~kLoadMediaResource;
sent_stalled_event_ = false;
have_fired_loaded_data_ = false;
autoplay_policy_->StopAutoplayMutedWhenVisible();
// 1 - Abort any already-running instance of the resource selection algorithm
// for this element.
load_state_ = kWaitingForSource;
current_source_node_ = nullptr;
// 2 - Let pending tasks be a list of tasks from the media element's media
// element task source in one of the task queues.
//
// 3 - For each task in the pending tasks that would run resolve pending
// play promises or project pending play prmoises algorithms, immediately
// resolve or reject those promises in the order the corresponding tasks
// were queued.
//
// TODO(mlamouri): the promises are first resolved then rejected but the
// order between resolved/rejected promises isn't respected. This could be
// improved when the same task is used for both cases.
//
// TODO(mlamouri): don't run the callback synchronously if we are not allowed
// to run scripts. It can happen in some edge cases. https://crbug.com/660382
if (play_promise_resolve_task_handle_.IsActive() &&
!ScriptForbiddenScope::IsScriptForbidden()) {
play_promise_resolve_task_handle_.Cancel();
ResolveScheduledPlayPromises();
}
if (play_promise_reject_task_handle_.IsActive() &&
!ScriptForbiddenScope::IsScriptForbidden()) {
play_promise_reject_task_handle_.Cancel();
RejectScheduledPlayPromises();
}
// 4 - Remove each task in pending tasks from its task queue.
CancelPendingEventsAndCallbacks();
// 5 - If the media element's networkState is set to NETWORK_LOADING or
// NETWORK_IDLE, queue a task to fire a simple event named abort at the media
// element.
if (network_state_ == kNetworkLoading || network_state_ == kNetworkIdle)
ScheduleEvent(event_type_names::kAbort);
ResetMediaPlayerAndMediaSource();
// 6 - If the media element's networkState is not set to NETWORK_EMPTY, then
// run these substeps
if (network_state_ != kNetworkEmpty) {
// 4.1 - Queue a task to fire a simple event named emptied at the media
// element.
ScheduleEvent(event_type_names::kEmptied);
// 4.2 - If a fetching process is in progress for the media element, the
// user agent should stop it.
SetNetworkState(kNetworkEmpty);
// 4.4 - Forget the media element's media-resource-specific tracks.
ForgetResourceSpecificTracks();
// 4.5 - If readyState is not set to kHaveNothing, then set it to that
// state.
ready_state_ = kHaveNothing;
ready_state_maximum_ = kHaveNothing;
DCHECK(!paused_ || play_promise_resolvers_.IsEmpty());
// 4.6 - If the paused attribute is false, then run these substeps
if (!paused_) {
// 4.6.1 - Set the paused attribute to true.
paused_ = true;
// 4.6.2 - Take pending play promises and reject pending play promises
// with the result and an "AbortError" DOMException.
RecordPlayPromiseRejected(PlayPromiseRejectReason::kInterruptedByLoad);
RejectPlayPromises(DOMExceptionCode::kAbortError,
"The play() request was interrupted by a new load "
"request. https://goo.gl/LdLk22");
}
// 4.7 - If seeking is true, set it to false.
seeking_ = false;
// 4.8 - Set the current playback position to 0.
// Set the official playback position to 0.
// If this changed the official playback position, then queue a task
// to fire a simple event named timeupdate at the media element.
// 4.9 - Set the initial playback position to 0.
SetOfficialPlaybackPosition(0);
ScheduleTimeupdateEvent(false);
GetCueTimeline().OnReadyStateReset();
// 4.10 - Set the timeline offset to Not-a-Number (NaN).
// 4.11 - Update the duration attribute to Not-a-Number (NaN).
} else if (!paused_) {
// TODO(foolip): There is a proposal to always reset the paused state
// in the media element load algorithm, to avoid a bogus play() promise
// rejection: https://github.com/whatwg/html/issues/869
// This is where that change would have an effect, and it is measured to
// verify the assumption that it's a very rare situation.
UseCounter::Count(GetDocument(),
WebFeature::kHTMLMediaElementLoadNetworkEmptyNotPaused);
}
// 7 - Set the playbackRate attribute to the value of the defaultPlaybackRate
// attribute.
setPlaybackRate(defaultPlaybackRate());
// 8 - Set the error attribute to null and the can autoplay flag to true.
SetError(nullptr);
can_autoplay_ = true;
// 9 - Invoke the media element's resource selection algorithm.
InvokeResourceSelectionAlgorithm();
// 10 - Note: Playback of any previously playing media resource for this
// element stops.
}
void HTMLMediaElement::InvokeResourceSelectionAlgorithm() {
DVLOG(3) << "invokeResourceSelectionAlgorithm(" << *this << ")";
// The resource selection algorithm
// 1 - Set the networkState to NETWORK_NO_SOURCE
SetNetworkState(kNetworkNoSource);
// 2 - Set the element's show poster flag to true
SetShowPosterFlag(true);
played_time_ranges_ = MakeGarbageCollected<TimeRanges>();
// FIXME: Investigate whether these can be moved into network_state_ !=
// kNetworkEmpty block above
// so they are closer to the relevant spec steps.
last_seek_time_ = 0;
duration_ = std::numeric_limits<double>::quiet_NaN();
// 3 - Set the media element's delaying-the-load-event flag to true (this
// delays the load event)
SetShouldDelayLoadEvent(true);
if (GetMediaControls() && isConnected())
GetMediaControls()->Reset();
// 4 - Await a stable state, allowing the task that invoked this algorithm to
// continue
// TODO(srirama.m): Remove scheduleNextSourceChild() and post a microtask
// instead. See http://crbug.com/593289 for more details.
ScheduleNextSourceChild();
}
void HTMLMediaElement::LoadInternal() {
// HTMLMediaElement::textTracksAreReady will need "... the text tracks whose
// mode was not in the disabled state when the element's resource selection
// algorithm last started".
text_tracks_when_resource_selection_began_.clear();
if (text_tracks_) {
for (unsigned i = 0; i < text_tracks_->length(); ++i) {
TextTrack* track = text_tracks_->AnonymousIndexedGetter(i);
if (track->mode() != TextTrack::DisabledKeyword())
text_tracks_when_resource_selection_began_.push_back(track);
}
}
SelectMediaResource();
}
void HTMLMediaElement::SelectMediaResource() {
DVLOG(3) << "selectMediaResource(" << *this << ")";
enum Mode { kObject, kAttribute, kChildren, kNothing };
Mode mode = kNothing;
// 6 - If the media element has an assigned media provider object, then let
// mode be object.
if (src_object_) {
mode = kObject;
} else if (FastHasAttribute(html_names::kSrcAttr)) {
// Otherwise, if the media element has no assigned media provider object
// but has a src attribute, then let mode be attribute.
mode = kAttribute;
} else if (HTMLSourceElement* element =
Traversal<HTMLSourceElement>::FirstChild(*this)) {
// Otherwise, if the media element does not have an assigned media
// provider object and does not have a src attribute, but does have a
// source element child, then let mode be children and let candidate be
// the first such source element child in tree order.
mode = kChildren;
next_child_node_to_consider_ = element;
current_source_node_ = nullptr;
} else {
// Otherwise the media element has no assigned media provider object and
// has neither a src attribute nor a source element child: set the
// networkState to kNetworkEmpty, and abort these steps; the synchronous
// section ends.
// TODO(mlamouri): Setting the network state to empty implies that there
// should be no |web_media_player_|. However, if a previous playback ended
// due to an error, we can get here and still have one. Decide on a plan
// to deal with this properly. https://crbug.com/789737
load_state_ = kWaitingForSource;
SetShouldDelayLoadEvent(false);
if (!GetWebMediaPlayer() || (ready_state_ < kHaveFutureData &&
ready_state_maximum_ < kHaveFutureData)) {
SetNetworkState(kNetworkEmpty);
} else {
UseCounter::Count(GetDocument(),
WebFeature::kHTMLMediaElementEmptyLoadWithFutureData);
}
UpdateLayoutObject();
DVLOG(3) << "selectMediaResource(" << *this << "), nothing to load";
return;
}
// 7 - Set the media element's networkState to NETWORK_LOADING.
SetNetworkState(kNetworkLoading);
// 8 - Queue a task to fire a simple event named loadstart at the media
// element.
ScheduleEvent(event_type_names::kLoadstart);
// 9 - Run the appropriate steps...
switch (mode) {
case kObject:
LoadSourceFromObject();
DVLOG(3) << "selectMediaResource(" << *this
<< ", using 'srcObject' attribute";
break;
case kAttribute:
LoadSourceFromAttribute();
DVLOG(3) << "selectMediaResource(" << *this
<< "), using 'src' attribute url";
break;
case kChildren:
LoadNextSourceChild();
DVLOG(3) << "selectMediaResource(" << *this << "), using source element";
break;
default:
NOTREACHED();
}
}
void HTMLMediaElement::LoadSourceFromObject() {
DCHECK(src_object_);
load_state_ = kLoadingFromSrcObject;
// No type is available when the resource comes from the 'srcObject'
// attribute.
LoadResource(WebMediaPlayerSource(WebMediaStream(src_object_)), String());
}
void HTMLMediaElement::LoadSourceFromAttribute() {
load_state_ = kLoadingFromSrcAttr;
const AtomicString& src_value = FastGetAttribute(html_names::kSrcAttr);
// If the src attribute's value is the empty string ... jump down to the
// failed step below
if (src_value.IsEmpty()) {
DVLOG(3) << "LoadSourceFromAttribute(" << *this << "), empty 'src'";
MediaLoadingFailed(WebMediaPlayer::kNetworkStateFormatError,
BuildElementErrorMessage("Empty src attribute"));
return;
}
KURL media_url = GetDocument().CompleteURL(src_value);
if (!IsSafeToLoadURL(media_url, kComplain)) {
MediaLoadingFailed(
WebMediaPlayer::kNetworkStateFormatError,
BuildElementErrorMessage("Media load rejected by URL safety check"));
return;
}
// No type is available when the url comes from the 'src' attribute so
// MediaPlayer will have to pick a media engine based on the file extension.
LoadResource(WebMediaPlayerSource(WebURL(media_url)), String());
}
void HTMLMediaElement::LoadNextSourceChild() {
String content_type;
KURL media_url = SelectNextSourceChild(&content_type, kComplain);
if (!media_url.IsValid()) {
WaitForSourceChange();
return;
}
// Reset the MediaPlayer and MediaSource if any
ResetMediaPlayerAndMediaSource();
load_state_ = kLoadingFromSourceElement;
LoadResource(WebMediaPlayerSource(WebURL(media_url)), content_type);
}
void HTMLMediaElement::LoadResource(const WebMediaPlayerSource& source,
const String& content_type) {
DCHECK(IsMainThread());
KURL url;
if (source.IsURL()) {
url = source.GetAsURL();
DCHECK(IsSafeToLoadURL(url, kComplain));
DVLOG(3) << "loadResource(" << *this << ", " << UrlForLoggingMedia(url)
<< ", " << content_type << ")";
}
LocalFrame* frame = GetDocument().GetFrame();
if (!frame) {
MediaLoadingFailed(WebMediaPlayer::kNetworkStateFormatError,
BuildElementErrorMessage(
"Resource load failure: document has no frame"));
return;
}
// The resource fetch algorithm
SetNetworkState(kNetworkLoading);
// Set current_src_ *before* changing to the cache url, the fact that we are
// loading from the app cache is an internal detail not exposed through the
// media element API.
current_src_ = url;
// Default this to empty, so that we use |current_src_| unless the player
// provides one later.
current_src_after_redirects_ = KURL();
if (audio_source_node_)
audio_source_node_->OnCurrentSrcChanged(current_src_);
// Update remote playback client with the new src and consider it incompatible
// until proved otherwise.
RemotePlaybackCompatibilityChanged(current_src_, false);
DVLOG(3) << "loadResource(" << *this << ") - current_src_ -> "
<< UrlForLoggingMedia(current_src_);
StartProgressEventTimer();
SetPlayerPreload();
DCHECK(!media_source_attachment_);
DCHECK(!media_source_tracer_);
DCHECK(!error_);
bool attempt_load = true;
media_source_attachment_ =
MediaSourceAttachment::LookupMediaSource(url.GetString());
if (media_source_attachment_) {
bool start_result = false;
media_source_tracer_ =
media_source_attachment_->StartAttachingToMediaElement(this,
&start_result);
if (start_result) {
// If the associated feature is enabled, auto-revoke the MediaSource
// object URL that was used for attachment on successful (start of)
// attachment. This can help reduce memory bloat later if the app does not
// revoke the object URL explicitly and the object URL was the only
// remaining strong reference to an attached HTMLMediaElement+MediaSource
// cycle of objects that could otherwise be garbage-collectable.
if (base::FeatureList::IsEnabled(
media::kRevokeMediaSourceObjectURLOnAttach)) {
URLFileAPI::revokeObjectURL(GetExecutionContext(), url.GetString());
}
} else {
// Forget our reference to the MediaSourceAttachment, so we leave it alone
// while processing remainder of load failure.
media_source_attachment_.reset();
media_source_tracer_ = nullptr;
attempt_load = false;
}
}
bool can_load_resource =
source.IsMediaStream() || CanLoadURL(url, content_type);
if (attempt_load && can_load_resource) {
DCHECK(!GetWebMediaPlayer());
// Conditionally defer the load if effective preload is 'none'.
// Skip this optional deferral for MediaStream sources or any blob URL,
// including MediaSource blob URLs.
if (!source.IsMediaStream() && !url.ProtocolIs("blob") &&
EffectivePreloadType() == WebMediaPlayer::kPreloadNone) {
DVLOG(3) << "loadResource(" << *this
<< ") : Delaying load because preload == 'none'";
DeferLoad();
} else {
StartPlayerLoad();
}
} else {
MediaLoadingFailed(
WebMediaPlayer::kNetworkStateFormatError,
BuildElementErrorMessage(attempt_load
? "Unable to load URL due to content type"
: "Unable to attach MediaSource"));
}
}
void HTMLMediaElement::StartPlayerLoad() {
DCHECK(!web_media_player_);
WebMediaPlayerSource source;
if (src_object_) {
source = WebMediaPlayerSource(WebMediaStream(src_object_));
} else {
// Filter out user:pass as those two URL components aren't
// considered for media resource fetches (including for the CORS
// use-credentials mode.) That behavior aligns with Gecko, with IE
// being more restrictive and not allowing fetches to such URLs.
//
// Spec reference: http://whatwg.org/c/#concept-media-load-resource
//
// FIXME: when the HTML spec switches to specifying resource
// fetches in terms of Fetch (http://fetch.spec.whatwg.org), and
// along with that potentially also specifying a setting for its
// 'authentication flag' to control how user:pass embedded in a
// media resource URL should be treated, then update the handling
// here to match.
KURL request_url = current_src_;
if (!request_url.User().IsEmpty())
request_url.SetUser(String());
if (!request_url.Pass().IsEmpty())
request_url.SetPass(String());
KURL kurl(request_url);
source = WebMediaPlayerSource(WebURL(kurl));
}
LocalFrame* frame = GetDocument().GetFrame();
// TODO(srirama.m): Figure out how frame can be null when
// coming from executeDeferredLoad()
if (!frame) {
MediaLoadingFailed(
WebMediaPlayer::kNetworkStateFormatError,
BuildElementErrorMessage("Player load failure: document has no frame"));
return;
}
web_media_player_ =
frame->Client()->CreateWebMediaPlayer(*this, source, this);
if (!web_media_player_) {
MediaLoadingFailed(WebMediaPlayer::kNetworkStateFormatError,
BuildElementErrorMessage(
"Player load failure: error creating media player"));
return;
}
OnWebMediaPlayerCreated();
// Setup the communication channels between the renderer and browser processes
// via the MediaPlayer and MediaPlayerObserver mojo interfaces.
DCHECK(media_player_receiver_set_->Value().empty());
mojo::PendingAssociatedRemote<media::mojom::blink::MediaPlayer>
media_player_remote;
BindMediaPlayerReceiver(
media_player_remote.InitWithNewEndpointAndPassReceiver());
GetMediaPlayerHostRemote().OnMediaPlayerAdded(
std::move(media_player_remote), AddMediaPlayerObserverAndPassReceiver(),
web_media_player_->GetDelegateId());
if (GetLayoutObject())
GetLayoutObject()->SetShouldDoFullPaintInvalidation();
// Make sure if we create/re-create the WebMediaPlayer that we update our
// wrapper.
audio_source_provider_.Wrap(web_media_player_->GetAudioSourceProvider());
web_media_player_->SetVolume(EffectiveMediaVolume());
web_media_player_->SetPoster(PosterImageURL());
const auto preload = EffectivePreloadType();
web_media_player_->SetPreload(preload);
web_media_player_->RequestRemotePlaybackDisabled(
FastHasAttribute(html_names::kDisableremoteplaybackAttr));
bool is_cache_disabled = false;
probe::IsCacheDisabled(GetDocument().GetExecutionContext(),
&is_cache_disabled);
auto load_timing = web_media_player_->Load(GetLoadType(), source, CorsMode(),
is_cache_disabled);
if (load_timing == WebMediaPlayer::LoadTiming::kDeferred) {
// Deferred media loading is not part of the spec, but intuition is that
// this should not hold up the Window's "load" event (similar to user
// gesture requirements).
SetShouldDelayLoadEvent(false);
}
if (IsFullscreen())
web_media_player_->EnteredFullscreen();
web_media_player_->SetLatencyHint(latencyHint());
web_media_player_->SetPreservesPitch(preservesPitch());
OnLoadStarted();
}
void HTMLMediaElement::SetPlayerPreload() {
if (web_media_player_)
web_media_player_->SetPreload(EffectivePreloadType());
if (LoadIsDeferred() &&
EffectivePreloadType() != WebMediaPlayer::kPreloadNone)
StartDeferredLoad();
}
bool HTMLMediaElement::LoadIsDeferred() const {
return deferred_load_state_ != kNotDeferred;
}
void HTMLMediaElement::DeferLoad() {
// This implements the "optional" step 4 from the resource fetch algorithm
// "If mode is remote".
DCHECK(!deferred_load_timer_.IsActive());
DCHECK_EQ(deferred_load_state_, kNotDeferred);
// 1. Set the networkState to NETWORK_IDLE.
// 2. Queue a task to fire a simple event named suspend at the element.
ChangeNetworkStateFromLoadingToIdle();
// 3. Queue a task to set the element's delaying-the-load-event
// flag to false. This stops delaying the load event.
deferred_load_timer_.StartOneShot(base::TimeDelta(), FROM_HERE);
// 4. Wait for the task to be run.
deferred_load_state_ = kWaitingForStopDelayingLoadEventTask;
// Continued in executeDeferredLoad().
}
void HTMLMediaElement::CancelDeferredLoad() {
deferred_load_timer_.Stop();
deferred_load_state_ = kNotDeferred;
}
void HTMLMediaElement::ExecuteDeferredLoad() {
DCHECK_GE(deferred_load_state_, kWaitingForTrigger);
// resource fetch algorithm step 4 - continued from deferLoad().
// 5. Wait for an implementation-defined event (e.g. the user requesting that
// the media element begin playback). This is assumed to be whatever 'event'
// ended up calling this method.
CancelDeferredLoad();
// 6. Set the element's delaying-the-load-event flag back to true (this
// delays the load event again, in case it hasn't been fired yet).
SetShouldDelayLoadEvent(true);
// 7. Set the networkState to NETWORK_LOADING.
SetNetworkState(kNetworkLoading);
StartProgressEventTimer();
StartPlayerLoad();
}
void HTMLMediaElement::StartDeferredLoad() {
if (deferred_load_state_ == kWaitingForTrigger) {
ExecuteDeferredLoad();
return;
}
if (deferred_load_state_ == kExecuteOnStopDelayingLoadEventTask)
return;
DCHECK_EQ(deferred_load_state_, kWaitingForStopDelayingLoadEventTask);
deferred_load_state_ = kExecuteOnStopDelayingLoadEventTask;
}
void HTMLMediaElement::DeferredLoadTimerFired(TimerBase*) {
SetShouldDelayLoadEvent(false);
if (deferred_load_state_ == kExecuteOnStopDelayingLoadEventTask) {
ExecuteDeferredLoad();
return;
}
DCHECK_EQ(deferred_load_state_, kWaitingForStopDelayingLoadEventTask);
deferred_load_state_ = kWaitingForTrigger;
}
WebMediaPlayer::LoadType HTMLMediaElement::GetLoadType() const {
if (media_source_attachment_)
return WebMediaPlayer::kLoadTypeMediaSource;
if (src_object_)
return WebMediaPlayer::kLoadTypeMediaStream;
return WebMediaPlayer::kLoadTypeURL;
}
bool HTMLMediaElement::PausedWhenVisible() const {
return paused_ && GetWebMediaPlayer() &&
!GetWebMediaPlayer()->PausedWhenHidden();
}
void HTMLMediaElement::DidAudioOutputSinkChanged(
const String& hashed_device_id) {
for (auto& observer : media_player_observer_remote_set_->Value())
observer->OnAudioOutputSinkChanged(hashed_device_id);
}
void HTMLMediaElement::SetMediaPlayerHostForTesting(
mojo::PendingAssociatedRemote<media::mojom::blink::MediaPlayerHost> host) {
media_player_host_remote_->Value().Bind(
std::move(host), GetDocument().GetTaskRunner(TaskType::kInternalMedia));
}
bool HTMLMediaElement::TextTracksAreReady() const {
// 4.8.12.11.1 Text track model
// ...
// The text tracks of a media element are ready if all the text tracks whose
// mode was not in the disabled state when the element's resource selection
// algorithm last started now have a text track readiness state of loaded or
// failed to load.
for (const auto& text_track : text_tracks_when_resource_selection_began_) {
if (text_track->GetReadinessState() == TextTrack::kLoading ||
text_track->GetReadinessState() == TextTrack::kNotLoaded)
return false;
}
return true;
}
void HTMLMediaElement::TextTrackReadyStateChanged(TextTrack* track) {
if (GetWebMediaPlayer() &&
text_tracks_when_resource_selection_began_.Contains(track)) {
if (track->GetReadinessState() != TextTrack::kLoading) {
SetReadyState(
static_cast<ReadyState>(GetWebMediaPlayer()->GetReadyState()));
}
} else {
// The track readiness state might have changed as a result of the user
// clicking the captions button. In this case, a check whether all the
// resources have failed loading should be done in order to hide the CC
// button.
// TODO(mlamouri): when an HTMLTrackElement fails to load, it is not
// propagated to the TextTrack object in a web exposed fashion. We have to
// keep relying on a custom glue to the controls while this is taken care
// of on the web side. See https://crbug.com/669977
if (GetMediaControls() &&
track->GetReadinessState() == TextTrack::kFailedToLoad) {
GetMediaControls()->OnTrackElementFailedToLoad();
}
}
}
void HTMLMediaElement::TextTrackModeChanged(TextTrack* track) {
// Mark this track as "configured" so configureTextTracks won't change the
// mode again.
if (IsA<LoadableTextTrack>(track))
track->SetHasBeenConfigured(true);
if (track->IsRendered()) {
GetDocument().GetStyleEngine().AddTextTrack(track);
} else {
GetDocument().GetStyleEngine().RemoveTextTrack(track);
}
ConfigureTextTrackDisplay();
DCHECK(textTracks()->Contains(track));
textTracks()->ScheduleChangeEvent();
}
void HTMLMediaElement::DisableAutomaticTextTrackSelection() {
should_perform_automatic_track_selection_ = false;
}
bool HTMLMediaElement::IsSafeToLoadURL(const KURL& url,
InvalidURLAction action_if_invalid) {
if (!url.IsValid()) {
DVLOG(3) << "isSafeToLoadURL(" << *this << ", " << UrlForLoggingMedia(url)
<< ") -> FALSE because url is invalid";
return false;
}
LocalDOMWindow* window = GetDocument().domWindow();
if (!window || !window->GetSecurityOrigin()->CanDisplay(url)) {
if (action_if_invalid == kComplain) {
GetDocument().AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>(
mojom::ConsoleMessageSource::kSecurity,
mojom::ConsoleMessageLevel::kError,
"Not allowed to load local resource: " + url.ElidedString()));
}
DVLOG(3) << "isSafeToLoadURL(" << *this << ", " << UrlForLoggingMedia(url)
<< ") -> FALSE rejected by SecurityOrigin";
return false;
}
if (!GetExecutionContext()->GetContentSecurityPolicy()->AllowMediaFromSource(
url)) {
DVLOG(3) << "isSafeToLoadURL(" << *this << ", " << UrlForLoggingMedia(url)
<< ") -> rejected by Content Security Policy";
return false;
}
return true;
}
bool HTMLMediaElement::IsMediaDataCorsSameOrigin() const {
if (!GetWebMediaPlayer())
return true;
const auto network_state = GetWebMediaPlayer()->GetNetworkState();
if (network_state == WebMediaPlayer::kNetworkStateNetworkError)
return false;
return !GetWebMediaPlayer()->WouldTaintOrigin();
}
void HTMLMediaElement::StartProgressEventTimer() {
if (progress_event_timer_.IsActive())
return;
previous_progress_time_ = base::ElapsedTimer();
// 350ms is not magic, it is in the spec!
progress_event_timer_.StartRepeating(base::TimeDelta::FromMilliseconds(350),
FROM_HERE);
}
void HTMLMediaElement::WaitForSourceChange() {
DVLOG(3) << "waitForSourceChange(" << *this << ")";
StopPeriodicTimers();
load_state_ = kWaitingForSource;
// 17 - Waiting: Set the element's networkState attribute to the
// NETWORK_NO_SOURCE value
SetNetworkState(kNetworkNoSource);
// 18 - Set the element's show poster flag to true.
SetShowPosterFlag(true);
// 19 - Set the element's delaying-the-load-event flag to false. This stops
// delaying the load event.
SetShouldDelayLoadEvent(false);
UpdateLayoutObject();
}
void HTMLMediaElement::NoneSupported(const String& input_message) {
DVLOG(3) << "NoneSupported(" << *this << ", message='" << input_message
<< "')";
StopPeriodicTimers();
load_state_ = kWaitingForSource;
current_source_node_ = nullptr;
String empty_string;
const String& message = MediaShouldBeOpaque() ? empty_string : input_message;
// 4.8.12.5
// The dedicated media source failure steps are the following steps:
// 1 - Set the error attribute to a new MediaError object whose code attribute
// is set to MEDIA_ERR_SRC_NOT_SUPPORTED.
SetError(MakeGarbageCollected<MediaError>(
MediaError::kMediaErrSrcNotSupported, message));
// 2 - Forget the media element's media-resource-specific text tracks.
ForgetResourceSpecificTracks();
// 3 - Set the element's networkState attribute to the NETWORK_NO_SOURCE
// value.
SetNetworkState(kNetworkNoSource);
// 4 - Set the element's show poster flag to true.
SetShowPosterFlag(true);
// 5 - Fire a simple event named error at the media element.
ScheduleEvent(event_type_names::kError);
// 6 - Reject pending play promises with NotSupportedError.
ScheduleRejectPlayPromises(DOMExceptionCode::kNotSupportedError);
CloseMediaSource();
// 7 - Set the element's delaying-the-load-event flag to false. This stops
// delaying the load event.
SetShouldDelayLoadEvent(false);
UpdateLayoutObject();
}
void HTMLMediaElement::MediaEngineError(MediaError* err) {
DCHECK_GE(ready_state_, kHaveMetadata);
DVLOG(3) << "mediaEngineError(" << *this << ", "
<< static_cast<int>(err->code()) << ")";
// 1 - The user agent should cancel the fetching process.
StopPeriodicTimers();
load_state_ = kWaitingForSource;
// 2 - Set the error attribute to a new MediaError object whose code attribute
// is set to MEDIA_ERR_NETWORK/MEDIA_ERR_DECODE.
SetError(err);
// 3 - Queue a task to fire a simple event named error at the media element.
ScheduleEvent(event_type_names::kError);
// 4 - Set the element's networkState attribute to the NETWORK_IDLE value.
SetNetworkState(kNetworkIdle);
// 5 - Set the element's delaying-the-load-event flag to false. This stops
// delaying the load event.
SetShouldDelayLoadEvent(false);
// 6 - Abort the overall resource selection algorithm.
current_source_node_ = nullptr;
}
void HTMLMediaElement::CancelPendingEventsAndCallbacks() {
DVLOG(3) << "cancelPendingEventsAndCallbacks(" << *this << ")";
async_event_queue_->CancelAllEvents();
for (HTMLSourceElement* source =
Traversal<HTMLSourceElement>::FirstChild(*this);
source; source = Traversal<HTMLSourceElement>::NextSibling(*source))
source->CancelPendingErrorEvent();
}
void HTMLMediaElement::NetworkStateChanged() {
SetNetworkState(GetWebMediaPlayer()->GetNetworkState());
}
void HTMLMediaElement::MediaLoadingFailed(WebMediaPlayer::NetworkState error,
const String& input_message) {
DVLOG(3) << "MediaLoadingFailed(" << *this << ", " << int{error}
<< ", message='" << input_message << "')";
bool should_be_opaque = MediaShouldBeOpaque();
if (should_be_opaque)
error = WebMediaPlayer::kNetworkStateNetworkError;
String empty_string;
const String& message = should_be_opaque ? empty_string : input_message;
StopPeriodicTimers();
// If we failed while trying to load a <source> element, the movie was never
// parsed, and there are more <source> children, schedule the next one
if (ready_state_ < kHaveMetadata &&
load_state_ == kLoadingFromSourceElement) {
// resource selection algorithm
// Step 9.Otherwise.9 - Failed with elements: Queue a task, using the DOM
// manipulation task source, to fire a simple event named error at the
// candidate element.
if (current_source_node_) {
current_source_node_->ScheduleErrorEvent();
} else {
DVLOG(3) << "mediaLoadingFailed(" << *this
<< ") - error event not sent, <source> was removed";
}
// 9.Otherwise.10 - Asynchronously await a stable state. The synchronous
// section consists of all the remaining steps of this algorithm until the
// algorithm says the synchronous section has ended.
// 9.Otherwise.11 - Forget the media element's media-resource-specific
// tracks.
ForgetResourceSpecificTracks();
if (HavePotentialSourceChild()) {
DVLOG(3) << "mediaLoadingFailed(" << *this
<< ") - scheduling next <source>";
ScheduleNextSourceChild();
} else {
DVLOG(3) << "mediaLoadingFailed(" << *this
<< ") - no more <source> elements, waiting";
WaitForSourceChange();
}
return;
}
if (error == WebMediaPlayer::kNetworkStateNetworkError &&
ready_state_ >= kHaveMetadata) {
MediaEngineError(MakeGarbageCollected<MediaError>(
MediaError::kMediaErrNetwork, message));
} else if (error == WebMediaPlayer::kNetworkStateDecodeError) {
MediaEngineError(
MakeGarbageCollected<MediaError>(MediaError::kMediaErrDecode, message));
} else if ((error == WebMediaPlayer::kNetworkStateFormatError ||
error == WebMediaPlayer::kNetworkStateNetworkError) &&
load_state_ == kLoadingFromSrcAttr) {
if (message.IsEmpty()) {
// Generate a more meaningful error message to differentiate the two types
// of MEDIA_SRC_ERR_NOT_SUPPORTED.
NoneSupported(BuildElementErrorMessage(
error == WebMediaPlayer::kNetworkStateFormatError ? "Format error"
: "Network error"));
} else {
NoneSupported(message);
}
}
UpdateLayoutObject();
}
void HTMLMediaElement::SetNetworkState(WebMediaPlayer::NetworkState state) {
DVLOG(3) << "setNetworkState(" << *this << ", " << static_cast<int>(state)
<< ") - current state is " << int{network_state_};
if (state == WebMediaPlayer::kNetworkStateEmpty) {
// Just update the cached state and leave, we can't do anything.
SetNetworkState(kNetworkEmpty);
return;
}
if (state == WebMediaPlayer::kNetworkStateFormatError ||
state == WebMediaPlayer::kNetworkStateNetworkError ||
state == WebMediaPlayer::kNetworkStateDecodeError) {
MediaLoadingFailed(state, web_media_player_->GetErrorMessage());
return;
}
if (state == WebMediaPlayer::kNetworkStateIdle) {
if (network_state_ > kNetworkIdle) {
ChangeNetworkStateFromLoadingToIdle();
SetShouldDelayLoadEvent(false);
} else {
SetNetworkState(kNetworkIdle);
}
}
if (state == WebMediaPlayer::kNetworkStateLoading) {
if (network_state_ < kNetworkLoading || network_state_ == kNetworkNoSource)
StartProgressEventTimer();
SetNetworkState(kNetworkLoading);
}
if (state == WebMediaPlayer::kNetworkStateLoaded) {
if (network_state_ != kNetworkIdle)
ChangeNetworkStateFromLoadingToIdle();
}
}
void HTMLMediaElement::ChangeNetworkStateFromLoadingToIdle() {
progress_event_timer_.Stop();
if (!MediaShouldBeOpaque()) {
// Schedule one last progress event so we guarantee that at least one is
// fired for files that load very quickly.
if (GetWebMediaPlayer() && GetWebMediaPlayer()->DidLoadingProgress())
ScheduleEvent(event_type_names::kProgress);
ScheduleEvent(event_type_names::kSuspend);
SetNetworkState(kNetworkIdle);
} else {
// TODO(dalecurtis): Replace c-style casts in follow up patch.
DVLOG(1) << __func__ << "(" << *this
<< ") - Deferred network state change to idle for opaque media";
}
}
void HTMLMediaElement::ReadyStateChanged() {
SetReadyState(static_cast<ReadyState>(GetWebMediaPlayer()->GetReadyState()));
}
void HTMLMediaElement::SetReadyState(ReadyState state) {
DVLOG(3) << "setReadyState(" << *this << ", " << int{state}
<< ") - current state is " << int{ready_state_};
// Set "wasPotentiallyPlaying" BEFORE updating ready_state_,
// potentiallyPlaying() uses it
bool was_potentially_playing = PotentiallyPlaying();
ReadyState old_state = ready_state_;
ReadyState new_state = state;
bool tracks_are_ready = TextTracksAreReady();
if (new_state == old_state && tracks_are_ready_ == tracks_are_ready)
return;
tracks_are_ready_ = tracks_are_ready;
if (tracks_are_ready) {
ready_state_ = new_state;
} else {
// If a media file has text tracks the readyState may not progress beyond
// kHaveFutureData until the text tracks are ready, regardless of the state
// of the media file.
if (new_state <= kHaveMetadata)
ready_state_ = new_state;
else
ready_state_ = kHaveCurrentData;
}
// If we're transitioning to / past kHaveMetadata, then cache the final URL.
if (old_state < kHaveMetadata && new_state >= kHaveMetadata &&
web_media_player_) {
current_src_after_redirects_ =
KURL(web_media_player_->GetSrcAfterRedirects());
// Sometimes WebMediaPlayer may load a URL from an in memory cache, which
// skips notification of insecure content. Ensure we always notify the
// MixedContentChecker of what happened, even if the load was skipped.
if (LocalFrame* frame = GetDocument().GetFrame()) {
// We don't care about the return value here. The MixedContentChecker will
// internally notify for insecure content if it needs to regardless of
// what the return value ends up being for this call.
MixedContentChecker::ShouldBlockFetch(
frame,
HasVideo() ? mojom::blink::RequestContextType::VIDEO
: mojom::blink::RequestContextType::AUDIO,
current_src_,
// Strictly speaking, this check is an approximation; a request could
// have have redirected back to its original URL, for example.
// However, the redirect status is only used to prevent leaking
// information cross-origin via CSP reports, so comparing URLs is
// sufficient for that purpose.
current_src_after_redirects_ == current_src_
? ResourceRequest::RedirectStatus::kNoRedirect
: ResourceRequest::RedirectStatus::kFollowedRedirect,
current_src_after_redirects_, /* devtools_id= */ absl::nullopt,
ReportingDisposition::kReport,
GetDocument().Loader()->GetContentSecurityNotifier());
}
// Prior to kHaveMetadata |network_state_| may be inaccurate to avoid side
// channel leaks. This be a no-op if nothing has changed.
NetworkStateChanged();
}
if (new_state > ready_state_maximum_)
ready_state_maximum_ = new_state;
if (network_state_ == kNetworkEmpty)
return;
if (seeking_) {
// 4.8.12.9, step 9 note: If the media element was potentially playing
// immediately before it started seeking, but seeking caused its readyState
// attribute to change to a value lower than kHaveFutureData, then a waiting
// will be fired at the element.
if (was_potentially_playing && ready_state_ < kHaveFutureData)
ScheduleEvent(event_type_names::kWaiting);
// 4.8.12.9 steps 12-14
if (ready_state_ >= kHaveCurrentData)
FinishSeek();
} else {
if (was_potentially_playing && ready_state_ < kHaveFutureData) {
// Force an update to official playback position. Automatic updates from
// currentPlaybackPosition() will be blocked while ready_state_ remains
// < kHaveFutureData. This blocking is desired after 'waiting' has been
// fired, but its good to update it one final time to accurately reflect
// media time at the moment we ran out of data to play.
SetOfficialPlaybackPosition(CurrentPlaybackPosition());
// 4.8.12.8
ScheduleTimeupdateEvent(false);
ScheduleEvent(event_type_names::kWaiting);
}
}
// Once enough of the media data has been fetched to determine the duration of
// the media resource, its dimensions, and other metadata...
if (ready_state_ >= kHaveMetadata && old_state < kHaveMetadata) {
CreatePlaceholderTracksIfNecessary();
MediaFragmentURIParser fragment_parser(current_src_);
fragment_end_time_ = fragment_parser.EndTime();
// Set the current playback position and the official playback position to
// the earliest possible position.
SetOfficialPlaybackPosition(EarliestPossiblePosition());
duration_ = web_media_player_->Duration();
ScheduleEvent(event_type_names::kDurationchange);
if (IsHTMLVideoElement())
ScheduleEvent(event_type_names::kResize);
ScheduleEvent(event_type_names::kLoadedmetadata);
bool jumped = false;
if (default_playback_start_position_ > 0) {
Seek(default_playback_start_position_);
jumped = true;
}
default_playback_start_position_ = 0;
double initial_playback_position = fragment_parser.StartTime();
if (std::isnan(initial_playback_position))
initial_playback_position = 0;
if (!jumped && initial_playback_position > 0) {
UseCounter::Count(GetDocument(),
WebFeature::kHTMLMediaElementSeekToFragmentStart);
Seek(initial_playback_position);
jumped = true;
}
web_media_player_->SetAutoplayInitiated(true);
UpdateLayoutObject();
}
bool is_potentially_playing = PotentiallyPlaying();
if (ready_state_ >= kHaveCurrentData && old_state < kHaveCurrentData &&
!have_fired_loaded_data_) {
// Force an update to official playback position to catch non-zero start
// times that were not known at kHaveMetadata, but are known now that the
// first packets have been demuxed.
SetOfficialPlaybackPosition(CurrentPlaybackPosition());
have_fired_loaded_data_ = true;
ScheduleEvent(event_type_names::kLoadeddata);
SetShouldDelayLoadEvent(false);
OnLoadFinished();
}
if (ready_state_ == kHaveFutureData && old_state <= kHaveCurrentData &&
tracks_are_ready) {
ScheduleEvent(event_type_names::kCanplay);
if (is_potentially_playing)
ScheduleNotifyPlaying();
}
if (ready_state_ == kHaveEnoughData && old_state < kHaveEnoughData &&
tracks_are_ready) {
if (old_state <= kHaveCurrentData) {
ScheduleEvent(event_type_names::kCanplay);
if (is_potentially_playing)
ScheduleNotifyPlaying();
}
if (autoplay_policy_->RequestAutoplayByAttribute()) {
paused_ = false;
SetShowPosterFlag(false);
GetCueTimeline().InvokeTimeMarchesOn();
ScheduleEvent(event_type_names::kPlay);
ScheduleNotifyPlaying();
can_autoplay_ = false;
}
ScheduleEvent(event_type_names::kCanplaythrough);
}
UpdatePlayState();
}
void HTMLMediaElement::SetShowPosterFlag(bool value) {
DVLOG(3) << "SetShowPosterFlag(" << *this << ", " << value
<< ") - current state is " << show_poster_flag_;
if (value == show_poster_flag_)
return;
show_poster_flag_ = value;
UpdateLayoutObject();
}
void HTMLMediaElement::UpdateLayoutObject() {
if (GetLayoutObject())
GetLayoutObject()->UpdateFromElement();
}
void HTMLMediaElement::ProgressEventTimerFired(TimerBase*) {
if (network_state_ != kNetworkLoading) {
RecordProgressEventTimerState(ProgressEventTimerState::kNotLoading);
return;
}
// If this is an cross-origin request, and we haven't discovered whether
// the media is actually playable yet, don't fire any progress events as
// those may let the page know information about the resource that it's
// not supposed to know.
if (MediaShouldBeOpaque()) {
RecordProgressEventTimerState(
ProgressEventTimerState::kMediaShouldBeOpaque);
return;
}
DCHECK(previous_progress_time_);
if (GetWebMediaPlayer() && GetWebMediaPlayer()->DidLoadingProgress()) {
ScheduleEvent(event_type_names::kProgress);
previous_progress_time_ = base::ElapsedTimer();
sent_stalled_event_ = false;
UpdateLayoutObject();
RecordProgressEventTimerState(ProgressEventTimerState::kProgress);
} else if (media_source_attachment_) {
RecordProgressEventTimerState(
ProgressEventTimerState::kHasMediaSourceAttachment);
} else if (previous_progress_time_->Elapsed() <=
kStalledNotificationInterval) {
RecordProgressEventTimerState(ProgressEventTimerState::kRecentProgress);
} else if (sent_stalled_event_) {
RecordProgressEventTimerState(
ProgressEventTimerState::kStalledEventAlreadyScheduled);
} else {
// Note the !media_source_attachment_ condition above. The 'stalled' event
// is not fired when using MSE. MSE's resource is considered 'local' (we
// don't manage the download - the app does), so the HTML5 spec text around
// 'stalled' does not apply. See discussion in https://crbug.com/517240 We
// also don't need to take any action wrt delaying-the-load-event.
// MediaSource disables the delayed load when first attached.
ScheduleEvent(event_type_names::kStalled);
sent_stalled_event_ = true;
SetShouldDelayLoadEvent(false);
RecordProgressEventTimerState(ProgressEventTimerState::kStalled);
}
}
void HTMLMediaElement::AddPlayedRange(double start, double end) {
DVLOG(3) << "addPlayedRange(" << *this << ", " << start << ", " << end << ")";
if (!played_time_ranges_)
played_time_ranges_ = MakeGarbageCollected<TimeRanges>();
played_time_ranges_->Add(start, end);
}
bool HTMLMediaElement::SupportsSave() const {
// Check if download is disabled per settings.
if (GetDocument().GetSettings() &&
GetDocument().GetSettings()->GetHideDownloadUI()) {
return false;
}
// Get the URL that we'll use for downloading.
const KURL url = downloadURL();
// URLs that lead to nowhere are ignored.
if (url.IsNull() || url.IsEmpty())
return false;
// If we have no source, we can't download.
if (network_state_ == kNetworkEmpty || network_state_ == kNetworkNoSource)
return false;
// It is not useful to offer a save feature on local files.
if (url.IsLocalFile())
return false;
// MediaStream can't be downloaded.
if (GetLoadType() == WebMediaPlayer::kLoadTypeMediaStream)
return false;
// MediaSource can't be downloaded.
if (HasMediaSource())
return false;
// HLS stream shouldn't have a download button.
if (IsHLSURL(url))
return false;
// Infinite streams don't have a clear end at which to finish the download.
if (duration() == std::numeric_limits<double>::infinity())
return false;
return true;
}
bool HTMLMediaElement::SupportsLoop() const {
// MediaStream can't be looped.
if (GetLoadType() == WebMediaPlayer::kLoadTypeMediaStream)
return false;
// Infinite streams don't have a clear end at which to loop.
if (duration() == std::numeric_limits<double>::infinity())
return false;
return true;
}
void HTMLMediaElement::SetIgnorePreloadNone() {
DVLOG(3) << "setIgnorePreloadNone(" << *this << ")";
ignore_preload_none_ = true;
SetPlayerPreload();
}
void HTMLMediaElement::Seek(double time) {
DVLOG(2) << "seek(" << *this << ", " << time << ")";
// 1 - Set the media element's show poster flag to false.
SetShowPosterFlag(false);
// 2 - If the media element's readyState is HAVE_NOTHING, abort these steps.
// FIXME: remove web_media_player_ check once we figure out how
// web_media_player_ is going out of sync with readystate.
// web_media_player_ is cleared but readystate is not set to HAVE_NOTHING.
if (!web_media_player_ || ready_state_ == kHaveNothing)
return;
// Ignore preload none and start load if necessary.
SetIgnorePreloadNone();
// Get the current time before setting seeking_, last_seek_time_ is returned
// once it is set.
double now = currentTime();
// 3 - If the element's seeking IDL attribute is true, then another instance
// of this algorithm is already running. Abort that other instance of the
// algorithm without waiting for the step that it is running to complete.
// Nothing specific to be done here.
// 4 - Set the seeking IDL attribute to true.
// The flag will be cleared when the engine tells us the time has actually
// changed.
seeking_ = true;
// 6 - If the new playback position is later than the end of the media
// resource, then let it be the end of the media resource instead.
time = std::min(time, duration());
// 7 - If the new playback position is less than the earliest possible
// position, let it be that position instead.
time = std::max(time, EarliestPossiblePosition());
// Ask the media engine for the time value in the movie's time scale before
// comparing with current time. This is necessary because if the seek time is
// not equal to currentTime but the delta is less than the movie's time scale,
// we will ask the media engine to "seek" to the current movie time, which may
// be a noop and not generate a timechanged callback. This means seeking_
// will never be cleared and we will never fire a 'seeked' event.
double media_time = GetWebMediaPlayer()->MediaTimeForTimeValue(time);
if (time != media_time) {
DVLOG(3) << "seek(" << *this << ", " << time
<< ") - media timeline equivalent is " << media_time;
time = media_time;
}
// 8 - If the (possibly now changed) new playback position is not in one of
// the ranges given in the seekable attribute, then let it be the position in
// one of the ranges given in the seekable attribute that is the nearest to
// the new playback position. ... If there are no ranges given in the seekable
// attribute then set the seeking IDL attribute to false and abort these
// steps.
WebTimeRanges seekable_ranges = SeekableInternal();
if (seekable_ranges.empty()) {
seeking_ = false;
return;
}
time = seekable_ranges.Nearest(time, now);
if (playing_ && last_seek_time_ < now)
AddPlayedRange(last_seek_time_, now);
last_seek_time_ = time;
// 10 - Queue a task to fire a simple event named seeking at the element.
ScheduleEvent(event_type_names::kSeeking);
// 11 - Set the current playback position to the given new playback position.
GetWebMediaPlayer()->Seek(time);
GetWebMediaPlayer()->OnTimeUpdate();
// 14-17 are handled, if necessary, when the engine signals a readystate
// change or otherwise satisfies seek completion and signals a time change.
}
void HTMLMediaElement::FinishSeek() {
DVLOG(3) << "finishSeek(" << *this << ")";
// 14 - Set the seeking IDL attribute to false.
seeking_ = false;
// Force an update to officialPlaybackPosition. Periodic updates generally
// handle this, but may be skipped paused or waiting for data.
SetOfficialPlaybackPosition(CurrentPlaybackPosition());
// 15 - Run the time marches on steps.
GetCueTimeline().InvokeTimeMarchesOn();
// 16 - Queue a task to fire a simple event named timeupdate at the element.
ScheduleTimeupdateEvent(false);
// 17 - Queue a task to fire a simple event named seeked at the element.
ScheduleEvent(event_type_names::kSeeked);
}
HTMLMediaElement::ReadyState HTMLMediaElement::getReadyState() const {
return ready_state_;
}
bool HTMLMediaElement::HasVideo() const {
return GetWebMediaPlayer() && GetWebMediaPlayer()->HasVideo();
}
bool HTMLMediaElement::HasAudio() const {
return GetWebMediaPlayer() && GetWebMediaPlayer()->HasAudio();
}
bool HTMLMediaElement::seeking() const {
return seeking_;
}
// https://www.w3.org/TR/html51/semantics-embedded-content.html#earliest-possible-position
// The earliest possible position is not explicitly exposed in the API; it
// corresponds to the start time of the first range in the seekable attribute’s
// TimeRanges object, if any, or the current playback position otherwise.
double HTMLMediaElement::EarliestPossiblePosition() const {
WebTimeRanges seekable_ranges = SeekableInternal();
if (!seekable_ranges.empty())
return seekable_ranges.front().start;
return CurrentPlaybackPosition();
}
double HTMLMediaElement::CurrentPlaybackPosition() const {
// "Official" playback position won't take updates from "current" playback
// position until ready_state_ > kHaveMetadata, but other callers (e.g.
// pauseInternal) may still request currentPlaybackPosition at any time.
// From spec: "Media elements have a current playback position, which must
// initially (i.e., in the absence of media data) be zero seconds."
if (ready_state_ == kHaveNothing)
return 0;
if (GetWebMediaPlayer())
return GetWebMediaPlayer()->CurrentTime();
if (ready_state_ >= kHaveMetadata) {
DVLOG(3) << __func__ << " readyState = " << ready_state_
<< " but no webMediaPlayer to provide currentPlaybackPosition";
}
return 0;
}
double HTMLMediaElement::OfficialPlaybackPosition() const {
// Hold updates to official playback position while paused or waiting for more
// data. The underlying media player may continue to make small advances in
// currentTime (e.g. as samples in the last rendered audio buffer are played
// played out), but advancing currentTime while paused/waiting sends a mixed
// signal about the state of playback.
bool waiting_for_data = ready_state_ <= kHaveCurrentData;
if (official_playback_position_needs_update_ && !paused_ &&
!waiting_for_data) {
SetOfficialPlaybackPosition(CurrentPlaybackPosition());
}
#if LOG_OFFICIAL_TIME_STATUS
static const double kMinCachedDeltaForWarning = 0.01;
double delta =
std::abs(official_playback_position_ - CurrentPlaybackPosition());
if (delta > kMinCachedDeltaForWarning) {
DVLOG(3) << "CurrentTime(" << (void*)this << ") - WARNING, cached time is "
<< delta << "seconds off of media time when paused/waiting";
}
#endif
return official_playback_position_;
}
void HTMLMediaElement::SetOfficialPlaybackPosition(double position) const {
#if LOG_OFFICIAL_TIME_STATUS
DVLOG(3) << "SetOfficialPlaybackPosition(" << (void*)this
<< ") was:" << official_playback_position_ << " now:" << position;
#endif
// Internal player position may advance slightly beyond duration because
// many files use imprecise duration. Clamp official position to duration when
// known. Duration may be unknown when readyState < HAVE_METADATA.
official_playback_position_ =
std::isnan(duration()) ? position : std::min(duration(), position);
if (official_playback_position_ != position) {
DVLOG(3) << "setOfficialPlaybackPosition(" << *this
<< ") position:" << position
<< " truncated to duration:" << official_playback_position_;
}
// Once set, official playback position should hold steady until the next
// stable state. We approximate this by using a microtask to mark the
// need for an update after the current (micro)task has completed. When
// needed, the update is applied in the next call to
// officialPlaybackPosition().
official_playback_position_needs_update_ = false;
Microtask::EnqueueMicrotask(
WTF::Bind(&HTMLMediaElement::RequireOfficialPlaybackPositionUpdate,
WrapWeakPersistent(this)));
}
void HTMLMediaElement::RequireOfficialPlaybackPositionUpdate() const {
official_playback_position_needs_update_ = true;
}
double HTMLMediaElement::currentTime() const {
if (default_playback_start_position_)
return default_playback_start_position_;
if (seeking_) {
DVLOG(3) << "currentTime(" << *this << ") - seeking, returning "
<< last_seek_time_;
return last_seek_time_;
}
return OfficialPlaybackPosition();
}
void HTMLMediaElement::setCurrentTime(double time) {
// If the media element's readyState is kHaveNothing, then set the default
// playback start position to that time.
if (ready_state_ == kHaveNothing) {
default_playback_start_position_ = time;
} else {
Seek(time);
}
ReportCurrentTimeToMediaSource();
}
double HTMLMediaElement::duration() const {
return duration_;
}
bool HTMLMediaElement::paused() const {
return paused_;
}
double HTMLMediaElement::defaultPlaybackRate() const {
if (GetLoadType() == WebMediaPlayer::kLoadTypeMediaStream)
return 1.0;
return default_playback_rate_;
}
void HTMLMediaElement::setDefaultPlaybackRate(double rate) {
if (GetLoadType() == WebMediaPlayer::kLoadTypeMediaStream)
return;
if (default_playback_rate_ == rate || !IsValidPlaybackRate(rate))
return;
default_playback_rate_ = rate;
ScheduleEvent(event_type_names::kRatechange);
}
double HTMLMediaElement::playbackRate() const {
if (GetLoadType() == WebMediaPlayer::kLoadTypeMediaStream)
return 1.0;
return playback_rate_;
}
void HTMLMediaElement::setPlaybackRate(double rate,
ExceptionState& exception_state) {
DVLOG(3) << "setPlaybackRate(" << *this << ", " << rate << ")";
if (GetLoadType() == WebMediaPlayer::kLoadTypeMediaStream)
return;
if (!IsValidPlaybackRate(rate)) {
UseCounter::Count(GetDocument(),
WebFeature::kHTMLMediaElementMediaPlaybackRateOutOfRange);
// When the proposed playbackRate is unsupported, throw a NotSupportedError
// DOMException and don't update the value.
exception_state.ThrowDOMException(
DOMExceptionCode::kNotSupportedError,
"The provided playback rate (" + String::Number(rate) +
") is not in the " + "supported playback range.");
// Do not update |playback_rate_|.
return;
}
if (playback_rate_ != rate) {
playback_rate_ = rate;
ScheduleEvent(event_type_names::kRatechange);
}
// FIXME: remove web_media_player_ check once we figure out how
// web_media_player_ is going out of sync with readystate.
// web_media_player_ is cleared but readystate is not set to kHaveNothing.
if (web_media_player_) {
if (PotentiallyPlaying())
web_media_player_->SetRate(playbackRate());
web_media_player_->OnTimeUpdate();
}
if (cue_timeline_ && PotentiallyPlaying())
cue_timeline_->OnPlaybackRateUpdated();
}
HTMLMediaElement::DirectionOfPlayback HTMLMediaElement::GetDirectionOfPlayback()
const {
return playback_rate_ >= 0 ? kForward : kBackward;
}
bool HTMLMediaElement::ended() const {
// 4.8.12.8 Playing the media resource
// The ended attribute must return true if the media element has ended
// playback and the direction of playback is forwards, and false otherwise.
return EndedPlayback() && GetDirectionOfPlayback() == kForward;
}
bool HTMLMediaElement::Autoplay() const {
return FastHasAttribute(html_names::kAutoplayAttr);
}
String HTMLMediaElement::preload() const {
if (GetLoadType() == WebMediaPlayer::kLoadTypeMediaStream)
return PreloadTypeToString(WebMediaPlayer::kPreloadNone);
return PreloadTypeToString(PreloadType());
}
void HTMLMediaElement::setPreload(const AtomicString& preload) {
DVLOG(2) << "setPreload(" << *this << ", " << preload << ")";
if (GetLoadType() == WebMediaPlayer::kLoadTypeMediaStream)
return;
setAttribute(html_names::kPreloadAttr, preload);
}
WebMediaPlayer::Preload HTMLMediaElement::PreloadType() const {
const AtomicString& preload = FastGetAttribute(html_names::kPreloadAttr);
if (EqualIgnoringASCIICase(preload, "none")) {
UseCounter::Count(GetDocument(), WebFeature::kHTMLMediaElementPreloadNone);
return WebMediaPlayer::kPreloadNone;
}
if (EqualIgnoringASCIICase(preload, "metadata")) {
UseCounter::Count(GetDocument(),
WebFeature::kHTMLMediaElementPreloadMetadata);
return WebMediaPlayer::kPreloadMetaData;
}
// Force preload to 'metadata' on cellular connections.
if (GetNetworkStateNotifier().IsCellularConnectionType()) {
UseCounter::Count(GetDocument(),
WebFeature::kHTMLMediaElementPreloadForcedMetadata);
return WebMediaPlayer::kPreloadMetaData;
}
// Per HTML spec, "The empty string ... maps to the Automatic state."
// https://html.spec.whatwg.org/C/#attr-media-preload
if (EqualIgnoringASCIICase(preload, "auto") ||
EqualIgnoringASCIICase(preload, "")) {
UseCounter::Count(GetDocument(), WebFeature::kHTMLMediaElementPreloadAuto);
return WebMediaPlayer::kPreloadAuto;
}
// "The attribute's missing value default is user-agent defined, though the
// Metadata state is suggested as a compromise between reducing server load
// and providing an optimal user experience."
// The spec does not define an invalid value default:
// https://www.w3.org/Bugs/Public/show_bug.cgi?id=28950
UseCounter::Count(GetDocument(), WebFeature::kHTMLMediaElementPreloadDefault);
return WebMediaPlayer::kPreloadMetaData;
}
String HTMLMediaElement::EffectivePreload() const {
return PreloadTypeToString(EffectivePreloadType());
}
WebMediaPlayer::Preload HTMLMediaElement::EffectivePreloadType() const {
if (Autoplay() && !autoplay_policy_->IsGestureNeededForPlayback())
return WebMediaPlayer::kPreloadAuto;
WebMediaPlayer::Preload preload = PreloadType();
if (ignore_preload_none_ && preload == WebMediaPlayer::kPreloadNone)
return WebMediaPlayer::kPreloadMetaData;
return preload;
}
ScriptPromise HTMLMediaElement::playForBindings(ScriptState* script_state) {
// We have to share the same logic for internal and external callers. The
// internal callers do not want to receive a Promise back but when ::play()
// is called, |play_promise_resolvers_| needs to be populated. What this code
// does is to populate |play_promise_resolvers_| before calling ::play() and
// remove the Promise if ::play() failed.
auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state);
ScriptPromise promise = resolver->Promise();
play_promise_resolvers_.push_back(resolver);
absl::optional<DOMExceptionCode> code = Play();
if (code) {
DCHECK(!play_promise_resolvers_.IsEmpty());
play_promise_resolvers_.pop_back();
String message;
switch (code.value()) {
case DOMExceptionCode::kNotAllowedError:
message = autoplay_policy_->GetPlayErrorMessage();
RecordPlayPromiseRejected(
PlayPromiseRejectReason::kFailedAutoplayPolicy);
break;
case DOMExceptionCode::kNotSupportedError:
message = "The element has no supported sources.";
RecordPlayPromiseRejected(PlayPromiseRejectReason::kNoSupportedSources);
break;
default:
NOTREACHED();
}
resolver->Reject(MakeGarbageCollected<DOMException>(code.value(), message));
return promise;
}
return promise;
}
absl::optional<DOMExceptionCode> HTMLMediaElement::Play() {
DVLOG(2) << "play(" << *this << ")";
absl::optional<DOMExceptionCode> exception_code =
autoplay_policy_->RequestPlay();
if (exception_code == DOMExceptionCode::kNotAllowedError) {
// If we're already playing, then this play would do nothing anyway.
// Call playInternal to handle scheduling the promise resolution.
if (!paused_) {
PlayInternal();
return absl::nullopt;
}
return exception_code;
}
autoplay_policy_->StopAutoplayMutedWhenVisible();
if (error_ && error_->code() == MediaError::kMediaErrSrcNotSupported)
return DOMExceptionCode::kNotSupportedError;
DCHECK(!exception_code.has_value());
PlayInternal();
return absl::nullopt;
}
void HTMLMediaElement::PlayInternal() {
DVLOG(3) << "playInternal(" << *this << ")";
// Playback aborts any lazy loading.
if (lazy_load_intersection_observer_) {
lazy_load_intersection_observer_->disconnect();
lazy_load_intersection_observer_ = nullptr;
}
// 4.8.12.8. Playing the media resource
if (network_state_ == kNetworkEmpty)
InvokeResourceSelectionAlgorithm();
// Generally "ended" and "looping" are exclusive. Here, the loop attribute
// is ignored to seek back to start in case loop was set after playback
// ended. See http://crbug.com/364442
if (EndedPlayback(LoopCondition::kIgnored))
Seek(0);
if (paused_) {
paused_ = false;
SetShowPosterFlag(false);
GetCueTimeline().InvokeTimeMarchesOn();
ScheduleEvent(event_type_names::kPlay);
if (ready_state_ <= kHaveCurrentData)
ScheduleEvent(event_type_names::kWaiting);
else if (ready_state_ >= kHaveFutureData)
ScheduleNotifyPlaying();
} else if (ready_state_ >= kHaveFutureData) {
ScheduleResolvePlayPromises();
}
can_autoplay_ = false;
OnPlay();
SetIgnorePreloadNone();
UpdatePlayState();
}
void HTMLMediaElement::pause() {
DVLOG(2) << "pause(" << *this << ")";
autoplay_policy_->StopAutoplayMutedWhenVisible();
PauseInternal();
}
void HTMLMediaElement::PauseInternal() {
DVLOG(3) << "pauseInternal(" << *this << ")";
if (network_state_ == kNetworkEmpty)
InvokeResourceSelectionAlgorithm();
can_autoplay_ = false;
if (!paused_) {
paused_ = true;
ScheduleTimeupdateEvent(false);
ScheduleEvent(event_type_names::kPause);
// Force an update to official playback position. Automatic updates from
// currentPlaybackPosition() will be blocked while paused_ = true. This
// blocking is desired while paused, but its good to update it one final
// time to accurately reflect movie time at the moment we paused.
SetOfficialPlaybackPosition(CurrentPlaybackPosition());
ScheduleRejectPlayPromises(DOMExceptionCode::kAbortError);
}
UpdatePlayState();
}
bool HTMLMediaElement::preservesPitch() const {
return preserves_pitch_;
}
void HTMLMediaElement::setPreservesPitch(bool preserves_pitch) {
preserves_pitch_ = preserves_pitch;
if (GetWebMediaPlayer())
GetWebMediaPlayer()->SetPreservesPitch(preserves_pitch_);
}
double HTMLMediaElement::latencyHint() const {
// Parse error will fallback to std::numeric_limits<double>::quiet_NaN()
double seconds = GetFloatingPointAttribute(html_names::kLatencyhintAttr);
// Return NaN for invalid values.
if (!std::isfinite(seconds) || seconds < 0)
return std::numeric_limits<double>::quiet_NaN();
return seconds;
}
void HTMLMediaElement::setLatencyHint(double seconds) {
SetFloatingPointAttribute(html_names::kLatencyhintAttr, seconds);
}
void HTMLMediaElement::FlingingStarted() {
if (GetWebMediaPlayer())
GetWebMediaPlayer()->FlingingStarted();
}
void HTMLMediaElement::FlingingStopped() {
if (GetWebMediaPlayer())
GetWebMediaPlayer()->FlingingStopped();
}
void HTMLMediaElement::CloseMediaSource() {
if (!media_source_attachment_)
return;
media_source_attachment_->Close(media_source_tracer_);
media_source_attachment_.reset();
media_source_tracer_ = nullptr;
}
bool HTMLMediaElement::Loop() const {
return FastHasAttribute(html_names::kLoopAttr);
}
void HTMLMediaElement::SetLoop(bool b) {
DVLOG(3) << "setLoop(" << *this << ", " << BoolString(b) << ")";
SetBooleanAttribute(html_names::kLoopAttr, b);
}
bool HTMLMediaElement::ShouldShowControls(
const RecordMetricsBehavior record_metrics) const {
Settings* settings = GetDocument().GetSettings();
if (settings && !settings->GetMediaControlsEnabled()) {
if (record_metrics == RecordMetricsBehavior::kDoRecord)
RecordShowControlsUsage(this, MediaControlsShow::kDisabledSettings);
return false;
}
// If the user has explicitly shown or hidden the controls, then force that
// choice.
if (user_wants_controls_visible_.has_value()) {
if (record_metrics == RecordMetricsBehavior::kDoRecord) {
RecordShowControlsUsage(this,
*user_wants_controls_visible_
? MediaControlsShow::kUserExplicitlyEnabled
: MediaControlsShow::kUserExplicitlyDisabled);
}
return *user_wants_controls_visible_;
}
if (FastHasAttribute(html_names::kControlsAttr)) {
if (record_metrics == RecordMetricsBehavior::kDoRecord)
RecordShowControlsUsage(this, MediaControlsShow::kAttribute);
return true;
}
if (IsFullscreen()) {
if (record_metrics == RecordMetricsBehavior::kDoRecord)
RecordShowControlsUsage(this, MediaControlsShow::kFullscreen);
return true;
}
ExecutionContext* context = GetExecutionContext();
if (context && !context->CanExecuteScripts(kNotAboutToExecuteScript)) {
if (record_metrics == RecordMetricsBehavior::kDoRecord)
RecordShowControlsUsage(this, MediaControlsShow::kNoScript);
return true;
}
if (record_metrics == RecordMetricsBehavior::kDoRecord)
RecordShowControlsUsage(this, MediaControlsShow::kNotShown);
return false;
}
DOMTokenList* HTMLMediaElement::controlsList() const {
return controls_list_.Get();
}
HTMLMediaElementControlsList* HTMLMediaElement::ControlsListInternal() const {
return controls_list_.Get();
}
double HTMLMediaElement::volume() const {
return volume_;
}
void HTMLMediaElement::setVolume(double vol, ExceptionState& exception_state) {
DVLOG(2) << "setVolume(" << *this << ", " << vol << ")";
if (volume_ == vol)
return;
if (RuntimeEnabledFeatures::MediaElementVolumeGreaterThanOneEnabled()) {
if (vol < 0.0f) {
exception_state.ThrowDOMException(
DOMExceptionCode::kIndexSizeError,
ExceptionMessages::IndexExceedsMinimumBound("volume", vol, 0.0));
return;
}
} else if (vol < 0.0f || vol > 1.0f) {
exception_state.ThrowDOMException(
DOMExceptionCode::kIndexSizeError,
ExceptionMessages::IndexOutsideRange(
"volume", vol, 0.0, ExceptionMessages::kInclusiveBound, 1.0,
ExceptionMessages::kInclusiveBound));
return;
}
volume_ = vol;
ScheduleEvent(event_type_names::kVolumechange);
// If it setting volume to audible and AutoplayPolicy doesn't want the
// playback to continue, pause the playback.
if (EffectiveMediaVolume() && !autoplay_policy_->RequestAutoplayUnmute())
pause();
// If playback was not paused by the autoplay policy and got audible, the
// element is marked as being allowed to play unmuted.
if (EffectiveMediaVolume() && PotentiallyPlaying())
was_always_muted_ = false;
if (GetWebMediaPlayer())
GetWebMediaPlayer()->SetVolume(EffectiveMediaVolume());
autoplay_policy_->StopAutoplayMutedWhenVisible();
}
bool HTMLMediaElement::muted() const {
return muted_;
}
void HTMLMediaElement::setMuted(bool muted) {
DVLOG(2) << "setMuted(" << *this << ", " << BoolString(muted) << ")";
if (muted_ == muted)
return;
muted_ = muted;
ScheduleEvent(event_type_names::kVolumechange);
// If it is unmute and AutoplayPolicy doesn't want the playback to continue,
// pause the playback.
if (EffectiveMediaVolume() && !autoplay_policy_->RequestAutoplayUnmute())
pause();
// If playback was not paused by the autoplay policy and got unmuted, the
// element is marked as being allowed to play unmuted.
if (EffectiveMediaVolume() && PotentiallyPlaying())
was_always_muted_ = false;
// This is called at the end to make sure the WebMediaPlayer has the right
// information.
if (GetWebMediaPlayer())
GetWebMediaPlayer()->SetVolume(EffectiveMediaVolume());
autoplay_policy_->StopAutoplayMutedWhenVisible();
}
void HTMLMediaElement::SetUserWantsControlsVisible(bool visible) {
user_wants_controls_visible_ = visible;
UpdateControlsVisibility();
}
double HTMLMediaElement::EffectiveMediaVolume() const {
if (muted_)
return 0;
return volume_;
}
// The spec says to fire periodic timeupdate events (those sent while playing)
// every "15 to 250ms", we choose the slowest frequency
static const base::TimeDelta kMaxTimeupdateEventFrequency =
base::TimeDelta::FromMilliseconds(250);
void HTMLMediaElement::StartPlaybackProgressTimer() {
if (playback_progress_timer_.IsActive())
return;
previous_progress_time_ = base::ElapsedTimer();
playback_progress_timer_.StartRepeating(kMaxTimeupdateEventFrequency,
FROM_HERE);
}
void HTMLMediaElement::PlaybackProgressTimerFired(TimerBase*) {
if (!std::isnan(fragment_end_time_) && currentTime() >= fragment_end_time_ &&
GetDirectionOfPlayback() == kForward) {
fragment_end_time_ = std::numeric_limits<double>::quiet_NaN();
if (!paused_) {
UseCounter::Count(GetDocument(),
WebFeature::kHTMLMediaElementPauseAtFragmentEnd);
// changes paused to true and fires a simple event named pause at the
// media element.
PauseInternal();
}
}
if (!seeking_)
ScheduleTimeupdateEvent(true);
// Playback progress is chosen here for simplicity as a proxy for a good
// periodic time to also update the attached MediaSource, if any, with our
// currentTime so that it can continue to have a "recent media time".
ReportCurrentTimeToMediaSource();
}
void HTMLMediaElement::ScheduleTimeupdateEvent(bool periodic_event) {
if (web_media_player_)
web_media_player_->OnTimeUpdate();
// Per spec, consult current playback position to check for changing time.
double media_time = CurrentPlaybackPosition();
bool media_time_has_progressed =
std::isnan(last_time_update_event_media_time_)
? media_time != 0
: media_time != last_time_update_event_media_time_;
if (periodic_event && !media_time_has_progressed)
return;
ScheduleEvent(event_type_names::kTimeupdate);
last_time_update_event_media_time_ = media_time;
// Ensure periodic event fires 250ms from _this_ event. Restarting the timer
// cancels pending callbacks.
if (!periodic_event && playback_progress_timer_.IsActive()) {
playback_progress_timer_.StartRepeating(kMaxTimeupdateEventFrequency,
FROM_HERE);
}
}
void HTMLMediaElement::TogglePlayState() {
if (paused())
Play();
else
pause();
}
AudioTrackList& HTMLMediaElement::audioTracks() {
return *audio_tracks_;
}
void HTMLMediaElement::AudioTrackChanged(AudioTrack* track) {
DVLOG(3) << "audioTrackChanged(" << *this
<< ") trackId= " << String(track->id())
<< " enabled=" << BoolString(track->enabled());
DCHECK(MediaTracksEnabledInternally());
audioTracks().ScheduleChangeEvent();
if (media_source_attachment_)
media_source_attachment_->OnTrackChanged(media_source_tracer_, track);
if (!audio_tracks_timer_.IsActive())
audio_tracks_timer_.StartOneShot(base::TimeDelta(), FROM_HERE);
}
void HTMLMediaElement::AudioTracksTimerFired(TimerBase*) {
Vector<WebMediaPlayer::TrackId> enabled_track_ids;
for (unsigned i = 0; i < audioTracks().length(); ++i) {
AudioTrack* track = audioTracks().AnonymousIndexedGetter(i);
if (track->enabled())
enabled_track_ids.push_back(track->id());
}
GetWebMediaPlayer()->EnabledAudioTracksChanged(enabled_track_ids);
}
WebMediaPlayer::TrackId HTMLMediaElement::AddAudioTrack(
const WebString& id,
WebMediaPlayerClient::AudioTrackKind kind,
const WebString& label,
const WebString& language,
bool enabled) {
AtomicString kind_string = AudioKindToString(kind);
DVLOG(3) << "addAudioTrack(" << *this << ", '" << String(id) << "', ' "
<< kind_string << "', '" << String(label) << "', '"
<< String(language) << "', " << BoolString(enabled) << ")";
auto* audio_track = MakeGarbageCollected<AudioTrack>(id, kind_string, label,
language, enabled);
audioTracks().Add(audio_track);
return audio_track->id();
}
void HTMLMediaElement::RemoveAudioTrack(WebMediaPlayer::TrackId track_id) {
DVLOG(3) << "removeAudioTrack(" << *this << ")";
audioTracks().Remove(track_id);
}
VideoTrackList& HTMLMediaElement::videoTracks() {
return *video_tracks_;
}
void HTMLMediaElement::SelectedVideoTrackChanged(VideoTrack* track) {
DVLOG(3) << "selectedVideoTrackChanged(" << *this << ") selectedTrackId="
<< (track->selected() ? String(track->id()) : "none");
DCHECK(MediaTracksEnabledInternally());
if (track->selected())
videoTracks().TrackSelected(track->id());
videoTracks().ScheduleChangeEvent();
if (media_source_attachment_)
media_source_attachment_->OnTrackChanged(media_source_tracer_, track);
WebMediaPlayer::TrackId id = track->id();
GetWebMediaPlayer()->SelectedVideoTrackChanged(track->selected() ? &id
: nullptr);
}
WebMediaPlayer::TrackId HTMLMediaElement::AddVideoTrack(
const WebString& id,
WebMediaPlayerClient::VideoTrackKind kind,
const WebString& label,
const WebString& language,
bool selected) {
AtomicString kind_string = VideoKindToString(kind);
DVLOG(3) << "addVideoTrack(" << *this << ", '" << String(id) << "', '"
<< kind_string << "', '" << String(label) << "', '"
<< String(language) << "', " << BoolString(selected) << ")";
// If another track was selected (potentially by the user), leave it selected.
if (selected && videoTracks().selectedIndex() != -1)
selected = false;
auto* video_track = MakeGarbageCollected<VideoTrack>(id, kind_string, label,
language, selected);
videoTracks().Add(video_track);
return video_track->id();
}
void HTMLMediaElement::RemoveVideoTrack(WebMediaPlayer::TrackId track_id) {
DVLOG(3) << "removeVideoTrack(" << *this << ")";
videoTracks().Remove(track_id);
}
void HTMLMediaElement::AddTextTrack(WebInbandTextTrack* web_track) {
// 4.8.12.11.2 Sourcing in-band text tracks
// 1. Associate the relevant data with a new text track and its corresponding
// new TextTrack object.
auto* text_track = MakeGarbageCollected<InbandTextTrack>(web_track);
// 2. Set the new text track's kind, label, and language based on the
// semantics of the relevant data, as defined by the relevant specification.
// If there is no label in that data, then the label must be set to the empty
// string.
// 3. Associate the text track list of cues with the rules for updating the
// text track rendering appropriate for the format in question.
// 4. If the new text track's kind is metadata, then set the text track
// in-band metadata track dispatch type as follows, based on the type of the
// media resource:
// 5. Populate the new text track's list of cues with the cues parsed so far,
// folllowing the guidelines for exposing cues, and begin updating it
// dynamically as necessary.
// - Thess are all done by the media engine.
// 6. Set the new text track's readiness state to loaded.
text_track->SetReadinessState(TextTrack::kLoaded);
// 7. Set the new text track's mode to the mode consistent with the user's
// preferences and the requirements of the relevant specification for the
// data.
// - This will happen in honorUserPreferencesForAutomaticTextTrackSelection()
ScheduleTextTrackResourceLoad();
// 8. Add the new text track to the media element's list of text tracks.
// 9. Fire an event with the name addtrack, that does not bubble and is not
// cancelable, and that uses the TrackEvent interface, with the track
// attribute initialized to the text track's TextTrack object, at the media
// element's textTracks attribute's TextTrackList object.
textTracks()->Append(text_track);
}
void HTMLMediaElement::RemoveTextTrack(WebInbandTextTrack* web_track) {
if (!text_tracks_)
return;
// This cast is safe because InbandTextTrack is the only concrete
// implementation of WebInbandTextTrackClient.
auto* text_track = To<InbandTextTrack>(web_track->Client());
if (!text_track)
return;
text_tracks_->Remove(text_track);
}
void HTMLMediaElement::ForgetResourceSpecificTracks() {
// Implements the "forget the media element's media-resource-specific tracks"
// algorithm. The order is explicitly specified as text, then audio, and
// finally video. Also 'removetrack' events should not be fired.
if (text_tracks_) {
auto scope = GetCueTimeline().BeginIgnoreUpdateScope();
text_tracks_->RemoveAllInbandTracks();
}
audio_tracks_->RemoveAll();
video_tracks_->RemoveAll();
audio_tracks_timer_.Stop();
}
TextTrack* HTMLMediaElement::addTextTrack(const AtomicString& kind,
const AtomicString& label,
const AtomicString& language,
ExceptionState& exception_state) {
// https://html.spec.whatwg.org/C/#dom-media-addtexttrack
// The addTextTrack(kind, label, language) method of media elements, when
// invoked, must run the following steps:
// 1. Create a new TextTrack object.
// 2. Create a new text track corresponding to the new object, and set its
// text track kind to kind, its text track label to label, its text
// track language to language, ..., and its text track list of cues to
// an empty list.
auto* text_track = MakeGarbageCollected<TextTrack>(kind, label, language);
// ..., its text track readiness state to the text track loaded state, ...
text_track->SetReadinessState(TextTrack::kLoaded);
// 3. Add the new text track to the media element's list of text tracks.
// 4. Queue a task to fire a trusted event with the name addtrack, that
// does not bubble and is not cancelable, and that uses the TrackEvent
// interface, with the track attribute initialised to the new text
// track's TextTrack object, at the media element's textTracks
// attribute's TextTrackList object.
textTracks()->Append(text_track);
// Note: Due to side effects when changing track parameters, we have to
// first append the track to the text track list.
// FIXME: Since setMode() will cause a 'change' event to be queued on the
// same task source as the 'addtrack' event (see above), the order is
// wrong. (The 'change' event shouldn't be fired at all in this case...)
// ..., its text track mode to the text track hidden mode, ...
text_track->setMode(TextTrack::HiddenKeyword());
// 5. Return the new TextTrack object.
return text_track;
}
std::vector<TextTrackMetadata> HTMLMediaElement::GetTextTrackMetadata() {
TextTrackList* tracks = textTracks();
std::vector<TextTrackMetadata> result;
for (unsigned i = 0; i < tracks->length(); i++) {
TextTrack* track = tracks->AnonymousIndexedGetter(i);
result.emplace_back(track->language().GetString().Utf8(),
track->kind().GetString().Utf8(),
track->label().GetString().Utf8(), track->id().Utf8());
}
return result;
}
TextTrackList* HTMLMediaElement::textTracks() {
if (!text_tracks_) {
UseCounter::Count(GetDocument(), WebFeature::kMediaElementTextTrackList);
text_tracks_ = MakeGarbageCollected<TextTrackList>(this);
}
return text_tracks_.Get();
}
void HTMLMediaElement::DidAddTrackElement(HTMLTrackElement* track_element) {
// 4.8.12.11.3 Sourcing out-of-band text tracks
// When a track element's parent element changes and the new parent is a media
// element, then the user agent must add the track element's corresponding
// text track to the media element's list of text tracks ... [continues in
// TextTrackList::append]
TextTrack* text_track = track_element->track();
if (!text_track)
return;
textTracks()->Append(text_track);
// Do not schedule the track loading until parsing finishes so we don't start
// before all tracks in the markup have been added.
if (IsFinishedParsingChildren())
ScheduleTextTrackResourceLoad();
}
void HTMLMediaElement::DidRemoveTrackElement(HTMLTrackElement* track_element) {
KURL url = track_element->GetNonEmptyURLAttribute(html_names::kSrcAttr);
DVLOG(3) << "didRemoveTrackElement(" << *this << ") - 'src' is "
<< UrlForLoggingMedia(url);
TextTrack* text_track = track_element->track();
if (!text_track)
return;
text_track->SetHasBeenConfigured(false);
if (!text_tracks_)
return;
// 4.8.12.11.3 Sourcing out-of-band text tracks
// When a track element's parent element changes and the old parent was a
// media element, then the user agent must remove the track element's
// corresponding text track from the media element's list of text tracks.
text_tracks_->Remove(text_track);
wtf_size_t index =
text_tracks_when_resource_selection_began_.Find(text_track);
if (index != kNotFound)
text_tracks_when_resource_selection_began_.EraseAt(index);
}
void HTMLMediaElement::HonorUserPreferencesForAutomaticTextTrackSelection() {
if (!text_tracks_ || !text_tracks_->length())
return;
if (!should_perform_automatic_track_selection_)
return;
AutomaticTrackSelection::Configuration configuration;
if (processing_preference_change_)
configuration.disable_currently_enabled_tracks = true;
if (text_tracks_visible_)
configuration.force_enable_subtitle_or_caption_track = true;
Settings* settings = GetDocument().GetSettings();
if (settings) {
configuration.text_track_kind_user_preference =
settings->GetTextTrackKindUserPreference();
}
AutomaticTrackSelection track_selection(configuration);
track_selection.Perform(*text_tracks_);
}
bool HTMLMediaElement::HavePotentialSourceChild() {
// Stash the current <source> node and next nodes so we can restore them after
// checking to see there is another potential.
HTMLSourceElement* current_source_node = current_source_node_;
Node* next_node = next_child_node_to_consider_;
KURL next_url = SelectNextSourceChild(nullptr, kDoNothing);
current_source_node_ = current_source_node;
next_child_node_to_consider_ = next_node;
return next_url.IsValid();
}
KURL HTMLMediaElement::SelectNextSourceChild(
String* content_type,
InvalidURLAction action_if_invalid) {
// Don't log if this was just called to find out if there are any valid
// <source> elements.
bool should_log = action_if_invalid != kDoNothing;
if (should_log)
DVLOG(3) << "selectNextSourceChild(" << *this << ")";
if (!next_child_node_to_consider_) {
if (should_log) {
DVLOG(3) << "selectNextSourceChild(" << *this << ") -> 0x0000, \"\"";
}
return KURL();
}
KURL media_url;
Node* node;
HTMLSourceElement* source = nullptr;
String type;
bool looking_for_start_node = next_child_node_to_consider_;
bool can_use_source_element = false;
NodeVector potential_source_nodes;
GetChildNodes(*this, potential_source_nodes);
for (unsigned i = 0;
!can_use_source_element && i < potential_source_nodes.size(); ++i) {
node = potential_source_nodes[i].Get();
if (looking_for_start_node && next_child_node_to_consider_ != node)
continue;
looking_for_start_node = false;
source = DynamicTo<HTMLSourceElement>(node);
if (!source || node->parentNode() != this)
continue;
// 2. If candidate does not have a src attribute, or if its src
// attribute's value is the empty string ... jump down to the failed
// step below
const AtomicString& src_value =
source->FastGetAttribute(html_names::kSrcAttr);
if (should_log) {
DVLOG(3) << "selectNextSourceChild(" << *this << ") - 'src' is "
<< UrlForLoggingMedia(media_url);
}
if (src_value.IsEmpty())
goto checkAgain;
// 3. Let urlString be the resulting URL string that would have resulted
// from parsing the URL specified by candidate's src attribute's value
// relative to the candidate's node document when the src attribute was
// last changed.
media_url = source->GetDocument().CompleteURL(src_value);
// 4. If urlString was not obtained successfully, then end the
// synchronous section, and jump down to the failed with elements step
// below.
if (!IsSafeToLoadURL(media_url, action_if_invalid))
goto checkAgain;
// 5. If candidate has a type attribute whose value, when parsed as a
// MIME type ...
type = source->type();
if (type.IsEmpty() && media_url.ProtocolIsData())
type = MimeTypeFromDataURL(media_url);
if (!type.IsEmpty()) {
if (should_log) {
DVLOG(3) << "selectNextSourceChild(" << *this << ") - 'type' is '"
<< type << "'";
}
if (!GetSupportsType(ContentType(type)))
goto checkAgain;
}
// Making it this far means the <source> looks reasonable.
can_use_source_element = true;
checkAgain:
if (!can_use_source_element && action_if_invalid == kComplain && source)
source->ScheduleErrorEvent();
}
if (can_use_source_element) {
if (content_type)
*content_type = type;
current_source_node_ = source;
next_child_node_to_consider_ = source->nextSibling();
} else {
current_source_node_ = nullptr;
next_child_node_to_consider_ = nullptr;
}
if (should_log) {
DVLOG(3) << "selectNextSourceChild(" << *this << ") -> "
<< current_source_node_.Get() << ", "
<< (can_use_source_element ? UrlForLoggingMedia(media_url) : "");
}
return can_use_source_element ? media_url : KURL();
}
void HTMLMediaElement::SourceWasAdded(HTMLSourceElement* source) {
DVLOG(3) << "sourceWasAdded(" << *this << ", " << source << ")";
KURL url = source->GetNonEmptyURLAttribute(html_names::kSrcAttr);
DVLOG(3) << "sourceWasAdded(" << *this << ") - 'src' is "
<< UrlForLoggingMedia(url);
// We should only consider a <source> element when there is not src attribute
// at all.
if (FastHasAttribute(html_names::kSrcAttr))
return;
// 4.8.8 - If a source element is inserted as a child of a media element that
// has no src attribute and whose networkState has the value NETWORK_EMPTY,
// the user agent must invoke the media element's resource selection
// algorithm.
if (getNetworkState() == HTMLMediaElement::kNetworkEmpty) {
InvokeResourceSelectionAlgorithm();
// Ignore current |next_child_node_to_consider_| and consider |source|.
next_child_node_to_consider_ = source;
return;
}
if (current_source_node_ && source == current_source_node_->nextSibling()) {
DVLOG(3) << "sourceWasAdded(" << *this
<< ") - <source> inserted immediately after current source";
// Ignore current |next_child_node_to_consider_| and consider |source|.
next_child_node_to_consider_ = source;
return;
}
// Consider current |next_child_node_to_consider_| as it is already in the
// middle of processing.
if (next_child_node_to_consider_)
return;
if (load_state_ != kWaitingForSource)
return;
// 4.8.9.5, resource selection algorithm, source elements section:
// 21. Wait until the node after pointer is a node other than the end of the
// list. (This step might wait forever.)
// 22. Asynchronously await a stable state...
// 23. Set the element's delaying-the-load-event flag back to true (this
// delays the load event again, in case it hasn't been fired yet).
SetShouldDelayLoadEvent(true);
// 24. Set the networkState back to NETWORK_LOADING.
SetNetworkState(kNetworkLoading);
// 25. Jump back to the find next candidate step above.
next_child_node_to_consider_ = source;
ScheduleNextSourceChild();
}
void HTMLMediaElement::SourceWasRemoved(HTMLSourceElement* source) {
DVLOG(3) << "sourceWasRemoved(" << *this << ", " << source << ")";
KURL url = source->GetNonEmptyURLAttribute(html_names::kSrcAttr);
DVLOG(3) << "sourceWasRemoved(" << *this << ") - 'src' is "
<< UrlForLoggingMedia(url);
if (source != current_source_node_ && source != next_child_node_to_consider_)
return;
if (source == next_child_node_to_consider_) {
if (current_source_node_)
next_child_node_to_consider_ = current_source_node_->nextSibling();
DVLOG(3) << "sourceWasRemoved(" << *this
<< ") - next_child_node_to_consider_ set to "
<< next_child_node_to_consider_.Get();
} else if (source == current_source_node_) {
// Clear the current source node pointer, but don't change the movie as the
// spec says:
// 4.8.8 - Dynamically modifying a source element and its attribute when the
// element is already inserted in a video or audio element will have no
// effect.
current_source_node_ = nullptr;
DVLOG(3) << "SourceWasRemoved(" << *this
<< ") - current_source_node_ set to 0";
}
}
void HTMLMediaElement::TimeChanged() {
DVLOG(3) << "timeChanged(" << *this << ")";
// 4.8.12.9 steps 12-14. Needed if no ReadyState change is associated with the
// seek.
if (seeking_ && ready_state_ >= kHaveCurrentData &&
!GetWebMediaPlayer()->Seeking()) {
FinishSeek();
}
// When the current playback position reaches the end of the media resource
// when the direction of playback is forwards, then the user agent must follow
// these steps:
if (EndedPlayback(LoopCondition::kIgnored)) {
// If the media element has a loop attribute specified
if (Loop()) {
// then seek to the earliest possible position of the media resource and
// abort these steps.
Seek(EarliestPossiblePosition());
} else {
// Queue a task to fire a simple event named timeupdate at the media
// element.
ScheduleTimeupdateEvent(false);
// If the media element has still ended playback, and the direction of
// playback is still forwards, and paused is false,
if (!paused_) {
// Trigger an update to `official_playback_position_` (if necessary)
// BEFORE setting `paused_ = false`, to ensure a final sync with
// `WebMediaPlayer()->CurrentPlaybackPosition()`.
OfficialPlaybackPosition();
// changes paused to true and fires a simple event named pause at the
// media element.
paused_ = true;
ScheduleEvent(event_type_names::kPause);
ScheduleRejectPlayPromises(DOMExceptionCode::kAbortError);
}
// Queue a task to fire a simple event named ended at the media element.
ScheduleEvent(event_type_names::kEnded);
}
}
UpdatePlayState();
}
void HTMLMediaElement::DurationChanged() {
DVLOG(3) << "durationChanged(" << *this << ")";
// durationChanged() is triggered by media player.
CHECK(web_media_player_);
double new_duration = web_media_player_->Duration();
// If the duration is changed such that the *current playback position* ends
// up being greater than the time of the end of the media resource, then the
// user agent must also seek to the time of the end of the media resource.
DurationChanged(new_duration, CurrentPlaybackPosition() > new_duration);
}
void HTMLMediaElement::DurationChanged(double duration, bool request_seek) {
DVLOG(3) << "durationChanged(" << *this << ", " << duration << ", "
<< BoolString(request_seek) << ")";
// Abort if duration unchanged.
if (duration_ == duration)
return;
DVLOG(3) << "durationChanged(" << *this << ") : " << duration_ << " -> "
<< duration;
duration_ = duration;
ScheduleEvent(event_type_names::kDurationchange);
if (web_media_player_)
web_media_player_->OnTimeUpdate();
UpdateLayoutObject();
if (request_seek)
Seek(duration);
}
bool HTMLMediaElement::HasRemoteRoutes() const {
// TODO(mlamouri): used by MediaControlsPainter; should be refactored out.
return RemotePlaybackClient() &&
RemotePlaybackClient()->RemotePlaybackAvailable();
}
void HTMLMediaElement::RemotePlaybackCompatibilityChanged(const WebURL& url,
bool is_compatible) {
if (RemotePlaybackClient())
RemotePlaybackClient()->SourceChanged(url, is_compatible);
}
bool HTMLMediaElement::HasSelectedVideoTrack() {
return video_tracks_ && video_tracks_->selectedIndex() != -1;
}
WebMediaPlayer::TrackId HTMLMediaElement::GetSelectedVideoTrackId() {
DCHECK(HasSelectedVideoTrack());
int selected_track_index = video_tracks_->selectedIndex();
VideoTrack* track =
video_tracks_->AnonymousIndexedGetter(selected_track_index);
return track->id();
}
bool HTMLMediaElement::WasAlwaysMuted() {
return was_always_muted_;
}
// MediaPlayerPresentation methods
void HTMLMediaElement::Repaint() {
if (cc_layer_)
cc_layer_->SetNeedsDisplay();
UpdateLayoutObject();
if (GetLayoutObject())
GetLayoutObject()->SetShouldDoFullPaintInvalidation();
}
void HTMLMediaElement::SizeChanged() {
DVLOG(3) << "sizeChanged(" << *this << ")";
DCHECK(HasVideo()); // "resize" makes no sense in absence of video.
if (ready_state_ > kHaveNothing && IsHTMLVideoElement())
ScheduleEvent(event_type_names::kResize);
UpdateLayoutObject();
}
WebTimeRanges HTMLMediaElement::BufferedInternal() const {
if (media_source_attachment_)
return media_source_attachment_->BufferedInternal(media_source_tracer_);
if (!GetWebMediaPlayer())
return {};
return GetWebMediaPlayer()->Buffered();
}
TimeRanges* HTMLMediaElement::buffered() const {
return MakeGarbageCollected<TimeRanges>(BufferedInternal());
}
TimeRanges* HTMLMediaElement::played() {
if (playing_) {
double time = currentTime();
if (time > last_seek_time_)
AddPlayedRange(last_seek_time_, time);
}
if (!played_time_ranges_)
played_time_ranges_ = MakeGarbageCollected<TimeRanges>();
return played_time_ranges_->Copy();
}
WebTimeRanges HTMLMediaElement::SeekableInternal() const {
if (!GetWebMediaPlayer())
return {};
if (media_source_attachment_)
return media_source_attachment_->SeekableInternal(media_source_tracer_);
return GetWebMediaPlayer()->Seekable();
}
TimeRanges* HTMLMediaElement::seekable() const {
return MakeGarbageCollected<TimeRanges>(SeekableInternal());
}
bool HTMLMediaElement::PotentiallyPlaying() const {
// Once we've reached the metadata state the WebMediaPlayer is ready to accept
// play state changes.
return ready_state_ >= kHaveMetadata && CouldPlayIfEnoughData();
}
bool HTMLMediaElement::CouldPlayIfEnoughData() const {
return !paused() && !EndedPlayback() && !StoppedDueToErrors();
}
bool HTMLMediaElement::EndedPlayback(LoopCondition loop_condition) const {
// If we have infinite duration, we'll never have played for long enough to
// have ended playback.
const double dur = duration();
if (std::isnan(dur) || dur == std::numeric_limits<double>::infinity())
return false;
// 4.8.12.8 Playing the media resource
// A media element is said to have ended playback when the element's
// readyState attribute is HAVE_METADATA or greater,
if (ready_state_ < kHaveMetadata)
return false;
DCHECK_EQ(GetDirectionOfPlayback(), kForward);
if (auto* wmp = GetWebMediaPlayer()) {
return wmp->IsEnded() &&
(loop_condition == LoopCondition::kIgnored || !Loop());
}
return false;
}
bool HTMLMediaElement::StoppedDueToErrors() const {
if (ready_state_ >= kHaveMetadata && error_) {
WebTimeRanges seekable_ranges = SeekableInternal();
if (!seekable_ranges.Contain(currentTime()))
return true;
}
return false;
}
void HTMLMediaElement::UpdatePlayState() {
bool is_playing = GetWebMediaPlayer() && !GetWebMediaPlayer()->Paused();
bool should_be_playing = PotentiallyPlaying();
DVLOG(3) << "updatePlayState(" << *this
<< ") - shouldBePlaying = " << BoolString(should_be_playing)
<< ", isPlaying = " << BoolString(is_playing);
if (should_be_playing && !muted_)
was_always_muted_ = false;
if (should_be_playing) {
if (!is_playing) {
// Set rate, muted before calling play in case they were set before the
// media engine was setup. The media engine should just stash the rate
// and muted values since it isn't already playing.
GetWebMediaPlayer()->SetRate(playbackRate());
GetWebMediaPlayer()->SetVolume(EffectiveMediaVolume());
GetWebMediaPlayer()->Play();
// These steps should not be necessary, but if `play()` is called before
// a source change, we may get into a state where `paused_ == false` and
// `show_poster_flag_ == true`. My (cassew@google.com) interpretation of
// the spec is that we should not be playing in this scenario.
// https://crbug.com/633591
SetShowPosterFlag(false);
GetCueTimeline().InvokeTimeMarchesOn();
}
StartPlaybackProgressTimer();
playing_ = true;
} else { // Should not be playing right now
if (is_playing) {
GetWebMediaPlayer()->Pause();
}
playback_progress_timer_.Stop();
playing_ = false;
double time = currentTime();
if (time > last_seek_time_)
AddPlayedRange(last_seek_time_, time);
GetCueTimeline().OnPause();
}
UpdateLayoutObject();
if (web_media_player_)
web_media_player_->OnTimeUpdate();
ReportCurrentTimeToMediaSource();
PseudoStateChanged(CSSSelector::kPseudoPaused);
PseudoStateChanged(CSSSelector::kPseudoPlaying);
}
void HTMLMediaElement::StopPeriodicTimers() {
progress_event_timer_.Stop();
playback_progress_timer_.Stop();
if (lazy_load_intersection_observer_) {
lazy_load_intersection_observer_->disconnect();
lazy_load_intersection_observer_ = nullptr;
}
}
void HTMLMediaElement::
ClearMediaPlayerAndAudioSourceProviderClientWithoutLocking() {
GetAudioSourceProvider().SetClient(nullptr);
if (web_media_player_) {
audio_source_provider_.Wrap(nullptr);
web_media_player_.reset();
// The lifetime of the mojo endpoints are tied to the WebMediaPlayer's, so
// we need to reset those as well.
media_player_receiver_set_->Value().Clear();
media_player_observer_remote_set_->Value().Clear();
}
OnWebMediaPlayerCleared();
}
void HTMLMediaElement::ClearMediaPlayer() {
ForgetResourceSpecificTracks();
CloseMediaSource();
CancelDeferredLoad();
{
AudioSourceProviderClientLockScope scope(*this);
ClearMediaPlayerAndAudioSourceProviderClientWithoutLocking();
}
StopPeriodicTimers();
load_timer_.Stop();
pending_action_flags_ = 0;
load_state_ = kWaitingForSource;
if (GetLayoutObject())
GetLayoutObject()->SetShouldDoFullPaintInvalidation();
}
void HTMLMediaElement::ContextLifecycleStateChanged(
mojom::FrameLifecycleState state) {
if (state == mojom::FrameLifecycleState::kFrozenAutoResumeMedia && playing_) {
paused_by_context_paused_ = true;
pause();
} else if (state == mojom::FrameLifecycleState::kFrozen && playing_) {
pause();
} else if (state == mojom::FrameLifecycleState::kRunning &&
paused_by_context_paused_) {
paused_by_context_paused_ = false;
Play();
}
}
void HTMLMediaElement::ContextDestroyed() {
DVLOG(3) << "contextDestroyed(" << static_cast<void*>(this) << ")";
// Close the async event queue so that no events are enqueued.
CancelPendingEventsAndCallbacks();
// Clear everything in the Media Element
if (media_source_attachment_)
media_source_attachment_->OnElementContextDestroyed();
ClearMediaPlayer();
ready_state_ = kHaveNothing;
ready_state_maximum_ = kHaveNothing;
SetNetworkState(kNetworkEmpty);
SetShouldDelayLoadEvent(false);
current_source_node_ = nullptr;
official_playback_position_ = 0;
official_playback_position_needs_update_ = true;
playing_ = false;
paused_ = true;
seeking_ = false;
GetCueTimeline().OnReadyStateReset();
UpdateLayoutObject();
StopPeriodicTimers();
removed_from_document_timer_.Stop();
}
bool HTMLMediaElement::HasPendingActivity() const {
const auto result = HasPendingActivityInternal();
// TODO(dalecurtis): Replace c-style casts in followup patch.
DVLOG(3) << "HasPendingActivity(" << *this << ") = " << result;
return result;
}
bool HTMLMediaElement::HasPendingActivityInternal() const {
// The delaying-the-load-event flag is set by resource selection algorithm
// when looking for a resource to load, before networkState has reached to
// kNetworkLoading.
if (should_delay_load_event_)
return true;
// When networkState is kNetworkLoading, progress and stalled events may be
// fired.
//
// When connected to a MediaSource, ignore |network_state_|. The rest
// of this method's logic and the HasPendingActivity() of the various
// MediaSource API objects more precisely indicate whether or not any pending
// activity is expected on the group of connected HTMLMediaElement +
// MediaSource API objects. This lets the group of objects be garbage
// collected if there is no pending activity nor reachability from a GC root,
// even while in kNetworkLoading.
//
// We use the WebMediaPlayer's network state instead of |network_state_| since
// it's value is unreliable prior to ready state kHaveMetadata.
if (!media_source_attachment_) {
const auto* wmp = GetWebMediaPlayer();
if (!wmp) {
if (network_state_ == kNetworkLoading)
return true;
} else if (wmp->GetNetworkState() == WebMediaPlayer::kNetworkStateLoading) {
return true;
}
}
{
// Disable potential updating of playback position, as that will
// require v8 allocations; not allowed while GCing
// (hasPendingActivity() is called during a v8 GC.)
base::AutoReset<bool> scope(&official_playback_position_needs_update_,
false);
// When playing or if playback may continue, timeupdate events may be fired.
if (CouldPlayIfEnoughData())
return true;
}
// When the seek finishes timeupdate and seeked events will be fired.
if (seeking_)
return true;
// Wait for any pending events to be fired.
if (async_event_queue_->HasPendingEvents())
return true;
return false;
}
bool HTMLMediaElement::IsFullscreen() const {
return Fullscreen::IsFullscreenElement(*this);
}
cc::Layer* HTMLMediaElement::CcLayer() const {
return cc_layer_;
}
bool HTMLMediaElement::HasClosedCaptions() const {
if (!text_tracks_)
return false;
for (unsigned i = 0; i < text_tracks_->length(); ++i) {
if (text_tracks_->AnonymousIndexedGetter(i)->CanBeRendered())
return true;
}
return false;
}
bool HTMLMediaElement::TextTracksVisible() const {
return text_tracks_visible_;
}
// static
void HTMLMediaElement::AssertShadowRootChildren(ShadowRoot& shadow_root) {
#if DCHECK_IS_ON()
// There can be up to three children: an interstitial (media remoting or
// picture in picture), text track container, and media controls. The media
// controls has to be the last child if present, and has to be the next
// sibling of the text track container if both present. When present, media
// remoting interstitial has to be the first child.
unsigned number_of_children = shadow_root.CountChildren();
DCHECK_LE(number_of_children, 3u);
Node* first_child = shadow_root.firstChild();
Node* last_child = shadow_root.lastChild();
if (number_of_children == 1) {
DCHECK(first_child->IsTextTrackContainer() ||
first_child->IsMediaControls() ||
first_child->IsMediaRemotingInterstitial() ||
first_child->IsPictureInPictureInterstitial());
} else if (number_of_children == 2) {
DCHECK(first_child->IsTextTrackContainer() ||
first_child->IsMediaRemotingInterstitial() ||
first_child->IsPictureInPictureInterstitial());
DCHECK(last_child->IsTextTrackContainer() || last_child->IsMediaControls());
if (first_child->IsTextTrackContainer())
DCHECK(last_child->IsMediaControls());
} else if (number_of_children == 3) {
Node* second_child = first_child->nextSibling();
DCHECK(first_child->IsMediaRemotingInterstitial() ||
first_child->IsPictureInPictureInterstitial());
DCHECK(second_child->IsTextTrackContainer());
DCHECK(last_child->IsMediaControls());
}
#endif
}
TextTrackContainer& HTMLMediaElement::EnsureTextTrackContainer() {
UseCounter::Count(GetDocument(), WebFeature::kMediaElementTextTrackContainer);
ShadowRoot& shadow_root = EnsureUserAgentShadowRoot();
AssertShadowRootChildren(shadow_root);
Node* first_child = shadow_root.firstChild();
if (auto* first_child_text_track = DynamicTo<TextTrackContainer>(first_child))
return *first_child_text_track;
Node* to_be_inserted = first_child;
if (first_child && (first_child->IsMediaRemotingInterstitial() ||
first_child->IsPictureInPictureInterstitial())) {
Node* second_child = first_child->nextSibling();
if (auto* second_child_text_track =
DynamicTo<TextTrackContainer>(second_child))
return *second_child_text_track;
to_be_inserted = second_child;
}
auto* text_track_container = MakeGarbageCollected<TextTrackContainer>(*this);
// The text track container should be inserted before the media controls,
// so that they are rendered behind them.
shadow_root.InsertBefore(text_track_container, to_be_inserted);
AssertShadowRootChildren(shadow_root);
return *text_track_container;
}
void HTMLMediaElement::UpdateTextTrackDisplay() {
DVLOG(3) << "updateTextTrackDisplay(" << *this << ")";
EnsureTextTrackContainer().UpdateDisplay(
*this, TextTrackContainer::kDidNotStartExposingControls);
}
void HTMLMediaElement::MediaControlsDidBecomeVisible() {
DVLOG(3) << "mediaControlsDidBecomeVisible(" << *this << ")";
// When the user agent starts exposing a user interface for a video element,
// the user agent should run the rules for updating the text track rendering
// of each of the text tracks in the video element's list of text tracks ...
if (IsHTMLVideoElement() && TextTracksVisible()) {
EnsureTextTrackContainer().UpdateDisplay(
*this, TextTrackContainer::kDidStartExposingControls);
}
}
void HTMLMediaElement::SetTextTrackKindUserPreferenceForAllMediaElements(
Document* document) {
auto it = DocumentToElementSetMap().find(document);
if (it == DocumentToElementSetMap().end())
return;
DCHECK(it->value);
WeakMediaElementSet& elements = *it->value;
for (const auto& element : elements)
element->AutomaticTrackSelectionForUpdatedUserPreference();
}
void HTMLMediaElement::AutomaticTrackSelectionForUpdatedUserPreference() {
if (!text_tracks_ || !text_tracks_->length())
return;
MarkCaptionAndSubtitleTracksAsUnconfigured();
processing_preference_change_ = true;
text_tracks_visible_ = false;
HonorUserPreferencesForAutomaticTextTrackSelection();
processing_preference_change_ = false;
// If a track is set to 'showing' post performing automatic track selection,
// set text tracks state to visible to update the CC button and display the
// track.
text_tracks_visible_ = text_tracks_->HasShowingTracks();
UpdateTextTrackDisplay();
}
void HTMLMediaElement::MarkCaptionAndSubtitleTracksAsUnconfigured() {
if (!text_tracks_)
return;
// Mark all tracks as not "configured" so that
// honorUserPreferencesForAutomaticTextTrackSelection() will reconsider
// which tracks to display in light of new user preferences (e.g. default
// tracks should not be displayed if the user has turned off captions and
// non-default tracks should be displayed based on language preferences if
// the user has turned captions on).
for (unsigned i = 0; i < text_tracks_->length(); ++i) {
TextTrack* text_track = text_tracks_->AnonymousIndexedGetter(i);
if (text_track->IsVisualKind())
text_track->SetHasBeenConfigured(false);
}
}
uint64_t HTMLMediaElement::webkitAudioDecodedByteCount() const {
if (!GetWebMediaPlayer())
return 0;
return GetWebMediaPlayer()->AudioDecodedByteCount();
}
uint64_t HTMLMediaElement::webkitVideoDecodedByteCount() const {
if (!GetWebMediaPlayer())
return 0;
return GetWebMediaPlayer()->VideoDecodedByteCount();
}
bool HTMLMediaElement::IsURLAttribute(const Attribute& attribute) const {
return attribute.GetName() == html_names::kSrcAttr ||
HTMLElement::IsURLAttribute(attribute);
}
void HTMLMediaElement::SetShouldDelayLoadEvent(bool should_delay) {
if (should_delay_load_event_ == should_delay)
return;
DVLOG(3) << "setShouldDelayLoadEvent(" << *this << ", "
<< BoolString(should_delay) << ")";
should_delay_load_event_ = should_delay;
if (should_delay)
GetDocument().IncrementLoadEventDelayCount();
else
GetDocument().DecrementLoadEventDelayCount();
}
MediaControls* HTMLMediaElement::GetMediaControls() const {
return media_controls_;
}
void HTMLMediaElement::EnsureMediaControls() {
if (GetMediaControls())
return;
ShadowRoot& shadow_root = EnsureUserAgentShadowRoot();
UseCounterMuteScope scope(*this);
media_controls_ =
CoreInitializer::GetInstance().CreateMediaControls(*this, shadow_root);
// The media controls should be inserted after the text track container,
// so that they are rendered in front of captions and subtitles. This check
// is verifying the contract.
AssertShadowRootChildren(shadow_root);
}
void HTMLMediaElement::UpdateControlsVisibility() {
if (!isConnected())
return;
bool native_controls = ShouldShowControls(RecordMetricsBehavior::kDoRecord);
// When LazyInitializeMediaControls is enabled, initialize the controls only
// if native controls should be used or if using the cast overlay.
if (!RuntimeEnabledFeatures::LazyInitializeMediaControlsEnabled() ||
RuntimeEnabledFeatures::MediaCastOverlayButtonEnabled() ||
native_controls) {
EnsureMediaControls();
// TODO(mlamouri): this doesn't sound needed but the following tests, on
// Android fails when removed:
// fullscreen/compositor-touch-hit-rects-fullscreen-video-controls.html
GetMediaControls()->Reset();
}
if (native_controls)
GetMediaControls()->MaybeShow();
else if (GetMediaControls())
GetMediaControls()->Hide();
if (web_media_player_)
web_media_player_->OnHasNativeControlsChanged(native_controls);
}
CueTimeline& HTMLMediaElement::GetCueTimeline() {
if (!cue_timeline_)
cue_timeline_ = MakeGarbageCollected<CueTimeline>(*this);
return *cue_timeline_;
}
void HTMLMediaElement::ConfigureTextTrackDisplay() {
DCHECK(text_tracks_);
DVLOG(3) << "configureTextTrackDisplay(" << *this << ")";
if (processing_preference_change_)
return;
bool have_visible_text_track = text_tracks_->HasShowingTracks();
text_tracks_visible_ = have_visible_text_track;
if (!have_visible_text_track && !GetMediaControls())
return;
// Note: The "time marches on" algorithm |CueTimeline::TimeMarchesOn| runs
// the "rules for updating the text track rendering" (updateTextTrackDisplay)
// only for "affected tracks", i.e. tracks where the the active cues have
// changed. This misses cues in tracks that changed mode between hidden and
// showing. This appears to be a spec bug, which we work around here:
// https://www.w3.org/Bugs/Public/show_bug.cgi?id=28236
UpdateTextTrackDisplay();
}
// TODO(srirama.m): Merge it to resetMediaElement if possible and remove it.
void HTMLMediaElement::ResetMediaPlayerAndMediaSource() {
CloseMediaSource();
{
AudioSourceProviderClientLockScope scope(*this);
ClearMediaPlayerAndAudioSourceProviderClientWithoutLocking();
}
if (audio_source_node_)
GetAudioSourceProvider().SetClient(audio_source_node_);
}
void HTMLMediaElement::SetAudioSourceNode(
AudioSourceProviderClient* source_node) {
DCHECK(IsMainThread());
audio_source_node_ = source_node;
// No need to lock the |audio_source_node| because it locks itself when
// setFormat() is invoked.
GetAudioSourceProvider().SetClient(audio_source_node_);
}
WebMediaPlayer::CorsMode HTMLMediaElement::CorsMode() const {
const AtomicString& cross_origin_mode =
FastGetAttribute(html_names::kCrossoriginAttr);
if (cross_origin_mode.IsNull())
return WebMediaPlayer::kCorsModeUnspecified;
if (EqualIgnoringASCIICase(cross_origin_mode, "use-credentials"))
return WebMediaPlayer::kCorsModeUseCredentials;
return WebMediaPlayer::kCorsModeAnonymous;
}
void HTMLMediaElement::SetCcLayer(cc::Layer* cc_layer) {
if (cc_layer == cc_layer_)
return;
// We need to update the GraphicsLayer when the cc layer changes.
SetNeedsCompositingUpdate();
cc_layer_ = cc_layer;
}
void HTMLMediaElement::MediaSourceOpened(WebMediaSource* web_media_source) {
SetShouldDelayLoadEvent(false);
media_source_attachment_->CompleteAttachingToMediaElement(
media_source_tracer_, base::WrapUnique(web_media_source));
}
bool HTMLMediaElement::IsInteractiveContent() const {
return FastHasAttribute(html_names::kControlsAttr);
}
void HTMLMediaElement::BindMediaPlayerReceiver(
mojo::PendingAssociatedReceiver<media::mojom::blink::MediaPlayer>
receiver) {
media_player_receiver_set_->Value().Add(
std::move(receiver),
GetDocument().GetTaskRunner(TaskType::kInternalMedia));
}
void HTMLMediaElement::Trace(Visitor* visitor) const {
visitor->Trace(audio_source_node_);
visitor->Trace(load_timer_);
visitor->Trace(progress_event_timer_);
visitor->Trace(playback_progress_timer_);
visitor->Trace(audio_tracks_timer_);
visitor->Trace(removed_from_document_timer_);
visitor->Trace(played_time_ranges_);
visitor->Trace(async_event_queue_);
visitor->Trace(error_);
visitor->Trace(current_source_node_);
visitor->Trace(next_child_node_to_consider_);
visitor->Trace(deferred_load_timer_);
visitor->Trace(media_source_tracer_);
visitor->Trace(audio_tracks_);
visitor->Trace(video_tracks_);
visitor->Trace(cue_timeline_);
visitor->Trace(text_tracks_);
visitor->Trace(text_tracks_when_resource_selection_began_);
visitor->Trace(play_promise_resolvers_);
visitor->Trace(play_promise_resolve_list_);
visitor->Trace(play_promise_reject_list_);
visitor->Trace(audio_source_provider_);
visitor->Trace(src_object_);
visitor->Trace(autoplay_policy_);
visitor->Trace(media_controls_);
visitor->Trace(controls_list_);
visitor->Trace(lazy_load_intersection_observer_);
visitor->Trace(media_player_host_remote_);
visitor->Trace(media_player_observer_remote_set_);
visitor->Trace(media_player_receiver_set_);
Supplementable<HTMLMediaElement>::Trace(visitor);
HTMLElement::Trace(visitor);
ExecutionContextLifecycleStateObserver::Trace(visitor);
}
void HTMLMediaElement::CreatePlaceholderTracksIfNecessary() {
if (!MediaTracksEnabledInternally())
return;
// Create a placeholder audio track if the player says it has audio but it
// didn't explicitly announce the tracks.
if (HasAudio() && !audioTracks().length()) {
AddAudioTrack("audio", WebMediaPlayerClient::kAudioTrackKindMain,
"Audio Track", "", true);
}
// Create a placeholder video track if the player says it has video but it
// didn't explicitly announce the tracks.
if (HasVideo() && !videoTracks().length()) {
AddVideoTrack("video", WebMediaPlayerClient::kVideoTrackKindMain,
"Video Track", "", true);
}
}
void HTMLMediaElement::SetNetworkState(NetworkState state) {
if (network_state_ == state)
return;
network_state_ = state;
if (GetMediaControls())
GetMediaControls()->NetworkStateChanged();
}
void HTMLMediaElement::VideoWillBeDrawnToCanvas() const {
DCHECK(IsHTMLVideoElement());
UseCounter::Count(GetDocument(), WebFeature::kVideoInCanvas);
autoplay_policy_->VideoWillBeDrawnToCanvas();
}
void HTMLMediaElement::ScheduleResolvePlayPromises() {
// TODO(mlamouri): per spec, we should create a new task but we can't create
// a new cancellable task without cancelling the previous one. There are two
// approaches then: cancel the previous task and create a new one with the
// appended promise list or append the new promise to the current list. The
// latter approach is preferred because it might be the less observable
// change.
DCHECK(play_promise_resolve_list_.IsEmpty() ||
play_promise_resolve_task_handle_.IsActive());
if (play_promise_resolvers_.IsEmpty())
return;
play_promise_resolve_list_.AppendVector(play_promise_resolvers_);
play_promise_resolvers_.clear();
if (play_promise_resolve_task_handle_.IsActive())
return;
play_promise_resolve_task_handle_ = PostCancellableTask(
*GetDocument().GetTaskRunner(TaskType::kMediaElementEvent), FROM_HERE,
WTF::Bind(&HTMLMediaElement::ResolveScheduledPlayPromises,
WrapWeakPersistent(this)));
}
void HTMLMediaElement::ScheduleRejectPlayPromises(DOMExceptionCode code) {
// TODO(mlamouri): per spec, we should create a new task but we can't create
// a new cancellable task without cancelling the previous one. There are two
// approaches then: cancel the previous task and create a new one with the
// appended promise list or append the new promise to the current list. The
// latter approach is preferred because it might be the less observable
// change.
DCHECK(play_promise_reject_list_.IsEmpty() ||
play_promise_reject_task_handle_.IsActive());
if (play_promise_resolvers_.IsEmpty())
return;
play_promise_reject_list_.AppendVector(play_promise_resolvers_);
play_promise_resolvers_.clear();
if (play_promise_reject_task_handle_.IsActive())
return;
// TODO(nhiroki): Bind this error code to a cancellable task instead of a
// member field.
play_promise_error_code_ = code;
play_promise_reject_task_handle_ = PostCancellableTask(
*GetDocument().GetTaskRunner(TaskType::kMediaElementEvent), FROM_HERE,
WTF::Bind(&HTMLMediaElement::RejectScheduledPlayPromises,
WrapWeakPersistent(this)));
}
void HTMLMediaElement::ScheduleNotifyPlaying() {
ScheduleEvent(event_type_names::kPlaying);
ScheduleResolvePlayPromises();
}
void HTMLMediaElement::ResolveScheduledPlayPromises() {
for (auto& resolver : play_promise_resolve_list_)
resolver->Resolve();
play_promise_resolve_list_.clear();
}
void HTMLMediaElement::RejectScheduledPlayPromises() {
// TODO(mlamouri): the message is generated based on the code because
// arguments can't be passed to a cancellable task. In order to save space
// used by the object, the string isn't saved.
DCHECK(play_promise_error_code_ == DOMExceptionCode::kAbortError ||
play_promise_error_code_ == DOMExceptionCode::kNotSupportedError);
if (play_promise_error_code_ == DOMExceptionCode::kAbortError) {
RecordPlayPromiseRejected(PlayPromiseRejectReason::kInterruptedByPause);
RejectPlayPromisesInternal(DOMExceptionCode::kAbortError,
"The play() request was interrupted by a call "
"to pause(). https://goo.gl/LdLk22");
} else {
RecordPlayPromiseRejected(PlayPromiseRejectReason::kNoSupportedSources);
RejectPlayPromisesInternal(
DOMExceptionCode::kNotSupportedError,
"Failed to load because no supported source was found.");
}
}
void HTMLMediaElement::RejectPlayPromises(DOMExceptionCode code,
const String& message) {
play_promise_reject_list_.AppendVector(play_promise_resolvers_);
play_promise_resolvers_.clear();
RejectPlayPromisesInternal(code, message);
}
void HTMLMediaElement::RejectPlayPromisesInternal(DOMExceptionCode code,
const String& message) {
DCHECK(code == DOMExceptionCode::kAbortError ||
code == DOMExceptionCode::kNotSupportedError);
for (auto& resolver : play_promise_reject_list_)
resolver->Reject(MakeGarbageCollected<DOMException>(code, message));
play_promise_reject_list_.clear();
}
void HTMLMediaElement::OnRemovedFromDocumentTimerFired(TimerBase*) {
if (InActiveDocument())
return;
// Video should not pause when playing in Picture-in-Picture and subsequently
// removed from the Document.
if (!PictureInPictureController::IsElementInPictureInPicture(this))
PauseInternal();
}
void HTMLMediaElement::AudioSourceProviderImpl::Wrap(
scoped_refptr<WebAudioSourceProviderImpl> provider) {
MutexLocker locker(provide_input_lock);
if (web_audio_source_provider_ && provider != web_audio_source_provider_)
web_audio_source_provider_->SetClient(nullptr);
web_audio_source_provider_ = std::move(provider);
if (web_audio_source_provider_)
web_audio_source_provider_->SetClient(client_.Get());
}
void HTMLMediaElement::AudioSourceProviderImpl::SetClient(
AudioSourceProviderClient* client) {
MutexLocker locker(provide_input_lock);
if (client)
client_ = MakeGarbageCollected<HTMLMediaElement::AudioClientImpl>(client);
else
client_.Clear();
if (web_audio_source_provider_)
web_audio_source_provider_->SetClient(client_.Get());
}
void HTMLMediaElement::AudioSourceProviderImpl::ProvideInput(
AudioBus* bus,
uint32_t frames_to_process) {
DCHECK(bus);
MutexTryLocker try_locker(provide_input_lock);
if (!try_locker.Locked() || !web_audio_source_provider_ || !client_.Get()) {
bus->Zero();
return;
}
// Wrap the AudioBus channel data using WebVector.
unsigned n = bus->NumberOfChannels();
WebVector<float*> web_audio_data(n);
for (unsigned i = 0; i < n; ++i)
web_audio_data[i] = bus->Channel(i)->MutableData();
web_audio_source_provider_->ProvideInput(web_audio_data, frames_to_process);
}
void HTMLMediaElement::AudioClientImpl::SetFormat(uint32_t number_of_channels,
float sample_rate) {
if (client_)
client_->SetFormat(number_of_channels, sample_rate);
}
void HTMLMediaElement::AudioClientImpl::Trace(Visitor* visitor) const {
visitor->Trace(client_);
}
void HTMLMediaElement::AudioSourceProviderImpl::Trace(Visitor* visitor) const {
visitor->Trace(client_);
}
bool HTMLMediaElement::HasNativeControls() {
return ShouldShowControls(RecordMetricsBehavior::kDoRecord);
}
bool HTMLMediaElement::IsAudioElement() {
return IsHTMLAudioElement();
}
DisplayType HTMLMediaElement::GetDisplayType() const {
return IsFullscreen() ? DisplayType::kFullscreen : DisplayType::kInline;
}
gfx::ColorSpace HTMLMediaElement::TargetColorSpace() {
LocalFrame* frame = GetDocument().GetFrame();
if (!frame)
return gfx::ColorSpace();
return frame->GetPage()
->GetChromeClient()
.GetScreenInfo(*frame)
.display_color_spaces.GetScreenInfoColorSpace();
}
bool HTMLMediaElement::WasAutoplayInitiated() {
return autoplay_policy_->WasAutoplayInitiated();
}
void HTMLMediaElement::ResumePlayback() {
autoplay_policy_->EnsureAutoplayInitiatedSet();
PlayInternal();
}
void HTMLMediaElement::PausePlayback() {
PauseInternal();
}
void HTMLMediaElement::DidPlayerStartPlaying() {
for (auto& observer : media_player_observer_remote_set_->Value())
observer->OnMediaPlaying();
}
void HTMLMediaElement::DidPlayerPaused(bool stream_ended) {
for (auto& observer : media_player_observer_remote_set_->Value())
observer->OnMediaPaused(stream_ended);
}
void HTMLMediaElement::DidPlayerMutedStatusChange(bool muted) {
for (auto& observer : media_player_observer_remote_set_->Value())
observer->OnMutedStatusChanged(muted);
}
void HTMLMediaElement::DidMediaMetadataChange(
bool has_audio,
bool has_video,
media::MediaContentType media_content_type) {
for (auto& observer : media_player_observer_remote_set_->Value())
observer->OnMediaMetadataChanged(has_audio, has_video, media_content_type);
}
void HTMLMediaElement::DidPlayerMediaPositionStateChange(
double playback_rate,
base::TimeDelta duration,
base::TimeDelta position) {
for (auto& observer : media_player_observer_remote_set_->Value()) {
observer->OnMediaPositionStateChanged(
media_session::mojom::blink::MediaPosition::New(
playback_rate, duration, position, base::TimeTicks::Now()));
}
}
void HTMLMediaElement::DidDisableAudioOutputSinkChanges() {
for (auto& observer : media_player_observer_remote_set_->Value())
observer->OnAudioOutputSinkChangingDisabled();
}
void HTMLMediaElement::DidPlayerSizeChange(const gfx::Size& size) {
for (auto& observer : media_player_observer_remote_set_->Value())
observer->OnMediaSizeChanged(size);
}
void HTMLMediaElement::DidBufferUnderflow() {
for (auto& observer : media_player_observer_remote_set_->Value())
observer->OnBufferUnderflow();
}
void HTMLMediaElement::DidSeek() {
// Send the seek updates to the browser process only once per second.
if (last_seek_update_time_.is_null() ||
(base::TimeTicks::Now() - last_seek_update_time_ >=
base::TimeDelta::FromSeconds(1))) {
last_seek_update_time_ = base::TimeTicks::Now();
for (auto& observer : media_player_observer_remote_set_->Value())
observer->OnSeek();
}
}
media::mojom::blink::MediaPlayerHost&
HTMLMediaElement::GetMediaPlayerHostRemote() {
// It is an error to call this before having access to the document's frame.
DCHECK(GetDocument().GetFrame());
if (!media_player_host_remote_->Value().is_bound()) {
GetDocument()
.GetFrame()
->GetRemoteNavigationAssociatedInterfaces()
->GetInterface(
media_player_host_remote_->Value().BindNewEndpointAndPassReceiver(
GetDocument().GetTaskRunner(TaskType::kInternalMedia)));
}
return *media_player_host_remote_->Value().get();
}
mojo::PendingAssociatedReceiver<media::mojom::blink::MediaPlayerObserver>
HTMLMediaElement::AddMediaPlayerObserverAndPassReceiver() {
mojo::PendingAssociatedRemote<media::mojom::blink::MediaPlayerObserver>
observer;
auto observer_receiver = observer.InitWithNewEndpointAndPassReceiver();
media_player_observer_remote_set_->Value().Add(
std::move(observer),
GetDocument().GetTaskRunner(TaskType::kInternalMedia));
return observer_receiver;
}
void HTMLMediaElement::RequestPlay() {
LocalFrame* frame = GetDocument().GetFrame();
if (frame) {
LocalFrame::NotifyUserActivation(
frame, mojom::blink::UserActivationNotificationType::kInteraction);
}
autoplay_policy_->EnsureAutoplayInitiatedSet();
PlayInternal();
}
void HTMLMediaElement::RequestPause(bool triggered_by_user) {
if (triggered_by_user) {
LocalFrame* frame = GetDocument().GetFrame();
if (frame) {
LocalFrame::NotifyUserActivation(
frame, mojom::blink::UserActivationNotificationType::kInteraction);
}
}
PauseInternal();
}
void HTMLMediaElement::RequestSeekForward(base::TimeDelta seek_time) {
double seconds = seek_time.InSecondsF();
DCHECK_GE(seconds, 0) << "Attempted to seek by a negative number of seconds";
setCurrentTime(currentTime() + seconds);
}
void HTMLMediaElement::RequestSeekBackward(base::TimeDelta seek_time) {
double seconds = seek_time.InSecondsF();
DCHECK_GE(seconds, 0) << "Attempted to seek by a negative number of seconds";
setCurrentTime(currentTime() - seconds);
}
void HTMLMediaElement::RequestSeekTo(base::TimeDelta seek_time) {
setCurrentTime(seek_time.InSecondsF());
}
void HTMLMediaElement::SetVolumeMultiplier(double multiplier) {
if (web_media_player_)
web_media_player_->SetVolumeMultiplier(multiplier);
}
void HTMLMediaElement::SetPowerExperimentState(bool enabled) {
if (web_media_player_)
web_media_player_->SetPowerExperimentState(enabled);
}
void HTMLMediaElement::SetAudioSinkId(const String& sink_id) {
auto* audio_output_controller = AudioOutputDeviceController::From(*this);
DCHECK(audio_output_controller);
audio_output_controller->SetSinkId(sink_id);
}
void HTMLMediaElement::SuspendForFrameClosed() {
if (web_media_player_)
web_media_player_->SuspendForFrameClosed();
}
bool HTMLMediaElement::MediaShouldBeOpaque() const {
return !IsMediaDataCorsSameOrigin() && ready_state_ < kHaveMetadata &&
EffectivePreloadType() != WebMediaPlayer::kPreloadNone;
}
void HTMLMediaElement::SetError(MediaError* error) {
error_ = error;
if (!error || !media_source_attachment_)
return;
media_source_attachment_->OnElementError();
}
void HTMLMediaElement::ReportCurrentTimeToMediaSource() {
if (!media_source_attachment_)
return;
// See MediaSourceAttachment::OnElementTimeUpdate() for why the attachment
// needs our currentTime.
media_source_attachment_->OnElementTimeUpdate(currentTime());
}
WebMediaPlayerClient::Features HTMLMediaElement::GetFeatures() {
WebMediaPlayerClient::Features features;
features.id = FastGetAttribute(html_names::kIdAttr);
features.width = FastGetAttribute(html_names::kWidthAttr);
if (auto* parent = parentElement())
features.parent_id = parent->FastGetAttribute(html_names::kIdAttr);
features.alt_text = AltText();
features.is_page_visible = GetDocument().IsPageVisible();
features.is_in_main_frame = GetDocument().IsInMainFrame();
const KURL& url = GetDocument().Url();
features.url_host = url.Host();
features.url_path = url.GetPath();
return features;
}
STATIC_ASSERT_ENUM(WebMediaPlayer::kReadyStateHaveNothing,
HTMLMediaElement::kHaveNothing);
STATIC_ASSERT_ENUM(WebMediaPlayer::kReadyStateHaveMetadata,
HTMLMediaElement::kHaveMetadata);
STATIC_ASSERT_ENUM(WebMediaPlayer::kReadyStateHaveCurrentData,
HTMLMediaElement::kHaveCurrentData);
STATIC_ASSERT_ENUM(WebMediaPlayer::kReadyStateHaveFutureData,
HTMLMediaElement::kHaveFutureData);
STATIC_ASSERT_ENUM(WebMediaPlayer::kReadyStateHaveEnoughData,
HTMLMediaElement::kHaveEnoughData);
} // namespace blink
| 36.244312
| 96
| 0.722065
|
DamieFC
|
10523a3eaec88d2cc899f57e981f7d4acd7a9853
| 9,250
|
cpp
|
C++
|
zurch_barzer.cpp
|
barzerman/barzer
|
3211507d5ed0294ee77986f58d781a2fa4142e0d
|
[
"MIT"
] | 1
|
2018-10-22T12:53:13.000Z
|
2018-10-22T12:53:13.000Z
|
zurch_barzer.cpp
|
barzerman/barzer
|
3211507d5ed0294ee77986f58d781a2fa4142e0d
|
[
"MIT"
] | null | null | null |
zurch_barzer.cpp
|
barzerman/barzer
|
3211507d5ed0294ee77986f58d781a2fa4142e0d
|
[
"MIT"
] | null | null | null |
#include <zurch_barzer.h>
#include <zurch_docidx.h>
#include <zurch_settings.h>
/// Copyright Barzer LLC 2012
/// Code is property Barzer for authorized use only
///
////// THIS IS A TEMPLATE forcustomized XML PARSER
///// clone it into a new file and fill out the TAGS (search for XXX)
#include <iostream>
#include <vector>
#include <string>
#include <expat.h>
#include <ay_logger.h>
#include <ay_util_time.h>
#include <barzer_universe.h>
#include <zurch_docidx.h>
/// KEEP IT IN ANONYMOUS NAMESPACE
namespace {
using namespace barzer;
using namespace zurch;
const float WEIGHT_BOOST=2.0;
const float WEIGHT_IDENTITY=1.0;
const float WEIGHT_ZERO=0.0;
struct ay_xml_parser {
/// set by E tag. cleared upon close
BarzerEntity d_curEntity; // the loader is entity centric.
float d_curWeight;
BarzerEntityDocLinkIndex& d_index;
XML_ParserStruct* expat;
std::ostream& d_os;
size_t d_entCount;
// current stack of tags - see .cpp file for tag codes
std::vector< int > tagStack;
void setEntity( const StoredEntityClass& ec , const char* s, float w )
{
d_curEntity = BarzerEntity(ec,d_index.d_zurchLoader.index().storeExternalString(s));
d_curWeight = w;
}
void takeTag( const char* tag, const char** attr, size_t attr_sz, bool open=true );
void takeCData( const char* dta, size_t dta_len );
bool isCurTag( int tid ) const
{ return ( tagStack.back() == tid ); }
bool isParentTag( int tid ) const
{ return ( tagStack.size() > 1 && (*(tagStack.rbegin()+1)) == tid ); }
ay_xml_parser& init();
void parse( std::istream& fp );
~ay_xml_parser();
ay_xml_parser( BarzerEntityDocLinkIndex& idx, std::ostream& os) :
d_index(idx),
expat(0),
d_os(os),
d_entCount(0)
{ }
};
enum {
TAG_ZURCHENT, // top level tag
TAG_E, // entity (parent ZURCHENT) (c,s,i for class, subclass and id - all mandatory)
TAG_D, // doc (parent ENT) (i - mandatory)
/// add new tags above this line
TAG_INVALID, /// invalid tag
TAG_MAX=TAG_INVALID
};
/// OPEN handles
#define DECL_TAGHANDLE(X) inline int xmlth_##X( ay_xml_parser& parser, int tagId, const char* tag, const char**attr, size_t attr_sz, bool open)
/// IS_PARENT_TAG(X) (X1,X2) (X1,X2,X3) - is parent tag one of the ...
#define IS_PARENT_TAG(X) ( parser.tagStack.size() && (parser.tagStack.back()== TAG_##X) )
#define IS_PARENT_TAG2(X,Y) ( parser.tagStack.size() && (parser.tagStack.back()== TAG_##X || parser.tagStack.back()== TAG_##Y) )
#define IS_PARENT_TAG3(X,Y,Z) ( parser.tagStack.size() && (parser.tagStack.back()== TAG_##X || \
parser.tagStack.back()== TAG_##Y || parser.tagStack.back()== TAG_##Z) )
#define ALS_BEGIN {const char** attr_end = attr+ attr_sz;\
for( const char** a=attr; a< attr_end; a+=2 ) {\
const char* n = a[0];\
const char* v = a[1]; \
switch(n[0]) {
#define ALS_END }}}
enum {
TAGHANDLE_ERROR_OK,
TAGHANDLE_ERROR_PARENT, // wrong parent
TAGHANDLE_ERROR_ENTITY, // misplaced entity
};
////////// TAG HANDLES
DECL_TAGHANDLE(ZURCHENT) {
return TAGHANDLE_ERROR_OK;
}
DECL_TAGHANDLE(E) {
if( !IS_PARENT_TAG(ZURCHENT) )
return TAGHANDLE_ERROR_PARENT;
StoredEntityClass eclass;
std::string idStr;
// float weight= WEIGHT_BOOST;
float weight= WEIGHT_IDENTITY;
if( open ) {
/// loops over all atributes
ALS_BEGIN
case 'c': eclass.ec = atoi(v); break;
case 's': eclass.subclass = atoi(v); break;
case 'i': {
idStr.assign(v);
}
break;
case 'w': {
weight = atof(v);
break;
}
ALS_END
if( !idStr.empty() && eclass.isValid() )
parser.setEntity(eclass,idStr.c_str(),weight);
} else { // closing E - time to process
}
return TAGHANDLE_ERROR_OK;
}
DECL_TAGHANDLE(D) {
if( !IS_PARENT_TAG(E) )
return TAGHANDLE_ERROR_PARENT;
std::string docStr;
float weight = WEIGHT_BOOST;
if( open ) {
/// loops over all atributes
ALS_BEGIN
case 'i': {
docStr.assign(v);
}
case 'w': {
weight = atof(v);
break;
}
break;
ALS_END
if( parser.d_curEntity.isValid() )
parser.d_index.addLink( parser.d_curEntity, docStr, weight );
} else { // closing D - time to process
if( ! ((++parser.d_entCount)%100) ) {
std::cerr << ".";
}
}
return TAGHANDLE_ERROR_OK;
}
////////// DEFINE SPECIFIC TAG HANDLES ABOVE (SEE DECL_TAGHANDLE(XXX) )
#define SETTAG(X) (handler=((tagId=TAG_##X),xmlth_##X))
inline void tagRouter( ay_xml_parser& parser, const char* t, const char** attr, size_t attr_sz, bool open)
{
char c0= toupper(t[0]),c1=(c0?toupper(t[1]):0),c2=(c1?toupper(t[2]):0),c3=(c2? toupper(t[3]):0);
typedef int (*TAGHANDLE)( ay_xml_parser& , int , const char* , const char**, size_t, bool );
TAGHANDLE handler = 0;
int tagId = TAG_INVALID;
switch( c0 ) {
case 'D': SETTAG(D); break;
case 'E': SETTAG(E); break;
case 'Z': SETTAG(ZURCHENT); break;
}
if( tagId != TAG_INVALID ) {
if( !open ) { /// closing tag
if( parser.tagStack.size() ) {
parser.tagStack.pop_back();
} else {
// maybe we will report an error (however silent non reporting is safer)
}
}
if( handler )
handler(parser,tagId,t,attr,attr_sz,open);
if( open ) {
parser.tagStack.push_back( tagId );
}
}
}
void ay_xml_parser::takeTag( const char* tag, const char** attr, size_t attr_sz, bool open)
{ tagRouter(*this,tag,attr,attr_sz,open); }
void ay_xml_parser::takeCData( const char* dta, size_t dta_len )
{
/// if it's in your power enforce no CData in the schema
}
extern "C" {
// cast to XML_StartElementHandler
static void startElement(void* ud, const XML_Char *n, const XML_Char **a)
{
const char* name = (const char*)n;
const char** atts = (const char**)a;
ay_xml_parser *parser =(ay_xml_parser *)ud;
int attrCount = XML_GetSpecifiedAttributeCount( parser->expat );
if( attrCount <=0 || (attrCount & 1) )
attrCount = 0; // odd number of attributes is invalid
parser->takeTag( name, atts, attrCount );
}
// cast to XML_EndElementHandler
static void endElement(void *ud, const XML_Char *n)
{
const char *name = (const char*) n;
ay_xml_parser *parser =(ay_xml_parser *)ud;
parser->takeTag(name, 0,0,false);
}
// cast to XML_CharacterDataHandler
static void charDataHandle( void * ud, const XML_Char *str, int len)
{
if( !len )
return;
const char* s = (const char*)str;
ay_xml_parser *parser =(ay_xml_parser *)ud;
if( len>1 || !isspace(*s) )
parser->takeCData( s, len );
}
} // extern "C" ends
ay_xml_parser& ay_xml_parser::init()
{
if( !expat )
expat= XML_ParserCreate(NULL);
else
XML_ParserReset(expat,0);
XML_SetUserData(expat,this);
XML_SetElementHandler(expat, startElement, endElement);
XML_SetCharacterDataHandler(expat, charDataHandle);
return *this;
}
ay_xml_parser::~ay_xml_parser()
{
if(expat)
XML_ParserFree(expat);
}
void ay_xml_parser::parse( std::istream& fp )
{
if(!expat) {
AYLOG(ERROR) << "invalid expat instance\n";
}
char buf[ 1024*1024 ];
bool done = false;
const size_t buf_len = sizeof(buf)-1;
do {
fp.read( buf,buf_len );
size_t len = fp.gcount();
done = len < buf_len;
if (!XML_Parse(expat, buf, len, done)) {
fprintf(stderr, "%s at line %d\n", XML_ErrorString(XML_GetErrorCode(expat)), (int)XML_GetCurrentLineNumber(expat));
return;
}
} while (!done);
}
} // anon
namespace zurch {
void BarzerEntityDocLinkIndex::addLink( const BarzerEntity& ent, uint32_t docId, float w )
{
d_zurchLoader.index().appendOwnedEntity( docId, ent, (w*d_zurchLoader.getCurrentWeight()) );
m_doc2linkedEnts[docId].push_back( { d_zurchLoader.index().getOwnedEntId(ent),w });
}
void BarzerEntityDocLinkIndex::addLink( const BarzerEntity& ent, const std::string& s, float w )
{
uint32_t docId = d_zurchLoader.addDocName( s.c_str() );
addLink(ent, docId, w );
}
const std::vector<BarzerEntityDocLinkIndex::DocIdData>* BarzerEntityDocLinkIndex::getLinkedEnts(uint32_t docId) const
{
const auto pos = m_doc2linkedEnts.find(docId);
return pos == m_doc2linkedEnts.end() ? nullptr : &pos->second;
}
int BarzerEntityDocLinkIndex::loadFromFile( const std::string& fname )
{
ay::stopwatch timer;
std::fstream fp;
std::cerr << "loading zurch entity document links from " << fname << " ";
fp.open( fname.c_str() );
if( !fp.is_open() )
std::cerr << "Cant load " << fname << std::endl;
ay_xml_parser parser( *this, std::cerr );
parser.init().parse( fp );
std::cerr << parser.d_entCount << " links created " << " in " << timer.calcTime() << " seconds " << std::endl;
return 0;
}
} // namepace zurch
| 29.742765
| 143
| 0.617189
|
barzerman
|
10535a22ff7c6548667fedb088a3596c5bb22ef7
| 787
|
cpp
|
C++
|
windows/advcore/gdiplus/test/functest/chalfpixel.cpp
|
npocmaka/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 17
|
2020-11-13T13:42:52.000Z
|
2021-09-16T09:13:13.000Z
|
windows/advcore/gdiplus/test/functest/chalfpixel.cpp
|
sancho1952007/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 2
|
2020-10-19T08:02:06.000Z
|
2020-10-19T08:23:18.000Z
|
windows/advcore/gdiplus/test/functest/chalfpixel.cpp
|
sancho1952007/Windows-Server-2003
|
5c6fe3db626b63a384230a1aa6b92ac416b0765f
|
[
"Unlicense"
] | 14
|
2020-11-14T09:43:20.000Z
|
2021-08-28T08:59:57.000Z
|
/******************************Module*Header*******************************\
* Module Name: CAntialias.cpp
*
* This file contains the code to support the functionality test harness
* for GDI+. This includes menu options and calling the appropriate
* functions for execution.
*
* Created: 05-May-2000 - Jeff Vezina [t-jfvez]
*
* Copyright (c) 2000 Microsoft Corporation
*
\**************************************************************************/
#include "CHalfPixel.h"
CHalfPixel::CHalfPixel(BOOL bRegression)
{
strcpy(m_szName,"Half Pixel Offset");
m_bRegression=bRegression;
}
CHalfPixel::~CHalfPixel()
{
}
void CHalfPixel::Set(Graphics *g)
{
g->SetPixelOffsetMode(
m_bUseSetting ? PixelOffsetModeHalf : PixelOffsetModeNone
);
}
| 25.387097
| 77
| 0.579416
|
npocmaka
|
105390b9e6ff92441f266aad23094bdf083e5570
| 9,997
|
cpp
|
C++
|
winsdkfb-master/samples/SDKCppUnit/SDKCppUnit.Shared/TestRunner.cpp
|
NestedWorld/NestedWorld-Windows-10
|
96e9e8d8b97199bc1d9ce3f8cd5133e63db513a5
|
[
"MIT"
] | null | null | null |
winsdkfb-master/samples/SDKCppUnit/SDKCppUnit.Shared/TestRunner.cpp
|
NestedWorld/NestedWorld-Windows-10
|
96e9e8d8b97199bc1d9ce3f8cd5133e63db513a5
|
[
"MIT"
] | null | null | null |
winsdkfb-master/samples/SDKCppUnit/SDKCppUnit.Shared/TestRunner.cpp
|
NestedWorld/NestedWorld-Windows-10
|
96e9e8d8b97199bc1d9ce3f8cd5133e63db513a5
|
[
"MIT"
] | null | null | null |
//******************************************************************************
//
// Copyright (c) 2015 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// 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.
//
//******************************************************************************
//
// TestRunner.cpp
// Implementation of the TestRunner class.
//
#include "pch.h"
#include "SDKCppUnitStrings.h"
#include "TestContext.h"
#include "TestPhoto.h"
#include "TestRunner.h"
#include <vector>
using namespace SDKCppUnit;
using namespace concurrency;
using namespace Facebook;
using namespace Facebook::Graph;
using namespace Platform;
using namespace Platform::Collections;
using namespace std;
using namespace Windows::ApplicationModel::Core;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::Storage;
using namespace Windows::Storage::Streams;
using namespace Windows::Web::Http;
using namespace Windows::Web::Http::Filters;
const int FBDeleteOpenGraphUserErrorCode = 2904;
TestRunner::TestRunner()
{
}
void TestRunner::RunAllTests()
{
NotifyTestSuiteStarted(GraphAPISuite);
NotifyTestCaseStarted(CreateAppTokenTest);
create_task(TestCreateAppToken())
.then([=](bool TestResult)
{
NotifyTestCaseCompleted(CreateAppTokenTest, TestResult);
})
.then([=]() -> task<bool>
{
NotifyTestCaseStarted(CreateTestUserTest);
return TestCreateTestUser();
})
.then([=](bool TestResult)
{
NotifyTestCaseCompleted(CreateTestUserTest, TestResult);
})
.then([=]() -> task < bool >
{
NotifyTestCaseStarted(DeleteAllTestUsersTest);
return TestDeleteAllTestUsers();
})
.then([=](bool TestResult)
{
NotifyTestCaseCompleted(DeleteAllTestUsersTest, TestResult);
})
.then([=]() -> task < bool >
{
NotifyTestCaseStarted(UploadPhotoTest);
return TestUploadPhoto();
})
.then([=](bool TestResult)
{
NotifyTestCaseCompleted(UploadPhotoTest, TestResult);
NotifyTestSuiteCompleted(GraphAPISuite);
});
}
task<bool> TestRunner::TestCreateAppToken(
)
{
TestContext* ctx = TestContext::Get();
return ctx->GetAppToken();
}
task<bool> TestRunner::TestCreateTestUser(
)
{
TestContext* ctx = TestContext::Get();
return ctx->GetAppToken()
.then([this, ctx](bool result) -> task<FBResult^>
{
if (!result)
{
throw ref new InvalidArgumentException(TestAppErrorNoToken);
}
return ctx->CreateTestUser(nullptr);
})
.then([=](FBResult^ result) -> bool
{
return (result && result->Succeeded);
});
}
task<bool> TestRunner::TestDeleteAllTestUsers(
)
{
TestContext* ctx = TestContext::Get();
return ctx->GetAppToken()
.then([=](bool gotToken) -> task<FBResult^>
{
if (!gotToken)
{
throw ref new InvalidArgumentException(TestAppErrorNoToken);
}
return ctx->CreateTestUser(nullptr);
})
.then([=](FBResult^ result) -> task<bool>
{
if (result->Succeeded)
{
return ctx->GetTestUsers();
}
else
{
return create_task([]()
{
return false;
});
}
})
.then([=](bool gotTestUsers) -> vector<task<FBResult^>>
{
vector<task<FBResult^>> deleteResults;
if (gotTestUsers)
{
IVector<TestUser^>^ users = ctx->TestUsers();
for (unsigned int i = 0; i < users->Size; i++)
{
deleteResults.push_back(ctx->DeleteTestUser(users->GetAt(i)));
}
}
return deleteResults;
})
.then([=](vector<task<FBResult^>> results) -> bool
{
bool success = true;
if (results.size() == 0)
{
success = false;
}
for (unsigned int i = 0; i < results.size(); i++)
{
FBResult^ deleteResult = results.at(i).get();
if (!deleteResult->Succeeded)
{
if (deleteResult->ErrorInfo->Code !=
FBDeleteOpenGraphUserErrorCode)
{
success = false;
}
}
}
return success;
});
}
IAsyncOperation<IRandomAccessStreamWithContentType^>^
TestRunner::GetStreamOnFileAsync(
String^ path
)
{
return create_async([=]()
{
StorageFolder^ appFolder =
Windows::ApplicationModel::Package::Current->InstalledLocation;
return create_task(appFolder->GetFileAsync(FBTestImagePath))
.then([=](StorageFile^ file) -> IAsyncOperation<IRandomAccessStreamWithContentType^>^
{
if (file)
{
return file->OpenReadAsync();
}
else
{
return create_async([]()
{
return (IRandomAccessStreamWithContentType^)nullptr;
});
}
});
});
}
IAsyncOperation<FBResult^>^ TestRunner::UploadPhotoFromStreamAsync(
String^ Path,
IRandomAccessStreamWithContentType^ Stream,
PropertySet^ Parameters
)
{
if (Stream)
{
FBMediaStream^ streamWrapper = ref new FBMediaStream(FBTestImageName,
Stream);
Parameters->Insert(SourceParameterKey, streamWrapper);
FBSingleValue^ sval = ref new FBSingleValue(Path, Parameters,
ref new FBJsonClassFactory(TestPhoto::FromJson));
return sval->PostAsync();
}
else
{
return create_async([]()
{
return (FBResult^)nullptr;
});
}
}
IAsyncOperation<FBResult^>^ TestRunner::GetExtendedPhotoInfoForAsync(
FBResult^ Result,
PropertySet^ Parameters
)
{
IAsyncOperation<FBResult^>^ op = nullptr;
if (Result->Succeeded)
{
TestPhoto^ photo = static_cast<TestPhoto^>(Result->Object);
String^ path = L"/" + photo->Id;
FBSingleValue^ sval = ref new FBSingleValue(path, Parameters,
ref new FBJsonClassFactory(TestPhoto::FromJson));
op = sval->GetAsync();
}
return op;
}
task<bool> TestRunner::TestUploadPhoto(
)
{
TestContext* ctx = TestContext::Get();
PropertySet^ parameters = ref new PropertySet();
FBSession^ sess = FBSession::ActiveSession;
String^ graphPath = sess->FBAppId + FBSDKTestUsersPath;
return ctx->GetAppToken()
.then([=](bool gotToken) -> task<FBResult^>
{
if (!gotToken)
{
throw ref new InvalidArgumentException(TestAppErrorNoToken);
}
parameters->Insert(L"permissions",
L"public_profile,publish_actions,user_photos");
return ctx->CreateTestUser(parameters);
})
.then([=](FBResult^ result) -> IAsyncOperation<IRandomAccessStreamWithContentType^>^
{
IAsyncOperation<IRandomAccessStreamWithContentType^>^ op = nullptr;
parameters->Clear();
if (result->Succeeded)
{
TestUser^ user = static_cast<TestUser^>(result->Object);
String^ path = "/" + user->Id + "/photos";
parameters->Insert(AccessTokenParameterKey, user->AccessToken);
parameters->Insert(PathParameterKey, path);
StorageFolder^ appFolder =
Windows::ApplicationModel::Package::Current->InstalledLocation;
op = GetStreamOnFileAsync(FBTestImagePath);
}
return op;
})
.then([=](IRandomAccessStreamWithContentType^ stream) -> IAsyncOperation<FBResult^>^
{
String^ path =
static_cast<String^>(parameters->Lookup(PathParameterKey));
parameters->Remove(PathParameterKey);
return UploadPhotoFromStreamAsync(path, stream, parameters);
})
.then([=](FBResult^ result) -> IAsyncOperation<FBResult^>^
{
return GetExtendedPhotoInfoForAsync(result, parameters);
})
.then([=](FBResult^ result) -> bool
{
return result->Succeeded;
});
}
void TestRunner::NotifyTestSuiteStarted(
String^ SuiteName
)
{
CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(
Windows::UI::Core::CoreDispatcherPriority::Normal,
ref new Windows::UI::Core::DispatchedHandler([this, SuiteName]()
{
TestSuiteStarted(SuiteName);
}));
}
void TestRunner::NotifyTestSuiteCompleted(
Platform::String^ SuiteName
)
{
CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(
Windows::UI::Core::CoreDispatcherPriority::Normal,
ref new Windows::UI::Core::DispatchedHandler([this, SuiteName]()
{
TestSuiteCompleted(SuiteName);
}));
}
void TestRunner::NotifyTestCaseStarted(
Platform::String^ CaseName
)
{
CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(
Windows::UI::Core::CoreDispatcherPriority::Normal,
ref new Windows::UI::Core::DispatchedHandler([this, CaseName]()
{
TestCaseStarted(CaseName);
}));
}
void TestRunner::NotifyTestCaseCompleted(
Platform::String^ CaseName,
bool TestResult
)
{
CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(
Windows::UI::Core::CoreDispatcherPriority::Normal,
ref new Windows::UI::Core::DispatchedHandler(
[this, CaseName, TestResult]()
{
TestCaseCompleted(CaseName, TestResult);
}));
}
| 26.946092
| 93
| 0.607582
|
NestedWorld
|
1054666e5dc6a9be623b69119f9add414b7ad7d6
| 3,498
|
cpp
|
C++
|
src/src/fractals/julia/Julia.cpp
|
migregal/bmstu_iu7_cg_course
|
8ec2bb5c319328d9b0de307c1a8236b6b5188136
|
[
"MIT"
] | null | null | null |
src/src/fractals/julia/Julia.cpp
|
migregal/bmstu_iu7_cg_course
|
8ec2bb5c319328d9b0de307c1a8236b6b5188136
|
[
"MIT"
] | null | null | null |
src/src/fractals/julia/Julia.cpp
|
migregal/bmstu_iu7_cg_course
|
8ec2bb5c319328d9b0de307c1a8236b6b5188136
|
[
"MIT"
] | null | null | null |
#include <fractals/julia/Julia.h>
#include <algorithm>
#include <cmath>
#include <math/Vector.h>
#include <QDebug>
#define MAX_RAYCAST_STEP 128
namespace CGCP::fractal {
float JuliaParametrized::raycast(
math::Vector3 const &ro,
math::Vector3 const &rd,
math::Vector4 &rescol,
float fov,
math::Vector3 const &c) {
float res = -1.0;
auto dis = bounder_->intersect(ro, rd);
if (dis.y() < 0.0) return -1.0;
dis.setX(std::max(dis.x(), 0.0f));
// raymarch fractal distance field
math::Vector4 trap;
float fovfactor = 1.0 / sqrt(1.0 + fov * fov);
float t = dis.x();
for (int i = 0; i < MAX_RAYCAST_STEP; i++) {
auto pos = ro + rd * t;
float surface = std::clamp(1e-3f * t * fovfactor, 1e-4f, 0.1f);
float dt = map(pos, c, trap);
if (t > dis.y() || dt < surface) break;
t += std::min(dt, 5e-2f);
}
if (t < dis.y()) {
rescol = trap;
res = t;
}
return res;
}
math::Vector3 JuliaParametrized::calcNormal(math::Vector3 &pos,
float t,
float fovfactor,
const math::Vector3 &c) {
math::Vector4 tmp;
float surface = std::clamp(5e-4f * t * fovfactor, 0.0f, 0.1f);
auto eps = math::Vector2(surface, 0.0);
auto e_xyy = math::Vector3(eps.x(), eps.y(), eps.y()),
e_yyx = math::Vector3(eps.y(), eps.y(), eps.x()),
e_yxy = math::Vector3(eps.y(), eps.x(), eps.y()),
e_xxx = math::Vector3(eps.x(), eps.x(), eps.x());
return math::Vector3(
map(pos + e_xyy, c, tmp) - map(pos - e_xyy, c, tmp),
map(pos + e_yxy, c, tmp) - map(pos - e_yxy, c, tmp),
map(pos + e_yyx, c, tmp) - map(pos - e_yyx, c, tmp))
.normalized();
}
float JuliaParametrized::map(const math::Vector3 &p, const math::Vector3 &c, math::Vector4 &resColor) {
math::Vector3 z = p;
float m = math::Vector3::dotProduct(z, z);
auto trap = math::Vector4(std::abs(z.x()), std::abs(z.y()), std::abs(z.z()), m);
float dz = 1.0;
for (int i = 0; i < 4; i++) {
// dz = 8*z^7*dz
dz = 8.0 * std::pow(m, 3.5) * dz;
// z = z^8+z
float r = z.length();
float b = 8.0 * std::acos(std::clamp(z.y() / r, -1.0f, 1.0f));
float a = 8.0 * std::atan2(z.x(), z.z());
z = c + std::pow(r, 8.0) *
math::Vector3(std::sin(b) * std::sin(a),
std::cos(b),
std::sin(b) * std::cos(a));
trap.setX(std::min(trap.x(), std::abs(z.x())));
trap.setY(std::min(trap.y(), std::abs(z.y())));
trap.setZ(std::min(trap.z(), std::abs(z.z())));
trap.setZ(std::min(trap.w(), m));
m = math::Vector3::dotProduct(z, z);
if (m > 2.0)
break;
}
// resColor = math::Vector4(m, trap.y(), trap.z(), trap.w());
resColor = trap;
// distance estimation (through the Hubbard-Douady potential)
return 0.25 * log(m) * sqrt(m) / dz;
}
}// namespace CGCP::fractal
| 33.314286
| 107
| 0.445969
|
migregal
|
1054d6d9d8f0cb216d372576bf8147d76d19b906
| 3,646
|
cpp
|
C++
|
kernel/node/Directory.cpp
|
busybox11/skift
|
778ae3a0dc5ac29d7de02200c49d3533e47854c5
|
[
"MIT"
] | 2
|
2020-07-14T21:16:54.000Z
|
2020-10-08T08:40:47.000Z
|
kernel/node/Directory.cpp
|
busybox11/skift
|
778ae3a0dc5ac29d7de02200c49d3533e47854c5
|
[
"MIT"
] | null | null | null |
kernel/node/Directory.cpp
|
busybox11/skift
|
778ae3a0dc5ac29d7de02200c49d3533e47854c5
|
[
"MIT"
] | null | null | null |
#include <libsystem/Logger.h>
#include <libsystem/Result.h>
#include <libsystem/core/CString.h>
#include "kernel/node/Directory.h"
#include "kernel/node/Handle.h"
static Result directory_open(FsDirectory *node, FsHandle *handle)
{
DirectoryListing *listing = (DirectoryListing *)malloc(sizeof(DirectoryListing) + sizeof(DirectoryEntry) * node->childs->count());
listing->count = node->childs->count();
int current_index = 0;
list_foreach(FsDirectoryEntry, entry, node->childs)
{
DirectoryEntry *record = &listing->entries[current_index];
FsNode *node = entry->node;
strcpy(record->name, entry->name);
record->stat.type = node->type;
if (node->size)
{
record->stat.size = node->size(entry->node, nullptr);
}
else
{
record->stat.size = 0;
}
current_index++;
};
handle->attached = listing;
return SUCCESS;
}
static void directory_close(FsDirectory *node, FsHandle *handle)
{
__unused(node);
free(handle->attached);
}
static Result directory_read(FsDirectory *node, FsHandle *handle, void *buffer, uint size, size_t *read)
{
__unused(node);
// FIXME: directories should no be read using read().
if (size == sizeof(DirectoryEntry))
{
size_t index = handle->offset / sizeof(DirectoryEntry);
DirectoryListing *listing = (DirectoryListing *)handle->attached;
if (index < listing->count)
{
*((DirectoryEntry *)buffer) = listing->entries[index];
*read = sizeof(DirectoryEntry);
}
}
return SUCCESS;
}
static FsNode *directory_find(FsDirectory *node, const char *name)
{
list_foreach(FsDirectoryEntry, entry, node->childs)
{
if (strcmp(entry->name, name) == 0)
{
return fsnode_ref(entry->node);
}
};
return nullptr;
}
static Result directory_link(FsDirectory *node, const char *name, FsNode *child)
{
list_foreach(FsDirectoryEntry, entry, node->childs)
{
if (strcmp(entry->name, name) == 0)
{
return ERR_FILE_EXISTS;
}
};
FsDirectoryEntry *new_entry = __create(FsDirectoryEntry);
new_entry->node = fsnode_ref(child);
strcpy(new_entry->name, name);
list_pushback(node->childs, new_entry);
return SUCCESS;
}
static void directory_entry_destroy(FsDirectoryEntry *entry)
{
fsnode_deref(entry->node);
free(entry);
}
static Result directory_unlink(FsDirectory *node, const char *name)
{
list_foreach(FsDirectoryEntry, entry, node->childs)
{
if (strcmp(entry->name, name) == 0)
{
list_remove(node->childs, entry);
directory_entry_destroy(entry);
return SUCCESS;
}
}
return ERR_NO_SUCH_FILE_OR_DIRECTORY;
}
static void directory_destroy(FsDirectory *node)
{
list_destroy_with_callback(node->childs, (ListDestroyElementCallback)directory_entry_destroy);
}
FsNode *directory_create()
{
FsDirectory *directory = __create(FsDirectory);
fsnode_init(directory, FILE_TYPE_DIRECTORY);
directory->open = (FsNodeOpenCallback)directory_open;
directory->close = (FsNodeCloseCallback)directory_close;
directory->read = (FsNodeReadCallback)directory_read;
directory->find = (FsNodeFindCallback)directory_find;
directory->link = (FsNodeLinkCallback)directory_link;
directory->unlink = (FsNodeUnlinkCallback)directory_unlink;
directory->destroy = (FsNodeDestroyCallback)directory_destroy;
directory->childs = list_create();
return (FsNode *)directory;
}
| 24.469799
| 134
| 0.657707
|
busybox11
|
10550b46ecac278de7d8e133f356940e447e8b84
| 3,291
|
cc
|
C++
|
FWCore/Framework/src/HCTypeTag.cc
|
ckamtsikis/cmssw
|
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
|
[
"Apache-2.0"
] | 852
|
2015-01-11T21:03:51.000Z
|
2022-03-25T21:14:00.000Z
|
FWCore/Framework/src/HCTypeTag.cc
|
ckamtsikis/cmssw
|
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
|
[
"Apache-2.0"
] | 30,371
|
2015-01-02T00:14:40.000Z
|
2022-03-31T23:26:05.000Z
|
FWCore/Framework/src/HCTypeTag.cc
|
ckamtsikis/cmssw
|
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
|
[
"Apache-2.0"
] | 3,240
|
2015-01-02T05:53:18.000Z
|
2022-03-31T17:24:21.000Z
|
#ifndef Framework_HCTypeTag_icc
#define Framework_HCTypeTag_icc
// -*- C++ -*-
//
// Package: HeteroContainer
// Module: HCTypeTag
//
// Description: <one line class summary>
//
// Implementation:
// <Notes on implementation>
//
// Author: Chris D. Jones
// Created: Sun Sep 20 15:27:25 EDT 1998
//
// Revision history
//
// $Log: HCTypeTag.cc,v $
// Revision 1.2 2010/01/23 02:03:42 chrjones
// moved type lookup used by EventSetup to FWCore/Utilities to avoid unneeded external dependencies from FWCore/Framework
//
// Revision 1.1 2010/01/15 20:35:49 chrjones
// Changed type identifier for the EventSetup to no longer be a template
//
// Revision 1.6 2005/11/11 20:55:54 chrjones
// use new TypeIDBase for basis of all type comparisons
//
// Revision 1.5 2005/09/01 23:30:48 wmtan
// fix rule violations found by rulechecker
//
// Revision 1.4 2005/09/01 05:20:56 wmtan
// Fix Rules violations found by RuleChecker
//
// Revision 1.3 2005/07/14 22:50:52 wmtan
// Rename packages
//
// Revision 1.2 2005/06/23 19:59:30 wmtan
// fix rules violations found by rulechecker
//
// Revision 1.1 2005/05/29 02:29:53 wmtan
// initial population
//
// Revision 1.2 2005/04/04 20:31:22 chrjones
// added namespace
//
// Revision 1.1 2005/03/28 15:03:30 chrjones
// first submission
//
// Revision 1.2 2000/07/25 13:42:37 cdj
// HCTypeTag can now find a TypeTag from the name of a type
//
// Revision 1.1.1.1 1998/09/23 14:13:12 cdj
// first submission
//
// system include files
#include <map>
#include <cstring>
// user include files
//#include "Logger/interface/report.h"
#include "FWCore/Framework/interface/HCTypeTag.h"
// STL classes
//
// constants, enums and typedefs
//
namespace edm {
namespace eventsetup {
namespace heterocontainer {
//
// static data member definitions
//
//
// constructors and destructor
//
//HCTypeTag::HCTypeTag()
//{
//}
// HCTypeTag::HCTypeTag(const HCTypeTag& rhs)
// {
// // do actual copying here; if you implemented
// // operator= correctly, you may be able to use just say
// *this = rhs;
// }
//HCTypeTag::~HCTypeTag()
//{
//}
//
// assignment operators
//
// const HCTypeTag& HCTypeTag::operator=(const HCTypeTag& rhs)
// {
// if(this != &rhs) {
// // do actual copying here, plus:
// // "SuperClass"::operator=(rhs);
// }
//
// return *this;
// }
//
// member functions
//
//
// const member functions
//
//
// static member functions
//
HCTypeTag HCTypeTag::findType(const std::string& iTypeName) { return HCTypeTag::findType(iTypeName.c_str()); }
HCTypeTag HCTypeTag::findType(const char* iTypeName) {
std::pair<const char*, const std::type_info*> p = typelookup::findType(iTypeName);
if (nullptr == p.second) {
return HCTypeTag();
}
//need to take name from the 'findType' since that address is guaranteed to be long lived
return HCTypeTag(*p.second, p.first);
}
} // namespace heterocontainer
} // namespace eventsetup
} // namespace edm
#endif
| 24.377778
| 121
| 0.613187
|
ckamtsikis
|
10563e7a19863fd6b7c1c62240c38c3222a06c1f
| 1,488
|
cpp
|
C++
|
src/main_collector.cpp
|
despargy/KukaImplementation-kinetic
|
3a9ab106b117acfc6478fbf3e60e49b7e94b2722
|
[
"MIT"
] | 1
|
2021-08-21T12:49:27.000Z
|
2021-08-21T12:49:27.000Z
|
src/main_collector.cpp
|
despargy/KukaImplementation-kinetic
|
3a9ab106b117acfc6478fbf3e60e49b7e94b2722
|
[
"MIT"
] | null | null | null |
src/main_collector.cpp
|
despargy/KukaImplementation-kinetic
|
3a9ab106b117acfc6478fbf3e60e49b7e94b2722
|
[
"MIT"
] | null | null | null |
#include <ros/ros.h>
#include <thread>
// #include <autharl_core/controller/gravity_compensation.h>
// #include <autharl_core/robot/robot_sim.h>
#include <autharl_core>
#include <lwr_robot/robot.h>
//
// #include <autharl_core/viz/ros_state_publisher.h>
// #include <autharl_core/robot/ros_model.h>
#include <kuka_implementation/collector.h>
int main(int argc, char** argv)
{
// Initialize the ROS node
ros::init(argc, argv, "get_desired_trajectory");
ros::NodeHandle n;
// Create the robot after you have launch the URDF on the parameter server
auto model = std::make_shared<arl::robot::ROSModel>();
// Create a simulated robot, use can use a real robot also
// auto robot = std::make_shared<arl::robot::RobotSim>(model, 1e-3);
auto robot = std::make_shared<arl::lwr::Robot>(model);
// Create a visualizater for see the result in rviz
auto rviz = std::make_shared<arl::viz::RosStatePublisher>(robot);
// Create the joint trajectory controller
// auto gravity_compensation_position = std::make_shared<arl::controller::GravityCompensation>(robot);
auto collector = std::make_shared<Collector>(robot);
std::thread rviz_thread(&arl::viz::RosStatePublisher::run, rviz);
//thread for keyboard inter
// Run the trajectory controller
collector->run();
ros::spin();
rviz_thread.join();
// // thread to collect Data
// robot->getJointPosition();
// store them by GravityX.txt , GravitY.txt GravityZ.txt under /data folder
return 0;
}
| 28.075472
| 104
| 0.719758
|
despargy
|
105733a2cf1f9575daf8c3ca8fe0d4a164591a0b
| 2,245
|
cc
|
C++
|
net/spdy/spdy_protocol_test.cc
|
iplo/Chain
|
8bc8943d66285d5258fffc41bed7c840516c4422
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 231
|
2015-01-08T09:04:44.000Z
|
2021-12-30T03:03:10.000Z
|
net/spdy/spdy_protocol_test.cc
|
JasonEric/chromium
|
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1
|
2017-02-14T21:55:58.000Z
|
2017-02-14T21:55:58.000Z
|
net/spdy/spdy_protocol_test.cc
|
JasonEric/chromium
|
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 268
|
2015-01-21T05:53:28.000Z
|
2022-03-25T22:09:01.000Z
|
// 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 "net/spdy/spdy_protocol.h"
#include <limits>
#include "base/basictypes.h"
#include "base/memory/scoped_ptr.h"
#include "net/spdy/spdy_bitmasks.h"
#include "net/spdy/spdy_framer.h"
#include "net/test/gtest_util.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
enum SpdyProtocolTestTypes {
SPDY2 = 2,
SPDY3 = 3,
};
} // namespace
namespace net {
class SpdyProtocolTest
: public ::testing::TestWithParam<SpdyProtocolTestTypes> {
protected:
virtual void SetUp() {
spdy_version_ = GetParam();
}
// Version of SPDY protocol to be used.
int spdy_version_;
};
// All tests are run with two different SPDY versions: SPDY/2 and SPDY/3.
INSTANTIATE_TEST_CASE_P(SpdyProtocolTests,
SpdyProtocolTest,
::testing::Values(SPDY2, SPDY3));
// Test our protocol constants
TEST_P(SpdyProtocolTest, ProtocolConstants) {
EXPECT_EQ(1, SYN_STREAM);
EXPECT_EQ(2, SYN_REPLY);
EXPECT_EQ(3, RST_STREAM);
EXPECT_EQ(4, SETTINGS);
EXPECT_EQ(5, NOOP);
EXPECT_EQ(6, PING);
EXPECT_EQ(7, GOAWAY);
EXPECT_EQ(8, HEADERS);
EXPECT_EQ(9, WINDOW_UPDATE);
EXPECT_EQ(10, CREDENTIAL);
EXPECT_EQ(11, BLOCKED);
EXPECT_EQ(12, PUSH_PROMISE);
EXPECT_EQ(12, LAST_CONTROL_TYPE);
EXPECT_EQ(std::numeric_limits<int32>::max(), kSpdyMaximumWindowSize);
}
class SpdyProtocolDeathTest : public SpdyProtocolTest {};
// All tests are run with two different SPDY versions: SPDY/2 and SPDY/3.
INSTANTIATE_TEST_CASE_P(SpdyProtocolDeathTests,
SpdyProtocolDeathTest,
::testing::Values(SPDY2, SPDY3));
TEST_P(SpdyProtocolDeathTest, TestSpdySettingsAndIdOutOfBounds) {
scoped_ptr<SettingsFlagsAndId> flags_and_id;
EXPECT_DFATAL(flags_and_id.reset(new SettingsFlagsAndId(1, ~0)),
"SPDY setting ID too large.");
// Make sure that we get expected values in opt mode.
if (flags_and_id.get() != NULL) {
EXPECT_EQ(1, flags_and_id->flags());
EXPECT_EQ(static_cast<SpdyPingId>(0xffffff), flags_and_id->id());
}
}
} // namespace net
| 27.716049
| 73
| 0.703786
|
iplo
|
105793bb3faf489b211eac8900a8075c54b92406
| 1,179
|
cpp
|
C++
|
SISASG/Source/genericEntity.cpp
|
Ristellise/JUMP-Sprint
|
f664270aebabec60fc527f7e875319885bc43749
|
[
"WTFPL"
] | 2
|
2019-02-12T00:34:01.000Z
|
2019-02-12T00:36:27.000Z
|
SISASG/Source/genericEntity.cpp
|
Ristellise/JUMP-Sprint
|
f664270aebabec60fc527f7e875319885bc43749
|
[
"WTFPL"
] | 22
|
2019-02-11T04:53:50.000Z
|
2019-02-27T05:38:06.000Z
|
SISASG/Source/genericEntity.cpp
|
Ristellise/JUMP-Sprint
|
f664270aebabec60fc527f7e875319885bc43749
|
[
"WTFPL"
] | null | null | null |
#include "genericEntity.h"
#include "Application.h"
genericEntity::genericEntity()
{
}
genericEntity::~genericEntity()
{
}
void genericEntity::Init(const Vector3& pos, const Vector3& target, const Vector3& up)
{
this->position = pos;
this->target = target;
view = (target - position).Normalized();
right = view.Cross(up);
right.y = 0;
right.Normalize();
this->up = right.Cross(view).Normalized();
this->size = Vector3(1.0f, 1.0f, 1.0f);
this->Boxsize = BBoxDimensions::toBBox(this->size);
}
void genericEntity::Init(const Vector3& pos, const Vector3& target, const Vector3& up, const Vector3& size)
{
this->Init(pos, target, up);
this->size = size;
}
void genericEntity::Reset()
{
position.Set(1, 0, 0);
target.Set(0, 0, 0);
up.Set(0, 1, 0);
}
void genericEntity::OnHit(entity * Ent)
{
}
void genericEntity::Update(double dt)
{
static const float ENTITY_SPEED = 20.f;
position = position + view * (float)(velocity * dt);
if (this->velocity > 0)
{
this->velocity -= (float)(1.0f * dt);
}
if (this->SoundSrc != nullptr)
{
this->SoundSrc->updatePos(&this->position);
}
}
| 21.436364
| 107
| 0.626802
|
Ristellise
|
10584bac766b71c8bedf792af1ae53c0665fe320
| 612
|
cpp
|
C++
|
src/RE/TESContainer.cpp
|
FruitsBerriesMelons123/CommonLibSSE
|
7ae21d11b9e9c86b0596fc1cfa58b6993a568125
|
[
"MIT"
] | 1
|
2020-09-25T18:18:09.000Z
|
2020-09-25T18:18:09.000Z
|
src/RE/TESContainer.cpp
|
FruitsBerriesMelons123/CommonLibSSE
|
7ae21d11b9e9c86b0596fc1cfa58b6993a568125
|
[
"MIT"
] | null | null | null |
src/RE/TESContainer.cpp
|
FruitsBerriesMelons123/CommonLibSSE
|
7ae21d11b9e9c86b0596fc1cfa58b6993a568125
|
[
"MIT"
] | 1
|
2020-10-26T19:05:05.000Z
|
2020-10-26T19:05:05.000Z
|
#include "RE/TESContainer.h"
#include "RE/FormTypes.h"
#include "RE/TESForm.h"
namespace RE
{
auto TESContainer::GetContainerObjectAt(UInt32 a_idx) const
-> std::optional<ContainerObject*>
{
if (a_idx < numContainerObjects) {
return std::make_optional(containerObjects[a_idx]);
} else {
return std::nullopt;
}
}
SInt32 TESContainer::CountObjectsInContainer(TESBoundObject* a_object) const
{
SInt32 count = 0;
ForEachContainerObject([&](ContainerObject* a_contObj)
{
if (a_contObj->obj == a_object) {
count += a_contObj->count;
}
return true;
});
return count;
}
}
| 18.545455
| 77
| 0.69281
|
FruitsBerriesMelons123
|
105bcf462092ff27827ffc0a14e2ee79ecbcb6e0
| 426
|
hpp
|
C++
|
include/3dstris/gui/widget.hpp
|
geniiii/3DStris
|
556ef42ec2e131ffd7ac92065773dbaa483d743a
|
[
"MIT"
] | null | null | null |
include/3dstris/gui/widget.hpp
|
geniiii/3DStris
|
556ef42ec2e131ffd7ac92065773dbaa483d743a
|
[
"MIT"
] | null | null | null |
include/3dstris/gui/widget.hpp
|
geniiii/3DStris
|
556ef42ec2e131ffd7ac92065773dbaa483d743a
|
[
"MIT"
] | null | null | null |
#pragma once
#include <3dstris/util.hpp>
class GUI;
class Widget {
public:
Widget(GUI& parent, const Pos pos, const WH wh);
virtual ~Widget() = default;
virtual void draw() const = 0;
virtual void update(const touchPosition touch,
const touchPosition previousTouch) = 0;
Pos getPos() const noexcept { return pos; }
WH getWH() const noexcept { return wh; }
protected:
GUI& parent;
Pos pos;
WH wh;
};
| 17.75
| 49
| 0.683099
|
geniiii
|
105c103a138ed79b39bd4eee2f74f05f80c12d92
| 3,180
|
hpp
|
C++
|
include/eve/module/core/regular/impl/reduce.hpp
|
clayne/eve
|
dc268b5db474376e1c53f5a474f5bb42b7c4cb59
|
[
"MIT"
] | null | null | null |
include/eve/module/core/regular/impl/reduce.hpp
|
clayne/eve
|
dc268b5db474376e1c53f5a474f5bb42b7c4cb59
|
[
"MIT"
] | null | null | null |
include/eve/module/core/regular/impl/reduce.hpp
|
clayne/eve
|
dc268b5db474376e1c53f5a474f5bb42b7c4cb59
|
[
"MIT"
] | null | null | null |
//==================================================================================================
/*
EVE - Expressive Vector Engine
Copyright : EVE Contributors & Maintainers
SPDX-License-Identifier: MIT
*/
//==================================================================================================
#pragma once
#include <eve/concept/vectorized.hpp>
#include <eve/detail/implementation.hpp>
#include <eve/detail/function/reduce.hpp>
#include <eve/detail/function/sum.hpp>
#include <eve/module/core/regular/swap_adjacent_groups.hpp>
#include <eve/module/core/regular/logical_and.hpp>
#include <eve/module/core/regular/logical_or.hpp>
#include <eve/module/core/regular/minimum.hpp>
#include <eve/module/core/regular/maximum.hpp>
#include <eve/module/core/regular/splat.hpp>
#include <eve/module/core/regular/plus.hpp>
#include <eve/module/core/regular/add.hpp>
#include <eve/module/core/regular/any.hpp>
#include <eve/module/core/regular/all.hpp>
namespace eve::detail
{
//================================================================================================
// Find the proper callable if optimization is doable, else return a generic call
template<typename Callable, typename Option = int>
EVE_FORCEINLINE auto find_reduction( Callable f, Option = 0) noexcept
{
if constexpr( std::same_as<Callable, callable_plus_> ) return eve::detail::sum;
else if constexpr( std::same_as<Callable, callable_add_> ) return eve::detail::sum;
else if constexpr( std::same_as<Callable, callable_min_> ) return eve::minimum;
else if constexpr( std::same_as<Callable, callable_max_> ) return eve::maximum;
else if constexpr( std::same_as<Callable, callable_logical_and_> ) return eve::all;
else if constexpr( std::same_as<Callable, callable_logical_or_> ) return eve::any;
else if constexpr( std::same_as<Option, splat_type> )
{
return [f]<typename Wide>(splat_type const&, Wide v) { return butterfly_reduction(v,f); };
}
else
{
return [f]<typename Wide>(Wide v) { return butterfly_reduction(v,f).get(0); };
}
}
template<scalar_value T, typename N, typename Callable>
EVE_FORCEINLINE auto reduce_( EVE_SUPPORTS(cpu_), splat_type const& s
, wide<T,N> v, Callable f
) noexcept
{
auto op = find_reduction(f,s);
return op(s, v);
}
template<scalar_value T, typename N, typename Callable>
EVE_FORCEINLINE auto reduce_(EVE_SUPPORTS(cpu_), wide<T,N> v, Callable f) noexcept
{
auto op = find_reduction(f);
return op(v);
}
template<scalar_value T, typename N>
EVE_FORCEINLINE auto reduce_( EVE_SUPPORTS(cpu_), splat_type const& s, wide<T,N> v ) noexcept
{
return eve::detail::sum(s, v);
}
template<scalar_value T, typename N>
EVE_FORCEINLINE auto reduce_(EVE_SUPPORTS(cpu_), wide<T,N> v) noexcept
{
return eve::detail::sum(v);
}
template<scalar_value T, typename N, typename Callable>
EVE_FORCEINLINE auto reduce_(EVE_SUPPORTS(cpu_), logical<wide<T,N>> v, Callable f) noexcept
{
auto op = find_reduction(f);
return op(v);
}
}
| 38.313253
| 100
| 0.628931
|
clayne
|
105cab27d49365dbaf757988f845fbdbf7e5449c
| 9,785
|
cc
|
C++
|
chrome/utility/importer/edge_database_reader_win.cc
|
zipated/src
|
2b8388091c71e442910a21ada3d97ae8bc1845d3
|
[
"BSD-3-Clause"
] | 2,151
|
2020-04-18T07:31:17.000Z
|
2022-03-31T08:39:18.000Z
|
chrome/utility/importer/edge_database_reader_win.cc
|
cangulcan/src
|
2b8388091c71e442910a21ada3d97ae8bc1845d3
|
[
"BSD-3-Clause"
] | 395
|
2020-04-18T08:22:18.000Z
|
2021-12-08T13:04:49.000Z
|
chrome/utility/importer/edge_database_reader_win.cc
|
cangulcan/src
|
2b8388091c71e442910a21ada3d97ae8bc1845d3
|
[
"BSD-3-Clause"
] | 338
|
2020-04-18T08:03:10.000Z
|
2022-03-29T12:33:22.000Z
|
// 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/utility/importer/edge_database_reader_win.h"
#include <windows.h>
#include <stddef.h>
#include <stdint.h>
#include <vector>
namespace {
// This is an arbitary size chosen for the database error message buffer.
const size_t kErrorMessageSize = 1024;
// This is the page size of the Edge data. It's unlikely to change.
const JET_API_PTR kEdgeDatabasePageSize = 8192;
// This is the code page value for a Unicode (UCS-2) column.
const unsigned short kJetUnicodeCodePage = 1200;
template <typename T>
bool ValidateAndConvertValueGeneric(const JET_COLTYP match_column_type,
const JET_COLTYP column_type,
const std::vector<uint8_t>& column_data,
T* value) {
if ((column_type == match_column_type) && (column_data.size() == sizeof(T))) {
memcpy(value, &column_data[0], sizeof(T));
return true;
}
return false;
}
bool ValidateAndConvertValue(const JET_COLTYP column_type,
const std::vector<uint8_t>& column_data,
bool* value) {
if ((column_type == JET_coltypBit) && (column_data.size() == 1)) {
*value = (column_data[0] & 1) == 1;
return true;
}
return false;
}
bool ValidateAndConvertValue(const JET_COLTYP column_type,
const std::vector<uint8_t>& column_data,
base::string16* value) {
if ((column_type == JET_coltypLongText) &&
((column_data.size() % sizeof(base::char16)) == 0)) {
base::string16& value_ref = *value;
size_t char_length = column_data.size() / sizeof(base::char16);
value_ref.resize(char_length);
memcpy(&value_ref[0], &column_data[0], column_data.size());
// Remove any trailing NUL characters.
while (char_length > 0) {
if (value_ref[char_length - 1])
break;
char_length--;
}
value_ref.resize(char_length);
return true;
}
return false;
}
bool ValidateAndConvertValue(const JET_COLTYP column_type,
const std::vector<uint8_t>& column_data,
GUID* value) {
return ValidateAndConvertValueGeneric(JET_coltypGUID, column_type,
column_data, value);
}
bool ValidateAndConvertValue(const JET_COLTYP column_type,
const std::vector<uint8_t>& column_data,
int32_t* value) {
return ValidateAndConvertValueGeneric(JET_coltypLong, column_type,
column_data, value);
}
bool ValidateAndConvertValue(const JET_COLTYP column_type,
const std::vector<uint8_t>& column_data,
int64_t* value) {
return ValidateAndConvertValueGeneric(JET_coltypLongLong, column_type,
column_data, value);
}
bool ValidateAndConvertValue(const JET_COLTYP column_type,
const std::vector<uint8_t>& column_data,
FILETIME* value) {
return ValidateAndConvertValueGeneric(JET_coltypLongLong, column_type,
column_data, value);
}
bool ValidateAndConvertValue(const JET_COLTYP column_type,
const std::vector<uint8_t>& column_data,
uint32_t* value) {
return ValidateAndConvertValueGeneric(JET_coltypUnsignedLong, column_type,
column_data, value);
}
} // namespace
base::string16 EdgeErrorObject::GetErrorMessage() const {
WCHAR error_message[kErrorMessageSize] = {};
JET_API_PTR err = last_error_;
JET_ERR result = JetGetSystemParameter(JET_instanceNil, JET_sesidNil,
JET_paramErrorToString, &err,
error_message, sizeof(error_message));
if (result != JET_errSuccess)
return L"";
return error_message;
}
bool EdgeErrorObject::SetLastError(JET_ERR error) {
last_error_ = error;
return error == JET_errSuccess;
}
EdgeDatabaseTableEnumerator::EdgeDatabaseTableEnumerator(
const base::string16& table_name,
JET_SESID session_id,
JET_TABLEID table_id)
: table_id_(table_id), table_name_(table_name), session_id_(session_id) {}
EdgeDatabaseTableEnumerator::~EdgeDatabaseTableEnumerator() {
if (table_id_ != JET_tableidNil)
JetCloseTable(session_id_, table_id_);
}
bool EdgeDatabaseTableEnumerator::Reset() {
return SetLastError(JetMove(session_id_, table_id_, JET_MoveFirst, 0));
}
bool EdgeDatabaseTableEnumerator::Next() {
return SetLastError(JetMove(session_id_, table_id_, JET_MoveNext, 0));
}
template <typename T>
bool EdgeDatabaseTableEnumerator::RetrieveColumn(
const base::string16& column_name,
T* value) {
const JET_COLUMNBASE& column_base = GetColumnByName(column_name);
if (column_base.cbMax == 0) {
SetLastError(JET_errColumnNotFound);
return false;
}
if (column_base.coltyp == JET_coltypLongText &&
column_base.cp != kJetUnicodeCodePage) {
SetLastError(JET_errInvalidColumnType);
return false;
}
std::vector<uint8_t> column_data(column_base.cbMax);
unsigned long actual_size = 0;
JET_ERR err = JetRetrieveColumn(session_id_, table_id_, column_base.columnid,
&column_data[0], column_data.size(),
&actual_size, 0, nullptr);
SetLastError(err);
if (err != JET_errSuccess && err != JET_wrnColumnNull) {
return false;
}
if (err == JET_errSuccess) {
column_data.resize(actual_size);
if (!ValidateAndConvertValue(column_base.coltyp, column_data, value)) {
SetLastError(JET_errInvalidColumnType);
return false;
}
} else {
*value = T();
}
return true;
}
// Explicitly instantiate implementations of RetrieveColumn for various types.
template bool EdgeDatabaseTableEnumerator::RetrieveColumn(const base::string16&,
bool*);
template bool EdgeDatabaseTableEnumerator::RetrieveColumn(const base::string16&,
FILETIME*);
template bool EdgeDatabaseTableEnumerator::RetrieveColumn(const base::string16&,
GUID*);
template bool EdgeDatabaseTableEnumerator::RetrieveColumn(const base::string16&,
int32_t*);
template bool EdgeDatabaseTableEnumerator::RetrieveColumn(const base::string16&,
int64_t*);
template bool EdgeDatabaseTableEnumerator::RetrieveColumn(const base::string16&,
base::string16*);
template bool EdgeDatabaseTableEnumerator::RetrieveColumn(const base::string16&,
uint32_t*);
const JET_COLUMNBASE& EdgeDatabaseTableEnumerator::GetColumnByName(
const base::string16& column_name) {
auto found_col = columns_by_name_.find(column_name);
if (found_col == columns_by_name_.end()) {
JET_COLUMNBASE column_base = {};
column_base.cbStruct = sizeof(JET_COLUMNBASE);
if (!SetLastError(JetGetTableColumnInfo(
session_id_, table_id_, column_name.c_str(), &column_base,
sizeof(column_base), JET_ColInfoBase))) {
// 0 indicates an invalid column.
column_base.cbMax = 0;
}
columns_by_name_[column_name] = column_base;
found_col = columns_by_name_.find(column_name);
}
return found_col->second;
}
EdgeDatabaseReader::~EdgeDatabaseReader() {
// We don't need to collect other ID handles, terminating instance
// is enough to shut the entire session down.
if (instance_id_ != JET_instanceNil)
JetTerm(instance_id_);
}
bool EdgeDatabaseReader::OpenDatabase(const base::string16& database_file) {
if (IsOpen()) {
SetLastError(JET_errOneDatabasePerSession);
return false;
}
if (!SetLastError(JetSetSystemParameter(nullptr, JET_sesidNil,
JET_paramDatabasePageSize,
kEdgeDatabasePageSize, nullptr)))
return false;
if (!SetLastError(JetCreateInstance(&instance_id_, L"EdgeDataImporter")))
return false;
if (!SetLastError(JetSetSystemParameter(&instance_id_, JET_sesidNil,
JET_paramRecovery, 0, L"Off")))
return false;
if (!SetLastError(JetInit(&instance_id_)))
return false;
if (!SetLastError(
JetBeginSession(instance_id_, &session_id_, nullptr, nullptr)))
return false;
if (!SetLastError(JetAttachDatabase2(session_id_, database_file.c_str(), 0,
JET_bitDbReadOnly)))
return false;
if (!SetLastError(JetOpenDatabase(session_id_, database_file.c_str(), nullptr,
&db_id_, JET_bitDbReadOnly)))
return false;
return true;
}
std::unique_ptr<EdgeDatabaseTableEnumerator>
EdgeDatabaseReader::OpenTableEnumerator(const base::string16& table_name) {
JET_TABLEID table_id;
if (!IsOpen()) {
SetLastError(JET_errDatabaseNotFound);
return nullptr;
}
if (!SetLastError(JetOpenTable(session_id_, db_id_, table_name.c_str(),
nullptr, 0, JET_bitTableReadOnly, &table_id)))
return nullptr;
return std::make_unique<EdgeDatabaseTableEnumerator>(table_name, session_id_,
table_id);
}
| 37.490421
| 80
| 0.633112
|
zipated
|
105e8a8c8849240134205cbad4b48cc321374235
| 3,738
|
cpp
|
C++
|
src/eigensolve.cpp
|
norlab-ulaval/wmrde
|
69e1f20bedd9c145878d44dbe17b3de405696fe3
|
[
"BSD-2-Clause"
] | 18
|
2015-05-09T21:53:43.000Z
|
2021-12-01T07:52:09.000Z
|
src/eigensolve.cpp
|
norlab-ulaval/wmrde
|
69e1f20bedd9c145878d44dbe17b3de405696fe3
|
[
"BSD-2-Clause"
] | 5
|
2016-05-29T09:02:09.000Z
|
2021-05-07T16:36:38.000Z
|
src/eigensolve.cpp
|
norlab-ulaval/wmrde
|
69e1f20bedd9c145878d44dbe17b3de405696fe3
|
[
"BSD-2-Clause"
] | 11
|
2016-07-15T16:46:51.000Z
|
2022-03-14T13:11:22.000Z
|
#include <wmrde/eigensolve.h>
void eigenSolveDynamic( const int nrows, const int ncols, Real* A, Real* b, Real* x ) {
Eigen::Map<MatrixXr> A_(A,nrows,ncols);
Eigen::Map<MatrixXr> b_(b,nrows,1);
Eigen::Map<MatrixXr> x_(x,ncols,1);
if ( nrows == ncols ) {
x_ = A_.llt().solve(b_); //requires positive definite
} else {
x_ = A_.householderQr().solve(b_);
}
}
void eigenSolveFixed( const int nrows, const int ncols, Real* A, Real* b, Real* x ) {
#ifdef FIXED_NROWS_0
if (FIXED_NROWS_0 == nrows && FIXED_NCOLS_0 == ncols) {
Eigen::Map<Eigen::Matrix<Real,FIXED_NROWS_0,FIXED_NCOLS_0>> A_(A);
Eigen::Map<Eigen::Matrix<Real,FIXED_NROWS_0,1>> b_(b);
Eigen::Map<Eigen::Matrix<Real,FIXED_NCOLS_0,1>> x_(x);
#if FIXED_NROWS_0 == FIXED_NCOLS_0
x_ = A_.llt().solve(b_);
#else
x_ = A_.householderQr().solve(b_);
#endif
return;
}
#endif
#ifdef FIXED_NROWS_1
if (FIXED_NROWS_1 == nrows && FIXED_NCOLS_1 == ncols) {
Eigen::Map<Eigen::Matrix<Real,FIXED_NROWS_1,FIXED_NCOLS_1>> A_(A);
Eigen::Map<Eigen::Matrix<Real,FIXED_NROWS_1,1>> b_(b);
Eigen::Map<Eigen::Matrix<Real,FIXED_NCOLS_1,1>> x_(x);
#if FIXED_NROWS_1 == FIXED_NCOLS_1
x_ = A_.llt().solve(b_);
#else
x_ = A_.householderQr().solve(b_);
#endif
return;
}
#endif
#ifdef FIXED_NROWS_2
if (FIXED_NROWS_2 == nrows && FIXED_NCOLS_2 == ncols) {
Eigen::Map<Eigen::Matrix<Real,FIXED_NROWS_2,FIXED_NCOLS_2>> A_(A);
Eigen::Map<Eigen::Matrix<Real,FIXED_NROWS_2,1>> b_(b);
Eigen::Map<Eigen::Matrix<Real,FIXED_NCOLS_2,1>> x_(x);
#if FIXED_NROWS_2 == FIXED_NCOLS_2
x_ = A_.llt().solve(b_);
#else
x_ = A_.householderQr().solve(b_);
#endif
return;
}
#endif
#ifdef FIXED_NROWS_3
if (FIXED_NROWS_3 == nrows && FIXED_NCOLS_3 == ncols) {
Eigen::Map<Eigen::Matrix<Real,FIXED_NROWS_3,FIXED_NCOLS_3>> A_(A);
Eigen::Map<Eigen::Matrix<Real,FIXED_NROWS_3,1>> b_(b);
Eigen::Map<Eigen::Matrix<Real,FIXED_NCOLS_3,1>> x_(x);
#if FIXED_NROWS_3 == FIXED_NCOLS_3
x_ = A_.llt().solve(b_);
#else
x_ = A_.householderQr().solve(b_);
#endif
return;
}
#endif
#if PRINT_MATRIX_SIZE_IF_DYNAMIC
std::cout << "resorting to eigenSolveDynamic, nrows = " << nrows << ", ncols = " << ncols << std::endl;
#endif
eigenSolveDynamic(nrows, ncols, A, b, x); //fail safe
}
//Cholesky decomposition
bool eigenCholDynamic( const int n, Real* A, Real* L) {
Eigen::Map<MatrixXr> A_(A,n,n);
Eigen::Map<MatrixXr> L_(L,n,n);
// L_ = A_.llt().matrixL();
Eigen::LLT<MatrixXr> A_llt(A_);
L_ = A_llt.matrixL();
return A_llt.info() == Eigen::Success;
}
bool eigenCholFixed( const int n, Real* A, Real* L) {
#ifdef FIXED_N_0
if (FIXED_N_0 == n) {
Eigen::Map<Eigen::Matrix<Real,FIXED_N_0,FIXED_N_0>> A_(A);
Eigen::Map<Eigen::Matrix<Real,FIXED_N_0,FIXED_N_0>> L_(L);
// L_ = A_.llt().matrixL();
Eigen::LLT<Eigen::Matrix<Real,FIXED_N_0,FIXED_N_0>> A_llt(A_);
L_ = A_llt.matrixL();
return A_llt.info() == Eigen::Success;
}
#endif
#ifdef FIXED_N_1
if (FIXED_N_1 == n) {
Eigen::Map<Eigen::Matrix<Real,FIXED_N_1,FIXED_N_1>> A_(A);
Eigen::Map<Eigen::Matrix<Real,FIXED_N_1,FIXED_N_1>> L_(L);
// L_ = A_.llt().matrixL();
Eigen::LLT<Eigen::Matrix<Real,FIXED_N_1,FIXED_N_1>> A_llt(A_);
L_ = A_llt.matrixL();
return A_llt.info() == Eigen::Success;
}
#endif
#ifdef FIXED_N_2
if (FIXED_N_2 == n) {
Eigen::Map<Eigen::Matrix<Real,FIXED_N_2,FIXED_N_2>> A_(A);
Eigen::Map<Eigen::Matrix<Real,FIXED_N_2,FIXED_N_2>> L_(L);
// L_ = A_.llt().matrixL();
Eigen::LLT<Eigen::Matrix<Real,FIXED_N_2,FIXED_N_2>> A_llt(A_);
L_ = A_llt.matrixL();
return A_llt.info() == Eigen::Success;
}
#endif
#if PRINT_MATRIX_SIZE_IF_DYNAMIC
std::cout << "resorting to eigenCholDynamic, n = " << n << std::endl;
#endif
return eigenCholDynamic(n,A,L); //fail safe
}
| 26.892086
| 104
| 0.67603
|
norlab-ulaval
|
105eae46a93cf2dfed9c56935880b1b46319e7b6
| 827
|
cpp
|
C++
|
src/StillDataTask.cpp
|
stefunkk/openstill
|
17cc439fe9dbe7dea02588d77e51652fc1cc50ce
|
[
"MIT"
] | 1
|
2021-02-13T08:40:50.000Z
|
2021-02-13T08:40:50.000Z
|
src/StillDataTask.cpp
|
stefunkk/openstill
|
17cc439fe9dbe7dea02588d77e51652fc1cc50ce
|
[
"MIT"
] | null | null | null |
src/StillDataTask.cpp
|
stefunkk/openstill
|
17cc439fe9dbe7dea02588d77e51652fc1cc50ce
|
[
"MIT"
] | null | null | null |
#include "StillDataTask.h"
StillDataTaskClass::StillDataTaskClass(StillDataContextClass &context, FileServiceClass &fileService, SensorDataClass &data, SettingsClass &settings) : _settings(settings), _data(data), _fileService(fileService), _context(context)
{
}
void StillDataTaskClass::exec()
{
if (_context.clearCsv)
{
_fileService.removeFile(_fileName);
_context.clearCsv = false;
}
char csvEntry[100];
sprintf(csvEntry, "%i;%.2f;%.2f;%.2f;%.2f;%i; %\n", (int)(millis()/1000) ,(float)_data.shelf10, (float)_data.header, (float)_data.tank, (float)_data.water, (int)_settings.percentagePower);
_fileService.saveFile(_fileName, csvEntry);
}
uint32_t StillDataTaskClass::timeOfNextCheck()
{
setTriggered(true);
return millisToMicros(_settings.csvTimeFrameInSeconds * 1000);
}
| 33.08
| 230
| 0.729141
|
stefunkk
|
105ebb36a30368684c583ffef1020750b09a6c59
| 3,176
|
cc
|
C++
|
gazebo/rendering/Grid_TEST.cc
|
traversaro/gazebo
|
6fd426b3949c4ca73fa126cde68f5cc4a59522eb
|
[
"ECL-2.0",
"Apache-2.0"
] | 887
|
2020-04-18T08:43:06.000Z
|
2022-03-31T11:58:50.000Z
|
gazebo/rendering/Grid_TEST.cc
|
traversaro/gazebo
|
6fd426b3949c4ca73fa126cde68f5cc4a59522eb
|
[
"ECL-2.0",
"Apache-2.0"
] | 462
|
2020-04-21T21:59:19.000Z
|
2022-03-31T23:23:21.000Z
|
gazebo/rendering/Grid_TEST.cc
|
traversaro/gazebo
|
6fd426b3949c4ca73fa126cde68f5cc4a59522eb
|
[
"ECL-2.0",
"Apache-2.0"
] | 421
|
2020-04-21T09:13:03.000Z
|
2022-03-30T02:22:01.000Z
|
/*
* Copyright (C) 2016 Open Source Robotics Foundation
*
* 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 <gtest/gtest.h>
#include "gazebo/rendering/RenderingIface.hh"
#include "gazebo/rendering/Scene.hh"
#include "gazebo/rendering/Grid.hh"
#include "gazebo/test/ServerFixture.hh"
using namespace gazebo;
class Grid_TEST : public RenderingFixture
{
};
//////////////////////////////////////////////////
TEST_F(Grid_TEST, SetSize)
{
this->Load("worlds/empty.world");
auto scene = gazebo::rendering::get_scene("default");
if (!scene)
scene = gazebo::rendering::create_scene("default", false);
EXPECT_TRUE(scene != nullptr);
// Create a grid
int cellCount = 10;
float cellLength = 1;
auto grid = new gazebo::rendering::Grid(scene.get(), cellCount, cellLength,
ignition::math::Color::Red);
ASSERT_TRUE(grid != nullptr);
grid->Init();
// Get scene node and manual object
rendering::VisualPtr vis = grid->GridVisual();
ASSERT_TRUE(vis != nullptr);
auto sceneNode = vis->GetSceneNode();
ASSERT_TRUE(sceneNode != nullptr);
EXPECT_EQ(sceneNode->numAttachedObjects(), 1u);
auto manualObject = sceneNode->getAttachedObject(0);
ASSERT_TRUE(manualObject != nullptr);
// Check size
EXPECT_EQ(manualObject->getBoundingBox(),
Ogre::AxisAlignedBox(-cellCount * cellLength / 2,
-cellCount * cellLength / 2,
0.015,
cellCount * cellLength / 2,
cellCount * cellLength / 2,
0.015));
// Various sizes
std::vector<int> cellCountList = {1, 33, 100, 40};
std::vector<float> cellLengthList = {0.001, 0.4, 9.3, 1000};
for (auto count : cellCountList)
{
grid->SetCellCount(count);
for (auto length : cellLengthList)
{
grid->SetCellLength(length);
gzmsg << "Checking count [" << count << "] length [" << length << "]"
<< std::endl;
// Check size
const Ogre::AxisAlignedBox &box = manualObject->getBoundingBox();
const Ogre::Vector3 &actualMin = box.getMinimum();
const Ogre::Vector3 &actualMax = box.getMaximum();
Ogre::Vector3 expectedMin(-count * length / 2,
-count * length / 2, 0.015);
Ogre::Vector3 expectedMax(count * length / 2, count * length / 2, 0.015);
EXPECT_TRUE(actualMin.positionEquals(expectedMin));
EXPECT_TRUE(actualMax.positionEquals(expectedMax));
}
}
delete grid;
}
/////////////////////////////////////////////////
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 30.538462
| 79
| 0.628463
|
traversaro
|
105edc5729ebb32360624ec4625447ed5f1c6029
| 1,303
|
cxx
|
C++
|
VTK/Common/vtkTensor.cxx
|
certik/paraview
|
973d37b466552ce770ac0674f30040bb7e31d7fe
|
[
"BSD-3-Clause"
] | 1
|
2016-05-09T00:36:44.000Z
|
2016-05-09T00:36:44.000Z
|
VTK/Common/vtkTensor.cxx
|
certik/paraview
|
973d37b466552ce770ac0674f30040bb7e31d7fe
|
[
"BSD-3-Clause"
] | null | null | null |
VTK/Common/vtkTensor.cxx
|
certik/paraview
|
973d37b466552ce770ac0674f30040bb7e31d7fe
|
[
"BSD-3-Clause"
] | 3
|
2015-05-14T21:18:53.000Z
|
2022-03-07T02:53:45.000Z
|
/*=========================================================================
Program: Visualization Toolkit
Module: $RCSfile: vtkTensor.cxx,v $
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 "vtkTensor.h"
#include "vtkObjectFactory.h"
vtkCxxRevisionMacro(vtkTensor, "$Revision: 1.15 $");
vtkStandardNewMacro(vtkTensor);
// Construct tensor initially pointing to internal storage.
vtkTensor::vtkTensor()
{
this->T = this->Storage;
for (int j=0; j<3; j++)
{
for (int i=0; i<3; i++)
{
this->T[i+j*3] = 0.0;
}
}
}
//----------------------------------------------------------------------------
void vtkTensor::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
for (int j=0; j<3; j++)
{
os << indent;
for (int i=0; i<3; i++)
{
os << this->Storage[i+j*3] << " ";
}
os << "\n";
}
}
| 26.591837
| 78
| 0.523408
|
certik
|
105fe483961cb78caa1f8d264789e68c31b7447f
| 6,327
|
cpp
|
C++
|
src/VAC/VectorAnimationComplex/ProperCycle.cpp
|
CELLINKAB/VPaint
|
7f415b54bdaeff8b0bbd11f101d4aa34135a4404
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
src/VAC/VectorAnimationComplex/ProperCycle.cpp
|
CELLINKAB/VPaint
|
7f415b54bdaeff8b0bbd11f101d4aa34135a4404
|
[
"ECL-2.0",
"Apache-2.0"
] | 3
|
2022-01-16T22:33:35.000Z
|
2022-03-25T07:27:52.000Z
|
src/VAC/VectorAnimationComplex/ProperCycle.cpp
|
CELLINKAB/VPaint
|
7f415b54bdaeff8b0bbd11f101d4aa34135a4404
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
// Copyright (C) 2012-2019 The VPaint Developers.
// See the COPYRIGHT file at the top-level directory of this distribution
// and at https://github.com/dalboris/vpaint/blob/master/COPYRIGHT
//
// 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 "ProperCycle.h"
#include "KeyEdge.h"
#include "../SaveAndLoad.h"
#include <QMessageBox>
namespace VectorAnimationComplex
{
ProperCycle::ProperCycle()
{
// invalid by default, nothing to do (since edges_ is empty)
}
ProperCycle::ProperCycle(const KeyEdgeSet & edgeSetConst)
{
// If no edge, then invalid
if(edgeSetConst.isEmpty())
return;
// if not all edges at same time, then invalid
KeyEdge * first = *edgeSetConst.begin();
Time t = first->time();
for(KeyEdge * iedge: edgeSetConst)
{
if(iedge->time() != t)
{
//QMessageBox::information(0, QObject::tr("operation aborted"),
// QObject::tr("not all edges are on same time"));
return;
}
}
// copy the set to be able to modify it
KeyEdgeSet edgeSet = edgeSetConst;
// insert first edge
halfedges_ << KeyHalfedge(first, true);
edgeSet.erase(edgeSet.begin());
// check case where it's a pure loop
if(first->isClosed())
{
if(!edgeSet.isEmpty())
{
//QMessageBox::information(0, QObject::tr("operation aborted"),
// QObject::tr("more than one edge and one of them is a pure loop"));
halfedges_.clear();
return;
}
// else: good!
}
else
{
// not a pure loop, let's find the chain
while(!edgeSet.isEmpty())
{
KeyHalfedge lastAddedHalfedge = halfedges_.last(); // we know it's not a loop, otherwise couldn't be here
KeyVertex * lastVertex = lastAddedHalfedge.endVertex(); // hence this is a valid vertex
// find next
KeyHalfedge nextHalfedge;
auto it = edgeSet.begin();
auto itEnd = edgeSet.end();
for(;it!=itEnd;++it)
{
if((*it)->startVertex() == lastVertex)
{
nextHalfedge = KeyHalfedge(*it, true);
break;
}
else if((*it)->endVertex() == lastVertex)
{
nextHalfedge = KeyHalfedge(*it, false);
break;
}
}
// if found: great, insert it!
if(nextHalfedge.isValid())
{
halfedges_ << nextHalfedge;
edgeSet.erase(it);
}
else
{
//QMessageBox::information(0, QObject::tr("operation aborted"),
// QObject::tr("not a valid loop: no valid next edge found"));
halfedges_.clear();
return;
}
}
// So far, we've inserted all N edges, and every edge i in [0,N-2]
// satisfies edges_[i]->endVertex() == edges_[i+1]->startVertex()
// Check that it's looping
if(halfedges_.last().endVertex() != halfedges_.first().startVertex())
{
//QMessageBox::information(0, QObject::tr("operation aborted"),
// QObject::tr("not a valid loop: last edge not compatible with first one"));
halfedges_.clear();
return;
}
// Check that it's simple
KeyVertexSet vertices;
for(KeyHalfedge he: qAsConst(halfedges_))
{
KeyVertex * vertex = he.startVertex();
if(vertices.contains(vertex))
{
//QMessageBox::information(0, QObject::tr("operation aborted"),
// QObject::tr("not a valid loop: not simple"));
halfedges_.clear();
return;
}
else
{
vertices << vertex;
}
}
// Done :-) If you're here you have a valid simple loop
}
}
bool ProperCycle::isValid() const
{
return !halfedges_.isEmpty();
}
Time ProperCycle::time() const
{
return halfedges_[0].time();
}
int ProperCycle::size() const
{
return halfedges_.size();
}
KeyHalfedge ProperCycle::operator[](int i) const
{
return halfedges_[i];
}
void ProperCycle::remapPointers(VAC * newVAC)
{
for(int i=0; i<halfedges_.size(); ++i)
halfedges_[i].remapPointers(newVAC);
}
void ProperCycle::convertTempIdsToPointers(VAC * vac)
{
for(int i=0; i<halfedges_.size(); ++i)
halfedges_[i].convertTempIdsToPointers(vac);
}
// Replace pointed edges
void ProperCycle::replaceEdges(KeyEdge * oldEdge, const KeyEdgeList & newEdges)
{
QList<KeyHalfedge> newHalfedges;
for(KeyHalfedge he: qAsConst(halfedges_))
{
if(he.edge == oldEdge)
{
// Replace halfedge
if(he.side)
{
for(int i=0; i<newEdges.size(); ++i)
newHalfedges << KeyHalfedge(newEdges[i], he.side);
}
else
{
for(int i=newEdges.size()-1; i>=0; --i)
newHalfedges << KeyHalfedge(newEdges[i], he.side);
}
}
else
{
// Keep halfedge as is
newHalfedges << he;
}
}
halfedges_ = newHalfedges;
}
} // end namespace VectorAnimationComplex
QTextStream & operator<<(QTextStream & out, const VectorAnimationComplex::ProperCycle & loop)
{
out << loop.halfedges_;
return out;
}
QTextStream & operator>>(QTextStream & in, VectorAnimationComplex::ProperCycle & loop)
{
in >> loop.halfedges_;
return in;
}
| 28.245536
| 117
| 0.549708
|
CELLINKAB
|
106028bea8c96f4985efaf4ab67d71352f11a2f7
| 1,473
|
cpp
|
C++
|
SDK/ARKSurvivalEvolved_PlayerPawnTest_Male_functions.cpp
|
2bite/ARK-SDK
|
c38ca9925309516b2093ad8c3a70ed9489e1d573
|
[
"MIT"
] | 10
|
2020-02-17T19:08:46.000Z
|
2021-07-31T11:07:19.000Z
|
SDK/ARKSurvivalEvolved_PlayerPawnTest_Male_functions.cpp
|
2bite/ARK-SDK
|
c38ca9925309516b2093ad8c3a70ed9489e1d573
|
[
"MIT"
] | 9
|
2020-02-17T18:15:41.000Z
|
2021-06-06T19:17:34.000Z
|
SDK/ARKSurvivalEvolved_PlayerPawnTest_Male_functions.cpp
|
2bite/ARK-SDK
|
c38ca9925309516b2093ad8c3a70ed9489e1d573
|
[
"MIT"
] | 3
|
2020-07-22T17:42:07.000Z
|
2021-06-19T17:16:13.000Z
|
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_PlayerPawnTest_Male_parameters.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function PlayerPawnTest_Male.PlayerPawnTest_Male_C.UserConstructionScript
// ()
void APlayerPawnTest_Male_C::UserConstructionScript()
{
static auto fn = UObject::FindObject<UFunction>("Function PlayerPawnTest_Male.PlayerPawnTest_Male_C.UserConstructionScript");
APlayerPawnTest_Male_C_UserConstructionScript_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function PlayerPawnTest_Male.PlayerPawnTest_Male_C.ExecuteUbergraph_PlayerPawnTest_Male
// ()
// Parameters:
// int EntryPoint (Parm, ZeroConstructor, IsPlainOldData)
void APlayerPawnTest_Male_C::ExecuteUbergraph_PlayerPawnTest_Male(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function PlayerPawnTest_Male.PlayerPawnTest_Male_C.ExecuteUbergraph_PlayerPawnTest_Male");
APlayerPawnTest_Male_C_ExecuteUbergraph_PlayerPawnTest_Male_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 25.842105
| 140
| 0.700611
|
2bite
|
10602be24a2497a4266315d313a235479c764566
| 5,441
|
cpp
|
C++
|
l-ten/optimizer.cpp
|
adeobootpin/light-tensor
|
dfc2d19495848e773b7367427cf848e4ac30b29d
|
[
"MIT"
] | null | null | null |
l-ten/optimizer.cpp
|
adeobootpin/light-tensor
|
dfc2d19495848e773b7367427cf848e4ac30b29d
|
[
"MIT"
] | null | null | null |
l-ten/optimizer.cpp
|
adeobootpin/light-tensor
|
dfc2d19495848e773b7367427cf848e4ac30b29d
|
[
"MIT"
] | null | null | null |
#include <cmath>
#include <string.h>
#include "tensor.h"
#include "layers.h"
#include "net.h"
#include "optimizer.h"
#include "error.h"
namespace lten {
void SGDOptimizer::setup_optimizer()
{
int i;
uint64_t numels;
for (i = 0; i < num_params_; i++)
{
numels = network_params_ptr_[i].param_->get_numels();
network_params_ptr_[i].param_data_ = new Tensor;
*network_params_ptr_[i].param_data_ = AllocateTensor(network_params_ptr_[i].param_->get_sizes(), network_params_ptr_[i].param_->get_ndims(),0); // allocate buffer for momentum/velocity
memset(network_params_ptr_[i].param_data_->get_data_ptr(), 0, sizeof(float) * numels);
}
}
void SGDOptimizer::step()
{
float* weight_ptr;
float* weight_grad_ptr;
float* velocity_ptr;
int i;
uint64_t j;
uint64_t numels;
device device_type;
if (!num_params_)
{
LTEN_ERR("No parameters have been added to the optimizer");
}
device_type = network_params_ptr_[0].param_->get_device(); // key off first param
if (device_type == CPU)
{
for (i = 0; i < num_params_; i++)
{
weight_ptr = (float*)network_params_ptr_[i].param_->get_data_ptr();
weight_grad_ptr = (float*)network_params_ptr_[i].param_->get_grad_ptr();
numels = network_params_ptr_[i].param_->get_numels();
velocity_ptr = (float*)network_params_ptr_[i].param_data_->get_data_ptr();
for (j = 0; j < numels; j++)
{
weight_grad_ptr[j] = wd_ * weight_ptr[j] + weight_grad_ptr[j];
velocity_ptr[j] = velocity_ptr[j] * mo_ + (1.0f - mo_) * weight_grad_ptr[j];
weight_ptr[j] = weight_ptr[j] - (velocity_ptr[j] * lr_);
}
}
}
else
{
if (device_type == GPU)
{
#ifdef USE_CUDA
for (i = 0; i < num_params_; i++)
{
weight_ptr = (float*)network_params_ptr_[i].param_->get_data_ptr();
weight_grad_ptr = (float*)network_params_ptr_[i].param_->get_grad_ptr();
numels = network_params_ptr_[i].param_->get_numels();
velocity_ptr = (float*)network_params_ptr_[i].param_data_->get_data_ptr();
gpu_sgd_step(weight_ptr, weight_grad_ptr, velocity_ptr, numels, mo_, wd_, lr_);
}
#else
LTEN_ERR("The USE_CUDA flag was not be set during the build (this flag must be set in order to use GPU tensors)");
#endif
}
else
{
LTEN_ERR("Invalid tensor device type");
}
}
}
void AdamOptimizer::setup_optimizer()
{
int i;
uint64_t dims[MAX_DIMS];
uint64_t numels;
for (i = 0; i < num_params_; i++)
{
numels = network_params_ptr_[i].param_->get_numels();
network_params_ptr_[i].param_data_ = new Tensor;
memcpy(dims, network_params_ptr_[i].param_->get_sizes(), sizeof(uint64_t) * network_params_ptr_[i].param_->get_ndims());
dims[0] *= 3; // make room for momentum, rmsprop histories and scratch space
*network_params_ptr_[i].param_data_ = AllocateTensor(dims, network_params_ptr_[i].param_->get_ndims(), 0); // allocate history buffer
memset(network_params_ptr_[i].param_data_->get_data_ptr(), 0, sizeof(float) * numels * 3);
}
}
void AdamOptimizer::step()
{
float* weight_ptr;
float* weight_grad_ptr;
float* v_dw;
float* s_dw;
float* scratch;
float epsilon;
uint64_t numels;
int i;
device device_type;
float bias_correction1;
float bias_correction2;
if (!num_params_)
{
LTEN_ERR("No parameters have been added to the optimizer");
}
device_type = network_params_ptr_[0].param_->get_device(); // key off first param
iteration_++;
epsilon = 1.0e-8f;
for (i = 0; i < num_params_; i++)
{
weight_grad_ptr = static_cast<float*>(network_params_ptr_[i].param_->get_grad_ptr());
if (!weight_grad_ptr)
{
continue;
}
weight_ptr = static_cast<float*>(network_params_ptr_[i].param_->get_data_ptr());
numels = network_params_ptr_[i].param_->get_numels();
v_dw = static_cast<float*>(network_params_ptr_[i].param_data_->get_data_ptr());
s_dw = v_dw + (numels);
scratch = v_dw + (2 * numels);
bias_correction1 = 1.0f - powf(beta1_, static_cast<float>(iteration_));
bias_correction2 = 1.0f - powf(beta2_, static_cast<float>(iteration_));
if (device_type == CPU)
{
cpu_axpby(numels, 1.0f - beta1_, weight_grad_ptr, beta1_, v_dw, v_dw);
cpu_mul(numels, weight_grad_ptr, weight_grad_ptr, scratch);
cpu_axpby(numels, 1.0f - beta2_, scratch, beta2_, s_dw, s_dw);
cpu_mul(numels, 1.0f / bias_correction2, s_dw, scratch);
cpu_powx(numels, scratch, 0.5f, scratch);
cpu_add(numels, epsilon, scratch, scratch);
cpu_div(numels, v_dw, scratch, scratch);
cpu_axpy(numels, -(1.0f / bias_correction1) * lr_, scratch, weight_ptr, weight_ptr);
}
else
{
if (device_type == GPU)
{
#ifdef USE_CUDA
gpu_axpby(numels, 1.0f - beta1_, weight_grad_ptr, beta1_, v_dw, v_dw);
gpu_mul(numels, weight_grad_ptr, weight_grad_ptr, scratch);
gpu_axpby(numels, 1.0f - beta2_, scratch, beta2_, s_dw, s_dw);
gpu_mul(numels, 1.0f / bias_correction2, s_dw, scratch);
gpu_powx(numels, scratch, 0.5f, scratch);
gpu_add(numels, epsilon, scratch, scratch);
gpu_div(numels, v_dw, scratch, scratch);
gpu_axpy(numels, -(1.0f / bias_correction1) * lr_, scratch, weight_ptr, weight_ptr);
#else
LTEN_ERR("The USE_CUDA flag was not be set during the build (this flag must be set in order to use GPU tensors)");
#endif
}
else
{
LTEN_ERR("Invalid tensor device type");
}
}
}
}
} // namespace btpn
| 28.78836
| 187
| 0.679287
|
adeobootpin
|
1060d8c918966a41ece1a66555cd052063418fbf
| 46,376
|
cpp
|
C++
|
compiler/src/iree/compiler/Codegen/LLVMCPU/KernelDispatch.cpp
|
mariecwhite/iree
|
6031ff4080f5755bcc52826a8d41ae7360106ffd
|
[
"Apache-2.0"
] | null | null | null |
compiler/src/iree/compiler/Codegen/LLVMCPU/KernelDispatch.cpp
|
mariecwhite/iree
|
6031ff4080f5755bcc52826a8d41ae7360106ffd
|
[
"Apache-2.0"
] | null | null | null |
compiler/src/iree/compiler/Codegen/LLVMCPU/KernelDispatch.cpp
|
mariecwhite/iree
|
6031ff4080f5755bcc52826a8d41ae7360106ffd
|
[
"Apache-2.0"
] | null | null | null |
// Copyright 2020 The IREE Authors
//
// Licensed 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
#include "iree/compiler/Codegen/LLVMCPU/KernelDispatch.h"
#include <numeric>
#include "iree-dialects/Dialect/LinalgExt/IR/LinalgExtOps.h"
#include "iree/compiler/Codegen/Transforms/Transforms.h"
#include "iree/compiler/Codegen/Utils/MarkerUtils.h"
#include "iree/compiler/Codegen/Utils/Utils.h"
#include "iree/compiler/Dialect/Flow/IR/FlowOps.h"
#include "llvm/ADT/TypeSwitch.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/TargetSelect.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/Dialect/Linalg/IR/Linalg.h"
#include "mlir/Dialect/Linalg/IR/LinalgInterfaces.h"
#include "mlir/Dialect/Linalg/Transforms/Transforms.h"
#include "mlir/Dialect/MemRef/IR/MemRef.h"
#include "mlir/Dialect/MemRef/Transforms/Passes.h"
#include "mlir/Dialect/Utils/StaticValueUtils.h"
#include "mlir/IR/Matchers.h"
#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
namespace mlir {
namespace iree_compiler {
/// NOTE: None of these flags are supported in any form long term. This are
/// temporary hooks added for development purposes. They could be
/// changed/modified at any time.
/// TODO: Find a way to plumb this through to not rely on these flags.
static llvm::cl::opt<int> clNativeVectorSizeInBytes(
"iree-codegen-llvm-vector-size-in-bytes",
llvm::cl::desc("native vector size to use on the hardware"),
llvm::cl::init(16));
static llvm::cl::opt<int> clNumberOfRuntimeThreads(
"iree-codegen-llvm-number-of-threads",
llvm::cl::desc("number of threads that are used at runtime"),
llvm::cl::init(8));
static llvm::cl::list<int> mmt4dWorkgroupTileSizes(
"iree-codegen-llvm-mmt4d-workgroup-tile-sizes",
llvm::cl::desc("linalg.mmt4d workgroup tile size"), llvm::cl::ZeroOrMore);
static llvm::cl::list<int> mmt4dL1TileSizes(
"iree-codegen-llvm-mmt4d-l1-tile-size",
llvm::cl::desc("linalg.mmt4d L1 tile size"), llvm::cl::ZeroOrMore);
static llvm::cl::list<int> mmt4dVectorSizes(
"iree-codegen-llvm-mmt4d-vector-size",
llvm::cl::desc("linalg.mmt4d vector tile size"), llvm::cl::ZeroOrMore);
static llvm::cl::opt<int> defaultWorkgroupTileSize(
"iree-codegen-llvm-generic-ops-workgroup-size",
llvm::cl::desc(
"linalg.generic and linalg.indexed_generic workgroup tile size"),
llvm::cl::init(64));
static llvm::cl::opt<bool> useLinalgTransformInterp(
"iree-codegen-use-linalg-transform-interp",
llvm::cl::desc(
"experimental path to use the linalg transform dialect interpreter"),
llvm::cl::init(false));
using IREE::Codegen::DispatchLoweringPassPipeline;
/// Looks for the `native_vector_size` attribute in the hal.executable.variant
/// op.
static Optional<int64_t> getNativeVectorSizeInBytes(func::FuncOp entryPointFn) {
auto variantOp =
entryPointFn->getParentOfType<IREE::HAL::ExecutableVariantOp>();
if (!variantOp) return llvm::None;
IREE::HAL::ExecutableTargetAttr targetAttr = variantOp.target();
if (!targetAttr) return llvm::None;
auto config = targetAttr.getConfiguration();
if (!config) return llvm::None;
auto nativeVectorSizeAttr = config.getAs<IntegerAttr>("native_vector_size");
if (!nativeVectorSizeAttr) return llvm::None;
int64_t nativeVectorSizeVal = nativeVectorSizeAttr.getInt();
if (!nativeVectorSizeVal) return llvm::None;
return nativeVectorSizeVal;
}
/// For a given `shapedType` or (`byteWidth` of element type) return the number
/// of elements that correspond to the native vector size. Returns 1 as the
/// fallback.
static int64_t getVectorSize(func::FuncOp entryPointFn, unsigned byteWidth) {
if (Optional<int64_t> nativeVectorSize =
getNativeVectorSizeInBytes(entryPointFn)) {
return nativeVectorSize.getValue() / byteWidth;
}
return clNativeVectorSizeInBytes / byteWidth;
}
static int64_t getVectorSize(func::FuncOp entryPointFn, ShapedType shapedType) {
Type elementType = shapedType.getElementType();
if (!elementType.isIntOrFloat()) return 1;
unsigned byteWidth = IREE::Util::getRoundedElementByteWidth(elementType);
return getVectorSize(entryPointFn, byteWidth);
}
/// Returns minimum tiling sizes for each dimension. One dimension is possible
/// to access at different element types. It determines the tiling sizes by
/// looking into all the operands.
static SmallVector<int64_t> getMinTilingSizesForEachDim(
func::FuncOp entryPointFn, linalg::LinalgOp op) {
unsigned numLoops = op.getNumLoops();
SmallVector<int64_t> minTileSizes(numLoops, 1);
auto inputOutputOpOperands = op.getInputAndOutputOperands();
for (auto map : llvm::enumerate(op.getIndexingMaps())) {
// Check the fastest varying dimension of the operand. Set the vector size
// of the corresponding loop to the vector size.
if (map.value().getNumResults() == 0) continue;
auto fastestVaryingDimExpr =
map.value().getResults().back().dyn_cast<AffineDimExpr>();
if (!fastestVaryingDimExpr) continue;
unsigned fastestVaryingDim = fastestVaryingDimExpr.getPosition();
// If the indexing map has result it has to be a shaped type.
auto operandType =
inputOutputOpOperands[map.index()]->get().getType().cast<ShapedType>();
minTileSizes[fastestVaryingDim] =
std::max<int64_t>(minTileSizes[fastestVaryingDim],
getVectorSize(entryPointFn, operandType));
}
return minTileSizes;
}
/// Returns the type length in bytes. Looks through all the interface binding
/// ops to see the ABI types and guess-timates the type size to use. This is
/// used to convert the vector size in bytes to vector size in number of
/// elements.
static unsigned getReferenceTypeLengthInBytes(func::FuncOp entryPointFn) {
unsigned referenceTypeLengthInBytes = 4;
entryPointFn.walk([&](IREE::HAL::InterfaceBindingSubspanOp subSpanOp) {
Type type = subSpanOp.getResult().getType();
Type elementType = TypeSwitch<Type, Type>(type)
.Case<ShapedType, IREE::Flow::DispatchTensorType>(
[&](auto shapedType) -> Type {
// Ignore operands that are 0D tensors. These
// are not vector-loadable, so using these to
// get vector length would be a pessimization.
if (!shapedType.getRank()) return nullptr;
return shapedType.getElementType();
})
.Default([&](Type t) -> Type { return nullptr; });
if (!elementType || !elementType.isIntOrFloat()) return;
unsigned typeWidthInBytes =
IREE::Util::getRoundedElementByteWidth(elementType);
referenceTypeLengthInBytes =
std::min<unsigned>(referenceTypeLengthInBytes, typeWidthInBytes);
});
return referenceTypeLengthInBytes;
}
/// Returns the default tile sizes to use for the loops that are distributed at
/// Flow level.
static SmallVector<int64_t> getDefaultDistributedLoopTileSizes(
ArrayRef<int64_t> lbs, ArrayRef<int64_t> ubs,
ArrayRef<int64_t> minTileSizes, ArrayRef<int64_t> maxTileSizes,
ArrayRef<int64_t> vectorSizeHints) {
assert(lbs.size() == ubs.size() && lbs.size() == minTileSizes.size() &&
lbs.size() == maxTileSizes.size() &&
"expected all vectors to be of equal size");
size_t numDims = lbs.size();
SmallVector<int64_t> distributedTileSizes(numDims, 1);
SmallVector<int64_t> numWorkgroupsPerDim(numDims, 1);
SmallVector<int64_t> workload(numDims, 1);
for (auto i : llvm::seq<size_t>(0, numDims)) {
if (maxTileSizes[i] == 0 || ShapedType::isDynamic(lbs[i]) ||
ShapedType::isDynamic(ubs[i])) {
distributedTileSizes[i] = maxTileSizes[i];
workload[i] = ShapedType::kDynamicSize;
continue;
}
assert(lbs[i] <= ubs[i]);
workload[i] = ubs[i] - lbs[i];
int64_t candidateTileSize = 1;
int64_t targetSize = std::min(workload[i] / 2, maxTileSizes[i]);
int64_t vectorSize = vectorSizeHints[i];
if (vectorSize > 1) {
// Pick the factor of dim which is closest to the target tile size and
// is a multiplier of vector size.
for (int64_t k = vectorSize; k <= targetSize; k += vectorSize) {
if (workload[i] % k == 0 && k >= minTileSizes[i]) {
candidateTileSize = k;
}
}
}
// Fallback to power of 2 if there's no hint or can't find the ideal size.
if (vectorSize <= 1 || candidateTileSize == 1) {
candidateTileSize =
std::max<int64_t>(llvm::PowerOf2Floor(targetSize), minTileSizes[i]);
}
// Limit the workload per workgroup to the default being the max to keep the
// work per invocation reasonable.
distributedTileSizes[i] =
std::min<int64_t>(candidateTileSize, maxTileSizes[i]);
numWorkgroupsPerDim[i] =
llvm::divideCeil(workload[i], distributedTileSizes[i]);
}
// Reduce the number of workgroups in cases where we are dividing the work too
// much. Over-provision the number of workgroups to twice the number of
// threads.
int64_t numWorkgroupsLimit = 2 * clNumberOfRuntimeThreads;
int64_t numWorkgroups =
std::accumulate(numWorkgroupsPerDim.begin(), numWorkgroupsPerDim.end(),
1LL, std::multiplies<int64_t>{});
unsigned currDim = numDims;
while (numWorkgroups > numWorkgroupsLimit && currDim > 0) {
unsigned index = currDim - 1;
int64_t currSize = distributedTileSizes[index];
if (currSize >= maxTileSizes[index] ||
workload[index] == ShapedType::kDynamicSize ||
currSize >= workload[index]) {
currDim--;
continue;
}
int64_t newSize = std::min<int64_t>(currSize * 2, maxTileSizes[index]);
int64_t vectorSize = vectorSizeHints[index];
// Chech if it's the ideal size with vector size hint. And skip if the new
// size will break the ideal size.
if (vectorSize > 1 &&
(currSize % vectorSize == 0 && workload[index] % currSize == 0) &&
(newSize % vectorSize != 0 || workload[index] % newSize != 0)) {
currDim--;
continue;
}
distributedTileSizes[index] = newSize;
int64_t nwg =
llvm::divideCeil(workload[index], distributedTileSizes[index]);
if (nwg < numWorkgroupsPerDim[index]) {
numWorkgroups /= numWorkgroupsPerDim[index];
numWorkgroups *= nwg;
} else {
currDim--;
}
}
return distributedTileSizes;
}
/// Adjusts the workload per workgroup to be a multiple of vector size to ensure
/// that the op vectorizes.
static int64_t getMaxTileSize(int64_t lb, int64_t ub, int64_t maxSize,
int64_t vectorSizeVal) {
if (ub == ShapedType::kDynamicSize || lb == ShapedType::kDynamicSize) {
return maxSize;
}
int64_t dim = ub - lb;
if (dim < vectorSizeVal) return dim;
for (int64_t i = std::min(maxSize, dim); i > 0; --i) {
if (dim % i == 0 && i % vectorSizeVal == 0) {
return i;
}
}
// If it can't be a multiple of vectorSizeVal, let's choose a factor of dim
// sizes heuristically.
int64_t start = std::min(maxSize, dim);
start = std::min(start, vectorSizeVal * 2);
for (int64_t i = start; i > 0; --i) {
if (dim % i == 0) {
return i;
}
}
return 1;
}
/// Returns the tile size to use for the Flow level.
///
/// The vectorSizeHints can be empty or as many as the number of loops. When not
/// empty, each hint should be 1 or the vector size. On the dimensions where the
/// hints != 1, it will try to find the tile sizes which are multipliers of the
/// hints.
static SmallVector<int64_t> getDefaultDistributedLevelTileSizes(
ArrayRef<unsigned> partitionableLoops, ArrayRef<int64_t> lbs,
ArrayRef<int64_t> ubs, ArrayRef<int64_t> minTileSizes,
ArrayRef<int64_t> maxTileSizes, ArrayRef<int64_t> vectorSizeHints = {}) {
int64_t numLoops = lbs.size();
assert(numLoops == minTileSizes.size() && maxTileSizes.size() == numLoops &&
"expected as many min/max tile sizes as number of loops");
assert(
vectorSizeHints.empty() ||
vectorSizeHints.size() == numLoops &&
"vector size hints should be empty or equal to the number of loops");
// Only set values when the loop is partitionable.
SmallVector<int64_t> adjustedMinTileSizes(numLoops, 0);
SmallVector<int64_t> adjustedMaxTileSizes(numLoops, 0);
SmallVector<int64_t> adjustedVectorSizeHints(numLoops, 1);
for (auto i : partitionableLoops) {
adjustedMinTileSizes[i] = minTileSizes[i];
adjustedMaxTileSizes[i] = maxTileSizes[i];
if (!vectorSizeHints.empty()) {
adjustedVectorSizeHints[i] = vectorSizeHints[i];
}
}
SmallVector<int64_t> distributedTileSizes =
getDefaultDistributedLoopTileSizes(lbs, ubs, adjustedMinTileSizes,
adjustedMaxTileSizes,
adjustedVectorSizeHints);
// Final fix up of the tile sizes to make sure that they divide the problem
// size to make it vectorizable.
for (auto i : llvm::seq<unsigned>(0, distributedTileSizes.size())) {
if (!distributedTileSizes[i]) continue;
distributedTileSizes[i] = getMaxTileSize(
lbs[i], ubs[i], distributedTileSizes[i], minTileSizes[i]);
}
return distributedTileSizes;
}
static SmallVector<int64_t> getDefaultDistributedLevelTileSizes(
linalg::LinalgOp linalgOp, ArrayRef<int64_t> minTileSizes,
ArrayRef<int64_t> maxTileSizes, ArrayRef<int64_t> vectorSizeHints = {}) {
OpBuilder builder(linalgOp.getContext());
builder.setInsertionPoint(linalgOp);
SmallVector<int64_t> lbs(linalgOp.getNumLoops(), 0);
SmallVector<int64_t> ubs = linalgOp.getStaticLoopRanges();
auto loops =
cast<IREE::Flow::PartitionableLoopsInterface>(linalgOp.getOperation())
.getPartitionableLoops(kNumMaxParallelDims);
return getDefaultDistributedLevelTileSizes(loops, lbs, ubs, minTileSizes,
maxTileSizes, vectorSizeHints);
}
/// Splits the tile sizes in `parallelSizes` into `reductionSizes` for the
/// reduction loops.
static void splitParallelAndReductionTiles(
linalg::LinalgOp op, SmallVectorImpl<int64_t> ¶llelSizes,
SmallVectorImpl<int64_t> &reductionSizes) {
reductionSizes.assign(parallelSizes.begin(), parallelSizes.end());
for (auto iteratorType : llvm::enumerate(op.iterator_types())) {
if (iteratorType.value().cast<StringAttr>().getValue() ==
getParallelIteratorTypeName()) {
reductionSizes[iteratorType.index()] = 0;
} else {
parallelSizes[iteratorType.index()] = 0;
}
}
}
static void setAlwaysVectorizeSizes(linalg::LinalgOp op,
SmallVectorImpl<int64_t> ¶llelSizes,
SmallVectorImpl<int64_t> &reductionSizes) {
SmallVector<int64_t, 4> staticLoopRanges = op.getStaticLoopRanges();
for (auto en :
llvm::enumerate(llvm::zip(staticLoopRanges, op.iterator_types()))) {
auto size = std::get<0>(en.value());
if (!ShapedType::isDynamic(size)) continue;
auto iterType = std::get<1>(en.value()).cast<StringAttr>().getValue();
if (iterType == getParallelIteratorTypeName()) {
parallelSizes[en.index()] = 1;
} else {
reductionSizes[en.index()] = 1;
}
}
}
/// Sets the default configuration to use for an operation that implements the
/// `PartitionableLoopsInterface`, given the `lbs` and `ubs` of all the loops.
static LogicalResult setDefaultRootConfig(
func::FuncOp entryPointFn,
IREE::Flow::PartitionableLoopsInterface partitionableLoopsInterfaceOp,
ArrayRef<int64_t> lbs, ArrayRef<int64_t> ubs, bool hasTensorSemantics) {
if (getLoweringConfig(partitionableLoopsInterfaceOp)) return success();
SmallVector<unsigned> partitionableLoops =
partitionableLoopsInterfaceOp.getPartitionableLoops(kNumMaxParallelDims);
SmallVector<int64_t> minTileSizes(lbs.size(), 1);
SmallVector<int64_t> maxTileSizes(lbs.size(), 1);
if (!partitionableLoops.empty()) {
// TODO: Here the min tile size is just looking at the type of the data in
// the entry point function, and using a vector size that depends on just
// that. For `LinalgOp`s we can use the indexing map, find the loops that
// are fastest varying and set those to have a min tile size of vector
// length. A version of this is done for generic ops. Generalize that and
// use it for `LinalgOp`s.
unsigned typeWidthInBytes = getReferenceTypeLengthInBytes(entryPointFn);
minTileSizes[partitionableLoops.back()] =
getVectorSize(entryPointFn, typeWidthInBytes);
for (auto partitionableLoopId : partitionableLoops) {
maxTileSizes[partitionableLoopId] = defaultWorkgroupTileSize;
}
}
SmallVector<int64_t> flowTileSizes = getDefaultDistributedLevelTileSizes(
partitionableLoops, lbs, ubs, minTileSizes, maxTileSizes);
TileSizesListType tileSizes;
tileSizes.emplace_back(std::move(flowTileSizes));
return setOpConfigAndEntryPointFnTranslation(
entryPointFn, partitionableLoopsInterfaceOp, tileSizes,
hasTensorSemantics ? DispatchLoweringPassPipeline::CPUDefault
: DispatchLoweringPassPipeline::CPUBufferOpsDefault);
}
static LogicalResult setSandboxRootConfig(func::FuncOp entryPointFn,
linalg::ContractionOpInterface op,
ArrayRef<int64_t> flowTileSizes,
ArrayRef<int64_t> target2ndTileSizes,
int vectorSize) {
assert(target2ndTileSizes.size() == 3 &&
"the current configuration is driven by matmul which has exactly "
"three loops");
// The tiling for parallel dims and reduction dims should be separated.
SmallVector<int64_t> parallelTileSizes;
auto linalgOp = cast<linalg::LinalgOp>(op.getOperation());
int64_t nLoops = linalgOp.getNumLoops();
if (nLoops >= 3) {
parallelTileSizes.append(nLoops - 3, 1);
parallelTileSizes.push_back(getMaxTileSize(
0, flowTileSizes[nLoops - 3], target2ndTileSizes[0], vectorSize));
}
if (nLoops >= 2) {
parallelTileSizes.push_back(getMaxTileSize(
0, flowTileSizes[nLoops - 2], target2ndTileSizes[1], vectorSize));
}
parallelTileSizes.push_back(0);
auto lhsShapedType = op.lhs().getType().cast<ShapedType>();
int64_t K = lhsShapedType.getShape().back();
SmallVector<int64_t> reductionTileSizes;
reductionTileSizes.append(nLoops - 1, 0);
reductionTileSizes.push_back(
getMaxTileSize(0, K, target2ndTileSizes[2], vectorSize));
setAlwaysVectorizeSizes(linalgOp, parallelTileSizes, reductionTileSizes);
TileSizesListType tileSizes;
tileSizes.emplace_back(flowTileSizes.begin(), flowTileSizes.end());
tileSizes.push_back(parallelTileSizes);
tileSizes.push_back(reductionTileSizes);
return setOpConfigAndEntryPointFnTranslation(
entryPointFn, op, tileSizes,
DispatchLoweringPassPipeline::CPUDoubleTilingExpert);
}
static LogicalResult setARMRootConfig(func::FuncOp entryPointFn,
linalg::ContractionOpInterface op,
ArrayRef<int64_t> flowTileSizes,
int vectorSize) {
// Hardcoded tile sizes, where v is the native vector size.
// L1 tile sizes are {1, ..., 5v, v, 16v}.
// Vector tile sizes are {1, ..., v, v, v}
SmallVector<int64_t> l1TileSizes, vectorTileSizes;
int64_t nLoops = cast<linalg::LinalgOp>(op.getOperation()).getNumLoops();
if (nLoops >= 3) {
l1TileSizes.append(nLoops - 3, 1);
l1TileSizes.push_back(getMaxTileSize(0, flowTileSizes[nLoops - 3],
5 * vectorSize, vectorSize));
vectorTileSizes.append(nLoops - 3, 1);
vectorTileSizes.push_back(vectorSize);
}
if (nLoops >= 2) {
l1TileSizes.push_back(
getMaxTileSize(0, flowTileSizes[nLoops - 2], vectorSize, vectorSize));
vectorTileSizes.push_back(vectorSize);
}
// L1/vector tile size for k dimensions.
auto lhsShapedType = op.lhs().getType().cast<ShapedType>();
int64_t K = lhsShapedType.getShape().back();
l1TileSizes.push_back(getMaxTileSize(0, K, 16 * vectorSize, vectorSize));
vectorTileSizes.push_back(vectorSize);
TileSizesListType tileSizes;
tileSizes.emplace_back(flowTileSizes.begin(), flowTileSizes.end());
tileSizes.push_back(l1TileSizes);
tileSizes.push_back(vectorTileSizes);
return setOpConfigAndEntryPointFnTranslation(
entryPointFn, op, tileSizes,
DispatchLoweringPassPipeline::CPUTileFuseAndVectorize);
}
/// Sets the lowering configuration for dispatch region with root op that
/// implements the contraction operation interface.
static LogicalResult setRootConfig(
func::FuncOp entryPointFn, linalg::ContractionOpInterface contractionOp,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops) {
auto linalgOp = cast<linalg::LinalgOp>(contractionOp.getOperation());
unsigned numLoops = linalgOp.getNumLoops();
{
SmallVector<unsigned> dims;
linalgOp.getReductionDims(dims);
if (dims.size() != 1 || dims[0] != numLoops - 1) {
return contractionOp.emitOpError(
"expected to have exactly one reduction dim, and it is the innermost "
"dim");
}
}
// Consider all element types and use the smallest vector size. The tiling
// sizes are chosen based on the vector size.
auto lhsShapedType = contractionOp.lhs().getType().cast<ShapedType>();
auto rhsShapedType = contractionOp.rhs().getType().cast<ShapedType>();
auto resShapedType =
linalgOp.getOutputOperand(0)->get().getType().cast<ShapedType>();
int64_t vectorSize = getVectorSize(entryPointFn, lhsShapedType);
vectorSize = std::min(vectorSize, getVectorSize(entryPointFn, rhsShapedType));
vectorSize = std::min(vectorSize, getVectorSize(entryPointFn, resShapedType));
// Use the default distribution for the matmul loops.
SmallVector<int64_t> minTileSizes =
getMinTilingSizesForEachDim(entryPointFn, linalgOp);
SmallVector<int64_t> maxTileSizes(numLoops, defaultWorkgroupTileSize);
if (numLoops > 3) {
minTileSizes[0] = 1;
maxTileSizes[0] = 1;
}
SmallVector<int64_t> flowTileSizes =
getDefaultDistributedLevelTileSizes(linalgOp, minTileSizes, maxTileSizes);
// TODO(dcaballe): Find better configurations for RISC-V backends.
if (isX86(entryPointFn) || isRISCV(entryPointFn)) {
SmallVector<int64_t> tileSizes = {8, 32, 16};
return setSandboxRootConfig(entryPointFn, contractionOp, flowTileSizes,
tileSizes, vectorSize);
}
// Fall back to ARM configurations.
bool isQuantized =
lhsShapedType.getElementType() != resShapedType.getElementType();
if (isQuantized) {
SmallVector<int64_t> tileSizes = {4, 16, 4};
return setSandboxRootConfig(entryPointFn, contractionOp, flowTileSizes,
tileSizes, vectorSize);
} else {
return setARMRootConfig(entryPointFn, contractionOp, flowTileSizes,
vectorSize);
}
}
/// Sets the lowering configuration for dispatch region for linalg.mmt4d root
/// op
static LogicalResult setRootConfig(
func::FuncOp entryPointFn, linalg::Mmt4DOp mmt4dOp,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops) {
// TODO(ataei): These are hand tuned for some performance benchmarks for
// now, we want to adapt the same strategy as matmul that dynamically sets
// tile size.
auto getWorkgroupTileSizes = [&]() -> SmallVector<int64_t> {
if (!mmt4dWorkgroupTileSizes.empty()) {
return SmallVector<int64_t>(mmt4dWorkgroupTileSizes.begin(),
mmt4dWorkgroupTileSizes.end());
}
return {48, 32};
};
auto getL1TileSizes = [&]() -> SmallVector<int64_t> {
auto lhsShape = mmt4dOp.inputs()[0].getType().cast<ShapedType>().getShape();
auto rhsShape = mmt4dOp.inputs()[1].getType().cast<ShapedType>().getShape();
int M0 = lhsShape[2];
int N0 = rhsShape[2];
int K0 = lhsShape[3];
if (!mmt4dL1TileSizes.empty()) {
return SmallVector<int64_t>(mmt4dL1TileSizes.begin(),
mmt4dL1TileSizes.end());
}
return {1, 1, 1, M0, N0, K0};
};
auto getVectorSizes = [&]() -> SmallVector<int64_t> {
auto lhsShape = mmt4dOp.inputs()[0].getType().cast<ShapedType>().getShape();
auto rhsShape = mmt4dOp.inputs()[1].getType().cast<ShapedType>().getShape();
int M0 = lhsShape[2];
int N0 = rhsShape[2];
int K0 = lhsShape[3];
if (!mmt4dVectorSizes.empty()) {
return SmallVector<int64_t>(mmt4dVectorSizes.begin(),
mmt4dVectorSizes.end());
}
return {1, 1, 1, M0, N0, K0};
};
SmallVector<int64_t> nativeVectorSize = getVectorSizes();
TileSizesListType tileSizes = {getWorkgroupTileSizes(), getL1TileSizes(),
nativeVectorSize};
return setOpConfigAndEntryPointFnTranslation(
entryPointFn, mmt4dOp, tileSizes,
DispatchLoweringPassPipeline::CPUTileFuseAndVectorize);
}
/// Sets the lowering configuration for dispatch region for linalg_ext.fft
/// root op.
static LogicalResult setRootConfig(
func::FuncOp entryPointFn, IREE::LinalgExt::FftOp fftOp,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops) {
unsigned numLoops = fftOp.getLoopIteratorTypes().size();
auto partitionedLoops = fftOp.getPartitionableLoops(kNumMaxParallelDims);
SmallVector<int64_t> workgroupTileSizes(numLoops, defaultWorkgroupTileSize);
llvm::DenseSet<unsigned> partitionedLoopsSet(partitionedLoops.begin(),
partitionedLoops.end());
for (auto dim : llvm::seq<int64_t>(0, workgroupTileSizes.size())) {
if (!partitionedLoopsSet.count(dim)) {
workgroupTileSizes[dim] = 0;
}
}
auto rank = fftOp.getOperandRank();
if (workgroupTileSizes.size() >= rank && workgroupTileSizes[rank - 1] != 0) {
APInt value;
if (matchPattern(fftOp.getStage(), m_ConstantInt(&value))) {
workgroupTileSizes[rank - 1] = 1ll << value.getSExtValue();
workgroupTileSizes[rank - 1] =
std::max(workgroupTileSizes[rank - 1],
static_cast<int64_t>(defaultWorkgroupTileSize));
} else {
return fftOp.emitOpError("non-constant stage might not work for fft op");
}
}
TileSizesListType tileSizes = {workgroupTileSizes};
return setOpConfigAndEntryPointFnTranslation(
entryPointFn, fftOp, tileSizes, DispatchLoweringPassPipeline::CPUDefault);
}
static void setX86WorkgroupTileSizes(
linalg::GenericOp genericOp, unsigned numLoops,
ArrayRef<int64_t> flowTileSizes, ArrayRef<int64_t> minTileSizes,
ArrayRef<int64_t> maxTileSizes,
SmallVectorImpl<int64_t> &workgroupTileSizes) {
workgroupTileSizes.append(numLoops, 0);
SmallVector<int64_t, 4> staticLoopRanges = genericOp.getStaticLoopRanges();
for (auto loopNum : llvm::seq<unsigned>(0, numLoops)) {
if (flowTileSizes[loopNum]) {
workgroupTileSizes[loopNum] =
getMaxTileSize(0, flowTileSizes[loopNum], minTileSizes[loopNum],
minTileSizes[loopNum]);
} else {
// If the flow level tile size is zero, and static loop range is 0 as
// well, set the tile sizes here to zero as well.
workgroupTileSizes[loopNum] =
staticLoopRanges[loopNum] == 1 ? 0 : minTileSizes[loopNum];
}
}
}
/// Returns true if the operation is a GenericOp implementing a supported
/// transposition.
static bool isSupportedTransposeOp(linalg::GenericOp genericOp) {
// Check that the op has at least 2 dimensions.
if (genericOp.getNumLoops() < 2) {
return false;
}
// Check that the op has only one input and one output.
// TODO(diegocaballero): Generalize to multiple inputs.
if ((genericOp.getNumInputs() != 1) || (genericOp.getNumOutputs() != 1)) {
return false;
}
// Check that all the iterators are parallel.
if (genericOp.getNumParallelLoops() != genericOp.getNumLoops()) {
return false;
}
// Check that the two indexing maps are a permutation of each other.
auto indexing_maps = genericOp.getIndexingMaps();
return !indexing_maps[0].isEmpty() && !indexing_maps[1].isEmpty() &&
((indexing_maps[0].isIdentity() && !indexing_maps[1].isIdentity() &&
indexing_maps[1].isPermutation()) ||
(!indexing_maps[0].isIdentity() && indexing_maps[0].isPermutation() &&
indexing_maps[1].isIdentity()));
}
/// Sets the default lowering configuration for a generic op to use
/// CPUDoubleTilingExpert pipeline.
static LogicalResult setDefaultGenericOpRootConfig(
func::FuncOp entryPointFn, linalg::GenericOp genericOp,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops) {
if (getLoweringConfig(genericOp)) {
return success();
}
// If there are no loops, there is nothing to do.
unsigned numLoops = genericOp.getNumLoops();
if (numLoops == 0) return success();
SmallVector<int64_t> minTileSizes =
getMinTilingSizesForEachDim(entryPointFn, genericOp);
SmallVector<int64_t> maxTileSizes(numLoops, defaultWorkgroupTileSize);
if (llvm::all_of(minTileSizes, [](int64_t vs) { return vs == 1; })) {
// Nothing to vectorize just lower to loops.
return success();
}
// Set the flow level tiling to the default.
SmallVector<int64_t> flowTileSizes = getDefaultDistributedLevelTileSizes(
genericOp, minTileSizes, maxTileSizes);
// Set the next level tile sizes.
SmallVector<int64_t> parallelTileSizes;
SmallVector<int64_t> reductionTileSizes;
setX86WorkgroupTileSizes(genericOp, numLoops, flowTileSizes, minTileSizes,
maxTileSizes, parallelTileSizes);
splitParallelAndReductionTiles(genericOp, parallelTileSizes,
reductionTileSizes);
setAlwaysVectorizeSizes(genericOp, parallelTileSizes, reductionTileSizes);
TileSizesListType tileSizes;
tileSizes.push_back(flowTileSizes);
tileSizes.push_back(parallelTileSizes);
tileSizes.push_back(reductionTileSizes);
// For non-tensor based ops use the Buffer ops pipeline.
auto passPipeline =
genericOp.hasTensorSemantics()
? DispatchLoweringPassPipeline::CPUDoubleTilingExpert
: DispatchLoweringPassPipeline::CPUBufferOpsTileAndVectorize;
return setOpConfigAndEntryPointFnTranslation(entryPointFn, genericOp,
tileSizes, passPipeline);
}
/// Sets the lowering configuration for a generic op implementing a
/// transposition to use CPUDoubleTilingExpert pipeline.
static LogicalResult setTransposeLikeOpRootConfig(
func::FuncOp entryPointFn, linalg::GenericOp genericOp,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops) {
if (getLoweringConfig(genericOp)) {
return success();
}
if (!hasAVX2Features(genericOp) || !isSupportedTransposeOp(genericOp)) {
return success();
}
unsigned numLoops = genericOp.getNumLoops();
SmallVector<int64_t> minTileSizes =
getMinTilingSizesForEachDim(entryPointFn, genericOp);
SmallVector<int64_t> maxTileSizes(numLoops, defaultWorkgroupTileSize);
if (llvm::all_of(minTileSizes, [](int64_t vs) { return vs == 1; })) {
// Nothing to vectorize just lower to loops.
return success();
}
if (llvm::count_if(minTileSizes,
[](int64_t tileSize) { return tileSize > 1; }) != 2) {
// Transpose patterns are not applicable if vectorizing more or less than
// two dims.
return success();
}
// Make sure that the original tile sizes are multiple of the tile sizes
// to be used for the transpose op (i.e., 8x8).
// TODO(diegocaballero): Enable 4x8 tile sizes if we find it useful.
if (llvm::any_of(minTileSizes, [](int64_t tileSize) {
return tileSize > 1 && (tileSize % 8) != 0;
})) {
return success();
}
// Replace dims to be vectorized with the new 8x8 tile sizes.
std::replace_if(
minTileSizes.begin(), minTileSizes.end(),
[](int64_t tileSize) { return tileSize > 1; }, 8);
// Set the flow level tiling to the default.
SmallVector<int64_t> flowTileSizes = getDefaultDistributedLevelTileSizes(
genericOp, minTileSizes, maxTileSizes);
// Set the next level tile sizes.
SmallVector<int64_t> parallelTileSizes;
setX86WorkgroupTileSizes(genericOp, numLoops, flowTileSizes, minTileSizes,
maxTileSizes, parallelTileSizes);
TileSizesListType tileSizes;
tileSizes.push_back(flowTileSizes);
tileSizes.push_back(parallelTileSizes);
tileSizes.push_back(/*reduction tile sizes=*/{});
// For non-tensor based ops use the Buffer ops pipeline.
auto passPipeline =
genericOp.hasTensorSemantics()
? DispatchLoweringPassPipeline::CPUDoubleTilingExpert
: DispatchLoweringPassPipeline::CPUBufferOpsTileAndVectorize;
return setOpConfigAndEntryPointFnTranslation(entryPointFn, genericOp,
tileSizes, passPipeline);
}
/// Sets the lowering configuration for a generic op to use
/// CPUDoubleTilingExpert pipeline.
static LogicalResult setRootConfig(
func::FuncOp entryPointFn, linalg::GenericOp genericOp,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops) {
if (failed(
setTransposeLikeOpRootConfig(entryPointFn, genericOp, tiledLoops)) ||
failed(
setDefaultGenericOpRootConfig(entryPointFn, genericOp, tiledLoops))) {
return failure();
}
return success();
}
/// Sets the lowering configuration for linalg.conv_2d_nhwc_hwcf and
/// linalg.depthwise_conv_2d_nhwc_hwc operations.
static LogicalResult setConvRootConfig(
func::FuncOp entryPointFn, linalg::LinalgOp convOp,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops,
ArrayRef<int64_t> targetTileSizes, int64_t vectorSize) {
if (!isa<linalg::Conv2DNhwcHwcfOp, linalg::DepthwiseConv2DNhwcHwcOp>(
convOp.getOperation())) {
return failure();
}
// Use the default distribution for the conv loops.
unsigned numLoops = convOp.getNumLoops();
SmallVector<int64_t> minTileSizes(numLoops, 1);
SmallVector<int64_t> maxTileSizes(numLoops, defaultWorkgroupTileSize);
SmallVector<int64_t> vectorSizeHints(numLoops, 1);
// Give the vector size hint on OC.
vectorSizeHints[3] = vectorSize;
// Set the flow level tiling to the default.
SmallVector<int64_t> flowTileSizes = getDefaultDistributedLevelTileSizes(
convOp, minTileSizes, maxTileSizes, vectorSizeHints);
// Shapes of N, OH, OW, OC, KH, KW, (IC)
SmallVector<int64_t, 4> shapes = convOp.getStaticLoopRanges();
SmallVector<int64_t> parallelTileSizes(targetTileSizes.begin(),
targetTileSizes.end());
for (auto i : llvm::seq<unsigned>(0, parallelTileSizes.size())) {
auto tileSize = flowTileSizes[i] ? flowTileSizes[i] : shapes[i];
// If the tile size is intended to be 1, do not adjust it to `vectorSize`.
// The ops will be decomposed to lower-rank named ops.
if (parallelTileSizes[i] != 1) {
parallelTileSizes[i] =
getMaxTileSize(0, tileSize, parallelTileSizes[i], vectorSize);
}
}
SmallVector<int64_t> reductionTileSizes;
splitParallelAndReductionTiles(convOp, parallelTileSizes, reductionTileSizes);
setAlwaysVectorizeSizes(convOp, parallelTileSizes, reductionTileSizes);
TileSizesListType tileSizes;
tileSizes.push_back(flowTileSizes);
tileSizes.push_back(parallelTileSizes);
tileSizes.push_back(reductionTileSizes);
return setOpConfigAndEntryPointFnTranslation(
entryPointFn, convOp, tileSizes,
DispatchLoweringPassPipeline::CPUConvTileAndDecomposeExpert);
}
static LogicalResult setRootConfig(
func::FuncOp entryPointFn, linalg::Conv2DNhwcHwcfOp convOp,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops) {
int64_t vectorSize =
getVectorSize(entryPointFn, convOp.getResult(0).getType());
SmallVector<int64_t> targetTileSizes = {1, 1, 8, vectorSize * 2, 1, 1, 8};
return setConvRootConfig(entryPointFn, convOp, tiledLoops, targetTileSizes,
vectorSize);
}
/// Sets the lowering configuration for linalg.depthwise_conv_2d_nhwc_hwc
/// operations.
static LogicalResult setRootConfig(
func::FuncOp entryPointFn, linalg::DepthwiseConv2DNhwcHwcOp convOp,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops) {
int64_t vectorSize =
getVectorSize(entryPointFn, convOp.getResult(0).getType());
SmallVector<int64_t> targetTileSizes = {1, 1, 8, vectorSize * 2, 1, 3};
return setConvRootConfig(entryPointFn, convOp, tiledLoops, targetTileSizes,
vectorSize);
}
/// Set default configuration for Linalg ops.
static LogicalResult setRootConfig(
func::FuncOp entryPointFn, linalg::LinalgOp linalgOp,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops) {
if (getLoweringConfig(linalgOp)) return success();
auto partitionableLoopOp =
cast<IREE::Flow::PartitionableLoopsInterface>(linalgOp.getOperation());
SmallVector<int64_t> lbs(linalgOp.getNumLoops(), 0);
SmallVector<int64_t> ubs = linalgOp.getStaticLoopRanges();
return setDefaultRootConfig(entryPointFn, partitionableLoopOp, lbs, ubs,
linalgOp.hasTensorSemantics());
}
/// Set the default configuration for operations that implement the
/// `TiledOpInterface`.
static LogicalResult setRootConfig(
func::FuncOp entryPointFn,
IREE::LinalgExt::TiledOpInterface tiledOpInterfaceOp,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops) {
if (getLoweringConfig(tiledOpInterfaceOp)) return success();
auto partitionableLoopOp = cast<IREE::Flow::PartitionableLoopsInterface>(
tiledOpInterfaceOp.getOperation());
// TODO(hanchung): Implement getStaticLoopRanges method for TiledOpInterface.
OpBuilder builder(tiledOpInterfaceOp.getContext());
builder.setInsertionPoint(tiledOpInterfaceOp);
SmallVector<Range> iterationDomain =
tiledOpInterfaceOp.getIterationDomain(builder);
auto getStaticValue = [](Value v) -> int64_t {
IntegerAttr attr;
if (!matchPattern(v, m_Constant(&attr))) return ShapedType::kDynamicSize;
return attr.getInt();
};
auto lbs = llvm::to_vector(llvm::map_range(
iterationDomain, [&](Range r) { return getStaticValue(r.offset); }));
auto ubs = llvm::to_vector(llvm::map_range(
iterationDomain, [&](Range r) { return getStaticValue(r.size); }));
return setDefaultRootConfig(entryPointFn, partitionableLoopOp, lbs, ubs,
/*hasTensorSemantics=*/true);
}
/// Redirects to methods that set the configuration based on operation type.
static LogicalResult setRootConfigImpl(
func::FuncOp entryPointFn, Operation *op,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops) {
// Do not overwrite default configuration.
if (getLoweringConfig(op)) return success();
// Redirect to individual operations.
auto setRootConfigFn = [&](Operation *op) -> LogicalResult {
return TypeSwitch<Operation *, LogicalResult>(op)
.Case<IREE::LinalgExt::FftOp, linalg::GenericOp, linalg::Mmt4DOp,
linalg::Conv2DNhwcHwcfOp, linalg::DepthwiseConv2DNhwcHwcOp>(
[&](auto op) {
return setRootConfig(entryPointFn, op, tiledLoops);
})
.Case<linalg::ContractionOpInterface>([&](auto op) {
return setRootConfig(entryPointFn, op, tiledLoops);
})
.Case<linalg::LinalgOp, IREE::LinalgExt::TiledOpInterface>(
[&](auto op) {
return setRootConfig(entryPointFn, op, tiledLoops);
})
.Default([&](Operation *op) { return success(); });
};
return setRootConfigFn(op);
}
/// Redirects to methods that set the configuration based on operation type for
/// VMVX backend.
static LogicalResult setVMVXRootConfigImpl(
func::FuncOp entryPointFn, Operation *op,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops) {
if (getLoweringConfig(op)) return success();
// Redirect to individual operations.
auto setRootConfigFn = [&](Operation *op) -> LogicalResult {
return TypeSwitch<Operation *, LogicalResult>(op)
.Case<linalg::LinalgOp, IREE::LinalgExt::TiledOpInterface>(
[&](auto op) {
return setRootConfig(entryPointFn, op, tiledLoops);
})
.Default([&](Operation *op) { return success(); });
};
return setRootConfigFn(op);
}
/// Find the root operation for the dispatch region.
static FailureOr<Operation *> getRootOperation(
ArrayRef<Operation *> computeOps) {
Operation *rootOperation = nullptr;
auto updateRootOperation = [&](Operation *op) -> LogicalResult {
if (rootOperation) {
return op->emitOpError(
"unhandled multiple root operations in dispatch region");
}
rootOperation = op;
return success();
};
for (auto op : computeOps) {
if (auto linalgOp = dyn_cast<linalg::LinalgOp>(op)) {
// Do not not treat linalg ops that are all parallel as root operations in
// this sweep.
if (linalgOp.getNumLoops() == linalgOp.getNumParallelLoops()) continue;
// All other linalg ops are root ops.
if (failed(updateRootOperation(op))) return failure();
continue;
}
if (auto tiledOpInterfaceOp =
dyn_cast<IREE::LinalgExt::TiledOpInterface>(op)) {
// TODO(ravishankarm): For now
// `tensor.extract_slice`/`tensor.insert_slice` implement the
// `tiledInterfaceOp`. With tile + distribute moved out of Flow
// dialect, this doesnt work anymore. Remove this when the external
// model implementation of
// `tensor.extract_slice`/`tensor.insert_slice` are dropped.
if (isa<tensor::ExtractSliceOp, tensor::InsertSliceOp>(op)) continue;
// All other operations that implement this interface are root ops.
if (failed(updateRootOperation(op))) return failure();
continue;
}
}
if (rootOperation) return rootOperation;
// If no root operation is found yet. Look for linalg generic ops.
for (auto op : llvm::reverse(computeOps)) {
if (isa<linalg::LinalgOp>(op)) {
if (failed(updateRootOperation(op))) return failure();
}
}
return rootOperation;
}
/// Finds the root operation in the given list of Linalg operations and sets
/// its configuration. Returns error for multiple root operations.
static LogicalResult setRootConfig(
func::FuncOp entryPointFn, ArrayRef<Operation *> computeOps,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops) {
FailureOr<Operation *> rootOp = getRootOperation(computeOps);
if (failed(rootOp)) {
return failure();
}
Operation *rootOperation = rootOp.getValue();
if (rootOperation) {
if (isVMVXBackend(entryPointFn)) {
if (failed(
setVMVXRootConfigImpl(entryPointFn, rootOperation, tiledLoops))) {
return failure();
}
} else {
if (failed(setRootConfigImpl(entryPointFn, rootOperation, tiledLoops))) {
return failure();
}
}
}
if (!getTranslationInfo(entryPointFn)) {
// Fall back, just set the translation to CPUDefault.
setTranslationInfo(entryPointFn, DispatchLoweringPassPipeline::CPUDefault,
/*workloadPerWorkgroup=*/ArrayRef<int64_t>{},
/*workgroupSize=*/ArrayRef<int64_t>{});
}
return success();
}
/// Sets the translation information to use for a dispatch region.
static LogicalResult setTranslationInfoAndRootConfig(
func::FuncOp entryPointFn, ArrayRef<Operation *> computeOps,
ArrayRef<LoopTilingAndDistributionInfo> tiledLoops) {
// First check if the operations have a preset pipeline.
for (auto computeOp : computeOps) {
if (IREE::Codegen::CompilationInfoAttr compilationInfo =
getCompilationInfo(computeOp)) {
// If the function already has a translation, error out.
if (auto translationInfo = getTranslationInfo(entryPointFn)) {
return computeOp->emitOpError(
"multiple ops within dispatch trying to set the translation "
"info");
}
SmallVector<int64_t> workgroupSize =
compilationInfo.getWorkgroupSizeVals();
setTranslationInfo(entryPointFn, compilationInfo.getTranslationInfo(),
workgroupSize);
setLoweringConfig(computeOp, compilationInfo.getLoweringConfig());
eraseCompilationInfo(computeOp);
}
}
// Next set the configuration of the operations.
return setRootConfig(entryPointFn, computeOps, tiledLoops);
}
LogicalResult initCPULaunchConfig(ModuleOp moduleOp) {
llvm::StringMap<IREE::HAL::ExecutableEntryPointOp> entryPointOps =
getAllEntryPoints(moduleOp);
for (auto funcOp : moduleOp.getOps<func::FuncOp>()) {
auto entryPointOp = entryPointOps.lookup(funcOp.getName());
if (!entryPointOp) continue;
if (getTranslationInfo(entryPointOp)) continue;
// If using sandbox passes, currently set the workload_per_wg to be
// empty for single-threaded execution.
if (useLinalgTransformInterp) {
auto translationInfo = IREE::Codegen::TranslationInfoAttr::get(
moduleOp.getContext(), IREE::Codegen::DispatchLoweringPassPipeline::
LinalgTransformInterpCodegen);
setTranslationInfo(funcOp, translationInfo);
continue;
}
SmallVector<Operation *> computeOps;
SmallVector<LoopTilingAndDistributionInfo> tiledLoops;
// If there are no linalg ops, not using Linalg based lowering.
if (failed(getComputeOps(funcOp, computeOps, tiledLoops))) {
return failure();
}
if (failed(
setTranslationInfoAndRootConfig(funcOp, computeOps, tiledLoops))) {
return failure();
}
}
// The root confguration setting introduces `tensor.dim` operations. Resolve
// those away.
RewritePatternSet patterns(moduleOp.getContext());
memref::populateResolveRankedShapeTypeResultDimsPatterns(patterns);
return applyPatternsAndFoldGreedily(moduleOp, std::move(patterns));
}
} // namespace iree_compiler
} // namespace mlir
| 41.518353
| 80
| 0.697149
|
mariecwhite
|
106272359d63eaacfdb71a1a111401c3f2153631
| 5,015
|
cpp
|
C++
|
src/bwtransform.cpp
|
Mathtin/mazip
|
5d06f7934c801dc7d9433511fa0eb84225792a0a
|
[
"MIT"
] | null | null | null |
src/bwtransform.cpp
|
Mathtin/mazip
|
5d06f7934c801dc7d9433511fa0eb84225792a0a
|
[
"MIT"
] | null | null | null |
src/bwtransform.cpp
|
Mathtin/mazip
|
5d06f7934c801dc7d9433511fa0eb84225792a0a
|
[
"MIT"
] | null | null | null |
#include "bwtransform.h"
/*
* Author: Daniil [Mathtin] Shigapov
* Copyright (c) 2017 Mathtin <wdaniil@mail.ru>
* This file is released under the MIT license.
*/
size_t sa[L_PAGE];
size_t tmp[L_PAGE];
size_t tmp2[L_PAGE];
size_t count[L_PAGE];
size_t *cl, *workTmp;
#define REP(i, n) for (size_t i = 0; i < n; ++i)
#define REP1(i, n) for (size_t i = 1; i < n; ++i)
#define REVREP(i, n) for (size_t i = n; i + 1; --i)
#define NOT_EQUAL_CL(i, step, sz) \
cl[sa[i]] != cl[sa[i - 1]] || \
cl[(sa[i] + step) % sz] != cl[(sa[i - 1] + step) % sz]
static void SortSA(const size_t & step, const size_t & clcount,
const size_t & sz) {
REP(i, sz) {
workTmp[i] = (sa[i] + sz - step) % sz;
}
memset(count, 0, clcount * sizeof(size_t));
REP(i, sz) {
++count[cl[workTmp[i]]];
}
REP1(i, clcount) {
count[i] += count[i - 1];
}
REVREP(i, sz - 1) {
sa[--count[cl[workTmp[i]]]] = workTmp[i];
}
}
static void CalcCl(const size_t & step, size_t & clcount, const size_t & sz) {
workTmp[sa[0]] = 0;
clcount = 0;
REP1(i, sz) {
if (NOT_EQUAL_CL(i, step, sz)) {
++clcount;
}
workTmp[sa[i]] = clcount;
}
++clcount;
std::swap(cl, workTmp);
}
static void buildSA(const byte * s, const size_t & sz) {
cl = tmp, workTmp = tmp2;
memset(count, 0, 0x100 * sizeof(size_t));
REP(i, sz) {
++count[s[i]];
}
REP1(i, 0x100) {
count[i] += count[i - 1];
}
REP(i, sz) {
sa[--count[s[i]]] = i;
}
cl[sa[0]] = 0;
size_t clcount = 0;
REP1(i, sz) {
if (s[sa[i]] != s[sa[i - 1]]) {
++clcount;
}
cl[sa[i]] = clcount;
}
++clcount;
for (size_t h = 0; (1u << h) < sz; ++h) {
SortSA(1 << h, clcount, sz);
CalcCl(1 << h, clcount, sz);
}
}
static uint16_t BWTBuffer(byte * input, byte * output, size_t sz) {
if (sz == 0) {
return 0;
}
uint16_t opos = 0;
buildSA(input, sz);
REP(i, sz) {
output[i] = input[(sa[i] + sz - 1) % sz];
if (sa[i] == 0) {
opos = i;
}
}
return opos;
}
static void BWRBuffer(byte * input, byte * output, size_t sz, size_t j) {
memset(count, 0, 0x100 * sizeof(size_t));
REP(i, sz) {
++count[input[i]];
}
size_t sum = 0;
REP(i, 0x100) {
sum += count[i];
count[i] = sum - count[i];
}
REP(i, sz) {
tmp[count[input[i]]++] = i;
}
j = tmp[j];
REP(i, sz) {
output[i] = input[j];
j = tmp[j];
}
}
static byte PageToFlag(size_t page) {
if (page == L_PAGE) {
return FLAG_BEST;
} else if (page == S_PAGE) {
return FLAG_FAST;
}
return 0;
}
BWTransform::BWTransform(TMaFile & buffer, bool write)
: file(buffer)
, offsetPages(-1)
, grow(0)
, gpos(0)
, w(write)
, pageSet(false) {
bwtpage = file.Page() + sizeof(uint16_t);
bwtsize = (file.size() / file.Page()) * bwtpage + 1;
if (file.size() % file.Page()) {
bwtsize += file.size() % file.Page() + sizeof(uint16_t);
}
gpos = (bwtsize - 1) % bwtpage;
if (w) {
LoadPage(0);
}
}
BWTransform::~BWTransform() {
if (w && offsetPages != (size_t)-1) {
SwapOff();
}
}
void BWTransform::LoadPage(size_t p) {
if (p == offsetPages) {
return;
} else if (w && offsetPages != (size_t)-1) {
SwapOff();
}
file.LoadPage(p);
offsetPages = p;
if (w) {
return;
}
uint16_t opos = BWTBuffer(file.data(), buff + 3, file.PageSize());
buff[0] = PageToFlag(file.Page());
buff[1] = opos;
buff[2] = opos >> 8;
}
void BWTransform::SwapOff() {
if (grow > 2) {
resize(bwtsize + grow);
grow = 0;
}
BWRBuffer(buff + 3, file.data(), file.PageSize(),
buff[1] | ((buff[2]) << 8));
}
void BWTransformSTDIN::LoadPage(size_t p) {
bwtsize = file.size();
if (bwtsize == 0) {
return;
}
offsetPages = p;
byte * filepage = file.data();
size_t i;
for (i = 0; i < file.size() && i < file.Page(); ++i) {
filepage[i] = file[i];
}
grow = i + sizeof(uint16_t);
if (p == 0) {
++grow;
}
uint16_t opos = BWTBuffer(filepage, buff + 3, i);
buff[0] = PageToFlag(file.Page());
buff[1] = opos;
buff[2] = opos >> 8;
}
void BWTransformSTDOUT::LoadPage(size_t p) {
if (p == offsetPages) {
return;
} else if (offsetPages != (size_t)-1) {
SwapOff();
}
offsetPages = p;
}
void BWTransformSTDOUT::SwapOff() {
if (gpos < 2) {
return;
}
size_t off = gpos - 2;
gpos = 0;
byte * offBuff = file.data();
BWRBuffer(buff + 3, offBuff, off, buff[1] | ((buff[2]) << 8));
for (size_t i = 0; i < off; ++i) {
file[i] = offBuff[i];
}
}
| 23.434579
| 80
| 0.485543
|
Mathtin
|
1062ce617d1f9a3bdc8442fd27d859de02c7627b
| 5,990
|
cpp
|
C++
|
src/array_list.cpp
|
Algorithms-and-Data-Structures-2021/h02_data_structures-DRIbaev004
|
8f61838429414fec507b26db48d2546d31066e94
|
[
"MIT"
] | null | null | null |
src/array_list.cpp
|
Algorithms-and-Data-Structures-2021/h02_data_structures-DRIbaev004
|
8f61838429414fec507b26db48d2546d31066e94
|
[
"MIT"
] | null | null | null |
src/array_list.cpp
|
Algorithms-and-Data-Structures-2021/h02_data_structures-DRIbaev004
|
8f61838429414fec507b26db48d2546d31066e94
|
[
"MIT"
] | null | null | null |
#include "array_list.hpp" // подключаем заголовочный файл с объявлениями
#include <algorithm> // copy, fill
#include <cassert> // assert
#include <stdexcept> // out_of_range, invalid_argument
#include "private/internal.hpp" // вспомогательные функции
namespace itis {
ArrayList::ArrayList(int capacity) : capacity_{capacity} {
if (capacity <= 0) {
throw std::invalid_argument("ArrayList::capacity must be positive");
}
// Tip 1: используйте std::fill для заполнения выделенных ячеек массива значением Element::UNINITIALIZED
// здесь должен быть ваш код ...
data_ = new Element[capacity_]{};
std::fill(data_, data_ + capacity_, Element::UNINITIALIZED);
}
ArrayList::~ArrayList() {
// Tip 1: высвободите выделенную память
// Tip 2: не забудьте про логическую целостность объекта (инвариантность)
if (data_ != nullptr) {
delete[] data_;
data_ = nullptr;
}
size_ = 0;
capacity_ = 0;
}
void ArrayList::Add(Element e) {
// Tip 1: используйте метод resize(new_capacity) для расширения емкости массива
// здесь должен быть ваш код ...
if (size_ == capacity_)
resize(capacity_+kCapacityGrowthCoefficient);
assert(size_ < capacity_); // я здесь, чтобы не дать тебе сойти с правильного пути
// напишите свой код после расширения емкости массива здесь ...
data_[size_++] = e;
}
void ArrayList::Insert(int index, Element e) {
if (index != 0 && index != size_) {
// index = 0 и index == size это особые случаи, при которых всегда можно выполнить операцию вставки
internal::check_out_of_range(index, 0, size_);
}
// Tip 1: используйте метод resize(new_capacity) для расширения емкости массива
// напишите свой код здесь ...
if (size_ >= capacity_)
resize(capacity_+kCapacityGrowthCoefficient);
assert(size_ < capacity_); // я ни в коем случае не дам вам совершить ошибку всей вашей жизни
// Tip 2: для свдига элементов вправо можете использовать std::copy
// напишите свой код после расширения емкости массива здесь ...
std::copy(data_ + index, data_ + size_, data_ + index + 1);
data_[index] = e;
size_ += 1;
}
void ArrayList::Set(int index, Element value) {
internal::check_out_of_range(index, 0, size_);
// напишите свой код здесь ...
data_[index] = value;
}
Element ArrayList::Remove(int index) {
internal::check_out_of_range(index, 0, size_);
// Tip 1: можете использовать std::copy для сдвига элементов влево
// Tip 2: не забудьте задать значение Element::UNINITIALIZED освободившейся ячейке
// напишите свой код здесь ...
Element element = data_[index];
std::copy(data_ + index + 1, data_+size_, data_+index );
data_[size_ - 1] = Element::UNINITIALIZED;
size_--;
return element;
}
void ArrayList::Clear() {
// Tip 1: можете использовать std::fill для заполнения ячеек массива значением Element::UNINITIALIZED
// напишите свой код здесь ...
std::fill(data_, data_+capacity_, Element::UNINITIALIZED);
size_ = 0;
}
Element ArrayList::Get(int index) const {
internal::check_out_of_range(index, 0, size_);
// напишите свой код здесь ...
return data_[index];
}
int ArrayList::IndexOf(Element e) const {
// напишите свой код здесь ...
for (int i = 0; i < size_; ++i) {
if (data_[i] == e){
return i;
}
}
return -1;
}
// === РЕАЛИЗОВАНО ===
bool ArrayList::Contains(Element e) const {
// здесь был Рамиль
return IndexOf(e) != kNotFoundElementIndex;
}
// это делегирующий конструктор если что
ArrayList::ArrayList() : ArrayList(kInitCapacity) {}
int ArrayList::GetSize() const {
return size_;
}
int ArrayList::GetCapacity() const {
return capacity_;
}
bool ArrayList::IsEmpty() const {
return size_ == 0;
}
// Легенда: давным давно на планете под названием Земля жил да был Аватар...
// Аватар мог управлять четырьмя стихиями, но никак не мог совладать с C++ (фейспалм).
// Помогите найти непростительную ошибку Аватара,
// которая привела к гибели десятков тысяч котиков (плак-плак, шмыгание носом, втягивание соплей).
// P.S. кол-во ошибок может быть более одной, порядку операций можно верить
void ArrayList::resize(int new_capacity) {
assert(new_capacity > capacity_); // не ошибается тот, кто ничего не делает ...
// 1. выделяем новый участок памяти
auto new_data = new Element[new_capacity];
// 2. копируем данные на новый участок
std::copy(data_, data_ + size_, new_data);
// 3. заполняем "свободные" ячейки памяти значением Element::UNINITIALIZED
std::fill(new_data + size_, new_data + new_capacity, Element::UNINITIALIZED);
// 4. высвобождаем старый участок памяти меньшего размера
delete[] data_;
// 5. пересылаем указатель на новый участок памяти
data_ = new_data;
// 6. не забываем посолить ... кхм... обновить емкость массива
capacity_ = new_capacity;
}
// === ЗОНА 51: необходимо для тестирования ===
ArrayList::ArrayList(Element *data, int size, int capacity) : size_{size}, capacity_{capacity} {
assert(capacity > 0 && size >= 0 && size <= capacity);
data_ = new Element[capacity];
std::fill(data_, data_ + capacity, Element::UNINITIALIZED);
if (data != nullptr) {
std::copy(data, data + size, data_);
}
}
std::ostream &operator<<(std::ostream &os, const ArrayList &list) {
if (list.data_ != nullptr) {
os << "{ ";
for (int index = 0; index < list.capacity_ - 1; index++) {
os << internal::elem_to_str(list.data_[index]) << ", ";
}
os << internal::elem_to_str(list.data_[list.capacity_ - 1]) << " }";
} else {
os << "{ nullptr }";
}
return os;
}
bool operator==(const ArrayList &list, const std::vector<Element> &elements) {
if (list.data_ == nullptr) return false;
if (list.capacity_ != static_cast<int>(elements.size())) return false;
for (int index = 0; index < list.capacity_; index++) {
if (list.data_[index] != elements.at(index)) return false;
}
return true;
}
} // namespace itis
| 31.197917
| 106
| 0.676294
|
Algorithms-and-Data-Structures-2021
|
106323492a98902789dfeb47937ab53fcc9a0397
| 74,686
|
hpp
|
C++
|
packages/kokkos/core/unit_test/TestViewSubview.hpp
|
mathstuf/seacas
|
49b3466e3bba12ec6597e364ce0f0f149f9ca909
|
[
"BSD-3-Clause",
"NetCDF",
"Zlib",
"MIT"
] | null | null | null |
packages/kokkos/core/unit_test/TestViewSubview.hpp
|
mathstuf/seacas
|
49b3466e3bba12ec6597e364ce0f0f149f9ca909
|
[
"BSD-3-Clause",
"NetCDF",
"Zlib",
"MIT"
] | null | null | null |
packages/kokkos/core/unit_test/TestViewSubview.hpp
|
mathstuf/seacas
|
49b3466e3bba12ec6597e364ce0f0f149f9ca909
|
[
"BSD-3-Clause",
"NetCDF",
"Zlib",
"MIT"
] | null | null | null |
/*
//@HEADER
// ************************************************************************
//
// Kokkos v. 2.0
// Copyright (2014) Sandia Corporation
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Questions? Contact H. Carter Edwards (hcedwar@sandia.gov)
//
// ************************************************************************
//@HEADER
*/
#ifndef TESTVIEWSUBVIEW_HPP_
#define TESTVIEWSUBVIEW_HPP_
#include <gtest/gtest.h>
#include <Kokkos_Core.hpp>
#include <stdexcept>
#include <sstream>
#include <iostream>
namespace TestViewSubview {
template< class Layout, class Space >
struct getView {
static
Kokkos::View< double**, Layout, Space > get( int n, int m ) {
return Kokkos::View< double**, Layout, Space >( "G", n, m );
}
};
template< class Space >
struct getView< Kokkos::LayoutStride, Space > {
static
Kokkos::View< double**, Kokkos::LayoutStride, Space > get( int n, int m ) {
const int rank = 2;
const int order[] = { 0, 1 };
const unsigned dim[] = { unsigned( n ), unsigned( m ) };
Kokkos::LayoutStride stride = Kokkos::LayoutStride::order_dimensions( rank, order, dim );
return Kokkos::View< double**, Kokkos::LayoutStride, Space >( "G", stride );
}
};
template< class ViewType, class Space >
struct fill_1D {
typedef typename Space::execution_space execution_space;
typedef typename ViewType::size_type size_type;
ViewType a;
double val;
fill_1D( ViewType a_, double val_ ) : a( a_ ), val( val_ ) {}
KOKKOS_INLINE_FUNCTION
void operator()( const int i ) const { a( i ) = val; }
};
template< class ViewType, class Space >
struct fill_2D {
typedef typename Space::execution_space execution_space;
typedef typename ViewType::size_type size_type;
ViewType a;
double val;
fill_2D( ViewType a_, double val_ ) : a( a_ ), val( val_ ) {}
KOKKOS_INLINE_FUNCTION
void operator()( const int i ) const
{
for ( int j = 0; j < static_cast< int >( a.dimension_1() ); j++ ) {
a( i, j ) = val;
}
}
};
template< class Layout, class Space >
void test_auto_1d ()
{
typedef Kokkos::View< double**, Layout, Space > mv_type;
typedef typename mv_type::size_type size_type;
const double ZERO = 0.0;
const double ONE = 1.0;
const double TWO = 2.0;
const size_type numRows = 10;
const size_type numCols = 3;
mv_type X = getView< Layout, Space >::get( numRows, numCols );
typename mv_type::HostMirror X_h = Kokkos::create_mirror_view( X );
fill_2D< mv_type, Space > f1( X, ONE );
Kokkos::parallel_for( X.dimension_0(), f1 );
Kokkos::fence();
Kokkos::deep_copy( X_h, X );
for ( size_type j = 0; j < numCols; ++j ) {
for ( size_type i = 0; i < numRows; ++i ) {
ASSERT_TRUE( X_h( i, j ) == ONE );
}
}
fill_2D< mv_type, Space > f2( X, 0.0 );
Kokkos::parallel_for( X.dimension_0(), f2 );
Kokkos::fence();
Kokkos::deep_copy( X_h, X );
for ( size_type j = 0; j < numCols; ++j ) {
for ( size_type i = 0; i < numRows; ++i ) {
ASSERT_TRUE( X_h( i, j ) == ZERO );
}
}
fill_2D< mv_type, Space > f3( X, TWO );
Kokkos::parallel_for( X.dimension_0(), f3 );
Kokkos::fence();
Kokkos::deep_copy( X_h, X );
for ( size_type j = 0; j < numCols; ++j ) {
for ( size_type i = 0; i < numRows; ++i ) {
ASSERT_TRUE( X_h( i, j ) == TWO );
}
}
for ( size_type j = 0; j < numCols; ++j ) {
auto X_j = Kokkos::subview( X, Kokkos::ALL, j );
fill_1D< decltype( X_j ), Space > f4( X_j, ZERO );
Kokkos::parallel_for( X_j.dimension_0(), f4 );
Kokkos::fence();
Kokkos::deep_copy( X_h, X );
for ( size_type i = 0; i < numRows; ++i ) {
ASSERT_TRUE( X_h( i, j ) == ZERO );
}
for ( size_type jj = 0; jj < numCols; ++jj ) {
auto X_jj = Kokkos::subview ( X, Kokkos::ALL, jj );
fill_1D< decltype( X_jj ), Space > f5( X_jj, ONE );
Kokkos::parallel_for( X_jj.dimension_0(), f5 );
Kokkos::fence();
Kokkos::deep_copy( X_h, X );
for ( size_type i = 0; i < numRows; ++i ) {
ASSERT_TRUE( X_h( i, jj ) == ONE );
}
}
}
}
template< class LD, class LS, class Space >
void test_1d_strided_assignment_impl( bool a, bool b, bool c, bool d, int n, int m ) {
Kokkos::View< double**, LS, Space > l2d( "l2d", n, m );
int col = n > 2 ? 2 : 0;
int row = m > 2 ? 2 : 0;
if ( Kokkos::Impl::SpaceAccessibility< Kokkos::HostSpace, typename Space::memory_space >::accessible ) {
if ( a ) {
Kokkos::View< double*, LD, Space > l1da = Kokkos::subview( l2d, Kokkos::ALL, row );
ASSERT_TRUE( & l1da( 0 ) == & l2d( 0, row ) );
if ( n > 1 ) {
ASSERT_TRUE( & l1da( 1 ) == & l2d( 1, row ) );
}
}
if ( b && n > 13 ) {
Kokkos::View< double*, LD, Space > l1db = Kokkos::subview( l2d, std::pair< unsigned, unsigned >( 2, 13 ), row );
ASSERT_TRUE( & l1db( 0 ) == & l2d( 2, row ) );
ASSERT_TRUE( & l1db( 1 ) == & l2d( 3, row ) );
}
if ( c ) {
Kokkos::View< double*, LD, Space > l1dc = Kokkos::subview( l2d, col, Kokkos::ALL );
ASSERT_TRUE( & l1dc( 0 ) == & l2d( col, 0 ) );
if( m > 1 ) {
ASSERT_TRUE( & l1dc( 1 ) == & l2d( col, 1 ) );
}
}
if ( d && m > 13 ) {
Kokkos::View< double*, LD, Space > l1dd = Kokkos::subview( l2d, col, std::pair< unsigned, unsigned >( 2, 13 ) );
ASSERT_TRUE( & l1dd( 0 ) == & l2d( col, 2 ) );
ASSERT_TRUE( & l1dd( 1 ) == & l2d( col, 3 ) );
}
}
}
template< class Space >
void test_1d_strided_assignment() {
test_1d_strided_assignment_impl< Kokkos::LayoutStride, Kokkos::LayoutLeft, Space >( true, true, true, true, 17, 3 );
test_1d_strided_assignment_impl< Kokkos::LayoutStride, Kokkos::LayoutRight, Space >( true, true, true, true, 17, 3 );
test_1d_strided_assignment_impl< Kokkos::LayoutLeft, Kokkos::LayoutLeft, Space >( true, true, false, false, 17, 3 );
test_1d_strided_assignment_impl< Kokkos::LayoutRight, Kokkos::LayoutLeft, Space >( true, true, false, false, 17, 3 );
test_1d_strided_assignment_impl< Kokkos::LayoutLeft, Kokkos::LayoutRight, Space >( false, false, true, true, 17, 3 );
test_1d_strided_assignment_impl< Kokkos::LayoutRight, Kokkos::LayoutRight, Space >( false, false, true, true, 17, 3 );
test_1d_strided_assignment_impl< Kokkos::LayoutLeft, Kokkos::LayoutLeft, Space >( true, true, false, false, 17, 1 );
test_1d_strided_assignment_impl< Kokkos::LayoutLeft, Kokkos::LayoutLeft, Space >( true, true, true, true, 1, 17 );
test_1d_strided_assignment_impl< Kokkos::LayoutRight, Kokkos::LayoutLeft, Space >( true, true, true, true, 1, 17 );
test_1d_strided_assignment_impl< Kokkos::LayoutRight, Kokkos::LayoutLeft, Space >( true, true, false, false, 17, 1 );
test_1d_strided_assignment_impl< Kokkos::LayoutLeft, Kokkos::LayoutRight, Space >( true, true, true, true, 17, 1 );
test_1d_strided_assignment_impl< Kokkos::LayoutLeft, Kokkos::LayoutRight, Space >( false, false, true, true, 1, 17 );
test_1d_strided_assignment_impl< Kokkos::LayoutRight, Kokkos::LayoutRight, Space >( false, false, true, true, 1, 17 );
test_1d_strided_assignment_impl< Kokkos::LayoutRight, Kokkos::LayoutRight, Space >( true, true, true, true, 17, 1 );
}
template< class Space >
void test_left_0()
{
typedef Kokkos::View< int [2][3][4][5][2][3][4][5], Kokkos::LayoutLeft, Space > view_static_8_type;
if ( Kokkos::Impl::SpaceAccessibility< Kokkos::HostSpace, typename Space::memory_space >::accessible ) {
view_static_8_type x_static_8( "x_static_left_8" );
ASSERT_TRUE( x_static_8.is_contiguous() );
Kokkos::View< int, Kokkos::LayoutLeft, Space > x0 = Kokkos::subview( x_static_8, 0, 0, 0, 0, 0, 0, 0, 0 );
ASSERT_TRUE( x0.is_contiguous() );
ASSERT_TRUE( & x0() == & x_static_8( 0, 0, 0, 0, 0, 0, 0, 0 ) );
Kokkos::View< int*, Kokkos::LayoutLeft, Space > x1 =
Kokkos::subview( x_static_8, Kokkos::pair< int, int >( 0, 2 ), 1, 2, 3, 0, 1, 2, 3 );
ASSERT_TRUE( x1.is_contiguous() );
ASSERT_TRUE( & x1( 0 ) == & x_static_8( 0, 1, 2, 3, 0, 1, 2, 3 ) );
ASSERT_TRUE( & x1( 1 ) == & x_static_8( 1, 1, 2, 3, 0, 1, 2, 3 ) );
Kokkos::View< int**, Kokkos::LayoutLeft, Space > x2 =
Kokkos::subview( x_static_8, Kokkos::pair< int, int >( 0, 2 ), 1, 2, 3
, Kokkos::pair< int, int >( 0, 2 ), 1, 2, 3 );
ASSERT_TRUE( ! x2.is_contiguous() );
ASSERT_TRUE( & x2( 0, 0 ) == & x_static_8( 0, 1, 2, 3, 0, 1, 2, 3 ) );
ASSERT_TRUE( & x2( 1, 0 ) == & x_static_8( 1, 1, 2, 3, 0, 1, 2, 3 ) );
ASSERT_TRUE( & x2( 0, 1 ) == & x_static_8( 0, 1, 2, 3, 1, 1, 2, 3 ) );
ASSERT_TRUE( & x2( 1, 1 ) == & x_static_8( 1, 1, 2, 3, 1, 1, 2, 3 ) );
// Kokkos::View< int**, Kokkos::LayoutLeft, Space > error_2 =
Kokkos::View< int**, Kokkos::LayoutStride, Space > sx2 =
Kokkos::subview( x_static_8, 1, Kokkos::pair< int, int >( 0, 2 ), 2, 3
, Kokkos::pair< int, int >( 0, 2 ), 1, 2, 3 );
ASSERT_TRUE( ! sx2.is_contiguous() );
ASSERT_TRUE( & sx2( 0, 0 ) == & x_static_8( 1, 0, 2, 3, 0, 1, 2, 3 ) );
ASSERT_TRUE( & sx2( 1, 0 ) == & x_static_8( 1, 1, 2, 3, 0, 1, 2, 3 ) );
ASSERT_TRUE( & sx2( 0, 1 ) == & x_static_8( 1, 0, 2, 3, 1, 1, 2, 3 ) );
ASSERT_TRUE( & sx2( 1, 1 ) == & x_static_8( 1, 1, 2, 3, 1, 1, 2, 3 ) );
Kokkos::View< int****, Kokkos::LayoutStride, Space > sx4 =
Kokkos::subview( x_static_8, 0, Kokkos::pair< int, int >( 0, 2 ) /* of [3] */
, 1, Kokkos::pair< int, int >( 1, 3 ) /* of [5] */
, 1, Kokkos::pair< int, int >( 0, 2 ) /* of [3] */
, 2, Kokkos::pair< int, int >( 2, 4 ) /* of [5] */
);
ASSERT_TRUE( ! sx4.is_contiguous() );
for ( int i0 = 0; i0 < (int) sx4.dimension_0(); ++i0 )
for ( int i1 = 0; i1 < (int) sx4.dimension_1(); ++i1 )
for ( int i2 = 0; i2 < (int) sx4.dimension_2(); ++i2 )
for ( int i3 = 0; i3 < (int) sx4.dimension_3(); ++i3 )
{
ASSERT_TRUE( & sx4( i0, i1, i2, i3 ) == & x_static_8( 0, 0 + i0, 1, 1 + i1, 1, 0 + i2, 2, 2 + i3 ) );
}
}
}
template< class Space >
void test_left_1()
{
typedef Kokkos::View< int ****[2][3][4][5], Kokkos::LayoutLeft, Space > view_type;
if ( Kokkos::Impl::SpaceAccessibility< Kokkos::HostSpace, typename Space::memory_space >::accessible ) {
view_type x8( "x_left_8", 2, 3, 4, 5 );
ASSERT_TRUE( x8.is_contiguous() );
Kokkos::View< int, Kokkos::LayoutLeft, Space > x0 = Kokkos::subview( x8, 0, 0, 0, 0, 0, 0, 0, 0 );
ASSERT_TRUE( x0.is_contiguous() );
ASSERT_TRUE( & x0() == & x8( 0, 0, 0, 0, 0, 0, 0, 0 ) );
Kokkos::View< int*, Kokkos::LayoutLeft, Space > x1 =
Kokkos::subview( x8, Kokkos::pair< int, int >( 0, 2 ), 1, 2, 3, 0, 1, 2, 3 );
ASSERT_TRUE( x1.is_contiguous() );
ASSERT_TRUE( & x1( 0 ) == & x8( 0, 1, 2, 3, 0, 1, 2, 3 ) );
ASSERT_TRUE( & x1( 1 ) == & x8( 1, 1, 2, 3, 0, 1, 2, 3 ) );
Kokkos::View< int**, Kokkos::LayoutLeft, Space > x2 =
Kokkos::subview( x8, Kokkos::pair< int, int >( 0, 2 ), 1, 2, 3
, Kokkos::pair< int, int >( 0, 2 ), 1, 2, 3 );
ASSERT_TRUE( ! x2.is_contiguous() );
ASSERT_TRUE( & x2( 0, 0 ) == & x8( 0, 1, 2, 3, 0, 1, 2, 3 ) );
ASSERT_TRUE( & x2( 1, 0 ) == & x8( 1, 1, 2, 3, 0, 1, 2, 3 ) );
ASSERT_TRUE( & x2( 0, 1 ) == & x8( 0, 1, 2, 3, 1, 1, 2, 3 ) );
ASSERT_TRUE( & x2( 1, 1 ) == & x8( 1, 1, 2, 3, 1, 1, 2, 3 ) );
// Kokkos::View< int**, Kokkos::LayoutLeft, Space > error_2 =
Kokkos::View< int**, Kokkos::LayoutStride, Space > sx2 =
Kokkos::subview( x8, 1, Kokkos::pair< int, int >( 0, 2 ), 2, 3
, Kokkos::pair< int, int >( 0, 2 ), 1, 2, 3 );
ASSERT_TRUE( ! sx2.is_contiguous() );
ASSERT_TRUE( & sx2( 0, 0 ) == & x8( 1, 0, 2, 3, 0, 1, 2, 3 ) );
ASSERT_TRUE( & sx2( 1, 0 ) == & x8( 1, 1, 2, 3, 0, 1, 2, 3 ) );
ASSERT_TRUE( & sx2( 0, 1 ) == & x8( 1, 0, 2, 3, 1, 1, 2, 3 ) );
ASSERT_TRUE( & sx2( 1, 1 ) == & x8( 1, 1, 2, 3, 1, 1, 2, 3 ) );
Kokkos::View< int****, Kokkos::LayoutStride, Space > sx4 =
Kokkos::subview( x8, 0, Kokkos::pair< int, int >( 0, 2 ) /* of [3] */
, 1, Kokkos::pair< int, int >( 1, 3 ) /* of [5] */
, 1, Kokkos::pair< int, int >( 0, 2 ) /* of [3] */
, 2, Kokkos::pair< int, int >( 2, 4 ) /* of [5] */
);
ASSERT_TRUE( ! sx4.is_contiguous() );
for ( int i0 = 0; i0 < (int) sx4.dimension_0(); ++i0 )
for ( int i1 = 0; i1 < (int) sx4.dimension_1(); ++i1 )
for ( int i2 = 0; i2 < (int) sx4.dimension_2(); ++i2 )
for ( int i3 = 0; i3 < (int) sx4.dimension_3(); ++i3 )
{
ASSERT_TRUE( & sx4( i0, i1, i2, i3 ) == & x8( 0, 0 + i0, 1, 1 + i1, 1, 0 + i2, 2, 2 + i3 ) );
}
}
}
template< class Space >
void test_left_2()
{
typedef Kokkos::View< int ****, Kokkos::LayoutLeft, Space > view_type;
if ( Kokkos::Impl::SpaceAccessibility<Kokkos::HostSpace, typename Space::memory_space>::accessible ) {
view_type x4( "x4", 2, 3, 4, 5 );
ASSERT_TRUE( x4.is_contiguous() );
Kokkos::View< int, Kokkos::LayoutLeft, Space > x0 = Kokkos::subview( x4, 0, 0, 0, 0 );
ASSERT_TRUE( x0.is_contiguous() );
ASSERT_TRUE( & x0() == & x4( 0, 0, 0, 0 ) );
Kokkos::View< int*, Kokkos::LayoutLeft, Space > x1 =
Kokkos::subview( x4, Kokkos::pair< int, int >( 0, 2 ), 1, 2, 3 );
ASSERT_TRUE( x1.is_contiguous() );
ASSERT_TRUE( & x1( 0 ) == & x4( 0, 1, 2, 3 ) );
ASSERT_TRUE( & x1( 1 ) == & x4( 1, 1, 2, 3 ) );
Kokkos::View< int**, Kokkos::LayoutLeft, Space > x2 =
Kokkos::subview( x4, Kokkos::pair< int, int >( 0, 2 ), 1
, Kokkos::pair< int, int >( 1, 3 ), 2 );
ASSERT_TRUE( ! x2.is_contiguous() );
ASSERT_TRUE( & x2( 0, 0 ) == & x4( 0, 1, 1, 2 ) );
ASSERT_TRUE( & x2( 1, 0 ) == & x4( 1, 1, 1, 2 ) );
ASSERT_TRUE( & x2( 0, 1 ) == & x4( 0, 1, 2, 2 ) );
ASSERT_TRUE( & x2( 1, 1 ) == & x4( 1, 1, 2, 2 ) );
// Kokkos::View< int**, Kokkos::LayoutLeft, Space > error_2 =
Kokkos::View< int**, Kokkos::LayoutStride, Space > sx2 =
Kokkos::subview( x4, 1, Kokkos::pair< int, int >( 0, 2 )
, 2, Kokkos::pair< int, int >( 1, 4 ) );
ASSERT_TRUE( ! sx2.is_contiguous() );
ASSERT_TRUE( & sx2( 0, 0 ) == & x4( 1, 0, 2, 1 ) );
ASSERT_TRUE( & sx2( 1, 0 ) == & x4( 1, 1, 2, 1 ) );
ASSERT_TRUE( & sx2( 0, 1 ) == & x4( 1, 0, 2, 2 ) );
ASSERT_TRUE( & sx2( 1, 1 ) == & x4( 1, 1, 2, 2 ) );
ASSERT_TRUE( & sx2( 0, 2 ) == & x4( 1, 0, 2, 3 ) );
ASSERT_TRUE( & sx2( 1, 2 ) == & x4( 1, 1, 2, 3 ) );
Kokkos::View< int****, Kokkos::LayoutStride, Space > sx4 =
Kokkos::subview( x4, Kokkos::pair< int, int >( 1, 2 ) /* of [2] */
, Kokkos::pair< int, int >( 1, 3 ) /* of [3] */
, Kokkos::pair< int, int >( 0, 4 ) /* of [4] */
, Kokkos::pair< int, int >( 2, 4 ) /* of [5] */
);
ASSERT_TRUE( ! sx4.is_contiguous() );
for ( int i0 = 0; i0 < (int) sx4.dimension_0(); ++i0 )
for ( int i1 = 0; i1 < (int) sx4.dimension_1(); ++i1 )
for ( int i2 = 0; i2 < (int) sx4.dimension_2(); ++i2 )
for ( int i3 = 0; i3 < (int) sx4.dimension_3(); ++i3 )
{
ASSERT_TRUE( & sx4( i0, i1, i2, i3 ) == & x4( 1 + i0, 1 + i1, 0 + i2, 2 + i3 ) );
}
}
}
template< class Space >
void test_left_3()
{
typedef Kokkos::View< int **, Kokkos::LayoutLeft, Space > view_type;
if ( Kokkos::Impl::SpaceAccessibility< Kokkos::HostSpace, typename Space::memory_space >::accessible ) {
view_type xm( "x4", 10, 5 );
ASSERT_TRUE( xm.is_contiguous() );
Kokkos::View< int, Kokkos::LayoutLeft, Space > x0 = Kokkos::subview( xm, 5, 3 );
ASSERT_TRUE( x0.is_contiguous() );
ASSERT_TRUE( & x0() == & xm( 5, 3 ) );
Kokkos::View< int*, Kokkos::LayoutLeft, Space > x1 = Kokkos::subview( xm, Kokkos::ALL, 3 );
ASSERT_TRUE( x1.is_contiguous() );
for ( int i = 0; i < int( xm.dimension_0() ); ++i ) {
ASSERT_TRUE( & x1( i ) == & xm( i, 3 ) );
}
Kokkos::View< int**, Kokkos::LayoutLeft, Space > x2 =
Kokkos::subview( xm, Kokkos::pair< int, int >( 1, 9 ), Kokkos::ALL );
ASSERT_TRUE( ! x2.is_contiguous() );
for ( int j = 0; j < int( x2.dimension_1() ); ++j )
for ( int i = 0; i < int( x2.dimension_0() ); ++i )
{
ASSERT_TRUE( & x2( i, j ) == & xm( 1 + i, j ) );
}
Kokkos::View< int**, Kokkos::LayoutLeft, Space > x2c =
Kokkos::subview( xm, Kokkos::ALL, std::pair< int, int >( 2, 4 ) );
ASSERT_TRUE( x2c.is_contiguous() );
for ( int j = 0; j < int( x2c.dimension_1() ); ++j )
for ( int i = 0; i < int( x2c.dimension_0() ); ++i )
{
ASSERT_TRUE( & x2c( i, j ) == & xm( i, 2 + j ) );
}
Kokkos::View< int**, Kokkos::LayoutLeft, Space > x2_n1 =
Kokkos::subview( xm, std::pair< int, int >( 1, 1 ), Kokkos::ALL );
ASSERT_TRUE( x2_n1.dimension_0() == 0 );
ASSERT_TRUE( x2_n1.dimension_1() == xm.dimension_1() );
Kokkos::View< int**, Kokkos::LayoutLeft, Space > x2_n2 =
Kokkos::subview( xm, Kokkos::ALL, std::pair< int, int >( 1, 1 ) );
ASSERT_TRUE( x2_n2.dimension_0() == xm.dimension_0() );
ASSERT_TRUE( x2_n2.dimension_1() == 0 );
}
}
//----------------------------------------------------------------------------
template< class Space >
void test_right_0()
{
typedef Kokkos::View< int [2][3][4][5][2][3][4][5], Kokkos::LayoutRight, Space > view_static_8_type;
if ( Kokkos::Impl::SpaceAccessibility<Kokkos::HostSpace, typename Space::memory_space>::accessible ) {
view_static_8_type x_static_8( "x_static_right_8" );
Kokkos::View< int, Kokkos::LayoutRight, Space > x0 = Kokkos::subview( x_static_8, 0, 0, 0, 0, 0, 0, 0, 0 );
ASSERT_TRUE( & x0() == & x_static_8( 0, 0, 0, 0, 0, 0, 0, 0 ) );
Kokkos::View< int*, Kokkos::LayoutRight, Space > x1 =
Kokkos::subview( x_static_8, 0, 1, 2, 3, 0, 1, 2, Kokkos::pair< int, int >( 1, 3 ) );
ASSERT_TRUE( x1.dimension_0() == 2 );
ASSERT_TRUE( & x1( 0 ) == & x_static_8( 0, 1, 2, 3, 0, 1, 2, 1 ) );
ASSERT_TRUE( & x1( 1 ) == & x_static_8( 0, 1, 2, 3, 0, 1, 2, 2 ) );
Kokkos::View< int**, Kokkos::LayoutRight, Space > x2 =
Kokkos::subview( x_static_8, 0, 1, 2, Kokkos::pair< int, int >( 1, 3 )
, 0, 1, 2, Kokkos::pair< int, int >( 1, 3 ) );
ASSERT_TRUE( x2.dimension_0() == 2 );
ASSERT_TRUE( x2.dimension_1() == 2 );
ASSERT_TRUE( & x2( 0, 0 ) == & x_static_8( 0, 1, 2, 1, 0, 1, 2, 1 ) );
ASSERT_TRUE( & x2( 1, 0 ) == & x_static_8( 0, 1, 2, 2, 0, 1, 2, 1 ) );
ASSERT_TRUE( & x2( 0, 1 ) == & x_static_8( 0, 1, 2, 1, 0, 1, 2, 2 ) );
ASSERT_TRUE( & x2( 1, 1 ) == & x_static_8( 0, 1, 2, 2, 0, 1, 2, 2 ) );
// Kokkos::View< int**, Kokkos::LayoutRight, Space > error_2 =
Kokkos::View< int**, Kokkos::LayoutStride, Space > sx2 =
Kokkos::subview( x_static_8, 1, Kokkos::pair< int, int >( 0, 2 ), 2, 3
, Kokkos::pair< int, int >( 0, 2 ), 1, 2, 3 );
ASSERT_TRUE( sx2.dimension_0() == 2 );
ASSERT_TRUE( sx2.dimension_1() == 2 );
ASSERT_TRUE( & sx2( 0, 0 ) == & x_static_8( 1, 0, 2, 3, 0, 1, 2, 3 ) );
ASSERT_TRUE( & sx2( 1, 0 ) == & x_static_8( 1, 1, 2, 3, 0, 1, 2, 3 ) );
ASSERT_TRUE( & sx2( 0, 1 ) == & x_static_8( 1, 0, 2, 3, 1, 1, 2, 3 ) );
ASSERT_TRUE( & sx2( 1, 1 ) == & x_static_8( 1, 1, 2, 3, 1, 1, 2, 3 ) );
Kokkos::View< int****, Kokkos::LayoutStride, Space > sx4 =
Kokkos::subview( x_static_8, 0, Kokkos::pair< int, int >( 0, 2 ) /* of [3] */
, 1, Kokkos::pair< int, int >( 1, 3 ) /* of [5] */
, 1, Kokkos::pair< int, int >( 0, 2 ) /* of [3] */
, 2, Kokkos::pair< int, int >( 2, 4 ) /* of [5] */
);
ASSERT_TRUE( sx4.dimension_0() == 2 );
ASSERT_TRUE( sx4.dimension_1() == 2 );
ASSERT_TRUE( sx4.dimension_2() == 2 );
ASSERT_TRUE( sx4.dimension_3() == 2 );
for ( int i0 = 0; i0 < (int) sx4.dimension_0(); ++i0 )
for ( int i1 = 0; i1 < (int) sx4.dimension_1(); ++i1 )
for ( int i2 = 0; i2 < (int) sx4.dimension_2(); ++i2 )
for ( int i3 = 0; i3 < (int) sx4.dimension_3(); ++i3 )
{
ASSERT_TRUE( & sx4( i0, i1, i2, i3 ) == & x_static_8( 0, 0 + i0, 1, 1 + i1, 1, 0 + i2, 2, 2 + i3 ) );
}
}
}
template< class Space >
void test_right_1()
{
typedef Kokkos::View< int ****[2][3][4][5], Kokkos::LayoutRight, Space > view_type;
if ( Kokkos::Impl::SpaceAccessibility<Kokkos::HostSpace, typename Space::memory_space>::accessible ) {
view_type x8( "x_right_8", 2, 3, 4, 5 );
Kokkos::View< int, Kokkos::LayoutRight, Space > x0 = Kokkos::subview( x8, 0, 0, 0, 0, 0, 0, 0, 0 );
ASSERT_TRUE( & x0() == & x8( 0, 0, 0, 0, 0, 0, 0, 0 ) );
Kokkos::View< int*, Kokkos::LayoutRight, Space > x1 =
Kokkos::subview( x8, 0, 1, 2, 3, 0, 1, 2, Kokkos::pair< int, int >( 1, 3 ) );
ASSERT_TRUE( & x1( 0 ) == & x8( 0, 1, 2, 3, 0, 1, 2, 1 ) );
ASSERT_TRUE( & x1( 1 ) == & x8( 0, 1, 2, 3, 0, 1, 2, 2 ) );
Kokkos::View< int**, Kokkos::LayoutRight, Space > x2 =
Kokkos::subview( x8, 0, 1, 2, Kokkos::pair< int, int >( 1, 3 )
, 0, 1, 2, Kokkos::pair< int, int >( 1, 3 ) );
ASSERT_TRUE( & x2( 0, 0 ) == & x8( 0, 1, 2, 1, 0, 1, 2, 1 ) );
ASSERT_TRUE( & x2( 1, 0 ) == & x8( 0, 1, 2, 2, 0, 1, 2, 1 ) );
ASSERT_TRUE( & x2( 0, 1 ) == & x8( 0, 1, 2, 1, 0, 1, 2, 2 ) );
ASSERT_TRUE( & x2( 1, 1 ) == & x8( 0, 1, 2, 2, 0, 1, 2, 2 ) );
// Kokkos::View< int**, Kokkos::LayoutRight, Space > error_2 =
Kokkos::View< int**, Kokkos::LayoutStride, Space > sx2 =
Kokkos::subview( x8, 1, Kokkos::pair< int, int >( 0, 2 ), 2, 3
, Kokkos::pair< int, int >( 0, 2 ), 1, 2, 3 );
ASSERT_TRUE( & sx2( 0, 0 ) == & x8( 1, 0, 2, 3, 0, 1, 2, 3 ) );
ASSERT_TRUE( & sx2( 1, 0 ) == & x8( 1, 1, 2, 3, 0, 1, 2, 3 ) );
ASSERT_TRUE( & sx2( 0, 1 ) == & x8( 1, 0, 2, 3, 1, 1, 2, 3 ) );
ASSERT_TRUE( & sx2( 1, 1 ) == & x8( 1, 1, 2, 3, 1, 1, 2, 3 ) );
Kokkos::View< int****, Kokkos::LayoutStride, Space > sx4 =
Kokkos::subview( x8, 0, Kokkos::pair< int, int >( 0, 2 ) /* of [3] */
, 1, Kokkos::pair< int, int >( 1, 3 ) /* of [5] */
, 1, Kokkos::pair< int, int >( 0, 2 ) /* of [3] */
, 2, Kokkos::pair< int, int >( 2, 4 ) /* of [5] */
);
for ( int i0 = 0; i0 < (int) sx4.dimension_0(); ++i0 )
for ( int i1 = 0; i1 < (int) sx4.dimension_1(); ++i1 )
for ( int i2 = 0; i2 < (int) sx4.dimension_2(); ++i2 )
for ( int i3 = 0; i3 < (int) sx4.dimension_3(); ++i3 )
{
ASSERT_TRUE( & sx4( i0, i1, i2, i3 ) == & x8( 0, 0 + i0, 1, 1 + i1, 1, 0 + i2, 2, 2 + i3 ) );
}
}
}
template< class Space >
void test_right_3()
{
typedef Kokkos::View< int **, Kokkos::LayoutRight, Space > view_type;
if ( Kokkos::Impl::SpaceAccessibility< Kokkos::HostSpace, typename Space::memory_space >::accessible ) {
view_type xm( "x4", 10, 5 );
ASSERT_TRUE( xm.is_contiguous() );
Kokkos::View< int, Kokkos::LayoutRight, Space > x0 = Kokkos::subview( xm, 5, 3 );
ASSERT_TRUE( x0.is_contiguous() );
ASSERT_TRUE( & x0() == & xm( 5, 3 ) );
Kokkos::View< int*, Kokkos::LayoutRight, Space > x1 = Kokkos::subview( xm, 3, Kokkos::ALL );
ASSERT_TRUE( x1.is_contiguous() );
for ( int i = 0; i < int( xm.dimension_1() ); ++i ) {
ASSERT_TRUE( & x1( i ) == & xm( 3, i ) );
}
Kokkos::View< int**, Kokkos::LayoutRight, Space > x2c =
Kokkos::subview( xm, Kokkos::pair< int, int >( 1, 9 ), Kokkos::ALL );
ASSERT_TRUE( x2c.is_contiguous() );
for ( int j = 0; j < int( x2c.dimension_1() ); ++j )
for ( int i = 0; i < int( x2c.dimension_0() ); ++i ) {
ASSERT_TRUE( & x2c( i, j ) == & xm( 1 + i, j ) );
}
Kokkos::View< int**, Kokkos::LayoutRight, Space > x2 =
Kokkos::subview( xm, Kokkos::ALL, std::pair< int, int >( 2, 4 ) );
ASSERT_TRUE( ! x2.is_contiguous() );
for ( int j = 0; j < int( x2.dimension_1() ); ++j )
for ( int i = 0; i < int( x2.dimension_0() ); ++i )
{
ASSERT_TRUE( & x2( i, j ) == & xm( i, 2 + j ) );
}
Kokkos::View< int**, Kokkos::LayoutRight, Space > x2_n1 =
Kokkos::subview( xm, std::pair< int, int >( 1, 1 ), Kokkos::ALL );
ASSERT_TRUE( x2_n1.dimension_0() == 0 );
ASSERT_TRUE( x2_n1.dimension_1() == xm.dimension_1() );
Kokkos::View< int**, Kokkos::LayoutRight, Space > x2_n2 =
Kokkos::subview( xm, Kokkos::ALL, std::pair< int, int >( 1, 1 ) );
ASSERT_TRUE( x2_n2.dimension_0() == xm.dimension_0() );
ASSERT_TRUE( x2_n2.dimension_1() == 0 );
}
}
namespace Impl {
constexpr int N0 = 113;
constexpr int N1 = 11;
constexpr int N2 = 17;
constexpr int N3 = 5;
constexpr int N4 = 7;
template< class SubView, class View >
void test_Check1D( SubView a, View b, std::pair< int, int > range ) {
int errors = 0;
for ( int i = 0; i < range.second - range.first; i++ ) {
if ( a( i ) != b( i + range.first ) ) errors++;
}
if ( errors > 0 ) {
std::cout << "Error Suviews test_Check1D: " << errors << std::endl;
}
ASSERT_TRUE( errors == 0 );
}
template< class SubView, class View >
void test_Check1D2D( SubView a, View b, int i0, std::pair< int, int > range ) {
int errors = 0;
for ( int i1 = 0; i1 < range.second - range.first; i1++ ) {
if ( a( i1 ) != b( i0, i1 + range.first ) ) errors++;
}
if ( errors > 0 ) {
std::cout << "Error Suviews test_Check1D2D: " << errors << std::endl;
}
ASSERT_TRUE( errors == 0 );
}
template< class SubView, class View >
void test_Check2D3D( SubView a, View b, int i0, std::pair< int, int > range1
, std::pair< int, int > range2 )
{
int errors = 0;
for ( int i1 = 0; i1 < range1.second - range1.first; i1++ ) {
for ( int i2 = 0; i2 < range2.second - range2.first; i2++ ) {
if ( a( i1, i2 ) != b( i0, i1 + range1.first, i2 + range2.first ) ) errors++;
}
}
if ( errors > 0 ) {
std::cout << "Error Suviews test_Check2D3D: " << errors << std::endl;
}
ASSERT_TRUE( errors == 0 );
}
template<class SubView, class View>
void test_Check3D5D( SubView a, View b, int i0, int i1, std::pair< int, int > range2
, std::pair< int, int > range3, std::pair< int, int > range4 )
{
int errors = 0;
for ( int i2 = 0; i2 < range2.second - range2.first; i2++ ) {
for ( int i3 = 0; i3 < range3.second - range3.first; i3++ ) {
for ( int i4 = 0; i4 < range4.second - range4.first; i4++ ) {
if ( a( i2, i3, i4 ) != b( i0, i1, i2 + range2.first, i3 + range3.first, i4 + range4.first ) ) {
errors++;
}
}
}
}
if ( errors > 0 ) {
std::cout << "Error Suviews test_Check3D5D: " << errors << std::endl;
}
ASSERT_TRUE( errors == 0 );
}
template< class Space, class LayoutSub, class Layout, class LayoutOrg, class MemTraits >
void test_1d_assign_impl() {
{ // Breaks.
Kokkos::View< int*, LayoutOrg, Space > a_org( "A", N0 );
Kokkos::View< int*, LayoutOrg, Space, MemTraits > a( a_org );
Kokkos::fence();
for ( int i = 0; i < N0; i++ ) a_org( i ) = i;
Kokkos::View< int[N0], Layout, Space, MemTraits > a1( a );
Kokkos::fence();
test_Check1D( a1, a, std::pair< int, int >( 0, N0 ) );
Kokkos::View< int[N0], LayoutSub, Space, MemTraits > a2( a1 );
Kokkos::fence();
test_Check1D( a2, a, std::pair< int, int >( 0, N0 ) );
a1 = a;
test_Check1D( a1, a, std::pair< int, int >( 0, N0 ) );
// Runtime Fail expected.
//Kokkos::View< int[N1] > afail1( a );
// Compile Time Fail expected.
//Kokkos::View< int[N1] > afail2( a1 );
}
{ // Works.
Kokkos::View< int[N0], LayoutOrg, Space, MemTraits > a( "A" );
Kokkos::View< int*, Layout, Space, MemTraits > a1( a );
Kokkos::fence();
test_Check1D( a1, a, std::pair< int, int >( 0, N0 ) );
a1 = a;
Kokkos::fence();
test_Check1D( a1, a, std::pair< int, int >( 0, N0 ) );
}
}
template< class Space, class Type, class TypeSub, class LayoutSub, class Layout, class LayoutOrg, class MemTraits >
void test_2d_subview_3d_impl_type() {
Kokkos::View< int***, LayoutOrg, Space > a_org( "A", N0, N1, N2 );
Kokkos::View< Type, Layout, Space, MemTraits > a( a_org );
for ( int i0 = 0; i0 < N0; i0++ )
for ( int i1 = 0; i1 < N1; i1++ )
for ( int i2 = 0; i2 < N2; i2++ )
{
a_org( i0, i1, i2 ) = i0 * 1000000 + i1 * 1000 + i2;
}
Kokkos::View< TypeSub, LayoutSub, Space, MemTraits > a1;
a1 = Kokkos::subview( a, 3, Kokkos::ALL, Kokkos::ALL );
Kokkos::fence();
test_Check2D3D( a1, a, 3, std::pair< int, int >( 0, N1 ), std::pair< int, int >( 0, N2 ) );
Kokkos::View< TypeSub, LayoutSub, Space, MemTraits > a2( a, 3, Kokkos::ALL, Kokkos::ALL );
Kokkos::fence();
test_Check2D3D( a2, a, 3, std::pair< int, int >( 0, N1 ), std::pair< int, int >( 0, N2 ) );
}
template< class Space, class LayoutSub, class Layout, class LayoutOrg, class MemTraits >
void test_2d_subview_3d_impl_layout() {
test_2d_subview_3d_impl_type< Space, int[N0][N1][N2], int[N1][N2], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, int[N0][N1][N2], int* [N2], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, int[N0][N1][N2], int** , LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, int* [N1][N2], int[N1][N2], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, int* [N1][N2], int* [N2], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, int* [N1][N2], int** , LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, int** [N2], int[N1][N2], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, int** [N2], int* [N2], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, int** [N2], int** , LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, int*** , int[N1][N2], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, int*** , int* [N2], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, int*** , int** , LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, const int[N0][N1][N2], const int[N1][N2], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, const int[N0][N1][N2], const int* [N2], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, const int[N0][N1][N2], const int** , LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, const int* [N1][N2], const int[N1][N2], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, const int* [N1][N2], const int* [N2], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, const int* [N1][N2], const int** , LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, const int** [N2], const int[N1][N2], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, const int** [N2], const int* [N2], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, const int** [N2], const int** , LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, const int*** , const int[N1][N2], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, const int*** , const int* [N2], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_2d_subview_3d_impl_type< Space, const int*** , const int** , LayoutSub, Layout, LayoutOrg, MemTraits >();
}
template< class Space, class Type, class TypeSub, class LayoutSub, class Layout, class LayoutOrg, class MemTraits >
void test_3d_subview_5d_impl_type() {
Kokkos::View< int*****, LayoutOrg, Space > a_org( "A", N0, N1, N2, N3, N4 );
Kokkos::View< Type, Layout, Space, MemTraits > a( a_org );
for ( int i0 = 0; i0 < N0; i0++ )
for ( int i1 = 0; i1 < N1; i1++ )
for ( int i2 = 0; i2 < N2; i2++ )
for ( int i3 = 0; i3 < N3; i3++ )
for ( int i4 = 0; i4 < N4; i4++ )
{
a_org( i0, i1, i2, i3, i4 ) = i0 * 1000000 + i1 * 10000 + i2 * 100 + i3 * 10 + i4;
}
Kokkos::View< TypeSub, LayoutSub, Space, MemTraits > a1;
a1 = Kokkos::subview( a, 3, 5, Kokkos::ALL, Kokkos::ALL, Kokkos::ALL );
Kokkos::fence();
test_Check3D5D( a1, a, 3, 5, std::pair< int, int >( 0, N2 ), std::pair< int, int >( 0, N3 ), std::pair< int, int >( 0, N4 ) );
Kokkos::View< TypeSub, LayoutSub, Space, MemTraits > a2( a, 3, 5, Kokkos::ALL, Kokkos::ALL, Kokkos::ALL );
Kokkos::fence();
test_Check3D5D( a2, a, 3, 5, std::pair< int, int >( 0, N2 ), std::pair< int, int >( 0, N3 ), std::pair< int, int >( 0, N4 ) );
}
template< class Space, class LayoutSub, class Layout, class LayoutOrg, class MemTraits >
void test_3d_subview_5d_impl_layout() {
test_3d_subview_5d_impl_type< Space, int[N0][N1][N2][N3][N4], int[N2][N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int[N0][N1][N2][N3][N4], int* [N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int[N0][N1][N2][N3][N4], int** [N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int[N0][N1][N2][N3][N4], int*** , LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int* [N1][N2][N3][N4], int[N2][N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int* [N1][N2][N3][N4], int* [N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int* [N1][N2][N3][N4], int** [N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int* [N1][N2][N3][N4], int*** , LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int** [N2][N3][N4], int[N2][N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int** [N2][N3][N4], int* [N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int** [N2][N3][N4], int** [N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int** [N2][N3][N4], int*** , LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int*** [N3][N4], int[N2][N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int*** [N3][N4], int* [N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int*** [N3][N4], int** [N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int*** [N3][N4], int*** , LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int**** [N4], int[N2][N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int**** [N4], int* [N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int**** [N4], int** [N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int**** [N4], int*** , LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int***** , int[N2][N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int***** , int* [N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int***** , int** [N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, int***** , int*** , LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int[N0][N1][N2][N3][N4], const int[N2][N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int[N0][N1][N2][N3][N4], const int* [N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int[N0][N1][N2][N3][N4], const int** [N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int[N0][N1][N2][N3][N4], const int*** , LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int* [N1][N2][N3][N4], const int[N2][N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int* [N1][N2][N3][N4], const int* [N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int* [N1][N2][N3][N4], const int** [N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int* [N1][N2][N3][N4], const int*** , LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int** [N2][N3][N4], const int[N2][N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int** [N2][N3][N4], const int* [N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int** [N2][N3][N4], const int** [N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int** [N2][N3][N4], const int*** , LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int*** [N3][N4], const int[N2][N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int*** [N3][N4], const int* [N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int*** [N3][N4], const int** [N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int*** [N3][N4], const int*** , LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int**** [N4], const int[N2][N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int**** [N4], const int* [N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int**** [N4], const int** [N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int**** [N4], const int*** , LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int***** , const int[N2][N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int***** , const int* [N3][N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int***** , const int** [N4], LayoutSub, Layout, LayoutOrg, MemTraits >();
test_3d_subview_5d_impl_type< Space, const int***** , const int*** , LayoutSub, Layout, LayoutOrg, MemTraits >();
}
inline
void test_subview_legal_args_right() {
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, Kokkos::pair<int, int>, int, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::pair<int, int>, Kokkos::pair<int, int>, Kokkos::pair<int, int>, int, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::pair<int, int>, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::Impl::ALL_t, int, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::Impl::ALL_t, int, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::Impl::ALL_t, int, Kokkos::pair<int, int>, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::Impl::ALL_t, int, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::pair<int, int>, int, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::pair<int, int>, int, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::pair<int, int>, int, Kokkos::pair<int, int>, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::pair<int, int>, int, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int, Kokkos::Impl::ALL_t, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int, Kokkos::Impl::ALL_t, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int, Kokkos::Impl::ALL_t, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::pair<int, int>, Kokkos::pair<int, int>, int, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, Kokkos::pair<int, int>, Kokkos::pair<int, int>, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, Kokkos::pair<int, int>, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int, Kokkos::pair<int, int> >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int, Kokkos::pair<int, int> >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int, Kokkos::pair<int, int> >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, Kokkos::pair<int, int>, Kokkos::pair<int, int>, int, Kokkos::pair<int, int> >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, Kokkos::pair<int, int>, Kokkos::pair<int, int>, int, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, int, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, Kokkos::pair<int, int> >::value ) );
ASSERT_EQ( 1, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, int, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, int, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, Kokkos::pair<int, int> >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, int, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, int, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, Kokkos::pair<int, int> >::value ) );
ASSERT_EQ( 1, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, int, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, int, Kokkos::pair<int, int>, Kokkos::pair<int, int>, Kokkos::pair<int, int> >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 5, 0, int, int, Kokkos::pair<int, int>, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 1, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 3, 0, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 3, 0, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, Kokkos::pair<int, int> >::value ) );
ASSERT_EQ( 1, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 3, 0, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 3, 0, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, Kokkos::pair<int, int> >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 3, 0, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 3, 0, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, Kokkos::pair<int, int> >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 3, 0, Kokkos::pair<int, int>, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutRight, Kokkos::LayoutRight, 3, 3, 0, Kokkos::pair<int, int>, Kokkos::pair<int, int>, Kokkos::pair<int, int> >::value ) );
}
inline
void test_subview_legal_args_left() {
ASSERT_EQ( 1, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int, int >::value ) );
ASSERT_EQ( 1, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, Kokkos::pair<int, int>, int, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int, int >::value ) );
ASSERT_EQ( 1, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int, int >::value ) );
ASSERT_EQ( 1, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::pair<int, int>, Kokkos::pair<int, int>, Kokkos::pair<int, int>, int, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::pair<int, int>, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::Impl::ALL_t, int, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::Impl::ALL_t, int, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::Impl::ALL_t, int, Kokkos::pair<int, int>, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::Impl::ALL_t, int, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::pair<int, int>, int, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::pair<int, int>, int, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::pair<int, int>, int, Kokkos::pair<int, int>, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::pair<int, int>, int, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int, Kokkos::Impl::ALL_t, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int, Kokkos::Impl::ALL_t, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int, Kokkos::Impl::ALL_t, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::pair<int, int>, Kokkos::pair<int, int>, int, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, Kokkos::pair<int, int>, Kokkos::pair<int, int>, Kokkos::pair<int, int>, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, Kokkos::pair<int, int>, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int, Kokkos::pair<int, int> >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, int, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int, Kokkos::pair<int, int> >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, int, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int, Kokkos::pair<int, int> >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, int, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, Kokkos::pair<int, int>, Kokkos::pair<int, int>, int, Kokkos::pair<int, int> >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, Kokkos::pair<int, int>, Kokkos::pair<int, int>, int, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, int, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, Kokkos::pair<int, int> >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, int, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, int, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, Kokkos::pair<int, int> >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, int, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, int, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, Kokkos::pair<int, int> >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, int, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, int, Kokkos::pair<int, int>, Kokkos::pair<int, int>, Kokkos::pair<int, int> >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 5, 0, int, int, Kokkos::pair<int, int>, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 1, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 3, 0, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, Kokkos::pair<int, int> >::value ) );
ASSERT_EQ( 1, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 3, 0, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 1, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 3, 0, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, Kokkos::pair<int, int> >::value ) );
ASSERT_EQ( 1, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 3, 0, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 3, 0, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 3, 0, Kokkos::Impl::ALL_t, Kokkos::pair<int, int>, Kokkos::pair<int, int> >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 3, 0, Kokkos::pair<int, int>, Kokkos::pair<int, int>, Kokkos::Impl::ALL_t >::value ) );
ASSERT_EQ( 0, ( Kokkos::Impl::SubviewLegalArgsCompileTime< Kokkos::LayoutLeft, Kokkos::LayoutLeft, 3, 3, 0, Kokkos::pair<int, int>, Kokkos::pair<int, int>, Kokkos::pair<int, int> >::value ) );
}
} // namespace Impl
template< class Space, class MemTraits = void >
void test_1d_assign() {
Impl::test_1d_assign_impl< Space, Kokkos::LayoutLeft, Kokkos::LayoutLeft, Kokkos::LayoutLeft, MemTraits >();
//Impl::test_1d_assign_impl< Space, Kokkos::LayoutRight, Kokkos::LayoutLeft, Kokkos::LayoutLeft >();
Impl::test_1d_assign_impl< Space, Kokkos::LayoutStride, Kokkos::LayoutLeft, Kokkos::LayoutLeft, MemTraits >();
//Impl::test_1d_assign_impl< Space, Kokkos::LayoutLeft, Kokkos::LayoutRight, Kokkos::LayoutLeft >();
Impl::test_1d_assign_impl< Space, Kokkos::LayoutRight, Kokkos::LayoutRight, Kokkos::LayoutRight, MemTraits >();
Impl::test_1d_assign_impl< Space, Kokkos::LayoutStride, Kokkos::LayoutRight, Kokkos::LayoutRight, MemTraits >();
//Impl::test_1d_assign_impl< Space, Kokkos::LayoutLeft, Kokkos::LayoutStride, Kokkos::LayoutLeft >();
//Impl::test_1d_assign_impl< Space, Kokkos::LayoutRight, Kokkos::LayoutStride, Kokkos::LayoutLeft >();
Impl::test_1d_assign_impl< Space, Kokkos::LayoutStride, Kokkos::LayoutStride, Kokkos::LayoutLeft, MemTraits >();
}
template< class Space, class MemTraits = void >
void test_2d_subview_3d() {
Impl::test_2d_subview_3d_impl_layout< Space, Kokkos::LayoutRight, Kokkos::LayoutRight, Kokkos::LayoutRight, MemTraits >();
Impl::test_2d_subview_3d_impl_layout< Space, Kokkos::LayoutStride, Kokkos::LayoutRight, Kokkos::LayoutRight, MemTraits >();
Impl::test_2d_subview_3d_impl_layout< Space, Kokkos::LayoutStride, Kokkos::LayoutStride, Kokkos::LayoutRight, MemTraits >();
Impl::test_2d_subview_3d_impl_layout< Space, Kokkos::LayoutStride, Kokkos::LayoutLeft, Kokkos::LayoutLeft, MemTraits >();
Impl::test_2d_subview_3d_impl_layout< Space, Kokkos::LayoutStride, Kokkos::LayoutStride, Kokkos::LayoutLeft, MemTraits >();
}
template< class Space, class MemTraits = void >
void test_3d_subview_5d_right() {
Impl::test_3d_subview_5d_impl_layout< Space, Kokkos::LayoutStride, Kokkos::LayoutRight, Kokkos::LayoutRight, MemTraits >();
Impl::test_3d_subview_5d_impl_layout< Space, Kokkos::LayoutStride, Kokkos::LayoutStride, Kokkos::LayoutRight, MemTraits >();
}
template< class Space, class MemTraits = void >
void test_3d_subview_5d_left() {
Impl::test_3d_subview_5d_impl_layout< Space, Kokkos::LayoutStride, Kokkos::LayoutLeft, Kokkos::LayoutLeft, MemTraits >();
Impl::test_3d_subview_5d_impl_layout< Space, Kokkos::LayoutStride, Kokkos::LayoutStride, Kokkos::LayoutLeft, MemTraits >();
}
namespace Impl {
template< class Layout, class Space >
struct FillView_3D {
Kokkos::View< int***, Layout, Space > a;
KOKKOS_INLINE_FUNCTION
void operator()( const int & ii ) const
{
const int i = std::is_same< Layout, Kokkos::LayoutLeft >::value
? ii % a.dimension_0()
: ii / ( a.dimension_1() * a.dimension_2() );
const int j = std::is_same< Layout, Kokkos::LayoutLeft >::value
? ( ii / a.dimension_0() ) % a.dimension_1()
: ( ii / a.dimension_2() ) % a.dimension_1();
const int k = std::is_same< Layout, Kokkos::LayoutRight >::value
? ii / ( a.dimension_0() * a.dimension_1() )
: ii % a.dimension_2();
a( i, j, k ) = 1000000 * i + 1000 * j + k;
}
};
template< class Layout, class Space >
struct FillView_4D {
Kokkos::View< int****, Layout, Space > a;
KOKKOS_INLINE_FUNCTION
void operator()( const int & ii ) const {
const int i = std::is_same< Layout, Kokkos::LayoutLeft >::value
? ii % a.dimension_0()
: ii / ( a.dimension_1() * a.dimension_2() * a.dimension_3() );
const int j = std::is_same< Layout, Kokkos::LayoutLeft >::value
? ( ii / a.dimension_0() ) % a.dimension_1()
: ( ii / ( a.dimension_2() * a.dimension_3() ) % a.dimension_1() );
const int k = std::is_same< Layout, Kokkos::LayoutRight >::value
? ( ii / ( a.dimension_0() * a.dimension_1() ) ) % a.dimension_2()
: ( ii / a.dimension_3() ) % a.dimension_2();
const int l = std::is_same< Layout, Kokkos::LayoutRight >::value
? ii / ( a.dimension_0() * a.dimension_1() * a.dimension_2() )
: ii % a.dimension_3();
a( i, j, k, l ) = 1000000 * i + 10000 * j + 100 * k + l;
}
};
template< class Layout, class Space, class MemTraits >
struct CheckSubviewCorrectness_3D_3D {
Kokkos::View< const int***, Layout, Space, MemTraits > a;
Kokkos::View< const int***, Layout, Space, MemTraits > b;
int offset_0, offset_2;
KOKKOS_INLINE_FUNCTION
void operator()( const int & ii ) const
{
const int i = std::is_same< Layout, Kokkos::LayoutLeft >::value
? ii % b.dimension_0()
: ii / ( b.dimension_1() * b.dimension_2() );
const int j = std::is_same< Layout, Kokkos::LayoutLeft >::value
? ( ii / b.dimension_0() ) % b.dimension_1()
: ( ii / b.dimension_2() ) % b.dimension_1();
const int k = std::is_same< Layout, Kokkos::LayoutRight >::value
? ii / ( b.dimension_0() * b.dimension_1() )
: ii % b.dimension_2();
if ( a( i + offset_0, j, k + offset_2 ) != b( i, j, k ) ) {
Kokkos::abort( "Error: check_subview_correctness 3D-3D (LayoutLeft -> LayoutLeft or LayoutRight -> LayoutRight)" );
}
}
};
template< class Layout, class Space, class MemTraits >
struct CheckSubviewCorrectness_3D_4D {
Kokkos::View< const int****, Layout, Space, MemTraits > a;
Kokkos::View< const int***, Layout, Space, MemTraits > b;
int offset_0, offset_2, index;
KOKKOS_INLINE_FUNCTION
void operator()( const int & ii ) const {
const int i = std::is_same< Layout, Kokkos::LayoutLeft >::value
? ii % b.dimension_0()
: ii / ( b.dimension_1() * b.dimension_2() );
const int j = std::is_same< Layout, Kokkos::LayoutLeft >::value
? ( ii / b.dimension_0() ) % b.dimension_1()
: ( ii / b.dimension_2() ) % b.dimension_1();
const int k = std::is_same< Layout, Kokkos::LayoutRight >::value
? ii / ( b.dimension_0() * b.dimension_1() )
: ii % b.dimension_2();
int i0, i1, i2, i3;
if ( std::is_same< Layout, Kokkos::LayoutLeft >::value ) {
i0 = i + offset_0;
i1 = j;
i2 = k + offset_2;
i3 = index;
}
else {
i0 = index;
i1 = i + offset_0;
i2 = j;
i3 = k + offset_2;
}
if ( a( i0, i1, i2, i3 ) != b( i, j, k ) ) {
Kokkos::abort( "Error: check_subview_correctness 3D-4D (LayoutLeft -> LayoutLeft or LayoutRight -> LayoutRight)" );
}
}
};
} // namespace Impl
template< class Space, class MemTraits = void >
void test_layoutleft_to_layoutleft() {
Impl::test_subview_legal_args_left();
{
Kokkos::View< int***, Kokkos::LayoutLeft, Space > a( "A", 100, 4, 3 );
Kokkos::View< int***, Kokkos::LayoutLeft, Space > b( a, Kokkos::pair< int, int >( 16, 32 ), Kokkos::ALL, Kokkos::ALL );
Impl::FillView_3D< Kokkos::LayoutLeft, Space > fill;
fill.a = a;
Kokkos::parallel_for( Kokkos::RangePolicy< typename Space::execution_space >( 0, a.extent( 0 ) * a.extent( 1 ) * a.extent( 2 ) ), fill );
Impl::CheckSubviewCorrectness_3D_3D< Kokkos::LayoutLeft, Space, MemTraits > check;
check.a = a;
check.b = b;
check.offset_0 = 16;
check.offset_2 = 0;
Kokkos::parallel_for( Kokkos::RangePolicy< typename Space::execution_space >( 0, b.extent( 0 ) * b.extent( 1 ) * b.extent( 2 ) ), check );
}
{
Kokkos::View< int***, Kokkos::LayoutLeft, Space > a( "A", 100, 4, 5 );
Kokkos::View< int***, Kokkos::LayoutLeft, Space > b( a, Kokkos::pair< int, int >( 16, 32 ), Kokkos::ALL, Kokkos::pair< int, int >( 1, 3 ) );
Impl::FillView_3D<Kokkos::LayoutLeft, Space> fill;
fill.a = a;
Kokkos::parallel_for( Kokkos::RangePolicy< typename Space::execution_space >( 0, a.extent( 0 ) * a.extent( 1 ) * a.extent( 2 ) ), fill );
Impl::CheckSubviewCorrectness_3D_3D< Kokkos::LayoutLeft, Space, MemTraits > check;
check.a = a;
check.b = b;
check.offset_0 = 16;
check.offset_2 = 1;
Kokkos::parallel_for( Kokkos::RangePolicy< typename Space::execution_space >( 0, b.extent( 0 ) * b.extent( 1 ) * b.extent( 2 ) ), check );
}
{
Kokkos::View< int****, Kokkos::LayoutLeft, Space > a( "A", 100, 4, 5, 3 );
Kokkos::View< int***, Kokkos::LayoutLeft, Space > b( a, Kokkos::pair< int, int >( 16, 32 ), Kokkos::ALL, Kokkos::pair< int, int >( 1, 3 ), 1 );
Impl::FillView_4D< Kokkos::LayoutLeft, Space > fill;
fill.a = a;
Kokkos::parallel_for( Kokkos::RangePolicy< typename Space::execution_space >( 0, a.extent( 0 ) * a.extent( 1 ) * a.extent( 2 ) * a.extent( 3 ) ), fill );
Impl::CheckSubviewCorrectness_3D_4D< Kokkos::LayoutLeft, Space, MemTraits > check;
check.a = a;
check.b = b;
check.offset_0 = 16;
check.offset_2 = 1;
check.index = 1;
Kokkos::parallel_for( Kokkos::RangePolicy< typename Space::execution_space >( 0, b.extent( 0 ) * b.extent( 1 ) * b.extent( 2 ) ), check );
}
}
template< class Space, class MemTraits = void >
void test_layoutright_to_layoutright() {
Impl::test_subview_legal_args_right();
{
Kokkos::View< int***, Kokkos::LayoutRight, Space > a( "A", 100, 4, 3 );
Kokkos::View< int***, Kokkos::LayoutRight, Space > b( a, Kokkos::pair< int, int >( 16, 32 ), Kokkos::ALL, Kokkos::ALL );
Impl::FillView_3D<Kokkos::LayoutRight, Space> fill;
fill.a = a;
Kokkos::parallel_for( Kokkos::RangePolicy< typename Space::execution_space >( 0, a.extent( 0 ) * a.extent( 1 ) * a.extent( 2 ) ), fill );
Impl::CheckSubviewCorrectness_3D_3D< Kokkos::LayoutRight, Space, MemTraits > check;
check.a = a;
check.b = b;
check.offset_0 = 16;
check.offset_2 = 0;
Kokkos::parallel_for( Kokkos::RangePolicy< typename Space::execution_space >( 0, b.extent( 0 ) * b.extent( 1 ) * b.extent( 2 ) ), check );
}
{
Kokkos::View< int****, Kokkos::LayoutRight, Space > a( "A", 3, 4, 5, 100 );
Kokkos::View< int***, Kokkos::LayoutRight, Space > b( a, 1, Kokkos::pair< int, int >( 1, 3 ), Kokkos::ALL, Kokkos::ALL );
Impl::FillView_4D< Kokkos::LayoutRight, Space > fill;
fill.a = a;
Kokkos::parallel_for( Kokkos::RangePolicy< typename Space::execution_space >( 0, a.extent( 0 ) * a.extent( 1 ) * a.extent( 2 ) * a.extent( 3 ) ), fill );
Impl::CheckSubviewCorrectness_3D_4D< Kokkos::LayoutRight, Space, MemTraits > check;
check.a = a;
check.b = b;
check.offset_0 = 1;
check.offset_2 = 0;
check.index = 1;
Kokkos::parallel_for( Kokkos::RangePolicy< typename Space::execution_space >( 0, b.extent( 0 ) * b.extent( 1 ) * b.extent( 2 ) ), check );
}
}
} // namespace TestViewSubview
#endif
| 57.494996
| 206
| 0.619808
|
mathstuf
|
10657de129cf0bec27e58132bad7f2a326edd139
| 17,327
|
cpp
|
C++
|
third/3rd_qwt/qwt_plot_spectrogram.cpp
|
alexwang815/QWidgetDemo
|
293a8d9c40d686397829c5d415fc531b6956883e
|
[
"MulanPSL-1.0"
] | 3,095
|
2019-10-11T03:00:33.000Z
|
2022-03-31T08:15:13.000Z
|
third/3rd_qwt/qwt_plot_spectrogram.cpp
|
alexwang815/QWidgetDemo
|
293a8d9c40d686397829c5d415fc531b6956883e
|
[
"MulanPSL-1.0"
] | 28
|
2019-11-12T07:24:06.000Z
|
2022-02-28T02:04:48.000Z
|
third/3rd_qwt/qwt_plot_spectrogram.cpp
|
alexwang815/QWidgetDemo
|
293a8d9c40d686397829c5d415fc531b6956883e
|
[
"MulanPSL-1.0"
] | 1,023
|
2019-10-09T12:54:07.000Z
|
2022-03-30T04:02:07.000Z
|
/* -*- mode: C++ ; c-file-style: "stroustrup" -*- *****************************
* Qwt Widget Library
* Copyright (C) 1997 Josef Wilgen
* Copyright (C) 2002 Uwe Rathmann
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the Qwt License, Version 1.0
*****************************************************************************/
#include "qwt_plot_spectrogram.h"
#include "qwt_painter.h"
#include "qwt_interval.h"
#include "qwt_scale_map.h"
#include "qwt_color_map.h"
#include <qimage.h>
#include <qpen.h>
#include <qpainter.h>
#include <qmath.h>
#include <qalgorithms.h>
#if QT_VERSION >= 0x040400
#include <qthread.h>
#include <qfuture.h>
#include <qtconcurrentrun.h>
#endif
#define DEBUG_RENDER 0
#if DEBUG_RENDER
#include <QElapsedTimer>
#endif
class QwtPlotSpectrogram::PrivateData
{
public:
PrivateData():
data( NULL )
{
colorMap = new QwtLinearColorMap();
displayMode = ImageMode;
conrecFlags = QwtRasterData::IgnoreAllVerticesOnLevel;
#if 0
conrecFlags |= QwtRasterData::IgnoreOutOfRange;
#endif
}
~PrivateData()
{
delete data;
delete colorMap;
}
QwtRasterData *data;
QwtColorMap *colorMap;
DisplayModes displayMode;
QList<double> contourLevels;
QPen defaultContourPen;
QwtRasterData::ConrecFlags conrecFlags;
};
/*!
Sets the following item attributes:
- QwtPlotItem::AutoScale: true
- QwtPlotItem::Legend: false
The z value is initialized by 8.0.
\param title Title
\sa QwtPlotItem::setItemAttribute(), QwtPlotItem::setZ()
*/
QwtPlotSpectrogram::QwtPlotSpectrogram( const QString &title ):
QwtPlotRasterItem( title )
{
d_data = new PrivateData();
setItemAttribute( QwtPlotItem::AutoScale, true );
setItemAttribute( QwtPlotItem::Legend, false );
setZ( 8.0 );
}
//! Destructor
QwtPlotSpectrogram::~QwtPlotSpectrogram()
{
delete d_data;
}
//! \return QwtPlotItem::Rtti_PlotSpectrogram
int QwtPlotSpectrogram::rtti() const
{
return QwtPlotItem::Rtti_PlotSpectrogram;
}
/*!
The display mode controls how the raster data will be represented.
\param mode Display mode
\param on On/Off
The default setting enables ImageMode.
\sa DisplayMode, displayMode()
*/
void QwtPlotSpectrogram::setDisplayMode( DisplayMode mode, bool on )
{
if ( on != bool( mode & d_data->displayMode ) )
{
if ( on )
d_data->displayMode |= mode;
else
d_data->displayMode &= ~mode;
}
legendChanged();
itemChanged();
}
/*!
The display mode controls how the raster data will be represented.
\param mode Display mode
\return true if mode is enabled
*/
bool QwtPlotSpectrogram::testDisplayMode( DisplayMode mode ) const
{
return ( d_data->displayMode & mode );
}
/*!
Change the color map
Often it is useful to display the mapping between intensities and
colors as an additional plot axis, showing a color bar.
\param colorMap Color Map
\sa colorMap(), QwtScaleWidget::setColorBarEnabled(),
QwtScaleWidget::setColorMap()
*/
void QwtPlotSpectrogram::setColorMap( QwtColorMap *colorMap )
{
if ( d_data->colorMap != colorMap )
{
delete d_data->colorMap;
d_data->colorMap = colorMap;
}
invalidateCache();
legendChanged();
itemChanged();
}
/*!
\return Color Map used for mapping the intensity values to colors
\sa setColorMap()
*/
const QwtColorMap *QwtPlotSpectrogram::colorMap() const
{
return d_data->colorMap;
}
/*!
Build and assign the default pen for the contour lines
In Qt5 the default pen width is 1.0 ( 0.0 in Qt4 ) what makes it
non cosmetic ( see QPen::isCosmetic() ). This method has been introduced
to hide this incompatibility.
\param color Pen color
\param width Pen width
\param style Pen style
\sa pen(), brush()
*/
void QwtPlotSpectrogram::setDefaultContourPen(
const QColor &color, qreal width, Qt::PenStyle style )
{
setDefaultContourPen( QPen( color, width, style ) );
}
/*!
\brief Set the default pen for the contour lines
If the spectrogram has a valid default contour pen
a contour line is painted using the default contour pen.
Otherwise (pen.style() == Qt::NoPen) the pen is calculated
for each contour level using contourPen().
\sa defaultContourPen(), contourPen()
*/
void QwtPlotSpectrogram::setDefaultContourPen( const QPen &pen )
{
if ( pen != d_data->defaultContourPen )
{
d_data->defaultContourPen = pen;
legendChanged();
itemChanged();
}
}
/*!
\return Default contour pen
\sa setDefaultContourPen()
*/
QPen QwtPlotSpectrogram::defaultContourPen() const
{
return d_data->defaultContourPen;
}
/*!
\brief Calculate the pen for a contour line
The color of the pen is the color for level calculated by the color map
\param level Contour level
\return Pen for the contour line
\note contourPen is only used if defaultContourPen().style() == Qt::NoPen
\sa setDefaultContourPen(), setColorMap(), setContourLevels()
*/
QPen QwtPlotSpectrogram::contourPen( double level ) const
{
if ( d_data->data == NULL || d_data->colorMap == NULL )
return QPen();
const QwtInterval intensityRange = d_data->data->interval(Qt::ZAxis);
const QColor c( d_data->colorMap->rgb( intensityRange, level ) );
return QPen( c );
}
/*!
Modify an attribute of the CONREC algorithm, used to calculate
the contour lines.
\param flag CONREC flag
\param on On/Off
\sa testConrecFlag(), renderContourLines(),
QwtRasterData::contourLines()
*/
void QwtPlotSpectrogram::setConrecFlag(
QwtRasterData::ConrecFlag flag, bool on )
{
if ( bool( d_data->conrecFlags & flag ) == on )
return;
if ( on )
d_data->conrecFlags |= flag;
else
d_data->conrecFlags &= ~flag;
itemChanged();
}
/*!
Test an attribute of the CONREC algorithm, used to calculate
the contour lines.
\param flag CONREC flag
\return true, is enabled
The default setting enables QwtRasterData::IgnoreAllVerticesOnLevel
\sa setConrecClag(), renderContourLines(),
QwtRasterData::contourLines()
*/
bool QwtPlotSpectrogram::testConrecFlag(
QwtRasterData::ConrecFlag flag ) const
{
return d_data->conrecFlags & flag;
}
/*!
Set the levels of the contour lines
\param levels Values of the contour levels
\sa contourLevels(), renderContourLines(),
QwtRasterData::contourLines()
\note contourLevels returns the same levels but sorted.
*/
void QwtPlotSpectrogram::setContourLevels( const QList<double> &levels )
{
d_data->contourLevels = levels;
qSort( d_data->contourLevels );
legendChanged();
itemChanged();
}
/*!
\return Levels of the contour lines.
The levels are sorted in increasing order.
\sa contourLevels(), renderContourLines(),
QwtRasterData::contourLines()
*/
QList<double> QwtPlotSpectrogram::contourLevels() const
{
return d_data->contourLevels;
}
/*!
Set the data to be displayed
\param data Spectrogram Data
\sa data()
*/
void QwtPlotSpectrogram::setData( QwtRasterData *data )
{
if ( data != d_data->data )
{
delete d_data->data;
d_data->data = data;
invalidateCache();
itemChanged();
}
}
/*!
\return Spectrogram data
\sa setData()
*/
const QwtRasterData *QwtPlotSpectrogram::data() const
{
return d_data->data;
}
/*!
\return Spectrogram data
\sa setData()
*/
QwtRasterData *QwtPlotSpectrogram::data()
{
return d_data->data;
}
/*!
\return Bounding interval for an axis
The default implementation returns the interval of the
associated raster data object.
\param axis X, Y, or Z axis
\sa QwtRasterData::interval()
*/
QwtInterval QwtPlotSpectrogram::interval(Qt::Axis axis) const
{
if ( d_data->data == NULL )
return QwtInterval();
return d_data->data->interval( axis );
}
/*!
\brief Pixel hint
The geometry of a pixel is used to calculated the resolution and
alignment of the rendered image.
The default implementation returns data()->pixelHint( rect );
\param area In most implementations the resolution of the data doesn't
depend on the requested area.
\return Bounding rectangle of a pixel
\sa QwtPlotRasterItem::pixelHint(), QwtRasterData::pixelHint(),
render(), renderImage()
*/
QRectF QwtPlotSpectrogram::pixelHint( const QRectF &area ) const
{
if ( d_data->data == NULL )
return QRectF();
return d_data->data->pixelHint( area );
}
/*!
\brief Render an image from data and color map.
For each pixel of area the value is mapped into a color.
\param xMap X-Scale Map
\param yMap Y-Scale Map
\param area Requested area for the image in scale coordinates
\param imageSize Size of the requested image
\return A QImage::Format_Indexed8 or QImage::Format_ARGB32 depending
on the color map.
\sa QwtRasterData::value(), QwtColorMap::rgb(),
QwtColorMap::colorIndex()
*/
QImage QwtPlotSpectrogram::renderImage(
const QwtScaleMap &xMap, const QwtScaleMap &yMap,
const QRectF &area, const QSize &imageSize ) const
{
if ( imageSize.isEmpty() || d_data->data == NULL
|| d_data->colorMap == NULL )
{
return QImage();
}
const QwtInterval intensityRange = d_data->data->interval( Qt::ZAxis );
if ( !intensityRange.isValid() )
return QImage();
QImage::Format format = ( d_data->colorMap->format() == QwtColorMap::RGB )
? QImage::Format_ARGB32 : QImage::Format_Indexed8;
QImage image( imageSize, format );
if ( d_data->colorMap->format() == QwtColorMap::Indexed )
image.setColorTable( d_data->colorMap->colorTable( intensityRange ) );
d_data->data->initRaster( area, image.size() );
#if DEBUG_RENDER
QElapsedTimer time;
time.start();
#endif
#if QT_VERSION >= 0x040400 && !defined(QT_NO_QFUTURE)
uint numThreads = renderThreadCount();
if ( numThreads <= 0 )
numThreads = QThread::idealThreadCount();
if ( numThreads <= 0 )
numThreads = 1;
const int numRows = imageSize.height() / numThreads;
QList< QFuture<void> > futures;
for ( uint i = 0; i < numThreads; i++ )
{
QRect tile( 0, i * numRows, image.width(), numRows );
if ( i == numThreads - 1 )
{
tile.setHeight( image.height() - i * numRows );
renderTile( xMap, yMap, tile, &image );
}
else
{
futures += QtConcurrent::run(
this, &QwtPlotSpectrogram::renderTile,
xMap, yMap, tile, &image );
}
}
for ( int i = 0; i < futures.size(); i++ )
futures[i].waitForFinished();
#else // QT_VERSION < 0x040400
const QRect tile( 0, 0, image.width(), image.height() );
renderTile( xMap, yMap, tile, &image );
#endif
#if DEBUG_RENDER
const qint64 elapsed = time.elapsed();
qDebug() << "renderImage" << imageSize << elapsed;
#endif
d_data->data->discardRaster();
return image;
}
/*!
\brief Render a tile of an image.
Rendering in tiles can be used to composite an image in parallel
threads.
\param xMap X-Scale Map
\param yMap Y-Scale Map
\param tile Geometry of the tile in image coordinates
\param image Image to be rendered
*/
void QwtPlotSpectrogram::renderTile(
const QwtScaleMap &xMap, const QwtScaleMap &yMap,
const QRect &tile, QImage *image ) const
{
const QwtInterval range = d_data->data->interval( Qt::ZAxis );
if ( !range.isValid() )
return;
if ( d_data->colorMap->format() == QwtColorMap::RGB )
{
for ( int y = tile.top(); y <= tile.bottom(); y++ )
{
const double ty = yMap.invTransform( y );
QRgb *line = reinterpret_cast<QRgb *>( image->scanLine( y ) );
line += tile.left();
for ( int x = tile.left(); x <= tile.right(); x++ )
{
const double tx = xMap.invTransform( x );
*line++ = d_data->colorMap->rgb( range,
d_data->data->value( tx, ty ) );
}
}
}
else if ( d_data->colorMap->format() == QwtColorMap::Indexed )
{
for ( int y = tile.top(); y <= tile.bottom(); y++ )
{
const double ty = yMap.invTransform( y );
unsigned char *line = image->scanLine( y );
line += tile.left();
for ( int x = tile.left(); x <= tile.right(); x++ )
{
const double tx = xMap.invTransform( x );
*line++ = d_data->colorMap->colorIndex( range,
d_data->data->value( tx, ty ) );
}
}
}
}
/*!
\brief Return the raster to be used by the CONREC contour algorithm.
A larger size will improve the precision of the CONREC algorithm,
but will slow down the time that is needed to calculate the lines.
The default implementation returns rect.size() / 2 bounded to
the resolution depending on pixelSize().
\param area Rectangle, where to calculate the contour lines
\param rect Rectangle in pixel coordinates, where to paint the contour lines
\return Raster to be used by the CONREC contour algorithm.
\note The size will be bounded to rect.size().
\sa drawContourLines(), QwtRasterData::contourLines()
*/
QSize QwtPlotSpectrogram::contourRasterSize(
const QRectF &area, const QRect &rect ) const
{
QSize raster = rect.size() / 2;
const QRectF pixelRect = pixelHint( area );
if ( !pixelRect.isEmpty() )
{
const QSize res( qCeil( rect.width() / pixelRect.width() ),
qCeil( rect.height() / pixelRect.height() ) );
raster = raster.boundedTo( res );
}
return raster;
}
/*!
Calculate contour lines
\param rect Rectangle, where to calculate the contour lines
\param raster Raster, used by the CONREC algorithm
\return Calculated contour lines
\sa contourLevels(), setConrecFlag(),
QwtRasterData::contourLines()
*/
QwtRasterData::ContourLines QwtPlotSpectrogram::renderContourLines(
const QRectF &rect, const QSize &raster ) const
{
if ( d_data->data == NULL )
return QwtRasterData::ContourLines();
return d_data->data->contourLines( rect, raster,
d_data->contourLevels, d_data->conrecFlags );
}
/*!
Paint the contour lines
\param painter Painter
\param xMap Maps x-values into pixel coordinates.
\param yMap Maps y-values into pixel coordinates.
\param contourLines Contour lines
\sa renderContourLines(), defaultContourPen(), contourPen()
*/
void QwtPlotSpectrogram::drawContourLines( QPainter *painter,
const QwtScaleMap &xMap, const QwtScaleMap &yMap,
const QwtRasterData::ContourLines &contourLines ) const
{
if ( d_data->data == NULL )
return;
const int numLevels = d_data->contourLevels.size();
for ( int l = 0; l < numLevels; l++ )
{
const double level = d_data->contourLevels[l];
QPen pen = defaultContourPen();
if ( pen.style() == Qt::NoPen )
pen = contourPen( level );
if ( pen.style() == Qt::NoPen )
continue;
painter->setPen( pen );
const QPolygonF &lines = contourLines[level];
for ( int i = 0; i < lines.size(); i += 2 )
{
const QPointF p1( xMap.transform( lines[i].x() ),
yMap.transform( lines[i].y() ) );
const QPointF p2( xMap.transform( lines[i+1].x() ),
yMap.transform( lines[i+1].y() ) );
QwtPainter::drawLine( painter, p1, p2 );
}
}
}
/*!
\brief Draw the spectrogram
\param painter Painter
\param xMap Maps x-values into pixel coordinates.
\param yMap Maps y-values into pixel coordinates.
\param canvasRect Contents rectangle of the canvas in painter coordinates
\sa setDisplayMode(), renderImage(),
QwtPlotRasterItem::draw(), drawContourLines()
*/
void QwtPlotSpectrogram::draw( QPainter *painter,
const QwtScaleMap &xMap, const QwtScaleMap &yMap,
const QRectF &canvasRect ) const
{
if ( d_data->displayMode & ImageMode )
QwtPlotRasterItem::draw( painter, xMap, yMap, canvasRect );
if ( d_data->displayMode & ContourMode )
{
// Add some pixels at the borders
const int margin = 2;
QRectF rasterRect( canvasRect.x() - margin, canvasRect.y() - margin,
canvasRect.width() + 2 * margin, canvasRect.height() + 2 * margin );
QRectF area = QwtScaleMap::invTransform( xMap, yMap, rasterRect );
const QRectF br = boundingRect();
if ( br.isValid() )
{
area &= br;
if ( area.isEmpty() )
return;
rasterRect = QwtScaleMap::transform( xMap, yMap, area );
}
QSize raster = contourRasterSize( area, rasterRect.toRect() );
raster = raster.boundedTo( rasterRect.toRect().size() );
if ( raster.isValid() )
{
const QwtRasterData::ContourLines lines =
renderContourLines( area, raster );
drawContourLines( painter, xMap, yMap, lines );
}
}
}
| 25.593796
| 80
| 0.638656
|
alexwang815
|
1065eeaf318f78ed4feed93033341be6eec19c41
| 1,077
|
hpp
|
C++
|
libs/core/include/fcppt/math/from_array.hpp
|
pmiddend/fcppt
|
9f437acbb10258e6df6982a550213a05815eb2be
|
[
"BSL-1.0"
] | null | null | null |
libs/core/include/fcppt/math/from_array.hpp
|
pmiddend/fcppt
|
9f437acbb10258e6df6982a550213a05815eb2be
|
[
"BSL-1.0"
] | null | null | null |
libs/core/include/fcppt/math/from_array.hpp
|
pmiddend/fcppt
|
9f437acbb10258e6df6982a550213a05815eb2be
|
[
"BSL-1.0"
] | null | null | null |
// Copyright Carl Philipp Reh 2009 - 2018.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef FCPPT_MATH_FROM_ARRAY_HPP_INCLUDED
#define FCPPT_MATH_FROM_ARRAY_HPP_INCLUDED
#include <fcppt/math/to_array_type.hpp>
#include <fcppt/config/external_begin.hpp>
#include <utility>
#include <fcppt/config/external_end.hpp>
namespace fcppt
{
namespace math
{
/**
\brief Constructs an object with static storage from an array rvalue
\ingroup fcpptmath
*/
template<
typename Type
>
inline
Type
from_array(
fcppt::math::to_array_type<
Type
> &&_value
)
{
return
Type{
typename
Type::storage_type{
std::move(
_value
)
}
};
}
/**
\brief Constructs an object with static storage from an array lvalue
\ingroup fcpptmath
*/
template<
typename Type
>
inline
Type
from_array(
fcppt::math::to_array_type<
Type
> const &_value
)
{
return
Type{
typename
Type::storage_type{
_value
}
};
}
}
}
#endif
| 13.987013
| 68
| 0.702878
|
pmiddend
|
10677ee5952433bf423e50d1f02b932be93f7c50
| 2,067
|
cpp
|
C++
|
logdevice/common/configuration/nodes/ServiceDiscoveryConfig.cpp
|
mickvav/LogDevice
|
24a8b6abe4576418eceb72974083aa22d7844705
|
[
"BSD-3-Clause"
] | 1
|
2021-05-19T23:01:58.000Z
|
2021-05-19T23:01:58.000Z
|
logdevice/common/configuration/nodes/ServiceDiscoveryConfig.cpp
|
mickvav/LogDevice
|
24a8b6abe4576418eceb72974083aa22d7844705
|
[
"BSD-3-Clause"
] | null | null | null |
logdevice/common/configuration/nodes/ServiceDiscoveryConfig.cpp
|
mickvav/LogDevice
|
24a8b6abe4576418eceb72974083aa22d7844705
|
[
"BSD-3-Clause"
] | null | null | null |
/**
* Copyright (c) 2017-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "ServiceDiscoveryConfig.h"
#include <folly/Range.h>
#include "logdevice/common/debug.h"
#include "logdevice/common/types_internal.h"
namespace facebook { namespace logdevice { namespace configuration {
namespace nodes {
namespace {
template <typename F>
bool isFieldValid(const F& field, folly::StringPiece name) {
if (!field.valid()) {
RATELIMIT_ERROR(
std::chrono::seconds(10), 5, "invalid %s.", name.str().c_str());
return false;
}
return true;
}
template <typename F>
bool isOptionalFieldValid(const F& field, folly::StringPiece name) {
return !field.hasValue() || isFieldValid(field.value(), name);
}
} // namespace
bool NodeServiceDiscovery::isValid() const {
if (!isFieldValid(address, "address") &&
!isFieldValid(gossip_address, "gossip_address") &&
!isOptionalFieldValid(ssl_address, "ssl_address") &&
!isOptionalFieldValid(admin_address, "admin_address")) {
return false;
}
if (roles.count() == 0) {
RATELIMIT_ERROR(std::chrono::seconds(10),
5,
"no role is set. expect at least one role.");
return false;
}
return true;
}
template <>
bool ServiceDiscoveryConfig::attributeSpecificValidate() const {
// check for address duplication in service discovery
std::unordered_map<Sockaddr, node_index_t, Sockaddr::Hash> seen_addresses;
for (const auto& kv : node_states_) {
auto res =
seen_addresses.insert(std::make_pair(kv.second.address, kv.first));
if (!res.second) {
RATELIMIT_ERROR(std::chrono::seconds(10),
5,
"Multiple nodes with the same address (idx: %hd, %hd).",
res.first->second,
kv.first);
return false;
}
}
return true;
}
}}}} // namespace facebook::logdevice::configuration::nodes
| 27.56
| 78
| 0.652637
|
mickvav
|
1069154212618384b2b5d27c09594afb0fdf6f97
| 32,407
|
cpp
|
C++
|
filament/src/Engine.cpp
|
tombsar/filament
|
20dadf06f1399fc03aaa7c8796daaf237f96416d
|
[
"Apache-2.0"
] | 1
|
2021-06-12T21:17:58.000Z
|
2021-06-12T21:17:58.000Z
|
filament/src/Engine.cpp
|
tombsar/filament
|
20dadf06f1399fc03aaa7c8796daaf237f96416d
|
[
"Apache-2.0"
] | null | null | null |
filament/src/Engine.cpp
|
tombsar/filament
|
20dadf06f1399fc03aaa7c8796daaf237f96416d
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (C) 2015 The Android Open Source Project
*
* 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 "details/Engine.h"
#include "MaterialParser.h"
#include "ResourceAllocator.h"
#include "backend/DriverEnums.h"
#include "details/DFG.h"
#include "details/VertexBuffer.h"
#include "details/Fence.h"
#include "details/Camera.h"
#include "details/IndexBuffer.h"
#include "details/IndirectLight.h"
#include "details/Material.h"
#include "details/Renderer.h"
#include "details/RenderPrimitive.h"
#include "details/Scene.h"
#include "details/Skybox.h"
#include "details/Stream.h"
#include "details/SwapChain.h"
#include "details/Texture.h"
#include "details/View.h"
#include <private/filament/SibGenerator.h>
#include <filament/MaterialEnums.h>
#include <utils/compiler.h>
#include <utils/Log.h>
#include <utils/Panic.h>
#include <utils/Systrace.h>
#include <utils/debug.h>
#include <memory>
#include "generated/resources/materials.h"
using namespace filament::math;
using namespace utils;
namespace filament {
using namespace backend;
using namespace filaflat;
FEngine* FEngine::create(Backend backend, Platform* platform, void* sharedGLContext) {
SYSTRACE_ENABLE();
SYSTRACE_CALL();
FEngine* instance = new FEngine(backend, platform, sharedGLContext);
// initialize all fields that need an instance of FEngine
// (this cannot be done safely in the ctor)
// Normally we launch a thread and create the context and Driver from there (see FEngine::loop).
// In the single-threaded case, we do so in the here and now.
if (!UTILS_HAS_THREADING) {
if (platform == nullptr) {
platform = DefaultPlatform::create(&instance->mBackend);
instance->mPlatform = platform;
instance->mOwnPlatform = true;
}
if (platform == nullptr) {
slog.e << "Selected backend not supported in this build." << io::endl;
return nullptr;
}
instance->mDriver = platform->createDriver(sharedGLContext);
} else {
// start the driver thread
instance->mDriverThread = std::thread(&FEngine::loop, instance);
// wait for the driver to be ready
instance->mDriverBarrier.await();
if (UTILS_UNLIKELY(!instance->mDriver)) {
// something went horribly wrong during driver initialization
instance->mDriverThread.join();
return nullptr;
}
}
// now we can initialize the largest part of the engine
instance->init();
if (!UTILS_HAS_THREADING) {
instance->execute();
}
return instance;
}
#if UTILS_HAS_THREADING
void FEngine::createAsync(CreateCallback callback, void* user,
Backend backend, Platform* platform, void* sharedGLContext) {
SYSTRACE_ENABLE();
SYSTRACE_CALL();
FEngine* instance = new FEngine(backend, platform, sharedGLContext);
// start the driver thread
instance->mDriverThread = std::thread(&FEngine::loop, instance);
// launch a thread to call the callback -- so it can't do any damage.
std::thread callbackThread = std::thread([instance, callback, user]() {
instance->mDriverBarrier.await();
callback(user, instance);
});
// let the callback thread die on its own
callbackThread.detach();
}
FEngine* FEngine::getEngine(void* token) {
FEngine* instance = static_cast<FEngine*>(token);
ASSERT_PRECONDITION(instance->mMainThreadId == std::this_thread::get_id(),
"Engine::createAsync() and Engine::getEngine() must be called on the same thread.");
// we use mResourceAllocator as a proxy for "am I already initialized"
if (!instance->mResourceAllocator) {
if (UTILS_UNLIKELY(!instance->mDriver)) {
// something went horribly wrong during driver initialization
instance->mDriverThread.join();
return nullptr;
}
// now we can initialize the largest part of the engine
instance->init();
}
return instance;
}
#endif
// these must be static because only a pointer is copied to the render stream
// Note that these coordinates are specified in OpenGL clip space. Other backends can transform
// these in the vertex shader as needed.
static constexpr float4 sFullScreenTriangleVertices[3] = {
{ -1.0f, -1.0f, 1.0f, 1.0f },
{ 3.0f, -1.0f, 1.0f, 1.0f },
{ -1.0f, 3.0f, 1.0f, 1.0f }
};
// these must be static because only a pointer is copied to the render stream
static const uint16_t sFullScreenTriangleIndices[3] = { 0, 1, 2 };
FEngine::FEngine(Backend backend, Platform* platform, void* sharedGLContext) :
mBackend(backend),
mPlatform(platform),
mSharedGLContext(sharedGLContext),
mPostProcessManager(*this),
mEntityManager(EntityManager::get()),
mRenderableManager(*this),
mTransformManager(),
mLightManager(*this),
mCameraManager(*this),
mCommandBufferQueue(CONFIG_MIN_COMMAND_BUFFERS_SIZE, CONFIG_COMMAND_BUFFERS_SIZE),
mPerRenderPassAllocator("per-renderpass allocator", CONFIG_PER_RENDER_PASS_ARENA_SIZE),
mEngineEpoch(std::chrono::steady_clock::now()),
mDriverBarrier(1),
mMainThreadId(std::this_thread::get_id())
{
// we're assuming we're on the main thread here.
// (it may not be the case)
mJobSystem.adopt();
slog.i << "FEngine (" << sizeof(void*) * 8 << " bits) created at " << this << " "
<< "(threading is " << (UTILS_HAS_THREADING ? "enabled)" : "disabled)") << io::endl;
}
/*
* init() is called just after the driver thread is initialized. Driver commands are therefore
* possible.
*/
void FEngine::init() {
SYSTRACE_CALL();
// this must be first.
mCommandStream = CommandStream(*mDriver, mCommandBufferQueue.getCircularBuffer());
DriverApi& driverApi = getDriverApi();
mResourceAllocator = new ResourceAllocator(driverApi);
mFullScreenTriangleVb = upcast(VertexBuffer::Builder()
.vertexCount(3)
.bufferCount(1)
.attribute(VertexAttribute::POSITION, 0, VertexBuffer::AttributeType::FLOAT4, 0)
.build(*this));
mFullScreenTriangleVb->setBufferAt(*this, 0,
{ sFullScreenTriangleVertices, sizeof(sFullScreenTriangleVertices) });
mFullScreenTriangleIb = upcast(IndexBuffer::Builder()
.indexCount(3)
.bufferType(IndexBuffer::IndexType::USHORT)
.build(*this));
mFullScreenTriangleIb->setBuffer(*this,
{ sFullScreenTriangleIndices, sizeof(sFullScreenTriangleIndices) });
mFullScreenTriangleRph = driverApi.createRenderPrimitive();
driverApi.setRenderPrimitiveBuffer(mFullScreenTriangleRph,
mFullScreenTriangleVb->getHwHandle(), mFullScreenTriangleIb->getHwHandle(),
mFullScreenTriangleVb->getDeclaredAttributes().getValue());
driverApi.setRenderPrimitiveRange(mFullScreenTriangleRph, PrimitiveType::TRIANGLES,
0, 0, 2, (uint32_t)mFullScreenTriangleIb->getIndexCount());
mDefaultIblTexture = upcast(Texture::Builder()
.width(1).height(1).levels(1)
.format(Texture::InternalFormat::RGBA8)
.sampler(Texture::Sampler::SAMPLER_CUBEMAP)
.build(*this));
static uint32_t pixel = 0;
Texture::PixelBufferDescriptor buffer(
&pixel, 4, // 4 bytes in 1 RGBA pixel
Texture::Format::RGBA, Texture::Type::UBYTE);
Texture::FaceOffsets offsets = {};
mDefaultIblTexture->setImage(*this, 0, std::move(buffer), offsets);
// 3 bands = 9 float3
const float sh[9 * 3] = { 0.0f };
mDefaultIbl = upcast(IndirectLight::Builder()
.irradiance(3, reinterpret_cast<const float3*>(sh))
.build(*this));
mDefaultColorGrading = upcast(ColorGrading::Builder().build(*this));
// Always initialize the default material, most materials' depth shaders fallback on it.
mDefaultMaterial = upcast(
FMaterial::DefaultMaterialBuilder()
.package(MATERIALS_DEFAULTMATERIAL_DATA, MATERIALS_DEFAULTMATERIAL_SIZE)
.build(*const_cast<FEngine*>(this)));
mPostProcessManager.init();
mLightManager.init(*this);
mDFG = std::make_unique<DFG>(*this);
}
FEngine::~FEngine() noexcept {
SYSTRACE_CALL();
ASSERT_DESTRUCTOR(mTerminated, "Engine destroyed but not terminated!");
delete mResourceAllocator;
delete mDriver;
if (mOwnPlatform) {
DefaultPlatform::destroy((DefaultPlatform**)&mPlatform);
}
}
void FEngine::shutdown() {
SYSTRACE_CALL();
ASSERT_PRECONDITION(std::this_thread::get_id() == mMainThreadId,
"Engine::shutdown() called from the wrong thread!");
#ifndef NDEBUG
// print out some statistics about this run
size_t wm = mCommandBufferQueue.getHighWatermark();
size_t wmpct = wm / (CONFIG_COMMAND_BUFFERS_SIZE / 100);
slog.d << "CircularBuffer: High watermark "
<< wm / 1024 << " KiB (" << wmpct << "%)" << io::endl;
#endif
DriverApi& driver = getDriverApi();
/*
* Destroy our own state first
*/
mPostProcessManager.terminate(driver); // free-up post-process manager resources
mResourceAllocator->terminate();
mDFG->terminate(); // free-up the DFG
mRenderableManager.terminate(); // free-up all renderables
mLightManager.terminate(); // free-up all lights
mCameraManager.terminate(); // free-up all cameras
driver.destroyRenderPrimitive(mFullScreenTriangleRph);
destroy(mFullScreenTriangleIb);
destroy(mFullScreenTriangleVb);
destroy(mDefaultIblTexture);
destroy(mDefaultIbl);
destroy(mDefaultColorGrading);
destroy(mDefaultMaterial);
/*
* clean-up after the user -- we call terminate on each "leaked" object and clear each list.
*
* This should free up everything.
*/
// try to destroy objects in the inverse dependency
cleanupResourceList(mRenderers);
cleanupResourceList(mViews);
cleanupResourceList(mScenes);
cleanupResourceList(mSkyboxes);
cleanupResourceList(mColorGradings);
// this must be done after Skyboxes and before materials
destroy(mSkyboxMaterial);
cleanupResourceList(mIndexBuffers);
cleanupResourceList(mVertexBuffers);
cleanupResourceList(mTextures);
cleanupResourceList(mRenderTargets);
cleanupResourceList(mMaterials);
for (auto& item : mMaterialInstances) {
cleanupResourceList(item.second);
}
cleanupResourceList(mFences);
/*
* Shutdown the backend...
*/
// There might be commands added by the terminate() calls, so we need to flush all commands
// up to this point. After flushCommandBuffer() is called, all pending commands are guaranteed
// to be executed before the driver thread exits.
flushCommandBuffer(mCommandBufferQueue);
// now wait for all pending commands to be executed and the thread to exit
mCommandBufferQueue.requestExit();
if (!UTILS_HAS_THREADING) {
execute();
getDriverApi().terminate();
} else {
mDriverThread.join();
}
// Finally, call user callbacks that might have been scheduled.
// These callbacks CANNOT call driver APIs.
getDriver().purge();
/*
* Terminate the JobSystem...
*/
// detach this thread from the jobsystem
mJobSystem.emancipate();
mTerminated = true;
}
void FEngine::prepare() {
SYSTRACE_CALL();
// prepare() is called once per Renderer frame. Ideally we would upload the content of
// UBOs that are visible only. It's not such a big issue because the actual upload() is
// skipped is the UBO hasn't changed. Still we could have a lot of these.
FEngine::DriverApi& driver = getDriverApi();
for (auto& materialInstanceList : mMaterialInstances) {
for (const auto& item : materialInstanceList.second) {
item->commit(driver);
}
}
// Commit default material instances.
for (const auto& material : mMaterials) {
material->getDefaultInstance()->commit(driver);
}
}
void FEngine::gc() {
// Note: this runs in a Job
JobSystem& js = mJobSystem;
auto *parent = js.createJob();
auto em = std::ref(mEntityManager);
js.run(jobs::createJob(js, parent, &FRenderableManager::gc, &mRenderableManager, em),
JobSystem::DONT_SIGNAL);
js.run(jobs::createJob(js, parent, &FLightManager::gc, &mLightManager, em),
JobSystem::DONT_SIGNAL);
js.run(jobs::createJob(js, parent, &FTransformManager::gc, &mTransformManager, em),
JobSystem::DONT_SIGNAL);
js.run(jobs::createJob(js, parent, &FCameraManager::gc, &mCameraManager, em),
JobSystem::DONT_SIGNAL);
js.runAndWait(parent);
}
void FEngine::flush() {
// flush the command buffer
flushCommandBuffer(mCommandBufferQueue);
}
void FEngine::flushAndWait() {
#if defined(ANDROID)
// first make sure we've not terminated filament
ASSERT_PRECONDITION(!mCommandBufferQueue.isExitRequested(),
"calling Engine::flushAndWait() after Engine::shutdown()!");
#endif
// enqueue finish command -- this will stall in the driver until the GPU is done
getDriverApi().finish();
#if defined(ANDROID)
// then create a fence that will trigger when we're past the finish() above
size_t tryCount = 8;
FFence* fence = FEngine::createFence(FFence::Type::SOFT);
do {
FenceStatus status = fence->wait(FFence::Mode::FLUSH,250000000u);
// if the fence didn't trigger after 250ms, check that the command queue thread is still
// running (otherwise indicating a precondition violation).
if (UTILS_UNLIKELY(status == FenceStatus::TIMEOUT_EXPIRED)) {
ASSERT_PRECONDITION(!mCommandBufferQueue.isExitRequested(),
"called Engine::shutdown() WHILE in Engine::flushAndWait()!");
tryCount--;
ASSERT_POSTCONDITION(tryCount, "flushAndWait() failed inexplicably after 2s");
// if the thread is still running, maybe we just need to give it more time
continue;
}
break;
} while (true);
destroy(fence);
#else
FFence::waitAndDestroy(
FEngine::createFence(FFence::Type::SOFT), FFence::Mode::FLUSH);
#endif
// finally, execute callbacks that might have been scheduled
getDriver().purge();
}
// -----------------------------------------------------------------------------------------------
// Render thread / command queue
// -----------------------------------------------------------------------------------------------
int FEngine::loop() {
if (mPlatform == nullptr) {
mPlatform = DefaultPlatform::create(&mBackend);
mOwnPlatform = true;
const char* const backend = backendToString(mBackend);
slog.d << "FEngine resolved backend: " << backend << io::endl;
if (mPlatform == nullptr) {
slog.e << "Selected backend not supported in this build." << io::endl;
mDriverBarrier.latch();
return 0;
}
}
#if FILAMENT_ENABLE_MATDBG
#ifdef ANDROID
const char* portString = "8081";
#else
const char* portString = getenv("FILAMENT_MATDBG_PORT");
#endif
if (portString != nullptr) {
const int port = atoi(portString);
debug.server = new matdbg::DebugServer(mBackend, port);
// Sometimes the server can fail to spin up (e.g. if the above port is already in use).
// When this occurs, carry onward, developers can look at civetweb.txt for details.
if (!debug.server->isReady()) {
delete debug.server;
debug.server = nullptr;
} else {
debug.server->setEditCallback(FMaterial::onEditCallback);
debug.server->setQueryCallback(FMaterial::onQueryCallback);
}
}
#endif
JobSystem::setThreadName("FEngine::loop");
JobSystem::setThreadPriority(JobSystem::Priority::DISPLAY);
mDriver = mPlatform->createDriver(mSharedGLContext);
mDriverBarrier.latch();
if (UTILS_UNLIKELY(!mDriver)) {
// if we get here, it's because the driver couldn't be initialized and the problem has
// been logged.
return 0;
}
// We use the highest affinity bit, assuming this is a Big core in a big.little
// configuration. This is also a core not used by the JobSystem.
// Either way the main reason to do this is to avoid this thread jumping from core to core
// and loose its caches in the process.
uint32_t id = std::thread::hardware_concurrency() - 1;
while (true) {
// looks like thread affinity needs to be reset regularly (on Android)
JobSystem::setThreadAffinityById(id);
if (!execute()) {
break;
}
}
// terminate() is a synchronous API
getDriverApi().terminate();
return 0;
}
void FEngine::flushCommandBuffer(CommandBufferQueue& commandQueue) {
getDriver().purge();
commandQueue.flush();
}
const FMaterial* FEngine::getSkyboxMaterial() const noexcept {
FMaterial const* material = mSkyboxMaterial;
if (UTILS_UNLIKELY(material == nullptr)) {
material = FSkybox::createMaterial(*const_cast<FEngine*>(this));
mSkyboxMaterial = material;
}
return material;
}
// -----------------------------------------------------------------------------------------------
// Resource management
// -----------------------------------------------------------------------------------------------
/*
* Object created from a Builder
*/
template <typename T>
inline T* FEngine::create(ResourceList<T>& list, typename T::Builder const& builder) noexcept {
T* p = mHeapAllocator.make<T>(*this, builder);
list.insert(p);
return p;
}
FVertexBuffer* FEngine::createVertexBuffer(const VertexBuffer::Builder& builder) noexcept {
return create(mVertexBuffers, builder);
}
FIndexBuffer* FEngine::createIndexBuffer(const IndexBuffer::Builder& builder) noexcept {
return create(mIndexBuffers, builder);
}
FTexture* FEngine::createTexture(const Texture::Builder& builder) noexcept {
return create(mTextures, builder);
}
FIndirectLight* FEngine::createIndirectLight(const IndirectLight::Builder& builder) noexcept {
return create(mIndirectLights, builder);
}
FMaterial* FEngine::createMaterial(const Material::Builder& builder) noexcept {
return create(mMaterials, builder);
}
FSkybox* FEngine::createSkybox(const Skybox::Builder& builder) noexcept {
return create(mSkyboxes, builder);
}
FColorGrading* FEngine::createColorGrading(const ColorGrading::Builder& builder) noexcept {
return create(mColorGradings, builder);
}
FStream* FEngine::createStream(const Stream::Builder& builder) noexcept {
return create(mStreams, builder);
}
FRenderTarget* FEngine::createRenderTarget(const RenderTarget::Builder& builder) noexcept {
return create(mRenderTargets, builder);
}
/*
* Special cases
*/
FRenderer* FEngine::createRenderer() noexcept {
FRenderer* p = mHeapAllocator.make<FRenderer>(*this);
if (p) {
mRenderers.insert(p);
p->init();
}
return p;
}
FMaterialInstance* FEngine::createMaterialInstance(const FMaterial* material,
const char* name) noexcept {
FMaterialInstance* p = mHeapAllocator.make<FMaterialInstance>(*this, material, name);
if (p) {
auto pos = mMaterialInstances.emplace(material, "MaterialInstance");
pos.first->second.insert(p);
}
return p;
}
/*
* Objects created without a Builder
*/
FScene* FEngine::createScene() noexcept {
FScene* p = mHeapAllocator.make<FScene>(*this);
if (p) {
mScenes.insert(p);
}
return p;
}
FView* FEngine::createView() noexcept {
FView* p = mHeapAllocator.make<FView>(*this);
if (p) {
mViews.insert(p);
}
return p;
}
FFence* FEngine::createFence(FFence::Type type) noexcept {
FFence* p = mHeapAllocator.make<FFence>(*this, type);
if (p) {
mFences.insert(p);
}
return p;
}
FSwapChain* FEngine::createSwapChain(void* nativeWindow, uint64_t flags) noexcept {
if (UTILS_UNLIKELY(flags & backend::SWAP_CHAIN_CONFIG_APPLE_CVPIXELBUFFER)) {
// If this flag is set, then the nativeWindow is a CVPixelBufferRef.
// The call to setupExternalImage is synchronous, and allows the driver to take ownership of
// the buffer on this thread.
// For non-Metal backends, this is a no-op.
getDriverApi().setupExternalImage(nativeWindow);
}
FSwapChain* p = mHeapAllocator.make<FSwapChain>(*this, nativeWindow, flags);
if (p) {
mSwapChains.insert(p);
}
return p;
}
FSwapChain* FEngine::createSwapChain(uint32_t width, uint32_t height, uint64_t flags) noexcept {
FSwapChain* p = mHeapAllocator.make<FSwapChain>(*this, width, height, flags);
if (p) {
mSwapChains.insert(p);
}
return p;
}
/*
* Objects created with a component manager
*/
FCamera* FEngine::createCamera(Entity entity) noexcept {
return mCameraManager.create(entity);
}
FCamera* FEngine::getCameraComponent(Entity entity) noexcept {
auto ci = mCameraManager.getInstance(entity);
return ci ? mCameraManager.getCamera(ci) : nullptr;
}
void FEngine::destroyCameraComponent(utils::Entity entity) noexcept {
mCameraManager.destroy(entity);
}
void FEngine::createRenderable(const RenderableManager::Builder& builder, Entity entity) {
mRenderableManager.create(builder, entity);
auto& tcm = mTransformManager;
// if this entity doesn't have a transform component, add one.
if (!tcm.hasComponent(entity)) {
tcm.create(entity, 0, mat4f());
}
}
void FEngine::createLight(const LightManager::Builder& builder, Entity entity) {
mLightManager.create(builder, entity);
}
// -----------------------------------------------------------------------------------------------
template<typename T, typename L>
void FEngine::cleanupResourceList(ResourceList<T, L>& list) {
if (!list.empty()) {
#ifndef NDEBUG
slog.d << "cleaning up " << list.size()
<< " leaked " << CallStack::typeName<T>().c_str() << io::endl;
#endif
// Move the list (copy-and-clear). We can only modify/access the list from this
// thread, because it's not thread-safe.
auto copy(list.getListAndClear());
for (T* item : copy) {
item->terminate(*this);
mHeapAllocator.destroy(item);
}
}
}
// -----------------------------------------------------------------------------------------------
template<typename T, typename L>
bool FEngine::terminateAndDestroy(const T* ptr, ResourceList<T, L>& list) {
if (ptr == nullptr) return true;
bool success = list.remove(ptr);
if (ASSERT_PRECONDITION_NON_FATAL(success,
"Object %s at %p doesn't exist (double free?)",
CallStack::typeName<T>().c_str(), ptr)) {
const_cast<T*>(ptr)->terminate(*this);
mHeapAllocator.destroy(const_cast<T*>(ptr));
}
return success;
}
// -----------------------------------------------------------------------------------------------
bool FEngine::destroy(const FVertexBuffer* p) {
return terminateAndDestroy(p, mVertexBuffers);
}
bool FEngine::destroy(const FIndexBuffer* p) {
return terminateAndDestroy(p, mIndexBuffers);
}
inline bool FEngine::destroy(const FRenderer* p) {
return terminateAndDestroy(p, mRenderers);
}
inline bool FEngine::destroy(const FScene* p) {
return terminateAndDestroy(p, mScenes);
}
inline bool FEngine::destroy(const FSkybox* p) {
return terminateAndDestroy(p, mSkyboxes);
}
inline bool FEngine::destroy(const FColorGrading* p) {
return terminateAndDestroy(p, mColorGradings);
}
UTILS_NOINLINE
bool FEngine::destroy(const FTexture* p) {
return terminateAndDestroy(p, mTextures);
}
bool FEngine::destroy(const FRenderTarget* p) {
return terminateAndDestroy(p, mRenderTargets);
}
inline bool FEngine::destroy(const FView* p) {
return terminateAndDestroy(p, mViews);
}
inline bool FEngine::destroy(const FIndirectLight* p) {
return terminateAndDestroy(p, mIndirectLights);
}
UTILS_NOINLINE
bool FEngine::destroy(const FFence* p) {
return terminateAndDestroy(p, mFences);
}
bool FEngine::destroy(const FSwapChain* p) {
return terminateAndDestroy(p, mSwapChains);
}
bool FEngine::destroy(const FStream* p) {
return terminateAndDestroy(p, mStreams);
}
bool FEngine::destroy(const FMaterial* ptr) {
if (ptr == nullptr) return true;
auto pos = mMaterialInstances.find(ptr);
if (pos != mMaterialInstances.cend()) {
// ensure we've destroyed all instances before destroying the material
if (!ASSERT_PRECONDITION_NON_FATAL(pos->second.empty(),
"destroying material \"%s\" but %u instances still alive",
ptr->getName().c_str(), (*pos).second.size())) {
return false;
}
}
return terminateAndDestroy(ptr, mMaterials);
}
bool FEngine::destroy(const FMaterialInstance* ptr) {
if (ptr == nullptr) return true;
auto pos = mMaterialInstances.find(ptr->getMaterial());
assert_invariant(pos != mMaterialInstances.cend());
if (pos != mMaterialInstances.cend()) {
return terminateAndDestroy(ptr, pos->second);
}
// if we don't find this instance's material it might be because it's the default instance
// in which case it fine to ignore.
return true;
}
void FEngine::destroy(Entity e) {
mRenderableManager.destroy(e);
mLightManager.destroy(e);
mTransformManager.destroy(e);
mCameraManager.destroy(e);
}
void* FEngine::streamAlloc(size_t size, size_t alignment) noexcept {
// we allow this only for small allocations
if (size > 1024) {
return nullptr;
}
return getDriverApi().allocate(size, alignment);
}
bool FEngine::execute() {
// wait until we get command buffers to be executed (or thread exit requested)
auto buffers = mCommandBufferQueue.waitForCommands();
if (UTILS_UNLIKELY(buffers.empty())) {
return false;
}
// execute all command buffers
for (auto& item : buffers) {
if (UTILS_LIKELY(item.begin)) {
mCommandStream.execute(item.begin);
mCommandBufferQueue.releaseBuffer(item);
}
}
return true;
}
void FEngine::destroy(FEngine* engine) {
if (engine) {
engine->shutdown();
delete engine;
}
}
// ------------------------------------------------------------------------------------------------
// Trampoline calling into private implementation
// ------------------------------------------------------------------------------------------------
Engine* Engine::create(Backend backend, Platform* platform, void* sharedGLContext) {
return FEngine::create(backend, platform, sharedGLContext);
}
void Engine::destroy(Engine* engine) {
FEngine::destroy(upcast(engine));
}
#if UTILS_HAS_THREADING
void Engine::createAsync(Engine::CreateCallback callback, void* user, Backend backend,
Platform* platform, void* sharedGLContext) {
FEngine::createAsync(callback, user, backend, platform, sharedGLContext);
}
Engine* Engine::getEngine(void* token) {
return FEngine::getEngine(token);
}
#endif
void Engine::destroy(Engine** pEngine) {
if (pEngine) {
Engine* engine = *pEngine;
FEngine::destroy(upcast(engine));
*pEngine = nullptr;
}
}
// -----------------------------------------------------------------------------------------------
// Resource management
// -----------------------------------------------------------------------------------------------
const Material* Engine::getDefaultMaterial() const noexcept {
return upcast(this)->getDefaultMaterial();
}
Backend Engine::getBackend() const noexcept {
return upcast(this)->getBackend();
}
Renderer* Engine::createRenderer() noexcept {
return upcast(this)->createRenderer();
}
View* Engine::createView() noexcept {
return upcast(this)->createView();
}
Scene* Engine::createScene() noexcept {
return upcast(this)->createScene();
}
Camera* Engine::createCamera(Entity entity) noexcept {
return upcast(this)->createCamera(entity);
}
Camera* Engine::getCameraComponent(utils::Entity entity) noexcept {
return upcast(this)->getCameraComponent(entity);
}
void Engine::destroyCameraComponent(utils::Entity entity) noexcept {
upcast(this)->destroyCameraComponent(entity);
}
Fence* Engine::createFence() noexcept {
return upcast(this)->createFence(FFence::Type::SOFT);
}
SwapChain* Engine::createSwapChain(void* nativeWindow, uint64_t flags) noexcept {
return upcast(this)->createSwapChain(nativeWindow, flags);
}
SwapChain* Engine::createSwapChain(uint32_t width, uint32_t height, uint64_t flags) noexcept {
return upcast(this)->createSwapChain(width, height, flags);
}
bool Engine::destroy(const VertexBuffer* p) {
return upcast(this)->destroy(upcast(p));
}
bool Engine::destroy(const IndexBuffer* p) {
return upcast(this)->destroy(upcast(p));
}
bool Engine::destroy(const IndirectLight* p) {
return upcast(this)->destroy(upcast(p));
}
bool Engine::destroy(const Material* p) {
return upcast(this)->destroy(upcast(p));
}
bool Engine::destroy(const MaterialInstance* p) {
return upcast(this)->destroy(upcast(p));
}
bool Engine::destroy(const Renderer* p) {
return upcast(this)->destroy(upcast(p));
}
bool Engine::destroy(const View* p) {
return upcast(this)->destroy(upcast(p));
}
bool Engine::destroy(const Scene* p) {
return upcast(this)->destroy(upcast(p));
}
bool Engine::destroy(const Skybox* p) {
return upcast(this)->destroy(upcast(p));
}
bool Engine::destroy(const ColorGrading* p) {
return upcast(this)->destroy(upcast(p));
}
bool Engine::destroy(const Stream* p) {
return upcast(this)->destroy(upcast(p));
}
bool Engine::destroy(const Texture* p) {
return upcast(this)->destroy(upcast(p));
}
bool Engine::destroy(const RenderTarget* p) {
return upcast(this)->destroy(upcast(p));
}
bool Engine::destroy(const Fence* p) {
return upcast(this)->destroy(upcast(p));
}
bool Engine::destroy(const SwapChain* p) {
return upcast(this)->destroy(upcast(p));
}
void Engine::destroy(Entity e) {
upcast(this)->destroy(e);
}
void Engine::flushAndWait() {
upcast(this)->flushAndWait();
}
RenderableManager& Engine::getRenderableManager() noexcept {
return upcast(this)->getRenderableManager();
}
LightManager& Engine::getLightManager() noexcept {
return upcast(this)->getLightManager();
}
TransformManager& Engine::getTransformManager() noexcept {
return upcast(this)->getTransformManager();
}
void* Engine::streamAlloc(size_t size, size_t alignment) noexcept {
return upcast(this)->streamAlloc(size, alignment);
}
// The external-facing execute does a flush, and is meant only for single-threaded environments.
// It also discards the boolean return value, which would otherwise indicate a thread exit.
void Engine::execute() {
ASSERT_PRECONDITION(!UTILS_HAS_THREADING, "Execute is meant for single-threaded platforms.");
upcast(this)->flush();
upcast(this)->execute();
}
utils::JobSystem& Engine::getJobSystem() noexcept {
return upcast(this)->getJobSystem();
}
DebugRegistry& Engine::getDebugRegistry() noexcept {
return upcast(this)->getDebugRegistry();
}
Camera* Engine::createCamera() noexcept {
return createCamera(upcast(this)->getEntityManager().create());
}
void Engine::destroy(const Camera* camera) {
Entity e = camera->getEntity();
destroyCameraComponent(e);
upcast(this)->getEntityManager().destroy(e);
}
} // namespace filament
| 31.160577
| 100
| 0.654612
|
tombsar
|
106d74f8240eaa35c87f3ee5222180f298987580
| 5,684
|
cc
|
C++
|
chrome/browser/android/metrics/launch_metrics.cc
|
zipated/src
|
2b8388091c71e442910a21ada3d97ae8bc1845d3
|
[
"BSD-3-Clause"
] | 2,151
|
2020-04-18T07:31:17.000Z
|
2022-03-31T08:39:18.000Z
|
chrome/browser/android/metrics/launch_metrics.cc
|
cangulcan/src
|
2b8388091c71e442910a21ada3d97ae8bc1845d3
|
[
"BSD-3-Clause"
] | 395
|
2020-04-18T08:22:18.000Z
|
2021-12-08T13:04:49.000Z
|
chrome/browser/android/metrics/launch_metrics.cc
|
cangulcan/src
|
2b8388091c71e442910a21ada3d97ae8bc1845d3
|
[
"BSD-3-Clause"
] | 338
|
2020-04-18T08:03:10.000Z
|
2022-03-29T12:33:22.000Z
|
// Copyright (c) 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 "base/android/jni_string.h"
#include "base/metrics/histogram_macros.h"
#include "base/time/time.h"
#include "chrome/browser/android/shortcut_info.h"
#include "chrome/browser/banners/app_banner_settings_helper.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/engagement/site_engagement_service.h"
#include "chrome/browser/prefs/pref_metrics_service.h"
#include "chrome/browser/profiles/profile.h"
#include "components/rappor/public/rappor_utils.h"
#include "components/rappor/rappor_service_impl.h"
#include "content/public/browser/web_contents.h"
#include "jni/LaunchMetrics_jni.h"
#include "third_party/blink/public/common/manifest/web_display_mode.h"
#include "url/gurl.h"
using base::android::JavaParamRef;
namespace metrics {
enum class HomeScreenLaunchType { STANDALONE = 0, SHORTCUT = 1, COUNT = 2 };
static void JNI_LaunchMetrics_RecordLaunch(
JNIEnv* env,
const JavaParamRef<jclass>& caller,
jboolean is_shortcut,
const JavaParamRef<jstring>& jurl,
int source,
int display_mode,
const JavaParamRef<jobject>& jweb_contents) {
// Interpolate the legacy ADD_TO_HOMESCREEN source into standalone/shortcut.
// Unfortunately, we cannot concretely determine whether a standalone add to
// homescreen source means a full PWA (with service worker) or a site that has
// a manifest with display: standalone.
int histogram_source = source;
if (histogram_source == ShortcutInfo::SOURCE_ADD_TO_HOMESCREEN_DEPRECATED) {
if (is_shortcut)
histogram_source = ShortcutInfo::SOURCE_ADD_TO_HOMESCREEN_SHORTCUT;
else
histogram_source = ShortcutInfo::SOURCE_ADD_TO_HOMESCREEN_STANDALONE;
}
GURL url(base::android::ConvertJavaStringToUTF8(env, jurl));
content::WebContents* web_contents =
content::WebContents::FromJavaWebContents(jweb_contents);
if (web_contents &&
(histogram_source == ShortcutInfo::SOURCE_APP_BANNER ||
histogram_source == ShortcutInfo::SOURCE_ADD_TO_HOMESCREEN_PWA)) {
// What a user has installed on the Home screen can become disconnected from
// what Chrome believes is on the Home screen if the user clears their data.
// Use the launch as a signal that the shortcut still exists.
AppBannerSettingsHelper::RecordBannerEvent(
web_contents, url, url.spec(),
AppBannerSettingsHelper::APP_BANNER_EVENT_DID_ADD_TO_HOMESCREEN,
base::Time::Now());
// Tell the Site Engagement Service about this launch as sites recently
// launched from a shortcut receive a boost to their engagement.
SiteEngagementService* service = SiteEngagementService::Get(
Profile::FromBrowserContext(web_contents->GetBrowserContext()));
service->SetLastShortcutLaunchTime(web_contents, url);
}
std::string rappor_metric_source;
switch (histogram_source) {
case ShortcutInfo::SOURCE_ADD_TO_HOMESCREEN_DEPRECATED:
case ShortcutInfo::SOURCE_ADD_TO_HOMESCREEN_PWA:
case ShortcutInfo::SOURCE_ADD_TO_HOMESCREEN_STANDALONE:
case ShortcutInfo::SOURCE_ADD_TO_HOMESCREEN_SHORTCUT:
rappor_metric_source = "Launch.HomeScreenSource.AddToHomeScreen";
break;
case ShortcutInfo::SOURCE_APP_BANNER:
rappor_metric_source = "Launch.HomeScreenSource.AppBanner";
break;
case ShortcutInfo::SOURCE_BOOKMARK_NAVIGATOR_WIDGET:
rappor_metric_source = "Launch.HomeScreenSource.BookmarkNavigatorWidget";
break;
case ShortcutInfo::SOURCE_BOOKMARK_SHORTCUT_WIDGET:
rappor_metric_source = "Launch.HomeScreenSource.BookmarkShortcutWidget";
break;
case ShortcutInfo::SOURCE_NOTIFICATION:
rappor_metric_source = "Launch.HomeScreenSource.Notification";
break;
case ShortcutInfo::SOURCE_UNKNOWN:
case ShortcutInfo::SOURCE_COUNT:
rappor_metric_source = "Launch.HomeScreenSource.Unknown";
break;
}
UMA_HISTOGRAM_ENUMERATION("Launch.HomeScreenSource",
static_cast<ShortcutInfo::Source>(histogram_source),
ShortcutInfo::SOURCE_COUNT);
if (!is_shortcut) {
UMA_HISTOGRAM_ENUMERATION("Launch.WebAppDisplayMode",
static_cast<blink::WebDisplayMode>(display_mode),
blink::WebDisplayMode::kWebDisplayModeLast + 1);
}
rappor::SampleDomainAndRegistryFromGURL(g_browser_process->rappor_service(),
rappor_metric_source, url);
HomeScreenLaunchType action = is_shortcut ? HomeScreenLaunchType::SHORTCUT
: HomeScreenLaunchType::STANDALONE;
std::string rappor_metric_action = is_shortcut
? "Launch.HomeScreen.Shortcut"
: "Launch.HomeScreen.Standalone";
UMA_HISTOGRAM_ENUMERATION("Launch.HomeScreen", action,
HomeScreenLaunchType::COUNT);
rappor::SampleDomainAndRegistryFromGURL(g_browser_process->rappor_service(),
rappor_metric_action, url);
}
static void JNI_LaunchMetrics_RecordHomePageLaunchMetrics(
JNIEnv* env,
const JavaParamRef<jclass>& caller,
jboolean show_home_button,
jboolean homepage_is_ntp,
const JavaParamRef<jstring>& jhomepage_url) {
GURL homepage_url(base::android::ConvertJavaStringToUTF8(env, jhomepage_url));
PrefMetricsService::RecordHomePageLaunchMetrics(
show_home_button,
homepage_is_ntp,
homepage_url);
}
}; // namespace metrics
| 42.103704
| 80
| 0.725897
|
zipated
|
106df08aa4f507ae607ea7a170e973388c577b8a
| 651
|
cc
|
C++
|
src/include/XESystem/Entityx/help/Timer.cc
|
devxkh/FrankE
|
72faca02759b54aaec842831f3c7a051e7cf5335
|
[
"MIT"
] | 11
|
2017-01-17T15:02:25.000Z
|
2020-11-27T16:54:42.000Z
|
src/include/XESystem/Entityx/help/Timer.cc
|
devxkh/FrankE
|
72faca02759b54aaec842831f3c7a051e7cf5335
|
[
"MIT"
] | 9
|
2016-10-23T20:15:38.000Z
|
2018-02-06T11:23:17.000Z
|
src/include/XESystem/Entityx/help/Timer.cc
|
devxkh/FrankE
|
72faca02759b54aaec842831f3c7a051e7cf5335
|
[
"MIT"
] | 2
|
2019-08-29T10:23:51.000Z
|
2020-04-03T06:08:34.000Z
|
/*
* Copyright (C) 2013 Antony Woods <antony@teamwoods.org>
* All rights reserved.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution.
*
* Author: Antony Woods <antony@teamwoods.org>
*/
#include "Timer.h"
namespace entityx {
namespace help {
Timer::Timer() {
_start = std::chrono::system_clock::now();
}
Timer::~Timer() {
}
void Timer::restart() {
_start = std::chrono::system_clock::now();
}
double Timer::elapsed() {
return std::chrono::duration<double>(std::chrono::system_clock::now() - _start).count();
}
} // namespace help
} // namespace entityx
| 19.727273
| 90
| 0.680492
|
devxkh
|
106ffdd4c86ffa7dbfe8caeeb09fa5fa4ef75185
| 3,644
|
hpp
|
C++
|
Math/include/Extended/AABB3.hpp
|
C-And-Cpp-Libraries/handycpp
|
85f4e4f93856988e729e1e81512eab99a02b5a5a
|
[
"Unlicense",
"Apache-2.0",
"BSD-2-Clause",
"MIT"
] | 25
|
2017-12-28T22:09:11.000Z
|
2020-04-02T15:49:51.000Z
|
Math/include/Extended/AABB3.hpp
|
C-And-Cpp-Libraries/handycpp
|
85f4e4f93856988e729e1e81512eab99a02b5a5a
|
[
"Unlicense",
"Apache-2.0",
"BSD-2-Clause",
"MIT"
] | 1
|
2019-07-30T08:59:00.000Z
|
2019-07-30T21:35:50.000Z
|
Math/include/Extended/AABB3.hpp
|
C-And-Cpp-Libraries/handycpp
|
85f4e4f93856988e729e1e81512eab99a02b5a5a
|
[
"Unlicense",
"Apache-2.0",
"BSD-2-Clause",
"MIT"
] | 1
|
2021-12-26T14:14:09.000Z
|
2021-12-26T14:14:09.000Z
|
/// See ../../License.txt for license info.
#pragma once
#include <cmath>
#include <vector>
#include "../Core/Vector3.hpp"
namespace HANDYMATH_NS
{
struct AABB3
{
Vector3 Min;
Vector3 Max;
AABB3();
AABB3(Vector3 const & point);
AABB3(std::vector<Vector3> const & points);
AABB3(Vector3 const & min, Vector3 const & max);
bool IsEverything() const;
bool IsNothing() const;
bool IsPoint() const;
Vector3 PointCenter() const;
Vector3 Size() const;
Vector3 HalfSize() const;
float Volume() const;
float SurfaceArea() const;
void AddPoint(Vector3 const & p);
void AddPoints(std::vector<Vector3> const & ps);
void AddAABB(AABB3 const & aabb);
bool Envelopes (AABB3 const & aabb) const;
bool Intersects(AABB3 const & aabb) const;
bool Intersects(Vector3 const & v) const;
static AABB3 Everything();
static AABB3 Nothing();
};
FORCEINLINE AABB3::AABB3() : Min(Vector3::NaN()), Max(Vector3::NaN()) { }
FORCEINLINE AABB3::AABB3(Vector3 const & point) : AABB3() { AddPoint(point); }
FORCEINLINE AABB3::AABB3(std::vector<Vector3> const & points) : AABB3() { AddPoints(points); }
FORCEINLINE AABB3::AABB3(Vector3 const & min, Vector3 const & max) : Min(min), Max(max) { }
FORCEINLINE bool AABB3::IsEverything() const { return Min.IsNegativeInfinity() && Max.IsPositiveInfinity(); }
FORCEINLINE bool AABB3::IsNothing() const { return Min.IsNaN() || Max.IsNaN(); }
FORCEINLINE bool AABB3::IsPoint() const { return Min == Max; }
FORCEINLINE Vector3 AABB3::PointCenter() const { return (Min + Max) * 0.5f; }
FORCEINLINE Vector3 AABB3::Size() const { return (Max - Min); }
FORCEINLINE Vector3 AABB3::HalfSize() const { return (Max - Min) * 0.5f; }
FORCEINLINE float AABB3::Volume() const { return Size().Product(); }
FORCEINLINE float AABB3::SurfaceArea() const { Vector3 sz = Size(); return 2.0f * (sz.X * sz.Y + sz.Y * sz.Z + sz.X * sz.Z); }
FORCEINLINE void AABB3::AddPoint(Vector3 const & point)
{
if (point.HasNaN())
throw std::runtime_error("Cannot add NaN to AABB2.");
if (IsEverything())
return;
if (IsNothing())
{
Min = Max = point;
return;
}
Min = Min.Min(point);
Max = Max.Max(point);
}
FORCEINLINE void AABB3::AddPoints(std::vector<Vector3> const & points)
{
if (IsEverything())
return;
for (auto const & point : points)
AddPoint(point);
}
FORCEINLINE void AABB3::AddAABB(AABB3 const & aabb)
{
if (aabb.IsNothing() || IsEverything())
return;
if (aabb.IsEverything() || IsNothing())
{
*this = aabb;
return;
}
AddPoint(aabb.Min);
AddPoint(aabb.Max);
}
FORCEINLINE bool AABB3::Envelopes(AABB3 const & aabb) const
{
if (IsNothing() || aabb.IsNothing())
return false;
if (IsEverything())
return true;
return Min.X <= aabb.Min.X && Min.Y <= aabb.Min.Y && Min.Z <= aabb.Min.Z &&
Max.X >= aabb.Max.X && Max.Y >= aabb.Max.Y && Max.Z >= aabb.Max.Z;
}
FORCEINLINE bool AABB3::Intersects(AABB3 const & aabb) const
{
if (IsNothing() || aabb.IsNothing())
return false;
if (IsEverything() || aabb.IsEverything())
return true;
return !(Max.X < aabb.Min.X || Min.X > aabb.Max.X ||
Max.Y < aabb.Min.Y || Min.Y > aabb.Max.Y ||
Max.Z < aabb.Min.Z || Min.Z > aabb.Max.Z);
}
FORCEINLINE bool AABB3::Intersects(Vector3 const & v) const
{
return Intersects(AABB3(v));
}
FORCEINLINE /*static*/ AABB3 AABB3::Everything() { return AABB3(Vector3::NegativeInfinity(), Vector3::PositiveInfinity()); }
FORCEINLINE /*static*/ AABB3 AABB3::Nothing() { return AABB3(Vector3::NaN(), Vector3::NaN()); }
}
| 25.843972
| 130
| 0.642975
|
C-And-Cpp-Libraries
|
10719b53b8cce6cf10b9b0a139d37b6637b560a4
| 6,660
|
cpp
|
C++
|
examples/Cpp/RealSense.cpp
|
fangchuan/Open3D
|
61f991ba5d9fe3ee1e4e195a607bf48f4695d821
|
[
"MIT"
] | null | null | null |
examples/Cpp/RealSense.cpp
|
fangchuan/Open3D
|
61f991ba5d9fe3ee1e4e195a607bf48f4695d821
|
[
"MIT"
] | null | null | null |
examples/Cpp/RealSense.cpp
|
fangchuan/Open3D
|
61f991ba5d9fe3ee1e4e195a607bf48f4695d821
|
[
"MIT"
] | null | null | null |
// ----------------------------------------------------------------------------
// - Open3D: www.open3d.org -
// ----------------------------------------------------------------------------
// The MIT License (MIT)
//
// Copyright (c) 2018 www.open3d.org
//
// 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 <iostream>
#include <librealsense/rs.hpp>
#include <thread>
#include "Open3D/Open3D.h"
using namespace open3d;
int main(int argc, char **args) {
rs::context ctx;
utility::LogInfo("There are {:d} connected RealSense devices.",
ctx.get_device_count());
if (ctx.get_device_count() == 0) {
return 1;
}
rs::device *dev = ctx.get_device(0);
utility::LogInfo("Using device 0, an {}", dev->get_name());
utility::LogInfo(" Serial number: {}", dev->get_serial());
utility::LogInfo(" Firmware version: {}", dev->get_firmware_version());
dev->set_option(rs::option::color_enable_auto_exposure, 0.0);
dev->set_option(rs::option::color_exposure, 625);
dev->set_option(rs::option::color_gain, 128);
dev->set_option(rs::option::color_enable_auto_white_balance, 0.0);
dev->enable_stream(rs::stream::depth, 640, 480, rs::format::z16, 30);
dev->enable_stream(rs::stream::color, 1920, 1080, rs::format::rgb8, 30);
dev->start();
std::this_thread::sleep_for(std::chrono::milliseconds(50));
dev->set_option(rs::option::color_white_balance, 2100.0);
auto depth_image_ptr = std::make_shared<geometry::Image>();
depth_image_ptr->Prepare(640, 480, 1, 2);
auto color_image_ptr = std::make_shared<geometry::Image>();
color_image_ptr->Prepare(1920, 1080, 3, 1);
utility::FPSTimer timer("Realsense stream");
rs::extrinsics extrinsics =
dev->get_extrinsics(rs::stream::depth, rs::stream::rectified_color);
for (int i = 0; i < 9; i++) {
utility::LogInfo("{:.6f} ", extrinsics.rotation[i]);
}
utility::LogInfo("");
for (int i = 0; i < 3; i++) {
utility::LogInfo("{:.6f} ", extrinsics.translation[i]);
}
utility::LogInfo("");
rs::intrinsics depth_intr = dev->get_stream_intrinsics(rs::stream::depth);
utility::LogInfo("{:d} {:d} {:.6f} {:.6f} {:.6f} {:.6f}", depth_intr.width,
depth_intr.height, depth_intr.fx, depth_intr.fy,
depth_intr.ppx, depth_intr.ppy);
for (int i = 0; i < 5; i++) {
utility::LogInfo("{:.6f} ", depth_intr.coeffs[i]);
}
utility::LogInfo("");
rs::intrinsics color_intr = dev->get_stream_intrinsics(rs::stream::color);
utility::LogInfo("{:d} {:d} {:.6f} {:.6f} {:.6f} {:.6f}", color_intr.width,
color_intr.height, color_intr.fx, color_intr.fy,
color_intr.ppx, color_intr.ppy);
for (int i = 0; i < 5; i++) {
utility::LogInfo("{:.6f} ", color_intr.coeffs[i]);
}
utility::LogInfo("");
rs::intrinsics rect_intr =
dev->get_stream_intrinsics(rs::stream::rectified_color);
utility::LogInfo("{:d} {:d} {:.6f} {:.6f} {:.6f} {:.6f}", rect_intr.width,
rect_intr.height, rect_intr.fx, rect_intr.fy,
rect_intr.ppx, rect_intr.ppy);
for (int i = 0; i < 5; i++) {
utility::LogInfo("{:.6f} ", rect_intr.coeffs[i]);
}
utility::LogInfo("");
visualization::Visualizer depth_vis, color_vis;
if (!depth_vis.CreateVisualizerWindow("Depth", 640, 480, 15, 50) ||
!depth_vis.AddGeometry(depth_image_ptr) ||
!color_vis.CreateVisualizerWindow("Color", 1920, 1080, 675, 50) ||
!color_vis.AddGeometry(color_image_ptr)) {
return 0;
}
while (depth_vis.PollEvents() && color_vis.PollEvents()) {
timer.Signal();
dev->wait_for_frames();
memcpy(depth_image_ptr->data_.data(),
dev->get_frame_data(rs::stream::depth), 640 * 480 * 2);
memcpy(color_image_ptr->data_.data(),
dev->get_frame_data(rs::stream::rectified_color),
1920 * 1080 * 3);
depth_vis.UpdateGeometry();
color_vis.UpdateGeometry();
utility::LogInfo("{:.2f}",
dev->get_option(rs::option::color_white_balance));
/*
rs::option opts[10] = {
rs::option::color_enable_auto_exposure,
rs::option::color_exposure,
rs::option::color_backlight_compensation,
rs::option::color_brightness,
rs::option::color_contrast,
rs::option::color_gain,
rs::option::color_gamma,
rs::option::color_saturation,
rs::option::color_sharpness,
rs::option::color_hue
};
double value[10];
dev->get_options((const rs::option *)opts, 10, (double *)value);
utility::LogInfo("{:.2f} {:.2f} {:.2f} {:.2f} {:.2f} {:.2f} {:.2f}
{:.2f} {:.2f}
{:.2f}", value[0], value[1], value[2], value[3], value[4], value[5],
value[6], value[7], value[8], value[9]);
*/
}
// DrawGeometryWithAnimationCallback(depth_image_ptr,
// [&](Visualizer &vis) {
// timer.Signal();
// dev->wait_for_frames();
// memcpy(depth_image_ptr->data_.data(),
// dev->get_frame_data(rs::stream::depth), 640 * 480 *
// 2);
// return true;
// }, "Depth", 640, 480);
return 0;
}
| 41.886792
| 80
| 0.572823
|
fangchuan
|
10727506f5e0bdde87cb655c781abe724f11ae6c
| 2,090
|
cpp
|
C++
|
clib/RecursiveMutex.cpp
|
dehilsterlexis/eclide-1
|
0c1685cc7165191b5033d450c59aec479f01010a
|
[
"Apache-2.0"
] | 8
|
2016-08-29T13:34:18.000Z
|
2020-12-04T15:20:36.000Z
|
clib/RecursiveMutex.cpp
|
dehilsterlexis/eclide-1
|
0c1685cc7165191b5033d450c59aec479f01010a
|
[
"Apache-2.0"
] | 221
|
2016-06-20T19:51:48.000Z
|
2022-03-29T20:46:46.000Z
|
clib/RecursiveMutex.cpp
|
dehilsterlexis/eclide-1
|
0c1685cc7165191b5033d450c59aec479f01010a
|
[
"Apache-2.0"
] | 13
|
2016-06-24T15:59:31.000Z
|
2022-01-01T11:48:20.000Z
|
#include "StdAfx.h"
#include ".\recursivemutex.h"
#include "atlsync.h"
namespace clib
{
recursive_mutex::recursive_mutex() : m_lockCount(0)
{
}
recursive_mutex::~recursive_mutex()
{
}
LONG recursive_mutex::GetLockCount()
{
return m_lockCount;
}
void recursive_mutex::do_lock()
{
::InterlockedIncrement(&m_lockCount);
m_critSec.Lock();
}
void recursive_mutex::do_unlock()
{
m_critSec.Unlock();
::InterlockedDecrement(&m_lockCount);
}
rwrecursive_mutex::rwrecursive_mutex()
{
m_nReaders = 0;
m_nWriters = 0;
}
rwrecursive_mutex::~rwrecursive_mutex()
{
}
void rwrecursive_mutex::do_lockr()
{
for(;;)
{
::InterlockedIncrement(&m_nReaders);
if(m_nWriters == 0)
break;
::InterlockedDecrement(&m_nReaders);
::Sleep(0);
}
}
void rwrecursive_mutex::do_lockw()
{
for(;;)
{
if( ::InterlockedExchange( &m_nWriters, 1 ) == 1 )
::Sleep(0);
else
{
while(m_nReaders != 0)
::Sleep(0);
break;
}
}
}
void rwrecursive_mutex::do_unlockr()
{
//DWORD ThreadId = GetCurrentThreadId();
::InterlockedDecrement(&m_nReaders);
}
void rwrecursive_mutex::do_unlockw()
{
//DWORD ThreadId = GetCurrentThreadId();
::InterlockedDecrement(&m_nWriters);
}
scoped_lock_ref_counted::scoped_lock_ref_counted(recursive_mutex & m)
{
m_lock = new recursive_mutex::scoped_lock(m);
}
scoped_lock_ref_counted::~scoped_lock_ref_counted()
{
delete(m_lock);
}
rwscoped_lock_ref_counted::rwscoped_lock_ref_counted(CRWMutex &m)
{
m_lock = new rwscoped_mutex_lock(m);
}
rwscoped_lock_ref_counted::~rwscoped_lock_ref_counted()
{
delete(m_lock);
}
void CLockableUnknown::Lock(CComPtr<clib::scoped_lock_ref_counted> & lock)
{
lock = new clib::scoped_lock_ref_counted(m_mutex);
}
}
namespace boost
{
scoped_lock_ref_counted::scoped_lock_ref_counted(recursive_mutex & m)
{
m_lock = new recursive_mutex::scoped_lock(m);
}
scoped_lock_ref_counted::~scoped_lock_ref_counted()
{
delete(m_lock);
}
}
| 17.131148
| 74
| 0.669378
|
dehilsterlexis
|
107329f5ce381018f781bb18961bc0a19004c420
| 7,386
|
cpp
|
C++
|
src/ObservableVectorUnitTest.cpp
|
k2snowman69/threadily-sample-cpp-test
|
2edf49d11032ff8efa2dc77ea67cf7092c60b0b8
|
[
"MIT"
] | null | null | null |
src/ObservableVectorUnitTest.cpp
|
k2snowman69/threadily-sample-cpp-test
|
2edf49d11032ff8efa2dc77ea67cf7092c60b0b8
|
[
"MIT"
] | null | null | null |
src/ObservableVectorUnitTest.cpp
|
k2snowman69/threadily-sample-cpp-test
|
2edf49d11032ff8efa2dc77ea67cf7092c60b0b8
|
[
"MIT"
] | null | null | null |
// Main test framework
#include <bandit/bandit.h>
// std includes
#include <iostream>
#include <memory>
// Threadily includes
#include <ReadyEvent.h>
#include <Observable.h>
#include <ThreadManager.h>
#include <ThreadQueueItem.h>
#include <ThreadIds.h>
using namespace snowhouse;
using namespace bandit;
namespace threadily
{
namespace test
{
go_bandit([]() {
describe("ObservableVectorUnitTest", []() {
it("Observable_Vector_Int_Insert_1", [&]() {
auto observableVector = Observable<std::vector<int>>();
AssertThat((size_t)0, Equals(observableVector.size()));
observableVector.insert(0, 1);
observableVector.insert(1, 2);
observableVector.insert(0, 0);
AssertThat((size_t)3, Equals(observableVector.size()));
AssertThat(0, Equals(observableVector.at(0)));
AssertThat(1, Equals(observableVector.at(1)));
AssertThat(2, Equals(observableVector.at(2)));
});
it("Observable_Vector_Int_Insert_2", [&]() {
auto observableVector = Observable<std::vector<int>>();
AssertThat((size_t)0, Equals(observableVector.size()));
observableVector.insert(2, 2);
AssertThat((size_t)3, Equals(observableVector.size()));
AssertThat(0, Equals(observableVector.at(0)));
AssertThat(0, Equals(observableVector.at(1)));
AssertThat(2, Equals(observableVector.at(2)));
});
it("Observable_Vector_Int_Set", [&]() {
auto observableVector = Observable<std::vector<int>>();
AssertThat((size_t)0, Equals(observableVector.size()));
observableVector.insert(2, 2);
observableVector.set(1, 1);
observableVector.set(0, 0);
AssertThat((size_t)3, Equals(observableVector.size()));
AssertThat(0, Equals(observableVector.at(0)));
AssertThat(1, Equals(observableVector.at(1)));
AssertThat(2, Equals(observableVector.at(2)));
});
it("Observable_Vector_Int_Set_OutOfOrder", [&]() {
auto observableVector = Observable<std::vector<int>>();
AssertThat((size_t)0, Equals(observableVector.size()));
observableVector.set(2, 2);
observableVector.set(1, 1);
observableVector.set(0, 0);
AssertThat((size_t)3, Equals(observableVector.size()));
AssertThat(0, Equals(observableVector.at(0)));
AssertThat(1, Equals(observableVector.at(1)));
AssertThat(2, Equals(observableVector.at(2)));
});
it("Observable_Vector_Ptr_Insert_1", [&]() {
auto observableVector = Observable<std::vector<std::shared_ptr<int>>>();
AssertThat((size_t)0, Equals(observableVector.size()));
observableVector.insert(0, std::make_shared<int>(1));
observableVector.insert(1, std::make_shared<int>(2));
observableVector.insert(0, std::make_shared<int>(0));
AssertThat((size_t)3, Equals(observableVector.size()));
AssertThat(0, Equals(*(observableVector.at(0).get())));
AssertThat(1, Equals(*(observableVector.at(1).get())));
AssertThat(2, Equals(*(observableVector.at(2).get())));
});
it("Observable_Vector_Ptr_Insert_2", [&]() {
auto observableVector = Observable<std::vector<std::shared_ptr<int>>>();
AssertThat((size_t)0, Equals(observableVector.size()));
observableVector.insert(2, std::make_shared<int>(2));
AssertThat((size_t)3, Equals(observableVector.size()));
AssertThat(observableVector.at(0).get(), IsNull());
AssertThat(observableVector.at(1).get(), IsNull());
AssertThat(2, Equals(*(observableVector.at(2).get())));
});
it("Observable_Vector_Ptr_Set", [&]() {
auto observableVector = Observable<std::vector<std::shared_ptr<int>>>();
AssertThat((size_t)0, Equals(observableVector.size()));
observableVector.insert(2, std::make_shared<int>(2));
observableVector.set(1, std::make_shared<int>(1));
observableVector.set(0, std::make_shared<int>(0));
AssertThat((size_t)3, Equals(observableVector.size()));
AssertThat(0, Equals(*(observableVector.at(0).get())));
AssertThat(1, Equals(*(observableVector.at(1).get())));
AssertThat(2, Equals(*(observableVector.at(2).get())));
});
it("Observable_Vector_Ptr_Set_OutOfOrder", [&]() {
auto observableVector = Observable<std::vector<std::shared_ptr<int>>>();
AssertThat((size_t)0, Equals(observableVector.size()));
observableVector.set(2, std::make_shared<int>(2));
observableVector.set(1, std::make_shared<int>(1));
observableVector.set(0, std::make_shared<int>(0));
AssertThat((size_t)3, Equals(observableVector.size()));
AssertThat(0, Equals(*(observableVector.at(0).get())));
AssertThat(1, Equals(*(observableVector.at(1).get())));
AssertThat(2, Equals(*(observableVector.at(2).get())));
});
it("Observable_Vector_Ptr_Subscription_Insert", [&]() {
auto observableVector = Observable<std::vector<std::shared_ptr<int>>>();
AssertThat((size_t)0, Equals(observableVector.size()));
auto valueAdded = std::make_shared<int>(4);
auto subscribe = observableVector.subscribe([valueAdded](std::shared_ptr<int> newValue, size_t index, ObservableActionType action) {
AssertThat(valueAdded, Equals(newValue));
AssertThat((size_t)2, Equals(index));
AssertThat(ObservableActionType::Insert, Equals(action));
});
observableVector.insert(2, valueAdded);
AssertThat((size_t)3, Equals(observableVector.size()));
observableVector.unsubscribe(subscribe);
});
it("Observable_Vector_Ptr_Subscription_Remove", [&]() {
auto observableVector = Observable<std::vector<std::shared_ptr<int>>>();
AssertThat((size_t)0, Equals(observableVector.size()));
bool isDeleted = false;
auto valueAdded = std::make_shared<int>(4);
auto subscribe = observableVector.subscribe([valueAdded, &isDeleted](std::shared_ptr<int> newValue, size_t index, ObservableActionType action) {
if (ObservableActionType::Erase == action)
{
AssertThat(valueAdded, Equals(newValue));
AssertThat((size_t)2, Equals(index));
isDeleted = true;
}
});
observableVector.set(0, std::make_shared<int>(0));
observableVector.set(1, std::make_shared<int>(2));
observableVector.set(2, valueAdded);
AssertThat((size_t)3, Equals(observableVector.size()));
observableVector.erase(2);
AssertThat((size_t)2, Equals(observableVector.size()));
AssertThat(isDeleted, IsTrue());
observableVector.unsubscribe(subscribe);
});
it("Observable_Vector_Ptr_Subscription_Update", [&]() {
auto observableVector = Observable<std::vector<std::shared_ptr<int>>>();
AssertThat((size_t)0, Equals(observableVector.size()));
bool isUpdated = false;
auto valueAdded = std::make_shared<int>(4);
auto valueUpdated = std::make_shared<int>(6);
auto subscribe = observableVector.subscribe([valueUpdated, &isUpdated](std::shared_ptr<int> newValue, size_t index, ObservableActionType action) {
if (ObservableActionType::Set == action)
{
AssertThat(valueUpdated, Equals(newValue));
AssertThat((size_t)2, Equals(index));
AssertThat(ObservableActionType::Set, Equals(action));
isUpdated = true;
}
});
observableVector.set(0, std::make_shared<int>(0));
observableVector.set(1, std::make_shared<int>(2));
observableVector.set(2, valueAdded);
AssertThat((size_t)3, Equals(observableVector.size()));
observableVector.set(2, valueUpdated);
AssertThat((size_t)3, Equals(observableVector.size()));
AssertThat(isUpdated, IsTrue());
observableVector.unsubscribe(subscribe);
});
});
});
}
}
| 34.514019
| 149
| 0.69537
|
k2snowman69
|
1076475f1860606c70a4de5c9685e6ccf0440147
| 46,677
|
cpp
|
C++
|
ocv/text/ocr_hmm_decoder.cpp
|
privet56/qRabbifier
|
4289016f9ba40658ad444580818292456574ffb5
|
[
"Apache-2.0"
] | 16
|
2016-07-04T10:32:22.000Z
|
2021-11-10T11:26:45.000Z
|
ocv/text/ocr_hmm_decoder.cpp
|
privet56/qRabbifier
|
4289016f9ba40658ad444580818292456574ffb5
|
[
"Apache-2.0"
] | null | null | null |
ocv/text/ocr_hmm_decoder.cpp
|
privet56/qRabbifier
|
4289016f9ba40658ad444580818292456574ffb5
|
[
"Apache-2.0"
] | 22
|
2015-10-23T19:36:18.000Z
|
2021-02-02T12:20:32.000Z
|
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation 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.
//
//M*/
#include "precomp.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/ml.hpp"
#include <iostream>
#include <fstream>
#include <queue>
namespace cv
{
namespace text
{
using namespace std;
using namespace cv::ml;
/* OCR HMM Decoder */
void OCRHMMDecoder::run(Mat& image, string& output_text, vector<Rect>* component_rects,
vector<string>* component_texts, vector<float>* component_confidences,
int component_level)
{
CV_Assert( (image.type() == CV_8UC1) || (image.type() == CV_8UC3) );
CV_Assert( (component_level == OCR_LEVEL_TEXTLINE) || (component_level == OCR_LEVEL_WORD) );
output_text.clear();
if (component_rects != NULL)
component_rects->clear();
if (component_texts != NULL)
component_texts->clear();
if (component_confidences != NULL)
component_confidences->clear();
}
void OCRHMMDecoder::run(Mat& image, Mat& mask, string& output_text, vector<Rect>* component_rects,
vector<string>* component_texts, vector<float>* component_confidences,
int component_level)
{
CV_Assert( (image.type() == CV_8UC1) || (image.type() == CV_8UC3) );
CV_Assert( mask.type() == CV_8UC1 );
CV_Assert( (component_level == OCR_LEVEL_TEXTLINE) || (component_level == OCR_LEVEL_WORD) );
output_text.clear();
if (component_rects != NULL)
component_rects->clear();
if (component_texts != NULL)
component_texts->clear();
if (component_confidences != NULL)
component_confidences->clear();
}
CV_WRAP String OCRHMMDecoder::run(InputArray image, int min_confidence, int component_level)
{
std::string output1;
std::string output2;
vector<string> component_texts;
vector<float> component_confidences;
Mat image_m = image.getMat();
run(image_m, output1, NULL, &component_texts, &component_confidences, component_level);
for(unsigned int i = 0; i < component_texts.size(); i++)
{
//cout << "confidence: " << component_confidences[i] << " text:" << component_texts[i] << endl;
if(component_confidences[i] > min_confidence)
{
output2 += component_texts[i];
}
}
return String(output2);
}
CV_WRAP cv::String OCRHMMDecoder::run(InputArray image, InputArray mask, int min_confidence, int component_level)
{
std::string output1;
std::string output2;
vector<string> component_texts;
vector<float> component_confidences;
Mat image_m = image.getMat();
Mat mask_m = mask.getMat();
run(image_m, mask_m, output1, NULL, &component_texts, &component_confidences, component_level);
for(unsigned int i = 0; i < component_texts.size(); i++)
{
cout << "confidence: " << component_confidences[i] << " text:" << component_texts[i] << endl;
if(component_confidences[i] > min_confidence)
{
output2 += component_texts[i];
}
}
return String(output2);
}
void OCRHMMDecoder::ClassifierCallback::eval( InputArray image, vector<int>& out_class, vector<double>& out_confidence)
{
CV_Assert(( image.getMat().type() == CV_8UC3 ) || ( image.getMat().type() == CV_8UC1 ));
out_class.clear();
out_confidence.clear();
}
bool sort_rect_horiz (Rect a,Rect b);
bool sort_rect_horiz (Rect a,Rect b) { return (a.x<b.x); }
class OCRHMMDecoderImpl : public OCRHMMDecoder
{
public:
//Default constructor
OCRHMMDecoderImpl( Ptr<OCRHMMDecoder::ClassifierCallback> _classifier,
const string& _vocabulary,
InputArray transition_probabilities_table,
InputArray emission_probabilities_table,
decoder_mode _mode)
{
classifier = _classifier;
transition_p = transition_probabilities_table.getMat();
emission_p = emission_probabilities_table.getMat();
vocabulary = _vocabulary;
mode = _mode;
}
~OCRHMMDecoderImpl()
{
}
void run( Mat& image,
string& out_sequence,
vector<Rect>* component_rects,
vector<string>* component_texts,
vector<float>* component_confidences,
int component_level)
{
CV_Assert( (image.type() == CV_8UC1) || (image.type() == CV_8UC3) );
CV_Assert( (image.cols > 0) && (image.rows > 0) );
CV_Assert( component_level == OCR_LEVEL_WORD );
out_sequence.clear();
if (component_rects != NULL)
component_rects->clear();
if (component_texts != NULL)
component_texts->clear();
if (component_confidences != NULL)
component_confidences->clear();
// First we split a line into words
vector<Mat> words_mask;
vector<Rect> words_rect;
/// Find contours
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
Mat tmp;
image.copyTo(tmp);
findContours( tmp, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0, 0) );
if (contours.size() < 6)
{
//do not split lines with less than 6 characters
words_mask.push_back(image);
words_rect.push_back(Rect(0,0,image.cols,image.rows));
}
else
{
Mat_<float> vector_w((int)image.cols,1);
reduce(image, vector_w, 0, REDUCE_SUM, -1);
vector<int> spaces;
vector<int> spaces_start;
vector<int> spaces_end;
int space_count=0;
int last_one_idx;
int s_init = 0, s_end=vector_w.cols;
for (int s=0; s<vector_w.cols; s++)
{
if (vector_w.at<float>(0,s) == 0)
s_init = s+1;
else
break;
}
for (int s=vector_w.cols-1; s>=0; s--)
{
if (vector_w.at<float>(0,s) == 0)
s_end = s;
else
break;
}
for (int s=s_init; s<s_end; s++)
{
if (vector_w.at<float>(0,s) == 0)
{
space_count++;
} else {
if (space_count!=0)
{
spaces.push_back(space_count);
spaces_start.push_back(last_one_idx);
spaces_end.push_back(s-1);
}
space_count = 0;
last_one_idx = s;
}
}
Scalar mean_space,std_space;
meanStdDev(Mat(spaces),mean_space,std_space);
int num_word_spaces = 0;
int last_word_space_end = 0;
for (int s=0; s<(int)spaces.size(); s++)
{
if (spaces_end.at(s)-spaces_start.at(s) > mean_space[0]+(mean_space[0]*1.1)) //this 1.1 is a param?
{
if (num_word_spaces == 0)
{
//cout << " we have a word from 0 to " << spaces_start.at(s) << endl;
Mat word_mask;
Rect word_rect = Rect(0,0,spaces_start.at(s),image.rows);
image(word_rect).copyTo(word_mask);
words_mask.push_back(word_mask);
words_rect.push_back(word_rect);
}
else
{
//cout << " we have a word from " << last_word_space_end << " to " << spaces_start.at(s) << endl;
Mat word_mask;
Rect word_rect = Rect(last_word_space_end,0,spaces_start.at(s)-last_word_space_end,image.rows);
image(word_rect).copyTo(word_mask);
words_mask.push_back(word_mask);
words_rect.push_back(word_rect);
}
num_word_spaces++;
last_word_space_end = spaces_end.at(s);
}
}
//cout << " we have a word from " << last_word_space_end << " to " << vector_w.cols << endl << endl << endl;
Mat word_mask;
Rect word_rect = Rect(last_word_space_end,0,vector_w.cols-last_word_space_end,image.rows);
image(word_rect).copyTo(word_mask);
words_mask.push_back(word_mask);
words_rect.push_back(word_rect);
}
for (int w=0; w<(int)words_mask.size(); w++)
{
vector< vector<int> > observations;
vector< vector<double> > confidences;
vector<int> obs;
// First find contours and sort by x coordinate of bbox
words_mask[w].copyTo(tmp);
if (tmp.empty())
continue;
contours.clear();
hierarchy.clear();
/// Find contours
findContours( tmp, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0, 0) );
vector<Rect> contours_rect;
for (int i=0; i<(int)contours.size(); i++)
{
contours_rect.push_back(boundingRect(contours[i]));
}
sort(contours_rect.begin(), contours_rect.end(), sort_rect_horiz);
// Do character recognition foreach contour
for (int i=0; i<(int)contours.size(); i++)
{
Mat tmp_mask;
words_mask[w](contours_rect.at(i)).copyTo(tmp_mask);
vector<int> out_class;
vector<double> out_conf;
classifier->eval(tmp_mask,out_class,out_conf);
if (!out_class.empty())
obs.push_back(out_class[0]);
observations.push_back(out_class);
confidences.push_back(out_conf);
//cout << " out class = " << vocabulary[out_class[0]] << endl;
}
//This must be extracted from dictionary, or just assumed to be equal for all characters
vector<double> start_p(vocabulary.size());
for (int i=0; i<(int)vocabulary.size(); i++)
start_p[i] = 1.0/vocabulary.size();
Mat V = Mat::zeros((int)observations.size(),(int)vocabulary.size(),CV_64FC1);
vector<string> path(vocabulary.size());
// Initialize base cases (t == 0)
for (int i=0; i<(int)vocabulary.size(); i++)
{
for (int j=0; j<(int)observations[0].size(); j++)
{
emission_p.at<double>(observations[0][j],obs[0]) = confidences[0][j];
}
V.at<double>(0,i) = start_p[i] * emission_p.at<double>(i,obs[0]);
path[i] = vocabulary.at(i);
}
// Run Viterbi for t > 0
for (int t=1; t<(int)obs.size(); t++)
{
//Dude this has to be done each time!!
emission_p = Mat::eye(62,62,CV_64FC1);
for (int e=0; e<(int)observations[t].size(); e++)
{
emission_p.at<double>(observations[t][e],obs[t]) = confidences[t][e];
}
vector<string> newpath(vocabulary.size());
for (int i=0; i<(int)vocabulary.size(); i++)
{
double max_prob = 0;
int best_idx = 0;
for (int j=0; j<(int)vocabulary.size(); j++)
{
double prob = V.at<double>(t-1,j) * transition_p.at<double>(j,i) * emission_p.at<double>(i,obs[t]);
if ( prob > max_prob)
{
max_prob = prob;
best_idx = j;
}
}
V.at<double>(t,i) = max_prob;
newpath[i] = path[best_idx] + vocabulary.at(i);
}
// Don't need to remember the old paths
path.swap(newpath);
}
double max_prob = 0;
int best_idx = 0;
for (int i=0; i<(int)vocabulary.size(); i++)
{
double prob = V.at<double>((int)obs.size()-1,i);
if ( prob > max_prob)
{
max_prob = prob;
best_idx = i;
}
}
//cout << path[best_idx] << endl;
if (out_sequence.size()>0) out_sequence = out_sequence+" "+path[best_idx];
else out_sequence = path[best_idx];
if (component_rects != NULL)
component_rects->push_back(words_rect[w]);
if (component_texts != NULL)
component_texts->push_back(path[best_idx]);
if (component_confidences != NULL)
component_confidences->push_back((float)max_prob);
}
return;
}
void run( Mat& image,
Mat& mask,
string& out_sequence,
vector<Rect>* component_rects,
vector<string>* component_texts,
vector<float>* component_confidences,
int component_level)
{
CV_Assert( (image.type() == CV_8UC1) || (image.type() == CV_8UC3) );
CV_Assert( mask.type() == CV_8UC1 );
CV_Assert( (image.cols > 0) && (image.rows > 0) );
CV_Assert( (image.cols == mask.cols) && (image.rows == mask.rows) );
CV_Assert( component_level == OCR_LEVEL_WORD );
out_sequence.clear();
if (component_rects != NULL)
component_rects->clear();
if (component_texts != NULL)
component_texts->clear();
if (component_confidences != NULL)
component_confidences->clear();
// First we split a line into words
vector<Mat> words_mask;
vector<Rect> words_rect;
/// Find contours
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
Mat tmp;
mask.copyTo(tmp);
findContours( tmp, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0, 0) );
if (contours.size() < 6)
{
//do not split lines with less than 6 characters
words_mask.push_back(mask);
words_rect.push_back(Rect(0,0,mask.cols,mask.rows));
}
else
{
Mat_<float> vector_w((int)mask.cols,1);
reduce(mask, vector_w, 0, REDUCE_SUM, -1);
vector<int> spaces;
vector<int> spaces_start;
vector<int> spaces_end;
int space_count=0;
int last_one_idx;
int s_init = 0, s_end=vector_w.cols;
for (int s=0; s<vector_w.cols; s++)
{
if (vector_w.at<float>(0,s) == 0)
s_init = s+1;
else
break;
}
for (int s=vector_w.cols-1; s>=0; s--)
{
if (vector_w.at<float>(0,s) == 0)
s_end = s;
else
break;
}
for (int s=s_init; s<s_end; s++)
{
if (vector_w.at<float>(0,s) == 0)
{
space_count++;
} else {
if (space_count!=0)
{
spaces.push_back(space_count);
spaces_start.push_back(last_one_idx);
spaces_end.push_back(s-1);
}
space_count = 0;
last_one_idx = s;
}
}
Scalar mean_space,std_space;
meanStdDev(Mat(spaces),mean_space,std_space);
int num_word_spaces = 0;
int last_word_space_end = 0;
for (int s=0; s<(int)spaces.size(); s++)
{
if (spaces_end.at(s)-spaces_start.at(s) > mean_space[0]+(mean_space[0]*1.1)) //this 1.1 is a param?
{
if (num_word_spaces == 0)
{
//cout << " we have a word from 0 to " << spaces_start.at(s) << endl;
Mat word_mask;
Rect word_rect = Rect(0,0,spaces_start.at(s),mask.rows);
mask(word_rect).copyTo(word_mask);
words_mask.push_back(word_mask);
words_rect.push_back(word_rect);
}
else
{
//cout << " we have a word from " << last_word_space_end << " to " << spaces_start.at(s) << endl;
Mat word_mask;
Rect word_rect = Rect(last_word_space_end,0,spaces_start.at(s)-last_word_space_end,mask.rows);
mask(word_rect).copyTo(word_mask);
words_mask.push_back(word_mask);
words_rect.push_back(word_rect);
}
num_word_spaces++;
last_word_space_end = spaces_end.at(s);
}
}
//cout << " we have a word from " << last_word_space_end << " to " << vector_w.cols << endl << endl << endl;
Mat word_mask;
Rect word_rect = Rect(last_word_space_end,0,vector_w.cols-last_word_space_end,mask.rows);
mask(word_rect).copyTo(word_mask);
words_mask.push_back(word_mask);
words_rect.push_back(word_rect);
}
for (int w=0; w<(int)words_mask.size(); w++)
{
vector< vector<int> > observations;
vector< vector<double> > confidences;
vector<int> obs;
// First find contours and sort by x coordinate of bbox
words_mask[w].copyTo(tmp);
if (tmp.empty())
continue;
contours.clear();
hierarchy.clear();
/// Find contours
findContours( tmp, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0, 0) );
vector<Rect> contours_rect;
for (int i=0; i<(int)contours.size(); i++)
{
contours_rect.push_back(boundingRect(contours[i]));
}
sort(contours_rect.begin(), contours_rect.end(), sort_rect_horiz);
// Do character recognition foreach contour
for (int i=0; i<(int)contours.size(); i++)
{
vector<int> out_class;
vector<double> out_conf;
//take the center of the char rect and translate it to the real origin
Point char_center = Point(contours_rect.at(i).x+contours_rect.at(i).width/2,
contours_rect.at(i).y+contours_rect.at(i).height/2);
char_center.x += words_rect[w].x;
char_center.y += words_rect[w].y;
int win_size = max(contours_rect.at(i).width,contours_rect.at(i).height);
win_size += (int)(win_size*0.6); // add some pixels in the border TODO: is this a parameter for the user space?
Rect char_rect = Rect(char_center.x-win_size/2,char_center.y-win_size/2,win_size,win_size);
char_rect &= Rect(0,0,image.cols,image.rows);
Mat tmp_image;
image(char_rect).copyTo(tmp_image);
classifier->eval(tmp_image,out_class,out_conf);
if (!out_class.empty())
obs.push_back(out_class[0]);
//cout << " out class = " << vocabulary[out_class[0]] << "(" << out_conf[0] << ")" << endl;
observations.push_back(out_class);
confidences.push_back(out_conf);
}
//This must be extracted from dictionary, or just assumed to be equal for all characters
vector<double> start_p(vocabulary.size());
for (int i=0; i<(int)vocabulary.size(); i++)
start_p[i] = 1.0/vocabulary.size();
Mat V = Mat::zeros((int)observations.size(),(int)vocabulary.size(),CV_64FC1);
vector<string> path(vocabulary.size());
// Initialize base cases (t == 0)
for (int i=0; i<(int)vocabulary.size(); i++)
{
for (int j=0; j<(int)observations[0].size(); j++)
{
emission_p.at<double>(observations[0][j],obs[0]) = confidences[0][j];
}
V.at<double>(0,i) = start_p[i] * emission_p.at<double>(i,obs[0]);
path[i] = vocabulary.at(i);
}
// Run Viterbi for t > 0
for (int t=1; t<(int)obs.size(); t++)
{
//Dude this has to be done each time!!
emission_p = Mat::eye(62,62,CV_64FC1);
for (int e=0; e<(int)observations[t].size(); e++)
{
emission_p.at<double>(observations[t][e],obs[t]) = confidences[t][e];
}
vector<string> newpath(vocabulary.size());
for (int i=0; i<(int)vocabulary.size(); i++)
{
double max_prob = 0;
int best_idx = 0;
for (int j=0; j<(int)vocabulary.size(); j++)
{
double prob = V.at<double>(t-1,j) * transition_p.at<double>(j,i) * emission_p.at<double>(i,obs[t]);
if ( prob > max_prob)
{
max_prob = prob;
best_idx = j;
}
}
V.at<double>(t,i) = max_prob;
newpath[i] = path[best_idx] + vocabulary.at(i);
}
// Don't need to remember the old paths
path.swap(newpath);
}
double max_prob = 0;
int best_idx = 0;
for (int i=0; i<(int)vocabulary.size(); i++)
{
double prob = V.at<double>((int)obs.size()-1,i);
if ( prob > max_prob)
{
max_prob = prob;
best_idx = i;
}
}
//cout << path[best_idx] << endl;
if (out_sequence.size()>0) out_sequence = out_sequence+" "+path[best_idx];
else out_sequence = path[best_idx];
if (component_rects != NULL)
component_rects->push_back(words_rect[w]);
if (component_texts != NULL)
component_texts->push_back(path[best_idx]);
if (component_confidences != NULL)
component_confidences->push_back((float)max_prob);
}
return;
}
};
Ptr<OCRHMMDecoder> OCRHMMDecoder::create( Ptr<OCRHMMDecoder::ClassifierCallback> _classifier,
const string& _vocabulary,
InputArray transition_p,
InputArray emission_p,
decoder_mode _mode)
{
return makePtr<OCRHMMDecoderImpl>(_classifier, _vocabulary, transition_p, emission_p, _mode);
}
Ptr<OCRHMMDecoder> OCRHMMDecoder::create( Ptr<OCRHMMDecoder::ClassifierCallback> _classifier,
const String& _vocabulary,
InputArray transition_p,
InputArray emission_p,
int _mode)
{
return makePtr<OCRHMMDecoderImpl>(_classifier, _vocabulary, transition_p, emission_p, (decoder_mode)_mode);
}
class CV_EXPORTS OCRHMMClassifierKNN : public OCRHMMDecoder::ClassifierCallback
{
public:
//constructor
OCRHMMClassifierKNN(const std::string& filename);
// Destructor
~OCRHMMClassifierKNN() {}
void eval( InputArray mask, vector<int>& out_class, vector<double>& out_confidence );
private:
Ptr<KNearest> knn;
};
OCRHMMClassifierKNN::OCRHMMClassifierKNN (const string& filename)
{
knn = KNearest::create();
if (ifstream(filename.c_str()))
{
Mat hus, labels;
cv::FileStorage storage(filename.c_str(), cv::FileStorage::READ);
storage["hus"] >> hus;
storage["labels"] >> labels;
storage.release();
knn->train(hus, ROW_SAMPLE, labels);
}
else
CV_Error(Error::StsBadArg, "Default classifier data file not found!");
}
void OCRHMMClassifierKNN::eval( InputArray _mask, vector<int>& out_class, vector<double>& out_confidence )
{
CV_Assert( _mask.getMat().type() == CV_8UC1 );
out_class.clear();
out_confidence.clear();
int image_height = 35;
int image_width = 35;
int num_features = 200;
Mat img = _mask.getMat();
Mat tmp;
img.copyTo(tmp);
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
/// Find contours
findContours( tmp, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0, 0) );
if (contours.empty())
return;
int idx = 0;
if (contours.size() > 1)
{
// this is to make sure we have the mask with a single contour
// e.g "i" and "j" have two contours, but it may be also a part of a neighbour character
// we take the larger one and clean the outside in order to have a single contour
int max_area = 0;
for (int cc=0; cc<(int)contours.size(); cc++)
{
int area_c = boundingRect(contours[cc]).area();
if ( area_c > max_area)
{
idx = cc;
max_area = area_c;
}
}
// clean-up the outside of the contour
Mat tmp_c = Mat::zeros(tmp.rows, tmp.cols, CV_8UC1);
drawContours(tmp_c, contours, idx, Scalar(255), FILLED);
img = img & tmp_c;
}
Rect bbox = boundingRect(contours[idx]);
//Crop to fit the exact rect of the contour and resize to a fixed-sized matrix of 35 x 35 pixel, while retaining the centroid of the region and aspect ratio.
Mat mask = Mat::zeros(image_height,image_width,CV_8UC1);
img(bbox).copyTo(tmp);
if (tmp.cols>tmp.rows)
{
int height = image_width*tmp.rows/tmp.cols;
if(height == 0) height = 1;
resize(tmp,tmp,Size(image_width,height));
tmp.copyTo(mask(Rect(0,(image_height-height)/2,image_width,height)));
}
else
{
int width = image_height*tmp.cols/tmp.rows;
if(width == 0) width = 1;
resize(tmp,tmp,Size(width,image_height));
tmp.copyTo(mask(Rect((image_width-width)/2,0,width,image_height)));
}
//find contours again (now resized)
mask.copyTo(tmp);
findContours( tmp, contours, hierarchy, RETR_LIST, CHAIN_APPROX_SIMPLE, Point(0, 0) );
vector<Mat> maps;
for (int i=0; i<8; i++)
{
Mat map = Mat::zeros(image_height,image_width,CV_8UC1);
maps.push_back(map);
}
for (int c=0; c<(int)contours.size(); c++)
{
for (int i=0; i<(int)contours[c].size(); i++)
{
//cout << contours[c][i] << " -- " << contours[c][(i+1)%contours[c].size()] << endl;
double dy = contours[c][i].y - contours[c][(i+1)%contours[c].size()].y;
double dx = contours[c][i].x - contours[c][(i+1)%contours[c].size()].x;
double angle = atan2 (dy,dx) * 180 / 3.14159265;
//cout << " angle = " << angle << endl;
int idx_a = 0;
if ((angle>=157.5)||(angle<=-157.5))
idx_a = 0;
else if ((angle>=-157.5)&&(angle<=-112.5))
idx_a = 1;
else if ((angle>=-112.5)&&(angle<=-67.5))
idx_a = 2;
else if ((angle>=-67.5)&&(angle<=-22.5))
idx_a = 3;
else if ((angle>=-22.5)&&(angle<=22.5))
idx_a = 4;
else if ((angle>=22.5)&&(angle<=67.5))
idx_a = 5;
else if ((angle>=67.5)&&(angle<=112.5))
idx_a = 6;
else if ((angle>=112.5)&&(angle<=157.5))
idx_a = 7;
line(maps[idx_a],contours[c][i],contours[c][(i+1)%contours[c].size()],Scalar(255));
}
}
//On each bitmap a regular 7x7 Gaussian masks are evenly placed
for (int i=0; i<(int)maps.size(); i++)
{
copyMakeBorder(maps[i],maps[i],7,7,7,7,BORDER_CONSTANT,Scalar(0));
GaussianBlur(maps[i], maps[i], Size(7,7), 2, 2);
normalize(maps[i],maps[i],0,255,NORM_MINMAX);
resize(maps[i],maps[i],Size(image_width,image_height));
}
//Generate features for each bitmap
Mat sample = Mat(1,num_features,CV_32FC1);
Mat patch;
for (int i=0; i<(int)maps.size(); i++)
{
for(int y=0; y<image_height; y=y+7)
{
for(int x=0; x<image_width; x=x+7)
{
maps[i](Rect(x,y,7,7)).copyTo(patch);
Scalar mean,std;
meanStdDev(patch,mean,std);
sample.at<float>(0,i*25+((int)x/7)+((int)y/7)*5) = (float)(mean[0]/255);
//cout << " avg " << mean[0] << " in patch " << x << "," << y << " channel " << i << " idx = " << i*25+((int)x/7)+((int)y/7)*5<< endl;
}
}
}
Mat responses,dists,predictions;
knn->findNearest( sample, 11, predictions, responses, dists);
Scalar dist_sum = sum(dists);
Mat class_predictions = Mat::zeros(1,62,CV_64FC1);
vector<vector<int> > equivalency_mat(62);
equivalency_mat[2].push_back(28); // c -> C
equivalency_mat[28].push_back(2); // C -> c
equivalency_mat[8].push_back(34); // i -> I
equivalency_mat[8].push_back(11); // i -> l
equivalency_mat[11].push_back(8); // l -> i
equivalency_mat[11].push_back(34); // l -> I
equivalency_mat[34].push_back(8); // I -> i
equivalency_mat[34].push_back(11); // I -> l
equivalency_mat[9].push_back(35); // j -> J
equivalency_mat[35].push_back(9); // J -> j
equivalency_mat[14].push_back(40); // o -> O
equivalency_mat[14].push_back(52); // o -> 0
equivalency_mat[40].push_back(14); // O -> o
equivalency_mat[40].push_back(52); // O -> 0
equivalency_mat[52].push_back(14); // 0 -> o
equivalency_mat[52].push_back(40); // 0 -> O
equivalency_mat[15].push_back(41); // p -> P
equivalency_mat[41].push_back(15); // P -> p
equivalency_mat[18].push_back(44); // s -> S
equivalency_mat[44].push_back(18); // S -> s
equivalency_mat[20].push_back(46); // u -> U
equivalency_mat[46].push_back(20); // U -> u
equivalency_mat[21].push_back(47); // v -> V
equivalency_mat[47].push_back(21); // V -> v
equivalency_mat[22].push_back(48); // w -> W
equivalency_mat[48].push_back(22); // W -> w
equivalency_mat[23].push_back(49); // x -> X
equivalency_mat[49].push_back(23); // X -> x
equivalency_mat[25].push_back(51); // z -> Z
equivalency_mat[51].push_back(25); // Z -> z
for (int j=0; j<responses.cols; j++)
{
if (responses.at<float>(0,j)<0)
continue;
class_predictions.at<double>(0,(int)responses.at<float>(0,j)) += dists.at<float>(0,j);
for (int e=0; e<(int)equivalency_mat[(int)responses.at<float>(0,j)].size(); e++)
{
class_predictions.at<double>(0,equivalency_mat[(int)responses.at<float>(0,j)][e]) += dists.at<float>(0,j);
dist_sum[0] += dists.at<float>(0,j);
}
}
class_predictions = class_predictions/dist_sum[0];
out_class.push_back((int)predictions.at<float>(0,0));
out_confidence.push_back(class_predictions.at<double>(0,(int)predictions.at<float>(0,0)));
for (int i=0; i<class_predictions.cols; i++)
{
if ((class_predictions.at<double>(0,i) > 0) && (i != out_class[0]))
{
out_class.push_back(i);
out_confidence.push_back(class_predictions.at<double>(0,i));
}
}
}
Ptr<OCRHMMDecoder::ClassifierCallback> loadOCRHMMClassifierNM(const String& filename)
{
return makePtr<OCRHMMClassifierKNN>(std::string(filename));
}
class CV_EXPORTS OCRHMMClassifierCNN : public OCRHMMDecoder::ClassifierCallback
{
public:
//constructor
OCRHMMClassifierCNN(const std::string& filename);
// Destructor
~OCRHMMClassifierCNN() {}
void eval( InputArray image, vector<int>& out_class, vector<double>& out_confidence );
protected:
void normalizeAndZCA(Mat& patches);
double eval_feature(Mat& feature, double* prob_estimates);
private:
int nr_class; // number of classes
int nr_feature; // number of features
Mat feature_min; // scale range
Mat feature_max;
Mat weights; // Logistic Regression weights
Mat kernels; // CNN kernels
Mat M, P; // ZCA Whitening parameters
int window_size; // window size
int quad_size;
int patch_size;
int num_quads; // extract 25 quads (12x12) from each image
int num_tiles; // extract 25 patches (8x8) from each quad
double alpha; // used in non-linear activation function z = max(0, |D*a| - alpha)
};
OCRHMMClassifierCNN::OCRHMMClassifierCNN (const string& filename)
{
if (ifstream(filename.c_str()))
{
FileStorage fs(filename, FileStorage::READ);
// Load kernels bank and withenning params
fs["kernels"] >> kernels;
fs["M"] >> M;
fs["P"] >> P;
// Load Logistic Regression weights
fs["weights"] >> weights;
// Load feature scaling ranges
fs["feature_min"] >> feature_min;
fs["feature_max"] >> feature_max;
fs.release();
}
else
CV_Error(Error::StsBadArg, "Default classifier data file not found!");
// check all matrix dimensions match correctly and no one is empty
CV_Assert( (M.cols > 0) && (M.rows > 0) );
CV_Assert( (P.cols > 0) && (P.rows > 0) );
CV_Assert( (kernels.cols > 0) && (kernels.rows > 0) );
CV_Assert( (weights.cols > 0) && (weights.rows > 0) );
CV_Assert( (feature_min.cols > 0) && (feature_min.rows > 0) );
CV_Assert( (feature_max.cols > 0) && (feature_max.rows > 0) );
nr_feature = weights.rows;
nr_class = weights.cols;
patch_size = (int)sqrt((float)kernels.cols);
// algorithm internal parameters
window_size = 32;
num_quads = 25;
num_tiles = 25;
quad_size = 12;
alpha = 0.5;
}
void OCRHMMClassifierCNN::eval( InputArray _src, vector<int>& out_class, vector<double>& out_confidence )
{
CV_Assert(( _src.getMat().type() == CV_8UC3 ) || ( _src.getMat().type() == CV_8UC1 ));
out_class.clear();
out_confidence.clear();
Mat img = _src.getMat();
if(img.type() == CV_8UC3)
{
cvtColor(img,img,COLOR_RGB2GRAY);
}
// shall we resize the input image or make a copy ?
resize(img,img,Size(window_size,window_size));
Mat quad;
Mat tmp;
int patch_count = 0;
vector< vector<double> > data_pool(9);
int quad_id = 1;
for (int q_x=0; q_x<=window_size-quad_size; q_x=q_x+(int)(quad_size/2-1))
{
for (int q_y=0; q_y<=window_size-quad_size; q_y=q_y+(int)(quad_size/2-1))
{
Rect quad_rect = Rect(q_x,q_y,quad_size,quad_size);
quad = img(quad_rect);
//start sliding window (8x8) in each tile and store the patch as row in data_pool
for (int w_x=0; w_x<=quad_size-patch_size; w_x++)
{
for (int w_y=0; w_y<=quad_size-patch_size; w_y++)
{
quad(Rect(w_x,w_y,patch_size,patch_size)).copyTo(tmp);
tmp = tmp.reshape(0,1);
tmp.convertTo(tmp, CV_64F);
normalizeAndZCA(tmp);
vector<double> patch;
tmp.copyTo(patch);
if ((quad_id == 1)||(quad_id == 2)||(quad_id == 6)||(quad_id == 7))
data_pool[0].insert(data_pool[0].end(),patch.begin(),patch.end());
if ((quad_id == 2)||(quad_id == 7)||(quad_id == 3)||(quad_id == 8)||(quad_id == 4)||(quad_id == 9))
data_pool[1].insert(data_pool[1].end(),patch.begin(),patch.end());
if ((quad_id == 4)||(quad_id == 9)||(quad_id == 5)||(quad_id == 10))
data_pool[2].insert(data_pool[2].end(),patch.begin(),patch.end());
if ((quad_id == 6)||(quad_id == 11)||(quad_id == 16)||(quad_id == 7)||(quad_id == 12)||(quad_id == 17))
data_pool[3].insert(data_pool[3].end(),patch.begin(),patch.end());
if ((quad_id == 7)||(quad_id == 12)||(quad_id == 17)||(quad_id == 8)||(quad_id == 13)||(quad_id == 18)||(quad_id == 9)||(quad_id == 14)||(quad_id == 19))
data_pool[4].insert(data_pool[4].end(),patch.begin(),patch.end());
if ((quad_id == 9)||(quad_id == 14)||(quad_id == 19)||(quad_id == 10)||(quad_id == 15)||(quad_id == 20))
data_pool[5].insert(data_pool[5].end(),patch.begin(),patch.end());
if ((quad_id == 16)||(quad_id == 21)||(quad_id == 17)||(quad_id == 22))
data_pool[6].insert(data_pool[6].end(),patch.begin(),patch.end());
if ((quad_id == 17)||(quad_id == 22)||(quad_id == 18)||(quad_id == 23)||(quad_id == 19)||(quad_id == 24))
data_pool[7].insert(data_pool[7].end(),patch.begin(),patch.end());
if ((quad_id == 19)||(quad_id == 24)||(quad_id == 20)||(quad_id == 25))
data_pool[8].insert(data_pool[8].end(),patch.begin(),patch.end());
patch_count++;
}
}
quad_id++;
}
}
//do dot product of each normalized and whitened patch
//each pool is averaged and this yields a representation of 9xD
Mat feature = Mat::zeros(9,kernels.rows,CV_64FC1);
for (int i=0; i<9; i++)
{
Mat pool = Mat(data_pool[i]);
pool = pool.reshape(0,(int)data_pool[i].size()/kernels.cols);
for (int p=0; p<pool.rows; p++)
{
for (int f=0; f<kernels.rows; f++)
{
feature.row(i).at<double>(0,f) = feature.row(i).at<double>(0,f) + max(0.0,std::abs(pool.row(p).dot(kernels.row(f)))-alpha);
}
}
}
feature = feature.reshape(0,1);
// data must be normalized within the range obtained during training
double lower = -1.0;
double upper = 1.0;
for (int k=0; k<feature.cols; k++)
{
feature.at<double>(0,k) = lower + (upper-lower) *
(feature.at<double>(0,k)-feature_min.at<double>(0,k))/
(feature_max.at<double>(0,k)-feature_min.at<double>(0,k));
}
double *p = new double[nr_class];
double predict_label = eval_feature(feature,p);
//cout << " Prediction: " << vocabulary[predict_label] << " with probability " << p[0] << endl;
if (predict_label < 0)
CV_Error(Error::StsInternal, "OCRHMMClassifierCNN::eval Error: unexpected prediction in eval_feature()");
out_class.push_back((int)predict_label);
out_confidence.push_back(p[(int)predict_label]);
for (int i = 0; i<nr_class; i++)
{
if ( (i != (int)predict_label) && (p[i] != 0.) )
{
out_class.push_back(i);
out_confidence.push_back(p[i]);
}
}
}
// normalize for contrast and apply ZCA whitening to a set of image patches
void OCRHMMClassifierCNN::normalizeAndZCA(Mat& patches)
{
//Normalize for contrast
for (int i=0; i<patches.rows; i++)
{
Scalar row_mean, row_std;
meanStdDev(patches.row(i),row_mean,row_std);
row_std[0] = sqrt(pow(row_std[0],2)*patches.cols/(patches.cols-1)+10);
patches.row(i) = (patches.row(i) - row_mean[0]) / row_std[0];
}
//ZCA whitening
if ((M.dims == 0) || (P.dims == 0))
{
Mat CC;
calcCovarMatrix(patches,CC,M,COVAR_NORMAL|COVAR_ROWS|COVAR_SCALE);
CC = CC * patches.rows / (patches.rows-1);
Mat e_val,e_vec;
eigen(CC.t(),e_val,e_vec);
e_vec = e_vec.t();
sqrt(1./(e_val + 0.1), e_val);
Mat V = Mat::zeros(e_vec.rows, e_vec.cols, CV_64FC1);
Mat D = Mat::eye(e_vec.rows, e_vec.cols, CV_64FC1);
for (int i=0; i<e_vec.cols; i++)
{
e_vec.col(e_vec.cols-i-1).copyTo(V.col(i));
D.col(i) = D.col(i) * e_val.at<double>(0,e_val.rows-i-1);
}
P = V * D * V.t();
}
for (int i=0; i<patches.rows; i++)
patches.row(i) = patches.row(i) - M;
patches = patches * P;
}
double OCRHMMClassifierCNN::eval_feature(Mat& feature, double* prob_estimates)
{
for(int i=0;i<nr_class;i++)
prob_estimates[i] = 0;
for(int idx=0; idx<nr_feature; idx++)
for(int i=0;i<nr_class;i++)
prob_estimates[i] += weights.at<float>(idx,i)*feature.at<double>(0,idx); //TODO use vectorized dot product
int dec_max_idx = 0;
for(int i=1;i<nr_class;i++)
{
if(prob_estimates[i] > prob_estimates[dec_max_idx])
dec_max_idx = i;
}
for(int i=0;i<nr_class;i++)
prob_estimates[i]=1/(1+exp(-prob_estimates[i]));
double sum=0;
for(int i=0; i<nr_class; i++)
sum+=prob_estimates[i];
for(int i=0; i<nr_class; i++)
prob_estimates[i]=prob_estimates[i]/sum;
return dec_max_idx;
}
Ptr<OCRHMMDecoder::ClassifierCallback> loadOCRHMMClassifierCNN(const String& filename)
{
return makePtr<OCRHMMClassifierCNN>(std::string(filename));
}
/** @brief Utility function to create a tailored language model transitions table from a given list of words (lexicon).
@param vocabulary The language vocabulary (chars when ascii english text).
@param lexicon The list of words that are expected to be found in a particular image.
@param transition_probabilities_table Output table with transition probabilities between character pairs. cols == rows == vocabulary.size().
The function calculate frequency statistics of character pairs from the given lexicon and fills
the output transition_probabilities_table with them.
The transition_probabilities_table can be used as input in the OCRHMMDecoder::create() and OCRBeamSearchDecoder::create() methods.
@note
- (C++) An alternative would be to load the default generic language transition table provided in the text module samples folder (created from ispell 42869 english words list) :
<https://github.com/Itseez/opencv_contrib/blob/master/modules/text/samples/OCRHMM_transitions_table.xml>
*/
void createOCRHMMTransitionsTable(string& vocabulary, vector<string>& lexicon, OutputArray _transitions)
{
CV_Assert( vocabulary.size() > 0 );
CV_Assert( lexicon.size() > 0 );
if ( (_transitions.getMat().cols != (int)vocabulary.size()) ||
(_transitions.getMat().rows != (int)vocabulary.size()) ||
(_transitions.getMat().type() != CV_64F) )
{
_transitions.create((int)vocabulary.size(), (int)vocabulary.size(), CV_64F);
}
Mat transitions = _transitions.getMat();
transitions = Scalar(0);
Mat count_pairs = Mat::zeros(1, (int)vocabulary.size(), CV_64F);
for (size_t w=0; w<lexicon.size(); w++)
{
for (size_t i=0,j=1; i<lexicon[w].size()-1; i++,j++)
{
size_t idx_i = vocabulary.find(lexicon[w][i]);
size_t idx_j = vocabulary.find(lexicon[w][j]);
if ((idx_i == string::npos) || (idx_j == string::npos))
{
CV_Error(Error::StsBadArg, "Found a non-vocabulary char in lexicon!");
}
transitions.at<double>((int)idx_i,(int)idx_j) += 1;
count_pairs.at<double>(0,(int)idx_i) += 1;
}
}
for (int i=0; i<transitions.rows; i++)
{
transitions.row(i) = transitions.row(i) / count_pairs.at<double>(0,i); //normalize
}
return;
}
Mat createOCRHMMTransitionsTable(const String& vocabulary, vector<cv::String>& lexicon)
{
std::string voc(vocabulary);
vector<string> lex;
for(vector<cv::String>::iterator l = lexicon.begin(); l != lexicon.end(); l++)
lex.push_back(std::string(*l));
Mat _transitions;
createOCRHMMTransitionsTable(voc, lex, _transitions);
return _transitions;
}
}
}
| 36.869668
| 182
| 0.546715
|
privet56
|
1076b2333ef3bf8cc319dbab583179a11e05836c
| 4,376
|
cpp
|
C++
|
test/mafCoreTest/mafObjectFactoryTest.cpp
|
tartarini/MAF3
|
f9614d36591754544b23e3a670980799254dfd2c
|
[
"Apache-2.0"
] | 1
|
2021-05-10T19:01:48.000Z
|
2021-05-10T19:01:48.000Z
|
test/mafCoreTest/mafObjectFactoryTest.cpp
|
examyes/MAF3
|
f9614d36591754544b23e3a670980799254dfd2c
|
[
"Apache-2.0"
] | null | null | null |
test/mafCoreTest/mafObjectFactoryTest.cpp
|
examyes/MAF3
|
f9614d36591754544b23e3a670980799254dfd2c
|
[
"Apache-2.0"
] | 1
|
2018-02-06T03:51:57.000Z
|
2018-02-06T03:51:57.000Z
|
/*
* mafObjectFactoryTest.cpp
* mafCoreTest
*
* Created by Paolo Quadrani on 22/09/09.
* Copyright 2009 SCS-B3C. All rights reserved.
*
* See Licence at: http://tiny.cc/QXJ4D
*
*/
#include <mafTestSuite.h>
#include <mafObjectBase.h>
#include <mafObject.h>
#include <mafSmartPointer.h>
using namespace mafCore;
/**
Class name: mafObjectFactoryTest
This class implements the test suite for mafObjectFactory.
*/
//! <title>
//mafObjectFactory
//! </title>
//! <description>
//mafObjectFactory represent the factory for all the MAF3 objects.
//Objects are instantiated by calling the static method CreateObject and passing as argument the typename of the object to create.
//! </description>
class mafObjectFactoryTest : public QObject {
Q_OBJECT
private Q_SLOTS:
/// Initialize test variables
void initTestCase() {
}
/// Cleanup tes variables memory allocation.
void cleanupTestCase() {
}
/// register new object in factory test case.
void registerObjectTest();
/// create object instance test case.
void instantiateObjectTest();
/// create object instance test case (return the base type).
void instantiateObjectBaseTest();
/// create object instance test case.
void instantiateQObjectTest();
/// create object instance test case (return the base type).
void instantiateQObjectFromStringTest();
/// unregister object test case.
void unregisterObjectTest();
/// smart pointer creation test case.
void instantiateSmartObjectTest();
/// smart pointer creation test case.
void bindObjectToIconTest();
private:
};
void mafObjectFactoryTest::registerObjectTest() {
mafUnregisterObject(mafCore::mafObjectBase);
// Not registered object should not be present in factory.
bool res = mafObjectFactory::instance()->isObjectRegistered("mafCore::mafObjectBase");
QVERIFY(res == false);
// Register mafObjectBase.
//! <snippet>
mafRegisterObject(mafCore::mafObjectBase);
//! </snippet>
// Now mafObjectBase is present into the factory.
//! <snippet>
res = mafObjectFactory::instance()->isObjectRegistered("mafCore::mafObjectBase");
//! </snippet>
QVERIFY(res == true);
// Register qt Object
mafRegisterQtObject(QObject)
res = mafObjectFactory::instance()->isQtObjectRegistered("QObject");
QVERIFY(res == true);
}
void mafObjectFactoryTest::instantiateObjectTest() {
// registered object.
mafObjectBase *obj_base = mafNEW(mafCore::mafObjectBase);
QVERIFY(obj_base != NULL);
mafDEL(obj_base);
}
void mafObjectFactoryTest::instantiateObjectBaseTest() {
mafRegisterObject(mafCore::mafObject);
mafObjectBase *obj = mafNEWFromString("mafCore::mafObject");
QVERIFY(obj != NULL);
QString cn = obj->metaObject()->className();
QVERIFY(cn == "mafCore::mafObject");
mafDEL(obj);
}
void mafObjectFactoryTest::instantiateQObjectTest() {
mafRegisterQtObject(QObject)
QObject *obj = mafNEWQt(QObject);
QVERIFY(obj != NULL);
delete obj;
}
void mafObjectFactoryTest::instantiateQObjectFromStringTest() {
mafRegisterQtObject(QObject);
QObject *obj = mafNEWQtFromString("QObject");
QVERIFY(obj != NULL);
QString cn = obj->metaObject()->className();
QVERIFY(cn == "QObject");
delete obj;
}
void mafObjectFactoryTest::unregisterObjectTest() {
mafUnregisterObject(mafCore::mafObjectBase);
bool res = mafObjectFactory::instance()->isObjectRegistered("mafCore::mafObjectBase");
QVERIFY(res == false);
}
void mafObjectFactoryTest::instantiateSmartObjectTest() {
// Register again mafObjectBase (previous test case unregistered it).
mafRegisterObject(mafCore::mafObjectBase);
mafSmartPointer<mafObjectBase> obj = mafCreateSmartObject(mafCore::mafObjectBase);
QVERIFY(obj.isNull() == false);
}
void mafObjectFactoryTest::bindObjectToIconTest() {
// Bind an object type with a file name
QString objectType = "mafTestType";
QString testFileName = "testFileName";
mafBindObjectToIcon(objectType, testFileName);
// Verify if the bind has worked, getting the file name form object type
QString returnFileName = mafIconFromObjectType(objectType);
QVERIFY(testFileName.compare(returnFileName) == 0);
}
MAF_REGISTER_TEST(mafObjectFactoryTest);
#include "mafObjectFactoryTest.moc"
| 28.415584
| 130
| 0.714808
|
tartarini
|
10774cef6d1870a500580c378f09a70b58456ebe
| 5,943
|
cc
|
C++
|
tensorflow/compiler/tf2xla/side_effect_util.cc
|
yage99/tensorflow
|
c7fa71b32a3635eb25596ae80d007b41007769c4
|
[
"Apache-2.0"
] | 78
|
2020-08-04T12:36:25.000Z
|
2022-03-25T04:23:40.000Z
|
tensorflow/compiler/tf2xla/side_effect_util.cc
|
sseung0703/tensorflow
|
be084bd7a4dd241eb781fc704f57bcacc5c9b6dd
|
[
"Apache-2.0"
] | 203
|
2019-06-14T23:53:10.000Z
|
2022-02-10T02:27:23.000Z
|
tensorflow/compiler/tf2xla/side_effect_util.cc
|
sseung0703/tensorflow
|
be084bd7a4dd241eb781fc704f57bcacc5c9b6dd
|
[
"Apache-2.0"
] | 66
|
2020-05-15T10:05:12.000Z
|
2022-02-14T07:28:18.000Z
|
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/tf2xla/side_effect_util.h"
#include "absl/strings/numbers.h"
#include "tensorflow/core/graph/algorithm.h"
namespace tensorflow {
const char kXlaTokenInputNodesAttrName[] = "_xla_token_input_nodes";
const char kXlaTokenArgNodeName[] = "_xla_token_arg_node";
const char kXlaHasHostTransferAttrName[] = "_xla_has_host_transfer";
const char kXlaReplicaIdAttrName[] = "_xla_replica_id";
const char kXlaIsPlaceholderForTailOcAttrName[] =
"_xla_is_placeholder_for_tail_oc";
const char kXlaOriginalOutsideCompilationNodeName[] =
"_xla_original_oc_node_name";
const char kXlaHostTransferRendezvousNameAttr[] =
"_xla_host_transfer_rendezvous";
const char kXlaHostTransferOriginalTypeAttr[] =
"_xla_host_transfer_original_type";
const char kXlaHostTransferIsLowerBitsAttr[] =
"_xla_host_transfer_is_lower_bits";
Status SetDeviceOrdinalAttributeForNode(Node* node, int device_ordinal) {
if (!HasNodeAttr(node->def(), kXlaHasHostTransferAttrName)) {
return errors::InvalidArgument("Node ", node->DebugString(),
" does not have attribute ",
kXlaHasHostTransferAttrName);
}
if (node->type_string() == "_XlaRecvAtHost" ||
node->type_string() == "_XlaSendFromHost") {
node->ClearAttr("device_ordinal");
node->AddAttr("device_ordinal", device_ordinal);
} else if (node->IsIfNode()) {
AttrValue device_ordinal_value;
device_ordinal_value.set_i(device_ordinal);
for (const string& attr_name :
std::vector<string>{"then_branch", "else_branch"}) {
NameAttrList branch_func;
TF_RETURN_IF_ERROR(GetNodeAttr(node->attrs(), attr_name, &branch_func));
(*branch_func.mutable_attr())["_device_ordinal"] = device_ordinal_value;
node->ClearAttr(attr_name);
node->AddAttr(attr_name, branch_func);
}
} else if (node->IsWhileNode()) {
AttrValue device_ordinal_value;
device_ordinal_value.set_i(device_ordinal);
for (const string& attr_name : std::vector<string>{"cond", "body"}) {
NameAttrList branch_func;
TF_RETURN_IF_ERROR(GetNodeAttr(node->attrs(), attr_name, &branch_func));
(*branch_func.mutable_attr())["_device_ordinal"] = device_ordinal_value;
node->ClearAttr(attr_name);
node->AddAttr(attr_name, branch_func);
}
} else if (HasNodeAttr(node->def(), "_device_ordinal")) {
// Function call node containing outside compilation.
node->ClearAttr("_device_ordinal");
node->AddAttr("_device_ordinal", device_ordinal);
} else {
return errors::Internal("Unknown node type to set 'device_ordinal': ",
node->DebugString());
}
return Status::OK();
}
std::set<std::string> CalculateTokenInputsForOutputToken(const Graph& g) {
std::set<std::string> results;
Node* first_side_effecting_node_on_path = nullptr;
ReverseDFS(g,
[&](Node* n) {
std::vector<string> token_input_nodes;
if (!GetNodeAttr(n->attrs(), kXlaTokenInputNodesAttrName,
&token_input_nodes)
.ok() ||
token_input_nodes.empty()) {
return;
}
if (first_side_effecting_node_on_path != nullptr) {
return;
}
first_side_effecting_node_on_path = n;
string original_node_name;
TF_CHECK_OK(GetNodeAttr(n->def(),
kXlaOriginalOutsideCompilationNodeName,
&original_node_name));
results.insert(original_node_name);
},
[&](Node* n) {
if (first_side_effecting_node_on_path == n) {
first_side_effecting_node_on_path = nullptr;
}
},
NodeComparatorName());
return results;
}
bool HasSideEffectingNodes(const Graph& g) {
for (Node* n : g.nodes()) {
std::vector<string> token_input_nodes;
if (GetNodeAttr(n->attrs(), kXlaTokenInputNodesAttrName, &token_input_nodes)
.ok() &&
!token_input_nodes.empty()) {
return true;
}
}
return false;
}
Status ParseHostComputeCoreList(absl::Span<const string> list_from_attr,
std::map<string, int>* host_compute_core) {
for (const auto& hc_core : list_from_attr) {
std::vector<string> parts = str_util::Split(hc_core, ":");
if (parts.size() != 2) {
return errors::InvalidArgument(
"Malformed host_compute_core entry ", hc_core,
" should be <cluster_name>:<core_number>.");
}
int core;
if (!absl::numbers_internal::safe_strto32_base(parts[1], &core, 10)) {
return errors::InvalidArgument("Malformed host_compute_core entry ",
hc_core,
" part after ':' should be an integer.");
}
if (host_compute_core->find(parts[0]) != host_compute_core->end()) {
return errors::InvalidArgument(
"Duplicate host_compute_core entry for cluster ", parts[0]);
}
(*host_compute_core)[parts[0]] = core;
}
return Status::OK();
}
} // namespace tensorflow
| 37.377358
| 80
| 0.639071
|
yage99
|
10780f16b1b92e9d72ac1ac15e2bda4b0a7ddae8
| 1,645
|
cpp
|
C++
|
proxygen/lib/http/codec/compress/test/HPACKHeaderTests.cpp
|
rhzx3519/proxygen
|
ad1f5dc3c90d6215e322360d77bbd920f846d27b
|
[
"BSD-3-Clause"
] | 8
|
2015-09-05T14:24:38.000Z
|
2019-09-02T05:48:28.000Z
|
proxygen/lib/http/codec/compress/test/HPACKHeaderTests.cpp
|
Yeolar/coral-proxygen
|
345b69711852698326634c295266c1823a9c668b
|
[
"BSD-3-Clause"
] | null | null | null |
proxygen/lib/http/codec/compress/test/HPACKHeaderTests.cpp
|
Yeolar/coral-proxygen
|
345b69711852698326634c295266c1823a9c668b
|
[
"BSD-3-Clause"
] | 1
|
2021-09-19T12:13:52.000Z
|
2021-09-19T12:13:52.000Z
|
/*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <glog/logging.h>
#include <gtest/gtest.h>
#include <memory>
#include <proxygen/lib/http/codec/compress/HPACKHeader.h>
#include <sstream>
using namespace proxygen;
using namespace std;
using namespace testing;
class HPACKHeaderTests : public testing::Test {
};
TEST_F(HPACKHeaderTests, size) {
HPACKHeader h(":path", "/");
EXPECT_EQ(h.bytes(), 32 + 5 + 1);
}
TEST_F(HPACKHeaderTests, operators) {
HPACKHeader h0(":path", "/");
HPACKHeader h1(":path", "/");
HPACKHeader h2(":path", "/index.php");
HPACKHeader h3("x-fb-debug", "test");
// ==
EXPECT_TRUE(h0 == h1);
EXPECT_FALSE(h1 == h2);
// <
EXPECT_FALSE(h1 < h1);
EXPECT_TRUE(h1 < h2);
EXPECT_TRUE(h1 < h3);
// >
EXPECT_FALSE(h2 > h2);
EXPECT_TRUE(h3 > h2);
EXPECT_TRUE(h2 > h1);
stringstream out;
out << h1;
EXPECT_EQ(out.str(), ":path: /");
}
TEST_F(HPACKHeaderTests, has_value) {
HPACKHeader h1(":path", "");
HPACKHeader h2(":path", "/");
EXPECT_FALSE(h1.hasValue());
EXPECT_TRUE(h2.hasValue());
}
TEST_F(HPACKHeaderTests, is_indexable) {
HPACKHeader path(":path", "index.php?q=42");
EXPECT_FALSE(path.isIndexable());
HPACKHeader cdn(":path", "/hprofile-ak-prn1/49496_6024432_1026115112_n.jpg");
EXPECT_FALSE(cdn.isIndexable());
HPACKHeader clen("content-length", "512");
EXPECT_FALSE(clen.isIndexable());
}
| 25.307692
| 79
| 0.674772
|
rhzx3519
|
1079356793ededa288a040e9c60eda37a3c91ca1
| 6,989
|
cpp
|
C++
|
src/Master/Interface/GridCtrlSource/GridCell.cpp
|
averkhaturau/Tarificator
|
90a976d16ecab8c6a1cd75f4cb6a860dc4c76ce5
|
[
"MIT"
] | null | null | null |
src/Master/Interface/GridCtrlSource/GridCell.cpp
|
averkhaturau/Tarificator
|
90a976d16ecab8c6a1cd75f4cb6a860dc4c76ce5
|
[
"MIT"
] | null | null | null |
src/Master/Interface/GridCtrlSource/GridCell.cpp
|
averkhaturau/Tarificator
|
90a976d16ecab8c6a1cd75f4cb6a860dc4c76ce5
|
[
"MIT"
] | null | null | null |
// GridCell.cpp : implementation file
//
// MFC Grid Control - Main grid cell class
//
// Provides the implementation for the "default" cell type of the
// grid control. Adds in cell editing.
//
// Written by Chris Maunder <cmaunder@mail.com>
// Copyright (c) 1998-2001. All Rights Reserved.
//
// This code may be used in compiled form in any way you desire. This
// file may be redistributed unmodified by any means PROVIDING it is
// not sold for profit without the authors written consent, and
// providing that this notice and the authors name and all copyright
// notices remains intact.
//
// An email letting me know how you are using it would be nice as well.
//
// This file is provided "as is" with no expressed or implied warranty.
// The author accepts no liability for any damage/loss of business that
// this product may cause.
//
// For use with CGridCtrl v2.20+
//
// History:
// Eric Woodruff - 20 Feb 2000 - Added PrintCell() plus other minor changes
// Ken Bertelson - 12 Apr 2000 - Split CGridCell into CGridCell and CGridCellBase
// <kenbertelson@hotmail.com>
// C Maunder - 17 Jun 2000 - Font handling optimsed, Added CGridDefaultCell
//
/////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "GridCell.h"
#include "InPlaceEdit.h"
#include "GridCtrl.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
IMPLEMENT_DYNCREATE(CGridCell, CGridCellBase)
IMPLEMENT_DYNCREATE(CGridDefaultCell, CGridCell)
/////////////////////////////////////////////////////////////////////////////
// GridCell
CGridCell::CGridCell()
{
m_plfFont = NULL;
Reset();
}
CGridCell::~CGridCell()
{
delete m_plfFont;
}
/////////////////////////////////////////////////////////////////////////////
// GridCell Attributes
void CGridCell::operator=(const CGridCell& cell)
{
CGridCellBase::operator=( cell);
}
void CGridCell::Reset()
{
CGridCellBase::Reset();
m_strText.Empty();
m_nImage = -1;
m_pGrid = NULL;
m_bEditing = FALSE;
m_pEditWnd = NULL;
m_nFormat = (DWORD)-1; // Use default from CGridDefaultCell
m_crBkClr = CLR_DEFAULT; // Background colour (or CLR_DEFAULT)
m_crFgClr = CLR_DEFAULT; // Forground colour (or CLR_DEFAULT)
m_nMargin = (UINT)-1; // Use default from CGridDefaultCell
delete m_plfFont;
m_plfFont = NULL; // Cell font
}
void CGridCell::SetFont(const LOGFONT* plf)
{
if (plf == NULL)
{
delete m_plfFont;
m_plfFont = NULL;
}
else
{
if (!m_plfFont)
m_plfFont = new LOGFONT;
if (m_plfFont)
memcpy(m_plfFont, plf, sizeof(LOGFONT));
}
}
LOGFONT* CGridCell::GetFont() const
{
if (m_plfFont == NULL)
{
CGridDefaultCell *pDefaultCell = (CGridDefaultCell*) GetDefaultCell();
if (!pDefaultCell)
return NULL;
return pDefaultCell->GetFont();
}
return m_plfFont;
}
CFont* CGridCell::GetFontObject() const
{
// If the default font is specified, use the default cell implementation
if (m_plfFont == NULL)
{
CGridDefaultCell *pDefaultCell = (CGridDefaultCell*) GetDefaultCell();
if (!pDefaultCell)
return NULL;
return pDefaultCell->GetFontObject();
}
else
{
static CFont Font;
Font.DeleteObject();
Font.CreateFontIndirect(m_plfFont);
return &Font;
}
}
DWORD CGridCell::GetFormat() const
{
if (m_nFormat == (DWORD)-1)
{
CGridDefaultCell *pDefaultCell = (CGridDefaultCell*) GetDefaultCell();
if (!pDefaultCell)
return 0;
return pDefaultCell->GetFormat();
}
return m_nFormat;
}
UINT CGridCell::GetMargin() const
{
if (m_nMargin == (UINT)-1)
{
CGridDefaultCell *pDefaultCell = (CGridDefaultCell*) GetDefaultCell();
if (!pDefaultCell)
return 0;
return pDefaultCell->GetMargin();
}
return m_nMargin;
}
/////////////////////////////////////////////////////////////////////////////
// GridCell Operations
BOOL CGridCell::Edit(int nRow, int nCol, CRect rect, CPoint /* point */, UINT nID, UINT nChar)
{
if ( m_bEditing )
{
if (m_pEditWnd)
m_pEditWnd->SendMessage ( WM_CHAR, nChar );
}
else
{
DWORD dwStyle = ES_LEFT;
if (GetFormat() & DT_RIGHT)
dwStyle = ES_RIGHT;
else if (GetFormat() & DT_CENTER)
dwStyle = ES_CENTER;
m_bEditing = TRUE;
// InPlaceEdit auto-deletes itself
CGridCtrl* pGrid = GetGrid();
m_pEditWnd = new CInPlaceEdit(pGrid, rect, dwStyle, nID, nRow, nCol, GetText(), nChar);
}
return TRUE;
}
void CGridCell::EndEdit()
{
if (m_pEditWnd)
((CInPlaceEdit*)m_pEditWnd)->EndEdit();
}
void CGridCell::OnEndEdit()
{
m_bEditing = FALSE;
m_pEditWnd = NULL;
}
/////////////////////////////////////////////////////////////////////////////
// CGridDefaultCell
CGridDefaultCell::CGridDefaultCell()
{
#ifdef _WIN32_WCE
m_nFormat = DT_LEFT|DT_VCENTER|DT_SINGLELINE|DT_NOPREFIX;
#else
m_nFormat = DT_LEFT|DT_VCENTER|DT_SINGLELINE|DT_NOPREFIX | DT_END_ELLIPSIS;
#endif
m_crFgClr = CLR_DEFAULT;
m_crBkClr = CLR_DEFAULT;
m_Size = CSize(30,10);
m_dwStyle = 0;
#ifdef _WIN32_WCE
LOGFONT lf;
GetObject(GetStockObject(SYSTEM_FONT), sizeof(LOGFONT), &lf);
SetFont(&lf);
#else // not CE
NONCLIENTMETRICS ncm;
ncm.cbSize = sizeof(NONCLIENTMETRICS);
VERIFY(SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(NONCLIENTMETRICS), &ncm, 0));
SetFont(&(ncm.lfMessageFont));
#endif
}
CGridDefaultCell::~CGridDefaultCell()
{
m_Font.DeleteObject();
}
void CGridDefaultCell::SetFont(const LOGFONT* plf)
{
ASSERT(plf);
if (!plf) return;
m_Font.DeleteObject();
m_Font.CreateFontIndirect(plf);
CGridCell::SetFont(plf);
// Get the font size and hence the default cell size
CDC* pDC = CDC::FromHandle(::GetDC(NULL));
if (pDC)
{
CFont* pOldFont = pDC->SelectObject(&m_Font);
SetMargin(pDC->GetTextExtent(_T(" "), 1).cx);
m_Size = pDC->GetTextExtent(_T(" XXXXXXXXXXXX "), 14);
m_Size.cy = (m_Size.cy * 3) / 2;
pDC->SelectObject(pOldFont);
ReleaseDC(NULL, pDC->GetSafeHdc());
}
else
{
SetMargin(3);
m_Size = CSize(40,16);
}
}
LOGFONT* CGridDefaultCell::GetFont() const
{
ASSERT(m_plfFont); // This is the default - it CAN'T be NULL!
return m_plfFont;
}
CFont* CGridDefaultCell::GetFontObject() const
{
ASSERT(m_Font.GetSafeHandle());
return (CFont*) &m_Font;
}
| 25.050179
| 95
| 0.586922
|
averkhaturau
|
1079bd8161b38341748a734f38734f58fe95344f
| 472
|
cpp
|
C++
|
leetcode_archived_cpp/LeetCode_402.cpp
|
Sean10/Algorithm_code
|
46ff1cb5b81400cbcc324dabdf4298bf7a55e5eb
|
[
"BSD-3-Clause"
] | null | null | null |
leetcode_archived_cpp/LeetCode_402.cpp
|
Sean10/Algorithm_code
|
46ff1cb5b81400cbcc324dabdf4298bf7a55e5eb
|
[
"BSD-3-Clause"
] | 7
|
2021-03-19T04:41:21.000Z
|
2021-10-19T15:46:36.000Z
|
leetcode_archived_cpp/LeetCode_402.cpp
|
Sean10/Algorithm_code
|
46ff1cb5b81400cbcc324dabdf4298bf7a55e5eb
|
[
"BSD-3-Clause"
] | null | null | null |
class Solution {
public:
string removeKdigits(string num, int k) {
string ans = "";
for (char i: num)
{
while (ans.length() && ans.back() > i && k)
{
ans.pop_back();
k--;
}
if (ans.length() || i != '0')
ans.push_back(i);
}
while (ans.length() && k--)
ans.pop_back();
return ans.empty() ? "0" : ans;
}
};
| 19.666667
| 55
| 0.372881
|
Sean10
|
107a40d24c606582780a0f24666762bf478b59ff
| 8,094
|
cpp
|
C++
|
src/MySimple3D.cpp
|
Qt-Widgets/EasyQPainter
|
328d4fc22dc96f8219cb7153f140327c66417b5a
|
[
"MIT"
] | 4
|
2021-01-10T06:31:11.000Z
|
2021-09-07T23:16:19.000Z
|
src/MySimple3D.cpp
|
Qt-Widgets/EasyQPainter
|
328d4fc22dc96f8219cb7153f140327c66417b5a
|
[
"MIT"
] | null | null | null |
src/MySimple3D.cpp
|
Qt-Widgets/EasyQPainter
|
328d4fc22dc96f8219cb7153f140327c66417b5a
|
[
"MIT"
] | 2
|
2020-12-16T03:20:38.000Z
|
2021-02-24T05:26:03.000Z
|
#include "MySimple3D.h"
#include <QPaintEvent>
#include <QResizeEvent>
#include <QPainter>
#include <QPainterPath>
#include <QtMath>
#include <algorithm>
#include <QTimer>
#include <QtConcurrent>
#include <QDebug>
MySimple3D::MySimple3D(QWidget *parent)
: QWidget(parent)
{
initItems();
//异步处理结束,获取结果并刷新窗口
connect(&watcher,&QFutureWatcher<QImage>::finished,[this](){
image=watcher.result();
update();
});
fpsTime=QTime::currentTime();
fpsTime.start();
//定时旋转风车
QTimer *timer=new QTimer(this);
connect(timer,&QTimer::timeout,[=]{
animationStep+=2.0;
drawImage(width(),height());
});
timer->start(50);
}
MySimple3D::~MySimple3D()
{
if(!watcher.isFinished())
watcher.waitForFinished();
}
void MySimple3D::paintEvent(QPaintEvent *event)
{
event->accept();
QPainter painter(this);
painter.fillRect(this->rect(),Qt::black);
if(image.size().isValid())
painter.drawImage(0,0,image);
//fps统计
if(fpsTime.elapsed()>1000){
fpsTime.restart();
fpsCounter=fpsTemp;
fpsTemp=0;
}else{
fpsTemp++;
}
painter.setPen(QPen(Qt::white));
painter.drawText(10,30,"FPS:"+QString::number(fpsCounter));
painter.drawText(10,50,"Drag Moving ... ...");
}
void MySimple3D::mousePressEvent(QMouseEvent *event)
{
mousePressed=true;
mousePos=event->pos();
QWidget::mousePressEvent(event);
}
void MySimple3D::mouseMoveEvent(QMouseEvent *event)
{
if(mousePressed){
const QPoint posOffset=event->pos()-mousePos;
mousePos=event->pos();
//旋转矩阵 x和y分量
xRotate+=-posOffset.y();
yRotate+=-posOffset.x();
//update();
drawImage(width(),height());
}
QWidget::mouseMoveEvent(event);
}
void MySimple3D::mouseReleaseEvent(QMouseEvent *event)
{
mousePressed=false;
QWidget::mouseReleaseEvent(event);
}
void MySimple3D::resizeEvent(QResizeEvent *event)
{
if(event->size().isValid()){
const int width=event->size().width();
const int height=event->size().height();
drawImage(width,height);
}
QWidget::resizeEvent(event);
}
void MySimple3D::initItems()
{
//模板的嵌套时自动格式化太难看了
//四个扇叶
My3DMeta* sub_fan1=new My3DMeta{{
QVector3D(0,0,0),QVector3D(-250,250,0),QVector3D(-300,200,10),QVector3D(-100,0,10)},
QColor(110,250,250,200)};
My3DMeta* sub_fan2=new My3DMeta{{
QVector3D(0,0,0),QVector3D(-250,-250,0),QVector3D(-200,-300,10),QVector3D(0,-100,10)},
QColor(130,250,250,200)};
My3DMeta* sub_fan3=new My3DMeta{{
QVector3D(0,0,0),QVector3D(250,-250,0),QVector3D(300,-200,10),QVector3D(100,0,10)},
QColor(110,250,250,200)};
My3DMeta* sub_fan4=new My3DMeta{{
QVector3D(0,0,0),QVector3D(250,250,0),QVector3D(200,300,10),QVector3D(0,100,10)},
QColor(130,250,250,200)};
auto sub_fanmetas=QList<QSharedPointer<My3DMeta>>{QSharedPointer<My3DMeta>(sub_fan1),
QSharedPointer<My3DMeta>(sub_fan2),
QSharedPointer<My3DMeta>(sub_fan3),
QSharedPointer<My3DMeta>(sub_fan4)};
auto sub_fansubs=QList<QSharedPointer<My3DItem>>{};
My3DItem *sub_fanitem=new My3DItem{
QVector3D(0,400,-150),
QVector3D(0,0,0),
sub_fanmetas,
sub_fansubs,
QVector3D(0,0,-1)}; //给z加了动画因子
//风车主干,共9个面,顶部尖塔4+主干4+底面
My3DMeta* sub_main1=new My3DMeta{{
QVector3D(100,400,100),QVector3D(-100,400,100),QVector3D(0,500,0)},
QColor(250,0,0)};
My3DMeta* sub_main2=new My3DMeta{{
QVector3D(-100,400,100),QVector3D(-100,400,-100),QVector3D(0,500,0)},
QColor(0,250,0)};
My3DMeta* sub_main3=new My3DMeta{{
QVector3D(-100,400,-100),QVector3D(100,400,-100),QVector3D(0,500,0)},
QColor(0,0,250)};
My3DMeta* sub_main4=new My3DMeta{{
QVector3D(100,400,-100),QVector3D(100,400,100),QVector3D(0,500,0)},
QColor(250,250,0)};
My3DMeta* sub_main5=new My3DMeta{{
QVector3D(100,400,100),QVector3D(-100,400,100),QVector3D(-120,0,120),QVector3D(120,0,120)},
QColor(205,150,100)};
My3DMeta* sub_main6=new My3DMeta{{
QVector3D(-100,400,100),QVector3D(-100,400,-100),QVector3D(-120,0,-120),QVector3D(-120,0,120)},
QColor(220,150,100)};
My3DMeta* sub_main7=new My3DMeta{{
QVector3D(-100,400,-100),QVector3D(100,400,-100),QVector3D(120,0,-120),QVector3D(-120,0,-120)},
QColor(235,150,100)};
My3DMeta* sub_main8=new My3DMeta{{
QVector3D(100,400,-100),QVector3D(100,400,100),QVector3D(120,0,120),QVector3D(120,0,-120)},
QColor(250,150,100)};
My3DMeta* sub_main9=new My3DMeta{{
QVector3D(-120,0,120),QVector3D(-120,0,-120),QVector3D(120,0,-120),QVector3D(120,0,120)},
QColor(200,150,0)};
auto sub_mainmetas=QList<QSharedPointer<My3DMeta>>{QSharedPointer<My3DMeta>(sub_main1),
QSharedPointer<My3DMeta>(sub_main2),
QSharedPointer<My3DMeta>(sub_main3),
QSharedPointer<My3DMeta>(sub_main4),
QSharedPointer<My3DMeta>(sub_main5),
QSharedPointer<My3DMeta>(sub_main6),
QSharedPointer<My3DMeta>(sub_main7),
QSharedPointer<My3DMeta>(sub_main8),
QSharedPointer<My3DMeta>(sub_main9)};
auto sub_mainsubs=QList<QSharedPointer<My3DItem>>{QSharedPointer<My3DItem>(sub_fanitem)};
My3DItem *sub_mainitem=new My3DItem{
QVector3D(0,0,0),
QVector3D(0,0,0),
sub_mainmetas,
sub_mainsubs};
//根节点,一个平面,(平面用半透明是为了穿模时看起来没那么别扭)
My3DMeta* root_meta=new My3DMeta{{
QVector3D(-200,0,200),QVector3D(200,0,200),
QVector3D(200,0,-200),QVector3D(-200,0,-200)},
QColor(255,255,255,100)};
auto root_metas=QList<QSharedPointer<My3DMeta>>{QSharedPointer<My3DMeta>(root_meta)};
auto root_subs=QList<QSharedPointer<My3DItem>>{QSharedPointer<My3DItem>(sub_mainitem)};
rootItem=My3DItem{
QVector3D(0,-300,0),
QVector3D(0,0,0),
root_metas,
root_subs,
QVector3D(0,0.1f,0)}; //给y加了动画因子
}
void MySimple3D::drawImage(int width, int height)
{
if(width>10&&height>10&&watcher.isFinished()){
QVector3D rotate=QVector3D(xRotate,yRotate,0);
int step=animationStep;
//多线程绘制到image上,绘制完后返回image并绘制到窗口上
QFuture<QImage> futures=QtConcurrent::run([this,width,height,rotate,step](){
QImage img(width,height,QImage::Format_ARGB32);
img.fill(Qt::transparent);
QPainter painter(&img);
if(!painter.isActive())
return img;
painter.fillRect(img.rect(),Qt::black);
//painter.save();
//坐标原点移动到中心
painter.translate(width/2,height/2);
//计算所有的图元顶点路径
QList<QSharedPointer<My3DMeta>> surface_metas=rootItem.calculateSurfaceMetas(QVector3D(0,0,0),rotate,step);
//根据z轴排序
std::sort(surface_metas.begin(),surface_metas.end(),
[](const QSharedPointer<My3DMeta> &left,const QSharedPointer<My3DMeta> &right){
return left->z<right->z;
});
//根据z值从远处开始绘制图元路径
for(QSharedPointer<My3DMeta> meta:surface_metas)
{
painter.fillPath(meta->path,meta->color);
}
//painter.restore();
return img;
});
watcher.setFuture(futures);
}
}
| 35.5
| 119
| 0.578453
|
Qt-Widgets
|
107b6ea10ec0c7ffabde63763b40b16f15bb4380
| 12,809
|
hpp
|
C++
|
include/GlobalNamespace/TutorialPause.hpp
|
RedBrumbler/BeatSaber-Quest-Codegen
|
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
|
[
"Unlicense"
] | null | null | null |
include/GlobalNamespace/TutorialPause.hpp
|
RedBrumbler/BeatSaber-Quest-Codegen
|
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
|
[
"Unlicense"
] | null | null | null |
include/GlobalNamespace/TutorialPause.hpp
|
RedBrumbler/BeatSaber-Quest-Codegen
|
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
|
[
"Unlicense"
] | null | null | null |
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: IGamePause
#include "GlobalNamespace/IGamePause.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
// Forward declaring type: TutorialSongController
class TutorialSongController;
// Forward declaring type: SaberManager
class SaberManager;
// Forward declaring type: AudioListenerController
class AudioListenerController;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Action
class Action;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Forward declaring type: TutorialPause
class TutorialPause;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::GlobalNamespace::TutorialPause);
DEFINE_IL2CPP_ARG_TYPE(::GlobalNamespace::TutorialPause*, "", "TutorialPause");
// Type namespace:
namespace GlobalNamespace {
// Size: 0x41
#pragma pack(push, 1)
// Autogenerated type: TutorialPause
// [TokenAttribute] Offset: FFFFFFFF
class TutorialPause : public ::Il2CppObject/*, public ::GlobalNamespace::IGamePause*/ {
public:
#ifdef USE_CODEGEN_FIELDS
public:
#else
#ifdef CODEGEN_FIELD_ACCESSIBILITY
CODEGEN_FIELD_ACCESSIBILITY:
#else
protected:
#endif
#endif
// [InjectAttribute] Offset: 0x12565E0
// private readonly TutorialSongController _tutorialSongController
// Size: 0x8
// Offset: 0x10
::GlobalNamespace::TutorialSongController* tutorialSongController;
// Field size check
static_assert(sizeof(::GlobalNamespace::TutorialSongController*) == 0x8);
// [InjectAttribute] Offset: 0x12565F0
// private readonly SaberManager _saberManager
// Size: 0x8
// Offset: 0x18
::GlobalNamespace::SaberManager* saberManager;
// Field size check
static_assert(sizeof(::GlobalNamespace::SaberManager*) == 0x8);
// [InjectAttribute] Offset: 0x1256600
// private readonly AudioListenerController _audioListenerController
// Size: 0x8
// Offset: 0x20
::GlobalNamespace::AudioListenerController* audioListenerController;
// Field size check
static_assert(sizeof(::GlobalNamespace::AudioListenerController*) == 0x8);
// private System.Action didPauseEvent
// Size: 0x8
// Offset: 0x28
::System::Action* didPauseEvent;
// Field size check
static_assert(sizeof(::System::Action*) == 0x8);
// private System.Action willResumeEvent
// Size: 0x8
// Offset: 0x30
::System::Action* willResumeEvent;
// Field size check
static_assert(sizeof(::System::Action*) == 0x8);
// private System.Action didResumeEvent
// Size: 0x8
// Offset: 0x38
::System::Action* didResumeEvent;
// Field size check
static_assert(sizeof(::System::Action*) == 0x8);
// private System.Boolean _pause
// Size: 0x1
// Offset: 0x40
bool pause;
// Field size check
static_assert(sizeof(bool) == 0x1);
public:
// Creating interface conversion operator: operator ::GlobalNamespace::IGamePause
operator ::GlobalNamespace::IGamePause() noexcept {
return *reinterpret_cast<::GlobalNamespace::IGamePause*>(this);
}
// Get instance field reference: private readonly TutorialSongController _tutorialSongController
::GlobalNamespace::TutorialSongController*& dyn__tutorialSongController();
// Get instance field reference: private readonly SaberManager _saberManager
::GlobalNamespace::SaberManager*& dyn__saberManager();
// Get instance field reference: private readonly AudioListenerController _audioListenerController
::GlobalNamespace::AudioListenerController*& dyn__audioListenerController();
// Get instance field reference: private System.Action didPauseEvent
::System::Action*& dyn_didPauseEvent();
// Get instance field reference: private System.Action willResumeEvent
::System::Action*& dyn_willResumeEvent();
// Get instance field reference: private System.Action didResumeEvent
::System::Action*& dyn_didResumeEvent();
// Get instance field reference: private System.Boolean _pause
bool& dyn__pause();
// public System.Boolean get_isPaused()
// Offset: 0x2AB2338
bool get_isPaused();
// public System.Void add_didPauseEvent(System.Action value)
// Offset: 0x2AB2340
void add_didPauseEvent(::System::Action* value);
// public System.Void remove_didPauseEvent(System.Action value)
// Offset: 0x2AB23E4
void remove_didPauseEvent(::System::Action* value);
// public System.Void add_willResumeEvent(System.Action value)
// Offset: 0x2AB2488
void add_willResumeEvent(::System::Action* value);
// public System.Void remove_willResumeEvent(System.Action value)
// Offset: 0x2AB252C
void remove_willResumeEvent(::System::Action* value);
// public System.Void add_didResumeEvent(System.Action value)
// Offset: 0x2AB25D0
void add_didResumeEvent(::System::Action* value);
// public System.Void remove_didResumeEvent(System.Action value)
// Offset: 0x2AB2674
void remove_didResumeEvent(::System::Action* value);
// public System.Void Pause()
// Offset: 0x2AB2718
void Pause();
// public System.Void WillResume()
// Offset: 0x2AB2798
void WillResume();
// public System.Void Resume()
// Offset: 0x2AB27AC
void Resume();
// public System.Void .ctor()
// Offset: 0x2AB2828
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static TutorialPause* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::GlobalNamespace::TutorialPause::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<TutorialPause*, creationType>()));
}
}; // TutorialPause
#pragma pack(pop)
static check_size<sizeof(TutorialPause), 64 + sizeof(bool)> __GlobalNamespace_TutorialPauseSizeCheck;
static_assert(sizeof(TutorialPause) == 0x41);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: GlobalNamespace::TutorialPause::get_isPaused
// Il2CppName: get_isPaused
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::TutorialPause::*)()>(&GlobalNamespace::TutorialPause::get_isPaused)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::TutorialPause*), "get_isPaused", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::TutorialPause::add_didPauseEvent
// Il2CppName: add_didPauseEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::TutorialPause::*)(::System::Action*)>(&GlobalNamespace::TutorialPause::add_didPauseEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Action")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::TutorialPause*), "add_didPauseEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::TutorialPause::remove_didPauseEvent
// Il2CppName: remove_didPauseEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::TutorialPause::*)(::System::Action*)>(&GlobalNamespace::TutorialPause::remove_didPauseEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Action")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::TutorialPause*), "remove_didPauseEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::TutorialPause::add_willResumeEvent
// Il2CppName: add_willResumeEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::TutorialPause::*)(::System::Action*)>(&GlobalNamespace::TutorialPause::add_willResumeEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Action")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::TutorialPause*), "add_willResumeEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::TutorialPause::remove_willResumeEvent
// Il2CppName: remove_willResumeEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::TutorialPause::*)(::System::Action*)>(&GlobalNamespace::TutorialPause::remove_willResumeEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Action")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::TutorialPause*), "remove_willResumeEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::TutorialPause::add_didResumeEvent
// Il2CppName: add_didResumeEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::TutorialPause::*)(::System::Action*)>(&GlobalNamespace::TutorialPause::add_didResumeEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Action")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::TutorialPause*), "add_didResumeEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::TutorialPause::remove_didResumeEvent
// Il2CppName: remove_didResumeEvent
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::TutorialPause::*)(::System::Action*)>(&GlobalNamespace::TutorialPause::remove_didResumeEvent)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Action")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::TutorialPause*), "remove_didResumeEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: GlobalNamespace::TutorialPause::Pause
// Il2CppName: Pause
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::TutorialPause::*)()>(&GlobalNamespace::TutorialPause::Pause)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::TutorialPause*), "Pause", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::TutorialPause::WillResume
// Il2CppName: WillResume
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::TutorialPause::*)()>(&GlobalNamespace::TutorialPause::WillResume)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::TutorialPause*), "WillResume", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::TutorialPause::Resume
// Il2CppName: Resume
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::TutorialPause::*)()>(&GlobalNamespace::TutorialPause::Resume)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::TutorialPause*), "Resume", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::TutorialPause::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
| 50.231373
| 190
| 0.727145
|
RedBrumbler
|
107ba00900206a88c11f64b4bcb2d22ec3d73aa0
| 7,117
|
cpp
|
C++
|
gen/blink/bindings/core/v8/V8TrackEvent.cpp
|
wenfeifei/miniblink49
|
2ed562ff70130485148d94b0e5f4c343da0c2ba4
|
[
"Apache-2.0"
] | 5,964
|
2016-09-27T03:46:29.000Z
|
2022-03-31T16:25:27.000Z
|
gen/blink/bindings/core/v8/V8TrackEvent.cpp
|
w4454962/miniblink49
|
b294b6eacb3333659bf7b94d670d96edeeba14c0
|
[
"Apache-2.0"
] | 459
|
2016-09-29T00:51:38.000Z
|
2022-03-07T14:37:46.000Z
|
gen/blink/bindings/core/v8/V8TrackEvent.cpp
|
w4454962/miniblink49
|
b294b6eacb3333659bf7b94d670d96edeeba14c0
|
[
"Apache-2.0"
] | 1,006
|
2016-09-27T05:17:27.000Z
|
2022-03-30T02:46:51.000Z
|
// 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 "V8TrackEvent.h"
#include "bindings/core/v8/ExceptionState.h"
#include "bindings/core/v8/UnionTypesCore.h"
#include "bindings/core/v8/V8AudioTrack.h"
#include "bindings/core/v8/V8DOMConfiguration.h"
#include "bindings/core/v8/V8ObjectConstructor.h"
#include "bindings/core/v8/V8TextTrack.h"
#include "bindings/core/v8/V8TrackEventInit.h"
#include "bindings/core/v8/V8VideoTrack.h"
#include "core/dom/ContextFeatures.h"
#include "core/dom/Document.h"
#include "core/frame/LocalDOMWindow.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/TraceEvent.h"
#include "wtf/GetPtr.h"
#include "wtf/RefPtr.h"
namespace blink {
// Suppress warning: global constructors, because struct WrapperTypeInfo is trivial
// and does not depend on another global objects.
#if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wglobal-constructors"
#endif
const WrapperTypeInfo V8TrackEvent::wrapperTypeInfo = { gin::kEmbedderBlink, V8TrackEvent::domTemplate, V8TrackEvent::refObject, V8TrackEvent::derefObject, V8TrackEvent::trace, 0, 0, V8TrackEvent::preparePrototypeObject, V8TrackEvent::installConditionallyEnabledProperties, "TrackEvent", &V8Event::wrapperTypeInfo, WrapperTypeInfo::WrapperTypeObjectPrototype, WrapperTypeInfo::ObjectClassId, WrapperTypeInfo::NotInheritFromEventTarget, WrapperTypeInfo::Independent, WrapperTypeInfo::WillBeGarbageCollectedObject };
#if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG)
#pragma clang diagnostic pop
#endif
// This static member must be declared by DEFINE_WRAPPERTYPEINFO in TrackEvent.h.
// For details, see the comment of DEFINE_WRAPPERTYPEINFO in
// bindings/core/v8/ScriptWrappable.h.
const WrapperTypeInfo& TrackEvent::s_wrapperTypeInfo = V8TrackEvent::wrapperTypeInfo;
namespace TrackEventV8Internal {
static void trackAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TrackEvent* impl = V8TrackEvent::toImpl(holder);
VideoTrackOrAudioTrackOrTextTrack result;
impl->track(result);
v8SetReturnValue(info, result);
}
static void trackAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
TrackEventV8Internal::trackAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void constructor(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ConstructionContext, "TrackEvent", info.Holder(), info.GetIsolate());
if (UNLIKELY(info.Length() < 1)) {
setMinimumArityTypeError(exceptionState, 1, info.Length());
exceptionState.throwIfNeeded();
return;
}
V8StringResource<> type;
TrackEventInit eventInitDict;
{
type = info[0];
if (!type.prepare())
return;
if (!isUndefinedOrNull(info[1]) && !info[1]->IsObject()) {
exceptionState.throwTypeError("parameter 2 ('eventInitDict') is not an object.");
exceptionState.throwIfNeeded();
return;
}
V8TrackEventInit::toImpl(info.GetIsolate(), info[1], eventInitDict, exceptionState);
if (exceptionState.throwIfNeeded())
return;
}
RefPtrWillBeRawPtr<TrackEvent> impl = TrackEvent::create(type, eventInitDict);
v8::Local<v8::Object> wrapper = info.Holder();
wrapper = impl->associateWithWrapper(info.GetIsolate(), &V8TrackEvent::wrapperTypeInfo, wrapper);
v8SetReturnValue(info, wrapper);
}
} // namespace TrackEventV8Internal
static const V8DOMConfiguration::AccessorConfiguration V8TrackEventAccessors[] = {
{"track", TrackEventV8Internal::trackAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder},
};
void V8TrackEvent::constructorCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SCOPED_SAMPLING_STATE("blink", "DOMConstructor");
if (!info.IsConstructCall()) {
V8ThrowException::throwTypeError(info.GetIsolate(), ExceptionMessages::constructorNotCallableAsFunction("TrackEvent"));
return;
}
if (ConstructorMode::current(info.GetIsolate()) == ConstructorMode::WrapExistingObject) {
v8SetReturnValue(info, info.Holder());
return;
}
TrackEventV8Internal::constructor(info);
}
static void installV8TrackEventTemplate(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate)
{
functionTemplate->ReadOnlyPrototype();
v8::Local<v8::Signature> defaultSignature;
defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, "TrackEvent", V8Event::domTemplate(isolate), V8TrackEvent::internalFieldCount,
0, 0,
V8TrackEventAccessors, WTF_ARRAY_LENGTH(V8TrackEventAccessors),
0, 0);
functionTemplate->SetCallHandler(V8TrackEvent::constructorCallback);
functionTemplate->SetLength(1);
v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate();
ALLOW_UNUSED_LOCAL(instanceTemplate);
v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate();
ALLOW_UNUSED_LOCAL(prototypeTemplate);
// Custom toString template
functionTemplate->Set(v8AtomicString(isolate, "toString"), V8PerIsolateData::from(isolate)->toStringTemplate());
}
v8::Local<v8::FunctionTemplate> V8TrackEvent::domTemplate(v8::Isolate* isolate)
{
return V8DOMConfiguration::domClassTemplate(isolate, const_cast<WrapperTypeInfo*>(&wrapperTypeInfo), installV8TrackEventTemplate);
}
bool V8TrackEvent::hasInstance(v8::Local<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->hasInstance(&wrapperTypeInfo, v8Value);
}
v8::Local<v8::Object> V8TrackEvent::findInstanceInPrototypeChain(v8::Local<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->findInstanceInPrototypeChain(&wrapperTypeInfo, v8Value);
}
TrackEvent* V8TrackEvent::toImplWithTypeCheck(v8::Isolate* isolate, v8::Local<v8::Value> value)
{
return hasInstance(value, isolate) ? toImpl(v8::Local<v8::Object>::Cast(value)) : 0;
}
void V8TrackEvent::refObject(ScriptWrappable* scriptWrappable)
{
#if !ENABLE(OILPAN)
scriptWrappable->toImpl<TrackEvent>()->ref();
#endif
}
void V8TrackEvent::derefObject(ScriptWrappable* scriptWrappable)
{
#if !ENABLE(OILPAN)
scriptWrappable->toImpl<TrackEvent>()->deref();
#endif
}
} // namespace blink
| 42.363095
| 515
| 0.739216
|
wenfeifei
|
107d7ec8a92c6a27de175150a6be5eda68ed18cc
| 797
|
cpp
|
C++
|
nowcoder/9799B.cpp
|
freedomDR/coding
|
310a68077de93ef445ccd2929e90ba9c22a9b8eb
|
[
"MIT"
] | null | null | null |
nowcoder/9799B.cpp
|
freedomDR/coding
|
310a68077de93ef445ccd2929e90ba9c22a9b8eb
|
[
"MIT"
] | null | null | null |
nowcoder/9799B.cpp
|
freedomDR/coding
|
310a68077de93ef445ccd2929e90ba9c22a9b8eb
|
[
"MIT"
] | null | null | null |
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
int n; cin >> n;
vector<vector<int> > arr(n, vector<int>());
for(int i = 0; i < n; i++)
{
int nums = 0; cin >> nums;
for(int j = 0; j < nums; j++)
{
int v; cin >> v; arr[i].push_back(v);
}
sort(arr[i].begin(), arr[i].end());
}
int q; cin >> q;
while(q--)
{
int l, r, k, p;
cin >> l >> r >> k >> p;
l--;r--;k--;
int f = arr[k][arr[k].size()-p];
int ans = 0;
for(int i = l; i <= r; i++)
{
auto ret = upper_bound(arr[i].begin(), arr[i].end(), f);
ans += distance(ret, arr[i].end());
}
cout << ans+1 << endl;
}
return 0;
}
| 22.771429
| 68
| 0.410289
|
freedomDR
|
107fa58a6b11c81278fd518782e586f36ea81e45
| 52,694
|
cpp
|
C++
|
XMPCore/source/XMPUtils-FileInfo.cpp
|
freedesktop-unofficial-mirror/exempi
|
2f6450de4e8e02003b8fb27ace5cf802571b761e
|
[
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | null | null | null |
XMPCore/source/XMPUtils-FileInfo.cpp
|
freedesktop-unofficial-mirror/exempi
|
2f6450de4e8e02003b8fb27ace5cf802571b761e
|
[
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | null | null | null |
XMPCore/source/XMPUtils-FileInfo.cpp
|
freedesktop-unofficial-mirror/exempi
|
2f6450de4e8e02003b8fb27ace5cf802571b761e
|
[
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | null | null | null |
// =================================================================================================
// Copyright 2003 Adobe Systems Incorporated
// All Rights Reserved.
//
// NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms
// of the Adobe license agreement accompanying it.
// =================================================================================================
#include "public/include/XMP_Environment.h" // ! This must be the first include!
#include "XMPCore/source/XMPCore_Impl.hpp"
#include "XMPCore/source/XMPUtils.hpp"
#include <algorithm> // For binary_search.
#include <time.h>
#include <string.h>
#include <stdlib.h>
#include <locale.h>
#include <errno.h>
#include <stdio.h> // For snprintf.
#if XMP_WinBuild
#pragma warning ( disable : 4800 ) // forcing value to bool 'true' or 'false' (performance warning)
#endif
// =================================================================================================
// Local Types and Constants
// =========================
typedef unsigned long UniCodePoint;
enum UniCharKind {
UCK_normal,
UCK_space,
UCK_comma,
UCK_semicolon,
UCK_quote,
UCK_control
};
typedef enum UniCharKind UniCharKind;
#define UnsByte(c) ((unsigned char)(c))
#define UCP(u) ((UniCodePoint)(u))
// ! Needed on Windows (& PC Linux?) for inequalities with literals ito avoid sign extension.
#ifndef TraceMultiFile
#define TraceMultiFile 0
#endif
// =================================================================================================
// Static Variables
// ================
// =================================================================================================
// Local Utilities
// ===============
// -------------------------------------------------------------------------------------------------
// ClassifyCharacter
// -----------------
static void
ClassifyCharacter ( XMP_StringPtr fullString, size_t offset,
UniCharKind * charKind, size_t * charSize, UniCodePoint * uniChar )
{
*charKind = UCK_normal; // Assume typical case.
unsigned char currByte = UnsByte ( fullString[offset] );
if ( currByte < UnsByte(0x80) ) {
// ----------------------------------------
// We've got a single byte ASCII character.
*charSize = 1;
*uniChar = currByte;
if ( currByte > UnsByte(0x22) ) {
if ( currByte == UnsByte(0x2C) ) {
*charKind = UCK_comma;
} else if ( currByte == UnsByte(0x3B) ) {
*charKind = UCK_semicolon;
}
// [2674672] Discontinue to interpret square brackets
// as Asian quotes in XMPUtils::SeparateArrayItems(..))
// *** else if ( (currByte == UnsByte(0x5B)) || (currByte == UnsByte(0x5D)) ) {
// *** *charKind = UCK_quote; // ! ASCII '[' and ']' are used as quotes in Chinese and Korean.
// *** }
} else { // currByte <= 0x22
if ( currByte == UnsByte(0x22) ) {
*charKind = UCK_quote;
} else if ( currByte == UnsByte(0x21) ) {
*charKind = UCK_normal;
} else if ( currByte == UnsByte(0x20) ) {
*charKind = UCK_space;
} else {
*charKind = UCK_control;
}
}
} else { // currByte >= 0x80
// ---------------------------------------------------------------------------------------
// We've got a multibyte Unicode character. The first byte has the number of bytes and the
// highest order bits. The other bytes each add 6 more bits. Compose the UTF-32 form so we
// can classify directly with the Unicode code points. Order the upperBits tests to be
// fastest for Japan, probably the most common non-ASCII usage.
*charSize = 0;
*uniChar = currByte;
while ( (*uniChar & 0x80) != 0 ) { // Count the leading 1 bits in the byte.
++(*charSize);
*uniChar = *uniChar << 1;
}
XMP_Assert ( (offset + *charSize) <= strlen(fullString) );
*uniChar = *uniChar & 0x7F; // Put the character bits in the bottom of uniChar.
*uniChar = *uniChar >> *charSize;
for ( size_t i = (offset + 1); i < (offset + *charSize); ++i ) {
*uniChar = (*uniChar << 6) | (UnsByte(fullString[i]) & 0x3F);
}
XMP_Uns32 upperBits = *uniChar >> 8; // First filter on just the high order 24 bits.
if ( upperBits == 0xFF ) { // U+FFxx
if ( *uniChar == UCP(0xFF0C) ) {
*charKind = UCK_comma; // U+FF0C, full width comma.
} else if ( *uniChar == UCP(0xFF1B) ) {
*charKind = UCK_semicolon; // U+FF1B, full width semicolon.
} else if ( *uniChar == UCP(0xFF64) ) {
*charKind = UCK_comma; // U+FF64, half width ideographic comma.
}
} else if ( upperBits == 0xFE ) { // U+FE--
if ( *uniChar == UCP(0xFE50) ) {
*charKind = UCK_comma; // U+FE50, small comma.
} else if ( *uniChar == UCP(0xFE51) ) {
*charKind = UCK_comma; // U+FE51, small ideographic comma.
} else if ( *uniChar == UCP(0xFE54) ) {
*charKind = UCK_semicolon; // U+FE54, small semicolon.
}
} else if ( upperBits == 0x30 ) { // U+30--
if ( *uniChar == UCP(0x3000) ) {
*charKind = UCK_space; // U+3000, ideographic space.
} else if ( *uniChar == UCP(0x3001) ) {
*charKind = UCK_comma; // U+3001, ideographic comma.
} else if ( (UCP(0x3008) <= *uniChar) && (*uniChar <= UCP(0x300F)) ) {
*charKind = UCK_quote; // U+3008..U+300F, various quotes.
} else if ( *uniChar == UCP(0x303F) ) {
*charKind = UCK_space; // U+303F, ideographic half fill space.
} else if ( (UCP(0x301D) <= *uniChar) && (*uniChar <= UCP(0x301F)) ) {
*charKind = UCK_quote; // U+301D..U+301F, double prime quotes.
}
} else if ( upperBits == 0x20 ) { // U+20--
if ( (UCP(0x2000) <= *uniChar) && (*uniChar <= UCP(0x200B)) ) {
*charKind = UCK_space; // U+2000..U+200B, en quad through zero width space.
} else if ( *uniChar == UCP(0x2015) ) {
*charKind = UCK_quote; // U+2015, dash quote.
} else if ( (UCP(0x2018) <= *uniChar) && (*uniChar <= UCP(0x201F)) ) {
*charKind = UCK_quote; // U+2018..U+201F, various quotes.
} else if ( *uniChar == UCP(0x2028) ) {
*charKind = UCK_control; // U+2028, line separator.
} else if ( *uniChar == UCP(0x2029) ) {
*charKind = UCK_control; // U+2029, paragraph separator.
} else if ( (*uniChar == UCP(0x2039)) || (*uniChar == UCP(0x203A)) ) {
*charKind = UCK_quote; // U+2039 and U+203A, guillemet quotes.
}
} else if ( upperBits == 0x06 ) { // U+06--
if ( *uniChar == UCP(0x060C) ) {
*charKind = UCK_comma; // U+060C, Arabic comma.
} else if ( *uniChar == UCP(0x061B) ) {
*charKind = UCK_semicolon; // U+061B, Arabic semicolon.
}
} else if ( upperBits == 0x05 ) { // U+05--
if ( *uniChar == UCP(0x055D) ) {
*charKind = UCK_comma; // U+055D, Armenian comma.
}
} else if ( upperBits == 0x03 ) { // U+03--
if ( *uniChar == UCP(0x037E) ) {
*charKind = UCK_semicolon; // U+037E, Greek "semicolon" (really a question mark).
}
} else if ( upperBits == 0x00 ) { // U+00--
if ( (*uniChar == UCP(0x00AB)) || (*uniChar == UCP(0x00BB)) ) {
*charKind = UCK_quote; // U+00AB and U+00BB, guillemet quotes.
}
}
}
} // ClassifyCharacter
// -------------------------------------------------------------------------------------------------
// IsClosingingQuote
// -----------------
static inline bool
IsClosingingQuote ( UniCodePoint uniChar, UniCodePoint openQuote, UniCodePoint closeQuote )
{
if ( (uniChar == closeQuote) ||
( (openQuote == UCP(0x301D)) && ((uniChar == UCP(0x301E)) || (uniChar == UCP(0x301F))) ) ) {
return true;
} else {
return false;
}
} // IsClosingingQuote
// -------------------------------------------------------------------------------------------------
// IsSurroundingQuote
// ------------------
static inline bool
IsSurroundingQuote ( UniCodePoint uniChar, UniCodePoint openQuote, UniCodePoint closeQuote )
{
if ( (uniChar == openQuote) || IsClosingingQuote ( uniChar, openQuote, closeQuote ) ) {
return true;
} else {
return false;
}
} // IsSurroundingQuote
// -------------------------------------------------------------------------------------------------
// GetClosingQuote
// ---------------
static UniCodePoint
GetClosingQuote ( UniCodePoint openQuote )
{
UniCodePoint closeQuote;
switch ( openQuote ) {
case UCP(0x0022) : closeQuote = UCP(0x0022); // ! U+0022 is both opening and closing.
break;
// *** [2674672] Discontinue to interpret square brackets
// *** as Asian quotes in XMPUtils::SeparateArrayItems(..))
// *** case UCP(0x005B) : closeQuote = UCP(0x005D);
// *** break;
case UCP(0x00AB) : closeQuote = UCP(0x00BB); // ! U+00AB and U+00BB are reversible.
break;
case UCP(0x00BB) : closeQuote = UCP(0x00AB);
break;
case UCP(0x2015) : closeQuote = UCP(0x2015); // ! U+2015 is both opening and closing.
break;
case UCP(0x2018) : closeQuote = UCP(0x2019);
break;
case UCP(0x201A) : closeQuote = UCP(0x201B);
break;
case UCP(0x201C) : closeQuote = UCP(0x201D);
break;
case UCP(0x201E) : closeQuote = UCP(0x201F);
break;
case UCP(0x2039) : closeQuote = UCP(0x203A); // ! U+2039 and U+203A are reversible.
break;
case UCP(0x203A) : closeQuote = UCP(0x2039);
break;
case UCP(0x3008) : closeQuote = UCP(0x3009);
break;
case UCP(0x300A) : closeQuote = UCP(0x300B);
break;
case UCP(0x300C) : closeQuote = UCP(0x300D);
break;
case UCP(0x300E) : closeQuote = UCP(0x300F);
break;
case UCP(0x301D) : closeQuote = UCP(0x301F); // ! U+301E also closes U+301D.
break;
default : closeQuote = 0;
break;
}
return closeQuote;
} // GetClosingQuote
// -------------------------------------------------------------------------------------------------
// CodePointToUTF8
// ---------------
static void
CodePointToUTF8 ( UniCodePoint uniChar, XMP_VarString & utf8Str )
{
size_t i, byteCount;
XMP_Uns8 buffer [8];
UniCodePoint cpTemp;
if ( uniChar <= 0x7F ) {
i = 7;
byteCount = 1;
buffer[7] = char(uniChar);
} else {
// ---------------------------------------------------------------------------------------
// Copy the data bits from the low order end to the high order end, include the 0x80 mask.
i = 8;
cpTemp = uniChar;
while ( cpTemp != 0 ) {
-- i; // Exit with i pointing to the last byte stored.
buffer[i] = UnsByte(0x80) | (UnsByte(cpTemp) & 0x3F);
cpTemp = cpTemp >> 6;
}
byteCount = 8 - i; // The total number of bytes needed.
XMP_Assert ( (2 <= byteCount) && (byteCount <= 6) );
// -------------------------------------------------------------------------------------
// Make sure the high order byte can hold the byte count mask, compute and set the mask.
size_t bitCount = 0; // The number of data bits in the first byte.
for ( cpTemp = (buffer[i] & UnsByte(0x3F)); cpTemp != 0; cpTemp = cpTemp >> 1 ) bitCount += 1;
if ( bitCount > (8 - (byteCount + 1)) ) byteCount += 1;
i = 8 - byteCount; // First byte index and mask shift count.
XMP_Assert ( (0 <= i) && (i <= 6) );
buffer[i] |= (UnsByte(0xFF) << i) & UnsByte(0xFF); // AUDIT: Safe, i is between 0 and 6.
}
utf8Str.assign ( (char*)(&buffer[i]), byteCount );
} // CodePointToUTF8
// -------------------------------------------------------------------------------------------------
// ApplyQuotes
// -----------
static void
ApplyQuotes ( XMP_VarString * item, UniCodePoint openQuote, UniCodePoint closeQuote, bool allowCommas )
{
bool prevSpace = false;
size_t charOffset, charLen;
UniCharKind charKind;
UniCodePoint uniChar;
// -----------------------------------------------------------------------------------------
// See if there are any separators in the value. Stop at the first occurrance. This is a bit
// tricky in order to make typical typing work conveniently. The purpose of applying quotes
// is to preserve the values when splitting them back apart. That is CatenateContainerItems
// and SeparateContainerItems must round trip properly. For the most part we only look for
// separators here. Internal quotes, as in -- Irving "Bud" Jones -- won't cause problems in
// the separation. An initial quote will though, it will make the value look quoted.
charOffset = 0;
ClassifyCharacter ( item->c_str(), charOffset, &charKind, &charLen, &uniChar );
if ( charKind != UCK_quote ) {
for ( charOffset = 0; size_t(charOffset) < item->size(); charOffset += charLen ) {
ClassifyCharacter ( item->c_str(), charOffset, &charKind, &charLen, &uniChar );
if ( charKind == UCK_space ) {
if ( prevSpace ) break; // Multiple spaces are a separator.
prevSpace = true;
} else {
prevSpace = false;
if ( (charKind == UCK_semicolon) || (charKind == UCK_control) ) break;
if ( (charKind == UCK_comma) && (! allowCommas) ) break;
}
}
}
if ( size_t(charOffset) < item->size() ) {
// --------------------------------------------------------------------------------------
// Create a quoted copy, doubling any internal quotes that match the outer ones. Internal
// quotes did not stop the "needs quoting" search, but they do need doubling. So we have
// to rescan the front of the string for quotes. Handle the special case of U+301D being
// closed by either U+301E or U+301F.
XMP_VarString newItem;
size_t splitPoint;
for ( splitPoint = 0; splitPoint <= charOffset; ++splitPoint ) {
ClassifyCharacter ( item->c_str(), splitPoint, &charKind, &charLen, &uniChar );
if ( charKind == UCK_quote ) break;
}
CodePointToUTF8 ( openQuote, newItem );
newItem.append ( *item, 0, splitPoint ); // Copy the leading "normal" portion.
for ( charOffset = splitPoint; size_t(charOffset) < item->size(); charOffset += charLen ) {
ClassifyCharacter ( item->c_str(), charOffset, &charKind, &charLen, &uniChar );
newItem.append ( *item, charOffset, charLen );
if ( (charKind == UCK_quote) && IsSurroundingQuote ( uniChar, openQuote, closeQuote ) ) {
newItem.append ( *item, charOffset, charLen );
}
}
XMP_VarString closeStr;
CodePointToUTF8 ( closeQuote, closeStr );
newItem.append ( closeStr );
*item = newItem;
}
} // ApplyQuotes
// -------------------------------------------------------------------------------------------------
// IsInternalProperty
// ------------------
// *** Need static checks of the schema prefixes!
static const char * kExternalxmpDM[] =
{ "xmpDM:album",
"xmpDM:altTapeName",
"xmpDM:altTimecode",
"xmpDM:artist",
"xmpDM:cameraAngle",
"xmpDM:cameraLabel",
"xmpDM:cameraModel",
"xmpDM:cameraMove",
"xmpDM:client",
"xmpDM:comment",
"xmpDM:composer",
"xmpDM:director",
"xmpDM:directorPhotography",
"xmpDM:engineer",
"xmpDM:genre",
"xmpDM:good",
"xmpDM:instrument",
"xmpDM:logComment",
"xmpDM:projectName",
"xmpDM:releaseDate",
"xmpDM:scene",
"xmpDM:shotDate",
"xmpDM:shotDay",
"xmpDM:shotLocation",
"xmpDM:shotName",
"xmpDM:shotNumber",
"xmpDM:shotSize",
"xmpDM:speakerPlacement",
"xmpDM:takeNumber",
"xmpDM:tapeName",
"xmpDM:trackNumber",
"xmpDM:videoAlphaMode",
"xmpDM:videoAlphaPremultipleColor",
0 }; // ! Must have zero sentinel!
typedef const char ** CharStarIterator; // Used for binary search of kExternalxmpDM;
static const char ** kLastExternalxmpDM = 0; // Set on first use.
static int CharStarLess (const char * left, const char * right )
{ return (strcmp ( left, right ) < 0); }
#define IsExternalProperty(s,p) (! IsInternalProperty ( s, p ))
static bool
IsInternalProperty ( const XMP_VarString & schema, const XMP_VarString & prop )
{
bool isInternal = false;
if ( schema == kXMP_NS_DC ) {
if ( (prop == "dc:format") ||
(prop == "dc:language") ) {
isInternal = true;
}
} else if ( schema == kXMP_NS_XMP ) {
if ( (prop == "xmp:BaseURL") ||
(prop == "xmp:CreatorTool") ||
(prop == "xmp:Format") ||
(prop == "xmp:Locale") ||
(prop == "xmp:MetadataDate") ||
(prop == "xmp:ModifyDate") ) {
isInternal = true;
}
} else if ( schema == kXMP_NS_PDF ) {
if ( (prop == "pdf:BaseURL") ||
(prop == "pdf:Creator") ||
(prop == "pdf:ModDate") ||
(prop == "pdf:PDFVersion") ||
(prop == "pdf:Producer") ) {
isInternal = true;
}
} else if ( schema == kXMP_NS_TIFF ) {
isInternal = true; // ! The TIFF properties are internal by default.
if ( (prop == "tiff:ImageDescription") || // ! ImageDescription, Artist, and Copyright are aliased.
(prop == "tiff:Artist") ||
(prop == "tiff:Copyright") ) {
isInternal = false;
}
} else if ( schema == kXMP_NS_EXIF ) {
isInternal = true; // ! The EXIF properties are internal by default.
if ( prop == "exif:UserComment" ) isInternal = false;
} else if ( schema == kXMP_NS_EXIF_Aux ) {
isInternal = true; // ! The EXIF Aux properties are internal by default.
} else if ( schema == kXMP_NS_Photoshop ) {
if ( (prop == "photoshop:ICCProfile") ||
(prop == "photoshop:TextLayers") ) isInternal = true;
} else if ( schema == kXMP_NS_CameraRaw ) {
isInternal = true; // All of crs: is internal, they are processing settings.
} else if ( schema == kXMP_NS_DM ) {
// ! Most of the xmpDM schema is internal, and unknown properties default to internal.
if ( kLastExternalxmpDM == 0 ) {
for ( kLastExternalxmpDM = &kExternalxmpDM[0]; *kLastExternalxmpDM != 0; ++kLastExternalxmpDM ) {}
}
isInternal = (! std::binary_search ( &kExternalxmpDM[0], kLastExternalxmpDM, prop.c_str(), CharStarLess ));
} else if ( schema == kXMP_NS_Script ) {
isInternal = true; // ! Most of the xmpScript schema is internal, and unknown properties default to internal.
if ( (prop == "xmpScript:action") || (prop == "xmpScript:character") || (prop == "xmpScript:dialog") ||
(prop == "xmpScript:sceneSetting") || (prop == "xmpScript:sceneTimeOfDay") ) {
isInternal = false;
}
} else if ( schema == kXMP_NS_BWF ) {
if ( prop == "bext:version" ) isInternal = true;
} else if ( schema == kXMP_NS_AdobeStockPhoto ) {
isInternal = true; // ! The bmsp schema has only internal properties.
} else if ( schema == kXMP_NS_XMP_MM ) {
isInternal = true; // ! The xmpMM schema has only internal properties.
} else if ( schema == kXMP_NS_XMP_Text ) {
isInternal = true; // ! The xmpT schema has only internal properties.
} else if ( schema == kXMP_NS_XMP_PagedFile ) {
isInternal = true; // ! The xmpTPg schema has only internal properties.
} else if ( schema == kXMP_NS_XMP_Graphics ) {
isInternal = true; // ! The xmpG schema has only internal properties.
} else if ( schema == kXMP_NS_XMP_Image ) {
isInternal = true; // ! The xmpGImg schema has only internal properties.
} else if ( schema == kXMP_NS_XMP_Font ) {
isInternal = true; // ! The stFNT schema has only internal properties.
}
return isInternal;
} // IsInternalProperty
// -------------------------------------------------------------------------------------------------
// RemoveSchemaChildren
// --------------------
static void
RemoveSchemaChildren ( XMP_NodePtrPos schemaPos, bool doAll )
{
XMP_Node * schemaNode = *schemaPos;
XMP_Assert ( XMP_NodeIsSchema ( schemaNode->options ) );
// ! Iterate backwards to reduce shuffling as children are erased and to simplify the logic for
// ! denoting the current child. (Erasing child n makes the old n+1 now be n.)
size_t propCount = schemaNode->children.size();
XMP_NodePtrPos beginPos = schemaNode->children.begin();
for ( size_t propNum = propCount-1, propLim = (size_t)(-1); propNum != propLim; --propNum ) {
XMP_NodePtrPos currProp = beginPos + propNum;
if ( doAll || IsExternalProperty ( schemaNode->name, (*currProp)->name ) ) {
delete *currProp; // ! Both delete the node and erase the pointer from the parent.
schemaNode->children.erase ( currProp );
}
}
if ( schemaNode->children.empty() ) {
XMP_Node * tree = schemaNode->parent;
tree->children.erase ( schemaPos );
delete schemaNode;
}
} // RemoveSchemaChildren
// -------------------------------------------------------------------------------------------------
// ItemValuesMatch
// ---------------
//
// Does the value comparisons for array merging as part of XMPUtils::AppendProperties.
static bool
ItemValuesMatch ( const XMP_Node * leftNode, const XMP_Node * rightNode )
{
const XMP_OptionBits leftForm = leftNode->options & kXMP_PropCompositeMask;
const XMP_OptionBits rightForm = leftNode->options & kXMP_PropCompositeMask;
if ( leftForm != rightForm ) return false;
if ( leftForm == 0 ) {
// Simple nodes, check the values and xml:lang qualifiers.
if ( leftNode->value != rightNode->value ) return false;
if ( (leftNode->options & kXMP_PropHasLang) != (rightNode->options & kXMP_PropHasLang) ) return false;
if ( leftNode->options & kXMP_PropHasLang ) {
if ( leftNode->qualifiers[0]->value != rightNode->qualifiers[0]->value ) return false;
}
} else if ( leftForm == kXMP_PropValueIsStruct ) {
// Struct nodes, see if all fields match, ignoring order.
if ( leftNode->children.size() != rightNode->children.size() ) return false;
for ( size_t leftNum = 0, leftLim = leftNode->children.size(); leftNum != leftLim; ++leftNum ) {
const XMP_Node * leftField = leftNode->children[leftNum];
const XMP_Node * rightField = FindConstChild ( rightNode, leftField->name.c_str() );
if ( (rightField == 0) || (! ItemValuesMatch ( leftField, rightField )) ) return false;
}
} else {
// Array nodes, see if the "leftNode" values are present in the "rightNode", ignoring order, duplicates,
// and extra values in the rightNode-> The rightNode is the destination for AppendProperties.
XMP_Assert ( leftForm & kXMP_PropValueIsArray );
for ( size_t leftNum = 0, leftLim = leftNode->children.size(); leftNum != leftLim; ++leftNum ) {
const XMP_Node * leftItem = leftNode->children[leftNum];
size_t rightNum, rightLim;
for ( rightNum = 0, rightLim = rightNode->children.size(); rightNum != rightLim; ++rightNum ) {
const XMP_Node * rightItem = rightNode->children[rightNum];
if ( ItemValuesMatch ( leftItem, rightItem ) ) break;
}
if ( rightNum == rightLim ) return false;
}
}
return true; // All of the checks passed.
} // ItemValuesMatch
// -------------------------------------------------------------------------------------------------
// AppendSubtree
// -------------
//
// The main implementation of XMPUtils::AppendProperties. See the description in TXMPMeta.hpp.
static void
AppendSubtree ( const XMP_Node * sourceNode, XMP_Node * destParent,
const bool mergeCompound, const bool replaceOld, const bool deleteEmpty )
{
XMP_NodePtrPos destPos;
XMP_Node * destNode = FindChildNode ( destParent, sourceNode->name.c_str(), kXMP_ExistingOnly, &destPos );
bool valueIsEmpty = false;
if ( XMP_PropIsSimple ( sourceNode->options ) ) {
valueIsEmpty = sourceNode->value.empty();
} else {
valueIsEmpty = sourceNode->children.empty();
}
if ( valueIsEmpty ) {
if ( deleteEmpty && (destNode != 0) ) {
delete ( destNode );
destParent->children.erase ( destPos );
}
return; // ! Done, empty values are either ignored or cause deletions.
}
if ( destNode == 0 ) {
// The one easy case, the destination does not exist.
destNode = CloneSubtree ( sourceNode, destParent, true /* skipEmpty */ );
XMP_Assert ( (destNode == 0) || (! destNode->value.empty()) || (! destNode->children.empty()) );
return;
}
// If we get here we're going to modify an existing property, either replacing or merging.
XMP_Assert ( (! valueIsEmpty) && (destNode != 0) );
XMP_OptionBits sourceForm = sourceNode->options & kXMP_PropCompositeMask;
XMP_OptionBits destForm = destNode->options & kXMP_PropCompositeMask;
bool replaceThis = replaceOld; // ! Don't modify replaceOld, it gets passed to inner calls.
if ( mergeCompound && (! XMP_PropIsSimple ( sourceForm )) ) replaceThis = false;
if ( replaceThis ) {
destNode->value = sourceNode->value; // *** Should use SetNode.
destNode->options = sourceNode->options;
destNode->RemoveChildren();
destNode->RemoveQualifiers();
CloneOffspring ( sourceNode, destNode, true /* skipEmpty */ );
if ( (! XMP_PropIsSimple ( destNode->options )) && destNode->children.empty() ) {
// Don't keep an empty array or struct. The source might be implicitly empty due to
// all children being empty. In this case CloneOffspring should skip them.
DeleteSubtree ( destPos );
}
return;
}
// From here on are cases for merging arrays or structs.
if ( XMP_PropIsSimple ( sourceForm ) || (sourceForm != destForm) ) return;
if ( sourceForm == kXMP_PropValueIsStruct ) {
// To merge a struct process the fields recursively. E.g. add simple missing fields. The
// recursive call to AppendSubtree will handle deletion for fields with empty values.
for ( size_t sourceNum = 0, sourceLim = sourceNode->children.size(); sourceNum != sourceLim && destNode!= NULL; ++sourceNum ) {
const XMP_Node * sourceField = sourceNode->children[sourceNum];
AppendSubtree ( sourceField, destNode, mergeCompound, replaceOld, deleteEmpty );
if ( deleteEmpty && destNode->children.empty() ) {
delete ( destNode );
destParent->children.erase ( destPos );
}
}
} else if ( sourceForm & kXMP_PropArrayIsAltText ) {
// Merge AltText arrays by the xml:lang qualifiers. Make sure x-default is first. Make a
// special check for deletion of empty values. Meaningful in AltText arrays because the
// xml:lang qualifier provides unambiguous source/dest correspondence.
XMP_Assert ( mergeCompound );
for ( size_t sourceNum = 0, sourceLim = sourceNode->children.size(); sourceNum != sourceLim && destNode!= NULL; ++sourceNum ) {
const XMP_Node * sourceItem = sourceNode->children[sourceNum];
if ( sourceItem->qualifiers.empty() || (sourceItem->qualifiers[0]->name != "xml:lang") ) continue;
XMP_Index destIndex = LookupLangItem ( destNode, sourceItem->qualifiers[0]->value );
if ( sourceItem->value.empty() ) {
if ( deleteEmpty && (destIndex != -1) ) {
delete ( destNode->children[destIndex] );
destNode->children.erase ( destNode->children.begin() + destIndex );
if ( destNode->children.empty() ) {
delete ( destNode );
destParent->children.erase ( destPos );
}
}
} else {
if ( destIndex != -1 ) {
// The source and dest arrays both have this language item.
if ( replaceOld ) { // ! Yes, check replaceOld not replaceThis!
destNode->children[destIndex]->value = sourceItem->value;
}
} else {
// The dest array does not have this language item, add it.
if ( (sourceItem->qualifiers[0]->value != "x-default") || destNode->children.empty() ) {
// Typical case, empty dest array or not "x-default". Non-empty should always have "x-default".
CloneSubtree ( sourceItem, destNode, true /* skipEmpty */ );
} else {
// Edge case, non-empty dest array had no "x-default", insert that at the beginning.
XMP_Node * destItem = new XMP_Node ( destNode, sourceItem->name, sourceItem->value, sourceItem->options );
CloneOffspring ( sourceItem, destItem, true /* skipEmpty */ );
destNode->children.insert ( destNode->children.begin(), destItem );
}
}
}
}
} else if ( sourceForm & kXMP_PropValueIsArray ) {
// Merge other arrays by item values. Don't worry about order or duplicates. Source
// items with empty values do not cause deletion, that conflicts horribly with merging.
for ( size_t sourceNum = 0, sourceLim = sourceNode->children.size(); sourceNum != sourceLim; ++sourceNum ) {
const XMP_Node * sourceItem = sourceNode->children[sourceNum];
size_t destNum, destLim;
for ( destNum = 0, destLim = destNode->children.size(); destNum != destLim; ++destNum ) {
const XMP_Node * destItem = destNode->children[destNum];
if ( ItemValuesMatch ( sourceItem, destItem ) ) break;
}
if ( destNum == destLim ) CloneSubtree ( sourceItem, destNode, true /* skipEmpty */ );
}
}
} // AppendSubtree
// =================================================================================================
// Class Static Functions
// ======================
// -------------------------------------------------------------------------------------------------
// CatenateArrayItems
// ------------------
/* class static */ void
XMPUtils::CatenateArrayItems ( const XMPMeta & xmpObj,
XMP_StringPtr schemaNS,
XMP_StringPtr arrayName,
XMP_StringPtr separator,
XMP_StringPtr quotes,
XMP_OptionBits options,
XMP_VarString * catedStr )
{
XMP_Assert ( (schemaNS != 0) && (arrayName != 0) ); // ! Enforced by wrapper.
XMP_Assert ( (separator != 0) && (quotes != 0) && (catedStr != 0) ); // ! Enforced by wrapper.
size_t strLen, strPos, charLen;
UniCharKind charKind;
UniCodePoint currUCP, openQuote, closeQuote;
const bool allowCommas = ((options & kXMPUtil_AllowCommas) != 0);
const XMP_Node * arrayNode = 0; // ! Move up to avoid gcc complaints.
XMP_OptionBits arrayForm = 0;
const XMP_Node * currItem = 0;
// Make sure the separator is OK. It must be one semicolon surrounded by zero or more spaces.
// Any of the recognized semicolons or spaces are allowed.
strPos = 0;
strLen = strlen ( separator );
bool haveSemicolon = false;
while ( strPos < strLen ) {
ClassifyCharacter ( separator, strPos, &charKind, &charLen, &currUCP );
strPos += charLen;
if ( charKind == UCK_semicolon ) {
if ( haveSemicolon ) XMP_Throw ( "Separator can have only one semicolon", kXMPErr_BadParam );
haveSemicolon = true;
} else if ( charKind != UCK_space ) {
XMP_Throw ( "Separator can have only spaces and one semicolon", kXMPErr_BadParam );
}
};
if ( ! haveSemicolon ) XMP_Throw ( "Separator must have one semicolon", kXMPErr_BadParam );
// Make sure the open and close quotes are a legitimate pair.
strLen = strlen ( quotes );
ClassifyCharacter ( quotes, 0, &charKind, &charLen, &openQuote );
if ( charKind != UCK_quote ) XMP_Throw ( "Invalid quoting character", kXMPErr_BadParam );
if ( charLen == strLen ) {
closeQuote = openQuote;
} else {
strPos = charLen;
ClassifyCharacter ( quotes, strPos, &charKind, &charLen, &closeQuote );
if ( charKind != UCK_quote ) XMP_Throw ( "Invalid quoting character", kXMPErr_BadParam );
if ( (strPos + charLen) != strLen ) XMP_Throw ( "Quoting string too long", kXMPErr_BadParam );
}
if ( closeQuote != GetClosingQuote ( openQuote ) ) XMP_Throw ( "Mismatched quote pair", kXMPErr_BadParam );
// Return an empty result if the array does not exist, hurl if it isn't the right form.
catedStr->erase();
XMP_ExpandedXPath arrayPath;
ExpandXPath ( schemaNS, arrayName, &arrayPath );
arrayNode = FindConstNode ( &xmpObj.tree, arrayPath );
if ( arrayNode == 0 ) return;
arrayForm = arrayNode->options & kXMP_PropCompositeMask;
if ( (! (arrayForm & kXMP_PropValueIsArray)) || (arrayForm & kXMP_PropArrayIsAlternate) ) {
XMP_Throw ( "Named property must be non-alternate array", kXMPErr_BadParam );
}
if ( arrayNode->children.empty() ) return;
// Build the result, quoting the array items, adding separators. Hurl if any item isn't simple.
// Start the result with the first value, then add the rest with a preceeding separator.
currItem = arrayNode->children[0];
if ( (currItem->options & kXMP_PropCompositeMask) != 0 ) XMP_Throw ( "Array items must be simple", kXMPErr_BadParam );
*catedStr = currItem->value;
ApplyQuotes ( catedStr, openQuote, closeQuote, allowCommas );
for ( size_t itemNum = 1, itemLim = arrayNode->children.size(); itemNum != itemLim; ++itemNum ) {
const XMP_Node * item = arrayNode->children[itemNum];
if ( (item->options & kXMP_PropCompositeMask) != 0 ) XMP_Throw ( "Array items must be simple", kXMPErr_BadParam );
XMP_VarString tempStr ( item->value );
ApplyQuotes ( &tempStr, openQuote, closeQuote, allowCommas );
*catedStr += separator;
*catedStr += tempStr;
}
} // CatenateArrayItems
// -------------------------------------------------------------------------------------------------
// SeparateArrayItems
// ------------------
/* class static */ void
XMPUtils::SeparateArrayItems ( XMPMeta * xmpObj,
XMP_StringPtr schemaNS,
XMP_StringPtr arrayName,
XMP_OptionBits options,
XMP_StringPtr catedStr )
{
XMP_Assert ( (schemaNS != 0) && (arrayName != 0) && (catedStr != 0) ); // ! Enforced by wrapper.
XMP_VarString itemValue;
size_t itemStart, itemEnd;
size_t nextSize, charSize = 0; // Avoid VS uninit var warnings.
UniCharKind nextKind, charKind = UCK_normal;
UniCodePoint nextChar, uniChar = 0;
// Extract "special" option bits, verify and normalize the others.
bool preserveCommas = false;
if ( options & kXMPUtil_AllowCommas ) {
preserveCommas = true;
options ^= kXMPUtil_AllowCommas;
}
options = VerifySetOptions ( options, 0 ); // Keep a zero value, has special meaning below.
if ( options & ~kXMP_PropArrayFormMask ) XMP_Throw ( "Options can only provide array form", kXMPErr_BadOptions );
// Find the array node, make sure it is OK. Move the current children aside, to be readded later if kept.
XMP_ExpandedXPath arrayPath;
ExpandXPath ( schemaNS, arrayName, &arrayPath );
XMP_Node * arrayNode = FindNode ( &xmpObj->tree, arrayPath, kXMP_ExistingOnly );
if ( arrayNode != 0 ) {
// The array exists, make sure the form is compatible. Zero arrayForm means take what exists.
XMP_OptionBits arrayForm = arrayNode->options & kXMP_PropArrayFormMask;
if ( (arrayForm == 0) || (arrayForm & kXMP_PropArrayIsAlternate) ) {
XMP_Throw ( "Named property must be non-alternate array", kXMPErr_BadXPath );
}
if ( (options != 0) && (options != arrayForm) ) XMP_Throw ( "Mismatch of specified and existing array form", kXMPErr_BadXPath ); // *** Right error?
} else {
// The array does not exist, try to create it.
arrayNode = FindNode ( &xmpObj->tree, arrayPath, kXMP_CreateNodes, (options | kXMP_PropValueIsArray) );
if ( arrayNode == 0 ) XMP_Throw ( "Failed to create named array", kXMPErr_BadXPath );
}
XMP_NodeOffspring oldChildren ( arrayNode->children );
size_t oldChildCount = oldChildren.size();
arrayNode->children.clear();
// Extract the item values one at a time, until the whole input string is done. Be very careful
// in the extraction about the string positions. They are essentially byte pointers, while the
// contents are UTF-8. Adding or subtracting 1 does not necessarily move 1 Unicode character!
size_t endPos = strlen ( catedStr );
itemEnd = 0;
while ( itemEnd < endPos ) {
// Skip any leading spaces and separation characters. Always skip commas here. They can be
// kept when within a value, but not when alone between values.
for ( itemStart = itemEnd; itemStart < endPos; itemStart += charSize ) {
ClassifyCharacter ( catedStr, itemStart, &charKind, &charSize, &uniChar );
if ( (charKind == UCK_normal) || (charKind == UCK_quote) ) break;
}
if ( itemStart >= endPos ) break;
if ( charKind != UCK_quote ) {
// This is not a quoted value. Scan for the end, create an array item from the substring.
for ( itemEnd = itemStart; itemEnd < endPos; itemEnd += charSize ) {
ClassifyCharacter ( catedStr, itemEnd, &charKind, &charSize, &uniChar );
if ( (charKind == UCK_normal) || (charKind == UCK_quote) ) continue;
if ( (charKind == UCK_comma) && preserveCommas ) continue;
if ( charKind != UCK_space ) break;
if ( (itemEnd + charSize) >= endPos ) break; // Anything left?
ClassifyCharacter ( catedStr, (itemEnd+charSize), &nextKind, &nextSize, &nextChar );
if ( (nextKind == UCK_normal) || (nextKind == UCK_quote) ) continue;
if ( (nextKind == UCK_comma) && preserveCommas ) continue;
break; // Have multiple spaces, or a space followed by a separator.
}
itemValue.assign ( catedStr, itemStart, (itemEnd - itemStart) );
} else {
// Accumulate quoted values into a local string, undoubling internal quotes that
// match the surrounding quotes. Do not undouble "unmatching" quotes.
UniCodePoint openQuote = uniChar;
UniCodePoint closeQuote = GetClosingQuote ( openQuote );
itemStart += charSize; // Skip the opening quote;
itemValue.erase();
for ( itemEnd = itemStart; itemEnd < endPos; itemEnd += charSize ) {
ClassifyCharacter ( catedStr, itemEnd, &charKind, &charSize, &uniChar );
if ( (charKind != UCK_quote) || (! IsSurroundingQuote ( uniChar, openQuote, closeQuote)) ) {
// This is not a matching quote, just append it to the item value.
itemValue.append ( catedStr, itemEnd, charSize );
} else {
// This is a "matching" quote. Is it doubled, or the final closing quote? Tolerate
// various edge cases like undoubled opening (non-closing) quotes, or end of input.
if ( (itemEnd + charSize) < endPos ) {
ClassifyCharacter ( catedStr, itemEnd+charSize, &nextKind, &nextSize, &nextChar );
} else {
nextKind = UCK_semicolon; nextSize = 0; nextChar = 0x3B;
}
if ( uniChar == nextChar ) {
// This is doubled, copy it and skip the double.
itemValue.append ( catedStr, itemEnd, charSize );
itemEnd += nextSize; // Loop will add in charSize.
} else if ( ! IsClosingingQuote ( uniChar, openQuote, closeQuote ) ) {
// This is an undoubled, non-closing quote, copy it.
itemValue.append ( catedStr, itemEnd, charSize );
} else {
// This is an undoubled closing quote, skip it and exit the loop.
itemEnd += charSize;
break;
}
}
} // Loop to accumulate the quoted value.
}
// Add the separated item to the array. Keep a matching old value in case it had separators.
size_t oldChild;
for ( oldChild = 0; oldChild < oldChildCount; ++oldChild ) {
if ( (oldChildren[oldChild] != 0) && (itemValue == oldChildren[oldChild]->value) ) break;
}
XMP_Node * newItem = 0;
if ( oldChild == oldChildCount ) {
newItem = new XMP_Node ( arrayNode, kXMP_ArrayItemName, itemValue.c_str(), 0 );
} else {
newItem = oldChildren[oldChild];
oldChildren[oldChild] = 0; // ! Don't match again, let duplicates be seen.
}
arrayNode->children.push_back ( newItem );
} // Loop through all of the returned items.
// Delete any of the old children that were not kept.
for ( size_t i = 0; i < oldChildCount; ++i ) {
if ( oldChildren[i] != 0 ) delete oldChildren[i];
}
} // SeparateArrayItems
// -------------------------------------------------------------------------------------------------
// ApplyTemplate
// -------------
/* class static */ void
XMPUtils::ApplyTemplate ( XMPMeta * workingXMP,
const XMPMeta & templateXMP,
XMP_OptionBits actions )
{
bool doClear = XMP_OptionIsSet ( actions, kXMPTemplate_ClearUnnamedProperties );
bool doAdd = XMP_OptionIsSet ( actions, kXMPTemplate_AddNewProperties );
bool doReplace = XMP_OptionIsSet ( actions, kXMPTemplate_ReplaceExistingProperties );
bool deleteEmpty = XMP_OptionIsSet ( actions, kXMPTemplate_ReplaceWithDeleteEmpty );
doReplace |= deleteEmpty; // Delete-empty implies Replace.
deleteEmpty &= (! doClear); // Clear implies not delete-empty, but keep the implicit Replace.
bool doAll = XMP_OptionIsSet ( actions, kXMPTemplate_IncludeInternalProperties );
// ! In several places we do loops backwards so that deletions do not perturb the remaining indices.
// ! These loops use ordinals (size .. 1), we must use a zero based index inside the loop.
if ( doClear ) {
// Visit the top level working properties, delete if not in the template.
for ( size_t schemaOrdinal = workingXMP->tree.children.size(); schemaOrdinal > 0; --schemaOrdinal ) {
size_t schemaNum = schemaOrdinal-1; // ! Convert ordinal to index!
XMP_Node * workingSchema = workingXMP->tree.children[schemaNum];
const XMP_Node * templateSchema = FindConstSchema ( &templateXMP.tree, workingSchema->name.c_str() );
if ( templateSchema == 0 ) {
// The schema is not in the template, delete all properties or just all external ones.
if ( doAll ) {
workingSchema->RemoveChildren(); // Remove the properties here, delete the schema below.
} else {
for ( size_t propOrdinal = workingSchema->children.size(); propOrdinal > 0; --propOrdinal ) {
size_t propNum = propOrdinal-1; // ! Convert ordinal to index!
XMP_Node * workingProp = workingSchema->children[propNum];
if ( IsExternalProperty ( workingSchema->name, workingProp->name ) ) {
delete ( workingProp );
workingSchema->children.erase ( workingSchema->children.begin() + propNum );
}
}
}
} else {
// Check each of the working XMP's properties to see if it is in the template.
for ( size_t propOrdinal = workingSchema->children.size(); propOrdinal > 0; --propOrdinal ) {
size_t propNum = propOrdinal-1; // ! Convert ordinal to index!
XMP_Node * workingProp = workingSchema->children[propNum];
if ( (doAll || IsExternalProperty ( workingSchema->name, workingProp->name )) &&
(FindConstChild ( templateSchema, workingProp->name.c_str() ) == 0) ) {
delete ( workingProp );
workingSchema->children.erase ( workingSchema->children.begin() + propNum );
}
}
}
if ( workingSchema->children.empty() ) {
delete ( workingSchema );
workingXMP->tree.children.erase ( workingXMP->tree.children.begin() + schemaNum );
}
}
}
if ( doAdd | doReplace ) {
for ( size_t schemaNum = 0, schemaLim = templateXMP.tree.children.size(); schemaNum < schemaLim; ++schemaNum ) {
const XMP_Node * templateSchema = templateXMP.tree.children[schemaNum];
// Make sure we have an output schema node, then process the top level template properties.
XMP_NodePtrPos workingSchemaPos;
XMP_Node * workingSchema = FindSchemaNode ( &workingXMP->tree, templateSchema->name.c_str(),
kXMP_ExistingOnly, &workingSchemaPos );
if ( workingSchema == 0 ) {
workingSchema = new XMP_Node ( &workingXMP->tree, templateSchema->name, templateSchema->value, kXMP_SchemaNode );
workingXMP->tree.children.push_back ( workingSchema );
workingSchemaPos = workingXMP->tree.children.end() - 1;
}
for ( size_t propNum = 0, propLim = templateSchema->children.size(); propNum < propLim; ++propNum ) {
const XMP_Node * templateProp = templateSchema->children[propNum];
if ( doAll || IsExternalProperty ( templateSchema->name, templateProp->name ) ) {
AppendSubtree ( templateProp, workingSchema, doAdd, doReplace, deleteEmpty );
}
}
if ( workingSchema->children.empty() ) {
delete ( workingSchema );
workingXMP->tree.children.erase ( workingSchemaPos );
}
}
}
} // ApplyTemplate
// -------------------------------------------------------------------------------------------------
// RemoveProperties
// ----------------
/* class static */ void
XMPUtils::RemoveProperties ( XMPMeta * xmpObj,
XMP_StringPtr schemaNS,
XMP_StringPtr propName,
XMP_OptionBits options )
{
XMP_Assert ( (schemaNS != 0) && (propName != 0) ); // ! Enforced by wrapper.
const bool doAll = XMP_TestOption (options, kXMPUtil_DoAllProperties );
const bool includeAliases = XMP_TestOption ( options, kXMPUtil_IncludeAliases );
if ( *propName != 0 ) {
// Remove just the one indicated property. This might be an alias, the named schema might
// not actually exist. So don't lookup the schema node.
if ( *schemaNS == 0 ) XMP_Throw ( "Property name requires schema namespace", kXMPErr_BadParam );
XMP_ExpandedXPath expPath;
ExpandXPath ( schemaNS, propName, &expPath );
XMP_NodePtrPos propPos;
XMP_Node * propNode = FindNode ( &(xmpObj->tree), expPath, kXMP_ExistingOnly, kXMP_NoOptions, &propPos );
if ( propNode != 0 ) {
if ( doAll || IsExternalProperty ( expPath[kSchemaStep].step, expPath[kRootPropStep].step ) ) {
XMP_Node * parent = propNode->parent; // *** Should have XMP_Node::RemoveChild(pos).
delete propNode; // ! Both delete the node and erase the pointer from the parent.
parent->children.erase ( propPos );
DeleteEmptySchema ( parent );
}
}
} else if ( *schemaNS != 0 ) {
// Remove all properties from the named schema. Optionally include aliases, in which case
// there might not be an actual schema node.
XMP_NodePtrPos schemaPos;
XMP_Node * schemaNode = FindSchemaNode ( &xmpObj->tree, schemaNS, kXMP_ExistingOnly, &schemaPos );
if ( schemaNode != 0 ) RemoveSchemaChildren ( schemaPos, doAll );
if ( includeAliases ) {
// We're removing the aliases also. Look them up by their namespace prefix. Yes, the
// alias map is sorted so we could process just that portion. But that takes more code
// and the extra speed isn't worth it. (Plus this way we avoid a dependence on the map
// implementation.) Lookup the XMP node from the alias, to make sure the actual exists.
XMP_StringPtr nsPrefix;
XMP_StringLen nsLen;
(void) XMPMeta::GetNamespacePrefix ( schemaNS, &nsPrefix, &nsLen );
XMP_AliasMapPos currAlias = sRegisteredAliasMap->begin();
XMP_AliasMapPos endAlias = sRegisteredAliasMap->end();
for ( ; currAlias != endAlias; ++currAlias ) {
if ( strncmp ( currAlias->first.c_str(), nsPrefix, nsLen ) == 0 ) {
XMP_NodePtrPos actualPos;
XMP_Node * actualProp = FindNode ( &xmpObj->tree, currAlias->second, kXMP_ExistingOnly, kXMP_NoOptions, &actualPos );
if ( actualProp != 0 ) {
XMP_Node * rootProp = actualProp;
while ( ! XMP_NodeIsSchema ( rootProp->parent->options ) ) rootProp = rootProp->parent;
if ( doAll || IsExternalProperty ( rootProp->parent->name, rootProp->name ) ) {
XMP_Node * parent = actualProp->parent;
delete actualProp; // ! Both delete the node and erase the pointer from the parent.
parent->children.erase ( actualPos );
DeleteEmptySchema ( parent );
}
}
}
}
}
} else {
// Remove all appropriate properties from all schema. In this case we don't have to be
// concerned with aliases, they are handled implicitly from the actual properties.
// ! Iterate backwards to reduce shuffling if schema are erased and to simplify the logic
// ! for denoting the current schema. (Erasing schema n makes the old n+1 now be n.)
size_t schemaCount = xmpObj->tree.children.size();
XMP_NodePtrPos beginPos = xmpObj->tree.children.begin();
for ( size_t schemaNum = schemaCount-1, schemaLim = (size_t)(-1); schemaNum != schemaLim; --schemaNum ) {
XMP_NodePtrPos currSchema = beginPos + schemaNum;
RemoveSchemaChildren ( currSchema, doAll );
}
}
} // RemoveProperties
// -------------------------------------------------------------------------------------------------
// DuplicateSubtree
// ----------------
/* class static */ void
XMPUtils::DuplicateSubtree ( const XMPMeta & source,
XMPMeta * dest,
XMP_StringPtr sourceNS,
XMP_StringPtr sourceRoot,
XMP_StringPtr destNS,
XMP_StringPtr destRoot,
XMP_OptionBits options )
{
IgnoreParam(options);
bool fullSourceTree = false;
bool fullDestTree = false;
XMP_ExpandedXPath sourcePath, destPath;
const XMP_Node * sourceNode = 0;
XMP_Node * destNode = 0;
XMP_Assert ( (sourceNS != 0) && (*sourceNS != 0) );
XMP_Assert ( (sourceRoot != 0) && (*sourceRoot != 0) );
XMP_Assert ( (dest != 0) && (destNS != 0) && (destRoot != 0) );
if ( *destNS == 0 ) destNS = sourceNS;
if ( *destRoot == 0 ) destRoot = sourceRoot;
if ( XMP_LitMatch ( sourceNS, "*" ) ) fullSourceTree = true;
if ( XMP_LitMatch ( destNS, "*" ) ) fullDestTree = true;
if ( (&source == dest) && (fullSourceTree | fullDestTree) ) {
XMP_Throw ( "Can't duplicate tree onto itself", kXMPErr_BadParam );
}
if ( fullSourceTree & fullDestTree ) XMP_Throw ( "Use Clone for full tree to full tree", kXMPErr_BadParam );
if ( fullSourceTree ) {
// The destination must be an existing empty struct, copy all of the source top level as fields.
ExpandXPath ( destNS, destRoot, &destPath );
destNode = FindNode ( &dest->tree, destPath, kXMP_ExistingOnly );
if ( (destNode == 0) || (! XMP_PropIsStruct ( destNode->options )) ) {
XMP_Throw ( "Destination must be an existing struct", kXMPErr_BadXPath );
}
if ( ! destNode->children.empty() ) {
if ( options & kXMP_DeleteExisting ) {
destNode->RemoveChildren();
} else {
XMP_Throw ( "Destination must be an empty struct", kXMPErr_BadXPath );
}
}
for ( size_t schemaNum = 0, schemaLim = source.tree.children.size(); schemaNum < schemaLim; ++schemaNum ) {
const XMP_Node * currSchema = source.tree.children[schemaNum];
for ( size_t propNum = 0, propLim = currSchema->children.size(); propNum < propLim; ++propNum ) {
sourceNode = currSchema->children[propNum];
XMP_Node * copyNode = new XMP_Node ( destNode, sourceNode->name, sourceNode->value, sourceNode->options );
destNode->children.push_back ( copyNode );
CloneOffspring ( sourceNode, copyNode );
}
}
} else if ( fullDestTree ) {
// The source node must be an existing struct, copy all of the fields to the dest top level.
XMP_ExpandedXPath srcPath;
ExpandXPath ( sourceNS, sourceRoot, &srcPath );
sourceNode = FindConstNode ( &source.tree, srcPath );
if ( (sourceNode == 0) || (! XMP_PropIsStruct ( sourceNode->options )) ) {
XMP_Throw ( "Source must be an existing struct", kXMPErr_BadXPath );
}
destNode = &dest->tree;
if ( ! destNode->children.empty() ) {
if ( options & kXMP_DeleteExisting ) {
destNode->RemoveChildren();
} else {
XMP_Throw ( "Destination tree must be empty", kXMPErr_BadXPath );
}
}
std::string nsPrefix;
XMP_StringPtr nsURI;
XMP_StringLen nsLen;
for ( size_t fieldNum = 0, fieldLim = sourceNode->children.size(); fieldNum < fieldLim; ++fieldNum ) {
const XMP_Node * currField = sourceNode->children[fieldNum];
size_t colonPos = currField->name.find ( ':' );
if ( colonPos == std::string::npos ) continue;
nsPrefix.assign ( currField->name.c_str(), colonPos );
bool nsOK = XMPMeta::GetNamespaceURI ( nsPrefix.c_str(), &nsURI, &nsLen );
if ( ! nsOK ) XMP_Throw ( "Source field namespace is not global", kXMPErr_BadSchema );
XMP_Node * destSchema = FindSchemaNode ( &dest->tree, nsURI, kXMP_CreateNodes );
if ( destSchema == 0 ) XMP_Throw ( "Failed to find destination schema", kXMPErr_BadSchema );
XMP_Node * copyNode = new XMP_Node ( destSchema, currField->name, currField->value, currField->options );
destSchema->children.push_back ( copyNode );
CloneOffspring ( currField, copyNode );
}
} else {
// Find the root nodes for the source and destination subtrees.
ExpandXPath ( sourceNS, sourceRoot, &sourcePath );
ExpandXPath ( destNS, destRoot, &destPath );
sourceNode = FindConstNode ( &source.tree, sourcePath );
if ( sourceNode == 0 ) XMP_Throw ( "Can't find source subtree", kXMPErr_BadXPath );
destNode = FindNode ( &dest->tree, destPath, kXMP_ExistingOnly ); // Dest must not yet exist.
if ( destNode != 0 ) XMP_Throw ( "Destination subtree must not exist", kXMPErr_BadXPath );
destNode = FindNode ( &dest->tree, destPath, kXMP_CreateNodes ); // Now create the dest.
if ( destNode == 0 ) XMP_Throw ( "Can't create destination root node", kXMPErr_BadXPath );
// Make sure the destination is not within the source! The source can't be inside the destination
// because the source already existed and the destination was just created.
if ( &source == dest ) {
for ( XMP_Node * testNode = destNode; testNode != 0; testNode = testNode->parent ) {
if ( testNode == sourceNode ) {
// *** delete the just-created dest root node
XMP_Throw ( "Destination subtree is within the source subtree", kXMPErr_BadXPath );
}
}
}
// *** Could use a CloneTree util here and maybe elsewhere.
destNode->value = sourceNode->value; // *** Should use SetNode.
destNode->options = sourceNode->options;
CloneOffspring ( sourceNode, destNode );
}
} // DuplicateSubtree
// =================================================================================================
| 35.270415
| 150
| 0.626978
|
freedesktop-unofficial-mirror
|
108070f6094b0b08212bb82111a07086e41f5b00
| 16,332
|
cc
|
C++
|
src/algorithms/RSAPI.cc
|
litlpoet/beliefbox
|
6b303e49017f8054f43c6c840686fcc632205e4e
|
[
"OLDAP-2.3"
] | null | null | null |
src/algorithms/RSAPI.cc
|
litlpoet/beliefbox
|
6b303e49017f8054f43c6c840686fcc632205e4e
|
[
"OLDAP-2.3"
] | null | null | null |
src/algorithms/RSAPI.cc
|
litlpoet/beliefbox
|
6b303e49017f8054f43c6c840686fcc632205e4e
|
[
"OLDAP-2.3"
] | null | null | null |
/* -*- Mode: C++; -*- */
// copyright (c) 2010 by Christos Dimitrakakis <christos.dimitrakakis@gmail.com>
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "RSAPI.h"
#include "GeometricDistribution.h"
#include "RandomNumberGenerator.h"
RolloutState::RolloutState(Environment<Vector, int>* environment_,
AbstractPolicy<Vector, int>* policy_,
Vector& start_state_, real gamma_)
: environment(environment_),
policy(policy_),
start_state(start_state_),
gamma(gamma_) {
V_U = 0;
V_L = 0;
V = 0;
U = INF;
}
RolloutState::~RolloutState() {
for (uint i = 0; i < rollouts.size(); ++i) {
delete rollouts[i];
}
}
Rollout<Vector, int, AbstractPolicy<Vector, int> >* RolloutState::NewRollout(
AbstractPolicy<Vector, int>* policy, int action) {
Rollout<Vector, int, AbstractPolicy<Vector, int> >* rollout =
new Rollout<Vector, int, AbstractPolicy<Vector, int> >(
start_state, action, policy, environment, gamma); // valgrind
rollouts.push_back(rollout);
return rollout;
}
/// Extend all rollouts by T
void RolloutState::ExtendAllRollouts(const int T) {
for (uint i = 0; i < rollouts.size(); ++i) {
// logmsg("performing %d-th rollout for state\n", i);
rollouts[i]->Sample(T);
}
}
/// Get the best empirical action in isolation
///
/// If no improved action is found, then it returns the normal action
int RolloutState::BestEmpiricalAction(real delta) {
Vector Q_U((int)environment->getNActions()); // Upper bound on Q
Vector Q_L((int)environment->getNActions()); // Lower bound on Q
Vector N(
(int)environment->getNActions()); // number of times action was played
Q_U += 1 / (1 - gamma);
real log_gamma = log(gamma);
for (uint i = 0; i < rollouts.size(); ++i) {
Rollout<Vector, int, AbstractPolicy<Vector, int> >* rollout = rollouts[i];
real error_bound = 0;
if (rollout->running) {
error_bound = exp(rollout->T * log_gamma);
}
int a = rollout->start_action;
N(a)++;
Q_U(a) += rollout->discounted_reward + error_bound;
Q_L(a) += rollout->discounted_reward - error_bound;
}
Q_U = Q_U / (N + 1); // normalise
Q_L = Q_L / (N + 1); // normalise
Vector confidence_interval =
pow(N + 1, (real)-0.5) * sqrt(0.5 * log(1.0 / delta));
Q_U += confidence_interval;
Q_L -= confidence_interval;
V_U = Max(Q_U);
V_L = Min(Q_L);
V = 0.5 * (V_U + V_L);
policy->setState(start_state);
int normal_action = policy->SelectAction();
start_action = normal_action;
// int optimistic_action = ArgMax(Q_U);
int pessimistic_action = ArgMax(Q_L);
real gap = (Q_L(pessimistic_action) - Q_U(normal_action));
#if 0
dbgmsg("CI: "); confidence_interval.print(stdout);
dbgmsg("QU: "); Q_U.print(stdout);
dbgmsg("QL: "); Q_L.print(stdout);
dbgmsg ("gap: %f, %f %f, a: %d->%d, s: ",
gap,
Q_U(pessimistic_action),
Q_U(normal_action),
normal_action,
pessimistic_action);
start_state.print(stdout);
#endif
if (gap > 0) {
return pessimistic_action;
} else {
return normal_action;
}
}
real RolloutState::Gap() {
Vector Q((int)environment->getNActions()); // Average Q
Vector N(
(int)environment->getNActions()); // number of times action was played
for (uint i = 0; i < rollouts.size(); ++i) {
Rollout<Vector, int, AbstractPolicy<Vector, int> >* rollout = rollouts[i];
int a = rollout->start_action;
N(a)++;
Q(a) += rollout->discounted_reward;
}
Q /= N; // normalise
real maxQ = Max(Q);
real Q2 = -1e-9;
for (uint i = 0; i < environment->getNActions(); ++i) {
if (Q(i) > Q2 && Q(i) < maxQ) {
Q2 = Q(i);
}
}
return maxQ - Q2;
}
/// Get the best empirical action in isolation
///
/// This actually returns no action if no improvement seems possible.
///
int RolloutState::BestHighProbabilityAction(real delta) {
Vector Q_U((int)environment->getNActions()); // Upper bound on Q
Vector Q_L((int)environment->getNActions()); // Lower bound on Q
Vector N(
(int)environment->getNActions()); // number of times action was played
real log_gamma = log(gamma);
for (uint i = 0; i < rollouts.size(); ++i) {
Rollout<Vector, int, AbstractPolicy<Vector, int> >* rollout = rollouts[i];
real error_bound = 0;
if (0) { // rollout->running) {
error_bound = exp(rollout->T * log_gamma);
}
int a = rollout->start_action;
N(a)++;
Q_U(a) += rollout->discounted_reward + error_bound;
Q_L(a) += rollout->discounted_reward - error_bound;
}
Q_U = Q_U / N; // normalise
Q_L = Q_L / N; // normalise
Vector confidence_interval =
pow(N, (real)-0.5) * sqrt(0.5 * log(1.0 / delta));
Q_U += confidence_interval;
Q_L -= confidence_interval;
V_U = Max(Q_U);
V_L = Min(Q_L);
V = 0.5 * (V_U + V_L);
policy->setState(start_state);
int normal_action = policy->SelectAction();
// int optimistic_action = ArgMax(Q_U);
int pessimistic_action = ArgMax(Q_L);
real gap = (Q_L(pessimistic_action) - Q_U(normal_action));
#if 0
printf ("# gap: %f, p:[%f %f] n:[%f %f] u:[%f %f]\n",
gap,
Q_L(pessimistic_action), Q_U(pessimistic_action),
Q_L(normal_action), Q_U(normal_action),
Q_L(optimistic_action), Q_U(optimistic_action));
#endif
if (gap > 0) {
// dbgmsg ("# gap: %f, a: %d->%d, s: ", gap, normal_action,
// pessimistic_action); start_state.print(stdout);
return pessimistic_action;
} else {
return -1;
}
}
/** Sample from the current policy.
This uses a gamma-discount sample from the current policy.
The idea is the following.
An infinite horizon problem with discount factor \f$\gamma\f$ is
equivalent to a finite horizon problem with a random horizon,
geometrically distributed, such that at any time \f$t > 0\f$, the
probability that the horizon \f$T = t\f$ is equal to \f$1 - \gamma\f$.
We can thus sample from that distribution easily.
*/
Vector RolloutState::SampleFromPolicy() {
GeometricDistribution horizon_distribution(1 - gamma);
int horizon_sample = horizon_distribution.generate();
policy->setState(start_state);
int normal_action = policy->SelectAction();
Rollout<Vector, int, AbstractPolicy<Vector, int> > rollout(
start_state, normal_action, policy, environment, gamma);
rollout.Sample(horizon_sample);
return rollout.end_state;
}
/// Group best and worst actions together.
///
/// Give 0 probability to any completely dominated action.
/// Other actions get a probability proportional to the number
/// of other actions they dominate.
std::pair<Vector, bool> RolloutState::BestGroupAction(real delta) {
Vector Q_U((int)environment->getNActions()); // Upper bound on Q
Vector Q_L((int)environment->getNActions()); // Lower bound on Q
Vector N(
(int)environment->getNActions()); // number of times action was played
real log_gamma = log(gamma);
for (uint i = 0; i < rollouts.size(); ++i) {
Rollout<Vector, int, AbstractPolicy<Vector, int> >* rollout = rollouts[i];
real error_bound = 0;
if (rollout->running) {
error_bound = exp(rollout->T * log_gamma);
// printf ("error bound not zero: %f\n", error_bound);
}
int a = rollout->start_action;
N(a)++;
Q_U(a) += rollout->discounted_reward + error_bound;
Q_L(a) += rollout->discounted_reward - error_bound;
}
Q_U = Q_U / N; // normalise
Q_L = Q_L / N; // normalise
Vector confidence_interval =
pow(N, (real)-0.5) * sqrt(0.5 * log(1.0 / delta));
Q_U += confidence_interval;
Q_L -= confidence_interval;
V_U = Max(Q_U);
V_L = Min(Q_L);
V = 0.5 * (V_U + V_L);
policy->setState(start_state);
std::pair<Vector, bool> retval;
Vector& Pr = retval.first;
Pr.Resize(environment->getNActions()); // Action probabilitie
bool& domination = retval.second;
domination = false;
for (uint i = 0; i < environment->getNActions(); ++i) {
Pr(i) = 0.5;
for (uint j = 0; j < environment->getNActions(); ++j) {
if (i == j) {
continue;
}
if (Q_U(i) <= Q_L(j)) {
Pr(i) = 0;
domination = true;
}
if (Q_L(i) >= Q_U(j)) {
Pr(i) += 1;
domination = true;
}
}
}
Pr /= Pr.Sum();
// printf("U: "); Q_U.print(stdout);
// printf("L: "); Q_L.print(stdout);
#if 0
if (domination) {
printf("# S: "); start_state.print(stdout);
printf("# P: "); Pr.print(stdout);
}
#endif
return retval;
}
/** Bootstrap from values of neighbouring states.
TODO This does not work at the moment.
*/
void RolloutState::Bootstrap(KDTree<RolloutState>& tree, real L) {
Vector Q_U((int)environment->getNActions()); // Upper bound on Q
Vector Q_L((int)environment->getNActions()); // Lower bound on Q
Vector N(
(int)environment->getNActions()); // number of times action was played
real log_gamma = log(gamma);
for (uint i = 0; i < rollouts.size(); ++i) {
Rollout<Vector, int, AbstractPolicy<Vector, int> >* rollout = rollouts[i];
real error_bound = 0;
if (rollout->running) {
error_bound = exp(rollout->T * log_gamma);
Vector s_T = rollout->end_state;
OrderedFixedList<KDNode> knn_list = tree.FindKNearestNeighbours(s_T, 3);
#if 0
std::list<std::pair<real, KDNode*> >::iterator knn_iter;
for (knn_iter = knn_list.S.begin();
knn_iter != knn_list.S.end();
++knn_iter) {
KDNode* node = knn_iter->second;
}
#endif
}
int a = rollout->start_action;
N(a)++;
Q_U(a) += rollout->discounted_reward + error_bound;
Q_L(a) += rollout->discounted_reward - error_bound;
}
Q_U = Q_U / N; // normalise
Q_L = Q_L / N; // normalise
Vector confidence_interval = pow(N, (real)-0.5);
Q_U += confidence_interval;
Q_L -= confidence_interval;
V_U = Max(Q_U);
V_L = Min(Q_L);
V = 0.5 * (V_U + V_L);
// Serror("Buggy!\n");
// exit(-1);
}
RSAPI::RSAPI(Environment<Vector, int>* environment_,
RandomNumberGenerator* rng_, real gamma_)
: environment(environment_), policy(NULL), rng(rng_), gamma(gamma_) {
// nothing to do here.
}
RSAPI::~RSAPI() {
for (uint i = 0; i < states.size(); ++i) {
delete states[i];
}
}
void RSAPI::AddState(Vector& state) {
states.push_back(new RolloutState(environment, policy, state, gamma));
}
/// Sample a new state
Vector RSAPI::SampleStateFromPolicy() const {
int k = rng->discrete_uniform(states.size());
return states[k]->SampleFromPolicy();
}
void RSAPI::SampleRandomly(const int T) {
RolloutState* state = states[rng->discrete_uniform(states.size())];
// logmsg("Randomly sampling state");
state->ExtendAllRollouts(T);
}
void RSAPI::NewRandomRollouts(const int K, const int T) {
for (int k = 0; k < K; ++k) {
RolloutState* state = states[rng->discrete_uniform(states.size())];
state->NewRollout(policy,
rng->discrete_uniform(environment->getNActions()));
state->ExtendAllRollouts(T);
}
}
/// Sample uniformly from all states
///
/// Take K rollouts from all state-action pairs, of length T
void RSAPI::SampleUniformly(const int K, const int T) {
for (uint i = 0; i < states.size(); ++i) {
RolloutState* state = states[i];
for (uint a = 0; a < environment->getNActions(); ++a) {
for (int k = 0; k < K; ++k) {
state->NewRollout(policy, a);
}
}
// logmsg("Sampling state %d\n", i);
state->ExtendAllRollouts(T);
}
}
/// Sample uniformly from all states till an error bound is met
///
/// Take K rollouts from all state-action pairs, of length T
void RSAPI::SampleToErrorBound(const int K, const int T, const real delta) {
int total_rollouts = states.size() * K;
int k = 0;
int n_sampled_states = 1;
int total_updates = 0;
std::vector<bool> state_ok(states.size());
for (uint i = 0; i < states.size(); ++i) {
state_ok[i] = false;
}
while (k < total_rollouts && n_sampled_states) {
n_sampled_states = 0;
for (uint i = 0; i < states.size(); ++i) {
if (state_ok[i]) {
continue;
}
RolloutState* state = states[i];
++n_sampled_states;
++k;
for (uint a = 0; a < environment->getNActions(); ++a) {
Rollout<Vector, int, AbstractPolicy<Vector, int> >* rollout =
state->NewRollout(policy, a);
rollout->Sample(T);
}
int a_max = state->BestHighProbabilityAction(delta);
if (a_max >= 0) {
state_ok[i] = true;
total_updates++;
}
}
}
// printf ("# n updates: %d\n", total_updates);
}
void RSAPI::SampleUpperBound(const int K, const int T, const real delta) {
int total_rollouts = states.size() * K;
int total_updates = 0;
Vector U((uint)states.size());
U += 1e9;
for (int k = 0; k < total_rollouts; ++k) {
uint i = ArgMax(U);
if (U(i) == 0) {
// logmsg("Early break from upper bound sampling\n");
break;
}
RolloutState* state = states[i];
++k;
for (uint a = 0; a < environment->getNActions(); ++a) {
Rollout<Vector, int, AbstractPolicy<Vector, int> >* rollout =
state->NewRollout(policy, a);
rollout->Sample(T);
}
int a_max = state->BestHighProbabilityAction(delta);
if (a_max >= 0) {
U(i) = 0;
total_updates++;
}
}
// printf ("# n updates: %d\n", total_updates);
}
/// Simply train the classifier
int RSAPI::TrainClassifier(Classifier<Vector, int, Vector>* classifier,
real delta) {
int n_improved_actions = 0;
for (uint i = 0; i < states.size(); ++i) {
int best_action = states[i]->BestEmpiricalAction(delta);
// int best_action = states[i]->BestHighProbabilityAction(delta);
if (best_action >= 0 && best_action != states[i]->start_action) {
// printf("# Action: %d state: ", best_action);
// states[i]->start_state.print(stdout);
n_improved_actions++;
}
if (best_action >= 0) {
classifier->Observe(states[i]->start_state, best_action);
}
}
return n_improved_actions;
}
real RSAPI::LipschitzBound() {
real L = 1e-3;
for (uint i = 0; i < states.size(); ++i) {
for (uint j = 0; j < states.size(); ++j) {
if (i == j) {
continue;
}
real D_U = states[i]->V_U - states[j]->V_U;
real D_L = states[i]->V_L - states[j]->V_L;
real D = std::max(D_U, D_L);
real s = EuclideanNorm(&states[i]->start_state, &states[j]->start_state);
if (s > 0) {
L = std::max(L, D / s);
}
}
}
return L;
}
void RSAPI::Bootstrap() {
/// Make a KNN tree.
KDTree<RolloutState> tree(environment->getNStates());
for (uint i = 0; i < states.size(); ++i) {
tree.AddVectorObject(states[i]->start_state, states[i]);
}
#if 0
for (uint i=0; i<states.size(); ++i) {
printf ("%f %f # state bounds\n", states[i]->V_U, states[i]->V_L);
}
#endif
real L = LipschitzBound();
for (uint i = 0; i < states.size(); ++i) {
states[i]->Bootstrap(tree, L);
}
#if 0
for (uint i=0; i<states.size(); ++i) {
printf ("%f %f # new state bounds\n", states[i]->V_U, states[i]->V_L);
}
#endif
}
/// Simply train the classifier with action groups
///
/// delta is the error probability that is deemed acceptable
int RSAPI::GroupTrainClassifier(Classifier<Vector, int, Vector>* classifier,
real delta) {
int n_improved_actions = 0;
for (uint i = 0; i < states.size(); ++i) {
std::pair<Vector, bool> retval = states[i]->BestGroupAction(delta);
if (retval.second) {
n_improved_actions++;
classifier->Observe(states[i]->start_state, retval.first);
}
}
return n_improved_actions;
}
| 31.712621
| 80
| 0.604274
|
litlpoet
|
10808f845b91b608644aec96cdbbfe9f9e0ebbc0
| 2,929
|
cpp
|
C++
|
implementations/bowtie2/presets.cpp
|
r-barnes/sw_comparison
|
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
|
[
"BSD-Source-Code"
] | null | null | null |
implementations/bowtie2/presets.cpp
|
r-barnes/sw_comparison
|
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
|
[
"BSD-Source-Code"
] | null | null | null |
implementations/bowtie2/presets.cpp
|
r-barnes/sw_comparison
|
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
|
[
"BSD-Source-Code"
] | null | null | null |
/*
* Copyright 2011, Ben Langmead <langmea@cs.jhu.edu>
*
* This file is part of Bowtie 2.
*
* Bowtie 2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Bowtie 2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Bowtie 2. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include "presets.h"
#include "opts.h"
using namespace std;
void PresetsV0::apply(
const std::string& preset,
std::string& policy,
EList<std::pair<int, std::string> >& opts)
{
// Presets: Same as:
// For --end-to-end:
// --very-fast -D 5 -R 1 -N 0 -L 22 -i S,0,2.50
// --fast -D 10 -R 2 -N 0 -L 22 -i S,0,2.50
// --sensitive -D 15 -R 2 -N 0 -L 22 -i S,1,1.15
// --very-sensitive -D 20 -R 3 -N 0 -L 20 -i S,1,0.50
if(preset == "very-fast") {
policy += ";SEED=0";
policy += ";SEEDLEN=22";
policy += ";DPS=5";
policy += ";ROUNDS=1";
policy += ";IVAL=S,0,2.50";
} else if(preset == "fast") {
policy += ";SEED=0";
policy += ";SEEDLEN=22";
policy += ";DPS=10";
policy += ";ROUNDS=2";
policy += ";IVAL=S,0,2.50";
} else if(preset == "sensitive") {
policy += ";SEED=0";
policy += ";SEEDLEN=22";
policy += ";DPS=15";
policy += ";ROUNDS=2";
policy += ";IVAL=S,1,1.15";
} else if(preset == "very-sensitive") {
policy += ";SEED=0";
policy += ";SEEDLEN=20";
policy += ";DPS=20";
policy += ";ROUNDS=3";
policy += ";IVAL=S,1,0.50";
}
// For --local:
// --very-fast-local -D 5 -R 1 -N 0 -L 25 -i S,1,2.00
// --fast-local -D 10 -R 2 -N 0 -L 22 -i S,1,1.75
// --sensitive-local -D 15 -R 2 -N 0 -L 20 -i S,1,0.75 (default)
// --very-sensitive-local -D 20 -R 3 -N 0 -L 20 -i S,1,0.50
else if(preset == "very-fast-local") {
policy += ";SEED=0";
policy += ";SEEDLEN=25";
policy += ";DPS=5";
policy += ";ROUNDS=1";
policy += ";IVAL=S,1,2.00";
} else if(preset == "fast-local") {
policy += ";SEED=0";
policy += ";SEEDLEN=22";
policy += ";DPS=10";
policy += ";ROUNDS=2";
policy += ";IVAL=S,1,1.75";
} else if(preset == "sensitive-local") {
policy += ";SEED=0";
policy += ";SEEDLEN=20";
policy += ";DPS=15";
policy += ";ROUNDS=2";
policy += ";IVAL=S,1,0.75";
} else if(preset == "very-sensitive-local") {
policy += ";SEED=0";
policy += ";SEEDLEN=20";
policy += ";DPS=20";
policy += ";ROUNDS=3";
policy += ";IVAL=S,1,0.50";
}
else {
cerr << "Unknown preset: " << preset.c_str() << endl;
}
}
| 30.510417
| 72
| 0.567771
|
r-barnes
|
10838fc9048120c9519b496bbca4dc7ae3f0560d
| 102,010
|
cpp
|
C++
|
external/vulkancts/modules/vulkan/spirv_assembly/vktSpvAsmCrossStageInterfaceTests.cpp
|
jingpad-bsp/android_external_deqp
|
50f948294cb12f5384633efc9327c571feb0fa21
|
[
"Apache-2.0"
] | 1
|
2021-02-25T09:06:00.000Z
|
2021-02-25T09:06:00.000Z
|
external/vulkancts/modules/vulkan/spirv_assembly/vktSpvAsmCrossStageInterfaceTests.cpp
|
jingpad-bsp/android_external_deqp
|
50f948294cb12f5384633efc9327c571feb0fa21
|
[
"Apache-2.0"
] | null | null | null |
external/vulkancts/modules/vulkan/spirv_assembly/vktSpvAsmCrossStageInterfaceTests.cpp
|
jingpad-bsp/android_external_deqp
|
50f948294cb12f5384633efc9327c571feb0fa21
|
[
"Apache-2.0"
] | null | null | null |
/*-------------------------------------------------------------------------
* Vulkan Conformance Tests
* ------------------------
*
* Copyright (c) 2017 Google 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.
*
*//*!
* \file
* \brief Shader cross-stage interface tests
*//*--------------------------------------------------------------------*/
#include "vktSpvAsmCrossStageInterfaceTests.hpp"
#include "tcuTestLog.hpp"
#include "tcuTextureUtil.hpp"
#include "tcuImageCompare.hpp"
#include "vkDefs.hpp"
#include "vkMemUtil.hpp"
#include "deSharedPtr.hpp"
#include "vkQueryUtil.hpp"
#include "vkRefUtil.hpp"
#include "vkStrUtil.hpp"
#include "vkTypeUtil.hpp"
#include "vkImageUtil.hpp"
#include "vkCmdUtil.hpp"
#include "vkObjUtil.hpp"
#include "deUniquePtr.hpp"
#include "vktSpvAsmGraphicsShaderTestUtil.hpp"
#include "vktTestCaseUtil.hpp"
#include "vktTestGroupUtil.hpp"
#include <map>
#include <vector>
namespace vkt
{
namespace SpirVAssembly
{
using namespace vk;
namespace
{
using std::string;
using std::map;
using std::vector;
typedef de::SharedPtr<Unique<VkShaderModule> > ShaderModuleSP;
using de::MovePtr;
using tcu::Vec4;
enum TestType
{
TEST_TYPE_FLAT = 0,
TEST_TYPE_NOPERSPECTIVE,
TEST_TYPE_RELAXEDPRECISION,
TEST_TYPE_LAST
};
struct TestParameters
{
TestParameters (TestType q, size_t s)
:testOptions (s)
,qualifier (q)
{}
vector<int> testOptions;
TestType qualifier;
};
VkBufferCreateInfo makeBufferCreateInfo (const VkDeviceSize bufferSize, const VkBufferUsageFlags usage)
{
const VkBufferCreateInfo bufferCreateInfo =
{
VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
(VkBufferCreateFlags)0, // VkBufferCreateFlags flags;
bufferSize, // VkDeviceSize size;
usage, // VkBufferUsageFlags usage;
VK_SHARING_MODE_EXCLUSIVE, // VkSharingMode sharingMode;
0u, // deUint32 queueFamilyIndexCount;
DE_NULL, // const deUint32* pQueueFamilyIndices;
};
return bufferCreateInfo;
}
VkImageCreateInfo makeImageCreateInfo (const VkImageType imageType, const VkExtent3D& extent, const VkFormat format, const VkImageUsageFlags usage, deUint32 queueFamilyIndex)
{
const VkImageCreateInfo imageInfo =
{
VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
(VkImageCreateFlags)0, // VkImageCreateFlags flags;
imageType, // VkImageType imageType;
format, // VkFormat format;
{extent.width, extent.height, 1u}, // VkExtent3D extent;
1u, // uint32_t mipLevels;
extent.depth, // uint32_t arrayLayers;
VK_SAMPLE_COUNT_1_BIT, // VkSampleCountFlagBits samples;
VK_IMAGE_TILING_OPTIMAL, // VkImageTiling tiling;
usage, // VkImageUsageFlags usage;
VK_SHARING_MODE_EXCLUSIVE, // VkSharingMode sharingMode;
1u, // uint32_t queueFamilyIndexCount;
&queueFamilyIndex, // const uint32_t* pQueueFamilyIndices;
VK_IMAGE_LAYOUT_UNDEFINED, // VkImageLayout initialLayout;
};
return imageInfo;
}
Move<VkImageView> makeImageView (const DeviceInterface& vk,
const VkDevice device,
const VkImage image,
const VkImageViewType viewType,
const VkFormat format,
const VkImageSubresourceRange subresourceRange)
{
const VkImageViewCreateInfo imageViewParams =
{
VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
(VkImageViewCreateFlags)0, // VkImageViewCreateFlags flags;
image, // VkImage image;
viewType, // VkImageViewType viewType;
format, // VkFormat format;
makeComponentMappingRGBA(), // VkComponentMapping components;
subresourceRange, // VkImageSubresourceRange subresourceRange;
};
return createImageView(vk, device, &imageViewParams);
}
Move<VkFramebuffer> makeFramebuffer (const DeviceInterface& vk,
const VkDevice device,
const VkRenderPass renderPass,
const VkImageView attachments,
const deUint32 width,
const deUint32 height)
{
const VkFramebufferCreateInfo framebufferInfo =
{
VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
(VkFramebufferCreateFlags)0, // VkFramebufferCreateFlags flags;
renderPass, // VkRenderPass renderPass;
1u, // uint32_t attachmentCount;
&attachments, // const VkImageView* pAttachments;
width, // uint32_t width;
height, // uint32_t height;
1u, // uint32_t layers;
};
return createFramebuffer(vk, device, &framebufferInfo);
}
Move<VkPipelineLayout> makePipelineLayout (const DeviceInterface& vk,
const VkDevice device)
{
VkPipelineLayoutCreateInfo pipelineLayoutParams =
{
VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
(VkPipelineLayoutCreateFlags)0,
0u, // deUint32 descriptorSetCount;
DE_NULL, // const VkDescriptorSetLayout* pSetLayouts;
0u, // deUint32 pushConstantRangeCount;
DE_NULL, // const VkPushConstantRange* pPushConstantRanges;
};
return createPipelineLayout(vk, device, &pipelineLayoutParams);
}
void imageBarrier (const DeviceInterface& vk,
const VkCommandBuffer cmdBuffer,
const VkImage image,
const VkImageSubresourceRange subresourceRange,
const VkImageLayout oldLayout,
const VkImageLayout newLayout,
const VkAccessFlags srcAccessMask,
const VkAccessFlags dstAccessMask,
const VkPipelineStageFlags srcStageMask,
const VkPipelineStageFlags dstStageMask)
{
const VkImageMemoryBarrier barrier =
{
VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, // VkStructureType sType;
DE_NULL, // const void* pNext;
srcAccessMask, // VkAccessFlags srcAccessMask;
dstAccessMask, // VkAccessFlags dstAccessMask;
oldLayout, // VkImageLayout oldLayout;
newLayout, // VkImageLayout newLayout;
VK_QUEUE_FAMILY_IGNORED, // deUint32 srcQueueFamilyIndex;
VK_QUEUE_FAMILY_IGNORED, // deUint32 dstQueueFamilyIndex;
image, // VkImage image;
subresourceRange, // VkImageSubresourceRange subresourceRange;
};
vk.cmdPipelineBarrier(cmdBuffer, srcStageMask, dstStageMask, (VkDependencyFlags)0, 0u, (const VkMemoryBarrier*)DE_NULL,
0u, (const VkBufferMemoryBarrier*)DE_NULL,
1u, &barrier);
}
class CrossStageTestInstance : public TestInstance
{
public:
CrossStageTestInstance (Context& context, const TestParameters& parameters)
: TestInstance (context)
, m_parameters (parameters)
, m_verticesCount (4u)
, m_data (2u * m_verticesCount)
, m_colorFormat (VK_FORMAT_R8G8B8A8_UNORM)
, m_colorRed (1.0f, 0.0f, 0.0f, 1.0f)
, m_colorGreen (0.0f, 1.0f, 0.0f, 1.0f)
{
createVertexData();
m_extent.width = 51u;
m_extent.height = 51u;
m_extent.depth = 1u;
}
enum
{
DECORATION_IN_VERTEX = 0,
DECORATION_IN_FRAGMENT,
DECORATION_IN_ALL_SHADERS,
DECORATION_LAST
};
protected:
tcu::TestStatus iterate (void);
private:
void createVertexData (void);
void makeShaderModule (map<VkShaderStageFlagBits, ShaderModuleSP>& shaderModule,
const VkShaderStageFlagBits stageFlag,
const int optionNdx);
Move<VkPipeline> makeGraphicsPipeline (const VkRenderPass renderPass,
const VkPipelineLayout pipelineLayout,
const VkShaderStageFlagBits stageFlags,
map<VkShaderStageFlagBits, ShaderModuleSP>& shaderModules,
const VkPrimitiveTopology primitiveTopology);
bool checkImage (VkImage image,
VkCommandBuffer cmdBuffer,
const string& description,
const tcu::Texture2DArray& referenceFrame);
void interpolationFill (tcu::Texture2DArray& referenceFrame);
void perspectiveFill (tcu::Texture2DArray& referenceFrame);
void redFill (tcu::Texture2DArray& referenceFrame);
const TestParameters m_parameters;
const deUint32 m_verticesCount;
vector<Vec4> m_data;
VkExtent3D m_extent;
const VkFormat m_colorFormat;
const Vec4 m_colorRed;
const Vec4 m_colorGreen;
};
tcu::TestStatus CrossStageTestInstance::iterate (void)
{
const DeviceInterface& vk = m_context.getDeviceInterface();
const VkDevice vkDevice = m_context.getDevice();
const VkPhysicalDeviceFeatures& features = m_context.getDeviceFeatures();
const bool supportsGeometry = features.geometryShader == VK_TRUE;
const bool supportsTessellation = features.tessellationShader == VK_TRUE;
const VkDeviceSize vertexDataSize = static_cast<VkDeviceSize>(deAlignSize(static_cast<size_t>( m_data.size() * sizeof(Vec4)),
static_cast<size_t>(m_context.getDeviceProperties().limits.nonCoherentAtomSize)));
const VkBufferCreateInfo bufferInfo = makeBufferCreateInfo(vertexDataSize, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT);
Move<VkBuffer> vertexBuffer = createBuffer(vk, vkDevice, &bufferInfo);
MovePtr<Allocation> allocationVertex = m_context.getDefaultAllocator().allocate(getBufferMemoryRequirements(vk, vkDevice, *vertexBuffer), MemoryRequirement::HostVisible);
const VkImageSubresourceRange imageSubresourceRange = makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, 1u, 0u, 1u);
const VkImageCreateInfo colorAttachmentInfo = makeImageCreateInfo(VK_IMAGE_TYPE_2D, m_extent, m_colorFormat,
VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, m_context.getUniversalQueueFamilyIndex());
Move<VkImage> colorAttachmentImage = createImage(vk, vkDevice, &colorAttachmentInfo);
MovePtr<Allocation> allocationAttachment = m_context.getDefaultAllocator().allocate(getImageMemoryRequirements(vk, vkDevice, *colorAttachmentImage), MemoryRequirement::Any);
VK_CHECK(vk.bindImageMemory(vkDevice, *colorAttachmentImage, allocationAttachment->getMemory(), allocationAttachment->getOffset()));
Move<VkImageView> colorAttachmentView = makeImageView(vk, vkDevice, *colorAttachmentImage, VK_IMAGE_VIEW_TYPE_2D, m_colorFormat, imageSubresourceRange);
MovePtr<tcu::Texture2DArray> referenceImage1 = MovePtr<tcu::Texture2DArray>(new tcu::Texture2DArray(mapVkFormat(m_colorFormat), m_extent.width, m_extent.height, m_extent.depth));
MovePtr<tcu::Texture2DArray> referenceImage2 = MovePtr<tcu::Texture2DArray>(new tcu::Texture2DArray(mapVkFormat(m_colorFormat), m_extent.width, m_extent.height, m_extent.depth));
// Init host buffer data
VK_CHECK(vk.bindBufferMemory(vkDevice, *vertexBuffer, allocationVertex->getMemory(), allocationVertex->getOffset()));
deMemcpy(allocationVertex->getHostPtr(), m_data.data(), static_cast<size_t>(vertexDataSize));
flushAlloc(vk, vkDevice, *allocationVertex);
Move<VkRenderPass> renderPass = makeRenderPass (vk, vkDevice, m_colorFormat);
Move<VkFramebuffer> frameBuffer = makeFramebuffer (vk, vkDevice, *renderPass, *colorAttachmentView, m_extent.width, m_extent.height);
Move<VkPipelineLayout> pipelineLayout = makePipelineLayout (vk, vkDevice);
Move<VkCommandPool> cmdPool;
Move<VkCommandBuffer> cmdBuffer;
// cmdPool
{
const VkCommandPoolCreateInfo cmdPoolParams =
{
VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, // VkCmdPoolCreateFlags flags;
m_context.getUniversalQueueFamilyIndex(), // deUint32 queueFamilyIndex;
};
cmdPool = createCommandPool(vk, vkDevice, &cmdPoolParams);
}
// cmdBuffer
{
const VkCommandBufferAllocateInfo cmdBufferAllocateInfo =
{
VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
*cmdPool, // VkCommandPool commandPool;
VK_COMMAND_BUFFER_LEVEL_PRIMARY, // VkCommandBufferLevel level;
1u, // deUint32 bufferCount;
};
cmdBuffer = allocateCommandBuffer(vk, vkDevice, &cmdBufferAllocateInfo);
}
if (!supportsTessellation)
m_context.getTestContext().getLog() << tcu::TestLog::Message << "Tessellation not supported" << tcu::TestLog::EndMessage;
if (!supportsGeometry)
m_context.getTestContext().getLog() << tcu::TestLog::Message << "Geometry not supported" << tcu::TestLog::EndMessage;
vector<deUint32> shadersStagesFlagsBits;
shadersStagesFlagsBits.push_back(VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT);
if (supportsTessellation)
shadersStagesFlagsBits.push_back(VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT | VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT | VK_SHADER_STAGE_FRAGMENT_BIT);
if (supportsGeometry)
shadersStagesFlagsBits.push_back(VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_GEOMETRY_BIT | VK_SHADER_STAGE_FRAGMENT_BIT);
if (supportsTessellation && supportsGeometry)
shadersStagesFlagsBits.push_back(VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT | VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT | VK_SHADER_STAGE_GEOMETRY_BIT | VK_SHADER_STAGE_FRAGMENT_BIT);
referenceImage1->allocLevel(0);
referenceImage2->allocLevel(0);
switch(m_parameters.qualifier)
{
case TEST_TYPE_FLAT:
interpolationFill(*referenceImage1);
redFill(*referenceImage2);
break;
case TEST_TYPE_NOPERSPECTIVE:
perspectiveFill(*referenceImage1);
interpolationFill(*referenceImage2);
break;
case TEST_TYPE_RELAXEDPRECISION:
interpolationFill(*referenceImage1);
interpolationFill(*referenceImage2);
break;
default:
DE_ASSERT(0);
}
for (deUint32 optionNdx = 0; optionNdx < m_parameters.testOptions.size(); optionNdx++)
for (size_t stagesNdx = 0ull; stagesNdx < shadersStagesFlagsBits.size(); stagesNdx++)
{
map<VkShaderStageFlagBits, ShaderModuleSP> shaderModule;
string imageDescription;
const VkClearValue renderPassClearValue = makeClearValueColor(tcu::Vec4(0.0f));
makeShaderModule(shaderModule, (VkShaderStageFlagBits)shadersStagesFlagsBits[stagesNdx], optionNdx);
Move<VkPipeline> graphicsPipeline = makeGraphicsPipeline (*renderPass, *pipelineLayout, (VkShaderStageFlagBits)shadersStagesFlagsBits[stagesNdx], shaderModule, ((VkShaderStageFlagBits)shadersStagesFlagsBits[stagesNdx] & VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT) ? VK_PRIMITIVE_TOPOLOGY_PATCH_LIST : VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP);
const VkDeviceSize vertexBufferOffset = 0u;
beginCommandBuffer(vk, *cmdBuffer);
imageBarrier(vk, *cmdBuffer, *colorAttachmentImage, imageSubresourceRange,
VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
0u, 0u,
VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT);
vk.cmdClearColorImage(*cmdBuffer, *colorAttachmentImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &renderPassClearValue.color, 1, &imageSubresourceRange);
imageBarrier(vk, *cmdBuffer, *colorAttachmentImage, imageSubresourceRange,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT);
beginRenderPass(vk, *cmdBuffer, *renderPass, *frameBuffer, makeRect2D(0, 0, m_extent.width, m_extent.height), tcu::Vec4(0.0f));
vk.cmdBindVertexBuffers(*cmdBuffer, 0u, 1u, &(*vertexBuffer), &vertexBufferOffset);
vk.cmdBindPipeline(*cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, *graphicsPipeline);
vk.cmdDraw(*cmdBuffer, m_verticesCount, 1u, 0u, 0u);
endRenderPass(vk, *cmdBuffer);
endCommandBuffer(vk, *cmdBuffer);
submitCommandsAndWait(vk, vkDevice, m_context.getUniversalQueue(), *cmdBuffer);
{
const string geometry = (VK_SHADER_STAGE_GEOMETRY_BIT & (VkShaderStageFlagBits)shadersStagesFlagsBits[stagesNdx]) ? "Geometry->" : "";
const string tessellation = ( VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT & (VkShaderStageFlagBits)shadersStagesFlagsBits[stagesNdx]) ? "Tessellation->" : "";
imageDescription = "Pipeline: Vertex->" + tessellation + geometry + "Fragment | ";
}
if (DECORATION_IN_VERTEX == m_parameters.testOptions[optionNdx])
imageDescription+= "decoration in vertex | ";
if (DECORATION_IN_FRAGMENT == m_parameters.testOptions[optionNdx])
imageDescription+= "decoration in fragment | ";
if (DECORATION_IN_ALL_SHADERS == m_parameters.testOptions[optionNdx])
imageDescription+= "decoration in all shaders | ";
{
bool resultComparison = false;
if (TEST_TYPE_RELAXEDPRECISION == m_parameters.qualifier)
{
resultComparison = checkImage(*colorAttachmentImage, *cmdBuffer, imageDescription+" Expected Pass", *referenceImage1);
}
else
{
if (DECORATION_IN_VERTEX == m_parameters.testOptions[optionNdx])
resultComparison = checkImage(*colorAttachmentImage, *cmdBuffer, imageDescription+" Expected Pass", *referenceImage1);
else if ((VkShaderStageFlagBits)(VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT) == (VkShaderStageFlagBits)shadersStagesFlagsBits[stagesNdx])
resultComparison = checkImage(*colorAttachmentImage, *cmdBuffer, imageDescription+" Expected Pass", *referenceImage2);
else
resultComparison = !checkImage(*colorAttachmentImage, *cmdBuffer, imageDescription+" Expected Fail", *referenceImage1);
}
if(!resultComparison)
return tcu::TestStatus::fail("Fail");
}
}
return tcu::TestStatus::pass("Pass");
}
void CrossStageTestInstance::createVertexData (void)
{
int ndx = -1;
if (TEST_TYPE_NOPERSPECTIVE == m_parameters.qualifier)
m_data[++ndx] = Vec4(-2.0f,-2.0f, 1.0f, 2.0f); //position
else
m_data[++ndx] = Vec4(-1.0f,-1.0f, 1.0f, 1.0f); //position
m_data[++ndx] = m_colorRed;
if (TEST_TYPE_NOPERSPECTIVE == m_parameters.qualifier)
m_data[++ndx] = Vec4(-2.0f, 2.0f, 1.0f, 2.0f); //position
else
m_data[++ndx] = Vec4(-1.0f, 1.0f, 1.0f, 1.0f); //position
m_data[++ndx] = m_colorRed;
m_data[++ndx] = Vec4( 1.0f,-1.0f, 1.0f, 1.0f); //position
m_data[++ndx] = m_colorGreen;
m_data[++ndx] = Vec4( 1.0f, 1.0f, 1.0f, 1.0f); //position
m_data[++ndx] = m_colorGreen;
}
void CrossStageTestInstance::makeShaderModule (map<VkShaderStageFlagBits, ShaderModuleSP>& shaderModule,
const VkShaderStageFlagBits stageFlag,
const int optionNdx)
{
const DeviceInterface& vk = m_context.getDeviceInterface();
const VkDevice vkDevice = m_context.getDevice();
std::ostringstream vertex;
vertex<<"vertex"<<optionNdx;
std::ostringstream fragment;
fragment<<"fragment"<<optionNdx;
if (stageFlag & VK_SHADER_STAGE_VERTEX_BIT)
shaderModule[VK_SHADER_STAGE_VERTEX_BIT] = (ShaderModuleSP(new Unique<VkShaderModule>(createShaderModule(vk, vkDevice, m_context.getBinaryCollection().get(vertex.str()), 0))));
if (stageFlag & VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT)
shaderModule[VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT] = (ShaderModuleSP(new Unique<VkShaderModule>(createShaderModule(vk, vkDevice, m_context.getBinaryCollection().get("tessellation_control"), 0))));
if (stageFlag & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT)
shaderModule[VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT] = (ShaderModuleSP(new Unique<VkShaderModule>(createShaderModule(vk, vkDevice, m_context.getBinaryCollection().get("tessellation_evaluation"), 0))));
if (stageFlag & VK_SHADER_STAGE_GEOMETRY_BIT)
shaderModule[VK_SHADER_STAGE_GEOMETRY_BIT] = (ShaderModuleSP(new Unique<VkShaderModule>(createShaderModule(vk, vkDevice, m_context.getBinaryCollection().get("geometry"), 0))));
if (stageFlag & VK_SHADER_STAGE_FRAGMENT_BIT)
shaderModule[VK_SHADER_STAGE_FRAGMENT_BIT] = (ShaderModuleSP(new Unique<VkShaderModule>(createShaderModule(vk, vkDevice, m_context.getBinaryCollection().get(fragment.str()), 0))));
}
Move<VkPipeline> CrossStageTestInstance::makeGraphicsPipeline (const VkRenderPass renderPass,
const VkPipelineLayout pipelineLayout,
const VkShaderStageFlagBits shaderFlags,
map<VkShaderStageFlagBits, ShaderModuleSP>& shaderModules,
const VkPrimitiveTopology primitiveTopology)
{
const DeviceInterface& vk = m_context.getDeviceInterface();
const VkDevice vkDevice = m_context.getDevice();
const VkVertexInputBindingDescription vertexInputBindingDescription =
{
0u, // binding;
static_cast<deUint32>(2u*sizeof(Vec4)), // stride;
VK_VERTEX_INPUT_RATE_VERTEX // inputRate
};
const VkVertexInputAttributeDescription vertexInputAttributeDescriptions[] =
{
{
0u,
0u,
VK_FORMAT_R32G32B32A32_SFLOAT,
0u
}, // VertexElementData::position
{
1u,
0u,
VK_FORMAT_R32G32B32A32_SFLOAT,
static_cast<deUint32>(sizeof(tcu::Vec4))
}, // VertexElementData::color
};
const VkPipelineVertexInputStateCreateInfo vertexInputStateParams =
{ // sType;
VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO, // pNext;
NULL, // flags;
0u, // vertexBindingDescriptionCount;
1u, // pVertexBindingDescriptions;
&vertexInputBindingDescription, // vertexAttributeDescriptionCount;
2u, // pVertexAttributeDescriptions;
vertexInputAttributeDescriptions
};
const std::vector<VkViewport> viewports (1, makeViewport(m_extent));
const std::vector<VkRect2D> scissors (1, makeRect2D(m_extent));
VkPipelineDepthStencilStateCreateInfo depthStencilStateParams =
{
VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
0u, // VkPipelineDepthStencilStateCreateFlags flags;
VK_TRUE, // VkBool32 depthTestEnable;
VK_TRUE, // VkBool32 depthWriteEnable;
VK_COMPARE_OP_LESS_OR_EQUAL, // VkCompareOp depthCompareOp;
VK_FALSE, // VkBool32 depthBoundsTestEnable;
VK_FALSE, // VkBool32 stencilTestEnable;
// VkStencilOpState front;
{
VK_STENCIL_OP_KEEP, // VkStencilOp failOp;
VK_STENCIL_OP_KEEP, // VkStencilOp passOp;
VK_STENCIL_OP_KEEP, // VkStencilOp depthFailOp;
VK_COMPARE_OP_NEVER, // VkCompareOp compareOp;
0u, // deUint32 compareMask;
0u, // deUint32 writeMask;
0u, // deUint32 reference;
},
// VkStencilOpState back;
{
VK_STENCIL_OP_KEEP, // VkStencilOp failOp;
VK_STENCIL_OP_KEEP, // VkStencilOp passOp;
VK_STENCIL_OP_KEEP, // VkStencilOp depthFailOp;
VK_COMPARE_OP_NEVER, // VkCompareOp compareOp;
0u, // deUint32 compareMask;
0u, // deUint32 writeMask;
0u, // deUint32 reference;
},
0.0f, // float minDepthBounds;
1.0f, // float maxDepthBounds;
};
const VkShaderModule vertShader = shaderFlags & VK_SHADER_STAGE_VERTEX_BIT ? **shaderModules[VK_SHADER_STAGE_VERTEX_BIT] : DE_NULL;
const VkShaderModule tessControlShader = shaderFlags & VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT ? **shaderModules[VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT] : DE_NULL;
const VkShaderModule tessEvalShader = shaderFlags & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT ? **shaderModules[VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT] : DE_NULL;
const VkShaderModule geomShader = shaderFlags & VK_SHADER_STAGE_GEOMETRY_BIT ? **shaderModules[VK_SHADER_STAGE_GEOMETRY_BIT] : DE_NULL;
const VkShaderModule fragShader = shaderFlags & VK_SHADER_STAGE_FRAGMENT_BIT ? **shaderModules[VK_SHADER_STAGE_FRAGMENT_BIT] : DE_NULL;
return vk::makeGraphicsPipeline(vk, // const DeviceInterface& vk
vkDevice, // const VkDevice device
pipelineLayout, // const VkPipelineLayout pipelineLayout
vertShader, // const VkShaderModule vertexShaderModule
tessControlShader, // const VkShaderModule tessellationControlShaderModule
tessEvalShader, // const VkShaderModule tessellationEvalShaderModule
geomShader, // const VkShaderModule geometryShaderModule
fragShader, // const VkShaderModule fragmentShaderModule
renderPass, // const VkRenderPass renderPass
viewports, // const std::vector<VkViewport>& viewports
scissors, // const std::vector<VkRect2D>& scissors
primitiveTopology, // const VkPrimitiveTopology topology
0u, // const deUint32 subpass
4u, // const deUint32 patchControlPoints
&vertexInputStateParams, // const VkPipelineVertexInputStateCreateInfo* vertexInputStateCreateInfo
DE_NULL, // const VkPipelineRasterizationStateCreateInfo* rasterizationStateCreateInfo
DE_NULL, // const VkPipelineMultisampleStateCreateInfo* multisampleStateCreateInfo
&depthStencilStateParams); // const VkPipelineDepthStencilStateCreateInfo* depthStencilStateCreateInfo
}
bool CrossStageTestInstance::checkImage (VkImage image, VkCommandBuffer cmdBuffer, const string& description, const tcu::Texture2DArray& referenceFrame)
{
const DeviceInterface& vk = m_context.getDeviceInterface();
const VkDevice vkDevice = m_context.getDevice();
const int pixelSize = referenceFrame.getFormat().getPixelSize();
Move<VkBuffer> buffer;
MovePtr<Allocation> bufferAlloc;
vector<deUint8> pixelAccessData (m_extent.width * m_extent.height * m_extent.depth * pixelSize);
tcu::PixelBufferAccess dst (referenceFrame.getFormat(), m_extent.width, m_extent.height, m_extent.depth, pixelAccessData.data());
const VkDeviceSize pixelDataSize = dst.getWidth() * dst.getHeight() * dst.getDepth() * pixelSize;
// Create destination buffer
{
const VkBufferCreateInfo bufferParams =
{
VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
0u, // VkBufferCreateFlags flags;
pixelDataSize, // VkDeviceSize size;
VK_BUFFER_USAGE_TRANSFER_DST_BIT, // VkBufferUsageFlags usage;
VK_SHARING_MODE_EXCLUSIVE, // VkSharingMode sharingMode;
0u, // deUint32 queueFamilyIndexCount;
DE_NULL, // const deUint32* pQueueFamilyIndices;
};
buffer = createBuffer(vk, vkDevice, &bufferParams);
bufferAlloc = m_context.getDefaultAllocator().allocate(getBufferMemoryRequirements(vk, vkDevice, *buffer), MemoryRequirement::HostVisible);
VK_CHECK(vk.bindBufferMemory(vkDevice, *buffer, bufferAlloc->getMemory(), bufferAlloc->getOffset()));
deMemset(bufferAlloc->getHostPtr(), 0, static_cast<size_t>(pixelDataSize));
flushAlloc(vk, vkDevice, *bufferAlloc);
}
beginCommandBuffer (vk, cmdBuffer);
copyImageToBuffer(vk, cmdBuffer, image, *buffer, tcu::IVec2(m_extent.width, m_extent.height), 0u, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, m_extent.depth);
endCommandBuffer(vk, cmdBuffer);
submitCommandsAndWait(vk, vkDevice, m_context.getUniversalQueue(), cmdBuffer);
// Read buffer data
invalidateAlloc(vk, vkDevice, *bufferAlloc);
tcu::copy(dst, tcu::ConstPixelBufferAccess(dst.getFormat(), dst.getSize(), bufferAlloc->getHostPtr()));
if (tcu::floatThresholdCompare(m_context.getTestContext().getLog(), "Result", description.c_str(), referenceFrame.getLevel(0), dst, tcu::Vec4(0.05f), tcu::COMPARE_LOG_EVERYTHING))
return true;
return false;
}
void CrossStageTestInstance::interpolationFill (tcu::Texture2DArray& referenceFrame)
{
for (deUint32 x = 0u; x < m_extent.width; ++x)
{
float u = static_cast<float>(x)/static_cast<float>(m_extent.width - 1);
const Vec4 resultColor (m_colorRed.x() * (1.0f - u) + m_colorGreen.x() * u,
m_colorRed.y() * (1.0f - u) + m_colorGreen.y() * u,
m_colorRed.z() * (1.0f - u) + m_colorGreen.z() * u,
m_colorRed.w() * (1.0f - u) + m_colorGreen.w() * u);
referenceFrame.getLevel(0).setPixel(resultColor,x,0);
}
for (deUint32 y = 0u; y < m_extent.height; ++y)
{
deMemcpy (referenceFrame.getLevel(0).getPixelPtr(0,y), referenceFrame.getLevel(0).getPixelPtr(0,0), m_extent.width * m_extent.depth* referenceFrame.getFormat().getPixelSize());
}
}
void CrossStageTestInstance::perspectiveFill (tcu::Texture2DArray& referenceFrame)
{
float dynamics = 1.732f;
float dynamicChange = 0.732f / static_cast<float>(m_extent.width);
for (deUint32 x = 0u; x < m_extent.width; ++x)
{
float u = static_cast<float>(x)/static_cast<float>(m_extent.width - 1);
const Vec4 resultColor (m_colorRed.x() * (1.0f - dynamics * u) + m_colorGreen.x() * u* dynamics,
m_colorRed.y() * (1.0f - dynamics * u) + m_colorGreen.y() * u* dynamics,
m_colorRed.z() * (1.0f - dynamics * u) + m_colorGreen.z() * u* dynamics,
m_colorRed.w() * (1.0f - dynamics * u) + m_colorGreen.w() * u* dynamics);
dynamics -= dynamicChange;
if (dynamics < 1.0f)
dynamics = 1.0f;
referenceFrame.getLevel(0).setPixel(resultColor,x,0);
}
for (deUint32 y = 0u; y < m_extent.height; ++y)
{
deMemcpy (referenceFrame.getLevel(0).getPixelPtr(0,y), referenceFrame.getLevel(0).getPixelPtr(0,0), m_extent.width * m_extent.depth* referenceFrame.getFormat().getPixelSize());
}
}
void CrossStageTestInstance::redFill (tcu::Texture2DArray& referenceFrame)
{
for (deUint32 x = 0u; x < m_extent.width; ++x)
referenceFrame.getLevel(0).setPixel(m_colorRed,x,0);
for (deUint32 y = 0u; y < m_extent.height; ++y)
deMemcpy (referenceFrame.getLevel(0).getPixelPtr(0,y), referenceFrame.getLevel(0).getPixelPtr(0,0), m_extent.width * m_extent.depth* referenceFrame.getFormat().getPixelSize());
}
struct Decorations
{
Decorations()
{};
Decorations(const string& f, const string& v, const string& o)
: fragment (f)
, vertex (v)
, others (o)
{};
string fragment;
string vertex;
string others;
};
class CrossStageBasicTestsCase : public vkt::TestCase
{
public:
CrossStageBasicTestsCase (tcu::TestContext &context, const char *name, const char *description, const TestParameters& parameters)
: TestCase (context, name, description)
, m_parameters (parameters)
{
}
private:
vkt::TestInstance* createInstance (vkt::Context& context) const;
void initPrograms (SourceCollections& programCollection) const;
const TestParameters m_parameters;
};
vkt::TestInstance* CrossStageBasicTestsCase::createInstance (vkt::Context& context) const
{
return new CrossStageTestInstance(context, m_parameters);
}
void CrossStageBasicTestsCase::initPrograms (SourceCollections& programCollection) const
{
vector<Decorations> decorations;
string epsilon = "6e-8";
switch(m_parameters.qualifier)
{
case TEST_TYPE_FLAT:
decorations.push_back(Decorations("",
//Vertex
"OpDecorate %color_out Flat\n"
"OpDecorate %color_in Flat\n"
"OpDecorate %r_float_out Flat\n"
"OpDecorate %rg_float_out Flat\n"
"OpDecorate %rgb_float_out Flat\n"
"OpDecorate %rgba_float_out Flat\n",
""));
decorations.push_back(Decorations(//Fragment
"OpDecorate %color_in Flat\n"
"OpDecorate %r_float_in Flat\n"
"OpDecorate %rg_float_in Flat\n"
"OpDecorate %rgb_float_in Flat\n"
"OpDecorate %rgba_float_in Flat\n",
"",
""));
decorations.push_back(Decorations(//Fragment
"OpDecorate %color_in Flat\n"
"OpDecorate %r_float_in Flat\n"
"OpDecorate %rg_float_in Flat\n"
"OpDecorate %rgb_float_in Flat\n"
"OpDecorate %rgba_float_in Flat\n",
//Vertex
"OpDecorate %color_out Flat\n"
"OpDecorate %color_in Flat\n"
"OpDecorate %r_float_out Flat\n"
"OpDecorate %rg_float_out Flat\n"
"OpDecorate %rgb_float_out Flat\n"
"OpDecorate %rgba_float_out Flat\n",
""));
epsilon = "0.0";
break;
case TEST_TYPE_NOPERSPECTIVE:
decorations.push_back(Decorations("",
//Vertex
"OpDecorate %color_out NoPerspective\n"
"OpDecorate %color_in NoPerspective\n"
"OpDecorate %r_float_out NoPerspective\n"
"OpDecorate %rg_float_out NoPerspective\n"
"OpDecorate %rgb_float_out NoPerspective\n"
"OpDecorate %rgba_float_out NoPerspective\n",
""));
decorations.push_back(Decorations(//Fragment
"OpDecorate %color_in NoPerspective\n"
"OpDecorate %r_float_in NoPerspective\n"
"OpDecorate %rg_float_in NoPerspective\n"
"OpDecorate %rgb_float_in NoPerspective\n"
"OpDecorate %rgba_float_in NoPerspective\n",
"",
""));
decorations.push_back(Decorations(//Fragment
"OpDecorate %color_in NoPerspective\n"
"OpDecorate %r_float_in NoPerspective\n"
"OpDecorate %rg_float_in NoPerspective\n"
"OpDecorate %rgb_float_in NoPerspective\n"
"OpDecorate %rgba_float_in NoPerspective\n",
//Vertex
"OpDecorate %color_out NoPerspective\n"
"OpDecorate %color_in NoPerspective\n"
"OpDecorate %r_float_out NoPerspective\n"
"OpDecorate %rg_float_out NoPerspective\n"
"OpDecorate %rgb_float_out NoPerspective\n"
"OpDecorate %rgba_float_out NoPerspective\n",
//Others
""));
break;
case TEST_TYPE_RELAXEDPRECISION:
decorations.push_back(Decorations(//Fragment
"OpDecorate %color_out RelaxedPrecision\n"
"OpDecorate %color_in RelaxedPrecision\n"
"OpDecorate %r_float_in RelaxedPrecision\n"
"OpDecorate %rg_float_in RelaxedPrecision\n"
"OpDecorate %rgb_float_in RelaxedPrecision\n"
"OpDecorate %rgba_float_in RelaxedPrecision\n",
//Vertex
"OpDecorate %color_out RelaxedPrecision\n"
"OpDecorate %color_in RelaxedPrecision\n"
"OpDecorate %r_float_out RelaxedPrecision\n"
"OpDecorate %rg_float_out RelaxedPrecision\n"
"OpDecorate %rgb_float_out RelaxedPrecision\n"
"OpDecorate %rgba_float_out RelaxedPrecision\n",
//Others
"OpDecorate %color_out RelaxedPrecision\n"
"OpDecorate %color_in RelaxedPrecision\n"
"OpDecorate %r_float_out RelaxedPrecision\n"
"OpDecorate %rg_float_out RelaxedPrecision\n"
"OpDecorate %rgb_float_out RelaxedPrecision\n"
"OpDecorate %rgba_float_out RelaxedPrecision\n"
"OpDecorate %r_float_in RelaxedPrecision\n"
"OpDecorate %rg_float_in RelaxedPrecision\n"
"OpDecorate %rgb_float_in RelaxedPrecision\n"
"OpDecorate %rgba_float_in RelaxedPrecision\n"));
break;
default:
DE_ASSERT(0);
}
//Spir-v spec: decoration flat can be used only in Shader (fragment or vertex)
for (deUint32 ndx = 0; ndx < decorations.size(); ++ndx)
{
/*#version 450
layout(location = 0) in highp vec4 in_position;
layout(location = 1) in vec4 in_color;
layout(location = 0) out vec4 out_color;
layout(location = 1) out float r_float_out;
layout(location = 2) out vec2 rg_float_out;
layout(location = 3) out vec3 rgb_float_out;
layout(location = 4) out vec4 rgba_float_out;
void main (void)
{
gl_Position = in_position;
out_color = in_color;
r_float_out = in_color.r;
rg_float_out = vec2(in_color.r, in_color.g);
rgb_float_out = vec3(in_color.r, in_color.g,in_color.b);
rgba_float_out = vec4(in_color.r, in_color.g, in_color.b, in_color.a);
}
*/
const string vertexShaderSource =
"; SPIR-V\n"
"; Version: 1.3\n"
"; Generator: Khronos Glslang Reference Front End; 2\n"
"; Bound: 60\n"
"; Schema: 0\n"
"OpCapability Shader\n"
"%1 = OpExtInstImport \"GLSL.std.450\"\n"
"OpMemoryModel Logical GLSL450\n"
"OpEntryPoint Vertex %4 \"main\" %13 %17 %color_out %color_in %r_float_out %rg_float_out %rgb_float_out %rgba_float_out\n"
"OpMemberDecorate %11 0 BuiltIn Position\n"
"OpMemberDecorate %11 1 BuiltIn PointSize\n"
"OpMemberDecorate %11 2 BuiltIn ClipDistance\n"
"OpMemberDecorate %11 3 BuiltIn CullDistance\n"
"OpDecorate %11 Block\n"
"OpDecorate %17 Location 0\n"
"OpDecorate %color_out Location 0\n"
"OpDecorate %color_in Location 1\n"
"OpDecorate %r_float_out Location 1\n"
"OpDecorate %rg_float_out Location 2\n"
"OpDecorate %rgb_float_out Location 3\n"
"OpDecorate %rgba_float_out Location 4\n"
+decorations[ndx].vertex+
"%2 = OpTypeVoid\n"
"%3 = OpTypeFunction %2\n"
"%6 = OpTypeFloat 32\n"
"%7 = OpTypeVector %6 4\n"
"%8 = OpTypeInt 32 0\n"
"%9 = OpConstant %8 1\n"
"%10 = OpTypeArray %6 %9\n"
"%11 = OpTypeStruct %7 %6 %10 %10\n"
"%12 = OpTypePointer Output %11\n"
"%13 = OpVariable %12 Output\n"
"%14 = OpTypeInt 32 1\n"
"%15 = OpConstant %14 0\n"
"%16 = OpTypePointer Input %7\n"
"%17 = OpVariable %16 Input\n"
"%19 = OpTypePointer Output %7\n"
"%color_out = OpVariable %19 Output\n"
"%color_in = OpVariable %16 Input\n"
"%24 = OpTypePointer Output %6\n"
"%r_float_out = OpVariable %24 Output\n"
"%26 = OpConstant %8 0\n"
"%27 = OpTypePointer Input %6\n"
"%30 = OpTypeVector %6 2\n"
"%31 = OpTypePointer Output %30\n"
"%rg_float_out = OpVariable %31 Output\n"
"%38 = OpTypeVector %6 3\n"
"%39 = OpTypePointer Output %38\n"
"%rgb_float_out = OpVariable %39 Output\n"
"%45 = OpConstant %8 2\n"
"%rgba_float_out = OpVariable %19 Output\n"
"%56 = OpConstant %8 3\n"
"%4 = OpFunction %2 None %3\n"
"%5 = OpLabel\n"
"%18 = OpLoad %7 %17\n"
"%20 = OpAccessChain %19 %13 %15\n"
"OpStore %20 %18\n"
"%23 = OpLoad %7 %color_in\n"
"OpStore %color_out %23\n"
"%28 = OpAccessChain %27 %color_in %26\n"
"%29 = OpLoad %6 %28\n"
"OpStore %r_float_out %29\n"
"%33 = OpAccessChain %27 %color_in %26\n"
"%34 = OpLoad %6 %33\n"
"%35 = OpAccessChain %27 %color_in %9\n"
"%36 = OpLoad %6 %35\n"
"%37 = OpCompositeConstruct %30 %34 %36\n"
"OpStore %rg_float_out %37\n"
"%41 = OpAccessChain %27 %color_in %26\n"
"%42 = OpLoad %6 %41\n"
"%43 = OpAccessChain %27 %color_in %9\n"
"%44 = OpLoad %6 %43\n"
"%46 = OpAccessChain %27 %color_in %45\n"
"%47 = OpLoad %6 %46\n"
"%48 = OpCompositeConstruct %38 %42 %44 %47\n"
"OpStore %rgb_float_out %48\n"
"%50 = OpAccessChain %27 %color_in %26\n"
"%51 = OpLoad %6 %50\n"
"%52 = OpAccessChain %27 %color_in %9\n"
"%53 = OpLoad %6 %52\n"
"%54 = OpAccessChain %27 %color_in %45\n"
"%55 = OpLoad %6 %54\n"
"%57 = OpAccessChain %27 %color_in %56\n"
"%58 = OpLoad %6 %57\n"
"%59 = OpCompositeConstruct %7 %51 %53 %55 %58\n"
"OpStore %rgba_float_out %59\n"
"OpReturn\n"
"OpFunctionEnd\n";
/* #version 450
layout(location = 0) out vec4 out_color;
layout(location = 0) in vec4 in_color;
layout(location = 1) in float r_float_in;
layout(location = 2) in vec2 rg_float_in;
layout(location = 3) in vec3 rgb_float_in;
layout(location = 4) in vec4 rgba_float_in;
void main()
{
float epsilon = 6e-8; // or 0.0 for flat
out_color = in_color;
if(abs(r_float_in - in_color.r) > epsilon)
out_color.r = 1.0f;
if(any(greaterThan(abs(rg_float_in - in_color.rg), vec2(epsilon))))
out_color.rg = vec2(1.0f);
if(any(greaterThan(abs(rgb_float_in - in_color.rgb), vec3(epsilon))))
out_color.rgb = vec3(1.0f);
if(any(greaterThan(abs(rgba_float_in - in_color.rgba), vec4(epsilon))))
out_color.rgba = vec4(1.0f);
}
*/
const string fragmentShaderSource =
"; SPIR-V\n"
"; Version: 1.3\n"
"; Generator: Khronos Glslang Reference Front End; 2\n"
"; Bound: 64\n"
"; Schema: 0\n"
"OpCapability Shader\n"
"%1 = OpExtInstImport \"GLSL.std.450\"\n"
"OpMemoryModel Logical GLSL450\n"
"OpEntryPoint Fragment %4 \"main\" %color_out %color_in %r_float_in %rg_float_in %rgb_float_in %rgba_float_in\n"
"OpExecutionMode %4 OriginUpperLeft\n"
"OpDecorate %color_out Location 0\n"
"OpDecorate %color_in Location 0\n"
"OpDecorate %r_float_in Location 1\n"
"OpDecorate %rg_float_in Location 2\n"
"OpDecorate %rgb_float_in Location 3\n"
"OpDecorate %rgba_float_in Location 4\n"
+decorations[ndx].fragment+
"%2 = OpTypeVoid\n"
"%3 = OpTypeFunction %2\n"
"%6 = OpTypeFloat 32\n"
"%7 = OpTypeVector %6 4\n"
"%8 = OpTypePointer Output %7\n"
"%color_out = OpVariable %8 Output\n"
"%10 = OpTypePointer Input %7\n"
"%color_in = OpVariable %10 Input\n"
"%13 = OpTypePointer Input %6\n"
"%r_float_in = OpVariable %13 Input\n"
"%16 = OpTypeInt 32 0\n"
"%17 = OpConstant %16 0\n"
"%20 = OpTypeBool\n"
"%ep = OpConstant %6 " + epsilon + "\n"
"%24 = OpConstant %6 1\n"
"%25 = OpTypePointer Output %6\n"
"%27 = OpTypeVector %6 2\n"
"%28 = OpTypePointer Input %27\n"
"%rg_float_in = OpVariable %28 Input\n"
"%ep2 = OpConstantComposite %27 %ep %ep\n"
"%33 = OpTypeVector %20 2\n"
"%38 = OpConstantComposite %27 %24 %24\n"
"%41 = OpTypeVector %6 3\n"
"%42 = OpTypePointer Input %41\n"
"%rgb_float_in = OpVariable %42 Input\n"
"%ep3 = OpConstantComposite %41 %ep %ep %ep\n"
"%47 = OpTypeVector %20 3\n"
"%52 = OpConstantComposite %41 %24 %24 %24\n"
"%rgba_float_in = OpVariable %10 Input\n"
"%ep4 = OpConstantComposite %7 %ep %ep %ep %ep\n"
"%58 = OpTypeVector %20 4\n"
"%63 = OpConstantComposite %7 %24 %24 %24 %24\n"
"%4 = OpFunction %2 None %3\n"
"%5 = OpLabel\n"
"%12 = OpLoad %7 %color_in\n"
"OpStore %color_out %12\n"
"%15 = OpLoad %6 %r_float_in\n"
"%18 = OpAccessChain %13 %color_in %17\n"
"%19 = OpLoad %6 %18\n"
"%sub = OpFSub %6 %15 %19\n"
"%abs = OpExtInst %6 %1 FAbs %sub\n"
"%cmp = OpFOrdGreaterThan %20 %abs %ep\n"
"OpSelectionMerge %23 None\n"
"OpBranchConditional %cmp %22 %23\n"
"%22 = OpLabel\n"
"%26 = OpAccessChain %25 %color_out %17\n"
"OpStore %26 %24\n"
"OpBranch %23\n"
"%23 = OpLabel\n"
"%30 = OpLoad %27 %rg_float_in\n"
"%31 = OpLoad %7 %color_in\n"
"%32 = OpVectorShuffle %27 %31 %31 0 1\n"
"%sub2 = OpFSub %27 %30 %32\n"
"%abs2 = OpExtInst %27 %1 FAbs %sub2\n"
"%cmp2 = OpFOrdGreaterThan %33 %abs2 %ep2\n"
"%35 = OpAny %20 %cmp2\n"
"OpSelectionMerge %37 None\n"
"OpBranchConditional %35 %36 %37\n"
"%36 = OpLabel\n"
"%39 = OpLoad %7 %color_out\n"
"%40 = OpVectorShuffle %7 %39 %38 4 5 2 3\n"
"OpStore %color_out %40\n"
"OpBranch %37\n"
"%37 = OpLabel\n"
"%44 = OpLoad %41 %rgb_float_in\n"
"%45 = OpLoad %7 %color_in\n"
"%46 = OpVectorShuffle %41 %45 %45 0 1 2\n"
"%sub3 = OpFSub %41 %44 %46\n"
"%abs3 = OpExtInst %41 %1 FAbs %sub3\n"
"%cmp3 = OpFOrdGreaterThan %47 %abs3 %ep3\n"
"%49 = OpAny %20 %cmp3\n"
"OpSelectionMerge %51 None\n"
"OpBranchConditional %49 %50 %51\n"
"%50 = OpLabel\n"
"%53 = OpLoad %7 %color_out\n"
"%54 = OpVectorShuffle %7 %53 %52 4 5 6 3\n"
"OpStore %color_out %54\n"
"OpBranch %51\n"
"%51 = OpLabel\n"
"%56 = OpLoad %7 %rgba_float_in\n"
"%57 = OpLoad %7 %color_in\n"
"%sub4 = OpFSub %7 %56 %57\n"
"%abs4 = OpExtInst %7 %1 FAbs %sub4\n"
"%cmp4 = OpFOrdGreaterThan %58 %abs4 %ep4\n"
"%60 = OpAny %20 %cmp4\n"
"OpSelectionMerge %62 None\n"
"OpBranchConditional %60 %61 %62\n"
"%61 = OpLabel\n"
"OpStore %color_out %63\n"
"OpBranch %62\n"
"%62 = OpLabel\n"
"OpReturn\n"
"OpFunctionEnd\n";
std::ostringstream vertex;
vertex << "vertex" << ndx;
std::ostringstream fragment;
fragment << "fragment" << ndx;
programCollection.spirvAsmSources.add(vertex.str()) << vertexShaderSource;
programCollection.spirvAsmSources.add(fragment.str()) << fragmentShaderSource;
}
{
/*#version 450
#extension GL_EXT_tessellation_shader : require
layout(vertices = 4) out;
layout(location = 0) in vec4 in_color[];
layout(location = 1) in float r_float_in[];
layout(location = 2) in vec2 rg_float_in[];
layout(location = 3) in vec3 rgb_float_in[];
layout(location = 4) in vec4 rgba_float_in[];
layout(location = 0) out vec4 out_color[];
layout(location = 1) out float r_float_out[];
layout(location = 2) out vec2 rg_float_out[];
layout(location = 3) out vec3 rgb_float_out[];
layout(location = 4) out vec4 rgba_float_out[];
void main (void)
{
if ( gl_InvocationID == 0 )
{
gl_TessLevelInner[0] = 4.0f;
gl_TessLevelInner[1] = 4.0f;
gl_TessLevelOuter[0] = 4.0f;
gl_TessLevelOuter[1] = 4.0f;
gl_TessLevelOuter[2] = 4.0f;
gl_TessLevelOuter[3] = 4.0f;
}
out_color[gl_InvocationID] = in_color[gl_InvocationID];
r_float_out[gl_InvocationID] = r_float_in[gl_InvocationID];
rg_float_out[gl_InvocationID] = rg_float_in[gl_InvocationID];
rgb_float_out[gl_InvocationID] = rgb_float_in[gl_InvocationID];
rgba_float_out[gl_InvocationID] = rgba_float_in[gl_InvocationID];
gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position;
}*/
const string tessellationControlSource =
"; SPIR-V\n"
"; Version: 1.3\n"
"; Generator: Khronos Glslang Reference Front End; 2\n"
"; Bound: 111\n"
"; Schema: 0\n"
"OpCapability Tessellation\n"
"%1 = OpExtInstImport \"GLSL.std.450\"\n"
"OpMemoryModel Logical GLSL450\n"
"OpEntryPoint TessellationControl %4 \"main\" %8 %20 %29 %color_out %color_in %r_float_out %r_float_in %rg_float_out %rg_float_in %rgb_float_out %rgb_float_in %rgba_float_out %rgba_float_in %101 %106\n"
"OpExecutionMode %4 OutputVertices 4\n"
"OpDecorate %8 BuiltIn InvocationId\n"
"OpDecorate %20 Patch\n"
"OpDecorate %20 BuiltIn TessLevelInner\n"
"OpDecorate %29 Patch\n"
"OpDecorate %29 BuiltIn TessLevelOuter\n"
"OpDecorate %color_out Location 0\n"
"OpDecorate %color_in Location 0\n"
"OpDecorate %r_float_out Location 1\n"
"OpDecorate %r_float_in Location 1\n"
"OpDecorate %rg_float_out Location 2\n"
"OpDecorate %rg_float_in Location 2\n"
"OpDecorate %rgb_float_out Location 3\n"
"OpDecorate %rgb_float_in Location 3\n"
"OpDecorate %rgba_float_out Location 4\n"
"OpDecorate %rgba_float_in Location 4\n"
+decorations[0].others+
"OpMemberDecorate %98 0 BuiltIn Position\n"
"OpMemberDecorate %98 1 BuiltIn PointSize\n"
"OpMemberDecorate %98 2 BuiltIn ClipDistance\n"
"OpMemberDecorate %98 3 BuiltIn CullDistance\n"
"OpDecorate %98 Block\n"
"OpMemberDecorate %103 0 BuiltIn Position\n"
"OpMemberDecorate %103 1 BuiltIn PointSize\n"
"OpMemberDecorate %103 2 BuiltIn ClipDistance\n"
"OpMemberDecorate %103 3 BuiltIn CullDistance\n"
"OpDecorate %103 Block\n"
"%2 = OpTypeVoid\n"
"%3 = OpTypeFunction %2\n"
"%6 = OpTypeInt 32 1\n"
"%7 = OpTypePointer Input %6\n"
"%8 = OpVariable %7 Input\n"
"%10 = OpConstant %6 0\n"
"%11 = OpTypeBool\n"
"%15 = OpTypeFloat 32\n"
"%16 = OpTypeInt 32 0\n"
"%17 = OpConstant %16 2\n"
"%18 = OpTypeArray %15 %17\n"
"%19 = OpTypePointer Output %18\n"
"%20 = OpVariable %19 Output\n"
"%21 = OpConstant %15 4\n"
"%22 = OpTypePointer Output %15\n"
"%24 = OpConstant %6 1\n"
"%26 = OpConstant %16 4\n"
"%27 = OpTypeArray %15 %26\n"
"%28 = OpTypePointer Output %27\n"
"%29 = OpVariable %28 Output\n"
"%32 = OpConstant %6 2\n"
"%34 = OpConstant %6 3\n"
"%36 = OpTypeVector %15 4\n"
"%37 = OpTypeArray %36 %26\n"
"%38 = OpTypePointer Output %37\n"
"%color_out = OpVariable %38 Output\n"
"%41 = OpConstant %16 32\n"
"%42 = OpTypeArray %36 %41\n"
"%43 = OpTypePointer Input %42\n"
"%color_in = OpVariable %43 Input\n"
"%46 = OpTypePointer Input %36\n"
"%49 = OpTypePointer Output %36\n"
"%r_float_out = OpVariable %28 Output\n"
"%53 = OpTypeArray %15 %41\n"
"%54 = OpTypePointer Input %53\n"
"%r_float_in = OpVariable %54 Input\n"
"%57 = OpTypePointer Input %15\n"
"%61 = OpTypeVector %15 2\n"
"%62 = OpTypeArray %61 %26\n"
"%63 = OpTypePointer Output %62\n"
"%rg_float_out = OpVariable %63 Output\n"
"%66 = OpTypeArray %61 %41\n"
"%67 = OpTypePointer Input %66\n"
"%rg_float_in = OpVariable %67 Input\n"
"%70 = OpTypePointer Input %61\n"
"%73 = OpTypePointer Output %61\n"
"%75 = OpTypeVector %15 3\n"
"%76 = OpTypeArray %75 %26\n"
"%77 = OpTypePointer Output %76\n"
"%rgb_float_out = OpVariable %77 Output\n"
"%80 = OpTypeArray %75 %41\n"
"%81 = OpTypePointer Input %80\n"
"%rgb_float_in = OpVariable %81 Input\n"
"%84 = OpTypePointer Input %75\n"
"%87 = OpTypePointer Output %75\n"
"%rgba_float_out = OpVariable %38 Output\n"
"%rgba_float_in = OpVariable %43 Input\n"
"%96 = OpConstant %16 1\n"
"%97 = OpTypeArray %15 %96\n"
"%98 = OpTypeStruct %36 %15 %97 %97\n"
"%99 = OpTypeArray %98 %26\n"
"%100 = OpTypePointer Output %99\n"
"%101 = OpVariable %100 Output\n"
"%103 = OpTypeStruct %36 %15 %97 %97\n"
"%104 = OpTypeArray %103 %41\n"
"%105 = OpTypePointer Input %104\n"
"%106 = OpVariable %105 Input\n"
"%4 = OpFunction %2 None %3\n"
"%5 = OpLabel\n"
"%9 = OpLoad %6 %8\n"
"%12 = OpIEqual %11 %9 %10\n"
"OpSelectionMerge %14 None\n"
"OpBranchConditional %12 %13 %14\n"
"%13 = OpLabel\n"
"%23 = OpAccessChain %22 %20 %10\n"
"OpStore %23 %21\n"
"%25 = OpAccessChain %22 %20 %24\n"
"OpStore %25 %21\n"
"%30 = OpAccessChain %22 %29 %10\n"
"OpStore %30 %21\n"
"%31 = OpAccessChain %22 %29 %24\n"
"OpStore %31 %21\n"
"%33 = OpAccessChain %22 %29 %32\n"
"OpStore %33 %21\n"
"%35 = OpAccessChain %22 %29 %34\n"
"OpStore %35 %21\n"
"OpBranch %14\n"
"%14 = OpLabel\n"
"%40 = OpLoad %6 %8\n"
"%45 = OpLoad %6 %8\n"
"%47 = OpAccessChain %46 %color_in %45\n"
"%48 = OpLoad %36 %47\n"
"%50 = OpAccessChain %49 %color_out %40\n"
"OpStore %50 %48\n"
"%52 = OpLoad %6 %8\n"
"%56 = OpLoad %6 %8\n"
"%58 = OpAccessChain %57 %r_float_in %56\n"
"%59 = OpLoad %15 %58\n"
"%60 = OpAccessChain %22 %r_float_out %52\n"
"OpStore %60 %59\n"
"%65 = OpLoad %6 %8\n"
"%69 = OpLoad %6 %8\n"
"%71 = OpAccessChain %70 %rg_float_in %69\n"
"%72 = OpLoad %61 %71\n"
"%74 = OpAccessChain %73 %rg_float_out %65\n"
"OpStore %74 %72\n"
"%79 = OpLoad %6 %8\n"
"%83 = OpLoad %6 %8\n"
"%85 = OpAccessChain %84 %rgb_float_in %83\n"
"%86 = OpLoad %75 %85\n"
"%88 = OpAccessChain %87 %rgb_float_out %79\n"
"OpStore %88 %86\n"
"%90 = OpLoad %6 %8\n"
"%92 = OpLoad %6 %8\n"
"%93 = OpAccessChain %46 %rgba_float_in %92\n"
"%94 = OpLoad %36 %93\n"
"%95 = OpAccessChain %49 %rgba_float_out %90\n"
"OpStore %95 %94\n"
"%102 = OpLoad %6 %8\n"
"%107 = OpLoad %6 %8\n"
"%108 = OpAccessChain %46 %106 %107 %10\n"
"%109 = OpLoad %36 %108\n"
"%110 = OpAccessChain %49 %101 %102 %10\n"
"OpStore %110 %109\n"
"OpReturn\n"
"OpFunctionEnd\n";
/*#version 450
#extension GL_EXT_tessellation_shader : require
layout( quads, equal_spacing, ccw ) in;
layout(location = 0) in vec4 in_color[];
layout(location = 1) in float r_float_in[];
layout(location = 2) in vec2 rg_float_in[];
layout(location = 3) in vec3 rgb_float_in[];
layout(location = 4) in vec4 rgba_float_in[];
layout(location = 0) out vec4 out_color;
layout(location = 1) out float r_float_out;
layout(location = 2) out vec2 rg_float_out;
layout(location = 3) out vec3 rgb_float_out;
layout(location = 4) out vec4 rgba_float_out;
void main (void)
{
const float u = gl_TessCoord.x;
const float v = gl_TessCoord.y;
const float w = gl_TessCoord.z;
out_color = (1 - u) * (1 - v) * in_color[0] +(1 - u) * v * in_color[1] + u * (1 - v) * in_color[2] + u * v * in_color[3];
r_float_out = (1 - u) * (1 - v) * r_float_in[0] +(1 - u) * v * r_float_in[1] + u * (1 - v) * r_float_in[2] + u * v * r_float_in[3];
rg_float_out = (1 - u) * (1 - v) * rg_float_in[0] +(1 - u) * v * rg_float_in[1] + u * (1 - v) * rg_float_in[2] + u * v * rg_float_in[3];
rgb_float_out = (1 - u) * (1 - v) * rgb_float_in[0] +(1 - u) * v * rgb_float_in[1] + u * (1 - v) * rgb_float_in[2] + u * v * rgb_float_in[3];
rgba_float_out = (1 - u) * (1 - v) * rgba_float_in[0] +(1 - u) * v * rgba_float_in[1] + u * (1 - v) * rgba_float_in[2] + u * v * rgba_float_in[3];
gl_Position = (1 - u) * (1 - v) * gl_in[0].gl_Position +(1 - u) * v * gl_in[1].gl_Position + u * (1 - v) * gl_in[2].gl_Position + u * v * gl_in[3].gl_Position;
}*/
const string tessellationEvaluationSource =
"; SPIR-V\n"
"; Version: 1.3\n"
"; Generator: Khronos Glslang Reference Front End; 2\n"
"; Bound: 253\n"
"; Schema: 0\n"
"OpCapability Tessellation\n"
"%1 = OpExtInstImport \"GLSL.std.450\"\n"
"OpMemoryModel Logical GLSL450\n"
"OpEntryPoint TessellationEvaluation %4 \"main\" %11 %color_out %color_in %r_float_out %r_float_in %rg_float_out %rg_float_in %rgb_float_out %rgb_float_in %rgba_float_out %rgba_float_in %216 %225\n"
"OpExecutionMode %4 Quads\n"
"OpExecutionMode %4 SpacingEqual\n"
"OpExecutionMode %4 VertexOrderCcw\n"
"OpDecorate %11 BuiltIn TessCoord\n"
"OpDecorate %color_out Location 0\n"
"OpDecorate %color_in Location 0\n"
"OpDecorate %r_float_out Location 1\n"
"OpDecorate %r_float_in Location 1\n"
"OpDecorate %rg_float_out Location 2\n"
"OpDecorate %rg_float_in Location 2\n"
"OpDecorate %rgb_float_out Location 3\n"
"OpDecorate %rgb_float_in Location 3\n"
"OpDecorate %rgba_float_out Location 4\n"
"OpDecorate %rgba_float_in Location 4\n"
+decorations[0].others+
"OpMemberDecorate %214 0 BuiltIn Position\n"
"OpMemberDecorate %214 1 BuiltIn PointSize\n"
"OpMemberDecorate %214 2 BuiltIn ClipDistance\n"
"OpMemberDecorate %214 3 BuiltIn CullDistance\n"
"OpDecorate %214 Block\n"
"OpMemberDecorate %222 0 BuiltIn Position\n"
"OpMemberDecorate %222 1 BuiltIn PointSize\n"
"OpMemberDecorate %222 2 BuiltIn ClipDistance\n"
"OpMemberDecorate %222 3 BuiltIn CullDistance\n"
"OpDecorate %222 Block\n"
"%2 = OpTypeVoid\n"
"%3 = OpTypeFunction %2\n"
"%6 = OpTypeFloat 32\n"
"%7 = OpTypePointer Function %6\n"
"%9 = OpTypeVector %6 3\n"
"%10 = OpTypePointer Input %9\n"
"%11 = OpVariable %10 Input\n"
"%12 = OpTypeInt 32 0\n"
"%13 = OpConstant %12 0\n"
"%14 = OpTypePointer Input %6\n"
"%18 = OpConstant %12 1\n"
"%22 = OpConstant %12 2\n"
"%25 = OpTypeVector %6 4\n"
"%26 = OpTypePointer Output %25\n"
"%color_out = OpVariable %26 Output\n"
"%28 = OpConstant %6 1\n"
"%34 = OpConstant %12 32\n"
"%35 = OpTypeArray %25 %34\n"
"%36 = OpTypePointer Input %35\n"
"%color_in = OpVariable %36 Input\n"
"%38 = OpTypeInt 32 1\n"
"%39 = OpConstant %38 0\n"
"%40 = OpTypePointer Input %25\n"
"%48 = OpConstant %38 1\n"
"%57 = OpConstant %38 2\n"
"%65 = OpConstant %38 3\n"
"%70 = OpTypePointer Output %6\n"
"%r_float_out = OpVariable %70 Output\n"
"%77 = OpTypeArray %6 %34\n"
"%78 = OpTypePointer Input %77\n"
"%r_float_in = OpVariable %78 Input\n"
"%106 = OpTypeVector %6 2\n"
"%107 = OpTypePointer Output %106\n"
"%rg_float_out = OpVariable %107 Output\n"
"%114 = OpTypeArray %106 %34\n"
"%115 = OpTypePointer Input %114\n"
"%rg_float_in = OpVariable %115 Input\n"
"%117 = OpTypePointer Input %106\n"
"%144 = OpTypePointer Output %9\n"
"%rgb_float_out = OpVariable %144 Output\n"
"%151 = OpTypeArray %9 %34\n"
"%152 = OpTypePointer Input %151\n"
"%rgb_float_in = OpVariable %152 Input\n"
"%rgba_float_out = OpVariable %26 Output\n"
"%rgba_float_in = OpVariable %36 Input\n"
"%213 = OpTypeArray %6 %18\n"
"%214 = OpTypeStruct %25 %6 %213 %213\n"
"%215 = OpTypePointer Output %214\n"
"%216 = OpVariable %215 Output\n"
"%222 = OpTypeStruct %25 %6 %213 %213\n"
"%223 = OpTypeArray %222 %34\n"
"%224 = OpTypePointer Input %223\n"
"%225 = OpVariable %224 Input\n"
"%4 = OpFunction %2 None %3\n"
"%5 = OpLabel\n"
"%8 = OpVariable %7 Function\n"
"%17 = OpVariable %7 Function\n"
"%21 = OpVariable %7 Function\n"
"%15 = OpAccessChain %14 %11 %13\n"
"%16 = OpLoad %6 %15\n"
"OpStore %8 %16\n"
"%19 = OpAccessChain %14 %11 %18\n"
"%20 = OpLoad %6 %19\n"
"OpStore %17 %20\n"
"%23 = OpAccessChain %14 %11 %22\n"
"%24 = OpLoad %6 %23\n"
"OpStore %21 %24\n"
"%29 = OpLoad %6 %8\n"
"%30 = OpFSub %6 %28 %29\n"
"%31 = OpLoad %6 %17\n"
"%32 = OpFSub %6 %28 %31\n"
"%33 = OpFMul %6 %30 %32\n"
"%41 = OpAccessChain %40 %color_in %39\n"
"%42 = OpLoad %25 %41\n"
"%43 = OpVectorTimesScalar %25 %42 %33\n"
"%44 = OpLoad %6 %8\n"
"%45 = OpFSub %6 %28 %44\n"
"%46 = OpLoad %6 %17\n"
"%47 = OpFMul %6 %45 %46\n"
"%49 = OpAccessChain %40 %color_in %48\n"
"%50 = OpLoad %25 %49\n"
"%51 = OpVectorTimesScalar %25 %50 %47\n"
"%52 = OpFAdd %25 %43 %51\n"
"%53 = OpLoad %6 %8\n"
"%54 = OpLoad %6 %17\n"
"%55 = OpFSub %6 %28 %54\n"
"%56 = OpFMul %6 %53 %55\n"
"%58 = OpAccessChain %40 %color_in %57\n"
"%59 = OpLoad %25 %58\n"
"%60 = OpVectorTimesScalar %25 %59 %56\n"
"%61 = OpFAdd %25 %52 %60\n"
"%62 = OpLoad %6 %8\n"
"%63 = OpLoad %6 %17\n"
"%64 = OpFMul %6 %62 %63\n"
"%66 = OpAccessChain %40 %color_in %65\n"
"%67 = OpLoad %25 %66\n"
"%68 = OpVectorTimesScalar %25 %67 %64\n"
"%69 = OpFAdd %25 %61 %68\n"
"OpStore %color_out %69\n"
"%72 = OpLoad %6 %8\n"
"%73 = OpFSub %6 %28 %72\n"
"%74 = OpLoad %6 %17\n"
"%75 = OpFSub %6 %28 %74\n"
"%76 = OpFMul %6 %73 %75\n"
"%80 = OpAccessChain %14 %r_float_in %39\n"
"%81 = OpLoad %6 %80\n"
"%82 = OpFMul %6 %76 %81\n"
"%83 = OpLoad %6 %8\n"
"%84 = OpFSub %6 %28 %83\n"
"%85 = OpLoad %6 %17\n"
"%86 = OpFMul %6 %84 %85\n"
"%87 = OpAccessChain %14 %r_float_in %48\n"
"%88 = OpLoad %6 %87\n"
"%89 = OpFMul %6 %86 %88\n"
"%90 = OpFAdd %6 %82 %89\n"
"%91 = OpLoad %6 %8\n"
"%92 = OpLoad %6 %17\n"
"%93 = OpFSub %6 %28 %92\n"
"%94 = OpFMul %6 %91 %93\n"
"%95 = OpAccessChain %14 %r_float_in %57\n"
"%96 = OpLoad %6 %95\n"
"%97 = OpFMul %6 %94 %96\n"
"%98 = OpFAdd %6 %90 %97\n"
"%99 = OpLoad %6 %8\n"
"%100 = OpLoad %6 %17\n"
"%101 = OpFMul %6 %99 %100\n"
"%102 = OpAccessChain %14 %r_float_in %65\n"
"%103 = OpLoad %6 %102\n"
"%104 = OpFMul %6 %101 %103\n"
"%105 = OpFAdd %6 %98 %104\n"
"OpStore %r_float_out %105\n"
"%109 = OpLoad %6 %8\n"
"%110 = OpFSub %6 %28 %109\n"
"%111 = OpLoad %6 %17\n"
"%112 = OpFSub %6 %28 %111\n"
"%113 = OpFMul %6 %110 %112\n"
"%118 = OpAccessChain %117 %rg_float_in %39\n"
"%119 = OpLoad %106 %118\n"
"%120 = OpVectorTimesScalar %106 %119 %113\n"
"%121 = OpLoad %6 %8\n"
"%122 = OpFSub %6 %28 %121\n"
"%123 = OpLoad %6 %17\n"
"%124 = OpFMul %6 %122 %123\n"
"%125 = OpAccessChain %117 %rg_float_in %48\n"
"%126 = OpLoad %106 %125\n"
"%127 = OpVectorTimesScalar %106 %126 %124\n"
"%128 = OpFAdd %106 %120 %127\n"
"%129 = OpLoad %6 %8\n"
"%130 = OpLoad %6 %17\n"
"%131 = OpFSub %6 %28 %130\n"
"%132 = OpFMul %6 %129 %131\n"
"%133 = OpAccessChain %117 %rg_float_in %57\n"
"%134 = OpLoad %106 %133\n"
"%135 = OpVectorTimesScalar %106 %134 %132\n"
"%136 = OpFAdd %106 %128 %135\n"
"%137 = OpLoad %6 %8\n"
"%138 = OpLoad %6 %17\n"
"%139 = OpFMul %6 %137 %138\n"
"%140 = OpAccessChain %117 %rg_float_in %65\n"
"%141 = OpLoad %106 %140\n"
"%142 = OpVectorTimesScalar %106 %141 %139\n"
"%143 = OpFAdd %106 %136 %142\n"
"OpStore %rg_float_out %143\n"
"%146 = OpLoad %6 %8\n"
"%147 = OpFSub %6 %28 %146\n"
"%148 = OpLoad %6 %17\n"
"%149 = OpFSub %6 %28 %148\n"
"%150 = OpFMul %6 %147 %149\n"
"%154 = OpAccessChain %10 %rgb_float_in %39\n"
"%155 = OpLoad %9 %154\n"
"%156 = OpVectorTimesScalar %9 %155 %150\n"
"%157 = OpLoad %6 %8\n"
"%158 = OpFSub %6 %28 %157\n"
"%159 = OpLoad %6 %17\n"
"%160 = OpFMul %6 %158 %159\n"
"%161 = OpAccessChain %10 %rgb_float_in %48\n"
"%162 = OpLoad %9 %161\n"
"%163 = OpVectorTimesScalar %9 %162 %160\n"
"%164 = OpFAdd %9 %156 %163\n"
"%165 = OpLoad %6 %8\n"
"%166 = OpLoad %6 %17\n"
"%167 = OpFSub %6 %28 %166\n"
"%168 = OpFMul %6 %165 %167\n"
"%169 = OpAccessChain %10 %rgb_float_in %57\n"
"%170 = OpLoad %9 %169\n"
"%171 = OpVectorTimesScalar %9 %170 %168\n"
"%172 = OpFAdd %9 %164 %171\n"
"%173 = OpLoad %6 %8\n"
"%174 = OpLoad %6 %17\n"
"%175 = OpFMul %6 %173 %174\n"
"%176 = OpAccessChain %10 %rgb_float_in %65\n"
"%177 = OpLoad %9 %176\n"
"%178 = OpVectorTimesScalar %9 %177 %175\n"
"%179 = OpFAdd %9 %172 %178\n"
"OpStore %rgb_float_out %179\n"
"%181 = OpLoad %6 %8\n"
"%182 = OpFSub %6 %28 %181\n"
"%183 = OpLoad %6 %17\n"
"%184 = OpFSub %6 %28 %183\n"
"%185 = OpFMul %6 %182 %184\n"
"%187 = OpAccessChain %40 %rgba_float_in %39\n"
"%188 = OpLoad %25 %187\n"
"%189 = OpVectorTimesScalar %25 %188 %185\n"
"%190 = OpLoad %6 %8\n"
"%191 = OpFSub %6 %28 %190\n"
"%192 = OpLoad %6 %17\n"
"%193 = OpFMul %6 %191 %192\n"
"%194 = OpAccessChain %40 %rgba_float_in %48\n"
"%195 = OpLoad %25 %194\n"
"%196 = OpVectorTimesScalar %25 %195 %193\n"
"%197 = OpFAdd %25 %189 %196\n"
"%198 = OpLoad %6 %8\n"
"%199 = OpLoad %6 %17\n"
"%200 = OpFSub %6 %28 %199\n"
"%201 = OpFMul %6 %198 %200\n"
"%202 = OpAccessChain %40 %rgba_float_in %57\n"
"%203 = OpLoad %25 %202\n"
"%204 = OpVectorTimesScalar %25 %203 %201\n"
"%205 = OpFAdd %25 %197 %204\n"
"%206 = OpLoad %6 %8\n"
"%207 = OpLoad %6 %17\n"
"%208 = OpFMul %6 %206 %207\n"
"%209 = OpAccessChain %40 %rgba_float_in %65\n"
"%210 = OpLoad %25 %209\n"
"%211 = OpVectorTimesScalar %25 %210 %208\n"
"%212 = OpFAdd %25 %205 %211\n"
"OpStore %rgba_float_out %212\n"
"%217 = OpLoad %6 %8\n"
"%218 = OpFSub %6 %28 %217\n"
"%219 = OpLoad %6 %17\n"
"%220 = OpFSub %6 %28 %219\n"
"%221 = OpFMul %6 %218 %220\n"
"%226 = OpAccessChain %40 %225 %39 %39\n"
"%227 = OpLoad %25 %226\n"
"%228 = OpVectorTimesScalar %25 %227 %221\n"
"%229 = OpLoad %6 %8\n"
"%230 = OpFSub %6 %28 %229\n"
"%231 = OpLoad %6 %17\n"
"%232 = OpFMul %6 %230 %231\n"
"%233 = OpAccessChain %40 %225 %48 %39\n"
"%234 = OpLoad %25 %233\n"
"%235 = OpVectorTimesScalar %25 %234 %232\n"
"%236 = OpFAdd %25 %228 %235\n"
"%237 = OpLoad %6 %8\n"
"%238 = OpLoad %6 %17\n"
"%239 = OpFSub %6 %28 %238\n"
"%240 = OpFMul %6 %237 %239\n"
"%241 = OpAccessChain %40 %225 %57 %39\n"
"%242 = OpLoad %25 %241\n"
"%243 = OpVectorTimesScalar %25 %242 %240\n"
"%244 = OpFAdd %25 %236 %243\n"
"%245 = OpLoad %6 %8\n"
"%246 = OpLoad %6 %17\n"
"%247 = OpFMul %6 %245 %246\n"
"%248 = OpAccessChain %40 %225 %65 %39\n"
"%249 = OpLoad %25 %248\n"
"%250 = OpVectorTimesScalar %25 %249 %247\n"
"%251 = OpFAdd %25 %244 %250\n"
"%252 = OpAccessChain %26 %216 %39\n"
"OpStore %252 %251\n"
"OpReturn\n"
"OpFunctionEnd\n";
programCollection.spirvAsmSources.add("tessellation_control") << tessellationControlSource;
programCollection.spirvAsmSources.add("tessellation_evaluation") << tessellationEvaluationSource;
}
{
/*#version 450
layout(triangles) in;
layout(triangle_strip, max_vertices = 3) out;
layout(location = 0) in vec4 in_color[];
layout(location = 1) in float r_float_in[];
layout(location = 2) in vec2 rg_float_in[];
layout(location = 3) in vec3 rgb_float_in[];
layout(location = 4) in vec4 rgba_float_in[];
layout(location = 0) out vec4 out_color;
layout(location = 1) out float r_float_out;
layout(location = 2) out vec2 rg_float_out;
layout(location = 3) out vec3 rgb_float_out;
layout(location = 4) out vec4 rgba_float_out;
void main (void)
{
out_color = in_color[0];
r_float_out = r_float_in[0];
rg_float_out = rg_float_in[0];
rgb_float_out = rgb_float_in[0];
rgba_float_out = rgba_float_in[0];
gl_Position = gl_in[0].gl_Position;
EmitVertex();
out_color = in_color[1];
r_float_out = r_float_in[1];
rg_float_out = rg_float_in[1];
rgb_float_out = rgb_float_in[1];
rgba_float_out = rgba_float_in[1];
gl_Position = gl_in[1].gl_Position;
EmitVertex();
out_color = in_color[2];
r_float_out = r_float_in[2];
rg_float_out = rg_float_in[2];
rgb_float_out = rgb_float_in[2];
rgba_float_out = rgba_float_in[2];
gl_Position = gl_in[2].gl_Position;
EmitVertex();
EndPrimitive();
}
*/
const string geometrySource =
"; SPIR-V\n"
"; Version: 1.3\n"
"; Generator: Khronos Glslang Reference Front End; 2\n"
"; Bound: 90\n"
"; Schema: 0\n"
"OpCapability Geometry\n"
"%1 = OpExtInstImport \"GLSL.std.450\"\n"
"OpMemoryModel Logical GLSL450\n"
"OpEntryPoint Geometry %4 \"main\" %color_out %color_in %r_float_out %r_float_in %rg_float_out %rg_float_in %rgb_float_out %rgb_float_in %rgba_float_out %rgba_float_in %54 %58\n"
"OpExecutionMode %4 Triangles\n"
"OpExecutionMode %4 Invocations 1\n"
"OpExecutionMode %4 OutputTriangleStrip\n"
"OpExecutionMode %4 OutputVertices 3\n"
"OpDecorate %color_out Location 0\n"
"OpDecorate %color_in Location 0\n"
"OpDecorate %r_float_out Location 1\n"
"OpDecorate %r_float_in Location 1\n"
"OpDecorate %rg_float_out Location 2\n"
"OpDecorate %rg_float_in Location 2\n"
"OpDecorate %rgb_float_out Location 3\n"
"OpDecorate %rgb_float_in Location 3\n"
"OpDecorate %rgba_float_out Location 4\n"
"OpDecorate %rgba_float_in Location 4\n"
+decorations[0].others+
"OpMemberDecorate %52 0 BuiltIn Position\n"
"OpMemberDecorate %52 1 BuiltIn PointSize\n"
"OpMemberDecorate %52 2 BuiltIn ClipDistance\n"
"OpMemberDecorate %52 3 BuiltIn CullDistance\n"
"OpDecorate %52 Block\n"
"OpMemberDecorate %55 0 BuiltIn Position\n"
"OpMemberDecorate %55 1 BuiltIn PointSize\n"
"OpMemberDecorate %55 2 BuiltIn ClipDistance\n"
"OpMemberDecorate %55 3 BuiltIn CullDistance\n"
"OpDecorate %55 Block\n"
"%2 = OpTypeVoid\n"
"%3 = OpTypeFunction %2\n"
"%6 = OpTypeFloat 32\n"
"%7 = OpTypeVector %6 4\n"
"%8 = OpTypePointer Output %7\n"
"%color_out = OpVariable %8 Output\n"
"%10 = OpTypeInt 32 0\n"
"%11 = OpConstant %10 3\n"
"%12 = OpTypeArray %7 %11\n"
"%13 = OpTypePointer Input %12\n"
"%color_in = OpVariable %13 Input\n"
"%15 = OpTypeInt 32 1\n"
"%16 = OpConstant %15 0\n"
"%17 = OpTypePointer Input %7\n"
"%20 = OpTypePointer Output %6\n"
"%r_float_out = OpVariable %20 Output\n"
"%22 = OpTypeArray %6 %11\n"
"%23 = OpTypePointer Input %22\n"
"%r_float_in = OpVariable %23 Input\n"
"%25 = OpTypePointer Input %6\n"
"%28 = OpTypeVector %6 2\n"
"%29 = OpTypePointer Output %28\n"
"%rg_float_out = OpVariable %29 Output\n"
"%31 = OpTypeArray %28 %11\n"
"%32 = OpTypePointer Input %31\n"
"%rg_float_in = OpVariable %32 Input\n"
"%34 = OpTypePointer Input %28\n"
"%37 = OpTypeVector %6 3\n"
"%38 = OpTypePointer Output %37\n"
"%rgb_float_out = OpVariable %38 Output\n"
"%40 = OpTypeArray %37 %11\n"
"%41 = OpTypePointer Input %40\n"
"%rgb_float_in = OpVariable %41 Input\n"
"%43 = OpTypePointer Input %37\n"
"%rgba_float_out = OpVariable %8 Output\n"
"%rgba_float_in = OpVariable %13 Input\n"
"%50 = OpConstant %10 1\n"
"%51 = OpTypeArray %6 %50\n"
"%52 = OpTypeStruct %7 %6 %51 %51\n"
"%53 = OpTypePointer Output %52\n"
"%54 = OpVariable %53 Output\n"
"%55 = OpTypeStruct %7 %6 %51 %51\n"
"%56 = OpTypeArray %55 %11\n"
"%57 = OpTypePointer Input %56\n"
"%58 = OpVariable %57 Input\n"
"%62 = OpConstant %15 1\n"
"%76 = OpConstant %15 2\n"
"%4 = OpFunction %2 None %3\n"
"%5 = OpLabel\n"
"%18 = OpAccessChain %17 %color_in %16\n"
"%19 = OpLoad %7 %18\n"
"OpStore %color_out %19\n"
"%26 = OpAccessChain %25 %r_float_in %16\n"
"%27 = OpLoad %6 %26\n"
"OpStore %r_float_out %27\n"
"%35 = OpAccessChain %34 %rg_float_in %16\n"
"%36 = OpLoad %28 %35\n"
"OpStore %rg_float_out %36\n"
"%44 = OpAccessChain %43 %rgb_float_in %16\n"
"%45 = OpLoad %37 %44\n"
"OpStore %rgb_float_out %45\n"
"%48 = OpAccessChain %17 %rgba_float_in %16\n"
"%49 = OpLoad %7 %48\n"
"OpStore %rgba_float_out %49\n"
"%59 = OpAccessChain %17 %58 %16 %16\n"
"%60 = OpLoad %7 %59\n"
"%61 = OpAccessChain %8 %54 %16\n"
"OpStore %61 %60\n"
"OpEmitVertex\n"
"%63 = OpAccessChain %17 %color_in %62\n"
"%64 = OpLoad %7 %63\n"
"OpStore %color_out %64\n"
"%65 = OpAccessChain %25 %r_float_in %62\n"
"%66 = OpLoad %6 %65\n"
"OpStore %r_float_out %66\n"
"%67 = OpAccessChain %34 %rg_float_in %62\n"
"%68 = OpLoad %28 %67\n"
"OpStore %rg_float_out %68\n"
"%69 = OpAccessChain %43 %rgb_float_in %62\n"
"%70 = OpLoad %37 %69\n"
"OpStore %rgb_float_out %70\n"
"%71 = OpAccessChain %17 %rgba_float_in %62\n"
"%72 = OpLoad %7 %71\n"
"OpStore %rgba_float_out %72\n"
"%73 = OpAccessChain %17 %58 %62 %16\n"
"%74 = OpLoad %7 %73\n"
"%75 = OpAccessChain %8 %54 %16\n"
"OpStore %75 %74\n"
"OpEmitVertex\n"
"%77 = OpAccessChain %17 %color_in %76\n"
"%78 = OpLoad %7 %77\n"
"OpStore %color_out %78\n"
"%79 = OpAccessChain %25 %r_float_in %76\n"
"%80 = OpLoad %6 %79\n"
"OpStore %r_float_out %80\n"
"%81 = OpAccessChain %34 %rg_float_in %76\n"
"%82 = OpLoad %28 %81\n"
"OpStore %rg_float_out %82\n"
"%83 = OpAccessChain %43 %rgb_float_in %76\n"
"%84 = OpLoad %37 %83\n"
"OpStore %rgb_float_out %84\n"
"%85 = OpAccessChain %17 %rgba_float_in %76\n"
"%86 = OpLoad %7 %85\n"
"OpStore %rgba_float_out %86\n"
"%87 = OpAccessChain %17 %58 %76 %16\n"
"%88 = OpLoad %7 %87\n"
"%89 = OpAccessChain %8 %54 %16\n"
"OpStore %89 %88\n"
"OpEmitVertex\n"
"OpEndPrimitive\n"
"OpReturn\n"
"OpFunctionEnd\n";
programCollection.spirvAsmSources.add("geometry") << geometrySource;
}
}
class CrossStageInterfaceTestsCase : public vkt::TestCase
{
public:
CrossStageInterfaceTestsCase (tcu::TestContext &context, const char *name, const char *description, const TestParameters& parameters)
: TestCase (context, name, description)
, m_parameters (parameters)
{
}
private:
vkt::TestInstance* createInstance (vkt::Context& context) const;
void initPrograms (SourceCollections& programCollection) const;
const TestParameters m_parameters;
};
vkt::TestInstance* CrossStageInterfaceTestsCase::createInstance (vkt::Context& context) const
{
return new CrossStageTestInstance(context, m_parameters);
}
void CrossStageInterfaceTestsCase::initPrograms (SourceCollections& programCollection) const
{
vector<Decorations> decorations;
string epsilon = "6e-8";
switch(m_parameters.qualifier)
{
case TEST_TYPE_FLAT:
decorations.push_back(Decorations("",
//Vertex
"OpDecorate %color_out Flat\n"
"OpDecorate %color_in Flat\n"
"OpMemberDecorate %block_out 0 Flat\n"
"OpMemberDecorate %block_out 1 Flat\n",
""));
decorations.push_back(Decorations(//Fragment
"OpDecorate %color_in Flat\n"
"OpMemberDecorate %block_in 0 Flat\n"
"OpMemberDecorate %block_in 1 Flat\n",
"",
""));
decorations.push_back(Decorations(//Fragment
"OpDecorate %color_in Flat\n"
"OpMemberDecorate %block_in 0 Flat\n"
"OpMemberDecorate %block_in 1 Flat\n",
//Vertex
"OpDecorate %color_out Flat\n"
"OpDecorate %color_in Flat\n"
"OpMemberDecorate %block_out 0 Flat\n"
"OpMemberDecorate %block_out 1 Flat\n",
""));
epsilon = "0.0";
break;
case TEST_TYPE_NOPERSPECTIVE:
decorations.push_back(Decorations("",
//Vertex
"OpDecorate %color_out NoPerspective\n"
"OpDecorate %color_in NoPerspective\n"
"OpMemberDecorate %block_out 0 NoPerspective\n"
"OpMemberDecorate %block_out 1 NoPerspective\n",
""));
decorations.push_back(Decorations(//Fragment
"OpDecorate %color_in NoPerspective\n"
"OpMemberDecorate %block_in 0 NoPerspective\n"
"OpMemberDecorate %block_in 1 NoPerspective\n",
"",
""));
decorations.push_back(Decorations(//Fragment
"OpDecorate %color_in NoPerspective\n"
"OpMemberDecorate %block_in 0 NoPerspective\n"
"OpMemberDecorate %block_in 1 NoPerspective\n",
//Vertex
"OpDecorate %color_out NoPerspective\n"
"OpDecorate %color_in NoPerspective\n"
"OpMemberDecorate %block_out 0 NoPerspective\n"
"OpMemberDecorate %block_out 1 NoPerspective\n",
""));
break;
case TEST_TYPE_RELAXEDPRECISION:
decorations.push_back(Decorations(//Fragment
"OpDecorate %color_in RelaxedPrecision\n"
"OpDecorate %color_out RelaxedPrecision\n"
"OpMemberDecorate %block_in 0 RelaxedPrecision\n"
"OpMemberDecorate %block_in 1 RelaxedPrecision\n",
//Vertex
"OpDecorate %color_out RelaxedPrecision\n"
"OpDecorate %color_in RelaxedPrecision\n"
"OpMemberDecorate %block_out 0 RelaxedPrecision\n"
"OpMemberDecorate %block_out 1 RelaxedPrecision\n",
//Others
"OpDecorate %color_out RelaxedPrecision\n"
"OpDecorate %color_in RelaxedPrecision\n"
"OpMemberDecorate %block_out 0 RelaxedPrecision\n"
"OpMemberDecorate %block_out 1 RelaxedPrecision\n"
"OpMemberDecorate %block_in 0 RelaxedPrecision\n"
"OpMemberDecorate %block_in 1 RelaxedPrecision\n"));
break;
default:
DE_ASSERT(0);
}
//Spir-v spec: decoration flat can be used only in Shader (fragment or vertex)
for (deUint32 ndx = 0; ndx < decorations.size(); ++ndx)
{
/*#version 450
#version 450
layout(location = 0) in highp vec4 in_position;
layout(location = 1) in vec4 in_color;
layout(location = 0) out vec4 out_color;
layout(location = 1) out ColorData
{
vec4 colorVec;
mat2 colorMat;
} outData;
void main (void)
{
gl_Position = in_position;
out_color = in_color;
outData.colorVec = in_color;
outData.colorMat = mat2(in_color.r, in_color.g, in_color.b, in_color.a);
}
*/
const string vertexShaderSource =
"; SPIR-V\n"
"; Version: 1.3\n"
"; Generator: Khronos Glslang Reference Front End; 2\n"
"; Bound: 51\n"
"; Schema: 0\n"
"OpCapability Shader\n"
"%1 = OpExtInstImport \"GLSL.std.450\"\n"
"OpMemoryModel Logical GLSL450\n"
"OpEntryPoint Vertex %4 \"main\" %13 %17 %color_out %color_in %28\n"
"OpMemberDecorate %11 0 BuiltIn Position\n"
"OpMemberDecorate %11 1 BuiltIn PointSize\n"
"OpMemberDecorate %11 2 BuiltIn ClipDistance\n"
"OpMemberDecorate %11 3 BuiltIn CullDistance\n"
"OpDecorate %11 Block\n"
"OpDecorate %17 Location 0\n"
"OpDecorate %color_out Location 0\n"
"OpDecorate %color_in Location 1\n"
"OpDecorate %block_out Block\n"
"OpDecorate %28 Location 1\n"
+decorations[ndx].vertex+
"%2 = OpTypeVoid\n"
"%3 = OpTypeFunction %2\n"
"%6 = OpTypeFloat 32\n"
"%7 = OpTypeVector %6 4\n"
"%8 = OpTypeInt 32 0\n"
"%9 = OpConstant %8 1\n"
"%10 = OpTypeArray %6 %9\n"
"%11 = OpTypeStruct %7 %6 %10 %10\n"
"%12 = OpTypePointer Output %11\n"
"%13 = OpVariable %12 Output\n"
"%14 = OpTypeInt 32 1\n"
"%15 = OpConstant %14 0\n"
"%16 = OpTypePointer Input %7\n"
"%17 = OpVariable %16 Input\n"
"%19 = OpTypePointer Output %7\n"
"%color_out = OpVariable %19 Output\n"
"%color_in = OpVariable %16 Input\n"
"%24 = OpTypeVector %6 2\n"
"%25 = OpTypeMatrix %24 2\n"
"%block_out = OpTypeStruct %7 %25\n"
"%27 = OpTypePointer Output %block_out\n"
"%28 = OpVariable %27 Output\n"
"%31 = OpConstant %14 1\n"
"%32 = OpConstant %8 0\n"
"%33 = OpTypePointer Input %6\n"
"%38 = OpConstant %8 2\n"
"%41 = OpConstant %8 3\n"
"%44 = OpConstant %6 1\n"
"%45 = OpConstant %6 0\n"
"%49 = OpTypePointer Output %25\n"
"%4 = OpFunction %2 None %3\n"
"%5 = OpLabel\n"
"%18 = OpLoad %7 %17\n"
"%20 = OpAccessChain %19 %13 %15\n"
"OpStore %20 %18\n"
"%23 = OpLoad %7 %color_in\n"
"OpStore %color_out %23\n"
"%29 = OpLoad %7 %color_in\n"
"%30 = OpAccessChain %19 %28 %15\n"
"OpStore %30 %29\n"
"%34 = OpAccessChain %33 %color_in %32\n"
"%35 = OpLoad %6 %34\n"
"%36 = OpAccessChain %33 %color_in %9\n"
"%37 = OpLoad %6 %36\n"
"%39 = OpAccessChain %33 %color_in %38\n"
"%40 = OpLoad %6 %39\n"
"%42 = OpAccessChain %33 %color_in %41\n"
"%43 = OpLoad %6 %42\n"
"%46 = OpCompositeConstruct %24 %35 %37\n"
"%47 = OpCompositeConstruct %24 %40 %43\n"
"%48 = OpCompositeConstruct %25 %46 %47\n"
"%50 = OpAccessChain %49 %28 %31\n"
"OpStore %50 %48\n"
"OpReturn\n"
"OpFunctionEnd\n";
/* #version 450
layout(location = 0) in vec4 in_color;
layout(location = 0) out vec4 out_color;
layout(location = 1) in ColorData
{
vec4 colorVec;
mat2 colorMat;
} inData;
void main()
{
float epsilon = 6e-8; // or 0.0 for flat
out_color = in_color;
if(any(greaterThan(abs(inData.colorVec - in_color), vec4(epsilon))))
out_color.rgba = vec4(1.0f);
if(abs(inData.colorMat[0][0] - in_color.r) > epsilon)
out_color.rgba = vec4(1.0f);
if(abs(inData.colorMat[1][1] - in_color.a) > epsilon)
out_color.rgba = vec4(1.0f);
}
*/
const string fragmentShaderSource =
"; SPIR-V\n"
"; Version: 1.3\n"
"; Generator: Khronos Glslang Reference Front End; 2\n"
"; Bound: 51\n"
"; Schema: 0\n"
"OpCapability Shader\n"
"%1 = OpExtInstImport \"GLSL.std.450\"\n"
"OpMemoryModel Logical GLSL450\n"
"OpEntryPoint Fragment %4 \"main\" %color_out %color_in %17\n"
"OpExecutionMode %4 OriginUpperLeft\n"
"OpDecorate %color_out Location 0\n"
"OpDecorate %color_in Location 0\n"
"OpDecorate %block_in Block\n"
"OpDecorate %17 Location 1\n"
+decorations[ndx].fragment+
"%2 = OpTypeVoid\n"
"%3 = OpTypeFunction %2\n"
"%6 = OpTypeFloat 32\n"
"%7 = OpTypeVector %6 4\n"
"%8 = OpTypePointer Output %7\n"
"%color_out = OpVariable %8 Output\n"
"%10 = OpTypePointer Input %7\n"
"%color_in = OpVariable %10 Input\n"
"%13 = OpTypeVector %6 2\n"
"%14 = OpTypeMatrix %13 2\n"
"%block_in = OpTypeStruct %7 %14\n"
"%16 = OpTypePointer Input %block_in\n"
"%17 = OpVariable %16 Input\n"
"%18 = OpTypeInt 32 1\n"
"%19 = OpConstant %18 0\n"
"%23 = OpTypeBool\n"
"%24 = OpTypeVector %23 4\n"
"%ep = OpConstant %6 " + epsilon + "\n"
"%ep4 = OpConstantComposite %7 %ep %ep %ep %ep\n"
"%29 = OpConstant %6 1\n"
"%30 = OpConstantComposite %7 %29 %29 %29 %29\n"
"%31 = OpConstant %18 1\n"
"%32 = OpTypeInt 32 0\n"
"%33 = OpConstant %32 0\n"
"%34 = OpTypePointer Input %6\n"
"%42 = OpConstant %32 1\n"
"%45 = OpConstant %32 3\n"
"%4 = OpFunction %2 None %3\n"
"%5 = OpLabel\n"
"%12 = OpLoad %7 %color_in\n"
"OpStore %color_out %12\n"
"%20 = OpAccessChain %10 %17 %19\n"
"%21 = OpLoad %7 %20\n"
"%22 = OpLoad %7 %color_in\n"
"%sub4 = OpFSub %7 %21 %22\n"
"%abs4 = OpExtInst %7 %1 FAbs %sub4\n"
"%cmp4 = OpFOrdGreaterThan %24 %abs4 %ep4\n"
"%26 = OpAny %23 %cmp4\n"
"OpSelectionMerge %28 None\n"
"OpBranchConditional %26 %27 %28\n"
"%27 = OpLabel\n"
"OpStore %color_out %30\n"
"OpBranch %28\n"
"%28 = OpLabel\n"
"%35 = OpAccessChain %34 %17 %31 %19 %33\n"
"%36 = OpLoad %6 %35\n"
"%37 = OpAccessChain %34 %color_in %33\n"
"%38 = OpLoad %6 %37\n"
"%subr = OpFSub %6 %36 %38\n"
"%absr = OpExtInst %6 %1 FAbs %subr\n"
"%cmpr = OpFOrdGreaterThan %23 %absr %ep\n"
"OpSelectionMerge %41 None\n"
"OpBranchConditional %cmpr %40 %41\n"
"%40 = OpLabel\n"
"OpStore %color_out %30\n"
"OpBranch %41\n"
"%41 = OpLabel\n"
"%43 = OpAccessChain %34 %17 %31 %31 %42\n"
"%44 = OpLoad %6 %43\n"
"%46 = OpAccessChain %34 %color_in %45\n"
"%47 = OpLoad %6 %46\n"
"%suba = OpFSub %6 %44 %47\n"
"%absa = OpExtInst %6 %1 FAbs %suba\n"
"%cmpa = OpFOrdGreaterThan %23 %absa %ep\n"
"OpSelectionMerge %50 None\n"
"OpBranchConditional %cmpa %49 %50\n"
"%49 = OpLabel\n"
"OpStore %color_out %30\n"
"OpBranch %50\n"
"%50 = OpLabel\n"
"OpReturn\n"
"OpFunctionEnd\n";
std::ostringstream vertex;
vertex << "vertex" << ndx;
std::ostringstream fragment;
fragment << "fragment" << ndx;
programCollection.spirvAsmSources.add(vertex.str()) << vertexShaderSource;
programCollection.spirvAsmSources.add(fragment.str()) << fragmentShaderSource;
}
{
/*#version 450
#extension GL_EXT_tessellation_shader : require
layout(vertices = 4) out;
layout(location = 0) in vec4 in_color[];
layout(location = 1) in ColorData
{
vec4 colorVec;
mat2 colorMat;
} inData[];
layout(location = 0) out vec4 out_color[];
layout(location = 1) out ColorData
{
vec4 colorVec;
mat2 colorMat;
} outData[];
void main (void)
{
if ( gl_InvocationID == 0 )
{
gl_TessLevelInner[0] = 4.0f;
gl_TessLevelInner[1] = 4.0f;
gl_TessLevelOuter[0] = 4.0f;
gl_TessLevelOuter[1] = 4.0f;
gl_TessLevelOuter[2] = 4.0f;
gl_TessLevelOuter[3] = 4.0f;
}
out_color[gl_InvocationID] = in_color[gl_InvocationID];
outData[gl_InvocationID].colorVec = inData[gl_InvocationID].colorVec;
outData[gl_InvocationID].colorMat = inData[gl_InvocationID].colorMat;
gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position;
}*/
const string tessellationControlSource =
"; SPIR-V\n"
"; Version: 1.3\n"
"; Generator: Khronos Glslang Reference Front End; 2\n"
"; Bound: 88\n"
"; Schema: 0\n"
"OpCapability Tessellation\n"
"%1 = OpExtInstImport \"GLSL.std.450\"\n"
"OpMemoryModel Logical GLSL450\n"
"OpEntryPoint TessellationControl %4 \"main\" %8 %20 %29 %color_out %color_in %56 %61 %78 %83\n"
"OpExecutionMode %4 OutputVertices 4\n"
"OpDecorate %8 BuiltIn InvocationId\n"
"OpDecorate %20 Patch\n"
"OpDecorate %20 BuiltIn TessLevelInner\n"
"OpDecorate %29 Patch\n"
"OpDecorate %29 BuiltIn TessLevelOuter\n"
"OpDecorate %color_out Location 0\n"
"OpDecorate %color_in Location 0\n"
"OpDecorate %block_out Block\n"
"OpDecorate %56 Location 1\n"
"OpDecorate %block_in Block\n"
"OpDecorate %61 Location 1\n"
+decorations[0].others+
"OpMemberDecorate %75 0 BuiltIn Position\n"
"OpMemberDecorate %75 1 BuiltIn PointSize\n"
"OpMemberDecorate %75 2 BuiltIn ClipDistance\n"
"OpMemberDecorate %75 3 BuiltIn CullDistance\n"
"OpDecorate %75 Block\n"
"OpMemberDecorate %80 0 BuiltIn Position\n"
"OpMemberDecorate %80 1 BuiltIn PointSize\n"
"OpMemberDecorate %80 2 BuiltIn ClipDistance\n"
"OpMemberDecorate %80 3 BuiltIn CullDistance\n"
"OpDecorate %80 Block\n"
"%2 = OpTypeVoid\n"
"%3 = OpTypeFunction %2\n"
"%6 = OpTypeInt 32 1\n"
"%7 = OpTypePointer Input %6\n"
"%8 = OpVariable %7 Input\n"
"%10 = OpConstant %6 0\n"
"%11 = OpTypeBool\n"
"%15 = OpTypeFloat 32\n"
"%16 = OpTypeInt 32 0\n"
"%17 = OpConstant %16 2\n"
"%18 = OpTypeArray %15 %17\n"
"%19 = OpTypePointer Output %18\n"
"%20 = OpVariable %19 Output\n"
"%21 = OpConstant %15 4\n"
"%22 = OpTypePointer Output %15\n"
"%24 = OpConstant %6 1\n"
"%26 = OpConstant %16 4\n"
"%27 = OpTypeArray %15 %26\n"
"%28 = OpTypePointer Output %27\n"
"%29 = OpVariable %28 Output\n"
"%32 = OpConstant %6 2\n"
"%34 = OpConstant %6 3\n"
"%36 = OpTypeVector %15 4\n"
"%37 = OpTypeArray %36 %26\n"
"%38 = OpTypePointer Output %37\n"
"%color_out = OpVariable %38 Output\n"
"%41 = OpConstant %16 32\n"
"%42 = OpTypeArray %36 %41\n"
"%43 = OpTypePointer Input %42\n"
"%color_in = OpVariable %43 Input\n"
"%46 = OpTypePointer Input %36\n"
"%49 = OpTypePointer Output %36\n"
"%51 = OpTypeVector %15 2\n"
"%52 = OpTypeMatrix %51 2\n"
"%block_out = OpTypeStruct %36 %52\n"
"%54 = OpTypeArray %block_out %26\n"
"%55 = OpTypePointer Output %54\n"
"%56 = OpVariable %55 Output\n"
"%block_in = OpTypeStruct %36 %52\n"
"%59 = OpTypeArray %block_in %41\n"
"%60 = OpTypePointer Input %59\n"
"%61 = OpVariable %60 Input\n"
"%68 = OpTypePointer Input %52\n"
"%71 = OpTypePointer Output %52\n"
"%73 = OpConstant %16 1\n"
"%74 = OpTypeArray %15 %73\n"
"%75 = OpTypeStruct %36 %15 %74 %74\n"
"%76 = OpTypeArray %75 %26\n"
"%77 = OpTypePointer Output %76\n"
"%78 = OpVariable %77 Output\n"
"%80 = OpTypeStruct %36 %15 %74 %74\n"
"%81 = OpTypeArray %80 %41\n"
"%82 = OpTypePointer Input %81\n"
"%83 = OpVariable %82 Input\n"
"%4 = OpFunction %2 None %3\n"
"%5 = OpLabel\n"
"%9 = OpLoad %6 %8\n"
"%12 = OpIEqual %11 %9 %10\n"
"OpSelectionMerge %14 None\n"
"OpBranchConditional %12 %13 %14\n"
"%13 = OpLabel\n"
"%23 = OpAccessChain %22 %20 %10\n"
"OpStore %23 %21\n"
"%25 = OpAccessChain %22 %20 %24\n"
"OpStore %25 %21\n"
"%30 = OpAccessChain %22 %29 %10\n"
"OpStore %30 %21\n"
"%31 = OpAccessChain %22 %29 %24\n"
"OpStore %31 %21\n"
"%33 = OpAccessChain %22 %29 %32\n"
"OpStore %33 %21\n"
"%35 = OpAccessChain %22 %29 %34\n"
"OpStore %35 %21\n"
"OpBranch %14\n"
"%14 = OpLabel\n"
"%40 = OpLoad %6 %8\n"
"%45 = OpLoad %6 %8\n"
"%47 = OpAccessChain %46 %color_in %45\n"
"%48 = OpLoad %36 %47\n"
"%50 = OpAccessChain %49 %color_out %40\n"
"OpStore %50 %48\n"
"%57 = OpLoad %6 %8\n"
"%62 = OpLoad %6 %8\n"
"%63 = OpAccessChain %46 %61 %62 %10\n"
"%64 = OpLoad %36 %63\n"
"%65 = OpAccessChain %49 %56 %57 %10\n"
"OpStore %65 %64\n"
"%66 = OpLoad %6 %8\n"
"%67 = OpLoad %6 %8\n"
"%69 = OpAccessChain %68 %61 %67 %24\n"
"%70 = OpLoad %52 %69\n"
"%72 = OpAccessChain %71 %56 %66 %24\n"
"OpStore %72 %70\n"
"%79 = OpLoad %6 %8\n"
"%84 = OpLoad %6 %8\n"
"%85 = OpAccessChain %46 %83 %84 %10\n"
"%86 = OpLoad %36 %85\n"
"%87 = OpAccessChain %49 %78 %79 %10\n"
"OpStore %87 %86\n"
"OpReturn\n"
"OpFunctionEnd\n";
/*#version 450
#extension GL_EXT_tessellation_shader : require
layout( quads, equal_spacing, ccw ) in;
layout(location = 0) in vec4 in_color[];
layout(location = 1) in ColorData
{
vec4 colorVec;
mat2 colorMat;
} inData[];
layout(location = 0) out vec4 out_color;
layout(location = 1) out ColorData
{
vec4 colorVec;
mat2 colorMat;
} outData;
void main (void)
{
const float u = gl_TessCoord.x;
const float v = gl_TessCoord.y;
const float w = gl_TessCoord.z;
out_color = (1 - u) * (1 - v) * in_color[0] +(1 - u) * v * in_color[1] + u * (1 - v) * in_color[2] + u * v * in_color[3];
outData.colorVec = (1 - u) * (1 - v) * inData[0].colorVec +(1 - u) * v * inData[1].colorVec + u * (1 - v) * inData[2].colorVec + u * v * inData[3].colorVec;
outData.colorMat = (1 - u) * (1 - v) * inData[0].colorMat +(1 - u) * v * inData[1].colorMat + u * (1 - v) * inData[2].colorMat + u * v * inData[3].colorMat;
gl_Position = (1 - u) * (1 - v) * gl_in[0].gl_Position +(1 - u) * v * gl_in[1].gl_Position + u * (1 - v) * gl_in[2].gl_Position + u * v * gl_in[3].gl_Position;
}*/
const string tessellationEvaluationSource =
"; SPIR-V\n"
"; Version: 1.3\n"
"; Generator: Khronos Glslang Reference Front End; 2\n"
"; Bound: 203\n"
"; Schema: 0\n"
"OpCapability Tessellation\n"
"%1 = OpExtInstImport \"GLSL.std.450\"\n"
"OpMemoryModel Logical GLSL450\n"
"OpEntryPoint TessellationEvaluation %4 \"main\" %11 %color_out %color_in %74 %83 %166 %175\n"
"OpExecutionMode %4 Quads\n"
"OpExecutionMode %4 SpacingEqual\n"
"OpExecutionMode %4 VertexOrderCcw\n"
"OpDecorate %11 BuiltIn TessCoord\n"
"OpDecorate %color_out Location 0\n"
"OpDecorate %color_in Location 0\n"
"OpDecorate %block_out Block\n"
"OpDecorate %74 Location 1\n"
"OpDecorate %block_in Block\n"
"OpDecorate %83 Location 1\n"
+decorations[0].others+
"OpMemberDecorate %164 0 BuiltIn Position\n"
"OpMemberDecorate %164 1 BuiltIn PointSize\n"
"OpMemberDecorate %164 2 BuiltIn ClipDistance\n"
"OpMemberDecorate %164 3 BuiltIn CullDistance\n"
"OpDecorate %164 Block\n"
"OpMemberDecorate %172 0 BuiltIn Position\n"
"OpMemberDecorate %172 1 BuiltIn PointSize\n"
"OpMemberDecorate %172 2 BuiltIn ClipDistance\n"
"OpMemberDecorate %172 3 BuiltIn CullDistance\n"
"OpDecorate %172 Block\n"
"%2 = OpTypeVoid\n"
"%3 = OpTypeFunction %2\n"
"%6 = OpTypeFloat 32\n"
"%7 = OpTypePointer Function %6\n"
"%9 = OpTypeVector %6 3\n"
"%10 = OpTypePointer Input %9\n"
"%11 = OpVariable %10 Input\n"
"%12 = OpTypeInt 32 0\n"
"%13 = OpConstant %12 0\n"
"%14 = OpTypePointer Input %6\n"
"%18 = OpConstant %12 1\n"
"%22 = OpConstant %12 2\n"
"%25 = OpTypeVector %6 4\n"
"%26 = OpTypePointer Output %25\n"
"%color_out = OpVariable %26 Output\n"
"%28 = OpConstant %6 1\n"
"%34 = OpConstant %12 32\n"
"%35 = OpTypeArray %25 %34\n"
"%36 = OpTypePointer Input %35\n"
"%color_in = OpVariable %36 Input\n"
"%38 = OpTypeInt 32 1\n"
"%39 = OpConstant %38 0\n"
"%40 = OpTypePointer Input %25\n"
"%48 = OpConstant %38 1\n"
"%57 = OpConstant %38 2\n"
"%65 = OpConstant %38 3\n"
"%70 = OpTypeVector %6 2\n"
"%71 = OpTypeMatrix %70 2\n"
"%block_out = OpTypeStruct %25 %71\n"
"%73 = OpTypePointer Output %block_out\n"
"%74 = OpVariable %73 Output\n"
"%block_in = OpTypeStruct %25 %71\n"
"%81 = OpTypeArray %block_in %34\n"
"%82 = OpTypePointer Input %81\n"
"%83 = OpVariable %82 Input\n"
"%116 = OpTypePointer Input %71\n"
"%161 = OpTypePointer Output %71\n"
"%163 = OpTypeArray %6 %18\n"
"%164 = OpTypeStruct %25 %6 %163 %163\n"
"%165 = OpTypePointer Output %164\n"
"%166 = OpVariable %165 Output\n"
"%172 = OpTypeStruct %25 %6 %163 %163\n"
"%173 = OpTypeArray %172 %34\n"
"%174 = OpTypePointer Input %173\n"
"%175 = OpVariable %174 Input\n"
"%4 = OpFunction %2 None %3\n"
"%5 = OpLabel\n"
"%8 = OpVariable %7 Function\n"
"%17 = OpVariable %7 Function\n"
"%21 = OpVariable %7 Function\n"
"%15 = OpAccessChain %14 %11 %13\n"
"%16 = OpLoad %6 %15\n"
"OpStore %8 %16\n"
"%19 = OpAccessChain %14 %11 %18\n"
"%20 = OpLoad %6 %19\n"
"OpStore %17 %20\n"
"%23 = OpAccessChain %14 %11 %22\n"
"%24 = OpLoad %6 %23\n"
"OpStore %21 %24\n"
"%29 = OpLoad %6 %8\n"
"%30 = OpFSub %6 %28 %29\n"
"%31 = OpLoad %6 %17\n"
"%32 = OpFSub %6 %28 %31\n"
"%33 = OpFMul %6 %30 %32\n"
"%41 = OpAccessChain %40 %color_in %39\n"
"%42 = OpLoad %25 %41\n"
"%43 = OpVectorTimesScalar %25 %42 %33\n"
"%44 = OpLoad %6 %8\n"
"%45 = OpFSub %6 %28 %44\n"
"%46 = OpLoad %6 %17\n"
"%47 = OpFMul %6 %45 %46\n"
"%49 = OpAccessChain %40 %color_in %48\n"
"%50 = OpLoad %25 %49\n"
"%51 = OpVectorTimesScalar %25 %50 %47\n"
"%52 = OpFAdd %25 %43 %51\n"
"%53 = OpLoad %6 %8\n"
"%54 = OpLoad %6 %17\n"
"%55 = OpFSub %6 %28 %54\n"
"%56 = OpFMul %6 %53 %55\n"
"%58 = OpAccessChain %40 %color_in %57\n"
"%59 = OpLoad %25 %58\n"
"%60 = OpVectorTimesScalar %25 %59 %56\n"
"%61 = OpFAdd %25 %52 %60\n"
"%62 = OpLoad %6 %8\n"
"%63 = OpLoad %6 %17\n"
"%64 = OpFMul %6 %62 %63\n"
"%66 = OpAccessChain %40 %color_in %65\n"
"%67 = OpLoad %25 %66\n"
"%68 = OpVectorTimesScalar %25 %67 %64\n"
"%69 = OpFAdd %25 %61 %68\n"
"OpStore %color_out %69\n"
"%75 = OpLoad %6 %8\n"
"%76 = OpFSub %6 %28 %75\n"
"%77 = OpLoad %6 %17\n"
"%78 = OpFSub %6 %28 %77\n"
"%79 = OpFMul %6 %76 %78\n"
"%84 = OpAccessChain %40 %83 %39 %39\n"
"%85 = OpLoad %25 %84\n"
"%86 = OpVectorTimesScalar %25 %85 %79\n"
"%87 = OpLoad %6 %8\n"
"%88 = OpFSub %6 %28 %87\n"
"%89 = OpLoad %6 %17\n"
"%90 = OpFMul %6 %88 %89\n"
"%91 = OpAccessChain %40 %83 %48 %39\n"
"%92 = OpLoad %25 %91\n"
"%93 = OpVectorTimesScalar %25 %92 %90\n"
"%94 = OpFAdd %25 %86 %93\n"
"%95 = OpLoad %6 %8\n"
"%96 = OpLoad %6 %17\n"
"%97 = OpFSub %6 %28 %96\n"
"%98 = OpFMul %6 %95 %97\n"
"%99 = OpAccessChain %40 %83 %57 %39\n"
"%100 = OpLoad %25 %99\n"
"%101 = OpVectorTimesScalar %25 %100 %98\n"
"%102 = OpFAdd %25 %94 %101\n"
"%103 = OpLoad %6 %8\n"
"%104 = OpLoad %6 %17\n"
"%105 = OpFMul %6 %103 %104\n"
"%106 = OpAccessChain %40 %83 %65 %39\n"
"%107 = OpLoad %25 %106\n"
"%108 = OpVectorTimesScalar %25 %107 %105\n"
"%109 = OpFAdd %25 %102 %108\n"
"%110 = OpAccessChain %26 %74 %39\n"
"OpStore %110 %109\n"
"%111 = OpLoad %6 %8\n"
"%112 = OpFSub %6 %28 %111\n"
"%113 = OpLoad %6 %17\n"
"%114 = OpFSub %6 %28 %113\n"
"%115 = OpFMul %6 %112 %114\n"
"%117 = OpAccessChain %116 %83 %39 %48\n"
"%118 = OpLoad %71 %117\n"
"%119 = OpMatrixTimesScalar %71 %118 %115\n"
"%120 = OpLoad %6 %8\n"
"%121 = OpFSub %6 %28 %120\n"
"%122 = OpLoad %6 %17\n"
"%123 = OpFMul %6 %121 %122\n"
"%124 = OpAccessChain %116 %83 %48 %48\n"
"%125 = OpLoad %71 %124\n"
"%126 = OpMatrixTimesScalar %71 %125 %123\n"
"%127 = OpCompositeExtract %70 %119 0\n"
"%128 = OpCompositeExtract %70 %126 0\n"
"%129 = OpFAdd %70 %127 %128\n"
"%130 = OpCompositeExtract %70 %119 1\n"
"%131 = OpCompositeExtract %70 %126 1\n"
"%132 = OpFAdd %70 %130 %131\n"
"%133 = OpCompositeConstruct %71 %129 %132\n"
"%134 = OpLoad %6 %8\n"
"%135 = OpLoad %6 %17\n"
"%136 = OpFSub %6 %28 %135\n"
"%137 = OpFMul %6 %134 %136\n"
"%138 = OpAccessChain %116 %83 %57 %48\n"
"%139 = OpLoad %71 %138\n"
"%140 = OpMatrixTimesScalar %71 %139 %137\n"
"%141 = OpCompositeExtract %70 %133 0\n"
"%142 = OpCompositeExtract %70 %140 0\n"
"%143 = OpFAdd %70 %141 %142\n"
"%144 = OpCompositeExtract %70 %133 1\n"
"%145 = OpCompositeExtract %70 %140 1\n"
"%146 = OpFAdd %70 %144 %145\n"
"%147 = OpCompositeConstruct %71 %143 %146\n"
"%148 = OpLoad %6 %8\n"
"%149 = OpLoad %6 %17\n"
"%150 = OpFMul %6 %148 %149\n"
"%151 = OpAccessChain %116 %83 %65 %48\n"
"%152 = OpLoad %71 %151\n"
"%153 = OpMatrixTimesScalar %71 %152 %150\n"
"%154 = OpCompositeExtract %70 %147 0\n"
"%155 = OpCompositeExtract %70 %153 0\n"
"%156 = OpFAdd %70 %154 %155\n"
"%157 = OpCompositeExtract %70 %147 1\n"
"%158 = OpCompositeExtract %70 %153 1\n"
"%159 = OpFAdd %70 %157 %158\n"
"%160 = OpCompositeConstruct %71 %156 %159\n"
"%162 = OpAccessChain %161 %74 %48\n"
"OpStore %162 %160\n"
"%167 = OpLoad %6 %8\n"
"%168 = OpFSub %6 %28 %167\n"
"%169 = OpLoad %6 %17\n"
"%170 = OpFSub %6 %28 %169\n"
"%171 = OpFMul %6 %168 %170\n"
"%176 = OpAccessChain %40 %175 %39 %39\n"
"%177 = OpLoad %25 %176\n"
"%178 = OpVectorTimesScalar %25 %177 %171\n"
"%179 = OpLoad %6 %8\n"
"%180 = OpFSub %6 %28 %179\n"
"%181 = OpLoad %6 %17\n"
"%182 = OpFMul %6 %180 %181\n"
"%183 = OpAccessChain %40 %175 %48 %39\n"
"%184 = OpLoad %25 %183\n"
"%185 = OpVectorTimesScalar %25 %184 %182\n"
"%186 = OpFAdd %25 %178 %185\n"
"%187 = OpLoad %6 %8\n"
"%188 = OpLoad %6 %17\n"
"%189 = OpFSub %6 %28 %188\n"
"%190 = OpFMul %6 %187 %189\n"
"%191 = OpAccessChain %40 %175 %57 %39\n"
"%192 = OpLoad %25 %191\n"
"%193 = OpVectorTimesScalar %25 %192 %190\n"
"%194 = OpFAdd %25 %186 %193\n"
"%195 = OpLoad %6 %8\n"
"%196 = OpLoad %6 %17\n"
"%197 = OpFMul %6 %195 %196\n"
"%198 = OpAccessChain %40 %175 %65 %39\n"
"%199 = OpLoad %25 %198\n"
"%200 = OpVectorTimesScalar %25 %199 %197\n"
"%201 = OpFAdd %25 %194 %200\n"
"%202 = OpAccessChain %26 %166 %39\n"
"OpStore %202 %201\n"
"OpReturn\n"
"OpFunctionEnd\n";
programCollection.spirvAsmSources.add("tessellation_control") << tessellationControlSource;
programCollection.spirvAsmSources.add("tessellation_evaluation") << tessellationEvaluationSource;
}
{
/*#version 450
layout(triangles) in;
layout(triangle_strip, max_vertices = 3) out;
layout(location = 0) in vec4 in_color[];
layout(location = 1) in ColorData
{
vec4 colorVec;
mat2 colorMat;
} inData[];
layout(location = 0) out vec4 out_color;
layout(location = 1) out ColorData
{
vec4 colorVec;
mat2 colorMat;
} outData;
void main (void)
{
out_color = in_color[0];
outData.colorVec = inData[0].colorVec;
outData.colorMat = inData[0].colorMat;
gl_Position = gl_in[0].gl_Position;
EmitVertex();
out_color = in_color[1];
outData.colorVec = inData[1].colorVec;
outData.colorMat = inData[1].colorMat;
gl_Position = gl_in[1].gl_Position;
EmitVertex();
out_color = in_color[2];
outData.colorVec = inData[2].colorVec;
outData.colorMat = inData[2].colorMat;
gl_Position = gl_in[2].gl_Position;
EmitVertex();
EndPrimitive();
}*/
const string geometrySource =
"; SPIR-V\n"
"; Version: 1.3\n"
"; Generator: Khronos Glslang Reference Front End; 2\n"
"; Bound: 73\n"
"; Schema: 0\n"
"OpCapability Geometry\n"
"%1 = OpExtInstImport \"GLSL.std.450\"\n"
"OpMemoryModel Logical GLSL450\n"
"OpEntryPoint Geometry %4 \"main\" %color_out %color_in %24 %28 %42 %46\n"
"OpExecutionMode %4 Triangles\n"
"OpExecutionMode %4 Invocations 1\n"
"OpExecutionMode %4 OutputTriangleStrip\n"
"OpExecutionMode %4 OutputVertices 3\n"
"OpDecorate %color_out Location 0\n"
"OpDecorate %color_in Location 0\n"
"OpDecorate %block_out Block\n"
"OpDecorate %24 Location 1\n"
"OpDecorate %block_in Block\n"
"OpDecorate %28 Location 1\n"
+decorations[0].others+
"OpMemberDecorate %40 0 BuiltIn Position\n"
"OpMemberDecorate %40 1 BuiltIn PointSize\n"
"OpMemberDecorate %40 2 BuiltIn ClipDistance\n"
"OpMemberDecorate %40 3 BuiltIn CullDistance\n"
"OpDecorate %40 Block\n"
"OpMemberDecorate %43 0 BuiltIn Position\n"
"OpMemberDecorate %43 1 BuiltIn PointSize\n"
"OpMemberDecorate %43 2 BuiltIn ClipDistance\n"
"OpMemberDecorate %43 3 BuiltIn CullDistance\n"
"OpDecorate %43 Block\n"
"%2 = OpTypeVoid\n"
"%3 = OpTypeFunction %2\n"
"%6 = OpTypeFloat 32\n"
"%7 = OpTypeVector %6 4\n"
"%8 = OpTypePointer Output %7\n"
"%color_out = OpVariable %8 Output\n"
"%10 = OpTypeInt 32 0\n"
"%11 = OpConstant %10 3\n"
"%12 = OpTypeArray %7 %11\n"
"%13 = OpTypePointer Input %12\n"
"%color_in = OpVariable %13 Input\n"
"%15 = OpTypeInt 32 1\n"
"%16 = OpConstant %15 0\n"
"%17 = OpTypePointer Input %7\n"
"%20 = OpTypeVector %6 2\n"
"%21 = OpTypeMatrix %20 2\n"
"%block_out = OpTypeStruct %7 %21\n"
"%23 = OpTypePointer Output %block_out\n"
"%24 = OpVariable %23 Output\n"
"%block_in = OpTypeStruct %7 %21\n"
"%26 = OpTypeArray %block_in %11\n"
"%27 = OpTypePointer Input %26\n"
"%28 = OpVariable %27 Input\n"
"%32 = OpConstant %15 1\n"
"%33 = OpTypePointer Input %21\n"
"%36 = OpTypePointer Output %21\n"
"%38 = OpConstant %10 1\n"
"%39 = OpTypeArray %6 %38\n"
"%40 = OpTypeStruct %7 %6 %39 %39\n"
"%41 = OpTypePointer Output %40\n"
"%42 = OpVariable %41 Output\n"
"%43 = OpTypeStruct %7 %6 %39 %39\n"
"%44 = OpTypeArray %43 %11\n"
"%45 = OpTypePointer Input %44\n"
"%46 = OpVariable %45 Input\n"
"%61 = OpConstant %15 2\n"
"%4 = OpFunction %2 None %3\n"
"%5 = OpLabel\n"
"%18 = OpAccessChain %17 %color_in %16\n"
"%19 = OpLoad %7 %18\n"
"OpStore %color_out %19\n"
"%29 = OpAccessChain %17 %28 %16 %16\n"
"%30 = OpLoad %7 %29\n"
"%31 = OpAccessChain %8 %24 %16\n"
"OpStore %31 %30\n"
"%34 = OpAccessChain %33 %28 %16 %32\n"
"%35 = OpLoad %21 %34\n"
"%37 = OpAccessChain %36 %24 %32\n"
"OpStore %37 %35\n"
"%47 = OpAccessChain %17 %46 %16 %16\n"
"%48 = OpLoad %7 %47\n"
"%49 = OpAccessChain %8 %42 %16\n"
"OpStore %49 %48\n"
"OpEmitVertex\n"
"%50 = OpAccessChain %17 %color_in %32\n"
"%51 = OpLoad %7 %50\n"
"OpStore %color_out %51\n"
"%52 = OpAccessChain %17 %28 %32 %16\n"
"%53 = OpLoad %7 %52\n"
"%54 = OpAccessChain %8 %24 %16\n"
"OpStore %54 %53\n"
"%55 = OpAccessChain %33 %28 %32 %32\n"
"%56 = OpLoad %21 %55\n"
"%57 = OpAccessChain %36 %24 %32\n"
"OpStore %57 %56\n"
"%58 = OpAccessChain %17 %46 %32 %16\n"
"%59 = OpLoad %7 %58\n"
"%60 = OpAccessChain %8 %42 %16\n"
"OpStore %60 %59\n"
"OpEmitVertex\n"
"%62 = OpAccessChain %17 %color_in %61\n"
"%63 = OpLoad %7 %62\n"
"OpStore %color_out %63\n"
"%64 = OpAccessChain %17 %28 %61 %16\n"
"%65 = OpLoad %7 %64\n"
"%66 = OpAccessChain %8 %24 %16\n"
"OpStore %66 %65\n"
"%67 = OpAccessChain %33 %28 %61 %32\n"
"%68 = OpLoad %21 %67\n"
"%69 = OpAccessChain %36 %24 %32\n"
"OpStore %69 %68\n"
"%70 = OpAccessChain %17 %46 %61 %16\n"
"%71 = OpLoad %7 %70\n"
"%72 = OpAccessChain %8 %42 %16\n"
"OpStore %72 %71\n"
"OpEmitVertex\n"
"OpEndPrimitive\n"
"OpReturn\n"
"OpFunctionEnd\n";
programCollection.spirvAsmSources.add("geometry") << geometrySource;
}
}
} // anonymous
tcu::TestCaseGroup* createCrossStageInterfaceTests (tcu::TestContext& testCtx)
{
de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "cross_stage", ""));
{
de::MovePtr<tcu::TestCaseGroup> basicGroup(new tcu::TestCaseGroup(testCtx, "basic_type", ""));
de::MovePtr<tcu::TestCaseGroup> interfaceGroup(new tcu::TestCaseGroup(testCtx, "interface_blocks", ""));
{
TestParameters parm(TEST_TYPE_FLAT,3);
for (int ndx = 0; ndx < CrossStageTestInstance::DECORATION_LAST; ++ndx)
parm.testOptions[ndx] = ndx;
basicGroup->addChild(new CrossStageBasicTestsCase(testCtx, "flat", "", parm));
interfaceGroup->addChild(new CrossStageInterfaceTestsCase(testCtx, "flat", "", parm));
parm.qualifier = TEST_TYPE_NOPERSPECTIVE;
basicGroup->addChild(new CrossStageBasicTestsCase(testCtx, "no_perspective", "", parm));
interfaceGroup->addChild(new CrossStageInterfaceTestsCase(testCtx, "no_perspective", "", parm));
}
{
TestParameters parm(TEST_TYPE_RELAXEDPRECISION,1);
parm.testOptions[0] = CrossStageTestInstance::DECORATION_IN_ALL_SHADERS;
basicGroup->addChild(new CrossStageBasicTestsCase(testCtx, "relaxedprecision", "", parm));
interfaceGroup->addChild(new CrossStageInterfaceTestsCase(testCtx, "relaxedprecision", "", parm));
}
testGroup->addChild(basicGroup.release());
testGroup->addChild(interfaceGroup.release());
}
return testGroup.release();
}
} // SpirVAssembly
} // vkt
| 36.933382
| 342
| 0.659867
|
jingpad-bsp
|
10845e1302b9122a421d8ccdce499eab41c65933
| 18,919
|
cpp
|
C++
|
sources/modules/contrib/src/fuzzymeanshifttracker.cpp
|
ovb197310/opencv_2.4.13.2
|
940159dab8ea8f5ee019d2038b59e1daf4119d1c
|
[
"BSD-3-Clause"
] | null | null | null |
sources/modules/contrib/src/fuzzymeanshifttracker.cpp
|
ovb197310/opencv_2.4.13.2
|
940159dab8ea8f5ee019d2038b59e1daf4119d1c
|
[
"BSD-3-Clause"
] | null | null | null |
sources/modules/contrib/src/fuzzymeanshifttracker.cpp
|
ovb197310/opencv_2.4.13.2
|
940159dab8ea8f5ee019d2038b59e1daf4119d1c
|
[
"BSD-3-Clause"
] | null | null | null |
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install, copy or use the software.
//
// Copyright (C) 2009, Farhad Dadgostar
// Intel Corporation and third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of Intel Corporation may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation 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.
//
//M*/
#include "precomp.hpp"
CvFuzzyPoint::CvFuzzyPoint(double _x, double _y)
{
x = _x;
y = _y;
}
bool CvFuzzyCurve::between(double x, double x1, double x2)
{
if ((x >= x1) && (x <= x2))
return true;
else if ((x >= x2) && (x <= x1))
return true;
return false;
}
CvFuzzyCurve::CvFuzzyCurve()
{
value = 0;
}
CvFuzzyCurve::~CvFuzzyCurve()
{
// nothing to do
}
void CvFuzzyCurve::setCentre(double _centre)
{
centre = _centre;
}
double CvFuzzyCurve::getCentre()
{
return centre;
}
void CvFuzzyCurve::clear()
{
points.clear();
}
void CvFuzzyCurve::addPoint(double x, double y)
{
points.push_back(CvFuzzyPoint(x, y));
}
double CvFuzzyCurve::calcValue(double param)
{
int size = (int)points.size();
double x1, y1, x2, y2, m, y;
for (int i = 1; i < size; i++)
{
x1 = points[i-1].x;
x2 = points[i].x;
if (between(param, x1, x2)) {
y1 = points[i-1].y;
y2 = points[i].y;
if (x2 == x1)
return y2;
m = (y2-y1)/(x2-x1);
y = m*(param-x1)+y1;
return y;
}
}
return 0;
}
double CvFuzzyCurve::getValue()
{
return value;
}
void CvFuzzyCurve::setValue(double _value)
{
value = _value;
}
CvFuzzyFunction::CvFuzzyFunction()
{
// nothing to do
}
CvFuzzyFunction::~CvFuzzyFunction()
{
curves.clear();
}
void CvFuzzyFunction::addCurve(CvFuzzyCurve *curve, double value)
{
curves.push_back(*curve);
curve->setValue(value);
}
void CvFuzzyFunction::resetValues()
{
int numCurves = (int)curves.size();
for (int i = 0; i < numCurves; i++)
curves[i].setValue(0);
}
double CvFuzzyFunction::calcValue()
{
double s1 = 0, s2 = 0, v;
int numCurves = (int)curves.size();
for (int i = 0; i < numCurves; i++)
{
v = curves[i].getValue();
s1 += curves[i].getCentre() * v;
s2 += v;
}
if (s2 != 0)
return s1/s2;
else
return 0;
}
CvFuzzyCurve *CvFuzzyFunction::newCurve()
{
CvFuzzyCurve *c;
c = new CvFuzzyCurve();
addCurve(c);
return c;
}
CvFuzzyRule::CvFuzzyRule()
{
fuzzyInput1 = NULL;
fuzzyInput2 = NULL;
fuzzyOutput = NULL;
}
CvFuzzyRule::~CvFuzzyRule()
{
if (fuzzyInput1 != NULL)
delete fuzzyInput1;
if (fuzzyInput2 != NULL)
delete fuzzyInput2;
if (fuzzyOutput != NULL)
delete fuzzyOutput;
}
void CvFuzzyRule::setRule(CvFuzzyCurve *c1, CvFuzzyCurve *c2, CvFuzzyCurve *o1)
{
fuzzyInput1 = c1;
fuzzyInput2 = c2;
fuzzyOutput = o1;
}
double CvFuzzyRule::calcValue(double param1, double param2)
{
double v1, v2;
v1 = fuzzyInput1->calcValue(param1);
if (fuzzyInput2 != NULL)
{
v2 = fuzzyInput2->calcValue(param2);
if (v1 < v2)
return v1;
else
return v2;
}
else
return v1;
}
CvFuzzyCurve *CvFuzzyRule::getOutputCurve()
{
return fuzzyOutput;
}
CvFuzzyController::CvFuzzyController()
{
// nothing to do
}
CvFuzzyController::~CvFuzzyController()
{
int size = (int)rules.size();
for(int i = 0; i < size; i++)
delete rules[i];
}
void CvFuzzyController::addRule(CvFuzzyCurve *c1, CvFuzzyCurve *c2, CvFuzzyCurve *o1)
{
CvFuzzyRule *f = new CvFuzzyRule();
rules.push_back(f);
f->setRule(c1, c2, o1);
}
double CvFuzzyController::calcOutput(double param1, double param2)
{
double v;
CvFuzzyFunction list;
int size = (int)rules.size();
for(int i = 0; i < size; i++)
{
v = rules[i]->calcValue(param1, param2);
if (v != 0)
list.addCurve(rules[i]->getOutputCurve(), v);
}
v = list.calcValue();
return v;
}
CvFuzzyMeanShiftTracker::FuzzyResizer::FuzzyResizer()
{
CvFuzzyCurve *i1L, *i1M, *i1H;
CvFuzzyCurve *oS, *oZE, *oE;
CvFuzzyCurve *c;
double MedStart = 0.1, MedWidth = 0.15;
c = iInput.newCurve();
c->addPoint(0, 1);
c->addPoint(0.1, 0);
c->setCentre(0);
i1L = c;
c = iInput.newCurve();
c->addPoint(0.05, 0);
c->addPoint(MedStart, 1);
c->addPoint(MedStart+MedWidth, 1);
c->addPoint(MedStart+MedWidth+0.05, 0);
c->setCentre(MedStart+(MedWidth/2));
i1M = c;
c = iInput.newCurve();
c->addPoint(MedStart+MedWidth, 0);
c->addPoint(1, 1);
c->addPoint(1000, 1);
c->setCentre(1);
i1H = c;
c = iOutput.newCurve();
c->addPoint(-10000, 1);
c->addPoint(-5, 1);
c->addPoint(-0.5, 0);
c->setCentre(-5);
oS = c;
c = iOutput.newCurve();
c->addPoint(-1, 0);
c->addPoint(-0.05, 1);
c->addPoint(0.05, 1);
c->addPoint(1, 0);
c->setCentre(0);
oZE = c;
c = iOutput.newCurve();
c->addPoint(-0.5, 0);
c->addPoint(5, 1);
c->addPoint(1000, 1);
c->setCentre(5);
oE = c;
fuzzyController.addRule(i1L, NULL, oS);
fuzzyController.addRule(i1M, NULL, oZE);
fuzzyController.addRule(i1H, NULL, oE);
}
int CvFuzzyMeanShiftTracker::FuzzyResizer::calcOutput(double edgeDensity, double density)
{
return (int)fuzzyController.calcOutput(edgeDensity, density);
}
CvFuzzyMeanShiftTracker::SearchWindow::SearchWindow()
{
x = 0;
y = 0;
width = 0;
height = 0;
maxWidth = 0;
maxHeight = 0;
xGc = 0;
yGc = 0;
m00 = 0;
m01 = 0;
m10 = 0;
m11 = 0;
m02 = 0;
m20 = 0;
ellipseHeight = 0;
ellipseWidth = 0;
ellipseAngle = 0;
density = 0;
depthLow = 0;
depthHigh = 0;
fuzzyResizer = NULL;
}
CvFuzzyMeanShiftTracker::SearchWindow::~SearchWindow()
{
if (fuzzyResizer != NULL)
delete fuzzyResizer;
}
void CvFuzzyMeanShiftTracker::SearchWindow::setSize(int _x, int _y, int _width, int _height)
{
x = _x;
y = _y;
width = _width;
height = _height;
if (x < 0)
x = 0;
if (y < 0)
y = 0;
if (x + width > maxWidth)
width = maxWidth - x;
if (y + height > maxHeight)
height = maxHeight - y;
}
void CvFuzzyMeanShiftTracker::SearchWindow::initDepthValues(IplImage *maskImage, IplImage *depthMap)
{
unsigned int d=0, mind = 0xFFFF, maxd = 0, m0 = 0, m1 = 0, mc, dd;
unsigned char *data = NULL;
unsigned short *depthData = NULL;
for (int j = 0; j < height; j++)
{
data = (unsigned char *)(maskImage->imageData + (maskImage->widthStep * (j + y)) + x);
if (depthMap)
depthData = (unsigned short *)(depthMap->imageData + (depthMap->widthStep * (j + y)) + x);
for (int i = 0; i < width; i++)
{
if (*data)
{
m0 += 1;
if (depthData)
{
if (*depthData)
{
d = *depthData;
m1 += d;
if (d < mind)
mind = d;
if (d > maxd)
maxd = d;
}
depthData++;
}
}
data++;
}
}
if (m0 > 0)
{
mc = m1/m0;
if ((mc - mind) > (maxd - mc))
dd = maxd - mc;
else
dd = mc - mind;
dd = dd - dd/10;
depthHigh = mc + dd;
depthLow = mc - dd;
}
else
{
depthHigh = 32000;
depthLow = 0;
}
}
bool CvFuzzyMeanShiftTracker::SearchWindow::shift()
{
if ((xGc != (width/2)) || (yGc != (height/2)))
{
setSize(x + (xGc-(width/2)), y + (yGc-(height/2)), width, height);
return true;
}
else
{
return false;
}
}
void CvFuzzyMeanShiftTracker::SearchWindow::extractInfo(IplImage *maskImage, IplImage *depthMap, bool initDepth)
{
m00 = 0;
m10 = 0;
m01 = 0;
m11 = 0;
density = 0;
m02 = 0;
m20 = 0;
ellipseHeight = 0;
ellipseWidth = 0;
maxWidth = maskImage->width;
maxHeight = maskImage->height;
if (initDepth)
initDepthValues(maskImage, depthMap);
unsigned char *maskData = NULL;
unsigned short *depthData = NULL, depth;
bool isOk;
unsigned long count;
verticalEdgeLeft = 0;
verticalEdgeRight = 0;
horizontalEdgeTop = 0;
horizontalEdgeBottom = 0;
for (int j = 0; j < height; j++)
{
maskData = (unsigned char *)(maskImage->imageData + (maskImage->widthStep * (j + y)) + x);
if (depthMap)
depthData = (unsigned short *)(depthMap->imageData + (depthMap->widthStep * (j + y)) + x);
count = 0;
for (int i = 0; i < width; i++)
{
if (*maskData)
{
isOk = true;
if (depthData)
{
depth = (*depthData);
if ((depth > depthHigh) || (depth < depthLow))
isOk = false;
depthData++;
}
if (isOk)
{
m00++;
m01 += j;
m10 += i;
m02 += (j * j);
m20 += (i * i);
m11 += (j * i);
if (i == 0)
verticalEdgeLeft++;
else if (i == width-1)
verticalEdgeRight++;
else if (j == 0)
horizontalEdgeTop++;
else if (j == height-1)
horizontalEdgeBottom++;
count++;
}
}
maskData++;
}
}
if (m00 > 0)
{
xGc = (int)(m10 / m00);
yGc = (int)(m01 / m00);
double a, b, c, e1, e2, e3;
a = ((double)m20/(double)m00)-(xGc * xGc);
b = 2*(((double)m11/(double)m00)-(xGc * yGc));
c = ((double)m02/(double)m00)-(yGc * yGc);
e1 = a+c;
e3 = a-c;
e2 = sqrt((b*b)+(e3*e3));
ellipseHeight = int(sqrt(0.5*(e1+e2)));
ellipseWidth = int(sqrt(0.5*(e1-e2)));
if (e3 == 0)
ellipseAngle = 0;
else
ellipseAngle = 0.5*atan(b/e3);
density = (double)m00/(double)(width * height);
}
else
{
xGc = width / 2;
yGc = height / 2;
ellipseHeight = 0;
ellipseWidth = 0;
ellipseAngle = 0;
density = 0;
}
}
void CvFuzzyMeanShiftTracker::SearchWindow::getResizeAttribsEdgeDensityLinear(int &resizeDx, int &resizeDy, int &resizeDw, int &resizeDh) {
int x1 = horizontalEdgeTop;
int x2 = horizontalEdgeBottom;
int y1 = verticalEdgeLeft;
int y2 = verticalEdgeRight;
int gx = (width*2)/5;
int gy = (height*2)/5;
int lx = width/10;
int ly = height/10;
resizeDy = 0;
resizeDh = 0;
resizeDx = 0;
resizeDw = 0;
if (x1 > gx) {
resizeDy = -1;
} else if (x1 < lx) {
resizeDy = +1;
}
if (x2 > gx) {
resizeDh = resizeDy + 1;
} else if (x2 < lx) {
resizeDh = - (resizeDy + 1);
} else {
resizeDh = - resizeDy;
}
if (y1 > gy) {
resizeDx = -1;
} else if (y1 < ly) {
resizeDx = +1;
}
if (y2 > gy) {
resizeDw = resizeDx + 1;
} else if (y2 < ly) {
resizeDw = - (resizeDx + 1);
} else {
resizeDw = - resizeDx;
}
}
void CvFuzzyMeanShiftTracker::SearchWindow::getResizeAttribsInnerDensity(int &resizeDx, int &resizeDy, int &resizeDw, int &resizeDh)
{
int newWidth, newHeight, dx, dy;
double px, py;
newWidth = int(sqrt(double(m00)*1.3));
newHeight = int(newWidth*1.2);
dx = (newWidth - width);
dy = (newHeight - height);
px = (double)xGc/(double)width;
py = (double)yGc/(double)height;
resizeDx = (int)(px*dx);
resizeDy = (int)(py*dy);
resizeDw = (int)((1-px)*dx);
resizeDh = (int)((1-py)*dy);
}
void CvFuzzyMeanShiftTracker::SearchWindow::getResizeAttribsEdgeDensityFuzzy(int &resizeDx, int &resizeDy, int &resizeDw, int &resizeDh)
{
double dx1=0, dx2, dy1, dy2;
resizeDy = 0;
resizeDh = 0;
resizeDx = 0;
resizeDw = 0;
if (fuzzyResizer == NULL)
fuzzyResizer = new FuzzyResizer();
dx2 = fuzzyResizer->calcOutput(double(verticalEdgeRight)/double(height), density);
if (dx1 == dx2)
{
resizeDx = int(-dx1);
resizeDw = int(dx1+dx2);
}
dy1 = fuzzyResizer->calcOutput(double(horizontalEdgeTop)/double(width), density);
dy2 = fuzzyResizer->calcOutput(double(horizontalEdgeBottom)/double(width), density);
dx1 = fuzzyResizer->calcOutput(double(verticalEdgeLeft)/double(height), density);
dx2 = fuzzyResizer->calcOutput(double(verticalEdgeRight)/double(height), density);
//if (dx1 == dx2)
{
resizeDx = int(-dx1);
resizeDw = int(dx1+dx2);
}
dy1 = fuzzyResizer->calcOutput(double(horizontalEdgeTop)/double(width), density);
dy2 = fuzzyResizer->calcOutput(double(horizontalEdgeBottom)/double(width), density);
//if (dy1 == dy2)
{
resizeDy = int(-dy1);
resizeDh = int(dy1+dy2);
}
}
bool CvFuzzyMeanShiftTracker::SearchWindow::meanShift(IplImage *maskImage, IplImage *depthMap, int maxIteration, bool initDepth)
{
numShifts = 0;
do
{
extractInfo(maskImage, depthMap, initDepth);
if (! shift())
return true;
} while (++numShifts < maxIteration);
return false;
}
void CvFuzzyMeanShiftTracker::findOptimumSearchWindow(SearchWindow &searchWindow, IplImage *maskImage, IplImage *depthMap, int maxIteration, int resizeMethod, bool initDepth)
{
int resizeDx, resizeDy, resizeDw, resizeDh;
resizeDx = 0;
resizeDy = 0;
resizeDw = 0;
resizeDh = 0;
searchWindow.numIters = 0;
for (int i = 0; i < maxIteration; i++)
{
searchWindow.numIters++;
searchWindow.meanShift(maskImage, depthMap, MaxMeanShiftIteration, initDepth);
switch (resizeMethod)
{
case rmEdgeDensityLinear :
searchWindow.getResizeAttribsEdgeDensityLinear(resizeDx, resizeDy, resizeDw, resizeDh);
break;
case rmEdgeDensityFuzzy :
//searchWindow.getResizeAttribsEdgeDensityLinear(resizeDx, resizeDy, resizeDw, resizeDh);
searchWindow.getResizeAttribsEdgeDensityFuzzy(resizeDx, resizeDy, resizeDw, resizeDh);
break;
case rmInnerDensity :
searchWindow.getResizeAttribsInnerDensity(resizeDx, resizeDy, resizeDw, resizeDh);
break;
default:
searchWindow.getResizeAttribsEdgeDensityLinear(resizeDx, resizeDy, resizeDw, resizeDh);
}
searchWindow.ldx = resizeDx;
searchWindow.ldy = resizeDy;
searchWindow.ldw = resizeDw;
searchWindow.ldh = resizeDh;
if ((resizeDx == 0) && (resizeDy == 0) && (resizeDw == 0) && (resizeDh == 0))
break;
searchWindow.setSize(searchWindow.x + resizeDx, searchWindow.y + resizeDy, searchWindow.width + resizeDw, searchWindow.height + resizeDh);
}
}
CvFuzzyMeanShiftTracker::CvFuzzyMeanShiftTracker()
{
searchMode = tsSetWindow;
}
CvFuzzyMeanShiftTracker::~CvFuzzyMeanShiftTracker()
{
// nothing to do
}
void CvFuzzyMeanShiftTracker::track(IplImage *maskImage, IplImage *depthMap, int resizeMethod, bool resetSearch, int minKernelMass)
{
bool initDepth = false;
if (resetSearch)
searchMode = tsSetWindow;
switch (searchMode)
{
case tsDisabled:
return;
case tsSearching:
return;
case tsSetWindow:
kernel.maxWidth = maskImage->width;
kernel.maxHeight = maskImage->height;
kernel.setSize(0, 0, maskImage->width, maskImage->height);
initDepth = true;
case tsTracking:
searchMode = tsSearching;
findOptimumSearchWindow(kernel, maskImage, depthMap, MaxSetSizeIteration, resizeMethod, initDepth);
if ((kernel.density == 0) || (kernel.m00 < minKernelMass))
searchMode = tsSetWindow;
else
searchMode = tsTracking;
}
}
| 26.239945
| 175
| 0.543052
|
ovb197310
|
1084b2d9e3d1eb38da6196c82593f51170b5a413
| 1,608
|
cpp
|
C++
|
src/poc/ncpp_build_exceptions.cpp
|
grendello/notcurses
|
a2cc5f096adb3991f264d96657b45a050fa8df2a
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
src/poc/ncpp_build_exceptions.cpp
|
grendello/notcurses
|
a2cc5f096adb3991f264d96657b45a050fa8df2a
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
src/poc/ncpp_build_exceptions.cpp
|
grendello/notcurses
|
a2cc5f096adb3991f264d96657b45a050fa8df2a
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
#define NCPP_EXCEPTIONS_PLEASE
//
// This is a **build** test - it does nothing else except ensure that all the C++ wrapper classes are included and that
// the program builds.
//
// Once there are demos which exercise all the C++ classes this "test" can be removed
//
#include <cstdlib>
#include <clocale>
#include <iostream>
#include <ncpp/NotCurses.hh>
#include <ncpp/Menu.hh>
#include <ncpp/Plane.hh>
#include <ncpp/Reel.hh>
#include <ncpp/MultiSelector.hh>
#include <ncpp/Selector.hh>
#include <ncpp/Visual.hh>
#include <ncpp/Direct.hh>
#include <ncpp/Plot.hh>
#include <ncpp/FDPlane.hh>
#include <ncpp/Subproc.hh>
using namespace ncpp;
int run ()
{
NotCurses nc;
const char *ncver = nc.version ();
{
Plane p1 (1, 1, 0, 0);
Plot plot1 (p1);
Plane p2 (1, 1, 0, 0);
PlotU plot2 (p2);
Plane p3 (1, 1, 0, 0);
PlotD plot3 (p3);
}
nc.stop ();
Direct direct (getenv ("TERM"));
direct.set_fg_rgb (0xb5, 0x0d, 0xff);
std::cout << "notcurses version: ";
direct.set_bg_rgb (0x05, 0x6e, 0xee);
direct.set_fg_rgb (0xe2, 0xbf, 0x00);
std::cout << ncver << std::endl;
return 0;
}
int main ()
{
if (!setlocale (LC_ALL, "")){
std::cerr << "Couldn't set locale based on user preferences" << std::endl;
return EXIT_FAILURE;
}
try {
return run ();
} catch (ncpp::init_error &e) {
std::cerr << "Initialization error: " << e.what () << std::endl;
} catch (ncpp::invalid_state_error &e) {
std::cerr << "Invalid state error: " << e.what () << std::endl;
} catch (ncpp::invalid_argument &e) {
std::cerr << "Invalid argument error: " << e.what () << std::endl;
}
return 1;
}
| 22.971429
| 119
| 0.648632
|
grendello
|
10881826d9401c0b6c63184528df5f059833ca13
| 5,429
|
hxx
|
C++
|
Modules/Filtering/AnisotropicSmoothing/include/itkCurvatureNDAnisotropicDiffusionFunction.hxx
|
HongdaZ/ITK
|
f5d004fa3607b8e11edc30f1ba299df35af8aff8
|
[
"Apache-2.0"
] | 1
|
2021-01-10T14:19:08.000Z
|
2021-01-10T14:19:08.000Z
|
Modules/Filtering/AnisotropicSmoothing/include/itkCurvatureNDAnisotropicDiffusionFunction.hxx
|
HongdaZ/ITK
|
f5d004fa3607b8e11edc30f1ba299df35af8aff8
|
[
"Apache-2.0"
] | 1
|
2017-03-19T12:56:50.000Z
|
2018-10-24T10:40:21.000Z
|
Modules/Filtering/AnisotropicSmoothing/include/itkCurvatureNDAnisotropicDiffusionFunction.hxx
|
HongdaZ/ITK
|
f5d004fa3607b8e11edc30f1ba299df35af8aff8
|
[
"Apache-2.0"
] | 1
|
2020-07-24T22:58:19.000Z
|
2020-07-24T22:58:19.000Z
|
/*=========================================================================
*
* Copyright NumFOCUS
*
* 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.txt
*
* 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.
*
*=========================================================================*/
#ifndef itkCurvatureNDAnisotropicDiffusionFunction_hxx
#define itkCurvatureNDAnisotropicDiffusionFunction_hxx
#include "itkCurvatureNDAnisotropicDiffusionFunction.h"
namespace itk
{
template <typename TImage>
double CurvatureNDAnisotropicDiffusionFunction<TImage>::m_MIN_NORM = 1.0e-10;
template <typename TImage>
CurvatureNDAnisotropicDiffusionFunction<TImage>::CurvatureNDAnisotropicDiffusionFunction()
: m_K(0.0)
{
unsigned int i, j;
RadiusType r;
for (i = 0; i < ImageDimension; ++i)
{
r[i] = 1;
}
this->SetRadius(r);
// Dummy neighborhood used to set up the slices.
Neighborhood<PixelType, ImageDimension> it;
it.SetRadius(r);
// Slice the neighborhood
m_Center = it.Size() / 2;
for (i = 0; i < ImageDimension; ++i)
{
m_Stride[i] = it.GetStride(i);
x_slice[i] = std::slice(m_Center - m_Stride[i], 3, m_Stride[i]);
}
for (i = 0; i < ImageDimension; ++i)
{
for (j = 0; j < ImageDimension; ++j)
{
// For taking derivatives in the i direction that are offset one
// pixel in the j direction.
xa_slice[i][j] = std::slice((m_Center + m_Stride[j]) - m_Stride[i], 3, m_Stride[i]);
xd_slice[i][j] = std::slice((m_Center - m_Stride[j]) - m_Stride[i], 3, m_Stride[i]);
}
}
// Allocate the derivative operator.
m_DerivativeOperator.SetDirection(0); // Not relevant, will be applied in a slice-based
// fashion.
m_DerivativeOperator.SetOrder(1);
m_DerivativeOperator.CreateDirectional();
}
template <typename TImage>
typename CurvatureNDAnisotropicDiffusionFunction<TImage>::PixelType
CurvatureNDAnisotropicDiffusionFunction<TImage>::ComputeUpdate(const NeighborhoodType & it,
void * itkNotUsed(globalData),
const FloatOffsetType & itkNotUsed(offset))
{
unsigned int i, j;
double speed, dx_forward_Cn, dx_backward_Cn, propagation_gradient;
double grad_mag_sq, grad_mag_sq_d, grad_mag, grad_mag_d;
double Cx, Cxd;
double dx_forward[ImageDimension];
double dx_backward[ImageDimension];
double dx[ImageDimension];
double dx_aug;
double dx_dim;
// Calculate the partial derivatives for each dimension
for (i = 0; i < ImageDimension; i++)
{
// "Half" derivatives
dx_forward[i] = it.GetPixel(m_Center + m_Stride[i]) - it.GetPixel(m_Center);
dx_forward[i] *= this->m_ScaleCoefficients[i];
dx_backward[i] = it.GetPixel(m_Center) - it.GetPixel(m_Center - m_Stride[i]);
dx_backward[i] *= this->m_ScaleCoefficients[i];
// Centralized differences
dx[i] = m_InnerProduct(x_slice[i], it, m_DerivativeOperator);
dx[i] *= this->m_ScaleCoefficients[i];
}
speed = 0.0;
for (i = 0; i < ImageDimension; i++)
{
// Gradient magnitude approximations
grad_mag_sq = dx_forward[i] * dx_forward[i];
grad_mag_sq_d = dx_backward[i] * dx_backward[i];
for (j = 0; j < ImageDimension; j++)
{
if (j != i)
{
dx_aug = m_InnerProduct(xa_slice[j][i], it, m_DerivativeOperator);
dx_aug *= this->m_ScaleCoefficients[j];
dx_dim = m_InnerProduct(xd_slice[j][i], it, m_DerivativeOperator);
dx_dim *= this->m_ScaleCoefficients[j];
grad_mag_sq += 0.25f * (dx[j] + dx_aug) * (dx[j] + dx_aug);
grad_mag_sq_d += 0.25f * (dx[j] + dx_dim) * (dx[j] + dx_dim);
}
}
grad_mag = std::sqrt(m_MIN_NORM + grad_mag_sq);
grad_mag_d = std::sqrt(m_MIN_NORM + grad_mag_sq_d);
// Conductance Terms
if (m_K == 0.0)
{
Cx = 0.0;
Cxd = 0.0;
}
else
{
Cx = std::exp(grad_mag_sq / m_K);
Cxd = std::exp(grad_mag_sq_d / m_K);
}
// First order normalized finite-difference conductance products
dx_forward_Cn = (dx_forward[i] / grad_mag) * Cx;
dx_backward_Cn = (dx_backward[i] / grad_mag_d) * Cxd;
// Second order conductance-modified curvature
speed += (dx_forward_Cn - dx_backward_Cn);
}
// "Upwind" gradient magnitude term
propagation_gradient = 0.0;
if (speed > 0)
{
for (i = 0; i < ImageDimension; i++)
{
propagation_gradient +=
itk::Math::sqr(std::min(dx_backward[i], 0.0)) + itk::Math::sqr(std::max(dx_forward[i], 0.0));
}
}
else
{
for (i = 0; i < ImageDimension; i++)
{
propagation_gradient +=
itk::Math::sqr(std::max(dx_backward[i], 0.0)) + itk::Math::sqr(std::min(dx_forward[i], 0.0));
}
}
return static_cast<PixelType>(std::sqrt(propagation_gradient) * speed);
}
} // end namespace itk
#endif
| 32.90303
| 111
| 0.620556
|
HongdaZ
|
1088318220664097cf7016c1710c3dd20f6a2ace
| 3,346
|
hpp
|
C++
|
include/bit/stl/utilities/monostate.hpp
|
bitwizeshift/bit-stl
|
cec555fbda2ea1b6e126fa719637dde8d3f2ddd3
|
[
"MIT"
] | 6
|
2017-03-29T07:20:30.000Z
|
2021-12-28T20:17:33.000Z
|
include/bit/stl/utilities/monostate.hpp
|
bitwizeshift/bit-stl
|
cec555fbda2ea1b6e126fa719637dde8d3f2ddd3
|
[
"MIT"
] | 6
|
2017-10-11T02:26:07.000Z
|
2018-04-16T03:09:48.000Z
|
include/bit/stl/utilities/monostate.hpp
|
bitwizeshift/bit-stl
|
cec555fbda2ea1b6e126fa719637dde8d3f2ddd3
|
[
"MIT"
] | 1
|
2018-08-27T15:03:47.000Z
|
2018-08-27T15:03:47.000Z
|
/*****************************************************************************
* \file
* \brief This header defines the type 'monotype'
*****************************************************************************/
/*
The MIT License (MIT)
Bit Standard Template Library.
https://github.com/bitwizeshift/bit-stl
Copyright (c) 2018 Matthew Rodusek
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.
*/
#ifndef BIT_STL_UTILITIES_MONOSTATE_HPP
#define BIT_STL_UTILITIES_MONOSTATE_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "hash.hpp" // hash_t
#include <cstddef> // std::size_t
namespace bit {
namespace stl {
//=========================================================================
// 23.7.8, class monostate
//=========================================================================
///////////////////////////////////////////////////////////////////////////
/// \brief Unit type intended for use as a well-behaved empty alternative
/// in \c variant.
///
/// In particular, a variant of non-default-constructible types may list
/// monostate as its first alternative: this makes the variant itself
/// default-constructible.
///////////////////////////////////////////////////////////////////////////
struct monostate{};
//-------------------------------------------------------------------------
// Comparison
//-------------------------------------------------------------------------
constexpr bool operator<(monostate, monostate) noexcept;
constexpr bool operator>(monostate, monostate) noexcept;
constexpr bool operator<=(monostate, monostate) noexcept;
constexpr bool operator>=(monostate, monostate) noexcept;
constexpr bool operator==(monostate, monostate) noexcept;
constexpr bool operator!=(monostate, monostate) noexcept;
//-------------------------------------------------------------------------
// Utilities
//-------------------------------------------------------------------------
/// \brief Hashes the monostate
///
/// \return 0
constexpr hash_t hash_value( const monostate& );
} // namespace stl
} // namespace bit
#include "detail/monostate.inl"
#endif /* BIT_STL_UTILITIES_MONOSTATE_HPP */
| 38.906977
| 79
| 0.558279
|
bitwizeshift
|
c80604d80e3dcda59957c5edb6dc48ca03cc44c1
| 18,607
|
cpp
|
C++
|
server/api/src/rsQuerySpecColl.cpp
|
JustinKyleJames/irods
|
59e9db75200e95796ec51ec20eb3b185d9e4b5f5
|
[
"BSD-3-Clause"
] | 333
|
2015-01-15T15:42:29.000Z
|
2022-03-19T19:16:15.000Z
|
server/api/src/rsQuerySpecColl.cpp
|
JustinKyleJames/irods
|
59e9db75200e95796ec51ec20eb3b185d9e4b5f5
|
[
"BSD-3-Clause"
] | 3,551
|
2015-01-02T19:55:40.000Z
|
2022-03-31T21:24:56.000Z
|
server/api/src/rsQuerySpecColl.cpp
|
JustinKyleJames/irods
|
59e9db75200e95796ec51ec20eb3b185d9e4b5f5
|
[
"BSD-3-Clause"
] | 148
|
2015-01-31T16:13:46.000Z
|
2022-03-23T20:23:43.000Z
|
/*** Copyright (c), The Unregents of the University of California ***
*** For more information please refer to files in the COPYRIGHT directory ***/
/* rsQuerySpecColl.c
*/
#include "querySpecColl.h"
#include "rcMisc.h"
#include "fileOpendir.h"
#include "fileReaddir.h"
#include "fileClosedir.h"
#include "objMetaOpr.hpp"
#include "specColl.hpp"
#include "dataObjClose.h"
#include "subStructFileOpendir.h"
#include "subStructFileReaddir.h"
#include "subStructFileClosedir.h"
#include "fileStat.h"
#include "genQuery.h"
#include "rsGlobalExtern.hpp"
#include "rcGlobalExtern.h"
#include "rsQuerySpecColl.hpp"
#include "rsSubStructFileReaddir.hpp"
#include "rsDataObjClose.hpp"
#include "rsFileReaddir.hpp"
#include "rsSubStructFileClosedir.hpp"
#include "rsFileClosedir.hpp"
#include "rsSubStructFileOpendir.hpp"
#include "rsFileOpendir.hpp"
#include "rsObjStat.hpp"
#include "irods_resource_backport.hpp"
#include "irods_resource_redirect.hpp"
#include "irods_stacktrace.hpp"
#include "irods_hierarchy_parser.hpp"
int
rsQuerySpecColl( rsComm_t *rsComm, dataObjInp_t *dataObjInp,
genQueryOut_t **genQueryOut ) {
int specCollInx;
int status;
int continueFlag; /* continue query */
int remoteFlag;
rodsServerHost_t *rodsServerHost;
remoteFlag = getAndConnRcatHost(
rsComm,
SLAVE_RCAT,
( const char* )dataObjInp->objPath,
&rodsServerHost );
if ( remoteFlag < 0 ) {
return remoteFlag;
}
else if ( remoteFlag == REMOTE_HOST ) {
status = rcQuerySpecColl( rodsServerHost->conn, dataObjInp,
genQueryOut );
return status;
}
// =-=-=-=-=-=-=-
// working on the "home zone", determine if we need to redirect to a different
// server in this zone for this operation. if there is a RESC_HIER_STR_KW then
// we know that the redirection decision has already been made
char* hier_kw = getValByKey( &dataObjInp->condInput, RESC_HIER_STR_KW );
if (!hier_kw) {
try {
auto result = irods::resolve_resource_hierarchy(irods::OPEN_OPERATION, rsComm, *dataObjInp);
const auto& hier = std::get<std::string>(result);
addKeyVal( &dataObjInp->condInput, RESC_HIER_STR_KW, hier.c_str() );
}
catch (const irods::exception& e ) {
irods::log(e);
return e.code();
}
}
if ( ( specCollInx = dataObjInp->openFlags ) <= 0 ) {
specCollInx = openSpecColl( rsComm, dataObjInp, -1 );
if ( specCollInx < 0 ) {
rodsLog( LOG_NOTICE,
"rsQuerySpecColl: openSpecColl error for %s, status = %d",
dataObjInp->objPath, specCollInx );
return specCollInx;
}
continueFlag = 0;
}
else {
continueFlag = 1;
}
initOutForQuerySpecColl( genQueryOut );
status = _rsQuerySpecColl( rsComm, specCollInx, dataObjInp,
*genQueryOut, continueFlag );
if ( status < 0 ) {
freeGenQueryOut( genQueryOut );
}
return status;
}
int
openSpecColl( rsComm_t *rsComm, dataObjInp_t *dataObjInp, int parentInx ) {
int specCollInx;
dataObjInfo_t *dataObjInfo = NULL;
int status;
int l3descInx;
status = resolvePathInSpecColl( rsComm, dataObjInp->objPath,
//READ_COLL_PERM, 0, &dataObjInfo);
UNKNOWN_COLL_PERM, 0, &dataObjInfo );
if ( status < 0 || NULL == dataObjInfo ) { // JMC cppcheck - nullptr
rodsLog( LOG_NOTICE,
"rsQuerySpecColl: resolveSpecColl error for %s, status = %d",
dataObjInp->objPath, status );
return status;
}
if ( dataObjInfo->specColl->collClass == LINKED_COLL ) {
rodsLog( LOG_ERROR,
"rsQuerySpecColl: %s is a linked collection",
dataObjInp->objPath );
return SYS_UNKNOWN_SPEC_COLL_CLASS;
}
char* resc_hier = getValByKey( &dataObjInp->condInput, RESC_HIER_STR_KW );
if ( resc_hier ) {
strncpy( dataObjInfo->rescHier, resc_hier, MAX_NAME_LEN );
irods::error ret = resc_mgr.hier_to_leaf_id(resc_hier,dataObjInfo->rescId);
if( !ret.ok() ) {
irods::log(PASS(ret));
}
}
l3descInx = l3Opendir( rsComm, dataObjInfo );
if ( l3descInx < 0 ) {
rodsLog( LOG_NOTICE,
"openSpecColl: specCollOpendir error for %s, status = %d",
dataObjInp->objPath, l3descInx );
return l3descInx;
}
specCollInx = allocSpecCollDesc();
if ( specCollInx < 0 ) {
freeDataObjInfo( dataObjInfo );
return specCollInx;
}
SpecCollDesc[specCollInx].l3descInx = l3descInx;
SpecCollDesc[specCollInx].dataObjInfo = dataObjInfo;
SpecCollDesc[specCollInx].parentInx = parentInx;
return specCollInx;
}
int
initOutForQuerySpecColl( genQueryOut_t **genQueryOut ) {
genQueryOut_t *myGenQueryOut;
/* will do collection, dataName, createTime, modifyTime, objSize */
myGenQueryOut = *genQueryOut =
( genQueryOut_t * ) malloc( sizeof( genQueryOut_t ) );
memset( myGenQueryOut, 0, sizeof( genQueryOut_t ) );
myGenQueryOut->attriCnt = 5;
myGenQueryOut->sqlResult[0].attriInx = COL_COLL_NAME;
myGenQueryOut->sqlResult[0].len = MAX_NAME_LEN;
myGenQueryOut->sqlResult[0].value =
( char* )malloc( MAX_NAME_LEN * MAX_SPEC_COLL_ROW );
memset( myGenQueryOut->sqlResult[0].value, 0,
MAX_NAME_LEN * MAX_SPEC_COLL_ROW );
myGenQueryOut->sqlResult[1].attriInx = COL_DATA_NAME;
myGenQueryOut->sqlResult[1].len = MAX_NAME_LEN;
myGenQueryOut->sqlResult[1].value =
( char* )malloc( MAX_NAME_LEN * MAX_SPEC_COLL_ROW );
memset( myGenQueryOut->sqlResult[1].value, 0,
MAX_NAME_LEN * MAX_SPEC_COLL_ROW );
myGenQueryOut->sqlResult[2].attriInx = COL_D_CREATE_TIME;
myGenQueryOut->sqlResult[2].len = NAME_LEN;
myGenQueryOut->sqlResult[2].value =
( char* )malloc( NAME_LEN * MAX_SPEC_COLL_ROW );
memset( myGenQueryOut->sqlResult[2].value, 0,
NAME_LEN * MAX_SPEC_COLL_ROW );
myGenQueryOut->sqlResult[3].attriInx = COL_D_MODIFY_TIME;
myGenQueryOut->sqlResult[3].len = NAME_LEN;
myGenQueryOut->sqlResult[3].value =
( char* )malloc( NAME_LEN * MAX_SPEC_COLL_ROW );
memset( myGenQueryOut->sqlResult[3].value, 0,
NAME_LEN * MAX_SPEC_COLL_ROW );
myGenQueryOut->sqlResult[4].attriInx = COL_DATA_SIZE;
myGenQueryOut->sqlResult[4].len = NAME_LEN;
myGenQueryOut->sqlResult[4].value =
( char* )malloc( NAME_LEN * MAX_SPEC_COLL_ROW );
memset( myGenQueryOut->sqlResult[4].value, 0,
NAME_LEN * MAX_SPEC_COLL_ROW );
myGenQueryOut->continueInx = -1;
return 0;
}
int
_rsQuerySpecColl( rsComm_t *rsComm, int specCollInx,
dataObjInp_t *dataObjInp, genQueryOut_t *genQueryOut, int continueFlag ) {
int status = 0;
rodsDirent_t *rodsDirent = NULL;
dataObjInfo_t *dataObjInfo;
int rowCnt;
objType_t selObjType;
char *tmpStr;
dataObjInp_t newDataObjInp;
int recurFlag;
if ( SpecCollDesc[specCollInx].inuseFlag != FD_INUSE ) {
rodsLog( LOG_ERROR,
"_rsQuerySpecColl: Input specCollInx %d not active", specCollInx );
return BAD_INPUT_DESC_INDEX;
}
if ( ( tmpStr = getValByKey( &dataObjInp->condInput, SEL_OBJ_TYPE_KW ) ) !=
NULL ) {
if ( strcmp( tmpStr, "dataObj" ) == 0 ) {
selObjType = DATA_OBJ_T;
}
else {
selObjType = COLL_OBJ_T;
}
}
else {
selObjType = UNKNOWN_OBJ_T;
}
if ( getValByKey( &dataObjInp->condInput, RECURSIVE_OPR__KW ) != NULL ) {
recurFlag = 1;
}
else {
recurFlag = 0;
}
dataObjInfo = SpecCollDesc[specCollInx].dataObjInfo;
while ( genQueryOut->rowCnt < MAX_SPEC_COLL_ROW ) {
dataObjInfo_t myDataObjInfo;
rodsDirent_t myRodsDirent;
status = specCollReaddir( rsComm, specCollInx, &rodsDirent );
if ( status < 0 ) {
break;
}
myRodsDirent = *rodsDirent;
free( rodsDirent );
if ( strcmp( myRodsDirent.d_name, "." ) == 0 ||
strcmp( myRodsDirent.d_name, ".." ) == 0 ) {
continue;
}
myDataObjInfo = *dataObjInfo;
snprintf( myDataObjInfo.subPath, MAX_NAME_LEN, "%s/%s",
dataObjInfo->subPath, myRodsDirent.d_name );
snprintf( myDataObjInfo.filePath, MAX_NAME_LEN, "%s/%s",
dataObjInfo->filePath, myRodsDirent.d_name );
rodsStat_t *fileStatOut = NULL;
status = l3Stat( rsComm, &myDataObjInfo, &fileStatOut );
if ( status < 0 ) {
rodsLog( LOG_ERROR,
"_rsQuerySpecColl: l3Stat for %s error, status = %d",
myDataObjInfo.filePath, status );
/* XXXXX need clean up */
return status;
}
if ( ( fileStatOut->st_mode & S_IFREG ) != 0 ) { /* a file */
if ( selObjType == COLL_OBJ_T ) {
free( fileStatOut );
continue;
}
rowCnt = genQueryOut->rowCnt;
rstrcpy( &genQueryOut->sqlResult[0].value[MAX_NAME_LEN * rowCnt],
dataObjInfo->subPath, MAX_NAME_LEN );
rstrcpy( &genQueryOut->sqlResult[1].value[MAX_NAME_LEN * rowCnt],
myRodsDirent.d_name, MAX_NAME_LEN );
snprintf( &genQueryOut->sqlResult[2].value[NAME_LEN * rowCnt],
NAME_LEN, "%d", fileStatOut->st_ctim );
snprintf( &genQueryOut->sqlResult[3].value[NAME_LEN * rowCnt],
NAME_LEN, "%d", fileStatOut->st_mtim );
snprintf( &genQueryOut->sqlResult[4].value[NAME_LEN * rowCnt],
NAME_LEN, "%lld", fileStatOut->st_size );
free( fileStatOut );
genQueryOut->rowCnt++;
}
else {
if ( selObjType != DATA_OBJ_T ) {
rowCnt = genQueryOut->rowCnt;
rstrcpy( &genQueryOut->sqlResult[0].value[MAX_NAME_LEN * rowCnt],
myDataObjInfo.subPath, MAX_NAME_LEN );
snprintf( &genQueryOut->sqlResult[2].value[NAME_LEN * rowCnt],
NAME_LEN, "%d", fileStatOut->st_ctim );
snprintf( &genQueryOut->sqlResult[3].value[NAME_LEN * rowCnt],
NAME_LEN, "%d", fileStatOut->st_mtim );
snprintf( &genQueryOut->sqlResult[4].value[NAME_LEN * rowCnt],
NAME_LEN, "%lld", fileStatOut->st_size );
genQueryOut->rowCnt++;
}
free( fileStatOut );
if ( recurFlag > 0 ) {
/* need to drill down */
int newSpecCollInx;
newDataObjInp = *dataObjInp;
rstrcpy( newDataObjInp.objPath, dataObjInfo->subPath,
MAX_NAME_LEN );
newSpecCollInx =
openSpecColl( rsComm, &newDataObjInp, specCollInx );
if ( newSpecCollInx < 0 ) {
rodsLog( LOG_ERROR,
"_rsQuerySpecColl: openSpecColl err for %s, stat = %d",
newDataObjInp.objPath, newSpecCollInx );
status = newSpecCollInx;
break;
}
status = _rsQuerySpecColl( rsComm, newSpecCollInx,
&newDataObjInp, genQueryOut, 0 );
if ( status < 0 ) {
break;
}
}
}
} // while
if ( status == EOF || status == CAT_NO_ROWS_FOUND ) {
status = 0;
}
if ( genQueryOut->rowCnt < MAX_SPEC_COLL_ROW ) {
int parentInx;
/* get to the end or error */
specCollClosedir( rsComm, specCollInx );
parentInx = SpecCollDesc[specCollInx].parentInx;
freeSpecCollDesc( specCollInx );
if ( status >= 0 && recurFlag && continueFlag && parentInx > 0 ) {
newDataObjInp = *dataObjInp;
rstrcpy( newDataObjInp.objPath,
SpecCollDesc[parentInx].dataObjInfo->objPath, MAX_NAME_LEN );
status = _rsQuerySpecColl( rsComm, parentInx,
&newDataObjInp, genQueryOut, continueFlag );
}
else {
/* no more */
genQueryOut->continueInx = -1;
}
if ( status == EOF || status == CAT_NO_ROWS_FOUND ) {
status = 0;
}
}
else {
/* more to come */
if ( genQueryOut->continueInx < 0 ) {
/* if one does not already exist */
genQueryOut->continueInx = specCollInx;
}
}
if ( status >= 0 && genQueryOut->rowCnt == 0 ) {
status = CAT_NO_ROWS_FOUND;
}
return status;
}
int
specCollReaddir( rsComm_t *rsComm, int specCollInx, rodsDirent_t **rodsDirent ) {
fileReaddirInp_t fileReaddirInp;
specColl_t *specColl;
int status;
dataObjInfo_t *dataObjInfo = SpecCollDesc[specCollInx].dataObjInfo;
if ( dataObjInfo == NULL || ( specColl = dataObjInfo->specColl ) == NULL ) {
return SYS_INTERNAL_NULL_INPUT_ERR;
}
// =-=-=-=-=-=-=-
// get the resc location of the hier leaf
std::string location;
irods::error ret = irods::get_loc_for_hier_string( dataObjInfo->rescHier, location );
if ( !ret.ok() ) {
irods::log( PASSMSG( "specCollReaddir - failed in get_loc_for_hier_string", ret ) );
return -1;
}
if ( getStructFileType( dataObjInfo->specColl ) >= 0 ) {
subStructFileFdOprInp_t subStructFileReaddirInp;
memset( &subStructFileReaddirInp, 0, sizeof( subStructFileReaddirInp ) );
subStructFileReaddirInp.type = dataObjInfo->specColl->type;
subStructFileReaddirInp.fd = SpecCollDesc[specCollInx].l3descInx;
rstrcpy( subStructFileReaddirInp.addr.hostAddr,
location.c_str(), NAME_LEN );
rstrcpy( subStructFileReaddirInp.resc_hier,
dataObjInfo->rescHier,
MAX_NAME_LEN );
status = rsSubStructFileReaddir( rsComm, &subStructFileReaddirInp,
rodsDirent );
}
else if ( specColl->collClass == MOUNTED_COLL ) {
fileReaddirInp.fileInx = SpecCollDesc[specCollInx].l3descInx;
status = rsFileReaddir( rsComm, &fileReaddirInp, rodsDirent );
}
else {
rodsLog( LOG_ERROR,
"specCollReaddir: Unknown specColl collClass = %d",
specColl->collClass );
status = SYS_UNKNOWN_SPEC_COLL_CLASS;
}
return status;
}
int
specCollClosedir( rsComm_t *rsComm, int specCollInx ) {
fileClosedirInp_t fileClosedirInp;
specColl_t *specColl;
int status;
dataObjInfo_t *dataObjInfo = SpecCollDesc[specCollInx].dataObjInfo;
if ( dataObjInfo == NULL || ( specColl = dataObjInfo->specColl ) == NULL ) {
return SYS_INTERNAL_NULL_INPUT_ERR;
}
// =-=-=-=-=-=-=-
// get the resc location of the hier leaf
std::string location;
irods::error ret = irods::get_loc_for_hier_string( dataObjInfo->rescHier, location );
if ( !ret.ok() ) {
irods::log( PASSMSG( "specCollClosedir - failed in get_loc_for_hier_string", ret ) );
return -1;
}
if ( getStructFileType( dataObjInfo->specColl ) >= 0 ) {
subStructFileFdOprInp_t subStructFileClosedirInp;
memset( &subStructFileClosedirInp, 0, sizeof( subStructFileClosedirInp ) );
subStructFileClosedirInp.type = dataObjInfo->specColl->type;
subStructFileClosedirInp.fd = SpecCollDesc[specCollInx].l3descInx;
rstrcpy( subStructFileClosedirInp.addr.hostAddr,
location.c_str(),
NAME_LEN );
rstrcpy( subStructFileClosedirInp.resc_hier,
dataObjInfo->rescHier,
MAX_NAME_LEN );
status = rsSubStructFileClosedir( rsComm, &subStructFileClosedirInp );
}
else if ( specColl->collClass == MOUNTED_COLL ) {
fileClosedirInp.fileInx = SpecCollDesc[specCollInx].l3descInx;
status = rsFileClosedir( rsComm, &fileClosedirInp );
}
else {
rodsLog( LOG_ERROR,
"specCollClosedir: Unknown specColl collClass = %d",
specColl->collClass );
status = SYS_UNKNOWN_SPEC_COLL_CLASS;
}
return status;
}
int
l3Opendir( rsComm_t *rsComm, dataObjInfo_t *dataObjInfo ) {
fileOpendirInp_t fileOpendirInp;
int status;
if ( dataObjInfo == NULL ) {
return SYS_INTERNAL_NULL_INPUT_ERR;
}
// =-=-=-=-=-=-=-
// get the resc location of the hier leaf
std::string location;
irods::error ret = irods::get_loc_for_hier_string( dataObjInfo->rescHier, location );
if ( !ret.ok() ) {
irods::log( PASSMSG( "l3Opendir - failed in get_loc_for_hier_string", ret ) );
return -1;
}
if ( getStructFileType( dataObjInfo->specColl ) >= 0 ) {
subFile_t subStructFileOpendirInp;
memset( &subStructFileOpendirInp, 0, sizeof( subStructFileOpendirInp ) );
rstrcpy( subStructFileOpendirInp.subFilePath, dataObjInfo->subPath, MAX_NAME_LEN );
//rstrcpy( subStructFileOpendirInp.addr.hostAddr, dataObjInfo->rescInfo->rescLoc, NAME_LEN );
rstrcpy( subStructFileOpendirInp.addr.hostAddr, location.c_str(), NAME_LEN );
subStructFileOpendirInp.specColl = dataObjInfo->specColl;
status = rsSubStructFileOpendir( rsComm, &subStructFileOpendirInp );
}
else {
memset( &fileOpendirInp, 0, sizeof( fileOpendirInp ) );
rstrcpy( fileOpendirInp.dirName, dataObjInfo->filePath, MAX_NAME_LEN );
rstrcpy( fileOpendirInp.resc_name_, dataObjInfo->rescName, MAX_NAME_LEN );
rstrcpy( fileOpendirInp.resc_hier_, dataObjInfo->rescHier, MAX_NAME_LEN );
rstrcpy( fileOpendirInp.addr.hostAddr, location.c_str(), NAME_LEN );
status = rsFileOpendir( rsComm, &fileOpendirInp );
if ( status < 0 ) {
rodsLog( LOG_ERROR,
"l3Opendir: rsFileOpendir for %s error, status = %d",
dataObjInfo->filePath, status );
}
}
return status;
}
| 35.714012
| 104
| 0.599291
|
JustinKyleJames
|
c8066f8a93d79afc2b8617619e8c4a6373223281
| 609
|
cpp
|
C++
|
Sistem Bilangan Digital/05_Decimal_to_Hexa.cpp
|
wardimanxixv/CPP-Basic
|
332adde53ebc73bef20080a7cf7f195820394c37
|
[
"MIT"
] | null | null | null |
Sistem Bilangan Digital/05_Decimal_to_Hexa.cpp
|
wardimanxixv/CPP-Basic
|
332adde53ebc73bef20080a7cf7f195820394c37
|
[
"MIT"
] | null | null | null |
Sistem Bilangan Digital/05_Decimal_to_Hexa.cpp
|
wardimanxixv/CPP-Basic
|
332adde53ebc73bef20080a7cf7f195820394c37
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
int main()
{
long int decimalNumber, remainder, quotient;
int i = 1, j, temp;
char hexadecimalNumber[100];
cout << "Masukkan Bilangan Decimal : "; cin >> decimalNumber;
quotient = decimalNumber;
while (quotient != 0)
{
temp = quotient % 16;
if (temp < 10) {
temp = temp + 48;
}
else {
temp = temp + 55;
}
hexadecimalNumber[i++] = temp;
quotient = quotient / 16;
}
cout << "Bilangan Hexadecimalnya adalah : ";
for (j = i; j > 0; j--)
{
cout << hexadecimalNumber[j];
}
return 0;
}
//@wardiman_xixv
| 19.03125
| 63
| 0.584565
|
wardimanxixv
|
c807bd8d0fbb1cc985db83edcbc2d5d1384e1cf9
| 5,697
|
hpp
|
C++
|
include/engine/Logger.hpp
|
Mathieu-Lala/NewDimension
|
9200692e79dc1d983f51043f3c195eb1b865a74d
|
[
"0BSD"
] | 4
|
2019-11-19T23:53:26.000Z
|
2019-12-10T11:19:28.000Z
|
include/engine/Logger.hpp
|
Mathieu-Lala/NewDimension
|
9200692e79dc1d983f51043f3c195eb1b865a74d
|
[
"0BSD"
] | null | null | null |
include/engine/Logger.hpp
|
Mathieu-Lala/NewDimension
|
9200692e79dc1d983f51043f3c195eb1b865a74d
|
[
"0BSD"
] | null | null | null |
/*
** EPITECH PROJECT, 2019
** NewDimension
** File description:
** Logger
*/
#ifndef LOGGER_HPP_
# define LOGGER_HPP_
# include <ostream>
# include <iostream>
# include <array>
# include <ctime>
# include <functional>
# include "config/config.hpp"
namespace nd {
namespace engine {
class Logger {
public:
Logger() = delete;
static bool set_stream(const std::string_view filepath);
enum level {
DEBUG,
INFO,
NOTICE,
WARNING,
ERROR,
ALERT,
CRITIC,
EMERGENCY,
UNKNOWN,
};
inline static level get_current_level() noexcept
{ return s_current_level; }
inline static void set_current_level(level new_level) noexcept
{ s_current_level = new_level; }
struct data {
level msg_level;
const char *file;
int line;
const char *func;
std::time_t timestamp;
};
static std::ostream &dump_info(const data &data_info);
inline static void set_format(const std::string &new_format) noexcept
{ s_display_format = new_format; }
protected:
private:
static std::ostream *s_stream;
static level s_current_level;
static std::string s_display_format;
static constexpr std::ostream *DEFAULT_STREAM = &std::cerr;
static constexpr level DEFAULT_LEVEL = DEBUG;
static constexpr auto DEFAULT_DISPLAY_FORMAT =
"[${info:level}] id:${info:uid} at:${style:underline}${info:timestamp}${style:reset} "
"in file ${info:file} at line ${style:bold:underline}${info:line}${style:reset} "
"in function ${style:fg-blue:bold}${info:func}${style:reset}:\r\n";
using uid = std::size_t;
static uid s_current_msg_uid;
static constexpr std::array S_LEVEL_AS_STRING {
std::make_pair(DEBUG, "${style:fg-lightcyan}DEBUG${style:reset}"),
std::make_pair(INFO, "${style:fg-lightgreen}INFO${style:reset}"),
std::make_pair(NOTICE, "${style:fg-green}NOTICE${style:reset}"),
std::make_pair(WARNING, "${style:fg-lightyellow}WARNING${style:reset}"),
std::make_pair(ERROR, "${style:fg-red:bold}ERROR${style:reset}"),
std::make_pair(ALERT, "${style:fg-lightred:underline:bold}ALERT${style:reset}"),
std::make_pair(CRITIC, "${style:fg-black:blink:bg-yellow}CRITIC${style:reset}"),
std::make_pair(EMERGENCY, "${style:fg-black:blink:bold:underline:bg-lightred}EMERGENCY${style:reset}"),
};
static constexpr std::optional<const char *> level_as_string(level search);
using PairStyle = std::pair<const char *, const char *>;
static constexpr std::array<const PairStyle, 47> S_SUPPORTED_STYLE {
// Colors
std::make_pair("fg-red", "31"), std::make_pair("bg-red", "41"),
std::make_pair("fg-lightred", "91"), std::make_pair("bg-lightred", "101"),
std::make_pair("fg-green", "32"), std::make_pair("bg-green", "42"),
std::make_pair("fg-lightgreen", "92"), std::make_pair("bg-lightgreen", "102"),
std::make_pair("fg-blue", "34"), std::make_pair("bg-blue", "44"),
std::make_pair("fg-lightblue", "94"), std::make_pair("bg-lightblue", "104"),
std::make_pair("fg-yellow", "33"), std::make_pair("bg-yellow", "43"),
std::make_pair("fg-lightyellow", "93"), std::make_pair("bg-lightyellow", "103"),
std::make_pair("fg-magenta", "35"), std::make_pair("bg-magenta", "45"),
std::make_pair("fg-lightmagenta", "95"), std::make_pair("bg-lightmagenta", "105"),
std::make_pair("fg-cyan", "36"), std::make_pair("bg-cyan", "46"),
std::make_pair("fg-lightcyan", "96"), std::make_pair("bg-lightcyan", "106"),
std::make_pair("fg-white", "97"), std::make_pair("bg-white", "107"),
std::make_pair("fg-lightgrey", "37"), std::make_pair("bg-lightgrey", "47"),
std::make_pair("fg-darkgrey", "90"), std::make_pair("bg-drakgrey", "100"),
std::make_pair("fg-black", "30"), std::make_pair("bg-black", "40"),
std::make_pair("fg-default", "39"), std::make_pair("bg-default", "49"),
// ... complete me
// Styles / Effects
std::make_pair("bold", "1"), std::make_pair("bold-off", "21"),
std::make_pair("dim", "2"), std::make_pair("dim-off", "22"),
std::make_pair("underline", "4"), std::make_pair("underline-off", "24"),
std::make_pair("blink", "5"), std::make_pair("blink-off", "25"),
std::make_pair("inverse", "7"), std::make_pair("inverse-off", "27"),
std::make_pair("hidden", "8"), std::make_pair("hidden-off", "28"),
// ... complete me
std::make_pair("reset", "0"),
};
static constexpr std::optional<PairStyle> get_style_value(const char *search);
};
} // namespace engine
} // namespace new dimension
# define LOG(level, exp) do { \
if (nd::engine::Logger::get_current_level() <= level) \
nd::engine::Logger::dump_info({ level, __FILE__, __LINE__, __func__, std::time(nullptr) }) \
<< exp << std::endl; \
} while (false)
# if PROJECT_BUILD_TYPE == Debug
# define DEBUG(exp) LOG(nd::engine::Logger::DEBUG, exp)
# else
# define DEBUG(exp)
# endif
# define INFO(exp) LOG(nd::engine::Logger::INFO, exp)
# define NOTICE(exp) LOG(nd::engine::Logger::NOTICE, exp)
# define WARNING(exp) LOG(nd::engine::Logger::WARNING, exp)
# define ERROR(exp) LOG(nd::engine::Logger::ERROR, exp)
# define ALERT(exp) LOG(nd::engine::Logger::ALERT, exp)
# define CRITIC(exp) LOG(nd::engine::Logger::CRITIC, exp)
# define EMERGENCY(exp) LOG(nd::engine::Logger::EMERGENCY, exp)
#endif /* !LOGGER_HPP_ */
| 35.385093
| 111
| 0.610848
|
Mathieu-Lala
|
c807e185b44fcba37d206a60d9a6e874368e4074
| 16,032
|
cpp
|
C++
|
common.cpp
|
SBcodework/Minesweeper-in-C-
|
e2ca6364f5afc6faa3ca723a926c64603d0f4ffc
|
[
"BSD-2-Clause"
] | null | null | null |
common.cpp
|
SBcodework/Minesweeper-in-C-
|
e2ca6364f5afc6faa3ca723a926c64603d0f4ffc
|
[
"BSD-2-Clause"
] | 4
|
2019-06-28T18:08:49.000Z
|
2019-07-04T03:41:32.000Z
|
common.cpp
|
SBcodework/Minesweeper-in-C-
|
e2ca6364f5afc6faa3ca723a926c64603d0f4ffc
|
[
"BSD-2-Clause"
] | null | null | null |
/**
BSD 2-Clause License
Copyright (c) 2019, SBcodework
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**/
#include <iostream>
#include "common.h"
#include "Parameter.h"
#include "Gridtype.h"
#include "Cordtype.h"
#include <string>
#include <typeinfo>
#include <algorithm>
#include <vector>
#include <bitset>
#include <random>
#include <time.h>
#include <cmath>
int extractDigitInt( int digits, std::string input )
{
int result = 0;
int length = input.length();
if ( length == 0 || digits < 0 )
{
return -1;
}
/// Find the furthest index of the string representing the smallest digit (under 10) as string length permits.
int digitsFirstGuess = digits; //(length > digits) ? length : digits;
int digitsSecondGuess = 0; /// Below: find the first digit.
for ( int i = 0; (i < digitsFirstGuess) && (isdigit(input[i])) && (i < length); i++ )
{
digitsSecondGuess++;
}
if ( digitsSecondGuess == 0 )
{
return -1;
}
//float digit = digitsSecondGuess;
for ( int i = (digitsSecondGuess - 1), magnitude = 0, inputDigit = 0, power = 0; i >= 0; i--, power++ ) /// Start backwards from the furthest index
{
inputDigit = (int)(input[i] - '0');
magnitude = (int)(std::pow(10.0, (float)power));
result += (inputDigit * magnitude);
}
return result;
}
void askXYMinesLoop(Parameter& out_param)
{
int x, y, mines, area; // Output containers
std::string strx;
std::string stry;
std::string strMines;
for (;;)
{
std::cout << "Grid Length? ";
std::cin >> strx;
std::cout << "Grid Height? ";
std::cin >> stry;
std::cout << "Number of mines? ";
std::cin >> strMines;
x = extractDigitInt(2, strx);
y = extractDigitInt(2, stry);
mines = extractDigitInt(4, strMines); //4 digits
if ( x < 1 || y < 1 || mines < 1 || x > 99 || y > 99 || mines > 9801 ||
( x < 4 && y < 4 ) || ( mines > ((x*y)-9) ) )
{
std::cout << "Invalid input! Try again.\n";
continue;
}
out_param.length = x;
out_param.height = y;
out_param.mines = mines;
out_param.init_dimensions();
return;
break;
}
}
void dispEmpty(Parameter& in_param)
{
int length = in_param.length;
int height = in_param.height;
std::cout << " "; // 5 spaces
for (int i=0; i<length; i++)
{
std::cout << "{" << (i/10) << (i%10) << "}";
}
std::cout << "\n";
for (int i=0; i<height; i++)
{
std::cout << "{" << (i/10) << (i%10) << "} ";
for (int n=0; n<length; n++)
{
std::cout << "[ ]";
}
std::cout << "\n";
}
return;
}
int askStartXYLoop(Parameter& out_param)
{
int error = 0, length = 0;
std::string line; // "cin.get()" Is not used, as it skips the first character of input.
for (int skip = 0; ;skip = 0)
{
line = ""; // Reset the line each loop
std::cout << "Enter X cord, followed by a comma, and Y cord. Like '13,8'. \n";
std::cin >> line;
length = line.length();
//std::getline(std::cin, line); Old method, above worked better
if ( (length < 3) || ((line[1] != ',') && (line[2] != ',')) || !isdigit(line[0]) ||
(!isdigit(line[1]) && (line[1] != ',')) || (!isdigit(line[2]) && (line[2] != ',')) ||
((length > 3) && (line[2] == ',') && !isdigit(line[3]) ) )
{
std::cout << "Invalid! Try again. Line: " << line << "\n";
continue;
}
error = h_extractCoords(line, out_param.xStart, out_param.yStart, nullptr, ',');
if ((out_param.xStart >= out_param.length) || (out_param.yStart >= out_param.height))
{
std::cout << "Coordinates out of range! Try again. Line: " << line << "\n";
continue;
}
switch (error)
{
case 0:
break;
case 1:
std::cout << "Error in askStartXYLoop! ";
std::cout << "x, y: " << out_param.xStart << " " << out_param.yStart << "\n";
return 1;
case 2:
std::cout << "Invalid! Try again. Line: " << line << "\n";
skip = 1;
}
if (skip)
{
continue;
}
out_param.init_start();
return 0;
}
}
int h_extractCoords(std::string in_line, int& out_x, int& out_y, char* out_sep, char sep)
{
int length = in_line.length();
if ( (length < 3) || (length > 5) )
{
return 2; // Too long or too short; for legacy reasons 2 is the error code for user errors
}
int x = extractDigitInt( 2, in_line );
int slicedStart = (x < 10) ? 2 : 3;
if ( (x == -1) || (slicedStart > length) )
{
return 2; // Invalid X or string is too short for a separator to fit
}
char separator = in_line[slicedStart - 1];
if ( ( (separator != sep) && sep != '\0' ) || ( (sep == '\0') && isdigit(separator) ) )
{
return 2; // An invalid separator is found when it is defined in the arguments, or if the separator is a digit when searching for one.
}
std::string slicedString = in_line.substr( slicedStart, length );
int y = extractDigitInt( 2, slicedString );
if ( y == -1 )
{
return 2; // Invalid y
}
if ( out_sep != nullptr )
{
*out_sep = separator;
}
out_x = x;
out_y = y;
return 0;
}
void gengrid(Gridtype& out_grid)
{ // Parameters are declared below
srand(time(0)); // Init randomizer
Parameter* params = out_grid.pParams;
int w = params->length;
int h = params->height;
int area = h*w;
int xstart = params->xStart;
int ystart = params->yStart;
int istart = params->iStart; //Unneeded at the moment
int mines = params->mines;
char* rawGrid = new char[area];
std::fill_n(rawGrid, area, '0'); // Fill with zeros
int startSquare[9] {0}; // Indexes of the start square
getSquare(xstart, ystart, w, h, startSquare);
int clearCounter = 0;
for (int i = 0, state = 0 ; i<9 ; i++) // Go through startSquare
{
state = startSquare[i]; /*
if (state > -1 && state < area)
{
continue;
}*/
if (state != -1 && state < area) // -1 means an invalid spot
{
rawGrid[state] = 'c';
clearCounter++; // Count the number of valid mine-less spots
}
}
int* mineList = new int[mines];
std::fill_n(mineList, mines, 0);
int mineLCounter = 0;
int mineCandidates[mines + 9] {0};
uniqueRand(mines+9, 0, area, mineCandidates); // mineCandidates now has a list of unique mines.
for (int i = 0; ((i < mines+9) && (mineLCounter < mines)) ; i++)
{
if ((rawGrid[mineCandidates[i]] != 'c') && mineLCounter < (mines))
{
mineList[mineLCounter] = mineCandidates[i];
rawGrid[mineList[mineLCounter]] = 'X';
mineLCounter++; /// This needs to be here, not in the above for() declaration.
}
}
for (int i = 0, state = 0 ; i<9 ; i++) // Go through startSquare, set back to 0's, we don't need 'c's anymore
{
state = startSquare[i];
if (state != -1 && state < area) // -1 means an invalid spot
{
rawGrid[state] = '0';
}
}
for (int i = 0, square[9] {0}, currentMine; i < mines; i++) // Count numbers and put them in
{
currentMine = mineList[i];
getSquare(currentMine % w, currentMine / w, w, h, square); ///Watch in case of bug
for (int n = 0, state = 0; n < 9; n++)
{
state = square[n];
if ( state != -1 && rawGrid[state] != 'X' && rawGrid[state] >= '0' && rawGrid[state] < '8' )
{
rawGrid[state]++; // '0' goes to '1' and so on
}
}
}
out_grid.set_grid(rawGrid); // Return
out_grid.set_minelist(mineList);
out_grid.action( istart, 's' );
return;
}
void getSquare(int centerX, int centerY, int w, int h, int out_square[9])
{
int xpart = 0;
int ypart = 0;
int startX = centerX - 1;
int startY = centerY - 1;
for (int iy = 0, counter = 0; iy < 3 ; iy++)
{
for (int ix = 0; ix < 3; ix++, counter++)
{
xpart = startX + ix;
ypart = startY + iy;
out_square[counter] = toIndexCheck(xpart, ypart, w, h);
}
}
return;
}
int toIndexCheck(int x, int y, int w, int h)
{
if (outOfBounds(x, y, w, h))
{
return -1;
}
return ((y*w) + x );
}
int outOfBounds(int x, int y, int w, int h)
{
if (x >= 0 && y >= 0 && x < w && y <h)
{
return 0;
}
return 1;
}
// Numlimit is exclusive. Output must be of size "size".
int uniqueRand(int size, int start, int numlimit, int* output)
{
/// init srand
std::vector<bool> bvector(numlimit, 0);
int currentStart = 0;
int currentEnd = 0; // Inclusive
int currentMiddle = 0; // Exclusive; the inclusive start of the second sequence.
int currentSize = 0;
for (int counter = 0; counter < size; counter++)
{
currentStart = start;
currentEnd = numlimit;
currentMiddle = (numlimit / 2); // Seperator at right. -1 used to be here
currentSize = numlimit - start; /// changed from numlimit
for (int state = 0, choice = 0 ; ; )
{
if (currentStart == (currentEnd-1))
{
if (bvector[currentStart] == 1)
{
std::cout << "Duplicate error!\n";
}
output[counter] = currentStart; // We have found our number
bvector[currentStart] = true;
break;
}
state = allCheck(currentStart, currentMiddle, currentEnd, bvector);
switch (state)
{
case 0: // Choose a random element. 0 = left, 1 = right.
choice = (rand() % 2);
break;
case 1: // Choose left
choice = 0;
break;
case 2: // Choose right
choice = 1;
break;
case 3:
std::cout << "Array full! Size: " << currentSize << " Start: " << currentStart << " Middle: " << currentMiddle << " End: " << currentEnd << "\n";
for ( int n=0; n<size; n++)
{
std::cout << output[n];
}
std::cout << "\n";
return 1;
}
switch (choice)
{
case 0:
currentEnd = currentMiddle;
currentSize = currentEnd - currentStart; // removed +1
currentMiddle = currentStart + (currentSize / 2); // removed -1, added currentstart
break;
case 1:
currentStart = currentMiddle; //removed +1
currentSize = currentEnd - currentStart; //removed +1
currentMiddle = currentStart + (currentSize / 2); //removed -1
break;
}
}
}
return 0;
}
// OLD documentation:
// Include start and end. Middle refers to the seperatation RIGHT of the index. It is added one locally, same with end.
// Return 0 if neither left or right is all 1's. 1 if only the left one has a zero in it, 2 if it's right, and 3 for both.
// New documentation: Include start, in_middle includes the start of the second sequence, in_end is exclusive.
int allCheck(int start, int middle, int end, std::vector<bool>& in_vector)
{
int allLeft = 1; // 1 meaning all ones are in the bit array.
int allRight = 1;
///int middle = in_middle + 1; // LEFT of index; testing
//int end = in_end + 1; // Exclusive
//int middle = (end - start) / 2;
for (int currentStart = start, currentEnd = middle, *flag = &allLeft, t = 0;
t < 2;
t++, currentStart = middle, currentEnd = end, flag = &allRight) // Two times, go through left and right
{
for (int i = currentStart , size = currentEnd - currentStart; i < currentEnd; i++ ) // Commented out portion was unused
{
if (in_vector[i] == false) // Remember to init the vector with zeroes, else seg fault here
{
*flag = 0; // There's a zero in the bit array.
break;
}
}
}
switch (allLeft + allRight)
{
case 0: // Neither are ones
return 0;
case 1:
if (allLeft) // Right only has no ones
{
return 2;
}
return 1; // Left has no ones
case 2:
std::cout << "Sub-array full! Dump: \n";
for ( int n=0; n<(end-start); n++)
{
std::cout << in_vector[n];
}
std::cout << "\n";
return 3; // Both have ones
}
std::cout << "Error in allCheck(...)!\n"; // Shouldn't reach here, added to avoid compiler warning
return 0;
}
void askSelectionXYTLoop( Cordtype& out_cord )
{
// Gather input (h_extract_cords)
// Output trimmed input to out_cord
// Find the seperator, then run h_extractcords
std::string line = "\0" ;
int x = 0, y = 0 ;
char sep = '1';
for (int error = 1, loopError = 1; loopError ;)
{
std::cout << "\nSelect a point and an action. 's' to uncover, 'm' to middle click, and 'f' to flag. Like '13f7'. \n";
std::cin >> line;
error = h_extractCoords( line, x, y, &sep ) ;
if ( error || (x < 0) || (y < 0) || (x > (out_cord.pParams->length)) || (y > (out_cord.pParams->height) ) )
{
std::cout << "Invalid input! Try again.\n";
continue;
}
switch (sep)
{
case 's':
case 'm':
case 'f':
loopError = 0;
break;
default:
std::cout << "AskXYT Error, sep is invalid! Sep: " << sep << ". Try again.\n";
}
}
out_cord.setter(x, y, sep) ;
return ;
}
| 31.130097
| 162
| 0.515594
|
SBcodework
|
c808a321f8cdb343a50a97fd6a0744fea37e4fd2
| 37,360
|
cpp
|
C++
|
llvm/lib/MC/MCContext.cpp
|
lxbndr/llvm-project
|
2b715b15f5f4c6dd60f05d1b62f9c404e8b56e34
|
[
"Apache-2.0"
] | null | null | null |
llvm/lib/MC/MCContext.cpp
|
lxbndr/llvm-project
|
2b715b15f5f4c6dd60f05d1b62f9c404e8b56e34
|
[
"Apache-2.0"
] | null | null | null |
llvm/lib/MC/MCContext.cpp
|
lxbndr/llvm-project
|
2b715b15f5f4c6dd60f05d1b62f9c404e8b56e34
|
[
"Apache-2.0"
] | null | null | null |
//===- lib/MC/MCContext.cpp - Machine Code Context ------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
#include "llvm/MC/MCContext.h"
#include "llvm/ADT/DenseMapInfo.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/Twine.h"
#include "llvm/BinaryFormat/COFF.h"
#include "llvm/BinaryFormat/ELF.h"
#include "llvm/BinaryFormat/Wasm.h"
#include "llvm/BinaryFormat/XCOFF.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCCodeView.h"
#include "llvm/MC/MCDwarf.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCFragment.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCLabel.h"
#include "llvm/MC/MCSectionCOFF.h"
#include "llvm/MC/MCSectionELF.h"
#include "llvm/MC/MCSectionGOFF.h"
#include "llvm/MC/MCSectionMachO.h"
#include "llvm/MC/MCSectionWasm.h"
#include "llvm/MC/MCSectionXCOFF.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCSubtargetInfo.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/MC/MCSymbolCOFF.h"
#include "llvm/MC/MCSymbolELF.h"
#include "llvm/MC/MCSymbolGOFF.h"
#include "llvm/MC/MCSymbolMachO.h"
#include "llvm/MC/MCSymbolWasm.h"
#include "llvm/MC/MCSymbolXCOFF.h"
#include "llvm/MC/MCTargetOptions.h"
#include "llvm/MC/SectionKind.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/SMLoc.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/raw_ostream.h"
#include <cassert>
#include <cstdlib>
#include <tuple>
#include <utility>
using namespace llvm;
static cl::opt<char*>
AsSecureLogFileName("as-secure-log-file-name",
cl::desc("As secure log file name (initialized from "
"AS_SECURE_LOG_FILE env variable)"),
cl::init(getenv("AS_SECURE_LOG_FILE")), cl::Hidden);
static void defaultDiagHandler(const SMDiagnostic &SMD, bool, const SourceMgr &,
std::vector<const MDNode *> &) {
SMD.print(nullptr, errs());
}
MCContext::MCContext(const Triple &TheTriple, const MCAsmInfo *mai,
const MCRegisterInfo *mri, const MCSubtargetInfo *msti,
const SourceMgr *mgr, MCTargetOptions const *TargetOpts,
bool DoAutoReset, StringRef Swift5ReflSegmentName)
: Swift5ReflectionSegmentName(Swift5ReflSegmentName), TT(TheTriple),
SrcMgr(mgr), InlineSrcMgr(nullptr), DiagHandler(defaultDiagHandler),
MAI(mai), MRI(mri), MSTI(msti), Symbols(Allocator), UsedNames(Allocator),
InlineAsmUsedLabelNames(Allocator),
CurrentDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0),
AutoReset(DoAutoReset), TargetOptions(TargetOpts) {
SecureLogFile = AsSecureLogFileName;
if (SrcMgr && SrcMgr->getNumBuffers())
MainFileName = std::string(SrcMgr->getMemoryBuffer(SrcMgr->getMainFileID())
->getBufferIdentifier());
switch (TheTriple.getObjectFormat()) {
case Triple::MachO:
Env = IsMachO;
break;
case Triple::COFF:
if (!TheTriple.isOSWindows())
report_fatal_error(
"Cannot initialize MC for non-Windows COFF object files.");
Env = IsCOFF;
break;
case Triple::ELF:
Env = IsELF;
break;
case Triple::Wasm:
Env = IsWasm;
break;
case Triple::XCOFF:
Env = IsXCOFF;
break;
case Triple::GOFF:
Env = IsGOFF;
break;
case Triple::UnknownObjectFormat:
report_fatal_error("Cannot initialize MC for unknown object file format.");
break;
}
}
MCContext::~MCContext() {
if (AutoReset)
reset();
// NOTE: The symbols are all allocated out of a bump pointer allocator,
// we don't need to free them here.
}
void MCContext::initInlineSourceManager() {
if (!InlineSrcMgr)
InlineSrcMgr.reset(new SourceMgr());
}
//===----------------------------------------------------------------------===//
// Module Lifetime Management
//===----------------------------------------------------------------------===//
void MCContext::reset() {
SrcMgr = nullptr;
InlineSrcMgr.reset();
LocInfos.clear();
DiagHandler = defaultDiagHandler;
// Call the destructors so the fragments are freed
COFFAllocator.DestroyAll();
ELFAllocator.DestroyAll();
GOFFAllocator.DestroyAll();
MachOAllocator.DestroyAll();
WasmAllocator.DestroyAll();
XCOFFAllocator.DestroyAll();
MCInstAllocator.DestroyAll();
MCSubtargetAllocator.DestroyAll();
InlineAsmUsedLabelNames.clear();
UsedNames.clear();
Symbols.clear();
Allocator.Reset();
Instances.clear();
CompilationDir.clear();
MainFileName.clear();
MCDwarfLineTablesCUMap.clear();
SectionsForRanges.clear();
MCGenDwarfLabelEntries.clear();
DwarfDebugFlags = StringRef();
DwarfCompileUnitID = 0;
CurrentDwarfLoc = MCDwarfLoc(0, 0, 0, DWARF2_FLAG_IS_STMT, 0, 0);
CVContext.reset();
MachOUniquingMap.clear();
ELFUniquingMap.clear();
GOFFUniquingMap.clear();
COFFUniquingMap.clear();
WasmUniquingMap.clear();
XCOFFUniquingMap.clear();
ELFEntrySizeMap.clear();
ELFSeenGenericMergeableSections.clear();
NextID.clear();
AllowTemporaryLabels = true;
DwarfLocSeen = false;
GenDwarfForAssembly = false;
GenDwarfFileNumber = 0;
HadError = false;
}
//===----------------------------------------------------------------------===//
// MCInst Management
//===----------------------------------------------------------------------===//
MCInst *MCContext::createMCInst() {
return new (MCInstAllocator.Allocate()) MCInst;
}
//===----------------------------------------------------------------------===//
// Symbol Manipulation
//===----------------------------------------------------------------------===//
MCSymbol *MCContext::getOrCreateSymbol(const Twine &Name) {
SmallString<128> NameSV;
StringRef NameRef = Name.toStringRef(NameSV);
assert(!NameRef.empty() && "Normal symbols cannot be unnamed!");
MCSymbol *&Sym = Symbols[NameRef];
if (!Sym)
Sym = createSymbol(NameRef, false, false);
return Sym;
}
MCSymbol *MCContext::getOrCreateFrameAllocSymbol(StringRef FuncName,
unsigned Idx) {
return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
"$frame_escape_" + Twine(Idx));
}
MCSymbol *MCContext::getOrCreateParentFrameOffsetSymbol(StringRef FuncName) {
return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + FuncName +
"$parent_frame_offset");
}
MCSymbol *MCContext::getOrCreateLSDASymbol(StringRef FuncName) {
return getOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + "__ehtable$" +
FuncName);
}
MCSymbol *MCContext::createSymbolImpl(const StringMapEntry<bool> *Name,
bool IsTemporary) {
static_assert(std::is_trivially_destructible<MCSymbolCOFF>(),
"MCSymbol classes must be trivially destructible");
static_assert(std::is_trivially_destructible<MCSymbolELF>(),
"MCSymbol classes must be trivially destructible");
static_assert(std::is_trivially_destructible<MCSymbolMachO>(),
"MCSymbol classes must be trivially destructible");
static_assert(std::is_trivially_destructible<MCSymbolWasm>(),
"MCSymbol classes must be trivially destructible");
static_assert(std::is_trivially_destructible<MCSymbolXCOFF>(),
"MCSymbol classes must be trivially destructible");
switch (getObjectFileType()) {
case MCContext::IsCOFF:
return new (Name, *this) MCSymbolCOFF(Name, IsTemporary);
case MCContext::IsELF:
return new (Name, *this) MCSymbolELF(Name, IsTemporary);
case MCContext::IsGOFF:
return new (Name, *this) MCSymbolGOFF(Name, IsTemporary);
case MCContext::IsMachO:
return new (Name, *this) MCSymbolMachO(Name, IsTemporary);
case MCContext::IsWasm:
return new (Name, *this) MCSymbolWasm(Name, IsTemporary);
case MCContext::IsXCOFF:
return createXCOFFSymbolImpl(Name, IsTemporary);
}
return new (Name, *this) MCSymbol(MCSymbol::SymbolKindUnset, Name,
IsTemporary);
}
MCSymbol *MCContext::createSymbol(StringRef Name, bool AlwaysAddSuffix,
bool CanBeUnnamed) {
if (CanBeUnnamed && !UseNamesOnTempLabels)
return createSymbolImpl(nullptr, true);
// Determine whether this is a user written assembler temporary or normal
// label, if used.
bool IsTemporary = CanBeUnnamed;
if (AllowTemporaryLabels && !IsTemporary)
IsTemporary = Name.startswith(MAI->getPrivateGlobalPrefix());
SmallString<128> NewName = Name;
bool AddSuffix = AlwaysAddSuffix;
unsigned &NextUniqueID = NextID[Name];
while (true) {
if (AddSuffix) {
NewName.resize(Name.size());
raw_svector_ostream(NewName) << NextUniqueID++;
}
auto NameEntry = UsedNames.insert(std::make_pair(NewName.str(), true));
if (NameEntry.second || !NameEntry.first->second) {
// Ok, we found a name.
// Mark it as used for a non-section symbol.
NameEntry.first->second = true;
// Have the MCSymbol object itself refer to the copy of the string that is
// embedded in the UsedNames entry.
return createSymbolImpl(&*NameEntry.first, IsTemporary);
}
assert(IsTemporary && "Cannot rename non-temporary symbols");
AddSuffix = true;
}
llvm_unreachable("Infinite loop");
}
MCSymbol *MCContext::createTempSymbol(const Twine &Name, bool AlwaysAddSuffix) {
SmallString<128> NameSV;
raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name;
return createSymbol(NameSV, AlwaysAddSuffix, true);
}
MCSymbol *MCContext::createNamedTempSymbol(const Twine &Name) {
SmallString<128> NameSV;
raw_svector_ostream(NameSV) << MAI->getPrivateGlobalPrefix() << Name;
return createSymbol(NameSV, true, false);
}
MCSymbol *MCContext::createLinkerPrivateTempSymbol() {
SmallString<128> NameSV;
raw_svector_ostream(NameSV) << MAI->getLinkerPrivateGlobalPrefix() << "tmp";
return createSymbol(NameSV, true, false);
}
MCSymbol *MCContext::createTempSymbol() { return createTempSymbol("tmp"); }
MCSymbol *MCContext::createNamedTempSymbol() {
return createNamedTempSymbol("tmp");
}
unsigned MCContext::NextInstance(unsigned LocalLabelVal) {
MCLabel *&Label = Instances[LocalLabelVal];
if (!Label)
Label = new (*this) MCLabel(0);
return Label->incInstance();
}
unsigned MCContext::GetInstance(unsigned LocalLabelVal) {
MCLabel *&Label = Instances[LocalLabelVal];
if (!Label)
Label = new (*this) MCLabel(0);
return Label->getInstance();
}
MCSymbol *MCContext::getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
unsigned Instance) {
MCSymbol *&Sym = LocalSymbols[std::make_pair(LocalLabelVal, Instance)];
if (!Sym)
Sym = createNamedTempSymbol();
return Sym;
}
MCSymbol *MCContext::createDirectionalLocalSymbol(unsigned LocalLabelVal) {
unsigned Instance = NextInstance(LocalLabelVal);
return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
}
MCSymbol *MCContext::getDirectionalLocalSymbol(unsigned LocalLabelVal,
bool Before) {
unsigned Instance = GetInstance(LocalLabelVal);
if (!Before)
++Instance;
return getOrCreateDirectionalLocalSymbol(LocalLabelVal, Instance);
}
MCSymbol *MCContext::lookupSymbol(const Twine &Name) const {
SmallString<128> NameSV;
StringRef NameRef = Name.toStringRef(NameSV);
return Symbols.lookup(NameRef);
}
void MCContext::setSymbolValue(MCStreamer &Streamer,
StringRef Sym,
uint64_t Val) {
auto Symbol = getOrCreateSymbol(Sym);
Streamer.emitAssignment(Symbol, MCConstantExpr::create(Val, *this));
}
void MCContext::registerInlineAsmLabel(MCSymbol *Sym) {
InlineAsmUsedLabelNames[Sym->getName()] = Sym;
}
MCSymbolXCOFF *
MCContext::createXCOFFSymbolImpl(const StringMapEntry<bool> *Name,
bool IsTemporary) {
if (!Name)
return new (nullptr, *this) MCSymbolXCOFF(nullptr, IsTemporary);
StringRef OriginalName = Name->first();
if (OriginalName.startswith("._Renamed..") ||
OriginalName.startswith("_Renamed.."))
reportError(SMLoc(), "invalid symbol name from source");
if (MAI->isValidUnquotedName(OriginalName))
return new (Name, *this) MCSymbolXCOFF(Name, IsTemporary);
// Now we have a name that contains invalid character(s) for XCOFF symbol.
// Let's replace with something valid, but save the original name so that
// we could still use the original name in the symbol table.
SmallString<128> InvalidName(OriginalName);
// If it's an entry point symbol, we will keep the '.'
// in front for the convention purpose. Otherwise, add "_Renamed.."
// as prefix to signal this is an renamed symbol.
const bool IsEntryPoint = !InvalidName.empty() && InvalidName[0] == '.';
SmallString<128> ValidName =
StringRef(IsEntryPoint ? "._Renamed.." : "_Renamed..");
// Append the hex values of '_' and invalid characters with "_Renamed..";
// at the same time replace invalid characters with '_'.
for (size_t I = 0; I < InvalidName.size(); ++I) {
if (!MAI->isAcceptableChar(InvalidName[I]) || InvalidName[I] == '_') {
raw_svector_ostream(ValidName).write_hex(InvalidName[I]);
InvalidName[I] = '_';
}
}
// Skip entry point symbol's '.' as we already have a '.' in front of
// "_Renamed".
if (IsEntryPoint)
ValidName.append(InvalidName.substr(1, InvalidName.size() - 1));
else
ValidName.append(InvalidName);
auto NameEntry = UsedNames.insert(std::make_pair(ValidName.str(), true));
assert((NameEntry.second || !NameEntry.first->second) &&
"This name is used somewhere else.");
// Mark the name as used for a non-section symbol.
NameEntry.first->second = true;
// Have the MCSymbol object itself refer to the copy of the string
// that is embedded in the UsedNames entry.
MCSymbolXCOFF *XSym = new (&*NameEntry.first, *this)
MCSymbolXCOFF(&*NameEntry.first, IsTemporary);
XSym->setSymbolTableName(MCSymbolXCOFF::getUnqualifiedName(OriginalName));
return XSym;
}
//===----------------------------------------------------------------------===//
// Section Management
//===----------------------------------------------------------------------===//
MCSectionMachO *MCContext::getMachOSection(StringRef Segment, StringRef Section,
unsigned TypeAndAttributes,
unsigned Reserved2, SectionKind Kind,
const char *BeginSymName) {
// We unique sections by their segment/section pair. The returned section
// may not have the same flags as the requested section, if so this should be
// diagnosed by the client as an error.
// Form the name to look up.
assert(Section.size() <= 16 && "section name is too long");
assert(!memchr(Section.data(), '\0', Section.size()) &&
"section name cannot contain NUL");
// Do the lookup, if we have a hit, return it.
auto R = MachOUniquingMap.try_emplace((Segment + Twine(',') + Section).str());
if (!R.second)
return R.first->second;
MCSymbol *Begin = nullptr;
if (BeginSymName)
Begin = createTempSymbol(BeginSymName, false);
// Otherwise, return a new section.
StringRef Name = R.first->first();
R.first->second = new (MachOAllocator.Allocate())
MCSectionMachO(Segment, Name.substr(Name.size() - Section.size()),
TypeAndAttributes, Reserved2, Kind, Begin);
return R.first->second;
}
void MCContext::renameELFSection(MCSectionELF *Section, StringRef Name) {
StringRef GroupName;
if (const MCSymbol *Group = Section->getGroup())
GroupName = Group->getName();
// This function is only used by .debug*, which should not have the
// SHF_LINK_ORDER flag.
unsigned UniqueID = Section->getUniqueID();
ELFUniquingMap.erase(
ELFSectionKey{Section->getName(), GroupName, "", UniqueID});
auto I = ELFUniquingMap
.insert(std::make_pair(
ELFSectionKey{Name, GroupName, "", UniqueID}, Section))
.first;
StringRef CachedName = I->first.SectionName;
const_cast<MCSectionELF *>(Section)->setSectionName(CachedName);
}
MCSectionELF *MCContext::createELFSectionImpl(StringRef Section, unsigned Type,
unsigned Flags, SectionKind K,
unsigned EntrySize,
const MCSymbolELF *Group,
bool Comdat, unsigned UniqueID,
const MCSymbolELF *LinkedToSym) {
MCSymbolELF *R;
MCSymbol *&Sym = Symbols[Section];
// A section symbol can not redefine regular symbols. There may be multiple
// sections with the same name, in which case the first such section wins.
if (Sym && Sym->isDefined() &&
(!Sym->isInSection() || Sym->getSection().getBeginSymbol() != Sym))
reportError(SMLoc(), "invalid symbol redefinition");
if (Sym && Sym->isUndefined()) {
R = cast<MCSymbolELF>(Sym);
} else {
auto NameIter = UsedNames.insert(std::make_pair(Section, false)).first;
R = new (&*NameIter, *this) MCSymbolELF(&*NameIter, /*isTemporary*/ false);
if (!Sym)
Sym = R;
}
R->setBinding(ELF::STB_LOCAL);
R->setType(ELF::STT_SECTION);
auto *Ret = new (ELFAllocator.Allocate())
MCSectionELF(Section, Type, Flags, K, EntrySize, Group, Comdat, UniqueID,
R, LinkedToSym);
auto *F = new MCDataFragment();
Ret->getFragmentList().insert(Ret->begin(), F);
F->setParent(Ret);
R->setFragment(F);
return Ret;
}
MCSectionELF *MCContext::createELFRelSection(const Twine &Name, unsigned Type,
unsigned Flags, unsigned EntrySize,
const MCSymbolELF *Group,
const MCSectionELF *RelInfoSection) {
StringMap<bool>::iterator I;
bool Inserted;
std::tie(I, Inserted) =
RelSecNames.insert(std::make_pair(Name.str(), true));
return createELFSectionImpl(
I->getKey(), Type, Flags, SectionKind::getReadOnly(), EntrySize, Group,
true, true, cast<MCSymbolELF>(RelInfoSection->getBeginSymbol()));
}
MCSectionELF *MCContext::getELFNamedSection(const Twine &Prefix,
const Twine &Suffix, unsigned Type,
unsigned Flags,
unsigned EntrySize) {
return getELFSection(Prefix + "." + Suffix, Type, Flags, EntrySize, Suffix,
/*IsComdat=*/true);
}
MCSectionELF *MCContext::getELFSection(const Twine &Section, unsigned Type,
unsigned Flags, unsigned EntrySize,
const Twine &Group, bool IsComdat,
unsigned UniqueID,
const MCSymbolELF *LinkedToSym) {
MCSymbolELF *GroupSym = nullptr;
if (!Group.isTriviallyEmpty() && !Group.str().empty())
GroupSym = cast<MCSymbolELF>(getOrCreateSymbol(Group));
return getELFSection(Section, Type, Flags, EntrySize, GroupSym, IsComdat,
UniqueID, LinkedToSym);
}
MCSectionELF *MCContext::getELFSection(const Twine &Section, unsigned Type,
unsigned Flags, unsigned EntrySize,
const MCSymbolELF *GroupSym,
bool IsComdat, unsigned UniqueID,
const MCSymbolELF *LinkedToSym) {
StringRef Group = "";
if (GroupSym)
Group = GroupSym->getName();
assert(!(LinkedToSym && LinkedToSym->getName().empty()));
// Do the lookup, if we have a hit, return it.
auto IterBool = ELFUniquingMap.insert(std::make_pair(
ELFSectionKey{Section.str(), Group,
LinkedToSym ? LinkedToSym->getName() : "", UniqueID},
nullptr));
auto &Entry = *IterBool.first;
if (!IterBool.second)
return Entry.second;
StringRef CachedName = Entry.first.SectionName;
SectionKind Kind;
if (Flags & ELF::SHF_ARM_PURECODE)
Kind = SectionKind::getExecuteOnly();
else if (Flags & ELF::SHF_EXECINSTR)
Kind = SectionKind::getText();
else
Kind = SectionKind::getReadOnly();
MCSectionELF *Result =
createELFSectionImpl(CachedName, Type, Flags, Kind, EntrySize, GroupSym,
IsComdat, UniqueID, LinkedToSym);
Entry.second = Result;
recordELFMergeableSectionInfo(Result->getName(), Result->getFlags(),
Result->getUniqueID(), Result->getEntrySize());
return Result;
}
MCSectionELF *MCContext::createELFGroupSection(const MCSymbolELF *Group,
bool IsComdat) {
return createELFSectionImpl(".group", ELF::SHT_GROUP, 0,
SectionKind::getReadOnly(), 4, Group, IsComdat,
MCSection::NonUniqueID, nullptr);
}
void MCContext::recordELFMergeableSectionInfo(StringRef SectionName,
unsigned Flags, unsigned UniqueID,
unsigned EntrySize) {
bool IsMergeable = Flags & ELF::SHF_MERGE;
if (UniqueID == GenericSectionID)
ELFSeenGenericMergeableSections.insert(SectionName);
// For mergeable sections or non-mergeable sections with a generic mergeable
// section name we enter their Unique ID into the ELFEntrySizeMap so that
// compatible globals can be assigned to the same section.
if (IsMergeable || isELFGenericMergeableSection(SectionName)) {
ELFEntrySizeMap.insert(std::make_pair(
ELFEntrySizeKey{SectionName, Flags, EntrySize}, UniqueID));
}
}
bool MCContext::isELFImplicitMergeableSectionNamePrefix(StringRef SectionName) {
return SectionName.startswith(".rodata.str") ||
SectionName.startswith(".rodata.cst");
}
bool MCContext::isELFGenericMergeableSection(StringRef SectionName) {
return isELFImplicitMergeableSectionNamePrefix(SectionName) ||
ELFSeenGenericMergeableSections.count(SectionName);
}
Optional<unsigned> MCContext::getELFUniqueIDForEntsize(StringRef SectionName,
unsigned Flags,
unsigned EntrySize) {
auto I = ELFEntrySizeMap.find(
MCContext::ELFEntrySizeKey{SectionName, Flags, EntrySize});
return (I != ELFEntrySizeMap.end()) ? Optional<unsigned>(I->second) : None;
}
MCSectionGOFF *MCContext::getGOFFSection(StringRef Section, SectionKind Kind) {
// Do the lookup. If we don't have a hit, return a new section.
auto &GOFFSection = GOFFUniquingMap[Section.str()];
if (!GOFFSection)
GOFFSection = new (GOFFAllocator.Allocate()) MCSectionGOFF(Section, Kind);
return GOFFSection;
}
MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
unsigned Characteristics,
SectionKind Kind,
StringRef COMDATSymName, int Selection,
unsigned UniqueID,
const char *BeginSymName) {
MCSymbol *COMDATSymbol = nullptr;
if (!COMDATSymName.empty()) {
COMDATSymbol = getOrCreateSymbol(COMDATSymName);
COMDATSymName = COMDATSymbol->getName();
}
// Do the lookup, if we have a hit, return it.
COFFSectionKey T{Section, COMDATSymName, Selection, UniqueID};
auto IterBool = COFFUniquingMap.insert(std::make_pair(T, nullptr));
auto Iter = IterBool.first;
if (!IterBool.second)
return Iter->second;
MCSymbol *Begin = nullptr;
if (BeginSymName)
Begin = createTempSymbol(BeginSymName, false);
StringRef CachedName = Iter->first.SectionName;
MCSectionCOFF *Result = new (COFFAllocator.Allocate()) MCSectionCOFF(
CachedName, Characteristics, COMDATSymbol, Selection, Kind, Begin);
Iter->second = Result;
return Result;
}
MCSectionCOFF *MCContext::getCOFFSection(StringRef Section,
unsigned Characteristics,
SectionKind Kind,
const char *BeginSymName) {
return getCOFFSection(Section, Characteristics, Kind, "", 0, GenericSectionID,
BeginSymName);
}
MCSectionCOFF *MCContext::getAssociativeCOFFSection(MCSectionCOFF *Sec,
const MCSymbol *KeySym,
unsigned UniqueID) {
// Return the normal section if we don't have to be associative or unique.
if (!KeySym && UniqueID == GenericSectionID)
return Sec;
// If we have a key symbol, make an associative section with the same name and
// kind as the normal section.
unsigned Characteristics = Sec->getCharacteristics();
if (KeySym) {
Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
return getCOFFSection(Sec->getName(), Characteristics, Sec->getKind(),
KeySym->getName(),
COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
}
return getCOFFSection(Sec->getName(), Characteristics, Sec->getKind(), "", 0,
UniqueID);
}
MCSectionWasm *MCContext::getWasmSection(const Twine &Section, SectionKind K,
unsigned Flags, const Twine &Group,
unsigned UniqueID,
const char *BeginSymName) {
MCSymbolWasm *GroupSym = nullptr;
if (!Group.isTriviallyEmpty() && !Group.str().empty()) {
GroupSym = cast<MCSymbolWasm>(getOrCreateSymbol(Group));
GroupSym->setComdat(true);
}
return getWasmSection(Section, K, Flags, GroupSym, UniqueID, BeginSymName);
}
MCSectionWasm *MCContext::getWasmSection(const Twine &Section, SectionKind Kind,
unsigned Flags,
const MCSymbolWasm *GroupSym,
unsigned UniqueID,
const char *BeginSymName) {
StringRef Group = "";
if (GroupSym)
Group = GroupSym->getName();
// Do the lookup, if we have a hit, return it.
auto IterBool = WasmUniquingMap.insert(
std::make_pair(WasmSectionKey{Section.str(), Group, UniqueID}, nullptr));
auto &Entry = *IterBool.first;
if (!IterBool.second)
return Entry.second;
StringRef CachedName = Entry.first.SectionName;
MCSymbol *Begin = createSymbol(CachedName, true, false);
Symbols[Begin->getName()] = Begin;
cast<MCSymbolWasm>(Begin)->setType(wasm::WASM_SYMBOL_TYPE_SECTION);
MCSectionWasm *Result = new (WasmAllocator.Allocate())
MCSectionWasm(CachedName, Kind, Flags, GroupSym, UniqueID, Begin);
Entry.second = Result;
auto *F = new MCDataFragment();
Result->getFragmentList().insert(Result->begin(), F);
F->setParent(Result);
Begin->setFragment(F);
return Result;
}
bool MCContext::hasXCOFFSection(StringRef Section,
XCOFF::CsectProperties CsectProp) const {
return XCOFFUniquingMap.count(
XCOFFSectionKey(Section.str(), CsectProp.MappingClass)) != 0;
}
MCSectionXCOFF *MCContext::getXCOFFSection(
StringRef Section, SectionKind Kind,
Optional<XCOFF::CsectProperties> CsectProp, bool MultiSymbolsAllowed,
const char *BeginSymName,
Optional<XCOFF::DwarfSectionSubtypeFlags> DwarfSectionSubtypeFlags) {
bool IsDwarfSec = DwarfSectionSubtypeFlags.hasValue();
assert((IsDwarfSec != CsectProp.hasValue()) && "Invalid XCOFF section!");
// Do the lookup. If we have a hit, return it.
auto IterBool = XCOFFUniquingMap.insert(std::make_pair(
IsDwarfSec
? XCOFFSectionKey(Section.str(), DwarfSectionSubtypeFlags.getValue())
: XCOFFSectionKey(Section.str(), CsectProp->MappingClass),
nullptr));
auto &Entry = *IterBool.first;
if (!IterBool.second) {
MCSectionXCOFF *ExistedEntry = Entry.second;
if (ExistedEntry->isMultiSymbolsAllowed() != MultiSymbolsAllowed)
report_fatal_error("section's multiply symbols policy does not match");
return ExistedEntry;
}
// Otherwise, return a new section.
StringRef CachedName = Entry.first.SectionName;
MCSymbolXCOFF *QualName = nullptr;
// Debug section don't have storage class attribute.
if (IsDwarfSec)
QualName = cast<MCSymbolXCOFF>(getOrCreateSymbol(CachedName));
else
QualName = cast<MCSymbolXCOFF>(getOrCreateSymbol(
CachedName + "[" +
XCOFF::getMappingClassString(CsectProp->MappingClass) + "]"));
MCSymbol *Begin = nullptr;
if (BeginSymName)
Begin = createTempSymbol(BeginSymName, false);
// QualName->getUnqualifiedName() and CachedName are the same except when
// CachedName contains invalid character(s) such as '$' for an XCOFF symbol.
MCSectionXCOFF *Result = nullptr;
if (IsDwarfSec)
Result = new (XCOFFAllocator.Allocate())
MCSectionXCOFF(QualName->getUnqualifiedName(), Kind, QualName,
DwarfSectionSubtypeFlags.getValue(), Begin, CachedName,
MultiSymbolsAllowed);
else
Result = new (XCOFFAllocator.Allocate())
MCSectionXCOFF(QualName->getUnqualifiedName(), CsectProp->MappingClass,
CsectProp->Type, Kind, QualName, Begin, CachedName,
MultiSymbolsAllowed);
Entry.second = Result;
auto *F = new MCDataFragment();
Result->getFragmentList().insert(Result->begin(), F);
F->setParent(Result);
if (Begin)
Begin->setFragment(F);
return Result;
}
MCSubtargetInfo &MCContext::getSubtargetCopy(const MCSubtargetInfo &STI) {
return *new (MCSubtargetAllocator.Allocate()) MCSubtargetInfo(STI);
}
void MCContext::addDebugPrefixMapEntry(const std::string &From,
const std::string &To) {
DebugPrefixMap.insert(std::make_pair(From, To));
}
void MCContext::RemapDebugPaths() {
const auto &DebugPrefixMap = this->DebugPrefixMap;
if (DebugPrefixMap.empty())
return;
const auto RemapDebugPath = [&DebugPrefixMap](std::string &Path) {
SmallString<256> P(Path);
for (const auto &Entry : DebugPrefixMap) {
if (llvm::sys::path::replace_path_prefix(P, Entry.first, Entry.second)) {
Path = P.str().str();
break;
}
}
};
// Remap compilation directory.
std::string CompDir = std::string(CompilationDir.str());
RemapDebugPath(CompDir);
CompilationDir = CompDir;
// Remap MCDwarfDirs in all compilation units.
for (auto &CUIDTablePair : MCDwarfLineTablesCUMap)
for (auto &Dir : CUIDTablePair.second.getMCDwarfDirs())
RemapDebugPath(Dir);
}
//===----------------------------------------------------------------------===//
// Dwarf Management
//===----------------------------------------------------------------------===//
void MCContext::setGenDwarfRootFile(StringRef InputFileName, StringRef Buffer) {
// MCDwarf needs the root file as well as the compilation directory.
// If we find a '.file 0' directive that will supersede these values.
Optional<MD5::MD5Result> Cksum;
if (getDwarfVersion() >= 5) {
MD5 Hash;
MD5::MD5Result Sum;
Hash.update(Buffer);
Hash.final(Sum);
Cksum = Sum;
}
// Canonicalize the root filename. It cannot be empty, and should not
// repeat the compilation dir.
// The MCContext ctor initializes MainFileName to the name associated with
// the SrcMgr's main file ID, which might be the same as InputFileName (and
// possibly include directory components).
// Or, MainFileName might have been overridden by a -main-file-name option,
// which is supposed to be just a base filename with no directory component.
// So, if the InputFileName and MainFileName are not equal, assume
// MainFileName is a substitute basename and replace the last component.
SmallString<1024> FileNameBuf = InputFileName;
if (FileNameBuf.empty() || FileNameBuf == "-")
FileNameBuf = "<stdin>";
if (!getMainFileName().empty() && FileNameBuf != getMainFileName()) {
llvm::sys::path::remove_filename(FileNameBuf);
llvm::sys::path::append(FileNameBuf, getMainFileName());
}
StringRef FileName = FileNameBuf;
if (FileName.consume_front(getCompilationDir()))
if (llvm::sys::path::is_separator(FileName.front()))
FileName = FileName.drop_front();
assert(!FileName.empty());
setMCLineTableRootFile(
/*CUID=*/0, getCompilationDir(), FileName, Cksum, None);
}
/// getDwarfFile - takes a file name and number to place in the dwarf file and
/// directory tables. If the file number has already been allocated it is an
/// error and zero is returned and the client reports the error, else the
/// allocated file number is returned. The file numbers may be in any order.
Expected<unsigned> MCContext::getDwarfFile(StringRef Directory,
StringRef FileName,
unsigned FileNumber,
Optional<MD5::MD5Result> Checksum,
Optional<StringRef> Source,
unsigned CUID) {
MCDwarfLineTable &Table = MCDwarfLineTablesCUMap[CUID];
return Table.tryGetFile(Directory, FileName, Checksum, Source, DwarfVersion,
FileNumber);
}
/// isValidDwarfFileNumber - takes a dwarf file number and returns true if it
/// currently is assigned and false otherwise.
bool MCContext::isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID) {
const MCDwarfLineTable &LineTable = getMCDwarfLineTable(CUID);
if (FileNumber == 0)
return getDwarfVersion() >= 5;
if (FileNumber >= LineTable.getMCDwarfFiles().size())
return false;
return !LineTable.getMCDwarfFiles()[FileNumber].Name.empty();
}
/// Remove empty sections from SectionsForRanges, to avoid generating
/// useless debug info for them.
void MCContext::finalizeDwarfSections(MCStreamer &MCOS) {
SectionsForRanges.remove_if(
[&](MCSection *Sec) { return !MCOS.mayHaveInstructions(*Sec); });
}
CodeViewContext &MCContext::getCVContext() {
if (!CVContext.get())
CVContext.reset(new CodeViewContext);
return *CVContext.get();
}
//===----------------------------------------------------------------------===//
// Error Reporting
//===----------------------------------------------------------------------===//
void MCContext::diagnose(const SMDiagnostic &SMD) {
assert(DiagHandler && "MCContext::DiagHandler is not set");
bool UseInlineSrcMgr = false;
const SourceMgr *SMP = nullptr;
if (SrcMgr) {
SMP = SrcMgr;
} else if (InlineSrcMgr) {
SMP = InlineSrcMgr.get();
UseInlineSrcMgr = true;
} else
llvm_unreachable("Either SourceMgr should be available");
DiagHandler(SMD, UseInlineSrcMgr, *SMP, LocInfos);
}
void MCContext::reportCommon(
SMLoc Loc,
std::function<void(SMDiagnostic &, const SourceMgr *)> GetMessage) {
// * MCContext::SrcMgr is null when the MC layer emits machine code for input
// other than assembly file, say, for .c/.cpp/.ll/.bc.
// * MCContext::InlineSrcMgr is null when the inline asm is not used.
// * A default SourceMgr is needed for diagnosing when both MCContext::SrcMgr
// and MCContext::InlineSrcMgr are null.
SourceMgr SM;
const SourceMgr *SMP = &SM;
bool UseInlineSrcMgr = false;
// FIXME: Simplify these by combining InlineSrcMgr & SrcMgr.
// For MC-only execution, only SrcMgr is used;
// For non MC-only execution, InlineSrcMgr is only ctor'd if there is
// inline asm in the IR.
if (Loc.isValid()) {
if (SrcMgr) {
SMP = SrcMgr;
} else if (InlineSrcMgr) {
SMP = InlineSrcMgr.get();
UseInlineSrcMgr = true;
} else
llvm_unreachable("Either SourceMgr should be available");
}
SMDiagnostic D;
GetMessage(D, SMP);
DiagHandler(D, UseInlineSrcMgr, *SMP, LocInfos);
}
void MCContext::reportError(SMLoc Loc, const Twine &Msg) {
HadError = true;
reportCommon(Loc, [&](SMDiagnostic &D, const SourceMgr *SMP) {
D = SMP->GetMessage(Loc, SourceMgr::DK_Error, Msg);
});
}
void MCContext::reportWarning(SMLoc Loc, const Twine &Msg) {
if (TargetOptions && TargetOptions->MCNoWarn)
return;
if (TargetOptions && TargetOptions->MCFatalWarnings) {
reportError(Loc, Msg);
} else {
reportCommon(Loc, [&](SMDiagnostic &D, const SourceMgr *SMP) {
D = SMP->GetMessage(Loc, SourceMgr::DK_Warning, Msg);
});
}
}
| 37.66129
| 82
| 0.641247
|
lxbndr
|
c808ab04bf668e3806d4b1e55823bf4a3b80a69c
| 1,731
|
cpp
|
C++
|
ui/widget/ChangeFrontBackColorWidget.cpp
|
shinehanx/openphoto
|
e4466e5e80829385d2aa84813f2d5a8960053845
|
[
"Apache-2.0"
] | 5
|
2021-03-11T00:30:25.000Z
|
2021-07-28T00:31:20.000Z
|
ui/widget/ChangeFrontBackColorWidget.cpp
|
shinehanx/openphoto
|
e4466e5e80829385d2aa84813f2d5a8960053845
|
[
"Apache-2.0"
] | null | null | null |
ui/widget/ChangeFrontBackColorWidget.cpp
|
shinehanx/openphoto
|
e4466e5e80829385d2aa84813f2d5a8960053845
|
[
"Apache-2.0"
] | 1
|
2021-09-14T16:28:26.000Z
|
2021-09-14T16:28:26.000Z
|
#include "ChangeFrontBackColorWidget.h"
#include <QDebug>
#define CHANGEFRONTBACKCOLORWIDGET_MARGIN 3
#define CHANGEFRONTBACKCOLORWIDGET_BTN_W 12
#define CHANGEFRONTBACKCOLORWIDGET_BTN_H 12
ChangeFrontBackColorWidget::ChangeFrontBackColorWidget(QWidget *parent) : QWidget(parent)
{
setAutoFillBackground(true);
}
/**
* @brief ChangeFrontBackColorWidget::setup
* 初始化UI
*/
void ChangeFrontBackColorWidget::setup()
{
int x = CHANGEFRONTBACKCOLORWIDGET_MARGIN,
y = CHANGEFRONTBACKCOLORWIDGET_MARGIN,
w = CHANGEFRONTBACKCOLORWIDGET_BTN_W,
h = CHANGEFRONTBACKCOLORWIDGET_BTN_H;
QRect rect = geometry();
qDebug() << "ChangeFrontBackColorWidget this rect:" << rect;
//填充和描边按钮
fillStrokeBtn = new ImageView(this);
fillStrokeBtn->show(x, y, w, h, ":/rc/images/widget/fill-stroke.png");
qDebug() << "ChangeFrontBackColorWidget.left rect:" << QRect(x,y,w,h);
//切换填充和描边按钮
x = rect.width() - CHANGEFRONTBACKCOLORWIDGET_MARGIN - CHANGEFRONTBACKCOLORWIDGET_BTN_W;
changeFillStrokeBtn = new ImageView(this);
changeFillStrokeBtn->show(x, y, w, h, ":/rc/images/widget/change-fill-stroke.png");
qDebug() << "ChangeFrontBackColorWidget.right rect:" << QRect(x,y,w,h);
//切换填充和描边控件
fillStrokeColorWidget = new FillStrokeColorWidget(this);
x = CHANGEFRONTBACKCOLORWIDGET_MARGIN;
y = CHANGEFRONTBACKCOLORWIDGET_MARGIN * 3 + CHANGEFRONTBACKCOLORWIDGET_BTN_H;
w = rect.width() - 2 * CHANGEFRONTBACKCOLORWIDGET_MARGIN;
h = rect.height() - y - 2 * CHANGEFRONTBACKCOLORWIDGET_MARGIN;
fillStrokeColorWidget->setGeometry(x, y, w, h);
qDebug() << "ChangeFrontBackColorWidget.bottom rect:" << QRect(x,y,w,h);
fillStrokeColorWidget->setup();
}
| 36.829787
| 92
| 0.732525
|
shinehanx
|
c809e3589cfc1978c63cd92586504509d741b649
| 9,270
|
cpp
|
C++
|
rviz_default_plugins/test/rviz_default_plugins/displays/path/path_display_test.cpp
|
Tobias-Fischer/rviz-1
|
2d84e191873befa86c1b4060ddf7e25b39d095c1
|
[
"BSD-3-Clause-Clear"
] | 108
|
2017-08-29T11:01:08.000Z
|
2022-03-31T06:07:52.000Z
|
rviz_default_plugins/test/rviz_default_plugins/displays/path/path_display_test.cpp
|
Tobias-Fischer/rviz-1
|
2d84e191873befa86c1b4060ddf7e25b39d095c1
|
[
"BSD-3-Clause-Clear"
] | 741
|
2017-08-29T06:30:27.000Z
|
2022-03-29T14:46:07.000Z
|
rviz_default_plugins/test/rviz_default_plugins/displays/path/path_display_test.cpp
|
Tobias-Fischer/rviz-1
|
2d84e191873befa86c1b4060ddf7e25b39d095c1
|
[
"BSD-3-Clause-Clear"
] | 141
|
2017-08-31T08:31:26.000Z
|
2022-03-31T14:46:36.000Z
|
/*
* Copyright (c) 2018, Bosch Software Innovations GmbH.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted (subject to the limitations in the disclaimer
* below) 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.
*
* NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS
* LICENSE. 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 <gmock/gmock.h>
#include <memory>
#include <string>
#include <vector>
#include <OgreEntity.h>
#include <OgreMesh.h>
#include <OgreManualObject.h>
#include "visualization_msgs/msg/marker.hpp"
#include "rviz_rendering/objects/arrow.hpp"
#include "rviz_rendering/objects/shape.hpp"
#include "../../scene_graph_introspection.hpp"
#include "rviz_default_plugins/displays/path/path_display.hpp"
#include "../display_test_fixture.hpp"
using namespace ::testing; // NOLINT
class PathTestFixture : public DisplayTestFixture
{
public:
PathTestFixture()
{
path_display_ = std::make_shared<rviz_default_plugins::displays::PathDisplay>(context_.get());
}
std::shared_ptr<rviz_default_plugins::displays::PathDisplay> path_display_;
};
nav_msgs::msg::Path::ConstSharedPtr createPathMessage()
{
auto message = std::make_shared<nav_msgs::msg::Path>();
message->header = std_msgs::msg::Header();
message->header.frame_id = "path_frame";
message->header.stamp = rclcpp::Clock().now();
auto pose = geometry_msgs::msg::PoseStamped();
pose.pose.position.x = 1;
pose.pose.position.y = 1;
pose.pose.position.z = 1;
auto orientation = Ogre::Quaternion::IDENTITY;
pose.pose.orientation.w = orientation.w;
pose.pose.orientation.x = orientation.x;
pose.pose.orientation.y = orientation.y;
pose.pose.orientation.z = orientation.z;
auto pose2 = geometry_msgs::msg::PoseStamped();
pose2.pose.position.x = 4;
pose2.pose.position.y = 2;
pose2.pose.position.z = 0;
auto orientation2 = Ogre::Quaternion::IDENTITY;
pose2.pose.orientation.w = orientation2.w;
pose2.pose.orientation.x = orientation2.x;
pose2.pose.orientation.y = orientation2.y;
pose2.pose.orientation.z = orientation2.z;
message->poses = std::vector<geometry_msgs::msg::PoseStamped>({pose, pose2});
return message;
}
TEST_F(PathTestFixture, processMessage_adds_nothing_to_scene_if_invalid_transformation) {
EXPECT_CALL(*frame_manager_, getTransform(_, _, _, _)).WillOnce(Return(false)); // NOLINT
path_display_->processMessage(createPathMessage());
auto object = rviz_default_plugins::findOneManualObject(scene_manager_->getRootSceneNode());
EXPECT_THAT(object->getNumSections(), Eq(0u));
}
TEST_F(PathTestFixture, processMessage_adds_vertices_to_scene) {
auto position = Ogre::Vector3::ZERO;
auto orientation = Ogre::Quaternion::IDENTITY;
mockValidTransform(position, orientation);
path_display_->processMessage(createPathMessage());
auto object = rviz_default_plugins::findOneManualObject(scene_manager_->getRootSceneNode());
EXPECT_THAT(object->getSection(0)->getRenderOperation()->vertexData->vertexCount, Eq(2u));
}
TEST_F(PathTestFixture, reset_clears_the_scene) {
auto position = Ogre::Vector3::ZERO;
auto orientation = Ogre::Quaternion::IDENTITY;
mockValidTransform(position, orientation);
path_display_->processMessage(createPathMessage());
path_display_->reset();
auto object = rviz_default_plugins::findOneManualObject(scene_manager_->getRootSceneNode());
EXPECT_THAT(object->getNumSections(), Eq(0u));
}
TEST_F(PathTestFixture, reset_is_idempotent) {
auto position = Ogre::Vector3::ZERO;
auto orientation = Ogre::Quaternion::IDENTITY;
mockValidTransform(position, orientation);
path_display_->processMessage(createPathMessage());
path_display_->reset();
path_display_->reset();
ASSERT_TRUE(1);
}
TEST_F(PathTestFixture, reset_removes_all_axes) {
path_display_->findProperty("Pose Style")->setValue("Axes");
auto position = Ogre::Vector3::ZERO;
auto orientation = Ogre::Quaternion::IDENTITY;
mockValidTransform(position, orientation);
path_display_->processMessage(createPathMessage());
EXPECT_THAT(rviz_default_plugins::findAllAxes(scene_manager_->getRootSceneNode()), SizeIs(2));
path_display_->reset();
EXPECT_THAT(rviz_default_plugins::findAllAxes(scene_manager_->getRootSceneNode()), SizeIs(0));
}
TEST_F(PathTestFixture, reset_removes_all_arrows) {
path_display_->findProperty("Pose Style")->setValue("Arrows");
auto position = Ogre::Vector3::ZERO;
auto orientation = Ogre::Quaternion::IDENTITY;
mockValidTransform(position, orientation);
path_display_->processMessage(createPathMessage());
EXPECT_THAT(rviz_default_plugins::findAllArrows(scene_manager_->getRootSceneNode()), SizeIs(2));
path_display_->reset();
EXPECT_THAT(rviz_default_plugins::findAllArrows(scene_manager_->getRootSceneNode()), SizeIs(0));
}
TEST_F(PathTestFixture, processMessage_transforms_the_vertices_correctly) {
auto position = Ogre::Vector3(1, 2, 3);
auto orientation = Ogre::Quaternion::IDENTITY;
mockValidTransform(position, orientation);
path_display_->processMessage(createPathMessage());
auto object = rviz_default_plugins::findOneManualObject(scene_manager_->getRootSceneNode());
EXPECT_THAT(object->getSection(0)->getRenderOperation()->vertexData->vertexCount, Eq(2u));
// Use bounding box to indirectly assert the vertices
EXPECT_THAT(object->getBoundingBox().getMinimum(), Vector3Eq(Ogre::Vector3(2, 3, 3)));
EXPECT_THAT(object->getBoundingBox().getMaximum(), Vector3Eq(Ogre::Vector3(5, 4, 4)));
}
TEST_F(PathTestFixture, processMessage_adds_billboard_line_to_scene) {
path_display_->findProperty("Line Style")->setValue("Billboards");
auto position = Ogre::Vector3::ZERO;
auto orientation = Ogre::Quaternion::IDENTITY;
mockValidTransform(position, orientation);
path_display_->processMessage(createPathMessage());
auto object = rviz_default_plugins::findOneBillboardChain(scene_manager_->getRootSceneNode());
EXPECT_THAT(object->getNumberOfChains(), Eq(1u));
EXPECT_THAT(object->getNumChainElements(0), Eq(2u));
EXPECT_THAT(object->getChainElement(0, 0).position, Vector3Eq(Ogre::Vector3(4, 2, 0)));
EXPECT_THAT(object->getChainElement(0, 1).position, Vector3Eq(Ogre::Vector3(1, 1, 1)));
}
TEST_F(PathTestFixture, processMessage_adds_axes_to_scene) {
path_display_->findProperty("Pose Style")->setValue("Axes");
auto position = Ogre::Vector3::ZERO;
auto orientation = Ogre::Quaternion::IDENTITY;
mockValidTransform(position, orientation);
path_display_->processMessage(createPathMessage());
auto axes = rviz_default_plugins::findAllAxes(scene_manager_->getRootSceneNode());
EXPECT_THAT(axes, SizeIs(2));
auto axes_positions = rviz_default_plugins::getPositionsFromNodes(axes);
EXPECT_THAT(axes_positions, Contains(Vector3Eq(Ogre::Vector3(4, 2, 0))));
EXPECT_THAT(axes_positions, Contains(Vector3Eq(Ogre::Vector3(1, 1, 1))));
}
TEST_F(PathTestFixture, processMessage_adds_arrows_to_scene) {
path_display_->findProperty("Pose Style")->setValue("Arrows");
auto position = Ogre::Vector3::ZERO;
auto orientation = Ogre::Quaternion::IDENTITY;
mockValidTransform(position, orientation);
path_display_->processMessage(createPathMessage());
auto arrows = rviz_default_plugins::findAllArrows(scene_manager_->getRootSceneNode());
EXPECT_THAT(arrows, SizeIs(2));
auto arrow_positions = rviz_default_plugins::getPositionsFromNodes(arrows);
EXPECT_THAT(arrow_positions, Contains(Vector3Eq(Ogre::Vector3(1, 1, 1))));
EXPECT_THAT(arrow_positions, Contains(Vector3Eq(Ogre::Vector3(4, 2, 0))));
// default orientation is set to (0.5, -0.5, -0.5, -0.5) by arrow
auto default_orientation = Ogre::Quaternion(0.5f, -0.5f, -0.5f, -0.5f);
auto arrow_orientations = rviz_default_plugins::getOrientationsFromNodes(arrows);
EXPECT_THAT(arrow_orientations, Each(QuaternionEq(default_orientation)));
}
| 38.46473
| 98
| 0.763323
|
Tobias-Fischer
|
c80b8970465cd21883aa8b06d13425182124e32c
| 233
|
cpp
|
C++
|
test/po/gtest.cpp
|
JieDing/WasmEdge
|
b2f17c807ba2b4b6294af9e15113cca04919906e
|
[
"Apache-2.0"
] | 2,084
|
2021-04-30T11:20:17.000Z
|
2022-03-31T21:31:47.000Z
|
test/po/gtest.cpp
|
JieDing/WasmEdge
|
b2f17c807ba2b4b6294af9e15113cca04919906e
|
[
"Apache-2.0"
] | 990
|
2021-04-29T18:43:51.000Z
|
2022-03-31T15:32:51.000Z
|
test/po/gtest.cpp
|
JieDing/WasmEdge
|
b2f17c807ba2b4b6294af9e15113cca04919906e
|
[
"Apache-2.0"
] | 343
|
2021-05-04T20:27:10.000Z
|
2022-03-29T03:31:26.000Z
|
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: 2019-2022 Second State INC
#include "gtest/gtest.h"
GTEST_API_ int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 23.3
| 53
| 0.729614
|
JieDing
|
c80c61f83383dd0e7ad4570bcc5265a725ed5d94
| 13,390
|
cpp
|
C++
|
SDK/BP_Mast_functions.cpp
|
alxalx14/Sea-Of-Thieves-SDK
|
f56a0340eb33726c98fc53eb0678fa2d59aa8294
|
[
"MIT"
] | 3
|
2021-03-27T08:30:37.000Z
|
2021-04-18T19:32:53.000Z
|
SDK/BP_Mast_functions.cpp
|
alxalx14/Sea-Of-Thieves-SDK
|
f56a0340eb33726c98fc53eb0678fa2d59aa8294
|
[
"MIT"
] | null | null | null |
SDK/BP_Mast_functions.cpp
|
alxalx14/Sea-Of-Thieves-SDK
|
f56a0340eb33726c98fc53eb0678fa2d59aa8294
|
[
"MIT"
] | 1
|
2021-06-01T03:05:50.000Z
|
2021-06-01T03:05:50.000Z
|
// Name: SeaOfThieves, Version: 2.0.23
#include "../pch.h"
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Functions
//---------------------------------------------------------------------------
// Function BP_Mast.BP_Mast_C.AttemptToAddDamageDecal
// (Public, HasOutParms, BlueprintCallable, BlueprintEvent)
// Parameters:
// TEnumAsByte<Repair_ERepairableState> RepairableState (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
// class UDecalComponent* DecalComponent (Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor)
// struct FTransform RelativeTransform (ConstParm, Parm, IsPlainOldData, NoDestructor)
// class UMaterialInterface* NewDecalMaterial (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
void ABP_Mast_C::AttemptToAddDamageDecal(TEnumAsByte<Repair_ERepairableState> RepairableState, class UDecalComponent** DecalComponent, const struct FTransform& RelativeTransform, class UMaterialInterface* NewDecalMaterial)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_Mast.BP_Mast_C.AttemptToAddDamageDecal");
ABP_Mast_C_AttemptToAddDamageDecal_Params params;
params.RepairableState = RepairableState;
params.RelativeTransform = RelativeTransform;
params.NewDecalMaterial = NewDecalMaterial;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (DecalComponent != nullptr)
*DecalComponent = params.DecalComponent;
}
// Function BP_Mast.BP_Mast_C.IsMastVisuallyFractured
// (Event, Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure, Const)
// Parameters:
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor)
bool ABP_Mast_C::IsMastVisuallyFractured()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_Mast.BP_Mast_C.IsMastVisuallyFractured");
ABP_Mast_C_IsMastVisuallyFractured_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function BP_Mast.BP_Mast_C.Customise Static Mesh
// (Public, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UStaticMesh* New_Static_Mesh (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
// class UStaticMeshComponent* Static_Mesh_Component (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
void ABP_Mast_C::Customise_Static_Mesh(class UStaticMesh* New_Static_Mesh, class UStaticMeshComponent* Static_Mesh_Component)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_Mast.BP_Mast_C.Customise Static Mesh");
ABP_Mast_C_Customise_Static_Mesh_Params params;
params.New_Static_Mesh = New_Static_Mesh;
params.Static_Mesh_Component = Static_Mesh_Component;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_Mast.BP_Mast_C.Trim Array Func
// (Public, HasOutParms, BlueprintCallable, BlueprintEvent)
// Parameters:
// TArray<class UObject*> TargetArray (Parm, OutParm, ZeroConstructor, ReferenceParm)
// int Size (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
void ABP_Mast_C::Trim_Array_Func(TArray<class UObject*>* TargetArray, int Size)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_Mast.BP_Mast_C.Trim Array Func");
ABP_Mast_C_Trim_Array_Func_Params params;
params.Size = Size;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (TargetArray != nullptr)
*TargetArray = params.TargetArray;
}
// Function BP_Mast.BP_Mast_C.Initialise Sail Parameters
// (Public, HasDefaults, BlueprintCallable, BlueprintEvent)
void ABP_Mast_C::Initialise_Sail_Parameters()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_Mast.BP_Mast_C.Initialise Sail Parameters");
ABP_Mast_C_Initialise_Sail_Parameters_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_Mast.BP_Mast_C.Populate Lists of Yards and Sails
// (Public, BlueprintCallable, BlueprintEvent)
void ABP_Mast_C::Populate_Lists_of_Yards_and_Sails()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_Mast.BP_Mast_C.Populate Lists of Yards and Sails");
ABP_Mast_C_Populate_Lists_of_Yards_and_Sails_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_Mast.BP_Mast_C.Cull Excess Components
// (Public, HasOutParms, BlueprintCallable, BlueprintEvent)
// Parameters:
// TArray<class UActorComponent*> TargetArray (Parm, OutParm, ZeroConstructor, ReferenceParm)
void ABP_Mast_C::Cull_Excess_Components(TArray<class UActorComponent*>* TargetArray)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_Mast.BP_Mast_C.Cull Excess Components");
ABP_Mast_C_Cull_Excess_Components_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (TargetArray != nullptr)
*TargetArray = params.TargetArray;
}
// Function BP_Mast.BP_Mast_C.Initialise Sails
// (Public, HasDefaults, BlueprintCallable, BlueprintEvent)
void ABP_Mast_C::Initialise_Sails()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_Mast.BP_Mast_C.Initialise Sails");
ABP_Mast_C_Initialise_Sails_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_Mast.BP_Mast_C.UserConstructionScript
// (Event, Public, BlueprintCallable, BlueprintEvent)
void ABP_Mast_C::UserConstructionScript()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_Mast.BP_Mast_C.UserConstructionScript");
ABP_Mast_C_UserConstructionScript_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_Mast.BP_Mast_C.OnMastDescLoaded
// (Event, Public, BlueprintEvent)
// Parameters:
// class UMastDescAsset* MastDesc (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
void ABP_Mast_C::OnMastDescLoaded(class UMastDescAsset* MastDesc)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_Mast.BP_Mast_C.OnMastDescLoaded");
ABP_Mast_C_OnMastDescLoaded_Params params;
params.MastDesc = MastDesc;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_Mast.BP_Mast_C.OnMastMeshSwapRequested
// (Event, Protected, BlueprintEvent)
// Parameters:
// class UStaticMesh* NewMeshBottom (ConstParm, Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
// class UStaticMesh* NewMeshTop (ConstParm, Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
void ABP_Mast_C::OnMastMeshSwapRequested(class UStaticMesh* NewMeshBottom, class UStaticMesh* NewMeshTop)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_Mast.BP_Mast_C.OnMastMeshSwapRequested");
ABP_Mast_C_OnMastMeshSwapRequested_Params params;
params.NewMeshBottom = NewMeshBottom;
params.NewMeshTop = NewMeshTop;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_Mast.BP_Mast_C.BndEvt__RepairableComponentFirst_K2Node_ComponentBoundEvent_3_RepairableStateChangedDelegate__DelegateSignature
// (BlueprintEvent)
// Parameters:
// TEnumAsByte<Repair_ERepairableState> State (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
// TEnumAsByte<Repair_ERepairableState> PreviousState (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
// class URepairableComponent* RepairableComponent (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
void ABP_Mast_C::BndEvt__RepairableComponentFirst_K2Node_ComponentBoundEvent_3_RepairableStateChangedDelegate__DelegateSignature(TEnumAsByte<Repair_ERepairableState> State, TEnumAsByte<Repair_ERepairableState> PreviousState, class URepairableComponent* RepairableComponent)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_Mast.BP_Mast_C.BndEvt__RepairableComponentFirst_K2Node_ComponentBoundEvent_3_RepairableStateChangedDelegate__DelegateSignature");
ABP_Mast_C_BndEvt__RepairableComponentFirst_K2Node_ComponentBoundEvent_3_RepairableStateChangedDelegate__DelegateSignature_Params params;
params.State = State;
params.PreviousState = PreviousState;
params.RepairableComponent = RepairableComponent;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_Mast.BP_Mast_C.BndEvt__RepairableComponentSecond_K2Node_ComponentBoundEvent_6_RepairableStateChangedDelegate__DelegateSignature
// (BlueprintEvent)
// Parameters:
// TEnumAsByte<Repair_ERepairableState> State (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
// TEnumAsByte<Repair_ERepairableState> PreviousState (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
// class URepairableComponent* RepairableComponent (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
void ABP_Mast_C::BndEvt__RepairableComponentSecond_K2Node_ComponentBoundEvent_6_RepairableStateChangedDelegate__DelegateSignature(TEnumAsByte<Repair_ERepairableState> State, TEnumAsByte<Repair_ERepairableState> PreviousState, class URepairableComponent* RepairableComponent)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_Mast.BP_Mast_C.BndEvt__RepairableComponentSecond_K2Node_ComponentBoundEvent_6_RepairableStateChangedDelegate__DelegateSignature");
ABP_Mast_C_BndEvt__RepairableComponentSecond_K2Node_ComponentBoundEvent_6_RepairableStateChangedDelegate__DelegateSignature_Params params;
params.State = State;
params.PreviousState = PreviousState;
params.RepairableComponent = RepairableComponent;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_Mast.BP_Mast_C.BndEvt__RepairableComponentThird_K2Node_ComponentBoundEvent_10_RepairableStateChangedDelegate__DelegateSignature
// (BlueprintEvent)
// Parameters:
// TEnumAsByte<Repair_ERepairableState> State (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
// TEnumAsByte<Repair_ERepairableState> PreviousState (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
// class URepairableComponent* RepairableComponent (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
void ABP_Mast_C::BndEvt__RepairableComponentThird_K2Node_ComponentBoundEvent_10_RepairableStateChangedDelegate__DelegateSignature(TEnumAsByte<Repair_ERepairableState> State, TEnumAsByte<Repair_ERepairableState> PreviousState, class URepairableComponent* RepairableComponent)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_Mast.BP_Mast_C.BndEvt__RepairableComponentThird_K2Node_ComponentBoundEvent_10_RepairableStateChangedDelegate__DelegateSignature");
ABP_Mast_C_BndEvt__RepairableComponentThird_K2Node_ComponentBoundEvent_10_RepairableStateChangedDelegate__DelegateSignature_Params params;
params.State = State;
params.PreviousState = PreviousState;
params.RepairableComponent = RepairableComponent;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_Mast.BP_Mast_C.ExecuteUbergraph_BP_Mast
// (HasDefaults)
// Parameters:
// int EntryPoint (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
void ABP_Mast_C::ExecuteUbergraph_BP_Mast(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_Mast.BP_Mast_C.ExecuteUbergraph_BP_Mast");
ABP_Mast_C_ExecuteUbergraph_BP_Mast_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
void ABP_Mast_C::AfterRead()
{
AMast::AfterRead();
READ_PTR_FULL(MastTopComponent, UStaticMeshComponent);
READ_PTR_FULL(TopgallantActor, UChildActorComponent);
READ_PTR_FULL(MainsailActor, UChildActorComponent);
READ_PTR_FULL(TopsailActor, UChildActorComponent);
READ_PTR_FULL(Main_Yard, UStaticMeshComponent);
READ_PTR_FULL(Topgallant_Yard, UStaticMeshComponent);
READ_PTR_FULL(Top_Yard, UStaticMeshComponent);
READ_PTR_FULL(MastBaseComponent, UStaticMeshComponent);
READ_PTR_FULL(Sail_Material, UMaterialInstance);
READ_PTR_FULL(DamageDecalRight, UDecalComponent);
READ_PTR_FULL(DamageDecalLeft, UDecalComponent);
}
void ABP_Mast_C::BeforeDelete()
{
AMast::BeforeDelete();
DELE_PTR_FULL(MastTopComponent);
DELE_PTR_FULL(TopgallantActor);
DELE_PTR_FULL(MainsailActor);
DELE_PTR_FULL(TopsailActor);
DELE_PTR_FULL(Main_Yard);
DELE_PTR_FULL(Topgallant_Yard);
DELE_PTR_FULL(Top_Yard);
DELE_PTR_FULL(MastBaseComponent);
DELE_PTR_FULL(Sail_Material);
DELE_PTR_FULL(DamageDecalRight);
DELE_PTR_FULL(DamageDecalLeft);
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 36.785714
| 274
| 0.776699
|
alxalx14
|
c80cf7b6a374680e884cff2ef4acdb1c77deae35
| 794
|
hpp
|
C++
|
test-suite/generated-src/cwrapper/dh__foo_some_other_record.hpp
|
trafi/trafi-djinni
|
47cd2c849782e2ab4b38e5dc6a5a3104cc87f673
|
[
"Apache-2.0"
] | 3
|
2019-11-07T03:38:03.000Z
|
2020-03-28T10:24:40.000Z
|
test-suite/generated-src/cwrapper/dh__foo_some_other_record.hpp
|
trafi/trafi-djinni
|
47cd2c849782e2ab4b38e5dc6a5a3104cc87f673
|
[
"Apache-2.0"
] | null | null | null |
test-suite/generated-src/cwrapper/dh__foo_some_other_record.hpp
|
trafi/trafi-djinni
|
47cd2c849782e2ab4b38e5dc6a5a3104cc87f673
|
[
"Apache-2.0"
] | 2
|
2020-12-01T18:39:26.000Z
|
2021-02-04T03:55:31.000Z
|
// AUTOGENERATED FILE - DO NOT MODIFY!
// This file generated by Djinni from foo_client_interface.djinni
#pragma once
#include <atomic>
#include <experimental/optional>
#include "foo_some_other_record.hpp"
#ifdef __cplusplus
extern "C" {
#endif
#include "dh__foo_some_other_record.h"
#ifdef __cplusplus
}
#endif
struct DjinniFooSomeOtherRecord {
static djinni::Handle<DjinniRecordHandle> fromCpp(const ::testsuite::FooSomeOtherRecord& dr);
static ::testsuite::FooSomeOtherRecord toCpp(djinni::Handle<DjinniRecordHandle> dh);
static djinni::Handle<DjinniOptionalRecordHandle> fromCpp(std::experimental::optional<::testsuite::FooSomeOtherRecord> dc);
static std::experimental::optional<::testsuite::FooSomeOtherRecord> toCpp(djinni::Handle<DjinniOptionalRecordHandle> dh);
};
| 33.083333
| 127
| 0.789673
|
trafi
|
c80eb117a88136d8a488b4d0ae220c3ce70ceb17
| 5,486
|
cc
|
C++
|
src/Core/Algorithms/Field/Tests/GetFieldBoundaryTests.cc
|
Haydelj/SCIRun
|
f7ee04d85349b946224dbff183438663e54b9413
|
[
"MIT"
] | 92
|
2015-02-09T22:42:11.000Z
|
2022-03-25T09:14:50.000Z
|
src/Core/Algorithms/Field/Tests/GetFieldBoundaryTests.cc
|
Haydelj/SCIRun
|
f7ee04d85349b946224dbff183438663e54b9413
|
[
"MIT"
] | 1,618
|
2015-01-05T19:39:13.000Z
|
2022-03-27T20:28:45.000Z
|
src/Core/Algorithms/Field/Tests/GetFieldBoundaryTests.cc
|
Haydelj/SCIRun
|
f7ee04d85349b946224dbff183438663e54b9413
|
[
"MIT"
] | 64
|
2015-02-20T17:51:23.000Z
|
2021-11-19T07:08:08.000Z
|
/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2020 Scientific Computing and Imaging Institute,
University of Utah.
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 <gtest/gtest.h>
#include <Core/Datatypes/Legacy/Field/VField.h>
#include <Core/Datatypes/Legacy/Field/FieldInformation.h>
#include <Core/Datatypes/Matrix.h>
#include <Core/Datatypes/MatrixIO.h>
#include <Core/Algorithms/Base/AlgorithmPreconditions.h>
#include <Core/Algorithms/Legacy/Fields/MeshDerivatives/GetFieldBoundaryAlgo.h>
#include <Core/Datatypes/MatrixTypeConversions.h>
#include <Testing/Utils/SCIRunUnitTests.h>
using namespace SCIRun;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Core::Geometry;
using namespace SCIRun::Core::Algorithms::Fields;
using namespace SCIRun::TestUtils;
// TODO: test with more field types...
namespace
{
void runTest(int basis, int expectedMatrixRows, int expectedMatrixColumns, const std::string& expectedMatrixString = "")
{
std::cout << "Basis # " << basis << std::endl;
FieldInformation lfi("LatVolMesh", basis, "double");
size_type sizex = 2, sizey = 3, sizez = 4;
Point minb(-1.0, -1.0, -1.0);
Point maxb(1.0, 1.0, 1.0);
MeshHandle mesh = CreateMesh(lfi,sizex, sizey, sizez, minb, maxb);
FieldHandle ofh = CreateField(lfi,mesh);
ofh->vfield()->clear_all_values();
GetFieldBoundaryAlgo algo;
FieldHandle boundary;
MatrixHandle mapping;
algo.run(ofh, boundary, mapping);
ASSERT_TRUE(boundary.get() != nullptr);
/// @todo: need assertions on boundary field
if (basis != -1)
{
ASSERT_TRUE(mapping != nullptr);
EXPECT_EQ(expectedMatrixRows, mapping->nrows());
EXPECT_EQ(expectedMatrixColumns, mapping->ncols());
EXPECT_EQ(expectedMatrixString, matrix_to_string(*convertMatrix::toDense(mapping)));
}
}
const std::string matrixCells =
"1 0 0 0 0 0 \n"
"1 0 0 0 0 0 \n"
"1 0 0 0 0 0 \n"
"1 0 0 0 0 0 \n"
"0 1 0 0 0 0 \n"
"0 1 0 0 0 0 \n"
"0 1 0 0 0 0 \n"
"0 1 0 0 0 0 \n"
"0 0 1 0 0 0 \n"
"0 0 1 0 0 0 \n"
"0 0 1 0 0 0 \n"
"0 0 0 1 0 0 \n"
"0 0 0 1 0 0 \n"
"0 0 0 1 0 0 \n"
"0 0 0 0 1 0 \n"
"0 0 0 0 1 0 \n"
"0 0 0 0 1 0 \n"
"0 0 0 0 1 0 \n"
"0 0 0 0 0 1 \n"
"0 0 0 0 0 1 \n"
"0 0 0 0 0 1 \n"
"0 0 0 0 0 1 \n";
const std::string matrixNodes =
"1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 \n";
}
TEST(GetFieldBoundaryTest, LatVolBoundary)
{
runTest(0, 22, 6, matrixCells);
runTest(-1, 0, 0);
runTest(1, 24, 24, matrixNodes);
/*
EXPECT_EQ("GenericField<LatVolMesh<HexTrilinearLgn<Point> > ,NoDataBasis<double> ,FData3d<double,LatVolMesh<HexTrilinearLgn<Point> > > > ", info.type);
EXPECT_EQ(0, info.dataMin);
EXPECT_EQ(0, info.dataMax);
EXPECT_EQ(0, info.numdata_);
EXPECT_EQ(sizex * sizey * sizez, info.numnodes_);
EXPECT_EQ((sizex-1) * (sizey-1) * (sizez-1), info.numelements_);
EXPECT_EQ("None (nodata basis)", info.dataLocation);*/
}
TEST(GetFieldBoundaryTest, CanLogErrorMessage)
{
GetFieldBoundaryAlgo algo;
FieldHandle input, output;
MatrixHandle mapping;
EXPECT_FALSE(algo.run(input, output, mapping));
EXPECT_FALSE(algo.run(input, output));
}
| 34.503145
| 153
| 0.644185
|
Haydelj
|
c81028836b3520283ef874f8e452541d01b699db
| 5,695
|
cc
|
C++
|
chrome/browser/chromeos/file_system_provider/throttled_file_system_unittest.cc
|
Wzzzx/chromium-crosswalk
|
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2
|
2019-01-28T08:09:58.000Z
|
2021-11-15T15:32:10.000Z
|
chrome/browser/chromeos/file_system_provider/throttled_file_system_unittest.cc
|
maidiHaitai/haitaibrowser
|
a232a56bcfb177913a14210e7733e0ea83a6b18d
|
[
"BSD-3-Clause"
] | 1
|
2016-07-11T15:19:20.000Z
|
2017-04-02T20:38:55.000Z
|
chrome/browser/chromeos/file_system_provider/throttled_file_system_unittest.cc
|
maidiHaitai/haitaibrowser
|
a232a56bcfb177913a14210e7733e0ea83a6b18d
|
[
"BSD-3-Clause"
] | 6
|
2020-09-23T08:56:12.000Z
|
2021-11-18T03:40:49.000Z
|
// 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/chromeos/file_system_provider/throttled_file_system.h"
#include <stddef.h>
#include <memory>
#include <vector>
#include "base/files/file.h"
#include "base/memory/ptr_util.h"
#include "base/run_loop.h"
#include "chrome/browser/chromeos/file_system_provider/abort_callback.h"
#include "chrome/browser/chromeos/file_system_provider/fake_provided_file_system.h"
#include "chrome/browser/chromeos/file_system_provider/provided_file_system_info.h"
#include "chrome/common/extensions/api/file_system_provider_capabilities/file_system_provider_capabilities_handler.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace chromeos {
namespace file_system_provider {
namespace {
const char kExtensionId[] = "mbflcebpggnecokmikipoihdbecnjfoj";
const char kFileSystemId[] = "camera-pictures";
const char kDisplayName[] = "Camera Pictures";
typedef std::vector<base::File::Error> StatusLog;
typedef std::vector<std::pair<int, base::File::Error>> OpenLog;
// Writes a |result| to the |log| vector for a status callback.
void LogStatus(StatusLog* log, base::File::Error result) {
log->push_back(result);
}
// Writes a |result| to the |log| vector for opening a file.
void LogOpen(OpenLog* log, int handle, base::File::Error result) {
log->push_back(std::make_pair(handle, result));
}
} // namespace
class FileSystemProviderThrottledFileSystemTest : public testing::Test {
protected:
FileSystemProviderThrottledFileSystemTest() {}
~FileSystemProviderThrottledFileSystemTest() override {}
void SetUp() override {}
// Initializes the throttled file system with |limit| number of opened files
// at once. If 0, then no limit.
void SetUpFileSystem(size_t limit) {
MountOptions options(kFileSystemId, kDisplayName);
options.opened_files_limit = limit;
ProvidedFileSystemInfo file_system_info(
kExtensionId, options, base::FilePath() /* mount_path */,
false /* configurable */, true /* watchable */,
extensions::SOURCE_FILE);
file_system_.reset(new ThrottledFileSystem(
base::WrapUnique(new FakeProvidedFileSystem(file_system_info))));
}
content::TestBrowserThreadBundle thread_bundle_;
std::unique_ptr<ThrottledFileSystem> file_system_;
};
TEST_F(FileSystemProviderThrottledFileSystemTest, OpenFile_LimitedToOneAtOnce) {
SetUpFileSystem(1);
OpenLog first_open_log;
file_system_->OpenFile(base::FilePath(kFakeFilePath), OPEN_FILE_MODE_READ,
base::Bind(&LogOpen, &first_open_log));
OpenLog second_open_log;
file_system_->OpenFile(base::FilePath(kFakeFilePath), OPEN_FILE_MODE_READ,
base::Bind(&LogOpen, &second_open_log));
base::RunLoop().RunUntilIdle();
ASSERT_EQ(1u, first_open_log.size());
EXPECT_EQ(base::File::FILE_OK, first_open_log[0].second);
EXPECT_EQ(0u, second_open_log.size());
// Close the first file.
StatusLog close_log;
file_system_->CloseFile(first_open_log[0].first,
base::Bind(&LogStatus, &close_log));
base::RunLoop().RunUntilIdle();
ASSERT_EQ(1u, close_log.size());
EXPECT_EQ(base::File::FILE_OK, close_log[0]);
// The second enqueued file should be opened.
ASSERT_EQ(1u, first_open_log.size());
EXPECT_EQ(base::File::FILE_OK, first_open_log[0].second);
ASSERT_EQ(1u, second_open_log.size());
EXPECT_EQ(base::File::FILE_OK, second_open_log[0].second);
}
TEST_F(FileSystemProviderThrottledFileSystemTest, OpenFile_NoLimit) {
SetUpFileSystem(0); // No limit.
OpenLog first_open_log;
file_system_->OpenFile(base::FilePath(kFakeFilePath), OPEN_FILE_MODE_READ,
base::Bind(&LogOpen, &first_open_log));
OpenLog second_open_log;
file_system_->OpenFile(base::FilePath(kFakeFilePath), OPEN_FILE_MODE_READ,
base::Bind(&LogOpen, &second_open_log));
base::RunLoop().RunUntilIdle();
ASSERT_EQ(1u, first_open_log.size());
EXPECT_EQ(base::File::FILE_OK, first_open_log[0].second);
ASSERT_EQ(1u, second_open_log.size());
EXPECT_EQ(base::File::FILE_OK, second_open_log[0].second);
// Close files.
StatusLog first_close_log;
file_system_->CloseFile(first_open_log[0].first,
base::Bind(&LogStatus, &first_close_log));
StatusLog second_close_log;
file_system_->CloseFile(second_open_log[0].first,
base::Bind(&LogStatus, &second_close_log));
base::RunLoop().RunUntilIdle();
ASSERT_EQ(1u, first_close_log.size());
EXPECT_EQ(base::File::FILE_OK, first_close_log[0]);
ASSERT_EQ(1u, second_close_log.size());
EXPECT_EQ(base::File::FILE_OK, second_close_log[0]);
// Confirm, that files are not opened again.
EXPECT_EQ(1u, first_open_log.size());
EXPECT_EQ(1u, second_open_log.size());
}
TEST_F(FileSystemProviderThrottledFileSystemTest, AbortAfterRun) {
SetUpFileSystem(1);
OpenLog first_open_log;
AbortCallback abort_callback =
file_system_->OpenFile(base::FilePath(kFakeFilePath), OPEN_FILE_MODE_READ,
base::Bind(&LogOpen, &first_open_log));
OpenLog second_open_log;
file_system_->OpenFile(base::FilePath(kFakeFilePath), OPEN_FILE_MODE_READ,
base::Bind(&LogOpen, &second_open_log));
base::RunLoop().RunUntilIdle();
ASSERT_EQ(1u, first_open_log.size());
EXPECT_EQ(base::File::FILE_OK, first_open_log[0].second);
EXPECT_EQ(0u, second_open_log.size());
}
} // namespace file_system_provider
} // namespace chromeos
| 34.93865
| 117
| 0.731168
|
Wzzzx
|
c811c8e0527012cbdded435ce014a7ac3b332128
| 967
|
cc
|
C++
|
src/media/audio/audio_core/pipeline_config_unittest.cc
|
wwjiang007/fuchsia-1
|
0db66b52b5bcd3e27c8b8c2163925309e8522f94
|
[
"BSD-2-Clause"
] | 210
|
2019-02-05T12:45:09.000Z
|
2022-03-28T07:59:06.000Z
|
src/media/audio/audio_core/pipeline_config_unittest.cc
|
wwjiang007/fuchsia-1
|
0db66b52b5bcd3e27c8b8c2163925309e8522f94
|
[
"BSD-2-Clause"
] | 56
|
2021-06-03T03:16:25.000Z
|
2022-03-20T01:07:44.000Z
|
src/media/audio/audio_core/pipeline_config_unittest.cc
|
wwjiang007/fuchsia-1
|
0db66b52b5bcd3e27c8b8c2163925309e8522f94
|
[
"BSD-2-Clause"
] | 73
|
2019-03-06T18:55:23.000Z
|
2022-03-26T12:04:51.000Z
|
// Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/media/audio/audio_core/pipeline_config.h"
#include <gtest/gtest.h>
namespace media::audio {
namespace {
TEST(PipelineConfigTest, CalculateChannels) {
auto config = PipelineConfig::Default();
// No effects, the pipeline channelization is the same as the output of the root mix stage.
EXPECT_EQ(config.root().output_channels, config.channels());
// With rechannelization effects, the last effect defines the channelization.
config.mutable_root().effects.push_back(
{"lib.so", "effect", "e1", "", {config.root().output_channels + 1}});
config.mutable_root().effects.push_back(
{"lib.so", "effect", "e2", "", {config.root().output_channels + 2}});
EXPECT_EQ(config.root().output_channels + 2, config.channels());
}
} // namespace
} // namespace media::audio
| 34.535714
| 93
| 0.715615
|
wwjiang007
|
c81318664086f895c7665d7bece4e25cd0ec40f8
| 8,272
|
cpp
|
C++
|
src/GPU/pair_beck_gpu.cpp
|
luwei0917/GlpG_Nature_Communication
|
a7f4f8b526e633b158dc606050e8993d70734943
|
[
"MIT"
] | 1
|
2018-11-28T15:04:55.000Z
|
2018-11-28T15:04:55.000Z
|
src/GPU/pair_beck_gpu.cpp
|
luwei0917/GlpG_Nature_Communication
|
a7f4f8b526e633b158dc606050e8993d70734943
|
[
"MIT"
] | null | null | null |
src/GPU/pair_beck_gpu.cpp
|
luwei0917/GlpG_Nature_Communication
|
a7f4f8b526e633b158dc606050e8993d70734943
|
[
"MIT"
] | null | null | null |
/* ----------------------------------------------------------------------
LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator
http://lammps.sandia.gov, Sandia National Laboratories
Steve Plimpton, sjplimp@sandia.gov
Copyright (2003) Sandia Corporation. Under the terms of Contract
DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains
certain rights in this software. This software is distributed under
the GNU General Public License.
See the README file in the top-level LAMMPS directory.
------------------------------------------------------------------------- */
/* ----------------------------------------------------------------------
Contributing author: Trung Dac Nguyen (ORNL)
------------------------------------------------------------------------- */
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include "pair_beck_gpu.h"
#include "atom.h"
#include "atom_vec.h"
#include "comm.h"
#include "force.h"
#include "neighbor.h"
#include "neigh_list.h"
#include "integrate.h"
#include "memory.h"
#include "error.h"
#include "neigh_request.h"
#include "universe.h"
#include "update.h"
#include "domain.h"
#include <string.h>
#include "gpu_extra.h"
#include "math_special.h"
using namespace LAMMPS_NS;
using namespace MathSpecial;
// External functions from cuda library for atom decomposition
int beck_gpu_init(const int ntypes, double **cutsq, double **host_aa,
double **alpha, double **beta, double **AA, double **BB,
double *special_lj, const int nlocal,
const int nall, const int max_nbors, const int maxspecial,
const double cell_size, int &gpu_mode, FILE *screen);
void beck_gpu_clear();
int ** beck_gpu_compute_n(const int ago, const int inum,
const int nall, double **host_x, int *host_type,
double *sublo, double *subhi, tagint *tag, int **nspecial,
tagint **special, const bool eflag, const bool vflag,
const bool eatom, const bool vatom, int &host_start,
int **ilist, int **jnum,
const double cpu_time, bool &success);
void beck_gpu_compute(const int ago, const int inum, const int nall,
double **host_x, int *host_type, int *ilist, int *numj,
int **firstneigh, const bool eflag, const bool vflag,
const bool eatom, const bool vatom, int &host_start,
const double cpu_time, bool &success);
double beck_gpu_bytes();
/* ---------------------------------------------------------------------- */
PairBeckGPU::PairBeckGPU(LAMMPS *lmp) : PairBeck(lmp), gpu_mode(GPU_FORCE)
{
respa_enable = 0;
reinitflag = 0;
cpu_time = 0.0;
GPU_EXTRA::gpu_ready(lmp->modify, lmp->error);
}
/* ----------------------------------------------------------------------
free all arrays
------------------------------------------------------------------------- */
PairBeckGPU::~PairBeckGPU()
{
beck_gpu_clear();
}
/* ---------------------------------------------------------------------- */
void PairBeckGPU::compute(int eflag, int vflag)
{
if (eflag || vflag) ev_setup(eflag,vflag);
else evflag = vflag_fdotr = 0;
int nall = atom->nlocal + atom->nghost;
int inum, host_start;
bool success = true;
int *ilist, *numneigh, **firstneigh;
if (gpu_mode != GPU_FORCE) {
inum = atom->nlocal;
firstneigh = beck_gpu_compute_n(neighbor->ago, inum, nall,
atom->x, atom->type, domain->sublo,
domain->subhi, atom->tag, atom->nspecial,
atom->special, eflag, vflag, eflag_atom,
vflag_atom, host_start,
&ilist, &numneigh, cpu_time, success);
} else {
inum = list->inum;
ilist = list->ilist;
numneigh = list->numneigh;
firstneigh = list->firstneigh;
beck_gpu_compute(neighbor->ago, inum, nall, atom->x, atom->type,
ilist, numneigh, firstneigh, eflag, vflag, eflag_atom,
vflag_atom, host_start, cpu_time, success);
}
if (!success)
error->one(FLERR,"Insufficient memory on accelerator");
if (host_start<inum) {
cpu_time = MPI_Wtime();
cpu_compute(host_start, inum, eflag, vflag, ilist, numneigh, firstneigh);
cpu_time = MPI_Wtime() - cpu_time;
}
}
/* ----------------------------------------------------------------------
init specific to this pair style
------------------------------------------------------------------------- */
void PairBeckGPU::init_style()
{
if (force->newton_pair)
error->all(FLERR,"Cannot use newton pair with beck/gpu pair style");
// Repeat cutsq calculation because done after call to init_style
double maxcut = -1.0;
double cut;
for (int i = 1; i <= atom->ntypes; i++) {
for (int j = i; j <= atom->ntypes; j++) {
if (setflag[i][j] != 0 || (setflag[i][i] != 0 && setflag[j][j] != 0)) {
cut = init_one(i,j);
cut *= cut;
if (cut > maxcut)
maxcut = cut;
cutsq[i][j] = cutsq[j][i] = cut;
} else
cutsq[i][j] = cutsq[j][i] = 0.0;
}
}
double cell_size = sqrt(maxcut) + neighbor->skin;
int maxspecial=0;
if (atom->molecular)
maxspecial=atom->maxspecial;
int success = beck_gpu_init(atom->ntypes+1, cutsq, aa, alpha, beta,
AA, BB, force->special_lj, atom->nlocal,
atom->nlocal+atom->nghost, 300, maxspecial,
cell_size, gpu_mode, screen);
GPU_EXTRA::check_flag(success,error,world);
if (gpu_mode == GPU_FORCE) {
int irequest = neighbor->request(this,instance_me);
neighbor->requests[irequest]->half = 0;
neighbor->requests[irequest]->full = 1;
}
}
/* ---------------------------------------------------------------------- */
double PairBeckGPU::memory_usage()
{
double bytes = Pair::memory_usage();
return bytes + beck_gpu_bytes();
}
/* ---------------------------------------------------------------------- */
void PairBeckGPU::cpu_compute(int start, int inum, int eflag, int vflag,
int *ilist, int *numneigh, int **firstneigh) {
int i,j,ii,jj,jnum,itype,jtype;
double xtmp,ytmp,ztmp,delx,dely,delz,evdwl,fpair;
double rsq,r5,force_beck,factor_lj;
double r,rinv;
double aaij,alphaij,betaij;
double term1,term1inv,term2,term3,term4,term5,term6;
int *jlist;
double **x = atom->x;
double **f = atom->f;
int *type = atom->type;
double *special_lj = force->special_lj;
// loop over neighbors of my atoms
for (ii = start; ii < inum; ii++) {
i = ilist[ii];
xtmp = x[i][0];
ytmp = x[i][1];
ztmp = x[i][2];
itype = type[i];
jlist = firstneigh[i];
jnum = numneigh[i];
for (jj = 0; jj < jnum; jj++) {
j = jlist[jj];
factor_lj = special_lj[sbmask(j)];
j &= NEIGHMASK;
delx = xtmp - x[j][0];
dely = ytmp - x[j][1];
delz = ztmp - x[j][2];
rsq = delx*delx + dely*dely + delz*delz;
jtype = type[j];
if (rsq < cutsq[itype][jtype]) {
r = sqrt(rsq);
r5 = rsq*rsq*r;
aaij = aa[itype][jtype];
alphaij = alpha[itype][jtype];
betaij = beta[itype][jtype];
term1 = aaij*aaij + rsq;
term2 = powint(term1,-5);
term3 = 21.672 + 30.0*aaij*aaij + 6.0*rsq;
term4 = alphaij + r5*betaij;
term5 = alphaij + 6.0*r5*betaij;
rinv = 1.0/r;
force_beck = AA[itype][jtype]*exp(-1.0*r*term4)*term5;
force_beck -= BB[itype][jtype]*r*term2*term3;
fpair = factor_lj*force_beck*rinv;
f[i][0] += delx*fpair;
f[i][1] += dely*fpair;
f[i][2] += delz*fpair;
if (eflag) {
term6 = powint(term1,-3);
term1inv = 1.0/term1;
evdwl = AA[itype][jtype]*exp(-1.0*r*term4);
evdwl -= BB[itype][jtype]*term6*(1.0+(2.709+3.0*aaij*aaij)*term1inv);
evdwl *= factor_lj;
}
if (evflag) ev_tally_full(i,evdwl,0.0,fpair,delx,dely,delz);
}
}
}
}
| 33.763265
| 84
| 0.525145
|
luwei0917
|
c813490b6f20955ac18a0b771bb4fc7c506fa4ef
| 3,157
|
cpp
|
C++
|
test/src/thd/monitor_test.cpp
|
CppPhil/philslib
|
9d60d7f3a43b9de62f7e5d9550541293e0b15333
|
[
"Unlicense"
] | 3
|
2017-10-29T09:36:18.000Z
|
2022-03-07T20:04:08.000Z
|
test/src/thd/monitor_test.cpp
|
CppPhil/philslib
|
9d60d7f3a43b9de62f7e5d9550541293e0b15333
|
[
"Unlicense"
] | 1
|
2018-02-13T16:07:30.000Z
|
2018-02-13T16:07:30.000Z
|
test/src/thd/monitor_test.cpp
|
CppPhil/philslib
|
9d60d7f3a43b9de62f7e5d9550541293e0b15333
|
[
"Unlicense"
] | 3
|
2017-10-29T09:24:20.000Z
|
2018-11-03T09:53:46.000Z
|
/* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or
* distribute this software, either in source code form or as a compiled
* binary, for any purpose, commercial or non-commercial, and by any
* means.
*
* In jurisdictions that recognize copyright laws, the author or authors
* of this software dedicate any and all copyright interest in the
* software to the public domain. We make this dedication for the benefit
* of the public at large and to the detriment of our heirs and
* successors. We intend this dedication to be an overt act of
* relinquishment in perpetuity of all present and future rights to this
* software under copyright law.
*
* 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 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.
*
* For more information, please refer to <http://unlicense.org/>
*/
#include "../../../include/pl/compiler.hpp"
#if PL_COMPILER == PL_COMPILER_GCC
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmissing-noreturn"
#endif // PL_COMPILER == PL_COMPILER_GCC
#include "../../doctest.h"
#if PL_COMPILER == PL_COMPILER_GCC
#pragma GCC diagnostic pop
#endif // PL_COMPILER == PL_COMPILER_GCC
#include "../../../include/pl/thd/monitor.hpp" // pl::thd::monitor
#include <cstring> // std::strcmp
#include <string> // std::string
#include <utility> // std::move
namespace pl {
namespace test {
namespace {
class monitor_test_type {
public:
using this_type = monitor_test_type;
monitor_test_type(int i, double d, std::string s)
: m_i{i}, m_d{d}, m_s{std::move(s)}
{
}
double d() const noexcept
{
return m_d;
}
void d(double d) noexcept
{
m_d = d;
}
void set_d_to_25() noexcept
{
d(25.0);
}
const char* str() const noexcept
{
return m_s.data();
}
int m_i;
private:
double m_d;
std::string m_s;
};
} // anonymous namespace
} // namespace test
} // namespace pl
TEST_CASE("monitor_test")
{
pl::thd::monitor<pl::test::monitor_test_type> monitor{
pl::test::monitor_test_type{1, 2.0, "text"}};
CHECK(
monitor([](pl::test::monitor_test_type& o) { return o.d(); })
== doctest::Approx{2.0});
monitor(&pl::test::monitor_test_type::set_d_to_25);
CHECK(
monitor(static_cast<double (pl::test::monitor_test_type::*)() const>(
&pl::test::monitor_test_type::d))
== doctest::Approx{25.0});
CHECK(std::strcmp(monitor(&pl::test::monitor_test_type::str), "text") == 0);
CHECK(monitor(&pl::test::monitor_test_type::m_i) == 1);
}
| 31.888889
| 80
| 0.649351
|
CppPhil
|
c813af4fe5af344c979ee5bb7ec4f8f332ea8838
| 7,886
|
cpp
|
C++
|
testsams/sams_crypto/software/DLLDemo.cpp
|
quchunguang/test
|
dd1dde14a69d9e8b2c9ed3efbf536df7840f0487
|
[
"MIT"
] | 1
|
2021-05-06T02:02:59.000Z
|
2021-05-06T02:02:59.000Z
|
testsams/sams_crypto/software/DLLDemo.cpp
|
SrikanthParsha14/test
|
8cee69e09c8557d53d8d30382cec8ea5c1f82f6e
|
[
"MIT"
] | null | null | null |
testsams/sams_crypto/software/DLLDemo.cpp
|
SrikanthParsha14/test
|
8cee69e09c8557d53d8d30382cec8ea5c1f82f6e
|
[
"MIT"
] | 1
|
2019-06-17T13:20:39.000Z
|
2019-06-17T13:20:39.000Z
|
// DLLDemo.cpp : Defines the entry point for the DLL application.
//
#include "sense4.h"
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include "common.h"
#include "..\inc\sample_26.h"
#include "DLLDemo.h"
/* global variables definition */
SENSE4_CONTEXT stS4Ctx = {0};
unsigned long dwBytesReturned = 0;
IO_PACKAGE stDataPkgIn = {0};
IO_PACKAGE stDataPkgOut = {0};
#define S4_EXE_FILE_1 "f001"
#define S4_EXE_FILE_2 "f002"
int enc_dec_ecb(int id, unsigned char cmd, unsigned char *in, unsigned char inlen,
unsigned char *out, unsigned char *outlen)
{
unsigned long dwResult = S4_SUCCESS;
assert(NULL != out && NULL != outlen && NULL != in);
assert(cmd == DES_ENC_ECB || cmd == DES_DEC_ECB || cmd == TDES_ENC_ECB || cmd == TDES_DEC_ECB);
stDataPkgIn.tag = cmd;
stDataPkgIn.len = inlen;
memcpy(stDataPkgIn.buff, in, inlen);
//printf("id=%d\n",id);
if (id == 1) {
dwResult = S4Execute(&stS4Ctx, S4_EXE_FILE_1, &stDataPkgIn,
IO_PACKAGE_HEADER_SIZE+stDataPkgIn.len,
&stDataPkgOut, sizeof(IO_PACKAGE), &dwBytesReturned);
//printf("%s\n",S4_EXE_FILE_1);
} else if (id == 2){
dwResult = S4Execute(&stS4Ctx, S4_EXE_FILE_2, &stDataPkgIn,
IO_PACKAGE_HEADER_SIZE+stDataPkgIn.len,
&stDataPkgOut, sizeof(IO_PACKAGE), &dwBytesReturned);
//printf("%s\n",S4_EXE_FILE_2);
}
if (dwResult != S4_SUCCESS)
{
return S4_ERROR_INVALID_DATA;
}
if (*outlen < stDataPkgOut.len)
{
return S4_ERROR_OUT_BUFFER;
}
*outlen = stDataPkgOut.len;
memcpy(out,stDataPkgOut.buff,stDataPkgOut.len);
return S4_SUCCESS;
}
int enc_dec_cbc(unsigned char cmd, unsigned char *iv, unsigned char *in, unsigned char inlen,
unsigned char *out, unsigned char *outlen)
{
unsigned long dwResult = S4_SUCCESS;
DATA_BLOCK stDataBlk = {0};
assert(NULL != out && NULL != outlen && NULL != in && iv != NULL);
assert(cmd == DES_ENC_CBC || cmd == DES_DEC_CBC || cmd == TDES_ENC_CBC || cmd == TDES_DEC_CBC);
if (inlen > MAX_DATA_BLOCK_LEN)
{
return S4_ERROR_INPUT_TOO_LONG;
}
memcpy(stDataBlk.iv, iv, sizeof(stDataBlk.iv));
stDataBlk.len = inlen;
memcpy(stDataBlk.buff, in, inlen);
stDataPkgIn.tag = cmd;
stDataPkgIn.len = sizeof(stDataBlk) - sizeof(stDataBlk.buff) + stDataBlk.len;
memcpy(stDataPkgIn.buff, &stDataBlk, stDataPkgIn.len);
dwResult = S4Execute(&stS4Ctx, S4_EXE_FILE_1, &stDataPkgIn,
IO_PACKAGE_HEADER_SIZE+stDataPkgIn.len,
&stDataPkgOut, sizeof(IO_PACKAGE), &dwBytesReturned);
if (dwResult != S4_SUCCESS)
{
return dwResult;
}
if (*outlen < stDataPkgOut.len)
{
return S4_ERROR_INSUFFICIENT_BUFFER;
}
*outlen = stDataPkgOut.len;
memcpy(out,stDataPkgOut.buff,stDataPkgOut.len);
return S4_SUCCESS;
}
extern "C" _declspec(dllexport) unsigned long TestEIV(unsigned char * buff)
{
SENSE4_CONTEXT ctx = {0};
SENSE4_CONTEXT *pctx = NULL;
unsigned long size = 0;
unsigned long ret = 0;
S4Enum(pctx, &size);
if (size == 0)
{
//printf("EliteIV not found!\n");
return 111;
}
pctx = (SENSE4_CONTEXT *)malloc(size);
if (pctx == NULL)
{
//printf("Not enough memory!\n");
return 222;
}
ret = S4Enum(pctx, &size);
if (ret != S4_SUCCESS)
{
//printf("Enumerate EliteIV error!\n");
free(pctx);
return ret;
}
memcpy(&ctx, pctx, sizeof(SENSE4_CONTEXT));
free(pctx);
pctx = NULL;
ret = S4Open(&ctx);
if (ret != S4_SUCCESS)
{
//printf("Open EliteIV failed!\n");
return ret;
}
ret = S4ChangeDir(&ctx, "\\");
if (ret != S4_SUCCESS)
{
//printf("No root directory found!\n");
S4Close(&ctx);
return ret;
}
ret = S4VerifyPin(&ctx, (unsigned char *)"12345678", 8, S4_USER_PIN);
if (ret != S4_SUCCESS)
{
//printf("Verify user PIN failed!\n");
S4Close(&ctx);
return ret;
}
ret = S4Execute(&ctx, "0001", buff, 10, buff, 10, &size);
if (ret != S4_SUCCESS)
{
//printf("Execute EliteIV exe failed!\n");
S4Close(&ctx);
return ret;
}
S4Close(&ctx);
return 0;
}
extern "C" _declspec(dllexport) int crypto(
int type, /* 0=encryptpgraphy, 1=decryptography */
unsigned char fromText[],
unsigned char toText[]
)
/*extern "C" __declspec(dllexport) int crypto(int type,
unsigned char fromText[],
unsigned char toText[]
)*/
{
unsigned long dwResult = S4_SUCCESS;
unsigned char lpUserPin[] = USERPEN;
unsigned char TextLen = BUFFERLENGTH;
unsigned char tmp;
//printf("call crypto\n");
if (!(dwResult = OpenS4ByIndex(FIRST_S4_INDEX,&stS4Ctx)))
{
return S4_ERROR_DEVICE;
}
dwResult = S4ChangeDir(&stS4Ctx, "\\");
if (dwResult != S4_SUCCESS)
{
S4Close(&stS4Ctx);
return dwResult;
}
// Call S4VerifyPin(...) to verify User PIN so as to get the privilege to execute the program in EliteIV.
dwResult = S4VerifyPin(&stS4Ctx, lpUserPin, strlen((LPCSTR)lpUserPin), S4_USER_PIN);
if (dwResult != S4_SUCCESS)
{
S4Close(&stS4Ctx);
return dwResult;
}
if(type == 0){
if (dwResult = enc_dec_ecb(1, TDES_ENC_ECB, fromText, TextLen, toText, &tmp))
{
ResetAndCloseS4(&stS4Ctx);
return dwResult;
}
}
else {
if (dwResult = enc_dec_ecb(1, TDES_DEC_ECB, fromText, TextLen, toText, &tmp))
{
ResetAndCloseS4(&stS4Ctx);
return dwResult;
}
}
/* for better security,use the following instead of using S4close() directly */
ResetAndCloseS4(&stS4Ctx);
return S4_SUCCESS;
}
extern "C" _declspec(dllexport) int crypto2(
int type, /* 0=encryptpgraphy, 1=decryptography */
unsigned char fromText[],
unsigned char toText[]
)
/*extern "C" __declspec(dllexport) int crypto(int type,
unsigned char fromText[],
unsigned char toText[]
)*/
{
unsigned long dwResult = S4_SUCCESS;
unsigned char lpUserPin[] = USERPEN;
unsigned char TextLen = BUFFERLENGTH;
unsigned char tmp;
//printf("call crypto2\n");
if (!(dwResult = OpenS4ByIndex(FIRST_S4_INDEX,&stS4Ctx)))
{
return S4_ERROR_DEVICE;
}
dwResult = S4ChangeDir(&stS4Ctx, "\\");
if (dwResult != S4_SUCCESS)
{
S4Close(&stS4Ctx);
return dwResult;
}
// Call S4VerifyPin(...) to verify User PIN so as to get the privilege to execute the program in EliteIV.
dwResult = S4VerifyPin(&stS4Ctx, lpUserPin, strlen((LPCSTR)lpUserPin), S4_USER_PIN);
if (dwResult != S4_SUCCESS)
{
S4Close(&stS4Ctx);
return dwResult;
}
if(type == 0){
if (dwResult = enc_dec_ecb(2, TDES_ENC_ECB, fromText, TextLen, toText, &tmp))
{
ResetAndCloseS4(&stS4Ctx);
return dwResult;
}
}
else {
if (dwResult = enc_dec_ecb(2, TDES_DEC_ECB, fromText, TextLen, toText, &tmp))
{
ResetAndCloseS4(&stS4Ctx);
return dwResult;
}
}
/* for better security,use the following instead of using S4close() directly */
ResetAndCloseS4(&stS4Ctx);
return S4_SUCCESS;
}
char char2hex(char c)
{
if (c < 0x0A) {
return c + 0x30;
}
else if (c >= 0x0A && c <= 0x0F) {
return c + 0x41 - 0x0A;
}
else {
return 'x';
}
}
/* using crypto2() encrypt random pass from server */
extern "C" _declspec(dllexport) int encryptrand(
unsigned char random[], /* 16 byte chars like: dasf98723478fd7a */
unsigned char encrypt_hex[] /* 32 byte hex chars like: 00010203040506070809f0f1f2f3f4f5 */
)
{
int i;
char a, b;
unsigned char encrypt[200];
unsigned long dwResult;
memset(encrypt, 0, 200);
dwResult = crypto2(0, random, encrypt);
for (i=0; i<16; i++){
a = (encrypt[i] & 0xF0) >> 4;
b = encrypt[i] & 0x0F;
encrypt_hex[2 * i] = char2hex(a);
encrypt_hex[2 * i + 1] = char2hex(b);
}
return dwResult;
}
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
return TRUE;
}
| 24.490683
| 107
| 0.644433
|
quchunguang
|
c8143f4acce02eb5866bb688628c0da88133b559
| 10,360
|
cpp
|
C++
|
src/sim/airframe/atmos.cpp
|
Terebinth/freefalcon-central
|
c28d807183ab447ef6a801068aa3769527d55deb
|
[
"BSD-2-Clause"
] | 117
|
2015-01-13T14:48:49.000Z
|
2022-03-16T01:38:19.000Z
|
src/sim/airframe/atmos.cpp
|
darongE/freefalcon-central
|
c28d807183ab447ef6a801068aa3769527d55deb
|
[
"BSD-2-Clause"
] | 4
|
2015-05-01T13:09:53.000Z
|
2017-07-22T09:11:06.000Z
|
src/sim/airframe/atmos.cpp
|
darongE/freefalcon-central
|
c28d807183ab447ef6a801068aa3769527d55deb
|
[
"BSD-2-Clause"
] | 78
|
2015-01-13T09:27:47.000Z
|
2022-03-18T14:39:09.000Z
|
/******************************************************************************/
/* */
/* Unit Name : atmos.cpp */
/* */
/* Abstract : Calculates atmosphere at the current altitude */
/* */
/* Naming Conventions : */
/* */
/* Public Functions : Mixed case with no underscores */
/* Private Functions : Mixed case with no underscores */
/* Public Functions : Mixed case with no underscores */
/* Global Variables : Mixed case with no underscores */
/* Classless Functions : Mixed case with no underscores */
/* Classes : All upper case seperated by an underscore */
/* Defined Constants : All upper case seperated by an underscore */
/* Macros : All upper case seperated by an underscore */
/* Structs/Types : All upper case seperated by an underscore */
/* Private Variables : All lower case seperated by an underscore */
/* Public Variables : All lower case seperated by an underscore */
/* Local Variables : All lower case seperated by an underscore */
/* */
/* Development History : */
/* Date Programer Description */
/*----------------------------------------------------------------------------*/
/* 23-Jan-95 LR Initial Write */
/* */
/******************************************************************************/
#include "stdhdr.h"
#include "airframe.h"
#include "simdrive.h"
#include "ffeedbk.h"
#include "Graphics/Include/drawsgmt.h"
static float lastqBar = 0; // Note: This limits us to 1 ownship/Force feedback stick per machine
static const float tropoAlt = 36089.0F, tropoAlt2 = 65617;
extern bool g_bFFCenterFix;
/********************************************************************/
/* */
/* Routine: void AirframeClass::Atmosphere(void) */
/* */
/* Description: */
/* Calculates current state included pressure, mach, qbar and */
/* qsom for normalizing. */
/* */
/* Inputs: */
/* None */
/* */
/* Outputs: */
/* None */
/* */
/* Development History : */
/* Date Programer Description */
/*------------------------------------------------------------------*/
/* 23-Jan-95 LR Initial Write */
/* */
/********************************************************************/
void AirframeClass::Atmosphere(void)
{
float ttheta, rsigma;
float pdelta, sound;
float qpasl1, oper, pa, qc;
pdelta = CalcPressureRatio(-z, &ttheta, &rsigma);
sound = (float)sqrt(ttheta) * AASL;
rho = rsigma * RHOASL;
pa = pdelta * PASL;
if (IsSet(Trimming))
{
if (mach > 3.0)
//vt = CalcMach(mach, pdelta) * sound;
vt = mach * KNOTS_TO_FTPSEC;
else
vt = mach * sound;
}
/*----------------------------*/
/* calculate dynamic pressure */
/*----------------------------*/
mach = vt / ((float)sqrt(ttheta) * AASL);//ME123 CALCULATE A TRUE MACH...NOT JUST VT/SPEEDOFSOUND
if (fabs(vt) > 1.0F)
{
qbar = 0.5F * rho * vt * vt;
/*-------------------------------*/
/* calculate calibrated airspeed */
/*-------------------------------*/
if (mach <= 1.0F)
qc = ((float)pow((1.0F + 0.2F * mach * mach), 3.5F) - 1.0F) * pa;
else
qc = ((166.9F * mach * mach) / (float)(pow((7.0F - 1.0F / (mach * mach)), 2.5F)) - 1.0F) * pa;
qpasl1 = qc / PASL + 1.0F;
vcas = 1479.12F * (float)sqrt(pow(qpasl1, 0.285714F) - 1.0F);
if (qc > 1889.64F)
{
oper = qpasl1 * (float)pow((7.0F - AASLK * AASLK / (vcas * vcas)), 2.5F);
if (oper < 0.0F) oper = 0.1F;
vcas = 51.1987F * (float)sqrt(oper);
}
/*------------------------*/
/* normalizing parameters */
/*------------------------*/
qsom = qbar * area / mass;
qovt = qbar / vt;
}
else
{
vcas = max(vt * FTPSEC_TO_KNOTS, 0.001F);
qsom = 0.1F;
qovt = 0.1F;
qbar = 0.001F;
mach = 0.001F;
}
//Wombat778 12-02-2003 Removed
/*
if (platform == SimDriver.GetPlayerEntity())
{
if (g_bFFCenterFix) JoystickPlayEffect (JoyAutoCenter, 20000); //Wombat778 11-26-2003 Changed method of FFCenterfix. Added because of some reports that centering cuts out after an effect is played
{
if (qbar < 250)
{
if (fabs (qbar - lastqBar) > 5.0F)
{
if ( not g_bFFCenterFix) //Wombat778 9-29-2003 Allows user to have the fixed centering force for FF sticks
JoystickPlayEffect (JoyAutoCenter, FloatToInt32((qbar/250.0F * 0.5F + 0.5F) * 10000.0F));
//lastqBar = qbar; // JB 010301 FF would cut out < 250
}
lastqBar = qbar; // JB 010301 FF would cut out < 250
}
else
{
if (fabs (qbar - lastqBar) > 5.0F)
if ( not g_bFFCenterFix) //Wombat778 9-29-2003 Allows user to have the fixed centering force for FF sticks
JoystickPlayEffect (JoyAutoCenter, 10000);
lastqBar = qbar;
}
}
}*/
//Wombat778 12-02-2003 redid this section to be tighter. Also, this should fix centering properly. g_bFFCenterFix now means that a constant instead of variable FF force is used
if (platform == SimDriver.GetPlayerAircraft())
{
if ((fabs(qbar - lastqBar) > 5.0F) or not lastqBar)
{
if ((qbar > 250) or g_bFFCenterFix)
{
JoystickPlayEffect(JoyAutoCenter, 10000);
}
else
{
JoystickPlayEffect(JoyAutoCenter, FloatToInt32((qbar / 250.0F * 0.5F + 0.5F) * 10000.0F));
}
lastqBar = qbar;
}
}
}
float AirframeClass::CalcTASfromCAS(float cas)
{
float ttheta, rsigma;
float sound, pdelta, desMach;
pdelta = CalcPressureRatio(-z, &ttheta, &rsigma);
desMach = CalcMach(cas, pdelta);
sound = (float)sqrt(ttheta) * AASL;
return desMach * sound * 3600.0F / 6080.0F;
}
float AirframeClass::CalcMach(float GetKias, float press_ratio)
{
float a0 = 661.4785F;
float kiasa, qcp0, qcpa;
float u, fu, fpu;
kiasa = GetKias / a0;
qcp0 = (float)pow((1.0 + 0.2 * kiasa * kiasa), 3.5) - 1.0F;
if (kiasa >= 1.0)
qcp0 = 166.921F * (float)pow(kiasa, 7.0F) / (float)pow((7.0F * kiasa * kiasa - 1.0F), 2.5F) - 1.0F;
qcpa = qcp0 / press_ratio;
if (qcpa >= 0.892929F)
{
u = 2.0F;
do
{
fu = 166.921F * (float)pow(u, 7.0F) / (float)pow((7.0F * u * u - 1.0F), 2.5F) - (1.0F + qcpa);
fpu = 7.0F * 166.921F * (float)pow(u, 6.0F) * (2.0F * u * u - 1.0F) / (float)pow((7.0F * u * u - 1.0F), 3.5F);
u -= fu / fpu;
}
while (fabs(fu) > 0.001F);
return (u);
}
else
{
return ((float)sqrt((pow((qcpa + 1.0F), (1.0F / 3.5F)) - 1.0F) / 0.2F));
}
}
float AirframeClass::CalcPressureRatio(float alt, float* ttheta, float* rsigma)
{
/*-----------------------------------------------*/
/* calculate temperature ratio and density ratio */
/*-----------------------------------------------*/
if (alt <= tropoAlt)
{
*ttheta = 1.0F - 0.000006875F * alt;
*rsigma = (float)pow(*ttheta, 4.255876F);
}
else if (alt < tropoAlt2)
{
*ttheta = 0.751865F;
*rsigma = 0.297076F * (float)exp(0.00004806 * (tropoAlt - alt));
}
else
{
*ttheta = 0.682457f + alt / 945374.0f;
*rsigma = (float)pow(0.978261 + alt / 659515.0, -35.16319);
}
return (*ttheta) * (*rsigma);
}
// sort of atmospheric
float AirframeClass::EngineSmokeFactor()
{
switch (auxaeroData->engineSmokes)
{
default:
return 2;
case 1: // vortex
case 0: // nothing
return 1;
case 2: // light smoke
return 2;
case 3:
return 4;
}
}
int AirframeClass::EngineTrail()
{
switch (auxaeroData->engineSmokes)
{
case 0: // nothing
return -1;
case 1: // vortex
return TRAIL_VORTEX;
case 2: // light smoke
return TRAIL_SMOKE;
case 3:
return TRAIL_DARKSMOKE;
default:
/*if (auxaeroData->engineSmokes > 3 and auxaeroData->engineSmokes - 3 < TRAIL_MAX)
return auxaeroData->engineSmokes - 3;*/
if (auxaeroData->engineSmokes > 3)
return auxaeroData->engineSmokes;//Cobra Allow for more engine trails
else return -1;
}
}
| 35.479452
| 207
| 0.415444
|
Terebinth
|
c815d1e6895510162db703d82cf0f2cf848efa33
| 3,661
|
cpp
|
C++
|
Worms/src/InGame/Entity/World/World.cpp
|
GearEngine/GearEngine
|
fa5ed49ca6289a215799a7b84ece1241eb33bd36
|
[
"Apache-2.0"
] | 3
|
2020-03-05T06:56:51.000Z
|
2020-03-12T09:36:20.000Z
|
Worms/src/InGame/Entity/World/World.cpp
|
GearEngine/GearEngine
|
fa5ed49ca6289a215799a7b84ece1241eb33bd36
|
[
"Apache-2.0"
] | 2
|
2020-03-05T15:40:28.000Z
|
2020-03-11T16:04:44.000Z
|
Worms/src/InGame/Entity/World/World.cpp
|
GearEngine/GearEngine
|
fa5ed49ca6289a215799a7b84ece1241eb33bd36
|
[
"Apache-2.0"
] | null | null | null |
#include "wmpch.h"
#include "World.h"
namespace InGame {
float World::s_LimitTurnTime = 0;
int World::s_LimitSuddenDeathTurn = 0;
int World::s_CurrentTurn = 0;
World::World(const InitiateData& initData)
{
s_LimitSuddenDeathTurn = initData.LimitSuddenDeathTurn;
s_LimitTurnTime = initData.LimitTurnTime;
s_CurrentTurn = 0;
//Create Entity
m_ID = Gear::EntitySystem::CreateEntity(true, "World");
//Attach Component
Gear::EntitySystem::AttachComponent(m_ID, {
Gear::ComponentID::FSM, Gear::ComponentID::Status, Gear::ComponentID::Timer,
Gear::ComponentID::LateDrawer
});
//Set Component specific
Gear::EntitySystem::SetFSM(m_ID, {
{ WorldState::InGameStart, new InGemeStartHandler }, { WorldState::OnStart, new WorldOnStartHandler },
{ WorldState::OnPrepareRun, new WorldOnPrepareRunHandler }, { WorldState::OnRunning, new WorldOnRunningHandler},
{ WorldState::OnQuitWindow, new WorldOnQuitWindowHandler}, {WorldState::OnWaiting, new WorldOnWaitingHandler },
{ WorldState::OnGameVictory, new WorldOnVictoryHandler }, { WorldState::OnGameDraw, new WorldOnDrawHandler },
{WorldState::OnGameEnd, new WorldOnGameEndHandler }
});
Gear::EntitySystem::GetFSM(m_ID)->SetCurrentState(WorldState::InGameStart);
Gear::EntitySystem::SetStatus(m_ID, {
{ WorldInfo::CurrentWormName, std::string("") }, { WorldInfo::CurrentWormID, -1},
{ WorldInfo::DyeInfo, std::stack<int>()},
{ WorldInfo::CurrnetTeam, std::string("") }, { WorldInfo::CurrentTeamColor, TeamColor::Blue },
{ WorldInfo::TeamInfo, initData.Teams }, { WorldInfo::TeamInfoBlink, false }
});
Gear::EntitySystem::SetStatusHanlder(m_ID, {
{ WorldStatusHandleType::DisplayWaitingCount, Gear::CreateRef<WorldDisplayWaitingCountHandler>() },
{ WorldStatusHandleType::DisplayTeamInfo, Gear::CreateRef<WorldDisplayTeamInfoHandler>() },
{ WorldStatusHandleType::DisplayMassage, Gear::CreateRef<WorldDisplayMasageHandler>() },
});
auto status = Gear::EntitySystem::GetStatus(m_ID);
status->PushNeedHandleData(WorldStatusHandleType::DisplayTeamInfo,
Gear::Status::StatHandleData(WorldTeamInfoDenoteData(Gear::TextureStorage::GetTexture2D("WormNameBorder"))));
auto lateDrawer = Gear::EntitySystem::GetLateDrawer(m_ID);
glm::mat4 fogTranslate = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, 1.0f)) * glm::scale(glm::mat4(1.0f), glm::vec3(1000.0f, 1000.0f, 1.0f));
lateDrawer->UpLoadDrawStuff("Fog", Gear::LateDrawer::QuardStuff(fogTranslate, glm::vec4(0.0f, 0.0f, 0.001f, 1.0f)));
//Subscpribe EventChannel
//Gear::EventSystem::SubscribeChannel(m_ID, EventChannel::MouseClick);
Gear::EventSystem::SubscribeChannel(m_ID, EventChannel::World);
Gear::EventSystem::RegisterEventHandler(m_ID, EventChannel::World, Gear::CreateRef<WorldEventHandler>());
bgms.push_back("ingame-01-generic");
bgms.push_back("ingame-02-cavern");
bgms.push_back("ingame-03-jungle");
bgms.push_back("ingame-04-battlezone");
bgms.push_back("ingame-05-forest");
bgms.push_back("ingame-06-weird-alien-plan");
bgms.push_back("ingame-07-outerspace");
bgms.push_back("ingame-08-desert");
bgms.push_back("ingame-09-hell");
bgms.push_back("ingame-10-mech-workshop");
bgms.push_back("ingame-11-rain&surf");
}
World::~World()
{
Gear::EventSystem::UnSubscribeChannel(m_ID, EventChannel::MouseClick);
Gear::EntitySystem::DeleteEntity(m_ID);
}
void World::Update(Gear::Timestep ts)
{
if (!IS_PLAYING_SOUND(WormsSound::bgm) && !IS_PLAYING_SOUND(WormsSound::Hos))
{
PLAY_SOUND_NAME(bgms[Gear::Util::GetRndInt(11)], WormsSound::bgm);
Gear::SoundSystem::Get()->SetVolue(WormsSound::bgm, 0.5f);
}
}
}
| 40.677778
| 153
| 0.734772
|
GearEngine
|
c81825bda8ba08b264adf5b80f6e9a3c5fe6a9d4
| 8,739
|
cpp
|
C++
|
src/mfx/pi/nzbl/FilterBank.cpp
|
mikelange49/pedalevite
|
a81bd8a6119c5920995ec91b9f70e11e9379580e
|
[
"WTFPL"
] | null | null | null |
src/mfx/pi/nzbl/FilterBank.cpp
|
mikelange49/pedalevite
|
a81bd8a6119c5920995ec91b9f70e11e9379580e
|
[
"WTFPL"
] | null | null | null |
src/mfx/pi/nzbl/FilterBank.cpp
|
mikelange49/pedalevite
|
a81bd8a6119c5920995ec91b9f70e11e9379580e
|
[
"WTFPL"
] | null | null | null |
/*****************************************************************************
FilterBank.cpp
Author: Laurent de Soras, 2017
--- Legal stuff ---
This program is free software. It comes without any warranty, to
the extent permitted by applicable law. You can redistribute it
and/or modify it under the terms of the Do What The Fuck You Want
To Public License, Version 2, as published by Sam Hocevar. See
http://sam.zoy.org/wtfpl/COPYING for more details.
*Tab=3***********************************************************************/
#if defined (_MSC_VER)
#pragma warning (1 : 4130 4223 4705 4706)
#pragma warning (4 : 4355 4786 4800)
#endif
/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
#include "fstb/def.h"
#include "mfx/dsp/iir/DesignEq2p.h"
#include "mfx/dsp/iir/TransSZBilin.h"
#include "mfx/dsp/mix/Fpu.h"
#include "mfx/pi/nzbl/FilterBank.h"
#include <algorithm>
#include <cassert>
#include <cmath>
namespace mfx
{
namespace pi
{
namespace nzbl
{
/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
// Does not compute the latency if latency < 0 as input
void FilterBank::reset (double sample_freq, int max_buf_len, double &latency)
{
assert (sample_freq > 0);
assert (max_buf_len > 0);
fstb::unused (max_buf_len);
const bool lat_flag = (latency >= 0);
latency = 0;
_sample_freq = float ( sample_freq);
_inv_fs = float (1 / sample_freq);
for (int band_cnt = 0; band_cnt < _nbr_bands; ++band_cnt)
{
Band & band = _band_arr [band_cnt];
band._env.set_sample_freq (sample_freq);
// Computes the envelope times.
// For the lowest band, we use 30 Hz as reference to make sure that the
// lowest frequencies are not distorded. Consequently, the gate will be
// slow to react. But low frequency rumble is generally steady (it comes
// from the power supply) therefore this is not a problem.
float f = 30;
if (band_cnt > 0)
{
f = compute_split_freq (band_cnt - 1);
}
const int mult = 16;
float t = float (mult / (2 * fstb::PI)) / f;
// Longer release helps preventing amplitude modulation on periodic
// noise bursts
const float min_at = 0.005f;
const float min_rt = 0.050f;
const float at = std::max (t, min_at);
const float rt = std::max (t, min_rt);
band._env.set_times (at, rt);
}
constexpr float k = 0.65f; // Thiele coefficient
const float alpha = float (sqrt (2 * (1 - k * k)));
static const float as [3] = { 1, alpha, 1 }; // Shared poles
static const float bls [_nbr_stages] [3] = { { 1, 0, 0 }, { 1, 0, k } };
static const float bhs [_nbr_stages] [3] = { { 0, 0, 1 }, { k, 0, 1 } };
for (int split_cnt = 0; split_cnt < _nbr_split; ++split_cnt)
{
Split & split = _split_arr [split_cnt];
const float f0 = compute_split_freq (split_cnt);
const float kf =
mfx::dsp::iir::TransSZBilin::compute_k_approx (f0 * _inv_fs);
for (int stage = 0; stage < _nbr_stages; ++stage)
{
float bz [3];
float az [3];
// LP
mfx::dsp::iir::TransSZBilin::map_s_to_z_approx (
bz, az, bls [stage], as, kf
);
split._lpf [stage].set_z_eq (bz, az);
split._fix [stage].set_z_eq (bz, az);
// HP
mfx::dsp::iir::TransSZBilin::map_s_to_z_approx (
bz, az, bhs [stage], as, kf
);
split._hpf [stage].set_z_eq (bz, az);
// Evaluates the group delay
if (lat_flag)
{
// Base frequency for latency evaluation. Hz
constexpr double f_lat = 700;
// Uses the HPs or LPs depending on the tested frequency
if (f0 < f_lat)
{
split._hpf [stage].get_z_eq (bz, az);
}
else
{
split._lpf [stage].get_z_eq (bz, az);
}
az [0] = 1;
const double gd = mfx::dsp::iir::DesignEq2p::compute_group_delay (
bz, az, sample_freq, f_lat
);
latency += gd;
}
}
}
clear_buffers ();
}
// thr is a linear value
void FilterBank::set_threshold (int band_idx, float thr)
{
assert (band_idx >= 0);
assert (band_idx < _nbr_bands);
assert (thr >= 0);
_band_arr [band_idx]._thr = thr;
}
// Can work in-place
void FilterBank::process_block (float dst_ptr [], const float src_ptr [], int nbr_spl)
{
assert (_sample_freq > 0);
assert (dst_ptr != nullptr);
assert (src_ptr != nullptr);
assert (nbr_spl > 0);
assert (nbr_spl <= _max_blk_size);
// Splits the signal in several bands
for (int split_idx = 0; split_idx < _nbr_split; ++split_idx)
{
Split & split = _split_arr [split_idx];
// The lower part goes to the current band, and the higher part
// propagates to the next band
float * lo_ptr = _band_arr [split_idx ]._buf.data ();
float * hi_ptr = _band_arr [split_idx + 1]._buf.data ();
split._hpf [0].process_block (hi_ptr, src_ptr, nbr_spl);
split._hpf [1].process_block (hi_ptr, hi_ptr, nbr_spl);
split._lpf [0].process_block (lo_ptr, src_ptr, nbr_spl);
split._lpf [1].process_block (lo_ptr, lo_ptr, nbr_spl);
// Next bands will be filtered in-place.
src_ptr = hi_ptr;
}
// Band processing
// Divides the current block in almost equal sub-blocks, fitting in
// the maximum processing length.
const int nbr_sub_blocks = (nbr_spl + _dspl_rate - 1) >> _dspl_rate_l2;
const int sub_block_len = (nbr_spl + nbr_sub_blocks - 1) / nbr_sub_blocks;
for (int band_cnt = 0; band_cnt < _nbr_bands; ++band_cnt)
{
process_band (band_cnt, nbr_spl, sub_block_len);
}
// Band merging
for (int split_idx = 1; split_idx < _nbr_split; ++split_idx)
{
Split & split = _split_arr [split_idx];
float * prv_ptr = _band_arr [split_idx - 1]._buf.data ();
float * cur_ptr = _band_arr [split_idx ]._buf.data ();
split._fix [0].process_block (prv_ptr, prv_ptr, nbr_spl);
split._fix [1].process_block (prv_ptr, prv_ptr, nbr_spl);
mfx::dsp::mix::Fpu::mix_1_1 (cur_ptr, prv_ptr, nbr_spl);
}
// The last two bands don't need compensation processing
mfx::dsp::mix::Fpu::copy_2_1 (
dst_ptr,
_band_arr [_nbr_bands - 2]._buf.data (),
_band_arr [_nbr_bands - 1]._buf.data (),
nbr_spl
);
}
void FilterBank::clear_buffers ()
{
for (int split_cnt = 0; split_cnt < _nbr_split; ++split_cnt)
{
Split & split = _split_arr [split_cnt];
for (int stage = 0; stage < _nbr_stages; ++stage)
{
split._lpf [stage].clear_buffers ();
split._hpf [stage].clear_buffers ();
split._fix [stage].clear_buffers ();
}
}
for (int band_cnt = 0; band_cnt < _nbr_bands; ++band_cnt)
{
Band & band = _band_arr [band_cnt];
band._env.clear_buffers ();
}
}
/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
/*
Other possible formula for the gain shape:
x = (limit (env / thr, 1, _thr_hi_rel) - 1) / (_thr_hi_rel - 1)
g = 0.5 * ((1 - (1 - x) ^ 8) ^ 2 + (1 - (1 - x) ^ 3) ^ 2)
No div, but 1 / thr must be precalculated too
*/
void FilterBank::process_band (int band_idx, int nbr_spl, int sub_block_len)
{
assert (band_idx >= 0);
assert (band_idx < _nbr_bands);
assert (nbr_spl > 0);
assert (nbr_spl <= _max_blk_size);
assert (sub_block_len > 0);
assert (sub_block_len <= nbr_spl);
Band & band = _band_arr [band_idx];
if (band._thr >= 1e-9f)
{
float * buf_ptr = band._buf.data ();
const float thr = band._thr;
int block_pos = 0;
do
{
float * buf2_ptr = buf_ptr + block_pos;
const int block_len = std::min (nbr_spl - block_pos, sub_block_len);
const float blen_inv = fstb::rcp_uint <float> (block_len);
// Downsamples input^2 by averaging
float sum = 0;
for (int pos = 0; pos < block_len; ++pos)
{
const auto x = buf2_ptr [pos];
sum += x * x;
}
const float avg = sum * blen_inv;
const float e2 = band._env.analyse_block_raw_cst (avg, block_len);
const float env = sqrtf (e2);
// g0 = thr / max (env, thr)
const float g0 = thr / std::max (env, thr);
// gain = (1 - max ((_thr_hi_rel * g0 - 1) / (_thr_hi_rel - 1), 0)) ^ 4
float g = (_thr_hi_rel * g0 - 1) * _mul_thr_hi;
g = fstb::ipowpc <4> (1 - std::max (g, 0.f));
// Volume
mfx::dsp::mix::Fpu::scale_1_vlr (buf2_ptr, block_len, band._g_old, g);
// Next sub-block
band._g_old = g;
block_pos += block_len;
}
while (block_pos < nbr_spl);
}
}
constexpr float FilterBank::compute_split_freq (int split_idx)
{
return float (125 << split_idx);
}
} // namespace nzbl
} // namespace pi
} // namespace mfx
/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
| 26.164671
| 86
| 0.594347
|
mikelange49
|
c8182c8564f7b2f7088cae92ac19ea7d58a7bc76
| 10,958
|
cc
|
C++
|
tensorflow/core/kernels/sparse_concat_op_gpu.cu.cc
|
EricRemmerswaal/tensorflow
|
141ff27877579c81a213fa113bd1b474c1749aca
|
[
"Apache-2.0"
] | 190,993
|
2015-11-09T13:17:30.000Z
|
2022-03-31T23:05:27.000Z
|
tensorflow/core/kernels/sparse_concat_op_gpu.cu.cc
|
EricRemmerswaal/tensorflow
|
141ff27877579c81a213fa113bd1b474c1749aca
|
[
"Apache-2.0"
] | 48,461
|
2015-11-09T14:21:11.000Z
|
2022-03-31T23:17:33.000Z
|
tensorflow/core/kernels/sparse_concat_op_gpu.cu.cc
|
EricRemmerswaal/tensorflow
|
141ff27877579c81a213fa113bd1b474c1749aca
|
[
"Apache-2.0"
] | 104,981
|
2015-11-09T13:40:17.000Z
|
2022-03-31T19:51:54.000Z
|
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#define EIGEN_USE_GPU
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/kernels/gpu_device_array.h"
#include "tensorflow/core/kernels/gpu_device_array_gpu.h"
#include "tensorflow/core/kernels/gpu_prim_helpers.h"
#include "tensorflow/core/kernels/sparse_concat_op.h"
#include "tensorflow/core/lib/core/bits.h"
#include "tensorflow/core/util/gpu_kernel_helper.h"
namespace tensorflow {
typedef Eigen::GpuDevice GPUDevice;
namespace functor {
namespace {
template <typename T>
__global__ void SparseConcatKernel(
int64 output_nnz, int rank, int concat_dim, bool need_to_sort,
GpuDeviceArrayStruct<const int64*> ind_ptrs_data,
GpuDeviceArrayStruct<const T*> val_ptrs_data,
GpuDeviceArrayStruct<int64_t> nnz_scan_data,
GpuDeviceArrayStruct<int64_t> concat_size_scan_data,
GpuDeviceArrayStruct<int64_t> output_shape_data,
int64* __restrict__ output_inds, T* __restrict__ output_vals,
int64* __restrict__ output_flat_inds) {
const int64* __restrict__* __restrict__ ind_ptrs =
GetGpuDeviceArrayOnDevice(&ind_ptrs_data);
const T* __restrict__* __restrict__ val_ptrs =
GetGpuDeviceArrayOnDevice(&val_ptrs_data);
const int64* __restrict__ nnz_scan =
GetGpuDeviceArrayOnDevice(&nnz_scan_data);
const int64* __restrict__ concat_size_scan =
GetGpuDeviceArrayOnDevice(&concat_size_scan_data);
const int64* __restrict__ output_shape =
GetGpuDeviceArrayOnDevice(&output_shape_data);
const int64 num_inputs = ind_ptrs_data.size;
for (int64 nz : GpuGridRangeX<int64_t>(output_nnz)) {
const int64 input_num =
gpu_helper::upper_bound<int64_t>(nnz_scan, num_inputs, nz) - 1;
const int64 input_nz = nz - nnz_scan[input_num];
const int64 ind_offset = concat_size_scan[input_num];
if (!need_to_sort) {
output_vals[nz] = val_ptrs[input_num][input_nz];
}
int64 flat_ind = 0;
for (int j = 0; j < rank; ++j) {
const int64 output_ind = ind_ptrs[input_num][input_nz * rank + j] +
(j == concat_dim ? ind_offset : 0);
if (!need_to_sort) {
output_inds[nz * rank + j] = output_ind;
} else {
flat_ind = flat_ind * output_shape[j] + output_ind;
output_flat_inds[nz] = flat_ind;
}
}
}
}
template <typename T>
__global__ void SparseConcatPermuteKernel(
int64 output_nnz, int rank, GpuDeviceArrayStruct<const T*> val_ptrs_data,
GpuDeviceArrayStruct<int64_t> nnz_scan_data,
GpuDeviceArrayStruct<int64_t> output_shape_data,
const int64* __restrict__ output_flat_inds,
const int64* __restrict__ permutation, int64* __restrict__ output_inds,
T* __restrict__ output_vals) {
const T* __restrict__* __restrict__ val_ptrs =
GetGpuDeviceArrayOnDevice(&val_ptrs_data);
const int64* __restrict__ nnz_scan =
GetGpuDeviceArrayOnDevice(&nnz_scan_data);
const int64* __restrict__ output_shape =
GetGpuDeviceArrayOnDevice(&output_shape_data);
const int64 num_inputs = val_ptrs_data.size;
for (int64 nz : GpuGridRangeX<int64_t>(output_nnz)) {
const int64 permuted_nz = permutation[nz];
const int64 input_num =
gpu_helper::upper_bound<int64_t>(nnz_scan, num_inputs, permuted_nz) - 1;
const int64 input_nz = permuted_nz - nnz_scan[input_num];
output_vals[nz] = val_ptrs[input_num][input_nz];
int64 output_flat_ind = output_flat_inds[permuted_nz];
for (int j = rank - 1; j >= 0; --j) {
const int64 output_dim_size = output_shape[j];
output_inds[nz * rank + j] = output_flat_ind % output_dim_size;
output_flat_ind /= output_dim_size;
}
}
}
} // namespace
template <typename T>
struct SparseConcatFunctor<GPUDevice, T> {
void operator()(OpKernelContext* context, const OpInputList& inds,
const OpInputList& vals, const OpInputList& shapes,
int concat_dim) {
const int N = inds.size();
const TensorShape input_shape0(shapes[0].vec<int64_t>());
const int rank = input_shape0.dims();
// The input non-zeros are assumed to be sorted by increasing dimension
// number (i.e., row-major order), so if the concatenation is along the
// first dimension then they remain in order and we can directly compute the
// output indices and values. To concatenate along other dimensions, we
// first compute the flattened (1D) row-major output indices, then sort
// these to obtain the required permutation, and finally gather the permuted
// input values.
GpuDeviceArrayOnHost<const int64*> ind_ptrs(context, N);
GpuDeviceArrayOnHost<const T*> val_ptrs(context, N);
GpuDeviceArrayOnHost<int64_t> nnz_scan(context, N + 1);
GpuDeviceArrayOnHost<int64_t> concat_size_scan(context, N + 1);
OP_REQUIRES_OK(context, ind_ptrs.Init());
OP_REQUIRES_OK(context, val_ptrs.Init());
OP_REQUIRES_OK(context, nnz_scan.Init());
OP_REQUIRES_OK(context, concat_size_scan.Init());
int64 nnz_sum = 0;
int64 concat_size_sum = 0;
nnz_scan.Set(0, nnz_sum);
concat_size_scan.Set(0, concat_size_sum);
for (int i = 0; i < N; ++i) {
ind_ptrs.Set(i, inds[i].matrix<int64_t>().data());
val_ptrs.Set(i, vals[i].vec<T>().data());
nnz_sum += inds[i].dim_size(0);
nnz_scan.Set(i + 1, nnz_sum);
const TensorShape current_shape(shapes[i].vec<int64_t>());
concat_size_sum += current_shape.dim_size(concat_dim);
concat_size_scan.Set(i + 1, concat_size_sum);
}
OP_REQUIRES_OK(context, ind_ptrs.Finalize());
OP_REQUIRES_OK(context, val_ptrs.Finalize());
OP_REQUIRES_OK(context, nnz_scan.Finalize());
OP_REQUIRES_OK(context, concat_size_scan.Finalize());
const int64 output_nnz = nnz_sum;
const int64 output_concat_size = concat_size_sum;
const bool need_to_sort = concat_dim != 0;
GpuDeviceArrayOnHost<int64_t> output_shape(context, rank);
int64 output_dense_elements;
if (need_to_sort) {
OP_REQUIRES_OK(context, output_shape.Init());
output_dense_elements = 1;
for (int j = 0; j < rank; ++j) {
int64 output_dim_size =
j == concat_dim ? output_concat_size : input_shape0.dim_size(j);
output_shape.Set(j, output_dim_size);
output_dense_elements *= output_dim_size;
}
OP_REQUIRES_OK(context, output_shape.Finalize());
}
int64* output_inds_ptr = nullptr;
T* output_vals_ptr = nullptr;
int64* output_flat_inds_ptr = nullptr;
Tensor output_flat_inds;
if (need_to_sort) {
// SparseConcatKernel will (only) produce output_flat_inds.
OP_REQUIRES_OK(context,
context->allocate_temp(DT_INT64, TensorShape({output_nnz}),
&output_flat_inds));
output_flat_inds_ptr = output_flat_inds.vec<int64_t>().data();
} else {
OP_REQUIRES_OK(
context, allocate_outputs(context, rank, output_nnz, &output_inds_ptr,
&output_vals_ptr));
}
const GPUDevice& device = context->eigen_gpu_device();
GpuLaunchConfig config = GetGpuLaunchConfig(
output_nnz, device, &SparseConcatKernel<T>,
/*dynamic_shared_memory_size=*/0, /*block_size_limit=*/0);
OP_REQUIRES_OK(
context, GpuLaunchKernel(
SparseConcatKernel<T>, config.block_count,
config.thread_per_block, 0, device.stream(), output_nnz,
rank, concat_dim, need_to_sort, ind_ptrs.data(),
val_ptrs.data(), nnz_scan.data(), concat_size_scan.data(),
(need_to_sort ? output_shape.data()
: GpuDeviceArrayStruct<int64_t>()),
output_inds_ptr, output_vals_ptr, output_flat_inds_ptr));
if (!need_to_sort) return;
OP_REQUIRES_OK(context,
allocate_outputs(context, rank, output_nnz, &output_inds_ptr,
&output_vals_ptr));
Tensor permutation;
OP_REQUIRES_OK(context,
context->allocate_temp(DT_INT64, TensorShape({output_nnz}),
&permutation));
int64* permutation_ptr = permutation.vec<int64_t>().data();
OP_REQUIRES_OK(
context,
GpuRadixSort(context, /*size=*/output_nnz,
/*keys_in=*/output_flat_inds_ptr,
/*keys_out=*/static_cast<int64*>(nullptr),
/*indices_in=*/static_cast<const int64*>(nullptr),
/*indices_out=*/permutation_ptr,
/*num_bits=*/Log2Ceiling64(output_dense_elements)));
config = GetGpuLaunchConfig(
output_nnz, device, &SparseConcatPermuteKernel<T>,
/*dynamic_shared_memory_size=*/0, /*block_size_limit=*/0);
OP_REQUIRES_OK(
context,
GpuLaunchKernel(SparseConcatPermuteKernel<T>, config.block_count,
config.thread_per_block, 0, device.stream(), output_nnz,
rank, val_ptrs.data(), nnz_scan.data(),
output_shape.data(), output_flat_inds_ptr,
permutation_ptr, output_inds_ptr, output_vals_ptr));
}
private:
Status allocate_outputs(OpKernelContext* context, int rank, int64 output_nnz,
int64** output_inds_ptr, T** output_vals_ptr) const {
Tensor* output_inds = nullptr;
TF_RETURN_IF_ERROR(context->allocate_output(
0, TensorShape({output_nnz, rank}), &output_inds));
*output_inds_ptr = output_inds->matrix<int64_t>().data();
Tensor* output_vals = nullptr;
TF_RETURN_IF_ERROR(
context->allocate_output(1, TensorShape({output_nnz}), &output_vals));
*output_vals_ptr = output_vals->vec<T>().data();
return Status::OK();
}
};
#define DEFINE_SPARSE_CONCAT_FUNCTOR(T) \
template struct SparseConcatFunctor<GPUDevice, T>;
TF_CALL_POD_TYPES(DEFINE_SPARSE_CONCAT_FUNCTOR);
#undef DEFINE_SPARSE_CONCAT_FUNCTOR
} // namespace functor
} // namespace tensorflow
#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM
| 41.195489
| 80
| 0.68069
|
EricRemmerswaal
|
c81a8400836f894b503597b48b8c795fc7afccd0
| 36,032
|
cxx
|
C++
|
PWGCF/FEMTOSCOPY/AliFemtoUser/AliFemtoESDTrackCut.cxx
|
Tingchenxi/AliPhysics
|
16ea676341c0d417efa849673baa54bed717cd54
|
[
"BSD-3-Clause"
] | null | null | null |
PWGCF/FEMTOSCOPY/AliFemtoUser/AliFemtoESDTrackCut.cxx
|
Tingchenxi/AliPhysics
|
16ea676341c0d417efa849673baa54bed717cd54
|
[
"BSD-3-Clause"
] | null | null | null |
PWGCF/FEMTOSCOPY/AliFemtoUser/AliFemtoESDTrackCut.cxx
|
Tingchenxi/AliPhysics
|
16ea676341c0d417efa849673baa54bed717cd54
|
[
"BSD-3-Clause"
] | 1
|
2018-09-22T01:09:25.000Z
|
2018-09-22T01:09:25.000Z
|
/*
***************************************************************************
*
* $Id$
*
*
***************************************************************************
*
*
*
*
***************************************************************************
*
* $Log$
* Revision 1.3 2007/05/22 09:01:42 akisiel
* Add the possibiloity to save cut settings in the ROOT file
*
* Revision 1.2 2007/05/21 10:38:25 akisiel
* More coding rule conformance
*
* Revision 1.1 2007/05/16 10:25:06 akisiel
* Making the directory structure of AliFemtoUser flat. All files go into one common directory
*
* Revision 1.4 2007/05/03 09:46:10 akisiel
* Fixing Effective C++ warnings
*
* Revision 1.3 2007/04/27 07:25:59 akisiel
* Make revisions needed for compilation from the main AliRoot tree
*
* Revision 1.1.1.1 2007/04/25 15:38:41 panos
* Importing the HBT code dir
*
* Revision 1.4 2007-04-03 16:00:08 mchojnacki
* Changes to iprove memory managing
*
* Revision 1.3 2007/03/13 15:30:03 mchojnacki
* adding reader for simulated data
*
* Revision 1.2 2007/03/08 14:58:03 mchojnacki
* adding some alice stuff
*
* Revision 1.1.1.1 2007/03/07 10:14:49 mchojnacki
* First version on CVS
*
**************************************************************************/
#include "AliFemtoESDTrackCut.h"
#include <cstdio>
#ifdef __ROOT__
/// \cond CLASSIMP
ClassImp(AliFemtoESDTrackCut);
/// \endcond
#endif
// electron
// 0.13 - 1.8
// 0 7.594129e-02 8.256141e-03
// 1 -5.535827e-01 8.170825e-02
// 2 1.728591e+00 3.104210e-01
// 3 -2.827893e+00 5.827802e-01
// 4 2.503553e+00 5.736207e-01
// 5 -1.125965e+00 2.821170e-01
// 6 2.009036e-01 5.438876e-02
// pion
// 0.13 - 2.0
// 0 1.063457e+00 8.872043e-03
// 1 -4.222208e-01 2.534402e-02
// 2 1.042004e-01 1.503945e-02
// kaon
// 0.18 - 2.0
// 0 -7.289406e-02 1.686074e-03
// 1 4.415666e-01 1.143939e-02
// 2 -2.996790e-01 1.840964e-02
// 3 6.704652e-02 7.783990e-03
// proton
// 0.26 - 2.0
// 0 -3.730200e-02 2.347311e-03
// 1 1.163684e-01 1.319316e-02
// 2 8.354116e-02 1.997948e-02
// 3 -4.608098e-02 8.336400e-03
AliFemtoESDTrackCut::AliFemtoESDTrackCut():
fCharge(0), // takes both charges 0
fLabel(false),
fStatus(0),
fPIDMethod(knSigma),
fNsigmaTPCTOF(kFALSE),
fNsigmaTPConly(kFALSE),
fNsigma(3.),
fminTPCclsF(0),
fminTPCncls(0),
fminITScls(0),
fMaxITSchiNdof(1000.0),
fMaxTPCchiNdof(1000.0),
fMaxSigmaToVertex(1000.0),
fNTracksPassed(0),
fNTracksFailed(0),
fRemoveKinks(kFALSE),
fRemoveITSFake(kFALSE),
fMostProbable(0),
fMaxImpactXY(1000.0),
fMinImpactXY(-1000.0),
fMaxImpactZ(1000.0),
fMaxImpactXYPtOff(1000.0),
fMaxImpactXYPtNrm(1000.0),
fMaxImpactXYPtPow(1000.0),
fMinPforTOFpid(0.0),
fMaxPforTOFpid(10000.0),
fMinPforTPCpid(0.0),
fMaxPforTPCpid(10000.0),
fMinPforITSpid(0.0),
fMaxPforITSpid(10000.0),
fElectronRejection(0)
{
// Default constructor
fPt[0]=0.0; fPt[1] = 100.0;//100
fRapidity[0]=-2; fRapidity[1]=2;//-2 2
fEta[0]=-2; fEta[1]=2;//-2 2
// all Probabilities range from [-1.0, 2.0]
fPidProbElectron[0] = fPidProbPion[0] = fPidProbKaon[0] = fPidProbProton[0] = fPidProbMuon[0]=-1.0;
fPidProbElectron[1] = fPidProbPion[1] = fPidProbKaon[1] = fPidProbProton[1] = fPidProbMuon[1]=2.0;
for (Int_t i = 0; i < 3; i++)
fCutClusterRequirementITS[i] = AliESDtrackCuts::kOff;
}
//------------------------------
AliFemtoESDTrackCut::~AliFemtoESDTrackCut()
{
/* noop */
}
//------------------------------
bool AliFemtoESDTrackCut::Pass(const AliFemtoTrack* track)
{
//cout<<"AliFemtoESDTrackCut::Pass"<<endl;
// test the particle and return
// true if it meets all the criteria
// false if it doesn't meet at least one of the criteria
float tMost[5];
if (fStatus && (track->Flags() & fStatus) != fStatus) {
return false;
}
if (fRemoveKinks && (track->KinkIndex(0) || track->KinkIndex(1) || track->KinkIndex(2))) {
return false;
}
if (fRemoveITSFake && track->ITSncls() < 0) {
return false;
}
if (fminTPCclsF > track->TPCnclsF()) {
return false;
}
if (fminTPCncls > track->TPCncls()) {
return false;
}
if (fminITScls > track->ITSncls()) {
return false;
}
if (fMaxImpactXY < TMath::Abs(track->ImpactD())) {
return false;
}
if (fMinImpactXY > TMath::Abs(track->ImpactD())) {
return false;
}
if (fMaxImpactZ < TMath::Abs(track->ImpactZ())) {
return false;
}
if (fMaxSigmaToVertex < track->SigmaToVertex()) {
return false;
}
if (track->ITSncls() > 0 && (track->ITSchi2() / track->ITSncls()) > fMaxITSchiNdof) {
return false;
}
if (track->TPCncls() > 0 && (track->TPCchi2() / track->TPCncls()) > fMaxTPCchiNdof) {
return false;
}
// ITS cluster requirenments
for (Int_t i = 0; i < 3; i++) {
if (!CheckITSClusterRequirement(fCutClusterRequirementITS[i], track->HasPointOnITSLayer(i * 2), track->HasPointOnITSLayer(i*2+1))) {
return false;
}
}
if (fLabel) {
if (track->Label() < 0) {
fNTracksFailed++;
return false;
}
}
if (fCharge != 0 && (track->Charge() != fCharge)) {
fNTracksFailed++;
return false;
}
Bool_t tTPCPidIn = (track->Flags() & AliFemtoTrack::kTPCpid) > 0;
Bool_t tITSPidIn = (track->Flags() & AliFemtoTrack::kITSpid) > 0;
Bool_t tTOFPidIn = (track->Flags() & AliFemtoTrack::kTOFpid) > 0;
const double momentum = track->P().Mag();
if (fMinPforTOFpid > 0
&& fMinPforTOFpid < momentum && momentum < fMaxPforTOFpid
&& !tTOFPidIn) {
fNTracksFailed++;
return false;
}
if (fMinPforTPCpid > 0
&& fMinPforTPCpid < momentum && momentum < fMaxPforTPCpid
&& !tTPCPidIn) {
fNTracksFailed++;
return false;
}
if (fMinPforITSpid > 0
&& fMinPforITSpid < momentum && momentum < fMaxPforITSpid
&& !tITSPidIn) {
fNTracksFailed++;
return false;
}
float tEnergy = ::sqrt(track->P().Mag2() + fMass * fMass);
float tRapidity = 0;
if (tEnergy-track->P().z() != 0 && (tEnergy + track->P().z()) / (tEnergy-track->P().z()) > 0)
tRapidity = 0.5 * ::log((tEnergy + track->P().z())/(tEnergy-track->P().z()));
float tPt = track->P().Perp();
float tEta = track->P().PseudoRapidity();
if (fMaxImpactXYPtOff < 999.0) {
if ((fMaxImpactXYPtOff + fMaxImpactXYPtNrm*TMath::Power(tPt, fMaxImpactXYPtPow)) < TMath::Abs(track->ImpactD())) {
fNTracksFailed++;
return false;
}
}
if ((tRapidity < fRapidity[0]) || (tRapidity > fRapidity[1])) {
fNTracksFailed++;
return false;
}
if ((tEta < fEta[0]) || (tEta > fEta[1])) {
fNTracksFailed++;
return false;
}
if ((tPt < fPt[0]) || (tPt > fPt[1])) {
fNTracksFailed++;
return false;
}
// cout << "Track has pids: "
// << track->PidProbElectron() << " "
// << track->PidProbMuon() << " "
// << track->PidProbPion() << " "
// << track->PidProbKaon() << " "
// << track->PidProbProton() << " "
// << track->PidProbElectron()+track->PidProbMuon()+track->PidProbPion()+track->PidProbKaon()+track->PidProbProton() << endl;
if ((track->PidProbElectron() < fPidProbElectron[0]) || (track->PidProbElectron() > fPidProbElectron[1])) {
fNTracksFailed++;
return false;
}
if ((track->PidProbPion() < fPidProbPion[0]) || (track->PidProbPion() > fPidProbPion[1])) {
fNTracksFailed++;
return false;
}
if ((track->PidProbKaon() < fPidProbKaon[0]) || (track->PidProbKaon() > fPidProbKaon[1])) {
fNTracksFailed++;
return false;
}
if ((track->PidProbProton() < fPidProbProton[0]) || (track->PidProbProton() > fPidProbProton[1])) {
fNTracksFailed++;
return false;
}
if ((track->PidProbMuon() < fPidProbMuon[0]) || (track->PidProbMuon() > fPidProbMuon[1])) {
fNTracksFailed++;
return false;
}
//****N Sigma Method -- electron rejection****
if (fElectronRejection)
if (!IsElectron(track->NSigmaTPCE(),track->NSigmaTPCPi(),track->NSigmaTPCK(), track->NSigmaTPCP()))
return false;
if (fMostProbable) {
int imost=0;
tMost[0] = track->PidProbElectron()*PidFractionElectron(track->P().Mag());
tMost[1] = 0.0;
tMost[2] = track->PidProbPion()*PidFractionPion(track->P().Mag());
tMost[3] = track->PidProbKaon()*PidFractionKaon(track->P().Mag());
tMost[4] = track->PidProbProton()*PidFractionProton(track->P().Mag());
float ipidmax = 0.0;
//****N Sigma Method****
if (fPIDMethod==0) {
// Looking for pions
if (fMostProbable == 2) {
if (IsPionNSigma(track->P().Mag(), track->NSigmaTPCPi(), track->NSigmaTOFPi())) {
imost = 2;
}
}
else if (fMostProbable == 3) {
if (IsKaonNSigma(track->P().Mag(), track->NSigmaTPCK(), track->NSigmaTOFK())){
imost = 3;
}
}
else if (fMostProbable == 4) { // proton nsigma-PID required contour adjusting (in LHC10h)
if (IsProtonNSigma(track->P().Mag(), track->NSigmaTPCP(), track->NSigmaTOFP())
// && (TMath::Abs(track->NSigmaTPCP()) < TMath::Abs(track->NSigmaTPCPi()))
// && (TMath::Abs(track->NSigmaTPCP()) < TMath::Abs(track->NSigmaTPCK()))
// && (TMath::Abs(track->NSigmaTOFP()) < TMath::Abs(track->NSigmaTOFPi()))
// && (TMath::Abs(track->NSigmaTOFP()) < TMath::Abs(track->NSigmaTOFK()))
// && IsProtonTPCdEdx(track->P().Mag(), track->TPCsignal())
) {
imost = 4;
}
}
else if (fMostProbable == 13) {
if (IsDeuteronNSigma(track->P().Mag(),track->MassTOF(), fNsigmaMass, track->NSigmaTPCD(), track->NSigmaTOFD()))
imost = 13;
if ((track->P().Mag() < 1) &&!(IsDeuteronTPCdEdx(track->P().Mag(), track->TPCsignal())))
imost = 0;
}
else if (fMostProbable == 14) {
if (IsTritonNSigma(track->P().Mag(), track->NSigmaTPCT(), track->NSigmaTOFT())){
imost = 14;
}
}
else if (fMostProbable == 15) {
if ( IsHe3NSigma(track->P().Mag(), track->NSigmaTPCH(), track->NSigmaTOFH())
)
imost = 15;
}
else if (fMostProbable == 16) {
if ( IsAlphaNSigma(track->P().Mag(), track->NSigmaTPCA(), track->NSigmaTOFA())
)
imost = 16;
}
else if (fMostProbable == 5) { // no-protons
if ( !IsProtonNSigma(track->P().Mag(), track->NSigmaTPCP(), track->NSigmaTOFP()) )
imost = 5;
}
else if (fMostProbable == 6) { //pions OR kaons OR protons
if (IsPionNSigma(track->P().Mag(), track->NSigmaTPCPi(), track->NSigmaTOFPi()))
imost = 6;
else if (IsKaonNSigma(track->P().Mag(), track->NSigmaTPCK(), track->NSigmaTOFK()))
imost = 6;
else if (IsProtonNSigma(track->P().Mag(), track->NSigmaTPCP(), track->NSigmaTOFP()) )
imost = 6;
}
else if (fMostProbable == 7) { // pions OR kaons OR protons OR electrons or or or
if (IsPionNSigma(track->P().Mag(), track->NSigmaTPCPi(), track->NSigmaTOFPi()))
imost = 7;
else if (IsKaonNSigma(track->P().Mag(), track->NSigmaTPCK(), track->NSigmaTOFK()))
imost = 7;
else if (IsProtonNSigma(track->P().Mag(), track->NSigmaTPCP(), track->NSigmaTOFP()) )
imost = 7;
else if (TMath::Abs(track->NSigmaTPCE())<3)
imost = 7;
}
else if (fMostProbable == 8) { // TOF matching
if (track->NSigmaTOFPi() != -1000 || track->Pt()<0.5){
imost = 8;
}
}
else if (fMostProbable == 9) { // Other: no kaons, no pions, no protons
if (IsPionNSigma(track->P().Mag(), track->NSigmaTPCPi(), track->NSigmaTOFPi()))
imost = -1;
else if (IsKaonNSigma(track->P().Mag(), track->NSigmaTPCK(), track->NSigmaTOFK()))
imost = -1;
else if (IsProtonNSigma(track->P().Mag(), track->NSigmaTPCP(), track->NSigmaTOFP()) )
imost = -1;
else if (track->NSigmaTOFPi() != -1000 || track->Pt()<0.5){
imost = 9;
}
}
if (fMostProbable == 10) {//cut on Nsigma in pT not p
if (IsPionNSigma(track->Pt(), track->NSigmaTPCPi(), track->NSigmaTOFPi()))
imost = 10;
}
else if (fMostProbable == 11) {//cut on Nsigma in pT not p
if (IsKaonNSigma(track->Pt(), track->NSigmaTPCK(), track->NSigmaTOFK())){
imost = 11;
}
}
else if (fMostProbable == 12) { //cut on Nsigma in pT not p
if ( IsProtonNSigma(track->Pt(), track->NSigmaTPCP(), track->NSigmaTOFP()) )
imost = 12;
}
}
//****Contour Method****
if (fPIDMethod==1) {
for (int ip=0; ip<5; ip++) {
if (tMost[ip] > ipidmax) {
ipidmax = tMost[ip];
imost = ip;
}
}
// Looking for pions
if (fMostProbable == 2) {
if (imost == 2) {
// Using the TPC to reject non-pions
if (!(IsPionTPCdEdx(track->P().Mag(), track->TPCsignal()))) {
imost = 0;
}
if (0) {
// Using the TOF to reject non-pions
if (track->P().Mag() < 0.6) {
if (tTOFPidIn)
if (!IsPionTOFTime(track->P().Mag(), track->TOFpionTime()))
imost = 0;
}
else {
if (tTOFPidIn) {
if (!IsPionTOFTime(track->P().Mag(), track->TOFpionTime()))
imost = 0;
}
else {
imost = 0;
}
}
}
}
}
// Looking for kaons
else if (fMostProbable == 3) {
// if (imost == 3) {
// Using the TPC to reject non-kaons
if (track->P().Mag() < 0.6) {
if (!(IsKaonTPCdEdx(track->P().Mag(), track->TPCsignal()))) {
imost = 0;
} else {
imost = 3;
}
if (1) {
// Using the TOF to reject non-kaons
if (tTOFPidIn)
if (!IsKaonTOFTime(track->P().Mag(), track->TOFkaonTime()))
imost = 0;
}
}
else {
if (1) {
if (tTOFPidIn) {
if (!IsKaonTOFTime(track->P().Mag(), track->TOFkaonTime()))
imost = 0;
else
imost = 3;
}
else {
if (!(IsKaonTPCdEdx(track->P().Mag(), track->TPCsignal())))
imost = 0;
else
imost = 3;
}
}
}
// }
}
// Looking for protons
else if (fMostProbable == 4) {
// if (imost == 3) {
// Using the TPC to reject non-kaons
if (track->P().Mag() < 0.8) {
if (!(IsProtonTPCdEdx(track->P().Mag(), track->TPCsignal())))
imost = 0;
else imost = 4;
if (0) {
// Using the TOF to reject non-kaons
if (tTOFPidIn)
if (!IsKaonTOFTime(track->P().Mag(), track->TOFkaonTime()))
imost = 0;
}
}
else {
if (0) {
if (tTOFPidIn) {
if (!IsKaonTOFTime(track->P().Mag(), track->TOFkaonTime()))
imost = 0;
else
imost = 3;
}
else {
if (!(IsKaonTPCdEdx(track->P().Mag(), track->TPCsignal())))
imost = 0;
else
imost = 3;
}
}
}
}
/**********************************/
else if (fMostProbable == 13) {
// if (imost == 3) {
// Using the TPC to reject non-deuterons
if (track->P().Mag() < 1) {
if (!(IsDeuteronTPCdEdx(track->P().Mag(), track->TPCsignal()))) {
imost = 0;
} else {
imost = 13;
}
}
}
/*************************************/
}
if (imost != fMostProbable) {
return false;
}
}
//fan
//cout<<"****** Go Through the cut ******"<<endl;
// cout<<fLabel<<" Label="<<track->Label()<<endl;
// cout<<fCharge<<" Charge="<<track->Charge()<<endl;
// cout<<fPt[0]<<" < Pt ="<<Pt<<" <"<<fPt[1]<<endl;
//cout<<fRapidity[0]<<" < Rapidity ="<<tRapidity<<" <"<<fRapidity[1]<<endl;
//cout<<fPidProbElectron[0]<<" < e="<<track->PidProbElectron()<<" <"<<fPidProbElectron[1]<<endl;
//cout<<fPidProbPion[0]<<" < pi="<<track->PidProbPion()<<" <"<<fPidProbPion[1]<<endl;
//cout<<fPidProbKaon[0]<<" < k="<<track->PidProbKaon()<<" <"<<fPidProbKaon[1]<<endl;
//cout<<fPidProbProton[0]<<" < p="<<track->PidProbProton()<<" <"<<fPidProbProton[1]<<endl;
//cout<<fPidProbMuon[0]<<" < mi="<<track->PidProbMuon()<<" <"<<fPidProbMuon[1]<<endl;
fNTracksPassed++ ;
return true;
}
//------------------------------
AliFemtoString AliFemtoESDTrackCut::Report()
{
// Prepare report from the execution
string tStemp;
char tCtemp[100];
snprintf(tCtemp , 100, "Particle mass:\t%E\n",this->Mass());
tStemp=tCtemp;
snprintf(tCtemp , 100, "Particle charge:\t%d\n",fCharge);
tStemp+=tCtemp;
snprintf(tCtemp , 100, "Particle pT:\t%E - %E\n",fPt[0],fPt[1]);
tStemp+=tCtemp;
snprintf(tCtemp , 100, "Particle rapidity:\t%E - %E\n",fRapidity[0],fRapidity[1]);
tStemp+=tCtemp;
snprintf(tCtemp , 100, "Particle eta:\t%E - %E\n",fEta[0],fEta[1]);
tStemp+=tCtemp;
snprintf(tCtemp , 100, "Number of tracks which passed:\t%ld Number which failed:\t%ld\n",fNTracksPassed,fNTracksFailed);
tStemp += tCtemp;
AliFemtoString returnThis = tStemp;
return returnThis;
}
TList *AliFemtoESDTrackCut::ListSettings()
{
// return a list of settings in a writable form
TList *tListSetttings = new TList();
char buf[200];
snprintf(buf, 200, "AliFemtoESDTrackCut.mass=%f", this->Mass());
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.charge=%i", fCharge);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.pidprobpion.minimum=%f", fPidProbPion[0]);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.pidprobpion.maximum=%f", fPidProbPion[1]);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.pidprobkaon.minimum=%f", fPidProbKaon[0]);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.pidprobkaon.maximum=%f", fPidProbKaon[1]);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.pidprobproton.minimum=%f", fPidProbProton[0]);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.pidprobproton.maximum=%f", fPidProbProton[1]);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.pidprobelectron.minimum=%f", fPidProbElectron[0]);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.pidprobelectron.maximum=%f", fPidProbElectron[1]);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.pidprobMuon.minimum=%f", fPidProbMuon[0]);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.pidprobMuon.maximum=%f", fPidProbMuon[1]);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.minimumtpcclusters=%i", fminTPCclsF);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.minimumitsclusters=%i", fminTPCclsF);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.pt.minimum=%f", fPt[0]);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.pt.maximum=%f", fPt[1]);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.rapidity.minimum=%f", fRapidity[0]);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.rapidity.maximum=%f", fRapidity[1]);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.removekinks=%i", fRemoveKinks);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.maxitschindof=%f", fMaxITSchiNdof);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.maxtpcchindof=%f", fMaxTPCchiNdof);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.maxsigmatovertex=%f", fMaxSigmaToVertex);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.maximpactxy=%f", fMaxImpactXY);
tListSetttings->AddLast(new TObjString(buf));
snprintf(buf, 200, "AliFemtoESDTrackCut.maximpactz=%f", fMaxImpactZ);
tListSetttings->AddLast(new TObjString(buf));
if (fMostProbable) {
if (fMostProbable == 2)
snprintf(buf, 200, "AliFemtoESDTrackCut.mostprobable=%s", "Pion");
if (fMostProbable == 3)
snprintf(buf, 200, "AliFemtoESDTrackCut.mostprobable=%s", "Kaon");
if (fMostProbable == 4)
snprintf(buf, 200, "AliFemtoESDTrackCut.mostprobable=%s", "Proton");
tListSetttings->AddLast(new TObjString(buf));
}
return tListSetttings;
}
void AliFemtoESDTrackCut::SetRemoveKinks(const bool& flag)
{
fRemoveKinks = flag;
}
void AliFemtoESDTrackCut::SetRemoveITSFake(const bool& flag)
{
fRemoveITSFake = flag;
}
// electron
// 0.13 - 1.8
// 0 7.594129e-02 8.256141e-03
// 1 -5.535827e-01 8.170825e-02
// 2 1.728591e+00 3.104210e-01
// 3 -2.827893e+00 5.827802e-01
// 4 2.503553e+00 5.736207e-01
// 5 -1.125965e+00 2.821170e-01
// 6 2.009036e-01 5.438876e-02
float AliFemtoESDTrackCut::PidFractionElectron(float mom) const
{
// Provide a parameterized fraction of electrons dependent on momentum
if (mom<0.13)
return (7.594129e-02
-5.535827e-01*0.13
+1.728591e+00*0.13*0.13
-2.827893e+00*0.13*0.13*0.13
+2.503553e+00*0.13*0.13*0.13*0.13
-1.125965e+00*0.13*0.13*0.13*0.13*0.13
+2.009036e-01*0.13*0.13*0.13*0.13*0.13*0.13);
if (mom>1.8)
return (7.594129e-02
-5.535827e-01*1.8
+1.728591e+00*1.8*1.8
-2.827893e+00*1.8*1.8*1.8
+2.503553e+00*1.8*1.8*1.8*1.8
-1.125965e+00*1.8*1.8*1.8*1.8*1.8
+2.009036e-01*1.8*1.8*1.8*1.8*1.8*1.8);
return (7.594129e-02
-5.535827e-01*mom
+1.728591e+00*mom*mom
-2.827893e+00*mom*mom*mom
+2.503553e+00*mom*mom*mom*mom
-1.125965e+00*mom*mom*mom*mom*mom
+2.009036e-01*mom*mom*mom*mom*mom*mom);
}
// pion
// 0.13 - 2.0
// 0 1.063457e+00 8.872043e-03
// 1 -4.222208e-01 2.534402e-02
// 2 1.042004e-01 1.503945e-02
float AliFemtoESDTrackCut::PidFractionPion(float mom) const
{
// Provide a parameterized fraction of pions dependent on momentum
if (mom<0.13)
return ( 1.063457e+00
-4.222208e-01*0.13
+1.042004e-01*0.0169);
if (mom>2.0)
return ( 1.063457e+00
-4.222208e-01*2.0
+1.042004e-01*4.0);
return ( 1.063457e+00
-4.222208e-01*mom
+1.042004e-01*mom*mom);
}
// kaon
// 0.18 - 2.0
// 0 -7.289406e-02 1.686074e-03
// 1 4.415666e-01 1.143939e-02
// 2 -2.996790e-01 1.840964e-02
// 3 6.704652e-02 7.783990e-03
float AliFemtoESDTrackCut::PidFractionKaon(float mom) const
{
// Provide a parameterized fraction of kaons dependent on momentum
if (mom<0.18)
return (-7.289406e-02
+4.415666e-01*0.18
-2.996790e-01*0.18*0.18
+6.704652e-02*0.18*0.18*0.18);
if (mom>2.0)
return (-7.289406e-02
+4.415666e-01*2.0
-2.996790e-01*2.0*2.0
+6.704652e-02*2.0*2.0*2.0);
return (-7.289406e-02
+4.415666e-01*mom
-2.996790e-01*mom*mom
+6.704652e-02*mom*mom*mom);
}
// proton
// 0.26 - 2.0
// 0 -3.730200e-02 2.347311e-03
// 1 1.163684e-01 1.319316e-02
// 2 8.354116e-02 1.997948e-02
// 3 -4.608098e-02 8.336400e-03
float AliFemtoESDTrackCut::PidFractionProton(float mom) const
{
// Provide a parameterized fraction of protons dependent on momentum
if (mom<0.26) return 0.0;
if (mom>2.0)
return (-3.730200e-02
+1.163684e-01*2.0
+8.354116e-02*2.0*2.0
-4.608098e-02*2.0*2.0*2.0);
return (-3.730200e-02
+1.163684e-01*mom
+8.354116e-02*mom*mom
-4.608098e-02*mom*mom*mom);
}
void AliFemtoESDTrackCut::SetMomRangeTOFpidIs(const float& minp, const float& maxp)
{
fMinPforTOFpid = minp;
fMaxPforTOFpid = maxp;
}
void AliFemtoESDTrackCut::SetMomRangeTPCpidIs(const float& minp, const float& maxp)
{
fMinPforTPCpid = minp;
fMaxPforTPCpid = maxp;
}
void AliFemtoESDTrackCut::SetMomRangeITSpidIs(const float& minp, const float& maxp)
{
fMinPforITSpid = minp;
fMaxPforITSpid = maxp;
}
bool AliFemtoESDTrackCut::IsPionTPCdEdx(float mom, float dEdx)
{
// double a1 = -95.4545, b1 = 86.5455;
// double a2 = 0.0, b2 = 56.0;
double a1 = -343.75, b1 = 168.125;
double a2 = 0.0, b2 = 65.0;
if (mom < 0.32) {
if (dEdx < a1*mom+b1) return true;
}
if (dEdx < a2*mom+b2) return true;
return false;
}
bool AliFemtoESDTrackCut::IsKaonTPCdEdx(float mom, float dEdx)
{
// double a1 = -547.0; double b1 = 297.0;
// double a2 = -125.0; double b2 = 145.0;
// double a3 = -420.0; double b3 = 357.0;
// double a4 = -110.0; double b4 = 171.0;
// double b5 = 72.0;
// if (mom<0.2) return false;
// if (mom<0.36) {
// if (dEdx < a1*mom+b1) return false;
// if (dEdx > a3*mom+b3) return false;
// }
// else if (mom<0.6) {
// if (dEdx < a2*mom+b2) return false;
// if (dEdx > a3*mom+b3) return false;
// }
// else if (mom<0.9) {
// if (dEdx > a4*mom+b4) return false;
// if (dEdx < b5) return false;
// }
// else
// return false;
// // else {
// // if (dEdx > b5) return false;
// // }
// return true;
double a1 = -268.896; double b1 = 198.669;
double a2 = -49.0012; double b2 = 88.7214;
if (mom<0.2) return false;
if (mom>0.3 && mom<0.5) {
if (dEdx < a1*mom+b1) return false;
}
else if (mom<1.2) {
if (dEdx < a2*mom+b2) return false;
}
return true;
}
bool AliFemtoESDTrackCut::IsDeuteronTPCdEdx(float mom, float dEdx)
{
double a1 = -250.0, b1 = 400.0;
double a2 = 0.0, b2 = 30.0;
if (mom < 1) {
if (dEdx < a1*mom+b1) return false;
}
//if (dEdx < a2*mom+b2) return true;
return true;
}
bool AliFemtoESDTrackCut::IsProtonTPCdEdx(float mom, float dEdx)
{
double a1 = -1800.0; double b1 = 940.0;
double a2 = -500.0; double b2 = 420.0;
double a3 = -216.7; double b3 = 250.0;
if (mom<0.2) return false;
if (mom>0.3 && mom<0.4) {
if (dEdx < a1*mom+b1) return false;
}
else if (mom<0.6) {
if (dEdx < a2*mom+b2) return false;
}
else if (mom<0.9) {
if (dEdx < a3*mom+b3) return false;
}
return true;
}
bool AliFemtoESDTrackCut::IsPionTOFTime(float mom, float ttof)
{
double a1 = -427.0; double b1 = 916.0;
double a2 = 327.0; double b2 = -888.0;
if (mom<0.3) return kFALSE;
if (mom>2.0) return kFALSE;
if (ttof > a1*mom+b1) return kFALSE;
if (ttof < a2*mom+b2) return kFALSE;
return kTRUE;
}
bool AliFemtoESDTrackCut::IsKaonTOFTime(float mom, float ttof)
{
double a1 = 000.0; double b1 = -500.0;
double a2 = 000.0; double b2 = 500.0;
double a3 = 850.0; double b3 = -1503.0;
double a4 = -1637.0; double b4 = 3621.0;
if (mom<0.3) return kFALSE;
if (mom>2.06) return kFALSE;
if (mom<1.2) {
if (ttof > a2*mom+b2) return kFALSE;
if (ttof < a1*mom+b1) return kFALSE;
}
if (mom<1.9) {
if (ttof > a2*mom+b2) return kFALSE;
if (ttof < a3*mom+b3) return kFALSE;
}
if (mom<2.06) {
if (ttof > a4*mom+b4) return kFALSE;
if (ttof < a3*mom+b3) return kFALSE;
}
return kTRUE;
}
bool AliFemtoESDTrackCut::IsProtonTOFTime(float mom, float ttof)
{
double a1 = 000.0; double b1 = -915.0;
double a2 = 000.0; double b2 = 600.0;
double a3 = 572.0; double b3 = -1715.0;
if (mom<0.3) return kFALSE;
if (mom>3.0) return kFALSE;
if (mom<1.4) {
if (ttof > a2*mom+b2) return kFALSE;
if (ttof < a1*mom+b1) return kFALSE;
}
if (mom<3.0) {
if (ttof > a2*mom+b2) return kFALSE;
if (ttof < a3*mom+b3) return kFALSE;
}
return kTRUE;
}
bool AliFemtoESDTrackCut::IsKaonTPCdEdxNSigma(float mom, float nsigmaK)
{
// cout<<" AliFemtoESDTrackCut::IsKaonTPCdEdxNSigma "<<mom<<" "<<nsigmaK<<endl;
if (mom<0.35 && TMath::Abs(nsigmaK)<5.0) return true;
if (mom>=0.35 && mom<0.5 && TMath::Abs(nsigmaK)<3.0) return true;
if (mom>=0.5 && mom<0.7 && TMath::Abs(nsigmaK)<2.0) return true;
return false;
}
bool AliFemtoESDTrackCut::IsKaonTOFNSigma(float mom, float nsigmaK)
{
// cout<<" AliFemtoESDTrackCut::IsKaonTPCdEdxNSigma "<<mom<<" "<<nsigmaK<<endl;
//fan
// if (mom<1.5 && TMath::Abs(nsigmaK)<3.0) return true;
if (mom>=1.5 && TMath::Abs(nsigmaK)<2.0) return true;
return false;
}
/*
bool AliFemtoESDTrackCut::IsKaonNSigma(float mom, float nsigmaTPCK, float nsigmaTOFK)
{
if (mom<0.5)
{
if (TMath::Abs(nsigmaTPCK)<2.0)
{
return true;
}
else
{
return false;
}
}
if (mom>=0.5)
{
if (TMath::Abs(nsigmaTOFK)<3.0 && TMath::Abs(nsigmaTPCK)<3.0)
{
return true;
}
else
{
return false;
}
}
// if (mom>1.5 || mom<0.15) return false;
}
*/
//old
bool AliFemtoESDTrackCut::IsKaonNSigma(float mom, float nsigmaTPCK, float nsigmaTOFK)
{
if (fNsigmaTPCTOF) {
if (mom > 0.5) {
// if (TMath::Hypot( nsigmaTOFP, nsigmaTPCP )/TMath::Sqrt(2) < 3.0)
if (TMath::Hypot( nsigmaTOFK, nsigmaTPCK ) < fNsigma)
return true;
}
else {
if (TMath::Abs(nsigmaTPCK) < fNsigma)
return true;
}
}
else {
if (mom<0.4)
{
if (nsigmaTOFK<-999.)
{
if (TMath::Abs(nsigmaTPCK)<2.0) return true;
}
else if (TMath::Abs(nsigmaTOFK)<3.0 && TMath::Abs(nsigmaTPCK)<3.0)
{
return true;
}
}
else if (mom>=0.4 && mom<=0.6)
{
if (nsigmaTOFK < -999.)
{
if (TMath::Abs(nsigmaTPCK)<2.0) return true;
}
else if (TMath::Abs(nsigmaTOFK)<3.0 && TMath::Abs(nsigmaTPCK)<3.0)
{
return true;
}
}
else if (nsigmaTOFK < -999.)
{
return false;
}
else if (TMath::Abs(nsigmaTOFK)<3.0 && TMath::Abs(nsigmaTPCK)<3.0) return true;
}
return false;
}
bool AliFemtoESDTrackCut::IsPionNSigma(float mom, float nsigmaTPCPi, float nsigmaTOFPi)
{
if (fNsigmaTPCTOF) {
if (mom > 0.5) {
// if (TMath::Hypot( nsigmaTOFP, nsigmaTPCP )/TMath::Sqrt(2) < 3.0)
return TMath::Hypot( nsigmaTOFPi, nsigmaTPCPi ) < fNsigma;
}
return TMath::Abs(nsigmaTPCPi) < fNsigma;
}
if (mom < 0.65) {
if (nsigmaTOFPi < -999.) {
if (mom < 0.35 && TMath::Abs(nsigmaTPCPi)<3.0) return true;
else if (mom<0.5 && mom>=0.35 && TMath::Abs(nsigmaTPCPi)<3.0) return true;
else if (mom>=0.5 && TMath::Abs(nsigmaTPCPi)<2.0) return true;
else return false;
}
else if (TMath::Abs(nsigmaTOFPi)<3.0 && TMath::Abs(nsigmaTPCPi)<3.0) {
return true;
}
}
else if (nsigmaTOFPi < -999.) {
return false;
}
else if (mom<1.5 && TMath::Abs(nsigmaTOFPi)<3.0 && TMath::Abs(nsigmaTPCPi)<5.0) {
return true;
}
else if (mom>=1.5 && TMath::Abs(nsigmaTOFPi)<2.0 && TMath::Abs(nsigmaTPCPi)<5.0) {
return true;
}
return false;
}
bool AliFemtoESDTrackCut::IsProtonNSigma(float mom, float nsigmaTPCP, float nsigmaTOFP)
{
if (fNsigmaTPCTOF) {
if (mom > 0.5) {
// if (TMath::Hypot( nsigmaTOFP, nsigmaTPCP )/TMath::Sqrt(2) < 3.0)
if (TMath::Hypot( nsigmaTOFP, nsigmaTPCP ) < fNsigma)
return true;
} else if (TMath::Abs(nsigmaTPCP) < fNsigma) {
return true;
}
}
else if (fNsigmaTPConly) {
if (TMath::Abs(nsigmaTPCP) < fNsigma)
return true;
}
else {
if (mom > 0.8 && mom < 2.5) {
if ( TMath::Abs(nsigmaTPCP) < 3.0 && TMath::Abs(nsigmaTOFP) < 3.0)
return true;
}
else if (mom > 2.5) {
if ( TMath::Abs(nsigmaTPCP) < 3.0 && TMath::Abs(nsigmaTOFP) < 2.0)
return true;
}
else {
if (TMath::Abs(nsigmaTPCP) < 3.0)
return true;
}
}
return false;
}
/***********************************************************************/
bool AliFemtoESDTrackCut::IsDeuteronNSigma(float mom, float massTOFPDG,float sigmaMass, float nsigmaTPCD, float nsigmaTOFD)
{
double massPDGD=1.8756;
if (fNsigmaTPCTOF) {
if (mom > 1) { //if TOF avaliable: && (nsigmaTOFD != -1000) --> always TOF
//if (TMath::Hypot( nsigmaTOFP, nsigmaTPCP )/TMath::Sqrt(2) < 3.0)
if ((TMath::Hypot( nsigmaTOFD, nsigmaTPCD ) < fNsigma) && (TMath::Abs(massTOFPDG-massPDGD*massPDGD)<sigmaMass))
return true;
}
else {
if (TMath::Abs(nsigmaTPCD) < fNsigma)
return true;
}
}
return false;
}
bool AliFemtoESDTrackCut::IsTritonNSigma(float mom, float nsigmaTPCT, float nsigmaTOFT)
{
if (fNsigmaTPCTOF) {
return false;
}
else {
if (mom<2 && TMath::Abs(nsigmaTPCT)<fNsigma) return true;
}
return false;
}
bool AliFemtoESDTrackCut::IsHe3NSigma(float mom, float nsigmaTPCH, float nsigmaTOFH)
{
if (fNsigmaTPCTOF) {
return false;
}
else {
if (mom<3 && TMath::Abs(nsigmaTPCH)<fNsigma) return true;
}
return false;
}
bool AliFemtoESDTrackCut::IsAlphaNSigma(float mom, float nsigmaTPCA, float nsigmaTOFA)
{
if (fNsigmaTPCTOF) {
return false;
}
else {
if (mom<3 && TMath::Abs(nsigmaTPCA)<fNsigma) return true;
}
return false;
}
//
/*********************************************************************/
void AliFemtoESDTrackCut::SetPIDMethod(ReadPIDMethodType newMethod)
{
fPIDMethod = newMethod;
}
void AliFemtoESDTrackCut::SetNsigmaTPCTOF(Bool_t nsigma)
{
fNsigmaTPCTOF = nsigma;
}
void AliFemtoESDTrackCut::SetNsigmaTPConly(Bool_t nsigma)
{
fNsigmaTPConly = nsigma;
}
void AliFemtoESDTrackCut::SetNsigma(Double_t nsigma)
{
fNsigma = nsigma;
}
void AliFemtoESDTrackCut::SetNsigmaMass(Double_t nsigma)
{
fNsigmaMass = nsigma;
}
void AliFemtoESDTrackCut::SetClusterRequirementITS(AliESDtrackCuts::Detector det, AliESDtrackCuts::ITSClusterRequirement req)
{
fCutClusterRequirementITS[det] = req;
}
Bool_t AliFemtoESDTrackCut::CheckITSClusterRequirement(AliESDtrackCuts::ITSClusterRequirement req, Bool_t clusterL1, Bool_t clusterL2)
{
// checks if the cluster requirement is fullfilled (in this case: return kTRUE)
switch (req) {
case AliESDtrackCuts::kOff: return kTRUE;
case AliESDtrackCuts::kNone: return !clusterL1 && !clusterL2;
case AliESDtrackCuts::kAny: return clusterL1 || clusterL2;
case AliESDtrackCuts::kFirst: return clusterL1;
case AliESDtrackCuts::kOnlyFirst: return clusterL1 && !clusterL2;
case AliESDtrackCuts::kSecond: return clusterL2;
case AliESDtrackCuts::kOnlySecond: return clusterL2 && !clusterL1;
case AliESDtrackCuts::kBoth: return clusterL1 && clusterL2;
}
return kFALSE;
}
bool AliFemtoESDTrackCut::IsElectron(float nsigmaTPCE, float nsigmaTPCPi,float nsigmaTPCK, float nsigmaTPCP)
{
if (TMath::Abs(nsigmaTPCE)<3 && TMath::Abs(nsigmaTPCPi)>3 && TMath::Abs(nsigmaTPCK)>3 && TMath::Abs(nsigmaTPCP)>3)
return false;
else
return true;
}
| 29.437908
| 136
| 0.578264
|
Tingchenxi
|
c81d02b987611180df979fc2e4d959b222069e79
| 4,595
|
hpp
|
C++
|
vm/builtin/float.hpp
|
godfat/rubinius
|
d6a7a3323af0348800118ccd0b13fdf80adbbcef
|
[
"BSD-3-Clause"
] | 3
|
2015-02-02T01:21:27.000Z
|
2016-04-29T22:30:01.000Z
|
vm/builtin/float.hpp
|
godfat/rubinius
|
d6a7a3323af0348800118ccd0b13fdf80adbbcef
|
[
"BSD-3-Clause"
] | null | null | null |
vm/builtin/float.hpp
|
godfat/rubinius
|
d6a7a3323af0348800118ccd0b13fdf80adbbcef
|
[
"BSD-3-Clause"
] | 1
|
2018-03-04T03:19:02.000Z
|
2018-03-04T03:19:02.000Z
|
#ifndef RBX_FLOAT_HPP
#define RBX_FLOAT_HPP
#include "builtin/class.hpp"
#include "builtin/object.hpp"
#include "type_info.hpp"
/* Begin borrowing from MRI 1.8.6 stable */
#if defined(__FreeBSD__) && __FreeBSD__ < 4
#include <floatingpoint.h>
#endif
#include <math.h>
#include <float.h>
namespace rubinius {
class Array;
class String;
class Float : public Numeric {
public:
const static object_type type = FloatType;
double val;
static void init(STATE);
static Float* create(STATE, double val);
static Float* create(STATE, float val);
static Float* create(STATE, native_int val);
static Float* coerce(STATE, Object* value);
double to_double(STATE) { return val; }
void into_string(STATE, char* buf, size_t sz);
static Float* from_cstr(STATE, const char* str, Object* strict);
// Rubinius.primitive! :float_add
Float* add(STATE, Float* other);
// Rubinius.primitive! :float_add
Float* add(STATE, Integer* other);
// Rubinius.primitive! :float_sub
Float* sub(STATE, Float* other);
// Rubinius.primitive! :float_sub
Float* sub(STATE, Integer* other);
// Rubinius.primitive! :float_mul
Float* mul(STATE, Float* other);
// Rubinius.primitive! :float_mul
Float* mul(STATE, Integer* other);
// Rubinius.primitive! :float_pow
Object* fpow(STATE, Float* other);
// Rubinius.primitive! :float_pow
Float* fpow(STATE, Integer* other);
// Rubinius.primitive! :float_div
Float* div(STATE, Float* other);
// Rubinius.primitive! :float_div
Float* div(STATE, Integer* other);
// Rubinius.primitive! :float_mod
Float* mod(STATE, Float* other);
// Rubinius.primitive! :float_mod
Float* mod(STATE, Integer* other);
// Rubinius.primitive! :float_divmod
Array* divmod(STATE, Float* other);
// Rubinius.primitive! :float_divmod
Array* divmod(STATE, Integer* other);
// Rubinius.primitive :float_neg
Float* neg(STATE);
// Rubinius.primitive! :float_equal
Object* equal(STATE, Float* other);
// Rubinius.primitive! :float_equal
Object* equal(STATE, Integer* other);
// Rubinius.primitive! :float_eql
Object* eql(STATE, Float* other);
// Rubinius.primitive! :float_eql
Object* eql(STATE, Integer* other);
// Rubinius.primitive! :float_compare
Object* compare(STATE, Float* other);
// Rubinius.primitive! :float_compare
Object* compare(STATE, Integer* other);
// Rubinius.primitive! :float_gt
Object* gt(STATE, Float* other);
// Rubinius.primitive! :float_gt
Object* gt(STATE, Integer* other);
// Rubinius.primitive! :float_ge
Object* ge(STATE, Float* other);
// Rubinius.primitive! :float_ge
Object* ge(STATE, Integer* other);
// Rubinius.primitive! :float_lt
Object* lt(STATE, Float* other);
// Rubinius.primitive! :float_lt
Object* lt(STATE, Integer* other);
// Rubinius.primitive! :float_le
Object* le(STATE, Float* other);
// Rubinius.primitive! :float_le
Object* le(STATE, Integer* other);
// Rubinius.primitive :float_isinf
Object* fisinf(STATE);
// Rubinius.primitive :float_isnan
Object* fisnan(STATE);
// Rubinius.primitive :float_round
Integer* fround(STATE);
// Rubinius.primitive :float_to_i
Integer* to_i(STATE);
// Rubinius.primitive :float_to_s_formatted
String* to_s_formatted(STATE, String* format);
// Rubinius.primitive :float_to_s_minimal
String* to_s_minimal(STATE);
// Rubinius.primitive :float_to_packed
String* to_packed(STATE, Object* want_double);
static int radix() { return FLT_RADIX; }
static int rounds() { return FLT_ROUNDS; }
static double min() { return DBL_MIN; }
static double max() { return DBL_MAX; }
static int min_exp() { return DBL_MIN_EXP; }
static int max_exp() { return DBL_MAX_EXP; }
static int min_10_exp() { return DBL_MIN_10_EXP; }
static int max_10_exp() { return DBL_MAX_10_EXP; }
static int dig() { return DBL_DIG; }
static int mant_dig() { return DBL_MANT_DIG; }
static double epsilon() { return DBL_EPSILON; }
class Info : public TypeInfo {
public:
Info(object_type type)
: TypeInfo(type)
{
allow_user_allocate = false;
}
virtual void mark(Object* t, ObjectMark& mark);
virtual void show(STATE, Object* self, int level);
virtual void show_simple(STATE, Object* self, int level);
virtual void auto_mark(Object* obj, ObjectMark& mark) {}
};
};
}
#endif
| 28.899371
| 68
| 0.663765
|
godfat
|
c81d408903f8057f36faf3dace43172b0bced3b4
| 1,253
|
cpp
|
C++
|
MMOCoreORB/src/server/zone/objects/tangible/sign/SignObjectImplementation.cpp
|
V-Fib/FlurryClone
|
40e0ca7245ec31b3815eb6459329fd9e70f88936
|
[
"Zlib",
"OpenSSL"
] | 18
|
2017-02-09T15:36:05.000Z
|
2021-12-21T04:22:15.000Z
|
MMOCoreORB/src/server/zone/objects/tangible/sign/SignObjectImplementation.cpp
|
V-Fib/FlurryClone
|
40e0ca7245ec31b3815eb6459329fd9e70f88936
|
[
"Zlib",
"OpenSSL"
] | 61
|
2016-12-30T21:51:10.000Z
|
2021-12-10T20:25:56.000Z
|
MMOCoreORB/src/server/zone/objects/tangible/sign/SignObjectImplementation.cpp
|
V-Fib/FlurryClone
|
40e0ca7245ec31b3815eb6459329fd9e70f88936
|
[
"Zlib",
"OpenSSL"
] | 71
|
2017-01-01T05:34:38.000Z
|
2022-03-29T01:04:00.000Z
|
/*
* SignObjectImplementation.cpp
*
* Created on: Nov 20, 2010
* Author: crush
*/
#include "server/zone/objects/tangible/sign/SignObject.h"
#include "server/zone/objects/creature/CreatureObject.h"
#include "server/zone/objects/player/sui/messagebox/SuiMessageBox.h"
#include "server/zone/objects/building/BuildingObject.h"
int SignObjectImplementation::handleObjectMenuSelect(CreatureObject* player, byte selectedID) {
switch (selectedID) {
case 20: //Read Sign
sendSignNameTo(player);
break;
default:
return TangibleObjectImplementation::handleObjectMenuSelect(player, selectedID);
}
return 0;
}
void SignObjectImplementation::sendSignNameTo(CreatureObject* player) {
ManagedReference<SuiMessageBox*> suiBox = new SuiMessageBox(player, SuiWindowType::NONE);
suiBox->setPromptTitle("@sui:swg"); //Star Wars Galaxies
suiBox->setPromptText(getDisplayedName());
player->sendMessage(suiBox->generateMessage());
}
void SignObjectImplementation::initializeChildObject(SceneObject* controllerObject) {
if (controllerObject == nullptr)
return;
attachedObject = controllerObject;
if (controllerObject->isBuildingObject())
(cast<BuildingObject*>(controllerObject))->setSignObject(_this.getReferenceUnsafeStaticCast());
}
| 29.139535
| 97
| 0.782123
|
V-Fib
|
c81e7a2bdc8f3d46e5e2b0358aa0644afae5a269
| 4,919
|
cpp
|
C++
|
src/devices/bus/nes/cne.cpp
|
Robbbert/messui
|
49b756e2140d8831bc81335298ee8c5471045e79
|
[
"BSD-3-Clause"
] | 26
|
2015-03-31T06:25:51.000Z
|
2021-12-14T09:29:04.000Z
|
src/devices/bus/nes/cne.cpp
|
Robbbert/messui
|
49b756e2140d8831bc81335298ee8c5471045e79
|
[
"BSD-3-Clause"
] | null | null | null |
src/devices/bus/nes/cne.cpp
|
Robbbert/messui
|
49b756e2140d8831bc81335298ee8c5471045e79
|
[
"BSD-3-Clause"
] | 10
|
2015-03-27T05:45:51.000Z
|
2022-02-04T06:57:36.000Z
|
// license:BSD-3-Clause
// copyright-holders:Fabio Priuli
/***********************************************************************************************************
NES/Famicom cartridge emulation for C&E PCBs
Here we emulate the following PCBs
* C&E Decathlon [mapper 244]
* C&E Feng Shen Bang [mapper 246]
* C&E Sheng Huo Lie Zhuan [mapper 240]
***********************************************************************************************************/
#include "emu.h"
#include "cne.h"
#ifdef NES_PCB_DEBUG
#define VERBOSE 1
#else
#define VERBOSE 0
#endif
#define LOG_MMC(x) do { if (VERBOSE) logerror x; } while (0)
//-------------------------------------------------
// constructor
//-------------------------------------------------
DEFINE_DEVICE_TYPE(NES_CNE_DECATHL, nes_cne_decathl_device, "nes_cne_deca", "NES Cart C&E Decathlon PCB")
DEFINE_DEVICE_TYPE(NES_CNE_FSB, nes_cne_fsb_device, "nes_cne_fsb", "NES Cart C&E Feng Shen Bang PCB")
DEFINE_DEVICE_TYPE(NES_CNE_SHLZ, nes_cne_shlz_device, "nes_cne_shlz", "NES Cart C&E Sheng Huo Lie Zhuan PCB")
nes_cne_decathl_device::nes_cne_decathl_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock)
: nes_nrom_device(mconfig, NES_CNE_DECATHL, tag, owner, clock)
{
}
nes_cne_fsb_device::nes_cne_fsb_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock)
: nes_nrom_device(mconfig, NES_CNE_FSB, tag, owner, clock)
{
}
nes_cne_shlz_device::nes_cne_shlz_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock)
: nes_nrom_device(mconfig, NES_CNE_SHLZ, tag, owner, clock)
{
}
void nes_cne_decathl_device::device_start()
{
common_start();
}
void nes_cne_decathl_device::pcb_reset()
{
m_chr_source = m_vrom_chunks ? CHRROM : CHRRAM;
prg32(0);
chr8(0, m_chr_source);
}
void nes_cne_fsb_device::device_start()
{
common_start();
}
void nes_cne_fsb_device::pcb_reset()
{
m_chr_source = m_vrom_chunks ? CHRROM : CHRRAM;
prg32(0xff);
chr8(0, m_chr_source);
}
void nes_cne_shlz_device::device_start()
{
common_start();
}
void nes_cne_shlz_device::pcb_reset()
{
m_chr_source = m_vrom_chunks ? CHRROM : CHRRAM;
prg32(0);
chr8(0, m_chr_source);
}
/*-------------------------------------------------
mapper specific handlers
-------------------------------------------------*/
/*-------------------------------------------------
C & E Bootleg Board for Decathlon
Games: Decathlon
Pretty simple mapper: writes to 0x8065-0x80a4 set prg32 to
offset & 3; writes to 0x80a5-0x80e4 set chr8 to offset & 7
iNES: mapper 244
In MESS: Supported.
-------------------------------------------------*/
void nes_cne_decathl_device::write_h(offs_t offset, uint8_t data)
{
LOG_MMC(("cne_decathl_w, offset: %04x, data: %02x\n", offset, data));
if (offset < 0x0065)
return;
if (offset < 0x00a5)
{
prg32((offset - 0x0065) & 0x03);
return;
}
if (offset < 0x00e5)
{
chr8((offset - 0x00a5) & 0x07, CHRROM);
}
}
/*-------------------------------------------------
C & E Bootleg Board for Fong Shen Bang
Games: Fong Shen Bang - Zhu Lu Zhi Zhan
Simple mapper: writes to 0x6000-0x67ff set PRG and CHR banks.
Namely, 0x6000->0x6003 select resp. prg8_89, prg8_ab, prg8_cd
and prg8_ef. 0x6004->0x6007 select resp. crh2_0, chr2_2,
chr2_4 and chr2_6. In 0x6800-0x7fff lies WRAM. Battery backed?
iNES: mapper 246
In MESS: Supported.
-------------------------------------------------*/
void nes_cne_fsb_device::write_m(offs_t offset, uint8_t data)
{
LOG_MMC(("cne_fsb write_m, offset: %04x, data: %02x\n", offset, data));
if (offset < 0x0800)
{
switch (offset & 0x0007)
{
case 0x0000:
prg8_89(data);
break;
case 0x0001:
prg8_ab(data);
break;
case 0x0002:
prg8_cd(data);
break;
case 0x0003:
prg8_ef(data);
break;
case 0x0004:
chr2_0(data, CHRROM);
break;
case 0x0005:
chr2_2(data, CHRROM);
break;
case 0x0006:
chr2_4(data, CHRROM);
break;
case 0x0007:
chr2_6(data, CHRROM);
break;
}
}
else
m_battery[offset] = data;
}
uint8_t nes_cne_fsb_device::read_m(offs_t offset)
{
LOG_MMC(("cne_fsb read_m, offset: %04x\n", offset));
if (offset >= 0x0800)
return m_battery[offset];
return 0xff;
}
/*-------------------------------------------------
C & E Bootleg Board for Sheng Huo Lie Zhuan
Games: Jing Ke Xin Zhuan, Sheng Huo Lie Zhuan
Simple Mapper: writes to 0x4020-0x5fff sets prg32 to
data>>4 and chr8 to data&f. We currently do not map
writes to 0x4020-0x40ff (to do: verify if this produces
issues)
iNES: mapper 240
In MESS: Supported.
-------------------------------------------------*/
void nes_cne_shlz_device::write_l(offs_t offset, uint8_t data)
{
LOG_MMC(("cne_shlz write_l, offset: %04x, data: %02x\n", offset, data));
prg32(data >> 4);
chr8(data & 0x0f, CHRROM);
}
| 22.257919
| 127
| 0.603985
|
Robbbert
|
c81f7ec1089411b0df479216d500b675ca1b6ff4
| 399
|
cpp
|
C++
|
docs/parallel/concrt/codesnippet/CPP/best-practices-in-the-parallel-patterns-library_8.cpp
|
bobbrow/cpp-docs
|
769b186399141c4ea93400863a7d8463987bf667
|
[
"CC-BY-4.0",
"MIT"
] | 965
|
2017-06-25T23:57:11.000Z
|
2022-03-31T14:17:32.000Z
|
docs/parallel/concrt/codesnippet/CPP/best-practices-in-the-parallel-patterns-library_8.cpp
|
bobbrow/cpp-docs
|
769b186399141c4ea93400863a7d8463987bf667
|
[
"CC-BY-4.0",
"MIT"
] | 3,272
|
2017-06-24T00:26:34.000Z
|
2022-03-31T22:14:07.000Z
|
docs/parallel/concrt/codesnippet/CPP/best-practices-in-the-parallel-patterns-library_8.cpp
|
bobbrow/cpp-docs
|
769b186399141c4ea93400863a7d8463987bf667
|
[
"CC-BY-4.0",
"MIT"
] | 951
|
2017-06-25T12:36:14.000Z
|
2022-03-26T22:49:06.000Z
|
// Performs the given work function on the data element of the tree and
// on each child.
template<class Function>
void tree::for_all(Function& action)
{
// Perform the action on each child.
parallel_for_each(begin(_children), end(_children), [&](tree& child) {
child.for_all(action);
});
// Perform the action on this node.
action(*this);
}
| 30.692308
| 76
| 0.626566
|
bobbrow
|
c81fe98c66e0a10ea0fb3ed08c3f4a34de5072df
| 2,545
|
cpp
|
C++
|
Online Judges/Huxley/955OLabirintoDoKruskaltauro.cpp
|
NelsonGomesNeto/ProgramC
|
e743b1b869f58f7f3022d18bac00c5e0b078562e
|
[
"MIT"
] | 3
|
2018-12-18T13:39:42.000Z
|
2021-06-23T18:05:18.000Z
|
Online Judges/Huxley/955OLabirintoDoKruskaltauro.cpp
|
NelsonGomesNeto/ProgramC
|
e743b1b869f58f7f3022d18bac00c5e0b078562e
|
[
"MIT"
] | 1
|
2018-11-02T21:32:40.000Z
|
2018-11-02T22:47:12.000Z
|
Online Judges/Huxley/955OLabirintoDoKruskaltauro.cpp
|
NelsonGomesNeto/ProgramC
|
e743b1b869f58f7f3022d18bac00c5e0b078562e
|
[
"MIT"
] | 6
|
2018-10-27T14:07:52.000Z
|
2019-11-14T13:49:29.000Z
|
#include <bits/stdc++.h>
#include <limits.h>
using namespace std;
#define pb(a) push_back(a)
#define mp(a,b) make_pair(a,b)
#define inf INT_MAX
int waitTime(int period, int tempo)
{
return(period - tempo % period);
}
void dijkstra(vector<vector<pair<int, int> > > graph, int **cost, int start, int period)
{
for (int i = 0; i < period; i ++)
cost[start][i] = 0;
priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > pq;
pq.push({cost[start][0], start});
while (!pq.empty())
{
int tempo = pq.top().first, v = pq.top().second; pq.pop();
for (auto u : graph[v])
{
if (u.second == 0 || tempo % u.second == 0)
{
if (tempo + 1 < cost[u.first][(tempo + 1) % period])
{
cost[u.first][(tempo + 1) % period] = tempo + 1;
pq.push({tempo + 1, u.first});
}
}
else
{
int timeToWait = waitTime(u.second, tempo);
if (tempo + timeToWait + 1 < cost[u.first][(tempo + timeToWait + 1) % period])
{
cost[u.first][(tempo + timeToWait + 1) % period] = tempo + timeToWait + 1;
pq.push({tempo + timeToWait + 1, u.first});
}
}
}
}
}
int main()
{
int run = 0, tests; scanf("%d", &tests);
while (run < tests)
{
int y, x; scanf("%d %d", &y, &x);
vector<vector<pair<int, int> > > graph(y*x);
int totalSize = y*x;
for (int i = 0; i < totalSize; i ++)
{
char line[10];
scanf("%s", line);
for (int j = 0; line[j] != '\0'; j ++)
{
if (line[j] == 'N')
graph[i].pb(mp(i - x, 0));
else if (line[j] == 'E')
graph[i].pb(mp(i + 1, 0));
else if (line[j] == 'S')
graph[i].pb(mp(i + x, 0));
else // 'W'
graph[i].pb(mp(i - 1, 0));
}
}
int portals, period; scanf("%d %d", &portals, &period);
for (int i = 0; i < portals; i ++)
{
int ui, uj, vi, vj; scanf("%d %d %d %d", &ui, &uj, &vi, &vj);
graph[ui*x + uj].pb(mp(vi*x + vj, period));
}
int **cost = (int**) malloc(totalSize * sizeof(int*));
for (int i = 0; i < totalSize; i ++)
{
cost[i] = (int*) malloc(period * sizeof(int));
for (int j = 0; j < period; j ++)
cost[i][j] = inf;
}
dijkstra(graph, cost, 0, period);
int smallestTime = inf;
for (int i = 0; i < period; i ++)
smallestTime = min(smallestTime, cost[totalSize - 1][i]);
printf("%d: %d\n", run, smallestTime);
free(cost);
run ++;
}
return(0);
}
| 25.969388
| 88
| 0.489194
|
NelsonGomesNeto
|
c820581005b20220c023f536b9d1545fd55bf07a
| 5,608
|
cpp
|
C++
|
modules/juce_dsp/processors/juce_ProcessorChain_test.cpp
|
luzpaz/JUCE
|
2b16c1b94c90d0db3072f6dc9da481a9484d0435
|
[
"ISC"
] | null | null | null |
modules/juce_dsp/processors/juce_ProcessorChain_test.cpp
|
luzpaz/JUCE
|
2b16c1b94c90d0db3072f6dc9da481a9484d0435
|
[
"ISC"
] | null | null | null |
modules/juce_dsp/processors/juce_ProcessorChain_test.cpp
|
luzpaz/JUCE
|
2b16c1b94c90d0db3072f6dc9da481a9484d0435
|
[
"ISC"
] | null | null | null |
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2022 - Raw Material Software Limited
JUCE is an open source library subject to commercial or open-source
licensing.
By using JUCE, you agree to the terms of both the JUCE 7 End-User License
Agreement and JUCE Privacy Policy.
End User License Agreement: www.juce.com/juce-7-licence
Privacy Policy: www.juce.com/juce-privacy-policy
Or: You may also use this code under the terms of the GPL v3 (see
www.gnu.org/licenses).
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
namespace juce
{
namespace dsp
{
class ProcessorChainTest : public UnitTest
{
template <int AddValue>
struct MockProcessor
{
void prepare (const ProcessSpec&) noexcept { isPrepared = true; }
void reset() noexcept { isReset = true; }
template <typename Context>
void process (const Context& context) noexcept
{
bufferWasClear = context.getInputBlock().getSample (0, 0) == 0;
if (! context.isBypassed)
context.getOutputBlock().add (AddValue);
}
bool isPrepared = false;
bool isReset = false;
bool bufferWasClear = false;
};
public:
ProcessorChainTest()
: UnitTest ("ProcessorChain", UnitTestCategories::dsp) {}
void runTest() override
{
beginTest ("After calling setBypass, processor is bypassed");
{
ProcessorChain<MockProcessor<1>, MockProcessor<2>> chain;
setBypassed<0> (chain, true);
expect (isBypassed<0> (chain));
setBypassed<0> (chain, false);
expect (! isBypassed<0> (chain));
setBypassed<1> (chain, true);
expect (isBypassed<1> (chain));
setBypassed<1> (chain, false);
expect (! isBypassed<1> (chain));
}
beginTest ("After calling prepare, all processors are prepared");
{
ProcessorChain<MockProcessor<1>, MockProcessor<2>> chain;
expect (! get<0> (chain).isPrepared);
expect (! get<1> (chain).isPrepared);
chain.prepare (ProcessSpec{});
expect (get<0> (chain).isPrepared);
expect (get<1> (chain).isPrepared);
}
beginTest ("After calling reset, all processors are reset");
{
ProcessorChain<MockProcessor<1>, MockProcessor<2>> chain;
expect (! get<0> (chain).isReset);
expect (! get<1> (chain).isReset);
chain.reset();
expect (get<0> (chain).isReset);
expect (get<1> (chain).isReset);
}
beginTest ("After calling process, all processors contribute to processing");
{
ProcessorChain<MockProcessor<1>, MockProcessor<2>> chain;
AudioBuffer<float> buffer (1, 1);
AudioBlock<float> block (buffer);
ProcessContextReplacing<float> context (block);
block.clear();
chain.process (context);
expectEquals (buffer.getSample (0, 0), 3.0f);
expect (get<0> (chain).bufferWasClear);
expect (! get<1> (chain).bufferWasClear);
setBypassed<0> (chain, true);
block.clear();
chain.process (context);
expectEquals (buffer.getSample (0, 0), 2.0f);
expect (get<0> (chain).bufferWasClear);
expect (get<1> (chain).bufferWasClear);
setBypassed<1> (chain, true);
block.clear();
chain.process (context);
expectEquals (buffer.getSample (0, 0), 0.0f);
expect (get<0> (chain).bufferWasClear);
expect (get<1> (chain).bufferWasClear);
setBypassed<0> (chain, false);
block.clear();
chain.process (context);
expectEquals (buffer.getSample (0, 0), 1.0f);
expect (get<0> (chain).bufferWasClear);
expect (! get<1> (chain).bufferWasClear);
}
beginTest ("Chains with trailing items that only support replacing contexts can be built");
{
AudioBuffer<float> inBuf (1, 1), outBuf (1, 1);
juce::dsp::AudioBlock<float> in (inBuf), out (outBuf);
struct OnlyReplacing
{
void prepare (const juce::dsp::ProcessSpec&) {}
void process (const juce::dsp::ProcessContextReplacing<float>& c)
{
c.getOutputBlock().multiplyBy (2.0f);
}
void reset() {}
};
{
juce::dsp::ProcessorChain<juce::dsp::Gain<float>, OnlyReplacing, OnlyReplacing> c;
juce::dsp::ProcessContextNonReplacing<float> context (in, out);
get<0> (c).setGainLinear (1.0f);
c.prepare (ProcessSpec{});
inBuf.setSample (0, 0, 1.0f);
c.process (context);
expectEquals (outBuf.getSample (0, 0), 4.0f);
}
}
}
};
static ProcessorChainTest processorChainUnitTest;
} // namespace dsp
} // namespace juce
| 33.380952
| 100
| 0.532275
|
luzpaz
|
c821041336f42b23b4131c3abccb6bced4e64d39
| 7,363
|
cpp
|
C++
|
winston/external/asio/src/examples/cpp11/operations/composed_3.cpp
|
danie1kr/winston
|
18fe865dc59e8315cb1d85c6fa60c4ddeaf83202
|
[
"MIT"
] | 172
|
2018-10-31T13:47:10.000Z
|
2022-02-21T12:08:20.000Z
|
winston/external/asio/src/examples/cpp11/operations/composed_3.cpp
|
danie1kr/winston
|
18fe865dc59e8315cb1d85c6fa60c4ddeaf83202
|
[
"MIT"
] | 51
|
2018-11-01T12:46:25.000Z
|
2021-12-14T15:16:15.000Z
|
winston/external/asio/src/examples/cpp11/operations/composed_3.cpp
|
danie1kr/winston
|
18fe865dc59e8315cb1d85c6fa60c4ddeaf83202
|
[
"MIT"
] | 72
|
2018-10-31T13:50:02.000Z
|
2022-03-14T09:10:35.000Z
|
//
// composed_3.cpp
// ~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2021 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// 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 <asio/bind_executor.hpp>
#include <asio/io_context.hpp>
#include <asio/ip/tcp.hpp>
#include <asio/use_future.hpp>
#include <asio/write.hpp>
#include <cstring>
#include <functional>
#include <iostream>
#include <string>
#include <type_traits>
#include <utility>
using asio::ip::tcp;
// NOTE: This example requires the new asio::async_initiate function. For
// an example that works with the Networking TS style of completion tokens,
// please see an older version of asio.
//------------------------------------------------------------------------------
// In this composed operation we repackage an existing operation, but with a
// different completion handler signature. The asynchronous operation
// requirements are met by delegating responsibility to the underlying
// operation.
// In addition to determining the mechanism by which an asynchronous operation
// delivers its result, a completion token also determines the time when the
// operation commences. For example, when the completion token is a simple
// callback the operation commences before the initiating function returns.
// However, if the completion token's delivery mechanism uses a future, we
// might instead want to defer initiation of the operation until the returned
// future object is waited upon.
//
// To enable this, when implementing an asynchronous operation we must package
// the initiation step as a function object.
struct async_write_message_initiation
{
// The initiation function object's call operator is passed the concrete
// completion handler produced by the completion token. This completion
// handler matches the asynchronous operation's completion handler signature,
// which in this example is:
//
// void(std::error_code error)
//
// The initiation function object also receives any additional arguments
// required to start the operation. (Note: We could have instead passed these
// arguments as members in the initiaton function object. However, we should
// prefer to propagate them as function call arguments as this allows the
// completion token to optimise how they are passed. For example, a lazy
// future which defers initiation would need to make a decay-copy of the
// arguments, but when using a simple callback the arguments can be trivially
// forwarded straight through.)
template <typename CompletionHandler>
void operator()(CompletionHandler&& completion_handler,
tcp::socket& socket, const char* message) const
{
// The async_write operation has a completion handler signature of:
//
// void(std::error_code error, std::size n)
//
// This differs from our operation's signature in that it is also passed
// the number of bytes transferred as an argument of type std::size_t. We
// will adapt our completion handler to async_write's completion handler
// signature by using std::bind, which drops the additional argument.
//
// However, it is essential to the correctness of our composed operation
// that we preserve the executor of the user-supplied completion handler.
// The std::bind function will not do this for us, so we must do this by
// first obtaining the completion handler's associated executor (defaulting
// to the I/O executor - in this case the executor of the socket - if the
// completion handler does not have its own) ...
auto executor = asio::get_associated_executor(
completion_handler, socket.get_executor());
// ... and then binding this executor to our adapted completion handler
// using the asio::bind_executor function.
asio::async_write(socket,
asio::buffer(message, std::strlen(message)),
asio::bind_executor(executor,
std::bind(std::forward<CompletionHandler>(
completion_handler), std::placeholders::_1)));
}
};
template <typename CompletionToken>
auto async_write_message(tcp::socket& socket,
const char* message, CompletionToken&& token)
// The return type of the initiating function is deduced from the combination
// of CompletionToken type and the completion handler's signature. When the
// completion token is a simple callback, the return type is always void.
// In this example, when the completion token is asio::yield_context
// (used for stackful coroutines) the return type would be also be void, as
// there is no non-error argument to the completion handler. When the
// completion token is asio::use_future it would be std::future<void>.
-> typename asio::async_result<
typename std::decay<CompletionToken>::type,
void(std::error_code)>::return_type
{
// The asio::async_initiate function takes:
//
// - our initiation function object,
// - the completion token,
// - the completion handler signature, and
// - any additional arguments we need to initiate the operation.
//
// It then asks the completion token to create a completion handler (i.e. a
// callback) with the specified signature, and invoke the initiation function
// object with this completion handler as well as the additional arguments.
// The return value of async_initiate is the result of our operation's
// initiating function.
//
// Note that we wrap non-const reference arguments in std::reference_wrapper
// to prevent incorrect decay-copies of these objects.
return asio::async_initiate<
CompletionToken, void(std::error_code)>(
async_write_message_initiation(),
token, std::ref(socket), message);
}
//------------------------------------------------------------------------------
void test_callback()
{
asio::io_context io_context;
tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
tcp::socket socket = acceptor.accept();
// Test our asynchronous operation using a lambda as a callback.
async_write_message(socket, "Testing callback\r\n",
[](const std::error_code& error)
{
if (!error)
{
std::cout << "Message sent\n";
}
else
{
std::cout << "Error: " << error.message() << "\n";
}
});
io_context.run();
}
//------------------------------------------------------------------------------
void test_future()
{
asio::io_context io_context;
tcp::acceptor acceptor(io_context, {tcp::v4(), 55555});
tcp::socket socket = acceptor.accept();
// Test our asynchronous operation using the use_future completion token.
// This token causes the operation's initiating function to return a future,
// which may be used to synchronously wait for the result of the operation.
std::future<void> f = async_write_message(
socket, "Testing future\r\n", asio::use_future);
io_context.run();
// Get the result of the operation.
try
{
// Get the result of the operation.
f.get();
std::cout << "Message sent\n";
}
catch (const std::exception& e)
{
std::cout << "Error: " << e.what() << "\n";
}
}
//------------------------------------------------------------------------------
int main()
{
test_callback();
test_future();
}
| 38.150259
| 80
| 0.682602
|
danie1kr
|
c82275b68ae3cee945f5187d4807aef8b105eea5
| 10,641
|
cc
|
C++
|
src/msgpass/GlobalSynchronizeDevThr.cc
|
cea-hpc/pattern4gpu
|
bf606708b6a8bad1041369814e8443b7f1dedcef
|
[
"Apache-2.0"
] | 1
|
2022-03-23T10:33:16.000Z
|
2022-03-23T10:33:16.000Z
|
src/msgpass/GlobalSynchronizeDevThr.cc
|
cea-hpc/pattern4gpu
|
bf606708b6a8bad1041369814e8443b7f1dedcef
|
[
"Apache-2.0"
] | null | null | null |
src/msgpass/GlobalSynchronizeDevThr.cc
|
cea-hpc/pattern4gpu
|
bf606708b6a8bad1041369814e8443b7f1dedcef
|
[
"Apache-2.0"
] | null | null | null |
#include "msgpass/VarSyncMng.h"
#include "msgpass/PackTransfer.h"
#include <arcane/IParallelMng.h>
#include <arcane/MeshVariableScalarRef.h>
#include <arcane/MeshVariableArrayRef.h>
#include <arcane/VariableBuildInfo.h>
#include <thread>
#include <mpi.h>
/*---------------------------------------------------------------------------*/
/* Equivalent à un var.synchronize() où var est une variable globale */
/* (i.e. non multi-mat) en utilisant des comms non-bloquantes dans des taches*/
/*---------------------------------------------------------------------------*/
template<typename MeshVariableRefT>
void VarSyncMng::globalSynchronizeDevThr(MeshVariableRefT var)
{
if (m_nb_nei==0) {
return;
}
using ItemType = typename MeshVariableRefT::ItemType;
using DataType = typename MeshVariableRefT::DataType;
SyncItems<ItemType>* sync_items = getSyncItems<ItemType>();
auto nb_owned_item_idx_pn = sync_items->nbOwnedItemIdxPn();
auto nb_ghost_item_idx_pn = sync_items->nbGhostItemIdxPn();
auto owned_item_idx_pn = sync_items->ownedItemIdxPn();
auto ghost_item_idx_pn = sync_items->ghostItemIdxPn();
// Pour un ItemType donné, combien de DataType sont utilisés ? => degree
Integer degree = get_var_degree(var);
m_sync_buffers->resetBuf();
// On prévoit une taille max du buffer qui va contenir tous les messages
m_sync_buffers->addEstimatedMaxSz<DataType>(nb_owned_item_idx_pn, degree);
m_sync_buffers->addEstimatedMaxSz<DataType>(nb_ghost_item_idx_pn, degree);
// Le buffer de tous les messages est réalloué si pas assez de place
m_sync_buffers->allocIfNeeded();
// On récupère les adresses et tailles des buffers d'envoi et de réception
// sur l'HOTE (_h et LM_HostMem)
auto buf_snd_h = m_sync_buffers->multiBufView<DataType>(nb_owned_item_idx_pn, degree, 0);
auto buf_rcv_h = m_sync_buffers->multiBufView<DataType>(nb_ghost_item_idx_pn, degree, 0);
// On récupère les adresses et tailles des buffers d'envoi et de réception
// sur le DEVICE (_d et LM_DevMem)
auto buf_snd_d = m_sync_buffers->multiBufView<DataType>(nb_owned_item_idx_pn, degree, 1);
auto buf_rcv_d = m_sync_buffers->multiBufView<DataType>(nb_ghost_item_idx_pn, degree, 1);
#define USE_MPI_REQUEST
#ifdef USE_MPI_REQUEST
//#warning "USE_MPI_REQUEST"
using RequestType = MPI_Request;
#else
using RequestType = Parallel::Request;
#endif
// L'échange proprement dit des valeurs de var
Integer tag=1000;
UniqueArray<RequestType> requests(2*m_nb_nei);
IntegerUniqueArray msg_types(2*m_nb_nei); // nature des messages
// On amorce les réceptions
for(Integer inei=0 ; inei<m_nb_nei ; ++inei) {
Int32 rank_nei = m_neigh_ranks[inei]; // le rang du inei-ième voisin
// On amorce la réception
auto byte_buf_rcv_h = buf_rcv_h.byteBuf(inei); // le buffer de réception pour inei
#ifdef USE_MPI_REQUEST
MPI_Irecv(byte_buf_rcv_h.data(), byte_buf_rcv_h.size(), MPI_BYTE, rank_nei, tag,
MPI_COMM_WORLD, &(requests[inei]));
#else
requests[inei] = m_pm->recv(byte_buf_rcv_h, rank_nei, /*blocking=*/false);
#endif
msg_types[inei] = inei+1; // >0 pour la réception
}
// La tâche à effectuer pour un voisin
auto lbd_sender = [&](Integer inei, RunQueue& queue) {
Int32 rank_nei = m_neigh_ranks[inei]; // le rang du inei-ième voisin
auto byte_buf_snd_d = buf_snd_d.byteBuf(inei); // le buffer d'envoi pour inei sur le DEVICE
auto byte_buf_snd_h = buf_snd_h.byteBuf(inei); // le buffer d'envoi pour inei sur l'HOTE
// "byte_buf_snd_d <= var"
async_pack_var2buf(owned_item_idx_pn[inei], var, byte_buf_snd_d, queue);
// transfert buf_snd_d[inei] => buf_snd_h[inei]
async_transfer(byte_buf_snd_h, byte_buf_snd_d, queue);
// attendre que la copie sur l'hôte soit terminée pour envoyer les messages
queue.barrier();
// On amorce les envois
#ifdef USE_MPI_REQUEST
MPI_Isend(byte_buf_snd_h.data(), byte_buf_snd_h.size(), MPI_BYTE, rank_nei, tag,
MPI_COMM_WORLD, &(requests[m_nb_nei+inei]));
#else
requests[m_nb_nei+inei] = m_pm->send(byte_buf_snd_h, rank_nei, /*blocking=*/false);
#endif
msg_types[m_nb_nei+inei] = -inei-1; // <0 pour l'envoi
};
//#define USE_THR_SENDER
#ifdef USE_THR_SENDER
#warning "USE_THR_SENDER"
UniqueArray<std::thread*> thr_sender(m_nb_nei);
for(Integer inei=0 ; inei<m_nb_nei ; ++inei) {
thr_sender[inei] =
new std::thread(lbd_sender, inei, std::ref(m_neigh_queues->queue(inei)));
}
// On attend la fin de tous les threads
for(auto thr : thr_sender) {
thr->join();
delete thr;
}
#else
// On lance en SEQUENTIEL
for(Integer inei=0 ; inei<m_nb_nei ; ++inei) {
lbd_sender(inei, m_neigh_queues->queue(inei));
}
#endif
// Tache qui unpack les données du buffer reçues par un voisin inei
// copie de var_dev dans buf_dev
// puis transfert buf_dev => buf_hst
auto lbd_unpacker = [&](Integer inei, RunQueue& queue) {
auto byte_buf_rcv_h = buf_rcv_h.byteBuf(inei); // buffer des données reçues sur l'HOTE
auto byte_buf_rcv_d = buf_rcv_d.byteBuf(inei); // buffer des données reçues à transférer sur le DEVICE
// transfert buf_rcv_h[inei] => buf_rcv_d[inei]
async_transfer(byte_buf_rcv_d, byte_buf_rcv_h, queue);
// "var <= buf_rcv_d[inei]"
async_unpack_buf2var(ghost_item_idx_pn[inei], byte_buf_rcv_d, var, queue);
// attendre que les copies soient terminées sur GPU
queue.barrier();
};
UniqueArray<std::thread*> thr_unpacker;
ARCANE_ASSERT(2*m_nb_nei==requests.size(),
("Le nb de requetes n'est pas egal à 2 fois le nb de voisins"));
UniqueArray<RequestType> requests2(2*m_nb_nei);
IntegerUniqueArray msg_types2(2*m_nb_nei);
UniqueArray<bool> is_done_req(2*m_nb_nei);
#ifdef USE_MPI_REQUEST
IntegerUniqueArray array_of_indices(2*m_nb_nei);
#endif
// On utilise des vues pour éviter de réallouer en permanence des tableaux
ArrayView<RequestType> pending_requests(requests.view());
ArrayView<Integer> pending_types(msg_types.view());
ArrayView<RequestType> upd_pending_requests(requests2.view());
ArrayView<Integer> upd_pending_types(msg_types2.view());
ArrayView<RequestType> tmp_pending_requests;
ArrayView<Integer> tmp_pending_types;
Integer nb_iter_wait_some = 0;
Integer nb_pending_rcv = m_nb_nei;
while(nb_pending_rcv>0) {
Integer nb_pending_req = pending_requests.size();
// On dimenensionne is_done_requests au nb de requêtes d'avant waitSomeRequests
// et on initialise à false
ArrayView<bool> is_done_requests(is_done_req.subView(0, nb_pending_req));
for(Integer ireq=0 ; ireq<nb_pending_req ; ++ireq) {
is_done_requests[ireq]=false;
}
// Attente de quelques requetes
#ifdef USE_MPI_REQUEST
Integer nb_req_done=0;
MPI_Waitsome(pending_requests.size(), pending_requests.data(),
&nb_req_done, array_of_indices.data(), MPI_STATUSES_IGNORE);
IntegerArrayView done_indexes(array_of_indices.subView(0, nb_req_done));
#else
IntegerUniqueArray done_indexes = m_pm->waitSomeRequests(pending_requests);
#endif
for(Integer idone_req : done_indexes) {
if (pending_types[idone_req] > 0) { // >0 signifie que c'est une requête de reception
nb_pending_rcv--; // on une requete de reception en moins
// On récupère l'indice du voisin
Integer inei = pending_types[idone_req]-1;
ARCANE_ASSERT(inei>=0 && inei<m_nb_nei, ("Mauvais indice de voisin"));
// Maintenant qu'on a reçu le buffer pour le inei-ième voisin,
// on unpack les donnees dans un thread
//#define USE_THR_UNPACKER
#ifdef USE_THR_UNPACKER
#warning "USE_THR_UNPACKER"
thr_unpacker.add(
new std::thread(lbd_unpacker, inei, std::ref(m_neigh_queues->queue(inei)))
);
#else
lbd_unpacker(inei, m_neigh_queues->queue(inei));
#endif
}
is_done_requests[idone_req] = true;
}
// Il faut créer le nouveau tableau de requêtes pending dans upd_*
Integer upd_nb_pending_req=0;
for(Integer ireq=0 ; ireq<nb_pending_req ; ++ireq) {
if (!is_done_requests[ireq]) {
upd_pending_requests[upd_nb_pending_req]=pending_requests[ireq];
upd_pending_types [upd_nb_pending_req]=pending_types[ireq];
upd_nb_pending_req++;
}
}
// On échange les vues pour qu'à l'itération suivante
// pending_requests pointe vers upd_pending_types
tmp_pending_requests = upd_pending_requests.subView(0, upd_nb_pending_req);
upd_pending_requests = pending_requests;
pending_requests = tmp_pending_requests;
tmp_pending_types = upd_pending_types.subView(0, upd_nb_pending_req);
upd_pending_types = pending_types;
pending_types = tmp_pending_types;
nb_iter_wait_some++;
#if 0
std::ostringstream ostr;
ostr << "P=" << m_pm->commRank()
<< ", iter_wait_some=" << nb_iter_wait_some
<< ", nb_done=" << done_indexes.size();
std::cout << ostr.str() << std::endl;
#endif
}
// Ici, toutes les requetes de receptions sont forcement terminées
// (condition de la boucle while précédente)
// Mais il peut rester encore des requetes d'envoi en cours
if (pending_requests.size()) {
// Normalement, il ne reste que des requêtes d'envois
ARCANE_ASSERT(pending_requests.size()<=m_nb_nei,
("Il ne peut pas rester un nb de requetes d'envoi supérieur au nb de voisins"));
for(Integer msg_type : pending_types) {
ARCANE_ASSERT(msg_type<0,
("Un message d'envoi doit avoir un type négatif ce qui n'est pas le cas"));
}
#if 0
std::ostringstream ostr;
ostr << "P=" << m_pm->commRank()
<< ", WaitAll pending_requests.size()=" << pending_requests.size();
std::cout << ostr.str() << std::endl;
#endif
#ifdef USE_MPI_REQUEST
MPI_Waitall(pending_requests.size(), pending_requests.data(), MPI_STATUSES_IGNORE);
#else
m_pm->waitAllRequests(pending_requests);
#endif
}
#ifdef USE_THR_UNPACKER
#warning "USE_THR_UNPACKER : join"
// On attend la fin de tous les threads unpackers
for(auto thr : thr_unpacker) {
thr->join();
delete thr;
}
#endif
}
/*---------------------------------------------------------------------------*/
/* INSTANCIATIONS STATIQUES */
/*---------------------------------------------------------------------------*/
#define INST_VAR_SYNC_MNG_GLOBAL_SYNCHRONIZE_DEV_THR(__MeshVariableRefT__) \
template void VarSyncMng::globalSynchronizeDevThr(__MeshVariableRefT__ var)
INST_VAR_SYNC_MNG_GLOBAL_SYNCHRONIZE_DEV_THR(VariableCellReal);
INST_VAR_SYNC_MNG_GLOBAL_SYNCHRONIZE_DEV_THR(VariableNodeReal3);
| 36.56701
| 106
| 0.698807
|
cea-hpc
|
c824e57865e8752c5e9f6a7d37207b4e21d82cee
| 1,095
|
cpp
|
C++
|
coj.uci.cu/TobbyandSequence.cpp
|
facug91/OJ-Solutions
|
9aa55be066ce5596e4e64737c28cd3ff84e092fe
|
[
"Apache-2.0"
] | 6
|
2016-09-10T03:16:34.000Z
|
2020-04-07T14:45:32.000Z
|
coj.uci.cu/TobbyandSequence.cpp
|
facug91/OJ-Solutions
|
9aa55be066ce5596e4e64737c28cd3ff84e092fe
|
[
"Apache-2.0"
] | null | null | null |
coj.uci.cu/TobbyandSequence.cpp
|
facug91/OJ-Solutions
|
9aa55be066ce5596e4e64737c28cd3ff84e092fe
|
[
"Apache-2.0"
] | 2
|
2018-08-11T20:55:35.000Z
|
2020-01-15T23:23:11.000Z
|
/*
By: facug91
From: http://coj.uci.cu/24h/problem.xhtml?abb=2972
Name: Tobby and Sequence
Number: 2972
Date: 11/07/2014
*/
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <vector>
#include <queue>
#include <deque>
#include <set>
#include <map>
#include <iterator>
#include <utility>
#include <list>
#include <stack>
#include <iomanip>
#include <bitset>
#define MAX_INT 2147483647
#define MAX_LONG 9223372036854775807ll
#define MAX_ULONG 18446744073709551615ull
#define MAX_DBL 1.7976931348623158e+308
#define EPS 1e-9
#define _log2(x) log(x) * 1.44269504088896340736
//const long double PI = 2*acos(0);
#define INF 1000000000
using namespace std;
int n, seq[1005];
int main () {
int t, i, j;
seq[0] = 1;
for (i=1; i<1005; i++)
seq[i] = seq[i-1]+i+1;
reverse(seq, seq+1005);
while (scanf("%d", &n) != EOF) {
printf("%d", seq[0]);
for (i=1; i<n; i++)
printf(" %d", seq[i]);
printf("\n");
}
return 0;
}
| 17.95082
| 52
| 0.627397
|
facug91
|
c825e7f6b100bab1168fd79d5f5f1a856dc46b24
| 2,232
|
cpp
|
C++
|
OVFP426/Plugins/OVFPPlugin/Source/OVFPPlugin/Private/OVFPPluginStyle.cpp
|
ACaesuraIsStillMusic/Open-Virtual-Film-Project
|
f4cfb901da32d8101b7635aa5caed3fc075d6dd7
|
[
"Unlicense",
"MIT"
] | 15
|
2020-12-11T17:00:02.000Z
|
2022-03-08T04:43:56.000Z
|
OVFP425/Plugins/OVFPPlugin/Source/OVFPPlugin/Private/OVFPPluginStyle.cpp
|
ACaesuraIsStillMusic/Open-Virtual-Film-Project
|
f4cfb901da32d8101b7635aa5caed3fc075d6dd7
|
[
"Unlicense",
"MIT"
] | null | null | null |
OVFP425/Plugins/OVFPPlugin/Source/OVFPPlugin/Private/OVFPPluginStyle.cpp
|
ACaesuraIsStillMusic/Open-Virtual-Film-Project
|
f4cfb901da32d8101b7635aa5caed3fc075d6dd7
|
[
"Unlicense",
"MIT"
] | 2
|
2020-12-10T22:54:05.000Z
|
2021-07-22T10:25:22.000Z
|
// Copyright Dan Corrigan 2020 All Rights Reserved.
#include "OVFPPluginStyle.h"
#include "OVFPPlugin.h"
#include "Framework/Application/SlateApplication.h"
#include "Styling/SlateStyleRegistry.h"
#include "Slate/SlateGameResources.h"
#include "Interfaces/IPluginManager.h"
TSharedPtr< FSlateStyleSet > FOVFPPluginStyle::StyleInstance = NULL;
void FOVFPPluginStyle::Initialize()
{
if (!StyleInstance.IsValid())
{
StyleInstance = Create();
FSlateStyleRegistry::RegisterSlateStyle(*StyleInstance);
}
}
void FOVFPPluginStyle::Shutdown()
{
FSlateStyleRegistry::UnRegisterSlateStyle(*StyleInstance);
ensure(StyleInstance.IsUnique());
StyleInstance.Reset();
}
FName FOVFPPluginStyle::GetStyleSetName()
{
static FName StyleSetName(TEXT("OVFPPluginStyle"));
return StyleSetName;
}
#define IMAGE_BRUSH( RelativePath, ... ) FSlateImageBrush( Style->RootToContentDir( RelativePath, TEXT(".png") ), __VA_ARGS__ )
#define BOX_BRUSH( RelativePath, ... ) FSlateBoxBrush( Style->RootToContentDir( RelativePath, TEXT(".png") ), __VA_ARGS__ )
#define BORDER_BRUSH( RelativePath, ... ) FSlateBorderBrush( Style->RootToContentDir( RelativePath, TEXT(".png") ), __VA_ARGS__ )
#define TTF_FONT( RelativePath, ... ) FSlateFontInfo( Style->RootToContentDir( RelativePath, TEXT(".ttf") ), __VA_ARGS__ )
#define OTF_FONT( RelativePath, ... ) FSlateFontInfo( Style->RootToContentDir( RelativePath, TEXT(".otf") ), __VA_ARGS__ )
const FVector2D Icon16x16(16.0f, 16.0f);
const FVector2D Icon20x20(20.0f, 20.0f);
const FVector2D Icon40x40(40.0f, 40.0f);
TSharedRef< FSlateStyleSet > FOVFPPluginStyle::Create()
{
TSharedRef< FSlateStyleSet > Style = MakeShareable(new FSlateStyleSet("OVFPPluginStyle"));
Style->SetContentRoot(IPluginManager::Get().FindPlugin("OVFPPlugin")->GetBaseDir() / TEXT("Resources"));
Style->Set("OVFPPlugin.PluginAction", new IMAGE_BRUSH(TEXT("ButtonIcon_40x"), Icon40x40));
return Style;
}
#undef IMAGE_BRUSH
#undef BOX_BRUSH
#undef BORDER_BRUSH
#undef TTF_FONT
#undef OTF_FONT
void FOVFPPluginStyle::ReloadTextures()
{
if (FSlateApplication::IsInitialized())
{
FSlateApplication::Get().GetRenderer()->ReloadTextureResources();
}
}
const ISlateStyle& FOVFPPluginStyle::Get()
{
return *StyleInstance;
}
| 31
| 129
| 0.765681
|
ACaesuraIsStillMusic
|
c826867517354d4f1c4da53834c26f2709b20b43
| 1,615
|
cpp
|
C++
|
Sample14_1/app/src/main/cpp/bndev/ThreadTask.cpp
|
luopan007/Vulkan_Develpment_Samples
|
1be40631e3b2d44aae7140f0ef17c5643a86545e
|
[
"Unlicense"
] | 5
|
2020-11-20T00:06:30.000Z
|
2021-12-07T11:39:17.000Z
|
Sample15_2/app/src/main/cpp/bndev/ThreadTask.cpp
|
luopan007/Vulkan_Develpment_Samples
|
1be40631e3b2d44aae7140f0ef17c5643a86545e
|
[
"Unlicense"
] | null | null | null |
Sample15_2/app/src/main/cpp/bndev/ThreadTask.cpp
|
luopan007/Vulkan_Develpment_Samples
|
1be40631e3b2d44aae7140f0ef17c5643a86545e
|
[
"Unlicense"
] | 7
|
2021-01-01T10:54:58.000Z
|
2022-01-13T02:21:54.000Z
|
#include "ThreadTask.h"
#include "MyVulkanManager.h"
#include "ShaderQueueSuit_CommonTexLight.h"
void ThreadTask::doTask()
{
MyVulkanManager::init_vulkan_instance();
MyVulkanManager::enumerate_vulkan_phy_devices();
MyVulkanManager::create_vulkan_devices();
MyVulkanManager::create_vulkan_CommandBuffer();
MyVulkanManager::init_queue();
MyVulkanManager::create_vulkan_swapChain();
MyVulkanManager::create_vulkan_DepthBuffer();
MyVulkanManager::create_vulkan_SelfColorBuffer();
MyVulkanManager::create_render_pass_screen();
MyVulkanManager::create_render_pass_self();
MyVulkanManager::create_frame_buffer_screen();
MyVulkanManager::create_frame_buffer_self();
MyVulkanManager::init_texture();
MyVulkanManager::createDrawableObject();
MyVulkanManager::initPipeline();
MyVulkanManager::createFence();
MyVulkanManager::initPresentInfo();
MyVulkanManager::initMatrixAndLight();
MyVulkanManager::drawObject();
MyVulkanManager::destroyPipeline();
MyVulkanManager::destroyDrawableObject();
MyVulkanManager::destroy_textures();
MyVulkanManager::destroy_vulkan_SelfColorBuffer();
MyVulkanManager::destroy_frame_buffer();
MyVulkanManager::destroy_render_pass_self();
MyVulkanManager::destroy_render_pass_screen();
MyVulkanManager::destroy_vulkan_DepthBuffer();
MyVulkanManager::destroy_vulkan_swapChain();
MyVulkanManager::destroy_vulkan_CommandBuffer();
MyVulkanManager::destroy_vulkan_devices();
MyVulkanManager::destroy_vulkan_instance();
}
ThreadTask::ThreadTask()
{
}
ThreadTask:: ~ThreadTask()
{
}
| 37.55814
| 54
| 0.778947
|
luopan007
|
c82831f16eef38e0e073485241d80aa03272da99
| 78
|
cxx
|
C++
|
Modules/ThirdParty/VNL/src/vxl/core/vnl/Templates/vnl_matrix_fixed+double.2.8-.cxx
|
rdsouza10/ITK
|
07cb23f9866768b5f4ee48ebec8766b6e19efc69
|
[
"Apache-2.0"
] | 3
|
2019-11-19T09:47:25.000Z
|
2022-02-24T00:32:31.000Z
|
Modules/ThirdParty/VNL/src/vxl/core/vnl/Templates/vnl_matrix_fixed+double.2.8-.cxx
|
rdsouza10/ITK
|
07cb23f9866768b5f4ee48ebec8766b6e19efc69
|
[
"Apache-2.0"
] | 1
|
2019-03-18T14:19:49.000Z
|
2020-01-11T13:54:33.000Z
|
Modules/ThirdParty/VNL/src/vxl/core/vnl/Templates/vnl_matrix_fixed+double.2.8-.cxx
|
rdsouza10/ITK
|
07cb23f9866768b5f4ee48ebec8766b6e19efc69
|
[
"Apache-2.0"
] | 1
|
2022-02-24T00:32:36.000Z
|
2022-02-24T00:32:36.000Z
|
#include <vnl/vnl_matrix_fixed.hxx>
VNL_MATRIX_FIXED_INSTANTIATE(double,2,8);
| 26
| 41
| 0.833333
|
rdsouza10
|
c829ca837e3e275e946ac03ba0341d1c7314fdec
| 919
|
cpp
|
C++
|
ch16/ex16.5/main.cpp
|
regconfi/Cpp-Primer
|
6e59f24f4c7f3be4f679b7d29084d9d859a463d9
|
[
"CC0-1.0"
] | 46
|
2015-07-07T11:13:12.000Z
|
2022-03-27T10:20:54.000Z
|
ch16/ex16.5/main.cpp
|
lafener/Cpp-Primer
|
8cf1568f2d27622bce2d41493158f58527e5072f
|
[
"CC0-1.0"
] | 11
|
2015-03-10T12:52:06.000Z
|
2015-04-20T12:24:00.000Z
|
ch16/ex16.5/main.cpp
|
lafener/Cpp-Primer
|
8cf1568f2d27622bce2d41493158f58527e5072f
|
[
"CC0-1.0"
] | 65
|
2015-07-01T14:15:48.000Z
|
2021-04-10T08:44:19.000Z
|
/***************************************************************************
* @file main.cpp
* @author Alan.W
* @date 02 Feb 2014
* 13 Oct 2014
* @remark This code is for the exercises from C++ Primer 5th Edition
* @note
***************************************************************************/
//!
//! Exercise 16.5:
//! Write a template version of the print function from § 6.2.4 (p. 217) that
//! takes a reference to an array and can handle arrays of any size and any
//! element type.
//!
#include <iostream>
#include <string>
template<typename Arr>
void print(const Arr& a)
{
for(const auto& elem : a)
std::cout << elem << std::endl;
}
int main()
{
std::string p[] = {"ssss","aaa","ssssss"};
char c[] = {'a','b','c','d'};
int i[] = {1};
print(i);
print(c);
print(p);
std::cout << "\nexit normally\n";
return 0;
}
| 24.184211
| 77
| 0.460283
|
regconfi
|
c829db6408df02dec00f6c8868b7671672578f89
| 6,263
|
cc
|
C++
|
mindspore/core/ops/dynamic_resize_nearest_neighbor.cc
|
httpsgithu/mindspore
|
c29d6bb764e233b427319cb89ba79e420f1e2c64
|
[
"Apache-2.0"
] | 1
|
2022-02-23T09:13:43.000Z
|
2022-02-23T09:13:43.000Z
|
mindspore/core/ops/dynamic_resize_nearest_neighbor.cc
|
949144093/mindspore
|
c29d6bb764e233b427319cb89ba79e420f1e2c64
|
[
"Apache-2.0"
] | null | null | null |
mindspore/core/ops/dynamic_resize_nearest_neighbor.cc
|
949144093/mindspore
|
c29d6bb764e233b427319cb89ba79e420f1e2c64
|
[
"Apache-2.0"
] | null | null | null |
/**
* Copyright 2021 Huawei Technologies Co., Ltd
*
* 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 <string>
#include <algorithm>
#include <memory>
#include <set>
#include <vector>
#include "ops/op_utils.h"
#include "ops/dynamic_resize_nearest_neighbor.h"
#include "utils/check_convert_utils.h"
#include "abstract/ops/primitive_infer_map.h"
#include "mindapi/src/helper.h"
namespace mindspore {
namespace ops {
namespace {
abstract::ShapePtr DynamicResizeNearestNeighborInferShape(const PrimitivePtr &primitive,
const std::vector<AbstractBasePtr> &input_args) {
MS_EXCEPTION_IF_NULL(primitive);
auto prim_name = primitive->name();
auto x_shape_ptr = CheckAndConvertUtils::GetTensorInputShape(prim_name, input_args, 0);
auto x_shape = x_shape_ptr->shape();
const int64_t shape_size = 4;
const int64_t size_size = 2;
(void)CheckAndConvertUtils::CheckInteger("the dimension of input_x", SizeToLong(x_shape.size()), kEqual, shape_size,
prim_name);
auto size = input_args[1];
MS_EXCEPTION_IF_NULL(size);
auto size_v = size->BuildValue();
MS_EXCEPTION_IF_NULL(size_v);
std::vector<int64_t> size_value;
std::vector<int64_t> output_shape;
std::vector<int64_t> min_shape;
std::vector<int64_t> max_shape;
std::vector<int64_t> min_size;
std::vector<int64_t> max_size;
if (size->isa<abstract::AbstractTensor>()) {
if (size_v->isa<tensor::Tensor>()) {
size_value = CheckAndConvertUtils::CheckTensorIntValue("size", size_v, prim_name);
} else {
size_value.push_back(-1);
size_value.push_back(-1);
auto min_value = size->cast<abstract::AbstractTensorPtr>()->get_min_value();
auto max_value = size->cast<abstract::AbstractTensorPtr>()->get_max_value();
if (!min_value || !max_value) {
MS_EXCEPTION(ValueError) << "For 'ResizeNearestNeighbor', inputs['size'] min or max value is can not be empty.";
}
min_size = GetValue<std::vector<int64_t>>(min_value);
max_size = GetValue<std::vector<int64_t>>(max_value);
if (min_size.size() != size_size || max_size.size() != size_size) {
MS_EXCEPTION(ValueError)
<< "For 'ResizeNearestNeighbor', inputs['size'] min and max value size must be 2, but got min: "
<< min_size.size() << ", max: " << max_size.size() << ".";
}
}
} else if (size->isa<abstract::AbstractTuple>()) {
size_value = CheckAndConvertUtils::CheckIntOrTupleInt("size", size_v, prim_name);
}
(void)CheckAndConvertUtils::CheckInteger("the dimension of size", SizeToLong(size_value.size()), kEqual, size_size,
prim_name);
output_shape.push_back(x_shape[0]);
output_shape.push_back(x_shape[1]);
output_shape.push_back(size_value[0]);
output_shape.push_back(size_value[1]);
if (!x_shape_ptr->IsDynamic() && min_size.empty()) {
return std::make_shared<abstract::Shape>(output_shape);
} else if (x_shape_ptr->IsDynamic() && min_size.empty()) {
auto x_min_shape = x_shape_ptr->min_shape();
auto x_max_shape = x_shape_ptr->max_shape();
min_shape.push_back(x_min_shape[0]);
min_shape.push_back(x_min_shape[1]);
min_shape.push_back(size_value[0]);
min_shape.push_back(size_value[1]);
max_shape.push_back(x_max_shape[0]);
max_shape.push_back(x_max_shape[1]);
max_shape.push_back(size_value[0]);
max_shape.push_back(size_value[1]);
} else if (!x_shape_ptr->IsDynamic() && !min_size.empty()) {
min_shape.push_back(x_shape[0]);
min_shape.push_back(x_shape[1]);
min_shape.push_back(min_size[0]);
min_shape.push_back(min_size[1]);
max_shape.push_back(x_shape[0]);
max_shape.push_back(x_shape[1]);
max_shape.push_back(max_size[0]);
max_shape.push_back(max_size[1]);
} else {
auto x_min_shape = x_shape_ptr->min_shape();
auto x_max_shape = x_shape_ptr->max_shape();
min_shape.push_back(x_min_shape[0]);
min_shape.push_back(x_min_shape[1]);
min_shape.push_back(min_size[0]);
min_shape.push_back(min_size[1]);
max_shape.push_back(x_max_shape[0]);
max_shape.push_back(x_max_shape[1]);
max_shape.push_back(max_size[0]);
max_shape.push_back(max_size[1]);
}
return std::make_shared<abstract::Shape>(output_shape, min_shape, max_shape);
}
TypePtr DynamicResizeNearestNeighborInferType(const PrimitivePtr &prim,
const std::vector<AbstractBasePtr> &input_args) {
auto valid_types = common_valid_types;
valid_types.insert(kComplex128);
valid_types.insert(kComplex64);
return CheckAndConvertUtils::CheckTensorTypeValid("x", input_args[0]->BuildType(), valid_types, prim->name());
}
} // namespace
MIND_API_OPERATOR_IMPL(DynamicResizeNearestNeighbor, BaseOperator);
AbstractBasePtr DynamicResizeNearestNeighborInfer(const abstract::AnalysisEnginePtr &, const PrimitivePtr &primitive,
const std::vector<AbstractBasePtr> &input_args) {
auto prim_name = primitive->name();
const int64_t input_num = 2;
(void)CheckAndConvertUtils::CheckInteger("infer", SizeToLong(CheckAndConvertUtils::GetRemoveMonadAbsNum(input_args)),
kEqual, input_num, prim_name);
auto res = abstract::MakeAbstract(DynamicResizeNearestNeighborInferShape(primitive, input_args),
DynamicResizeNearestNeighborInferType(primitive, input_args));
return res;
}
REGISTER_PRIMITIVE_EVAL_IMPL(DynamicResizeNearestNeighbor, prim::kPrimDynamicResizeNearestNeighbor,
DynamicResizeNearestNeighborInfer, nullptr, true);
} // namespace ops
} // namespace mindspore
| 44.735714
| 120
| 0.695673
|
httpsgithu
|
c82ad37e70c228f2baedd5caa9553d6d07b8d2fa
| 277
|
cpp
|
C++
|
benchmark/raycast.cilk.cpp
|
mikerainey/taskparts
|
27d4bdda15a5c370c25df6ce8be1233362107cc8
|
[
"MIT"
] | null | null | null |
benchmark/raycast.cilk.cpp
|
mikerainey/taskparts
|
27d4bdda15a5c370c25df6ce8be1233362107cc8
|
[
"MIT"
] | null | null | null |
benchmark/raycast.cilk.cpp
|
mikerainey/taskparts
|
27d4bdda15a5c370c25df6ce8be1233362107cc8
|
[
"MIT"
] | null | null | null |
#include "cilk.hpp"
#include "raycast.hpp"
int main() {
taskparts::benchmark_cilk([&] { // benchmark
benchmark();
}, [&] { // setup
gen_input();
}, [&] { // teardown
// later: write results to outfile
}, [&] { // reset
reset();
});
return 0;
}
| 17.3125
| 46
| 0.519856
|
mikerainey
|
c82bbdfa543410901a5507226ae6a2c12e406136
| 3,292
|
cc
|
C++
|
cplusplus/leetcode/valid_parentheses/valid_parentheses.cc
|
ASMlover/study
|
5878f862573061f94c5776a351e30270dfd9966a
|
[
"BSD-2-Clause"
] | 22
|
2015-05-18T07:04:36.000Z
|
2021-08-02T03:01:43.000Z
|
cplusplus/leetcode/valid_parentheses/valid_parentheses.cc
|
ASMlover/study
|
5878f862573061f94c5776a351e30270dfd9966a
|
[
"BSD-2-Clause"
] | 1
|
2017-08-31T22:13:57.000Z
|
2017-09-05T15:00:25.000Z
|
cplusplus/leetcode/valid_parentheses/valid_parentheses.cc
|
ASMlover/study
|
5878f862573061f94c5776a351e30270dfd9966a
|
[
"BSD-2-Clause"
] | 6
|
2015-06-06T07:16:12.000Z
|
2021-07-06T13:45:56.000Z
|
// Copyright (c) 2020 ASMlover. 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 ofconditions 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 materialsprovided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <stack>
#include <string_view>
#include "../common.hh"
#include "../harness.hh"
// [ADDR] https://leetcode.com/problems/valid-parentheses/description
//
// Given a string containing just the characters '(', ')', '{', '}', '[' and ']',
// determine if the input string is valid.
//
// An input string is valid if:
//
// Open brackets must be closed by the same type of brackets.
// Open brackets must be closed in the correct order.
// Note that an empty string is also considered valid.
//
// Example 1:
//
// Input: "()"
// Output: true
// Example 2:
//
// Input: "()[]{}"
// Output: true
// Example 3:
//
// Input: "(]"
// Output: false
// Example 4:
//
// Input: "([)]"
// Output: false
// Example 5:
//
// Input: "{[]}"
// Output: true
class ValidParentheses final : public Singleton<ValidParentheses> {
inline bool is_lparen(char c) const noexcept {
return c == '(' || c == '[' || c == '{';
}
inline bool is_rparen(char c) const noexcept {
return c == ')' || c == ']' || c == '}';
}
bool is_match(char c, char expected) const noexcept {
switch (c) {
case ')': return expected == '(';
case ']': return expected == '[';
case '}': return expected == '{';
}
return false;
}
bool is_valid(std::string_view s) const {
std::stack<char> stack;
for (char c : s) {
if (is_lparen(c)) {
stack.push(c);
}
else if (is_rparen(c)) {
char top = stack.top();
stack.pop();
if (!is_match(c, top))
return false;
}
else {
return false;
}
}
return stack.empty();
}
public:
void run() {
HARNESS_TRUE(is_valid("()"));
HARNESS_TRUE(is_valid("()[]{}"));
HARNESS_TRUE(!is_valid("(]"));
HARNESS_TRUE(!is_valid("([)]"));
HARNESS_TRUE(is_valid("{[]}"));
}
};
HARNESS_TEST(ValidParentheses, harness::FakeTester) {
ValidParentheses::get_instance().run();
}
| 28.877193
| 81
| 0.648542
|
ASMlover
|
c82bd1b45b8f3949576cb1a37c6c04ea1f32bbb7
| 21,098
|
cpp
|
C++
|
src/vm/contractimpl.cpp
|
danmosemsft/coreclr
|
04a3d11e4eecec2a4b7dcc81ab1575a57e30e3e2
|
[
"MIT"
] | 6
|
2017-09-22T06:55:45.000Z
|
2021-07-02T07:07:08.000Z
|
src/vm/contractimpl.cpp
|
danmosemsft/coreclr
|
04a3d11e4eecec2a4b7dcc81ab1575a57e30e3e2
|
[
"MIT"
] | 3
|
2018-01-03T00:57:25.000Z
|
2018-10-05T16:17:52.000Z
|
src/vm/contractimpl.cpp
|
danmosemsft/coreclr
|
04a3d11e4eecec2a4b7dcc81ab1575a57e30e3e2
|
[
"MIT"
] | 2
|
2017-06-04T15:47:12.000Z
|
2020-03-16T07:01:47.000Z
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
// File: contractimpl.cpp
//
// Keeps track of contract implementations, used primarily in stub dispatch.
//
//
//
// ============================================================================
#include "common.h" // Precompiled header
#include "contractimpl.h"
#include "virtualcallstub.h"
#include "decodemd.h"
#ifdef FEATURE_PREJIT
#include "compile.h"
#endif
#if defined(_DEBUG)
DummyGlobalContract ___contract;
#endif
#ifdef LOGGING
//----------------------------------------------------------------------------
StubDispatchStats g_sdStats = {0};
#endif // LOGGING
#ifndef DACCESS_COMPILE
//----------------------------------------------------------------------------
MethodDesc * DispatchSlot::GetMethodDesc()
{
WRAPPER_NO_CONTRACT;
if (IsNull())
return NULL;
else
return MethodTable::GetMethodDescForSlotAddress(GetTarget());
}
//------------------------------------------------------------------------
void TypeIDMap::Init(UINT32 idStartValue, UINT32 idIncrementValue, BOOL fUseFatTokensForUniqueness)
{
STANDARD_VM_CONTRACT;
LockOwner lock = {&m_lock, IsOwnerOfCrst};
m_idMap.Init(11, TRUE, &lock);
m_mtMap.Init(11, TRUE, &lock);
m_idProvider.Init(idStartValue, idIncrementValue);
m_entryCount = 0;
m_fUseFatIdsForUniqueness = fUseFatTokensForUniqueness;
}
#endif // !DACCESS_COMPILE
//------------------------------------------------------------------------
// Returns the ID of the type if found. If not found, returns INVALID_TYPE_ID
UINT32 TypeIDMap::LookupTypeID(PTR_MethodTable pMT)
{
CONTRACTL {
NOTHROW;
SO_TOLERANT;
PRECONDITION(CheckPointer(GetThread()));
if (GetThread()->PreemptiveGCDisabled()) { GC_NOTRIGGER; } else { GC_TRIGGERS; }
} CONTRACTL_END;
UINT32 id = (UINT32) m_mtMap.LookupValue((UPTR)dac_cast<TADDR>(pMT), 0);
_ASSERTE(!m_fUseFatIdsForUniqueness || !pMT->RequiresFatDispatchTokens() || (DispatchToken::RequiresDispatchTokenFat(id, 0)));
return id;
}
//------------------------------------------------------------------------
// Returns the ID of the type if found. If not found, returns INVALID_TYPE_ID
PTR_MethodTable TypeIDMap::LookupType(UINT32 id)
{
CONTRACTL {
NOTHROW;
SO_TOLERANT;
PRECONDITION(CheckPointer(GetThread()));
if (GetThread()->PreemptiveGCDisabled()) { GC_NOTRIGGER; } else { GC_TRIGGERS; }
PRECONDITION(id <= TypeIDProvider::MAX_TYPE_ID);
} CONTRACTL_END;
if (!m_idProvider.OwnsID(id))
return NULL;
UPTR ret = m_idMap.LookupValue((UPTR)id, 0);
if (ret == static_cast<UPTR>(INVALIDENTRY))
return NULL;
ret <<= 1;
return PTR_MethodTable(ret);
}
//------------------------------------------------------------------------
// Returns the ID of the type if found. If not found, assigns the ID and
// returns the new ID.
UINT32 TypeIDMap::GetTypeID(PTR_MethodTable pMT)
{
CONTRACTL {
THROWS;
GC_TRIGGERS;
} CONTRACTL_END;
// Lookup the value.
UINT32 id = LookupTypeID(pMT);
#ifndef DACCESS_COMPILE
// If the value is not in the table, take the lock, get a new ID, and
// insert the new pair.
if (id == TypeIDProvider::INVALID_TYPE_ID)
{
// Take the lock
CrstHolder lh(&m_lock);
// Check to see if someone beat us to the punch
id = LookupTypeID(pMT);
if (id != TypeIDProvider::INVALID_TYPE_ID)
{
return id;
}
// Get the next ID
if (m_fUseFatIdsForUniqueness && pMT->RequiresFatDispatchTokens())
{
id = GetNextFatID();
}
else
{
id = GetNextID();
}
CONSISTENCY_CHECK(id <= TypeIDProvider::MAX_TYPE_ID);
// Insert the pair, with lookups in both directions
CONSISTENCY_CHECK((((UPTR)pMT) & 0x1) == 0);
m_idMap.InsertValue((UPTR)id, (UPTR)pMT >> 1);
m_mtMap.InsertValue((UPTR)pMT, (UPTR)id);
m_entryCount++;
CONSISTENCY_CHECK(GetThread()->GetDomain()->IsCompilationDomain() ||
(LookupType(id) == pMT));
}
#else // DACCESS_COMPILE
if (id == TypeIDProvider::INVALID_TYPE_ID)
DacError(E_FAIL);
#endif // DACCESS_COMPILE
// Return the ID for this type.
return id;
} // TypeIDMap::GetTypeID
#ifndef DACCESS_COMPILE
//------------------------------------------------------------------------
// If TRUE, it points to a matching entry.
// If FALSE, it is at the insertion point.
BOOL
DispatchMapBuilder::Find(
DispatchMapTypeID typeID,
UINT32 slotNumber,
Iterator & it)
{
WRAPPER_NO_CONTRACT;
for (; it.IsValid(); it.Next())
{
if (typeID == it.GetTypeID())
{
if (slotNumber == it.GetSlotNumber())
{
return TRUE;
}
if (slotNumber < it.GetSlotNumber())
{
return FALSE;
}
}
else if (typeID < it.GetTypeID())
{
return FALSE;
}
}
return FALSE;
} // DispatchMapBuilder::Find
//------------------------------------------------------------------------
// If TRUE, contains such an entry.
// If FALSE, no such entry exists.
BOOL DispatchMapBuilder::Contains(DispatchMapTypeID typeID, UINT32 slotNumber)
{
WRAPPER_NO_CONTRACT;
Iterator it(this);
return Find(typeID, slotNumber, it);
}
//------------------------------------------------------------------------
void
DispatchMapBuilder::InsertMDMapping(
DispatchMapTypeID typeID,
UINT32 slotNumber,
MethodDesc * pMDTarget,
BOOL fIsMethodImpl)
{
CONTRACTL {
THROWS;
GC_NOTRIGGER;
} CONTRACTL_END;
// Find a matching entry, or move the iterator to insertion point.
Iterator it(this);
BOOL fFound = Find(typeID, slotNumber, it);
// If we find an existing matching entry, fail.
if (fFound)
{
_ASSERTE(false);
COMPlusThrowHR(COR_E_TYPELOAD);
}
// Create and initialize a new entry
DispatchMapBuilderNode * pNew = NewEntry();
pNew->Init(typeID, slotNumber, pMDTarget);
if (fIsMethodImpl)
pNew->SetIsMethodImpl();
// Insert at the point of the iterator
pNew->m_next = NULL;
if (it.IsValid())
{
pNew->m_next = it.EntryNode();
}
*(it.EntryNodePtr()) = pNew;
m_cEntries++;
} // DispatchMapBuilder::InsertMDMapping
//--------------------------------------------------------------------
UINT32 DispatchMapBuilder::Iterator::GetTargetSlot()
{
WRAPPER_NO_CONTRACT;
CONSISTENCY_CHECK(IsValid());
if (GetTargetMD() != NULL)
{
return EntryNode()->m_pMDTarget->GetSlot();
}
else
{
return 0;
}
}
//------------------------------------------------------------------------
DispatchMapBuilderNode * DispatchMapBuilder::NewEntry()
{
CONTRACTL {
THROWS;
GC_NOTRIGGER;
INJECT_FAULT(COMPlusThrowOM());
} CONTRACTL_END;
return new (m_pAllocator) DispatchMapBuilderNode();
}
//----------------------------------------------------------------------------
DispatchMap::DispatchMap(
BYTE * pMap,
UINT32 cbMap)
{
LIMITED_METHOD_CONTRACT;
CONSISTENCY_CHECK(CheckPointer(pMap));
memcpyNoGCRefs(m_rgMap, pMap, cbMap);
}
//----------------------------------------------------------------------------
// This mapping consists of a list of the following entries.
// <type, [<slot, (index | slot)>]>. This is implemented as
//
// flag: 0 if the map is a part of a JIT'd module
// 1 if the map is a part of an NGEN'd module.
// count: number of types that have entries
// {
// type: The ID current type being mapped
// count: Number of subentries for the current type
// bool: Whether or not the target slot/index values can be negative.
// {
// slot: The slot of type that is being mapped
// index/slot: This is a slot mapping for the current type. The implementation search is
// modified to <this, slot> and the search is restarted from the initial type.
// }
// }
void
DispatchMap::CreateEncodedMapping(
MethodTable * pMT,
DispatchMapBuilder * pMapBuilder,
StackingAllocator * pAllocator,
BYTE ** ppbMap,
UINT32 * pcbMap)
{
CONTRACTL {
THROWS;
GC_TRIGGERS;
INJECT_FAULT(COMPlusThrowOM());
PRECONDITION(CheckPointer(pMT));
PRECONDITION(CheckPointer(pMapBuilder));
PRECONDITION(CheckPointer(pAllocator));
PRECONDITION(CheckPointer(ppbMap));
PRECONDITION(CheckPointer(pcbMap));
} CONTRACTL_END;
/////////////////////////////////
// Phase 1 - gather entry counts
UINT32 cNumTypes = 0;
UINT32 cNumEntries = 0;
{
DispatchMapBuilder::Iterator it(pMapBuilder);
// We don't want to record overrides or methodImpls in the dispatch map since
// we have vtables to track this information.
it.SkipThisTypeEntries();
if (it.IsValid())
{
DispatchMapTypeID curType = DispatchMapTypeID::FromUINT32(INVALIDENTRY);
do
{
cNumEntries++;
if (curType != it.GetTypeID())
{
cNumTypes++;
curType = it.GetTypeID();
}
}
while (it.Next());
}
}
/////////////////////////////////
// Phase 2 - allocate space
// Now that we have stats about the overall absolute maximum map size, we can allocate
// some working space for createing the encoded map in.
// Sizes: flag==UINT32, typeID==UINT32, slot==UINT32, index/slot==UINT32
S_UINT32 scbMap = S_UINT32(sizeof(UINT32)) +
S_UINT32(cNumTypes) * S_UINT32(sizeof(UINT32)) +
S_UINT32(cNumEntries) * S_UINT32((sizeof(UINT32) + sizeof(UINT32)));
BYTE * pbMap = (BYTE *)pAllocator->Alloc(scbMap);
/////////////////////////////////
// Phase 3 - encode the map
{
// Create the encoder over the newly allocated memory
Encoder e(pbMap);
// Encode the count of type entries
e.Encode((unsigned)cNumTypes);
// Start encoding the map
DispatchMapBuilder::Iterator it(pMapBuilder);
it.SkipThisTypeEntries();
INT32 curType = -1;
INT32 prevType;
INT32 deltaType;
while (it.IsValid())
{
// Encode the type ID
prevType = curType;
curType = (INT32)it.GetTypeID().ToUINT32();
deltaType = curType - prevType - ENCODING_TYPE_DELTA;
CONSISTENCY_CHECK(0 <= deltaType);
e.Encode((unsigned)deltaType);
// Variables for slot delta calculations
BOOL fHasNegatives = FALSE;
// Source slot
INT32 curSlot = -1;
INT32 prevSlot = -1;
// Target slot for virtual mappings
INT32 curTargetSlot = -1;
INT32 prevTargetSlot = -1;
// Count and encode the number of sub entries for this type
UINT32 cSubEntries = 0;
DispatchMapBuilder::Iterator subIt(it);
do
{
prevTargetSlot = curTargetSlot;
curTargetSlot = (INT32)subIt.GetTargetSlot();
INT32 deltaTargetSlot = curTargetSlot - prevTargetSlot - ENCODING_TARGET_SLOT_DELTA;
if (deltaTargetSlot < 0)
{
fHasNegatives = TRUE;
}
cSubEntries++;
}
while (subIt.Next() && (subIt.GetTypeID().ToUINT32() == (UINT32)curType));
e.Encode((unsigned)cSubEntries);
e.Encode((unsigned)fHasNegatives);
e.ContainsNegatives(fHasNegatives);
// Iterate each subentry and encode it
curTargetSlot = -1;
do
{
// Only virtual targets can be mapped virtually.
CONSISTENCY_CHECK((it.GetTargetMD() == NULL) ||
it.GetTargetMD()->IsVirtual());
// Encode the slot
prevSlot = curSlot;
curSlot = it.GetSlotNumber();
INT32 deltaSlot = curSlot - prevSlot - ENCODING_SLOT_DELTA;
CONSISTENCY_CHECK(0 <= deltaSlot);
e.Encode((unsigned)deltaSlot);
// Calculate and encode the target slot delta
prevTargetSlot = curTargetSlot;
curTargetSlot = (INT32)it.GetTargetSlot();
INT32 delta = curTargetSlot - prevTargetSlot - ENCODING_TARGET_SLOT_DELTA;
if (fHasNegatives)
{
e.EncodeSigned((signed)delta);
}
else
{
CONSISTENCY_CHECK(0 <= delta);
e.Encode((unsigned)delta);
}
}
while (it.Next() && it.GetTypeID().ToUINT32() == (UINT32)curType);
} // while (it.IsValid())
// Finish and finalize the map, and set the out params.
e.Done();
*pcbMap = e.Contents(ppbMap);
}
#ifdef _DEBUG
// Let's verify the mapping
{
EncodedMapIterator itMap(*ppbMap);
DispatchMapBuilder::Iterator itBuilder(pMapBuilder);
itBuilder.SkipThisTypeEntries();
while (itMap.IsValid())
{
CONSISTENCY_CHECK(itBuilder.IsValid());
DispatchMapEntry * pEntryMap = itMap.Entry();
CONSISTENCY_CHECK(pEntryMap->GetTypeID() == itBuilder.GetTypeID());
CONSISTENCY_CHECK(pEntryMap->GetTargetSlotNumber() == itBuilder.GetTargetSlot());
itMap.Next();
itBuilder.Next();
}
CONSISTENCY_CHECK(!itBuilder.IsValid());
}
#endif //_DEBUG
} // DispatchMap::CreateEncodedMapping
#ifdef FEATURE_NATIVE_IMAGE_GENERATION
//------------------------------------------------------------------------
void DispatchMap::Save(DataImage * image)
{
STANDARD_VM_CONTRACT;
CONSISTENCY_CHECK(!image->IsStored(this));
UINT32 cbMap = GetMapSize();
UINT32 cbObj = GetObjectSize(cbMap);
image->StoreInternedStructure(
this,
cbObj,
DataImage::ITEM_DISPATCH_MAP,
sizeof(void *));
#ifdef LOGGING
g_sdStats.m_cNGENDispatchMap++;
g_sdStats.m_cbNGENDispatchMap += cbObj;
#endif //LOGGING
}
//------------------------------------------------------------------------
void DispatchMap::Fixup(DataImage *image)
{
STANDARD_VM_CONTRACT;
}
#endif //FEATURE_NATIVE_IMAGE_GENERATION
#endif //!DACCESS_COMPILE
//------------------------------------------------------------------------
UINT32 DispatchMap::GetMapSize()
{
WRAPPER_NO_CONTRACT;
SUPPORTS_DAC;
EncodedMapIterator it(this);
for (; it.IsValid(); it.Next())
{
}
CONSISTENCY_CHECK(dac_cast<TADDR>(it.m_d.End()) > PTR_HOST_MEMBER_TADDR(DispatchMap, this, m_rgMap));
return (UINT32)(dac_cast<TADDR>(it.m_d.End()) - PTR_HOST_MEMBER_TADDR(DispatchMap, this, m_rgMap));
}
#ifdef DACCESS_COMPILE
//------------------------------------------------------------------------
void DispatchMap::EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
{
WRAPPER_NO_CONTRACT;
SUPPORTS_DAC;
DAC_ENUM_DTHIS();
EMEM_OUT(("MEM: %p DispatchMap\n", dac_cast<TADDR>(this)));
DacEnumMemoryRegion(PTR_HOST_MEMBER_TADDR(DispatchMap,this,m_rgMap), GetMapSize());
}
#endif // DACCESS_COMPILE
//--------------------------------------------------------------------
void DispatchMap::EncodedMapIterator::Invalidate()
{
LIMITED_METHOD_DAC_CONTRACT;
m_numTypes = 0;
m_curType = 0;
m_numEntries = 0;
m_curEntry = 0;
}
//--------------------------------------------------------------------
void DispatchMap::EncodedMapIterator::Init(PTR_BYTE pbMap)
{
CONTRACTL {
GC_NOTRIGGER;
NOTHROW;
INSTANCE_CHECK;
PRECONDITION(CheckPointer(pbMap, NULL_OK));
SUPPORTS_DAC;
} CONTRACTL_END;
if (pbMap != NULL)
{
// Initialize the map decoder
m_d.Init(pbMap);
m_numTypes = m_d.Next();
m_curType = -1;
m_curTypeId = DispatchMapTypeID::FromUINT32(static_cast<UINT32>(-1));
m_numEntries = 0;
m_curEntry = -1;
m_curTargetSlot = static_cast<UINT32>(-1);
}
else
{
Invalidate();
}
Next();
}
//--------------------------------------------------------------------
DispatchMap::EncodedMapIterator::EncodedMapIterator(MethodTable * pMT)
{
CONTRACTL {
GC_NOTRIGGER;
NOTHROW;
INSTANCE_CHECK;
SUPPORTS_DAC;
} CONTRACTL_END;
if (pMT->HasDispatchMap())
{
DispatchMap * pMap = pMT->GetDispatchMap();
Init(PTR_BYTE(PTR_HOST_MEMBER_TADDR(DispatchMap, pMap, m_rgMap)));
}
else
{
Init(NULL);
}
}
//--------------------------------------------------------------------
// This should be used only when a dispatch map needs to be used
// separately from its MethodTable.
DispatchMap::EncodedMapIterator::EncodedMapIterator(DispatchMap * pMap)
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
PTR_BYTE pBytes = NULL;
if (pMap != NULL)
{
pBytes = PTR_BYTE(PTR_HOST_MEMBER_TADDR(DispatchMap, pMap,m_rgMap));
}
Init(pBytes);
}
//--------------------------------------------------------------------
DispatchMap::EncodedMapIterator::EncodedMapIterator(PTR_BYTE pbMap)
{
LIMITED_METHOD_CONTRACT;
Init(pbMap);
}
//--------------------------------------------------------------------
BOOL DispatchMap::EncodedMapIterator::Next()
{
CONTRACTL {
GC_NOTRIGGER;
NOTHROW;
INSTANCE_CHECK;
SUPPORTS_DAC;
} CONTRACTL_END;
if (!IsValid())
{
return FALSE;
}
m_curEntry++;
if (m_curEntry == m_numEntries)
{
m_curType++;
if (m_curType == m_numTypes)
{
return FALSE;
}
m_curTypeId =
DispatchMapTypeID::FromUINT32(
(UINT32)((INT32)m_curTypeId.ToUINT32() +
(INT32)m_d.Next() +
ENCODING_TYPE_DELTA));
_ASSERTE(!m_curTypeId.IsThisClass());
m_curEntry = 0;
m_numEntries = m_d.Next();
m_fCurTypeHasNegativeEntries = (BOOL)m_d.Next();
m_curSlot = static_cast<UINT32>(-1);
m_curTargetSlot = static_cast<UINT32>(-1);
CONSISTENCY_CHECK(m_numEntries != 0);
}
// Now gather enough info to initialize the dispatch entry
// Get the source slot
m_curSlot = (UINT32)((INT32)m_curSlot + (INT32)m_d.Next() + ENCODING_SLOT_DELTA);
// If virtual, get the target virtual slot number
m_curTargetSlot =
(UINT32)((INT32)m_curTargetSlot +
ENCODING_TARGET_SLOT_DELTA +
(INT32)(m_fCurTypeHasNegativeEntries ? m_d.NextSigned() : m_d.Next()));
m_e.InitVirtualMapping(m_curTypeId, m_curSlot, m_curTargetSlot);
CONSISTENCY_CHECK(IsValid());
return TRUE;
} // DispatchMap::EncodedMapIterator::Next
//--------------------------------------------------------------------
DispatchMap::Iterator::Iterator(MethodTable * pMT)
: m_mapIt(pMT)
{
CONTRACTL {
THROWS;
GC_TRIGGERS;
} CONTRACTL_END;
}
//--------------------------------------------------------------------
BOOL DispatchMap::Iterator::IsValid()
{
WRAPPER_NO_CONTRACT;
return m_mapIt.IsValid();
}
//--------------------------------------------------------------------
BOOL DispatchMap::Iterator::Next()
{
WRAPPER_NO_CONTRACT;
CONSISTENCY_CHECK(!m_mapIt.Entry()->GetTypeID().IsThisClass());
if (m_mapIt.IsValid())
{
m_mapIt.Next();
CONSISTENCY_CHECK(!m_mapIt.IsValid() || !m_mapIt.Entry()->GetTypeID().IsThisClass());
}
return IsValid();
}
//--------------------------------------------------------------------
DispatchMapEntry * DispatchMap::Iterator::Entry()
{
/*
CONTRACTL {
INSTANCE_CHECK;
MODE_ANY;
if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS;
if (FORBIDGC_LOADER_USE_ENABLED()) GC_NOTRIGGER; else GC_TRIGGERS;
if (FORBIDGC_LOADER_USE_ENABLED()) FORBID_FAULT; else { INJECT_FAULT(COMPlusThrowOM()); }
PRECONDITION(IsValid());
} CONTRACTL_END;
*/
WRAPPER_NO_CONTRACT;
CONSISTENCY_CHECK(IsValid());
DispatchMapEntry * pEntry = NULL;
if (m_mapIt.IsValid())
{
pEntry = m_mapIt.Entry();
}
CONSISTENCY_CHECK(CheckPointer(pEntry));
return pEntry;
}
| 29.46648
| 130
| 0.545218
|
danmosemsft
|